diff --git "a/20230442_matlab.jsonl" "b/20230442_matlab.jsonl" new file mode 100644--- /dev/null +++ "b/20230442_matlab.jsonl" @@ -0,0 +1,1586 @@ +{"plateform": "github", "repo_name": "humnetlab/IndividualMobilityModel-master", "name": "PowerLawPlotWeighted.m", "ext": ".m", "path": "IndividualMobilityModel-master/PowerLawPlotWeighted.m", "size": 1316, "source_encoding": "utf_8", "md5": "0679a9a08821e11c1b3aaa6b96f5a0fb", "text": "%loglog plot\nfunction [x_ nbins_]=PowerLawPlotWeighted(m_data,marker,color,min_cut,max_cut,unit_bins)\nif nargin < 6\n unit_bins=10;\nend\nif nargin < 5\n max_cut = 9999999;\nend\nif nargin <4\n min_cut =0.0000001;\nend\nindex=find(m_data(:,1)>min_cut&m_data(:,1)1\n Nbins(i)=Nbins(i)/(x(i)-x(i-1));\n else\n Nbins(i)=Nbins(i)/(x(i)-0);\n end\nend\nindex=find(Nbins>0);\npolyfit(log10(x(index(17:end))),log10(Nbins(index(17:end))),1)\nx_=log10(x(index));\nnbins_=log10(Nbins(index));\nloglog(x(1:end),Nbins(1:end),[color,marker],'MarkerEdgeColor',color,'MarkerSize',5);\nset(gca,'FontName','Times New Roman','FontSize',10)\nxlabel('x','FontName','Times New Roman','FontSize',10)\nylabel('P(x)','FontName','Times New Roman','FontSize',10)\n\n"} +{"plateform": "github", "repo_name": "humnetlab/IndividualMobilityModel-master", "name": "PowerLawPlot.m", "ext": ".m", "path": "IndividualMobilityModel-master/PowerLawPlot.m", "size": 1177, "source_encoding": "utf_8", "md5": "19abd5bef383a967289d28b878b7df59", "text": "%loglog plot\nfunction PowerLawPlot(m_data,marker,color,min_cut,max_cut,unit_bins)\nif nargin < 6\n unit_bins=10;\nend\nif nargin < 5\n max_cut = 9999999;\nend\nif nargin <4\n min_cut =0.0000001;\nend\nindex=find(m_data>min_cut&m_data1\n Nbins(i)=Nbins(i)/(x(i)-x(i-1));\n else\n Nbins(i)=Nbins(i)/(x(i)-0);\n end\nend\nindex=find(Nbins>0);\n\nloglog(x(2:end),Nbins(2:end),[color,marker],'MarkerEdgeColor',color,'MarkerSize',4);\nset(gca,'FontName','Times New Roman','FontSize',10)\nxlabel('x','FontName','Times New Roman','FontSize',10)\nylabel('P(x)','FontName','Times New Roman','FontSize',10)\n%xlim([10^min_order,10^max_order])\n\n"} +{"plateform": "github", "repo_name": "NadineKroher/essentia-master", "name": "DetectPeaks.m", "ext": ".m", "path": "essentia-master/test/src/descriptortests/tuning/DetectPeaks.m", "size": 1325, "source_encoding": "utf_8", "md5": "c64072c666d438b9c9c181f2e5aba663", "text": "% Function for peak detection \r\n% Adaptations made to work with HPCP by emilia, 28-03-2007\r\nfunction [ploc, pval]=DetectPeaks(spectrum, nPeaks)\r\n\r\n% function DetectPeaks(spectrum)\r\n% Inputs:\r\n% spectrum: dB spectrum magnitude (abs(fft(signal))\r\n% nPeaks: maximum number of peaks to pick\r\n% Outputs:\r\n% ploc: bin number of peaks (if ploc(i)==0, no peak detected)\r\n% pval: magnitude values of the peaks in dB \r\n\r\npval = []; %ones(nPeaks,1)*-100;\r\nploc = []; %zeros(nPeaks,1);\r\n\r\n% Compute derivate\r\nminSpectrum = min(spectrum);\r\ndifference = diff([minSpectrum; spectrum; minSpectrum]);\r\n\r\n% Compute peak locatios from derivate\r\nsize = length(spectrum);\r\n% peak locations\r\niloc = find(difference(1:size)>= 0 & difference(2:size+1) <= 0);\r\n% peak values\r\nival = spectrum(iloc);\r\np = 1;\r\n\r\nwhile(max(ival)>-100)\r\n [maxi, l] = max(ival); % find current maximum, maximum value\r\n \r\n pval = [pval maxi];\r\n % Put maximum to -100 dB, so that it's not the maximum anymore\r\n ival(l) = -100;\r\n aux = iloc(l);\r\n ploc = [ploc aux]; % save value and location\r\n \r\n% ind = find(abs(iloc(l)-iloc) > minspace);\r\n % find peaks which are far away\r\n % if (isempty(ind))\r\n % break % no more local peaks to pick\r\n % end\r\n \r\n % ival = ival(ind); % shrink peak value and location array\r\n % iloc = iloc(ind);\r\n p=p+1;\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "NTCColumbia/ntc_CNMF-master", "name": "interp_missing_data.m", "ext": ".m", "path": "ntc_CNMF-master/interp_missing_data.m", "size": 744, "source_encoding": "utf_8", "md5": "db12d4c51a71a6cf53e8f04e40827629", "text": "\n\n\nfunction Y_interp = interp_missing_data(Y)\n\n% interpolate missing data using linear interpolation for each pixel\n% produce a sparse matrix with the values \n\nsizY = size(Y);\ndimY = length(sizY);\nd = prod(sizY(1:dimY-1));\nT = sizY(end);\nmis_data = cell(d,1);\n\nfor i = 1:d\n [ii,jj,kk] = ind2sub(sizY(1:dimY-1),i);\n if dimY == 2\n ytemp = Y(i,:);\n elseif dimY == 3\n ytemp = squeeze(Y(ii,jj,:));\n elseif dimY == 4\n ytemp = squeeze(Y(ii,jj,kk,:));\n end\n f = isnan(ytemp(:));\n y_val = interp1(find(~f),ytemp(~f),find(f),'linear','extrap');\n mis_data{i} = [i*ones(length(y_val),1),find(f(:)),y_val(:)];\nend\n\nmis_data = cell2mat(mis_data);\nY_interp = sparse(mis_data(:,1),mis_data(:,2),mis_data(:,3),d,T);\n"} +{"plateform": "github", "repo_name": "NTCColumbia/ntc_CNMF-master", "name": "lars_regression_noise.m", "ext": ".m", "path": "ntc_CNMF-master/lars_regression_noise.m", "size": 7310, "source_encoding": "utf_8", "md5": "57b6188ceb2fc027c7e65b5a96aac472", "text": "function [Ws, lambdas, W_lam, lam, flag] = lars_regression_noise(Y, X, positive, noise)\n\n% run LARS for regression problems with LASSO penalty, with optional positivity constraints\n% Author: Eftychios Pnevmatikakis. Adapted code from Ari Pakman\n\n\n% Input Parameters:\n% Y: Y(:,t) is the observed data at time t\n% X: the regresion problem is Y=X*W + noise\n% maxcomps: maximum number of active components to allow\n% positive: a flag to enforce positivity\n% noise: the noise of the observation equation. if it is not\n% provided as an argument, the noise is computed from the\n% variance at the end point of the algorithm. The noise is\n% used in the computation of the Cp criterion.\n\n\n% Output Parameters:\n% Ws: weights from each iteration\n% lambdas: lambda values at each iteration\n% Cps: C_p estimates\n% last_break: last_break(m) == n means that the last break with m non-zero weights is at Ws(:,:,n)\n\n\nverbose=false;\n%verbose=true;\n\nk=1;\n\nT = size(Y,2); % # of time steps\nN = size(X,2); % # of compartments\n\nmaxcomps = N;\n\nW = zeros(N,k);\nactive_set = zeros(N,k);\nvisited_set = zeros(N,k);\n\nlambdas = [];\n\nWs=zeros(size(W,1),size(W,2),maxcomps); % Just preallocation. Ws may end with more or less than maxcomp columns\n\n\n%% \n\nr = X'*Y(:); % N-dim vector\nM = -X'*X; % N x N matrix \n\n%% begin main loop\n\n%fprintf('\\n i = ');\ni = 1;\nflag = 0;\nwhile 1\n if flag == 1;\n W_lam = 0;\n break;\n end\n % fprintf('%d,',i);\n \n %% calculate new gradient component if necessary\n\n if i>1 && new && visited_set(new) ==0 \n\n visited_set(new) =1; % remember this direction was computed\n\n end\n\n %% Compute full gradient of Q \n\n dQ = r + M*W;\n \n %% Compute new W\n if i == 1\n if positive\n dQa = dQ;\n else\n dQa = abs(dQ);\n end\n [lambda, new] = max(dQa(:));\n \n if lambda < 0\n disp('All negative directions!')\n break\n end\n \n else\n\n % calculate vector to travel along \n \n% disp('calc velocity')\n \n [avec, gamma_plus, gamma_minus] = calcAvec(new, dQ, W, lambda, active_set, M, positive); \n \n % calculate time of travel and next new direction \n \n if new==0 % if we just dropped a direction we don't allow it to emerge \n if dropped_sign == 1 % with the same sign\n gamma_plus(dropped) = inf;\n else\n gamma_minus(dropped) = inf;\n end \n end\n \n\n gamma_plus(active_set == 1) = inf; % don't consider active components \n gamma_plus(gamma_plus <= 0) = inf; % or components outside the range [0, lambda]\n gamma_plus(gamma_plus> lambda) =inf;\n [gp_min, gp_min_ind] = min(gamma_plus(:));\n\n\n if positive\n gm_min = inf; % don't consider new directions that would grow negative\n else\n gamma_minus(active_set == 1) = inf; \n gamma_minus(gamma_minus> lambda) =inf;\n gamma_minus(gamma_minus <= 0) = inf; \n [gm_min, gm_min_ind] = min(gamma_minus(:));\n\n end\n\n [g_min, which] = min([gp_min, gm_min]);\n\n if g_min == inf; % if there are no possible new components, try move to the end\n g_min = lambda; % This happens when all the components are already active or, if positive==1, when there are no new positive directions \n end\n \n \n\n % LARS check (is g_min*avec too large?)\n gamma_zero = -W(active_set == 1) ./ avec;\n gamma_zero_full = zeros(N,k);\n gamma_zero_full(active_set == 1) = gamma_zero;\n gamma_zero_full(gamma_zero_full <= 0) = inf;\n [gz_min, gz_min_ind] = min(gamma_zero_full(:));\n \n if gz_min < g_min \n if verbose\n fprintf('DROPPING active weight: %d.\\n', gz_min_ind)\n end\n active_set(gz_min_ind) = 0;\n dropped = gz_min_ind;\n dropped_sign = sign(W(dropped));\n W(gz_min_ind) = 0;\n avec = avec(gamma_zero ~= gz_min);\n g_min = gz_min;\n new = 0;\n \n elseif g_min < lambda\n if which == 1\n new = gp_min_ind;\n if verbose\n fprintf('new positive component: %d.\\n', new)\n end\n else\n new = gm_min_ind;\n fprintf('new negative component: %d.\\n', new)\n end\n end\n \n W(active_set == 1) = W(active_set == 1) + g_min * avec;\n \n if positive\n if any (W<0)\n min(W);\n flag = 1;\n %error('negative W component');\n end\n end\n \n lambda = lambda - g_min;\n end\n\n \n \n\n%% Update weights and lambdas \n \n lambdas(i) = lambda;\n Ws(:,:,i)=W;\n res = norm(Y-X*W,'fro')^2;\n%% Check finishing conditions \n \n\n if lambda ==0 || (new && sum(active_set(:)) == maxcomps) || (res < noise) \n if verbose\n fprintf('end. \\n');\n end\n \n break\n end\n\n%% \n if new \n active_set(new) = 1;\n end\n\n \n i = i + 1;\nend\n%% end main loop \n\n%% final calculation of mus\nif flag == 0\n if i > 1\n Ws= squeeze(Ws(:,:,1:length(lambdas)));\n w_dir = -(Ws(:,i) - Ws(:,i-1))/(lambdas(i)-lambdas(i-1));\n Aw = X*w_dir;\n y_res = Y - X*(Ws(:,i-1) + w_dir*lambdas(i-1));\n ld = roots([norm(Aw)^2,-2*(Aw'*y_res),y_res'*y_res-noise]);\n lam = ld(intersect(find(ld>lambdas(i)),find(ld= 0;\n norm(Y-X*W_lam)<= sqrt(noise);\n cvx_end\n lam = 10;\n end\nelse\n W_lam = 0;\n Ws = 0;\n lambdas = 0; \n lam = 0;\nend\nend\n\n%%%%%%%%%% begin auxiliary functions %%%%%%%%%%\n\n\n%%\nfunction [avec, gamma_plus, gamma_minus] = calcAvec(new, dQ, W, lambda, active_set, M, positive)\n\n[r,c] = find(active_set);\nMm = -M(r,r);\n\n\nMm=(Mm + Mm')/2;\n\n% verify that there is no numerical instability \neigMm = eig(Mm);\nif any(eigMm < 0)\n min(eigMm)\n %error('The matrix Mm has negative eigenvalues') \n flag = 1;\nend\n\n\nb = sign(W);\nif new\n b(new) = sign(dQ(new));\nend\nb = b(active_set == 1);\n\navec = Mm\\b;\n\nif positive \n if new \n in = sum(active_set(1:new));\n if avec(in) <0\n new;\n %error('new component of a is negative')\n flag = 1;\n end\n end\nend\n\n \n\none_vec = ones(size(W));\n\ndQa = zeros(size(W));\nfor j=1:length(r)\n dQa = dQa + avec(j)*M(:, r(j));\nend\n\ngamma_plus = (lambda - dQ)./(one_vec + dQa);\ngamma_minus = (lambda + dQ)./(one_vec - dQa);\n\nend\n"} +{"plateform": "github", "repo_name": "NTCColumbia/ntc_CNMF-master", "name": "f_signalExtraction_dfof.m", "ext": ".m", "path": "ntc_CNMF-master/f_signalExtraction_dfof.m", "size": 3173, "source_encoding": "utf_8", "md5": "dd0d5cd3984f92046666a05629c69b91", "text": "% this program extract df/f\n\nfunction [ signal_inferred, signal_filtered, signal_raw, signal_inferred_DC, signal_filtered_DC, signal_raw_DC,Y_fres ] = f_signalExtraction_dfof(Y,A,C,b,f,d1,d2,backgroundSubtractionforRaw,baselineRatio)\n\nT = size(C,2);\nif ndims(Y) == 3\n Y = reshape(Y,d1*d2,T);\nend\nnr = size(A,2); % number of ROIs\nnb = size(f,1); % number of background components\nnA = full(sum(A.^2))'; % energy of each row\nYres = Y - A*C - full(b)*f;\nY_r = spdiags(nA,0,nr,nr)\\(A'*Yres) + C; \nY_fres=Y_r-C; %residuals from full ROI cf to Raw movie - used to be able to regenrate original raw traces in saved data structure \nsignal_inferred=C; % spatial weighting on the ROI pixels, background substraction, and denoising\nsignal_filtered=Y_r; % spatial weighting on the ROI pixels, background substraction\n\n% Binarize weights of pixels to fraction \"weight_thresh\" of max (if max weight is 0.6, and thresh is .1, set weights > 0.06-->1, < 0.06--> 0\nweight_thresh=.2;\nA_raw_mask=A;\nfor idx = 1:nr\n [tempA,ind] = sort(A(:,idx),'ascend');\n temp = cumsum(tempA);\n index_on = find(temp>=weight_thresh*temp(end));\n index_off=find(temp0);\n temp=temp(index);\n F_res=mean(temp(1:round(baselineRatio*length(temp))));\n signal_inferred(idx,:)=(df-F_res)./(mean(((A(:,idx)'*b)*f))+F_res);\n signal_inferred_DC(idx)=mean(((A(:,idx)'*b)*f))+F_res;\n% filtered signal \n df=(A(:,idx)'*A(:,idx))*signal_filtered(idx,:);\n temp=sort(df);\n index=find(temp>0);\n temp=temp(index);\n F_res=mean(temp(1:round(baselineRatio*length(temp)))); \n signal_filtered(idx,:)=(df-F_res)./(mean(((A(:,idx)'*b)*f))+F_res);\n signal_filtered_DC(idx)=mean(((A(:,idx)'*b)*f))+F_res;\n% raw signal: with background substraction \n df=(A_contour(:,idx)'*A_contour(:,idx))*signal_raw(idx,:); \n temp=sort(df);\n index=find(temp>0);\n temp=temp(index);\n F_res=mean(temp(1:round(baselineRatio*length(temp))));\n signal_raw(idx,:)=(df-F_res)./(mean(((A_contour(:,idx)'*b)*f))+F_res);\n signal_raw_DC(idx)=mean(((A_contour(:,idx)'*b)*f))+F_res;\nend\n\n% really raw data \n if backgroundSubtractionforRaw==0\n signal_raw=A_contour'*Y; % no weighting on the ROI pixels, no background substraction\n [signal_raw, signal_raw_DC]=f_calDfof(signal_raw,baselineRatio);\n end\nend\n\n"} +{"plateform": "github", "repo_name": "NTCColumbia/ntc_CNMF-master", "name": "greedyROI2d.m", "ext": ".m", "path": "ntc_CNMF-master/greedyROI2d.m", "size": 5442, "source_encoding": "utf_8", "md5": "b877b7e7eb03f99b0f7d8008bf364a35", "text": "function [basis, trace, center, data] = greedyROI2d(data, K, params)\n%greedyROI2d using greedy algorithm to identify neurons in 2d calcium movie\n%\n%Usage: [basis, trace, center, res] = greedyROI2d(data, K, params)\n%\n%Input:\n%data M x N x T movie, raw data, each column is a vectorized movie\n%K number of neurons to extract\n%params tuning parameter for fine-tuning the shape (optional)\n% params.nIter: number of iterations for shape tuning (default 5)\n% params.gSig: variance of Gaussian kernel to use (default 5)\n% params.gSiz: size of kernel (default 11)\n%\n%Output:\n%basis M x N x K matrix, location of each neuron\n%trace T x K matrix, calcium activity of each neuron\n%center K x 2 matrix, inferred center of each neuron\n%res M x N x T movie, residual\n%\n%Author: Yuanjun Gao\n\n[M, N, T] = size(data);\n\nmed = median(data, 3);\ndata = bsxfun(@minus, data, med);\n\nif ~exist('K', 'var'), %find K neurons\n K = 30; \n warning(['number of neurons are not specified, set to be the default value', num2str(K)]);\nend\n\nif ~exist('params', 'var') params = []; end\n\nif ~isfield(params, 'gSig'), gSig = [5, 5]; \nelseif length(params.gSig) == 1, gSig = params.gSig + zeros(1,2); end\n\nif ~isfield(params, 'gSiz'), gSiz = [11, 11];\nelseif length(params.gSiz) == 1, gSiz = params.gSiz + zeros(1,2); end\n\nif ~isfield(params, 'nIter'), nIter = 5; \nelse nIter = params.nIter; end\n\nbasis = zeros(M, N, K);\ntrace = zeros(T, K);\ncenter = zeros(K, 2);\n\ngHalf = floor(gSiz / 2); %half size of the kernel, used to calculate margin\ngSiz = 2 * gHalf + 1; %actual size\n\n%scan the whole image (only need to do this at the first iteration)\nrho = imblur(data, gSig, gSiz); %covariance of data and basis\nv = sum(rho.^2, 3); %variance explained\n\nfor k = 1:K, \n [~, ind] = max(v(:));\n [iHat, jHat] = ind2sub([M, N], ind);\n center(k, 1) = iHat; center(k, 2) = jHat;\n \n iSig = [max(iHat - gHalf(1), 1), min(iHat + gHalf(1), M)]; iSigLen = iSig(2) - iSig(1) + 1;\n jSig = [max(jHat - gHalf(2), 1), min(jHat + gHalf(2), N)]; jSigLen = jSig(2) - jSig(1) + 1;\n \n %fine tune the shape\n dataTemp = data(iSig(1):iSig(2), jSig(1):jSig(2), :);\n traceTemp = rho(iHat, jHat, :);\n [coef, score] = finetune2d(dataTemp, traceTemp, nIter); \n \n dataSig = bsxfun(@times, coef, reshape(score, [1,1,T]));\n basis(iSig(1):iSig(2), jSig(1):jSig(2), k) = coef;\n trace(:, k) = score';\n \n data(iSig(1):iSig(2), jSig(1):jSig(2), :) = data(iSig(1):iSig(2), jSig(1):jSig(2), :) - dataSig; %update residual\n fprintf('found %i out of %i neurons..\\n', k,K);\n \n %get next basis;\n if k < K,\n iMod = [max(iHat - 2 * gHalf(1), 1), min(iHat + 2 * gHalf(1), M)]; iModLen = iMod(2) - iMod(1) + 1;%patches to modify\n jMod = [max(jHat - 2 * gHalf(2), 1), min(jHat + 2 * gHalf(2), N)]; jModLen = jMod(2) - jMod(1) + 1;\n iLag = iSig - iMod(1) + 1; %relative location of iSig in the small patch\n jLag = jSig - jMod(1) + 1;\n dataTemp = zeros(iModLen, jModLen);\n dataTemp(iLag(1):iLag(2), jLag(1):jLag(2)) = reshape(coef, [iSigLen, jSigLen]);\n dataTemp = imblur(dataTemp, gSig, gSiz, 2);\n rhoTemp = bsxfun(@times, dataTemp, reshape(score, [1,1,T]));\n rhoTemp = rho(iMod(1):iMod(2), jMod(1):jMod(2), :) - rhoTemp;\n rho(iMod(1):iMod(2), jMod(1):jMod(2), :) = rhoTemp;\n v(iMod(1):iMod(2), jMod(1):jMod(2)) = sum(rhoTemp.^2, 3);\n end\nend\n\n%basis = reshape(basis, [M * N, K]);\n\n\nfunction [basis, trace] = finetune2d(data, trace, nIter)\n%using matrix factorization with lasso penalty to fine-tune the basis\n%\n%Input:\n%data M x N x T matrix, small patch containing one neuron\n%trace initial value for trace\n%nIter number of coordinate descent steps\n%\n%Output:\n%basis M x N matrix, result of the fine-tuned neuron shape\n%trace 1 x T matrix, result of the neuron\n\nT = size(data, 3);\nif ~exist('nIter', 'var'), nIter = 1; end\n\n%do block coordinate descent\nfor iter = 1:nIter,\n %update basis\n a = sum(trace.^2); %scale by num. of observation\n b = sum(bsxfun(@times, data, reshape(trace, [1,1,T])), 3);\n basis = max(b / a, 0);\n basisNorm = norm(basis(:));\n if basisNorm > 0, \n basis = basis / basisNorm; \n else\n fprintf('get degenerate basis!\\n')\n break\n end\n \n %updating trace\n trace = bsxfun(@times, data, basis);\n trace = squeeze(sum(sum(trace, 1), 2)); \nend\nend\n\n\n\nfunction data = imblur(data, sig, siz, nDimBlur)\n%Gaussian blur for high dimensional data\n%Input:\n%data original data\n%sig std of gaussian kernel\n%siz size of kernel\n%nDimBlur number of dims to blur (default: ndims(data) - 1)\n%\n%Output:\n%data result after the Gaussian blur\n\nif ~exist('nDimBlur', 'var'), nDimBlur = ndims(data) - 1; \nelse nDimBlur = min(nDimBlur, ndims(data)); end\n\nif length(sig) == 1, sig = sig * ones(1,nDimBlur); end\nassert(nDimBlur == length(sig));\n\nif length(siz) == 1, siz = siz * ones(1,nDimBlur); end\nassert(nDimBlur == length(siz));\n\nfor i = 1:nDimBlur,\n if sig(i) > 0,\n x = -floor(siz(i) / 2):floor(siz(i) / 2);\n H = exp(-(x.^2/ (2 * sig(i)^2)));\n H = H' / norm(H(:));\n if nDimBlur > 1,\n indH = 1:nDimBlur; indH(i) = 1; indH(1) = i;\n H = permute(H, indH);\n end\n data = imfilter(data, H, 'same', 0);\n end\nend\nend\n\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "NTCColumbia/ntc_CNMF-master", "name": "greedyROI2d_ROIList.m", "ext": ".m", "path": "ntc_CNMF-master/greedyROI2d_ROIList.m", "size": 5712, "source_encoding": "utf_8", "md5": "818b3c28af8114f845d0d45e7bd8ce1c", "text": "function [basis, trace, center, data] = greedyROI2d_ROIList(data, K, params, ROIList)\n%greedyROI2d using greedy algorithm to identify neurons in 2d calcium movie\n%\n%Usage: [basis, trace, center, res] = greedyROI2d(data, K, params)\n%\n%Input:\n%data M x N x T movie, raw data, each column is a vectorized movie\n%K number of neurons to extract\n%params tuning parameter for fine-tuning the shape (optional)\n% params.nIter: number of iterations for shape tuning (default 5)\n% params.gSig: variance of Gaussian kernel to use (default 5)\n% params.gSiz: size of kernel (default 11)\n%ROIList two column matrix that contains the x and y coordinate of the ROIs\n%\n%Output:\n%basis M x N x K matrix, location of each neuron\n%trace T x K matrix, calcium activity of each neuron\n%center K x 2 matrix, inferred center of each neuron\n%res M x N x T movie, residual\n%\n%Author: Yuanjun Gao\n%Modified by Weijian Yang\n\n[M, N, T] = size(data);\n\nmed = median(data, 3);\ndata = bsxfun(@minus, data, med);\n\nif ~exist('K', 'var'), %find K neurons\n K = 30; \n warning(['number of neurons are not specified, set to be the default value', num2str(K)]);\nend\n\nif ~exist('params', 'var') params = []; end\n\nif ~isfield(params, 'gSig'), gSig = [5, 5]; \nelseif length(params.gSig) == 1, gSig = params.gSig + zeros(1,2); end\n\nif ~isfield(params, 'gSiz'), gSiz = [11, 11];\nelseif length(params.gSiz) == 1, gSiz = params.gSiz + zeros(1,2); end\n\nif ~isfield(params, 'nIter'), nIter = 5; \nelse nIter = params.nIter; end\n\nK=size(ROIList,1);\n\nbasis = zeros(M, N, K);\ntrace = zeros(T, K);\ncenter = zeros(K, 2);\n\ngHalf = floor(gSiz / 2); %half size of the kernel, used to calculate margin\ngSiz = 2 * gHalf + 1; %actual size\n\n%scan the whole image (only need to do this at the first iteration)\nrho = imblur(data, gSig, gSiz); %covariance of data and basis\nv = sum(rho.^2, 3); %variance explained\n\nfor k = 1:K, \n% [~, ind] = max(v(:));\n% [iHat, jHat] = ind2sub([M, N], ind);\n iHat=ROIList(k,2); % Note that x and y is switched\n jHat=ROIList(k,1); % Note that x and y is switched\n center(k, 1) = iHat; center(k, 2) = jHat;\n \n iSig = [max(iHat - gHalf(1), 1), min(iHat + gHalf(1), M)]; iSigLen = iSig(2) - iSig(1) + 1;\n jSig = [max(jHat - gHalf(2), 1), min(jHat + gHalf(2), N)]; jSigLen = jSig(2) - jSig(1) + 1;\n \n %fine tune the shape\n dataTemp = data(iSig(1):iSig(2), jSig(1):jSig(2), :);\n traceTemp = rho(iHat, jHat, :);\n [coef, score] = finetune2d(dataTemp, traceTemp, nIter); \n \n dataSig = bsxfun(@times, coef, reshape(score, [1,1,T]));\n basis(iSig(1):iSig(2), jSig(1):jSig(2), k) = coef;\n trace(:, k) = score';\n \n data(iSig(1):iSig(2), jSig(1):jSig(2), :) = data(iSig(1):iSig(2), jSig(1):jSig(2), :) - dataSig; %update residual\n fprintf('found %i out of %i neurons..\\n', k,K);\n \n %get next basis;\n if k < K,\n iMod = [max(iHat - 2 * gHalf(1), 1), min(iHat + 2 * gHalf(1), M)]; iModLen = iMod(2) - iMod(1) + 1;%patches to modify\n jMod = [max(jHat - 2 * gHalf(2), 1), min(jHat + 2 * gHalf(2), N)]; jModLen = jMod(2) - jMod(1) + 1;\n iLag = iSig - iMod(1) + 1; %relative location of iSig in the small patch\n jLag = jSig - jMod(1) + 1;\n dataTemp = zeros(iModLen, jModLen);\n dataTemp(iLag(1):iLag(2), jLag(1):jLag(2)) = reshape(coef, [iSigLen, jSigLen]);\n dataTemp = imblur(dataTemp, gSig, gSiz, 2);\n rhoTemp = bsxfun(@times, dataTemp, reshape(score, [1,1,T]));\n rhoTemp = rho(iMod(1):iMod(2), jMod(1):jMod(2), :) - rhoTemp;\n rho(iMod(1):iMod(2), jMod(1):jMod(2), :) = rhoTemp;\n v(iMod(1):iMod(2), jMod(1):jMod(2)) = sum(rhoTemp.^2, 3);\n end\nend\n\n%basis = reshape(basis, [M * N, K]);\n\n\nfunction [basis, trace] = finetune2d(data, trace, nIter)\n%using matrix factorization with lasso penalty to fine-tune the basis\n%\n%Input:\n%data M x N x T matrix, small patch containing one neuron\n%trace initial value for trace\n%nIter number of coordinate descent steps\n%\n%Output:\n%basis M x N matrix, result of the fine-tuned neuron shape\n%trace 1 x T matrix, result of the neuron\n\nT = size(data, 3);\nif ~exist('nIter', 'var'), nIter = 1; end\n\n%do block coordinate descent\nfor iter = 1:nIter,\n %update basis\n a = sum(trace.^2); %scale by num. of observation\n b = sum(bsxfun(@times, data, reshape(trace, [1,1,T])), 3);\n basis = max(b / a, 0);\n basisNorm = norm(basis(:));\n if basisNorm > 0, \n basis = basis / basisNorm; \n else\n fprintf('get degenerate basis!\\n')\n break\n end\n \n %updating trace\n trace = bsxfun(@times, data, basis);\n trace = squeeze(sum(sum(trace, 1), 2)); \nend\nend\n\n\n\nfunction data = imblur(data, sig, siz, nDimBlur)\n%Gaussian blur for high dimensional data\n%Input:\n%data original data\n%sig std of gaussian kernel\n%siz size of kernel\n%nDimBlur number of dims to blur (default: ndims(data) - 1)\n%\n%Output:\n%data result after the Gaussian blur\n\nif ~exist('nDimBlur', 'var'), nDimBlur = ndims(data) - 1; \nelse nDimBlur = min(nDimBlur, ndims(data)); end\n\nif length(sig) == 1, sig = sig * ones(1,nDimBlur); end\nassert(nDimBlur == length(sig));\n\nif length(siz) == 1, siz = siz * ones(1,nDimBlur); end\nassert(nDimBlur == length(siz));\n\nfor i = 1:nDimBlur,\n if sig(i) > 0,\n x = -floor(siz(i) / 2):floor(siz(i) / 2);\n H = exp(-(x.^2/ (2 * sig(i)^2)));\n H = H' / norm(H(:));\n if nDimBlur > 1,\n indH = 1:nDimBlur; indH(i) = 1; indH(1) = i;\n H = permute(H, indH);\n end\n data = imfilter(data, H, 'same', 0);\n end\nend\nend\n\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "NTCColumbia/ntc_CNMF-master", "name": "greedyROI2d_multiscale.m", "ext": ".m", "path": "ntc_CNMF-master/greedyROI2d_multiscale.m", "size": 8289, "source_encoding": "utf_8", "md5": "122cf71e85924dcd91b0d493b6e297d4", "text": "function [basis, trace, center, data] = greedyROI2d_multiscale(data, K, K2, params)\n%greedyROI2d using greedy algorithm to identify neurons in 2d calcium movie\n%\n%Usage: [basis, trace, center, res] = greedyROI2d(data, K, params)\n%\n%Input:\n%data M x N x T movie, raw data, each column is a vectorized movie\n%K number of neurons with large spatial scale to extract\n%K2 number of neurons with small spatial scale to extract\n%params tuning parameter for fine-tuning the shape (optional)\n% params.nIter: number of iterations for shape tuning (default 5)\n% params.gSig: variance of Gaussian kernel to use for large scale ROIs (default 5)\n% params.gSiz: size of kernel for large scale ROIs (default 11)\n% params.gSigSmallScale: variance of Gaussian kernel to use for small scale ROIs (default 2)\n% params.gSizSmallScale: size of kernel for small scale ROIs (default 6)\n%\n%Output:\n%basis M x N x K matrix, location of each neuron\n%trace T x K matrix, calcium activity of each neuron\n%center K x 2 matrix, inferred center of each neuron\n%res M x N x T movie, residual\n%\n%Author: Yuanjun Gao\n%Modified by Weijian Yang\n\n[M, N, T] = size(data);\n\nmed = median(data, 3);\ndata = bsxfun(@minus, data, med);\n\nif ~exist('K', 'var'), %find K neurons\n K = 30; \n warning(['number of neurons are not specified, set to be the default value', num2str(K)]);\nend\nif ~exist('K2', 'var'), %find K neurons\n K2 = 30; \n warning(['number of neurons are not specified, set to be the default value', num2str(K)]);\nend\nif ~exist('params', 'var') params = []; end\n\nif ~isfield(params, 'gSig'), gSig = [5, 5]; \nelseif length(params.gSig) == 1, gSig = params.gSig + zeros(1,2); end\n\nif ~isfield(params, 'gSiz'), gSiz = [11, 11];\nelseif length(params.gSiz) == 1, gSiz = params.gSiz + zeros(1,2); end\n\nif ~isfield(params, 'gSigSmallScale'), gSigSmallScale = [2, 2]; \nelseif length(params.gSigSmallScale) == 1, gSigSmallScale = params.gSigSmallScale + zeros(1,2); end\n\nif ~isfield(params, 'gSizSmallScale'), gSizSmallScale = [6, 6];\nelseif length(params.gSizSmallScale) == 1, gSizSmallScale = params.gSizSmallScale + zeros(1,2); end\n\nif ~isfield(params, 'nIter'), nIter = 5; \nelse nIter = params.nIter; end\n\nbasis = zeros(M, N, K+K2);\ntrace = zeros(T, K+K2);\ncenter = zeros(K+K2, 2);\n\ngHalf = floor(gSiz / 2); %half size of the kernel, used to calculate margin\ngSiz = 2 * gHalf + 1; %actual size\n\n%% first run to get the center of the large ROIs\n%scan the whole image (only need to do this at the first iteration)\nrho = imblur(data, gSig, gSiz); %covariance of data and basis\nv = sum(rho.^2, 3); %variance explained\n\nfor k = 1:K\n [~, ind] = max(v(:));\n [iHat, jHat] = ind2sub([M, N], ind);\n center(k, 1) = iHat; center(k, 2) = jHat;\n \n iSig = [max(iHat - gHalf(1), 1), min(iHat + gHalf(1), M)]; iSigLen = iSig(2) - iSig(1) + 1;\n jSig = [max(jHat - gHalf(2), 1), min(jHat + gHalf(2), N)]; jSigLen = jSig(2) - jSig(1) + 1;\n \n %fine tune the shape\n dataTemp = data(iSig(1):iSig(2), jSig(1):jSig(2), :);\n traceTemp = rho(iHat, jHat, :);\n [coef, score] = finetune2d(dataTemp, traceTemp, nIter); \n \n dataSig = bsxfun(@times, coef, reshape(score, [1,1,T]));\n basis(iSig(1):iSig(2), jSig(1):jSig(2), k) = coef;\n trace(:, k) = score';\n \n data(iSig(1):iSig(2), jSig(1):jSig(2), :) = data(iSig(1):iSig(2), jSig(1):jSig(2), :) - dataSig; %update residual\n fprintf('found %i out of %i neurons..\\n', k,K);\n \n %get next basis;\n if k < K,\n iMod = [max(iHat - 2 * gHalf(1), 1), min(iHat + 2 * gHalf(1), M)]; iModLen = iMod(2) - iMod(1) + 1;%patches to modify\n jMod = [max(jHat - 2 * gHalf(2), 1), min(jHat + 2 * gHalf(2), N)]; jModLen = jMod(2) - jMod(1) + 1;\n iLag = iSig - iMod(1) + 1; %relative location of iSig in the small patch\n jLag = jSig - jMod(1) + 1;\n dataTemp = zeros(iModLen, jModLen);\n dataTemp(iLag(1):iLag(2), jLag(1):jLag(2)) = reshape(coef, [iSigLen, jSigLen]);\n dataTemp = imblur(dataTemp, gSig, gSiz, 2);\n rhoTemp = bsxfun(@times, dataTemp, reshape(score, [1,1,T]));\n rhoTemp = rho(iMod(1):iMod(2), jMod(1):jMod(2), :) - rhoTemp;\n rho(iMod(1):iMod(2), jMod(1):jMod(2), :) = rhoTemp;\n v(iMod(1):iMod(2), jMod(1):jMod(2)) = sum(rhoTemp.^2, 3);\n end\nend\n\n%% Second run to get the center of small ROIs\nrho = imblur(data, gSigSmallScale, gSizSmallScale); %covariance of data and basis\nv = sum(rho.^2, 3); %variance explained\n\nfor k = 1:K+K2\n if k>K\n [~, ind] = max(v(:));\n [iHat, jHat] = ind2sub([M, N], ind);\n center(k, 1) = iHat; center(k, 2) = jHat;\n else\n iHat=center(k,1); jHat=center(k,2);\n end\n \n iSig = [max(iHat - gHalf(1), 1), min(iHat + gHalf(1), M)]; iSigLen = iSig(2) - iSig(1) + 1;\n jSig = [max(jHat - gHalf(2), 1), min(jHat + gHalf(2), N)]; jSigLen = jSig(2) - jSig(1) + 1;\n \n %fine tune the shape\n dataTemp = data(iSig(1):iSig(2), jSig(1):jSig(2), :);\n traceTemp = rho(iHat, jHat, :);\n [coef, score] = finetune2d(dataTemp, traceTemp, nIter); \n \n dataSig = bsxfun(@times, coef, reshape(score, [1,1,T]));\n basis(iSig(1):iSig(2), jSig(1):jSig(2), k) = coef;\n trace(:, k) = score';\n \n data(iSig(1):iSig(2), jSig(1):jSig(2), :) = data(iSig(1):iSig(2), jSig(1):jSig(2), :) - dataSig; %update residual\n fprintf('found %i out of %i neurons..\\n', k,K+K2);\n \n %get next basis;\n if k < K+K2\n iMod = [max(iHat - 2 * gHalf(1), 1), min(iHat + 2 * gHalf(1), M)]; iModLen = iMod(2) - iMod(1) + 1;%patches to modify\n jMod = [max(jHat - 2 * gHalf(2), 1), min(jHat + 2 * gHalf(2), N)]; jModLen = jMod(2) - jMod(1) + 1;\n iLag = iSig - iMod(1) + 1; %relative location of iSig in the small patch\n jLag = jSig - jMod(1) + 1;\n dataTemp = zeros(iModLen, jModLen);\n dataTemp(iLag(1):iLag(2), jLag(1):jLag(2)) = reshape(coef, [iSigLen, jSigLen]);\n dataTemp = imblur(dataTemp, gSigSmallScale, gSizSmallScale, 2);\n rhoTemp = bsxfun(@times, dataTemp, reshape(score, [1,1,T]));\n rhoTemp = rho(iMod(1):iMod(2), jMod(1):jMod(2), :) - rhoTemp;\n rho(iMod(1):iMod(2), jMod(1):jMod(2), :) = rhoTemp;\n v(iMod(1):iMod(2), jMod(1):jMod(2)) = sum(rhoTemp.^2, 3);\n end\nend\n\n%%\nfunction [basis, trace] = finetune2d(data, trace, nIter)\n%using matrix factorization with lasso penalty to fine-tune the basis\n%\n%Input:\n%data M x N x T matrix, small patch containing one neuron\n%trace initial value for trace\n%nIter number of coordinate descent steps\n%\n%Output:\n%basis M x N matrix, result of the fine-tuned neuron shape\n%trace 1 x T matrix, result of the neuron\n\nT = size(data, 3);\nif ~exist('nIter', 'var'), nIter = 1; end\n\n%do block coordinate descent\nfor iter = 1:nIter,\n %update basis\n a = sum(trace.^2); %scale by num. of observation\n b = sum(bsxfun(@times, data, reshape(trace, [1,1,T])), 3);\n basis = max(b / a, 0);\n basisNorm = norm(basis(:));\n if basisNorm > 0, \n basis = basis / basisNorm; \n else\n fprintf('get degenerate basis!\\n')\n break\n end\n \n %updating trace\n trace = bsxfun(@times, data, basis);\n trace = squeeze(sum(sum(trace, 1), 2)); \nend\nend\n\n\n\nfunction data = imblur(data, sig, siz, nDimBlur)\n%Gaussian blur for high dimensional data\n%Input:\n%data original data\n%sig std of gaussian kernel\n%siz size of kernel\n%nDimBlur number of dims to blur (default: ndims(data) - 1)\n%\n%Output:\n%data result after the Gaussian blur\n\nif ~exist('nDimBlur', 'var'), nDimBlur = ndims(data) - 1; \nelse nDimBlur = min(nDimBlur, ndims(data)); end\n\nif length(sig) == 1, sig = sig * ones(1,nDimBlur); end\nassert(nDimBlur == length(sig));\n\nif length(siz) == 1, siz = siz * ones(1,nDimBlur); end\nassert(nDimBlur == length(siz));\n\nfor i = 1:nDimBlur,\n if sig(i) > 0,\n x = -floor(siz(i) / 2):floor(siz(i) / 2);\n H = exp(-(x.^2/ (2 * sig(i)^2)));\n H = H' / norm(H(:));\n if nDimBlur > 1,\n indH = 1:nDimBlur; indH(i) = 1; indH(1) = i;\n H = permute(H, indH);\n end\n data = imfilter(data, H, 'same', 0);\n end\nend\nend\n\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "f48net_c.m", "ext": ".m", "path": "2015_Face_Detection-master/f48net_c.m", "size": 2104, "source_encoding": "utf_8", "md5": "375f888e903269c98c8277feb9450d80", "text": "function net = f48net_c()\n\nopts.useBnorm = true ;\n\nnet.layers = {} ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(5,5,3,64, 'single'), zeros(1, 64, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n%net.layers{end+1} = struct('type', 'normalize', 'name', 'norm1', ...\n % 'param', [9 1 0.0001/5 0.75]) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.05*randn(5,5,64,64, 'single'), zeros(1, 64, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\n%net.layers{end+1} = struct('type', 'normalize', 'name', 'norm1', ...\n % 'param', [9 1 0.0001/5 0.75]) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.05*randn(2,2,64,1, 'single'), zeros(1, 1, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'fc_custom') ;\nnet.layers{end+1} = struct('type', 'relu') ;\n%net.layers{end+1} = struct('type', 'dropout', 'rate', 0.5) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.05*randn(1,1,256,45, 'single'), zeros(1, 45, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n% optionally switch to batch normalization\nif opts.useBnorm\n net = insertBnorm(net, 1) ;\n net = insertBnorm(net, 4) ;\n net = insertBnorm(net, 7) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = insertBnorm(net, l)\n% --------------------------------------------------------------------\nassert(isfield(net.layers{l}, 'weights'));\nndim = size(net.layers{l}.weights{1}, 4);\nlayer = struct('type', 'bnorm', ...\n 'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...\n 'learningRate', [1 1], ...\n 'weightDecay', [0 0]) ;\nnet.layers{l}.biases = [] ;\nnet.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cascadeface_12c.m", "ext": ".m", "path": "2015_Face_Detection-master/cascadeface_12c.m", "size": 2345, "source_encoding": "utf_8", "md5": "c7e5100f103c6be18b3d6ba02cbd0390", "text": "function cascadeface_12c(varargin)\nsetup;\n% -------------------------------------------------------------------------\n% Part 4.1: prepare the data\n% -------------------------------------------------------------------------\n\n% Load character dataset\nimdb = load('../../aflw/positive_c.mat') ;\nimdb = imdb.imdb;\nimdb.meta.sets=['train','val'];\nss = size(imdb.images.label);\nimdb.images.set = ones(1,ss(2));\nimdb.images.set(ceil(rand(1,ceil(ss(2)/5))*ss(2))) = 2;\n% -------------------------------------------------------------------------\n% Part 4.2: initialize a CNN architecture\n% -------------------------------------------------------------------------\n\nnet = f12net_c() ;\n\n% -------------------------------------------------------------------------\n% Part 4.3: train and evaluate the CNN\n% -------------------------------------------------------------------------\n\nopts.train.batchSize = 256 ;\nopts.train.numSubBatches = 1 ;\nopts.train.continue = true ;\nopts.train.gpus = 3 ;\n%opts.train.prefetch = true ;\nopts.train.sync = false ;\nopts.train.errorFunction = 'multiclass' ;\nopts.train.expDir = 'data/12net-cc-v1-v1.0-dropout0.5-pad2/' ;\nopts.train.learningRate = [0.05*ones(1,25),0.005*ones(1,15),0.0005*ones(1,7)] ;\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n[opts, varargin] = vl_argparse(opts.train, varargin) ;\n\n% Take the average image out\nimageMean = mean(imdb.images.data12(:)) ;\nimdb.images.data12 = imdb.images.data12 - imageMean ;\n\n% Call training function in MatConvNet\n[net,info] = cnn_train(net, imdb, @getBatch, opts) ;\n\n% Save the result for later use\nnet.layers(end) = [] ;\nnet.imageMean = imageMean ;\nsave(strcat(opts.expDir,'f12netc.mat'), '-struct', 'net') ;\n\n% -------------------------------------------------------------------------\n% Part 4.4: visualize the learned filters\n% -------------------------------------------------------------------------\n\nfigure(2) ; clf ; colormap gray ;\nvl_imarraysc(squeeze(net.layers{1}.weights{1}),'spacing',2)\naxis equal ; title('filters in the first layer') ;\n\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data12(:,:,:,batch) ;\nim = 256 * reshape(im, 12, 12, 3, []) ;\nlabels = imdb.images.label(1,batch) ;\n\n\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "f12net_c.m", "ext": ".m", "path": "2015_Face_Detection-master/f12net_c.m", "size": 1762, "source_encoding": "utf_8", "md5": "1be995c1e17799168617d7f192323ef7", "text": "function net = f12net_c()\n\nlr = [.1 2] ;\n\nopts.useBnorm = true ;\n\nnet.layers = {} ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(3,3,3,16, 'single'), zeros(1, 16, 'single')}}, ...\n 'stride', 1, ...\n 'learningRate', lr, ...\n 'pad', 2) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.05*randn(6,6,16,128, 'single'), zeros(1, 128, 'single')}}, ...\n 'stride', 1, ...\n 'learningRate', lr, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'dropout', 'rate', 0.5) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.05*randn(1,1,128,45, 'single'), zeros(1, 45, 'single')}}, ...\n 'stride', 1, ...\n 'learningRate', .1*lr, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n% optionally switch to batch normalization\nif opts.useBnorm\n net = insertBnorm(net, 1) ;\n net = insertBnorm(net, 5) ;\n net = insertBnorm(net, 9) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = insertBnorm(net, l)\n% --------------------------------------------------------------------\nassert(isfield(net.layers{l}, 'weights'));\nndim = size(net.layers{l}.weights{1}, 4);\nlayer = struct('type', 'bnorm', ...\n 'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...\n 'learningRate', [1 1], ...\n 'weightDecay', [0 0]) ;\nnet.layers{l}.biases = [] ;\nnet.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cascadeface_12net.m", "ext": ".m", "path": "2015_Face_Detection-master/cascadeface_12net.m", "size": 2332, "source_encoding": "utf_8", "md5": "b1c2a3b8a2b6c4e33899d7997deabbe3", "text": "function cascadeface_12net(varargin)\n% -------------------------------------------------------------------------\n% Part 4.1: prepare the data\n% -------------------------------------------------------------------------\n\n% Load character dataset\nimdb = load('../../aflw/imdb12_v2_extended.mat') ;\nimdb = imdb.imdb;\nimdb.meta.sets=['train','val'];\nss = size(imdb.images.label);\nimdb.images.set = ones(1,ss(2));\nimdb.images.set(ceil(rand(1,ceil(ss(2)/5))*ss(2))) = 2;\n% -------------------------------------------------------------------------\n% Part 4.2: initialize a CNN architecture\n% -------------------------------------------------------------------------\n\nnet = f12net() ;\n\n% -------------------------------------------------------------------------\n% Part 4.3: train and evaluate the CNN\n% -------------------------------------------------------------------------\n\nopts.train.batchSize = 256 ;\nopts.train.numSubBatches = 1 ;\nopts.train.continue = true ;\nopts.train.gpus = 3 ;\n%opts.train.prefetch = true ;\nopts.train.sync = false ;\nopts.train.errorFunction = 'binary' ;\nopts.train.expDir = 'data/12netv2-v2.0-test/' ;\nopts.train.learningRate = [0.001*ones(1,70),0.0001*ones(1,20),0.00001*ones(1,5)] ;\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n[opts, varargin] = vl_argparse(opts.train, varargin) ;\n\n% Take the average image out\nimageMean = mean(imdb.images.data(:)) ;\nimdb.images.data = imdb.images.data - imageMean ;\n% Call training function in MatConvNet\n[net,info] = cnn_train(net, imdb, @getBatch,opts) ;\n\n% Save the result for later use\nnet.layers(end) = [] ;\nnet.imageMean = imageMean ;\nsave(strcat(opts.expDir,'f12net.mat'), '-struct', 'net') ;\n\n% -------------------------------------------------------------------------\n% Part 4.4: visualize the learned filters\n% -------------------------------------------------------------------------\n\nfigure(2) ; clf ; colormap gray ;\nvl_imarraysc(squeeze(net.layers{1}.filters),'spacing',2)\naxis equal ; title('filters in the first layer') ;\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nim = 256 * reshape(im, 12, 12, 3, []) ;\nlabels = imdb.images.label(1,batch) ;\n%im = gpuArray(im) ;"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cascadeface_48net.m", "ext": ".m", "path": "2015_Face_Detection-master/cascadeface_48net.m", "size": 2601, "source_encoding": "utf_8", "md5": "a63382e5fb528ba3778ab2932a879913", "text": "function cascadeface_48net(varargin)\n% -------------------------------------------------------------------------\n% Part 4.1: prepare the data\n% -------------------------------------------------------------------------\n\n% Load character dataset\nimdb = load('../../aflw/matlab/imdb48_v1.mat') ;\nimdb = imdb.imdb;\nimdb.meta.sets=['train','val'];\nss = size(imdb.images.label);\nimdb.images.set = ones(1,ss(2));\nimdb.images.set(ceil(rand(1,ceil(ss(2)/5))*ss(2))) = 2;\n% -------------------------------------------------------------------------\n% Part 4.2: initialize a CNN architecture\n% -------------------------------------------------------------------------\n\nnet = f48net_v2() ;\n\n% -------------------------------------------------------------------------\n% Part 4.3: train and evaluate the CNN\n% -------------------------------------------------------------------------\n\nopts.train.batchSize = 256 ;\n%opts.train.numSubBatches = 1 ;\nopts.train.continue = true;\nopts.train.gpus = 3;\nopts.whitenData = true ;\nopts.contrastNormalization = true ;\n%opts.train.prefetch = true ;\nopts.train.sync = false ;\nopts.train.errorFunction = 'binary' ;\nopts.train.expDir = 'data/48net-v2.0-dropout0.8-normb1/' ;\nopts.train.learningRate = [0.05*ones(1,15) 0.005*ones(1,10)] ;\n%opts.train.weightDecay = 0.0001 ;\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n[opts, ~] = vl_argparse(opts.train, varargin) ;\n\n% Take the average image out\nimageMean = mean(imdb.images.data(:)) ;\nimdb.images.data = imdb.images.data - imageMean ;\nnet.imageMean = imageMean ;\n\nglobal net48;\nnet48 = net;\nglobal net24;\nnet24 = load('./data/24net-v2.0/f24net.mat');\nglobal net12;\nnet12 = load('./data/12netv2-v2.0/f12net.mat');\n% Call training function in MatConvNet\n[net,info] = cnn_train(net, imdb, @getBatch,opts) ;\n\n% Save the result for later use\nnet.layers(end) = [] ;\nnet = vl_simplenn_move(net,'cpu');\nsave(strcat(opts.expDir,'f48net.mat'), '-struct', 'net') ;\n\n% -------------------------------------------------------------------------\n% Part 4.4: visualize the learned filters\n% -------------------------------------------------------------------------\n\nfigure(2) ; clf ; colormap gray ;\nvl_imarraysc(squeeze(net.layers{1}.weights{1}),'spacing',2)\naxis equal ; title('filters in the first layer') ;\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nim = 256 * reshape(im, 48, 48, 3, []) ;\nlabels = imdb.images.label(1,batch) ;\n%im = gpuArray(im) ;"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "f24net_normB.m", "ext": ".m", "path": "2015_Face_Detection-master/f24net_normB.m", "size": 1596, "source_encoding": "utf_8", "md5": "8e2ee3a41fb92da9a24e4918514c167a", "text": "function net = f24net()\n\nopts.useBnorm = true ;\n\nnet.layers = {} ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(5,5,3,64, 'single'), zeros(1, 64, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(9,9,64,128, 'single'), zeros(1, 128, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'custom', ...\n 'weights', {{0.01*randn(1,1,144,2, 'single'), zeros(1, 2, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n% optionally switch to batch normalization\nif opts.useBnorm\n net = insertBnorm(net, 1) ;\n net = insertBnorm(net, 5) ;\n net = insertBnorm(net, 8) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = insertBnorm(net, l)\n% --------------------------------------------------------------------\nassert(isfield(net.layers{l}, 'weights'));\nndim = size(net.layers{l}.weights{1}, 4);\nlayer = struct('type', 'bnorm', ...\n 'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...\n 'learningRate', [1 1], ...\n 'weightDecay', [0 0]) ;\nnet.layers{l}.biases = [] ;\nnet.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "patch_nn.m", "ext": ".m", "path": "2015_Face_Detection-master/patch_nn.m", "size": 253, "source_encoding": "utf_8", "md5": "7719f1b84bc7ec9a0866786a45c9fd17", "text": "% --------------------------------------------------------------------\r\nfunction array2 = patch_nn(net,patch)\r\n% --------------------------------------------------------------------\r\nres12 = vl_simplenn(net,patch) ;\r\narray2 = reshape(res12(end).x,2,[]);"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "f24net_c.m", "ext": ".m", "path": "2015_Face_Detection-master/f24net_c.m", "size": 1631, "source_encoding": "utf_8", "md5": "9852ad8f8de1a2cf48fced1c8d754c11", "text": "function net = f24net_c()\n\nopts.useBnorm = true ;\n\nnet.layers = {} ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(5,5,3,32, 'single'), zeros(1, 32, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(9,9,32,64, 'single'), zeros(1, 64, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'dropout', 'rate', 0.5) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.05*randn(1,1,64,45, 'single'), zeros(1, 45, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n% optionally switch to batch normalization\nif opts.useBnorm\n net = insertBnorm(net, 1) ;\n net = insertBnorm(net, 5) ;\n %net = insertBnorm(net, 8) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = insertBnorm(net, l)\n% --------------------------------------------------------------------\nassert(isfield(net.layers{l}, 'weights'));\nndim = size(net.layers{l}.weights{1}, 4);\nlayer = struct('type', 'bnorm', ...\n 'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...\n 'learningRate', [1 1], ...\n 'weightDecay', [0 0]) ;\nnet.layers{l}.biases = [] ;\nnet.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cascadeface_24net_normB.m", "ext": ".m", "path": "2015_Face_Detection-master/cascadeface_24net_normB.m", "size": 2421, "source_encoding": "utf_8", "md5": "9a719719f91c6b78d9b4a422b6d11ab1", "text": "function cascadeface_24net_normB(varargin)\n% -------------------------------------------------------------------------\n% Part 4.1: prepare the data\n% -------------------------------------------------------------------------\n\n% Load character dataset\nimdb = load('../../aflw/matlab/imdb24_v2.mat') ;\nimdb = imdb.imdb;\nimdb.meta.sets=['train','val'];\nss = size(imdb.images.label);\nimdb.images.set = ones(1,ss(2));\nimdb.images.set(ceil(rand(1,ceil(ss(2)/5))*ss(2))) = 2;\n% -------------------------------------------------------------------------\n% Part 4.2: initialize a CNN architecture\n% -------------------------------------------------------------------------\n\nnet = f24net_normB() ;\n\n% -------------------------------------------------------------------------\n% Part 4.3: train and evaluate the CNN\n% -------------------------------------------------------------------------\n\nopts.train.batchSize = 256 ;\n%opts.train.numSubBatches = 1 ;\nopts.train.continue = false ;\nopts.train.gpus = 3 ;\n%opts.train.prefetch = true ;\nopts.train.sync = false ;\nopts.train.errorFunction = 'binary' ;\nopts.train.expDir = 'data/24net-v2.0-normB/' ;\nopts.train.learningRate = [0.003*ones(1,70),0.0005*ones(1,20)] ;\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n[opts, varargin] = vl_argparse(opts.train, varargin) ;\n\n% Take the average image out\nimageMean = mean(imdb.images.data(:)) ;\nimdb.images.data = imdb.images.data - imageMean ;\nnet.imageMean = imageMean ;\n\nglobal net24;\nnet24 = net;\nglobal net12;\nnet12 = load('./data/12netv2-v2.0/f12net.mat');\n% Call training function in MatConvNet\n[net,info] = cnn_train(net, imdb, @getBatch,opts) ;\n\n% Save the result for later use\nnet.layers(end) = [] ;\nsave(strcat(opts.expDir,'f24net-normB.mat'), '-struct', 'net') ;\n\n% -------------------------------------------------------------------------\n% Part 4.4: visualize the learned filters\n% -------------------------------------------------------------------------\n\nfigure(2) ; clf ; colormap gray ;\nvl_imarraysc(squeeze(net.layers{1}.filters),'spacing',2)\naxis equal ; title('filters in the first layer') ;\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nim = 256 * reshape(im, 24, 24, 3, []) ;\nlabels = imdb.images.label(1,batch) ;\n%im = gpuArray(im) ;"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cascadeface_24c.m", "ext": ".m", "path": "2015_Face_Detection-master/cascadeface_24c.m", "size": 2321, "source_encoding": "utf_8", "md5": "523ec695a26d03d9e0b62d66a0021cce", "text": "function cascadeface_24c(varargin)\nsetup;\n% -------------------------------------------------------------------------\n% Part 4.1: prepare the data\n% -------------------------------------------------------------------------\n\n% Load character dataset\nimdb = load('../../aflw/positive_c.mat') ;\nimdb = imdb.imdb;\nimdb.meta.sets=['train','val'];\nss = size(imdb.images.label);\nimdb.images.set = ones(1,ss(2));\nimdb.images.set(ceil(rand(1,ceil(ss(2)/5))*ss(2))) = 2;\n% -------------------------------------------------------------------------\n% Part 4.2: initialize a CNN architecture\n% -------------------------------------------------------------------------\n\nnet = f24net_c() ;\n\n% -------------------------------------------------------------------------\n% Part 4.3: train and evaluate the CNN\n% -------------------------------------------------------------------------\n\nopts.train.batchSize = 256 ;\nopts.train.numSubBatches = 1 ;\nopts.train.continue = true ;\nopts.train.gpus = 4 ;\n%opts.train.prefetch = true ;\nopts.train.sync = false ;\nopts.train.errorFunction = 'multiclass' ;\nopts.train.expDir = 'data/24net-cc-v1-v1.0-dropout0.5/' ;\nopts.train.learningRate = [0.001*ones(1,23),0.0001*ones(1,10)] ;\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n[opts, varargin] = vl_argparse(opts.train, varargin) ;\n\n% Take the average image out\nimageMean = mean(imdb.images.data24(:)) ;\nimdb.images.data24 = imdb.images.data24 - imageMean ;\n\n% Call training function in MatConvNet\n[net,info] = cnn_train(net, imdb, @getBatch, opts) ;\n\n% Save the result for later use\nnet.layers(end) = [] ;\nnet.imageMean = imageMean ;\nsave(strcat(opts.expDir,'f24netc.mat'), '-struct', 'net') ;\n\n% -------------------------------------------------------------------------\n% Part 4.4: visualize the learned filters\n% -------------------------------------------------------------------------\n\nfigure(2) ; clf ; colormap gray ;\nvl_imarraysc(squeeze(net.layers{1}.weights{1}),'spacing',2)\naxis equal ; title('filters in the first layer') ;\n\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data24(:,:,:,batch) ;\nim = 256 * reshape(im, 24, 24, 3, []) ;\nlabels = imdb.images.label(1,batch) ;"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cascadeface_24net.m", "ext": ".m", "path": "2015_Face_Detection-master/cascadeface_24net.m", "size": 2464, "source_encoding": "utf_8", "md5": "45c4a7cd0083d1c42bc4a7a857db29ed", "text": "function cascadeface_24net(varargin)\n% -------------------------------------------------------------------------\n% Part 4.1: prepare the data\n% -------------------------------------------------------------------------\n\n% Load character dataset\nimdb = load('../../aflw/matlab/imdb24_v2.mat') ;\nimdb = imdb.imdb;\nimdb.meta.sets=['train','val'];\nss = size(imdb.images.label);\nimdb.images.set = ones(1,ss(2));\nimdb.images.set(ceil(rand(1,ceil(ss(2)/5))*ss(2))) = 2;\n% -------------------------------------------------------------------------\n% Part 4.2: initialize a CNN architecture\n% -------------------------------------------------------------------------\n\nnet = f24net() ;\n\n% -------------------------------------------------------------------------\n% Part 4.3: train and evaluate the CNN\n% -------------------------------------------------------------------------\n\nopts.train.batchSize = 256 ;\n%opts.train.numSubBatches = 1 ;\nopts.train.continue = false ;\nopts.train.gpus = 4;\nopts.whitenData = true ;\nopts.contrastNormalization = true ;\n%opts.train.prefetch = true ;\nopts.train.sync = false ;\nopts.train.errorFunction = 'binary' ;\nopts.train.expDir = 'data/24net-v2.0-dropout0.5/' ;\nopts.train.learningRate = [0.001*ones(1,30),0.0001*ones(1,20)] ;\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n[opts, ~] = vl_argparse(opts.train, varargin) ;\n\n% Take the average image out\nimageMean = mean(imdb.images.data(:)) ;\nimdb.images.data = imdb.images.data - imageMean ;\nnet.imageMean = imageMean ;\n\nglobal net24;\nnet24 = net;\nglobal net12;\nnet12 = load('./data/12netv2-v2.0/f12net.mat');\n% Call training function in MatConvNet\n[net,info] = cnn_train(net, imdb, @getBatch,opts) ;\n\n% Save the result for later use\nnet.layers(end) = [] ;\nsave(strcat(opts.expDir,'f24net.mat'), '-struct', 'net') ;\n\n% -------------------------------------------------------------------------\n% Part 4.4: visualize the learned filters\n% -------------------------------------------------------------------------\n\nfigure(4) ; clf ; colormap gray ;\nvl_imarraysc(squeeze(net.layers{1}.weights{1}),'spacing',2)\naxis equal ; title('filters in the first layer') ;\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nim = 256 * reshape(im, 24, 24, 3, []) ;\nlabels = imdb.images.label(1,batch) ;\n%im = gpuArray(im) ;"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cascadeface_48c.m", "ext": ".m", "path": "2015_Face_Detection-master/cascadeface_48c.m", "size": 2328, "source_encoding": "utf_8", "md5": "a6c31fa253ea74afe1717fbfcd9c15c4", "text": "function cascadeface_48c(varargin)\nsetup;\n% -------------------------------------------------------------------------\n% Part 4.1: prepare the data\n% -------------------------------------------------------------------------\n\n% Load character dataset\nimdb = load('../../aflw/positive_c.mat') ;\nimdb = imdb.imdb;\nimdb.meta.sets=['train','val'];\nss = size(imdb.images.label);\nimdb.images.set = ones(1,ss(2));\nimdb.images.set(ceil(rand(1,ceil(ss(2)/5))*ss(2))) = 2;\n% -------------------------------------------------------------------------\n% Part 4.2: initialize a CNN architecture\n% -------------------------------------------------------------------------\n\nnet = f48net_c_2() ;\n\n% -------------------------------------------------------------------------\n% Part 4.3: train and evaluate the CNN\n% -------------------------------------------------------------------------\n\nopts.train.batchSize = 256 ;\nopts.train.numSubBatches = 1 ;\nopts.train.continue = false ;\nopts.train.gpus = 4 ;\n%opts.train.prefetch = true ;\nopts.train.sync = false ;\nopts.train.errorFunction = 'multiclass' ;\nopts.train.expDir = 'data/48net-cc-v1-v1.0-drop0.5-pad1/' ;\nopts.train.learningRate = [0.05*ones(1,25),0.005*ones(1,20)] ;\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n[opts, varargin] = vl_argparse(opts.train, varargin) ;\n\n% Take the average image out\nimageMean = mean(imdb.images.data48(:)) ;\nimdb.images.data48 = imdb.images.data48 - imageMean ;\n\n% Call training function in MatConvNet\n[net,info] = cnn_train(net, imdb, @getBatch, opts) ;\n\n% Save the result for later use\nnet.layers(end) = [] ;\nnet.imageMean = imageMean ;\nsave(strcat(opts.expDir,'f48netc.mat'), '-struct', 'net') ;\n\n% -------------------------------------------------------------------------\n% Part 4.4: visualize the learned filters\n% -------------------------------------------------------------------------\n\nfigure(2) ; clf ; colormap gray ;\nvl_imarraysc(squeeze(net.layers{1}.weights{1}),'spacing',2)\naxis equal ; title('filters in the first layer') ;\n\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data48(:,:,:,batch) ;\nim = 256 * reshape(im, 48, 48, 3, []) ;\nlabels = imdb.images.label(1,batch) ;\n\n\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cascadeface_48net2.m", "ext": ".m", "path": "2015_Face_Detection-master/cascadeface_48net2.m", "size": 2627, "source_encoding": "utf_8", "md5": "b56d64b301d01a2e4f39b35d285353f9", "text": "function cascadeface_48net(varargin)\n% -------------------------------------------------------------------------\n% Part 4.1: prepare the data\n% -------------------------------------------------------------------------\n\n% Load character dataset\nimdb = load('../../aflw/matlab/imdb48_v1.mat') ;\nimdb = imdb.imdb;\nimdb.meta.sets=['train','val'];\nss = size(imdb.images.label);\nimdb.images.set = ones(1,ss(2));\nimdb.images.set(ceil(rand(1,ceil(ss(2)/5))*ss(2))) = 2;\n% -------------------------------------------------------------------------\n% Part 4.2: initialize a CNN architecture\n% -------------------------------------------------------------------------\n\nnet = f48net() ;\n\n% -------------------------------------------------------------------------\n% Part 4.3: train and evaluate the CNN\n% -------------------------------------------------------------------------\n\nopts.train.batchSize = 256 ;\n%opts.train.numSubBatches = 1 ;\nopts.train.continue = false;\nopts.train.gpus = 3 ;\n%opts.train.prefetch = true ;\nopts.train.sync = false ;\nopts.train.errorFunction = 'binary' ;\nopts.train.expDir = 'data/48net-v1.0-4-dropout/' ;\nopts.train.learningRate = [0.05*ones(1,15) 0.005*ones(1,10) 0.0005*ones(1,5)] ;\nopts.train.weightDecay = 0.0001 ;\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n[opts, ~] = vl_argparse(opts.train, varargin) ;\n\n% Take the average image out\nimageMean = mean(imdb.images.data(:)) ;\nimdb.images.data = imdb.images.data - imageMean ;\nnet.imageMean = imageMean ;\n\nglobal net48;\nnet48 = net;\nglobal net24;\nnet24 = load('./data/24net-v2.0/f24net.mat');\nglobal net12;\nnet12 = load('./data/12netv2-v2.0/f12net.mat');\n%net12 = vl_simplenn_move(net12,'gpu');\n%net24 = vl_simplenn_move(net24,'gpu');\n% Call training function in MatConvNet\n[net,info] = cnn_train(net, imdb, @getBatch,opts) ;\n\n% Save the result for later use\nnet.layers(end) = [] ;\nnet = vl_simplenn_move(net,'cpu');\nsave(strcat(opts.expDir,'f48net.mat'), '-struct', 'net') ;\n\n% -------------------------------------------------------------------------\n% Part 4.4: visualize the learned filters\n% -------------------------------------------------------------------------\n\nfigure(2) ; clf ; colormap gray ;\nvl_imarraysc(squeeze(net.layers{1}.weights{1}),'spacing',2)\naxis equal ; title('filters in the first layer') ;\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nim = 256 * reshape(im, 48, 48, 3, []) ;\nlabels = imdb.images.label(1,batch) ;\n%im = gpuArray(im) ;"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "f24net_imagenet.m", "ext": ".m", "path": "2015_Face_Detection-master/f24net_imagenet.m", "size": 2682, "source_encoding": "utf_8", "md5": "0e9b813e9218a5d0a170743fee5f6a00", "text": "function net = f24net_imagenet(varargin)\n% CNN_IMAGENET_INIT Baseline CNN model\n\nopts.scale = 1 ;\nopts.initBias = 0.1 ;\nopts.weightDecay = 1 ;\nopts = vl_argparse(opts, varargin) ;\n\nnet.layers = {} ;\n\n% Define layers\nnet.layers = {} ;\n\n% Block 1\nnet = add_block(net, opts, 1, 5, 5, 3, 64, 1, 0) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 2\nnet.layers{end+1} = struct('type', 'normalize', 'name', 'norm2', ...\n 'param', [9 1 0.0001/5 0.75]) ;\nnet = add_block(net, opts, 2, 5, 5, 64, 64, 1, 0) ;\nnet.layers{end+1} = struct('type', 'normalize', 'name', 'norm3', ...\n 'param', [9 1 0.0001/5 0.75]) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 3\nnet = add_block(net, opts, 3, 8, 8, 64,256, 1, 1) ;\n\n% Block 4\nnet = add_block(net, opts, 4, 3, 3, 192, 384, 1, 1) ;\n\n% Block 5\nnet = add_block(net, opts, 5, 3, 3, 192, 256, 1, 1) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 6\nnet = add_block(net, opts, 6, 6, 6, 256, 4096, 1, 0) ;\nnet.layers{end+1} = struct('type', 'dropout', 'name', 'dropout6', 'rate', 0.5) ;\n\n\n% Block 7\nnet = add_block(net, opts, 7, 1, 1, 4096, 4096, 1, 0) ;\nnet.layers{end+1} = struct('type', 'dropout', 'name', 'dropout7', 'rate', 0.5) ;\n\n% Block 8\nnet = add_block(net, opts, 8, 1, 1, 4096, 1000, 1, 0) ;\nnet.layers(end) = [] ;\n\n% Block 9\nnet.layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ;\n\nfunction net = add_block(net, opts, id, h, w, in, out, stride, pad)\ninfo = vl_simplenn_display(net) ;\nfc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;\nif fc\n name = 'fc' ;\nelse\n name = 'conv' ;\nend\nnet.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%d', name, id), ...\n 'weights', {{0.01/opts.scale * randn(h, w, in, out, 'single'), []}}, ...\n 'stride', stride, ...\n 'pad', pad, ...\n 'learningRate', [1 2], ...\n 'weightDecay', [opts.weightDecay 0]) ;\nnet.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%d',id)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cascadeface_aflw_24net.m", "ext": ".m", "path": "2015_Face_Detection-master/cascadeface_aflw_24net.m", "size": 2956, "source_encoding": "utf_8", "md5": "9d06c324f8d511cddaaf94f902a6c6cf", "text": "function cascadeface_aflw_24net(varargin)\n\n setup;\n% -------------------------------------------------------------------------\n% Part 4.1: prepare the data\n% -------------------------------------------------------------------------\n\n% Load character dataset\nimdb = load('C:/Users/zhedong/Desktop/face-database/train24net.mat') ;\nimdb = imdb.imdb;\nimdb.meta.sets=['train','val'];\nss = size(imdb.images.label);\nimdb.images.set = ones(1,ss(2));\nimdb.images.set(round(rand(1,60000)*ss(2))) = 2;\n% -------------------------------------------------------------------------\n% Part 4.2: initialize a CNN architecture\n% -------------------------------------------------------------------------\n\nnet = f24net() ;\n\n% -------------------------------------------------------------------------\n% Part 4.3: train and evaluate the CNN\n% -------------------------------------------------------------------------\n\ntrainOpts.batchSize = 128 ;\ntrainOpts.numEpochs = 19 ;\ntrainOpts.continue = true ;\ntrainOpts.useGpu = false ;\ntrainOpts.errorType = 'binary';\ntrainOpts.learningRate = 0.003 ;\ntrainOpts.expDir = 'data/24net-experiment' ;\ntrainOpts = vl_argparse(trainOpts, varargin);\n\n% Take the average image out\nimageMean = mean(imdb.images.data(:)) ;\nimdb.images.data = imdb.images.data - imageMean ;\n\n% Convert to a GPU array if needed\nif trainOpts.useGpu\n imdb.images.data = gpuArray(imdb.images.data) ;\nend\n\n% Call training function in MatConvNet\n[net,info] = cnn_train(net, imdb, @getBatch, trainOpts) ;\n\n% Move the CNN back to the CPU if it was trained on the GPU\nif trainOpts.useGpu\n net = vl_simplenn_move(net, 'cpu') ;\nend\n\n% Save the result for later use\nnet.layers(end) = [] ;\nnet.imageMean = imageMean ;\nsave('data/24net-experiment/f24net.mat', '-struct', 'net') ;\n\n% -------------------------------------------------------------------------\n% Part 4.4: visualize the learned filters\n% -------------------------------------------------------------------------\n\nfigure(2) ; clf ; colormap gray ;\nvl_imarraysc(squeeze(net.layers{1}.filters),'spacing',2)\naxis equal ; title('filters in the first layer') ;\n\n% -------------------------------------------------------------------------\n% Part 4.5: apply the model\n% -------------------------------------------------------------------------\n\n% Load the CNN learned before\nnet = load('data/24net-experiment/f24net.mat') ;\n\n% Load the sentence\nim = imread('data/test3.png');\nim = imresize(im,[24 24]);\nim = im2single(im) ;\nim = 256 * (im - net.imageMean) ;\n\n% Apply the CNN to the larger image\nres = vl_simplenn(net, im) ;\n[value,index]=max(res(8).x);\nif(index==2)\n disp('no face');\nelse\n disp('is face');\nend\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nim = 256 * reshape(im, 24, 24, 3, []) ;\nlabels = imdb.images.label(1,batch) ;\n\n\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "f48net_c_2.m", "ext": ".m", "path": "2015_Face_Detection-master/f48net_c_2.m", "size": 2059, "source_encoding": "utf_8", "md5": "e417ef43c692588f5ea3f6e1f0ec9625", "text": "function net = f48net_c()\n\nopts.useBnorm = true ;\n\nnet.layers = {} ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(5,5,3,64, 'single'), zeros(1, 64, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 1) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n%net.layers{end+1} = struct('type', 'normalize', 'name', 'norm1', ...\n % 'param', [9 1 0.0001/5 0.75]) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.05*randn(5,5,64,64, 'single'), zeros(1, 64, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\n%net.layers{end+1} = struct('type', 'normalize', 'name', 'norm1', ...\n % 'param', [9 1 0.0001/5 0.75]) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.05*randn(18,18,64,256, 'single'), zeros(1, 256, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'dropout', 'rate', 0.5) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.05*randn(1,1,256,45, 'single'), zeros(1, 45, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n% optionally switch to batch normalization\nif opts.useBnorm\n net = insertBnorm(net, 1) ;\n net = insertBnorm(net, 4) ;\n net = insertBnorm(net, 7) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = insertBnorm(net, l)\n% --------------------------------------------------------------------\nassert(isfield(net.layers{l}, 'weights'));\nndim = size(net.layers{l}.weights{1}, 4);\nlayer = struct('type', 'bnorm', ...\n 'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...\n 'learningRate', [1 1], ...\n 'weightDecay', [0 0]) ;\nnet.layers{l}.biases = [] ;\nnet.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "f48net_v2.m", "ext": ".m", "path": "2015_Face_Detection-master/f48net_v2.m", "size": 2313, "source_encoding": "utf_8", "md5": "06a0ffa1046591965d0c6fa9bb7e6293", "text": "function net = f48net_v2()\n\nopts.useBnorm = true ;\n\nnet.layers = {} ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(5,5,3,64, 'single'), zeros(1, 64, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n%net.layers{end+1} = struct('type', 'normalize',...\n % 'param',[9 1 0.0001/5 0.75]) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(5,5,64,64, 'single'), zeros(1, 64, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\n%net.layers{end+1} = struct('type', 'normalize',...\n % 'param',[9 1 0.0001/5 0.75]) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(8,8,64,256, 'single'), zeros(1, 256, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'dropout', 'rate', 0.5) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{0.01*randn(1,1,256,2, 'single'), zeros(1, 2, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\n%{\nnet.layers{end+1} = struct('type', 'custom48', ...\n 'weights', {{0.01*randn(1,1,400,2, 'single'), zeros(1, 2, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\n%}\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n\n% optionally switch to batch normalization\nif opts.useBnorm\n net = insertBnorm(net, 1) ;\n %net = insertBnorm(net, 4) ;\n %net = insertBnorm(net, 8) ;\n %net = insertBnorm(net, 12) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = insertBnorm(net, l)\n% --------------------------------------------------------------------\nassert(isfield(net.layers{l}, 'weights'));\nndim = size(net.layers{l}.weights{1}, 4);\nlayer = struct('type', 'bnorm', ...\n 'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...\n 'learningRate', [1 1], ...\n 'weightDecay', [0 0]) ;\nnet.layers{l}.biases = [] ;\nnet.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_cifar.m", "ext": ".m", "path": "2015_Face_Detection-master/examples_12/cnn_cifar.m", "size": 4529, "source_encoding": "utf_8", "md5": "e4063362a0a852098aab32182613a0b9", "text": "function [net, info] = cnn_cifar(varargin)\n% CNN_CIFAR Demonstrates MatConvNet on CIFAR-10\n% The demo includes two standard model: LeNet and Network in\n% Network (NIN). Use the 'modelType' option to choose one.\n\nrun(fullfile(fileparts(mfilename('fullpath')), ...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.modelType = 'lenet' ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nswitch opts.modelType\n case 'lenet'\n opts.train.learningRate = [0.05*ones(1,15) 0.005*ones(1,10) 0.0005*ones(1,5)] ;\n opts.train.weightDecay = 0.0001 ;\n case 'nin'\n opts.train.learningRate = [0.5*ones(1,30) 0.1*ones(1,10) 0.02*ones(1,10)] ;\n opts.train.weightDecay = 0.0005 ;\n otherwise\n error('Unknown model type %s', opts.modelType) ;\nend\nopts.expDir = fullfile('data', sprintf('cifar-%s', opts.modelType)) ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.dataDir = fullfile('data','cifar') ;\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.whitenData = true ;\nopts.contrastNormalization = true ;\nopts.train.batchSize = 100 ;\nopts.train.continue = true ;\nopts.train.gpus = [] ;\nopts.train.expDir = opts.expDir ;\nopts = vl_argparse(opts, varargin) ;\n\n% --------------------------------------------------------------------\n% Prepare data and model\n% --------------------------------------------------------------------\n\nswitch opts.modelType\n case 'lenet', net = cnn_cifar_init(opts) ;\n case 'nin', net = cnn_cifar_init_nin(opts) ;\nend\n\nif exist(opts.imdbPath, 'file')\n imdb = load(opts.imdbPath) ;\nelse\n imdb = getCifarImdb(opts) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\n% --------------------------------------------------------------------\n% Train\n% --------------------------------------------------------------------\n\n[net, info] = cnn_train(net, imdb, @getBatch, ...\n opts.train, ...\n 'val', find(imdb.images.set == 3)) ;\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nlabels = imdb.images.labels(1,batch) ;\nif rand > 0.5, im=fliplr(im) ; end\n\n% --------------------------------------------------------------------\nfunction imdb = getCifarImdb(opts)\n% --------------------------------------------------------------------\n% Preapre the imdb structure, returns image data with mean image subtracted\nunpackPath = fullfile(opts.dataDir, 'cifar-10-batches-mat');\nfiles = [arrayfun(@(n) sprintf('data_batch_%d.mat', n), 1:5, 'UniformOutput', false) ...\n {'test_batch.mat'}];\nfiles = cellfun(@(fn) fullfile(unpackPath, fn), files, 'UniformOutput', false);\nfile_set = uint8([ones(1, 5), 3]);\n\nif any(cellfun(@(fn) ~exist(fn, 'file'), files))\n url = 'http://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz' ;\n fprintf('downloading %s\\n', url) ;\n untar(url, opts.dataDir) ;\nend\n\ndata = cell(1, numel(files));\nlabels = cell(1, numel(files));\nsets = cell(1, numel(files));\nfor fi = 1:numel(files)\n fd = load(files{fi}) ;\n data{fi} = permute(reshape(fd.data',32,32,3,[]),[2 1 3 4]) ;\n labels{fi} = fd.labels' + 1; % Index from 1\n sets{fi} = repmat(file_set(fi), size(labels{fi}));\nend\n\nset = cat(2, sets{:});\ndata = single(cat(4, data{:}));\n\n% remove mean in any case\ndataMean = mean(data(:,:,:,set == 1), 4);\ndata = bsxfun(@minus, data, dataMean);\n\n% normalize by image mean and std as suggested in `An Analysis of\n% Single-Layer Networks in Unsupervised Feature Learning` Adam\n% Coates, Honglak Lee, Andrew Y. Ng\n\nif opts.contrastNormalization\n z = reshape(data,[],60000) ;\n z = bsxfun(@minus, z, mean(z,1)) ;\n n = std(z,0,1) ;\n z = bsxfun(@times, z, mean(n) ./ max(n, 40)) ;\n data = reshape(z, 32, 32, 3, []) ;\nend\n\nif opts.whitenData\n z = reshape(data,[],60000) ;\n W = z(:,set == 1)*z(:,set == 1)'/60000 ;\n [V,D] = eig(W) ;\n % the scale is selected to approximately preserve the norm of W\n d2 = diag(D) ;\n en = sqrt(mean(d2)) ;\n z = V*diag(en./max(sqrt(d2), 10))*V'*z ;\n data = reshape(z, 32, 32, 3, []) ;\nend\n\nclNames = load(fullfile(unpackPath, 'batches.meta.mat'));\n\nimdb.images.data = data ;\nimdb.images.labels = single(cat(2, labels{:})) ;\nimdb.images.set = set;\nimdb.meta.sets = {'train', 'val', 'test'} ;\nimdb.meta.classes = clNames.label_names;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_mnist_init.m", "ext": ".m", "path": "2015_Face_Detection-master/examples_12/cnn_mnist_init.m", "size": 2359, "source_encoding": "utf_8", "md5": "f320ebc0228ef986a9b3d1f79e6b93b5", "text": "function net = cnn_mnist_init(varargin)\n% CNN_MNIST_LENET Initialize a CNN similar for MNIST\nopts.useBnorm = true ;\nopts = vl_argparse(opts, varargin) ;\n\nf=1/100 ;\nnet.layers = {} ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{f*randn(5,5,1,20, 'single'), zeros(1, 20, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [2 2], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{f*randn(5,5,20,50, 'single'),zeros(1,50,'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [2 2], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{f*randn(4,4,50,500, 'single'), zeros(1,500,'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{f*randn(1,1,500,10, 'single'), zeros(1,10,'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n% optionally switch to batch normalization\nif opts.useBnorm\n net = insertBnorm(net, 1) ;\n net = insertBnorm(net, 4) ;\n net = insertBnorm(net, 7) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = insertBnorm(net, l)\n% --------------------------------------------------------------------\nassert(isfield(net.layers{l}, 'weights'));\nndim = size(net.layers{l}.weights{1}, 4);\nlayer = struct('type', 'bnorm', ...\n 'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...\n 'learningRate', [1 1], ...\n 'weightDecay', [0 0]) ;\nnet.layers{l}.biases = [] ;\nnet.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_imagenet_init_bnorm.m", "ext": ".m", "path": "2015_Face_Detection-master/examples_12/cnn_imagenet_init_bnorm.m", "size": 2821, "source_encoding": "utf_8", "md5": "d50304a797673e101606fed94e114ed9", "text": "function net = cnn_imagenet_init_bnorm(varargin)\n% CNN_IMAGENET_INIT_BNORM Baseline CNN model with batch normalization\n\nopts.scale = 1 ;\nopts.initBias = 0.1 ;\nopts.weightDecay = 1 ;\nopts = vl_argparse(opts, varargin) ;\n\n% Define input\nnet.normalization.imageSize = [227, 227, 3] ;\nnet.normalization.interpolation = 'bicubic' ;\nnet.normalization.border = 256 - net.normalization.imageSize(1:2) ;\nnet.normalization.averageImage = [] ;\nnet.normalization.keepAspect = true ;\n\n% Define layers\nnet.layers = {} ;\n\n% Block 1\nnet = add_block(net, opts, 1, 11, 11, 3, 96, 4, 0) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 2\nnet = add_block(net, opts, 2, 5, 5, 48, 256, 1, 2) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 3\nnet = add_block(net, opts, 3, 3, 3, 256, 384, 1, 1) ;\n\n% Block 4\nnet = add_block(net, opts, 4, 3, 3, 192, 384, 1, 1) ;\n\n% Block 5\nnet = add_block(net, opts, 5, 3, 3, 192, 256, 1, 1) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 6\nnet = add_block(net, opts, 6, 6, 6, 256, 4096, 1, 0) ;\n\n% Block 7\nnet = add_block(net, opts, 7, 1, 1, 4096, 4096, 1, 0) ;\n\n% Block 8\nnet = add_block(net, opts, 8, 1, 1, 4096, 1000, 1, 0) ;\nnet.layers(end-1:end) = [] ;\n\n% Block 9\nnet.layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ;\n\nfunction net = add_block(net, opts, id, h, w, in, out, stride, pad)\ninfo = vl_simplenn_display(net) ;\nfc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;\nif fc\n name = 'fc' ;\nelse\n name = 'conv' ;\nend\nnet.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%d', name, id), ...\n 'weights', {{0.01/opts.scale * randn(h, w, in, out, 'single'), []}}, ...\n 'stride', stride, ...\n 'pad', pad, ...\n 'learningRate', [1 2], ...\n 'weightDecay', [opts.weightDecay 0]) ;\nnet.layers{end+1} = struct('type', 'bnorm', 'name', sprintf('bn%d',id), ...\n 'weights', {{ones(out, 1, 'single'), zeros(out, 1, 'single')}}, ...\n 'learningRate', [2 1], ...\n 'weightDecay', [0 0]) ;\nnet.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%d',id)) ;"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_imagenet_init.m", "ext": ".m", "path": "2015_Face_Detection-master/examples_12/cnn_imagenet_init.m", "size": 2942, "source_encoding": "utf_8", "md5": "19125e6eefe0760fedafc54a0599cf64", "text": "function net = cnn_imagenet_init(varargin)\n% CNN_IMAGENET_INIT Baseline CNN model\n\nopts.scale = 1 ;\nopts.initBias = 0.1 ;\nopts.weightDecay = 1 ;\nopts = vl_argparse(opts, varargin) ;\n\nnet.layers = {} ;\n\n% Define input\nnet.normalization.imageSize = [227, 227, 3] ;\nnet.normalization.interpolation = 'bicubic' ;\nnet.normalization.border = 256 - net.normalization.imageSize(1:2) ;\nnet.normalization.averageImage = [] ;\nnet.normalization.keepAspect = true ;\n\n% Define layers\nnet.layers = {} ;\n\n% Block 1\nnet = add_block(net, opts, 1, 11, 11, 3, 96, 4, 0) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'normalize', 'name', 'norm1', ...\n 'param', [5 1 0.0001/5 0.75]) ;\n\n% Block 2\nnet = add_block(net, opts, 2, 5, 5, 48, 256, 1, 2) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'normalize', 'name', 'norm2', ...\n 'param', [5 1 0.0001/5 0.75]) ;\n\n\n% Block 3\nnet = add_block(net, opts, 3, 3, 3, 256, 384, 1, 1) ;\n\n% Block 4\nnet = add_block(net, opts, 4, 3, 3, 192, 384, 1, 1) ;\n\n% Block 5\nnet = add_block(net, opts, 5, 3, 3, 192, 256, 1, 1) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 6\nnet = add_block(net, opts, 6, 6, 6, 256, 4096, 1, 0) ;\nnet.layers{end+1} = struct('type', 'dropout', 'name', 'dropout6', 'rate', 0.5) ;\n\n\n% Block 7\nnet = add_block(net, opts, 7, 1, 1, 4096, 4096, 1, 0) ;\nnet.layers{end+1} = struct('type', 'dropout', 'name', 'dropout7', 'rate', 0.5) ;\n\n% Block 8\nnet = add_block(net, opts, 8, 1, 1, 4096, 1000, 1, 0) ;\nnet.layers(end) = [] ;\n\n% Block 9\nnet.layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ;\n\nfunction net = add_block(net, opts, id, h, w, in, out, stride, pad)\ninfo = vl_simplenn_display(net) ;\nfc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;\nif fc\n name = 'fc' ;\nelse\n name = 'conv' ;\nend\nnet.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%d', name, id), ...\n 'weights', {{0.01/opts.scale * randn(h, w, in, out, 'single'), []}}, ...\n 'stride', stride, ...\n 'pad', pad, ...\n 'learningRate', [1 2], ...\n 'weightDecay', [opts.weightDecay 0]) ;\nnet.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%d',id)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_imagenet.m", "ext": ".m", "path": "2015_Face_Detection-master/examples_12/cnn_imagenet.m", "size": 4755, "source_encoding": "utf_8", "md5": "b3febbfe185546c63f36c48c38a275a3", "text": "function cnn_imagenet(varargin)\n% CNN_IMAGENET Demonstrates training a CNN on ImageNet\n% The demo uses a model similar to AlexNet or the Caffe reference\n% model. It can train it in the dropout and batch normalization\n% variants using the 'modelType' option.\n\nrun(fullfile(fileparts(mfilename('fullpath')), ...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.dataDir = fullfile('data','ILSVRC2012') ;\nopts.modelType = 'dropout' ; % bnorm or dropout\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.expDir = fullfile('data', sprintf('imagenet12-%s', opts.modelType)) ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.numFetchThreads = 12 ;\nopts.lite = false ;\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.train.batchSize = 256 ;\nopts.train.numSubBatches = 1 ;\nopts.train.continue = true ;\nopts.train.gpus = [] ;\nopts.train.prefetch = true ;\nopts.train.sync = false ;\nopts.train.expDir = opts.expDir ;\nswitch opts.modelType\n case 'dropout', opts.train.learningRate = logspace(-2, -4, 60) ;\n case 'bnorm', opts.train.learningRate = logspace(-1, -4, 20) ;\n otherwise, error('Unknown model type %s', opts.modelType) ;\nend\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.train.numEpochs = numel(opts.train.learningRate) ;\nopts = vl_argparse(opts, varargin) ;\n\n% -------------------------------------------------------------------------\n% Database initialization\n% -------------------------------------------------------------------------\n\nif exist(opts.imdbPath)\n imdb = load(opts.imdbPath) ;\nelse\n imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n\nswitch opts.modelType\n case 'dropout', net = cnn_imagenet_init() ;\n case 'bnorm', net = cnn_imagenet_init_bnorm() ;\nend\n\nbopts = net.normalization ;\nbopts.numThreads = opts.numFetchThreads ;\n\n% compute image statistics (mean, RGB covariances etc)\nimageStatsPath = fullfile(opts.expDir, 'imageStats.mat') ;\nif exist(imageStatsPath)\n load(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;\nelse\n [averageImage, rgbMean, rgbCovariance] = getImageStats(imdb, bopts)\n save(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;\nend\n\n% One can use the average RGB value, or use a different average for\n% each pixel\n%net.normalization.averageImage = averageImage ;\nnet.normalization.averageImage = rgbMean ;\n\n% -------------------------------------------------------------------------\n% Stochastic gradient descent\n% -------------------------------------------------------------------------\n\n[v,d] = eig(rgbCovariance) ;\nbopts.transformation = 'stretch' ;\nbopts.averageImage = rgbMean ;\nbopts.rgbVariance = 0.1*sqrt(d)*v' ;\nfn = getBatchWrapper(bopts) ;\n\n[net,info] = cnn_train(net, imdb, fn, opts.train, 'conserveMemory', true) ;\n\n% -------------------------------------------------------------------------\nfunction fn = getBatchWrapper(opts)\n% -------------------------------------------------------------------------\nfn = @(imdb,batch) getBatch(imdb,batch,opts) ;\n\n% -------------------------------------------------------------------------\nfunction [im,labels] = getBatch(imdb, batch, opts)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nim = cnn_imagenet_get_batch(images, opts, ...\n 'prefetch', nargout == 0) ;\nlabels = imdb.images.label(batch) ;\n\n% -------------------------------------------------------------------------\nfunction [averageImage, rgbMean, rgbCovariance] = getImageStats(imdb, opts)\n% -------------------------------------------------------------------------\ntrain = find(imdb.images.set == 1) ;\ntrain = train(1: 101: end);\nbs = 256 ;\nfn = getBatchWrapper(opts) ;\nfor t=1:bs:numel(train)\n batch_time = tic ;\n batch = train(t:min(t+bs-1, numel(train))) ;\n fprintf('collecting image stats: batch starting with image %d ...', batch(1)) ;\n temp = fn(imdb, batch) ;\n z = reshape(permute(temp,[3 1 2 4]),3,[]) ;\n n = size(z,2) ;\n avg{t} = mean(temp, 4) ;\n rgbm1{t} = sum(z,2)/n ;\n rgbm2{t} = z*z'/n ;\n batch_time = toc(batch_time) ;\n fprintf(' %.2f s (%.1f images/s)\\n', batch_time, numel(batch)/ batch_time) ;\nend\naverageImage = mean(cat(4,avg{:}),4) ;\nrgbm1 = mean(cat(2,rgbm1{:}),2) ;\nrgbm2 = mean(cat(3,rgbm2{:}),3) ;\nrgbMean = rgbm1 ;\nrgbCovariance = rgbm2 - rgbm1*rgbm1' ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_mnist.m", "ext": ".m", "path": "2015_Face_Detection-master/examples_12/cnn_mnist.m", "size": 3318, "source_encoding": "utf_8", "md5": "ec38784eef80636720cdb6d38a023814", "text": "function [net, info] = cnn_mnist(varargin)\n% CNN_MNIST Demonstrated MatConNet on MNIST\n\nrun(fullfile(fileparts(mfilename('fullpath')),...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.expDir = fullfile('data','mnist-baseline') ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.dataDir = fullfile('data','mnist') ;\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.useBnorm = false ;\nopts.train.batchSize = 100 ;\nopts.train.numEpochs = 20 ;\nopts.train.continue = false ;\nopts.train.gpus = [3,4] ;\nopts.train.learningRate = 0.001 ;\nopts.train.expDir = opts.expDir ;\nopts = vl_argparse(opts, varargin) ;\n\n% --------------------------------------------------------------------\n% Prepare data\n% --------------------------------------------------------------------\n\nif exist(opts.imdbPath, 'file')\n imdb = load(opts.imdbPath) ;\nelse\n imdb = getMnistImdb(opts) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\nnet = cnn_mnist_init('useBnorm', opts.useBnorm) ;\n\n% --------------------------------------------------------------------\n% Train\n% --------------------------------------------------------------------\n\n[net, info] = cnn_train(net, imdb, @getBatch, ...\n opts.train, ...\n 'val', find(imdb.images.set == 3)) ;\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nlabels = imdb.images.labels(1,batch) ;\n\n% --------------------------------------------------------------------\nfunction imdb = getMnistImdb(opts)\n% --------------------------------------------------------------------\n% Preapre the imdb structure, returns image data with mean image subtracted\nfiles = {'train-images-idx3-ubyte', ...\n 'train-labels-idx1-ubyte', ...\n 't10k-images-idx3-ubyte', ...\n 't10k-labels-idx1-ubyte'} ;\n\nif ~exist(opts.dataDir, 'dir')\n mkdir(opts.dataDir) ;\nend\n\nfor i=1:4\n if ~exist(fullfile(opts.dataDir, files{i}), 'file')\n url = sprintf('http://yann.lecun.com/exdb/mnist/%s.gz',files{i}) ;\n fprintf('downloading %s\\n', url) ;\n gunzip(url, opts.dataDir) ;\n end\nend\n\nf=fopen(fullfile(opts.dataDir, 'train-images-idx3-ubyte'),'r') ;\nx1=fread(f,inf,'uint8');\nfclose(f) ;\nx1=permute(reshape(x1(17:end),28,28,60e3),[2 1 3]) ;\n\nf=fopen(fullfile(opts.dataDir, 't10k-images-idx3-ubyte'),'r') ;\nx2=fread(f,inf,'uint8');\nfclose(f) ;\nx2=permute(reshape(x2(17:end),28,28,10e3),[2 1 3]) ;\n\nf=fopen(fullfile(opts.dataDir, 'train-labels-idx1-ubyte'),'r') ;\ny1=fread(f,inf,'uint8');\nfclose(f) ;\ny1=double(y1(9:end)')+1 ;\n\nf=fopen(fullfile(opts.dataDir, 't10k-labels-idx1-ubyte'),'r') ;\ny2=fread(f,inf,'uint8');\nfclose(f) ;\ny2=double(y2(9:end)')+1 ;\n\nset = [ones(1,numel(y1)) 3*ones(1,numel(y2))];\ndata = single(reshape(cat(3, x1, x2),28,28,1,[]));\ndataMean = mean(data(:,:,:,set == 1), 4);\ndata = bsxfun(@minus, data, dataMean) ;\n\nimdb.images.data = data ;\nimdb.images.data_mean = dataMean;\nimdb.images.labels = cat(2, y1, y2) ;\nimdb.images.set = set ;\nimdb.meta.sets = {'train', 'val', 'test'} ;\nimdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_train.m", "ext": ".m", "path": "2015_Face_Detection-master/examples_12/cnn_train.m", "size": 13874, "source_encoding": "utf_8", "md5": "0dc4a6af99246de00950fd4db12cb1d9", "text": "function [net, info] = cnn_train(net, imdb, getBatch, varargin)\n% CNN_TRAIN Demonstrates training a CNN\n% CNN_TRAIN() is an example learner implementing stochastic\n% gradient descent with momentum to train a CNN. It can be used\n% with different datasets and tasks by providing a suitable\n% getBatch function.\n%\n% The function automatically restarts after each training epoch by\n% checkpointing.\n%\n% The function supports training on CPU or on one or more GPUs\n% (specify the list of GPU IDs in the `gpus` option). Multi-GPU\n% support is relatively primitive but sufficient to obtain a\n% noticable speedup.\n\n% Copyright (C) 2014-15 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.batchSize = 256 ;\nopts.numSubBatches = 1 ;\nopts.train = [] ;\nopts.val = [] ;\nopts.numEpochs = 300 ;\nopts.gpus = [] ; % which GPU devices to use (none, one, or more)\nopts.learningRate = 0.001 ;\nopts.continue = false ;\nopts.expDir = fullfile('data','exp') ;\nopts.conserveMemory = false ;\nopts.backPropDepth = +inf ;\nopts.sync = false ;\nopts.prefetch = false ;\nopts.weightDecay = 0.0005 ;\nopts.momentum = 0.9 ;\nopts.errorFunction = 'multiclass' ;\nopts.errorLabels = {} ;\nopts.plotDiagnostics = false ;\nopts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;\nopts = vl_argparse(opts, varargin) ;\n\nif ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end\nif isempty(opts.train), opts.train = find(imdb.images.set==1) ; end\nif isempty(opts.val), opts.val = find(imdb.images.set==2) ; end\nif isnan(opts.train), opts.train = [] ; end\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n\nevaluateMode = isempty(opts.train) ;\n\nif ~evaluateMode\n for i=1:numel(net.layers)\n if isfield(net.layers{i}, 'weights')\n J = numel(net.layers{i}.weights) ;\n for j=1:J\n net.layers{i}.momentum{j} = zeros(size(net.layers{i}.weights{j}), 'single') ;\n end\n if ~isfield(net.layers{i}, 'learningRate')\n net.layers{i}.learningRate = ones(1, J, 'single') ;\n end\n if ~isfield(net.layers{i}, 'weightDecay')\n net.layers{i}.weightDecay = ones(1, J, 'single') ;\n end\n end\n % Legacy code: will be removed\n if isfield(net.layers{i}, 'filters')\n net.layers{i}.momentum{1} = zeros(size(net.layers{i}.filters), 'single') ;\n net.layers{i}.momentum{2} = zeros(size(net.layers{i}.biases), 'single') ;\n if ~isfield(net.layers{i}, 'learningRate')\n net.layers{i}.learningRate = ones(1, 2, 'single') ;\n end\n if ~isfield(net.layers{i}, 'weightDecay')\n net.layers{i}.weightDecay = single([1 0]) ;\n end\n end\n end\nend\n\n% setup GPUs\nnumGpus = numel(opts.gpus) ;\nif numGpus > 1\n if isempty(gcp('nocreate')),\n parpool('local',numGpus) ;\n spmd, gpuDevice(opts.gpus(labindex)), end\n end\nelseif numGpus == 1\n gpuDevice(opts.gpus)\nend\nif exist(opts.memoryMapFile), delete(opts.memoryMapFile) ; end\n\n% setup error calculation function\nif isstr(opts.errorFunction)\n switch opts.errorFunction\n case 'none'\n opts.errorFunction = @error_none ;\n case 'multiclass'\n opts.errorFunction = @error_multiclass ;\n if isempty(opts.errorLabels), opts.errorLabels = {'top1e', 'top5e'} ; end\n case 'binary'\n opts.errorFunction = @error_binary ;\n if isempty(opts.errorLabels), opts.errorLabels = {'bine'} ; end\n otherwise\n error('Uknown error function ''%s''', opts.errorFunction) ;\n end\nend\n\n% -------------------------------------------------------------------------\n% Train and validate\n% -------------------------------------------------------------------------\n\nfor epoch=1:opts.numEpochs\n learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;\n\n % fast-forward to last checkpoint\n modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));\n modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;\n if opts.continue\n if exist(modelPath(epoch),'file')\n if epoch == opts.numEpochs\n load(modelPath(epoch), 'net', 'info') ;\n end\n continue ;\n end\n if epoch > 1\n fprintf('resuming by loading epoch %d\\n', epoch-1) ;\n load(modelPath(epoch-1), 'net', 'info') ;\n end\n end\n\n % move CNN to GPU as needed\n if numGpus == 1\n net = vl_simplenn_move(net, 'gpu') ;\n elseif numGpus > 1\n spmd(numGpus)\n net_ = vl_simplenn_move(net, 'gpu') ;\n end\n end\n\n % train one epoch and validate\n train = opts.train(randperm(numel(opts.train))) ; % shuffle\n val = opts.val ;\n if numGpus <= 1\n [net,stats.train] = process_epoch(opts, getBatch, epoch, train, learningRate, imdb, net) ;\n [~,stats.val] = process_epoch(opts, getBatch, epoch, val, 0, imdb, net) ;\n else\n spmd(numGpus)\n [net_, stats_train_] = process_epoch(opts, getBatch, epoch, train, learningRate, imdb, net_) ;\n [~, stats_val_] = process_epoch(opts, getBatch, epoch, val, 0, imdb, net_) ;\n end\n stats.train = sum([stats_train_{:}],2) ;\n stats.val = sum([stats_val_{:}],2) ;\n end\n\n % save\n if evaluateMode, sets = {'val'} ; else sets = {'train', 'val'} ; end\n for f = sets\n f = char(f) ;\n n = numel(eval(f)) ;\n info.(f).speed(epoch) = n / stats.(f)(1) ;\n info.(f).objective(epoch) = stats.(f)(2) / n ;\n info.(f).error(:,epoch) = stats.(f)(3:end) / n ;\n end\n if numGpus > 1\n spmd(numGpus)\n net_ = vl_simplenn_move(net_, 'cpu') ;\n end\n net = net_{1} ;\n else\n net = vl_simplenn_move(net, 'cpu') ;\n end\n if ~evaluateMode, save(modelPath(epoch), 'net', 'info') ; end\n\n figure(1) ; clf ;\n hasError = isa(opts.errorFunction, 'function_handle') ;\n subplot(1,1+hasError,1) ;\n if ~evaluateMode\n semilogy(1:epoch, info.train.objective, '.-', 'linewidth', 2) ;\n hold on ;\n end\n semilogy(1:epoch, info.val.objective, '.--') ;\n xlabel('training epoch') ; ylabel('energy') ;\n grid on ;\n h=legend(sets) ;\n set(h,'color','none');\n title('objective') ;\n if hasError\n subplot(1,2,2) ; leg = {} ;\n if ~evaluateMode\n plot(1:epoch, info.train.error', '.-', 'linewidth', 2) ;\n hold on ;\n leg = horzcat(leg, strcat('train ', opts.errorLabels)) ;\n end\n plot(1:epoch, info.val.error', '.--') ;\n leg = horzcat(leg, strcat('val ', opts.errorLabels)) ;\n set(legend(leg{:}),'color','none') ;\n grid on ;\n xlabel('training epoch') ; ylabel('error') ;\n title('error') ;\n end\n drawnow ;\n print(1, modelFigPath, '-dpdf') ;\nend\n\n% -------------------------------------------------------------------------\nfunction err = error_multiclass(opts, labels, res)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\n[~,predictions] = sort(predictions, 3, 'descend') ;\nerror = ~bsxfun(@eq, predictions, reshape(labels, 1, 1, 1, [])) ;\nerr(1,1) = sum(sum(sum(error(:,:,1,:)))) ;\nerr(2,1) = sum(sum(sum(min(error(:,:,1:5,:),[],3)))) ;\n\n% -------------------------------------------------------------------------\nfunction err = error_binary(opts, labels, res)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\npredictions = reshape(predictions,2,[]);\n[~,predictions] = max(predictions);\nerror = ~bsxfun(@eq, predictions, labels) ;\nerr = sum(error(:)) ;\n\n% -------------------------------------------------------------------------\nfunction err = error_none(opts, labels, res)\n% -------------------------------------------------------------------------\nerr = zeros(0,1) ;\n\n% -------------------------------------------------------------------------\nfunction [net,stats,prof] = process_epoch(opts, getBatch, epoch, subset, learningRate, imdb, net)\n% -------------------------------------------------------------------------\n\n% validation mode if learning rate is zero\ntraining = learningRate > 0 ;\nif training, mode = 'training' ; else, mode = 'validation' ; end\nif nargout > 2, mpiprofile on ; end\n\nnumGpus = numel(opts.gpus) ;\nif numGpus >= 1\n one = gpuArray(single(1)) ;\nelse\n one = single(1) ;\nend\nres = [] ;\nmmap = [] ;\nstats = [] ;\n\nfor t=1:opts.batchSize:numel(subset)\n fprintf('%s: epoch %02d: batch %3d/%3d: ', mode, epoch, ...\n fix(t/opts.batchSize)+1, ceil(numel(subset)/opts.batchSize)) ;\n batchSize = min(opts.batchSize, numel(subset) - t + 1) ;\n batchTime = tic ;\n numDone = 0 ;\n error = [] ;\n for s=1:opts.numSubBatches\n % get this image batch and prefetch the next\n batchStart = t + (labindex-1) + (s-1) * numlabs ;\n batchEnd = min(t+opts.batchSize-1, numel(subset)) ;\n batch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ;\n [im, labels] = getBatch(imdb, batch) ;\n\n if opts.prefetch\n if s==opts.numSubBatches\n batchStart = t + (labindex-1) + opts.batchSize ;\n batchEnd = min(t+2*opts.batchSize-1, numel(subset)) ;\n else\n batchStart = batchStart + numlabs ;\n end\n nextBatch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ;\n getBatch(imdb, nextBatch) ;\n end\n\n if numGpus >= 1\n im = gpuArray(im) ;\n end\n\n % evaluate CNN\n net.layers{end}.class = labels ;\n if training, dzdy = one; else, dzdy = [] ; end\n res = vl_simplenn(net, im, dzdy, res, ...\n 'accumulate', s ~= 1, ...\n 'disableDropout', ~training, ...\n 'conserveMemory', opts.conserveMemory, ...\n 'backPropDepth', opts.backPropDepth, ...\n 'sync', opts.sync) ;\n\n % accumulate training errors\n error = sum([error, [...\n sum(double(gather(res(end).x))) ;\n reshape(opts.errorFunction(opts, labels, res),[],1) ; ]],2) ;\n numDone = numDone + numel(batch) ;\n end\n\n % gather and accumulate gradients across labs\n if training\n if numGpus <= 1\n net = accumulate_gradients(opts, learningRate, batchSize, net, res) ;\n else\n if isempty(mmap)\n mmap = map_gradients(opts.memoryMapFile, net, res, numGpus) ;\n end\n write_gradients(mmap, net, res) ;\n labBarrier() ;\n [net,res] = accumulate_gradients(opts, learningRate, batchSize, net, res, mmap) ;\n end\n end\n\n % print learning statistics\n batchTime = toc(batchTime) ;\n stats = sum([stats,[batchTime ; error]],2); % works even when stats=[]\n speed = batchSize/batchTime ;\n\n fprintf(' %.2f s (%.1f data/s)', batchTime, speed) ;\n n = (t + batchSize - 1) / max(1,numlabs) ;\n fprintf(' obj:%.3g', stats(2)/n) ;\n for i=1:numel(opts.errorLabels)\n fprintf(' %s:%.3g', opts.errorLabels{i}, stats(i+2)/n) ;\n end\n fprintf(' [%d/%d]', numDone, batchSize);\n fprintf('\\n') ;\n\n % debug info\n if opts.plotDiagnostics && numGpus <= 1\n figure(2) ; vl_simplenn_diagnose(net,res) ; drawnow ;\n end\nend\n\nif nargout > 2\n prof = mpiprofile('info');\n mpiprofile off ;\nend\n\n% -------------------------------------------------------------------------\nfunction [net,res] = accumulate_gradients(opts, lr, batchSize, net, res, mmap)\n% -------------------------------------------------------------------------\nfor l=1:numel(net.layers)\n for j=1:numel(res(l).dzdw)\n thisDecay = opts.weightDecay * net.layers{l}.weightDecay(j) ;\n thisLR = lr * net.layers{l}.learningRate(j) ;\n\n % accumualte from multiple labs (GPUs) if needed\n if nargin >= 6\n tag = sprintf('l%d_%d',l,j) ;\n tmp = zeros(size(mmap.Data(labindex).(tag)), 'single') ;\n for g = setdiff(1:numel(mmap.Data), labindex)\n tmp = tmp + mmap.Data(g).(tag) ;\n end\n res(l).dzdw{j} = res(l).dzdw{j} + tmp ;\n end\n\n if isfield(net.layers{l}, 'weights')\n net.layers{l}.momentum{j} = ...\n opts.momentum * net.layers{l}.momentum{j} ...\n - thisDecay * net.layers{l}.weights{j} ...\n - (1 / batchSize) * res(l).dzdw{j} ;\n net.layers{l}.weights{j} = net.layers{l}.weights{j} + thisLR * net.layers{l}.momentum{j} ;\n else\n % Legacy code: to be removed\n if j == 1\n net.layers{l}.momentum{j} = ...\n opts.momentum * net.layers{l}.momentum{j} ...\n - thisDecay * net.layers{l}.filters ...\n - (1 / batchSize) * res(l).dzdw{j} ;\n net.layers{l}.filters = net.layers{l}.filters + thisLR * net.layers{l}.momentum{j} ;\n else\n net.layers{l}.momentum{j} = ...\n opts.momentum * net.layers{l}.momentum{j} ...\n - thisDecay * net.layers{l}.biases ...\n - (1 / batchSize) * res(l).dzdw{j} ;\n net.layers{l}.biases = net.layers{l}.biases + thisLR * net.layers{l}.momentum{j} ;\n end\n end\n end\nend\n\n% -------------------------------------------------------------------------\nfunction mmap = map_gradients(fname, net, res, numGpus)\n% -------------------------------------------------------------------------\nformat = {} ;\nfor i=1:numel(net.layers)\n for j=1:numel(res(i).dzdw)\n format(end+1,1:3) = {'single', size(res(i).dzdw{j}), sprintf('l%d_%d',i,j)} ;\n end\nend\nformat(end+1,1:3) = {'double', [3 1], 'errors'} ;\nif ~exist(fname) && (labindex == 1)\n f = fopen(fname,'wb') ;\n for g=1:numGpus\n for i=1:size(format,1)\n fwrite(f,zeros(format{i,2},format{i,1}),format{i,1}) ;\n end\n end\n fclose(f) ;\nend\nlabBarrier() ;\nmmap = memmapfile(fname, 'Format', format, 'Repeat', numGpus, 'Writable', true) ;\n\n% -------------------------------------------------------------------------\nfunction write_gradients(mmap, net, res)\n% -------------------------------------------------------------------------\nfor i=1:numel(net.layers)\n for j=1:numel(res(i).dzdw)\n mmap.Data(labindex).(sprintf('l%d_%d',i,j)) = gather(res(i).dzdw{j}) ;\n end\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_imagenet_mgpu.m", "ext": ".m", "path": "2015_Face_Detection-master/examples_12/cnn_imagenet_mgpu.m", "size": 9705, "source_encoding": "utf_8", "md5": "8297e5ae85c01972f432a68fd13ac492", "text": "function cnn_imagenet_mgpu(varargin)\n% CNN_IMAGENET Demonstrates training a CNN on ImageNet\n\nrun(fullfile(fileparts(mfilename('fullpath')), ...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.dataDir = fullfile('data','ram','ILSVRC2012') ;\nopts.expDir = fullfile('data','imagenet12-baseline-mgpu') ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.lite = false ;\nopts.numFetchThreads = 12 ;\nopts.train.batchSize = 256*4 ;\nopts.train.numEpochs = 65 ;\nopts.train.continue = true ;\nopts.train.gpus = 1:4 ;\nopts.train.prefetch = true ;\nopts.train.learningRate = [0.01*ones(1, 25) 0.001*ones(1, 25) 0.0001*ones(1,15)] ;\nopts.train.expDir = opts.expDir ;\nopts.train.memoryMapFile = '/mnt/ramdisk/vedaldi/m.dat' ;\nopts = vl_argparse(opts, varargin) ;\n\n% -------------------------------------------------------------------------\n% Database initialization\n% -------------------------------------------------------------------------\n\nif exist(opts.imdbPath)\n imdb = load(opts.imdbPath) ;\n imdb.imageDir = fullfile(opts.dataDir, 'images') ;\nelse\n imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n\nnet = initializeNetwork(opts) ;\n\n% compute the average image\naverageImagePath = fullfile(opts.expDir, 'average.mat') ;\nif exist(averageImagePath)\n load(averageImagePath, 'averageImage') ;\nelse\n train = find(imdb.images.set == 1) ;\n bs = 256 ;\n fn = getBatchWrapper(net.normalization, opts.numFetchThreads) ;\n for t=1:bs:numel(train)\n batch_time = tic ;\n batch = train(t:min(t+bs-1, numel(train))) ;\n fprintf('computing average image: processing batch starting with image %d ...', batch(1)) ;\n temp = fn(imdb, batch) ;\n im{t} = mean(temp, 4) ;\n batch_time = toc(batch_time) ;\n fprintf(' %.2f s (%.1f images/s)\\n', batch_time, numel(batch)/ batch_time) ;\n end\n averageImage = mean(cat(4, im{:}),4) ;\n save(averageImagePath, 'averageImage') ;\nend\n\nnet.normalization.averageImage = averageImage ;\nclear averageImage im temp ;\n\n% -------------------------------------------------------------------------\n% Stochastic gradient descent\n% -------------------------------------------------------------------------\n\nfn = getBatchWrapper(net.normalization, opts.numFetchThreads) ;\n\n[net,info] = cnn_train_mgpu(net, imdb, fn, opts.train, 'conserveMemory', true) ;\n\n% -------------------------------------------------------------------------\nfunction fn = getBatchWrapper(opts, numThreads)\n% -------------------------------------------------------------------------\nfn = @(imdb,batch) getBatch(imdb,batch,opts,numThreads) ;\n\n% -------------------------------------------------------------------------\nfunction [im,labels] = getBatch(imdb, batch, opts, numThreads)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nim = cnn_imagenet_get_batch(images, opts, ...\n 'numThreads', numThreads, ...\n 'prefetch', nargout == 0, ...\n 'augmentation', 'f25') ;\n%im = zeros(256,256,3,numel(batch),'single') ;\nlabels = imdb.images.label(batch) ;\n\n% -------------------------------------------------------------------------\nfunction net = initializeNetwork(opt)\n% -------------------------------------------------------------------------\n\nscal = 1 ;\ninit_bias = 0.1;\n\nnet.layers = {} ;\n\n% Block 1\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(11, 11, 3, 96, 'single'), ...\n 'biases', zeros(1, 96, 'single'), ...\n 'stride', 4, ...\n 'pad', 0, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'normalize', ...\n 'param', [5 1 0.0001/5 0.75]) ;\n\n% Block 2\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(5, 5, 48, 256, 'single'), ...\n 'biases', init_bias*ones(1, 256, 'single'), ...\n 'stride', 1, ...\n 'pad', 2, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'normalize', ...\n 'param', [5 1 0.0001/5 0.75]) ;\n\n% Block 3\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(3,3,256,384,'single'), ...\n 'biases', init_bias*ones(1,384,'single'), ...\n 'stride', 1, ...\n 'pad', 1, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\n\n% Block 4\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(3,3,192,384,'single'), ...\n 'biases', init_bias*ones(1,384,'single'), ...\n 'stride', 1, ...\n 'pad', 1, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\n\n% Block 5\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(3,3,192,256,'single'), ...\n 'biases', init_bias*ones(1,256,'single'), ...\n 'stride', 1, ...\n 'pad', 1, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 6\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(6,6,256,4096,'single'),...\n 'biases', init_bias*ones(1,4096,'single'), ...\n 'stride', 1, ...\n 'pad', 0, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'dropout', ...\n 'rate', 0.5) ;\n\n% Block 7\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(1,1,4096,4096,'single'),...\n 'biases', init_bias*ones(1,4096,'single'), ...\n 'stride', 1, ...\n 'pad', 0, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'dropout', ...\n 'rate', 0.5) ;\n\n% Block 8\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(1,1,4096,1000,'single'), ...\n 'biases', zeros(1, 1000, 'single'), ...\n 'stride', 1, ...\n 'pad', 0, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\n\n% Block 9\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n% Other details\nnet.normalization.imageSize = [227, 227, 3] ;\nnet.normalization.interpolation = 'bicubic' ;\nnet.normalization.border = 256 - net.normalization.imageSize(1:2) ;\nnet.normalization.averageImage = [] ;\nnet.normalization.keepAspect = true ;\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_imagenet_evaluate.m", "ext": ".m", "path": "2015_Face_Detection-master/examples_12/cnn_imagenet_evaluate.m", "size": 2960, "source_encoding": "utf_8", "md5": "93a11af0121659362a46b7e80afe492b", "text": "function info = cnn_imagenet_evaluate(varargin)\n% CNN_IMAGENET_EVALUATE Evauate MatConvNet models on ImageNet\n\nrun(fullfile(fileparts(mfilename('fullpath')), ...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.dataDir = fullfile('data', 'ILSVRC2012') ;\nopts.expDir = fullfile('data', 'imagenet12-eval-vgg-f') ;\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.modelPath = fullfile('data', 'models', 'imagenet-vgg-f.mat') ;\nopts.lite = false ;\nopts.numFetchThreads = 12 ;\nopts.train.batchSize = 128 ;\nopts.train.numEpochs = 1 ;\nopts.train.gpus = [] ;\nopts.train.prefetch = true ;\nopts.train.expDir = opts.expDir ;\nopts.train.conserveMemory = true ;\nopts.train.sync = true ;\n\nopts = vl_argparse(opts, varargin) ;\ndisplay(opts);\n\n% -------------------------------------------------------------------------\n% Database initialization\n% -------------------------------------------------------------------------\n\nif exist(opts.imdbPath)\n imdb = load(opts.imdbPath) ;\nelse\n imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n\nnet = load(opts.modelPath) ;\nif isfield(net, 'net') ;\n net = net.net ;\n net.classes = imdb.classes ;\nend\nnet.layers{end}.type = 'softmaxloss' ; % softmax -> softmaxloss\nnet.normalization.border = [256 256] - net.normalization.imageSize(1:2) ;\nvl_simplenn_display(net, 'batchSize', opts.train.batchSize) ;\n\n% Synchronize label indexes between the model and the image database\nimdb = cnn_imagenet_sync_labels(imdb, net);\n\n% -------------------------------------------------------------------------\n% Stochastic gradient descent\n% -------------------------------------------------------------------------\n\nbopts = net.normalization ;\nbopts.numThreads = opts.numFetchThreads ;\nfn = getBatchWrapper(bopts) ;\n\n[net,info] = cnn_train(net, imdb, fn, opts.train, ...\n 'train', NaN, ...\n 'val', find(imdb.images.set==2)) ;\n\n% -------------------------------------------------------------------------\nfunction fn = getBatchWrapper(opts)\n% -------------------------------------------------------------------------\nfn = @(imdb,batch) getBatch(imdb,batch,opts) ;\n\n% -------------------------------------------------------------------------\nfunction [im,labels] = getBatch(imdb, batch, opts)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nim = cnn_imagenet_get_batch(images, opts, ...\n 'prefetch', nargout == 0) ;\nlabels = imdb.images.label(batch) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_cifar.m", "ext": ".m", "path": "2015_Face_Detection-master/examples/cnn_cifar.m", "size": 4529, "source_encoding": "utf_8", "md5": "e4063362a0a852098aab32182613a0b9", "text": "function [net, info] = cnn_cifar(varargin)\n% CNN_CIFAR Demonstrates MatConvNet on CIFAR-10\n% The demo includes two standard model: LeNet and Network in\n% Network (NIN). Use the 'modelType' option to choose one.\n\nrun(fullfile(fileparts(mfilename('fullpath')), ...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.modelType = 'lenet' ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nswitch opts.modelType\n case 'lenet'\n opts.train.learningRate = [0.05*ones(1,15) 0.005*ones(1,10) 0.0005*ones(1,5)] ;\n opts.train.weightDecay = 0.0001 ;\n case 'nin'\n opts.train.learningRate = [0.5*ones(1,30) 0.1*ones(1,10) 0.02*ones(1,10)] ;\n opts.train.weightDecay = 0.0005 ;\n otherwise\n error('Unknown model type %s', opts.modelType) ;\nend\nopts.expDir = fullfile('data', sprintf('cifar-%s', opts.modelType)) ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.dataDir = fullfile('data','cifar') ;\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.whitenData = true ;\nopts.contrastNormalization = true ;\nopts.train.batchSize = 100 ;\nopts.train.continue = true ;\nopts.train.gpus = [] ;\nopts.train.expDir = opts.expDir ;\nopts = vl_argparse(opts, varargin) ;\n\n% --------------------------------------------------------------------\n% Prepare data and model\n% --------------------------------------------------------------------\n\nswitch opts.modelType\n case 'lenet', net = cnn_cifar_init(opts) ;\n case 'nin', net = cnn_cifar_init_nin(opts) ;\nend\n\nif exist(opts.imdbPath, 'file')\n imdb = load(opts.imdbPath) ;\nelse\n imdb = getCifarImdb(opts) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\n% --------------------------------------------------------------------\n% Train\n% --------------------------------------------------------------------\n\n[net, info] = cnn_train(net, imdb, @getBatch, ...\n opts.train, ...\n 'val', find(imdb.images.set == 3)) ;\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nlabels = imdb.images.labels(1,batch) ;\nif rand > 0.5, im=fliplr(im) ; end\n\n% --------------------------------------------------------------------\nfunction imdb = getCifarImdb(opts)\n% --------------------------------------------------------------------\n% Preapre the imdb structure, returns image data with mean image subtracted\nunpackPath = fullfile(opts.dataDir, 'cifar-10-batches-mat');\nfiles = [arrayfun(@(n) sprintf('data_batch_%d.mat', n), 1:5, 'UniformOutput', false) ...\n {'test_batch.mat'}];\nfiles = cellfun(@(fn) fullfile(unpackPath, fn), files, 'UniformOutput', false);\nfile_set = uint8([ones(1, 5), 3]);\n\nif any(cellfun(@(fn) ~exist(fn, 'file'), files))\n url = 'http://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz' ;\n fprintf('downloading %s\\n', url) ;\n untar(url, opts.dataDir) ;\nend\n\ndata = cell(1, numel(files));\nlabels = cell(1, numel(files));\nsets = cell(1, numel(files));\nfor fi = 1:numel(files)\n fd = load(files{fi}) ;\n data{fi} = permute(reshape(fd.data',32,32,3,[]),[2 1 3 4]) ;\n labels{fi} = fd.labels' + 1; % Index from 1\n sets{fi} = repmat(file_set(fi), size(labels{fi}));\nend\n\nset = cat(2, sets{:});\ndata = single(cat(4, data{:}));\n\n% remove mean in any case\ndataMean = mean(data(:,:,:,set == 1), 4);\ndata = bsxfun(@minus, data, dataMean);\n\n% normalize by image mean and std as suggested in `An Analysis of\n% Single-Layer Networks in Unsupervised Feature Learning` Adam\n% Coates, Honglak Lee, Andrew Y. Ng\n\nif opts.contrastNormalization\n z = reshape(data,[],60000) ;\n z = bsxfun(@minus, z, mean(z,1)) ;\n n = std(z,0,1) ;\n z = bsxfun(@times, z, mean(n) ./ max(n, 40)) ;\n data = reshape(z, 32, 32, 3, []) ;\nend\n\nif opts.whitenData\n z = reshape(data,[],60000) ;\n W = z(:,set == 1)*z(:,set == 1)'/60000 ;\n [V,D] = eig(W) ;\n % the scale is selected to approximately preserve the norm of W\n d2 = diag(D) ;\n en = sqrt(mean(d2)) ;\n z = V*diag(en./max(sqrt(d2), 10))*V'*z ;\n data = reshape(z, 32, 32, 3, []) ;\nend\n\nclNames = load(fullfile(unpackPath, 'batches.meta.mat'));\n\nimdb.images.data = data ;\nimdb.images.labels = single(cat(2, labels{:})) ;\nimdb.images.set = set;\nimdb.meta.sets = {'train', 'val', 'test'} ;\nimdb.meta.classes = clNames.label_names;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_mnist_init.m", "ext": ".m", "path": "2015_Face_Detection-master/examples/cnn_mnist_init.m", "size": 2385, "source_encoding": "utf_8", "md5": "e4895ca0e40a022561d7a80114797bdb", "text": "function net = cnn_mnist_init(varargin)\n% CNN_MNIST_LENET Initialize a CNN similar for MNIST\nopts.useBnorm = true ;\nopts = vl_argparse(opts, varargin) ;\n\nrng('default');\nrng(0) ;\n\nf=1/100 ;\nnet.layers = {} ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{f*randn(5,5,1,20, 'single'), zeros(1, 20, 'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [2 2], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{f*randn(5,5,20,50, 'single'),zeros(1,50,'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [2 2], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{f*randn(4,4,50,500, 'single'), zeros(1,500,'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'conv', ...\n 'weights', {{f*randn(1,1,500,10, 'single'), zeros(1,10,'single')}}, ...\n 'stride', 1, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n% optionally switch to batch normalization\nif opts.useBnorm\n net = insertBnorm(net, 1) ;\n net = insertBnorm(net, 4) ;\n net = insertBnorm(net, 7) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = insertBnorm(net, l)\n% --------------------------------------------------------------------\nassert(isfield(net.layers{l}, 'weights'));\nndim = size(net.layers{l}.weights{1}, 4);\nlayer = struct('type', 'bnorm', ...\n 'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...\n 'learningRate', [1 1], ...\n 'weightDecay', [0 0]) ;\nnet.layers{l}.biases = [] ;\nnet.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_imagenet_init_bnorm.m", "ext": ".m", "path": "2015_Face_Detection-master/examples/cnn_imagenet_init_bnorm.m", "size": 2821, "source_encoding": "utf_8", "md5": "d50304a797673e101606fed94e114ed9", "text": "function net = cnn_imagenet_init_bnorm(varargin)\n% CNN_IMAGENET_INIT_BNORM Baseline CNN model with batch normalization\n\nopts.scale = 1 ;\nopts.initBias = 0.1 ;\nopts.weightDecay = 1 ;\nopts = vl_argparse(opts, varargin) ;\n\n% Define input\nnet.normalization.imageSize = [227, 227, 3] ;\nnet.normalization.interpolation = 'bicubic' ;\nnet.normalization.border = 256 - net.normalization.imageSize(1:2) ;\nnet.normalization.averageImage = [] ;\nnet.normalization.keepAspect = true ;\n\n% Define layers\nnet.layers = {} ;\n\n% Block 1\nnet = add_block(net, opts, 1, 11, 11, 3, 96, 4, 0) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 2\nnet = add_block(net, opts, 2, 5, 5, 48, 256, 1, 2) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 3\nnet = add_block(net, opts, 3, 3, 3, 256, 384, 1, 1) ;\n\n% Block 4\nnet = add_block(net, opts, 4, 3, 3, 192, 384, 1, 1) ;\n\n% Block 5\nnet = add_block(net, opts, 5, 3, 3, 192, 256, 1, 1) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 6\nnet = add_block(net, opts, 6, 6, 6, 256, 4096, 1, 0) ;\n\n% Block 7\nnet = add_block(net, opts, 7, 1, 1, 4096, 4096, 1, 0) ;\n\n% Block 8\nnet = add_block(net, opts, 8, 1, 1, 4096, 1000, 1, 0) ;\nnet.layers(end-1:end) = [] ;\n\n% Block 9\nnet.layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ;\n\nfunction net = add_block(net, opts, id, h, w, in, out, stride, pad)\ninfo = vl_simplenn_display(net) ;\nfc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;\nif fc\n name = 'fc' ;\nelse\n name = 'conv' ;\nend\nnet.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%d', name, id), ...\n 'weights', {{0.01/opts.scale * randn(h, w, in, out, 'single'), []}}, ...\n 'stride', stride, ...\n 'pad', pad, ...\n 'learningRate', [1 2], ...\n 'weightDecay', [opts.weightDecay 0]) ;\nnet.layers{end+1} = struct('type', 'bnorm', 'name', sprintf('bn%d',id), ...\n 'weights', {{ones(out, 1, 'single'), zeros(out, 1, 'single')}}, ...\n 'learningRate', [2 1], ...\n 'weightDecay', [0 0]) ;\nnet.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%d',id)) ;"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_imagenet_init.m", "ext": ".m", "path": "2015_Face_Detection-master/examples/cnn_imagenet_init.m", "size": 13358, "source_encoding": "utf_8", "md5": "029a55b46ee627afa3272d449917af3c", "text": "function net = cnn_imagenet_init(varargin)\n% CNN_IMAGENET_INIT Initialize a standard CNN for ImageNet\n\nopts.scale = 1 ;\nopts.initBias = 0.1 ;\nopts.weightDecay = 1 ;\n%opts.weightInitMethod = 'xavierimproved' ;\nopts.weightInitMethod = 'gaussian' ;\nopts.model = 'alexnet' ;\nopts.batchNormalization = false ;\nopts = vl_argparse(opts, varargin) ;\n\n% Define layers\nswitch opts.model\n case 'alexnet'\n net.normalization.imageSize = [227, 227, 3] ;\n net = alexnet(net, opts) ;\n case 'vgg-f'\n net.normalization.imageSize = [224, 224, 3] ;\n net = vgg_f(net, opts) ;\n case 'vgg-m'\n net.normalization.imageSize = [224, 224, 3] ;\n net = vgg_m(net, opts) ;\n case 'vgg-s'\n net.normalization.imageSize = [224, 224, 3] ;\n net = vgg_s(net, opts) ;\n case 'vgg-vd-16'\n net.normalization.imageSize = [224, 224, 3] ;\n net = vgg_vd(net, opts) ;\n case 'vgg-vd-19'\n net.normalization.imageSize = [224, 224, 3] ;\n net = vgg_vd(net, opts) ;\n otherwise\n error('Unknown model ''%s''', opts.model) ;\nend\n\n% final touches\nswitch lower(opts.weightInitMethod)\n case {'xavier', 'xavierimproved'}\n net.layers{end}.weights{1} = net.layers{end}.weights{1} / 10 ;\nend\nnet.layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ;\n\nnet.normalization.border = 256 - net.normalization.imageSize(1:2) ;\nnet.normalization.interpolation = 'bicubic' ;\nnet.normalization.averageImage = [] ;\nnet.normalization.keepAspect = true ;\n \n% --------------------------------------------------------------------\nfunction net = add_block(net, opts, id, h, w, in, out, stride, pad, init_bias)\n% --------------------------------------------------------------------\ninfo = vl_simplenn_display(net) ;\nfc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;\nif fc\n name = 'fc' ;\nelse\n name = 'conv' ;\nend\nnet.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%s', name, id), ...\n 'weights', {{init_weight(opts, h, w, in, out, 'single'), zeros(out, 1, 'single')}}, ...\n 'stride', stride, ...\n 'pad', pad, ...\n 'learningRate', [1 2], ...\n 'weightDecay', [opts.weightDecay 0]) ;\nif opts.batchNormalization\n net.layers{end+1} = struct('type', 'bnorm', 'name', sprintf('bn%d',id), ...\n 'weights', {{ones(out, 1, 'single'), zeros(out, 1, 'single')}}, ...\n 'learningRate', [2 1], ...\n 'weightDecay', [0 0]) ;\nend\nnet.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%s',id)) ;\n\n% -------------------------------------------------------------------------\nfunction weights = init_weight(opts, h, w, in, out, type)\n% -------------------------------------------------------------------------\n% See K. He, X. Zhang, S. Ren, and J. Sun. Delving deep into\n% rectifiers: Surpassing human-level performance on imagenet\n% classification. CoRR, (arXiv:1502.01852v1), 2015.\n\nswitch lower(opts.weightInitMethod)\n case 'gaussian'\n sc = 0.01/opts.scale ;\n weights = randn(h, w, in, out, type)*sc;\n case 'xavier'\n sc = sqrt(3/(h*w*in)) ;\n weights = (rand(h, w, in, out, type)*2 - 1)*sc ;\n case 'xavierimproved'\n sc = sqrt(2/(h*w*out)) ;\n weights = randn(h, w, in, out, type)*sc ;\n otherwise\n error('Unknown weight initialization method''%s''', opts.weightInitMethod) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = add_norm(net, opts, id)\n% --------------------------------------------------------------------\nif ~opts.batchNormalization\n net.layers{end+1} = struct('type', 'normalize', ...\n 'name', sprintf('norm%s', id), ...\n 'param', [5 1 0.0001/5 0.75]) ;\nend\n\n% --------------------------------------------------------------------\nfunction net = add_dropout(net, opts, id)\n% --------------------------------------------------------------------\nif ~opts.batchNormalization\n net.layers{end+1} = struct('type', 'dropout', ...\n 'name', sprintf('dropout%s', id), ...\n 'rate', 0.5) ;\nend\n\n\n% --------------------------------------------------------------------\nfunction net = alexnet(net, opts)\n% --------------------------------------------------------------------\n\nnet.layers = {} ;\n\nnet = add_block(net, opts, '1', 11, 11, 3, 96, 4, 0) ;\nnet = add_norm(net, opts, '1') ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n\nnet = add_block(net, opts, '2', 5, 5, 48, 256, 1, 2) ;\nnet = add_norm(net, opts, '2') ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n\nnet = add_block(net, opts, '3', 3, 3, 256, 384, 1, 1) ;\nnet = add_block(net, opts, '4', 3, 3, 192, 384, 1, 1) ;\nnet = add_block(net, opts, '5', 3, 3, 192, 256, 1, 1) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\nnet = add_block(net, opts, '6', 6, 6, 256, 4096, 1, 0) ;\nnet = add_dropout(net, opts, '6') ;\n\nnet = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;\nnet = add_dropout(net, opts, '7') ;\n\nnet = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;\nnet.layers(end) = [] ;\nif opts.batchNormalization, net.layers(end) = [] ; end\n\n% --------------------------------------------------------------------\nfunction net = vgg_s(net, opts)\n% --------------------------------------------------------------------\n\nnet.layers = {} ;\nnet = add_block(net, opts, '1', 7, 7, 3, 96, 2, 0) ;\nnet = add_norm(net, opts, '1') ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 3, ...\n 'pad', [0 2 0 2]) ;\n\nnet = add_block(net, opts, '2', 5, 5, 96, 256, 1, 0) ;\nnet = add_norm(net, opts, '2') ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...\n 'method', 'max', ...\n 'pool', [2 2], ...\n 'stride', 2, ...\n 'pad', [0 1 0 1]) ;\n\nnet = add_block(net, opts, '3', 3, 3, 256, 512, 1, 1) ;\nnet = add_block(net, opts, '4', 3, 3, 512, 512, 1, 1) ;\nnet = add_block(net, opts, '5', 3, 3, 512, 512, 1, 1) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 3, ...\n 'pad', [0 1 0 1]) ;\n\nnet = add_block(net, opts, '6', 6, 6, 512, 4096, 1, 0) ;\nnet = add_dropout(net, opts, '6') ;\n\nnet = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;\nnet = add_dropout(net, opts, '7') ;\n\nnet = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;\nnet.layers(end) = [] ;\nif opts.batchNormalization, net.layers(end) = [] ; end\n\n% --------------------------------------------------------------------\nfunction net = vgg_m(net, opts)\n% --------------------------------------------------------------------\n\nnet.layers = {} ;\nnet = add_block(net, opts, '1', 7, 7, 3, 96, 2, 0) ;\nnet = add_norm(net, opts, '1') ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\nnet = add_block(net, opts, '2', 5, 5, 96, 256, 2, 1) ;\nnet = add_norm(net, opts, '2') ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', [0 1 0 1]) ;\n\nnet = add_block(net, opts, '3', 3, 3, 256, 512, 1, 1) ;\nnet = add_block(net, opts, '4', 3, 3, 512, 512, 1, 1) ;\nnet = add_block(net, opts, '5', 3, 3, 512, 512, 1, 1) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\nnet = add_block(net, opts, '6', 6, 6, 512, 4096, 1, 0) ;\nnet = add_dropout(net, opts, '6') ;\n\nnet = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;\nnet = add_dropout(net, opts, '7') ;\n\nnet = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;\nnet.layers(end) = [] ;\nif opts.batchNormalization, net.layers(end) = [] ; end\n\n% --------------------------------------------------------------------\nfunction net = vgg_f(net, opts)\n% --------------------------------------------------------------------\n\nnet.layers = {} ;\nnet = add_block(net, opts, '1', 11, 11, 3, 64, 4, 0) ;\nnet = add_norm(net, opts, '1') ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', [0 1 0 1]) ;\n\nnet = add_block(net, opts, '2', 5, 5, 64, 256, 1, 2) ;\nnet = add_norm(net, opts, '2') ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\nnet = add_block(net, opts, '3', 3, 3, 256, 256, 1, 1) ;\nnet = add_block(net, opts, '4', 3, 3, 256, 256, 1, 1) ;\nnet = add_block(net, opts, '5', 3, 3, 256, 256, 1, 1) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\nnet = add_block(net, opts, '6', 6, 6, 256, 4096, 1, 0) ;\nnet = add_dropout(net, opts, '6') ;\n\nnet = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;\nnet = add_dropout(net, opts, '7') ;\n\nnet = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;\nnet.layers(end) = [] ;\nif opts.batchNormalization, net.layers(end) = [] ; end\n\n% --------------------------------------------------------------------\nfunction net = vgg_vd(net, opts)\n% --------------------------------------------------------------------\n\nnet.layers = {} ;\nnet = add_block(net, opts, '1_1', 3, 3, 3, 64, 1, 1) ;\nnet = add_block(net, opts, '1_2', 3, 3, 64, 64, 1, 1) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...\n 'method', 'max', ...\n 'pool', [2 2], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\nnet = add_block(net, opts, '2_1', 3, 3, 64, 128, 1, 1) ;\nnet = add_block(net, opts, '2_2', 3, 3, 128, 128, 1, 1) ;\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...\n 'method', 'max', ...\n 'pool', [2 2], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\nnet = add_block(net, opts, '3_1', 3, 3, 128, 256, 1, 1) ;\nnet = add_block(net, opts, '3_2', 3, 3, 256, 256, 1, 1) ;\nnet = add_block(net, opts, '3_3', 3, 3, 256, 256, 1, 1) ;\nif strcmp(opts.model, 'vgg-vd-19')\n net = add_block(net, opts, '3_4', 3, 3, 256, 256, 1, 1) ;\nend\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool3', ...\n 'method', 'max', ...\n 'pool', [2 2], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\nnet = add_block(net, opts, '4_1', 3, 3, 256, 512, 1, 1) ;\nnet = add_block(net, opts, '4_2', 3, 3, 512, 512, 1, 1) ;\nnet = add_block(net, opts, '4_3', 3, 3, 512, 512, 1, 1) ;\nif strcmp(opts.model, 'vgg-vd-19')\n net = add_block(net, opts, '4_4', 3, 3, 512, 512, 1, 1) ;\nend\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool4', ...\n 'method', 'max', ...\n 'pool', [2 2], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\nnet = add_block(net, opts, '5_1', 3, 3, 256, 512, 1, 1) ;\nnet = add_block(net, opts, '5_2', 3, 3, 512, 512, 1, 1) ;\nnet = add_block(net, opts, '5_3', 3, 3, 512, 512, 1, 1) ;\nif strcmp(opts.model, 'vgg-vd-19')\n net = add_block(net, opts, '5_4', 3, 3, 512, 512, 1, 1) ;\nend\nnet.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...\n 'method', 'max', ...\n 'pool', [2 2], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\nnet = add_block(net, opts, '6', 7, 7, 512, 4096, 1, 0) ;\nnet = add_dropout(net, opts, '6') ;\n\nnet = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;\nnet = add_dropout(net, opts, '7') ;\n\nnet = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;\nnet.layers(end) = [] ;\nif opts.batchNormalization, net.layers(end) = [] ; end"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_imagenet.m", "ext": ".m", "path": "2015_Face_Detection-master/examples/cnn_imagenet.m", "size": 4845, "source_encoding": "utf_8", "md5": "977ffcdc699d894c410a46c4024cef34", "text": "function cnn_imagenet(varargin)\n% CNN_IMAGENET Demonstrates training a CNN on ImageNet\n% This demo demonstrates training the AlexNet, VGG-F, VGG-S, VGG-M,\n% VGG-VD-16, and VGG-VD-19 architectures on ImageNet data.\n\nrun(fullfile(fileparts(mfilename('fullpath')), ...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.dataDir = fullfile('data','ILSVRC2012') ;\nopts.modelType = 'alexnet' ;\nopts.batchNormalization = false ;\nopts.weightInitMethod = 'gaussian' ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nsfx = opts.modelType ;\nif opts.batchNormalization, sfx = [sfx '-bnorm'] ; end\nopts.expDir = fullfile('data', sprintf('imagenet12-%s', sfx)) ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.numFetchThreads = 12 ;\nopts.lite = false ;\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.train.batchSize = 256 ;\nopts.train.numSubBatches = 1 ;\nopts.train.continue = true ;\nopts.train.gpus = [] ;\nopts.train.prefetch = true ;\nopts.train.sync = false ;\nopts.train.cudnn = true ;\nopts.train.expDir = opts.expDir ;\nif ~opts.batchNormalization\n opts.train.learningRate = logspace(-2, -4, 60) ;\nelse\n opts.train.learningRate = logspace(-1, -4, 20) ;\nend\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.train.numEpochs = numel(opts.train.learningRate) ;\nopts = vl_argparse(opts, varargin) ;\n\n% -------------------------------------------------------------------------\n% Database initialization\n% -------------------------------------------------------------------------\n\nif exist(opts.imdbPath)\n imdb = load(opts.imdbPath) ;\nelse\n imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n\nnet = cnn_imagenet_init('model', opts.modelType, ...\n 'batchNormalization', opts.batchNormalization, ...\n 'weightInitMethod', opts.weightInitMethod) ;\nbopts = net.normalization ;\nbopts.numThreads = opts.numFetchThreads ;\n\n% compute image statistics (mean, RGB covariances etc)\nimageStatsPath = fullfile(opts.expDir, 'imageStats.mat') ;\nif exist(imageStatsPath)\n load(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;\nelse\n [averageImage, rgbMean, rgbCovariance] = getImageStats(imdb, bopts) ;\n save(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;\nend\n\n% One can use the average RGB value, or use a different average for\n% each pixel\n%net.normalization.averageImage = averageImage ;\nnet.normalization.averageImage = rgbMean ;\n\n% -------------------------------------------------------------------------\n% Stochastic gradient descent\n% -------------------------------------------------------------------------\n\n[v,d] = eig(rgbCovariance) ;\nbopts.transformation = 'stretch' ;\nbopts.averageImage = rgbMean ;\nbopts.rgbVariance = 0.1*sqrt(d)*v' ;\nfn = getBatchWrapper(bopts) ;\n\n[net,info] = cnn_train(net, imdb, fn, opts.train, 'conserveMemory', true) ;\n\n% -------------------------------------------------------------------------\nfunction fn = getBatchWrapper(opts)\n% -------------------------------------------------------------------------\nfn = @(imdb,batch) getBatch(imdb,batch,opts) ;\n\n% -------------------------------------------------------------------------\nfunction [im,labels] = getBatch(imdb, batch, opts)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nim = cnn_imagenet_get_batch(images, opts, ...\n 'prefetch', nargout == 0) ;\nlabels = imdb.images.label(batch) ;\n\n% -------------------------------------------------------------------------\nfunction [averageImage, rgbMean, rgbCovariance] = getImageStats(imdb, opts)\n% -------------------------------------------------------------------------\ntrain = find(imdb.images.set == 1) ;\ntrain = train(1: 101: end);\nbs = 256 ;\nfn = getBatchWrapper(opts) ;\nfor t=1:bs:numel(train)\n batch_time = tic ;\n batch = train(t:min(t+bs-1, numel(train))) ;\n fprintf('collecting image stats: batch starting with image %d ...', batch(1)) ;\n temp = fn(imdb, batch) ;\n z = reshape(permute(temp,[3 1 2 4]),3,[]) ;\n n = size(z,2) ;\n avg{t} = mean(temp, 4) ;\n rgbm1{t} = sum(z,2)/n ;\n rgbm2{t} = z*z'/n ;\n batch_time = toc(batch_time) ;\n fprintf(' %.2f s (%.1f images/s)\\n', batch_time, numel(batch)/ batch_time) ;\nend\naverageImage = mean(cat(4,avg{:}),4) ;\nrgbm1 = mean(cat(2,rgbm1{:}),2) ;\nrgbm2 = mean(cat(3,rgbm2{:}),3) ;\nrgbMean = rgbm1 ;\nrgbCovariance = rgbm2 - rgbm1*rgbm1' ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_mnist.m", "ext": ".m", "path": "2015_Face_Detection-master/examples/cnn_mnist.m", "size": 3314, "source_encoding": "utf_8", "md5": "dcd8a9724a02c534f5157bdc1a521eaa", "text": "function [net, info] = cnn_mnist(varargin)\n% CNN_MNIST Demonstrated MatConNet on MNIST\n\nrun(fullfile(fileparts(mfilename('fullpath')),...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.expDir = fullfile('data','mnist-baseline') ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.dataDir = fullfile('data','mnist') ;\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.useBnorm = false ;\nopts.train.batchSize = 100 ;\nopts.train.numEpochs = 20 ;\nopts.train.continue = true ;\nopts.train.gpus = [] ;\nopts.train.learningRate = 0.001 ;\nopts.train.expDir = opts.expDir ;\nopts = vl_argparse(opts, varargin) ;\n\n% --------------------------------------------------------------------\n% Prepare data\n% --------------------------------------------------------------------\n\nif exist(opts.imdbPath, 'file')\n imdb = load(opts.imdbPath) ;\nelse\n imdb = getMnistImdb(opts) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\nnet = cnn_mnist_init('useBnorm', opts.useBnorm) ;\n\n% --------------------------------------------------------------------\n% Train\n% --------------------------------------------------------------------\n\n[net, info] = cnn_train(net, imdb, @getBatch, ...\n opts.train, ...\n 'val', find(imdb.images.set == 3)) ;\n\n% --------------------------------------------------------------------\nfunction [im, labels] = getBatch(imdb, batch)\n% --------------------------------------------------------------------\nim = imdb.images.data(:,:,:,batch) ;\nlabels = imdb.images.labels(1,batch) ;\n\n% --------------------------------------------------------------------\nfunction imdb = getMnistImdb(opts)\n% --------------------------------------------------------------------\n% Preapre the imdb structure, returns image data with mean image subtracted\nfiles = {'train-images-idx3-ubyte', ...\n 'train-labels-idx1-ubyte', ...\n 't10k-images-idx3-ubyte', ...\n 't10k-labels-idx1-ubyte'} ;\n\nif ~exist(opts.dataDir, 'dir')\n mkdir(opts.dataDir) ;\nend\n\nfor i=1:4\n if ~exist(fullfile(opts.dataDir, files{i}), 'file')\n url = sprintf('http://yann.lecun.com/exdb/mnist/%s.gz',files{i}) ;\n fprintf('downloading %s\\n', url) ;\n gunzip(url, opts.dataDir) ;\n end\nend\n\nf=fopen(fullfile(opts.dataDir, 'train-images-idx3-ubyte'),'r') ;\nx1=fread(f,inf,'uint8');\nfclose(f) ;\nx1=permute(reshape(x1(17:end),28,28,60e3),[2 1 3]) ;\n\nf=fopen(fullfile(opts.dataDir, 't10k-images-idx3-ubyte'),'r') ;\nx2=fread(f,inf,'uint8');\nfclose(f) ;\nx2=permute(reshape(x2(17:end),28,28,10e3),[2 1 3]) ;\n\nf=fopen(fullfile(opts.dataDir, 'train-labels-idx1-ubyte'),'r') ;\ny1=fread(f,inf,'uint8');\nfclose(f) ;\ny1=double(y1(9:end)')+1 ;\n\nf=fopen(fullfile(opts.dataDir, 't10k-labels-idx1-ubyte'),'r') ;\ny2=fread(f,inf,'uint8');\nfclose(f) ;\ny2=double(y2(9:end)')+1 ;\n\nset = [ones(1,numel(y1)) 3*ones(1,numel(y2))];\ndata = single(reshape(cat(3, x1, x2),28,28,1,[]));\ndataMean = mean(data(:,:,:,set == 1), 4);\ndata = bsxfun(@minus, data, dataMean) ;\n\nimdb.images.data = data ;\nimdb.images.data_mean = dataMean;\nimdb.images.labels = cat(2, y1, y2) ;\nimdb.images.set = set ;\nimdb.meta.sets = {'train', 'val', 'test'} ;\nimdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_train.m", "ext": ".m", "path": "2015_Face_Detection-master/examples/cnn_train.m", "size": 14403, "source_encoding": "utf_8", "md5": "fcc2369c67d94400cd15eca628af970c", "text": "function [net, info] = cnn_train(net, imdb, getBatch, varargin)\n% CNN_TRAIN Demonstrates training a CNN\n% CNN_TRAIN() is an example learner implementing stochastic\n% gradient descent with momentum to train a CNN. It can be used\n% with different datasets and tasks by providing a suitable\n% getBatch function.\n%\n% The function automatically restarts after each training epoch by\n% checkpointing.\n%\n% The function supports training on CPU or on one or more GPUs\n% (specify the list of GPU IDs in the `gpus` option). Multi-GPU\n% support is relatively primitive but sufficient to obtain a\n% noticable speedup.\n\n% Copyright (C) 2014-15 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.batchSize = 256 ;\nopts.numSubBatches = 1 ;\nopts.train = [] ;\nopts.val = [] ;\nopts.numEpochs = 300 ;\nopts.gpus = [] ; % which GPU devices to use (none, one, or more)\nopts.learningRate = 0.001 ;\nopts.continue = false ;\nopts.expDir = fullfile('data','exp') ;\nopts.conserveMemory = false ;\nopts.backPropDepth = +inf ;\nopts.sync = false ;\nopts.prefetch = false ;\nopts.cudnn = true ;\nopts.weightDecay = 0.0005 ;\nopts.momentum = 0.9 ;\nopts.errorFunction = 'multiclass' ;\nopts.errorLabels = {} ;\nopts.plotDiagnostics = false ;\nopts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;\nopts = vl_argparse(opts, varargin) ;\n\nif ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end\nif isempty(opts.train), opts.train = find(imdb.images.set==1) ; end\nif isempty(opts.val), opts.val = find(imdb.images.set==2) ; end\nif isnan(opts.train), opts.train = [] ; end\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n\nevaluateMode = isempty(opts.train) ;\n\nif ~evaluateMode\n for i=1:numel(net.layers)\n if isfield(net.layers{i}, 'weights')\n J = numel(net.layers{i}.weights) ;\n for j=1:J\n net.layers{i}.momentum{j} = zeros(size(net.layers{i}.weights{j}), 'single') ;\n end\n if ~isfield(net.layers{i}, 'learningRate')\n net.layers{i}.learningRate = ones(1, J, 'single') ;\n end\n if ~isfield(net.layers{i}, 'weightDecay')\n net.layers{i}.weightDecay = ones(1, J, 'single') ;\n end\n end\n % Legacy code: will be removed\n if isfield(net.layers{i}, 'filters')\n net.layers{i}.momentum{1} = zeros(size(net.layers{i}.filters), 'single') ;\n net.layers{i}.momentum{2} = zeros(size(net.layers{i}.biases), 'single') ;\n if ~isfield(net.layers{i}, 'learningRate')\n net.layers{i}.learningRate = ones(1, 2, 'single') ;\n end\n if ~isfield(net.layers{i}, 'weightDecay')\n net.layers{i}.weightDecay = single([1 0]) ;\n end\n end\n end\nend\n\n% setup GPUs\nnumGpus = numel(opts.gpus) ;\nif numGpus > 1\n if isempty(gcp('nocreate')),\n parpool('local',numGpus) ;\n spmd, gpuDevice(opts.gpus(labindex)), end\n end\nelseif numGpus == 1\n gpuDevice(opts.gpus)\nend\nif exist(opts.memoryMapFile), delete(opts.memoryMapFile) ; end\n\n% setup error calculation function\nif isstr(opts.errorFunction)\n switch opts.errorFunction\n case 'none'\n opts.errorFunction = @error_none ;\n case 'multiclass'\n opts.errorFunction = @error_multiclass ;\n if isempty(opts.errorLabels), opts.errorLabels = {'top1e', 'top5e'} ; end\n case 'binary'\n opts.errorFunction = @error_binary ;\n if isempty(opts.errorLabels), opts.errorLabels = {'bine'} ; end\n otherwise\n error('Uknown error function ''%s''', opts.errorFunction) ;\n end\nend\n\n% -------------------------------------------------------------------------\n% Train and validate\n% -------------------------------------------------------------------------\n\nfor epoch=1:opts.numEpochs\n learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;\n\n % fast-forward to last checkpoint\n modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));\n modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;\n if opts.continue\n if exist(modelPath(epoch),'file')\n if epoch == opts.numEpochs\n load(modelPath(epoch), 'net', 'info') ;\n end\n continue ;\n end\n if epoch > 1\n fprintf('resuming by loading epoch %d\\n', epoch-1) ;\n load(modelPath(epoch-1), 'net', 'info') ;\n end\n end\n\n % train one epoch and validate\n train = opts.train(randperm(numel(opts.train))) ; % shuffle\n val = opts.val ;\n if numGpus <= 1\n [net,stats.train] = process_epoch(opts, getBatch, epoch, train, learningRate, imdb, net) ;\n [~,stats.val] = process_epoch(opts, getBatch, epoch, val, 0, imdb, net) ;\n else\n spmd(numGpus)\n [net_, stats_train_] = process_epoch(opts, getBatch, epoch, train, learningRate, imdb, net) ;\n [~, stats_val_] = process_epoch(opts, getBatch, epoch, val, 0, imdb, net_) ;\n end\n net = net_{1} ;\n stats.train = sum([stats_train_{:}],2) ;\n stats.val = sum([stats_val_{:}],2) ;\n end\n\n % save\n if evaluateMode, sets = {'val'} ; else sets = {'train', 'val'} ; end\n for f = sets\n f = char(f) ;\n n = numel(eval(f)) ;\n info.(f).speed(epoch) = n / stats.(f)(1) * max(1, numGpus) ;\n info.(f).objective(epoch) = stats.(f)(2) / n ;\n info.(f).error(:,epoch) = stats.(f)(3:end) / n ;\n end\n if ~evaluateMode, save(modelPath(epoch), 'net', 'info') ; end\n\n figure(1) ; clf ;\n hasError = isa(opts.errorFunction, 'function_handle') ;\n subplot(1,1+hasError,1) ;\n if ~evaluateMode\n semilogy(1:epoch, info.train.objective, '.-', 'linewidth', 2) ;\n hold on ;\n end\n semilogy(1:epoch, info.val.objective, '.--') ;\n xlabel('training epoch') ; ylabel('energy') ;\n grid on ;\n h=legend(sets) ;\n set(h,'color','none');\n title('objective') ;\n if hasError\n subplot(1,2,2) ; leg = {} ;\n if ~evaluateMode\n plot(1:epoch, info.train.error', '.-', 'linewidth', 2) ;\n hold on ;\n leg = horzcat(leg, strcat('train ', opts.errorLabels)) ;\n end\n plot(1:epoch, info.val.error', '.--') ;\n leg = horzcat(leg, strcat('val ', opts.errorLabels)) ;\n set(legend(leg{:}),'color','none') ;\n grid on ;\n xlabel('training epoch') ; ylabel('error') ;\n title('error') ;\n end\n drawnow ;\n print(1, modelFigPath, '-dpdf') ;\nend\n\n% -------------------------------------------------------------------------\nfunction err = error_multiclass(opts, labels, res)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\n[~,predictions] = sort(predictions, 3, 'descend') ;\n\n% be resilient to badly formatted labels\nif numel(labels) == size(predictions, 4)\n labels = reshape(labels,1,1,1,[]) ;\nend\n\n% skip null labels\nmass = single(labels(:,:,1,:) > 0) ;\nif size(labels,3) == 2\n % if there is a second channel in labels, used it as weights\n mass = mass .* labels(:,:,2,:) ;\n labels(:,:,2,:) = [] ;\nend\n\nerror = ~bsxfun(@eq, predictions, labels) ;\nerr(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ;\nerr(2,1) = sum(sum(sum(mass .* min(error(:,:,1:5,:),[],3)))) ;\n\n% -------------------------------------------------------------------------\nfunction err = error_binary(opts, labels, res)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\n[~,predictions] = sort(predictions, 3, 'descend') ;\n\n% be resilient to badly formatted labels\nif numel(labels) == size(predictions, 4)\n labels = reshape(labels,1,1,1,[]) ;\nend\n\n% skip null labels\nmass = single(labels(:,:,1,:) > 0) ;\n\nerror = ~bsxfun(@eq, predictions, labels) ;\nerr = sum(sum(sum(mass .* error(:,:,1,:)))) ;\n\n% -------------------------------------------------------------------------\nfunction err = error_none(opts, labels, res)\n% -------------------------------------------------------------------------\nerr = zeros(0,1) ;\n\n% -------------------------------------------------------------------------\nfunction [net_cpu,stats,prof] = process_epoch(opts, getBatch, epoch, subset, learningRate, imdb, net_cpu)\n% -------------------------------------------------------------------------\n\n% move CNN to GPU as needed\nnumGpus = numel(opts.gpus) ;\nif numGpus >= 1\n net = vl_simplenn_move(net_cpu, 'gpu') ;\nelse\n net = net_cpu ;\n net_cpu = [] ;\nend\n\n% validation mode if learning rate is zero\ntraining = learningRate > 0 ;\nif training, mode = 'training' ; else, mode = 'validation' ; end\nif nargout > 2, mpiprofile on ; end\n\nnumGpus = numel(opts.gpus) ;\nif numGpus >= 1\n one = gpuArray(single(1)) ;\nelse\n one = single(1) ;\nend\nres = [] ;\nmmap = [] ;\nstats = [] ;\n\nfor t=1:opts.batchSize:numel(subset)\n fprintf('%s: epoch %02d: batch %3d/%3d: ', mode, epoch, ...\n fix(t/opts.batchSize)+1, ceil(numel(subset)/opts.batchSize)) ;\n batchSize = min(opts.batchSize, numel(subset) - t + 1) ;\n batchTime = tic ;\n numDone = 0 ;\n error = [] ;\n for s=1:opts.numSubBatches\n % get this image batch and prefetch the next\n batchStart = t + (labindex-1) + (s-1) * numlabs ;\n batchEnd = min(t+opts.batchSize-1, numel(subset)) ;\n batch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ;\n [im, labels] = getBatch(imdb, batch) ;\n\n if opts.prefetch\n if s==opts.numSubBatches\n batchStart = t + (labindex-1) + opts.batchSize ;\n batchEnd = min(t+2*opts.batchSize-1, numel(subset)) ;\n else\n batchStart = batchStart + numlabs ;\n end\n nextBatch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ;\n getBatch(imdb, nextBatch) ;\n end\n\n if numGpus >= 1\n im = gpuArray(im) ;\n end\n\n % evaluate CNN\n net.layers{end}.class = labels ;\n if training, dzdy = one; else, dzdy = [] ; end\n res = vl_simplenn(net, im, dzdy, res, ...\n 'accumulate', s ~= 1, ...\n 'disableDropout', ~training, ...\n 'conserveMemory', opts.conserveMemory, ...\n 'backPropDepth', opts.backPropDepth, ...\n 'sync', opts.sync, ...\n 'cudnn', opts.cudnn) ;\n\n % accumulate training errors\n error = sum([error, [...\n sum(double(gather(res(end).x))) ;\n reshape(opts.errorFunction(opts, labels, res),[],1) ; ]],2) ;\n numDone = numDone + numel(batch) ;\n end\n\n % gather and accumulate gradients across labs\n if training\n if numGpus <= 1\n [net,res] = accumulate_gradients(opts, learningRate, batchSize, net, res) ;\n else\n if isempty(mmap)\n mmap = map_gradients(opts.memoryMapFile, net, res, numGpus) ;\n end\n write_gradients(mmap, net, res) ;\n labBarrier() ;\n [net,res] = accumulate_gradients(opts, learningRate, batchSize, net, res, mmap) ;\n end\n end\n\n % print learning statistics\n batchTime = toc(batchTime) ;\n stats = sum([stats,[batchTime ; error]],2); % works even when stats=[]\n speed = batchSize/batchTime ;\n\n fprintf(' %.2f s (%.1f data/s)', batchTime, speed) ;\n n = (t + batchSize - 1) / max(1,numlabs) ;\n fprintf(' obj:%.3g', stats(2)/n) ;\n for i=1:numel(opts.errorLabels)\n fprintf(' %s:%.3g', opts.errorLabels{i}, stats(i+2)/n) ;\n end\n fprintf(' [%d/%d]', numDone, batchSize);\n fprintf('\\n') ;\n\n % debug info\n if opts.plotDiagnostics && numGpus <= 1\n figure(2) ; vl_simplenn_diagnose(net,res) ; drawnow ;\n end\nend\n\nif nargout > 2\n prof = mpiprofile('info');\n mpiprofile off ;\nend\n\nif numGpus >= 1\n net_cpu = vl_simplenn_move(net, 'cpu') ;\nelse\n net_cpu = net ;\nend\n\n% -------------------------------------------------------------------------\nfunction [net,res] = accumulate_gradients(opts, lr, batchSize, net, res, mmap)\n% -------------------------------------------------------------------------\nfor l=numel(net.layers):-1:1\n for j=1:numel(res(l).dzdw)\n thisDecay = opts.weightDecay * net.layers{l}.weightDecay(j) ;\n thisLR = lr * net.layers{l}.learningRate(j) ;\n\n % accumualte from multiple labs (GPUs) if needed\n if nargin >= 6\n tag = sprintf('l%d_%d',l,j) ;\n tmp = zeros(size(mmap.Data(labindex).(tag)), 'single') ;\n for g = setdiff(1:numel(mmap.Data), labindex)\n tmp = tmp + mmap.Data(g).(tag) ;\n end\n res(l).dzdw{j} = res(l).dzdw{j} + tmp ;\n end\n\n if isfield(net.layers{l}, 'weights')\n net.layers{l}.momentum{j} = ...\n opts.momentum * net.layers{l}.momentum{j} ...\n - thisDecay * net.layers{l}.weights{j} ...\n - (1 / batchSize) * res(l).dzdw{j} ;\n net.layers{l}.weights{j} = net.layers{l}.weights{j} + thisLR * net.layers{l}.momentum{j} ;\n else\n % Legacy code: to be removed\n if j == 1\n net.layers{l}.momentum{j} = ...\n opts.momentum * net.layers{l}.momentum{j} ...\n - thisDecay * net.layers{l}.filters ...\n - (1 / batchSize) * res(l).dzdw{j} ;\n net.layers{l}.filters = net.layers{l}.filters + thisLR * net.layers{l}.momentum{j} ;\n else\n net.layers{l}.momentum{j} = ...\n opts.momentum * net.layers{l}.momentum{j} ...\n - thisDecay * net.layers{l}.biases ...\n - (1 / batchSize) * res(l).dzdw{j} ;\n net.layers{l}.biases = net.layers{l}.biases + thisLR * net.layers{l}.momentum{j} ;\n end\n end\n end\nend\n\n% -------------------------------------------------------------------------\nfunction mmap = map_gradients(fname, net, res, numGpus)\n% -------------------------------------------------------------------------\nformat = {} ;\nfor i=1:numel(net.layers)\n for j=1:numel(res(i).dzdw)\n format(end+1,1:3) = {'single', size(res(i).dzdw{j}), sprintf('l%d_%d',i,j)} ;\n end\nend\nformat(end+1,1:3) = {'double', [3 1], 'errors'} ;\nif ~exist(fname) && (labindex == 1)\n f = fopen(fname,'wb') ;\n for g=1:numGpus\n for i=1:size(format,1)\n fwrite(f,zeros(format{i,2},format{i,1}),format{i,1}) ;\n end\n end\n fclose(f) ;\nend\nlabBarrier() ;\nmmap = memmapfile(fname, 'Format', format, 'Repeat', numGpus, 'Writable', true) ;\n\n% -------------------------------------------------------------------------\nfunction write_gradients(mmap, net, res)\n% -------------------------------------------------------------------------\nfor i=1:numel(net.layers)\n for j=1:numel(res(i).dzdw)\n mmap.Data(labindex).(sprintf('l%d_%d',i,j)) = gather(res(i).dzdw{j}) ;\n end\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_imagenet_mgpu.m", "ext": ".m", "path": "2015_Face_Detection-master/examples/cnn_imagenet_mgpu.m", "size": 9705, "source_encoding": "utf_8", "md5": "8297e5ae85c01972f432a68fd13ac492", "text": "function cnn_imagenet_mgpu(varargin)\n% CNN_IMAGENET Demonstrates training a CNN on ImageNet\n\nrun(fullfile(fileparts(mfilename('fullpath')), ...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.dataDir = fullfile('data','ram','ILSVRC2012') ;\nopts.expDir = fullfile('data','imagenet12-baseline-mgpu') ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.lite = false ;\nopts.numFetchThreads = 12 ;\nopts.train.batchSize = 256*4 ;\nopts.train.numEpochs = 65 ;\nopts.train.continue = true ;\nopts.train.gpus = 1:4 ;\nopts.train.prefetch = true ;\nopts.train.learningRate = [0.01*ones(1, 25) 0.001*ones(1, 25) 0.0001*ones(1,15)] ;\nopts.train.expDir = opts.expDir ;\nopts.train.memoryMapFile = '/mnt/ramdisk/vedaldi/m.dat' ;\nopts = vl_argparse(opts, varargin) ;\n\n% -------------------------------------------------------------------------\n% Database initialization\n% -------------------------------------------------------------------------\n\nif exist(opts.imdbPath)\n imdb = load(opts.imdbPath) ;\n imdb.imageDir = fullfile(opts.dataDir, 'images') ;\nelse\n imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n\nnet = initializeNetwork(opts) ;\n\n% compute the average image\naverageImagePath = fullfile(opts.expDir, 'average.mat') ;\nif exist(averageImagePath)\n load(averageImagePath, 'averageImage') ;\nelse\n train = find(imdb.images.set == 1) ;\n bs = 256 ;\n fn = getBatchWrapper(net.normalization, opts.numFetchThreads) ;\n for t=1:bs:numel(train)\n batch_time = tic ;\n batch = train(t:min(t+bs-1, numel(train))) ;\n fprintf('computing average image: processing batch starting with image %d ...', batch(1)) ;\n temp = fn(imdb, batch) ;\n im{t} = mean(temp, 4) ;\n batch_time = toc(batch_time) ;\n fprintf(' %.2f s (%.1f images/s)\\n', batch_time, numel(batch)/ batch_time) ;\n end\n averageImage = mean(cat(4, im{:}),4) ;\n save(averageImagePath, 'averageImage') ;\nend\n\nnet.normalization.averageImage = averageImage ;\nclear averageImage im temp ;\n\n% -------------------------------------------------------------------------\n% Stochastic gradient descent\n% -------------------------------------------------------------------------\n\nfn = getBatchWrapper(net.normalization, opts.numFetchThreads) ;\n\n[net,info] = cnn_train_mgpu(net, imdb, fn, opts.train, 'conserveMemory', true) ;\n\n% -------------------------------------------------------------------------\nfunction fn = getBatchWrapper(opts, numThreads)\n% -------------------------------------------------------------------------\nfn = @(imdb,batch) getBatch(imdb,batch,opts,numThreads) ;\n\n% -------------------------------------------------------------------------\nfunction [im,labels] = getBatch(imdb, batch, opts, numThreads)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nim = cnn_imagenet_get_batch(images, opts, ...\n 'numThreads', numThreads, ...\n 'prefetch', nargout == 0, ...\n 'augmentation', 'f25') ;\n%im = zeros(256,256,3,numel(batch),'single') ;\nlabels = imdb.images.label(batch) ;\n\n% -------------------------------------------------------------------------\nfunction net = initializeNetwork(opt)\n% -------------------------------------------------------------------------\n\nscal = 1 ;\ninit_bias = 0.1;\n\nnet.layers = {} ;\n\n% Block 1\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(11, 11, 3, 96, 'single'), ...\n 'biases', zeros(1, 96, 'single'), ...\n 'stride', 4, ...\n 'pad', 0, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'normalize', ...\n 'param', [5 1 0.0001/5 0.75]) ;\n\n% Block 2\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(5, 5, 48, 256, 'single'), ...\n 'biases', init_bias*ones(1, 256, 'single'), ...\n 'stride', 1, ...\n 'pad', 2, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\nnet.layers{end+1} = struct('type', 'normalize', ...\n 'param', [5 1 0.0001/5 0.75]) ;\n\n% Block 3\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(3,3,256,384,'single'), ...\n 'biases', init_bias*ones(1,384,'single'), ...\n 'stride', 1, ...\n 'pad', 1, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\n\n% Block 4\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(3,3,192,384,'single'), ...\n 'biases', init_bias*ones(1,384,'single'), ...\n 'stride', 1, ...\n 'pad', 1, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\n\n% Block 5\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(3,3,192,256,'single'), ...\n 'biases', init_bias*ones(1,256,'single'), ...\n 'stride', 1, ...\n 'pad', 1, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'pool', ...\n 'method', 'max', ...\n 'pool', [3 3], ...\n 'stride', 2, ...\n 'pad', 0) ;\n\n% Block 6\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(6,6,256,4096,'single'),...\n 'biases', init_bias*ones(1,4096,'single'), ...\n 'stride', 1, ...\n 'pad', 0, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'dropout', ...\n 'rate', 0.5) ;\n\n% Block 7\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(1,1,4096,4096,'single'),...\n 'biases', init_bias*ones(1,4096,'single'), ...\n 'stride', 1, ...\n 'pad', 0, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\nnet.layers{end+1} = struct('type', 'relu') ;\nnet.layers{end+1} = struct('type', 'dropout', ...\n 'rate', 0.5) ;\n\n% Block 8\nnet.layers{end+1} = struct('type', 'conv', ...\n 'filters', 0.01/scal * randn(1,1,4096,1000,'single'), ...\n 'biases', zeros(1, 1000, 'single'), ...\n 'stride', 1, ...\n 'pad', 0, ...\n 'filtersLearningRate', 1, ...\n 'biasesLearningRate', 2, ...\n 'filtersWeightDecay', 1, ...\n 'biasesWeightDecay', 0) ;\n\n% Block 9\nnet.layers{end+1} = struct('type', 'softmaxloss') ;\n\n% Other details\nnet.normalization.imageSize = [227, 227, 3] ;\nnet.normalization.interpolation = 'bicubic' ;\nnet.normalization.border = 256 - net.normalization.imageSize(1:2) ;\nnet.normalization.averageImage = [] ;\nnet.normalization.keepAspect = true ;\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "cnn_imagenet_evaluate.m", "ext": ".m", "path": "2015_Face_Detection-master/examples/cnn_imagenet_evaluate.m", "size": 2960, "source_encoding": "utf_8", "md5": "93a11af0121659362a46b7e80afe492b", "text": "function info = cnn_imagenet_evaluate(varargin)\n% CNN_IMAGENET_EVALUATE Evauate MatConvNet models on ImageNet\n\nrun(fullfile(fileparts(mfilename('fullpath')), ...\n '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.dataDir = fullfile('data', 'ILSVRC2012') ;\nopts.expDir = fullfile('data', 'imagenet12-eval-vgg-f') ;\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.modelPath = fullfile('data', 'models', 'imagenet-vgg-f.mat') ;\nopts.lite = false ;\nopts.numFetchThreads = 12 ;\nopts.train.batchSize = 128 ;\nopts.train.numEpochs = 1 ;\nopts.train.gpus = [] ;\nopts.train.prefetch = true ;\nopts.train.expDir = opts.expDir ;\nopts.train.conserveMemory = true ;\nopts.train.sync = true ;\n\nopts = vl_argparse(opts, varargin) ;\ndisplay(opts);\n\n% -------------------------------------------------------------------------\n% Database initialization\n% -------------------------------------------------------------------------\n\nif exist(opts.imdbPath)\n imdb = load(opts.imdbPath) ;\nelse\n imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n\nnet = load(opts.modelPath) ;\nif isfield(net, 'net') ;\n net = net.net ;\n net.classes = imdb.classes ;\nend\nnet.layers{end}.type = 'softmaxloss' ; % softmax -> softmaxloss\nnet.normalization.border = [256 256] - net.normalization.imageSize(1:2) ;\nvl_simplenn_display(net, 'batchSize', opts.train.batchSize) ;\n\n% Synchronize label indexes between the model and the image database\nimdb = cnn_imagenet_sync_labels(imdb, net);\n\n% -------------------------------------------------------------------------\n% Stochastic gradient descent\n% -------------------------------------------------------------------------\n\nbopts = net.normalization ;\nbopts.numThreads = opts.numFetchThreads ;\nfn = getBatchWrapper(bopts) ;\n\n[net,info] = cnn_train(net, imdb, fn, opts.train, ...\n 'train', NaN, ...\n 'val', find(imdb.images.set==2)) ;\n\n% -------------------------------------------------------------------------\nfunction fn = getBatchWrapper(opts)\n% -------------------------------------------------------------------------\nfn = @(imdb,batch) getBatch(imdb,batch,opts) ;\n\n% -------------------------------------------------------------------------\nfunction [im,labels] = getBatch(imdb, batch, opts)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nim = cnn_imagenet_get_batch(images, opts, ...\n 'prefetch', nargout == 0) ;\nlabels = imdb.images.label(batch) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_compilenn.m", "ext": ".m", "path": "2015_Face_Detection-master/matlab_12/vl_compilenn.m", "size": 24344, "source_encoding": "utf_8", "md5": "fdc476314ba2cd5c918dbc3a8b627eb2", "text": "function vl_compilenn( varargin )\n% VL_COMPILENN Compile the MatConvNet toolbox\n% The `vl_compilenn()` function compiles the MEX files in the\n% MatConvNet toolbox. See below for the requirements for compiling\n% CPU and GPU code, respectively.\n%\n% `vl_compilenn('OPTION', ARG, ...)` accepts the following options:\n%\n% `EnableGpu`:: `false`\n% Set to true in order to enable GPU support.\n%\n% `Verbose`:: 0\n% Set the verbosity level (0, 1 or 2).\n%\n% `Debug`:: `false`\n% Set to true to compile the binaries with debugging\n% information.\n%\n% `CudaMethod`:: Linux & Mac OS X: `mex`; Windows: `nvcc`\n% Choose the method used to compile the CUDA code. There are two\n% methods:\n%\n% * The **`mex`** method uses the MATLAB MEX command with the\n% configuration file\n% `/matlab/src/config/mex_CUDA_.[sh/xml]`\n% This configuration file is in XML format since MATLAB 8.3\n% (R2014a) and is a Shell script for earlier versions. This\n% is, principle, the preferred method as it uses the\n% MATLAB-sanctioned compiler options.\n%\n% * The **`nvcc`** method calls the NVIDIA CUDA compiler `nvcc`\n% directly to compile CUDA source code into object files.\n%\n% This method allows to use a CUDA toolkit version that is not\n% the one that officially supported by a particular MATALB\n% version (see below). It is also the default method for\n% compilation under Windows and with CuDNN.\n%\n% `CudaRoot`:: guessed automatically\n% This option specifies the path to the CUDA toolkit to use for\n% compilation.\n%\n% `EnableImreadJpeg`:: `true`\n% Set this option to `true` to compile `vl_imreadjpeg`.\n%\n% `ImageLibrary`:: `libjpeg` (Linux), `gdiplus` (Windows), `quartz` (Mac)\n% The image library to use for `vl_impreadjpeg`.\n%\n% `ImageLibraryCompileFlags`:: platform dependent\n% A cell-array of additional flags to use when compiling\n% `vl_imreadjpeg`.\n%\n% `ImageLibraryLinkFlags`:: platform dependent\n% A cell-array of additional flags to use when linking\n% `vl_imreadjpeg`.\n%\n% `EnableCudnn`:: `false`\n% Set to `true` to compile CuDNN support.\n%\n% `CudnnRoot`:: `'local/'`\n% Directory containing the unpacked binaries and header files of\n% the CuDNN library.\n%\n% ## Compiling the CPU code\n%\n% By default, the `EnableGpu` option is switched to off, such that\n% the GPU code support is not compiled in.\n%\n% Generally, you only need a C/C++ compiler (usually Xcode, GCC or\n% Visual Studio for Mac, Linux, and Windows respectively). The\n% compiler can be setup in MATLAB using the\n%\n% mex -setup\n%\n% command.\n%\n% ## Compiling the GPU code\n%\n% In order to compile the GPU code, set the `EnableGpu` option to\n% `true`. For this to work you will need:\n%\n% * To satisfy all the requirement to compile the CPU code (see\n% above).\n%\n% * A NVIDIA GPU with at least *compute capability 2.0*.\n%\n% * The *MATALB Parallel Computing Toolbox*. This can be purchased\n% from Mathworks (type `ver` in MATLAB to see if this toolbox is\n% already comprised in your MATLAB installation; it often is).\n%\n% * A copy of the *CUDA Devkit*, which can be downloaded for free\n% from NVIDIA. Note that each MATLAB version requires a\n% particular CUDA Devkit version:\n%\n% | MATLAB version | Release | CUDA Devkit |\n% |----------------|---------|-------------|\n% | 2013b | 2013b | 5.5 |\n% | 2014a | 2014a | 5.5 |\n% | 2014b | 2014b | 6.0 |\n%\n% A different versions of CUDA may work using the hack described\n% above (i.e. setting the `CudaMethod` to `nvcc`).\n%\n% The following configurations have been tested successfully:\n%\n% * Windows 7 x64, MATLAB R2014a, Visual C++ 2010 and CUDA Toolkit\n% 6.5 (unable to compile with Visual C++ 2013).\n% * Windows 8 x64, MATLAB R2014a, Visual C++ 2013 and CUDA\n% Toolkit 6.5.\n% * Mac OS X 10.9 and 10.10, MATLAB R2013a and R2013b, Xcode, CUDA\n% Toolkit 5.5.\n% * GNU/Linux, MATALB R2014a, gcc, CUDA Toolkit 5.5.\n%\n% Furthermore your GPU card must have ComputeCapability >= 2.0 (see\n% output of `gpuDevice()`) in order to be able to run the GPU code.\n% To change the compute capabilities, for `mex` `CudaMethod` edit\n% the particular config file. For the 'nvcc' method, compute\n% capability is guessed based on the GPUDEVICE output. You can\n% override it by setting the 'CudaArch' parameter (e.g. in case of\n% multiple GPUs with various architectures).\n%\n% See also: [Compliling MatConvNet](../install.md#compiling),\n% [Compiling MEX files containing CUDA\n% code](http://mathworks.com/help/distcomp/run-mex-functions-containing-cuda-code.html),\n% `vl_setup()`, `vl_imreadjpeg()`.\n\n% Copyright (C) 2014-15 Karel Lenc and Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% Get MatConvNet root directory\nroot = fileparts(fileparts(mfilename('fullpath'))) ;\naddpath(fullfile(root, 'matlab')) ;\n\n% --------------------------------------------------------------------\n% Parse options\n% --------------------------------------------------------------------\n\nopts.enableGpu = false;\nopts.enableImreadJpeg = true;\nopts.enableCudnn = false;\nopts.imageLibrary = [] ;\nopts.imageLibraryCompileFlags = {} ;\nopts.imageLibraryLinkFlags = [] ;\nopts.verbose = 0;\nopts.debug = false;\nopts.cudaMethod = [] ;\nopts.cudaRoot = [] ;\nopts.cudaArch = [] ;\nopts.defCudaArch = [...\n '-gencode=arch=compute_20,code=\\\"sm_20,compute_20\\\" '...\n '-gencode=arch=compute_30,code=\\\"sm_30,compute_30\\\"'];\nopts.cudnnRoot = 'local' ;\nopts = vl_argparse(opts, varargin);\n\n% --------------------------------------------------------------------\n% Files to compile\n% --------------------------------------------------------------------\n\narch = computer('arch') ;\nif isempty(opts.imageLibrary)\n switch arch\n case 'glnxa64', opts.imageLibrary = 'libjpeg' ;\n case 'maci64', opts.imageLibrary = 'quartz' ;\n case 'win64', opts.imageLibrary = 'gdiplus' ;\n end\nend\nif isempty(opts.imageLibraryLinkFlags)\n switch opts.imageLibrary\n case 'libjpeg', opts.imageLibraryLinkFlags = {'-ljpeg'} ;\n case 'quartz', opts.imageLibraryLinkFlags = {'LDFLAGS=$LDFLAGS -framework Cocoa -framework ImageIO'} ;\n case 'gdiplus', opts.imageLibraryLinkFlags = {'-lgdiplus'} ;\n end\nend\n\nlib_src = {} ;\nmex_src = {} ;\n\n% Files that are compiled as CPP or CU depending on whether GPU support\n% is enabled.\nif opts.enableGpu, ext = 'cu' ; else, ext='cpp' ; end\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['data.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['datamex.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnconv.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnfullyconnected.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnsubsample.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnpooling.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnnormalize.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbias.' ext]) ;\nmex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconv.' ext]) ;\nmex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconvt.' ext]) ;\nmex_src{end+1} = fullfile(root,'matlab','src',['vl_nnpool.' ext]) ;\nmex_src{end+1} = fullfile(root,'matlab','src',['vl_nnnormalize.' ext]) ;\n\n% CPU-specific files\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','tinythread.cpp') ;\n\n% GPU-specific files\nif opts.enableGpu\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','datacu.cu') ;\nend\n\n% cuDNN-specific files\nif opts.enableCudnn\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnconv_cudnn.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbias_cudnn.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnpooling_cudnn.cu') ;\nend\n\n% Other files\nif opts.enableImreadJpeg\n mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg.' ext]) ;\n lib_src{end+1} = fullfile(root,'matlab','src', 'bits', 'impl', ['imread_' opts.imageLibrary '.cpp']) ;\nend\n\n% --------------------------------------------------------------------\n% Setup CUDA toolkit\n% --------------------------------------------------------------------\n\nif opts.enableGpu\n opts.verbose && fprintf('%s: * CUDA configuration *\\n', mfilename) ;\n if isempty(opts.cudaRoot), opts.cudaRoot = search_cuda_devkit(opts); end\n check_nvcc(opts.cudaRoot);\n opts.verbose && fprintf('%s:\\tCUDA: using CUDA Devkit ''%s''.\\n', ...\n mfilename, opts.cudaRoot) ;\n switch arch\n case 'win64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib', 'x64') ;\n case 'maci64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib') ;\n case 'glnxa64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib64') ;\n otherwise, error('Unsupported architecture ''%s''.', arch) ;\n end\n opts.nvccPath = fullfile(opts.cudaRoot, 'bin', 'nvcc') ;\n\n % CUDA arch string (select GPU architecture)\n if isempty(opts.cudaArch), opts.cudaArch = get_cuda_arch(opts) ; end\n opts.verbose && fprintf('%s:\\tCUDA: NVCC architecture string: ''%s''.\\n', ...\n mfilename, opts.cudaArch) ;\n\n % Make sure NVCC is visible by MEX by setting the corresp. env. var\n if ~strcmp(getenv('MW_NVCC_PATH'), opts.nvccPath)\n warning('Setting the ''MW_NVCC_PATH'' environment variable to ''%s''', ...\n opts.nvccPath) ;\n setenv('MW_NVCC_PATH', opts.nvccPath) ;\n end\nend\n\n% --------------------------------------------------------------------\n% Compiler options\n% --------------------------------------------------------------------\n\n% Build directories\nmex_dir = fullfile(root, 'matlab', 'mex') ;\nbld_dir = fullfile(mex_dir, '.build');\nif ~exist(fullfile(bld_dir,'bits','impl'), 'dir')\n mkdir(fullfile(bld_dir,'bits','impl')) ;\nend\n\n% Compiler flags\nflags.cc = {} ;\nflags.link = {} ;\nif opts.verbose > 1\n flags.cc{end+1} = '-v' ;\n flags.link{end+1} = '-v' ;\nend\nif opts.debug\n flags.cc{end+1} = '-g' ;\nelse\n flags.cc{end+1} = '-DNDEBUG' ;\nend\nif opts.enableGpu, flags.cc{end+1} = '-DENABLE_GPU' ; end\nif opts.enableCudnn,\n flags.cc{end+1} = '-DENABLE_CUDNN' ;\n flags.cc{end+1} = ['-I' opts.cudnnRoot] ;\nend\nflags.link{end+1} = '-lmwblas' ;\nswitch arch\n case {'maci64', 'glnxa64'}\n case {'win64'}\n % VisualC does not pass this even if available in the CPU architecture\n flags.cc{end+1} = '-D__SSSE3__' ;\nend\n\nif opts.enableImreadJpeg\n flags.cc = horzcat(flags.cc, opts.imageLibraryCompileFlags) ;\n flags.link = horzcat(flags.link, opts.imageLibraryLinkFlags) ;\nend\n\nif opts.enableGpu\n flags.link{end+1} = ['-L' opts.cudaLibDir] ;\n flags.link{end+1} = '-lcudart' ;\n flags.link{end+1} = '-lcublas' ;\n switch arch\n case {'maci64', 'glnxa64'}\n flags.link{end+1} = '-lmwgpu' ;\n case 'win64'\n flags.link{end+1} = '-lgpu' ;\n end\n if opts.enableCudnn\n flags.link{end+1} = ['-L' opts.cudnnRoot] ;\n flags.link{end+1} = '-lcudnn' ;\n end\nend\n\n% For the MEX command\nflags.link{end+1} = '-largeArrayDims' ;\nflags.mexcc = flags.cc ;\nflags.mexcc{end+1} = '-largeArrayDims' ;\nflags.mexcc{end+1} = '-cxx' ;\nif strcmp(arch, 'maci64')\n % CUDA prior to 7.0 on Mac require GCC libstdc++ instead of the native\n % Clang libc++. This should go away in the future.\n flags.mexcc{end+1} = 'CXXFLAGS=$CXXFLAGS -stdlib=libstdc++' ;\n flags.link{end+1} = 'LDFLAGS=$LDFLAGS -stdlib=libstdc++' ;\n if ~verLessThan('matlab', '8.5.0')\n % Complicating matters, MATLAB 8.5.0 links to Clang c++ by default\n % when linking MEX files overriding the option above. More force\n % is needed:\n flags.link{end+1} = 'LINKLIBS=$LINKLIBS -L\"$MATLABROOT/bin/maci64\" -lmx -lmex -lmat -lstdc++' ;\n end\nend\nif opts.enableGpu\n flags.mexcu = flags.cc ;\n flags.mexcu{end+1} = '-largeArrayDims' ;\n flags.mexcu{end+1} = '-cxx' ;\n flags.mexcu(end+1:end+2) = {'-f' mex_cuda_config(root)} ;\n flags.mexcu{end+1} = ['NVCCFLAGS=' opts.cudaArch '$NVCC_FLAGS'] ;\nend\n\n% For the cudaMethod='nvcc'\nif opts.enableGpu && strcmp(opts.cudaMethod,'nvcc')\n flags.nvcc = flags.cc ;\n flags.nvcc{end+1} = ['-I\"' fullfile(matlabroot, 'extern', 'include') '\"'] ;\n flags.nvcc{end+1} = ['-I\"' fullfile(matlabroot, 'toolbox','distcomp','gpu','extern','include') '\"'] ;\n if opts.debug\n flags.nvcc{end+1} = '-O0' ;\n end\n flags.nvcc{end+1} = '-Xcompiler' ;\n switch arch\n case {'maci64', 'glnxa64'}\n flags.nvcc{end+1} = '-fPIC' ;\n case 'win64'\n flags.nvcc{end+1} = '/MD' ;\n check_clpath(); % check whether cl.exe in path\n end\n flags.nvcc{end+1} = opts.cudaArch;\nend\n\nif opts.verbose\n fprintf('%s: * Compiler and linker configurations *\\n', mfilename) ;\n fprintf('%s: \\tintermediate build products directory: %s\\n', mfilename, bld_dir) ;\n fprintf('%s: \\tMEX files: %s/\\n', mfilename, mex_dir) ;\n fprintf('%s: \\tMEX compiler options: %s\\n', mfilename, strjoin(flags.mexcc)) ;\n fprintf('%s: \\tMEX linker options: %s\\n', mfilename, strjoin(flags.link)) ;\nend\nif opts.verbose & opts.enableGpu\n fprintf('%s: \\tMEX compiler options (CUDA): %s\\n', mfilename, strjoin(flags.mexcu)) ;\nend\nif opts.verbose & opts.enableGpu & strcmp(opts.cudaMethod,'nvcc')\n fprintf('%s: \\tNVCC compiler options: %s\\n', mfilename, strjoin(flags.nvcc)) ;\nend\nif opts.verbose & opts.enableImreadJpeg\n fprintf('%s: * Reading images *\\n', mfilename) ;\n fprintf('%s: \\tvl_imreadjpeg enabled\\n', mfilename) ;\n fprintf('%s: \\timage library: %s\\n', mfilename, opts.imageLibrary) ;\n fprintf('%s: \\timage library compile flags: %s\\n', mfilename, strjoin(opts.imageLibraryCompileFlags)) ;\n fprintf('%s: \\timage library link flags: %s\\n', mfilename, strjoin(opts.imageLibraryLinkFlags)) ;\nend\n\n% --------------------------------------------------------------------\n% Compile\n% --------------------------------------------------------------------\n\n% Intermediate object files\nsrcs = horzcat(lib_src,mex_src) ;\nparfor i = 1:numel(horzcat(lib_src, mex_src))\n [~,~,ext] = fileparts(srcs{i}) ; ext(1) = [] ;\n if strcmp(ext,'cu')\n if strcmp(opts.cudaMethod,'nvcc')\n nvcc_compile(opts, srcs{i}, toobj(bld_dir,srcs{i}), flags.nvcc) ;\n else\n mex_compile(opts, srcs{i}, toobj(bld_dir,srcs{i}), flags.mexcu) ;\n end\n else\n mex_compile(opts, srcs{i}, toobj(bld_dir,srcs{i}), flags.mexcc) ;\n end\nend\n\n% Link into MEX files\nparfor i = 1:numel(mex_src)\n [~,base,~] = fileparts(mex_src{i}) ;\n objs = toobj(bld_dir, {mex_src{i}, lib_src{:}}) ;\n mex_link(opts, objs, mex_dir, flags.link) ;\nend\n\n% Reset path adding the mex subdirectory just created\nvl_setupnn() ;\n\n% --------------------------------------------------------------------\n% Utility functions\n% --------------------------------------------------------------------\n\n% --------------------------------------------------------------------\nfunction objs = toobj(bld_dir,srcs)\n% --------------------------------------------------------------------\nstr = fullfile('matlab','src') ;\nmultiple = iscell(srcs) ;\nif ~multiple, srcs = {srcs} ; end\nfor t = 1:numel(srcs)\n i = strfind(srcs{t},str);\n objs{t} = fullfile(bld_dir, srcs{t}(i+numel(str):end)) ;\nend\nif ~multiple, objs = objs{1} ; end\nobjs = strrep(objs,'.cpp',['.' objext]) ;\nobjs = strrep(objs,'.cu',['.' objext]) ;\nobjs = strrep(objs,'.c',['.' objext]) ;\n\n% --------------------------------------------------------------------\nfunction objs = mex_compile(opts, src, tgt, mex_opts)\n% --------------------------------------------------------------------\nmopts = {'-outdir', fileparts(tgt), src, '-c', mex_opts{:}} ;\nopts.verbose && fprintf('%s: MEX CC: %s\\n', mfilename, strjoin(mopts)) ;\nmex(mopts{:}) ;\n\n% --------------------------------------------------------------------\nfunction obj = nvcc_compile(opts, src, tgt, nvcc_opts)\n% --------------------------------------------------------------------\nnvcc_path = fullfile(opts.cudaRoot, 'bin', 'nvcc');\nnvcc_cmd = sprintf('\"%s\" -c \"%s\" %s -o \"%s\"', ...\n nvcc_path, src, ...\n strjoin(nvcc_opts), tgt);\nopts.verbose && fprintf('%s: NVCC CC: %s\\n', mfilename, nvcc_cmd) ;\nstatus = system(nvcc_cmd);\nif status, error('Command %s failed.', nvcc_cmd); end;\n\n% --------------------------------------------------------------------\nfunction mex_link(opts, objs, mex_dir, mex_flags)\n% --------------------------------------------------------------------\nmopts = {'-outdir', mex_dir, mex_flags{:}, objs{:}} ;\nopts.verbose && fprintf('%s: MEX LINK: %s\\n', mfilename, strjoin(mopts)) ;\nmex(mopts{:}) ;\n\n% --------------------------------------------------------------------\nfunction ext = objext()\n% --------------------------------------------------------------------\n% Get the extension for an 'object' file for the current computer\n% architecture\nswitch computer('arch')\n case 'win64', ext = 'obj';\n case {'maci64', 'glnxa64'}, ext = 'o' ;\n otherwise, error('Unsupported architecture %s.', computer) ;\nend\n\n% --------------------------------------------------------------------\nfunction conf_file = mex_cuda_config(root)\n% --------------------------------------------------------------------\n% Get mex CUDA config file\nmver = [1e4 1e2 1] * sscanf(version, '%d.%d.%d') ;\nif mver <= 80200, ext = 'sh' ; else ext = 'xml' ; end\narch = computer('arch') ;\nswitch arch\n case {'win64'}\n config_dir = fullfile(matlabroot, 'toolbox', ...\n 'distcomp', 'gpu', 'extern', ...\n 'src', 'mex', arch) ;\n case {'maci64', 'glnxa64'}\n config_dir = fullfile(root, 'matlab', 'src', 'config') ;\nend\nconf_file = fullfile(config_dir, ['mex_CUDA_' arch '.' ext]);\nfprintf('%s:\\tCUDA: MEX config file: ''%s''\\n', mfilename, conf_file);\n\n% --------------------------------------------------------------------\nfunction check_clpath()\n% --------------------------------------------------------------------\n% Checks whether the cl.exe is in the path (needed for the nvcc). If\n% not, tries to guess the location out of mex configuration.\nstatus = system('cl.exe -help');\nif status == 1\n warning('CL.EXE not found in PATH. Trying to guess out of mex setup.');\n cc = mex.getCompilerConfigurations('c++');\n if isempty(cc)\n error('Mex is not configured. Run \"mex -setup\".');\n end\n prev_path = getenv('PATH');\n cl_path = fullfile(cc.Location, 'VC','bin','x86_amd64');\n setenv('PATH', [prev_path ';' cl_path]);\n status = system('cl.exe');\n if status == 1\n setenv('PATH', prev_path);\n error('Unable to find cl.exe');\n else\n fprintf('Location of cl.exe (%s) successfully added to your PATH.\\n', ...\n cl_path);\n end\nend\n\n% -------------------------------------------------------------------------\nfunction paths = which_nvcc(opts)\n% -------------------------------------------------------------------------\nswitch computer('arch')\n case 'win64'\n [~, paths] = system('where nvcc.exe');\n paths = strtrim(paths);\n paths = paths(strfind(paths, '.exe'));\n case {'maci64', 'glnxa64'}\n [~, paths] = system('which nvcc');\n paths = strtrim(paths) ;\nend\n\n% -------------------------------------------------------------------------\nfunction cuda_root = search_cuda_devkit(opts)\n% -------------------------------------------------------------------------\n% This function tries to to locate a working copy of the CUDA Devkit.\n\nopts.verbose && fprintf(['%s:\\tCUDA: seraching for the CUDA Devkit' ...\n ' (use the option ''CudaRoot'' to override):\\n'], mfilename);\n\n% Propose a number of candidate paths for NVCC\npaths = {getenv('MW_NVCC_PATH')} ;\npaths = [paths, which_nvcc(opts)] ;\nfor v = {'5.5', '6.0', '6.5', '7.0'}\n switch computer('arch')\n case 'glnxa64'\n paths{end+1} = sprintf('/usr/local/cuda-%s/bin/nvcc', char(v)) ;\n case 'maci64'\n paths{end+1} = sprintf('/Developer/NVIDIA/CUDA-%s/bin/nvcc', char(v)) ;\n case 'win64'\n paths{end+1} = sprintf('C:\\\\Program Files\\\\NVIDIA GPU Computing Toolkit\\\\CUDA\\\\v%s\\\\bin\\\\nvcc.exe', char(v)) ;\n end\nend\npaths{end+1} = sprintf('/usr/local/cuda/bin/nvcc') ;\n\n% Validate each candidate NVCC path\nfor i=1:numel(paths)\n nvcc(i).path = paths{i} ;\n [nvcc(i).isvalid, nvcc(i).version] = validate_nvcc(opts,paths{i}) ;\nend\nif opts.verbose\n fprintf('\\t| %5s | %5s | %-70s |\\n', 'valid', 'ver', 'NVCC path') ;\n for i=1:numel(paths)\n fprintf('\\t| %5d | %5d | %-70s |\\n', ...\n nvcc(i).isvalid, nvcc(i).version, nvcc(i).path) ;\n end\nend\n\n% Pick an entry\nindex = find([nvcc.isvalid]) ;\nif isempty(index)\n error('Could not find a valid NVCC executable\\n') ;\nend\nnvcc = nvcc(index(1)) ;\ncuda_root = fileparts(fileparts(nvcc.path)) ;\n\nif opts.verbose\n fprintf('%s:\\tCUDA: choosing NVCC compiler ''%s'' (version %d)\\n', ...\n mfilename, nvcc.path, nvcc.version) ;\nend\n\n% -------------------------------------------------------------------------\nfunction [valid, cuver] = validate_nvcc(opts, nvcc_path)\n% -------------------------------------------------------------------------\nvalid = false ;\ncuver = 0 ;\nif ~isempty(nvcc_path)\n [status, output] = system(sprintf('\"%s\" --version', nvcc_path)) ;\n valid = (status == 0) ;\nend\nif ~valid, return ; end\nmatch = regexp(output, 'V(\\d+\\.\\d+\\.\\d+)', 'match') ;\nif isempty(match), valid = false ; return ; end\ncuver = [1e4 1e2 1] * sscanf(match{1}, 'V%d.%d.%d') ;\n\n% --------------------------------------------------------------------\nfunction check_nvcc(cuda_root)\n% --------------------------------------------------------------------\n% Checks whether the nvcc is in the path. If not, guessed out of CudaRoot.\n[status, ~] = system('nvcc --help');\nif status ~= 0\n warning('nvcc not found in PATH. Trying to guess out of CudaRoot.');\n cuda_bin_path = fullfile(cuda_root, 'bin');\n prev_path = getenv('PATH');\n switch computer\n case 'PCWIN64', separator = ';';\n case {'GLNXA64', 'MACI64'}, separator = ':';\n end\n setenv('PATH', [prev_path separator cuda_bin_path]);\n [status, ~] = system('nvcc --help');\n if status ~= 0\n setenv('PATH', prev_path);\n error('Unable to find nvcc.');\n else\n fprintf('Location of nvcc (%s) added to your PATH.\\n', cuda_bin_path);\n end\nend\n\n% --------------------------------------------------------------------\nfunction cudaArch = get_cuda_arch(opts)\n% --------------------------------------------------------------------\nopts.verbose && fprintf('%s:\\tCUDA: determining GPU compute capability (use the ''CudaArch'' option to override)\\n', mfilename);\ntry\n gpu_device = gpuDevice();\n arch_code = strrep(gpu_device.ComputeCapability, '.', '');\n cudaArch = ...\n sprintf('-gencode=arch=compute_%s,code=\\\\\\\"sm_%s,compute_%s\\\\\\\" ', ...\n arch_code, arch_code, arch_code) ;\ncatch\n opts.verbose && fprintf(['%s:\\tCUDA: cannot determine the capabilities of the installed GPU;' ...\n 'falling back to default\\n'], mfilename);\n cudaArch = opts.defCudaArch;\nend\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_simplenn_display.m", "ext": ".m", "path": "2015_Face_Detection-master/matlab_12/simplenn/vl_simplenn_display.m", "size": 10451, "source_encoding": "utf_8", "md5": "0056ef92cb611577ba1907653e32dd21", "text": "function info = vl_simplenn_display(net, varargin)\n% VL_SIMPLENN_DISPLAY Simple CNN statistics\n% VL_SIMPLENN_DISPLAY(NET) prints statistics about the network NET.\n%\n% INFO=VL_SIMPLENN_DISPLAY(NET) returns instead a structure INFO\n% with several statistics for each layer of the network NET.\n%\n% The function accepts the following options:\n%\n% `inputSize`:: heuristically set\n% Specifies the size of the input tensor X that will be passed\n% to the network. This is used in order to estiamte the memory\n% required to process the network. If not specified,\n% VL_SIMPLENN_DISPLAY uses the value in\n% NET.NORMALIZATION.IMAGESIZE assuming a batch size of one\n% image, unless otherwise specified by the `batchSize` option.\n%\n% `batchSize`:: 1\n% Specifies the number of data points in a batch in estimating\n% the memory consumption (see `inputSize`).\n\n% Copyright (C) 2014-15 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.inputSize = [] ;\nopts.batchSize = 1 ;\nopts.maxNumColumns = 18 ;\nopts.format = 'ascii' ;\nopts = vl_argparse(opts, varargin) ;\n\nfields={'layer', 'type', 'name', '-', ...\n 'support', 'filtd', 'nfilt', 'stride', 'pad', '-', ...\n 'rfsize', 'rfoffset', 'rfstride', '-', ...\n 'dsize', 'ddepth', 'dnum', '-', ...\n 'xmem', 'wmem'};\n\n% get the support, stride, and padding of the operators\nfor l = 1:numel(net.layers)\n ly = net.layers{l} ;\n switch ly.type\n case 'conv'\n if isfield(ly, 'weights')\n info.support(1:2,l) = max([size(ly.weights{1},1) ; size(ly.weights{1},2)],1) ;\n else\n info.support(1:2,l) = max([size(ly.filters,1) ; size(ly.filters,2)],1) ;\n end\n case 'pool'\n info.support(1:2,l) = ly.pool(:) ;\n otherwise\n info.support(1:2,l) = [1;1] ;\n end\n if isfield(ly, 'stride')\n info.stride(1:2,l) = ly.stride(:) ;\n else\n info.stride(1:2,l) = 1 ;\n end\n if isfield(ly, 'pad')\n info.pad(1:4,l) = ly.pad(:) ;\n else\n info.pad(1:4,l) = 0 ;\n end\n\n % operator applied to the input image\n info.receptiveFieldSize(1:2,l) = 1 + ...\n sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...\n (info.support(1:2,1:l)-1),2) ;\n info.receptiveFieldOffset(1:2,l) = 1 + ...\n sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...\n ((info.support(1:2,1:l)-1)/2 - info.pad([1 3],1:l)),2) ;\n info.receptiveFieldStride = cumprod(info.stride,2) ;\nend\n\n\n% get the dimensions of the data\nif ~isempty(opts.inputSize) ;\n info.dataSize(1:4,1) = opts.inputSize(:) ;\nelseif isfield(net, 'normalization') && isfield(net.normalization, 'imageSize')\n info.dataSize(1:4,1) = [net.normalization.imageSize(:) ; opts.batchSize] ;\nelse\n info.dataSize(1:4,1) = [NaN NaN NaN opts.batchSize] ;\nend\nfor l = 1:numel(net.layers)\n ly = net.layers{l} ;\n if strcmp(ly.type, 'custom') && isfield(ly, 'getForwardSize')\n sz = ly.getForwardSize(ly, info.dataSize(:,l)) ;\n info.dataSize(:,l+1) = sz(:) ;\n continue ;\n end\n\n info.dataSize(1, l+1) = floor((info.dataSize(1,l) + ...\n sum(info.pad(1:2,l)) - ...\n info.support(1,l)) / info.stride(1,l)) + 1 ;\n info.dataSize(2, l+1) = floor((info.dataSize(2,l) + ...\n sum(info.pad(3:4,l)) - ...\n info.support(2,l)) / info.stride(2,l)) + 1 ;\n info.dataSize(3, l+1) = info.dataSize(3,l) ;\n info.dataSize(4, l+1) = info.dataSize(4,l) ;\n switch ly.type\n case 'conv'\n if isfield(ly, 'weights')\n f = ly.weights{1} ;\n else\n f = ly.filters ;\n end\n if size(f, 3) ~= 0\n info.dataSize(3, l+1) = size(f,4) ;\n end\n case {'loss', 'softmaxloss'}\n info.dataSize(3:4, l+1) = 1 ;\n case 'custom'\n info.dataSize(3,l+1) = NaN ;\n end\nend\n\nif nargout > 0, return ; end\n\n% print table\ntable = {} ;\nwmem = 0 ;\nxmem = 0 ;\nfor wi=1:numel(fields)\n w = fields{wi} ;\n switch w\n case 'type', s = 'type' ;\n case 'stride', s = 'stride' ;\n case 'rfsize', s = 'rf size' ;\n case 'rfstride', s = 'rf stride' ;\n case 'rfoffset', s = 'rf offset' ;\n case 'dsize', s = 'data size' ;\n case 'ddepth', s = 'data depth' ;\n case 'dnum', s = 'data num' ;\n case 'nfilt', s = 'num filts' ;\n case 'filtd', s = 'filt dim' ;\n case 'wmem', s = 'param mem' ;\n case 'xmem', s = 'data mem' ;\n otherwise, s = char(w) ;\n end\n table{wi,1} = s ;\n\n % do input pseudo-layer\n for l=0:numel(net.layers)\n switch char(w)\n case '-', s='-' ;\n case 'layer', s=sprintf('%d', l) ;\n case 'dsize', s=pdims(info.dataSize(1:2,l+1)) ;\n case 'ddepth', s=sprintf('%d', info.dataSize(3,l+1)) ;\n case 'dnum', s=sprintf('%d', info.dataSize(4,l+1)) ;\n case 'xmem'\n a = prod(info.dataSize(:,l+1)) * 4 ;\n s = pmem(a) ;\n xmem = xmem + a ;\n otherwise\n if l == 0\n if strcmp(char(w),'type'), s = 'input';\n else s = 'n/a' ; end\n else\n ly=net.layers{l} ;\n switch char(w)\n case 'name'\n if isfield(ly, 'name')\n s=ly.name(max(1,end-6):end) ;\n else\n s='' ;\n end\n case 'type'\n switch ly.type\n case 'normalize', s='norm';\n case 'pool'\n if strcmpi(ly.method,'avg'), s='apool'; else s='mpool'; end\n case 'softmax', s='softmx' ;\n case 'softmaxloss', s='softmxl' ;\n otherwise s=ly.type ;\n end\n case 'nfilt'\n switch ly.type\n case 'conv'\n if isfield(ly, 'weights'), a = size(ly.weights{1},4) ;\n else, a = size(ly.filters,4) ; end\n s=sprintf('%d',a) ;\n otherwise\n s='n/a' ;\n end\n case 'filtd'\n switch ly.type\n case 'conv'\n if isfield(ly, 'weights'), a = size(ly.weights{1},3) ;\n else, a = size(ly.filters,3) ; end\n s=sprintf('%d',a) ;\n otherwise\n s='n/a' ;\n end\n case 'support'\n s = pdims(info.support(:,l)) ;\n case 'stride'\n s = pdims(info.stride(:,l)) ;\n case 'pad'\n s = pdims(info.pad(:,l)) ;\n case 'rfsize'\n s = pdims(info.receptiveFieldSize(:,l)) ;\n case 'rfoffset'\n s = pdims(info.receptiveFieldOffset(:,l)) ;\n case 'rfstride'\n s = pdims(info.receptiveFieldStride(:,l)) ;\n\n case 'wmem'\n a = 0 ;\n if isfield(ly, 'weights') ;\n for j=1:numel(ly.weights)\n a = a + numel(ly.weights{j}) * 4 ;\n end\n end\n % Legacy code to be removed\n if isfield(ly, 'filters') ;\n a = a + numel(ly.filters) * 4 ;\n end\n if isfield(ly, 'biases') ;\n a = a + numel(ly.biases) * 4 ;\n end\n s = pmem(a) ;\n wmem = wmem + a ;\n end\n end\n end\n table{wi,l+2} = s ;\n end\nend\n\nfor i=2:opts.maxNumColumns:size(table,2)\n sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ;\n switch opts.format\n case 'ascii', pascii(table(:,[1 sel])) ; fprintf('\\n') ;\n case 'latex', platex(table(:,[1 sel])) ;\n end\nend\n\nfprintf('parameter memory: %s (%.2g parameters)\\n', pmem(wmem), wmem/4) ;\nfprintf('data memory: %s (for batch size %d)\\n', pmem(xmem), info.dataSize(4,1)) ;\n\n% -------------------------------------------------------------------------\nfunction s = pmem(x)\n% -------------------------------------------------------------------------\nif isnan(x), s = 'NaN' ;\nelseif x < 1024^1, s = sprintf('%.0fB', x) ;\nelseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ;\nelseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ;\nelse s = sprintf('%.0fGB', x / 1024^3) ;\nend\n\n% -------------------------------------------------------------------------\nfunction s = pdims(x)\n% -------------------------------------------------------------------------\nif all(x==x(1))\n s = sprintf('%.4g', x(1)) ;\nelse\n s = sprintf('%.4gx', x(:)) ;\n s(end) = [] ;\nend\n\n% -------------------------------------------------------------------------\nfunction pascii(table)\n% -------------------------------------------------------------------------\nsizes = max(cellfun(@(x) numel(x), table),[],1) ;\nfor i=1:size(table,1)\n for j=1:size(table,2)\n s = table{i,j} ;\n fmt = sprintf('%%%ds|', sizes(j)) ;\n if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end\n fprintf(fmt, s) ;\n end\n fprintf('\\n') ;\nend\n\n% -------------------------------------------------------------------------\nfunction platex(table)\n% -------------------------------------------------------------------------\nsizes = max(cellfun(@(x) numel(x), table),[],1) ;\nfprintf('\\\\begin{tabular}{%s}\\n', repmat('c', 1, numel(sizes))) ;\nfor i=1:size(table,1)\n if isequal(table{i,1},'-'), fprintf('\\\\hline\\n') ; continue ; end\n for j=1:size(table,2)\n s = table{i,j} ;\n fmt = sprintf('%%%ds', sizes(j)) ;\n fprintf(fmt, latexesc(s)) ;\n if j b.bytes) ;\nvl_testsim(res_(1).dzdx,res__(1).dzdx,1e-4) ;\nvl_testsim(res_(1).dzdw{1},res__(1).dzdw{1},1e-4) ;\nvl_testsim(res_(1).dzdw{2},res__(1).dzdw{2},1e-4) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_compile.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/vl_compile.m", "size": 5060, "source_encoding": "utf_8", "md5": "978f5189bb9b2a16db3368891f79aaa6", "text": "function vl_compile(compiler)\n% VL_COMPILE Compile VLFeat MEX files\n% VL_COMPILE() uses MEX() to compile VLFeat MEX files. This command\n% works only under Windows and is used to re-build problematic\n% binaries. The preferred method of compiling VLFeat on both UNIX\n% and Windows is through the provided Makefiles.\n%\n% VL_COMPILE() only compiles the MEX files and assumes that the\n% VLFeat DLL (i.e. the file VLFEATROOT/bin/win{32,64}/vl.dll) has\n% already been built. This file is built by the Makefiles.\n%\n% By default VL_COMPILE() assumes that Visual C++ is the active\n% MATLAB compiler. VL_COMPILE('lcc') assumes that the active\n% compiler is LCC instead (see MEX -SETUP). Unfortunately LCC does\n% not seem to be able to compile the latest versions of VLFeat due\n% to bugs in the support of 64-bit integers. Therefore it is\n% recommended to use Visual C++ instead.\n%\n% See also: VL_NOPREFIX(), VL_HELP().\n\n% Authors: Andrea Vedadli, Jonghyun Choi\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif nargin < 1, compiler = 'visualc' ; end\nswitch lower(compiler)\n case 'visualc'\n fprintf('%s: assuming that Visual C++ is the active compiler\\n', mfilename) ;\n useLcc = false ;\n case 'lcc'\n fprintf('%s: assuming that LCC is the active compiler\\n', mfilename) ;\n warning('LCC may fail to compile VLFeat. See help vl_compile.') ;\n useLcc = true ;\n otherwise\n error('Unknown compiler ''%s''.', compiler)\nend\n\nvlDir = vl_root ;\ntoolboxDir = fullfile(vlDir, 'toolbox') ;\n\nswitch computer\n case 'PCWIN'\n fprintf('%s: compiling for PCWIN (32 bit)\\n', mfilename);\n mexwDir = fullfile(toolboxDir, 'mex', 'mexw32') ;\n binwDir = fullfile(vlDir, 'bin', 'win32') ;\n case 'PCWIN64'\n fprintf('%s: compiling for PCWIN64 (64 bit)\\n', mfilename);\n mexwDir = fullfile(toolboxDir, 'mex', 'mexw64') ;\n binwDir = fullfile(vlDir, 'bin', 'win64') ;\n otherwise\n error('The architecture is neither PCWIN nor PCWIN64. See help vl_compile.') ;\nend\n\nimpLibPath = fullfile(binwDir, 'vl.lib') ;\nlibDir = fullfile(binwDir, 'vl.dll') ;\n\nmkd(mexwDir) ;\n\n% find the subdirectories of toolbox that we should process\nsubDirs = dir(toolboxDir) ;\nsubDirs = subDirs([subDirs.isdir]) ;\ndiscard = regexp({subDirs.name}, '^(.|..|noprefix|mex.*)$', 'start') ;\nkeep = cellfun('isempty', discard) ;\nsubDirs = subDirs(keep) ;\nsubDirs = {subDirs.name} ;\n\n% Copy support files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nif ~exist(fullfile(binwDir, 'vl.dll'))\n error('The VLFeat DLL (%s) could not be found. See help vl_compile.', ...\n fullfile(binwDir, 'vl.dll')) ;\nend\ntmp = dir(fullfile(binwDir, '*.dll')) ;\nsupportFileNames = {tmp.name} ;\nfor fi = 1:length(supportFileNames)\n name = supportFileNames{fi} ;\n cp(fullfile(binwDir, name), ...\n fullfile(mexwDir, name) ) ;\nend\n\n% Ensure implib for LCC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nif useLcc\n lccImpLibDir = fullfile(mexwDir, 'lcc') ;\n lccImpLibPath = fullfile(lccImpLibDir, 'VL.lib') ;\n lccRoot = fullfile(matlabroot, 'sys', 'lcc', 'bin') ;\n lccImpExePath = fullfile(lccRoot, 'lcc_implib.exe') ;\n\n mkd(lccImpLibDir) ;\n cp(fullfile(binwDir, 'vl.dll'), fullfile(lccImpLibDir, 'vl.dll')) ;\n\n cmd = ['\"' lccImpExePath '\"', ' -u ', '\"' fullfile(lccImpLibDir, 'vl.dll') '\"'] ;\n fprintf('Running:\\n> %s\\n', cmd) ;\n\n curPath = pwd ;\n try\n cd(lccImpLibDir) ;\n [d,w] = system(cmd) ;\n if d, error(w); end\n cd(curPath) ;\n catch\n cd(curPath) ;\n error(lasterr) ;\n end\nend\n\n% Compile each mex file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nfor i = 1:length(subDirs)\n thisDir = fullfile(toolboxDir, subDirs{i}) ;\n fileNames = ls(fullfile(thisDir, '*.c'));\n\n for f = 1:size(fileNames,1)\n fileName = fileNames(f, :) ;\n\n sp = strfind(fileName, ' ');\n if length(sp) > 0, fileName = fileName(1:sp-1); end\n\n filePath = fullfile(thisDir, fileName);\n fprintf('MEX %s\\n', filePath);\n\n dot = strfind(fileName, '.');\n mexFile = fullfile(mexwDir, [fileName(1:dot) 'dll']);\n if exist(mexFile)\n delete(mexFile)\n end\n\n cmd = {['-I' toolboxDir], ...\n ['-I' vlDir], ...\n '-O', ...\n '-outdir', mexwDir, ...\n filePath } ;\n\n if useLcc\n cmd{end+1} = lccImpLibPath ;\n else\n cmd{end+1} = impLibPath ;\n end\n mex(cmd{:}) ;\n end\nend\n\n% --------------------------------------------------------------------\nfunction cp(src,dst)\n% --------------------------------------------------------------------\nif ~exist(dst,'file')\n fprintf('Copying ''%s'' to ''%s''.\\n', src,dst) ;\n copyfile(src,dst) ;\nend\n\n% --------------------------------------------------------------------\nfunction mkd(dst)\n% --------------------------------------------------------------------\nif ~exist(dst, 'dir')\n fprintf('Creating directory ''%s''.', dst) ;\n mkdir(dst) ;\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_noprefix.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/vl_noprefix.m", "size": 1875, "source_encoding": "utf_8", "md5": "97d8755f0ba139ac1304bc423d3d86d3", "text": "function vl_noprefix\n% VL_NOPREFIX Create a prefix-less version of VLFeat commands\n% VL_NOPREFIX() creats prefix-less stubs for VLFeat functions\n% (e.g. SIFT for VL_SIFT). This function is seldom used as the stubs\n% are included in the VLFeat binary distribution anyways. Moreover,\n% on UNIX platforms, the stubs are generally constructed by the\n% Makefile.\n%\n% See also: VL_COMPILE(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nroot = fileparts(which(mfilename)) ;\nlist = listMFilesX(root);\noutDir = fullfile(root, 'noprefix') ;\n\nif ~exist(outDir, 'dir')\n mkdir(outDir) ;\nend\n\nfor li = 1:length(list)\n name = list(li).name(1:end-2) ; % remove .m\n nname = name(4:end) ; % remove vl_\n stubPath = fullfile(outDir, [nname '.m']) ;\n fout = fopen(stubPath, 'w') ;\n\n fprintf('Creating stub %s for %s\\n', stubPath, nname) ;\n\n fprintf(fout, 'function varargout = %s(varargin)\\n', nname) ;\n fprintf(fout, '%% %s Stub for %s\\n', upper(nname), upper(name)) ;\n fprintf(fout, '[varargout{1:nargout}] = %s(varargin{:})\\n', name) ;\n\n fclose(fout) ;\nend\n\nend\n\nfunction list = listMFilesX(root)\nlist = struct('name', {}, 'path', {}) ;\nfiles = dir(root) ;\nfor fi = 1:length(files)\n name = files(fi).name ;\n if files(fi).isdir\n if any(regexp(name, '^(\\.|\\.\\.|noprefix)$'))\n continue ;\n else\n tmp = listMFilesX(fullfile(root, name)) ;\n list = [list, tmp] ;\n end\n end\n if any(regexp(name, '^vl_(demo|test).*m$'))\n continue ;\n elseif any(regexp(name, '^vl_(demo|setup|compile|help|root|noprefix)\\.m$'))\n continue ;\n elseif any(regexp(name, '\\.m$'))\n list(end+1) = struct(...\n 'name', {name}, ...\n 'path', {fullfile(root, name)}) ;\n end\nend\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_pegasos.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/misc/vl_pegasos.m", "size": 2837, "source_encoding": "utf_8", "md5": "d5e0915c439ece94eb5597a07090b67d", "text": "% VL_PEGASOS [deprecated]\n% VL_PEGASOS is deprecated. Please use VL_SVMTRAIN() instead.\n\nfunction [w b info] = vl_pegasos(X,Y,LAMBDA, varargin)\n\n% Verbose not supported\nif (sum(strcmpi('Verbose',varargin)))\n varargin(find(strcmpi('Verbose',varargin),1))=[];\n fprintf('Option VERBOSE is no longer supported.\\n');\nend\n\n% DiagnosticCallRef not supported\nif (sum(strcmpi('DiagnosticCallRef',varargin)))\n varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[];\n varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[];\n fprintf('Option DIAGNOSTICCALLREF is no longer supported.\\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\\n');\nend\n\n% different default value for MaxIterations\nif (sum(strcmpi('MaxIterations',varargin)) == 0)\n varargin{end+1} = 'MaxIterations';\n varargin{end+1} = ceil(10/LAMBDA);\nend\n\n% different default value for BiasMultiplier\nif (sum(strcmpi('BiasMultiplier',varargin)) == 0)\n varargin{end+1} = 'BiasMultiplier';\n varargin{end+1} = 0;\nend\n\n% parameters for vl_maketrainingset\nsetvarargin = {};\nif (sum(strcmpi('HOMKERMAP',varargin)))\n setvarargin{end+1} = 'HOMKERMAP';\n setvarargin{end+1} = varargin{find(strcmpi('HOMKERMAP',varargin),1)+1};\n varargin(find(strcmpi('HOMKERMAP',varargin),1)+1)=[];\n varargin(find(strcmpi('HOMKERMAP',varargin),1))=[];\nend\nif (sum(strcmpi('KChi2',varargin)))\n setvarargin{end+1} = 'KChi2';\n varargin(find(strcmpi('KChi2',varargin),1))=[];\nend\nif (sum(strcmpi('KINTERS',varargin)))\n setvarargin{end+1} = 'KINTERS';\n varargin(find(strcmpi('KINTERS',varargin),1))=[];\nend\nif (sum(strcmpi('KL1',varargin)))\n setvarargin{end+1} = 'KL1';\n varargin(find(strcmpi('KL1',varargin),1))=[];\nend\nif (sum(strcmpi('KJS',varargin)))\n setvarargin{end+1} = 'KJS';\n varargin(find(strcmpi('KJS',varargin),1))=[];\nend\nif (sum(strcmpi('Period',varargin)))\n setvarargin{end+1} = 'Period';\n setvarargin{end+1} = varargin{find(strcmpi('Period',varargin),1)+1};\n varargin(find(strcmpi('Period',varargin),1)+1)=[];\n varargin(find(strcmpi('Period',varargin),1))=[];\nend\nif (sum(strcmpi('Window',varargin)))\n setvarargin{end+1} = 'Window';\n setvarargin{end+1} = varargin{find(strcmpi('Window',varargin),1)+1};\n varargin(find(strcmpi('Window',varargin),1)+1)=[];\n varargin(find(strcmpi('Window',varargin),1))=[];\nend\nif (sum(strcmpi('Gamma',varargin)))\n setvarargin{end+1} = 'Gamma';\n setvarargin{end+1} = varargin{find(strcmpi('Gamma',varargin),1)+1};\n varargin(find(strcmpi('Gamma',varargin),1)+1)=[];\n varargin(find(strcmpi('Gamma',varargin),1))=[];\nend\n\nsetvarargin{:}\n\nDATA = vl_maketrainingset(double(X),int8(Y),setvarargin{:});\nDATA\n[w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:});\n\n\nfprintf('\\n vl_pegasos is DEPRECATED. Please use vl_svmtrain instead. \\n\\n');\n\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_svmpegasos.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/misc/vl_svmpegasos.m", "size": 1178, "source_encoding": "utf_8", "md5": "009c2a2b87a375d529ed1a4dbe3af59f", "text": "% VL_SVMPEGASOS [deprecated]\n% VL_SVMPEGASOS is deprecated. Please use VL_SVMTRAIN() instead.\n\n\n\nfunction [w b info] = vl_svmpegasos(DATA,LAMBDA, varargin)\n\n% Verbose not supported\nif (sum(strcmpi('Verbose',varargin)))\n varargin(find(strcmpi('Verbose',varargin),1))=[];\n fprintf('Option VERBOSE is no longer supported.\\n');\nend\n\n% DiagnosticCallRef not supported\nif (sum(strcmpi('DiagnosticCallRef',varargin)))\n varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[];\n varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[];\n fprintf('Option DIAGNOSTICCALLREF is no longer supported.\\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\\n');\nend\n\n% different default value for MaxIterations\nif (sum(strcmpi('MaxIterations',varargin)) == 0)\n varargin{end+1} = 'MaxIterations';\n varargin{end+1} = ceil(10/LAMBDA);\nend\n\n% different default value for BiasMultiplier\nif (sum(strcmpi('BiasMultiplier',varargin)) == 0)\n varargin{end+1} = 'BiasMultiplier';\n varargin{end+1} = 0;\nend\n\n[w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:});\n\nfprintf('\\n vl_svmpegasos is DEPRECATED. Please use vl_svmtrain instead. \\n\\n');\n\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_override.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/misc/vl_override.m", "size": 4654, "source_encoding": "utf_8", "md5": "e233d2ecaeb68f56034a976060c594c5", "text": "function config = vl_override(config,update,varargin)\n% VL_OVERRIDE Override structure subset\n% CONFIG = VL_OVERRIDE(CONFIG, UPDATE) copies recursively the fileds\n% of the structure UPDATE to the corresponding fields of the\n% struture CONFIG.\n%\n% Usually CONFIG is interpreted as a list of paramters with their\n% default values and UPDATE as a list of new paramete values.\n%\n% VL_OVERRIDE(..., 'Warn') prints a warning message whenever: (i)\n% UPDATE has a field not found in CONFIG, or (ii) non-leaf values of\n% CONFIG are overwritten.\n%\n% VL_OVERRIDE(..., 'Skip') skips fields of UPDATE that are not found\n% in CONFIG instead of copying them.\n%\n% VL_OVERRIDE(..., 'CaseI') matches field names in a\n% case-insensitive manner.\n%\n% Remark::\n% Fields are copied at the deepest possible level. For instance,\n% if CONFIG has fields A.B.C1=1 and A.B.C2=2, and if UPDATE is the\n% structure A.B.C1=3, then VL_OVERRIDE() returns a strucuture with\n% fields A.B.C1=3, A.B.C2=2. By contrast, if UPDATE is the\n% structure A.B=4, then the field A.B is copied, and VL_OVERRIDE()\n% returns the structure A.B=4 (specifying 'Warn' would warn about\n% the fact that the substructure B.C1, B.C2 is being deleted).\n%\n% Remark::\n% Two fields are matched if they correspond exactly. Specifically,\n% two fileds A(IA).(FA) and B(IA).FB of two struct arrays A and B\n% match if, and only if, (i) A and B have the same dimensions,\n% (ii) IA == IB, and (iii) FA == FB.\n%\n% See also: VL_ARGPARSE(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nwarn = false ;\nskip = false ;\nerr = false ;\ncasei = false ;\n\nif length(varargin) == 1 & ~ischar(varargin{1})\n % legacy\n warn = 1 ;\nend\n\nif ~warn & length(varargin) > 0\n for i=1:length(varargin)\n switch lower(varargin{i})\n case 'warn'\n warn = true ;\n case 'skip'\n skip = true ;\n case 'err'\n err = true ;\n case 'argparse'\n argparse = true ;\n case 'casei'\n casei = true ;\n otherwise\n error(sprintf('Unknown option ''%s''.',varargin{i})) ;\n end\n end\nend\n\n% if CONFIG is not a struct array just copy UPDATE verbatim\nif ~isstruct(config)\n config = update ;\n return ;\nend\n\n% if CONFIG is a struct array but UPDATE is not, no match can be\n% established and we simply copy UPDATE verbatim\nif ~isstruct(update)\n config = update ;\n return ;\nend\n\n% if CONFIG and UPDATE are both struct arrays, but have different\n% dimensions then nom atch can be established and we simply copy\n% UPDATE verbatim\nif numel(update) ~= numel(config)\n config = update ;\n return ;\nend\n\n% if CONFIG and UPDATE are both struct arrays of the same\n% dimension, we override recursively each field\n\nfor idx=1:numel(update)\n fields = fieldnames(update) ;\n\n for i = 1:length(fields)\n updateFieldName = fields{i} ;\n if casei\n configFieldName = findFieldI(config, updateFieldName) ;\n else\n configFieldName = findField(config, updateFieldName) ;\n end\n\n if ~isempty(configFieldName)\n config(idx).(configFieldName) = ...\n vl_override(config(idx).(configFieldName), ...\n update(idx).(updateFieldName)) ;\n else\n if warn\n warning(sprintf('copied field ''%s'' which is in UPDATE but not in CONFIG', ...\n updateFieldName)) ;\n end\n if err\n error(sprintf('The field ''%s'' is in UPDATE but not in CONFIG', ...\n updateFieldName)) ;\n end\n if skip\n if warn\n warning(sprintf('skipping field ''%s'' which is in UPDATE but not in CONFIG', ...\n updateFieldName)) ;\n end\n continue ;\n end\n config(idx).(updateFieldName) = update(idx).(updateFieldName) ;\n end\n end\nend\n\n% --------------------------------------------------------------------\nfunction field = findFieldI(S, matchField)\n% --------------------------------------------------------------------\nfield = '' ;\nfieldNames = fieldnames(S) ;\nfor fi=1:length(fieldNames)\n if strcmpi(fieldNames{fi}, matchField)\n field = fieldNames{fi} ;\n end\nend\n\n% --------------------------------------------------------------------\nfunction field = findField(S, matchField)\n% --------------------------------------------------------------------\n\nfield = '' ;\nfieldNames = fieldnames(S) ;\nfor fi=1:length(fieldNames)\n if strcmp(fieldNames{fi}, matchField)\n field = fieldNames{fi} ;\n end\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_quickvis.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/quickshift/vl_quickvis.m", "size": 3696, "source_encoding": "utf_8", "md5": "27f199dad4c5b9c192a5dd3abc59f9da", "text": "function [Iedge dists map gaps] = vl_quickvis(I, ratio, kernelsize, maxdist, maxcuts)\n% VL_QUICKVIS Create an edge image from a Quickshift segmentation.\n% IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) creates an edge\n% stability image from a Quickshift segmentation. RATIO controls the tradeoff\n% between color consistency and spatial consistency (See VL_QUICKSEG) and\n% KERNELSIZE controls the bandwidth of the density estimator (See VL_QUICKSEG,\n% VL_QUICKSHIFT). MAXDIST is the maximum distance between neighbors which\n% increase the density.\n%\n% VL_QUICKVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at\n% most MAXCUTS segmentations. The edges between regions in each of these\n% segmentations are labeled in IEDGE, where the label corresponds to the\n% largest DIST which preserves the edge.\n%\n% [IEDGE,DISTS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) also\n% returns the DIST thresholds that were chosen.\n%\n% IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, DISTS) will use the DISTS\n% specified\n%\n% [IEDGE,DISTS,MAP,GAPS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS)\n% also returns the MAP and GAPS from VL_QUICKSHIFT.\n%\n% See Also: VL_QUICKSHIFT(), VL_QUICKSEG(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif nargin == 4\n dists = maxdist;\n maxdist = max(dists);\n [Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist);\nelse\n [Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist);\n dists = unique(floor(gaps(:)));\n dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh\n if length(dists) > maxcuts\n ind = round(linspace(1,length(dists), maxcuts));\n dists = dists(ind);\n end\nend\n\n[Iedge dists] = mapvis(map, gaps, dists);\n\nfunction [Iedge dists] = mapvis(map, gaps, maxdist, maxcuts)\n% MAPVIS Create an edge image from a Quickshift segmentation.\n% IEDGE = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) creates an edge\n% stability image from a Quickshift segmentation. MAXDIST is the maximum\n% distance between neighbors which increase the density.\n%\n% MAPVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at most\n% MAXCUTS segmentations. The edges between regions in each of these\n% segmentations are labeled in IEDGE, where the label corresponds to the\n% largest DIST which preserves the edge.\n%\n% [IEDGE,DISTS] = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) also returns the DIST\n% thresholds that were chosen.\n%\n% IEDGE = MAPVIS(MAP, GAPS, DISTS) will use the DISTS specified\n%\n% See Also: VL_QUICKVIS, VL_QUICKSHIFT, VL_QUICKSEG\n\nif nargin == 3\n dists = maxdist;\n maxdist = max(dists);\nelse\n dists = unique(floor(gaps(:)));\n dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh\n % throw away min region size instead of maxdist?\n ind = find(dists < maxdist);\n dists = dists(ind);\n if length(dists) > maxcuts\n ind = round(linspace(1,length(dists), maxcuts));\n dists = dists(ind);\n end\nend\n\n\nIedge = zeros(size(map));\n\nfor i = 1:length(dists)\n s = find(gaps >= dists(i));\n mapdist = map;\n mapdist(s) = s;\n [mapped labels] = vl_flatmap(mapdist);\n fprintf('%d/%d %d regions\\n', i, length(dists), length(unique(mapped)))\n\n borders = getborders(mapped);\n\n Iedge(borders) = dists(i);\n %Iedge(borders) = Iedge(borders) + 1;\n %Iedge(borders) = i;\nend\n\n%%%%%%%%% GETBORDERS\nfunction borders = getborders(map)\n\ndx = conv2(map, [-1 1], 'same');\ndy = conv2(map, [-1 1]', 'same');\nborders = find(dx ~= 0 | dy ~= 0);\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_demo_aib.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/demo/vl_demo_aib.m", "size": 2928, "source_encoding": "utf_8", "md5": "590c6db09451ea608d87bfd094662cac", "text": "function vl_demo_aib\n% VL_DEMO_AIB Test Agglomerative Information Bottleneck (AIB)\n\nD = 4 ;\nK = 20 ;\n\nrandn('state',0) ;\nrand('state',0) ;\n\nX1 = randn(2,300) ; X1(1,:) = X1(1,:) + 2 ;\nX2 = randn(2,300) ; X2(1,:) = X2(1,:) - 2 ;\nX3 = randn(2,300) ; X3(2,:) = X3(2,:) + 2 ;\n\nfigure(1) ; clf ; hold on ;\nvl_plotframe(X1,'color','r') ;\nvl_plotframe(X2,'color','g') ;\nvl_plotframe(X3,'color','b') ;\naxis equal ;\nxlim([-4 4]);\nylim([-4 4]);\naxis off ;\nrectangle('position',D*[-1 -1 2 2])\n\nvl_demo_print('aib_basic_data', .6) ;\n\nC = 1:K*K ;\nPcx = zeros(3,K*K) ;\n\nf1 = quantize(X1,D,K) ;\nf2 = quantize(X2,D,K) ;\nf3 = quantize(X3,D,K) ;\n\nPcx(1,:) = vl_binsum(Pcx(1,:), ones(size(f1)), f1) ;\nPcx(2,:) = vl_binsum(Pcx(2,:), ones(size(f2)), f2) ;\nPcx(3,:) = vl_binsum(Pcx(3,:), ones(size(f3)), f3) ;\n\nPcx = Pcx / sum(Pcx(:)) ;\n\n[parents, cost] = vl_aib(Pcx) ;\n\ncutsize = [K*K, 10, 3, 2, 1] ;\nfor i=1:length(cutsize)\n\n [cut,map,short] = vl_aibcut(parents, cutsize(i)) ;\n parents_cut(short > 0) = parents(short(short > 0)) ;\n C = short(1:K*K+1) ; [drop1,drop2,C] = unique(C) ;\n\n figure(i+1) ; clf ;\n plotquantization(D,K,C) ; hold on ;\n %plottree(D,K,parents_cut) ;\n axis equal ;\n axis off ;\n title(sprintf('%d clusters', cutsize(i))) ;\n\n vl_demo_print(sprintf('aib_basic_clust_%d',i),.6) ;\nend\n\n% --------------------------------------------------------------------\nfunction f = quantize(X,D,K)\n% --------------------------------------------------------------------\nd = 2*D / K ;\nj = round((X(1,:) + D) / d) ;\ni = round((X(2,:) + D) / d) ;\nj = max(min(j,K),1) ;\ni = max(min(i,K),1) ;\nf = sub2ind([K K],i,j) ;\n\n% --------------------------------------------------------------------\nfunction [i,j] = plotquantization(D,K,C)\n% --------------------------------------------------------------------\nhold on ;\ncl = [[.3 .3 .3] ; .5*hsv(max(C)-1)+.5] ;\nd = 2*D / K ;\nfor i=0:K-1\n for j=0:K-1\n patch(d*(j+[0 1 1 0])-D, ...\n d*(i+[0 0 1 1])-D, ...\n cl(C(j*K+i+1),:)) ;\n end\nend\n% --------------------------------------------------------------------\nfunction h = plottree(D,K,parents)\n% --------------------------------------------------------------------\n\nd = 2*D / K ;\nC = zeros(2,2*K*K-1)+NaN ;\nN = zeros(1,2*K*K-1) ;\n\nfor i=0:K-1\n for j=0:K-1\n C(:,j*K+i+1) = [d*j-D; d*i-D]+d/2 ;\n N(:,j*K+i+1) = 1 ;\n end\nend\n\nfor i=1:length(parents)\n p = parents(i) ;\n if p==0, continue ; end;\n if all(isnan(C(:,i))), continue; end\n if all(isnan(C(:,p)))\n C(:,p) = C(:,i) / N(i) ;\n else\n C(:,p) = C(:,p) + C(:,i) / N(i) ;\n end\n N(p) = N(p) + 1 ;\nend\n\nC(1,:) = C(1,:) ./ N ;\nC(2,:) = C(2,:) ./ N ;\n\nxt = zeros(3, 2*length(parents)-1)+NaN ;\nyt = zeros(3, 2*length(parents)-1)+NaN ;\n\nfor i=1:length(parents)\n p = parents(i) ;\n if p==0, continue ; end;\n xt(1,i) = C(1,i) ; xt(2,i) = C(1,p) ;\n yt(1,i) = C(2,i) ; yt(2,i) = C(2,p) ;\nend\n\nh=line(xt(:),yt(:),'linestyle','-','marker','.','linewidth',3) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_demo_alldist.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/demo/vl_demo_alldist.m", "size": 5460, "source_encoding": "utf_8", "md5": "6d008a64d93445b9d7199b55d58db7eb", "text": "function vl_demo_alldist\n%\n\nnumRepetitions = 3 ;\nnumDimensions = 1000 ;\nnumSamplesRange = [300] ;\n\nsettingsRange = {{'alldist2', 'double', 'l2', }, ...\n {'alldist', 'double', 'l2', 'nosimd'}, ...\n {'alldist', 'double', 'l2' }, ...\n {'alldist2', 'single', 'l2', }, ...\n {'alldist', 'single', 'l2', 'nosimd'}, ...\n {'alldist', 'single', 'l2' }, ...\n {'alldist2', 'double', 'l1', }, ...\n {'alldist', 'double', 'l1', 'nosimd'}, ...\n {'alldist', 'double', 'l1' }, ...\n {'alldist2', 'single', 'l1', }, ...\n {'alldist', 'single', 'l1', 'nosimd'}, ...\n {'alldist', 'single', 'l1' }, ...\n {'alldist2', 'double', 'chi2', }, ...\n {'alldist', 'double', 'chi2', 'nosimd'}, ...\n {'alldist', 'double', 'chi2' }, ...\n {'alldist2', 'single', 'chi2', }, ...\n {'alldist', 'single', 'chi2', 'nosimd'}, ...\n {'alldist', 'single', 'chi2' }, ...\n {'alldist2', 'double', 'hell', }, ...\n {'alldist', 'double', 'hell', 'nosimd'}, ...\n {'alldist', 'double', 'hell' }, ...\n {'alldist2', 'single', 'hell', }, ...\n {'alldist', 'single', 'hell', 'nosimd'}, ...\n {'alldist', 'single', 'hell' }, ...\n {'alldist2', 'double', 'kl2', }, ...\n {'alldist', 'double', 'kl2', 'nosimd'}, ...\n {'alldist', 'double', 'kl2' }, ...\n {'alldist2', 'single', 'kl2', }, ...\n {'alldist', 'single', 'kl2', 'nosimd'}, ...\n {'alldist', 'single', 'kl2' }, ...\n {'alldist2', 'double', 'kl1', }, ...\n {'alldist', 'double', 'kl1', 'nosimd'}, ...\n {'alldist', 'double', 'kl1' }, ...\n {'alldist2', 'single', 'kl1', }, ...\n {'alldist', 'single', 'kl1', 'nosimd'}, ...\n {'alldist', 'single', 'kl1' }, ...\n {'alldist2', 'double', 'kchi2', }, ...\n {'alldist', 'double', 'kchi2', 'nosimd'}, ...\n {'alldist', 'double', 'kchi2' }, ...\n {'alldist2', 'single', 'kchi2', }, ...\n {'alldist', 'single', 'kchi2', 'nosimd'}, ...\n {'alldist', 'single', 'kchi2' }, ...\n {'alldist2', 'double', 'khell', }, ...\n {'alldist', 'double', 'khell', 'nosimd'}, ...\n {'alldist', 'double', 'khell' }, ...\n {'alldist2', 'single', 'khell', }, ...\n {'alldist', 'single', 'khell', 'nosimd'}, ...\n {'alldist', 'single', 'khell' }, ...\n } ;\n\n%settingsRange = settingsRange(end-5:end) ;\n\nstyles = {} ;\nfor marker={'x','+','.','*','o'}\n for color={'r','g','b','k','y'}\n styles{end+1} = {'color', char(color), 'marker', char(marker)} ;\n end\nend\n\nfor ni=1:length(numSamplesRange)\n for ti=1:length(settingsRange)\n tocs = [] ;\n for ri=1:numRepetitions\n rand('state',ri) ;\n randn('state',ri) ;\n numSamples = numSamplesRange(ni) ;\n settings = settingsRange{ti} ;\n [tocs(end+1), D] = run_experiment(numDimensions, ...\n numSamples, ...\n settings) ;\n end\n means(ni,ti) = mean(tocs) ;\n stds(ni,ti) = std(tocs) ;\n if mod(ti-1,3) == 0\n D0 = D ;\n else\n err = max(abs(D(:)-D0(:))) ;\n fprintf('err %f\\n', err) ;\n if err > 1, keyboard ; end\n end\n end\nend\n\nif 0\n figure(1) ; clf ; hold on ;\n numStyles = length(styles) ;\n for ti=1:length(settingsRange)\n si = mod(ti - 1, numStyles) + 1 ;\n h(ti) = plot(numSamplesRange, means(:,ti), styles{si}{:}) ;\n leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ;\n errorbar(numSamplesRange, means(:,ti), stds(:,ti), 'linestyle', 'none') ;\n end\nend\n\nfor ti=1:length(settingsRange)\n leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ;\nend\n\nfigure(1) ; clf ;\nbarh(means(end,:)) ;\nset(gca,'ytick', 1:length(leg), 'yticklabel', leg,'ydir','reverse') ;\nxlabel('Time [s]') ;\n\nfunction [elaps, D] = run_experiment(numDimensions, numSamples, settings)\n\ndistType = 'l2' ;\nalgType = 'alldist' ;\nclassType = 'double' ;\nuseSimd = true ;\n\nfor si=1:length(settings)\n arg = settings{si} ;\n switch arg\n case {'l1', 'l2', 'chi2', 'hell', 'kl2', 'kl1', 'kchi2', 'khell'}\n distType = arg ;\n case {'alldist', 'alldist2'}\n algType = arg ;\n case {'single', 'double'}\n classType = arg ;\n case 'simd'\n useSimd = true ;\n case 'nosimd'\n useSimd = false ;\n otherwise\n assert(false) ;\n end\nend\n\nX = rand(numDimensions, numSamples) ;\nX(X < .3) = 0 ;\n\nswitch classType\n case 'double'\n case 'single'\n X = single(X) ;\nend\n\nvl_simdctrl(double(useSimd)) ;\n\nswitch algType\n case 'alldist'\n tic ; D = vl_alldist(X, distType) ; elaps = toc ;\n case 'alldist2'\n tic ; D = vl_alldist2(X, distType) ; elaps = toc ;\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_demo_ikmeans.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/demo/vl_demo_ikmeans.m", "size": 774, "source_encoding": "utf_8", "md5": "17ff0bb7259d390fb4f91ea937ba7de0", "text": "function vl_demo_ikmeans()\n% VL_DEMO_IKMEANS\n\nnumData = 10000 ;\ndimension = 2 ;\ndata = uint8(255*rand(dimension,numData)) ;\nnumClusters = 3^3 ;\n\n[centers, assignments] = vl_ikmeans(data, numClusters);\n\nfigure(1) ; clf ; axis off ;\nplotClusters(data, centers, assignments) ;\nvl_demo_print('ikmeans_2d',0.6);\n\n[tree, assignments] = vl_hikmeans(data,3,numClusters) ;\nfigure(2) ; clf ; axis off ;\nplotClusters(data, [], [4 2 1] * double(assignments)) ;\nvl_demo_print('hikmeans_2d',0.6);\n\nfunction plotClusters(data, centers, assignments)\nhold on ;\ncc=jet(double(max(assignments(:))));\nfor i=1:max(assignments(:))\n plot(data(1,assignments == i),data(2,assignments == i),'.','color',cc(i,:));\nend\nif ~isempty(centers)\n plot(centers(1,:),centers(2,:),'k.','MarkerSize',20)\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_demo_svm.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/demo/vl_demo_svm.m", "size": 1235, "source_encoding": "utf_8", "md5": "7cf6b3504e4fc2cbd10ff3fec6e331a7", "text": "% VL_DEMO_SVM Demo: SVM: 2D linear learning\nfunction vl_demo_svm\ny=[];X=[];\n\n% Load training data X and their labels y\nload('vl_demo_svm_data.mat')\n\n\nXp = X(:,y==1);\nXn = X(:,y==-1);\n\nfigure\nplot(Xn(1,:),Xn(2,:),'*r')\nhold on\nplot(Xp(1,:),Xp(2,:),'*b')\naxis equal ;\nvl_demo_print('svm_training') ;\n% Parameters\nlambda = 0.01 ; % Regularization parameter\nmaxIter = 1000 ; % Maximum number of iterations\n\nenergy = [] ;\n% Diagnostic function\nfunction diagnostics(svm)\n energy = [energy [svm.objective ; svm.dualObjective ; svm.dualityGap ] ] ;\nend\n\n% Training the SVM\nenergy = [] ;\n[w b info] = vl_svmtrain(X, y, lambda,...\n 'MaxNumIterations',maxIter,...\n 'DiagnosticFunction',@diagnostics,...\n 'DiagnosticFrequency',1)\n\n% Visualisation\neq = [num2str(w(1)) '*x+' num2str(w(2)) '*y+' num2str(b)];\n\nline = ezplot(eq, [-0.9 0.9 -0.9 0.9]);\nset(line, 'Color', [0 0.8 0],'linewidth', 2);\n\nvl_demo_print('svm_training_result') ;\n\n\nfigure\nhold on\nplot(energy(1,:),'--b') ;\nplot(energy(2,:),'-.g') ;\nplot(energy(3,:),'r') ;\nlegend('Primal objective','Dual objective','Duality gap')\nxlabel('Diagnostics iteration')\nylabel('Energy')\nvl_demo_print('svm_energy') ;\n\nend"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_demo_kdtree_sift.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/demo/vl_demo_kdtree_sift.m", "size": 6832, "source_encoding": "utf_8", "md5": "e676f80ac330a351f0110533c6ebba89", "text": "function vl_demo_kdtree_sift\n% VL_DEMO_KDTREE_SIFT\n% Demonstrates the use of a kd-tree forest to match SIFT\n% features. If FLANN is present, this function runs a comparison\n% against it.\n\n% AUTORIGHS\n\nrand('state',0) ;\nrandn('state',0);\n\ndo_median = 0 ;\ndo_mean = 1 ;\n\n% try to setup flann\nif ~exist('flann_search', 'file')\n if exist(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab'))\n addpath(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) ;\n end\nend\ndo_flann = exist('nearest_neighbors') == 3 ;\nif ~do_flann\n warning('FLANN not found. Comparison disabled.') ;\nend\n\nmaxNumComparisonsRange = [1 10 50 100 200 300 400] ;\nnumTreesRange = [1 2 5 10] ;\n\n% get data (SIFT features)\nim1 = imread(fullfile(vl_root, 'data', 'roofs1.jpg')) ;\nim2 = imread(fullfile(vl_root, 'data', 'roofs2.jpg')) ;\nim1 = single(rgb2gray(im1)) ;\nim2 = single(rgb2gray(im2)) ;\n[f1,d1] = vl_sift(im1,'firstoctave',-1,'floatdescriptors','verbose') ;\n[f2,d2] = vl_sift(im2,'firstoctave',-1,'floatdescriptors','verbose') ;\n\n% add some noise to make matches unique\nd1 = single(d1) + rand(size(d1)) ;\nd2 = single(d2) + rand(size(d2)) ;\n\n% match exhaustively to get the ground truth\nelapsedDirect = tic ;\nD = vl_alldist(d1,d2) ;\n[drop, best] = min(D, [], 1) ;\nelapsedDirect = toc(elapsedDirect) ;\n\nfor ti=1:length(numTreesRange)\n for vi=1:length(maxNumComparisonsRange)\n v = maxNumComparisonsRange(vi) ;\n t = numTreesRange(ti) ;\n\n if do_median\n tic ;\n kdtree = vl_kdtreebuild(d1, ...\n 'verbose', ...\n 'thresholdmethod', 'median', ...\n 'numtrees', t) ;\n [i, d] = vl_kdtreequery(kdtree, d1, d2, ...\n 'verbose', ...\n 'maxcomparisons',v) ;\n elapsedKD_median(vi,ti) = toc ;\n errors_median(vi,ti) = sum(double(i) ~= best) / length(best) ;\n errorsD_median(vi,ti) = mean(abs(d - drop) ./ drop) ;\n end\n\n if do_mean\n tic ;\n kdtree = vl_kdtreebuild(d1, ...\n 'verbose', ...\n 'thresholdmethod', 'mean', ...\n 'numtrees', t) ;\n %kdtree = readflann(kdtree, '/tmp/flann.txt') ;\n %checkx(kdtree, d1, 1, 1) ;\n [i, d] = vl_kdtreequery(kdtree, d1, d2, ...\n 'verbose', ...\n 'maxcomparisons', v) ;\n elapsedKD_mean(vi,ti) = toc ;\n errors_mean(vi,ti) = sum(double(i) ~= best) / length(best) ;\n errorsD_mean(vi,ti) = mean(abs(d - drop) ./ drop) ;\n end\n\n if do_flann\n tic ;\n [i, d] = flann_search(d1, d2, 1, struct('algorithm','kdtree', ...\n 'trees', t, ...\n 'checks', v));\n ifla = i ;\n elapsedKD_flann(vi,ti) = toc;\n errors_flann(vi,ti) = sum(i ~= best) / length(best) ;\n errorsD_flann(vi,ti) = mean(abs(d - drop) ./ drop) ;\n end\n end\nend\n\nfigure(1) ; clf ;\nleg = {} ;\nhnd = [] ;\nsty = {{'color','r'},{'color','g'},...\n {'color','b'},{'color','c'},...\n {'color','k'}} ;\n\nfor ti=1:length(numTreesRange)\n s = sty{mod(ti,length(sty))+1} ;\n\n if do_median\n h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errors_median(:,ti),'-*',s{:}) ; hold on ;\n leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;\n hnd(end+1) = h1 ;\n end\n\n if do_mean\n h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errors_mean(:,ti), '-o',s{:}) ; hold on ;\n leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;\n hnd(end+1) = h2 ;\n end\n\n if do_flann\n h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errors_flann(:,ti), '+--',s{:}) ; hold on ;\n leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;\n hnd(end+1) = h3 ;\n end\nend\nset([hnd], 'linewidth', 2) ;\nxlabel('speedup over linear search (log times)') ;\nylabel('percentage of incorrect matches (%)') ;\nh=legend(hnd, leg{:}, 'location', 'southeast') ;\nset(h,'fontsize',8) ;\ngrid on ;\naxis square ;\nvl_demo_print('kdtree_sift_incorrect',.6) ;\n\nfigure(2) ; clf ;\nleg = {} ;\nhnd = [] ;\nfor ti=1:length(numTreesRange)\n s = sty{mod(ti,length(sty))+1} ;\n\n if do_median\n h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errorsD_median(:,ti),'*-',s{:}) ; hold on ;\n leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;\n hnd(end+1) = h1 ;\n end\n\n if do_mean\n h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errorsD_mean(:,ti), 'o-',s{:}) ; hold on ;\n leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;\n hnd(end+1) = h2 ;\n end\n\n if do_flann\n h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errorsD_flann(:,ti), '+--',s{:}) ; hold on ;\n leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;\n hnd(end+1) = h3 ;\n end\nend\nset([hnd], 'linewidth', 2) ;\nxlabel('speedup over linear search (log times)') ;\nylabel('relative overestimation of minmium distannce (%)') ;\nh=legend(hnd, leg{:}, 'location', 'southeast') ;\nset(h,'fontsize',8) ;\ngrid on ;\naxis square ;\nvl_demo_print('kdtree_sift_distortion',.6) ;\n\n% --------------------------------------------------------------------\nfunction checkx(kdtree, X, t, n, mib, mab)\n% --------------------------------------------------------------------\n\nif nargin <= 4\n mib = -inf * ones(size(X,1),1) ;\n mab = +inf * ones(size(X,1),1) ;\nend\n\nlc = kdtree.trees(t).nodes.lowerChild(n) ;\nuc = kdtree.trees(t).nodes.upperChild(n) ;\n\nif lc < 0\n for i=-lc:-uc-1\n di = kdtree.trees(t).dataIndex(i) ;\n if any(X(:,di) > mab)\n error('a') ;\n end\n if any(X(:,di) < mib)\n error('b') ;\n end\n end\n return\nend\n\ni = kdtree.trees(t).nodes.splitDimension(n) ;\nv = kdtree.trees(t).nodes.splitThreshold(n) ;\n\nmab_ = mab ;\nmab_(i) = min(mab(i), v) ;\ncheckx(kdtree, X, t, lc, mib, mab_) ;\n\nmib_ = mib ;\nmib_(i) = max(mib(i), v) ;\ncheckx(kdtree, X, t, uc, mib_, mab) ;\n\n% --------------------------------------------------------------------\nfunction kdtree = readflann(kdtree, path)\n% --------------------------------------------------------------------\n\ndata = textread(path)' ;\n\nfor i=1:size(data,2)\n nodeIds = data(1,:) ;\n ni = find(nodeIds == data(1,i)) ;\n if ~isnan(data(2,i))\n % internal node\n li = find(nodeIds == data(4,i)) ;\n ri = find(nodeIds == data(5,i)) ;\n kdtree.trees(1).nodes.lowerChild(ni) = int32(li) ;\n kdtree.trees(1).nodes.upperChild(ni) = int32(ri) ;\n kdtree.trees(1).nodes.splitThreshold(ni) = single(data(2,i)) ;\n kdtree.trees(1).nodes.splitDimension(ni) = single(data(3,i)+1) ;\n else\n di = data(3,i) + 1 ;\n kdtree.trees(1).nodes.lowerChild(ni) = int32(- di) ;\n kdtree.trees(1).nodes.upperChild(ni) = int32(- di - 1) ;\n end\n kdtree.trees(1).dataIndex = uint32(1:kdtree.numData) ;\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_impattern.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/imop/vl_impattern.m", "size": 6876, "source_encoding": "utf_8", "md5": "1716a4d107f0186be3d11c647bc628ce", "text": "function im = vl_impattern(varargin)\n% VL_IMPATTERN Generate an image from a stock pattern\n% IM=VLPATTERN(NAME) returns an instance of the specified\n% pattern. These stock patterns are useful for testing algoirthms.\n%\n% All generated patterns are returned as an image of class\n% DOUBLE. Both gray-scale and colour images have range in [0,1].\n%\n% VL_IMPATTERN() without arguments shows a gallery of the stock\n% patterns. The following patterns are supported:\n%\n% Wedge::\n% The image of a wedge.\n%\n% Cone::\n% The image of a cone.\n%\n% SmoothChecker::\n% A checkerboard with Gaussian filtering on top. Use the\n% option-value pair 'sigma', SIGMA to specify the standard\n% deviation of the smoothing and the pair 'step', STEP to specfity\n% the checker size in pixels.\n%\n% ThreeDotsSquare::\n% A pattern with three small dots and two squares.\n%\n% UniformNoise::\n% Random i.i.d. noise.\n%\n% Blobs:\n% Gaussian blobs of various sizes and anisotropies.\n%\n% Blobs1:\n% Gaussian blobs of various orientations and anisotropies.\n%\n% Blob:\n% One Gaussian blob. Use the option-value pairs 'sigma',\n% 'orientation', and 'anisotropy' to specify the respective\n% parameters. 'sigma' is the scalar standard deviation of an\n% isotropic blob (the image domain is the rectangle\n% [-1,1]^2). 'orientation' is the clockwise rotation (as the Y\n% axis points downards). 'anisotropy' (>= 1) is the ratio of the\n% the largest over the smallest axis of the blob (the smallest\n% axis length is set by 'sigma'). Set 'cut' to TRUE to cut half\n% half of the blob.\n%\n% A stock image::\n% Any of 'box', 'roofs1', 'roofs2', 'river1', 'river2', 'spotted'.\n%\n% All pattern accept a SIZE parameter [WIDTH,HEIGHT]. For all but\n% the stock images, the default size is [128,128].\n\n% Author: Andrea Vedaldi\n\n% Copyright (C) 2012 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif nargin > 0\n pattern=varargin{1} ;\n varargin=varargin(2:end) ;\nelse\n pattern = 'gallery' ;\nend\n\npatterns = {'wedge','cone','smoothChecker','threeDotsSquare', ...\n 'blob', 'blobs', 'blobs1', ...\n 'box', 'roofs1', 'roofs2', 'river1', 'river2'} ;\n\n% spooling\nswitch lower(pattern)\n case 'wedge', im = wedge(varargin) ;\n case 'cone', im = cone(varargin) ;\n case 'smoothchecker', im = smoothChecker(varargin) ;\n case 'threedotssquare', im = threeDotSquare(varargin) ;\n case 'uniformnoise', im = uniformNoise(varargin) ;\n case 'blob', im = blob(varargin) ;\n case 'blobs', im = blobs(varargin) ;\n case 'blobs1', im = blobs1(varargin) ;\n case {'box','roofs1','roofs2','river1','river2','spots'}\n im = stockImage(pattern, varargin) ;\n case 'gallery'\n clf ;\n num = numel(patterns) ;\n for p = 1:num\n vl_tightsubplot(num,p,'box','outer') ;\n imagesc(vl_impattern(patterns{p}),[0 1]) ;\n axis image off ;\n title(patterns{p}) ;\n end\n colormap gray ;\n return ;\n otherwise\n error('Unknown patter ''%s''.', pattern) ;\nend\n\nif nargout == 0\n clf ; imagesc(im) ; hold on ;\n colormap gray ; axis image off ;\n title(pattern) ;\n clear im ;\nend\n\nfunction [u,v,opts,args] = commonOpts(args)\nopts.size = [128 128] ;\n[opts,args] = vl_argparse(opts, args) ;\nur = linspace(-1,1,opts.size(2)) ;\nvr = linspace(-1,1,opts.size(1)) ;\n[u,v] = meshgrid(ur,vr);\n\nfunction im = wedge(args)\n[u,v,opts,args] = commonOpts(args) ;\nim = abs(u) + abs(v) > (1/4) ;\nim(v < 0) = 0 ;\n\nfunction im = cone(args)\n[u,v,opts,args] = commonOpts(args) ;\nim = sqrt(u.^2+v.^2) ;\nim = im / max(im(:)) ;\n\nfunction im = smoothChecker(args)\nopts.size = [128 128] ;\nopts.step = 16 ;\nopts.sigma = 2 ;\nopts = vl_argparse(opts, args) ;\n[u,v] = meshgrid(0:opts.size(1)-1, 0:opts.size(2)-1) ;\nim = xor((mod(u,opts.step*2) < opts.step),...\n (mod(v,opts.step*2) < opts.step)) ;\nim = double(im) ;\nim = vl_imsmooth(im, opts.sigma) ;\n\nfunction im = threeDotSquare(args)\n[u,v,opts,args] = commonOpts(args) ;\nim = ones(size(u)) ;\nim(-2/3 0) ;\nend\n\nfunction im = blobs1(args)\n[u,v,opts,args] = commonOpts(args) ;\nopts.number = 5 ;\nopts.sigma = [] ;\nopts = vl_argparse(opts, args) ;\nim = zeros(size(u)) ;\nsquare = 2 / opts.number ;\nnum = opts.number ;\nif isempty(opts.sigma)\n sigma = 1/6 * square ;\nelse\n sigma = opts.sigma * square ;\nend\nrotations = linspace(0,pi,num+1) ;\nrotations(end) = [] ;\nskews = linspace(1,2,num) ;\nfor i=1:num\n for j=1:num\n cy = (i-1) * square + square/2 - 1;\n cx = (j-1) * square + square/2 - 1;\n th = rotations(i) ;\n R = [cos(th) -sin(th); sin(th) cos(th)] ;\n A = sigma * R * diag([1 1/skews(j)]) ;\n C = inv(A*A') ;\n x = u - cx ;\n y = v - cy ;\n im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;\n end\nend\nim = im / max(im(:)) ;\n\nfunction im = uniformNoise(args)\nopts.size = [128 128] ;\nopts.seed = 1 ;\nopts = vl_argparse(opts, args) ;\nstate = vl_twister('state') ;\nvl_twister('state',opts.seed) ;\nim = vl_twister(opts.size([2 1])) ;\nvl_twister('state',state) ;\n\nfunction im = stockImage(pattern,args)\nopts.size = [] ;\nopts = vl_argparse(opts, args) ;\nswitch pattern\n case 'river1', path='river1.jpg' ;\n case 'river2', path='river2.jpg' ;\n case 'roofs1', path='roofs1.jpg' ;\n case 'roofs2', path='roofs2.jpg' ;\n case 'box', path='box.pgm' ;\n case 'spots', path='spots.jpg' ;\nend\nim = imread(fullfile(vl_root,'data',path)) ;\nim = im2double(im) ;\nif ~isempty(opts.size)\n im = imresize(im, opts.size) ;\n im = max(im,0) ;\n im = min(im,1) ;\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_tpsu.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/imop/vl_tpsu.m", "size": 1755, "source_encoding": "utf_8", "md5": "09f36e1a707c069b375eb2817d0e5f13", "text": "function [U,dU,delta]=vl_tpsu(X,Y)\n% VL_TPSU Compute the U matrix of a thin-plate spline transformation\n% U=VL_TPSU(X,Y) returns the matrix\n%\n% [ U(|X(:,1) - Y(:,1)|) ... U(|X(:,1) - Y(:,N)|) ]\n% [ ]\n% [ U(|X(:,M) - Y(:,1)|) ... U(|X(:,M) - Y(:,N)|) ]\n%\n% where X is a 2xM matrix and Y a 2xN matrix of points and U(r) is\n% the opposite -r^2 log(r^2) of the radial basis function of the\n% thin plate spline specified by X and Y.\n%\n% [U,dU]=vl_tpsu(x,y) returns the derivatives of the columns of U with\n% respect to the parameters Y. The derivatives are arranged in a\n% Mx2xN array, one layer per column of U.\n%\n% See also: VL_TPS(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif exist('tpsumx')\n\tU = tpsumx(X,Y) ;\nelse\n M=size(X,2) ;\n N=size(Y,2) ;\n\n % Faster than repmat, but still fairly slow\n r2 = ...\n (X( ones(N,1), :)' - Y( ones(1,M), :)).^2 + ...\n (X( 1+ones(N,1), :)' - Y(1+ones(1,M), :)).^2 ;\n U = - rb(r2) ;\nend\n\nif nargout > 1\n M=size(X,2) ;\n N=size(Y,2) ;\n\n dx = X( ones(N,1), :)' - Y( ones(1,M), :) ;\n dy = X(1+ones(N,1), :)' - Y(1+ones(1,M), :) ;\n r2 = (dx.^2 + dy.^2) ;\n r = sqrt(r2) ;\n coeff = drb(r)./(r+eps) ;\n dU = reshape( [coeff .* dx ; coeff .* dy], M, 2, N) ;\nend\n\n% The radial basis function\nfunction y = rb(r2)\ny = zeros(size(r2)) ;\nsel = find(r2 ~= 0) ;\ny(sel) = - r2(sel) .* log(r2(sel)) ;\n\n% The derivative of the radial basis function\nfunction y = drb(r)\ny = zeros(size(r)) ;\nsel = find(r ~= 0) ;\ny(sel) = - 4 * r(sel) .* log(r(sel)) - 2 * r(sel) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_xyz2lab.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/imop/vl_xyz2lab.m", "size": 1570, "source_encoding": "utf_8", "md5": "09f95a6f9ae19c22486ec1157357f0e3", "text": "function J=vl_xyz2lab(I,il)\n% VL_XYZ2LAB Convert XYZ color space to LAB\n% J = VL_XYZ2LAB(I) converts the image from XYZ format to LAB format.\n%\n% VL_XYZ2LAB(I,IL) uses one of the illuminants A, B, C, E, D50, D55,\n% D65, D75, D93. The default illuminatn is E.\n%\n% See also: VL_XYZ2LUV(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif nargin < 2\n il='E' ;\nend\n\nswitch lower(il)\n case 'a'\n xw = 0.4476 ;\n yw = 0.4074 ;\n case 'b'\n xw = 0.3324 ;\n yw = 0.3474 ;\n case 'c'\n xw = 0.3101 ;\n yw = 0.3162 ;\n case 'e'\n xw = 1/3 ;\n yw = 1/3 ;\n case 'd50'\n xw = 0.3457 ;\n yw = 0.3585 ;\n case 'd55'\n xw = 0.3324 ;\n yw = 0.3474 ;\n case 'd65'\n xw = 0.312713 ;\n yw = 0.329016 ;\n case 'd75'\n xw = 0.299 ;\n yw = 0.3149 ;\n case 'd93'\n xw = 0.2848 ;\n yw = 0.2932 ;\nend\n\nJ=zeros(size(I)) ;\n\n% Reference white\nYw = 1.0 ;\nXw = xw/yw ;\nZw = (1-xw-yw)/yw * Yw ;\n\n% XYZ components\nX = I(:,:,1) ;\nY = I(:,:,2) ;\nZ = I(:,:,3) ;\n\nx = X/Xw ;\ny = Y/Yw ;\nz = Z/Zw ;\n\nL = 116 * f(y) - 16 ;\na = 500*(f(x) - f(y)) ;\nb = 200*(f(y) - f(z)) ;\n\nJ = cat(3,L,a,b) ;\n\n% --------------------------------------------------------------------\nfunction b=f(a)\n% --------------------------------------------------------------------\nsp = find(a > 0.00856) ;\nsm = find(a <= 0.00856) ;\nk = 903.3 ;\nb=zeros(size(a)) ;\nb(sp) = a(sp).^(1/3) ;\nb(sm) = (k*a(sm) + 16)/116 ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_gmm.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_gmm.m", "size": 1332, "source_encoding": "utf_8", "md5": "76782cae6c98781c6c38d4cbf5549d94", "text": "function results = vl_test_gmm(varargin)\n% VL_TEST_GMM\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nvl_test_init ;\n\nend\n\nfunction s = setup()\n randn('state',0) ;\n s.X = randn(128, 1000) ;\nend\n\nfunction test_multithreading(s)\n dataTypes = {'single','double'} ;\n\n for dataType = dataTypes\n conversion = str2func(char(dataType)) ;\n X = conversion(s.X) ;\n vl_twister('state',0) ;\n vl_threads(0) ;\n [means, covariances, priors, ll, posteriors] = ...\n vl_gmm(X, 10, ...\n 'NumRepetitions', 1, ...\n 'MaxNumIterations', 10, ...\n 'Initialization', 'rand') ;\n vl_twister('state',0) ;\n vl_threads(1) ;\n [means_, covariances_, priors_, ll_, posteriors_] = ...\n vl_gmm(X, 10, ...\n 'NumRepetitions', 1, ...\n 'MaxNumIterations', 10, ...\n 'Initialization', 'rand') ;\n\n vl_assert_almost_equal(means, means_, 1e-2) ;\n vl_assert_almost_equal(covariances, covariances_, 1e-2) ;\n vl_assert_almost_equal(priors, priors_, 1e-2) ;\n vl_assert_almost_equal(ll, ll_, 1e-2 * abs(ll)) ;\n vl_assert_almost_equal(posteriors, posteriors_, 1e-2) ;\n end\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_twister.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_twister.m", "size": 1251, "source_encoding": "utf_8", "md5": "2bfb5a30cbd6df6ac80c66b73f8646da", "text": "function results = vl_test_twister(varargin)\n% VL_TEST_TWISTER\nvl_test_init ;\n\nfunction test_illegal_args()\nvl_assert_exception(@() vl_twister(-1), 'vl:invalidArgument') ;\nvl_assert_exception(@() vl_twister(1, -1), 'vl:invalidArgument') ;\nvl_assert_exception(@() vl_twister([1, -1]), 'vl:invalidArgument') ;\n\nfunction test_seed_by_scalar()\nrand('twister',1) ; a = rand ;\nvl_twister('state',1) ; b = vl_twister ;\nvl_assert_equal(a,b,'seed by scalar + VL_TWISTER()') ;\n\nfunction test_get_set_state()\nrand('twister',1) ; a = rand('twister') ;\nvl_twister('state',1) ; b = vl_twister('state') ;\nvl_assert_equal(a,b,'read state') ;\n\na(1) = a(1) + 1 ;\nvl_twister('state',a) ; b = vl_twister('state') ;\nvl_assert_equal(a,b,'set state') ;\n\nfunction test_multi_dimensions()\nb = rand('twister') ;\nrand('twister',b) ;\nvl_twister('state',b) ;\na=rand([1 2 3 4 5]) ;\nb=vl_twister([1 2 3 4 5]) ;\nvl_assert_equal(a,b,'VL_TWISTER([M N P ...])') ;\n\nfunction test_multi_multi_args()\nrand('twister',1) ; a=rand(1, 2, 3, 4, 5) ;\nvl_twister('state',1) ; b=vl_twister(1, 2, 3, 4, 5) ;\nvl_assert_equal(a,b,'VL_TWISTER(M, N, P, ...)') ;\n\nfunction test_square()\nrand('twister',1) ; a=rand(10) ;\nvl_twister('state',1) ; b=vl_twister(10) ;\nvl_assert_equal(a,b,'VL_TWISTER(N)') ;\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_kdtree.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_kdtree.m", "size": 2449, "source_encoding": "utf_8", "md5": "9d7ad2b435a88c22084b38e5eb5f9eb9", "text": "function results = vl_test_kdtree(varargin)\n% VL_TEST_KDTREE\nvl_test_init ;\n\nfunction s = setup()\nrandn('state',0) ;\ns.X = single(randn(10, 1000)) ;\ns.Q = single(randn(10, 10)) ;\n\nfunction test_nearest(s)\nfor tmethod = {'median', 'mean'}\n for type = {@single, @double}\n conv = type{1} ;\n tmethod = char(tmethod) ;\n\n X = conv(s.X) ;\n Q = conv(s.Q) ;\n tree = vl_kdtreebuild(X,'ThresholdMethod', tmethod) ;\n [nn, d2] = vl_kdtreequery(tree, X, Q) ;\n\n D2 = vl_alldist2(X, Q, 'l2') ;\n [d2_, nn_] = min(D2) ;\n\n vl_assert_equal(...\n nn,uint32(nn_),...\n 'incorrect nns: type=%s th. method=%s', func2str(conv), tmethod) ;\n vl_assert_almost_equal(...\n d2,d2_,...\n 'incorrect distances: type=%s th. method=%s', func2str(conv), tmethod) ;\n end\nend\n\nfunction test_nearests(s)\nnumNeighbors = 7 ;\ntree = vl_kdtreebuild(s.X) ;\n[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...\n 'numNeighbors', numNeighbors) ;\n\nD2 = vl_alldist2(s.X, s.Q, 'l2') ;\n[d2_, nn_] = sort(D2) ;\nd2_ = d2_(1:numNeighbors, :) ;\nnn_ = nn_(1:numNeighbors, :) ;\n\nvl_assert_equal(nn,uint32(nn_)) ;\nvl_assert_almost_equal(d2,d2_) ;\n\nfunction test_ann(s)\nvl_twister('state', 1) ;\nnumNeighbors = 7 ;\nmaxComparisons = numNeighbors * 50 ;\ntree = vl_kdtreebuild(s.X) ;\n[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...\n 'numNeighbors', numNeighbors, ...\n 'maxComparisons', maxComparisons) ;\n\nD2 = vl_alldist2(s.X, s.Q, 'l2') ;\n[d2_, nn_] = sort(D2) ;\nd2_ = d2_(1:numNeighbors, :) ;\nnn_ = nn_(1:numNeighbors, :) ;\n\nfor i=1:size(s.Q,2)\n overlap = numel(intersect(nn(:,i), nn_(:,i))) / ...\n numel(union(nn(:,i), nn_(:,i))) ;\n assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ;\nend\n\nfunction test_ann_forest(s)\nvl_twister('state', 1) ;\nnumNeighbors = 7 ;\nmaxComparisons = numNeighbors * 25 ;\nnumTrees = 5 ;\ntree = vl_kdtreebuild(s.X, 'numTrees', 5) ;\n[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...\n 'numNeighbors', numNeighbors, ...\n 'maxComparisons', maxComparisons) ;\n\nD2 = vl_alldist2(s.X, s.Q, 'l2') ;\n[d2_, nn_] = sort(D2) ;\nd2_ = d2_(1:numNeighbors, :) ;\nnn_ = nn_(1:numNeighbors, :) ;\n\nfor i=1:size(s.Q,2)\n overlap = numel(intersect(nn(:,i), nn_(:,i))) / ...\n numel(union(nn(:,i), nn_(:,i))) ;\n assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ;\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_imwbackward.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_imwbackward.m", "size": 514, "source_encoding": "utf_8", "md5": "33baa0784c8f6f785a2951d7f1b49199", "text": "function results = vl_test_imwbackward(varargin)\n% VL_TEST_IMWBACKWARD\nvl_test_init ;\n\nfunction s = setup()\ns.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;\n\nfunction test_identity(s)\nxr = 1:size(s.I,2) ;\nyr = 1:size(s.I,1) ;\n[x,y] = meshgrid(xr,yr) ;\nvl_assert_almost_equal(s.I, vl_imwbackward(xr,yr,s.I,x,y)) ;\n\nfunction test_invalid_args(s)\nxr = 1:size(s.I,2) ;\nyr = 1:size(s.I,1) ;\n[x,y] = meshgrid(xr,yr) ;\nvl_assert_exception(@() vl_imwbackward(xr,yr,single(s.I),x,y), 'vl:invalidArgument') ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_alphanum.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_alphanum.m", "size": 1624, "source_encoding": "utf_8", "md5": "2da2b768c2d0f86d699b8f31614aa424", "text": "function results = vl_test_alphanum(varargin)\n% VL_TEST_ALPHANUM\nvl_test_init ;\n\nfunction s = setup()\n\ns.strings = ...\n {'1000X Radonius Maximus','10X Radonius','200X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','Allegia 50 Clasteron','Allegia 500 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 6R Clasteron','Alpha 100','Alpha 2','Alpha 200','Alpha 2A','Alpha 2A-8000','Alpha 2A-900','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 5000','Callisto Morphamax 600','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 700','Callisto Morphamax 7000','Xiph Xlater 10000','Xiph Xlater 2000','Xiph Xlater 300','Xiph Xlater 40','Xiph Xlater 5','Xiph Xlater 50','Xiph Xlater 500','Xiph Xlater 5000','Xiph Xlater 58'} ;\n\ns.sortedStrings = ...\n {'10X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','200X Radonius','1000X Radonius Maximus','Allegia 6R Clasteron','Allegia 50 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 500 Clasteron','Alpha 2','Alpha 2A','Alpha 2A-900','Alpha 2A-8000','Alpha 100','Alpha 200','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 600','Callisto Morphamax 700','Callisto Morphamax 5000','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 7000','Xiph Xlater 5','Xiph Xlater 40','Xiph Xlater 50','Xiph Xlater 58','Xiph Xlater 300','Xiph Xlater 500','Xiph Xlater 2000','Xiph Xlater 5000','Xiph Xlater 10000'} ;\n\nfunction test_basic(s)\nsorted = vl_alphanum(s.strings) ;\nassert(isequal(sorted,s.sortedStrings)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_printsize.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_printsize.m", "size": 1447, "source_encoding": "utf_8", "md5": "0f0b6437c648b7a2e1310900262bd765", "text": "function results = vl_test_printsize(varargin)\n% VL_TEST_PRINTSIZE\nvl_test_init ;\n\nfunction s = setup()\ns.fig = figure(1) ;\ns.usletter = [8.5, 11] ; % inches\ns.a4 = [8.26772, 11.6929] ;\nclf(s.fig) ; plot(1:10) ;\n\nfunction teardown(s)\nclose(s.fig) ;\n\nfunction test_basic(s)\nfor sigma = [1 0.5 0.2]\n vl_printsize(s.fig, sigma) ;\n set(1, 'PaperUnits', 'inches') ;\n siz = get(1, 'PaperSize') ;\n pos = get(1, 'PaperPosition') ;\n vl_assert_almost_equal(siz(1), sigma*s.usletter(1), 1e-4) ;\n vl_assert_almost_equal(pos(1), 0, 1e-4) ;\n vl_assert_almost_equal(pos(3), sigma*s.usletter(1), 1e-4) ;\nend\n\nfunction test_papertype(s)\nvl_printsize(s.fig, 1, 'papertype', 'a4') ;\nset(1, 'PaperUnits', 'inches') ;\nsiz = get(1, 'PaperSize') ;\npos = get(1, 'PaperPosition') ;\nvl_assert_almost_equal(siz(1), s.a4(1), 1e-4) ;\n\nfunction test_margin(s)\nm = 0.5 ;\nvl_printsize(s.fig, 1, 'margin', m) ;\nset(1, 'PaperUnits', 'inches') ;\nsiz = get(1, 'PaperSize') ;\npos = get(1, 'PaperPosition') ;\nvl_assert_almost_equal(siz(1), s.usletter(1) * (1 + 2*m), 1e-4) ;\nvl_assert_almost_equal(pos(1), s.usletter(1) * m, 1e-4) ;\n\nfunction test_reference(s)\nsigma = 1 ;\nvl_printsize(s.fig, 1, 'reference', 'vertical') ;\nset(1, 'PaperUnits', 'inches') ;\nsiz = get(1, 'PaperSize') ;\npos = get(1, 'PaperPosition') ;\nvl_assert_almost_equal(siz(2), sigma*s.usletter(2), 1e-4) ;\nvl_assert_almost_equal(pos(2), 0, 1e-4) ;\nvl_assert_almost_equal(pos(4), sigma*s.usletter(2), 1e-4) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_cummax.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_cummax.m", "size": 838, "source_encoding": "utf_8", "md5": "5e98ee1681d4823f32ecc4feaa218611", "text": "function results = vl_test_cummax(varargin)\n% VL_TEST_CUMMAX\nvl_test_init ;\n\nfunction test_basic()\nvl_assert_almost_equal(...\n vl_cummax(1), 1) ;\nvl_assert_almost_equal(...\n vl_cummax([1 2 3 4], 2), [1 2 3 4]) ;\n\nfunction test_multidim()\na = [1 2 3 4 3 2 1] ;\nb = [1 2 3 4 4 4 4] ;\nfor k=1:6\n dims = ones(1,6) ;\n dims(k) = numel(a) ;\n a = reshape(a, dims) ;\n b = reshape(b, dims) ;\n vl_assert_almost_equal(...\n vl_cummax(a, k), b) ;\nend\n\nfunction test_storage_classes()\ntypes = {@double, @single, ...\n @int32, @uint32, ...\n @int16, @uint16, ...\n @int8, @uint8} ;\nif vl_matlabversion() > 71000\n types = horzcat(types, {@int64, @uint64}) ;\nend\nfor a = types\n a = a{1} ;\n for b = types\n b = b{1} ;\n vl_assert_almost_equal(...\n vl_cummax(a(eye(3))), a(toeplitz([1 1 1], [1 0 0 ]))) ;\n end\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_imintegral.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_imintegral.m", "size": 1429, "source_encoding": "utf_8", "md5": "4750f04ab0ac9fc4f55df2c8583e5498", "text": "function results = vl_test_imintegral(varargin)\n% VL_TEST_IMINTEGRAL\nvl_test_init ;\n\nfunction state = setup()\nstate.I = ones(5,6) ;\nstate.correct = [ 1 2 3 4 5 6 ;\n 2 4 6 8 10 12 ;\n 3 6 9 12 15 18 ;\n 4 8 12 16 20 24 ;\n 5 10 15 20 25 30 ; ] ;\n\nfunction test_matlab_equivalent(s)\nvl_assert_equal(slow_imintegral(s.I), s.correct) ;\n\nfunction test_basic(s)\nvl_assert_equal(vl_imintegral(s.I), s.correct) ;\n\nfunction test_multi_dimensional(s)\nvl_assert_equal(vl_imintegral(repmat(s.I, [1 1 3])), ...\n repmat(s.correct, [1 1 3])) ;\n\nfunction test_random(s)\nnumTests = 50 ;\nfor i = 1:numTests\n I = rand(5) ;\n vl_assert_almost_equal(vl_imintegral(s.I), ...\n slow_imintegral(s.I)) ;\nend\n\nfunction test_datatypes(s)\nvl_assert_equal(single(vl_imintegral(s.I)), single(s.correct)) ;\nvl_assert_equal(double(vl_imintegral(s.I)), double(s.correct)) ;\nvl_assert_equal(uint32(vl_imintegral(s.I)), uint32(s.correct)) ;\nvl_assert_equal(int32(vl_imintegral(s.I)), int32(s.correct)) ;\nvl_assert_equal(int32(vl_imintegral(-s.I)), -int32(s.correct)) ;\n\nfunction integral = slow_imintegral(I)\nintegral = zeros(size(I));\nfor k = 1:size(I,3)\n for r = 1:size(I,1)\n for c = 1:size(I,2)\n integral(r,c,k) = sum(sum(I(1:r,1:c,k)));\n end\n end\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_sift.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_sift.m", "size": 1318, "source_encoding": "utf_8", "md5": "806c61f9db9f2ebb1d649c9bfcf3dc0a", "text": "function results = vl_test_sift(varargin)\n% VL_TEST_SIFT\nvl_test_init ;\n\nfunction s = setup()\ns.I = im2single(imread(fullfile(vl_root,'data','box.pgm'))) ;\n[s.ubc.f, s.ubc.d] = ...\n vl_ubcread(fullfile(vl_root,'data','box.sift')) ;\n\nfunction test_ubc_descriptor(s)\nerr = [] ;\n[f, d] = vl_sift(s.I,...\n 'firstoctave', -1, ...\n 'frames', s.ubc.f) ;\nD2 = vl_alldist(f, s.ubc.f) ;\n[drop, perm] = min(D2) ;\nf = f(:,perm) ;\nd = d(:,perm) ;\nerror = mean(sqrt(sum((single(s.ubc.d) - single(d)).^2))) ...\n / mean(sqrt(sum(single(s.ubc.d).^2))) ;\nassert(error < 0.1, ...\n 'sift descriptor did not produce desctiptors similar to UBC ones') ;\n\nfunction test_ubc_detector(s)\n[f, d] = vl_sift(s.I,...\n 'firstoctave', -1, ...\n 'peakthresh', .01, ...\n 'edgethresh', 10) ;\n\ns.ubc.f(4,:) = mod(s.ubc.f(4,:), 2*pi) ;\nf(4,:) = mod(f(4,:), 2*pi) ;\n\n% scale the components so that 1 pixel erro in x,y,z is equal to a\n% 10-th of angle.\nS = diag([1 1 1 20/pi]);\nD2 = vl_alldist(S * s.ubc.f, S * f) ;\n[d2,perm] = sort(min(D2)) ;\nerror = sqrt(d2) ;\nquant80 = round(.8 * size(f,2)) ;\n\n% check for less than one pixel error at 80% quantile\nassert(error(quant80) < 1, ...\n 'sift detector did not produce enough keypoints similar to UBC ones') ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_binsum.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_binsum.m", "size": 1377, "source_encoding": "utf_8", "md5": "f07f0f29ba6afe0111c967ab0b353a9d", "text": "function results = vl_test_binsum(varargin)\n% VL_TEST_BINSUM\nvl_test_init ;\n\nfunction test_three_args()\nvl_assert_almost_equal(...\n vl_binsum([0 0], 1, 2), [0 1]) ;\nvl_assert_almost_equal(...\n vl_binsum([1 7], -1, 1), [0 7]) ;\nvl_assert_almost_equal(...\n vl_binsum([1 7], -1, [1 2 2 2 2 2 2 2]), [0 0]) ;\n\nfunction test_four_args()\nvl_assert_almost_equal(...\n vl_binsum(eye(3), [1 1 1], [1 2 3], 1), 2*eye(3)) ;\nvl_assert_almost_equal(...\n vl_binsum(eye(3), [1 1 1]', [1 2 3]', 2), 2*eye(3)) ;\nvl_assert_almost_equal(...\n vl_binsum(eye(3), 1, [1 2 3], 1), 2*eye(3)) ;\nvl_assert_almost_equal(...\n vl_binsum(eye(3), 1, [1 2 3]', 2), 2*eye(3)) ;\n\nfunction test_3d_one()\nZ = zeros(3,3,3) ;\nB = 3*ones(3,1,3) ;\nR = Z ; R(:,3,:) = 17 ;\nvl_assert_almost_equal(...\n vl_binsum(Z, 17, B, 2), R) ;\n\nfunction test_3d_two()\nZ = zeros(3,3,3) ;\nB = 3*ones(3,3,1) ;\nX = zeros(3,3,1) ; X(:,:,1) = 17 ;\nR = Z ; R(:,:,3) = 17 ;\nvl_assert_almost_equal(...\n vl_binsum(Z, X, B, 3), R) ;\n\nfunction test_storage_classes()\ntypes = {@double, @single, ...\n @int32, @uint32, ...\n @int16, @uint16, ...\n @int8, @uint8} ;\nif vl_matlabversion() > 71000\n types = horzcat(types, {@int64, @uint64}) ;\nend\nfor a = types\n a = a{1} ;\n for b = types\n b = b{1} ;\n vl_assert_almost_equal(...\n vl_binsum(a(eye(3)), a([1 1 1]), b([1 2 3]), 1), a(2*eye(3))) ;\n end\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_lbp.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_lbp.m", "size": 892, "source_encoding": "utf_8", "md5": "a79c0ce0c85e25c0b1657f3a0b499538", "text": "function results = vl_test_lbp(varargin)\n% VL_TEST_TWISTER\nvl_test_init ;\n\nfunction test_unfiorm_lbps(s)\n\n% enumerate the 56 uniform lbps\nq = 0 ;\nfor i=0:7\n for j=1:7\n I = zeros(3) ;\n p = mod(s.pixels - i + 8, 8) + 1 ;\n I(p <= j) = 1 ;\n f = vl_lbp(single(I), 3) ;\n q = q + 1 ;\n vl_assert_equal(find(f), q) ;\n end\nend\n\n% constant lbps\nI = [1 1 1 ; 1 0 1 ; 1 1 1] ;\nf = vl_lbp(single(I), 3) ;\nvl_assert_equal(find(f), 57) ;\n\nI = [1 1 1 ; 1 1 1 ; 1 1 1] ;\nf = vl_lbp(single(I), 3) ;\nvl_assert_equal(find(f), 57) ;\n\n% other lbps\nI = [1 0 1 ; 0 0 0 ; 1 0 1] ;\nf = vl_lbp(single(I), 3) ;\nvl_assert_equal(find(f), 58) ;\n\nfunction test_fliplr(s)\nrandn('state',0) ;\nI = randn(256,256,1,'single') ;\nf = vl_lbp(fliplr(I), 8) ;\nf_ = vl_lbpfliplr(vl_lbp(I, 8)) ;\nvl_assert_almost_equal(f,f_,1e-3) ;\n\nfunction s = setup()\ns.pixels = [5 6 7 ;\n 4 NaN 0 ;\n 3 2 1] ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_colsubset.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_colsubset.m", "size": 828, "source_encoding": "utf_8", "md5": "be0c080007445b36333b863326fb0f15", "text": "function results = vl_test_colsubset(varargin)\n% VL_TEST_COLSUBSET\nvl_test_init ;\n\nfunction s = setup()\ns.x = [5 2 3 6 4 7 1 9 8 0] ;\n\nfunction test_beginning(s)\nvl_assert_equal(1:5, vl_colsubset(1:10, 5, 'beginning')) ;\nvl_assert_equal(1:5, vl_colsubset(1:10, .5, 'beginning')) ;\n\nfunction test_ending(s)\nvl_assert_equal(6:10, vl_colsubset(1:10, 5, 'ending')) ;\nvl_assert_equal(6:10, vl_colsubset(1:10, .5, 'ending')) ;\n\nfunction test_largest(s)\nvl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, 5, 'largest')) ;\nvl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, .5, 'largest')) ;\n\nfunction test_smallest(s)\nvl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, 5, 'smallest')) ;\nvl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, .5, 'smallest')) ;\n\nfunction test_random(s)\nassert(numel(intersect(s.x, vl_colsubset(s.x, 5, 'random'))) == 5) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_alldist.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_alldist.m", "size": 2373, "source_encoding": "utf_8", "md5": "9ea1a36c97fe715dfa2b8693876808ff", "text": "function results = vl_test_alldist(varargin)\n% VL_TEST_ALLDIST\nvl_test_init ;\n\nfunction s = setup()\nvl_twister('state', 0) ;\ns.X = 3.1 * vl_twister(10,10) ;\ns.Y = 4.7 * vl_twister(10,7) ;\n\nfunction test_null_args(s)\nvl_assert_equal(...\n vl_alldist(zeros(15,12), zeros(15,0), 'kl2'), ...\n zeros(12,0)) ;\n\nvl_assert_equal(...\n vl_alldist(zeros(15,0), zeros(15,0), 'kl2'), ...\n zeros(0,0)) ;\n\nvl_assert_equal(...\n vl_alldist(zeros(15,0), zeros(15,12), 'kl2'), ...\n zeros(0,12)) ;\n\nvl_assert_equal(...\n vl_alldist(zeros(0,15), zeros(0,12), 'kl2'), ...\n zeros(15,12)) ;\n\nfunction test_self(s)\nvl_assert_almost_equal(...\n vl_alldist(s.X, 'kl2'), ...\n makedist(@(x,y) x*y, s.X, s.X), ...\n 1e-6) ;\n\nfunction test_distances(s)\ndists = {'chi2', 'l2', 'l1', 'hell', 'js', ...\n 'kchi2', 'kl2', 'kl1', 'khell', 'kjs'} ;\ndistsEquiv = { ...\n @(x,y) (x-y)^2 / (x + y), ...\n @(x,y) (x-y)^2, ...\n @(x,y) abs(x-y), ...\n @(x,y) (sqrt(x) - sqrt(y))^2, ...\n @(x,y) x - x .* log2(1 + y/x) + y - y .* log2(1 + x/y), ...\n @(x,y) 2 * (x*y) / (x + y), ...\n @(x,y) x*y, ...\n @(x,y) min(x,y), ...\n @(x,y) sqrt(x.*y), ...\n @(x,y) .5 * (x .* log2(1 + y/x) + y .* log2(1 + x/y))} ;\ntypes = {'single', 'double'} ;\n\nfor simd = [0 1]\n for d = 1:length(dists)\n for t = 1:length(types)\n vl_simdctrl(simd) ;\n X = feval(str2func(types{t}), s.X) ;\n Y = feval(str2func(types{t}), s.Y) ;\n vl_assert_almost_equal(...\n vl_alldist(X,Y,dists{d}), ...\n makedist(distsEquiv{d},X,Y), ...\n 1e-4, ...\n 'alldist failed for dist=%s type=%s simd=%d', ...\n dists{d}, ...\n types{t}, ...\n simd) ;\n end\n end\nend\n\nfunction test_distance_kernel_pairs(s)\ndists = {'chi2', 'l2', 'l1', 'hell', 'js'} ;\nfor d = 1:length(dists)\n dist = char(dists{d}) ;\n X = s.X ;\n Y = s.Y ;\n ker = ['k' dist] ;\n kxx = vl_alldist(X,X,ker) ;\n kyy = vl_alldist(Y,Y,ker) ;\n kxy = vl_alldist(X,Y,ker) ;\n kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;\n kyy = repmat(diag(kyy), 1, size(s.X,1))' ;\n d2 = vl_alldist(X,Y,dist) ;\n vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;\nend\n\nfunction D = makedist(cmp,X,Y)\n[d,m] = size(X) ;\n[d,n] = size(Y) ;\nD = zeros(m,n) ;\nfor i = 1:m\n for j = 1:n\n acc = 0 ;\n for k = 1:d\n acc = acc + cmp(X(k,i),Y(k,j)) ;\n end\n D(i,j) = acc ;\n end\nend\nconv = str2func(class(X)) ;\nD = conv(D) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_ihashsum.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_ihashsum.m", "size": 581, "source_encoding": "utf_8", "md5": "edc283062469af62056b0782b171f5fc", "text": "function results = vl_test_ihashsum(varargin)\n% VL_TEST_IHASHSUM\nvl_test_init ;\n\nfunction s = setup()\nrand('state',0) ;\ns.data = uint8(round(16*rand(2,100))) ;\nsel = find(all(s.data==0)) ;\ns.data(1,sel)=1 ;\n\nfunction test_hash(s)\nD = size(s.data,1) ;\nK = 5 ;\nh = zeros(1,K,'uint32') ;\nid = zeros(D,K,'uint8');\nnext = zeros(1,K,'uint32') ;\n[h,id,next] = vl_ihashsum(h,id,next,K,s.data) ;\n\nsel = vl_ihashfind(id,next,K,s.data) ;\ncount = double(h(sel)) ;\n\n[drop,i,j] = unique(s.data','rows') ;\nfor k=1:size(s.data,2)\n count_(k) = sum(j == j(k)) ;\nend\nvl_assert_equal(count,count_) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_grad.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_grad.m", "size": 434, "source_encoding": "utf_8", "md5": "4d03eb33a6a4f68659f868da95930ffb", "text": "function results = vl_test_grad(varargin)\n% VL_TEST_GRAD\nvl_test_init ;\n\nfunction s = setup()\ns.I = rand(150,253) ;\ns.I_small = rand(2,2) ;\n\nfunction test_equiv(s)\nvl_assert_equal(gradient(s.I), vl_grad(s.I)) ;\n\nfunction test_equiv_small(s)\nvl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;\n\nfunction test_equiv_forward(s)\nIx = diff(s.I,2,1) ;\nIy = diff(s.I,2,1) ;\n\nvl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_whistc.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_whistc.m", "size": 1384, "source_encoding": "utf_8", "md5": "81c446d35c82957659840ab2a579ec2c", "text": "function results = vl_test_whistc(varargin)\n% VL_TEST_WHISTC\nvl_test_init ;\n\nfunction test_acc()\nx = ones(1, 10) ;\ne = 1 ;\no = 1:10 ;\nvl_assert_equal(vl_whistc(x, o, e), 55) ;\n\nfunction test_basic()\nx = 1:10 ;\ne = 1:10 ;\no = ones(1, 10) ;\nvl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;\n\nx = linspace(-1,11,100) ;\no = ones(size(x)) ;\nvl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;\n\nfunction test_multidim()\nx = rand(10, 20, 30) ;\ne = linspace(0,1,10) ;\no = ones(size(x)) ;\n\nvl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;\nvl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;\nvl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;\nvl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;\n\nfunction test_nan()\nx = rand(10, 20, 30) ;\ne = linspace(0,1,10) ;\no = ones(size(x)) ;\nx(1:7:end) = NaN ;\n\nvl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;\nvl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;\nvl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;\nvl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;\n\nfunction test_no_edges()\nx = rand(10, 20, 30) ;\no = ones(size(x)) ;\nvl_assert_equal(histc(1, []), vl_whistc(1, 1, [])) ;\nvl_assert_equal(histc(x, []), vl_whistc(x, o, [])) ;\nvl_assert_equal(histc(x, [], 1), vl_whistc(x, o, [], 1)) ;\nvl_assert_equal(histc(x, [], 2), vl_whistc(x, o, [], 2)) ;\nvl_assert_equal(histc(x, [], 3), vl_whistc(x, o, [], 3)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_roc.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_roc.m", "size": 1019, "source_encoding": "utf_8", "md5": "9b2ae71c9dc3eda0fc54c65d55054d0c", "text": "function results = vl_test_roc(varargin)\n% VL_TEST_ROC\nvl_test_init ;\n\nfunction s = setup()\ns.scores0 = [5 4 3 2 1] ;\ns.scores1 = [5 3 4 2 1] ;\ns.labels = [1 1 -1 -1 -1] ;\n\nfunction test_perfect_tptn(s)\n[tpr,tnr] = vl_roc(s.labels,s.scores0) ;\nvl_assert_almost_equal(tpr, [0 1 2 2 2 2] / 2) ;\nvl_assert_almost_equal(tnr, [3 3 3 2 1 0] / 3) ;\n\nfunction test_perfect_metrics(s)\n[tpr,tnr,info] = vl_roc(s.labels,s.scores0) ;\nvl_assert_almost_equal(info.eer, 0) ;\nvl_assert_almost_equal(info.auc, 1) ;\n\nfunction test_swap1_tptn(s)\n[tpr,tnr] = vl_roc(s.labels,s.scores1) ;\nvl_assert_almost_equal(tpr, [0 1 1 2 2 2] / 2) ;\nvl_assert_almost_equal(tnr, [3 3 2 2 1 0] / 3) ;\n\nfunction test_swap1_tptn_stable(s)\n[tpr,tnr] = vl_roc(s.labels,s.scores1,'stable',true) ;\nvl_assert_almost_equal(tpr, [1 2 1 2 2] / 2) ;\nvl_assert_almost_equal(tnr, [3 2 2 1 0] / 3) ;\n\nfunction test_swap1_metrics(s)\n[tpr,tnr,info] = vl_roc(s.labels,s.scores1) ;\nvl_assert_almost_equal(info.eer, 1/3) ;\nvl_assert_almost_equal(info.auc, 1 - 1/(2*3)) ;\n\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_dsift.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_dsift.m", "size": 2048, "source_encoding": "utf_8", "md5": "fbbfb16d5a21936c1862d9551f657ccc", "text": "function results = vl_test_dsift(varargin)\n% VL_TEST_DSIFT\nvl_test_init ;\n\nfunction s = setup()\nI = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;\ns.I = rgb2gray(single(I)) ;\n\nfunction test_fast_slow(s)\nbinSize = 4 ; % bin size in pixels\nmagnif = 3 ; % bin size / keypoint scale\nscale = binSize / magnif ;\nwindowSize = 5 ;\n\n[f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...\n 'size', binSize, ...\n 'step', 10, ...\n 'bounds', [20,20,210,140], ...\n 'windowsize', windowSize, ...\n 'floatdescriptors') ;\n\n[f_, d_] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...\n 'size', binSize, ...\n 'step', 10, ...\n 'bounds', [20,20,210,140], ...\n 'windowsize', windowSize, ...\n 'floatdescriptors', ...\n 'fast') ;\n\nerror = std(d_(:) - d(:)) / std(d(:)) ;\nassert(error < 0.1, 'dsift fast approximation not close') ;\n\nfunction test_sift(s)\nbinSize = 4 ; % bin size in pixels\nmagnif = 3 ; % bin size / keypoint scale\nscale = binSize / magnif ;\n\nwindowSizeRange = [1 1.2 5] ;\nfor wi = 1:length(windowSizeRange)\n windowSize = windowSizeRange(wi) ;\n\n [f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...\n 'size', binSize, ...\n 'step', 10, ...\n 'bounds', [20,20,210,140], ...\n 'windowsize', windowSize, ...\n 'floatdescriptors') ;\n\n numKeys = size(f, 2) ;\n f_ = [f ; ones(1, numKeys) * scale ; zeros(1, numKeys)] ;\n\n [f_, d_] = vl_sift(s.I, ...\n 'magnif', magnif, ...\n 'frames', f_, ...\n 'firstoctave', -1, ...\n 'levels', 5, ...\n 'floatdescriptors', ...\n 'windowsize', windowSize) ;\n\n error = std(d_(:) - d(:)) / std(d(:)) ;\n assert(error < 0.1, 'dsift and sift equivalence') ;\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_alldist2.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_alldist2.m", "size": 2284, "source_encoding": "utf_8", "md5": "89a787e3d83516653ae8d99c808b9d67", "text": "function results = vl_test_alldist2(varargin)\n% VL_TEST_ALLDIST\nvl_test_init ;\n\n% TODO: test integer classes\n\nfunction s = setup()\nvl_twister('state', 0) ;\ns.X = 3.1 * vl_twister(10,10) ;\ns.Y = 4.7 * vl_twister(10,7) ;\n\nfunction test_null_args(s)\nvl_assert_equal(...\n vl_alldist2(zeros(15,12), zeros(15,0), 'kl2'), ...\n zeros(12,0)) ;\n\nvl_assert_equal(...\n vl_alldist2(zeros(15,0), zeros(15,0), 'kl2'), ...\n zeros(0,0)) ;\n\nvl_assert_equal(...\n vl_alldist2(zeros(15,0), zeros(15,12), 'kl2'), ...\n zeros(0,12)) ;\n\nvl_assert_equal(...\n vl_alldist2(zeros(0,15), zeros(0,12), 'kl2'), ...\n zeros(15,12)) ;\n\nfunction test_self(s)\nvl_assert_almost_equal(...\n vl_alldist2(s.X, 'kl2'), ...\n makedist(@(x,y) x*y, s.X, s.X), ...\n 1e-6) ;\n\nfunction test_distances(s)\ndists = {'chi2', 'l2', 'l1', 'hell', ...\n 'kchi2', 'kl2', 'kl1', 'khell'} ;\ndistsEquiv = { ...\n @(x,y) (x-y)^2 / (x + y), ...\n @(x,y) (x-y)^2, ...\n @(x,y) abs(x-y), ...\n @(x,y) (sqrt(x) - sqrt(y))^2, ...\n @(x,y) 2 * (x*y) / (x + y), ...\n @(x,y) x*y, ...\n @(x,y) min(x,y), ...\n @(x,y) sqrt(x.*y)};\ntypes = {'single', 'double', 'sparse'} ;\n\nfor simd = [0 1]\n for d = 1:length(dists)\n for t = 1:length(types)\n vl_simdctrl(simd) ;\n X = feval(str2func(types{t}), s.X) ;\n Y = feval(str2func(types{t}), s.Y) ;\n a = vl_alldist2(X,Y,dists{d}) ;\n b = makedist(distsEquiv{d},X,Y) ;\n vl_assert_almost_equal(a,b, ...\n 1e-4, ...\n 'alldist failed for dist=%s type=%s simd=%d', ...\n dists{d}, ...\n types{t}, ...\n simd) ;\n end\n end\nend\n\nfunction test_distance_kernel_pairs(s)\ndists = {'chi2', 'l2', 'l1', 'hell'} ;\nfor d = 1:length(dists)\n dist = char(dists{d}) ;\n X = s.X ;\n Y = s.Y ;\n ker = ['k' dist] ;\n kxx = vl_alldist2(X,X,ker) ;\n kyy = vl_alldist2(Y,Y,ker) ;\n kxy = vl_alldist2(X,Y,ker) ;\n kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;\n kyy = repmat(diag(kyy), 1, size(s.X,1))' ;\n d2 = vl_alldist2(X,Y,dist) ;\n vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;\nend\n\nfunction D = makedist(cmp,X,Y)\n[d,m] = size(X) ;\n[d,n] = size(Y) ;\nD = zeros(m,n) ;\nfor i = 1:m\n for j = 1:n\n acc = 0 ;\n for k = 1:d\n acc = acc + cmp(X(k,i),Y(k,j)) ;\n end\n D(i,j) = acc ;\n end\nend\nconv = str2func(class(X)) ;\nD = conv(D) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_fisher.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_fisher.m", "size": 2097, "source_encoding": "utf_8", "md5": "c9afd9ab635bd412cbf8be3c2d235f6b", "text": "function results = vl_test_fisher(varargin)\n% VL_TEST_FISHER\nvl_test_init ;\n\nfunction s = setup()\nrandn('state',0) ;\ndimension = 5 ;\nnumData = 21 ;\nnumComponents = 3 ;\ns.x = randn(dimension,numData) ;\ns.mu = randn(dimension,numComponents) ;\ns.sigma2 = ones(dimension,numComponents) ;\ns.prior = ones(1,numComponents) ;\ns.prior = s.prior / sum(s.prior) ;\n\nfunction test_basic(s)\nphi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;\nphi = vl_fisher(s.x, s.mu, s.sigma2, s.prior) ;\nvl_assert_almost_equal(phi, phi_, 1e-10) ;\n\nfunction test_norm(s)\nphi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;\nphi_ = phi_ / norm(phi_) ;\nphi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'normalized') ;\nvl_assert_almost_equal(phi, phi_, 1e-10) ;\n\nfunction test_sqrt(s)\nphi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;\nphi_ = sign(phi_) .* sqrt(abs(phi_)) ;\nphi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'squareroot') ;\nvl_assert_almost_equal(phi, phi_, 1e-10) ;\n\nfunction test_improved(s)\nphi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;\nphi_ = sign(phi_) .* sqrt(abs(phi_)) ;\nphi_ = phi_ / norm(phi_) ;\nphi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved') ;\nvl_assert_almost_equal(phi, phi_, 1e-10) ;\n\nfunction test_fast(s)\nphi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior, true) ;\nphi_ = sign(phi_) .* sqrt(abs(phi_)) ;\nphi_ = phi_ / norm(phi_) ;\nphi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved', 'fast') ;\nvl_assert_almost_equal(phi, phi_, 1e-10) ;\n\nfunction enc = simple_fisher(x, mu, sigma2, pri, fast)\nif nargin < 5, fast = false ; end\nsigma = sqrt(sigma2) ;\nfor k = 1:size(mu,2)\n delta{k} = bsxfun(@times, bsxfun(@minus, x, mu(:,k)), 1./sigma(:,k)) ;\n q(k,:) = log(pri(k)) - 0.5 * sum(log(sigma2(:,k))) - 0.5 * sum(delta{k}.^2,1) ;\nend\nq = exp(bsxfun(@minus, q, max(q,[],1))) ;\nq = bsxfun(@times, q, 1 ./ sum(q,1)) ;\nn = size(x,2) ;\nif fast\n [~,i] = max(q) ;\n q = zeros(size(q)) ;\n q(sub2ind(size(q),i,1:n)) = 1 ;\nend\nfor k = 1:size(mu,2)\n u{k} = delta{k} * q(k,:)' / n / sqrt(pri(k)) ;\n v{k} = (delta{k}.^2 - 1) * q(k,:)' / n / sqrt(2*pri(k)) ;\nend\nenc = cat(1, u{:}, v{:}) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_imsmooth.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_imsmooth.m", "size": 1837, "source_encoding": "utf_8", "md5": "718235242cad61c9804ba5e881c22f59", "text": "function results = vl_test_imsmooth(varargin)\n% VL_TEST_IMSMOOTH\nvl_test_init ;\n\nfunction s = setup()\nI = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;\nI = max(min(vl_imdown(I),1),0) ;\ns.I = single(I) ;\n\nfunction test_pad_by_continuity(s)\n% Convolving a constant signal padded with continuity does not change\n% the signal.\nI = ones(3) ;\nfor ker = {'triangular', 'gaussian'}\n ker = char(ker) ;\n J = vl_imsmooth(I, 2, ...\n 'kernel', ker, ...\n 'padding', 'continuity') ;\n vl_assert_almost_equal(J, I, 1e-4, ...\n 'padding by continutiy with kernel = %s', ker) ;\nend\n\nfunction test_kernels(s)\nfor ker = {'triangular', 'gaussian'}\n ker = char(ker) ;\n for type = {@single, @double}\n for simd = [0 1]\n for sigma = [1 2 7]\n for step = [1 2 3]\n vl_simdctrl(simd) ;\n conv = type{1} ;\n g = equivalent_kernel(ker, sigma) ;\n J = vl_imsmooth(conv(s.I), sigma, ...\n 'kernel', ker, ...\n 'padding', 'zero', ...\n 'subsample', step) ;\n J_ = conv(convolve(s.I, g, step)) ;\n vl_assert_almost_equal(J, J_, 1e-4, ...\n 'kernel=%s sigma=%f step=%d simd=%d', ...\n ker, sigma, step, simd) ;\n end\n end\n end\n end\nend\n\nfunction g = equivalent_kernel(ker, sigma)\nswitch ker\n case 'gaussian'\n W = ceil(4*sigma) ;\n g = exp(-.5*((-W:W)/(sigma+eps)).^2) ;\n case 'triangular'\n W = max(round(sigma),1) ;\n g = W - abs(-W+1:W-1) ;\nend\ng = g / sum(g) ;\n\nfunction I = convolve(I, g, step)\nif strcmp(class(I),'single')\n g = single(g) ;\nelse\n g = double(g) ;\nend\nfor k=1:size(I,3)\n I(:,:,k) = conv2(g,g,I(:,:,k),'same');\nend\nI = I(1:step:end,1:step:end,:) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_svmtrain.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_svmtrain.m", "size": 4277, "source_encoding": "utf_8", "md5": "071b7c66191a22e8236fda16752b27aa", "text": "function results = vl_test_svmtrain(varargin)\n% VL_TEST_SVMTRAIN\n vl_test_init ;\nend\n\nfunction s = setup()\n randn('state',0) ;\n Np = 10 ;\n Nn = 10 ;\n xp = diag([1 3])*randn(2, Np) ;\n xn = diag([1 3])*randn(2, Nn) ;\n xp(1,:) = xp(1,:) + 2 + 1 ;\n xn(1,:) = xn(1,:) - 2 + 1 ;\n\n s.x = [xp xn] ;\n s.y = [ones(1,Np) -ones(1,Nn)] ;\n s.lambda = 0.01 ;\n s.biasMultiplier = 10 ;\n\n if 0\n figure(1) ; clf;\n vl_plotframe(xp, 'g') ; hold on ;\n vl_plotframe(xn, 'r') ;\n axis equal ; grid on ;\n end\n\n % Run LibSVM as an accuate solver to compare results with. Note that\n % LibSVM optimizes a slightly different cost function due to the way\n % the bias is handled.\n % [s.w, s.b] = accurate_solver(s.x, s.y, s.lambda, s.biasMultiplier) ;\n s.w = [1.180762951236242; 0.098366470721632] ;\n s.b = -1.540018443946204 ;\n s.obj = obj(s, s.w, s.b) ;\nend\n\nfunction test_sgd_basic(s)\n for conv = {@single, @double}\n conv = conv{1} ;\n vl_twister('state',0) ;\n [w b info] = vl_svmtrain(s.x, s.y, s.lambda, ...\n 'Solver', 'sgd', ...\n 'BiasMultiplier', s.biasMultiplier, ...\n 'BiasLearningRate', 1/s.biasMultiplier, ...\n 'MaxNumIterations', 1e5, ...\n 'Epsilon', 1e-3) ;\n % there are no absolute guarantees on the objective gap, but\n % the heuristic SGD uses as stopping criterion seems reasonable\n % within a factor 10 at least.\n o = obj(s, w, b) ;\n gap = o - s.obj ;\n vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ;\n assert(gap <= 1e-2) ;\n end\nend\n\nfunction test_sdca_basic(s)\n for conv = {@single, @double}\n conv = conv{1} ;\n vl_twister('state',0) ;\n [w b info] = vl_svmtrain(s.x, s.y, s.lambda, ...\n 'Solver', 'sdca', ...\n 'BiasMultiplier', s.biasMultiplier, ...\n 'MaxNumIterations', 1e5, ...\n 'Epsilon', 1e-3) ;\n\n % the gap with the accurate solver cannot be\n % greater than the duality gap.\n o = obj(s, w, b) ;\n gap = o - s.obj ;\n vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ;\n assert(gap <= 1e-3) ;\n end\nend\n\nfunction test_weights(s)\n for algo = {'sgd', 'sdca'}\n for conv = {@single, @double}\n conv = conv{1} ;\n vl_twister('state',0) ;\n numRepeats = 10 ;\n pos = find(s.y > 0) ;\n neg = find(s.y < 0) ;\n weights = ones(1, numel(s.y)) ;\n weights(pos) = numRepeats ;\n\n % simulate weighting by repeating positives\n [w b info] = vl_svmtrain(...\n s.x(:, [repmat(pos,1,numRepeats) neg]), ...\n s.y(:, [repmat(pos,1,numRepeats) neg]), ...\n s.lambda / (numel(pos) *numRepeats + numel(neg)) / (numel(pos) + numel(neg)), ...\n 'Solver', 'sdca', ...\n 'BiasMultiplier', s.biasMultiplier, ...\n 'MaxNumIterations', 1e6, ...\n 'Epsilon', 1e-4) ;\n\n % apply weigthing\n [w_ b_ info_] = vl_svmtrain(...\n s.x, ...\n s.y, ...\n s.lambda, ...\n 'Solver', char(algo), ...\n 'BiasMultiplier', s.biasMultiplier, ...\n 'MaxNumIterations', 1e6, ...\n 'Epsilon', 1e-4, ...\n 'Weights', weights) ;\n vl_assert_almost_equal(conv([w; b]), conv([w_; b_]), 0.05) ;\n end\n end\nend\n\nfunction test_homkermap(s)\n for solver = {'sgd', 'sdca'}\n for conv = {@single,@double}\n conv = conv{1} ;\n dataset = vl_svmdataset(conv(s.x), 'homkermap', struct('order',1)) ;\n vl_twister('state',0) ;\n [w_ b_] = vl_svmtrain(dataset, s.y, s.lambda) ;\n\n x_hom = vl_homkermap(conv(s.x), 1) ;\n vl_twister('state',0) ;\n [w b] = vl_svmtrain(x_hom, s.y, s.lambda) ;\n vl_assert_almost_equal([w; b],[w_; b_], 1e-7) ;\n end\n end\nend\n\nfunction [w,b] = accurate_solver(X, y, lambda, biasMultiplier)\n addpath opt/libsvm/matlab/\n N = size(X,2) ;\n model = svmtrain(y', [(1:N)' X'*X], sprintf(' -c %f -t 4 -e 0.00001 ', 1/(lambda*N))) ;\n w = X(:,model.SVs) * model.sv_coef ;\n b = - model.rho ;\n format long ;\n disp('model w:')\n disp(w)\n disp('bias b:')\n disp(b)\nend\n\nfunction o = obj(s, w, b)\n o = (sum(w.*w) + b*b) * s.lambda / 2 + mean(max(0, 1 - s.y .* (w'*s.x + b))) ;\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_phow.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_phow.m", "size": 549, "source_encoding": "utf_8", "md5": "f761a3bb218af855986263c67b2da411", "text": "function results = vl_test_phow(varargin)\n% VL_TEST_PHOPW\nvl_test_init ;\n\nfunction s = setup()\ns.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;\ns.I = single(s.I) ;\n\nfunction test_gray(s)\n[f,d] = vl_phow(s.I, 'color', 'gray') ;\nassert(size(d,1) == 128) ;\n\nfunction test_rgb(s)\n[f,d] = vl_phow(s.I, 'color', 'rgb') ;\nassert(size(d,1) == 128*3) ;\n\nfunction test_hsv(s)\n[f,d] = vl_phow(s.I, 'color', 'hsv') ;\nassert(size(d,1) == 128*3) ;\n\nfunction test_opponent(s)\n[f,d] = vl_phow(s.I, 'color', 'opponent') ;\nassert(size(d,1) == 128*3) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_kmeans.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_kmeans.m", "size": 3632, "source_encoding": "utf_8", "md5": "0e1d6f4f8101c8982a0e743e0980c65a", "text": "function results = vl_test_kmeans(varargin)\n% VL_TEST_KMEANS\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nvl_test_init ;\n\nfunction s = setup()\nrandn('state',0) ;\ns.X = randn(128, 100) ;\n\nfunction test_basic(s)\n[centers, assignments, en] = vl_kmeans(s.X, 10, 'NumRepetitions', 10) ;\n[centers_, assignments_, en_] = simpleKMeans(s.X, 10) ;\nassert(en_ <= 1.1 * en, 'vl_kmeans did not optimize enough') ;\n\nfunction test_algorithms(s)\ndistances = {'l1', 'l2'} ;\ndataTypes = {'single','double'} ;\n\nfor dataType = dataTypes\n for distance = distances\n distance = char(distance) ;\n conversion = str2func(char(dataType)) ;\n X = conversion(s.X) ;\n vl_twister('state',0) ;\n [centers, assignments, en] = vl_kmeans(X, 10, ...\n 'NumRepetitions', 1, ...\n 'MaxNumIterations', 10, ...\n 'Algorithm', 'Lloyd', ...\n 'Distance', distance) ;\n vl_twister('state',0) ;\n [centers_, assignments_, en_] = vl_kmeans(X, 10, ...\n 'NumRepetitions', 1, ...\n 'MaxNumIterations', 10, ...\n 'Algorithm', 'Elkan', ...\n 'Distance', distance) ;\n\n vl_twister('state',0) ;\n [centers__, assignments__, en__] = vl_kmeans(X, 10, ...\n 'NumRepetitions', 1, ...\n 'MaxNumIterations', 10, ...\n 'Algorithm', 'ANN', ...\n 'Distance', distance, ...\n 'NumTrees', 3, ...\n 'MaxNumComparisons',0) ;\n\n vl_assert_almost_equal(centers, centers_, 1e-5) ;\n vl_assert_almost_equal(assignments, assignments_, 1e-5) ;\n vl_assert_almost_equal(en, en_, 1e-4) ;\n\n vl_assert_almost_equal(centers, centers__, 1e-5) ;\n vl_assert_almost_equal(assignments, assignments__, 1e-5) ;\n vl_assert_almost_equal(en, en__, 1e-4) ;\n\n vl_assert_almost_equal(centers_, centers__, 1e-5) ;\n vl_assert_almost_equal(assignments_, assignments__, 1e-5) ;\n vl_assert_almost_equal(en_, en__, 1e-4) ;\n end\nend\n\nfunction test_patterns(s)\ndistances = {'l1', 'l2'} ;\ndataTypes = {'single','double'} ;\nfor dataType = dataTypes\n for distance = distances\n distance = char(distance) ;\n conversion = str2func(char(dataType)) ;\n data = [1 1 0 0 ;\n 1 0 1 0] ;\n data = conversion(data) ;\n [centers, assignments, en] = vl_kmeans(data, 4, ...\n 'NumRepetitions', 100, ...\n 'Distance', distance) ;\n assert(isempty(setdiff(data', centers', 'rows'))) ;\n end\nend\n\nfunction [centers, assignments, en] = simpleKMeans(X, numCenters)\n[dimension, numData] = size(X) ;\ncenters = randn(dimension, numCenters) ;\n\nfor iter = 1:10\n [dists, assignments] = min(vl_alldist(centers, X)) ;\n en = sum(dists) ;\n centers = [zeros(dimension, numCenters) ; ones(1, numCenters)] ;\n centers = vl_binsum(centers, ...\n [X ; ones(1,numData)], ...\n repmat(assignments, dimension+1, 1), 2) ;\n centers = centers(1:end-1, :) ./ repmat(centers(end,:), dimension, 1) ;\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_hikmeans.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_hikmeans.m", "size": 463, "source_encoding": "utf_8", "md5": "dc3b493646e66316184e86ff4e6138ab", "text": "function results = vl_test_hikmeans(varargin)\n% VL_TEST_IKMEANS\nvl_test_init ;\n\nfunction s = setup()\nrand('state',0) ;\ns.data = uint8(rand(2,1000) * 255) ;\n\nfunction test_basic(s)\n[tree, assign] = vl_hikmeans(s.data,3,100) ;\nassign_ = vl_hikmeanspush(tree, s.data) ;\nvl_assert_equal(assign,assign_) ;\n\nfunction test_elkan(s)\n[tree, assign] = vl_hikmeans(s.data,3,100,'method','elkan') ;\nassign_ = vl_hikmeanspush(tree, s.data) ;\nvl_assert_equal(assign,assign_) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_aib.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_aib.m", "size": 1277, "source_encoding": "utf_8", "md5": "78978ae54e7ebe991d136336ba4bf9c6", "text": "function results = vl_test_aib(varargin)\n% VL_TEST_AIB\nvl_test_init ;\n\nfunction s = setup()\ns = [] ;\n\nfunction test_basic(s)\nPcx = [.3 .3 0 0\n 0 0 .2 .2] ;\n\n% This results in the AIB tree\n%\n% 1 - \\\n% 5 - \\\n% 2 - / \\\n% - 7\n% 3 - \\ /\n% 6 - /\n% 4 - /\n%\n% coded by the map [5 5 6 6 7 1] (1 denotes the root).\n\n[parents,cost] = vl_aib(Pcx) ;\nvl_assert_equal(parents, [5 5 6 6 7 7 1]) ;\nvl_assert_almost_equal(mi(Pcx)*[1 1 1], cost(1:3), 1e-3) ;\n\n[cut,map,short] = vl_aibcut(parents,2) ;\nvl_assert_equal(cut, [5 6]) ;\nvl_assert_equal(map, [1 1 2 2 1 2 0]) ;\nvl_assert_equal(short, [5 5 6 6 5 6 7]) ;\n\nfunction test_cluster_null(s)\nPcx = [.5 .5 0 0\n 0 0 0 0] ;\n\n% This results in the AIB tree\n%\n% 1 - \\\n% 5\n% 2 - /\n%\n% 3 x\n%\n% 4 x\n%\n% If ClusterNull is specified, the values 3 and 4\n% which have zero probability are merged first\n%\n% 1 ----------\\\n% 7\n% 2 ----- \\ /\n% 6-/\n% 3 -\\ /\n% 5 -/\n% 4 -/\n\nparents1 = vl_aib(Pcx) ;\nparents2 = vl_aib(Pcx,'ClusterNull') ;\nvl_assert_equal(parents1, [5 5 0 0 1 0 0]) ;\nvl_assert_equal(parents2(3), parents2(4)) ;\n\nfunction x = mi(P)\n% mutual information\nP1 = sum(P,1) ;\nP2 = sum(P,2) ;\nx = sum(sum(P .* log(max(P,1e-10) ./ (P2*P1)))) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_plotbox.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_plotbox.m", "size": 414, "source_encoding": "utf_8", "md5": "aa06ce4932a213fb933bbede6072b029", "text": "function results = vl_test_plotbox(varargin)\n% VL_TEST_PLOTBOX\nvl_test_init ;\n\nfunction test_basic(s)\nfigure(1) ; clf ;\nvl_plotbox([-1 -1 1 1]') ;\nxlim([-2 2]) ;\nylim([-2 2]) ;\nclose(1) ;\n\nfunction test_multiple(s)\nfigure(1) ; clf ;\nrandn('state', 0) ;\nvl_plotbox(randn(4,10)) ;\nclose(1) ;\n\nfunction test_style(s)\nfigure(1) ; clf ;\nrandn('state', 0) ;\nvl_plotbox(randn(4,10), 'r-.', 'LineWidth', 3) ;\nclose(1) ;\n\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_imarray.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_imarray.m", "size": 795, "source_encoding": "utf_8", "md5": "c5e6a5aa8c2e63e248814f5bd89832a8", "text": "function results = vl_test_imarray(varargin)\n% VL_TEST_IMARRAY\nvl_test_init ;\n\nfunction test_movie_rgb(s)\nA = rand(23,15,3,4) ;\nB = vl_imarray(A,'movie',true) ;\n\nfunction test_movie_indexed(s)\ncmap = get(0,'DefaultFigureColormap') ;\nA = uint8(size(cmap,1)*rand(23,15,4)) ;\nA = min(A,size(cmap,1)-1) ;\nB = vl_imarray(A,'movie',true) ;\n\nfunction test_movie_gray_indexed(s)\nA = uint8(255*rand(23,15,4)) ;\nB = vl_imarray(A,'movie',true,'cmap',gray(256)) ;\n\nfor k=1:size(A,3)\n vl_assert_equal(squeeze(A(:,:,k)), ...\n frame2im(B(k))) ;\nend\n\nfunction test_basic(s)\nM = 3 ;\nN = 4 ;\nwidth = 32 ;\nheight = 15 ;\nfor i=1:M\n for j=1:N\n A{i,j} = rand(width,height) ;\n end\nend\nA1 = A';\nA1 = cat(3,A1{:}) ;\nA2 = cell2mat(A) ;\nB = vl_imarray(A1, 'layout', [M N]) ;\nvl_assert_equal(A2,B) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_homkermap.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_homkermap.m", "size": 1903, "source_encoding": "utf_8", "md5": "c157052bf4213793a961bde1f73fb307", "text": "function results = vl_test_homkermap(varargin)\n% VL_TEST_HOMKERMAP\nvl_test_init ;\n\nfunction check_ker(ker, n, window, period)\nargs = {n, ker, 'window', window} ;\nif nargin > 3\n args = {args{:}, 'period', period} ;\nend\nx = [-1 -.5 0 .5 1] ;\ny = linspace(0,2,100) ;\nfor conv = {@single, @double}\n x = feval(conv{1}, x) ;\n y = feval(conv{1}, y) ;\n sx = sign(x) ;\n sy = sign(y) ;\n psix = vl_homkermap(x, args{:}) ;\n psiy = vl_homkermap(y, args{:}) ;\n k = vl_alldist(psix,psiy,'kl2') ;\n k_ = (sx'*sy) .* vl_alldist(sx.*x,sy.*y,ker) ;\n vl_assert_almost_equal(k, k_, 2e-2) ;\nend\n\nfunction test_uniform_kchi2(), check_ker('kchi2', 3, 'uniform', 15) ;\nfunction test_uniform_kjs(), check_ker('kjs', 3, 'uniform', 15) ;\nfunction test_uniform_kl1(), check_ker('kl1', 29, 'uniform', 15) ;\nfunction test_rect_kchi2(), check_ker('kchi2', 3, 'rectangular', 15) ;\nfunction test_rect_kjs(), check_ker('kjs', 3, 'rectangular', 15) ;\nfunction test_rect_kl1(), check_ker('kl1', 29, 'rectangular', 10) ;\nfunction test_auto_uniform_kchi2(),check_ker('kchi2', 3, 'uniform') ;\nfunction test_auto_uniform_kjs(), check_ker('kjs', 3, 'uniform') ;\nfunction test_auto_uniform_kl1(), check_ker('kl1', 25, 'uniform') ;\nfunction test_auto_rect_kchi2(), check_ker('kchi2', 3, 'rectangular') ;\nfunction test_auto_rect_kjs(), check_ker('kjs', 3, 'rectangular') ;\nfunction test_auto_rect_kl1(), check_ker('kl1', 25, 'rectangular') ;\n\nfunction test_gamma()\nx = linspace(0,1,20) ;\nfor gamma = linspace(.2,2,10)\n k = vl_alldist(x, 'kchi2') .* (x'*x + 1e-12).^((gamma-1)/2) ;\n psix = vl_homkermap(x, 3, 'kchi2', 'gamma', gamma) ;\n assert(norm(k - psix'*psix) < 1e-2) ;\nend\n\nfunction test_negative()\nx = linspace(-1,1,20) ;\nk = vl_alldist(abs(x), 'kchi2') .* (sign(x)'*sign(x)) ;\npsix = vl_homkermap(x, 3, 'kchi2') ;\nassert(norm(k - psix'*psix) < 1e-2) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_slic.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_slic.m", "size": 200, "source_encoding": "utf_8", "md5": "12a6465e3ef5b4bcfd7303cd8a9229d4", "text": "function results = vl_test_slic(varargin)\n% VL_TEST_SLIC\nvl_test_init ;\n\nfunction s = setup()\ns.im = im2single(vl_impattern('roofs1')) ;\n\nfunction test_slic(s)\nsegmentation = vl_slic(s.im, 10, 0.1) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_ikmeans.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_ikmeans.m", "size": 466, "source_encoding": "utf_8", "md5": "1ee2f647ac0035ed0d704a0cd615b040", "text": "function results = vl_test_ikmeans(varargin)\n% VL_TEST_IKMEANS\nvl_test_init ;\n\nfunction s = setup()\nrand('state',0) ;\ns.data = uint8(rand(2,1000) * 255) ;\n\nfunction test_basic(s)\n[centers, assign] = vl_ikmeans(s.data,100) ;\nassign_ = vl_ikmeanspush(s.data, centers) ;\nvl_assert_equal(assign,assign_) ;\n\nfunction test_elkan(s)\n[centers, assign] = vl_ikmeans(s.data,100,'method','elkan') ;\nassign_ = vl_ikmeanspush(s.data, centers) ;\nvl_assert_equal(assign,assign_) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_mser.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_mser.m", "size": 242, "source_encoding": "utf_8", "md5": "1ad33563b0c86542a2978ee94e0f4a39", "text": "function results = vl_test_mser(varargin)\n% VL_TEST_MSER\nvl_test_init ;\n\nfunction s = setup()\ns.im = im2uint8(rgb2gray(vl_impattern('roofs1'))) ;\n\nfunction test_mser(s)\n[regions,frames] = vl_mser(s.im) ;\nmask = vl_erfill(s.im, regions(1)) ;\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_inthist.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_inthist.m", "size": 811, "source_encoding": "utf_8", "md5": "459027d0c54d8f197563a02ab66ef45d", "text": "function results = vl_test_inthist(varargin)\n% VL_TEST_INTHIST\nvl_test_init ;\n\nfunction s = setup()\nrand('state',0) ;\ns.labels = uint32(8*rand(123, 76, 3)) ;\n\nfunction test_basic(s)\nl = 10 ;\nhist = vl_inthist(s.labels, 'numlabels', l) ;\nhist_ = inthist_slow(s.labels, l) ;\nvl_assert_equal(double(hist),hist_) ;\n\nfunction test_sample(s)\nrand('state',0) ;\nboxes = 10 * rand(4,20) + .5 ;\nboxes(3:4,:) = boxes(3:4,:) + boxes(1:2,:) ;\nboxes = min(boxes, 10) ;\nboxes = uint32(boxes) ;\ninthist = vl_inthist(s.labels) ;\nhist = vl_sampleinthist(inthist, boxes) ;\n\nfunction hist = inthist_slow(labels, numLabels)\nm = size(labels,1) ;\nn = size(labels,2) ;\nl = numLabels ;\nb = zeros(m*n,l) ;\nb = vl_binsum(b, 1, reshape(labels,m*n,[]), 2) ;\nb = reshape(b,m,n,l) ;\nfor k=1:l\n hist(:,:,k) = cumsum(cumsum(b(:,:,k)')') ;\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_imdisttf.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_imdisttf.m", "size": 1885, "source_encoding": "utf_8", "md5": "ae921197988abeb984cbcdf9eaf80e77", "text": "function results = vl_test_imdisttf(varargin)\n% VL_TEST_DISTTF\nvl_test_init ;\n\nfunction test_basic()\nfor conv = {@single, @double}\n conv = conv{1} ;\n\n I = conv([0 0 0 ; 0 -2 0 ; 0 0 0]) ;\n D = vl_imdisttf(I);\n assert(isequal(D, conv(- [0 1 0 ; 1 2 1 ; 0 1 0]))) ;\n\n I(2,2) = -3 ;\n [D,map] = vl_imdisttf(I) ;\n assert(isequal(D, conv(-1 - [0 1 0 ; 1 2 1 ; 0 1 0]))) ;\n assert(isequal(map, 5 * ones(3))) ;\nend\n\nfunction test_1x1()\nassert(isequal(1, vl_imdisttf(1))) ;\n\nfunction test_rand()\nI = rand(13,31) ;\nfor t=1:4\n param = [rand randn rand randn] ;\n [D0,map0] = imdisttf_equiv(I,param) ;\n [D,map] = vl_imdisttf(I,param) ;\n vl_assert_almost_equal(D,D0,1e-10)\n assert(isequal(map,map0)) ;\nend\n\nfunction test_param()\nI = zeros(3,4) ;\nI(1,1) = -1 ;\n\n[D,map] = vl_imdisttf(I,[1 0 1 0]);\nassert(isequal(-[1 0 0 0 ;\n 0 0 0 0 ;\n 0 0 0 0 ;], D)) ;\n\nD0 = -[1 .9 .6 .1 ;\n 0 0 0 0 ;\n 0 0 0 0 ;] ;\n[D,map] = vl_imdisttf(I,[.1 0 1 0]);\nvl_assert_almost_equal(D,D0,1e-10);\n\nD0 = -[1 .9 .6 .1 ;\n .9 .8 .5 0 ;\n .6 .5 .2 0 ;] ;\n[D,map] = vl_imdisttf(I,[.1 0 .1 0]);\nvl_assert_almost_equal(D,D0,1e-10);\n\nD0 = -[.9 1 .9 .6 ;\n .8 .9 .8 .5 ;\n .5 .6 .5 .2 ; ] ;\n[D,map] = vl_imdisttf(I,[.1 1 .1 0]);\nvl_assert_almost_equal(D,D0,1e-10);\n\nfunction test_special()\nI = rand(13,31) -.5 ;\nD = vl_imdisttf(I, [0 0 1e5 0]) ;\nvl_assert_almost_equal(D(:,1),min(I,[],2),1e-10);\nD = vl_imdisttf(I, [1e5 0 0 0]) ;\nvl_assert_almost_equal(D(1,:),min(I,[],1),1e-10);\n\nfunction [D,map]=imdisttf_equiv(I,param)\nD = inf + zeros(size(I)) ;\nmap = zeros(size(I)) ;\nur = 1:size(D,2) ;\nvr = 1:size(D,1) ;\n[u,v] = meshgrid(ur,vr) ;\nfor v_=vr\n for u_=ur\n E = I(v_,u_) + ...\n param(1) * (u - u_ - param(2)).^2 + ...\n param(3) * (v - v_ - param(4)).^2 ;\n map(E < D) = sub2ind(size(I),v_,u_) ;\n D = min(D,E) ;\n end\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_vlad.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_vlad.m", "size": 1977, "source_encoding": "utf_8", "md5": "d3797288d6edb1d445b890db3780c8ce", "text": "function results = vl_test_vlad(varargin)\n% VL_TEST_VLAD\nvl_test_init ;\n\nfunction s = setup()\nrandn('state',0) ;\ns.x = randn(128,256) ;\ns.mu = randn(128,16) ;\nassignments = rand(16, 256) ;\ns.assignments = bsxfun(@times, assignments, 1 ./ sum(assignments,1)) ;\n\nfunction test_basic (s)\nx = [1, 2, 3] ;\nmu = [0, 0, 0] ;\nassignments = eye(3) ;\nphi = vl_vlad(x, mu, assignments, 'unnormalized') ;\nvl_assert_equal(phi, [1 2 3]') ;\n\nmu = [0, 1, 2] ;\nphi = vl_vlad(x, mu, assignments, 'unnormalized') ;\nvl_assert_equal(phi, [1 1 1]') ;\nphi = vl_vlad([x x], mu, [assignments assignments], 'unnormalized') ;\nvl_assert_equal(phi, [2 2 2]') ;\n\nfunction test_rand (s)\nphi_ = simple_vlad(s.x, s.mu, s.assignments) ;\nphi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized') ;\nvl_assert_equal(phi, phi_) ;\n\nfunction test_norm (s)\nphi_ = simple_vlad(s.x, s.mu, s.assignments) ;\nphi_ = phi_ / norm(phi_) ;\nphi = vl_vlad(s.x, s.mu, s.assignments) ;\nvl_assert_almost_equal(phi, phi_, 1e-4) ;\n\nfunction test_sqrt (s)\nphi_ = simple_vlad(s.x, s.mu, s.assignments) ;\nphi_ = sign(phi_) .* sqrt(abs(phi_)) ;\nphi_ = phi_ / norm(phi_) ;\nphi = vl_vlad(s.x, s.mu, s.assignments, 'squareroot') ;\nvl_assert_almost_equal(phi, phi_, 1e-4) ;\n\nfunction test_individual (s)\nphi_ = simple_vlad(s.x, s.mu, s.assignments) ;\nphi_ = reshape(phi_, size(s.x,1), []) ;\nphi_ = bsxfun(@times, phi_, 1 ./ sqrt(sum(phi_.^2))) ;\nphi_ = phi_(:) ;\nphi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizecomponents') ;\nvl_assert_almost_equal(phi, phi_, 1e-4) ;\n\nfunction test_mass (s)\nphi_ = simple_vlad(s.x, s.mu, s.assignments) ;\nphi_ = reshape(phi_, size(s.x,1), []) ;\nphi_ = bsxfun(@times, phi_, 1 ./ sum(s.assignments,2)') ;\nphi_ = phi_(:) ;\nphi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizemass') ;\nvl_assert_almost_equal(phi, phi_, 1e-4) ;\n\nfunction enc = simple_vlad(x, mu, assign)\nfor i = 1:size(assign,1)\n enc{i} = x * assign(i,:)' - sum(assign(i,:)) * mu(:,i) ;\nend\nenc = cat(1, enc{:}) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_pr.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_pr.m", "size": 3763, "source_encoding": "utf_8", "md5": "4d1da5ccda1a7df2bec35b8f12fdd620", "text": "function results = vl_test_pr(varargin)\n% VL_TEST_PR\nvl_test_init ;\n\nfunction s = setup()\ns.scores0 = [5 4 3 2 1] ;\ns.scores1 = [5 3 4 2 1] ;\ns.labels = [1 1 -1 -1 -1] ;\n\nfunction test_perfect_tptn(s)\n[rc,pr] = vl_pr(s.labels,s.scores0) ;\nvl_assert_almost_equal(pr, [1 1/1 2/2 2/3 2/4 2/5]) ;\nvl_assert_almost_equal(rc, [0 1 2 2 2 2] / 2) ;\n\nfunction test_perfect_metrics(s)\n[rc,pr,info] = vl_pr(s.labels,s.scores0) ;\nvl_assert_almost_equal(info.auc, 1) ;\nvl_assert_almost_equal(info.ap, 1) ;\nvl_assert_almost_equal(info.ap_interp_11, 1) ;\n\nfunction test_swap1_tptn(s)\n[rc,pr] = vl_pr(s.labels,s.scores1) ;\nvl_assert_almost_equal(pr, [1 1/1 1/2 2/3 2/4 2/5]) ;\nvl_assert_almost_equal(rc, [0 1 1 2 2 2] / 2) ;\n\nfunction test_swap1_tptn_stable(s)\n[rc,pr] = vl_pr(s.labels,s.scores1,'stable',true) ;\nvl_assert_almost_equal(pr, [1/1 2/3 1/2 2/4 2/5]) ;\nvl_assert_almost_equal(rc, [1 2 1 2 2] / 2) ;\n\nfunction test_swap1_metrics(s)\n[rc,pr,info] = vl_pr(s.labels,s.scores1) ;\nclf; vl_pr(s.labels,s.scores1) ;\nvl_assert_almost_equal(info.auc, [.5 + .5 * (.5 + 2/3)/2]) ;\nvl_assert_almost_equal(info.ap, [1/1 + 2/3]/2) ;\nvl_assert_almost_equal(info.ap_interp_11, mean([1 1 1 1 1 1 2/3 2/3 2/3 2/3 2/3])) ;\n\nfunction test_inf(s)\nscores = [1 -inf -1 -1 -1 -1] ;\nlabels = [1 1 -1 -1 -1 -1] ;\n[rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true) ;\n[rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false) ;\n\nvl_assert_equal(numel(rc1), numel(rc2) + 1) ;\n\nvl_assert_almost_equal(info1.auc, [1 * .5 + (1/5 + 2/6)/2 * .5]) ;\nvl_assert_almost_equal(info1.ap, [1 * .5 + 2/6 * .5]) ;\nvl_assert_almost_equal(info1.ap_interp_11, [1 * 6/11 + 2/6 * 5/11]) ;\n\nvl_assert_almost_equal(info2.auc, 0.5) ;\nvl_assert_almost_equal(info2.ap, 0.5) ;\nvl_assert_almost_equal(info2.ap_interp_11, 1 * 6 / 11) ;\n\nfunction test_inf_stable(s)\nscores = [-1 -1 -1 -1 -inf +1] ;\nlabels = [-1 -1 -1 -1 +1 +1] ;\n[rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true, 'stable', true) ;\n[rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false, 'stable', true) ;\n[rc1_,pr1_,info1_] = vl_pr(labels, scores, 'includeInf', true, 'stable', false) ;\n[rc2_,pr2_,info2_] = vl_pr(labels, scores, 'includeInf', false, 'stable', false) ;\n\n% stability does not change scores\nvl_assert_almost_equal(info1,info1_) ;\nvl_assert_almost_equal(info2,info2_) ;\n\n% unstable with inf (first point (0,1) is conventional)\nvl_assert_almost_equal(rc1_, [0 .5 .5 .5 .5 .5 1])\nvl_assert_almost_equal(pr1_, [1 1 1/2 1/3 1/4 1/5 2/6])\n\n% unstable without inf\nvl_assert_almost_equal(rc2_, [0 .5 .5 .5 .5 .5])\nvl_assert_almost_equal(pr2_, [1 1 1/2 1/3 1/4 1/5])\n\n% stable with inf (no conventional point here)\nvl_assert_almost_equal(rc1, [.5 .5 .5 .5 1 .5]) ;\nvl_assert_almost_equal(pr1, [1/2 1/3 1/4 1/5 2/6 1]) ;\n\n% stable without inf (no conventional point and -inf are NaN)\nvl_assert_almost_equal(rc2, [.5 .5 .5 .5 NaN .5]) ;\nvl_assert_almost_equal(pr2, [1/2 1/3 1/4 1/5 NaN 1]) ;\n\nfunction test_normalised_pr(s)\nscores = [+1 +2] ;\nlabels = [+1 -1] ;\n[rc1,pr1,info1] = vl_pr(labels,scores) ;\n[rc2,pr2,info2] = vl_pr(labels,scores,'normalizePrior',.5) ;\nvl_assert_almost_equal(pr1, pr2) ;\nvl_assert_almost_equal(rc1, rc2) ;\n\nscores_ = [+1 +2 +2 +2] ;\nlabels_ = [+1 -1 -1 -1] ;\n[rc3,pr3,info3] = vl_pr(labels_,scores_) ;\n[rc4,pr4,info4] = vl_pr(labels,scores,'normalizePrior',1/4) ;\nvl_assert_almost_equal(info3, info4) ;\n\nfunction test_normalised_pr_corner_cases(s)\nscores = 1:10 ;\nlabels = ones(1,10) ;\n[rc1,pr1,info1] = vl_pr(labels,scores) ;\nvl_assert_almost_equal(rc1, (0:10)/10) ;\nvl_assert_almost_equal(pr1, ones(1,11)) ;\n\nscores = 1:10 ;\nlabels = zeros(1,10) ;\n[rc2,pr2,info2] = vl_pr(labels,scores) ;\nvl_assert_almost_equal(rc2, zeros(1,11)) ;\nvl_assert_almost_equal(pr2, ones(1,11)) ;\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_hog.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_hog.m", "size": 1555, "source_encoding": "utf_8", "md5": "eed7b2a116d142040587dc9c4eb7cd2e", "text": "function results = vl_test_hog(varargin)\n% VL_TEST_HOG\nvl_test_init ;\n\nfunction s = setup()\ns.im = im2single(vl_impattern('roofs1')) ;\n[x,y]= meshgrid(linspace(-1,1,128)) ;\ns.round = single(x.^2+y.^2);\ns.imSmall = s.im(1:128,1:128,:) ;\ns.imSmall = s.im ;\ns.imSmallFlipped = s.imSmall(:,end:-1:1,:) ;\n\nfunction test_basic_call(s)\ncellSize = 8 ;\nhog = vl_hog(s.im, cellSize) ;\n\nfunction test_bilinear_orientations(s)\ncellSize = 8 ;\nvl_hog(s.im, cellSize, 'bilinearOrientations') ;\n\nfunction test_variants_and_flipping(s)\nvariants = {'uoctti', 'dalaltriggs'} ;\nnumOrientationsRange = 3:9 ;\ncellSize = 8 ;\n\nfor cellSize = [4 8 16]\n for i=1:numel(variants)\n for j=1:numel(numOrientationsRange)\n args = {'bilinearOrientations', ...\n 'variant', variants{i}, ...\n 'numOrientations', numOrientationsRange(j)} ;\n hog = vl_hog(s.imSmall, cellSize, args{:}) ;\n perm = vl_hog('permutation', args{:}) ;\n hog1 = vl_hog(s.imSmallFlipped, cellSize, args{:}) ;\n hog2 = hog(:,end:-1:1,perm) ;\n %norm(hog1(:)-hog2(:))\n vl_assert_almost_equal(hog1,hog2,1e-3) ;\n end\n end\nend\n\nfunction test_polar(s)\ncellSize = 8 ;\nim = s.round ;\nfor b = [0 1]\n if b\n args = {'bilinearOrientations'} ;\n else\n args = {} ;\n end\n hog1 = vl_hog(im, cellSize, args{:}) ;\n [ix,iy] = vl_grad(im) ;\n m = sqrt(ix.^2 + iy.^2) ;\n a = atan2(iy,ix) ;\n m(:,[1 end]) = 0 ;\n m([1 end],:) = 0 ;\n hog2 = vl_hog(cat(3,m,a), cellSize, 'DirectedPolarField', args{:}) ;\n vl_assert_almost_equal(hog1,hog2,norm(hog1(:))/1000) ;\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_argparse.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_argparse.m", "size": 795, "source_encoding": "utf_8", "md5": "e72185b27206d0ee1dfdc19fe77a5be6", "text": "function results = vl_test_argparse(varargin)\n% VL_TEST_ARGPARSE\nvl_test_init ;\n\nfunction test_basic()\nopts.field1 = 1 ;\nopts.field2 = 2 ;\nopts.field3 = 3 ;\n\nopts_ = opts ;\nopts_.field1 = 3 ;\nopts_.field2 = 10 ;\n\nopts = vl_argparse(opts, {'field2', 10, 'field1', 3}) ;\nassert(isequal(opts, opts_)) ;\n\nopts_.field1 = 9 ;\nopts = vl_argparse(opts, {'field1', 4, 'field1', 9}) ;\nassert(isequal(opts, opts_)) ;\n\nfunction test_error()\nopts.field1 = 1 ;\ntry\n opts = vl_argparse(opts, {'field2', 5}) ;\ncatch e\n return ;\nend\nassert(false) ;\n\nfunction test_leftovers()\nopts1.field1 = 1 ;\nopts2.field2 = 1 ;\nopts1_.field1 = 2 ;\nopts2_.field2 = 2 ;\n\n[opts1,args] = vl_argparse(opts1, {'field1', 2, 'field2', 2}) ;\nopts2 = vl_argparse(opts2, args) ;\n\nassert(isequal(opts1,opts1_), isequal(opts2,opts2_)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_liop.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_liop.m", "size": 1023, "source_encoding": "utf_8", "md5": "a162be369073bed18e61210f44088cf3", "text": "function results = vl_test_liop(varargin)\n% VL_TEST_SIFT\nvl_test_init ;\n\nfunction s = setup()\nrandn('state',0) ;\ns.patch = randn(65,'single') ;\nxr = -32:32 ;\n[x,y] = meshgrid(xr) ;\ns.blob = - single(x.^2+y.^2) ;\n\nfunction test_basic(s)\nd = vl_liop(s.patch) ;\n\nfunction test_blob(s)\n% with a blob, all local intensity order pattern are equal. In\n% particular, if the blob intensity decreases away from the center,\n% then all local intensities sampled in a neighbourhood of 2 elements\n% are already sorted (see LIOP details).\nd = vl_liop(s.blob, ...\n 'IntensityThreshold', 0, ...\n 'NumNeighbours', 2, ...\n 'NumSpatialBins', 1) ;\nassert(isequal(d, single([1;0]))) ;\n\nfunction test_neighbours(s)\nfor n=2:5\n for p=1:3\n d = vl_liop(s.patch, 'NumNeighbours', n, 'NumSpatialBins', p) ;\n assert(numel(d) == p * factorial(n)) ;\n end\nend\n\nfunction test_multiple(s)\nx = randn(31,31,3, 'single') ;\nd = vl_liop(x) ;\nfor i=1:3\n d_(:,i) = vl_liop(squeeze(x(:,:,i))) ;\nend\nassert(isequal(d,d_)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_test_binsearch.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/xtest/vl_test_binsearch.m", "size": 1339, "source_encoding": "utf_8", "md5": "85dc020adce3f228fe7dfb24cf3acc63", "text": "function results = vl_test_binsearch(varargin)\n% VL_TEST_BINSEARCH\nvl_test_init ;\n\nfunction test_inf_bins()\nx = [-inf -1 0 1 +inf] ;\nvl_assert_equal(vl_binsearch([], x), [0 0 0 0 0]) ;\nvl_assert_equal(vl_binsearch([-inf 0], x), [1 1 2 2 2]) ;\nvl_assert_equal(vl_binsearch([-inf], x), [1 1 1 1 1]) ;\nvl_assert_equal(vl_binsearch([-inf +inf], x), [1 1 1 1 2]) ;\n\nfunction test_empty()\nvl_assert_equal(vl_binsearch([], []), []) ;\n\nfunction test_bnd()\nvl_assert_equal(vl_binsearch([], [1]), [0]) ;\nvl_assert_equal(vl_binsearch([], [-inf]), [0]) ;\nvl_assert_equal(vl_binsearch([], [+inf]), [0]) ;\n\nvl_assert_equal(vl_binsearch([1], [.9]), [0]) ;\nvl_assert_equal(vl_binsearch([1], [1]), [1]) ;\nvl_assert_equal(vl_binsearch([1], [-inf]), [0]) ;\nvl_assert_equal(vl_binsearch([1], [+inf]), [1]) ;\n\nfunction test_basic()\nvl_assert_equal(vl_binsearch(-10:10, -10:10), 1:21) ;\nvl_assert_equal(vl_binsearch(-10:10, -11:10), 0:21) ;\nvl_assert_equal(vl_binsearch(-10:10, [-inf, -11:10, +inf]), [0 0:21 21]) ;\n\nfunction test_frac()\nvl_assert_equal(vl_binsearch(1:10, 1:.5:10), floor(1:.5:10))\nvl_assert_equal(vl_binsearch(1:10, fliplr(1:.5:10)), ...\n fliplr(floor(1:.5:10))) ;\n\nfunction test_array()\na = reshape(1:100,10,10) ;\nb = reshape(1:.5:100.5, 2, []) ;\nc = floor(b) ;\nvl_assert_equal(vl_binsearch(a,b), c) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_roc.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/plotop/vl_roc.m", "size": 10113, "source_encoding": "utf_8", "md5": "22fd8ff455ee62a96ffd94b9074eafeb", "text": "function [tpr,tnr,info] = vl_roc(labels, scores, varargin)\n%VL_ROC ROC curve.\n% [TPR,TNR] = VL_ROC(LABELS, SCORES) computes the Receiver Operating\n% Characteristic (ROC) curve [1]. LABELS is a row vector of ground\n% truth labels, greater than zero for a positive sample and smaller\n% than zero for a negative one. SCORES is a row vector of\n% corresponding sample scores, usually obtained from a\n% classifier. The scores induce a ranking of the samples where\n% larger scores should correspond to positive labels.\n%\n% Without output arguments, the function plots the ROC graph of the\n% specified data in the current graphical axis.\n%\n% Otherwise, the function returns the true positive and true\n% negative rates TPR and TNR. These are vectors of the same size of\n% LABELS and SCORES and are computed as follows. Samples are ranked\n% by decreasing scores, starting from rank 1. TPR(K) and TNR(K) are\n% the true positive and true negative rates when samples of rank\n% smaller or equal to K-1 are predicted to be positive. So for\n% example TPR(3) is the true positive rate when the two samples with\n% largest score are predicted to be positive. Similarly, TPR(1) is\n% the true positive rate when no samples are predicted to be\n% positive, i.e. the constant 0.\n%\n% Setting a label to zero ignores the corresponding sample in the\n% calculations, as if the sample was removed from the data. Setting\n% the score of a sample to -INF causes the function to assume that\n% that sample was never retrieved. If there are samples with -INF\n% score, the ROC curve is incomplete as the maximum recall is less\n% than 1.\n%\n% [TPR,TNR,INFO] = VL_ROC(...) returns an additional structure INFO\n% with the following fields:\n%\n% info.auc:: Area under the ROC curve (AUC).\n% This is the area under the ROC plot, the parametric curve\n% (FPR(S), TPR(S)). The PLOT option can be used to plot variants\n% of this curve, which affects the calculation of a corresponding\n% AUC.\n%\n% info.eer:: Equal error rate (EER).\n% The equal error rate is the value of FPR (or FNR) when the ROC\n% curves intersects the line connecting (0,0) to (1,1).\n%\n% info.eerThreshold:: EER threshold.\n% The value of the score for which the EER is attained.\n%\n% VL_ROC() accepts the following options:\n%\n% Plot:: []\n% Setting this option turns on plotting unconditionally. The\n% following plot variants are supported:\n%\n% tntp:: Plot TPR against TNR (standard ROC plot).\n% tptn:: Plot TNR against TPR (recall on the horizontal axis).\n% fptp:: Plot TPR against FPR.\n% fpfn:: Plot FNR against FPR (similar to a DET curve).\n%\n% Note that this option will affect the INFO.AUC value computation\n% too.\n%\n% NumPositives:: []\n% NumNegatives:: []\n% If either of these parameters is set to a number, the function\n% pretends that LABELS contains the specified number of\n% positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be\n% smaller than the actual number of positive/negative entries in\n% LABELS. The additional positive/negative labels are appended to\n% the end of the sequence as if they had -INF scores (as explained\n% above, the function interprets such samples as `not\n% retrieved'). This feature can be used to evaluate the\n% performance of a large-scale retrieval experiment in which only\n% a subset of highly-scoring results are recorded for efficiency\n% reason.\n%\n% Stable:: false\n% If set to true, TPR and TNR are returned in the same order\n% of LABELS and SCORES rather than being sorted by decreasing\n% score.\n%\n% About the ROC curve::\n% Consider a classifier that predicts as positive all samples whose\n% score is not smaller than a threshold S. The ROC curve represents\n% the performance of such classifier as the threshold S is\n% changed. Formally, define\n%\n% P = overall num. of positive samples,\n% N = overall num. of negative samples,\n%\n% and for each threshold S\n%\n% TP(S) = num. of samples that are correctly classified as positive,\n% TN(S) = num. of samples that are correctly classified as negative,\n% FP(S) = num. of samples that are incorrectly classified as positive,\n% FN(S) = num. of samples that are incorrectly classified as negative.\n%\n% Consider also the rates:\n%\n% TPR = TP(S) / P, FNR = FN(S) / P,\n% TNR = TN(S) / N, FPR = FP(S) / N,\n%\n% and notice that, by definition,\n%\n% P = TP(S) + FN(S) , N = TN(S) + FP(S),\n% 1 = TPR(S) + FNR(S), 1 = TNR(S) + FPR(S).\n%\n% The ROC curve is the parametric curve (FPR(S), TPR(S)) obtained\n% as the classifier threshold S is varied in the reals. The TPR is\n% the same as `recall' in a PR curve (see VL_PR()).\n%\n% The ROC curve is contained in the square with vertices (0,0) The\n% (average) ROC curve of a random classifier is a line which\n% connects (1,0) and (0,1).\n%\n% The ROC curve is independent of the prior probability of the\n% labels (i.e. of P/(P+N) and N/(P+N)).\n%\n% REFERENCES:\n% [1] http://en.wikipedia.org/wiki/Receiver_operating_characteristic\n%\n% See also: VL_PR(), VL_DET(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n[tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ;\nopts.plot = [] ;\nopts.stable = false ;\nopts = vl_argparse(opts,varargin) ;\n\n% compute the rates\nsmall = 1e-10 ;\ntpr = tp / max(p, small) ;\nfpr = fp / max(n, small) ;\nfnr = 1 - tpr ;\ntnr = 1 - fpr ;\n\ndo_plots = ~isempty(opts.plot) || nargout == 0 ;\nif isempty(opts.plot), opts.plot = 'fptp' ; end\n\n% --------------------------------------------------------------------\n% Additional info\n% --------------------------------------------------------------------\n\nif nargout > 2 || do_plots\n % Area under the curve. Since the curve is a staircase (in the\n % sense that for each sample either tn is decremented by one\n % or tp is incremented by one but the other remains fixed),\n % the integral is particularly simple and exact.\n\n switch opts.plot\n case 'tntp', info.auc = -sum(tpr .* diff([0 tnr])) ;\n case 'fptp', info.auc = +sum(tpr .* diff([0 fpr])) ;\n case 'tptn', info.auc = +sum(tnr .* diff([0 tpr])) ;\n case 'fpfn', info.auc = +sum(fnr .* diff([0 fpr])) ;\n otherwise\n error('''%s'' is not a valid PLOT type.', opts.plot);\n end\n\n % Equal error rate. One must find the index S in correspondence of\n % which TNR(S) and TPR(s) cross. Note that TPR(S) is non-decreasing,\n % TNR(S) is non-increasing, and from rank S to rank S+1 only one of\n % the two quantities can change. Hence there are exactly two types\n % of crossing points:\n %\n % 1) TNR(S) = TNR(S+1) = EER and TPR(S) <= EER, TPR(S+1) > EER,\n % 2) TPR(S) = TPR(S+1) = EER and TNR(S) > EER, TNR(S+1) <= EER.\n %\n % Moreover, if the maximum TPR is smaller than 1, then it is\n % possible that neither of the two cases realizes. In the latter\n % case, we return EER=NaN.\n\n s = max(find(tnr > tpr)) ;\n if s == length(tpr)\n info.eer = NaN ;\n info.eerThreshold = 0 ;\n else\n if tpr(s) == tpr(s+1)\n info.eer = 1 - tpr(s) ;\n else\n info.eer = 1 - tnr(s) ;\n end\n info.eerThreshold = scores(perm(s)) ;\n end\nend\n\n% --------------------------------------------------------------------\n% Plot\n% --------------------------------------------------------------------\n\nif do_plots\n cla ; hold on ;\n switch lower(opts.plot)\n case 'tntp'\n hroc = plot(tnr, tpr, 'b', 'linewidth', 2) ;\n hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;\n spline([0 1], [0 1], 'k--', 'linewidth', 1) ;\n plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;\n xlabel('true negative rate') ;\n ylabel('true positive rate (recall)') ;\n loc = 'sw' ;\n\n case 'fptp'\n hroc = plot(fpr, tpr, 'b', 'linewidth', 2) ;\n hrand = spline([0 1], [0 1], 'r--', 'linewidth', 2) ;\n spline([1 0], [0 1], 'k--', 'linewidth', 1) ;\n plot(info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;\n xlabel('false positive rate') ;\n ylabel('true positive rate (recall)') ;\n loc = 'se' ;\n\n case 'tptn'\n hroc = plot(tpr, tnr, 'b', 'linewidth', 2) ;\n hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;\n spline([0 1], [0 1], 'k--', 'linewidth', 1) ;\n plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;\n xlabel('true positive rate (recall)') ;\n ylabel('false positive rate') ;\n loc = 'sw' ;\n\n case 'fpfn'\n hroc = plot(fpr, fnr, 'b', 'linewidth', 2) ;\n hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;\n spline([0 1], [0 1], 'k--', 'linewidth', 1) ;\n plot(info.eer, info.eer, 'k*', 'linewidth', 1) ;\n xlabel('false positive (false alarm) rate') ;\n ylabel('false negative (miss) rate') ;\n loc = 'ne' ;\n\n otherwise\n error('''%s'' is not a valid PLOT type.', opts.plot);\n end\n\n grid on ;\n xlim([0 1]) ;\n ylim([0 1]) ;\n axis square ;\n title(sprintf('ROC (AUC: %.2f%%, EER: %.2f%%)', info.auc * 100, info.eer * 100), ...\n 'interpreter', 'none') ;\n legend([hroc hrand], 'ROC', 'ROC rand.', 'location', loc) ;\nend\n\n% --------------------------------------------------------------------\n% Stable output\n% --------------------------------------------------------------------\n\nif opts.stable\n tpr(1) = [] ;\n tnr(1) = [] ;\n tpr_ = tpr ;\n tnr_ = tnr ;\n tpr = NaN(size(tpr)) ;\n tnr = NaN(size(tnr)) ;\n tpr(perm) = tpr_ ;\n tnr(perm) = tnr_ ;\nend\n\n% --------------------------------------------------------------------\nfunction h = spline(x,y,spec,varargin)\n% --------------------------------------------------------------------\nprop = vl_linespec2prop(spec) ;\nh = line(x,y,prop{:},varargin{:}) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_click.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/plotop/vl_click.m", "size": 2661, "source_encoding": "utf_8", "md5": "6982e869cf80da57fdf68f5ebcd05a86", "text": "function P = vl_click(N,varargin) ;\n% VL_CLICK Click a point\n% P=VL_CLICK() let the user click a point in the current figure and\n% returns its coordinates in P. P is a two dimensiona vectors where\n% P(1) is the point X-coordinate and P(2) the point Y-coordinate. The\n% user can abort the operation by pressing any key, in which case the\n% empty matrix is returned.\n%\n% P=VL_CLICK(N) lets the user select N points in a row. The user can\n% stop inserting points by pressing any key, in which case the\n% partial list is returned.\n%\n% VL_CLICK() accepts the following options:\n%\n% PlotMarker:: [0]\n% Plot a marker as points are selected. The markers are deleted on\n% exiting the function.\n%\n% See also: VL_CLICKPOINT(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nplot_marker = 0 ;\nfor k=1:2:length(varargin)\n switch lower(varargin{k})\n case 'plotmarker'\n plot_marker = varargin{k+1} ;\n otherwise\n error(['Uknown option ''', varargin{k}, '''.']) ;\n end\nend\n\nif nargin < 1\n N=1;\nend\n\n% --------------------------------------------------------------------\n% Do job\n% --------------------------------------------------------------------\n\nfig = gcf ;\n\nis_hold = ishold ;\nhold on ;\n\nbhandler = get(fig,'WindowButtonDownFcn') ;\nkhandler = get(fig,'KeyPressFcn') ;\npointer = get(fig,'Pointer') ;\n\nset(fig,'WindowButtonDownFcn',@click_handler) ;\nset(fig,'KeyPressFcn',@key_handler) ;\nset(fig,'Pointer','crosshair') ;\n\nP=[] ;\nh=[] ;\ndata.exit=0;\nguidata(fig,data) ;\nwhile size(P,2) < N\n uiwait(fig) ;\n data = guidata(fig) ;\n if(data.exit)\n break ;\n end\n P = [P data.P] ;\n if( plot_marker )\n h=[h plot(data.P(1),data.P(2),'rx')] ;\n end\nend\n\nif ~is_hold\n hold off ;\nend\n\nif( plot_marker )\n pause(.1);\n delete(h) ;\nend\n\nset(fig,'WindowButtonDownFcn',bhandler) ;\nset(fig,'KeyPressFcn',khandler) ;\nset(fig,'Pointer',pointer) ;\n\n% ====================================================================\nfunction click_handler(obj,event)\n% --------------------------------------------------------------------\ndata = guidata(gcbo) ;\n\nP = get(gca, 'CurrentPoint') ;\nP = [P(1,1); P(1,2)] ;\n\ndata.P = P ;\nguidata(obj,data) ;\nuiresume(gcbo) ;\n\n% ====================================================================\nfunction key_handler(obj,event)\n% --------------------------------------------------------------------\ndata = guidata(gcbo) ;\ndata.exit = 1 ;\nguidata(obj,data) ;\nuiresume(gcbo) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_pr.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/plotop/vl_pr.m", "size": 9138, "source_encoding": "utf_8", "md5": "c7fe6832d2b6b9917896810c52a05479", "text": "function [recall, precision, info] = vl_pr(labels, scores, varargin)\n%VL_PR Precision-recall curve.\n% [RECALL, PRECISION] = VL_PR(LABELS, SCORES) computes the\n% precision-recall (PR) curve. LABELS are the ground truth labels,\n% greather than zero for a positive sample and smaller than zero for\n% a negative one. SCORES are the scores of the samples obtained from\n% a classifier, where lager scores should correspond to positive\n% samples.\n%\n% Samples are ranked by decreasing scores, starting from rank 1.\n% PRECISION(K) and RECALL(K) are the precison and recall when\n% samples of rank smaller or equal to K-1 are predicted to be\n% positive and the remaining to be negative. So for example\n% PRECISION(3) is the percentage of positive samples among the two\n% samples with largest score. PRECISION(1) is the precision when no\n% samples are predicted to be positive and is conventionally set to\n% the value 1.\n%\n% Set to zero the lables of samples that should be ignored in the\n% evaluation. Set to -INF the scores of samples which are not\n% retrieved. If there are samples with -INF score, then the PR curve\n% may have maximum recall smaller than 1, unless the INCLUDEINF\n% option is used (see below). The options NUMNEGATIVES and\n% NUMPOSITIVES can be used to add additional surrogate samples with\n% -INF score (see below).\n%\n% [RECALL, PRECISION, INFO] = VL_PR(...) returns an additional\n% structure INFO with the following fields:\n%\n% info.auc::\n% The area under the precision-recall curve. If the INTERPOLATE\n% option is set to FALSE, then trapezoidal interpolation is used\n% to integrate the PR curve. If the INTERPOLATE option is set to\n% TRUE, then the curve is piecewise constant and no other\n% approximation is introduced in the calculation of the area. In\n% the latter case, INFO.AUC is the same as INFO.AP.\n%\n% info.ap::\n% Average precision as defined by TREC. This is the average of the\n% precision observed each time a new positive sample is\n% recalled. In this calculation, any sample with -INF score\n% (unless INCLUDEINF is used) and any additional positive induced\n% by NUMPOSITIVES has precision equal to zero. If the INTERPOLATE\n% option is set to true, the AP is computed from the interpolated\n% precision and the result is the same as INFO.AUC. Note that AP\n% as defined by TREC normally does not use interpolation [1].\n%\n% info.ap_interp_11::\n% 11-points interpolated average precision as defined by TREC.\n% This is the average of the maximum precision for recall levels\n% greather than 0.0, 0.1, 0.2, ..., 1.0. This measure was used in\n% the PASCAL VOC challenge up to the 2008 edition.\n%\n% info.auc_pa08::\n% Deprecated. It is the same of INFO.AP_INTERP_11.\n%\n% VL_PR(...) with no output arguments plots the PR curve in the\n% current axis.\n%\n% VL_PR() accepts the following options:\n%\n% Interpolate:: false\n% If set to true, use interpolated precision. The interpolated\n% precision is defined as the maximum precision for a given recall\n% level and onwards. Here it is implemented as the culumative\n% maximum from low to high scores of the precision.\n%\n% NumPositives:: []\n% NumNegatives:: []\n% If set to a number, pretend that LABELS contains this may\n% positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be\n% smaller than the actual number of positive/negative entrires in\n% LABELS. The additional positive/negative labels are appended to\n% the end of the sequence, as if they had -INF scores (not\n% retrieved). This is useful to evaluate large retrieval systems\n% for which one stores ony a handful of top results for efficiency\n% reasons.\n%\n% IncludeInf:: false\n% If set to true, data with -INF score SCORES is included in the\n% evaluation and the maximum recall is 1 even if -INF scores are\n% present. This option does not include any additional positive or\n% negative data introduced by specifying NUMPOSITIVES and\n% NUMNEGATIVES.\n%\n% Stable:: false\n% If set to true, RECALL and PRECISION are returned in the same order\n% of LABELS and SCORES rather than being sorted by decreasing\n% score (increasing recall). Samples with -INF scores are assigned\n% RECALL and PRECISION equal to NaN.\n%\n% NormalizePrior:: []\n% If set to a scalar, reweights positive and negative labels so\n% that the fraction of positive ones is equal to the specified\n% value. This computes the normalised PR curves of [2]\n%\n% About the PR curve::\n% This section uses the same symbols used in the documentation of\n% the VL_ROC() function. In addition to those quantities, define:\n%\n% PRECISION(S) = TP(S) / (TP(S) + FP(S))\n% RECALL(S) = TPR(S) = TP(S) / P\n%\n% The precision is the fraction of positivie predictions which are\n% correct, and the recall is the fraction of positive labels that\n% have been correctly classified (recalled). Notice that the recall\n% is also equal to the true positive rate for the ROC curve (see\n% VL_ROC()).\n%\n% REFERENCES:\n% [1] C. D. Manning, P. Raghavan, and H. Schutze. An Introduction to\n% Information Retrieval. Cambridge University Press, 2008.\n% [2] D. Hoiem, Y. Chodpathumwan, and Q. Dai. Diagnosing error in\n% object detectors. In Proc. ECCV, 2012.\n%\n% See also VL_ROC(), VL_HELP().\n\n% Author: Andrea Vedaldi\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% TP and FP are the vectors of true positie and false positve label\n% counts for decreasing scores, P and N are the total number of\n% positive and negative labels. Note that if certain options are used\n% some labels may actually not be stored explicitly by LABELS, so P+N\n% can be larger than the number of element of LABELS.\n\n[tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ;\nopts.stable = false ;\nopts.interpolate = false ;\nopts.normalizePrior = [] ;\nopts = vl_argparse(opts,varargin) ;\n\n% compute precision and recall\nsmall = 1e-10 ;\nrecall = tp / max(p, small) ;\nif isempty(opts.normalizePrior)\n precision = max(tp, small) ./ max(tp + fp, small) ;\nelse\n a = opts.normalizePrior ;\n precision = max(tp * a/max(p,small), small) ./ ...\n max(tp * a/max(p,small) + fp * (1-a)/max(n,small), small) ;\nend\n\n% interpolate precision if needed\nif opts.interpolate\n precision = fliplr(vl_cummax(fliplr(precision))) ;\nend\n\n% --------------------------------------------------------------------\n% Additional info\n% --------------------------------------------------------------------\n\nif nargout > 2 || nargout == 0\n\n % area under the curve using trapezoid interpolation\n if ~opts.interpolate\n info.auc = 0.5 * sum((precision(1:end-1) + precision(2:end)) .* diff(recall)) ;\n end\n\n % average precision (for each recalled positive sample)\n sel = find(diff(recall)) + 1 ;\n info.ap = sum(precision(sel)) / p ;\n if opts.interpolate\n info.auc = info.ap ;\n end\n\n % TREC 11 points average interpolated precision\n info.ap_interp_11 = 0.0 ;\n for rc = linspace(0,1,11)\n pr = max([0, precision(recall >= rc)]) ;\n info.ap_interp_11 = info.ap_interp_11 + pr / 11 ;\n end\n\n % legacy definition\n info.auc_pa08 = info.ap_interp_11 ;\nend\n\n% --------------------------------------------------------------------\n% Plot\n% --------------------------------------------------------------------\n\nif nargout == 0\n cla ; hold on ;\n plot(recall,precision,'linewidth',2) ;\n if isempty(opts.normalizePrior)\n randomPrecision = p / (p + n) ;\n else\n randomPrecision = opts.normalizePrior ;\n end\n spline([0 1], [1 1] * randomPrecision, 'r--', 'linewidth', 2) ;\n axis square ; grid on ;\n xlim([0 1]) ; xlabel('recall') ;\n ylim([0 1]) ; ylabel('precision') ;\n title(sprintf('PR (AUC: %.2f%%, AP: %.2f%%, AP11: %.2f%%)', ...\n info.auc * 100, ...\n info.ap * 100, ...\n info.ap_interp_11 * 100)) ;\n if opts.interpolate\n legend('PR interp.', 'PR rand.', 'Location', 'SouthEast') ;\n else\n legend('PR', 'PR rand.', 'Location', 'SouthEast') ;\n end\n clear recall precision info ;\nend\n\n% --------------------------------------------------------------------\n% Stable output\n% --------------------------------------------------------------------\n\nif opts.stable\n precision(1) = [] ;\n recall(1) = [] ;\n precision_ = precision ;\n recall_ = recall ;\n precision = NaN(size(precision)) ;\n recall = NaN(size(recall)) ;\n precision(perm) = precision_ ;\n recall(perm) = recall_ ;\nend\n\n% --------------------------------------------------------------------\nfunction h = spline(x,y,spec,varargin)\n% --------------------------------------------------------------------\nprop = vl_linespec2prop(spec) ;\nh = line(x,y,prop{:},varargin{:}) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_ubcread.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/sift/vl_ubcread.m", "size": 3015, "source_encoding": "utf_8", "md5": "e8ddd3ecd87e76b6c738ba153fef050f", "text": "function [f,d] = vl_ubcread(file, varargin)\n% SIFTREAD Read Lowe's SIFT implementation data files\n% [F,D] = VL_UBCREAD(FILE) reads the frames F and the descriptors D\n% from FILE in UBC (Lowe's original implementation of SIFT) format\n% and returns F and D as defined by VL_SIFT().\n%\n% VL_UBCREAD(FILE, 'FORMAT', 'OXFORD') assumes the format used by\n% Oxford VGG implementations .\n%\n% See also: VL_SIFT(), VL_HELP().\n\n% Authors: Andrea Vedaldi\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.verbosity = 0 ;\nopts.format = 'ubc' ;\nopts = vl_argparse(opts, varargin) ;\n\ng = fopen(file, 'r');\nif g == -1\n error(['Could not open file ''', file, '''.']) ;\nend\n[header, count] = fscanf(g, '%d', [1 2]) ;\nif count ~= 2\n error('Invalid keypoint file header.');\nend\nswitch opts.format\n case 'ubc'\n numKeypoints = header(1) ;\n descrLen = header(2) ;\n\n case 'oxford'\n numKeypoints = header(2) ;\n descrLen = header(1) ;\n\n otherwise\n error('Unknown format ''%s''.', opts.format) ;\nend\n\nif(opts.verbosity > 0)\n\tfprintf('%d keypoints, %d descriptor length.\\n', numKeypoints, descrLen) ;\nend\n\n%creates two output matrices\nswitch opts.format\n case 'ubc'\n P = zeros(4,numKeypoints) ;\n\n case 'oxford'\n P = zeros(5,numKeypoints) ;\nend\n\nL = zeros(descrLen, numKeypoints) ;\n\n%parse tmp.key\nfor k = 1:numKeypoints\n\n switch opts.format\n case 'ubc'\n % Record format: i,j,s,th\n [record, count] = fscanf(g, '%f', [1 4]) ;\n if count ~= 4\n error(...\n sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) );\n end\n P(:,k) = record(:) ;\n\n case 'oxford'\n % Record format: x, y, a, b, c such that x' [a b ; b c] x = 1\n [record, count] = fscanf(g, '%f', [1 5]) ;\n if count ~= 5\n error(...\n sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) );\n end\n P(:,k) = record(:) ;\n end\n\n\n\t% Record format: descriptor\n\t[record, count] = fscanf(g, '%d', [1 descrLen]) ;\n\tif count ~= descrLen\n\t\terror(...\n\t\t\tsprintf('Invalid keypoint file (parsing keypoint %d, descriptor part)',k) );\n\tend\n\tL(:,k) = record(:) ;\n\nend\nfclose(g) ;\n\nswitch opts.format\n case 'ubc'\n P(1:2,:) = flipud(P(1:2,:)) + 1 ; % i,j -> x,y\n\n f=[ P(1:2,:) ; P(3,:) ; -P(4,:) ] ;\n d=uint8(L) ;\n\n p=[1 2 3 4 5 6 7 8] ;\n q=[1 8 7 6 5 4 3 2] ;\n for j=0:3\n for i=0:3\n d(8*(i+4*j)+p,:) = d(8*(i+4*j)+q,:) ;\n end\n end\n\n case 'oxford'\n P(1:2,:) = P(1:2,:) + 1 ; % matlab origin\n f = P ;\n f(3:5,:) = inv2x2(f(3:5,:)) ;\n d = uint8(L) ;\nend\n\n\n% --------------------------------------------------------------------\nfunction S = inv2x2(C)\n% --------------------------------------------------------------------\n\nden = C(1,:) .* C(3,:) - C(2,:) .* C(2,:) ;\nS = [C(3,:) ; -C(2,:) ; C(1,:)] ./ den([1 1 1], :) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_frame2oell.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/sift/vl_frame2oell.m", "size": 2806, "source_encoding": "utf_8", "md5": "c93792632f630743485fa4c2cf12d647", "text": "function eframes = vl_frame2oell(frames)\n% VL_FRAMES2OELL Convert a geometric frame to an oriented ellipse\n% EFRAME = VL_FRAME2OELL(FRAME) converts the generic FRAME to an\n% oriented ellipses EFRAME. FRAME and EFRAME can be matrices, with\n% one frame per column.\n%\n% A frame is either a point, a disc, an oriented disc, an ellipse,\n% or an oriented ellipse. These are represented respectively by 2,\n% 3, 4, 5 and 6 parameters each, as described in VL_PLOTFRAME(). An\n% oriented ellipse is the most general geometric frame; hence, there\n% is no loss of information in this conversion.\n%\n% If FRAME is an oriented disc or ellipse, then the conversion is\n% immediate. If, however, FRAME is not oriented (it is either a\n% point or an unoriented disc or ellipse), then an orientation must\n% be assigned. The orientation is chosen in such a way that the\n% affine transformation that maps the standard oriented frame into\n% the output EFRAME does not rotate the Y axis. If frames represent\n% detected visual features, this convention corresponds to assume\n% that features are upright.\n%\n% If FRAME is a point, then the output is an ellipse with null area.\n%\n% See: feature frames,\n% VL_PLOTFRAME(), VL_HELP().\n\n% Author: Andrea Vedaldi\n\n% Copyright (C) 2013 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n[D,K] = size(frames) ;\neframes = zeros(6,K) ;\n\nswitch D\n case 2\n eframes(1:2,:) = frames(1:2,:) ;\n\n case 3\n eframes(1:2,:) = frames(1:2,:) ;\n eframes(3,:) = frames(3,:) ;\n eframes(6,:) = frames(3,:) ;\n\n case 4\n r = frames(3,:) ;\n c = r.*cos(frames(4,:)) ;\n s = r.*sin(frames(4,:)) ;\n\n eframes(1:2,:) = frames(1:2,:) ;\n eframes(3:6,:) = [c ; s ; -s ; c] ;\n\n case 5\n eframes(1:2,:) = frames(1:2,:) ;\n eframes(3:6,:) = mapFromS(frames(3:5,:)) ;\n\n case 6\n eframes = frames ;\n\n otherwise\n error('FRAMES format is unknown.') ;\nend\n\n% --------------------------------------------------------------------\nfunction A = mapFromS(S)\n% --------------------------------------------------------------------\n% Returns the (stacking of the) 2x2 matrix A that maps the unit circle\n% into the ellipses satisfying the equation x' inv(S) x = 1. Here S\n% is a stacked covariance matrix, with elements S11, S12 and S22.\n%\n% The goal is to find A such that AA' = S. In order to let the Y\n% direction unaffected (upright feature), the assumption is taht\n% A = [a b ; 0 c]. Hence\n%\n% AA' = [a^2, ab ; ab, b^2+c^2] = S.\n\nA = zeros(4,size(S,2)) ;\na = sqrt(S(1,:));\nb = S(2,:) ./ max(a, 1e-18) ;\n\nA(1,:) = a ;\nA(2,:) = b ;\nA(4,:) = sqrt(max(S(3,:) - b.*b, 0)) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_plotsiftdescriptor.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/toolbox/sift/vl_plotsiftdescriptor.m", "size": 5114, "source_encoding": "utf_8", "md5": "a4e125a8916653f00143b61cceda2f23", "text": "function h=vl_plotsiftdescriptor(d,f,varargin)\n% VL_PLOTSIFTDESCRIPTOR Plot SIFT descriptor\n% VL_PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptor D. If D is a\n% matrix, it plots one descriptor per column. D has the same format\n% used by VL_SIFT().\n%\n% VL_PLOTSIFTDESCRIPTOR(D,F) plots the SIFT descriptors warped to\n% the SIFT frames F, specified as columns of the matrix F. F has the\n% same format used by VL_SIFT().\n%\n% H=VL_PLOTSIFTDESCRIPTOR(...) returns the handle H to the line\n% drawing representing the descriptors.\n%\n% The function assumes that the SIFT descriptors use the standard\n% configuration of 4x4 spatial bins and 8 orientations bins. The\n% following parameters can be used to change this:\n%\n% NumSpatialBins:: 4\n% Number of spatial bins in both spatial directions X and Y.\n%\n% NumOrientationBins:: 8\n% Number of orientation bis.\n%\n% MagnificationFactor:: 3\n% Magnification factor. The width of one bin is equal to the scale\n% of the keypoint F multiplied by this factor.\n%\n% See also: VL_SIFT(), VL_PLOTFRAME(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.magnificationFactor = 3.0 ;\nopts.numSpatialBins = 4 ;\nopts.numOrientationBins = 8 ;\nopts.maxValue = 0 ;\n\nif nargin > 1\n if ~ isnumeric(f)\n error('F must be a numeric type (use [] to leave it unspecified)') ;\n end\nend\n\nopts = vl_argparse(opts, varargin) ;\n\n% --------------------------------------------------------------------\n% Check the arguments\n% --------------------------------------------------------------------\n\nif(size(d,1) ~= opts.numSpatialBins^2 * opts.numOrientationBins)\n error('The number of rows of D does not match the geometry of the descriptor') ;\nend\n\nif nargin > 1\n if (~isempty(f) & (size(f,1) < 2 | size(f,1) > 6))\n error('F must be either empty of have from 2 to six rows.');\n end\n\n if size(f,1) == 2\n % translation only\n f(3:6,:) = deal([10 0 0 10]') ;\n %f = [f; 10 * ones(1, size(f,2)) ; 0 * zeros(1, size(f,2))] ;\n end\n\n if size(f,1) == 3\n % translation and scale\n f(3:6,:) = [1 0 0 1]' * f(3,:) ;\n %f = [f; 0 * zeros(1, size(f,2))] ;\n end\n\n if size(f,1) == 4\n c = cos(f(4,:)) ;\n s = sin(f(4,:)) ;\n f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ;\n end\n\n if size(f,1) == 5\n assert(false) ;\n c = cos(f(4,:)) ;\n s = sin(f(4,:)) ;\n f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ;\n end\n\n if(~isempty(f) & size(f,2) ~= size(d,2))\n error('D and F have incompatible dimension') ;\n end\nend\n\n% Descriptors are often non-double numeric arrays\nd = double(d) ;\nK = size(d,2) ;\n\nif nargin < 2 | isempty(f)\n f = repmat([0;0;1;0;0;1],1,K) ;\nend\n\n% --------------------------------------------------------------------\n% Do the job\n% --------------------------------------------------------------------\n\nxall=[] ;\nyall=[] ;\n\nfor k=1:K\n [x,y] = render_descr(d(:,k), opts.numSpatialBins, opts.numOrientationBins, opts.maxValue) ;\n xall = [xall opts.magnificationFactor*f(3,k)*x + opts.magnificationFactor*f(5,k)*y + f(1,k)] ;\n yall = [yall opts.magnificationFactor*f(4,k)*x + opts.magnificationFactor*f(6,k)*y + f(2,k)] ;\nend\n\nh=line(xall,yall) ;\n\n% --------------------------------------------------------------------\nfunction [x,y] = render_descr(d, numSpatialBins, numOrientationBins, maxValue)\n% --------------------------------------------------------------------\n\n% Get the coordinates of the lines of the SIFT grid; each bin has side 1\n[x,y] = meshgrid(-numSpatialBins/2:numSpatialBins/2,-numSpatialBins/2:numSpatialBins/2) ;\n\n% Get the corresponding bin centers\nxc = x(1:end-1,1:end-1) + 0.5 ;\nyc = y(1:end-1,1:end-1) + 0.5 ;\n\n% Rescale the descriptor range so that the biggest peak fits inside the bin diagram\nif maxValue\n d = 0.4 * d / maxValue ;\nelse\n d = 0.4 * d / max(d(:)+eps) ;\nend\n\n% We scramble the the centers to have them in row major order\n% (descriptor convention).\nxc = xc' ;\nyc = yc' ;\n\n% Each spatial bin contains a star with numOrientationBins tips\nxc = repmat(xc(:)',numOrientationBins,1) ;\nyc = repmat(yc(:)',numOrientationBins,1) ;\n\n% Do the stars\nth=linspace(0,2*pi,numOrientationBins+1) ;\nth=th(1:end-1) ;\nxd = repmat(cos(th), 1, numSpatialBins*numSpatialBins) ;\nyd = repmat(sin(th), 1, numSpatialBins*numSpatialBins) ;\nxd = xd .* d(:)' ;\nyd = yd .* d(:)' ;\n\n% Re-arrange in sequential order the lines to draw\nnans = NaN * ones(1,numSpatialBins^2*numOrientationBins) ;\nx1 = xc(:)' ;\ny1 = yc(:)' ;\nx2 = x1 + xd ;\ny2 = y1 + yd ;\nxstars = [x1;x2;nans] ;\nystars = [y1;y2;nans] ;\n\n% Horizontal lines of the grid\nnans = NaN * ones(1,numSpatialBins+1);\nxh = [x(:,1)' ; x(:,end)' ; nans] ;\nyh = [y(:,1)' ; y(:,end)' ; nans] ;\n\n% Verical lines of the grid\nxv = [x(1,:) ; x(end,:) ; nans] ;\nyv = [y(1,:) ; y(end,:) ; nans] ;\n\nx=[xstars(:)' xh(:)' xv(:)'] ;\ny=[ystars(:)' yh(:)' yv(:)'] ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "phow_caltech101.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/apps/phow_caltech101.m", "size": 11594, "source_encoding": "utf_8", "md5": "7f4890a2e6844ca56debbfe23cca64f3", "text": "function phow_caltech101()\n% PHOW_CALTECH101 Image classification in the Caltech-101 dataset\n% This program demonstrates how to use VLFeat to construct an image\n% classifier on the Caltech-101 data. The classifier uses PHOW\n% features (dense SIFT), spatial histograms of visual words, and a\n% Chi2 SVM. To speedup computation it uses VLFeat fast dense SIFT,\n% kd-trees, and homogeneous kernel map. The program also\n% demonstrates VLFeat PEGASOS SVM solver, although for this small\n% dataset other solvers such as LIBLINEAR can be more efficient.\n%\n% By default 15 training images are used, which should result in\n% about 64% performance (a good performance considering that only a\n% single feature type is being used).\n%\n% Call PHOW_CALTECH101 to train and test a classifier on a small\n% subset of the Caltech-101 data. Note that the program\n% automatically downloads a copy of the Caltech-101 data from the\n% Internet if it cannot find a local copy.\n%\n% Edit the PHOW_CALTECH101 file to change the program configuration.\n%\n% To run on the entire dataset change CONF.TINYPROBLEM to FALSE.\n%\n% The Caltech-101 data is saved into CONF.CALDIR, which defaults to\n% 'data/caltech-101'. Change this path to the desired location, for\n% instance to point to an existing copy of the Caltech-101 data.\n%\n% The program can also be used to train a model on custom data by\n% pointing CONF.CALDIR to it. Just create a subdirectory for each\n% class and put the training images there. Make sure to adjust\n% CONF.NUMTRAIN accordingly.\n%\n% Intermediate files are stored in the directory CONF.DATADIR. All\n% such files begin with the prefix CONF.PREFIX, which can be changed\n% to test different parameter settings without overriding previous\n% results.\n%\n% The program saves the trained model in\n% /-model.mat. This model can be used to\n% test novel images independently of the Caltech data.\n%\n% load('data/baseline-model.mat') ; # change to the model path\n% label = model.classify(model, im) ;\n%\n\n% Author: Andrea Vedaldi\n\n% Copyright (C) 2011-2013 Andrea Vedaldi\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nconf.calDir = 'data/caltech-101' ;\nconf.dataDir = 'data/' ;\nconf.autoDownloadData = true ;\nconf.numTrain = 15 ;\nconf.numTest = 15 ;\nconf.numClasses = 102 ;\nconf.numWords = 600 ;\nconf.numSpatialX = [2 4] ;\nconf.numSpatialY = [2 4] ;\nconf.quantizer = 'kdtree' ;\nconf.svm.C = 10 ;\n\nconf.svm.solver = 'sdca' ;\n%conf.svm.solver = 'sgd' ;\n%conf.svm.solver = 'liblinear' ;\n\nconf.svm.biasMultiplier = 1 ;\nconf.phowOpts = {'Step', 3} ;\nconf.clobber = false ;\nconf.tinyProblem = true ;\nconf.prefix = 'baseline' ;\nconf.randSeed = 1 ;\n\nif conf.tinyProblem\n conf.prefix = 'tiny' ;\n conf.numClasses = 5 ;\n conf.numSpatialX = 2 ;\n conf.numSpatialY = 2 ;\n conf.numWords = 300 ;\n conf.phowOpts = {'Verbose', 2, 'Sizes', 7, 'Step', 5} ;\nend\n\nconf.vocabPath = fullfile(conf.dataDir, [conf.prefix '-vocab.mat']) ;\nconf.histPath = fullfile(conf.dataDir, [conf.prefix '-hists.mat']) ;\nconf.modelPath = fullfile(conf.dataDir, [conf.prefix '-model.mat']) ;\nconf.resultPath = fullfile(conf.dataDir, [conf.prefix '-result']) ;\n\nrandn('state',conf.randSeed) ;\nrand('state',conf.randSeed) ;\nvl_twister('state',conf.randSeed) ;\n\n% --------------------------------------------------------------------\n% Download Caltech-101 data\n% --------------------------------------------------------------------\n\nif ~exist(conf.calDir, 'dir') || ...\n (~exist(fullfile(conf.calDir, 'airplanes'),'dir') && ...\n ~exist(fullfile(conf.calDir, '101_ObjectCategories', 'airplanes')))\n if ~conf.autoDownloadData\n error(...\n ['Caltech-101 data not found. ' ...\n 'Set conf.autoDownloadData=true to download the required data.']) ;\n end\n vl_xmkdir(conf.calDir) ;\n calUrl = ['http://www.vision.caltech.edu/Image_Datasets/' ...\n 'Caltech101/101_ObjectCategories.tar.gz'] ;\n fprintf('Downloading Caltech-101 data to ''%s''. This will take a while.', conf.calDir) ;\n untar(calUrl, conf.calDir) ;\nend\n\nif ~exist(fullfile(conf.calDir, 'airplanes'),'dir')\n conf.calDir = fullfile(conf.calDir, '101_ObjectCategories') ;\nend\n\n% --------------------------------------------------------------------\n% Setup data\n% --------------------------------------------------------------------\nclasses = dir(conf.calDir) ;\nclasses = classes([classes.isdir]) ;\nclasses = {classes(3:conf.numClasses+2).name} ;\n\nimages = {} ;\nimageClass = {} ;\nfor ci = 1:length(classes)\n ims = dir(fullfile(conf.calDir, classes{ci}, '*.jpg'))' ;\n ims = vl_colsubset(ims, conf.numTrain + conf.numTest) ;\n ims = cellfun(@(x)fullfile(classes{ci},x),{ims.name},'UniformOutput',false) ;\n images = {images{:}, ims{:}} ;\n imageClass{end+1} = ci * ones(1,length(ims)) ;\nend\nselTrain = find(mod(0:length(images)-1, conf.numTrain+conf.numTest) < conf.numTrain) ;\nselTest = setdiff(1:length(images), selTrain) ;\nimageClass = cat(2, imageClass{:}) ;\n\nmodel.classes = classes ;\nmodel.phowOpts = conf.phowOpts ;\nmodel.numSpatialX = conf.numSpatialX ;\nmodel.numSpatialY = conf.numSpatialY ;\nmodel.quantizer = conf.quantizer ;\nmodel.vocab = [] ;\nmodel.w = [] ;\nmodel.b = [] ;\nmodel.classify = @classify ;\n\n% --------------------------------------------------------------------\n% Train vocabulary\n% --------------------------------------------------------------------\n\nif ~exist(conf.vocabPath) || conf.clobber\n\n % Get some PHOW descriptors to train the dictionary\n selTrainFeats = vl_colsubset(selTrain, 30) ;\n descrs = {} ;\n %for ii = 1:length(selTrainFeats)\n parfor ii = 1:length(selTrainFeats)\n im = imread(fullfile(conf.calDir, images{selTrainFeats(ii)})) ;\n im = standarizeImage(im) ;\n [drop, descrs{ii}] = vl_phow(im, model.phowOpts{:}) ;\n end\n\n descrs = vl_colsubset(cat(2, descrs{:}), 10e4) ;\n descrs = single(descrs) ;\n\n % Quantize the descriptors to get the visual words\n vocab = vl_kmeans(descrs, conf.numWords, 'verbose', 'algorithm', 'elkan', 'MaxNumIterations', 50) ;\n save(conf.vocabPath, 'vocab') ;\nelse\n load(conf.vocabPath) ;\nend\n\nmodel.vocab = vocab ;\n\nif strcmp(model.quantizer, 'kdtree')\n model.kdtree = vl_kdtreebuild(vocab) ;\nend\n\n% --------------------------------------------------------------------\n% Compute spatial histograms\n% --------------------------------------------------------------------\n\nif ~exist(conf.histPath) || conf.clobber\n hists = {} ;\n parfor ii = 1:length(images)\n % for ii = 1:length(images)\n fprintf('Processing %s (%.2f %%)\\n', images{ii}, 100 * ii / length(images)) ;\n im = imread(fullfile(conf.calDir, images{ii})) ;\n hists{ii} = getImageDescriptor(model, im);\n end\n\n hists = cat(2, hists{:}) ;\n save(conf.histPath, 'hists') ;\nelse\n load(conf.histPath) ;\nend\n\n% --------------------------------------------------------------------\n% Compute feature map\n% --------------------------------------------------------------------\n\npsix = vl_homkermap(hists, 1, 'kchi2', 'gamma', .5) ;\n\n% --------------------------------------------------------------------\n% Train SVM\n% --------------------------------------------------------------------\n\nif ~exist(conf.modelPath) || conf.clobber\n switch conf.svm.solver\n case {'sgd', 'sdca'}\n lambda = 1 / (conf.svm.C * length(selTrain)) ;\n w = [] ;\n parfor ci = 1:length(classes)\n perm = randperm(length(selTrain)) ;\n fprintf('Training model for class %s\\n', classes{ci}) ;\n y = 2 * (imageClass(selTrain) == ci) - 1 ;\n [w(:,ci) b(ci) info] = vl_svmtrain(psix(:, selTrain(perm)), y(perm), lambda, ...\n 'Solver', conf.svm.solver, ...\n 'MaxNumIterations', 50/lambda, ...\n 'BiasMultiplier', conf.svm.biasMultiplier, ...\n 'Epsilon', 1e-3);\n end\n\n case 'liblinear'\n svm = train(imageClass(selTrain)', ...\n sparse(double(psix(:,selTrain))), ...\n sprintf(' -s 3 -B %f -c %f', ...\n conf.svm.biasMultiplier, conf.svm.C), ...\n 'col') ;\n w = svm.w(:,1:end-1)' ;\n b = svm.w(:,end)' ;\n end\n\n model.b = conf.svm.biasMultiplier * b ;\n model.w = w ;\n\n save(conf.modelPath, 'model') ;\nelse\n load(conf.modelPath) ;\nend\n\n% --------------------------------------------------------------------\n% Test SVM and evaluate\n% --------------------------------------------------------------------\n\n% Estimate the class of the test images\nscores = model.w' * psix + model.b' * ones(1,size(psix,2)) ;\n[drop, imageEstClass] = max(scores, [], 1) ;\n\n% Compute the confusion matrix\nidx = sub2ind([length(classes), length(classes)], ...\n imageClass(selTest), imageEstClass(selTest)) ;\nconfus = zeros(length(classes)) ;\nconfus = vl_binsum(confus, ones(size(idx)), idx) ;\n\n% Plots\nfigure(1) ; clf;\nsubplot(1,2,1) ;\nimagesc(scores(:,[selTrain selTest])) ; title('Scores') ;\nset(gca, 'ytick', 1:length(classes), 'yticklabel', classes) ;\nsubplot(1,2,2) ;\nimagesc(confus) ;\ntitle(sprintf('Confusion matrix (%.2f %% accuracy)', ...\n 100 * mean(diag(confus)/conf.numTest) )) ;\nprint('-depsc2', [conf.resultPath '.ps']) ;\nsave([conf.resultPath '.mat'], 'confus', 'conf') ;\n\n% -------------------------------------------------------------------------\nfunction im = standarizeImage(im)\n% -------------------------------------------------------------------------\n\nim = im2single(im) ;\nif size(im,1) > 480, im = imresize(im, [480 NaN]) ; end\n\n% -------------------------------------------------------------------------\nfunction hist = getImageDescriptor(model, im)\n% -------------------------------------------------------------------------\n\nim = standarizeImage(im) ;\nwidth = size(im,2) ;\nheight = size(im,1) ;\nnumWords = size(model.vocab, 2) ;\n\n% get PHOW features\n[frames, descrs] = vl_phow(im, model.phowOpts{:}) ;\n\n% quantize local descriptors into visual words\nswitch model.quantizer\n case 'vq'\n [drop, binsa] = min(vl_alldist(model.vocab, single(descrs)), [], 1) ;\n case 'kdtree'\n binsa = double(vl_kdtreequery(model.kdtree, model.vocab, ...\n single(descrs), ...\n 'MaxComparisons', 50)) ;\nend\n\nfor i = 1:length(model.numSpatialX)\n binsx = vl_binsearch(linspace(1,width,model.numSpatialX(i)+1), frames(1,:)) ;\n binsy = vl_binsearch(linspace(1,height,model.numSpatialY(i)+1), frames(2,:)) ;\n\n % combined quantization\n bins = sub2ind([model.numSpatialY(i), model.numSpatialX(i), numWords], ...\n binsy,binsx,binsa) ;\n hist = zeros(model.numSpatialY(i) * model.numSpatialX(i) * numWords, 1) ;\n hist = vl_binsum(hist, ones(size(bins)), bins) ;\n hists{i} = single(hist / sum(hist)) ;\nend\nhist = cat(1,hists{:}) ;\nhist = hist / sum(hist) ;\n\n% -------------------------------------------------------------------------\nfunction [className, score] = classify(model, im)\n% -------------------------------------------------------------------------\n\nhist = getImageDescriptor(model, im) ;\npsix = vl_homkermap(hist, 1, 'kchi2', 'gamma', .5) ;\nscores = model.w' * psix + model.b' ;\n[score, best] = max(scores) ;\nclassName = model.classes{best} ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "sift_mosaic.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/apps/sift_mosaic.m", "size": 4621, "source_encoding": "utf_8", "md5": "8fa3ad91b401b8f2400fb65944c79712", "text": "function mosaic = sift_mosaic(im1, im2)\n% SIFT_MOSAIC Demonstrates matching two images using SIFT and RANSAC\n%\n% SIFT_MOSAIC demonstrates matching two images based on SIFT\n% features and RANSAC and computing their mosaic.\n%\n% SIFT_MOSAIC by itself runs the algorithm on two standard test\n% images. Use SIFT_MOSAIC(IM1,IM2) to compute the mosaic of two\n% custom images IM1 and IM2.\n\n% AUTORIGHTS\n\nif nargin == 0\n im1 = imread(fullfile(vl_root, 'data', 'river1.jpg')) ;\n im2 = imread(fullfile(vl_root, 'data', 'river2.jpg')) ;\nend\n\n% make single\nim1 = im2single(im1) ;\nim2 = im2single(im2) ;\n\n% make grayscale\nif size(im1,3) > 1, im1g = rgb2gray(im1) ; else im1g = im1 ; end\nif size(im2,3) > 1, im2g = rgb2gray(im2) ; else im2g = im2 ; end\n\n% --------------------------------------------------------------------\n% SIFT matches\n% --------------------------------------------------------------------\n\n[f1,d1] = vl_sift(im1g) ;\n[f2,d2] = vl_sift(im2g) ;\n\n[matches, scores] = vl_ubcmatch(d1,d2) ;\n\nnumMatches = size(matches,2) ;\n\nX1 = f1(1:2,matches(1,:)) ; X1(3,:) = 1 ;\nX2 = f2(1:2,matches(2,:)) ; X2(3,:) = 1 ;\n\n% --------------------------------------------------------------------\n% RANSAC with homography model\n% --------------------------------------------------------------------\n\nclear H score ok ;\nfor t = 1:100\n % estimate homograpyh\n subset = vl_colsubset(1:numMatches, 4) ;\n A = [] ;\n for i = subset\n A = cat(1, A, kron(X1(:,i)', vl_hat(X2(:,i)))) ;\n end\n [U,S,V] = svd(A) ;\n H{t} = reshape(V(:,9),3,3) ;\n\n % score homography\n X2_ = H{t} * X1 ;\n du = X2_(1,:)./X2_(3,:) - X2(1,:)./X2(3,:) ;\n dv = X2_(2,:)./X2_(3,:) - X2(2,:)./X2(3,:) ;\n ok{t} = (du.*du + dv.*dv) < 6*6 ;\n score(t) = sum(ok{t}) ;\nend\n\n[score, best] = max(score) ;\nH = H{best} ;\nok = ok{best} ;\n\n% --------------------------------------------------------------------\n% Optional refinement\n% --------------------------------------------------------------------\n\nfunction err = residual(H)\n u = H(1) * X1(1,ok) + H(4) * X1(2,ok) + H(7) ;\n v = H(2) * X1(1,ok) + H(5) * X1(2,ok) + H(8) ;\n d = H(3) * X1(1,ok) + H(6) * X1(2,ok) + 1 ;\n du = X2(1,ok) - u ./ d ;\n dv = X2(2,ok) - v ./ d ;\n err = sum(du.*du + dv.*dv) ;\nend\n\nif exist('fminsearch') == 2\n H = H / H(3,3) ;\n opts = optimset('Display', 'none', 'TolFun', 1e-8, 'TolX', 1e-8) ;\n H(1:8) = fminsearch(@residual, H(1:8)', opts) ;\nelse\n warning('Refinement disabled as fminsearch was not found.') ;\nend\n\n% --------------------------------------------------------------------\n% Show matches\n% --------------------------------------------------------------------\n\ndh1 = max(size(im2,1)-size(im1,1),0) ;\ndh2 = max(size(im1,1)-size(im2,1),0) ;\n\nfigure(1) ; clf ;\nsubplot(2,1,1) ;\nimagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ;\no = size(im1,2) ;\nline([f1(1,matches(1,:));f2(1,matches(2,:))+o], ...\n [f1(2,matches(1,:));f2(2,matches(2,:))]) ;\ntitle(sprintf('%d tentative matches', numMatches)) ;\naxis image off ;\n\nsubplot(2,1,2) ;\nimagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ;\no = size(im1,2) ;\nline([f1(1,matches(1,ok));f2(1,matches(2,ok))+o], ...\n [f1(2,matches(1,ok));f2(2,matches(2,ok))]) ;\ntitle(sprintf('%d (%.2f%%) inliner matches out of %d', ...\n sum(ok), ...\n 100*sum(ok)/numMatches, ...\n numMatches)) ;\naxis image off ;\n\ndrawnow ;\n\n% --------------------------------------------------------------------\n% Mosaic\n% --------------------------------------------------------------------\n\nbox2 = [1 size(im2,2) size(im2,2) 1 ;\n 1 1 size(im2,1) size(im2,1) ;\n 1 1 1 1 ] ;\nbox2_ = inv(H) * box2 ;\nbox2_(1,:) = box2_(1,:) ./ box2_(3,:) ;\nbox2_(2,:) = box2_(2,:) ./ box2_(3,:) ;\nur = min([1 box2_(1,:)]):max([size(im1,2) box2_(1,:)]) ;\nvr = min([1 box2_(2,:)]):max([size(im1,1) box2_(2,:)]) ;\n\n[u,v] = meshgrid(ur,vr) ;\nim1_ = vl_imwbackward(im2double(im1),u,v) ;\n\nz_ = H(3,1) * u + H(3,2) * v + H(3,3) ;\nu_ = (H(1,1) * u + H(1,2) * v + H(1,3)) ./ z_ ;\nv_ = (H(2,1) * u + H(2,2) * v + H(2,3)) ./ z_ ;\nim2_ = vl_imwbackward(im2double(im2),u_,v_) ;\n\nmass = ~isnan(im1_) + ~isnan(im2_) ;\nim1_(isnan(im1_)) = 0 ;\nim2_(isnan(im2_)) = 0 ;\nmosaic = (im1_ + im2_) ./ mass ;\n\nfigure(2) ; clf ;\nimagesc(mosaic) ; axis image off ;\ntitle('Mosaic') ;\n\nif nargout == 0, clear mosaic ; end\n\nend\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "encodeImage.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/apps/recognition/encodeImage.m", "size": 5278, "source_encoding": "utf_8", "md5": "5d9dc6161995b8e10366b5649bf4fda4", "text": "function descrs = encodeImage(encoder, im, varargin)\n% ENCODEIMAGE Apply an encoder to an image\n% DESCRS = ENCODEIMAGE(ENCODER, IM) applies the ENCODER\n% to image IM, returning a corresponding code vector PSI.\n%\n% IM can be an image, the path to an image, or a cell array of\n% the same, to operate on multiple images.\n%\n% ENCODEIMAGE(ENCODER, IM, CACHE) utilizes the specified CACHE\n% directory to store encodings for the given images. The cache\n% is used only if the images are specified as file names.\n%\n% See also: TRAINENCODER().\n\n% Author: Andrea Vedaldi\n\n% Copyright (C) 2013 Andrea Vedaldi\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.cacheDir = [] ;\nopts.cacheChunkSize = 512 ;\nopts = vl_argparse(opts,varargin) ;\n\nif ~iscell(im), im = {im} ; end\n\n% break the computation into cached chunks\nstartTime = tic ;\ndescrs = cell(1, numel(im)) ;\nnumChunks = ceil(numel(im) / opts.cacheChunkSize) ;\n\nfor c = 1:numChunks\n n = min(opts.cacheChunkSize, numel(im) - (c-1)*opts.cacheChunkSize) ;\n chunkPath = fullfile(opts.cacheDir, sprintf('chunk-%03d.mat',c)) ;\n if ~isempty(opts.cacheDir) && exist(chunkPath)\n fprintf('%s: loading descriptors from %s\\n', mfilename, chunkPath) ;\n load(chunkPath, 'data') ;\n else\n range = (c-1)*opts.cacheChunkSize + (1:n) ;\n fprintf('%s: processing a chunk of %d images (%3d of %3d, %5.1fs to go)\\n', ...\n mfilename, numel(range), ...\n c, numChunks, toc(startTime) / (c - 1) * (numChunks - c + 1)) ;\n data = processChunk(encoder, im(range)) ;\n if ~isempty(opts.cacheDir)\n save(chunkPath, 'data') ;\n end\n end\n descrs{c} = data ;\n clear data ;\nend\ndescrs = cat(2,descrs{:}) ;\n\n% --------------------------------------------------------------------\nfunction psi = processChunk(encoder, im)\n% --------------------------------------------------------------------\npsi = cell(1,numel(im)) ;\nif numel(im) > 1 & matlabpool('size') > 1\n parfor i = 1:numel(im)\n psi{i} = encodeOne(encoder, im{i}) ;\n end\nelse\n % avoiding parfor makes debugging easier\n for i = 1:numel(im)\n psi{i} = encodeOne(encoder, im{i}) ;\n end\nend\npsi = cat(2, psi{:}) ;\n\n% --------------------------------------------------------------------\nfunction psi = encodeOne(encoder, im)\n% --------------------------------------------------------------------\n\nim = encoder.readImageFn(im) ;\n\nfeatures = encoder.extractorFn(im) ;\n\nimageSize = size(im) ;\npsi = {} ;\nfor i = 1:size(encoder.subdivisions,2)\n minx = encoder.subdivisions(1,i) * imageSize(2) ;\n miny = encoder.subdivisions(2,i) * imageSize(1) ;\n maxx = encoder.subdivisions(3,i) * imageSize(2) ;\n maxy = encoder.subdivisions(4,i) * imageSize(1) ;\n\n ok = ...\n minx <= features.frame(1,:) & features.frame(1,:) < maxx & ...\n miny <= features.frame(2,:) & features.frame(2,:) < maxy ;\n\n descrs = encoder.projection * bsxfun(@minus, ...\n features.descr(:,ok), ...\n encoder.projectionCenter) ;\n if encoder.renormalize\n descrs = bsxfun(@times, descrs, 1./max(1e-12, sqrt(sum(descrs.^2)))) ;\n end\n\n w = size(im,2) ;\n h = size(im,1) ;\n frames = features.frame(1:2,:) ;\n frames = bsxfun(@times, bsxfun(@minus, frames, [w;h]/2), 1./[w;h]) ;\n\n descrs = extendDescriptorsWithGeometry(encoder.geometricExtension, frames, descrs) ;\n\n switch encoder.type\n case 'bovw'\n [words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ...\n descrs, ...\n 'MaxComparisons', 100) ;\n z = vl_binsum(zeros(encoder.numWords,1), 1, double(words)) ;\n z = sqrt(z) ;\n\n case 'fv'\n z = vl_fisher(descrs, ...\n encoder.means, ...\n encoder.covariances, ...\n encoder.priors, ...\n 'Improved') ;\n case 'vlad'\n [words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ...\n descrs, ...\n 'MaxComparisons', 15) ;\n assign = zeros(encoder.numWords, numel(words), 'single') ;\n assign(sub2ind(size(assign), double(words), 1:numel(words))) = 1 ;\n z = vl_vlad(descrs, ...\n encoder.words, ...\n assign, ...\n 'SquareRoot', ...\n 'NormalizeComponents') ;\n end\n z = z / max(sqrt(sum(z.^2)), 1e-12) ;\n psi{i} = z(:) ;\nend\npsi = cat(1, psi{:}) ;\n\n% --------------------------------------------------------------------\nfunction psi = getFromCache(name, cache)\n% --------------------------------------------------------------------\n[drop, name] = fileparts(name) ;\ncachePath = fullfile(cache, [name '.mat']) ;\nif exist(cachePath, 'file')\n data = load(cachePath) ;\n psi = data.psi ;\nelse\n psi = [] ;\nend\n\n% --------------------------------------------------------------------\nfunction storeToCache(name, cache, psi)\n% --------------------------------------------------------------------\n[drop, name] = fileparts(name) ;\ncachePath = fullfile(cache, [name '.mat']) ;\nvl_xmkdir(cache) ;\ndata.psi = psi ;\nsave(cachePath, '-STRUCT', 'data') ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "experiments.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/apps/recognition/experiments.m", "size": 6905, "source_encoding": "utf_8", "md5": "1e4a4911eed4a451b9488b9e6cc9b39c", "text": "function experiments()\n% EXPERIMENTS Run image classification experiments\n% The experimens download a number of benchmark datasets in the\n% 'data/' subfolder. Make sure that there are several GBs of\n% space available.\n%\n% By default, experiments run with a lite option turned on. This\n% quickly runs all of them on tiny subsets of the actual data.\n% This is used only for testing; to run the actual experiments,\n% set the lite variable to false.\n%\n% Running all the experiments is a slow process. Using parallel\n% MATLAB and several cores/machiens is suggested.\n\n% Author: Andrea Vedaldi\n\n% Copyright (C) 2013 Andrea Vedaldi\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nlite = true ;\nclear ex ;\n\nex(1).prefix = 'fv-aug' ;\nex(1).trainOpts = {'C', 10} ;\nex(1).datasets = {'fmd', 'scene67'} ;\nex(1).seed = 1 ;\nex(1).opts = {...\n 'type', 'fv', ...\n 'numWords', 256, ...\n 'layouts', {'1x1'}, ...\n 'geometricExtension', 'xy', ...\n 'numPcaDimensions', 80, ...\n 'extractorFn', @(x) getDenseSIFT(x, ...\n 'step', 4, ...\n 'scales', 2.^(1:-.5:-3))};\n\nex(2) = ex(1) ;\nex(2).datasets = {'caltech101'} ;\nex(2).opts{end} = @(x) getDenseSIFT(x, ...\n 'step', 4, ...\n 'scales', 2.^(0:-.5:-3)) ;\n\nex(3) = ex(1) ;\nex(3).datasets = {'voc07'} ;\nex(3).C = 1 ;\n\nex(4) = ex(1) ;\nex(4).prefix = 'vlad-aug' ;\nex(4).opts = {...\n 'type', 'vlad', ...\n 'numWords', 256, ...\n 'layouts', {'1x1'}, ...\n 'geometricExtension', 'xy', ...\n 'numPcaDimensions', 100, ...\n 'whitening', true, ...\n 'whiteningRegul', 0.01, ...\n 'renormalize', true, ...\n 'extractorFn', @(x) getDenseSIFT(x, ...\n 'step', 4, ...\n 'scales', 2.^(1:-.5:-3))};\nex(5) = ex(4) ;\nex(5).datasets = {'caltech101'} ;\nex(5).opts{end} = ex(2).opts{end} ;\n\nex(6) = ex(4) ;\nex(6).datasets = {'voc07'} ;\nex(6).C = 1 ;\n\nex(7) = ex(1) ;\nex(7).prefix = 'bovw-aug' ;\nex(7).opts = {...\n 'type', 'bovw', ...\n 'numWords', 4096, ...\n 'layouts', {'1x1'}, ...\n 'geometricExtension', 'xy', ...\n 'numPcaDimensions', 100, ...\n 'whitening', true, ...\n 'whiteningRegul', 0.01, ...\n 'renormalize', true, ...\n 'extractorFn', @(x) getDenseSIFT(x, ...\n 'step', 4, ...\n 'scales', 2.^(1:-.5:-3))};\n\nex(8) = ex(7) ;\nex(8).datasets = {'caltech101'} ;\nex(8).opts{end} = ex(2).opts{end} ;\n\nex(9) = ex(7) ;\nex(9).datasets = {'voc07'} ;\nex(9).C = 1 ;\n\nex(10).prefix = 'fv' ;\nex(10).trainOpts = {'C', 10} ;\nex(10).datasets = {'fmd', 'scene67'} ;\nex(10).seed = 1 ;\nex(10).opts = {...\n 'type', 'fv', ...\n 'numWords', 256, ...\n 'layouts', {'1x1'}, ...\n 'geometricExtension', 'none', ...\n 'numPcaDimensions', 80, ...\n 'extractorFn', @(x) getDenseSIFT(x, ...\n 'step', 4, ...\n 'scales', 2.^(1:-.5:-3))};\n\nex(11) = ex(10) ;\nex(11).datasets = {'caltech101'} ;\nex(11).opts{end} = @(x) getDenseSIFT(x, ...\n 'step', 4, ...\n 'scales', 2.^(0:-.5:-3)) ;\n\nex(12) = ex(10) ;\nex(12).datasets = {'voc07'} ;\nex(12).C = 1 ;\n\n\nex(13).prefix = 'fv-sp' ;\nex(13).trainOpts = {'C', 10} ;\nex(13).datasets = {'fmd', 'scene67'} ;\nex(13).seed = 1 ;\nex(13).opts = {...\n 'type', 'fv', ...\n 'numWords', 256, ...\n 'layouts', {'1x1', '3x1'}, ...\n 'geometricExtension', 'none', ...\n 'numPcaDimensions', 80, ...\n 'extractorFn', @(x) getDenseSIFT(x, ...\n 'step', 4, ...\n 'scales', 2.^(1:-.5:-3))};\n\nex(14) = ex(13) ;\nex(14).datasets = {'caltech101'} ;\nex(14).opts{6} = {'1x1', '2x2'} ;\nex(14).opts{end} = @(x) getDenseSIFT(x, ...\n 'step', 4, ...\n 'scales', 2.^(0:-.5:-3)) ;\n\nex(15) = ex(13) ;\nex(15).datasets = {'voc07'} ;\nex(15).C = 1 ;\n\n\nif lite, tag = 'lite' ;\nelse, tag = 'ex' ; end\n\nfor i=1:numel(ex)\n for j=1:numel(ex(i).datasets)\n dataset = ex(i).datasets{j} ;\n if ~isfield(ex(i), 'trainOpts') || ~iscell(ex(i).trainOpts)\n ex(i).trainOpts = {} ;\n end\n traintest(...\n 'prefix', [tag '-' dataset '-' ex(i).prefix], ...\n 'seed', ex(i).seed, ...\n 'dataset', char(dataset), ...\n 'datasetDir', fullfile('data', dataset), ...\n 'lite', lite, ...\n ex(i).trainOpts{:}, ...\n 'encoderParams', ex(i).opts) ;\n end\nend\n\n% print HTML table\npf('\\n') ;\nph('method', 'VOC07', 'Caltech 101', 'Scene 67', 'FMD') ;\npr('FV', ...\n ge([tag '-voc07-fv'],'ap11'), ...\n ge([tag '-caltech101-fv']), ...\n ge([tag '-scene67-fv']), ...\n ge([tag '-fmd-fv'])) ;\npr('FV + aug.', ...\n ge([tag '-voc07-fv-aug'],'ap11'), ...\n ge([tag '-caltech101-fv-aug']), ...\n ge([tag '-scene67-fv-aug']), ...\n ge([tag '-fmd-fv-aug'])) ;\npr('FV + s.p.', ...\n ge([tag '-voc07-fv-sp'],'ap11'), ...\n ge([tag '-caltech101-fv-sp']), ...\n ge([tag '-scene67-fv-sp']), ...\n ge([tag '-fmd-fv-sp'])) ;\n%pr('VLAD', ...\n% ge([tag '-voc07-vlad'],'ap11'), ...\n% ge([tag '-caltech101-vlad']), ...\n% ge([tag '-scene67-vlad']), ...\n% ge([tag '-fmd-vlad'])) ;\npr('VLAD + aug.', ...\n ge([tag '-voc07-vlad-aug'],'ap11'), ...\n ge([tag '-caltech101-vlad-aug']), ...\n ge([tag '-scene67-vlad-aug']), ...\n ge([tag '-fmd-vlad-aug'])) ;\n%pr('VLAD+sp', ...\n% ge([tag '-voc07-vlad-sp'],'ap11'), ...\n% ge([tag '-caltech101-vlad-sp']), ...\n% ge([tag '-scene67-vlad-sp']), ...\n% ge([tag '-fmd-vlad-sp'])) ;\n%pr('BOVW', ...\n% ge([tag '-voc07-bovw'],'ap11'), ...\n% ge([tag '-caltech101-bovw']), ...\n% ge([tag '-scene67-bovw']), ...\n% ge([tag '-fmd-bovw'])) ;\npr('BOVW + aug.', ...\n ge([tag '-voc07-bovw-aug'],'ap11'), ...\n ge([tag '-caltech101-bovw-aug']), ...\n ge([tag '-scene67-bovw-aug']), ...\n ge([tag '-fmd-bovw-aug'])) ;\n%pr('BOVW+sp', ...\n% ge([tag '-voc07-bovw-sp'],'ap11'), ...\n% ge([tag '-caltech101-bovw-sp']), ...\n% ge([tag '-scene67-bovw-sp']), ...\n% ge([tag '-fmd-bovw-sp'])) ;\npf('
\\n');\n\nfunction pf(str)\nfprintf(str) ;\n\nfunction str = ge(name, format)\nif nargin == 1, format = 'acc'; end\ndata = load(fullfile('data', name, 'result.mat')) ;\nswitch format\n case 'acc'\n str = sprintf('%.2f%% Acc', mean(diag(data.confusion)) * 100) ;\n case 'ap11'\n str = sprintf('%.2f%% mAP', mean(data.ap11) * 100) ;\nend\n\nfunction pr(varargin)\nfprintf('') ;\nfor i=1:numel(varargin), fprintf('%s',varargin{i}) ; end\nfprintf('\\n') ;\n\nfunction ph(varargin)\nfprintf('') ;\nfor i=1:numel(varargin), fprintf('%s',varargin{i}) ; end\nfprintf('\\n') ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "getDenseSIFT.m", "ext": ".m", "path": "2015_Face_Detection-master/vlfeat/apps/recognition/getDenseSIFT.m", "size": 1679, "source_encoding": "utf_8", "md5": "2059c0a2a4e762226d89121408c6e51c", "text": "function features = getDenseSIFT(im, varargin)\n% GETDENSESIFT Extract dense SIFT features\n% FEATURES = GETDENSESIFT(IM) extract dense SIFT features from\n% image IM.\n\n% Author: Andrea Vedaldi\n\n% Copyright (C) 2013 Andrea Vedaldi\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.scales = logspace(log10(1), log10(.25), 5) ;\nopts.contrastthreshold = 0 ;\nopts.step = 3 ;\nopts.rootSift = false ;\nopts.normalizeSift = true ;\nopts.binSize = 8 ;\nopts.geometry = [4 4 8] ;\nopts.sigma = 0 ;\nopts = vl_argparse(opts, varargin) ;\n\ndsiftOpts = {'norm', 'fast', 'floatdescriptors', ...\n 'step', opts.step, ...\n 'size', opts.binSize, ...\n 'geometry', opts.geometry} ;\n\nif size(im,3)>1, im = rgb2gray(im) ; end\nim = im2single(im) ;\nim = vl_imsmooth(im, opts.sigma) ;\n\nfor si = 1:numel(opts.scales)\n im_ = imresize(im, opts.scales(si)) ;\n\n [frames{si}, descrs{si}] = vl_dsift(im_, dsiftOpts{:}) ;\n\n % root SIFT\n if opts.rootSift\n descrs{si} = sqrt(descrs{si}) ;\n end\n if opts.normalizeSift\n descrs{si} = snorm(descrs{si}) ;\n end\n\n % zero low contrast descriptors\n info.contrast{si} = frames{si}(3,:) ;\n kill = info.contrast{si} < opts.contrastthreshold ;\n descrs{si}(:,kill) = 0 ;\n\n % store frames\n frames{si}(1:2,:) = (frames{si}(1:2,:)-1) / opts.scales(si) + 1 ;\n frames{si}(3,:) = opts.binSize / opts.scales(si) / 3 ;\nend\n\nfeatures.frame = cat(2, frames{:}) ;\nfeatures.descr = cat(2, descrs{:}) ;\nfeatures.contrast = cat(2, info.contrast{:}) ;\n\nfunction x = snorm(x)\nx = bsxfun(@times, x, 1./max(1e-5,sqrt(sum(x.^2,1)))) ;\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_argparse.m", "ext": ".m", "path": "2015_Face_Detection-master/matlab/vl_argparse.m", "size": 3148, "source_encoding": "utf_8", "md5": "74459d2b851e027208bd7ca9ea999037", "text": "function [opts, args] = vl_argparse(opts, args)\n% VL_ARGPARSE Parse list of parameter-value pairs\n% OPTS = VL_ARGPARSE(OPTS, ARGS) updates the structure OPTS based on\n% the specified parameter-value pairs ARGS={PAR1, VAL1, ... PARN,\n% VALN}. The function produces an error if an unknown parameter name\n% is passed on. Values that are structures are copied recursively.\n%\n% Any of the PAR, VAL pairs can be replaced by a structure; in this\n% case, the fields of the structure are used as paramaters and the\n% field values as values.\n%\n% [OPTS, ARGS] = VL_ARGPARSE(OPTS, ARGS) copies any parameter in\n% ARGS that does not match OPTS back to ARGS instead of producing an\n% error. Options specified as structures are expaned back to PAR,\n% VAL pairs.\n%\n% Example::\n% The function can be used to parse a list of arguments\n% passed to a MATLAB functions:\n%\n% function myFunction(x,y,z,varargin)\n% opts.parameterName = defaultValue ;\n% opts = vl_argparse(opts, varargin)\n%\n% If only a subset of the options should be parsed, for example\n% because the other options are interpreted by a subroutine, then\n% use the form\n%\n% [opts, varargin] = vl_argparse(opts, varargin)\n%\n% that copies back to VARARGIN any unknown parameter.\n%\n% See also: VL_HELP().\n\n% Authors: Andrea Vedaldi\n\n% Copyright (C) 2015 Andrea Vedaldi.\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif ~isstruct(opts), error('OPTS must be a structure') ; end\nif ~iscell(args), args = {args} ; end\n\n% convert ARGS into a structure\nai = 1 ;\nparams = {} ;\nvalues = {} ;\nwhile ai <= length(args)\n if isstr(args{ai})\n params{end+1} = args{ai} ; ai = ai + 1 ;\n values{end+1} = args{ai} ; ai = ai + 1 ;\n elseif isstruct(args{ai}) ;\n params = horzcat(params, fieldnames(args{ai})') ;\n values = horzcat(values, struct2cell(args{ai})') ;\n ai = ai + 1 ;\n else\n error('Expected either a param-value pair or a structure') ;\n end\nend\nargs = {} ;\n\n% copy parameters in the opts structure, recursively\nfor i = 1:numel(params)\n field = params{i} ;\n if ~isfield(opts, field)\n field = findfield(opts, field) ;\n end\n if ~isempty(field)\n if isstruct(values{i})\n if ~isstruct(opts.(field))\n error('The value of parameter %d is a structure in the arguments but not a structure in OPT.',field) ;\n end\n if nargout > 1\n [opts.(field), rest] = vl_argparse(opts.(field), values{i}) ;\n args = horzcat(args, {field, cell2struct(rest(2:2:end), rest(1:2:end), 2)}) ;\n else\n opts.(field) = vl_argparse(opts.(field), values{i}) ;\n end\n else\n opts.(field) = values{i} ;\n end\n else\n if nargout <= 1\n error('Uknown parameter ''%s''', params{i}) ;\n else\n args = horzcat(args, {params{i}, values{i}}) ;\n end\n end\nend\n\nfunction field = findfield(opts, field)\nfields=fieldnames(opts) ;\ni=find(strcmpi(fields, field)) ;\nif ~isempty(i)\n field=fields{i} ;\nelse\n field=[] ;\nend\n\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_compilenn.m", "ext": ".m", "path": "2015_Face_Detection-master/matlab/vl_compilenn.m", "size": 24645, "source_encoding": "utf_8", "md5": "8ffdf03179d5108a10b46a7fee6410e9", "text": "function vl_compilenn( varargin )\n% VL_COMPILENN Compile the MatConvNet toolbox\n% The `vl_compilenn()` function compiles the MEX files in the\n% MatConvNet toolbox. See below for the requirements for compiling\n% CPU and GPU code, respectively.\n%\n% `vl_compilenn('OPTION', ARG, ...)` accepts the following options:\n%\n% `EnableGpu`:: `false`\n% Set to true in order to enable GPU support.\n%\n% `Verbose`:: 0\n% Set the verbosity level (0, 1 or 2).\n%\n% `Debug`:: `false`\n% Set to true to compile the binaries with debugging\n% information.\n%\n% `CudaMethod`:: Linux & Mac OS X: `mex`; Windows: `nvcc`\n% Choose the method used to compile the CUDA code. There are two\n% methods:\n%\n% * The **`mex`** method uses the MATLAB MEX command with the\n% configuration file\n% `/matlab/src/config/mex_CUDA_.[sh/xml]`\n% This configuration file is in XML format since MATLAB 8.3\n% (R2014a) and is a Shell script for earlier versions. This\n% is, principle, the preferred method as it uses the\n% MATLAB-sanctioned compiler options.\n%\n% * The **`nvcc`** method calls the NVIDIA CUDA compiler `nvcc`\n% directly to compile CUDA source code into object files.\n%\n% This method allows to use a CUDA toolkit version that is not\n% the one that officially supported by a particular MATALB\n% version (see below). It is also the default method for\n% compilation under Windows and with CuDNN.\n%\n% `CudaRoot`:: guessed automatically\n% This option specifies the path to the CUDA toolkit to use for\n% compilation.\n%\n% `EnableImreadJpeg`:: `true`\n% Set this option to `true` to compile `vl_imreadjpeg`.\n%\n% `ImageLibrary`:: `libjpeg` (Linux), `gdiplus` (Windows), `quartz` (Mac)\n% The image library to use for `vl_impreadjpeg`.\n%\n% `ImageLibraryCompileFlags`:: platform dependent\n% A cell-array of additional flags to use when compiling\n% `vl_imreadjpeg`.\n%\n% `ImageLibraryLinkFlags`:: platform dependent\n% A cell-array of additional flags to use when linking\n% `vl_imreadjpeg`.\n%\n% `EnableCudnn`:: `false`\n% Set to `true` to compile CuDNN support.\n%\n% `CudnnRoot`:: `'local/'`\n% Directory containing the unpacked binaries and header files of\n% the CuDNN library.\n%\n% ## Compiling the CPU code\n%\n% By default, the `EnableGpu` option is switched to off, such that\n% the GPU code support is not compiled in.\n%\n% Generally, you only need a C/C++ compiler (usually Xcode, GCC or\n% Visual Studio for Mac, Linux, and Windows respectively). The\n% compiler can be setup in MATLAB using the\n%\n% mex -setup\n%\n% command.\n%\n% ## Compiling the GPU code\n%\n% In order to compile the GPU code, set the `EnableGpu` option to\n% `true`. For this to work you will need:\n%\n% * To satisfy all the requirement to compile the CPU code (see\n% above).\n%\n% * A NVIDIA GPU with at least *compute capability 2.0*.\n%\n% * The *MATALB Parallel Computing Toolbox*. This can be purchased\n% from Mathworks (type `ver` in MATLAB to see if this toolbox is\n% already comprised in your MATLAB installation; it often is).\n%\n% * A copy of the *CUDA Devkit*, which can be downloaded for free\n% from NVIDIA. Note that each MATLAB version requires a\n% particular CUDA Devkit version:\n%\n% | MATLAB version | Release | CUDA Devkit |\n% |----------------|---------|-------------|\n% | 2013b | 2013b | 5.5 |\n% | 2014a | 2014a | 5.5 |\n% | 2014b | 2014b | 6.0 |\n%\n% A different versions of CUDA may work using the hack described\n% above (i.e. setting the `CudaMethod` to `nvcc`).\n%\n% The following configurations have been tested successfully:\n%\n% * Windows 7 x64, MATLAB R2014a, Visual C++ 2010 and CUDA Toolkit\n% 6.5 (unable to compile with Visual C++ 2013).\n% * Windows 8 x64, MATLAB R2014a, Visual C++ 2013 and CUDA\n% Toolkit 6.5.\n% * Mac OS X 10.9 and 10.10, MATLAB R2013a and R2013b, Xcode, CUDA\n% Toolkit 5.5.\n% * GNU/Linux, MATALB R2014a, gcc, CUDA Toolkit 5.5.\n%\n% Furthermore your GPU card must have ComputeCapability >= 2.0 (see\n% output of `gpuDevice()`) in order to be able to run the GPU code.\n% To change the compute capabilities, for `mex` `CudaMethod` edit\n% the particular config file. For the 'nvcc' method, compute\n% capability is guessed based on the GPUDEVICE output. You can\n% override it by setting the 'CudaArch' parameter (e.g. in case of\n% multiple GPUs with various architectures).\n%\n% See also: [Compliling MatConvNet](../install.md#compiling),\n% [Compiling MEX files containing CUDA\n% code](http://mathworks.com/help/distcomp/run-mex-functions-containing-cuda-code.html),\n% `vl_setup()`, `vl_imreadjpeg()`.\n\n% Copyright (C) 2014-15 Karel Lenc and Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% Get MatConvNet root directory\nroot = fileparts(fileparts(mfilename('fullpath'))) ;\naddpath(fullfile(root, 'matlab')) ;\n\n% --------------------------------------------------------------------\n% Parse options\n% --------------------------------------------------------------------\n\nopts.enableGpu = false;\nopts.enableImreadJpeg = true;\nopts.enableCudnn = false;\nopts.imageLibrary = [] ;\nopts.imageLibraryCompileFlags = {} ;\nopts.imageLibraryLinkFlags = [] ;\nopts.verbose = 0;\nopts.debug = false;\nopts.cudaMethod = [] ;\nopts.cudaRoot = [] ;\nopts.cudaArch = [] ;\nopts.defCudaArch = [...\n '-gencode=arch=compute_20,code=\\\"sm_20,compute_20\\\" '...\n '-gencode=arch=compute_30,code=\\\"sm_30,compute_30\\\"'];\nopts.cudnnRoot = 'local' ;\nopts = vl_argparse(opts, varargin);\n\n% --------------------------------------------------------------------\n% Files to compile\n% --------------------------------------------------------------------\n\narch = computer('arch') ;\nif isempty(opts.imageLibrary)\n switch arch\n case 'glnxa64', opts.imageLibrary = 'libjpeg' ;\n case 'maci64', opts.imageLibrary = 'quartz' ;\n case 'win64', opts.imageLibrary = 'gdiplus' ;\n end\nend\nif isempty(opts.imageLibraryLinkFlags)\n switch opts.imageLibrary\n case 'libjpeg', opts.imageLibraryLinkFlags = {'-ljpeg'} ;\n case 'quartz', opts.imageLibraryLinkFlags = {'LDFLAGS=$LDFLAGS -framework Cocoa -framework ImageIO'} ;\n case 'gdiplus', opts.imageLibraryLinkFlags = {'-lgdiplus'} ;\n end\nend\n\nlib_src = {} ;\nmex_src = {} ;\n\n% Files that are compiled as CPP or CU depending on whether GPU support\n% is enabled.\nif opts.enableGpu, ext = 'cu' ; else, ext='cpp' ; end\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['data.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['datamex.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnconv.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnfullyconnected.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnsubsample.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnpooling.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnnormalize.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbnorm.' ext]) ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbias.' ext]) ;\nmex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconv.' ext]) ;\nmex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconvt.' ext]) ;\nmex_src{end+1} = fullfile(root,'matlab','src',['vl_nnpool.' ext]) ;\nmex_src{end+1} = fullfile(root,'matlab','src',['vl_nnnormalize.' ext]) ;\nmex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbnorm.' ext]) ;\n\n% CPU-specific files\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_cpu.cpp') ;\nlib_src{end+1} = fullfile(root,'matlab','src','bits','impl','tinythread.cpp') ;\n\n% GPU-specific files\nif opts.enableGpu\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_gpu.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','datacu.cu') ;\nend\n\n% cuDNN-specific files\nif opts.enableCudnn\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnconv_cudnn.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbias_cudnn.cu') ;\n lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnpooling_cudnn.cu') ;\nend\n\n% Other files\nif opts.enableImreadJpeg\n mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg.' ext]) ;\n lib_src{end+1} = fullfile(root,'matlab','src', 'bits', 'impl', ['imread_' opts.imageLibrary '.cpp']) ;\nend\n\n% --------------------------------------------------------------------\n% Setup CUDA toolkit\n% --------------------------------------------------------------------\n\nif opts.enableGpu\n opts.verbose && fprintf('%s: * CUDA configuration *\\n', mfilename) ;\n if isempty(opts.cudaRoot), opts.cudaRoot = search_cuda_devkit(opts); end\n check_nvcc(opts.cudaRoot);\n opts.verbose && fprintf('%s:\\tCUDA: using CUDA Devkit ''%s''.\\n', ...\n mfilename, opts.cudaRoot) ;\n switch arch\n case 'win64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib', 'x64') ;\n case 'maci64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib') ;\n case 'glnxa64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib64') ;\n otherwise, error('Unsupported architecture ''%s''.', arch) ;\n end\n opts.nvccPath = fullfile(opts.cudaRoot, 'bin', 'nvcc') ;\n\n % CUDA arch string (select GPU architecture)\n if isempty(opts.cudaArch), opts.cudaArch = get_cuda_arch(opts) ; end\n opts.verbose && fprintf('%s:\\tCUDA: NVCC architecture string: ''%s''.\\n', ...\n mfilename, opts.cudaArch) ;\n\n % Make sure NVCC is visible by MEX by setting the corresp. env. var\n if ~strcmp(getenv('MW_NVCC_PATH'), opts.nvccPath)\n warning('Setting the ''MW_NVCC_PATH'' environment variable to ''%s''', ...\n opts.nvccPath) ;\n setenv('MW_NVCC_PATH', opts.nvccPath) ;\n end\nend\n\n% --------------------------------------------------------------------\n% Compiler options\n% --------------------------------------------------------------------\n\n% Build directories\nmex_dir = fullfile(root, 'matlab', 'mex') ;\nbld_dir = fullfile(mex_dir, '.build');\nif ~exist(fullfile(bld_dir,'bits','impl'), 'dir')\n mkdir(fullfile(bld_dir,'bits','impl')) ;\nend\n\n% Compiler flags\nflags.cc = {} ;\nflags.link = {} ;\nif opts.verbose > 1\n flags.cc{end+1} = '-v' ;\n flags.link{end+1} = '-v' ;\nend\nif opts.debug\n flags.cc{end+1} = '-g' ;\nelse\n flags.cc{end+1} = '-DNDEBUG' ;\nend\nif opts.enableGpu, flags.cc{end+1} = '-DENABLE_GPU' ; end\nif opts.enableCudnn,\n flags.cc{end+1} = '-DENABLE_CUDNN' ;\n flags.cc{end+1} = ['-I' opts.cudnnRoot] ;\nend\nflags.link{end+1} = '-lmwblas' ;\nswitch arch\n case {'maci64', 'glnxa64'}\n case {'win64'}\n % VisualC does not pass this even if available in the CPU architecture\n flags.cc{end+1} = '-D__SSSE3__' ;\nend\n\nif opts.enableImreadJpeg\n flags.cc = horzcat(flags.cc, opts.imageLibraryCompileFlags) ;\n flags.link = horzcat(flags.link, opts.imageLibraryLinkFlags) ;\nend\n\nif opts.enableGpu\n flags.link{end+1} = ['-L' opts.cudaLibDir] ;\n flags.link{end+1} = '-lcudart' ;\n flags.link{end+1} = '-lcublas' ;\n switch arch\n case {'maci64', 'glnxa64'}\n flags.link{end+1} = '-lmwgpu' ;\n case 'win64'\n flags.link{end+1} = '-lgpu' ;\n end\n if opts.enableCudnn\n flags.link{end+1} = ['-L' opts.cudnnRoot] ;\n flags.link{end+1} = '-lcudnn' ;\n end\nend\n\n% For the MEX command\nflags.link{end+1} = '-largeArrayDims' ;\nflags.mexcc = flags.cc ;\nflags.mexcc{end+1} = '-largeArrayDims' ;\nflags.mexcc{end+1} = '-cxx' ;\nif strcmp(arch, 'maci64')\n % CUDA prior to 7.0 on Mac require GCC libstdc++ instead of the native\n % Clang libc++. This should go away in the future.\n flags.mexcc{end+1} = 'CXXFLAGS=$CXXFLAGS -stdlib=libstdc++' ;\n flags.link{end+1} = 'LDFLAGS=$LDFLAGS -stdlib=libstdc++' ;\n if ~verLessThan('matlab', '8.5.0')\n % Complicating matters, MATLAB 8.5.0 links to Clang c++ by default\n % when linking MEX files overriding the option above. More force\n % is needed:\n flags.link{end+1} = 'LINKLIBS=$LINKLIBS -L\"$MATLABROOT/bin/maci64\" -lmx -lmex -lmat -lstdc++' ;\n end\nend\nif opts.enableGpu\n flags.mexcu = flags.cc ;\n flags.mexcu{end+1} = '-largeArrayDims' ;\n flags.mexcu{end+1} = '-cxx' ;\n flags.mexcu(end+1:end+2) = {'-f' mex_cuda_config(root)} ;\n flags.mexcu{end+1} = ['NVCCFLAGS=' opts.cudaArch '$NVCC_FLAGS'] ;\nend\n\n% For the cudaMethod='nvcc'\nif opts.enableGpu && strcmp(opts.cudaMethod,'nvcc')\n flags.nvcc = flags.cc ;\n flags.nvcc{end+1} = ['-I\"' fullfile(matlabroot, 'extern', 'include') '\"'] ;\n flags.nvcc{end+1} = ['-I\"' fullfile(matlabroot, 'toolbox','distcomp','gpu','extern','include') '\"'] ;\n if opts.debug\n flags.nvcc{end+1} = '-O0' ;\n end\n flags.nvcc{end+1} = '-Xcompiler' ;\n switch arch\n case {'maci64', 'glnxa64'}\n flags.nvcc{end+1} = '-fPIC' ;\n case 'win64'\n flags.nvcc{end+1} = '/MD' ;\n check_clpath(); % check whether cl.exe in path\n end\n flags.nvcc{end+1} = opts.cudaArch;\nend\n\nif opts.verbose\n fprintf('%s: * Compiler and linker configurations *\\n', mfilename) ;\n fprintf('%s: \\tintermediate build products directory: %s\\n', mfilename, bld_dir) ;\n fprintf('%s: \\tMEX files: %s/\\n', mfilename, mex_dir) ;\n fprintf('%s: \\tMEX compiler options: %s\\n', mfilename, strjoin(flags.mexcc)) ;\n fprintf('%s: \\tMEX linker options: %s\\n', mfilename, strjoin(flags.link)) ;\nend\nif opts.verbose & opts.enableGpu\n fprintf('%s: \\tMEX compiler options (CUDA): %s\\n', mfilename, strjoin(flags.mexcu)) ;\nend\nif opts.verbose & opts.enableGpu & strcmp(opts.cudaMethod,'nvcc')\n fprintf('%s: \\tNVCC compiler options: %s\\n', mfilename, strjoin(flags.nvcc)) ;\nend\nif opts.verbose & opts.enableImreadJpeg\n fprintf('%s: * Reading images *\\n', mfilename) ;\n fprintf('%s: \\tvl_imreadjpeg enabled\\n', mfilename) ;\n fprintf('%s: \\timage library: %s\\n', mfilename, opts.imageLibrary) ;\n fprintf('%s: \\timage library compile flags: %s\\n', mfilename, strjoin(opts.imageLibraryCompileFlags)) ;\n fprintf('%s: \\timage library link flags: %s\\n', mfilename, strjoin(opts.imageLibraryLinkFlags)) ;\nend\n\n% --------------------------------------------------------------------\n% Compile\n% --------------------------------------------------------------------\n\n% Intermediate object files\nsrcs = horzcat(lib_src,mex_src) ;\nparfor i = 1:numel(horzcat(lib_src, mex_src))\n [~,~,ext] = fileparts(srcs{i}) ; ext(1) = [] ;\n if strcmp(ext,'cu')\n if strcmp(opts.cudaMethod,'nvcc')\n nvcc_compile(opts, srcs{i}, toobj(bld_dir,srcs{i}), flags.nvcc) ;\n else\n mex_compile(opts, srcs{i}, toobj(bld_dir,srcs{i}), flags.mexcu) ;\n end\n else\n mex_compile(opts, srcs{i}, toobj(bld_dir,srcs{i}), flags.mexcc) ;\n end\nend\n\n% Link into MEX files\nparfor i = 1:numel(mex_src)\n [~,base,~] = fileparts(mex_src{i}) ;\n objs = toobj(bld_dir, {mex_src{i}, lib_src{:}}) ;\n mex_link(opts, objs, mex_dir, flags.link) ;\nend\n\n% Reset path adding the mex subdirectory just created\nvl_setupnn() ;\n\n% --------------------------------------------------------------------\n% Utility functions\n% --------------------------------------------------------------------\n\n% --------------------------------------------------------------------\nfunction objs = toobj(bld_dir,srcs)\n% --------------------------------------------------------------------\nstr = fullfile('matlab','src') ;\nmultiple = iscell(srcs) ;\nif ~multiple, srcs = {srcs} ; end\nfor t = 1:numel(srcs)\n i = strfind(srcs{t},str);\n objs{t} = fullfile(bld_dir, srcs{t}(i+numel(str):end)) ;\nend\nif ~multiple, objs = objs{1} ; end\nobjs = strrep(objs,'.cpp',['.' objext]) ;\nobjs = strrep(objs,'.cu',['.' objext]) ;\nobjs = strrep(objs,'.c',['.' objext]) ;\n\n% --------------------------------------------------------------------\nfunction objs = mex_compile(opts, src, tgt, mex_opts)\n% --------------------------------------------------------------------\nmopts = {'-outdir', fileparts(tgt), src, '-c', mex_opts{:}} ;\nopts.verbose && fprintf('%s: MEX CC: %s\\n', mfilename, strjoin(mopts)) ;\nmex(mopts{:}) ;\n\n% --------------------------------------------------------------------\nfunction obj = nvcc_compile(opts, src, tgt, nvcc_opts)\n% --------------------------------------------------------------------\nnvcc_path = fullfile(opts.cudaRoot, 'bin', 'nvcc');\nnvcc_cmd = sprintf('\"%s\" -c \"%s\" %s -o \"%s\"', ...\n nvcc_path, src, ...\n strjoin(nvcc_opts), tgt);\nopts.verbose && fprintf('%s: NVCC CC: %s\\n', mfilename, nvcc_cmd) ;\nstatus = system(nvcc_cmd);\nif status, error('Command %s failed.', nvcc_cmd); end;\n\n% --------------------------------------------------------------------\nfunction mex_link(opts, objs, mex_dir, mex_flags)\n% --------------------------------------------------------------------\nmopts = {'-outdir', mex_dir, mex_flags{:}, objs{:}} ;\nopts.verbose && fprintf('%s: MEX LINK: %s\\n', mfilename, strjoin(mopts)) ;\nmex(mopts{:}) ;\n\n% --------------------------------------------------------------------\nfunction ext = objext()\n% --------------------------------------------------------------------\n% Get the extension for an 'object' file for the current computer\n% architecture\nswitch computer('arch')\n case 'win64', ext = 'obj';\n case {'maci64', 'glnxa64'}, ext = 'o' ;\n otherwise, error('Unsupported architecture %s.', computer) ;\nend\n\n% --------------------------------------------------------------------\nfunction conf_file = mex_cuda_config(root)\n% --------------------------------------------------------------------\n% Get mex CUDA config file\nmver = [1e4 1e2 1] * sscanf(version, '%d.%d.%d') ;\nif mver <= 80200, ext = 'sh' ; else ext = 'xml' ; end\narch = computer('arch') ;\nswitch arch\n case {'win64'}\n config_dir = fullfile(matlabroot, 'toolbox', ...\n 'distcomp', 'gpu', 'extern', ...\n 'src', 'mex', arch) ;\n case {'maci64', 'glnxa64'}\n config_dir = fullfile(root, 'matlab', 'src', 'config') ;\nend\nconf_file = fullfile(config_dir, ['mex_CUDA_' arch '.' ext]);\nfprintf('%s:\\tCUDA: MEX config file: ''%s''\\n', mfilename, conf_file);\n\n% --------------------------------------------------------------------\nfunction check_clpath()\n% --------------------------------------------------------------------\n% Checks whether the cl.exe is in the path (needed for the nvcc). If\n% not, tries to guess the location out of mex configuration.\nstatus = system('cl.exe -help');\nif status == 1\n warning('CL.EXE not found in PATH. Trying to guess out of mex setup.');\n cc = mex.getCompilerConfigurations('c++');\n if isempty(cc)\n error('Mex is not configured. Run \"mex -setup\".');\n end\n prev_path = getenv('PATH');\n cl_path = fullfile(cc.Location, 'VC','bin','x86_amd64');\n setenv('PATH', [prev_path ';' cl_path]);\n status = system('cl.exe');\n if status == 1\n setenv('PATH', prev_path);\n error('Unable to find cl.exe');\n else\n fprintf('Location of cl.exe (%s) successfully added to your PATH.\\n', ...\n cl_path);\n end\nend\n\n% -------------------------------------------------------------------------\nfunction paths = which_nvcc(opts)\n% -------------------------------------------------------------------------\nswitch computer('arch')\n case 'win64'\n [~, paths] = system('where nvcc.exe');\n paths = strtrim(paths);\n paths = paths(strfind(paths, '.exe'));\n case {'maci64', 'glnxa64'}\n [~, paths] = system('which nvcc');\n paths = strtrim(paths) ;\nend\n\n% -------------------------------------------------------------------------\nfunction cuda_root = search_cuda_devkit(opts)\n% -------------------------------------------------------------------------\n% This function tries to to locate a working copy of the CUDA Devkit.\n\nopts.verbose && fprintf(['%s:\\tCUDA: seraching for the CUDA Devkit' ...\n ' (use the option ''CudaRoot'' to override):\\n'], mfilename);\n\n% Propose a number of candidate paths for NVCC\npaths = {getenv('MW_NVCC_PATH')} ;\npaths = [paths, which_nvcc(opts)] ;\nfor v = {'5.5', '6.0', '6.5', '7.0'}\n switch computer('arch')\n case 'glnxa64'\n paths{end+1} = sprintf('/usr/local/cuda-%s/bin/nvcc', char(v)) ;\n case 'maci64'\n paths{end+1} = sprintf('/Developer/NVIDIA/CUDA-%s/bin/nvcc', char(v)) ;\n case 'win64'\n paths{end+1} = sprintf('C:\\\\Program Files\\\\NVIDIA GPU Computing Toolkit\\\\CUDA\\\\v%s\\\\bin\\\\nvcc.exe', char(v)) ;\n end\nend\npaths{end+1} = sprintf('/usr/local/cuda/bin/nvcc') ;\n\n% Validate each candidate NVCC path\nfor i=1:numel(paths)\n nvcc(i).path = paths{i} ;\n [nvcc(i).isvalid, nvcc(i).version] = validate_nvcc(opts,paths{i}) ;\nend\nif opts.verbose\n fprintf('\\t| %5s | %5s | %-70s |\\n', 'valid', 'ver', 'NVCC path') ;\n for i=1:numel(paths)\n fprintf('\\t| %5d | %5d | %-70s |\\n', ...\n nvcc(i).isvalid, nvcc(i).version, nvcc(i).path) ;\n end\nend\n\n% Pick an entry\nindex = find([nvcc.isvalid]) ;\nif isempty(index)\n error('Could not find a valid NVCC executable\\n') ;\nend\nnvcc = nvcc(index(1)) ;\ncuda_root = fileparts(fileparts(nvcc.path)) ;\n\nif opts.verbose\n fprintf('%s:\\tCUDA: choosing NVCC compiler ''%s'' (version %d)\\n', ...\n mfilename, nvcc.path, nvcc.version) ;\nend\n\n% -------------------------------------------------------------------------\nfunction [valid, cuver] = validate_nvcc(opts, nvcc_path)\n% -------------------------------------------------------------------------\nvalid = false ;\ncuver = 0 ;\nif ~isempty(nvcc_path)\n [status, output] = system(sprintf('\"%s\" --version', nvcc_path)) ;\n valid = (status == 0) ;\nend\nif ~valid, return ; end\nmatch = regexp(output, 'V(\\d+\\.\\d+\\.\\d+)', 'match') ;\nif isempty(match), valid = false ; return ; end\ncuver = [1e4 1e2 1] * sscanf(match{1}, 'V%d.%d.%d') ;\n\n% --------------------------------------------------------------------\nfunction check_nvcc(cuda_root)\n% --------------------------------------------------------------------\n% Checks whether the nvcc is in the path. If not, guessed out of CudaRoot.\n[status, ~] = system('nvcc --help');\nif status ~= 0\n warning('nvcc not found in PATH. Trying to guess out of CudaRoot.');\n cuda_bin_path = fullfile(cuda_root, 'bin');\n prev_path = getenv('PATH');\n switch computer\n case 'PCWIN64', separator = ';';\n case {'GLNXA64', 'MACI64'}, separator = ':';\n end\n setenv('PATH', [prev_path separator cuda_bin_path]);\n [status, ~] = system('nvcc --help');\n if status ~= 0\n setenv('PATH', prev_path);\n error('Unable to find nvcc.');\n else\n fprintf('Location of nvcc (%s) added to your PATH.\\n', cuda_bin_path);\n end\nend\n\n% --------------------------------------------------------------------\nfunction cudaArch = get_cuda_arch(opts)\n% --------------------------------------------------------------------\nopts.verbose && fprintf('%s:\\tCUDA: determining GPU compute capability (use the ''CudaArch'' option to override)\\n', mfilename);\ntry\n gpu_device = gpuDevice();\n arch_code = strrep(gpu_device.ComputeCapability, '.', '');\n cudaArch = ...\n sprintf('-gencode=arch=compute_%s,code=\\\\\\\"sm_%s,compute_%s\\\\\\\" ', ...\n arch_code, arch_code, arch_code) ;\ncatch\n opts.verbose && fprintf(['%s:\\tCUDA: cannot determine the capabilities of the installed GPU;' ...\n 'falling back to default\\n'], mfilename);\n cudaArch = opts.defCudaArch;\nend\n\n"} +{"plateform": "github", "repo_name": "layumi/2015_Face_Detection-master", "name": "vl_simplenn_display.m", "ext": ".m", "path": "2015_Face_Detection-master/matlab/simplenn/vl_simplenn_display.m", "size": 10932, "source_encoding": "utf_8", "md5": "c7ed88fccca92a96ffe9c36dcb72d278", "text": "function info = vl_simplenn_display(net, varargin)\n% VL_SIMPLENN_DISPLAY Simple CNN statistics\n% VL_SIMPLENN_DISPLAY(NET) prints statistics about the network NET.\n%\n% INFO=VL_SIMPLENN_DISPLAY(NET) returns instead a structure INFO\n% with several statistics for each layer of the network NET.\n%\n% The function accepts the following options:\n%\n% `inputSize`:: heuristically set\n% Specifies the size of the input tensor X that will be passed\n% to the network. This is used in order to estiamte the memory\n% required to process the network. If not specified,\n% VL_SIMPLENN_DISPLAY uses the value in\n% NET.NORMALIZATION.IMAGESIZE assuming a batch size of one\n% image, unless otherwise specified by the `batchSize` option.\n%\n% `batchSize`:: 1\n% Specifies the number of data points in a batch in estimating\n% the memory consumption (see `inputSize`).\n\n% Copyright (C) 2014-15 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.inputSize = [] ;\nopts.batchSize = 1 ;\nopts.maxNumColumns = 18 ;\nopts.format = 'ascii' ;\nopts = vl_argparse(opts, varargin) ;\n\nfields={'layer', 'type', 'name', '-', ...\n 'support', 'filtd', 'nfilt', 'stride', 'pad', '-', ...\n 'rfsize', 'rfoffset', 'rfstride', '-', ...\n 'dsize', 'ddepth', 'dnum', '-', ...\n 'xmem', 'wmem'};\n\n% get the support, stride, and padding of the operators\nfor l = 1:numel(net.layers)\n ly = net.layers{l} ;\n switch ly.type\n case 'conv'\n if isfield(ly, 'weights')\n info.support(1:2,l) = max([size(ly.weights{1},1) ; size(ly.weights{1},2)],1) ;\n else\n info.support(1:2,l) = max([size(ly.filters,1) ; size(ly.filters,2)],1) ;\n end\n case 'pool'\n info.support(1:2,l) = ly.pool(:) ;\n otherwise\n info.support(1:2,l) = [1;1] ;\n end\n if isfield(ly, 'stride')\n info.stride(1:2,l) = ly.stride(:) ;\n else\n info.stride(1:2,l) = 1 ;\n end\n if isfield(ly, 'pad')\n info.pad(1:4,l) = ly.pad(:) ;\n else\n info.pad(1:4,l) = 0 ;\n end\n\n % operator applied to the input image\n info.receptiveFieldSize(1:2,l) = 1 + ...\n sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...\n (info.support(1:2,1:l)-1),2) ;\n info.receptiveFieldOffset(1:2,l) = 1 + ...\n sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...\n ((info.support(1:2,1:l)-1)/2 - info.pad([1 3],1:l)),2) ;\n info.receptiveFieldStride = cumprod(info.stride,2) ;\nend\n\n\n% get the dimensions of the data\nif ~isempty(opts.inputSize) ;\n info.dataSize(1:4,1) = opts.inputSize(:) ;\nelseif isfield(net, 'normalization') && isfield(net.normalization, 'imageSize')\n info.dataSize(1:4,1) = [net.normalization.imageSize(:) ; opts.batchSize] ;\nelse\n info.dataSize(1:4,1) = [NaN NaN NaN opts.batchSize] ;\nend\nfor l = 1:numel(net.layers)\n ly = net.layers{l} ;\n if strcmp(ly.type, 'custom') && isfield(ly, 'getForwardSize')\n sz = ly.getForwardSize(ly, info.dataSize(:,l)) ;\n info.dataSize(:,l+1) = sz(:) ;\n continue ;\n end\n\n info.dataSize(1, l+1) = floor((info.dataSize(1,l) + ...\n sum(info.pad(1:2,l)) - ...\n info.support(1,l)) / info.stride(1,l)) + 1 ;\n info.dataSize(2, l+1) = floor((info.dataSize(2,l) + ...\n sum(info.pad(3:4,l)) - ...\n info.support(2,l)) / info.stride(2,l)) + 1 ;\n info.dataSize(3, l+1) = info.dataSize(3,l) ;\n info.dataSize(4, l+1) = info.dataSize(4,l) ;\n switch ly.type\n case 'conv'\n if isfield(ly, 'weights')\n f = ly.weights{1} ;\n else\n f = ly.filters ;\n end\n if size(f, 3) ~= 0\n info.dataSize(3, l+1) = size(f,4) ;\n end\n case {'loss', 'softmaxloss'}\n info.dataSize(3:4, l+1) = 1 ;\n case 'custom'\n info.dataSize(3,l+1) = NaN ;\n end\nend\n\nif nargout > 0, return ; end\n\n% print table\ntable = {} ;\nwmem = 0 ;\nxmem = 0 ;\nfor wi=1:numel(fields)\n w = fields{wi} ;\n switch w\n case 'type', s = 'type' ;\n case 'stride', s = 'stride' ;\n case 'rfsize', s = 'rf size' ;\n case 'rfstride', s = 'rf stride' ;\n case 'rfoffset', s = 'rf offset' ;\n case 'dsize', s = 'data size' ;\n case 'ddepth', s = 'data depth' ;\n case 'dnum', s = 'data num' ;\n case 'nfilt', s = 'num filts' ;\n case 'filtd', s = 'filt dim' ;\n case 'wmem', s = 'param mem' ;\n case 'xmem', s = 'data mem' ;\n otherwise, s = char(w) ;\n end\n table{wi,1} = s ;\n\n % do input pseudo-layer\n for l=0:numel(net.layers)\n switch char(w)\n case '-', s='-' ;\n case 'layer', s=sprintf('%d', l) ;\n case 'dsize', s=pdims(info.dataSize(1:2,l+1)) ;\n case 'ddepth', s=sprintf('%d', info.dataSize(3,l+1)) ;\n case 'dnum', s=sprintf('%d', info.dataSize(4,l+1)) ;\n case 'xmem'\n a = prod(info.dataSize(:,l+1)) * 4 ;\n s = pmem(a) ;\n xmem = xmem + a ;\n otherwise\n if l == 0\n if strcmp(char(w),'type'), s = 'input';\n else s = 'n/a' ; end\n else\n ly=net.layers{l} ;\n switch char(w)\n case 'name'\n if isfield(ly, 'name')\n s=ly.name ;\n else\n s='' ;\n end\n case 'type'\n switch ly.type\n case 'normalize', s='norm';\n case 'pool'\n if strcmpi(ly.method,'avg'), s='apool'; else s='mpool'; end\n case 'softmax', s='softmx' ;\n case 'softmaxloss', s='softmxl' ;\n otherwise s=ly.type ;\n end\n case 'nfilt'\n switch ly.type\n case 'conv'\n if isfield(ly, 'weights'), a = size(ly.weights{1},4) ;\n else, a = size(ly.filters,4) ; end\n s=sprintf('%d',a) ;\n otherwise\n s='n/a' ;\n end\n case 'filtd'\n switch ly.type\n case 'conv'\n if isfield(ly, 'weights'), a = size(ly.weights{1},3) ;\n else, a = size(ly.filters,3) ; end\n s=sprintf('%d',a) ;\n otherwise\n s='n/a' ;\n end\n case 'support'\n s = pdims(info.support(:,l)) ;\n case 'stride'\n s = pdims(info.stride(:,l)) ;\n case 'pad'\n s = pdims(info.pad(:,l)) ;\n case 'rfsize'\n s = pdims(info.receptiveFieldSize(:,l)) ;\n case 'rfoffset'\n s = pdims(info.receptiveFieldOffset(:,l)) ;\n case 'rfstride'\n s = pdims(info.receptiveFieldStride(:,l)) ;\n\n case 'wmem'\n a = 0 ;\n if isfield(ly, 'weights') ;\n for j=1:numel(ly.weights)\n a = a + numel(ly.weights{j}) * 4 ;\n end\n end\n % Legacy code to be removed\n if isfield(ly, 'filters') ;\n a = a + numel(ly.filters) * 4 ;\n end\n if isfield(ly, 'biases') ;\n a = a + numel(ly.biases) * 4 ;\n end\n s = pmem(a) ;\n wmem = wmem + a ;\n end\n end\n end\n table{wi,l+2} = s ;\n end\nend\n\nfor i=2:opts.maxNumColumns:size(table,2)\n sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ;\n switch opts.format\n case 'ascii', pascii(table(:,[1 sel])) ; fprintf('\\n') ;\n case 'latex', platex(table(:,[1 sel])) ;\n case 'csv', pcsv(table(:,[1 sel])) ; fprintf('\\n') ;\n end\nend\n\nfprintf('parameter memory: %s (%.2g parameters)\\n', pmem(wmem), wmem/4) ;\nfprintf('data memory: %s (for batch size %d)\\n', pmem(xmem), info.dataSize(4,1)) ;\n\n% -------------------------------------------------------------------------\nfunction s = pmem(x)\n% -------------------------------------------------------------------------\nif isnan(x), s = 'NaN' ;\nelseif x < 1024^1, s = sprintf('%.0fB', x) ;\nelseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ;\nelseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ;\nelse s = sprintf('%.0fGB', x / 1024^3) ;\nend\n\n% -------------------------------------------------------------------------\nfunction s = pdims(x)\n% -------------------------------------------------------------------------\nif all(x==x(1))\n s = sprintf('%.4g', x(1)) ;\nelse\n s = sprintf('%.4gx', x(:)) ;\n s(end) = [] ;\nend\n\n% -------------------------------------------------------------------------\nfunction pascii(table)\n% -------------------------------------------------------------------------\nsizes = max(cellfun(@(x) numel(x), table),[],1) ;\nfor i=1:size(table,1)\n for j=1:size(table,2)\n s = table{i,j} ;\n fmt = sprintf('%%%ds|', sizes(j)) ;\n if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end\n fprintf(fmt, s) ;\n end\n fprintf('\\n') ;\nend\n\n% -------------------------------------------------------------------------\nfunction pcsv(table)\n% -------------------------------------------------------------------------\nsizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ;\nfor i=1:size(table,1)\n if isequal(table{i,1},'-'), continue ; end\n for j=1:size(table,2)\n s = table{i,j} ;\n fmt = sprintf('%%%ds,', sizes(j)) ;\n fprintf(fmt, ['\"' s '\"']) ;\n end\n fprintf('\\n') ;\nend\n\n% -------------------------------------------------------------------------\nfunction platex(table)\n% -------------------------------------------------------------------------\nsizes = max(cellfun(@(x) numel(x), table),[],1) ;\nfprintf('\\\\begin{tabular}{%s}\\n', repmat('c', 1, numel(sizes))) ;\nfor i=1:size(table,1)\n if isequal(table{i,1},'-'), fprintf('\\\\hline\\n') ; continue ; end\n for j=1:size(table,2)\n s = table{i,j} ;\n fmt = sprintf('%%%ds', sizes(j)) ;\n fprintf(fmt, latexesc(s)) ;\n if j b.bytes) ;\nvl_testsim(res_(1).dzdx,res__(1).dzdx,1e-4) ;\nvl_testsim(res_(1).dzdw{1},res__(1).dzdw{1},1e-4) ;\nvl_testsim(res_(1).dzdw{2},res__(1).dzdw{2},1e-4) ;\n"} +{"plateform": "github", "repo_name": "bearpaw/clothing-co-parsing-master", "name": "show_image_anno.m", "ext": ".m", "path": "clothing-co-parsing-master/show_image_anno.m", "size": 1095, "source_encoding": "utf_8", "md5": "d7da2a40c62162641428e789a2d08ad2", "text": "function show_image_anno\n% SHOW_IMAGE_ANNO visualize image tags\n% Wei YANG 2014\n% platero.yang (at) gmail.com\nfprintf('Press any key to continue. Press Ctrl+Z to quit.')\n\nload('label_list', 'label_list'); % load label list\nimlist = dir('annotations/image-level/*.mat'); % browsing annotations\n\nfor i = 1:length(imlist)\n fprintf('%d | %d\\n', i, length(imlist));\n [p, name, ext] = fileparts(imlist(i).name);\n im = imread(['photos/' name '.jpg']); % original image\n load(['annotations/image-level/' name '.mat'], 'tags'); % image tags\n show_annotation(im, tags, label_list);\nend\nend\n\n\nfunction show_annotation(im, tags, label_list)\n% get image-level labels name\nlabel_names = cell(1, length(tags));\nfor i = 1:length(tags)\n label_names(i) = label_list( tags(i)+1 );\nend\n\nf = figure; %scrsz = get(0,'ScreenSize'); set(gcf,'Position',scrsz); % maximize figure window\ncolormap( jet(length(label_list)) ); % set color map\n\n% % 1. show original photo\nsubplot(1, 2, 1); imshow(im); hold on; \n\n% % 2. show label names\ntitle(sprintf('%s, ', label_names{:})); \npause; close all;\nend\n\n\n\n\n"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "checkNumericalGradient.m", "ext": ".m", "path": "UFLDL-Tutorial-master/sparseae_exercise/starter/checkNumericalGradient.m", "size": 1982, "source_encoding": "utf_8", "md5": "689a352eb2927b0838af5dc508f6374d", "text": "function [] = checkNumericalGradient()\n% This code can be used to check your numerical gradient implementation \n% in computeNumericalGradient.m\n% It analytically evaluates the gradient of a very simple function called\n% simpleQuadraticFunction (see below) and compares the result with your numerical\n% solution. Your numerical gradient implementation is incorrect if\n% your numerical solution deviates too much from the analytical solution.\n \n% Evaluate the function and gradient at x = [4; 10]; (Here, x is a 2d vector.)\nx = [4; 10];\n[value, grad] = simpleQuadraticFunction(x);\n\n% Use your code to numerically compute the gradient of simpleQuadraticFunction at x.\n% (The notation \"@simpleQuadraticFunction\" denotes a pointer to a function.)\nnumgrad = computeNumericalGradient(@simpleQuadraticFunction, x);\n\n% Visually examine the two gradient computations. The two columns\n% you get should be very similar. \ndisp([numgrad grad]);\nfprintf('The above two columns you get should be very similar.\\n(Left-Your Numerical Gradient, Right-Analytical Gradient)\\n\\n');\n\n% Evaluate the norm of the difference between two solutions. \n% If you have a correct implementation, and assuming you used EPSILON = 0.0001 \n% in computeNumericalGradient.m, then diff below should be 2.1452e-12 \ndiff = norm(numgrad-grad)/norm(numgrad+grad);\ndisp(diff); \nfprintf('Norm of the difference between numerical and analytical gradient (should be < 1e-9)\\n\\n');\nend\n\n\n \nfunction [value,grad] = simpleQuadraticFunction(x)\n% this function accepts a 2D vector as input. \n% Its outputs are:\n% value: h(x1, x2) = x1^2 + 3*x1*x2\n% grad: A 2x1 vector that gives the partial derivatives of h with respect to x1 and x2 \n% Note that when we pass @simpleQuadraticFunction(x) to computeNumericalGradients, we're assuming\n% that computeNumericalGradients will use only the first returned value of this function.\n\nvalue = x(1)^2 + 3*x(1)*x(2);\n\ngrad = zeros(2, 1);\ngrad(1) = 2*x(1) + 3*x(2);\ngrad(2) = 3*x(1);\n\nend\n"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "sparseAutoencoderCost.m", "ext": ".m", "path": "UFLDL-Tutorial-master/sparseae_exercise/starter/sparseAutoencoderCost.m", "size": 5099, "source_encoding": "utf_8", "md5": "f61c92aab9f9297824b73e8fd5cb04aa", "text": "function [cost,grad] = sparseAutoencoderCost(theta, visibleSize, hiddenSize, ...\n lambda, sparsityParam, beta, data)\n\n% visibleSize: the number of input units (probably 64) \n% hiddenSize: the number of hidden units (probably 25) \n% lambda: weight decay parameter\n% sparsityParam: The desired average activation for the hidden units (denoted in the lecture\n% notes by the greek alphabet rho, which looks like a lower-case \"p\").\n% beta: weight of sparsity penalty term\n% data: Our 64x10000 matrix containing the training data. So, data(:,i) is the i-th training example. \n \n% The input theta is a vector (because minFunc expects the parameters to be a vector). \n% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this \n% follows the notation convention of the lecture notes. \n\nW1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);\nW2 = reshape(theta(hiddenSize*visibleSize+1:2*hiddenSize*visibleSize), visibleSize, hiddenSize);\nb1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);\nb2 = theta(2*hiddenSize*visibleSize+hiddenSize+1:end);\n\n% Cost and gradient variables (your code needs to compute these values). \n% Here, we initialize them to zeros. \ncost = 0;\nW1grad = zeros(size(W1)); \nW2grad = zeros(size(W2));\nb1grad = zeros(size(b1)); \nb2grad = zeros(size(b2));\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Compute the cost/optimization objective J_sparse(W,b) for the Sparse Autoencoder,\n% and the corresponding gradients W1grad, W2grad, b1grad, b2grad.\n%\n% W1grad, W2grad, b1grad and b2grad should be computed using backpropagation.\n% Note that W1grad has the same dimensions as W1, b1grad has the same dimensions\n% as b1, etc. Your code should set W1grad to be the partial derivative of J_sparse(W,b) with\n% respect to W1. I.e., W1grad(i,j) should be the partial derivative of J_sparse(W,b) \n% with respect to the input parameter W1(i,j). Thus, W1grad should be equal to the term \n% [(1/m) \\Delta W^{(1)} + \\lambda W^{(1)}] in the last block of pseudo-code in Section 2.2 \n% of the lecture notes (and similarly for W2grad, b1grad, b2grad).\n% \n% Stated differently, if we were using batch gradient descent to optimize the parameters,\n% the gradient descent update to W1 would be W1 := W1 - alpha * W1grad, and similarly for W2, b1, b2. \n% \n\n[netIn, trExamples] = size(data);\n\nm = trExamples;\n\npartCost = 0;\n\n\nDW1 = zeros(size(W1));\nDW2 = zeros(size(W2));\nDb1 = zeros(size(b1));\nDb2 = zeros(size(b2));\n\n% rho accumulator vector\nrhoAcc = zeros(size(W1,1),1);\n\nfor i = 1:m\n\n y = data(:,i);\n x = y;\n \n a1 = x;\n z2 = W1*a1 + b1;\n a2 = sigmoid(z2);\n \n rhoAcc = rhoAcc + a2;\n \nend\n\nrho = 1/m*rhoAcc;\n\nfor i = 1:m\n\n y = data(:,i);\n x = y;\n \n a1 = x;\n z2 = W1*a1 + b1;\n a2 = sigmoid(z2);\n z3 = W2*a2 + b2;\n a3 = sigmoid(z3);\n hx = a3;\n \n partCost = partCost + 1/2*norm(hx-y).^2;\n \n delta3 = -(y-a3).*a3.*(1-a3);\n \n % dalta 2 withour sparsity parameter is:\n % delta2 = W2'*delta3.*a2.*(1-a2);\n delta2 = (W2'*delta3 + ...\n beta*(-sparsityParam./rho + (1-sparsityParam)./(1-rho))).*a2.*(1-a2);\n \n %delta1 = W1'*delta2.*a1.*(1-a1);\n \n curW1grad = delta2*a1';\n curb1grad = delta2;\n curW2grad = delta3*a2';\n curb2grad = delta3;\n \n DW1 = DW1 + curW1grad;\n DW2 = DW2 + curW2grad;\n Db1 = Db1 + curb1grad;\n Db2 = Db2 + curb2grad;\n \nend\n\n% Compute cost:\n% with lambda = 0 and beta = 0\n% cost = 1/m * partCost;\n% with beta = 0;\ncost = 1/m * partCost + lambda/2 * sum([sum(sum(W1.^2)) sum(sum(W2.^2))]);\n\n% Add sparsity term\ncost = cost + beta*sum(compKL(sparsityParam,rho));\n\n% Compute W1grad:\n% with lambda = 0 and beta = 0\n% W1grad = 1/m * DW1;\n% with beta = 0;\nW1grad = 1/m * DW1 + lambda * W1;\n\n% Compute W2grad:\n% with lambda = 0 and beta = 0\n% W2grad = 1/m * DW2;\n% with beta = 0;\nW2grad = 1/m * DW2 + lambda * W2;\n\n% Compute b1grad:\n% with lambda = 0 and beta = 0\n% b1grad = 1/m * Db1;\n% with beta = 0;\nb1grad = 1/m * Db1;\n\n% Compute b2grad:\n% with lambda = 0 and beta = 0\n% b2grad = 1/m * Db2;\n% with beta = 0;\nb2grad = 1/m * Db2;\n\n%-------------------------------------------------------------------\n% After computing the cost and gradient, we will convert the gradients back\n% to a vector format (suitable for minFunc). Specifically, we will unroll\n% your gradient matrices into a vector.\n\ngrad = [W1grad(:) ; W2grad(:) ; b1grad(:) ; b2grad(:)];\n\nend\n\nfunction kl = compKL(sparsityParam, rho)\n\n kl = sum(sparsityParam.*log(sparsityParam./rho) +...\n (1-sparsityParam).*log((1-sparsityParam)./(1-rho)));\n\nend\n\n%-------------------------------------------------------------------\n% Here's an implementation of the sigmoid function, which you may find useful\n% in your computation of the costs and the gradients. This inputs a (row or\n% column) vector (say (z1, z2, z3)) and returns (f(z1), f(z2), f(z3)). \n\nfunction sigm = sigmoid(x)\n \n sigm = 1 ./ (1 + exp(-x));\nend\n\n"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "sampleIMAGES.m", "ext": ".m", "path": "UFLDL-Tutorial-master/sparseae_exercise/starter/sampleIMAGES.m", "size": 2361, "source_encoding": "utf_8", "md5": "5bc148213efc91f20fe2ca18f84b7469", "text": "function patches = sampleIMAGES()\n% sampleIMAGES\n% Returns 10000 patches for training\n\nload IMAGES; % load images from disk \n\npatchsize = 8; % we'll use 8x8 patches \nnumpatches = 10000;\n\n% Initialize patches with zeros. Your code will fill in this matrix--one\n% column per patch, 10000 columns. \npatches = zeros(patchsize*patchsize, numpatches);\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Fill in the variable called \"patches\" using data \n% from IMAGES. \n% \n% IMAGES is a 3D array containing 10 images\n% For instance, IMAGES(:,:,6) is a 512x512 array containing the 6th image,\n% and you can type \"imagesc(IMAGES(:,:,6)), colormap gray;\" to visualize\n% it. (The contrast on these images look a bit off because they have\n% been preprocessed using using \"whitening.\" See the lecture notes for\n% more details.) As a second example, IMAGES(21:30,21:30,1) is an image\n% patch corresponding to the pixels in the block (21,21) to (30,30) of\n% Image 1\n\n% MAYBE(?):\n% It can also be implemented in a vectorized for; generate all imIndex,\n% xIndex, yIndex at once and the take all patches at once.\n[X,Y,N] = size(IMAGES);\n\nimageSample = zeros(patchsize,patchsize);\n\nfor i = 1:numpatches\n \n imIndex = ceil(N*rand);\n xIndex = ceil((X-patchsize)*rand);\n yIndex = ceil((Y-patchsize)*rand);\n \n imageSample = IMAGES(xIndex:xIndex+patchsize-1,yIndex:yIndex+patchsize-1,imIndex);\n \n patches(:,i) = imageSample(:);\nend\n\n\n%% ---------------------------------------------------------------\n% For the autoencoder to work well we need to normalize the data\n% Specifically, since the output of the network is bounded between [0,1]\n% (due to the sigmoid activation function), we have to make sure \n% the range of pixel values is also bounded between [0,1]\npatches = normalizeData(patches);\n\nend\n\n\n%% ---------------------------------------------------------------\nfunction patches = normalizeData(patches)\n\n% Squash data to [0.1, 0.9] since we use sigmoid as the activation\n% function in the output layer\n\n% Remove DC (mean of images). \npatches = bsxfun(@minus, patches, mean(patches));\n\n% Truncate to +/-3 standard deviations and scale to -1 to 1\npstd = 3 * std(patches(:));\npatches = max(min(patches, pstd), -pstd) / pstd;\n\n% Rescale from [-1,1] to [0.1,0.9]\npatches = (patches + 1) * 0.4 + 0.1;\n\nend\n"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "WolfeLineSearch.m", "ext": ".m", "path": "UFLDL-Tutorial-master/sparseae_exercise/starter/minFunc/WolfeLineSearch.m", "size": 11478, "source_encoding": "utf_8", "md5": "d10187f2fedfa4143ebd6300537b6be4", "text": "function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(...\r\n x,t,d,f,g,gtd,c1,c2,LS,maxLS,tolX,debug,doPlot,saveHessianComp,funObj,varargin)\r\n%\r\n% Bracketing Line Search to Satisfy Wolfe Conditions\r\n%\r\n% Inputs:\r\n% x: starting location\r\n% t: initial step size\r\n% d: descent direction\r\n% f: function value at starting location\r\n% g: gradient at starting location\r\n% gtd: directional derivative at starting location\r\n% c1: sufficient decrease parameter\r\n% c2: curvature parameter\r\n% debug: display debugging information\r\n% LS: type of interpolation\r\n% maxLS: maximum number of iterations\r\n% tolX: minimum allowable step length\r\n% doPlot: do a graphical display of interpolation\r\n% funObj: objective function\r\n% varargin: parameters of objective function\r\n%\r\n% Outputs:\r\n% t: step length\r\n% f_new: function value at x+t*d\r\n% g_new: gradient value at x+t*d\r\n% funEvals: number function evaluations performed by line search\r\n% H: Hessian at initial guess (only computed if requested\r\n\r\n% Evaluate the Objective and Gradient at the Initial Step\r\nif nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\nelse\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\nend\r\nfunEvals = 1;\r\ngtd_new = g_new'*d;\r\n\r\n% Bracket an Interval containing a point satisfying the\r\n% Wolfe criteria\r\n\r\nLSiter = 0;\r\nt_prev = 0;\r\nf_prev = f;\r\ng_prev = g;\r\ngtd_prev = gtd;\r\ndone = 0;\r\n\r\nwhile LSiter < maxLS\r\n\r\n %% Bracketing Phase\r\n if ~isLegal(f_new) || ~isLegal(g_new)\r\n if 0\r\n if debug\r\n fprintf('Extrapolated into illegal region, Bisecting\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n continue;\r\n else\r\n if debug\r\n fprintf('Extrapolated into illegal region, switching to Armijo line-search\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n % Do Armijo\r\n if nargout == 5\r\n [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n else\r\n [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n end\r\n funEvals = funEvals + armijoFunEvals;\r\n return;\r\n end\r\n end\r\n\r\n\r\n if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev)\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n elseif abs(gtd_new) <= -c2*gtd\r\n bracket = t;\r\n bracketFval = f_new;\r\n bracketGval = g_new;\r\n done = 1;\r\n break;\r\n elseif gtd_new >= 0\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n end\r\n temp = t_prev;\r\n t_prev = t;\r\n minStep = t + 0.01*(t-temp);\r\n maxStep = t*10;\r\n if LS == 3\r\n if debug\r\n fprintf('Extending Braket\\n');\r\n end\r\n t = maxStep;\r\n elseif LS ==4\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep);\r\n else\r\n t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot);\r\n end\r\n \r\n f_prev = f_new;\r\n g_prev = g_new;\r\n gtd_prev = gtd_new;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\nend\r\n\r\nif LSiter == maxLS\r\n bracket = [0 t];\r\n bracketFval = [f f_new];\r\n bracketGval = [g g_new];\r\nend\r\n\r\n%% Zoom Phase\r\n\r\n% We now either have a point satisfying the criteria, or a bracket\r\n% surrounding a point satisfying the criteria\r\n% Refine the bracket until we find a point satisfying the criteria\r\ninsufProgress = 0;\r\nTpos = 2;\r\nLOposRemoved = 0;\r\nwhile ~done && LSiter < maxLS\r\n\r\n % Find High and Low Points in bracket\r\n [f_LO LOpos] = min(bracketFval);\r\n HIpos = -LOpos + 3;\r\n\r\n % Compute new trial value\r\n if LS == 3 || ~isLegal(bracketFval) || ~isLegal(bracketGval)\r\n if debug\r\n fprintf('Bisecting\\n');\r\n end\r\n t = mean(bracket);\r\n elseif LS == 4\r\n if debug\r\n fprintf('Grad-Cubic Interpolation\\n');\r\n end\r\n t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d\r\n bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot);\r\n else\r\n % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n nonTpos = -Tpos+3;\r\n if LOposRemoved == 0\r\n oldLOval = bracket(nonTpos);\r\n oldLOFval = bracketFval(nonTpos);\r\n oldLOGval = bracketGval(:,nonTpos);\r\n end\r\n t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n end\r\n\r\n\r\n % Test that we are making sufficient progress\r\n if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1\r\n if debug\r\n fprintf('Interpolation close to boundary');\r\n end\r\n if insufProgress || t>=max(bracket) || t <= min(bracket)\r\n if debug\r\n fprintf(', Evaluating at 0.1 away from boundary\\n');\r\n end\r\n if abs(t-max(bracket)) < abs(t-min(bracket))\r\n t = max(bracket)-0.1*(max(bracket)-min(bracket));\r\n else\r\n t = min(bracket)+0.1*(max(bracket)-min(bracket));\r\n end\r\n insufProgress = 0;\r\n else\r\n if debug\r\n fprintf('\\n');\r\n end\r\n insufProgress = 1;\r\n end\r\n else\r\n insufProgress = 0;\r\n end\r\n\r\n % Evaluate new point\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n\r\n if f_new > f + c1*t*gtd || f_new >= f_LO\r\n % Armijo condition not satisfied or not lower than lowest\r\n % point\r\n bracket(HIpos) = t;\r\n bracketFval(HIpos) = f_new;\r\n bracketGval(:,HIpos) = g_new;\r\n Tpos = HIpos;\r\n else\r\n if abs(gtd_new) <= - c2*gtd\r\n % Wolfe conditions satisfied\r\n done = 1;\r\n elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0\r\n % Old HI becomes new LO\r\n bracket(HIpos) = bracket(LOpos);\r\n bracketFval(HIpos) = bracketFval(LOpos);\r\n bracketGval(:,HIpos) = bracketGval(:,LOpos);\r\n if LS == 5\r\n if debug\r\n fprintf('LO Pos is being removed!\\n');\r\n end\r\n LOposRemoved = 1;\r\n oldLOval = bracket(LOpos);\r\n oldLOFval = bracketFval(LOpos);\r\n oldLOGval = bracketGval(:,LOpos);\r\n end\r\n end\r\n % New point becomes new LO\r\n bracket(LOpos) = t;\r\n bracketFval(LOpos) = f_new;\r\n bracketGval(:,LOpos) = g_new;\r\n Tpos = LOpos;\r\n end\r\n\r\n if ~done && abs((bracket(1)-bracket(2))*gtd_new) < tolX\r\n if debug\r\n fprintf('Line Search can not make further progress\\n');\r\n end\r\n break;\r\n end\r\n\r\nend\r\n\r\n%%\r\nif LSiter == maxLS\r\n if debug\r\n fprintf('Line Search Exceeded Maximum Line Search Iterations\\n');\r\n end\r\nend\r\n\r\n[f_LO LOpos] = min(bracketFval);\r\nt = bracket(LOpos);\r\nf_new = bracketFval(LOpos);\r\ng_new = bracketGval(:,LOpos);\r\n\r\n\r\n\r\n% Evaluate Hessian at new point\r\nif nargout == 5 && funEvals > 1 && saveHessianComp\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n funEvals = funEvals + 1;\r\nend\r\n\r\nend\r\n\r\n\r\n%%\r\nfunction [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot);\r\nalpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep);\r\nalpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep);\r\nif alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1)\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\nelse\r\n if debug\r\n fprintf('Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\nend\r\nend\r\n\r\n%%\r\nfunction [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n\r\n% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nnonTpos = -Tpos+3;\r\n\r\ngtdT = bracketGval(:,Tpos)'*d;\r\ngtdNonT = bracketGval(:,nonTpos)'*d;\r\noldLOgtd = oldLOGval'*d;\r\nif bracketFval(Tpos) > oldLOFval\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot);\r\n if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval)\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Mixed Quad/Cubic Interpolation\\n');\r\n end\r\n t = (alpha_q + alpha_c)/2;\r\n end\r\nelseif gtdT'*oldLOgtd < 0\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) sqrt(-1) gtdT],doPlot);\r\n if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Quad Interpolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\nelseif abs(gtdT) <= abs(oldLOgtd)\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n if alpha_c > min(bracket) && alpha_c < max(bracket)\r\n if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Bounded Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n\r\n if bracket(Tpos) > oldLOval\r\n t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n else\r\n t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n end\r\nelse\r\n t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\nend\r\nend"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "minFunc_processInputOptions.m", "ext": ".m", "path": "UFLDL-Tutorial-master/sparseae_exercise/starter/minFunc/minFunc_processInputOptions.m", "size": 3704, "source_encoding": "utf_8", "md5": "dc74c67d849970de7f16c873fcf155bc", "text": "\r\nfunction [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,...\r\n corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,...\r\n HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...\r\n DerivativeCheck,Damped,HvFunc,bbType,cycle,...\r\n HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ...\r\n minFunc_processInputOptions(o)\r\n\r\n% Constants\r\nSD = 0;\r\nCSD = 1;\r\nBB = 2;\r\nCG = 3;\r\nPCG = 4;\r\nLBFGS = 5;\r\nQNEWTON = 6;\r\nNEWTON0 = 7;\r\nNEWTON = 8;\r\nTENSOR = 9;\r\n\r\nverbose = 1;\r\nverboseI= 1;\r\ndebug = 0;\r\ndoPlot = 0;\r\nmethod = LBFGS;\r\ncgSolve = 0;\r\n\r\no = toUpper(o);\r\n\r\nif isfield(o,'DISPLAY')\r\n switch(upper(o.DISPLAY))\r\n case 0\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FINAL'\r\n verboseI = 0;\r\n case 'OFF'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'NONE'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FULL'\r\n debug = 1;\r\n case 'EXCESSIVE'\r\n debug = 1;\r\n doPlot = 1;\r\n end\r\nend\r\n\r\n\r\nLS_init = 0;\r\nc2 = 0.9;\r\nLS = 4;\r\nFref = 1;\r\nDamped = 0;\r\nHessianIter = 1;\r\nif isfield(o,'METHOD')\r\n m = upper(o.METHOD);\r\n switch(m)\r\n case 'TENSOR'\r\n method = TENSOR;\r\n case 'NEWTON'\r\n method = NEWTON;\r\n case 'MNEWTON'\r\n method = NEWTON;\r\n HessianIter = 5;\r\n case 'PNEWTON0'\r\n method = NEWTON0;\r\n cgSolve = 1;\r\n case 'NEWTON0'\r\n method = NEWTON0;\r\n case 'QNEWTON'\r\n method = QNEWTON;\r\n Damped = 1;\r\n case 'LBFGS'\r\n method = LBFGS;\r\n case 'BB'\r\n method = BB;\r\n LS = 2;\r\n Fref = 20;\r\n case 'PCG'\r\n method = PCG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'SCG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 4;\r\n case 'CG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'CSD'\r\n method = CSD;\r\n c2 = 0.2;\r\n Fref = 10;\r\n LS_init = 2;\r\n case 'SD'\r\n method = SD;\r\n LS_init = 2;\r\n end\r\nend\r\n\r\nmaxFunEvals = getOpt(o,'MAXFUNEVALS',1000);\r\nmaxIter = getOpt(o,'MAXITER',500);\r\ntolFun = getOpt(o,'TOLFUN',1e-5);\r\ntolX = getOpt(o,'TOLX',1e-9);\r\ncorrections = getOpt(o,'CORR',100);\r\nc1 = getOpt(o,'C1',1e-4);\r\nc2 = getOpt(o,'C2',c2);\r\nLS_init = getOpt(o,'LS_INIT',LS_init);\r\nLS = getOpt(o,'LS',LS);\r\ncgSolve = getOpt(o,'CGSOLVE',cgSolve);\r\nqnUpdate = getOpt(o,'QNUPDATE',3);\r\ncgUpdate = getOpt(o,'CGUPDATE',2);\r\ninitialHessType = getOpt(o,'INITIALHESSTYPE',1);\r\nHessianModify = getOpt(o,'HESSIANMODIFY',0);\r\nFref = getOpt(o,'FREF',Fref);\r\nuseComplex = getOpt(o,'USECOMPLEX',0);\r\nnumDiff = getOpt(o,'NUMDIFF',0);\r\nLS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1);\r\nDerivativeCheck = getOpt(o,'DERIVATIVECHECK',0);\r\nDamped = getOpt(o,'DAMPED',Damped);\r\nHvFunc = getOpt(o,'HVFUNC',[]);\r\nbbType = getOpt(o,'BBTYPE',0);\r\ncycle = getOpt(o,'CYCLE',3);\r\nHessianIter = getOpt(o,'HESSIANITER',HessianIter);\r\noutputFcn = getOpt(o,'OUTPUTFCN',[]);\r\nuseMex = getOpt(o,'USEMEX',1);\r\nuseNegCurv = getOpt(o,'USENEGCURV',1);\r\nprecFunc = getOpt(o,'PRECFUNC',[]);\r\nend\r\n\r\nfunction [v] = getOpt(options,opt,default)\r\nif isfield(options,opt)\r\n if ~isempty(getfield(options,opt))\r\n v = getfield(options,opt);\r\n else\r\n v = default;\r\n end\r\nelse\r\n v = default;\r\nend\r\nend\r\n\r\nfunction [o] = toUpper(o)\r\nif ~isempty(o)\r\n fn = fieldnames(o);\r\n for i = 1:length(fn)\r\n o = setfield(o,upper(fn{i}),getfield(o,fn{i}));\r\n end\r\nend\r\nend"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "WolfeLineSearch.m", "ext": ".m", "path": "UFLDL-Tutorial-master/softmax_exercise/minFunc/WolfeLineSearch.m", "size": 11478, "source_encoding": "utf_8", "md5": "d10187f2fedfa4143ebd6300537b6be4", "text": "function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(...\r\n x,t,d,f,g,gtd,c1,c2,LS,maxLS,tolX,debug,doPlot,saveHessianComp,funObj,varargin)\r\n%\r\n% Bracketing Line Search to Satisfy Wolfe Conditions\r\n%\r\n% Inputs:\r\n% x: starting location\r\n% t: initial step size\r\n% d: descent direction\r\n% f: function value at starting location\r\n% g: gradient at starting location\r\n% gtd: directional derivative at starting location\r\n% c1: sufficient decrease parameter\r\n% c2: curvature parameter\r\n% debug: display debugging information\r\n% LS: type of interpolation\r\n% maxLS: maximum number of iterations\r\n% tolX: minimum allowable step length\r\n% doPlot: do a graphical display of interpolation\r\n% funObj: objective function\r\n% varargin: parameters of objective function\r\n%\r\n% Outputs:\r\n% t: step length\r\n% f_new: function value at x+t*d\r\n% g_new: gradient value at x+t*d\r\n% funEvals: number function evaluations performed by line search\r\n% H: Hessian at initial guess (only computed if requested\r\n\r\n% Evaluate the Objective and Gradient at the Initial Step\r\nif nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\nelse\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\nend\r\nfunEvals = 1;\r\ngtd_new = g_new'*d;\r\n\r\n% Bracket an Interval containing a point satisfying the\r\n% Wolfe criteria\r\n\r\nLSiter = 0;\r\nt_prev = 0;\r\nf_prev = f;\r\ng_prev = g;\r\ngtd_prev = gtd;\r\ndone = 0;\r\n\r\nwhile LSiter < maxLS\r\n\r\n %% Bracketing Phase\r\n if ~isLegal(f_new) || ~isLegal(g_new)\r\n if 0\r\n if debug\r\n fprintf('Extrapolated into illegal region, Bisecting\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n continue;\r\n else\r\n if debug\r\n fprintf('Extrapolated into illegal region, switching to Armijo line-search\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n % Do Armijo\r\n if nargout == 5\r\n [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n else\r\n [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n end\r\n funEvals = funEvals + armijoFunEvals;\r\n return;\r\n end\r\n end\r\n\r\n\r\n if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev)\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n elseif abs(gtd_new) <= -c2*gtd\r\n bracket = t;\r\n bracketFval = f_new;\r\n bracketGval = g_new;\r\n done = 1;\r\n break;\r\n elseif gtd_new >= 0\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n end\r\n temp = t_prev;\r\n t_prev = t;\r\n minStep = t + 0.01*(t-temp);\r\n maxStep = t*10;\r\n if LS == 3\r\n if debug\r\n fprintf('Extending Braket\\n');\r\n end\r\n t = maxStep;\r\n elseif LS ==4\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep);\r\n else\r\n t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot);\r\n end\r\n \r\n f_prev = f_new;\r\n g_prev = g_new;\r\n gtd_prev = gtd_new;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\nend\r\n\r\nif LSiter == maxLS\r\n bracket = [0 t];\r\n bracketFval = [f f_new];\r\n bracketGval = [g g_new];\r\nend\r\n\r\n%% Zoom Phase\r\n\r\n% We now either have a point satisfying the criteria, or a bracket\r\n% surrounding a point satisfying the criteria\r\n% Refine the bracket until we find a point satisfying the criteria\r\ninsufProgress = 0;\r\nTpos = 2;\r\nLOposRemoved = 0;\r\nwhile ~done && LSiter < maxLS\r\n\r\n % Find High and Low Points in bracket\r\n [f_LO LOpos] = min(bracketFval);\r\n HIpos = -LOpos + 3;\r\n\r\n % Compute new trial value\r\n if LS == 3 || ~isLegal(bracketFval) || ~isLegal(bracketGval)\r\n if debug\r\n fprintf('Bisecting\\n');\r\n end\r\n t = mean(bracket);\r\n elseif LS == 4\r\n if debug\r\n fprintf('Grad-Cubic Interpolation\\n');\r\n end\r\n t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d\r\n bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot);\r\n else\r\n % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n nonTpos = -Tpos+3;\r\n if LOposRemoved == 0\r\n oldLOval = bracket(nonTpos);\r\n oldLOFval = bracketFval(nonTpos);\r\n oldLOGval = bracketGval(:,nonTpos);\r\n end\r\n t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n end\r\n\r\n\r\n % Test that we are making sufficient progress\r\n if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1\r\n if debug\r\n fprintf('Interpolation close to boundary');\r\n end\r\n if insufProgress || t>=max(bracket) || t <= min(bracket)\r\n if debug\r\n fprintf(', Evaluating at 0.1 away from boundary\\n');\r\n end\r\n if abs(t-max(bracket)) < abs(t-min(bracket))\r\n t = max(bracket)-0.1*(max(bracket)-min(bracket));\r\n else\r\n t = min(bracket)+0.1*(max(bracket)-min(bracket));\r\n end\r\n insufProgress = 0;\r\n else\r\n if debug\r\n fprintf('\\n');\r\n end\r\n insufProgress = 1;\r\n end\r\n else\r\n insufProgress = 0;\r\n end\r\n\r\n % Evaluate new point\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n\r\n if f_new > f + c1*t*gtd || f_new >= f_LO\r\n % Armijo condition not satisfied or not lower than lowest\r\n % point\r\n bracket(HIpos) = t;\r\n bracketFval(HIpos) = f_new;\r\n bracketGval(:,HIpos) = g_new;\r\n Tpos = HIpos;\r\n else\r\n if abs(gtd_new) <= - c2*gtd\r\n % Wolfe conditions satisfied\r\n done = 1;\r\n elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0\r\n % Old HI becomes new LO\r\n bracket(HIpos) = bracket(LOpos);\r\n bracketFval(HIpos) = bracketFval(LOpos);\r\n bracketGval(:,HIpos) = bracketGval(:,LOpos);\r\n if LS == 5\r\n if debug\r\n fprintf('LO Pos is being removed!\\n');\r\n end\r\n LOposRemoved = 1;\r\n oldLOval = bracket(LOpos);\r\n oldLOFval = bracketFval(LOpos);\r\n oldLOGval = bracketGval(:,LOpos);\r\n end\r\n end\r\n % New point becomes new LO\r\n bracket(LOpos) = t;\r\n bracketFval(LOpos) = f_new;\r\n bracketGval(:,LOpos) = g_new;\r\n Tpos = LOpos;\r\n end\r\n\r\n if ~done && abs((bracket(1)-bracket(2))*gtd_new) < tolX\r\n if debug\r\n fprintf('Line Search can not make further progress\\n');\r\n end\r\n break;\r\n end\r\n\r\nend\r\n\r\n%%\r\nif LSiter == maxLS\r\n if debug\r\n fprintf('Line Search Exceeded Maximum Line Search Iterations\\n');\r\n end\r\nend\r\n\r\n[f_LO LOpos] = min(bracketFval);\r\nt = bracket(LOpos);\r\nf_new = bracketFval(LOpos);\r\ng_new = bracketGval(:,LOpos);\r\n\r\n\r\n\r\n% Evaluate Hessian at new point\r\nif nargout == 5 && funEvals > 1 && saveHessianComp\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n funEvals = funEvals + 1;\r\nend\r\n\r\nend\r\n\r\n\r\n%%\r\nfunction [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot);\r\nalpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep);\r\nalpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep);\r\nif alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1)\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\nelse\r\n if debug\r\n fprintf('Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\nend\r\nend\r\n\r\n%%\r\nfunction [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n\r\n% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nnonTpos = -Tpos+3;\r\n\r\ngtdT = bracketGval(:,Tpos)'*d;\r\ngtdNonT = bracketGval(:,nonTpos)'*d;\r\noldLOgtd = oldLOGval'*d;\r\nif bracketFval(Tpos) > oldLOFval\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot);\r\n if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval)\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Mixed Quad/Cubic Interpolation\\n');\r\n end\r\n t = (alpha_q + alpha_c)/2;\r\n end\r\nelseif gtdT'*oldLOgtd < 0\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) sqrt(-1) gtdT],doPlot);\r\n if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Quad Interpolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\nelseif abs(gtdT) <= abs(oldLOgtd)\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n if alpha_c > min(bracket) && alpha_c < max(bracket)\r\n if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Bounded Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n\r\n if bracket(Tpos) > oldLOval\r\n t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n else\r\n t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n end\r\nelse\r\n t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\nend\r\nend"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "minFunc_processInputOptions.m", "ext": ".m", "path": "UFLDL-Tutorial-master/softmax_exercise/minFunc/minFunc_processInputOptions.m", "size": 3704, "source_encoding": "utf_8", "md5": "dc74c67d849970de7f16c873fcf155bc", "text": "\r\nfunction [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,...\r\n corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,...\r\n HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...\r\n DerivativeCheck,Damped,HvFunc,bbType,cycle,...\r\n HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ...\r\n minFunc_processInputOptions(o)\r\n\r\n% Constants\r\nSD = 0;\r\nCSD = 1;\r\nBB = 2;\r\nCG = 3;\r\nPCG = 4;\r\nLBFGS = 5;\r\nQNEWTON = 6;\r\nNEWTON0 = 7;\r\nNEWTON = 8;\r\nTENSOR = 9;\r\n\r\nverbose = 1;\r\nverboseI= 1;\r\ndebug = 0;\r\ndoPlot = 0;\r\nmethod = LBFGS;\r\ncgSolve = 0;\r\n\r\no = toUpper(o);\r\n\r\nif isfield(o,'DISPLAY')\r\n switch(upper(o.DISPLAY))\r\n case 0\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FINAL'\r\n verboseI = 0;\r\n case 'OFF'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'NONE'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FULL'\r\n debug = 1;\r\n case 'EXCESSIVE'\r\n debug = 1;\r\n doPlot = 1;\r\n end\r\nend\r\n\r\n\r\nLS_init = 0;\r\nc2 = 0.9;\r\nLS = 4;\r\nFref = 1;\r\nDamped = 0;\r\nHessianIter = 1;\r\nif isfield(o,'METHOD')\r\n m = upper(o.METHOD);\r\n switch(m)\r\n case 'TENSOR'\r\n method = TENSOR;\r\n case 'NEWTON'\r\n method = NEWTON;\r\n case 'MNEWTON'\r\n method = NEWTON;\r\n HessianIter = 5;\r\n case 'PNEWTON0'\r\n method = NEWTON0;\r\n cgSolve = 1;\r\n case 'NEWTON0'\r\n method = NEWTON0;\r\n case 'QNEWTON'\r\n method = QNEWTON;\r\n Damped = 1;\r\n case 'LBFGS'\r\n method = LBFGS;\r\n case 'BB'\r\n method = BB;\r\n LS = 2;\r\n Fref = 20;\r\n case 'PCG'\r\n method = PCG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'SCG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 4;\r\n case 'CG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'CSD'\r\n method = CSD;\r\n c2 = 0.2;\r\n Fref = 10;\r\n LS_init = 2;\r\n case 'SD'\r\n method = SD;\r\n LS_init = 2;\r\n end\r\nend\r\n\r\nmaxFunEvals = getOpt(o,'MAXFUNEVALS',1000);\r\nmaxIter = getOpt(o,'MAXITER',500);\r\ntolFun = getOpt(o,'TOLFUN',1e-5);\r\ntolX = getOpt(o,'TOLX',1e-9);\r\ncorrections = getOpt(o,'CORR',100);\r\nc1 = getOpt(o,'C1',1e-4);\r\nc2 = getOpt(o,'C2',c2);\r\nLS_init = getOpt(o,'LS_INIT',LS_init);\r\nLS = getOpt(o,'LS',LS);\r\ncgSolve = getOpt(o,'CGSOLVE',cgSolve);\r\nqnUpdate = getOpt(o,'QNUPDATE',3);\r\ncgUpdate = getOpt(o,'CGUPDATE',2);\r\ninitialHessType = getOpt(o,'INITIALHESSTYPE',1);\r\nHessianModify = getOpt(o,'HESSIANMODIFY',0);\r\nFref = getOpt(o,'FREF',Fref);\r\nuseComplex = getOpt(o,'USECOMPLEX',0);\r\nnumDiff = getOpt(o,'NUMDIFF',0);\r\nLS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1);\r\nDerivativeCheck = getOpt(o,'DERIVATIVECHECK',0);\r\nDamped = getOpt(o,'DAMPED',Damped);\r\nHvFunc = getOpt(o,'HVFUNC',[]);\r\nbbType = getOpt(o,'BBTYPE',0);\r\ncycle = getOpt(o,'CYCLE',3);\r\nHessianIter = getOpt(o,'HESSIANITER',HessianIter);\r\noutputFcn = getOpt(o,'OUTPUTFCN',[]);\r\nuseMex = getOpt(o,'USEMEX',1);\r\nuseNegCurv = getOpt(o,'USENEGCURV',1);\r\nprecFunc = getOpt(o,'PRECFUNC',[]);\r\nend\r\n\r\nfunction [v] = getOpt(options,opt,default)\r\nif isfield(options,opt)\r\n if ~isempty(getfield(options,opt))\r\n v = getfield(options,opt);\r\n else\r\n v = default;\r\n end\r\nelse\r\n v = default;\r\nend\r\nend\r\n\r\nfunction [o] = toUpper(o)\r\nif ~isempty(o)\r\n fn = fieldnames(o);\r\n for i = 1:length(fn)\r\n o = setfield(o,upper(fn{i}),getfield(o,fn{i}));\r\n end\r\nend\r\nend"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "sparseAutoencoderCost.m", "ext": ".m", "path": "UFLDL-Tutorial-master/stl_exercise/sparseAutoencoderCost.m", "size": 4803, "source_encoding": "utf_8", "md5": "08ee2296b7f8fc2b5f0a0f87be847df9", "text": "function [cost,grad] = sparseAutoencoderCost(theta, visibleSize, hiddenSize, ...\n lambda, sparsityParam, beta, data)\n\n% visibleSize: the number of input units (probably 64) \n% hiddenSize: the number of hidden units (probably 25) \n% lambda: weight decay parameter\n% sparsityParam: The desired average activation for the hidden units (denoted in the lecture\n% notes by the greek alphabet rho, which looks like a lower-case \"p\").\n% beta: weight of sparsity penalty term\n% data: Our 64x10000 matrix containing the training data. So, data(:,i) is the i-th training example. \n \n% The input theta is a vector (because minFunc expects the parameters to be a vector). \n% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this \n% follows the notation convention of the lecture notes. \n\nW1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);\nW2 = reshape(theta(hiddenSize*visibleSize+1:2*hiddenSize*visibleSize), visibleSize, hiddenSize);\nb1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);\nb2 = theta(2*hiddenSize*visibleSize+hiddenSize+1:end);\n\n% Cost and gradient variables (your code needs to compute these values). \n% Here, we initialize them to zeros. \ncost = 0;\nW1grad = zeros(size(W1)); \nW2grad = zeros(size(W2));\nb1grad = zeros(size(b1)); \nb2grad = zeros(size(b2));\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Compute the cost/optimization objective J_sparse(W,b) for the Sparse Autoencoder,\n% and the corresponding gradients W1grad, W2grad, b1grad, b2grad.\n%\n% W1grad, W2grad, b1grad and b2grad should be computed using backpropagation.\n% Note that W1grad has the same dimensions as W1, b1grad has the same dimensions\n% as b1, etc. Your code should set W1grad to be the partial derivative of J_sparse(W,b) with\n% respect to W1. I.e., W1grad(i,j) should be the partial derivative of J_sparse(W,b) \n% with respect to the input parameter W1(i,j). Thus, W1grad should be equal to the term \n% [(1/m) \\Delta W^{(1)} + \\lambda W^{(1)}] in the last block of pseudo-code in Section 2.2 \n% of the lecture notes (and similarly for W2grad, b1grad, b2grad).\n% \n% Stated differently, if we were using batch gradient descent to optimize the parameters,\n% the gradient descent update to W1 would be W1 := W1 - alpha * W1grad, and similarly for W2, b1, b2. \n% \n\n[netIn, trExamples] = size(data);\n\nm = trExamples;\n\npartCost = 0;\n\nDW1 = zeros(size(W1));\nDW2 = zeros(size(W2));\nDb1 = zeros(size(b1));\nDb2 = zeros(size(b2));\n\n% compute rho\ny = data;\nx = y;\na1 = x;\nz2 = W1*a1 + repmat(b1,1,size(a1,2));\na2 = sigmoid(z2);\n\nrho = 1/size(x,2)*sum(a2,2);\n\n% Forward propagation\ny = data;\nx = y;\na1 = x;\nz2 = W1*a1 + repmat(b1,1,m);\na2 = sigmoid(z2);\nz3 = W2*a2 + repmat(b2,1,m);\na3 = sigmoid(z3);\nhx = a3;\n\n% Back propagation\npartCost = 1/2*sqrt(sum(abs(hx-y).^2,1)).^2;%sum(1/2*sqrt(dot(hx-y,hx-y,2)).^2);%trace(1/2*sqrt((hx - y)'*(hx - y)).^2);\n\ndelta3 = -(y-a3).*a3.*(1-a3);\ndelta2 = (W2'*delta3 +...\n repmat(beta*(-sparsityParam./rho + (1-sparsityParam)./(1-rho)),1,m)).*a2.*(1-a2);\n\nDW1 = delta2*a1';\nDb1 = sum(delta2,2);\nDW2 = delta3*a2';\nDb2 = sum(delta3,2);\n\n% Compute cost:\n% with lambda = 0 and beta = 0\n% cost = 1/m * partCost;\n% with beta = 0;\ncost = 1/m * sum(partCost) + lambda/2 * sum([sum(sum(W1.^2)) sum(sum(W2.^2))]);\n\n% Add sparsity term\ncost = cost + beta*sum(compKL(sparsityParam,rho));\n\n% Compute W1grad:\n% with lambda = 0 and beta = 0\n% W1grad = 1/m * DW1;\n% with beta = 0;\nW1grad = 1/m * DW1 + lambda * W1;\n\n% Compute W2grad:\n% with lambda = 0 and beta = 0\n% W2grad = 1/m * DW2;\n% with beta = 0;\nW2grad = 1/m * DW2 + lambda * W2;\n\n% Compute b1grad:\n% with lambda = 0 and beta = 0\n% b1grad = 1/m * Db1;\n% with beta = 0;\nb1grad = 1/m * Db1;\n\n% Compute b2grad:\n% with lambda = 0 and beta = 0\n% b2grad = 1/m * Db2;\n% with beta = 0;\nb2grad = 1/m * Db2;\n\n%-------------------------------------------------------------------\n% After computing the cost and gradient, we will convert the gradients back\n% to a vector format (suitable for minFunc). Specifically, we will unroll\n% your gradient matrices into a vector.\n\ngrad = [W1grad(:) ; W2grad(:) ; b1grad(:) ; b2grad(:)];\n\nend\n\nfunction kl = compKL(sparsityParam, rho)\n\n kl = sum(sparsityParam.*log(sparsityParam./rho) +...\n (1-sparsityParam).*log((1-sparsityParam)./(1-rho)));\n\nend\n\n%-------------------------------------------------------------------\n% Here's an implementation of the sigmoid function, which you may find useful\n% in your computation of the costs and the gradients. This inputs a (row or\n% column) vector (say (z1, z2, z3)) and returns (f(z1), f(z2), f(z3)). \n\nfunction sigm = sigmoid(x)\n \n sigm = 1 ./ (1 + exp(-x));\nend\n\n"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "feedForwardAutoencoder.m", "ext": ".m", "path": "UFLDL-Tutorial-master/stl_exercise/feedForwardAutoencoder.m", "size": 1321, "source_encoding": "utf_8", "md5": "3b9592dd9c982beab9320d5588d238cd", "text": "function [activation] = feedForwardAutoencoder(theta, hiddenSize, visibleSize, data)\n\n% theta: trained weights from the autoencoder\n% visibleSize: the number of input units (probably 64) \n% hiddenSize: the number of hidden units (probably 25) \n% data: Our matrix containing the training data as columns. So, data(:,i) is the i-th training example. \n \n% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this \n% follows the notation convention of the lecture notes. \n\nW1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);\nb1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Compute the activation of the hidden layer for the Sparse Autoencoder.\n\na1 = data;\nz2 = W1*a1 + repmat(b1,1,size(a1,2));\na2 = sigmoid(z2);\nactivation = a2;\n\n%-------------------------------------------------------------------\n\nend\n\n%-------------------------------------------------------------------\n% Here's an implementation of the sigmoid function, which you may find useful\n% in your computation of the costs and the gradients. This inputs a (row or\n% column) vector (say (z1, z2, z3)) and returns (f(z1), f(z2), f(z3)). \n\nfunction sigm = sigmoid(x)\n sigm = 1 ./ (1 + exp(-x));\nend\n"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "WolfeLineSearch.m", "ext": ".m", "path": "UFLDL-Tutorial-master/stl_exercise/minFunc/WolfeLineSearch.m", "size": 11478, "source_encoding": "utf_8", "md5": "d10187f2fedfa4143ebd6300537b6be4", "text": "function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(...\r\n x,t,d,f,g,gtd,c1,c2,LS,maxLS,tolX,debug,doPlot,saveHessianComp,funObj,varargin)\r\n%\r\n% Bracketing Line Search to Satisfy Wolfe Conditions\r\n%\r\n% Inputs:\r\n% x: starting location\r\n% t: initial step size\r\n% d: descent direction\r\n% f: function value at starting location\r\n% g: gradient at starting location\r\n% gtd: directional derivative at starting location\r\n% c1: sufficient decrease parameter\r\n% c2: curvature parameter\r\n% debug: display debugging information\r\n% LS: type of interpolation\r\n% maxLS: maximum number of iterations\r\n% tolX: minimum allowable step length\r\n% doPlot: do a graphical display of interpolation\r\n% funObj: objective function\r\n% varargin: parameters of objective function\r\n%\r\n% Outputs:\r\n% t: step length\r\n% f_new: function value at x+t*d\r\n% g_new: gradient value at x+t*d\r\n% funEvals: number function evaluations performed by line search\r\n% H: Hessian at initial guess (only computed if requested\r\n\r\n% Evaluate the Objective and Gradient at the Initial Step\r\nif nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\nelse\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\nend\r\nfunEvals = 1;\r\ngtd_new = g_new'*d;\r\n\r\n% Bracket an Interval containing a point satisfying the\r\n% Wolfe criteria\r\n\r\nLSiter = 0;\r\nt_prev = 0;\r\nf_prev = f;\r\ng_prev = g;\r\ngtd_prev = gtd;\r\ndone = 0;\r\n\r\nwhile LSiter < maxLS\r\n\r\n %% Bracketing Phase\r\n if ~isLegal(f_new) || ~isLegal(g_new)\r\n if 0\r\n if debug\r\n fprintf('Extrapolated into illegal region, Bisecting\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n continue;\r\n else\r\n if debug\r\n fprintf('Extrapolated into illegal region, switching to Armijo line-search\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n % Do Armijo\r\n if nargout == 5\r\n [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n else\r\n [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n end\r\n funEvals = funEvals + armijoFunEvals;\r\n return;\r\n end\r\n end\r\n\r\n\r\n if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev)\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n elseif abs(gtd_new) <= -c2*gtd\r\n bracket = t;\r\n bracketFval = f_new;\r\n bracketGval = g_new;\r\n done = 1;\r\n break;\r\n elseif gtd_new >= 0\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n end\r\n temp = t_prev;\r\n t_prev = t;\r\n minStep = t + 0.01*(t-temp);\r\n maxStep = t*10;\r\n if LS == 3\r\n if debug\r\n fprintf('Extending Braket\\n');\r\n end\r\n t = maxStep;\r\n elseif LS ==4\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep);\r\n else\r\n t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot);\r\n end\r\n \r\n f_prev = f_new;\r\n g_prev = g_new;\r\n gtd_prev = gtd_new;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\nend\r\n\r\nif LSiter == maxLS\r\n bracket = [0 t];\r\n bracketFval = [f f_new];\r\n bracketGval = [g g_new];\r\nend\r\n\r\n%% Zoom Phase\r\n\r\n% We now either have a point satisfying the criteria, or a bracket\r\n% surrounding a point satisfying the criteria\r\n% Refine the bracket until we find a point satisfying the criteria\r\ninsufProgress = 0;\r\nTpos = 2;\r\nLOposRemoved = 0;\r\nwhile ~done && LSiter < maxLS\r\n\r\n % Find High and Low Points in bracket\r\n [f_LO LOpos] = min(bracketFval);\r\n HIpos = -LOpos + 3;\r\n\r\n % Compute new trial value\r\n if LS == 3 || ~isLegal(bracketFval) || ~isLegal(bracketGval)\r\n if debug\r\n fprintf('Bisecting\\n');\r\n end\r\n t = mean(bracket);\r\n elseif LS == 4\r\n if debug\r\n fprintf('Grad-Cubic Interpolation\\n');\r\n end\r\n t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d\r\n bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot);\r\n else\r\n % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n nonTpos = -Tpos+3;\r\n if LOposRemoved == 0\r\n oldLOval = bracket(nonTpos);\r\n oldLOFval = bracketFval(nonTpos);\r\n oldLOGval = bracketGval(:,nonTpos);\r\n end\r\n t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n end\r\n\r\n\r\n % Test that we are making sufficient progress\r\n if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1\r\n if debug\r\n fprintf('Interpolation close to boundary');\r\n end\r\n if insufProgress || t>=max(bracket) || t <= min(bracket)\r\n if debug\r\n fprintf(', Evaluating at 0.1 away from boundary\\n');\r\n end\r\n if abs(t-max(bracket)) < abs(t-min(bracket))\r\n t = max(bracket)-0.1*(max(bracket)-min(bracket));\r\n else\r\n t = min(bracket)+0.1*(max(bracket)-min(bracket));\r\n end\r\n insufProgress = 0;\r\n else\r\n if debug\r\n fprintf('\\n');\r\n end\r\n insufProgress = 1;\r\n end\r\n else\r\n insufProgress = 0;\r\n end\r\n\r\n % Evaluate new point\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n\r\n if f_new > f + c1*t*gtd || f_new >= f_LO\r\n % Armijo condition not satisfied or not lower than lowest\r\n % point\r\n bracket(HIpos) = t;\r\n bracketFval(HIpos) = f_new;\r\n bracketGval(:,HIpos) = g_new;\r\n Tpos = HIpos;\r\n else\r\n if abs(gtd_new) <= - c2*gtd\r\n % Wolfe conditions satisfied\r\n done = 1;\r\n elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0\r\n % Old HI becomes new LO\r\n bracket(HIpos) = bracket(LOpos);\r\n bracketFval(HIpos) = bracketFval(LOpos);\r\n bracketGval(:,HIpos) = bracketGval(:,LOpos);\r\n if LS == 5\r\n if debug\r\n fprintf('LO Pos is being removed!\\n');\r\n end\r\n LOposRemoved = 1;\r\n oldLOval = bracket(LOpos);\r\n oldLOFval = bracketFval(LOpos);\r\n oldLOGval = bracketGval(:,LOpos);\r\n end\r\n end\r\n % New point becomes new LO\r\n bracket(LOpos) = t;\r\n bracketFval(LOpos) = f_new;\r\n bracketGval(:,LOpos) = g_new;\r\n Tpos = LOpos;\r\n end\r\n\r\n if ~done && abs((bracket(1)-bracket(2))*gtd_new) < tolX\r\n if debug\r\n fprintf('Line Search can not make further progress\\n');\r\n end\r\n break;\r\n end\r\n\r\nend\r\n\r\n%%\r\nif LSiter == maxLS\r\n if debug\r\n fprintf('Line Search Exceeded Maximum Line Search Iterations\\n');\r\n end\r\nend\r\n\r\n[f_LO LOpos] = min(bracketFval);\r\nt = bracket(LOpos);\r\nf_new = bracketFval(LOpos);\r\ng_new = bracketGval(:,LOpos);\r\n\r\n\r\n\r\n% Evaluate Hessian at new point\r\nif nargout == 5 && funEvals > 1 && saveHessianComp\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n funEvals = funEvals + 1;\r\nend\r\n\r\nend\r\n\r\n\r\n%%\r\nfunction [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot);\r\nalpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep);\r\nalpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep);\r\nif alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1)\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\nelse\r\n if debug\r\n fprintf('Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\nend\r\nend\r\n\r\n%%\r\nfunction [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n\r\n% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nnonTpos = -Tpos+3;\r\n\r\ngtdT = bracketGval(:,Tpos)'*d;\r\ngtdNonT = bracketGval(:,nonTpos)'*d;\r\noldLOgtd = oldLOGval'*d;\r\nif bracketFval(Tpos) > oldLOFval\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot);\r\n if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval)\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Mixed Quad/Cubic Interpolation\\n');\r\n end\r\n t = (alpha_q + alpha_c)/2;\r\n end\r\nelseif gtdT'*oldLOgtd < 0\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) sqrt(-1) gtdT],doPlot);\r\n if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Quad Interpolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\nelseif abs(gtdT) <= abs(oldLOgtd)\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n if alpha_c > min(bracket) && alpha_c < max(bracket)\r\n if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Bounded Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n\r\n if bracket(Tpos) > oldLOval\r\n t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n else\r\n t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n end\r\nelse\r\n t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\nend\r\nend"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "minFunc_processInputOptions.m", "ext": ".m", "path": "UFLDL-Tutorial-master/stl_exercise/minFunc/minFunc_processInputOptions.m", "size": 3704, "source_encoding": "utf_8", "md5": "dc74c67d849970de7f16c873fcf155bc", "text": "\r\nfunction [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,...\r\n corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,...\r\n HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...\r\n DerivativeCheck,Damped,HvFunc,bbType,cycle,...\r\n HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ...\r\n minFunc_processInputOptions(o)\r\n\r\n% Constants\r\nSD = 0;\r\nCSD = 1;\r\nBB = 2;\r\nCG = 3;\r\nPCG = 4;\r\nLBFGS = 5;\r\nQNEWTON = 6;\r\nNEWTON0 = 7;\r\nNEWTON = 8;\r\nTENSOR = 9;\r\n\r\nverbose = 1;\r\nverboseI= 1;\r\ndebug = 0;\r\ndoPlot = 0;\r\nmethod = LBFGS;\r\ncgSolve = 0;\r\n\r\no = toUpper(o);\r\n\r\nif isfield(o,'DISPLAY')\r\n switch(upper(o.DISPLAY))\r\n case 0\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FINAL'\r\n verboseI = 0;\r\n case 'OFF'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'NONE'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FULL'\r\n debug = 1;\r\n case 'EXCESSIVE'\r\n debug = 1;\r\n doPlot = 1;\r\n end\r\nend\r\n\r\n\r\nLS_init = 0;\r\nc2 = 0.9;\r\nLS = 4;\r\nFref = 1;\r\nDamped = 0;\r\nHessianIter = 1;\r\nif isfield(o,'METHOD')\r\n m = upper(o.METHOD);\r\n switch(m)\r\n case 'TENSOR'\r\n method = TENSOR;\r\n case 'NEWTON'\r\n method = NEWTON;\r\n case 'MNEWTON'\r\n method = NEWTON;\r\n HessianIter = 5;\r\n case 'PNEWTON0'\r\n method = NEWTON0;\r\n cgSolve = 1;\r\n case 'NEWTON0'\r\n method = NEWTON0;\r\n case 'QNEWTON'\r\n method = QNEWTON;\r\n Damped = 1;\r\n case 'LBFGS'\r\n method = LBFGS;\r\n case 'BB'\r\n method = BB;\r\n LS = 2;\r\n Fref = 20;\r\n case 'PCG'\r\n method = PCG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'SCG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 4;\r\n case 'CG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'CSD'\r\n method = CSD;\r\n c2 = 0.2;\r\n Fref = 10;\r\n LS_init = 2;\r\n case 'SD'\r\n method = SD;\r\n LS_init = 2;\r\n end\r\nend\r\n\r\nmaxFunEvals = getOpt(o,'MAXFUNEVALS',1000);\r\nmaxIter = getOpt(o,'MAXITER',500);\r\ntolFun = getOpt(o,'TOLFUN',1e-5);\r\ntolX = getOpt(o,'TOLX',1e-9);\r\ncorrections = getOpt(o,'CORR',100);\r\nc1 = getOpt(o,'C1',1e-4);\r\nc2 = getOpt(o,'C2',c2);\r\nLS_init = getOpt(o,'LS_INIT',LS_init);\r\nLS = getOpt(o,'LS',LS);\r\ncgSolve = getOpt(o,'CGSOLVE',cgSolve);\r\nqnUpdate = getOpt(o,'QNUPDATE',3);\r\ncgUpdate = getOpt(o,'CGUPDATE',2);\r\ninitialHessType = getOpt(o,'INITIALHESSTYPE',1);\r\nHessianModify = getOpt(o,'HESSIANMODIFY',0);\r\nFref = getOpt(o,'FREF',Fref);\r\nuseComplex = getOpt(o,'USECOMPLEX',0);\r\nnumDiff = getOpt(o,'NUMDIFF',0);\r\nLS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1);\r\nDerivativeCheck = getOpt(o,'DERIVATIVECHECK',0);\r\nDamped = getOpt(o,'DAMPED',Damped);\r\nHvFunc = getOpt(o,'HVFUNC',[]);\r\nbbType = getOpt(o,'BBTYPE',0);\r\ncycle = getOpt(o,'CYCLE',3);\r\nHessianIter = getOpt(o,'HESSIANITER',HessianIter);\r\noutputFcn = getOpt(o,'OUTPUTFCN',[]);\r\nuseMex = getOpt(o,'USEMEX',1);\r\nuseNegCurv = getOpt(o,'USENEGCURV',1);\r\nprecFunc = getOpt(o,'PRECFUNC',[]);\r\nend\r\n\r\nfunction [v] = getOpt(options,opt,default)\r\nif isfield(options,opt)\r\n if ~isempty(getfield(options,opt))\r\n v = getfield(options,opt);\r\n else\r\n v = default;\r\n end\r\nelse\r\n v = default;\r\nend\r\nend\r\n\r\nfunction [o] = toUpper(o)\r\nif ~isempty(o)\r\n fn = fieldnames(o);\r\n for i = 1:length(fn)\r\n o = setfield(o,upper(fn{i}),getfield(o,fn{i}));\r\n end\r\nend\r\nend"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "checkNumericalGradient.m", "ext": ".m", "path": "UFLDL-Tutorial-master/sparseae_exercise_vectorized/starter/checkNumericalGradient.m", "size": 1982, "source_encoding": "utf_8", "md5": "689a352eb2927b0838af5dc508f6374d", "text": "function [] = checkNumericalGradient()\n% This code can be used to check your numerical gradient implementation \n% in computeNumericalGradient.m\n% It analytically evaluates the gradient of a very simple function called\n% simpleQuadraticFunction (see below) and compares the result with your numerical\n% solution. Your numerical gradient implementation is incorrect if\n% your numerical solution deviates too much from the analytical solution.\n \n% Evaluate the function and gradient at x = [4; 10]; (Here, x is a 2d vector.)\nx = [4; 10];\n[value, grad] = simpleQuadraticFunction(x);\n\n% Use your code to numerically compute the gradient of simpleQuadraticFunction at x.\n% (The notation \"@simpleQuadraticFunction\" denotes a pointer to a function.)\nnumgrad = computeNumericalGradient(@simpleQuadraticFunction, x);\n\n% Visually examine the two gradient computations. The two columns\n% you get should be very similar. \ndisp([numgrad grad]);\nfprintf('The above two columns you get should be very similar.\\n(Left-Your Numerical Gradient, Right-Analytical Gradient)\\n\\n');\n\n% Evaluate the norm of the difference between two solutions. \n% If you have a correct implementation, and assuming you used EPSILON = 0.0001 \n% in computeNumericalGradient.m, then diff below should be 2.1452e-12 \ndiff = norm(numgrad-grad)/norm(numgrad+grad);\ndisp(diff); \nfprintf('Norm of the difference between numerical and analytical gradient (should be < 1e-9)\\n\\n');\nend\n\n\n \nfunction [value,grad] = simpleQuadraticFunction(x)\n% this function accepts a 2D vector as input. \n% Its outputs are:\n% value: h(x1, x2) = x1^2 + 3*x1*x2\n% grad: A 2x1 vector that gives the partial derivatives of h with respect to x1 and x2 \n% Note that when we pass @simpleQuadraticFunction(x) to computeNumericalGradients, we're assuming\n% that computeNumericalGradients will use only the first returned value of this function.\n\nvalue = x(1)^2 + 3*x(1)*x(2);\n\ngrad = zeros(2, 1);\ngrad(1) = 2*x(1) + 3*x(2);\ngrad(2) = 3*x(1);\n\nend\n"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "sparseAutoencoderCost.m", "ext": ".m", "path": "UFLDL-Tutorial-master/sparseae_exercise_vectorized/starter/sparseAutoencoderCost.m", "size": 4803, "source_encoding": "utf_8", "md5": "08ee2296b7f8fc2b5f0a0f87be847df9", "text": "function [cost,grad] = sparseAutoencoderCost(theta, visibleSize, hiddenSize, ...\n lambda, sparsityParam, beta, data)\n\n% visibleSize: the number of input units (probably 64) \n% hiddenSize: the number of hidden units (probably 25) \n% lambda: weight decay parameter\n% sparsityParam: The desired average activation for the hidden units (denoted in the lecture\n% notes by the greek alphabet rho, which looks like a lower-case \"p\").\n% beta: weight of sparsity penalty term\n% data: Our 64x10000 matrix containing the training data. So, data(:,i) is the i-th training example. \n \n% The input theta is a vector (because minFunc expects the parameters to be a vector). \n% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this \n% follows the notation convention of the lecture notes. \n\nW1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);\nW2 = reshape(theta(hiddenSize*visibleSize+1:2*hiddenSize*visibleSize), visibleSize, hiddenSize);\nb1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);\nb2 = theta(2*hiddenSize*visibleSize+hiddenSize+1:end);\n\n% Cost and gradient variables (your code needs to compute these values). \n% Here, we initialize them to zeros. \ncost = 0;\nW1grad = zeros(size(W1)); \nW2grad = zeros(size(W2));\nb1grad = zeros(size(b1)); \nb2grad = zeros(size(b2));\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Compute the cost/optimization objective J_sparse(W,b) for the Sparse Autoencoder,\n% and the corresponding gradients W1grad, W2grad, b1grad, b2grad.\n%\n% W1grad, W2grad, b1grad and b2grad should be computed using backpropagation.\n% Note that W1grad has the same dimensions as W1, b1grad has the same dimensions\n% as b1, etc. Your code should set W1grad to be the partial derivative of J_sparse(W,b) with\n% respect to W1. I.e., W1grad(i,j) should be the partial derivative of J_sparse(W,b) \n% with respect to the input parameter W1(i,j). Thus, W1grad should be equal to the term \n% [(1/m) \\Delta W^{(1)} + \\lambda W^{(1)}] in the last block of pseudo-code in Section 2.2 \n% of the lecture notes (and similarly for W2grad, b1grad, b2grad).\n% \n% Stated differently, if we were using batch gradient descent to optimize the parameters,\n% the gradient descent update to W1 would be W1 := W1 - alpha * W1grad, and similarly for W2, b1, b2. \n% \n\n[netIn, trExamples] = size(data);\n\nm = trExamples;\n\npartCost = 0;\n\nDW1 = zeros(size(W1));\nDW2 = zeros(size(W2));\nDb1 = zeros(size(b1));\nDb2 = zeros(size(b2));\n\n% compute rho\ny = data;\nx = y;\na1 = x;\nz2 = W1*a1 + repmat(b1,1,size(a1,2));\na2 = sigmoid(z2);\n\nrho = 1/size(x,2)*sum(a2,2);\n\n% Forward propagation\ny = data;\nx = y;\na1 = x;\nz2 = W1*a1 + repmat(b1,1,m);\na2 = sigmoid(z2);\nz3 = W2*a2 + repmat(b2,1,m);\na3 = sigmoid(z3);\nhx = a3;\n\n% Back propagation\npartCost = 1/2*sqrt(sum(abs(hx-y).^2,1)).^2;%sum(1/2*sqrt(dot(hx-y,hx-y,2)).^2);%trace(1/2*sqrt((hx - y)'*(hx - y)).^2);\n\ndelta3 = -(y-a3).*a3.*(1-a3);\ndelta2 = (W2'*delta3 +...\n repmat(beta*(-sparsityParam./rho + (1-sparsityParam)./(1-rho)),1,m)).*a2.*(1-a2);\n\nDW1 = delta2*a1';\nDb1 = sum(delta2,2);\nDW2 = delta3*a2';\nDb2 = sum(delta3,2);\n\n% Compute cost:\n% with lambda = 0 and beta = 0\n% cost = 1/m * partCost;\n% with beta = 0;\ncost = 1/m * sum(partCost) + lambda/2 * sum([sum(sum(W1.^2)) sum(sum(W2.^2))]);\n\n% Add sparsity term\ncost = cost + beta*sum(compKL(sparsityParam,rho));\n\n% Compute W1grad:\n% with lambda = 0 and beta = 0\n% W1grad = 1/m * DW1;\n% with beta = 0;\nW1grad = 1/m * DW1 + lambda * W1;\n\n% Compute W2grad:\n% with lambda = 0 and beta = 0\n% W2grad = 1/m * DW2;\n% with beta = 0;\nW2grad = 1/m * DW2 + lambda * W2;\n\n% Compute b1grad:\n% with lambda = 0 and beta = 0\n% b1grad = 1/m * Db1;\n% with beta = 0;\nb1grad = 1/m * Db1;\n\n% Compute b2grad:\n% with lambda = 0 and beta = 0\n% b2grad = 1/m * Db2;\n% with beta = 0;\nb2grad = 1/m * Db2;\n\n%-------------------------------------------------------------------\n% After computing the cost and gradient, we will convert the gradients back\n% to a vector format (suitable for minFunc). Specifically, we will unroll\n% your gradient matrices into a vector.\n\ngrad = [W1grad(:) ; W2grad(:) ; b1grad(:) ; b2grad(:)];\n\nend\n\nfunction kl = compKL(sparsityParam, rho)\n\n kl = sum(sparsityParam.*log(sparsityParam./rho) +...\n (1-sparsityParam).*log((1-sparsityParam)./(1-rho)));\n\nend\n\n%-------------------------------------------------------------------\n% Here's an implementation of the sigmoid function, which you may find useful\n% in your computation of the costs and the gradients. This inputs a (row or\n% column) vector (say (z1, z2, z3)) and returns (f(z1), f(z2), f(z3)). \n\nfunction sigm = sigmoid(x)\n \n sigm = 1 ./ (1 + exp(-x));\nend\n\n"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "sampleIMAGES.m", "ext": ".m", "path": "UFLDL-Tutorial-master/sparseae_exercise_vectorized/starter/sampleIMAGES.m", "size": 2361, "source_encoding": "utf_8", "md5": "5bc148213efc91f20fe2ca18f84b7469", "text": "function patches = sampleIMAGES()\n% sampleIMAGES\n% Returns 10000 patches for training\n\nload IMAGES; % load images from disk \n\npatchsize = 8; % we'll use 8x8 patches \nnumpatches = 10000;\n\n% Initialize patches with zeros. Your code will fill in this matrix--one\n% column per patch, 10000 columns. \npatches = zeros(patchsize*patchsize, numpatches);\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Fill in the variable called \"patches\" using data \n% from IMAGES. \n% \n% IMAGES is a 3D array containing 10 images\n% For instance, IMAGES(:,:,6) is a 512x512 array containing the 6th image,\n% and you can type \"imagesc(IMAGES(:,:,6)), colormap gray;\" to visualize\n% it. (The contrast on these images look a bit off because they have\n% been preprocessed using using \"whitening.\" See the lecture notes for\n% more details.) As a second example, IMAGES(21:30,21:30,1) is an image\n% patch corresponding to the pixels in the block (21,21) to (30,30) of\n% Image 1\n\n% MAYBE(?):\n% It can also be implemented in a vectorized for; generate all imIndex,\n% xIndex, yIndex at once and the take all patches at once.\n[X,Y,N] = size(IMAGES);\n\nimageSample = zeros(patchsize,patchsize);\n\nfor i = 1:numpatches\n \n imIndex = ceil(N*rand);\n xIndex = ceil((X-patchsize)*rand);\n yIndex = ceil((Y-patchsize)*rand);\n \n imageSample = IMAGES(xIndex:xIndex+patchsize-1,yIndex:yIndex+patchsize-1,imIndex);\n \n patches(:,i) = imageSample(:);\nend\n\n\n%% ---------------------------------------------------------------\n% For the autoencoder to work well we need to normalize the data\n% Specifically, since the output of the network is bounded between [0,1]\n% (due to the sigmoid activation function), we have to make sure \n% the range of pixel values is also bounded between [0,1]\npatches = normalizeData(patches);\n\nend\n\n\n%% ---------------------------------------------------------------\nfunction patches = normalizeData(patches)\n\n% Squash data to [0.1, 0.9] since we use sigmoid as the activation\n% function in the output layer\n\n% Remove DC (mean of images). \npatches = bsxfun(@minus, patches, mean(patches));\n\n% Truncate to +/-3 standard deviations and scale to -1 to 1\npstd = 3 * std(patches(:));\npatches = max(min(patches, pstd), -pstd) / pstd;\n\n% Rescale from [-1,1] to [0.1,0.9]\npatches = (patches + 1) * 0.4 + 0.1;\n\nend\n"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "WolfeLineSearch.m", "ext": ".m", "path": "UFLDL-Tutorial-master/sparseae_exercise_vectorized/starter/minFunc/WolfeLineSearch.m", "size": 11478, "source_encoding": "utf_8", "md5": "d10187f2fedfa4143ebd6300537b6be4", "text": "function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(...\r\n x,t,d,f,g,gtd,c1,c2,LS,maxLS,tolX,debug,doPlot,saveHessianComp,funObj,varargin)\r\n%\r\n% Bracketing Line Search to Satisfy Wolfe Conditions\r\n%\r\n% Inputs:\r\n% x: starting location\r\n% t: initial step size\r\n% d: descent direction\r\n% f: function value at starting location\r\n% g: gradient at starting location\r\n% gtd: directional derivative at starting location\r\n% c1: sufficient decrease parameter\r\n% c2: curvature parameter\r\n% debug: display debugging information\r\n% LS: type of interpolation\r\n% maxLS: maximum number of iterations\r\n% tolX: minimum allowable step length\r\n% doPlot: do a graphical display of interpolation\r\n% funObj: objective function\r\n% varargin: parameters of objective function\r\n%\r\n% Outputs:\r\n% t: step length\r\n% f_new: function value at x+t*d\r\n% g_new: gradient value at x+t*d\r\n% funEvals: number function evaluations performed by line search\r\n% H: Hessian at initial guess (only computed if requested\r\n\r\n% Evaluate the Objective and Gradient at the Initial Step\r\nif nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\nelse\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\nend\r\nfunEvals = 1;\r\ngtd_new = g_new'*d;\r\n\r\n% Bracket an Interval containing a point satisfying the\r\n% Wolfe criteria\r\n\r\nLSiter = 0;\r\nt_prev = 0;\r\nf_prev = f;\r\ng_prev = g;\r\ngtd_prev = gtd;\r\ndone = 0;\r\n\r\nwhile LSiter < maxLS\r\n\r\n %% Bracketing Phase\r\n if ~isLegal(f_new) || ~isLegal(g_new)\r\n if 0\r\n if debug\r\n fprintf('Extrapolated into illegal region, Bisecting\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n continue;\r\n else\r\n if debug\r\n fprintf('Extrapolated into illegal region, switching to Armijo line-search\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n % Do Armijo\r\n if nargout == 5\r\n [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n else\r\n [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n end\r\n funEvals = funEvals + armijoFunEvals;\r\n return;\r\n end\r\n end\r\n\r\n\r\n if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev)\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n elseif abs(gtd_new) <= -c2*gtd\r\n bracket = t;\r\n bracketFval = f_new;\r\n bracketGval = g_new;\r\n done = 1;\r\n break;\r\n elseif gtd_new >= 0\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n end\r\n temp = t_prev;\r\n t_prev = t;\r\n minStep = t + 0.01*(t-temp);\r\n maxStep = t*10;\r\n if LS == 3\r\n if debug\r\n fprintf('Extending Braket\\n');\r\n end\r\n t = maxStep;\r\n elseif LS ==4\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep);\r\n else\r\n t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot);\r\n end\r\n \r\n f_prev = f_new;\r\n g_prev = g_new;\r\n gtd_prev = gtd_new;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\nend\r\n\r\nif LSiter == maxLS\r\n bracket = [0 t];\r\n bracketFval = [f f_new];\r\n bracketGval = [g g_new];\r\nend\r\n\r\n%% Zoom Phase\r\n\r\n% We now either have a point satisfying the criteria, or a bracket\r\n% surrounding a point satisfying the criteria\r\n% Refine the bracket until we find a point satisfying the criteria\r\ninsufProgress = 0;\r\nTpos = 2;\r\nLOposRemoved = 0;\r\nwhile ~done && LSiter < maxLS\r\n\r\n % Find High and Low Points in bracket\r\n [f_LO LOpos] = min(bracketFval);\r\n HIpos = -LOpos + 3;\r\n\r\n % Compute new trial value\r\n if LS == 3 || ~isLegal(bracketFval) || ~isLegal(bracketGval)\r\n if debug\r\n fprintf('Bisecting\\n');\r\n end\r\n t = mean(bracket);\r\n elseif LS == 4\r\n if debug\r\n fprintf('Grad-Cubic Interpolation\\n');\r\n end\r\n t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d\r\n bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot);\r\n else\r\n % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n nonTpos = -Tpos+3;\r\n if LOposRemoved == 0\r\n oldLOval = bracket(nonTpos);\r\n oldLOFval = bracketFval(nonTpos);\r\n oldLOGval = bracketGval(:,nonTpos);\r\n end\r\n t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n end\r\n\r\n\r\n % Test that we are making sufficient progress\r\n if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1\r\n if debug\r\n fprintf('Interpolation close to boundary');\r\n end\r\n if insufProgress || t>=max(bracket) || t <= min(bracket)\r\n if debug\r\n fprintf(', Evaluating at 0.1 away from boundary\\n');\r\n end\r\n if abs(t-max(bracket)) < abs(t-min(bracket))\r\n t = max(bracket)-0.1*(max(bracket)-min(bracket));\r\n else\r\n t = min(bracket)+0.1*(max(bracket)-min(bracket));\r\n end\r\n insufProgress = 0;\r\n else\r\n if debug\r\n fprintf('\\n');\r\n end\r\n insufProgress = 1;\r\n end\r\n else\r\n insufProgress = 0;\r\n end\r\n\r\n % Evaluate new point\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n\r\n if f_new > f + c1*t*gtd || f_new >= f_LO\r\n % Armijo condition not satisfied or not lower than lowest\r\n % point\r\n bracket(HIpos) = t;\r\n bracketFval(HIpos) = f_new;\r\n bracketGval(:,HIpos) = g_new;\r\n Tpos = HIpos;\r\n else\r\n if abs(gtd_new) <= - c2*gtd\r\n % Wolfe conditions satisfied\r\n done = 1;\r\n elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0\r\n % Old HI becomes new LO\r\n bracket(HIpos) = bracket(LOpos);\r\n bracketFval(HIpos) = bracketFval(LOpos);\r\n bracketGval(:,HIpos) = bracketGval(:,LOpos);\r\n if LS == 5\r\n if debug\r\n fprintf('LO Pos is being removed!\\n');\r\n end\r\n LOposRemoved = 1;\r\n oldLOval = bracket(LOpos);\r\n oldLOFval = bracketFval(LOpos);\r\n oldLOGval = bracketGval(:,LOpos);\r\n end\r\n end\r\n % New point becomes new LO\r\n bracket(LOpos) = t;\r\n bracketFval(LOpos) = f_new;\r\n bracketGval(:,LOpos) = g_new;\r\n Tpos = LOpos;\r\n end\r\n\r\n if ~done && abs((bracket(1)-bracket(2))*gtd_new) < tolX\r\n if debug\r\n fprintf('Line Search can not make further progress\\n');\r\n end\r\n break;\r\n end\r\n\r\nend\r\n\r\n%%\r\nif LSiter == maxLS\r\n if debug\r\n fprintf('Line Search Exceeded Maximum Line Search Iterations\\n');\r\n end\r\nend\r\n\r\n[f_LO LOpos] = min(bracketFval);\r\nt = bracket(LOpos);\r\nf_new = bracketFval(LOpos);\r\ng_new = bracketGval(:,LOpos);\r\n\r\n\r\n\r\n% Evaluate Hessian at new point\r\nif nargout == 5 && funEvals > 1 && saveHessianComp\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n funEvals = funEvals + 1;\r\nend\r\n\r\nend\r\n\r\n\r\n%%\r\nfunction [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot);\r\nalpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep);\r\nalpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep);\r\nif alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1)\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\nelse\r\n if debug\r\n fprintf('Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\nend\r\nend\r\n\r\n%%\r\nfunction [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n\r\n% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nnonTpos = -Tpos+3;\r\n\r\ngtdT = bracketGval(:,Tpos)'*d;\r\ngtdNonT = bracketGval(:,nonTpos)'*d;\r\noldLOgtd = oldLOGval'*d;\r\nif bracketFval(Tpos) > oldLOFval\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot);\r\n if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval)\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Mixed Quad/Cubic Interpolation\\n');\r\n end\r\n t = (alpha_q + alpha_c)/2;\r\n end\r\nelseif gtdT'*oldLOgtd < 0\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) sqrt(-1) gtdT],doPlot);\r\n if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Quad Interpolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\nelseif abs(gtdT) <= abs(oldLOgtd)\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n if alpha_c > min(bracket) && alpha_c < max(bracket)\r\n if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Bounded Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n\r\n if bracket(Tpos) > oldLOval\r\n t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n else\r\n t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n end\r\nelse\r\n t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\nend\r\nend"} +{"plateform": "github", "repo_name": "cNikolaou/UFLDL-Tutorial-master", "name": "minFunc_processInputOptions.m", "ext": ".m", "path": "UFLDL-Tutorial-master/sparseae_exercise_vectorized/starter/minFunc/minFunc_processInputOptions.m", "size": 3704, "source_encoding": "utf_8", "md5": "dc74c67d849970de7f16c873fcf155bc", "text": "\r\nfunction [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,...\r\n corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,...\r\n HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...\r\n DerivativeCheck,Damped,HvFunc,bbType,cycle,...\r\n HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ...\r\n minFunc_processInputOptions(o)\r\n\r\n% Constants\r\nSD = 0;\r\nCSD = 1;\r\nBB = 2;\r\nCG = 3;\r\nPCG = 4;\r\nLBFGS = 5;\r\nQNEWTON = 6;\r\nNEWTON0 = 7;\r\nNEWTON = 8;\r\nTENSOR = 9;\r\n\r\nverbose = 1;\r\nverboseI= 1;\r\ndebug = 0;\r\ndoPlot = 0;\r\nmethod = LBFGS;\r\ncgSolve = 0;\r\n\r\no = toUpper(o);\r\n\r\nif isfield(o,'DISPLAY')\r\n switch(upper(o.DISPLAY))\r\n case 0\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FINAL'\r\n verboseI = 0;\r\n case 'OFF'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'NONE'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FULL'\r\n debug = 1;\r\n case 'EXCESSIVE'\r\n debug = 1;\r\n doPlot = 1;\r\n end\r\nend\r\n\r\n\r\nLS_init = 0;\r\nc2 = 0.9;\r\nLS = 4;\r\nFref = 1;\r\nDamped = 0;\r\nHessianIter = 1;\r\nif isfield(o,'METHOD')\r\n m = upper(o.METHOD);\r\n switch(m)\r\n case 'TENSOR'\r\n method = TENSOR;\r\n case 'NEWTON'\r\n method = NEWTON;\r\n case 'MNEWTON'\r\n method = NEWTON;\r\n HessianIter = 5;\r\n case 'PNEWTON0'\r\n method = NEWTON0;\r\n cgSolve = 1;\r\n case 'NEWTON0'\r\n method = NEWTON0;\r\n case 'QNEWTON'\r\n method = QNEWTON;\r\n Damped = 1;\r\n case 'LBFGS'\r\n method = LBFGS;\r\n case 'BB'\r\n method = BB;\r\n LS = 2;\r\n Fref = 20;\r\n case 'PCG'\r\n method = PCG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'SCG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 4;\r\n case 'CG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'CSD'\r\n method = CSD;\r\n c2 = 0.2;\r\n Fref = 10;\r\n LS_init = 2;\r\n case 'SD'\r\n method = SD;\r\n LS_init = 2;\r\n end\r\nend\r\n\r\nmaxFunEvals = getOpt(o,'MAXFUNEVALS',1000);\r\nmaxIter = getOpt(o,'MAXITER',500);\r\ntolFun = getOpt(o,'TOLFUN',1e-5);\r\ntolX = getOpt(o,'TOLX',1e-9);\r\ncorrections = getOpt(o,'CORR',100);\r\nc1 = getOpt(o,'C1',1e-4);\r\nc2 = getOpt(o,'C2',c2);\r\nLS_init = getOpt(o,'LS_INIT',LS_init);\r\nLS = getOpt(o,'LS',LS);\r\ncgSolve = getOpt(o,'CGSOLVE',cgSolve);\r\nqnUpdate = getOpt(o,'QNUPDATE',3);\r\ncgUpdate = getOpt(o,'CGUPDATE',2);\r\ninitialHessType = getOpt(o,'INITIALHESSTYPE',1);\r\nHessianModify = getOpt(o,'HESSIANMODIFY',0);\r\nFref = getOpt(o,'FREF',Fref);\r\nuseComplex = getOpt(o,'USECOMPLEX',0);\r\nnumDiff = getOpt(o,'NUMDIFF',0);\r\nLS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1);\r\nDerivativeCheck = getOpt(o,'DERIVATIVECHECK',0);\r\nDamped = getOpt(o,'DAMPED',Damped);\r\nHvFunc = getOpt(o,'HVFUNC',[]);\r\nbbType = getOpt(o,'BBTYPE',0);\r\ncycle = getOpt(o,'CYCLE',3);\r\nHessianIter = getOpt(o,'HESSIANITER',HessianIter);\r\noutputFcn = getOpt(o,'OUTPUTFCN',[]);\r\nuseMex = getOpt(o,'USEMEX',1);\r\nuseNegCurv = getOpt(o,'USENEGCURV',1);\r\nprecFunc = getOpt(o,'PRECFUNC',[]);\r\nend\r\n\r\nfunction [v] = getOpt(options,opt,default)\r\nif isfield(options,opt)\r\n if ~isempty(getfield(options,opt))\r\n v = getfield(options,opt);\r\n else\r\n v = default;\r\n end\r\nelse\r\n v = default;\r\nend\r\nend\r\n\r\nfunction [o] = toUpper(o)\r\nif ~isempty(o)\r\n fn = fieldnames(o);\r\n for i = 1:length(fn)\r\n o = setfield(o,upper(fn{i}),getfield(o,fn{i}));\r\n end\r\nend\r\nend"} +{"plateform": "github", "repo_name": "plartoo/product_image_classifier-main", "name": "plotKeypoints.m", "ext": ".m", "path": "product_image_classifier-main/plotKeypoints.m", "size": 956, "source_encoding": "utf_8", "md5": "c46418fa72acd11d4f6c441794743989", "text": "% plotKeypoints.m\n% Plot selected keypoints.\n\n% Run as \n% plotKeypoints('../images/la_pointy_21',1,50,'_nKeypoints=10000_keypointDetector=canny_sigmaPdf=oneOverXto0.5')\n\nfunction plotKeypoints(stemFileName,minSigma,minSiftNorm,howChoseKeypoints)\n\n[f d] = loadDescriptors(stemFileName,minSigma,minSiftNorm,howChoseKeypoints);\nf = f'; % they're reversed from the usual order\nd = d'; % same as above\n\n% To show points on image, uncomment below.\njpgFile = strcat(stemFileName,'.jpg');\nimshow(jpgFile);\nhold on;\nnShow = round(size(f,1) / 1);\nrandPermutation = randperm(size(f,1));\ncandidatesToShow = randPermutation(1:nShow);\nx = round(f(candidatesToShow,1));\ny = round(f(candidatesToShow,2));\nsigmas = f(candidatesToShow,3);\nMAX_SIGMA_SHOW = 10;\nsmallEnoughSigmas = find(sigmas=0),'vector1 must be nonnegative.');\nassert(all(vector2>=0),'vector2 must be nonnegative.');\nvector1 = vector1 / sum(vector1);\nvector2 = vector2 / sum(vector2);\n\n% Because we can't divide by 0, we should only include terms in the\n% chi-square sum for which vector1+vector2 at a particular index is > 0.\npositiveIndicies = find(vector1+vector2);\npositiveVector1 = vector1(positiveIndicies);\npositiveVector2 = vector2(positiveIndicies);\ndist = .5 * sum((positiveVector1 - positiveVector2).^2 ./ (positiveVector1 + positiveVector2));"} +{"plateform": "github", "repo_name": "plartoo/product_image_classifier-main", "name": "signatureDistances.m", "ext": ".m", "path": "product_image_classifier-main/signatureDistances.m", "size": 1788, "source_encoding": "utf_8", "md5": "dfff891d216d986fd0b37a859813f929", "text": "% signatureDistances.m\n% curSignature: column vector (already converted to double)\n% otherSignatures: matrix with # cols == # other signatures (already\n% converted to double)\n\nfunction distanceVector = ...\n signatureDistances(curSignature,otherSignatures,varargin)\n\n% Set constants.\nDEFAULT = 2*pi+3.2342; % some random value\n\n% Get input.\nparser = inputParser;\nparser.FunctionName = 'signatureDistances';\nparser.addRequired('curSignature');\nparser.addRequired('otherSignatures');\nparser.addParamValue('metric', 'cosine', @(x)any(strcmpi(x,{'L1','cosine','expchi2'})));\nparser.addParamValue('expchi2Avg', DEFAULT, @(x)x>0);\nparser.parse(curSignature,otherSignatures,varargin{:});\ncurSignature = parser.Results.curSignature;\notherSignatures = parser.Results.otherSignatures;\nmetric = parser.Results.metric;\nexpchi2Avg = parser.Results.expchi2Avg;\n\n% Choose metric.\nswitch metric\n case 'cosine'\n u = otherSignatures;\n v = repmat(curSignature,1,size(otherSignatures,2));\n cosines = sum(u .* v) ./ sqrt(sum(u .* u) .* sum(v .* v));\n assert(all(cosines>=0));\n assert(all(cosines<=1));\n distanceVector = 1 - cosines;\n case 'L1'\n u = otherSignatures;\n v = repmat(curSignature,1,size(otherSignatures,2));\n distanceVector = sum(abs(u-v));\n % The \"double\" command turns int8s to doubles.\n case 'expchi2'\n assert(expchi2Avg~=DEFAULT,'need to provide expchi2Avg!');\n distanceVector = zeros(1,size(otherSignatures,2));\n for col = 1:size(otherSignatures,2)\n distanceVector(col) = ...\n 1 - exp(-chi2Dist(curSignature,otherSignatures(:,col)) / expchi2Avg);\n end\n assert(all(all(distanceVector>=0)));\n otherwise\n error('Not a distance metric.');\nend"} +{"plateform": "github", "repo_name": "plartoo/product_image_classifier-main", "name": "writeDescriptionOfRun.m", "ext": ".m", "path": "product_image_classifier-main/writeDescriptionOfRun.m", "size": 4578, "source_encoding": "utf_8", "md5": "751065e87788cdaeb78c92348afa7060", "text": "% Write a text file that describes the parameters, images, etc. used in\n% this run.\n\nfunction writeDescriptionOfRun(fullFolderName,paramStruct,view,...\n imageNamesByNumber,results,varargin)\n\n% Get input.\nparser = inputParser;\nparser.FunctionName = 'writeDescriptionOfRun';\nparser.addRequired('fullFolderName');\nparser.addRequired('paramStruct');\nparser.addRequired('view');\nparser.addRequired('imageNamesByNumber');\nparser.addRequired('results');\nparser.parse(fullFolderName,paramStruct,view,imageNamesByNumber,...\n results,varargin{:});\nfullFolderName = parser.Results.fullFolderName;\nparamStruct = parser.Results.paramStruct;\nview = parser.Results.view;\nimageNamesByNumber = parser.Results.imageNamesByNumber;\nresults = parser.Results.results;\n\n% Open file.\nfileName = fullfile(fullFolderName,'readme.txt');\ntry\n file = fopen(fileName,'w');\n\n % Write parameters.\n fprintf(file,'************************************\\n');\n fprintf(file,'Printed %s.\\n',datestr(now));\n fprintf(file,'Elapsed time = %f seconds.\\n',results.timeElapsed);\n fprintf(file,'\\nParameters:\\n');\n fprintf(file,'view=%s\\n',view);\n fprintf(file,'classifier=%s\\n',paramStruct.classifier);\n fprintf(file,'k=%i\\n',paramStruct.k);\n fprintf(file,'fracDataTestOn=%g\\n',paramStruct.fracDataTestOn);\n fprintf(file,'data_min_sigma=%g\\n',paramStruct.data_min_sigma);\n fprintf(file,'data_shuffle=%i\\n',paramStruct.data_shuffle);\n fprintf(file,'tree_fair_data=%i\\n',paramStruct.tree_fair_data);\n fprintf(file,'tree_limit_data=%g\\n',paramStruct.tree_limit_data);\n fprintf(file,'tree_K=%i\\n',paramStruct.tree_K);\n fprintf(file,'tree_nleaves=%i\\n',paramStruct.tree_nleaves);\n fprintf(file,'keypointDetector=%s\\n',paramStruct.keypointDetector);\n fprintf(file,'sigmaPdf=%s\\n',paramStruct.sigmaPdfAsString);\n fprintf(file,'tree_restrict_to_train=%i\\n',paramStruct.tree_restrict_to_train);\n fprintf(file,'stat_downsample=%g\\n',paramStruct.stat_downsample);\n fprintf(file,'fracTrainExToVote=%g\\n',paramStruct.fracTrainExToVote);\n fprintf(file,'zScoreVoting=%i\\n',paramStruct.zScoreVoting);\n fprintf(file,'minSiftNorm=%i\\n',paramStruct.minSiftNorm);\n fprintf(file,'nKeypoints=%i\\n',paramStruct.nKeypoints);\n %fprintf(file,'cutoff=%g\\n',paramStruct.cutoff);\n fprintf(file,'maxViewsPerProduct=%i\\n',paramStruct.maxViewsPerProduct);\n fprintf(file,'combineDistances=%s\\n',paramStruct.combineDistances);\n fprintf(file,'signatureDistance=%s\\n',paramStruct.signatureDistance);\n fprintf(file,'leaveOneOut=%i\\n',paramStruct.leaveOneOut);\n fprintf(file,'coeffForPhog=%f\\n',paramStruct.coeffForPhog);\n fprintf(file,'maxProductsPerCategory=%i\\n',paramStruct.maxProductsPerCategory);\n\n % Write results.\n fprintf(file,'\\nResults:\\n');\n fprintf(file,'Accuracy=%g +/- %g\\n',results.accuracy,results.stdAccuracy);\n fprintf(file,'Class-size-adjusted accuracy=%g +/- %g\\n',...\n results.classSizeAdjustedAccuracy,...\n results.stdClassSizeAdjustedAccuracy);\n fprintf(file,'p-value of chi2 test=%g\\n',results.pVal);\n fprintf(file,'Raw confusion matrix:\\n');\n fclose(file);\n dlmwrite(fileName,results.confMatrix,'-append','roffset',0,...\n 'delimiter',' ','precision','%.2i');\n file = fopen(fileName,'a');\n fprintf(file,'Normalized confusion matrix:\\n');\n fclose(file);\n dlmwrite(fileName,results.normConfMatrix,'-append','roffset',0,...\n 'delimiter',' ','precision','%.2g');\n file = fopen(fileName,'a');\n\n % Write misclassifications.\n fprintf(file,'\\nMisclassifications:\\n');\n for cat = 1:length(paramStruct.categories)\n fprintf(file,'\\tYou wrongly said these were %s:\\n',paramStruct.categories{cat});\n for i = 1:length(results.misclassifications{cat})\n fprintf(file,'\\t\\t%s\\n',results.misclassifications{cat}{i});\n end\n end\n\n % Write images.\n fprintf(file,'\\nImages and their categories:\\n');\n for cat = 1:length(imageNamesByNumber)\n nImagesThisCat = 0;\n fprintf(file,'%s\\n',paramStruct.categories{cat});\n for num = 1:length(imageNamesByNumber{cat})\n for imgView = 1:length(imageNamesByNumber{cat}{num})\n fprintf(file,'\\t%s\\n',imageNamesByNumber{cat}{num}{imgView});\n nImagesThisCat = nImagesThisCat + 1;\n end\n end\n fprintf(file,'\\t\\tApprox # training examples = %.0f\\n',...\n nImagesThisCat * (1-paramStruct.fracDataTestOn));\n end\n fprintf(file,'************************************\\n');\n\n % Close file.\n fclose(file);\nend"} +{"plateform": "github", "repo_name": "plartoo/product_image_classifier-main", "name": "sigmasRandom.m", "ext": ".m", "path": "product_image_classifier-main/sigmasRandom.m", "size": 927, "source_encoding": "utf_8", "md5": "0b8e7d4c8969e941a8d30b0eb90bc5fe", "text": "% sigmasRandom.m\n% Produce a nSigmas x 1 vector of random sigma values such that their inverses\n% are uniformly distributed.\n\nfunction randSigmas = sigmasRandom(nSigmas,min,max,sigmaPdf)\n\n% Get input.\nparser = inputParser;\nparser.FunctionName = 'sigmasRandom';\nparser.addRequired('nSigmas', @(x)x>0);\nparser.addRequired('min', @(x)x>0);\nparser.addRequired('max', @(x)x>0);\nparser.addRequired('sigmaPdf');\nparser.parse(nSigmas,min,max,sigmaPdf);\nnSigmas = parser.Results.nSigmas;\nmin = parser.Results.min;\nmax = parser.Results.max;\nassert(max > min);\nsigmaPdf = parser.Results.sigmaPdf;\n\n% Make cdf.\nmin = round(min);\nmax = round(max);\nsupport = min:max;\nrawPdf = arrayfun(sigmaPdf,support);\npdf = rawPdf / sum(rawPdf);\ncdf = [0 cumsum(pdf)];\n\n% Return result.\nrandSigmas = zeros(nSigmas,1);\nfor i = 1:nSigmas\n position = find(cdf0);\nparser.parse(curPhog,otherPhogs,expchi2Avg,varargin{:});\ncurPhog = parser.Results.curPhog;\notherPhogs = parser.Results.otherPhogs;\nexpchi2Avg = parser.Results.expchi2Avg;\n\n% Compute distances.\ndistanceVector = zeros(1,size(otherPhogs,2));\nfor col = 1:size(otherPhogs,2)\n distanceVector(col) = ...\n 1 - exp(-chi2Dist(curPhog,otherPhogs(:,col)) / expchi2Avg);\nend\nassert(all(all(distanceVector>=0)));"} +{"plateform": "github", "repo_name": "plartoo/product_image_classifier-main", "name": "chi2TestConfusionMatrices.m", "ext": ".m", "path": "product_image_classifier-main/chi2TestConfusionMatrices.m", "size": 917, "source_encoding": "utf_8", "md5": "7978a90b3fa0cd70ecf237c929b2a12e", "text": "% chi2TestConfusionMatrices.m\n% Compute p-value of chi2 test for independence. See, e.g.,\n% http://homepage.mac.com/samchops/B733177502/C1517039664/E20060507073109/index.html\n% for the formula.\n\nfunction pVal = chi2TestConfusionMatrices(confusionMatrix,varargin)\n\n% Get input.\nparser = inputParser;\nparser.FunctionName = 'chi2TestConfusionMatrices';\nparser.addRequired('confusionMatrix');\nparser.parse(confusionMatrix,varargin{:});\nconfusionMatrix = parser.Results.confusionMatrix;\n\n% Check input.\nnCategories = size(confusionMatrix,1);\nassert(nCategories==size(confusionMatrix,2));\n\n% How many images were in each class?\nclassSizes = sum(confusionMatrix);\nexpectedNumEachCell = repmat(classSizes / nCategories,nCategories,1);\n\n% Compute test statistic.\n\ntestStatistic = ...\n sum(sum((confusionMatrix - expectedNumEachCell) .^ 2 ./ expectedNumEachCell));\ndf = (nCategories-1)^2;\npVal = 1-chi2cdf(testStatistic,df);"} +{"plateform": "github", "repo_name": "plartoo/product_image_classifier-main", "name": "gauss.m", "ext": ".m", "path": "product_image_classifier-main/canny_edge_test/gauss.m", "size": 91, "source_encoding": "utf_8", "md5": "b17cd93c67fcf48ce6d4bde690b0dc80", "text": "% Function \"gauss.m\":\nfunction y = gauss(x,std)\ny = exp(-x^2/(2*std^2)) / (std*sqrt(2*pi));"} +{"plateform": "github", "repo_name": "plartoo/product_image_classifier-main", "name": "dgauss.m", "ext": ".m", "path": "product_image_classifier-main/canny_edge_test/dgauss.m", "size": 122, "source_encoding": "utf_8", "md5": "591d5fbf3ebeaa21e61b145e3ebac82d", "text": "% Function \"dgauss.m\"(first order derivative of gauss function):\nfunction y = dgauss(x,std)\ny = -x * gauss(x,std) / std^2;"} +{"plateform": "github", "repo_name": "plartoo/product_image_classifier-main", "name": "canny.m", "ext": ".m", "path": "product_image_classifier-main/canny_edge_test/canny.m", "size": 2818, "source_encoding": "utf_8", "md5": "cab1abbd5a250eb5c62df3245c656a14", "text": "% canny.m\n\nfunction [x y] = canny(jpgFile,varargin)\n\n% Get input.\nparser = inputParser;\nparser.FunctionName = 'canny';\nparser.addRequired('jpgFile', @(x)exist(x,'file')==2);\nparser.addParamValue('showFigs', 0, @(x)or(x==0,x==1));\nparser.parse(jpgFile,varargin{:});\njpgFile = parser.Results.jpgFile;\nshowFigs = parser.Results.showFigs;\n\n%%%%%%%%%%%%% The main.m file %%%%%%%%%%%%%%%\n% The algorithm parameters:\n% 1. Parameters of edge detecting filters:\n% X-axis direction filter:\nNx1=10;\nSigmax1=1;\nNx2=10;\nSigmax2=1;\nTheta1=pi/2;\n% Y-axis direction filter:\nNy1=10;\nSigmay1=1;\nNy2=10;\nSigmay2=1;\nTheta2=0;\n% 2. The thresholding parameter alfa:\nalfa=0.1;\n\n% Get the initial image lena.gif\nx=imread(jpgFile);\nw = rgb2gray(x);\n%map = colormap;\n%w=ind2gray(x,map);\nif(showFigs)\n figure(1);colormap(gray);\n subplot(3,2,1);\n imagesc(w); %,200);\n title('Image: lena.gif');\nend\n\n% X-axis direction edge detection\nfilterx=d2dgauss(Nx1,Sigmax1,Nx2,Sigmax2,Theta1);\nIx= conv2(double(w),double(filterx),'same');\nif(showFigs)\n subplot(3,2,2);\n imagesc(Ix);\n title('Ix');\nend\n\n% Y-axis direction edge detection\nfiltery=d2dgauss(Ny1,Sigmay1,Ny2,Sigmay2,Theta2);\nIy=conv2(double(w),double(filtery),'same');\nif(showFigs)\n subplot(3,2,3)\n imagesc(Iy);\n title('Iy');\nend\n\n% Norm of the gradient (Combining the X and Y directional derivatives)\nNVI=sqrt(Ix.*Ix+Iy.*Iy);\nif(showFigs)\n subplot(3,2,4);\n imagesc(NVI);\n title('Norm of Gradient');\nend\n\n% Thresholding\nI_max=max(max(NVI));\nI_min=min(min(NVI));\nlevel=alfa*(I_max-I_min)+I_min;\nIbw=max(NVI,level.*ones(size(NVI)));\nif(showFigs)\n subplot(3,2,5);\n imagesc(Ibw);\n title('After Thresholding');\nend\n\n% Thinning (Using interpolation to find the pixels where the norms of\n% gradient are local maximum.)\n[n,m]=size(Ibw);\nfor i=2:n-1,\n for j=2:m-1,\n if Ibw(i,j) > level,\n X=[-1,0,+1;-1,0,+1;-1,0,+1];\n Y=[-1,-1,-1;0,0,0;+1,+1,+1];\n Z=[Ibw(i-1,j-1),Ibw(i-1,j),Ibw(i-1,j+1);\n Ibw(i,j-1),Ibw(i,j),Ibw(i,j+1);\n Ibw(i+1,j-1),Ibw(i+1,j),Ibw(i+1,j+1)];\n XI=[Ix(i,j)/NVI(i,j), -Ix(i,j)/NVI(i,j)];\n YI=[Iy(i,j)/NVI(i,j), -Iy(i,j)/NVI(i,j)];\n ZI=interp2(X,Y,Z,XI,YI);\n if Ibw(i,j) >= ZI(1) & Ibw(i,j) >= ZI(2)\n I_temp(i,j)=I_max;\n else\n I_temp(i,j)=I_min;\n end\n else\n I_temp(i,j)=I_min;\n end\n end\nend\nif(showFigs)\n subplot(3,2,6);\n imagesc(I_temp);\n title('After Thinning');\n colormap(gray);\nend\n%%%%%%%%%%%%%% End of the main.m file %%%%%%%%%%%%%%%\n\n[rows cols]=ind2sub(size(I_temp),find(I_temp>I_min));\n% May be off by 1....\nx = cols;\ny = rows;\nif(showFigs)\n figure(2);\n imshow(jpgFile);\n hold on;\n scatter(x,y,'r*');\nend"} +{"plateform": "github", "repo_name": "plartoo/product_image_classifier-main", "name": "d2dgauss.m", "ext": ".m", "path": "product_image_classifier-main/canny_edge_test/d2dgauss.m", "size": 623, "source_encoding": "utf_8", "md5": "166c4ddaefe733dbb7a5f153db9ca5da", "text": "%%%%%%% The functions used in the main.m file %%%%%%%\n% Function \"d2dgauss.m\":\n% This function returns a 2D edge detector (first order derivative\n% of 2D Gaussian function) with size n1*n2; theta is the angle that\n% the detector rotated counter clockwise; and sigma1 and sigma2 are the\n% standard deviation of the gaussian functions.\nfunction h = d2dgauss(n1,sigma1,n2,sigma2,theta)\nr=[cos(theta) -sin(theta);\n sin(theta) cos(theta)];\nfor i = 1 : n2 \n for j = 1 : n1\n u = r * [j-(n1+1)/2 i-(n2+1)/2]';\n h(i,j) = gauss(u(1),sigma1)*dgauss(u(2),sigma2);\n end\nend\nh = h / sqrt(sum(sum(abs(h).*abs(h))));"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submit.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex3-008/mlclass-ex3/submit.m", "size": 17041, "source_encoding": "utf_8", "md5": "07a62d95df0814b4ffbc6c2f4b433e22", "text": "function submit(partId, webSubmit)\n%SUBMIT Submit your code and output to the ml-class servers\n% SUBMIT() will connect to the ml-class server and submit your solution\n\n fprintf('==\\n== [ml-class] Submitting Solutions | Programming Exercise %s\\n==\\n', ...\n homework_id());\n if ~exist('partId', 'var') || isempty(partId)\n partId = promptPart();\n end\n\n if ~exist('webSubmit', 'var') || isempty(webSubmit)\n webSubmit = 0; % submit directly by default \n end\n\n % Check valid partId\n partNames = validParts();\n if ~isValidPartId(partId)\n fprintf('!! Invalid homework part selected.\\n');\n fprintf('!! Expected an integer from 1 to %d.\\n', numel(partNames) + 1);\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n if ~exist('ml_login_data.mat','file')\n [login password] = loginPrompt();\n save('ml_login_data.mat','login','password');\n else \n load('ml_login_data.mat');\n [login password] = quickLogin(login, password);\n save('ml_login_data.mat','login','password');\n end\n\n if isempty(login)\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n fprintf('\\n== Connecting to ml-class ... '); \n if exist('OCTAVE_VERSION') \n fflush(stdout);\n end\n\n % Setup submit list\n if partId == numel(partNames) + 1\n submitParts = 1:numel(partNames);\n else\n submitParts = [partId];\n end\n\n for s = 1:numel(submitParts)\n thisPartId = submitParts(s);\n if (~webSubmit) % submit directly to server\n [login, ch, signature, auxstring] = getChallenge(login, thisPartId);\n if isempty(login) || isempty(ch) || isempty(signature)\n % Some error occured, error string in first return element.\n fprintf('\\n!! Error: %s\\n\\n', login);\n return\n end\n\n % Attempt Submission with Challenge\n ch_resp = challengeResponse(login, password, ch);\n\n [result, str] = submitSolution(login, ch_resp, thisPartId, ...\n output(thisPartId, auxstring), source(thisPartId), signature);\n\n partName = partNames{thisPartId};\n\n fprintf('\\n== [ml-class] Submitted Assignment %s - Part %d - %s\\n', ...\n homework_id(), thisPartId, partName);\n fprintf('== %s\\n', strtrim(str));\n\n if exist('OCTAVE_VERSION')\n fflush(stdout);\n end\n else\n [result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...\n source(thisPartId));\n result = base64encode(result);\n\n fprintf('\\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...\n homework_id(), thisPartId);\n saveAsFile = input('', 's');\n if (isempty(saveAsFile))\n saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);\n end\n\n fid = fopen(saveAsFile, 'w');\n if (fid)\n fwrite(fid, result);\n fclose(fid);\n fprintf('\\nSaved your solutions to %s.\\n\\n', saveAsFile);\n fprintf(['You can now submit your solutions through the web \\n' ...\n 'form in the programming exercises. Select the corresponding \\n' ...\n 'programming exercise to access the form.\\n']);\n\n else\n fprintf('Unable to save to %s\\n\\n', saveAsFile);\n fprintf(['You can create a submission file by saving the \\n' ...\n 'following text in a file: (press enter to continue)\\n\\n']);\n pause;\n fprintf(result);\n end\n end\n end\nend\n\n% ================== CONFIGURABLES FOR EACH HOMEWORK ==================\n\nfunction id = homework_id() \n id = '3';\nend\n\nfunction [partNames] = validParts()\n partNames = { 'Vectorized Logistic Regression ', ...\n 'One-vs-all classifier training', ...\n 'One-vs-all classifier prediction', ...\n 'Neural network prediction function' ...\n };\nend\n\nfunction srcs = sources()\n % Separated by part\n srcs = { { 'lrCostFunction.m' }, ...\n { 'oneVsAll.m' }, ...\n { 'predictOneVsAll.m' }, ...\n { 'predict.m' } };\nend\n\nfunction out = output(partId, auxdata)\n % Random Test Cases\n X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];\n y = sin(X(:,1) + X(:,2)) > 0;\n Xm = [ -1 -1 ; -1 -2 ; -2 -1 ; -2 -2 ; ...\n 1 1 ; 1 2 ; 2 1 ; 2 2 ; ...\n -1 1 ; -1 2 ; -2 1 ; -2 2 ; ...\n 1 -1 ; 1 -2 ; -2 -1 ; -2 -2 ];\n ym = [ 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 ]';\n t1 = sin(reshape(1:2:24, 4, 3));\n t2 = cos(reshape(1:2:40, 4, 5));\n\n if partId == 1\n [J, grad] = lrCostFunction([0.25 0.5 -0.5]', X, y, 0.1);\n out = sprintf('%0.5f ', J);\n out = [out sprintf('%0.5f ', grad)];\n elseif partId == 2\n out = sprintf('%0.5f ', oneVsAll(Xm, ym, 4, 0.1));\n elseif partId == 3\n out = sprintf('%0.5f ', predictOneVsAll(t1, Xm));\n elseif partId == 4\n out = sprintf('%0.5f ', predict(t1, t2, Xm));\n end \nend\n\n\n% ====================== SERVER CONFIGURATION ===========================\n\n% ***************** REMOVE -staging WHEN YOU DEPLOY *********************\nfunction url = site_url()\n url = 'http://class.coursera.org/ml-008';\nend\n\nfunction url = challenge_url()\n url = [site_url() '/assignment/challenge'];\nend\n\nfunction url = submit_url()\n url = [site_url() '/assignment/submit'];\nend\n\n% ========================= CHALLENGE HELPERS =========================\n\nfunction src = source(partId)\n src = '';\n src_files = sources();\n if partId <= numel(src_files)\n flist = src_files{partId};\n for i = 1:numel(flist)\n fid = fopen(flist{i});\n if (fid == -1) \n error('Error opening %s (is it missing?)', flist{i});\n end\n line = fgets(fid);\n while ischar(line)\n src = [src line]; \n line = fgets(fid);\n end\n fclose(fid);\n src = [src '||||||||'];\n end\n end\nend\n\nfunction ret = isValidPartId(partId)\n partNames = validParts();\n ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);\nend\n\nfunction partId = promptPart()\n fprintf('== Select which part(s) to submit:\\n');\n partNames = validParts();\n srcFiles = sources();\n for i = 1:numel(partNames)\n fprintf('== %d) %s [', i, partNames{i});\n fprintf(' %s ', srcFiles{i}{:});\n fprintf(']\\n');\n end\n fprintf('== %d) All of the above \\n==\\nEnter your choice [1-%d]: ', ...\n numel(partNames) + 1, numel(partNames) + 1);\n selPart = input('', 's');\n partId = str2num(selPart);\n if ~isValidPartId(partId)\n partId = -1;\n end\nend\n\nfunction [email,ch,signature,auxstring] = getChallenge(email, part)\n str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});\n\n str = strtrim(str);\n r = struct;\n while(numel(str) > 0)\n [f, str] = strtok (str, '|');\n [v, str] = strtok (str, '|');\n r = setfield(r, f, v);\n end\n\n email = getfield(r, 'email_address');\n ch = getfield(r, 'challenge_key');\n signature = getfield(r, 'state');\n auxstring = getfield(r, 'challenge_aux_data');\nend\n\nfunction [result, str] = submitSolutionWeb(email, part, output, source)\n\n result = ['{\"assignment_part_sid\":\"' base64encode([homework_id() '-' num2str(part)], '') '\",' ...\n '\"email_address\":\"' base64encode(email, '') '\",' ...\n '\"submission\":\"' base64encode(output, '') '\",' ...\n '\"submission_aux\":\"' base64encode(source, '') '\"' ...\n '}'];\n str = 'Web-submission';\nend\n\nfunction [result, str] = submitSolution(email, ch_resp, part, output, ...\n source, signature)\n\n params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...\n 'email_address', email, ...\n 'submission', base64encode(output, ''), ...\n 'submission_aux', base64encode(source, ''), ...\n 'challenge_response', ch_resp, ...\n 'state', signature};\n\n str = urlread(submit_url(), 'post', params);\n\n % Parse str to read for success / failure\n result = 0;\n\nend\n\n% =========================== LOGIN HELPERS ===========================\n\nfunction [login password] = loginPrompt()\n % Prompt for password\n [login password] = basicPrompt();\n \n if isempty(login) || isempty(password)\n login = []; password = [];\n end\nend\n\n\nfunction [login password] = basicPrompt()\n login = input('Login (Email address): ', 's');\n password = input('Password: ', 's');\nend\n\nfunction [login password] = quickLogin(login,password)\n disp(['You are currently logged in as ' login '.']);\n cont_token = input('Is this you? (y/n - type n to reenter password)','s');\n if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')\n return;\n else\n [login password] = loginPrompt();\n end\nend\n\nfunction [str] = challengeResponse(email, passwd, challenge)\n str = sha1([challenge passwd]);\nend\n\n% =============================== SHA-1 ================================\n\nfunction hash = sha1(str)\n \n % Initialize variables\n h0 = uint32(1732584193);\n h1 = uint32(4023233417);\n h2 = uint32(2562383102);\n h3 = uint32(271733878);\n h4 = uint32(3285377520);\n \n % Convert to word array\n strlen = numel(str);\n\n % Break string into chars and append the bit 1 to the message\n mC = [double(str) 128];\n mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];\n \n numB = strlen * 8;\n if exist('idivide')\n numC = idivide(uint32(numB + 65), 512, 'ceil');\n else\n numC = ceil(double(numB + 65)/512);\n end\n numW = numC * 16;\n mW = zeros(numW, 1, 'uint32');\n \n idx = 1;\n for i = 1:4:strlen + 1\n mW(idx) = bitor(bitor(bitor( ...\n bitshift(uint32(mC(i)), 24), ...\n bitshift(uint32(mC(i+1)), 16)), ...\n bitshift(uint32(mC(i+2)), 8)), ...\n uint32(mC(i+3)));\n idx = idx + 1;\n end\n \n % Append length of message\n mW(numW - 1) = uint32(bitshift(uint64(numB), -32));\n mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));\n\n % Process the message in successive 512-bit chs\n for cId = 1 : double(numC)\n cSt = (cId - 1) * 16 + 1;\n cEnd = cId * 16;\n ch = mW(cSt : cEnd);\n \n % Extend the sixteen 32-bit words into eighty 32-bit words\n for j = 17 : 80\n ch(j) = ch(j - 3);\n ch(j) = bitxor(ch(j), ch(j - 8));\n ch(j) = bitxor(ch(j), ch(j - 14));\n ch(j) = bitxor(ch(j), ch(j - 16));\n ch(j) = bitrotate(ch(j), 1);\n end\n \n % Initialize hash value for this ch\n a = h0;\n b = h1;\n c = h2;\n d = h3;\n e = h4;\n \n % Main loop\n for i = 1 : 80\n if(i >= 1 && i <= 20)\n f = bitor(bitand(b, c), bitand(bitcmp(b), d));\n k = uint32(1518500249);\n elseif(i >= 21 && i <= 40)\n f = bitxor(bitxor(b, c), d);\n k = uint32(1859775393);\n elseif(i >= 41 && i <= 60)\n f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));\n k = uint32(2400959708);\n elseif(i >= 61 && i <= 80)\n f = bitxor(bitxor(b, c), d);\n k = uint32(3395469782);\n end\n \n t = bitrotate(a, 5);\n t = bitadd(t, f);\n t = bitadd(t, e);\n t = bitadd(t, k);\n t = bitadd(t, ch(i));\n e = d;\n d = c;\n c = bitrotate(b, 30);\n b = a;\n a = t;\n \n end\n h0 = bitadd(h0, a);\n h1 = bitadd(h1, b);\n h2 = bitadd(h2, c);\n h3 = bitadd(h3, d);\n h4 = bitadd(h4, e);\n\n end\n\n hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);\n \n hash = lower(hash);\n\nend\n\nfunction ret = bitadd(iA, iB)\n ret = double(iA) + double(iB);\n ret = bitset(ret, 33, 0);\n ret = uint32(ret);\nend\n\nfunction ret = bitrotate(iA, places)\n t = bitshift(iA, places - 32);\n ret = bitshift(iA, places);\n ret = bitor(ret, t);\nend\n\n% =========================== Base64 Encoder ============================\n% Thanks to Peter John Acklam\n%\n\nfunction y = base64encode(x, eol)\n%BASE64ENCODE Perform base64 encoding on a string.\n%\n% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending\n% sequence to use; it is optional and defaults to '\\n' (ASCII decimal 10).\n% The returned encoded string is broken into lines of no more than 76\n% characters each, and each line will end with EOL unless it is empty. Let\n% EOL be empty if you do not want the encoded string broken into lines.\n%\n% STR and EOL don't have to be strings (i.e., char arrays). The only\n% requirement is that they are vectors containing values in the range 0-255.\n%\n% This function may be used to encode strings into the Base64 encoding\n% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The\n% Base64 encoding is designed to represent arbitrary sequences of octets in a\n% form that need not be humanly readable. A 65-character subset\n% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per\n% printable character.\n%\n% Examples\n% --------\n%\n% If you want to encode a large file, you should encode it in chunks that are\n% a multiple of 57 bytes. This ensures that the base64 lines line up and\n% that you do not end up with padding in the middle. 57 bytes of data fills\n% one complete base64 line (76 == 57*4/3):\n%\n% If ifid and ofid are two file identifiers opened for reading and writing,\n% respectively, then you can base64 encode the data with\n%\n% while ~feof(ifid)\n% fwrite(ofid, base64encode(fread(ifid, 60*57)));\n% end\n%\n% or, if you have enough memory,\n%\n% fwrite(ofid, base64encode(fread(ifid)));\n%\n% See also BASE64DECODE.\n\n% Author: Peter John Acklam\n% Time-stamp: 2004-02-03 21:36:56 +0100\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n if isnumeric(x)\n x = num2str(x);\n end\n\n % make sure we have the EOL value\n if nargin < 2\n eol = sprintf('\\n');\n else\n if sum(size(eol) > 1) > 1\n error('EOL must be a vector.');\n end\n if any(eol(:) > 255)\n error('EOL can not contain values larger than 255.');\n end\n end\n\n if sum(size(x) > 1) > 1\n error('STR must be a vector.');\n end\n\n x = uint8(x);\n eol = uint8(eol);\n\n ndbytes = length(x); % number of decoded bytes\n nchunks = ceil(ndbytes / 3); % number of chunks/groups\n nebytes = 4 * nchunks; % number of encoded bytes\n\n % add padding if necessary, to make the length of x a multiple of 3\n if rem(ndbytes, 3)\n x(end+1 : 3*nchunks) = 0;\n end\n\n x = reshape(x, [3, nchunks]); % reshape the data\n y = repmat(uint8(0), 4, nchunks); % for the encoded data\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Split up every 3 bytes into 4 pieces\n %\n % aaaaaabb bbbbcccc ccdddddd\n %\n % to form\n %\n % 00aaaaaa 00bbbbbb 00cccccc 00dddddd\n %\n y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)\n\n y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)\n y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)\n\n y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)\n y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)\n\n y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Now perform the following mapping\n %\n % 0 - 25 -> A-Z\n % 26 - 51 -> a-z\n % 52 - 61 -> 0-9\n % 62 -> +\n % 63 -> /\n %\n % We could use a mapping vector like\n %\n % ['A':'Z', 'a':'z', '0':'9', '+/']\n %\n % but that would require an index vector of class double.\n %\n z = repmat(uint8(0), size(y));\n i = y <= 25; z(i) = 'A' + double(y(i));\n i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));\n i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));\n i = y == 62; z(i) = '+';\n i = y == 63; z(i) = '/';\n y = z;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Add padding if necessary.\n %\n npbytes = 3 * nchunks - ndbytes; % number of padding bytes\n if npbytes\n y(end-npbytes+1 : end) = '='; % '=' is used for padding\n end\n\n if isempty(eol)\n\n % reshape to a row vector\n y = reshape(y, [1, nebytes]);\n\n else\n\n nlines = ceil(nebytes / 76); % number of lines\n neolbytes = length(eol); % number of bytes in eol string\n\n % pad data so it becomes a multiple of 76 elements\n y = [y(:) ; zeros(76 * nlines - numel(y), 1)];\n y(nebytes + 1 : 76 * nlines) = 0;\n y = reshape(y, 76, nlines);\n\n % insert eol strings\n eol = eol(:);\n y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));\n\n % remove padding, but keep the last eol string\n m = nebytes + neolbytes * (nlines - 1);\n n = (76+neolbytes)*nlines - neolbytes;\n y(m+1 : n) = '';\n\n % extract and reshape to row vector\n y = reshape(y, 1, m+neolbytes);\n\n end\n\n % output is a character array\n y = char(y);\n\nend\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submitWeb.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex3-008/mlclass-ex3/submitWeb.m", "size": 807, "source_encoding": "utf_8", "md5": "a53188558a96eae6cd8b0e6cda4d478d", "text": "% submitWeb Creates files from your code and output for web submission.\n%\n% If the submit function does not work for you, use the web-submission mechanism.\n% Call this function to produce a file for the part you wish to submit. Then,\n% submit the file to the class servers using the \"Web Submission\" button on the \n% Programming Exercises page on the course website.\n%\n% You should call this function without arguments (submitWeb), to receive\n% an interactive prompt for submission; optionally you can call it with the partID\n% if you so wish. Make sure your working directory is set to the directory \n% containing the submitWeb.m file and your assignment files.\n\nfunction submitWeb(partId)\n if ~exist('partId', 'var') || isempty(partId)\n partId = [];\n end\n \n submit(partId, 1);\nend\n\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submit.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex2-008/mlclass-ex2/submit.m", "size": 17086, "source_encoding": "utf_8", "md5": "7b02ce6b9daa919a9a66ef0adb401b07", "text": "function submit(partId, webSubmit)\n%SUBMIT Submit your code and output to the ml-class servers\n% SUBMIT() will connect to the ml-class server and submit your solution\n\n fprintf('==\\n== [ml-class] Submitting Solutions | Programming Exercise %s\\n==\\n', ...\n homework_id());\n if ~exist('partId', 'var') || isempty(partId)\n partId = promptPart();\n end\n\n if ~exist('webSubmit', 'var') || isempty(webSubmit)\n webSubmit = 0; % submit directly by default \n end\n\n % Check valid partId\n partNames = validParts();\n if ~isValidPartId(partId)\n fprintf('!! Invalid homework part selected.\\n');\n fprintf('!! Expected an integer from 1 to %d.\\n', numel(partNames) + 1);\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n if ~exist('ml_login_data.mat','file')\n [login password] = loginPrompt();\n save('ml_login_data.mat','login','password');\n else \n load('ml_login_data.mat');\n [login password] = quickLogin(login, password);\n save('ml_login_data.mat','login','password');\n end\n\n if isempty(login)\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n fprintf('\\n== Connecting to ml-class ... '); \n if exist('OCTAVE_VERSION') \n fflush(stdout);\n end\n\n % Setup submit list\n if partId == numel(partNames) + 1\n submitParts = 1:numel(partNames);\n else\n submitParts = [partId];\n end\n\n for s = 1:numel(submitParts)\n thisPartId = submitParts(s);\n if (~webSubmit) % submit directly to server\n [login, ch, signature, auxstring] = getChallenge(login, thisPartId);\n if isempty(login) || isempty(ch) || isempty(signature)\n % Some error occured, error string in first return element.\n fprintf('\\n!! Error: %s\\n\\n', login);\n return\n end\n\n % Attempt Submission with Challenge\n ch_resp = challengeResponse(login, password, ch);\n\n [result, str] = submitSolution(login, ch_resp, thisPartId, ...\n output(thisPartId, auxstring), source(thisPartId), signature);\n\n partName = partNames{thisPartId};\n\n fprintf('\\n== [ml-class] Submitted Assignment %s - Part %d - %s\\n', ...\n homework_id(), thisPartId, partName);\n fprintf('== %s\\n', strtrim(str));\n\n if exist('OCTAVE_VERSION')\n fflush(stdout);\n end\n else\n [result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...\n source(thisPartId));\n result = base64encode(result);\n\n fprintf('\\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...\n homework_id(), thisPartId);\n saveAsFile = input('', 's');\n if (isempty(saveAsFile))\n saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);\n end\n\n fid = fopen(saveAsFile, 'w');\n if (fid)\n fwrite(fid, result);\n fclose(fid);\n fprintf('\\nSaved your solutions to %s.\\n\\n', saveAsFile);\n fprintf(['You can now submit your solutions through the web \\n' ...\n 'form in the programming exercises. Select the corresponding \\n' ...\n 'programming exercise to access the form.\\n']);\n\n else\n fprintf('Unable to save to %s\\n\\n', saveAsFile);\n fprintf(['You can create a submission file by saving the \\n' ...\n 'following text in a file: (press enter to continue)\\n\\n']);\n pause;\n fprintf(result);\n end\n end\n end\nend\n\n% ================== CONFIGURABLES FOR EACH HOMEWORK ==================\n\nfunction id = homework_id() \n id = '2';\nend\n\nfunction [partNames] = validParts()\n partNames = { 'Sigmoid Function ', ...\n 'Logistic Regression Cost', ...\n 'Logistic Regression Gradient', ...\n 'Predict', ...\n 'Regularized Logistic Regression Cost' ...\n 'Regularized Logistic Regression Gradient' ...\n };\nend\n\nfunction srcs = sources()\n % Separated by part\n srcs = { { 'sigmoid.m' }, ...\n { 'costFunction.m' }, ...\n { 'costFunction.m' }, ...\n { 'predict.m' }, ...\n { 'costFunctionReg.m' }, ...\n { 'costFunctionReg.m' } };\nend\n\nfunction out = output(partId, auxstring)\n % Random Test Cases\n X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];\n y = sin(X(:,1) + X(:,2)) > 0;\n if partId == 1\n out = sprintf('%0.5f ', sigmoid(X));\n elseif partId == 2\n out = sprintf('%0.5f ', costFunction([0.25 0.5 -0.5]', X, y));\n elseif partId == 3\n [cost, grad] = costFunction([0.25 0.5 -0.5]', X, y);\n out = sprintf('%0.5f ', grad);\n elseif partId == 4\n out = sprintf('%0.5f ', predict([0.25 0.5 -0.5]', X));\n elseif partId == 5\n out = sprintf('%0.5f ', costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1));\n elseif partId == 6\n [cost, grad] = costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1);\n out = sprintf('%0.5f ', grad);\n end \nend\n\n\n% ====================== SERVER CONFIGURATION ===========================\n\n% ***************** REMOVE -staging WHEN YOU DEPLOY *********************\nfunction url = site_url()\n url = 'http://class.coursera.org/ml-008';\nend\n\nfunction url = challenge_url()\n url = [site_url() '/assignment/challenge'];\nend\n\nfunction url = submit_url()\n url = [site_url() '/assignment/submit'];\nend\n\n% ========================= CHALLENGE HELPERS =========================\n\nfunction src = source(partId)\n src = '';\n src_files = sources();\n if partId <= numel(src_files)\n flist = src_files{partId};\n for i = 1:numel(flist)\n fid = fopen(flist{i});\n if (fid == -1) \n error('Error opening %s (is it missing?)', flist{i});\n end\n line = fgets(fid);\n while ischar(line)\n src = [src line]; \n line = fgets(fid);\n end\n fclose(fid);\n src = [src '||||||||'];\n end\n end\nend\n\nfunction ret = isValidPartId(partId)\n partNames = validParts();\n ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);\nend\n\nfunction partId = promptPart()\n fprintf('== Select which part(s) to submit:\\n');\n partNames = validParts();\n srcFiles = sources();\n for i = 1:numel(partNames)\n fprintf('== %d) %s [', i, partNames{i});\n fprintf(' %s ', srcFiles{i}{:});\n fprintf(']\\n');\n end\n fprintf('== %d) All of the above \\n==\\nEnter your choice [1-%d]: ', ...\n numel(partNames) + 1, numel(partNames) + 1);\n selPart = input('', 's');\n partId = str2num(selPart);\n if ~isValidPartId(partId)\n partId = -1;\n end\nend\n\nfunction [email,ch,signature,auxstring] = getChallenge(email, part)\n str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});\n\n str = strtrim(str);\n r = struct;\n while(numel(str) > 0)\n [f, str] = strtok (str, '|');\n [v, str] = strtok (str, '|');\n r = setfield(r, f, v);\n end\n\n email = getfield(r, 'email_address');\n ch = getfield(r, 'challenge_key');\n signature = getfield(r, 'state');\n auxstring = getfield(r, 'challenge_aux_data');\nend\n\nfunction [result, str] = submitSolutionWeb(email, part, output, source)\n\n result = ['{\"assignment_part_sid\":\"' base64encode([homework_id() '-' num2str(part)], '') '\",' ...\n '\"email_address\":\"' base64encode(email, '') '\",' ...\n '\"submission\":\"' base64encode(output, '') '\",' ...\n '\"submission_aux\":\"' base64encode(source, '') '\"' ...\n '}'];\n str = 'Web-submission';\nend\n\nfunction [result, str] = submitSolution(email, ch_resp, part, output, ...\n source, signature)\n\n params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...\n 'email_address', email, ...\n 'submission', base64encode(output, ''), ...\n 'submission_aux', base64encode(source, ''), ...\n 'challenge_response', ch_resp, ...\n 'state', signature};\n\n str = urlread(submit_url(), 'post', params);\n\n % Parse str to read for success / failure\n result = 0;\n\nend\n\n% =========================== LOGIN HELPERS ===========================\n\nfunction [login password] = loginPrompt()\n % Prompt for password\n [login password] = basicPrompt();\n \n if isempty(login) || isempty(password)\n login = []; password = [];\n end\nend\n\n\nfunction [login password] = basicPrompt()\n login = input('Login (Email address): ', 's');\n password = input('Password: ', 's');\nend\n\nfunction [login password] = quickLogin(login,password)\n disp(['You are currently logged in as ' login '.']);\n cont_token = input('Is this you? (y/n - type n to reenter password)','s');\n if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')\n return;\n else\n [login password] = loginPrompt();\n end\nend\n\nfunction [str] = challengeResponse(email, passwd, challenge)\n str = sha1([challenge passwd]);\nend\n\n% =============================== SHA-1 ================================\n\nfunction hash = sha1(str)\n \n % Initialize variables\n h0 = uint32(1732584193);\n h1 = uint32(4023233417);\n h2 = uint32(2562383102);\n h3 = uint32(271733878);\n h4 = uint32(3285377520);\n \n % Convert to word array\n strlen = numel(str);\n\n % Break string into chars and append the bit 1 to the message\n mC = [double(str) 128];\n mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];\n \n numB = strlen * 8;\n if exist('idivide')\n numC = idivide(uint32(numB + 65), 512, 'ceil');\n else\n numC = ceil(double(numB + 65)/512);\n end\n numW = numC * 16;\n mW = zeros(numW, 1, 'uint32');\n \n idx = 1;\n for i = 1:4:strlen + 1\n mW(idx) = bitor(bitor(bitor( ...\n bitshift(uint32(mC(i)), 24), ...\n bitshift(uint32(mC(i+1)), 16)), ...\n bitshift(uint32(mC(i+2)), 8)), ...\n uint32(mC(i+3)));\n idx = idx + 1;\n end\n \n % Append length of message\n mW(numW - 1) = uint32(bitshift(uint64(numB), -32));\n mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));\n\n % Process the message in successive 512-bit chs\n for cId = 1 : double(numC)\n cSt = (cId - 1) * 16 + 1;\n cEnd = cId * 16;\n ch = mW(cSt : cEnd);\n \n % Extend the sixteen 32-bit words into eighty 32-bit words\n for j = 17 : 80\n ch(j) = ch(j - 3);\n ch(j) = bitxor(ch(j), ch(j - 8));\n ch(j) = bitxor(ch(j), ch(j - 14));\n ch(j) = bitxor(ch(j), ch(j - 16));\n ch(j) = bitrotate(ch(j), 1);\n end\n \n % Initialize hash value for this ch\n a = h0;\n b = h1;\n c = h2;\n d = h3;\n e = h4;\n \n % Main loop\n for i = 1 : 80\n if(i >= 1 && i <= 20)\n f = bitor(bitand(b, c), bitand(bitcmp(b), d));\n k = uint32(1518500249);\n elseif(i >= 21 && i <= 40)\n f = bitxor(bitxor(b, c), d);\n k = uint32(1859775393);\n elseif(i >= 41 && i <= 60)\n f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));\n k = uint32(2400959708);\n elseif(i >= 61 && i <= 80)\n f = bitxor(bitxor(b, c), d);\n k = uint32(3395469782);\n end\n \n t = bitrotate(a, 5);\n t = bitadd(t, f);\n t = bitadd(t, e);\n t = bitadd(t, k);\n t = bitadd(t, ch(i));\n e = d;\n d = c;\n c = bitrotate(b, 30);\n b = a;\n a = t;\n \n end\n h0 = bitadd(h0, a);\n h1 = bitadd(h1, b);\n h2 = bitadd(h2, c);\n h3 = bitadd(h3, d);\n h4 = bitadd(h4, e);\n\n end\n\n hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);\n \n hash = lower(hash);\n\nend\n\nfunction ret = bitadd(iA, iB)\n ret = double(iA) + double(iB);\n ret = bitset(ret, 33, 0);\n ret = uint32(ret);\nend\n\nfunction ret = bitrotate(iA, places)\n t = bitshift(iA, places - 32);\n ret = bitshift(iA, places);\n ret = bitor(ret, t);\nend\n\n% =========================== Base64 Encoder ============================\n% Thanks to Peter John Acklam\n%\n\nfunction y = base64encode(x, eol)\n%BASE64ENCODE Perform base64 encoding on a string.\n%\n% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending\n% sequence to use; it is optional and defaults to '\\n' (ASCII decimal 10).\n% The returned encoded string is broken into lines of no more than 76\n% characters each, and each line will end with EOL unless it is empty. Let\n% EOL be empty if you do not want the encoded string broken into lines.\n%\n% STR and EOL don't have to be strings (i.e., char arrays). The only\n% requirement is that they are vectors containing values in the range 0-255.\n%\n% This function may be used to encode strings into the Base64 encoding\n% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The\n% Base64 encoding is designed to represent arbitrary sequences of octets in a\n% form that need not be humanly readable. A 65-character subset\n% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per\n% printable character.\n%\n% Examples\n% --------\n%\n% If you want to encode a large file, you should encode it in chunks that are\n% a multiple of 57 bytes. This ensures that the base64 lines line up and\n% that you do not end up with padding in the middle. 57 bytes of data fills\n% one complete base64 line (76 == 57*4/3):\n%\n% If ifid and ofid are two file identifiers opened for reading and writing,\n% respectively, then you can base64 encode the data with\n%\n% while ~feof(ifid)\n% fwrite(ofid, base64encode(fread(ifid, 60*57)));\n% end\n%\n% or, if you have enough memory,\n%\n% fwrite(ofid, base64encode(fread(ifid)));\n%\n% See also BASE64DECODE.\n\n% Author: Peter John Acklam\n% Time-stamp: 2004-02-03 21:36:56 +0100\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n if isnumeric(x)\n x = num2str(x);\n end\n\n % make sure we have the EOL value\n if nargin < 2\n eol = sprintf('\\n');\n else\n if sum(size(eol) > 1) > 1\n error('EOL must be a vector.');\n end\n if any(eol(:) > 255)\n error('EOL can not contain values larger than 255.');\n end\n end\n\n if sum(size(x) > 1) > 1\n error('STR must be a vector.');\n end\n\n x = uint8(x);\n eol = uint8(eol);\n\n ndbytes = length(x); % number of decoded bytes\n nchunks = ceil(ndbytes / 3); % number of chunks/groups\n nebytes = 4 * nchunks; % number of encoded bytes\n\n % add padding if necessary, to make the length of x a multiple of 3\n if rem(ndbytes, 3)\n x(end+1 : 3*nchunks) = 0;\n end\n\n x = reshape(x, [3, nchunks]); % reshape the data\n y = repmat(uint8(0), 4, nchunks); % for the encoded data\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Split up every 3 bytes into 4 pieces\n %\n % aaaaaabb bbbbcccc ccdddddd\n %\n % to form\n %\n % 00aaaaaa 00bbbbbb 00cccccc 00dddddd\n %\n y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)\n\n y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)\n y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)\n\n y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)\n y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)\n\n y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Now perform the following mapping\n %\n % 0 - 25 -> A-Z\n % 26 - 51 -> a-z\n % 52 - 61 -> 0-9\n % 62 -> +\n % 63 -> /\n %\n % We could use a mapping vector like\n %\n % ['A':'Z', 'a':'z', '0':'9', '+/']\n %\n % but that would require an index vector of class double.\n %\n z = repmat(uint8(0), size(y));\n i = y <= 25; z(i) = 'A' + double(y(i));\n i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));\n i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));\n i = y == 62; z(i) = '+';\n i = y == 63; z(i) = '/';\n y = z;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Add padding if necessary.\n %\n npbytes = 3 * nchunks - ndbytes; % number of padding bytes\n if npbytes\n y(end-npbytes+1 : end) = '='; % '=' is used for padding\n end\n\n if isempty(eol)\n\n % reshape to a row vector\n y = reshape(y, [1, nebytes]);\n\n else\n\n nlines = ceil(nebytes / 76); % number of lines\n neolbytes = length(eol); % number of bytes in eol string\n\n % pad data so it becomes a multiple of 76 elements\n y = [y(:) ; zeros(76 * nlines - numel(y), 1)];\n y(nebytes + 1 : 76 * nlines) = 0;\n y = reshape(y, 76, nlines);\n\n % insert eol strings\n eol = eol(:);\n y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));\n\n % remove padding, but keep the last eol string\n m = nebytes + neolbytes * (nlines - 1);\n n = (76+neolbytes)*nlines - neolbytes;\n y(m+1 : n) = '';\n\n % extract and reshape to row vector\n y = reshape(y, 1, m+neolbytes);\n\n end\n\n % output is a character array\n y = char(y);\n\nend\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submitWeb.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex2-008/mlclass-ex2/submitWeb.m", "size": 807, "source_encoding": "utf_8", "md5": "a53188558a96eae6cd8b0e6cda4d478d", "text": "% submitWeb Creates files from your code and output for web submission.\n%\n% If the submit function does not work for you, use the web-submission mechanism.\n% Call this function to produce a file for the part you wish to submit. Then,\n% submit the file to the class servers using the \"Web Submission\" button on the \n% Programming Exercises page on the course website.\n%\n% You should call this function without arguments (submitWeb), to receive\n% an interactive prompt for submission; optionally you can call it with the partID\n% if you so wish. Make sure your working directory is set to the directory \n% containing the submitWeb.m file and your assignment files.\n\nfunction submitWeb(partId)\n if ~exist('partId', 'var') || isempty(partId)\n partId = [];\n end\n \n submit(partId, 1);\nend\n\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submit.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex7-008/mlclass-ex7/submit.m", "size": 16958, "source_encoding": "utf_8", "md5": "cd11307f72915c0d3b58176b66081197", "text": "function submit(partId, webSubmit)\n%SUBMIT Submit your code and output to the ml-class servers\n% SUBMIT() will connect to the ml-class server and submit your solution\n\n fprintf('==\\n== [ml-class] Submitting Solutions | Programming Exercise %s\\n==\\n', ...\n homework_id());\n if ~exist('partId', 'var') || isempty(partId)\n partId = promptPart();\n end\n\n if ~exist('webSubmit', 'var') || isempty(webSubmit)\n webSubmit = 0; % submit directly by default \n end\n\n % Check valid partId\n partNames = validParts();\n if ~isValidPartId(partId)\n fprintf('!! Invalid homework part selected.\\n');\n fprintf('!! Expected an integer from 1 to %d.\\n', numel(partNames) + 1);\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n if ~exist('ml_login_data.mat','file')\n [login password] = loginPrompt();\n save('ml_login_data.mat','login','password');\n else \n load('ml_login_data.mat');\n [login password] = quickLogin(login, password);\n save('ml_login_data.mat','login','password');\n end\n\n if isempty(login)\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n fprintf('\\n== Connecting to ml-class ... '); \n if exist('OCTAVE_VERSION') \n fflush(stdout);\n end\n\n % Setup submit list\n if partId == numel(partNames) + 1\n submitParts = 1:numel(partNames);\n else\n submitParts = [partId];\n end\n\n for s = 1:numel(submitParts)\n thisPartId = submitParts(s);\n if (~webSubmit) % submit directly to server\n [login, ch, signature, auxstring] = getChallenge(login, thisPartId);\n if isempty(login) || isempty(ch) || isempty(signature)\n % Some error occured, error string in first return element.\n fprintf('\\n!! Error: %s\\n\\n', login);\n return\n end\n\n % Attempt Submission with Challenge\n ch_resp = challengeResponse(login, password, ch);\n\n [result, str] = submitSolution(login, ch_resp, thisPartId, ...\n output(thisPartId, auxstring), source(thisPartId), signature);\n\n partName = partNames{thisPartId};\n\n fprintf('\\n== [ml-class] Submitted Assignment %s - Part %d - %s\\n', ...\n homework_id(), thisPartId, partName);\n fprintf('== %s\\n', strtrim(str));\n\n if exist('OCTAVE_VERSION')\n fflush(stdout);\n end\n else\n [result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...\n source(thisPartId));\n result = base64encode(result);\n\n fprintf('\\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...\n homework_id(), thisPartId);\n saveAsFile = input('', 's');\n if (isempty(saveAsFile))\n saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);\n end\n\n fid = fopen(saveAsFile, 'w');\n if (fid)\n fwrite(fid, result);\n fclose(fid);\n fprintf('\\nSaved your solutions to %s.\\n\\n', saveAsFile);\n fprintf(['You can now submit your solutions through the web \\n' ...\n 'form in the programming exercises. Select the corresponding \\n' ...\n 'programming exercise to access the form.\\n']);\n\n else\n fprintf('Unable to save to %s\\n\\n', saveAsFile);\n fprintf(['You can create a submission file by saving the \\n' ...\n 'following text in a file: (press enter to continue)\\n\\n']);\n pause;\n fprintf(result);\n end\n end\n end\nend\n\n% ================== CONFIGURABLES FOR EACH HOMEWORK ==================\n\nfunction id = homework_id() \n id = '7';\nend\n\nfunction [partNames] = validParts()\n partNames = { \n 'Find Closest Centroids (k-Means)', ...\n 'Compute Centroid Means (k-Means)' ...\n 'PCA', ...\n 'Project Data (PCA)', ...\n 'Recover Data (PCA)' ...\n };\nend\n\nfunction srcs = sources()\n % Separated by part\n srcs = { { 'findClosestCentroids.m' }, ...\n { 'computeCentroids.m' }, ...\n { 'pca.m' }, ...\n { 'projectData.m' }, ...\n { 'recoverData.m' } ...\n };\nend\n\nfunction out = output(partId, auxstring)\n % Random Test Cases\n X = reshape(sin(1:165), 15, 11);\n Z = reshape(cos(1:121), 11, 11);\n C = Z(1:5, :);\n idx = (1 + mod(1:15, 3))';\n if partId == 1\n idx = findClosestCentroids(X, C);\n out = sprintf('%0.5f ', idx(:));\n elseif partId == 2\n centroids = computeCentroids(X, idx, 3);\n out = sprintf('%0.5f ', centroids(:));\n elseif partId == 3\n [U, S] = pca(X);\n out = sprintf('%0.5f ', abs([U(:); S(:)]));\n elseif partId == 4\n X_proj = projectData(X, Z, 5);\n out = sprintf('%0.5f ', X_proj(:));\n elseif partId == 5\n X_rec = recoverData(X(:,1:5), Z, 5);\n out = sprintf('%0.5f ', X_rec(:));\n end \nend\n\n% ====================== SERVER CONFIGURATION ===========================\n\n% ***************** REMOVE -staging WHEN YOU DEPLOY *********************\nfunction url = site_url()\n url = 'http://class.coursera.org/ml-008';\nend\n\nfunction url = challenge_url()\n url = [site_url() '/assignment/challenge'];\nend\n\nfunction url = submit_url()\n url = [site_url() '/assignment/submit'];\nend\n\n% ========================= CHALLENGE HELPERS =========================\n\nfunction src = source(partId)\n src = '';\n src_files = sources();\n if partId <= numel(src_files)\n flist = src_files{partId};\n for i = 1:numel(flist)\n fid = fopen(flist{i});\n if (fid == -1) \n error('Error opening %s (is it missing?)', flist{i});\n end\n line = fgets(fid);\n while ischar(line)\n src = [src line]; \n line = fgets(fid);\n end\n fclose(fid);\n src = [src '||||||||'];\n end\n end\nend\n\nfunction ret = isValidPartId(partId)\n partNames = validParts();\n ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);\nend\n\nfunction partId = promptPart()\n fprintf('== Select which part(s) to submit:\\n');\n partNames = validParts();\n srcFiles = sources();\n for i = 1:numel(partNames)\n fprintf('== %d) %s [', i, partNames{i});\n fprintf(' %s ', srcFiles{i}{:});\n fprintf(']\\n');\n end\n fprintf('== %d) All of the above \\n==\\nEnter your choice [1-%d]: ', ...\n numel(partNames) + 1, numel(partNames) + 1);\n selPart = input('', 's');\n partId = str2num(selPart);\n if ~isValidPartId(partId)\n partId = -1;\n end\nend\n\nfunction [email,ch,signature,auxstring] = getChallenge(email, part)\n str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});\n\n str = strtrim(str);\n r = struct;\n while(numel(str) > 0)\n [f, str] = strtok (str, '|');\n [v, str] = strtok (str, '|');\n r = setfield(r, f, v);\n end\n\n email = getfield(r, 'email_address');\n ch = getfield(r, 'challenge_key');\n signature = getfield(r, 'state');\n auxstring = getfield(r, 'challenge_aux_data');\nend\n\nfunction [result, str] = submitSolutionWeb(email, part, output, source)\n\n result = ['{\"assignment_part_sid\":\"' base64encode([homework_id() '-' num2str(part)], '') '\",' ...\n '\"email_address\":\"' base64encode(email, '') '\",' ...\n '\"submission\":\"' base64encode(output, '') '\",' ...\n '\"submission_aux\":\"' base64encode(source, '') '\"' ...\n '}'];\n str = 'Web-submission';\nend\n\nfunction [result, str] = submitSolution(email, ch_resp, part, output, ...\n source, signature)\n\n params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...\n 'email_address', email, ...\n 'submission', base64encode(output, ''), ...\n 'submission_aux', base64encode(source, ''), ...\n 'challenge_response', ch_resp, ...\n 'state', signature};\n\n str = urlread(submit_url(), 'post', params);\n\n % Parse str to read for success / failure\n result = 0;\n\nend\n\n% =========================== LOGIN HELPERS ===========================\n\nfunction [login password] = loginPrompt()\n % Prompt for password\n [login password] = basicPrompt();\n \n if isempty(login) || isempty(password)\n login = []; password = [];\n end\nend\n\n\nfunction [login password] = basicPrompt()\n login = input('Login (Email address): ', 's');\n password = input('Password: ', 's');\nend\n\nfunction [login password] = quickLogin(login,password)\n disp(['You are currently logged in as ' login '.']);\n cont_token = input('Is this you? (y/n - type n to reenter password)','s');\n if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')\n return;\n else\n [login password] = loginPrompt();\n end\nend\n\nfunction [str] = challengeResponse(email, passwd, challenge)\n str = sha1([challenge passwd]);\nend\n\n% =============================== SHA-1 ================================\n\nfunction hash = sha1(str)\n \n % Initialize variables\n h0 = uint32(1732584193);\n h1 = uint32(4023233417);\n h2 = uint32(2562383102);\n h3 = uint32(271733878);\n h4 = uint32(3285377520);\n \n % Convert to word array\n strlen = numel(str);\n\n % Break string into chars and append the bit 1 to the message\n mC = [double(str) 128];\n mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];\n \n numB = strlen * 8;\n if exist('idivide')\n numC = idivide(uint32(numB + 65), 512, 'ceil');\n else\n numC = ceil(double(numB + 65)/512);\n end\n numW = numC * 16;\n mW = zeros(numW, 1, 'uint32');\n \n idx = 1;\n for i = 1:4:strlen + 1\n mW(idx) = bitor(bitor(bitor( ...\n bitshift(uint32(mC(i)), 24), ...\n bitshift(uint32(mC(i+1)), 16)), ...\n bitshift(uint32(mC(i+2)), 8)), ...\n uint32(mC(i+3)));\n idx = idx + 1;\n end\n \n % Append length of message\n mW(numW - 1) = uint32(bitshift(uint64(numB), -32));\n mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));\n\n % Process the message in successive 512-bit chs\n for cId = 1 : double(numC)\n cSt = (cId - 1) * 16 + 1;\n cEnd = cId * 16;\n ch = mW(cSt : cEnd);\n \n % Extend the sixteen 32-bit words into eighty 32-bit words\n for j = 17 : 80\n ch(j) = ch(j - 3);\n ch(j) = bitxor(ch(j), ch(j - 8));\n ch(j) = bitxor(ch(j), ch(j - 14));\n ch(j) = bitxor(ch(j), ch(j - 16));\n ch(j) = bitrotate(ch(j), 1);\n end\n \n % Initialize hash value for this ch\n a = h0;\n b = h1;\n c = h2;\n d = h3;\n e = h4;\n \n % Main loop\n for i = 1 : 80\n if(i >= 1 && i <= 20)\n f = bitor(bitand(b, c), bitand(bitcmp(b), d));\n k = uint32(1518500249);\n elseif(i >= 21 && i <= 40)\n f = bitxor(bitxor(b, c), d);\n k = uint32(1859775393);\n elseif(i >= 41 && i <= 60)\n f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));\n k = uint32(2400959708);\n elseif(i >= 61 && i <= 80)\n f = bitxor(bitxor(b, c), d);\n k = uint32(3395469782);\n end\n \n t = bitrotate(a, 5);\n t = bitadd(t, f);\n t = bitadd(t, e);\n t = bitadd(t, k);\n t = bitadd(t, ch(i));\n e = d;\n d = c;\n c = bitrotate(b, 30);\n b = a;\n a = t;\n \n end\n h0 = bitadd(h0, a);\n h1 = bitadd(h1, b);\n h2 = bitadd(h2, c);\n h3 = bitadd(h3, d);\n h4 = bitadd(h4, e);\n\n end\n\n hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);\n \n hash = lower(hash);\n\nend\n\nfunction ret = bitadd(iA, iB)\n ret = double(iA) + double(iB);\n ret = bitset(ret, 33, 0);\n ret = uint32(ret);\nend\n\nfunction ret = bitrotate(iA, places)\n t = bitshift(iA, places - 32);\n ret = bitshift(iA, places);\n ret = bitor(ret, t);\nend\n\n% =========================== Base64 Encoder ============================\n% Thanks to Peter John Acklam\n%\n\nfunction y = base64encode(x, eol)\n%BASE64ENCODE Perform base64 encoding on a string.\n%\n% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending\n% sequence to use; it is optional and defaults to '\\n' (ASCII decimal 10).\n% The returned encoded string is broken into lines of no more than 76\n% characters each, and each line will end with EOL unless it is empty. Let\n% EOL be empty if you do not want the encoded string broken into lines.\n%\n% STR and EOL don't have to be strings (i.e., char arrays). The only\n% requirement is that they are vectors containing values in the range 0-255.\n%\n% This function may be used to encode strings into the Base64 encoding\n% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The\n% Base64 encoding is designed to represent arbitrary sequences of octets in a\n% form that need not be humanly readable. A 65-character subset\n% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per\n% printable character.\n%\n% Examples\n% --------\n%\n% If you want to encode a large file, you should encode it in chunks that are\n% a multiple of 57 bytes. This ensures that the base64 lines line up and\n% that you do not end up with padding in the middle. 57 bytes of data fills\n% one complete base64 line (76 == 57*4/3):\n%\n% If ifid and ofid are two file identifiers opened for reading and writing,\n% respectively, then you can base64 encode the data with\n%\n% while ~feof(ifid)\n% fwrite(ofid, base64encode(fread(ifid, 60*57)));\n% end\n%\n% or, if you have enough memory,\n%\n% fwrite(ofid, base64encode(fread(ifid)));\n%\n% See also BASE64DECODE.\n\n% Author: Peter John Acklam\n% Time-stamp: 2004-02-03 21:36:56 +0100\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n if isnumeric(x)\n x = num2str(x);\n end\n\n % make sure we have the EOL value\n if nargin < 2\n eol = sprintf('\\n');\n else\n if sum(size(eol) > 1) > 1\n error('EOL must be a vector.');\n end\n if any(eol(:) > 255)\n error('EOL can not contain values larger than 255.');\n end\n end\n\n if sum(size(x) > 1) > 1\n error('STR must be a vector.');\n end\n\n x = uint8(x);\n eol = uint8(eol);\n\n ndbytes = length(x); % number of decoded bytes\n nchunks = ceil(ndbytes / 3); % number of chunks/groups\n nebytes = 4 * nchunks; % number of encoded bytes\n\n % add padding if necessary, to make the length of x a multiple of 3\n if rem(ndbytes, 3)\n x(end+1 : 3*nchunks) = 0;\n end\n\n x = reshape(x, [3, nchunks]); % reshape the data\n y = repmat(uint8(0), 4, nchunks); % for the encoded data\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Split up every 3 bytes into 4 pieces\n %\n % aaaaaabb bbbbcccc ccdddddd\n %\n % to form\n %\n % 00aaaaaa 00bbbbbb 00cccccc 00dddddd\n %\n y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)\n\n y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)\n y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)\n\n y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)\n y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)\n\n y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Now perform the following mapping\n %\n % 0 - 25 -> A-Z\n % 26 - 51 -> a-z\n % 52 - 61 -> 0-9\n % 62 -> +\n % 63 -> /\n %\n % We could use a mapping vector like\n %\n % ['A':'Z', 'a':'z', '0':'9', '+/']\n %\n % but that would require an index vector of class double.\n %\n z = repmat(uint8(0), size(y));\n i = y <= 25; z(i) = 'A' + double(y(i));\n i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));\n i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));\n i = y == 62; z(i) = '+';\n i = y == 63; z(i) = '/';\n y = z;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Add padding if necessary.\n %\n npbytes = 3 * nchunks - ndbytes; % number of padding bytes\n if npbytes\n y(end-npbytes+1 : end) = '='; % '=' is used for padding\n end\n\n if isempty(eol)\n\n % reshape to a row vector\n y = reshape(y, [1, nebytes]);\n\n else\n\n nlines = ceil(nebytes / 76); % number of lines\n neolbytes = length(eol); % number of bytes in eol string\n\n % pad data so it becomes a multiple of 76 elements\n y = [y(:) ; zeros(76 * nlines - numel(y), 1)];\n y(nebytes + 1 : 76 * nlines) = 0;\n y = reshape(y, 76, nlines);\n\n % insert eol strings\n eol = eol(:);\n y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));\n\n % remove padding, but keep the last eol string\n m = nebytes + neolbytes * (nlines - 1);\n n = (76+neolbytes)*nlines - neolbytes;\n y(m+1 : n) = '';\n\n % extract and reshape to row vector\n y = reshape(y, 1, m+neolbytes);\n\n end\n\n % output is a character array\n y = char(y);\n\nend\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submitWeb.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex7-008/mlclass-ex7/submitWeb.m", "size": 807, "source_encoding": "utf_8", "md5": "a53188558a96eae6cd8b0e6cda4d478d", "text": "% submitWeb Creates files from your code and output for web submission.\n%\n% If the submit function does not work for you, use the web-submission mechanism.\n% Call this function to produce a file for the part you wish to submit. Then,\n% submit the file to the class servers using the \"Web Submission\" button on the \n% Programming Exercises page on the course website.\n%\n% You should call this function without arguments (submitWeb), to receive\n% an interactive prompt for submission; optionally you can call it with the partID\n% if you so wish. Make sure your working directory is set to the directory \n% containing the submitWeb.m file and your assignment files.\n\nfunction submitWeb(partId)\n if ~exist('partId', 'var') || isempty(partId)\n partId = [];\n end\n \n submit(partId, 1);\nend\n\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submit.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex1-008/mlclass-ex1/submit.m", "size": 17317, "source_encoding": "utf_8", "md5": "14dfeccc6eb749406cb5d77fabb6bf47", "text": "function submit(partId, webSubmit)\n%SUBMIT Submit your code and output to the ml-class servers\n% SUBMIT() will connect to the ml-class server and submit your solution\n\n fprintf('==\\n== [ml-class] Submitting Solutions | Programming Exercise %s\\n==\\n', ...\n homework_id());\n if ~exist('partId', 'var') || isempty(partId)\n partId = promptPart();\n end\n\n if ~exist('webSubmit', 'var') || isempty(webSubmit)\n webSubmit = 0; % submit directly by default \n end\n\n % Check valid partId\n partNames = validParts();\n if ~isValidPartId(partId)\n fprintf('!! Invalid homework part selected.\\n');\n fprintf('!! Expected an integer from 1 to %d.\\n', numel(partNames) + 1);\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n if ~exist('ml_login_data.mat','file')\n [login password] = loginPrompt();\n save('ml_login_data.mat','login','password');\n else \n load('ml_login_data.mat');\n [login password] = quickLogin(login, password);\n save('ml_login_data.mat','login','password');\n end\n\n if isempty(login)\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n fprintf('\\n== Connecting to ml-class ... '); \n if exist('OCTAVE_VERSION') \n fflush(stdout);\n end\n\n % Setup submit list\n if partId == numel(partNames) + 1\n submitParts = 1:numel(partNames);\n else\n submitParts = [partId];\n end\n\n for s = 1:numel(submitParts)\n thisPartId = submitParts(s);\n if (~webSubmit) % submit directly to server\n [login, ch, signature, auxstring] = getChallenge(login, thisPartId);\n if isempty(login) || isempty(ch) || isempty(signature)\n % Some error occured, error string in first return element.\n fprintf('\\n!! Error: %s\\n\\n', login);\n return\n end\n\n % Attempt Submission with Challenge\n ch_resp = challengeResponse(login, password, ch);\n\n [result, str] = submitSolution(login, ch_resp, thisPartId, ...\n output(thisPartId, auxstring), source(thisPartId), signature);\n\n partName = partNames{thisPartId};\n\n fprintf('\\n== [ml-class] Submitted Assignment %s - Part %d - %s\\n', ...\n homework_id(), thisPartId, partName);\n fprintf('== %s\\n', strtrim(str));\n\n if exist('OCTAVE_VERSION')\n fflush(stdout);\n end\n else\n [result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...\n source(thisPartId));\n result = base64encode(result);\n\n fprintf('\\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...\n homework_id(), thisPartId);\n saveAsFile = input('', 's');\n if (isempty(saveAsFile))\n saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);\n end\n\n fid = fopen(saveAsFile, 'w');\n if (fid)\n fwrite(fid, result);\n fclose(fid);\n fprintf('\\nSaved your solutions to %s.\\n\\n', saveAsFile);\n fprintf(['You can now submit your solutions through the web \\n' ...\n 'form in the programming exercises. Select the corresponding \\n' ...\n 'programming exercise to access the form.\\n']);\n\n else\n fprintf('Unable to save to %s\\n\\n', saveAsFile);\n fprintf(['You can create a submission file by saving the \\n' ...\n 'following text in a file: (press enter to continue)\\n\\n']);\n pause;\n fprintf(result);\n end\n end\n end\nend\n\n% ================== CONFIGURABLES FOR EACH HOMEWORK ==================\n\nfunction id = homework_id()\n id = '1';\nend\n\nfunction [partNames] = validParts()\n partNames = { 'Warm up exercise ', ...\n 'Computing Cost (for one variable)', ...\n 'Gradient Descent (for one variable)', ...\n 'Feature Normalization', ...\n 'Computing Cost (for multiple variables)', ...\n 'Gradient Descent (for multiple variables)', ...\n 'Normal Equations'};\nend\n\nfunction srcs = sources()\n % Separated by part\n srcs = { { 'warmUpExercise.m' }, ...\n { 'computeCost.m' }, ...\n { 'gradientDescent.m' }, ...\n { 'featureNormalize.m' }, ...\n { 'computeCostMulti.m' }, ...\n { 'gradientDescentMulti.m' }, ...\n { 'normalEqn.m' }, ...\n };\nend\n\nfunction out = output(partId, auxstring)\n % Random Test Cases\n X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))'];\n Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2));\n X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25];\n Y2 = Y1.^0.5 + Y1;\n if partId == 1\n out = sprintf('%0.5f ', warmUpExercise());\n elseif partId == 2\n out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]'));\n elseif partId == 3\n out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10));\n elseif partId == 4\n out = sprintf('%0.5f ', featureNormalize(X2(:,2:4)));\n elseif partId == 5\n out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]'));\n elseif partId == 6\n out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10));\n elseif partId == 7\n out = sprintf('%0.5f ', normalEqn(X2, Y2));\n end \nend\n\n% ====================== SERVER CONFIGURATION ===========================\n\n% ***************** REMOVE -staging WHEN YOU DEPLOY *********************\nfunction url = site_url()\n url = 'http://class.coursera.org/ml-008';\nend\n\nfunction url = challenge_url()\n url = [site_url() '/assignment/challenge'];\nend\n\nfunction url = submit_url()\n url = [site_url() '/assignment/submit'];\nend\n\n% ========================= CHALLENGE HELPERS =========================\n\nfunction src = source(partId)\n src = '';\n src_files = sources();\n if partId <= numel(src_files)\n flist = src_files{partId};\n for i = 1:numel(flist)\n fid = fopen(flist{i});\n if (fid == -1) \n error('Error opening %s (is it missing?)', flist{i});\n end\n line = fgets(fid);\n while ischar(line)\n src = [src line]; \n line = fgets(fid);\n end\n fclose(fid);\n src = [src '||||||||'];\n end\n end\nend\n\nfunction ret = isValidPartId(partId)\n partNames = validParts();\n ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);\nend\n\nfunction partId = promptPart()\n fprintf('== Select which part(s) to submit:\\n');\n partNames = validParts();\n srcFiles = sources();\n for i = 1:numel(partNames)\n fprintf('== %d) %s [', i, partNames{i});\n fprintf(' %s ', srcFiles{i}{:});\n fprintf(']\\n');\n end\n fprintf('== %d) All of the above \\n==\\nEnter your choice [1-%d]: ', ...\n numel(partNames) + 1, numel(partNames) + 1);\n selPart = input('', 's');\n partId = str2num(selPart);\n if ~isValidPartId(partId)\n partId = -1;\n end\nend\n\nfunction [email,ch,signature,auxstring] = getChallenge(email, part)\n str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});\n\n str = strtrim(str);\n r = struct;\n while(numel(str) > 0)\n [f, str] = strtok (str, '|');\n [v, str] = strtok (str, '|');\n r = setfield(r, f, v);\n end\n\n email = getfield(r, 'email_address');\n ch = getfield(r, 'challenge_key');\n signature = getfield(r, 'state');\n auxstring = getfield(r, 'challenge_aux_data');\nend\n\nfunction [result, str] = submitSolutionWeb(email, part, output, source)\n\n result = ['{\"assignment_part_sid\":\"' base64encode([homework_id() '-' num2str(part)], '') '\",' ...\n '\"email_address\":\"' base64encode(email, '') '\",' ...\n '\"submission\":\"' base64encode(output, '') '\",' ...\n '\"submission_aux\":\"' base64encode(source, '') '\"' ...\n '}'];\n str = 'Web-submission';\nend\n\nfunction [result, str] = submitSolution(email, ch_resp, part, output, ...\n source, signature)\n\n params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...\n 'email_address', email, ...\n 'submission', base64encode(output, ''), ...\n 'submission_aux', base64encode(source, ''), ...\n 'challenge_response', ch_resp, ...\n 'state', signature};\n\n str = urlread(submit_url(), 'post', params);\n\n % Parse str to read for success / failure\n result = 0;\n\nend\n\n% =========================== LOGIN HELPERS ===========================\n\nfunction [login password] = loginPrompt()\n % Prompt for password\n [login password] = basicPrompt();\n \n if isempty(login) || isempty(password)\n login = []; password = [];\n end\nend\n\n\nfunction [login password] = basicPrompt()\n login = input('Login (Email address): ', 's');\n password = input('Password: ', 's');\nend\n\nfunction [login password] = quickLogin(login,password)\n disp(['You are currently logged in as ' login '.']);\n cont_token = input('Is this you? (y/n - type n to reenter password)','s');\n if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')\n return;\n else\n [login password] = loginPrompt();\n end\nend\n\nfunction [str] = challengeResponse(email, passwd, challenge)\n str = sha1([challenge passwd]);\nend\n\n% =============================== SHA-1 ================================\n\nfunction hash = sha1(str)\n \n % Initialize variables\n h0 = uint32(1732584193);\n h1 = uint32(4023233417);\n h2 = uint32(2562383102);\n h3 = uint32(271733878);\n h4 = uint32(3285377520);\n \n % Convert to word array\n strlen = numel(str);\n\n % Break string into chars and append the bit 1 to the message\n mC = [double(str) 128];\n mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];\n \n numB = strlen * 8;\n if exist('idivide')\n numC = idivide(uint32(numB + 65), 512, 'ceil');\n else\n numC = ceil(double(numB + 65)/512);\n end\n numW = numC * 16;\n mW = zeros(numW, 1, 'uint32');\n \n idx = 1;\n for i = 1:4:strlen + 1\n mW(idx) = bitor(bitor(bitor( ...\n bitshift(uint32(mC(i)), 24), ...\n bitshift(uint32(mC(i+1)), 16)), ...\n bitshift(uint32(mC(i+2)), 8)), ...\n uint32(mC(i+3)));\n idx = idx + 1;\n end\n \n % Append length of message\n mW(numW - 1) = uint32(bitshift(uint64(numB), -32));\n mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));\n\n % Process the message in successive 512-bit chs\n for cId = 1 : double(numC)\n cSt = (cId - 1) * 16 + 1;\n cEnd = cId * 16;\n ch = mW(cSt : cEnd);\n \n % Extend the sixteen 32-bit words into eighty 32-bit words\n for j = 17 : 80\n ch(j) = ch(j - 3);\n ch(j) = bitxor(ch(j), ch(j - 8));\n ch(j) = bitxor(ch(j), ch(j - 14));\n ch(j) = bitxor(ch(j), ch(j - 16));\n ch(j) = bitrotate(ch(j), 1);\n end\n \n % Initialize hash value for this ch\n a = h0;\n b = h1;\n c = h2;\n d = h3;\n e = h4;\n \n % Main loop\n for i = 1 : 80\n if(i >= 1 && i <= 20)\n f = bitor(bitand(b, c), bitand(bitcmp(b), d));\n k = uint32(1518500249);\n elseif(i >= 21 && i <= 40)\n f = bitxor(bitxor(b, c), d);\n k = uint32(1859775393);\n elseif(i >= 41 && i <= 60)\n f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));\n k = uint32(2400959708);\n elseif(i >= 61 && i <= 80)\n f = bitxor(bitxor(b, c), d);\n k = uint32(3395469782);\n end\n \n t = bitrotate(a, 5);\n t = bitadd(t, f);\n t = bitadd(t, e);\n t = bitadd(t, k);\n t = bitadd(t, ch(i));\n e = d;\n d = c;\n c = bitrotate(b, 30);\n b = a;\n a = t;\n \n end\n h0 = bitadd(h0, a);\n h1 = bitadd(h1, b);\n h2 = bitadd(h2, c);\n h3 = bitadd(h3, d);\n h4 = bitadd(h4, e);\n\n end\n\n hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);\n \n hash = lower(hash);\n\nend\n\nfunction ret = bitadd(iA, iB)\n ret = double(iA) + double(iB);\n ret = bitset(ret, 33, 0);\n ret = uint32(ret);\nend\n\nfunction ret = bitrotate(iA, places)\n t = bitshift(iA, places - 32);\n ret = bitshift(iA, places);\n ret = bitor(ret, t);\nend\n\n% =========================== Base64 Encoder ============================\n% Thanks to Peter John Acklam\n%\n\nfunction y = base64encode(x, eol)\n%BASE64ENCODE Perform base64 encoding on a string.\n%\n% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending\n% sequence to use; it is optional and defaults to '\\n' (ASCII decimal 10).\n% The returned encoded string is broken into lines of no more than 76\n% characters each, and each line will end with EOL unless it is empty. Let\n% EOL be empty if you do not want the encoded string broken into lines.\n%\n% STR and EOL don't have to be strings (i.e., char arrays). The only\n% requirement is that they are vectors containing values in the range 0-255.\n%\n% This function may be used to encode strings into the Base64 encoding\n% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The\n% Base64 encoding is designed to represent arbitrary sequences of octets in a\n% form that need not be humanly readable. A 65-character subset\n% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per\n% printable character.\n%\n% Examples\n% --------\n%\n% If you want to encode a large file, you should encode it in chunks that are\n% a multiple of 57 bytes. This ensures that the base64 lines line up and\n% that you do not end up with padding in the middle. 57 bytes of data fills\n% one complete base64 line (76 == 57*4/3):\n%\n% If ifid and ofid are two file identifiers opened for reading and writing,\n% respectively, then you can base64 encode the data with\n%\n% while ~feof(ifid)\n% fwrite(ofid, base64encode(fread(ifid, 60*57)));\n% end\n%\n% or, if you have enough memory,\n%\n% fwrite(ofid, base64encode(fread(ifid)));\n%\n% See also BASE64DECODE.\n\n% Author: Peter John Acklam\n% Time-stamp: 2004-02-03 21:36:56 +0100\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n if isnumeric(x)\n x = num2str(x);\n end\n\n % make sure we have the EOL value\n if nargin < 2\n eol = sprintf('\\n');\n else\n if sum(size(eol) > 1) > 1\n error('EOL must be a vector.');\n end\n if any(eol(:) > 255)\n error('EOL can not contain values larger than 255.');\n end\n end\n\n if sum(size(x) > 1) > 1\n error('STR must be a vector.');\n end\n\n x = uint8(x);\n eol = uint8(eol);\n\n ndbytes = length(x); % number of decoded bytes\n nchunks = ceil(ndbytes / 3); % number of chunks/groups\n nebytes = 4 * nchunks; % number of encoded bytes\n\n % add padding if necessary, to make the length of x a multiple of 3\n if rem(ndbytes, 3)\n x(end+1 : 3*nchunks) = 0;\n end\n\n x = reshape(x, [3, nchunks]); % reshape the data\n y = repmat(uint8(0), 4, nchunks); % for the encoded data\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Split up every 3 bytes into 4 pieces\n %\n % aaaaaabb bbbbcccc ccdddddd\n %\n % to form\n %\n % 00aaaaaa 00bbbbbb 00cccccc 00dddddd\n %\n y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)\n\n y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)\n y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)\n\n y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)\n y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)\n\n y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Now perform the following mapping\n %\n % 0 - 25 -> A-Z\n % 26 - 51 -> a-z\n % 52 - 61 -> 0-9\n % 62 -> +\n % 63 -> /\n %\n % We could use a mapping vector like\n %\n % ['A':'Z', 'a':'z', '0':'9', '+/']\n %\n % but that would require an index vector of class double.\n %\n z = repmat(uint8(0), size(y));\n i = y <= 25; z(i) = 'A' + double(y(i));\n i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));\n i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));\n i = y == 62; z(i) = '+';\n i = y == 63; z(i) = '/';\n y = z;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Add padding if necessary.\n %\n npbytes = 3 * nchunks - ndbytes; % number of padding bytes\n if npbytes\n y(end-npbytes+1 : end) = '='; % '=' is used for padding\n end\n\n if isempty(eol)\n\n % reshape to a row vector\n y = reshape(y, [1, nebytes]);\n\n else\n\n nlines = ceil(nebytes / 76); % number of lines\n neolbytes = length(eol); % number of bytes in eol string\n\n % pad data so it becomes a multiple of 76 elements\n y = [y(:) ; zeros(76 * nlines - numel(y), 1)];\n y(nebytes + 1 : 76 * nlines) = 0;\n y = reshape(y, 76, nlines);\n\n % insert eol strings\n eol = eol(:);\n y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));\n\n % remove padding, but keep the last eol string\n m = nebytes + neolbytes * (nlines - 1);\n n = (76+neolbytes)*nlines - neolbytes;\n y(m+1 : n) = '';\n\n % extract and reshape to row vector\n y = reshape(y, 1, m+neolbytes);\n\n end\n\n % output is a character array\n y = char(y);\n\nend\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submitWeb.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex1-008/mlclass-ex1/submitWeb.m", "size": 807, "source_encoding": "utf_8", "md5": "a53188558a96eae6cd8b0e6cda4d478d", "text": "% submitWeb Creates files from your code and output for web submission.\n%\n% If the submit function does not work for you, use the web-submission mechanism.\n% Call this function to produce a file for the part you wish to submit. Then,\n% submit the file to the class servers using the \"Web Submission\" button on the \n% Programming Exercises page on the course website.\n%\n% You should call this function without arguments (submitWeb), to receive\n% an interactive prompt for submission; optionally you can call it with the partID\n% if you so wish. Make sure your working directory is set to the directory \n% containing the submitWeb.m file and your assignment files.\n\nfunction submitWeb(partId)\n if ~exist('partId', 'var') || isempty(partId)\n partId = [];\n end\n \n submit(partId, 1);\nend\n\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submit.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex8-008/mlclass-ex8/submit.m", "size": 17515, "source_encoding": "utf_8", "md5": "2949fbde41e47f99c42171e2e0a39efc", "text": "function submit(partId, webSubmit)\n%SUBMIT Submit your code and output to the ml-class servers\n% SUBMIT() will connect to the ml-class server and submit your solution\n\n fprintf('==\\n== [ml-class] Submitting Solutions | Programming Exercise %s\\n==\\n', ...\n homework_id());\n if ~exist('partId', 'var') || isempty(partId)\n partId = promptPart();\n end\n\n if ~exist('webSubmit', 'var') || isempty(webSubmit)\n webSubmit = 0; % submit directly by default \n end\n\n % Check valid partId\n partNames = validParts();\n if ~isValidPartId(partId)\n fprintf('!! Invalid homework part selected.\\n');\n fprintf('!! Expected an integer from 1 to %d.\\n', numel(partNames) + 1);\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n if ~exist('ml_login_data.mat','file')\n [login password] = loginPrompt();\n save('ml_login_data.mat','login','password');\n else \n load('ml_login_data.mat');\n [login password] = quickLogin(login, password);\n save('ml_login_data.mat','login','password');\n end\n\n if isempty(login)\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n fprintf('\\n== Connecting to ml-class ... '); \n if exist('OCTAVE_VERSION') \n fflush(stdout);\n end\n\n % Setup submit list\n if partId == numel(partNames) + 1\n submitParts = 1:numel(partNames);\n else\n submitParts = [partId];\n end\n\n for s = 1:numel(submitParts)\n thisPartId = submitParts(s);\n if (~webSubmit) % submit directly to server\n [login, ch, signature, auxstring] = getChallenge(login, thisPartId);\n if isempty(login) || isempty(ch) || isempty(signature)\n % Some error occured, error string in first return element.\n fprintf('\\n!! Error: %s\\n\\n', login);\n return\n end\n\n % Attempt Submission with Challenge\n ch_resp = challengeResponse(login, password, ch);\n\n [result, str] = submitSolution(login, ch_resp, thisPartId, ...\n output(thisPartId, auxstring), source(thisPartId), signature);\n\n partName = partNames{thisPartId};\n\n fprintf('\\n== [ml-class] Submitted Assignment %s - Part %d - %s\\n', ...\n homework_id(), thisPartId, partName);\n fprintf('== %s\\n', strtrim(str));\n\n if exist('OCTAVE_VERSION')\n fflush(stdout);\n end\n else\n [result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...\n source(thisPartId));\n result = base64encode(result);\n\n fprintf('\\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...\n homework_id(), thisPartId);\n saveAsFile = input('', 's');\n if (isempty(saveAsFile))\n saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);\n end\n\n fid = fopen(saveAsFile, 'w');\n if (fid)\n fwrite(fid, result);\n fclose(fid);\n fprintf('\\nSaved your solutions to %s.\\n\\n', saveAsFile);\n fprintf(['You can now submit your solutions through the web \\n' ...\n 'form in the programming exercises. Select the corresponding \\n' ...\n 'programming exercise to access the form.\\n']);\n\n else\n fprintf('Unable to save to %s\\n\\n', saveAsFile);\n fprintf(['You can create a submission file by saving the \\n' ...\n 'following text in a file: (press enter to continue)\\n\\n']);\n pause;\n fprintf(result);\n end\n end\n end\nend\n\n% ================== CONFIGURABLES FOR EACH HOMEWORK ==================\n\nfunction id = homework_id() \n id = '8';\nend\n\nfunction [partNames] = validParts()\n partNames = { 'Estimate Gaussian Parameters', ...\n 'Select Threshold' ...\n 'Collaborative Filtering Cost', ...\n 'Collaborative Filtering Gradient', ...\n 'Regularized Cost', ...\n 'Regularized Gradient' ...\n };\nend\n\nfunction srcs = sources()\n % Separated by part\n srcs = { { 'estimateGaussian.m' }, ...\n { 'selectThreshold.m' }, ...\n { 'cofiCostFunc.m' }, ...\n { 'cofiCostFunc.m' }, ...\n { 'cofiCostFunc.m' }, ...\n { 'cofiCostFunc.m' }, ...\n };\nend\n\nfunction out = output(partId, auxstring)\n % Random Test Cases\n n_u = 3; n_m = 4; n = 5;\n X = reshape(sin(1:n_m*n), n_m, n);\n Theta = reshape(cos(1:n_u*n), n_u, n);\n Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u);\n R = Y > 0.5;\n pval = [abs(Y(:)) ; 0.001; 1];\n yval = [R(:) ; 1; 0];\n params = [X(:); Theta(:)];\n if partId == 1\n [mu sigma2] = estimateGaussian(X);\n out = sprintf('%0.5f ', [mu(:); sigma2(:)]);\n elseif partId == 2\n [bestEpsilon bestF1] = selectThreshold(yval, pval);\n out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]);\n elseif partId == 3\n [J] = cofiCostFunc(params, Y, R, n_u, n_m, ...\n n, 0);\n out = sprintf('%0.5f ', J(:));\n elseif partId == 4\n [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...\n n, 0);\n out = sprintf('%0.5f ', grad(:));\n elseif partId == 5\n [J] = cofiCostFunc(params, Y, R, n_u, n_m, ...\n n, 1.5);\n out = sprintf('%0.5f ', J(:));\n elseif partId == 6\n [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...\n n, 1.5);\n out = sprintf('%0.5f ', grad(:));\n end \nend\n\n% ====================== SERVER CONFIGURATION ===========================\n\n% ***************** REMOVE -staging WHEN YOU DEPLOY *********************\nfunction url = site_url()\n url = 'http://class.coursera.org/ml-008';\nend\n\nfunction url = challenge_url()\n url = [site_url() '/assignment/challenge'];\nend\n\nfunction url = submit_url()\n url = [site_url() '/assignment/submit'];\nend\n\n% ========================= CHALLENGE HELPERS =========================\n\nfunction src = source(partId)\n src = '';\n src_files = sources();\n if partId <= numel(src_files)\n flist = src_files{partId};\n for i = 1:numel(flist)\n fid = fopen(flist{i});\n if (fid == -1) \n error('Error opening %s (is it missing?)', flist{i});\n end\n line = fgets(fid);\n while ischar(line)\n src = [src line]; \n line = fgets(fid);\n end\n fclose(fid);\n src = [src '||||||||'];\n end\n end\nend\n\nfunction ret = isValidPartId(partId)\n partNames = validParts();\n ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);\nend\n\nfunction partId = promptPart()\n fprintf('== Select which part(s) to submit:\\n');\n partNames = validParts();\n srcFiles = sources();\n for i = 1:numel(partNames)\n fprintf('== %d) %s [', i, partNames{i});\n fprintf(' %s ', srcFiles{i}{:});\n fprintf(']\\n');\n end\n fprintf('== %d) All of the above \\n==\\nEnter your choice [1-%d]: ', ...\n numel(partNames) + 1, numel(partNames) + 1);\n selPart = input('', 's');\n partId = str2num(selPart);\n if ~isValidPartId(partId)\n partId = -1;\n end\nend\n\nfunction [email,ch,signature,auxstring] = getChallenge(email, part)\n str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});\n\n str = strtrim(str);\n r = struct;\n while(numel(str) > 0)\n [f, str] = strtok (str, '|');\n [v, str] = strtok (str, '|');\n r = setfield(r, f, v);\n end\n\n email = getfield(r, 'email_address');\n ch = getfield(r, 'challenge_key');\n signature = getfield(r, 'state');\n auxstring = getfield(r, 'challenge_aux_data');\nend\n\nfunction [result, str] = submitSolutionWeb(email, part, output, source)\n\n result = ['{\"assignment_part_sid\":\"' base64encode([homework_id() '-' num2str(part)], '') '\",' ...\n '\"email_address\":\"' base64encode(email, '') '\",' ...\n '\"submission\":\"' base64encode(output, '') '\",' ...\n '\"submission_aux\":\"' base64encode(source, '') '\"' ...\n '}'];\n str = 'Web-submission';\nend\n\nfunction [result, str] = submitSolution(email, ch_resp, part, output, ...\n source, signature)\n\n params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...\n 'email_address', email, ...\n 'submission', base64encode(output, ''), ...\n 'submission_aux', base64encode(source, ''), ...\n 'challenge_response', ch_resp, ...\n 'state', signature};\n\n str = urlread(submit_url(), 'post', params);\n\n % Parse str to read for success / failure\n result = 0;\n\nend\n\n% =========================== LOGIN HELPERS ===========================\n\nfunction [login password] = loginPrompt()\n % Prompt for password\n [login password] = basicPrompt();\n \n if isempty(login) || isempty(password)\n login = []; password = [];\n end\nend\n\n\nfunction [login password] = basicPrompt()\n login = input('Login (Email address): ', 's');\n password = input('Password: ', 's');\nend\n\nfunction [login password] = quickLogin(login,password)\n disp(['You are currently logged in as ' login '.']);\n cont_token = input('Is this you? (y/n - type n to reenter password)','s');\n if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')\n return;\n else\n [login password] = loginPrompt();\n end\nend\n\nfunction [str] = challengeResponse(email, passwd, challenge)\n str = sha1([challenge passwd]);\nend\n\n% =============================== SHA-1 ================================\n\nfunction hash = sha1(str)\n \n % Initialize variables\n h0 = uint32(1732584193);\n h1 = uint32(4023233417);\n h2 = uint32(2562383102);\n h3 = uint32(271733878);\n h4 = uint32(3285377520);\n \n % Convert to word array\n strlen = numel(str);\n\n % Break string into chars and append the bit 1 to the message\n mC = [double(str) 128];\n mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];\n \n numB = strlen * 8;\n if exist('idivide')\n numC = idivide(uint32(numB + 65), 512, 'ceil');\n else\n numC = ceil(double(numB + 65)/512);\n end\n numW = numC * 16;\n mW = zeros(numW, 1, 'uint32');\n \n idx = 1;\n for i = 1:4:strlen + 1\n mW(idx) = bitor(bitor(bitor( ...\n bitshift(uint32(mC(i)), 24), ...\n bitshift(uint32(mC(i+1)), 16)), ...\n bitshift(uint32(mC(i+2)), 8)), ...\n uint32(mC(i+3)));\n idx = idx + 1;\n end\n \n % Append length of message\n mW(numW - 1) = uint32(bitshift(uint64(numB), -32));\n mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));\n\n % Process the message in successive 512-bit chs\n for cId = 1 : double(numC)\n cSt = (cId - 1) * 16 + 1;\n cEnd = cId * 16;\n ch = mW(cSt : cEnd);\n \n % Extend the sixteen 32-bit words into eighty 32-bit words\n for j = 17 : 80\n ch(j) = ch(j - 3);\n ch(j) = bitxor(ch(j), ch(j - 8));\n ch(j) = bitxor(ch(j), ch(j - 14));\n ch(j) = bitxor(ch(j), ch(j - 16));\n ch(j) = bitrotate(ch(j), 1);\n end\n \n % Initialize hash value for this ch\n a = h0;\n b = h1;\n c = h2;\n d = h3;\n e = h4;\n \n % Main loop\n for i = 1 : 80\n if(i >= 1 && i <= 20)\n f = bitor(bitand(b, c), bitand(bitcmp(b), d));\n k = uint32(1518500249);\n elseif(i >= 21 && i <= 40)\n f = bitxor(bitxor(b, c), d);\n k = uint32(1859775393);\n elseif(i >= 41 && i <= 60)\n f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));\n k = uint32(2400959708);\n elseif(i >= 61 && i <= 80)\n f = bitxor(bitxor(b, c), d);\n k = uint32(3395469782);\n end\n \n t = bitrotate(a, 5);\n t = bitadd(t, f);\n t = bitadd(t, e);\n t = bitadd(t, k);\n t = bitadd(t, ch(i));\n e = d;\n d = c;\n c = bitrotate(b, 30);\n b = a;\n a = t;\n \n end\n h0 = bitadd(h0, a);\n h1 = bitadd(h1, b);\n h2 = bitadd(h2, c);\n h3 = bitadd(h3, d);\n h4 = bitadd(h4, e);\n\n end\n\n hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);\n \n hash = lower(hash);\n\nend\n\nfunction ret = bitadd(iA, iB)\n ret = double(iA) + double(iB);\n ret = bitset(ret, 33, 0);\n ret = uint32(ret);\nend\n\nfunction ret = bitrotate(iA, places)\n t = bitshift(iA, places - 32);\n ret = bitshift(iA, places);\n ret = bitor(ret, t);\nend\n\n% =========================== Base64 Encoder ============================\n% Thanks to Peter John Acklam\n%\n\nfunction y = base64encode(x, eol)\n%BASE64ENCODE Perform base64 encoding on a string.\n%\n% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending\n% sequence to use; it is optional and defaults to '\\n' (ASCII decimal 10).\n% The returned encoded string is broken into lines of no more than 76\n% characters each, and each line will end with EOL unless it is empty. Let\n% EOL be empty if you do not want the encoded string broken into lines.\n%\n% STR and EOL don't have to be strings (i.e., char arrays). The only\n% requirement is that they are vectors containing values in the range 0-255.\n%\n% This function may be used to encode strings into the Base64 encoding\n% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The\n% Base64 encoding is designed to represent arbitrary sequences of octets in a\n% form that need not be humanly readable. A 65-character subset\n% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per\n% printable character.\n%\n% Examples\n% --------\n%\n% If you want to encode a large file, you should encode it in chunks that are\n% a multiple of 57 bytes. This ensures that the base64 lines line up and\n% that you do not end up with padding in the middle. 57 bytes of data fills\n% one complete base64 line (76 == 57*4/3):\n%\n% If ifid and ofid are two file identifiers opened for reading and writing,\n% respectively, then you can base64 encode the data with\n%\n% while ~feof(ifid)\n% fwrite(ofid, base64encode(fread(ifid, 60*57)));\n% end\n%\n% or, if you have enough memory,\n%\n% fwrite(ofid, base64encode(fread(ifid)));\n%\n% See also BASE64DECODE.\n\n% Author: Peter John Acklam\n% Time-stamp: 2004-02-03 21:36:56 +0100\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n if isnumeric(x)\n x = num2str(x);\n end\n\n % make sure we have the EOL value\n if nargin < 2\n eol = sprintf('\\n');\n else\n if sum(size(eol) > 1) > 1\n error('EOL must be a vector.');\n end\n if any(eol(:) > 255)\n error('EOL can not contain values larger than 255.');\n end\n end\n\n if sum(size(x) > 1) > 1\n error('STR must be a vector.');\n end\n\n x = uint8(x);\n eol = uint8(eol);\n\n ndbytes = length(x); % number of decoded bytes\n nchunks = ceil(ndbytes / 3); % number of chunks/groups\n nebytes = 4 * nchunks; % number of encoded bytes\n\n % add padding if necessary, to make the length of x a multiple of 3\n if rem(ndbytes, 3)\n x(end+1 : 3*nchunks) = 0;\n end\n\n x = reshape(x, [3, nchunks]); % reshape the data\n y = repmat(uint8(0), 4, nchunks); % for the encoded data\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Split up every 3 bytes into 4 pieces\n %\n % aaaaaabb bbbbcccc ccdddddd\n %\n % to form\n %\n % 00aaaaaa 00bbbbbb 00cccccc 00dddddd\n %\n y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)\n\n y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)\n y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)\n\n y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)\n y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)\n\n y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Now perform the following mapping\n %\n % 0 - 25 -> A-Z\n % 26 - 51 -> a-z\n % 52 - 61 -> 0-9\n % 62 -> +\n % 63 -> /\n %\n % We could use a mapping vector like\n %\n % ['A':'Z', 'a':'z', '0':'9', '+/']\n %\n % but that would require an index vector of class double.\n %\n z = repmat(uint8(0), size(y));\n i = y <= 25; z(i) = 'A' + double(y(i));\n i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));\n i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));\n i = y == 62; z(i) = '+';\n i = y == 63; z(i) = '/';\n y = z;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Add padding if necessary.\n %\n npbytes = 3 * nchunks - ndbytes; % number of padding bytes\n if npbytes\n y(end-npbytes+1 : end) = '='; % '=' is used for padding\n end\n\n if isempty(eol)\n\n % reshape to a row vector\n y = reshape(y, [1, nebytes]);\n\n else\n\n nlines = ceil(nebytes / 76); % number of lines\n neolbytes = length(eol); % number of bytes in eol string\n\n % pad data so it becomes a multiple of 76 elements\n y = [y(:) ; zeros(76 * nlines - numel(y), 1)];\n y(nebytes + 1 : 76 * nlines) = 0;\n y = reshape(y, 76, nlines);\n\n % insert eol strings\n eol = eol(:);\n y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));\n\n % remove padding, but keep the last eol string\n m = nebytes + neolbytes * (nlines - 1);\n n = (76+neolbytes)*nlines - neolbytes;\n y(m+1 : n) = '';\n\n % extract and reshape to row vector\n y = reshape(y, 1, m+neolbytes);\n\n end\n\n % output is a character array\n y = char(y);\n\nend\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submitWeb.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex8-008/mlclass-ex8/submitWeb.m", "size": 807, "source_encoding": "utf_8", "md5": "a53188558a96eae6cd8b0e6cda4d478d", "text": "% submitWeb Creates files from your code and output for web submission.\n%\n% If the submit function does not work for you, use the web-submission mechanism.\n% Call this function to produce a file for the part you wish to submit. Then,\n% submit the file to the class servers using the \"Web Submission\" button on the \n% Programming Exercises page on the course website.\n%\n% You should call this function without arguments (submitWeb), to receive\n% an interactive prompt for submission; optionally you can call it with the partID\n% if you so wish. Make sure your working directory is set to the directory \n% containing the submitWeb.m file and your assignment files.\n\nfunction submitWeb(partId)\n if ~exist('partId', 'var') || isempty(partId)\n partId = [];\n end\n \n submit(partId, 1);\nend\n\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submit.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex6-008/mlclass-ex6/submit.m", "size": 16836, "source_encoding": "utf_8", "md5": "d4c87e5dbf32a81bdaf04fd017fe4cb3", "text": "function submit(partId, webSubmit)\n%SUBMIT Submit your code and output to the ml-class servers\n% SUBMIT() will connect to the ml-class server and submit your solution\n\n fprintf('==\\n== [ml-class] Submitting Solutions | Programming Exercise %s\\n==\\n', ...\n homework_id());\n if ~exist('partId', 'var') || isempty(partId)\n partId = promptPart();\n end\n\n if ~exist('webSubmit', 'var') || isempty(webSubmit)\n webSubmit = 0; % submit directly by default \n end\n\n % Check valid partId\n partNames = validParts();\n if ~isValidPartId(partId)\n fprintf('!! Invalid homework part selected.\\n');\n fprintf('!! Expected an integer from 1 to %d.\\n', numel(partNames) + 1);\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n if ~exist('ml_login_data.mat','file')\n [login password] = loginPrompt();\n save('ml_login_data.mat','login','password');\n else \n load('ml_login_data.mat');\n [login password] = quickLogin(login, password);\n save('ml_login_data.mat','login','password');\n end\n\n if isempty(login)\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n fprintf('\\n== Connecting to ml-class ... '); \n if exist('OCTAVE_VERSION') \n fflush(stdout);\n end\n\n % Setup submit list\n if partId == numel(partNames) + 1\n submitParts = 1:numel(partNames);\n else\n submitParts = [partId];\n end\n\n for s = 1:numel(submitParts)\n thisPartId = submitParts(s);\n if (~webSubmit) % submit directly to server\n [login, ch, signature, auxstring] = getChallenge(login, thisPartId);\n if isempty(login) || isempty(ch) || isempty(signature)\n % Some error occured, error string in first return element.\n fprintf('\\n!! Error: %s\\n\\n', login);\n return\n end\n\n % Attempt Submission with Challenge\n ch_resp = challengeResponse(login, password, ch);\n\n [result, str] = submitSolution(login, ch_resp, thisPartId, ...\n output(thisPartId, auxstring), source(thisPartId), signature);\n\n partName = partNames{thisPartId};\n\n fprintf('\\n== [ml-class] Submitted Assignment %s - Part %d - %s\\n', ...\n homework_id(), thisPartId, partName);\n fprintf('== %s\\n', strtrim(str));\n\n if exist('OCTAVE_VERSION')\n fflush(stdout);\n end\n else\n [result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...\n source(thisPartId));\n result = base64encode(result);\n\n fprintf('\\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...\n homework_id(), thisPartId);\n saveAsFile = input('', 's');\n if (isempty(saveAsFile))\n saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);\n end\n\n fid = fopen(saveAsFile, 'w');\n if (fid)\n fwrite(fid, result);\n fclose(fid);\n fprintf('\\nSaved your solutions to %s.\\n\\n', saveAsFile);\n fprintf(['You can now submit your solutions through the web \\n' ...\n 'form in the programming exercises. Select the corresponding \\n' ...\n 'programming exercise to access the form.\\n']);\n\n else\n fprintf('Unable to save to %s\\n\\n', saveAsFile);\n fprintf(['You can create a submission file by saving the \\n' ...\n 'following text in a file: (press enter to continue)\\n\\n']);\n pause;\n fprintf(result);\n end\n end\n end\nend\n\n% ================== CONFIGURABLES FOR EACH HOMEWORK ==================\n\nfunction id = homework_id() \n id = '6';\nend\n\nfunction [partNames] = validParts()\n partNames = { 'Gaussian Kernel', ...\n 'Parameters (C, sigma) for Dataset 3', ...\n 'Email Preprocessing' ...\n 'Email Feature Extraction' ...\n };\nend\n\nfunction srcs = sources()\n % Separated by part\n srcs = { { 'gaussianKernel.m' }, ...\n { 'dataset3Params.m' }, ...\n { 'processEmail.m' }, ...\n { 'emailFeatures.m' } };\nend\n\nfunction out = output(partId, auxstring)\n % Random Test Cases\n x1 = sin(1:10)';\n x2 = cos(1:10)';\n ec = 'the quick brown fox jumped over the lazy dog';\n wi = 1 + abs(round(x1 * 1863));\n wi = [wi ; wi];\n if partId == 1\n sim = gaussianKernel(x1, x2, 2);\n out = sprintf('%0.5f ', sim);\n elseif partId == 2\n load('ex6data3.mat');\n [C, sigma] = dataset3Params(X, y, Xval, yval);\n out = sprintf('%0.5f ', C);\n out = [out sprintf('%0.5f ', sigma)];\n elseif partId == 3\n word_indices = processEmail(ec);\n out = sprintf('%d ', word_indices);\n elseif partId == 4\n x = emailFeatures(wi);\n out = sprintf('%d ', x);\n end \nend\n\n\n% ====================== SERVER CONFIGURATION ===========================\n\n% ***************** REMOVE -staging WHEN YOU DEPLOY *********************\nfunction url = site_url()\n url = 'http://class.coursera.org/ml-008';\nend\n\nfunction url = challenge_url()\n url = [site_url() '/assignment/challenge'];\nend\n\nfunction url = submit_url()\n url = [site_url() '/assignment/submit'];\nend\n\n% ========================= CHALLENGE HELPERS =========================\n\nfunction src = source(partId)\n src = '';\n src_files = sources();\n if partId <= numel(src_files)\n flist = src_files{partId};\n for i = 1:numel(flist)\n fid = fopen(flist{i});\n if (fid == -1) \n error('Error opening %s (is it missing?)', flist{i});\n end\n line = fgets(fid);\n while ischar(line)\n src = [src line]; \n line = fgets(fid);\n end\n fclose(fid);\n src = [src '||||||||'];\n end\n end\nend\n\nfunction ret = isValidPartId(partId)\n partNames = validParts();\n ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);\nend\n\nfunction partId = promptPart()\n fprintf('== Select which part(s) to submit:\\n');\n partNames = validParts();\n srcFiles = sources();\n for i = 1:numel(partNames)\n fprintf('== %d) %s [', i, partNames{i});\n fprintf(' %s ', srcFiles{i}{:});\n fprintf(']\\n');\n end\n fprintf('== %d) All of the above \\n==\\nEnter your choice [1-%d]: ', ...\n numel(partNames) + 1, numel(partNames) + 1);\n selPart = input('', 's');\n partId = str2num(selPart);\n if ~isValidPartId(partId)\n partId = -1;\n end\nend\n\nfunction [email,ch,signature,auxstring] = getChallenge(email, part)\n str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});\n\n str = strtrim(str);\n r = struct;\n while(numel(str) > 0)\n [f, str] = strtok (str, '|');\n [v, str] = strtok (str, '|');\n r = setfield(r, f, v);\n end\n\n email = getfield(r, 'email_address');\n ch = getfield(r, 'challenge_key');\n signature = getfield(r, 'state');\n auxstring = getfield(r, 'challenge_aux_data');\nend\n\nfunction [result, str] = submitSolutionWeb(email, part, output, source)\n\n result = ['{\"assignment_part_sid\":\"' base64encode([homework_id() '-' num2str(part)], '') '\",' ...\n '\"email_address\":\"' base64encode(email, '') '\",' ...\n '\"submission\":\"' base64encode(output, '') '\",' ...\n '\"submission_aux\":\"' base64encode(source, '') '\"' ...\n '}'];\n str = 'Web-submission';\nend\n\nfunction [result, str] = submitSolution(email, ch_resp, part, output, ...\n source, signature)\n\n params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...\n 'email_address', email, ...\n 'submission', base64encode(output, ''), ...\n 'submission_aux', base64encode(source, ''), ...\n 'challenge_response', ch_resp, ...\n 'state', signature};\n\n str = urlread(submit_url(), 'post', params);\n\n % Parse str to read for success / failure\n result = 0;\n\nend\n\n% =========================== LOGIN HELPERS ===========================\n\nfunction [login password] = loginPrompt()\n % Prompt for password\n [login password] = basicPrompt();\n \n if isempty(login) || isempty(password)\n login = []; password = [];\n end\nend\n\n\nfunction [login password] = basicPrompt()\n login = input('Login (Email address): ', 's');\n password = input('Password: ', 's');\nend\n\nfunction [login password] = quickLogin(login,password)\n disp(['You are currently logged in as ' login '.']);\n cont_token = input('Is this you? (y/n - type n to reenter password)','s');\n if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')\n return;\n else\n [login password] = loginPrompt();\n end\nend\n\nfunction [str] = challengeResponse(email, passwd, challenge)\n str = sha1([challenge passwd]);\nend\n\n% =============================== SHA-1 ================================\n\nfunction hash = sha1(str)\n \n % Initialize variables\n h0 = uint32(1732584193);\n h1 = uint32(4023233417);\n h2 = uint32(2562383102);\n h3 = uint32(271733878);\n h4 = uint32(3285377520);\n \n % Convert to word array\n strlen = numel(str);\n\n % Break string into chars and append the bit 1 to the message\n mC = [double(str) 128];\n mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];\n \n numB = strlen * 8;\n if exist('idivide')\n numC = idivide(uint32(numB + 65), 512, 'ceil');\n else\n numC = ceil(double(numB + 65)/512);\n end\n numW = numC * 16;\n mW = zeros(numW, 1, 'uint32');\n \n idx = 1;\n for i = 1:4:strlen + 1\n mW(idx) = bitor(bitor(bitor( ...\n bitshift(uint32(mC(i)), 24), ...\n bitshift(uint32(mC(i+1)), 16)), ...\n bitshift(uint32(mC(i+2)), 8)), ...\n uint32(mC(i+3)));\n idx = idx + 1;\n end\n \n % Append length of message\n mW(numW - 1) = uint32(bitshift(uint64(numB), -32));\n mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));\n\n % Process the message in successive 512-bit chs\n for cId = 1 : double(numC)\n cSt = (cId - 1) * 16 + 1;\n cEnd = cId * 16;\n ch = mW(cSt : cEnd);\n \n % Extend the sixteen 32-bit words into eighty 32-bit words\n for j = 17 : 80\n ch(j) = ch(j - 3);\n ch(j) = bitxor(ch(j), ch(j - 8));\n ch(j) = bitxor(ch(j), ch(j - 14));\n ch(j) = bitxor(ch(j), ch(j - 16));\n ch(j) = bitrotate(ch(j), 1);\n end\n \n % Initialize hash value for this ch\n a = h0;\n b = h1;\n c = h2;\n d = h3;\n e = h4;\n \n % Main loop\n for i = 1 : 80\n if(i >= 1 && i <= 20)\n f = bitor(bitand(b, c), bitand(bitcmp(b), d));\n k = uint32(1518500249);\n elseif(i >= 21 && i <= 40)\n f = bitxor(bitxor(b, c), d);\n k = uint32(1859775393);\n elseif(i >= 41 && i <= 60)\n f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));\n k = uint32(2400959708);\n elseif(i >= 61 && i <= 80)\n f = bitxor(bitxor(b, c), d);\n k = uint32(3395469782);\n end\n \n t = bitrotate(a, 5);\n t = bitadd(t, f);\n t = bitadd(t, e);\n t = bitadd(t, k);\n t = bitadd(t, ch(i));\n e = d;\n d = c;\n c = bitrotate(b, 30);\n b = a;\n a = t;\n \n end\n h0 = bitadd(h0, a);\n h1 = bitadd(h1, b);\n h2 = bitadd(h2, c);\n h3 = bitadd(h3, d);\n h4 = bitadd(h4, e);\n\n end\n\n hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);\n \n hash = lower(hash);\n\nend\n\nfunction ret = bitadd(iA, iB)\n ret = double(iA) + double(iB);\n ret = bitset(ret, 33, 0);\n ret = uint32(ret);\nend\n\nfunction ret = bitrotate(iA, places)\n t = bitshift(iA, places - 32);\n ret = bitshift(iA, places);\n ret = bitor(ret, t);\nend\n\n% =========================== Base64 Encoder ============================\n% Thanks to Peter John Acklam\n%\n\nfunction y = base64encode(x, eol)\n%BASE64ENCODE Perform base64 encoding on a string.\n%\n% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending\n% sequence to use; it is optional and defaults to '\\n' (ASCII decimal 10).\n% The returned encoded string is broken into lines of no more than 76\n% characters each, and each line will end with EOL unless it is empty. Let\n% EOL be empty if you do not want the encoded string broken into lines.\n%\n% STR and EOL don't have to be strings (i.e., char arrays). The only\n% requirement is that they are vectors containing values in the range 0-255.\n%\n% This function may be used to encode strings into the Base64 encoding\n% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The\n% Base64 encoding is designed to represent arbitrary sequences of octets in a\n% form that need not be humanly readable. A 65-character subset\n% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per\n% printable character.\n%\n% Examples\n% --------\n%\n% If you want to encode a large file, you should encode it in chunks that are\n% a multiple of 57 bytes. This ensures that the base64 lines line up and\n% that you do not end up with padding in the middle. 57 bytes of data fills\n% one complete base64 line (76 == 57*4/3):\n%\n% If ifid and ofid are two file identifiers opened for reading and writing,\n% respectively, then you can base64 encode the data with\n%\n% while ~feof(ifid)\n% fwrite(ofid, base64encode(fread(ifid, 60*57)));\n% end\n%\n% or, if you have enough memory,\n%\n% fwrite(ofid, base64encode(fread(ifid)));\n%\n% See also BASE64DECODE.\n\n% Author: Peter John Acklam\n% Time-stamp: 2004-02-03 21:36:56 +0100\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n if isnumeric(x)\n x = num2str(x);\n end\n\n % make sure we have the EOL value\n if nargin < 2\n eol = sprintf('\\n');\n else\n if sum(size(eol) > 1) > 1\n error('EOL must be a vector.');\n end\n if any(eol(:) > 255)\n error('EOL can not contain values larger than 255.');\n end\n end\n\n if sum(size(x) > 1) > 1\n error('STR must be a vector.');\n end\n\n x = uint8(x);\n eol = uint8(eol);\n\n ndbytes = length(x); % number of decoded bytes\n nchunks = ceil(ndbytes / 3); % number of chunks/groups\n nebytes = 4 * nchunks; % number of encoded bytes\n\n % add padding if necessary, to make the length of x a multiple of 3\n if rem(ndbytes, 3)\n x(end+1 : 3*nchunks) = 0;\n end\n\n x = reshape(x, [3, nchunks]); % reshape the data\n y = repmat(uint8(0), 4, nchunks); % for the encoded data\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Split up every 3 bytes into 4 pieces\n %\n % aaaaaabb bbbbcccc ccdddddd\n %\n % to form\n %\n % 00aaaaaa 00bbbbbb 00cccccc 00dddddd\n %\n y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)\n\n y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)\n y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)\n\n y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)\n y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)\n\n y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Now perform the following mapping\n %\n % 0 - 25 -> A-Z\n % 26 - 51 -> a-z\n % 52 - 61 -> 0-9\n % 62 -> +\n % 63 -> /\n %\n % We could use a mapping vector like\n %\n % ['A':'Z', 'a':'z', '0':'9', '+/']\n %\n % but that would require an index vector of class double.\n %\n z = repmat(uint8(0), size(y));\n i = y <= 25; z(i) = 'A' + double(y(i));\n i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));\n i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));\n i = y == 62; z(i) = '+';\n i = y == 63; z(i) = '/';\n y = z;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Add padding if necessary.\n %\n npbytes = 3 * nchunks - ndbytes; % number of padding bytes\n if npbytes\n y(end-npbytes+1 : end) = '='; % '=' is used for padding\n end\n\n if isempty(eol)\n\n % reshape to a row vector\n y = reshape(y, [1, nebytes]);\n\n else\n\n nlines = ceil(nebytes / 76); % number of lines\n neolbytes = length(eol); % number of bytes in eol string\n\n % pad data so it becomes a multiple of 76 elements\n y = [y(:) ; zeros(76 * nlines - numel(y), 1)];\n y(nebytes + 1 : 76 * nlines) = 0;\n y = reshape(y, 76, nlines);\n\n % insert eol strings\n eol = eol(:);\n y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));\n\n % remove padding, but keep the last eol string\n m = nebytes + neolbytes * (nlines - 1);\n n = (76+neolbytes)*nlines - neolbytes;\n y(m+1 : n) = '';\n\n % extract and reshape to row vector\n y = reshape(y, 1, m+neolbytes);\n\n end\n\n % output is a character array\n y = char(y);\n\nend\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "porterStemmer.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex6-008/mlclass-ex6/porterStemmer.m", "size": 9902, "source_encoding": "utf_8", "md5": "7ed5acd925808fde342fc72bd62ebc4d", "text": "function stem = porterStemmer(inString)\n% Applies the Porter Stemming algorithm as presented in the following\n% paper:\n% Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14,\n% no. 3, pp 130-137\n\n% Original code modeled after the C version provided at:\n% http://www.tartarus.org/~martin/PorterStemmer/c.txt\n\n% The main part of the stemming algorithm starts here. b is an array of\n% characters, holding the word to be stemmed. The letters are in b[k0],\n% b[k0+1] ending at b[k]. In fact k0 = 1 in this demo program (since\n% matlab begins indexing by 1 instead of 0). k is readjusted downwards as\n% the stemming progresses. Zero termination is not in fact used in the\n% algorithm.\n\n% To call this function, use the string to be stemmed as the input\n% argument. This function returns the stemmed word as a string.\n\n% Lower-case string\ninString = lower(inString);\n\nglobal j;\nb = inString;\nk = length(b);\nk0 = 1;\nj = k;\n\n\n\n% With this if statement, strings of length 1 or 2 don't go through the\n% stemming process. Remove this conditional to match the published\n% algorithm.\nstem = b;\nif k > 2\n % Output displays per step are commented out.\n %disp(sprintf('Word to stem: %s', b));\n x = step1ab(b, k, k0);\n %disp(sprintf('Steps 1A and B yield: %s', x{1}));\n x = step1c(x{1}, x{2}, k0);\n %disp(sprintf('Step 1C yields: %s', x{1}));\n x = step2(x{1}, x{2}, k0);\n %disp(sprintf('Step 2 yields: %s', x{1}));\n x = step3(x{1}, x{2}, k0);\n %disp(sprintf('Step 3 yields: %s', x{1}));\n x = step4(x{1}, x{2}, k0);\n %disp(sprintf('Step 4 yields: %s', x{1}));\n x = step5(x{1}, x{2}, k0);\n %disp(sprintf('Step 5 yields: %s', x{1}));\n stem = x{1};\nend\n\n% cons(j) is TRUE <=> b[j] is a consonant.\nfunction c = cons(i, b, k0)\nc = true;\nswitch(b(i))\n case {'a', 'e', 'i', 'o', 'u'}\n c = false;\n case 'y'\n if i == k0\n c = true;\n else\n c = ~cons(i - 1, b, k0);\n end\nend\n\n% mseq() measures the number of consonant sequences between k0 and j. If\n% c is a consonant sequence and v a vowel sequence, and <..> indicates\n% arbitrary presence,\n\n% gives 0\n% vc gives 1\n% vcvc gives 2\n% vcvcvc gives 3\n% ....\nfunction n = measure(b, k0)\nglobal j;\nn = 0;\ni = k0;\nwhile true\n if i > j\n return\n end\n if ~cons(i, b, k0)\n break;\n end\n i = i + 1;\nend\ni = i + 1;\nwhile true\n while true\n if i > j\n return\n end\n if cons(i, b, k0)\n break;\n end\n i = i + 1;\n end\n i = i + 1;\n n = n + 1;\n while true\n if i > j\n return\n end\n if ~cons(i, b, k0)\n break;\n end\n i = i + 1;\n end\n i = i + 1;\nend\n\n\n% vowelinstem() is TRUE <=> k0,...j contains a vowel\nfunction vis = vowelinstem(b, k0)\nglobal j;\nfor i = k0:j,\n if ~cons(i, b, k0)\n vis = true;\n return\n end\nend\nvis = false;\n\n%doublec(i) is TRUE <=> i,(i-1) contain a double consonant.\nfunction dc = doublec(i, b, k0)\nif i < k0+1\n dc = false;\n return\nend\nif b(i) ~= b(i-1)\n dc = false;\n return\nend\ndc = cons(i, b, k0);\n\n\n% cvc(j) is TRUE <=> j-2,j-1,j has the form consonant - vowel - consonant\n% and also if the second c is not w,x or y. this is used when trying to\n% restore an e at the end of a short word. e.g.\n%\n% cav(e), lov(e), hop(e), crim(e), but\n% snow, box, tray.\n\nfunction c1 = cvc(i, b, k0)\nif ((i < (k0+2)) || ~cons(i, b, k0) || cons(i-1, b, k0) || ~cons(i-2, b, k0))\n c1 = false;\nelse\n if (b(i) == 'w' || b(i) == 'x' || b(i) == 'y')\n c1 = false;\n return\n end\n c1 = true;\nend\n\n% ends(s) is TRUE <=> k0,...k ends with the string s.\nfunction s = ends(str, b, k)\nglobal j;\nif (str(length(str)) ~= b(k))\n s = false;\n return\nend % tiny speed-up\nif (length(str) > k)\n s = false;\n return\nend\nif strcmp(b(k-length(str)+1:k), str)\n s = true;\n j = k - length(str);\n return\nelse\n s = false;\nend\n\n% setto(s) sets (j+1),...k to the characters in the string s, readjusting\n% k accordingly.\n\nfunction so = setto(s, b, k)\nglobal j;\nfor i = j+1:(j+length(s))\n b(i) = s(i-j);\nend\nif k > j+length(s)\n b((j+length(s)+1):k) = '';\nend\nk = length(b);\nso = {b, k};\n\n% rs(s) is used further down.\n% [Note: possible null/value for r if rs is called]\nfunction r = rs(str, b, k, k0)\nr = {b, k};\nif measure(b, k0) > 0\n r = setto(str, b, k);\nend\n\n% step1ab() gets rid of plurals and -ed or -ing. e.g.\n\n% caresses -> caress\n% ponies -> poni\n% ties -> ti\n% caress -> caress\n% cats -> cat\n\n% feed -> feed\n% agreed -> agree\n% disabled -> disable\n\n% matting -> mat\n% mating -> mate\n% meeting -> meet\n% milling -> mill\n% messing -> mess\n\n% meetings -> meet\n\nfunction s1ab = step1ab(b, k, k0)\nglobal j;\nif b(k) == 's'\n if ends('sses', b, k)\n k = k-2;\n elseif ends('ies', b, k)\n retVal = setto('i', b, k);\n b = retVal{1};\n k = retVal{2};\n elseif (b(k-1) ~= 's')\n k = k-1;\n end\nend\nif ends('eed', b, k)\n if measure(b, k0) > 0;\n k = k-1;\n end\nelseif (ends('ed', b, k) || ends('ing', b, k)) && vowelinstem(b, k0)\n k = j;\n retVal = {b, k};\n if ends('at', b, k)\n retVal = setto('ate', b(k0:k), k);\n elseif ends('bl', b, k)\n retVal = setto('ble', b(k0:k), k);\n elseif ends('iz', b, k)\n retVal = setto('ize', b(k0:k), k);\n elseif doublec(k, b, k0)\n retVal = {b, k-1};\n if b(retVal{2}) == 'l' || b(retVal{2}) == 's' || ...\n b(retVal{2}) == 'z'\n retVal = {retVal{1}, retVal{2}+1};\n end\n elseif measure(b, k0) == 1 && cvc(k, b, k0)\n retVal = setto('e', b(k0:k), k);\n end\n k = retVal{2};\n b = retVal{1}(k0:k);\nend\nj = k;\ns1ab = {b(k0:k), k};\n\n% step1c() turns terminal y to i when there is another vowel in the stem.\nfunction s1c = step1c(b, k, k0)\nglobal j;\nif ends('y', b, k) && vowelinstem(b, k0)\n b(k) = 'i';\nend\nj = k;\ns1c = {b, k};\n\n% step2() maps double suffices to single ones. so -ization ( = -ize plus\n% -ation) maps to -ize etc. note that the string before the suffix must give\n% m() > 0.\nfunction s2 = step2(b, k, k0)\nglobal j;\ns2 = {b, k};\nswitch b(k-1)\n case {'a'}\n if ends('ational', b, k) s2 = rs('ate', b, k, k0);\n elseif ends('tional', b, k) s2 = rs('tion', b, k, k0); end;\n case {'c'}\n if ends('enci', b, k) s2 = rs('ence', b, k, k0);\n elseif ends('anci', b, k) s2 = rs('ance', b, k, k0); end;\n case {'e'}\n if ends('izer', b, k) s2 = rs('ize', b, k, k0); end;\n case {'l'}\n if ends('bli', b, k) s2 = rs('ble', b, k, k0);\n elseif ends('alli', b, k) s2 = rs('al', b, k, k0);\n elseif ends('entli', b, k) s2 = rs('ent', b, k, k0);\n elseif ends('eli', b, k) s2 = rs('e', b, k, k0);\n elseif ends('ousli', b, k) s2 = rs('ous', b, k, k0); end;\n case {'o'}\n if ends('ization', b, k) s2 = rs('ize', b, k, k0);\n elseif ends('ation', b, k) s2 = rs('ate', b, k, k0);\n elseif ends('ator', b, k) s2 = rs('ate', b, k, k0); end;\n case {'s'}\n if ends('alism', b, k) s2 = rs('al', b, k, k0);\n elseif ends('iveness', b, k) s2 = rs('ive', b, k, k0);\n elseif ends('fulness', b, k) s2 = rs('ful', b, k, k0);\n elseif ends('ousness', b, k) s2 = rs('ous', b, k, k0); end;\n case {'t'}\n if ends('aliti', b, k) s2 = rs('al', b, k, k0);\n elseif ends('iviti', b, k) s2 = rs('ive', b, k, k0);\n elseif ends('biliti', b, k) s2 = rs('ble', b, k, k0); end;\n case {'g'}\n if ends('logi', b, k) s2 = rs('log', b, k, k0); end;\nend\nj = s2{2};\n\n% step3() deals with -ic-, -full, -ness etc. similar strategy to step2.\nfunction s3 = step3(b, k, k0)\nglobal j;\ns3 = {b, k};\nswitch b(k)\n case {'e'}\n if ends('icate', b, k) s3 = rs('ic', b, k, k0);\n elseif ends('ative', b, k) s3 = rs('', b, k, k0);\n elseif ends('alize', b, k) s3 = rs('al', b, k, k0); end;\n case {'i'}\n if ends('iciti', b, k) s3 = rs('ic', b, k, k0); end;\n case {'l'}\n if ends('ical', b, k) s3 = rs('ic', b, k, k0);\n elseif ends('ful', b, k) s3 = rs('', b, k, k0); end;\n case {'s'}\n if ends('ness', b, k) s3 = rs('', b, k, k0); end;\nend\nj = s3{2};\n\n% step4() takes off -ant, -ence etc., in context vcvc.\nfunction s4 = step4(b, k, k0)\nglobal j;\nswitch b(k-1)\n case {'a'}\n if ends('al', b, k) end;\n case {'c'}\n if ends('ance', b, k)\n elseif ends('ence', b, k) end;\n case {'e'}\n if ends('er', b, k) end;\n case {'i'}\n if ends('ic', b, k) end;\n case {'l'}\n if ends('able', b, k)\n elseif ends('ible', b, k) end;\n case {'n'}\n if ends('ant', b, k)\n elseif ends('ement', b, k)\n elseif ends('ment', b, k)\n elseif ends('ent', b, k) end;\n case {'o'}\n if ends('ion', b, k)\n if j == 0\n elseif ~(strcmp(b(j),'s') || strcmp(b(j),'t'))\n j = k;\n end\n elseif ends('ou', b, k) end;\n case {'s'}\n if ends('ism', b, k) end;\n case {'t'}\n if ends('ate', b, k)\n elseif ends('iti', b, k) end;\n case {'u'}\n if ends('ous', b, k) end;\n case {'v'}\n if ends('ive', b, k) end;\n case {'z'}\n if ends('ize', b, k) end;\nend\nif measure(b, k0) > 1\n s4 = {b(k0:j), j};\nelse\n s4 = {b(k0:k), k};\nend\n\n% step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1.\nfunction s5 = step5(b, k, k0)\nglobal j;\nj = k;\nif b(k) == 'e'\n a = measure(b, k0);\n if (a > 1) || ((a == 1) && ~cvc(k-1, b, k0))\n k = k-1;\n end\nend\nif (b(k) == 'l') && doublec(k, b, k0) && (measure(b, k0) > 1)\n k = k-1;\nend\ns5 = {b(k0:k), k};\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submitWeb.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex6-008/mlclass-ex6/submitWeb.m", "size": 807, "source_encoding": "utf_8", "md5": "a53188558a96eae6cd8b0e6cda4d478d", "text": "% submitWeb Creates files from your code and output for web submission.\n%\n% If the submit function does not work for you, use the web-submission mechanism.\n% Call this function to produce a file for the part you wish to submit. Then,\n% submit the file to the class servers using the \"Web Submission\" button on the \n% Programming Exercises page on the course website.\n%\n% You should call this function without arguments (submitWeb), to receive\n% an interactive prompt for submission; optionally you can call it with the partID\n% if you so wish. Make sure your working directory is set to the directory \n% containing the submitWeb.m file and your assignment files.\n\nfunction submitWeb(partId)\n if ~exist('partId', 'var') || isempty(partId)\n partId = [];\n end\n \n submit(partId, 1);\nend\n\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submit.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex5-008/mlclass-ex5/submit.m", "size": 17211, "source_encoding": "utf_8", "md5": "057662350ffa8db95583373185a26a6b", "text": "function submit(partId, webSubmit)\n%SUBMIT Submit your code and output to the ml-class servers\n% SUBMIT() will connect to the ml-class server and submit your solution\n\n fprintf('==\\n== [ml-class] Submitting Solutions | Programming Exercise %s\\n==\\n', ...\n homework_id());\n if ~exist('partId', 'var') || isempty(partId)\n partId = promptPart();\n end\n\n if ~exist('webSubmit', 'var') || isempty(webSubmit)\n webSubmit = 0; % submit directly by default \n end\n\n % Check valid partId\n partNames = validParts();\n if ~isValidPartId(partId)\n fprintf('!! Invalid homework part selected.\\n');\n fprintf('!! Expected an integer from 1 to %d.\\n', numel(partNames) + 1);\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n if ~exist('ml_login_data.mat','file')\n [login password] = loginPrompt();\n save('ml_login_data.mat','login','password');\n else \n load('ml_login_data.mat');\n [login password] = quickLogin(login, password);\n save('ml_login_data.mat','login','password');\n end\n\n if isempty(login)\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n fprintf('\\n== Connecting to ml-class ... '); \n if exist('OCTAVE_VERSION') \n fflush(stdout);\n end\n\n % Setup submit list\n if partId == numel(partNames) + 1\n submitParts = 1:numel(partNames);\n else\n submitParts = [partId];\n end\n\n for s = 1:numel(submitParts)\n thisPartId = submitParts(s);\n if (~webSubmit) % submit directly to server\n [login, ch, signature, auxstring] = getChallenge(login, thisPartId);\n if isempty(login) || isempty(ch) || isempty(signature)\n % Some error occured, error string in first return element.\n fprintf('\\n!! Error: %s\\n\\n', login);\n return\n end\n\n % Attempt Submission with Challenge\n ch_resp = challengeResponse(login, password, ch);\n\n [result, str] = submitSolution(login, ch_resp, thisPartId, ...\n output(thisPartId, auxstring), source(thisPartId), signature);\n\n partName = partNames{thisPartId};\n\n fprintf('\\n== [ml-class] Submitted Assignment %s - Part %d - %s\\n', ...\n homework_id(), thisPartId, partName);\n fprintf('== %s\\n', strtrim(str));\n\n if exist('OCTAVE_VERSION')\n fflush(stdout);\n end\n else\n [result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...\n source(thisPartId));\n result = base64encode(result);\n\n fprintf('\\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...\n homework_id(), thisPartId);\n saveAsFile = input('', 's');\n if (isempty(saveAsFile))\n saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);\n end\n\n fid = fopen(saveAsFile, 'w');\n if (fid)\n fwrite(fid, result);\n fclose(fid);\n fprintf('\\nSaved your solutions to %s.\\n\\n', saveAsFile);\n fprintf(['You can now submit your solutions through the web \\n' ...\n 'form in the programming exercises. Select the corresponding \\n' ...\n 'programming exercise to access the form.\\n']);\n\n else\n fprintf('Unable to save to %s\\n\\n', saveAsFile);\n fprintf(['You can create a submission file by saving the \\n' ...\n 'following text in a file: (press enter to continue)\\n\\n']);\n pause;\n fprintf(result);\n end\n end\n end\nend\n\n% ================== CONFIGURABLES FOR EACH HOMEWORK ==================\n\nfunction id = homework_id() \n id = '5';\nend\n\nfunction [partNames] = validParts()\n partNames = { 'Regularized Linear Regression Cost Function', ...\n 'Regularized Linear Regression Gradient', ...\n 'Learning Curve', ...\n 'Polynomial Feature Mapping' ...\n 'Validation Curve' ...\n };\nend\n\nfunction srcs = sources()\n % Separated by part\n srcs = { { 'linearRegCostFunction.m' }, ...\n { 'linearRegCostFunction.m' }, ...\n { 'learningCurve.m' }, ...\n { 'polyFeatures.m' }, ...\n { 'validationCurve.m' } };\nend\n\nfunction out = output(partId, auxstring)\n % Random Test Cases\n X = [ones(10,1) sin(1:1.5:15)' cos(1:1.5:15)'];\n y = sin(1:3:30)';\n Xval = [ones(10,1) sin(0:1.5:14)' cos(0:1.5:14)'];\n yval = sin(1:10)';\n if partId == 1\n [J] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5);\n out = sprintf('%0.5f ', J);\n elseif partId == 2\n [J, grad] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5);\n out = sprintf('%0.5f ', grad);\n elseif partId == 3\n [error_train, error_val] = ...\n learningCurve(X, y, Xval, yval, 1);\n out = sprintf('%0.5f ', [error_train(:); error_val(:)]);\n elseif partId == 4\n [X_poly] = polyFeatures(X(2,:)', 8);\n out = sprintf('%0.5f ', X_poly);\n elseif partId == 5\n [lambda_vec, error_train, error_val] = ...\n validationCurve(X, y, Xval, yval);\n out = sprintf('%0.5f ', ...\n [lambda_vec(:); error_train(:); error_val(:)]);\n end \nend\n\n% ====================== SERVER CONFIGURATION ===========================\n\n% ***************** REMOVE -staging WHEN YOU DEPLOY *********************\nfunction url = site_url()\n url = 'http://class.coursera.org/ml-008';\nend\n\nfunction url = challenge_url()\n url = [site_url() '/assignment/challenge'];\nend\n\nfunction url = submit_url()\n url = [site_url() '/assignment/submit'];\nend\n\n% ========================= CHALLENGE HELPERS =========================\n\nfunction src = source(partId)\n src = '';\n src_files = sources();\n if partId <= numel(src_files)\n flist = src_files{partId};\n for i = 1:numel(flist)\n fid = fopen(flist{i});\n if (fid == -1) \n error('Error opening %s (is it missing?)', flist{i});\n end\n line = fgets(fid);\n while ischar(line)\n src = [src line]; \n line = fgets(fid);\n end\n fclose(fid);\n src = [src '||||||||'];\n end\n end\nend\n\nfunction ret = isValidPartId(partId)\n partNames = validParts();\n ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);\nend\n\nfunction partId = promptPart()\n fprintf('== Select which part(s) to submit:\\n');\n partNames = validParts();\n srcFiles = sources();\n for i = 1:numel(partNames)\n fprintf('== %d) %s [', i, partNames{i});\n fprintf(' %s ', srcFiles{i}{:});\n fprintf(']\\n');\n end\n fprintf('== %d) All of the above \\n==\\nEnter your choice [1-%d]: ', ...\n numel(partNames) + 1, numel(partNames) + 1);\n selPart = input('', 's');\n partId = str2num(selPart);\n if ~isValidPartId(partId)\n partId = -1;\n end\nend\n\nfunction [email,ch,signature,auxstring] = getChallenge(email, part)\n str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});\n\n str = strtrim(str);\n r = struct;\n while(numel(str) > 0)\n [f, str] = strtok (str, '|');\n [v, str] = strtok (str, '|');\n r = setfield(r, f, v);\n end\n\n email = getfield(r, 'email_address');\n ch = getfield(r, 'challenge_key');\n signature = getfield(r, 'state');\n auxstring = getfield(r, 'challenge_aux_data');\nend\n\nfunction [result, str] = submitSolutionWeb(email, part, output, source)\n\n result = ['{\"assignment_part_sid\":\"' base64encode([homework_id() '-' num2str(part)], '') '\",' ...\n '\"email_address\":\"' base64encode(email, '') '\",' ...\n '\"submission\":\"' base64encode(output, '') '\",' ...\n '\"submission_aux\":\"' base64encode(source, '') '\"' ...\n '}'];\n str = 'Web-submission';\nend\n\nfunction [result, str] = submitSolution(email, ch_resp, part, output, ...\n source, signature)\n\n params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...\n 'email_address', email, ...\n 'submission', base64encode(output, ''), ...\n 'submission_aux', base64encode(source, ''), ...\n 'challenge_response', ch_resp, ...\n 'state', signature};\n\n str = urlread(submit_url(), 'post', params);\n\n % Parse str to read for success / failure\n result = 0;\n\nend\n\n% =========================== LOGIN HELPERS ===========================\n\nfunction [login password] = loginPrompt()\n % Prompt for password\n [login password] = basicPrompt();\n \n if isempty(login) || isempty(password)\n login = []; password = [];\n end\nend\n\n\nfunction [login password] = basicPrompt()\n login = input('Login (Email address): ', 's');\n password = input('Password: ', 's');\nend\n\nfunction [login password] = quickLogin(login,password)\n disp(['You are currently logged in as ' login '.']);\n cont_token = input('Is this you? (y/n - type n to reenter password)','s');\n if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')\n return;\n else\n [login password] = loginPrompt();\n end\nend\n\nfunction [str] = challengeResponse(email, passwd, challenge)\n str = sha1([challenge passwd]);\nend\n\n% =============================== SHA-1 ================================\n\nfunction hash = sha1(str)\n \n % Initialize variables\n h0 = uint32(1732584193);\n h1 = uint32(4023233417);\n h2 = uint32(2562383102);\n h3 = uint32(271733878);\n h4 = uint32(3285377520);\n \n % Convert to word array\n strlen = numel(str);\n\n % Break string into chars and append the bit 1 to the message\n mC = [double(str) 128];\n mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];\n \n numB = strlen * 8;\n if exist('idivide')\n numC = idivide(uint32(numB + 65), 512, 'ceil');\n else\n numC = ceil(double(numB + 65)/512);\n end\n numW = numC * 16;\n mW = zeros(numW, 1, 'uint32');\n \n idx = 1;\n for i = 1:4:strlen + 1\n mW(idx) = bitor(bitor(bitor( ...\n bitshift(uint32(mC(i)), 24), ...\n bitshift(uint32(mC(i+1)), 16)), ...\n bitshift(uint32(mC(i+2)), 8)), ...\n uint32(mC(i+3)));\n idx = idx + 1;\n end\n \n % Append length of message\n mW(numW - 1) = uint32(bitshift(uint64(numB), -32));\n mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));\n\n % Process the message in successive 512-bit chs\n for cId = 1 : double(numC)\n cSt = (cId - 1) * 16 + 1;\n cEnd = cId * 16;\n ch = mW(cSt : cEnd);\n \n % Extend the sixteen 32-bit words into eighty 32-bit words\n for j = 17 : 80\n ch(j) = ch(j - 3);\n ch(j) = bitxor(ch(j), ch(j - 8));\n ch(j) = bitxor(ch(j), ch(j - 14));\n ch(j) = bitxor(ch(j), ch(j - 16));\n ch(j) = bitrotate(ch(j), 1);\n end\n \n % Initialize hash value for this ch\n a = h0;\n b = h1;\n c = h2;\n d = h3;\n e = h4;\n \n % Main loop\n for i = 1 : 80\n if(i >= 1 && i <= 20)\n f = bitor(bitand(b, c), bitand(bitcmp(b), d));\n k = uint32(1518500249);\n elseif(i >= 21 && i <= 40)\n f = bitxor(bitxor(b, c), d);\n k = uint32(1859775393);\n elseif(i >= 41 && i <= 60)\n f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));\n k = uint32(2400959708);\n elseif(i >= 61 && i <= 80)\n f = bitxor(bitxor(b, c), d);\n k = uint32(3395469782);\n end\n \n t = bitrotate(a, 5);\n t = bitadd(t, f);\n t = bitadd(t, e);\n t = bitadd(t, k);\n t = bitadd(t, ch(i));\n e = d;\n d = c;\n c = bitrotate(b, 30);\n b = a;\n a = t;\n \n end\n h0 = bitadd(h0, a);\n h1 = bitadd(h1, b);\n h2 = bitadd(h2, c);\n h3 = bitadd(h3, d);\n h4 = bitadd(h4, e);\n\n end\n\n hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);\n \n hash = lower(hash);\n\nend\n\nfunction ret = bitadd(iA, iB)\n ret = double(iA) + double(iB);\n ret = bitset(ret, 33, 0);\n ret = uint32(ret);\nend\n\nfunction ret = bitrotate(iA, places)\n t = bitshift(iA, places - 32);\n ret = bitshift(iA, places);\n ret = bitor(ret, t);\nend\n\n% =========================== Base64 Encoder ============================\n% Thanks to Peter John Acklam\n%\n\nfunction y = base64encode(x, eol)\n%BASE64ENCODE Perform base64 encoding on a string.\n%\n% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending\n% sequence to use; it is optional and defaults to '\\n' (ASCII decimal 10).\n% The returned encoded string is broken into lines of no more than 76\n% characters each, and each line will end with EOL unless it is empty. Let\n% EOL be empty if you do not want the encoded string broken into lines.\n%\n% STR and EOL don't have to be strings (i.e., char arrays). The only\n% requirement is that they are vectors containing values in the range 0-255.\n%\n% This function may be used to encode strings into the Base64 encoding\n% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The\n% Base64 encoding is designed to represent arbitrary sequences of octets in a\n% form that need not be humanly readable. A 65-character subset\n% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per\n% printable character.\n%\n% Examples\n% --------\n%\n% If you want to encode a large file, you should encode it in chunks that are\n% a multiple of 57 bytes. This ensures that the base64 lines line up and\n% that you do not end up with padding in the middle. 57 bytes of data fills\n% one complete base64 line (76 == 57*4/3):\n%\n% If ifid and ofid are two file identifiers opened for reading and writing,\n% respectively, then you can base64 encode the data with\n%\n% while ~feof(ifid)\n% fwrite(ofid, base64encode(fread(ifid, 60*57)));\n% end\n%\n% or, if you have enough memory,\n%\n% fwrite(ofid, base64encode(fread(ifid)));\n%\n% See also BASE64DECODE.\n\n% Author: Peter John Acklam\n% Time-stamp: 2004-02-03 21:36:56 +0100\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n if isnumeric(x)\n x = num2str(x);\n end\n\n % make sure we have the EOL value\n if nargin < 2\n eol = sprintf('\\n');\n else\n if sum(size(eol) > 1) > 1\n error('EOL must be a vector.');\n end\n if any(eol(:) > 255)\n error('EOL can not contain values larger than 255.');\n end\n end\n\n if sum(size(x) > 1) > 1\n error('STR must be a vector.');\n end\n\n x = uint8(x);\n eol = uint8(eol);\n\n ndbytes = length(x); % number of decoded bytes\n nchunks = ceil(ndbytes / 3); % number of chunks/groups\n nebytes = 4 * nchunks; % number of encoded bytes\n\n % add padding if necessary, to make the length of x a multiple of 3\n if rem(ndbytes, 3)\n x(end+1 : 3*nchunks) = 0;\n end\n\n x = reshape(x, [3, nchunks]); % reshape the data\n y = repmat(uint8(0), 4, nchunks); % for the encoded data\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Split up every 3 bytes into 4 pieces\n %\n % aaaaaabb bbbbcccc ccdddddd\n %\n % to form\n %\n % 00aaaaaa 00bbbbbb 00cccccc 00dddddd\n %\n y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)\n\n y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)\n y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)\n\n y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)\n y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)\n\n y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Now perform the following mapping\n %\n % 0 - 25 -> A-Z\n % 26 - 51 -> a-z\n % 52 - 61 -> 0-9\n % 62 -> +\n % 63 -> /\n %\n % We could use a mapping vector like\n %\n % ['A':'Z', 'a':'z', '0':'9', '+/']\n %\n % but that would require an index vector of class double.\n %\n z = repmat(uint8(0), size(y));\n i = y <= 25; z(i) = 'A' + double(y(i));\n i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));\n i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));\n i = y == 62; z(i) = '+';\n i = y == 63; z(i) = '/';\n y = z;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Add padding if necessary.\n %\n npbytes = 3 * nchunks - ndbytes; % number of padding bytes\n if npbytes\n y(end-npbytes+1 : end) = '='; % '=' is used for padding\n end\n\n if isempty(eol)\n\n % reshape to a row vector\n y = reshape(y, [1, nebytes]);\n\n else\n\n nlines = ceil(nebytes / 76); % number of lines\n neolbytes = length(eol); % number of bytes in eol string\n\n % pad data so it becomes a multiple of 76 elements\n y = [y(:) ; zeros(76 * nlines - numel(y), 1)];\n y(nebytes + 1 : 76 * nlines) = 0;\n y = reshape(y, 76, nlines);\n\n % insert eol strings\n eol = eol(:);\n y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));\n\n % remove padding, but keep the last eol string\n m = nebytes + neolbytes * (nlines - 1);\n n = (76+neolbytes)*nlines - neolbytes;\n y(m+1 : n) = '';\n\n % extract and reshape to row vector\n y = reshape(y, 1, m+neolbytes);\n\n end\n\n % output is a character array\n y = char(y);\n\nend\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submitWeb.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex5-008/mlclass-ex5/submitWeb.m", "size": 807, "source_encoding": "utf_8", "md5": "a53188558a96eae6cd8b0e6cda4d478d", "text": "% submitWeb Creates files from your code and output for web submission.\n%\n% If the submit function does not work for you, use the web-submission mechanism.\n% Call this function to produce a file for the part you wish to submit. Then,\n% submit the file to the class servers using the \"Web Submission\" button on the \n% Programming Exercises page on the course website.\n%\n% You should call this function without arguments (submitWeb), to receive\n% an interactive prompt for submission; optionally you can call it with the partID\n% if you so wish. Make sure your working directory is set to the directory \n% containing the submitWeb.m file and your assignment files.\n\nfunction submitWeb(partId)\n if ~exist('partId', 'var') || isempty(partId)\n partId = [];\n end\n \n submit(partId, 1);\nend\n\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submit.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex4-008/mlclass-ex4/submit.m", "size": 17129, "source_encoding": "utf_8", "md5": "917c487f37cf14037c77e3c57ad78ce1", "text": "function submit(partId, webSubmit)\n%SUBMIT Submit your code and output to the ml-class servers\n% SUBMIT() will connect to the ml-class server and submit your solution\n\n fprintf('==\\n== [ml-class] Submitting Solutions | Programming Exercise %s\\n==\\n', ...\n homework_id());\n if ~exist('partId', 'var') || isempty(partId)\n partId = promptPart();\n end\n\n if ~exist('webSubmit', 'var') || isempty(webSubmit)\n webSubmit = 0; % submit directly by default \n end\n\n % Check valid partId\n partNames = validParts();\n if ~isValidPartId(partId)\n fprintf('!! Invalid homework part selected.\\n');\n fprintf('!! Expected an integer from 1 to %d.\\n', numel(partNames) + 1);\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n if ~exist('ml_login_data.mat','file')\n [login password] = loginPrompt();\n save('ml_login_data.mat','login','password');\n else \n load('ml_login_data.mat');\n [login password] = quickLogin(login, password);\n save('ml_login_data.mat','login','password');\n end\n\n if isempty(login)\n fprintf('!! Submission Cancelled\\n');\n return\n end\n\n fprintf('\\n== Connecting to ml-class ... '); \n if exist('OCTAVE_VERSION') \n fflush(stdout);\n end\n\n % Setup submit list\n if partId == numel(partNames) + 1\n submitParts = 1:numel(partNames);\n else\n submitParts = [partId];\n end\n\n for s = 1:numel(submitParts)\n thisPartId = submitParts(s);\n if (~webSubmit) % submit directly to server\n [login, ch, signature, auxstring] = getChallenge(login, thisPartId);\n if isempty(login) || isempty(ch) || isempty(signature)\n % Some error occured, error string in first return element.\n fprintf('\\n!! Error: %s\\n\\n', login);\n return\n end\n\n % Attempt Submission with Challenge\n ch_resp = challengeResponse(login, password, ch);\n\n [result, str] = submitSolution(login, ch_resp, thisPartId, ...\n output(thisPartId, auxstring), source(thisPartId), signature);\n\n partName = partNames{thisPartId};\n\n fprintf('\\n== [ml-class] Submitted Assignment %s - Part %d - %s\\n', ...\n homework_id(), thisPartId, partName);\n fprintf('== %s\\n', strtrim(str));\n\n if exist('OCTAVE_VERSION')\n fflush(stdout);\n end\n else\n [result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...\n source(thisPartId));\n result = base64encode(result);\n\n fprintf('\\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...\n homework_id(), thisPartId);\n saveAsFile = input('', 's');\n if (isempty(saveAsFile))\n saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);\n end\n\n fid = fopen(saveAsFile, 'w');\n if (fid)\n fwrite(fid, result);\n fclose(fid);\n fprintf('\\nSaved your solutions to %s.\\n\\n', saveAsFile);\n fprintf(['You can now submit your solutions through the web \\n' ...\n 'form in the programming exercises. Select the corresponding \\n' ...\n 'programming exercise to access the form.\\n']);\n\n else\n fprintf('Unable to save to %s\\n\\n', saveAsFile);\n fprintf(['You can create a submission file by saving the \\n' ...\n 'following text in a file: (press enter to continue)\\n\\n']);\n pause;\n fprintf(result);\n end\n end\n end\nend\n\n% ================== CONFIGURABLES FOR EACH HOMEWORK ==================\n\nfunction id = homework_id() \n id = '4';\nend\n\nfunction [partNames] = validParts()\n partNames = { 'Feedforward and Cost Function', ...\n 'Regularized Cost Function', ...\n 'Sigmoid Gradient', ...\n 'Neural Network Gradient (Backpropagation)' ...\n 'Regularized Gradient' ...\n };\nend\n\nfunction srcs = sources()\n % Separated by part\n srcs = { { 'nnCostFunction.m' }, ...\n { 'nnCostFunction.m' }, ...\n { 'sigmoidGradient.m' }, ...\n { 'nnCostFunction.m' }, ...\n { 'nnCostFunction.m' } };\nend\n\nfunction out = output(partId, auxstring)\n % Random Test Cases\n X = reshape(3 * sin(1:1:30), 3, 10);\n Xm = reshape(sin(1:32), 16, 2) / 5;\n ym = 1 + mod(1:16,4)';\n t1 = sin(reshape(1:2:24, 4, 3));\n t2 = cos(reshape(1:2:40, 4, 5));\n t = [t1(:) ; t2(:)];\n if partId == 1\n [J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0);\n out = sprintf('%0.5f ', J);\n elseif partId == 2\n [J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5);\n out = sprintf('%0.5f ', J);\n elseif partId == 3\n out = sprintf('%0.5f ', sigmoidGradient(X));\n elseif partId == 4\n [J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0);\n out = sprintf('%0.5f ', J);\n out = [out sprintf('%0.5f ', grad)];\n elseif partId == 5\n [J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5);\n out = sprintf('%0.5f ', J);\n out = [out sprintf('%0.5f ', grad)];\n end \nend\n\n\n% ====================== SERVER CONFIGURATION ===========================\n\n% ***************** REMOVE -staging WHEN YOU DEPLOY *********************\nfunction url = site_url()\n url = 'http://class.coursera.org/ml-008';\nend\n\nfunction url = challenge_url()\n url = [site_url() '/assignment/challenge'];\nend\n\nfunction url = submit_url()\n url = [site_url() '/assignment/submit'];\nend\n\n% ========================= CHALLENGE HELPERS =========================\n\nfunction src = source(partId)\n src = '';\n src_files = sources();\n if partId <= numel(src_files)\n flist = src_files{partId};\n for i = 1:numel(flist)\n fid = fopen(flist{i});\n if (fid == -1) \n error('Error opening %s (is it missing?)', flist{i});\n end\n line = fgets(fid);\n while ischar(line)\n src = [src line]; \n line = fgets(fid);\n end\n fclose(fid);\n src = [src '||||||||'];\n end\n end\nend\n\nfunction ret = isValidPartId(partId)\n partNames = validParts();\n ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);\nend\n\nfunction partId = promptPart()\n fprintf('== Select which part(s) to submit:\\n');\n partNames = validParts();\n srcFiles = sources();\n for i = 1:numel(partNames)\n fprintf('== %d) %s [', i, partNames{i});\n fprintf(' %s ', srcFiles{i}{:});\n fprintf(']\\n');\n end\n fprintf('== %d) All of the above \\n==\\nEnter your choice [1-%d]: ', ...\n numel(partNames) + 1, numel(partNames) + 1);\n selPart = input('', 's');\n partId = str2num(selPart);\n if ~isValidPartId(partId)\n partId = -1;\n end\nend\n\nfunction [email,ch,signature,auxstring] = getChallenge(email, part)\n str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});\n\n str = strtrim(str);\n r = struct;\n while(numel(str) > 0)\n [f, str] = strtok (str, '|');\n [v, str] = strtok (str, '|');\n r = setfield(r, f, v);\n end\n\n email = getfield(r, 'email_address');\n ch = getfield(r, 'challenge_key');\n signature = getfield(r, 'state');\n auxstring = getfield(r, 'challenge_aux_data');\nend\n\nfunction [result, str] = submitSolutionWeb(email, part, output, source)\n\n result = ['{\"assignment_part_sid\":\"' base64encode([homework_id() '-' num2str(part)], '') '\",' ...\n '\"email_address\":\"' base64encode(email, '') '\",' ...\n '\"submission\":\"' base64encode(output, '') '\",' ...\n '\"submission_aux\":\"' base64encode(source, '') '\"' ...\n '}'];\n str = 'Web-submission';\nend\n\nfunction [result, str] = submitSolution(email, ch_resp, part, output, ...\n source, signature)\n\n params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...\n 'email_address', email, ...\n 'submission', base64encode(output, ''), ...\n 'submission_aux', base64encode(source, ''), ...\n 'challenge_response', ch_resp, ...\n 'state', signature};\n\n str = urlread(submit_url(), 'post', params);\n\n % Parse str to read for success / failure\n result = 0;\n\nend\n\n% =========================== LOGIN HELPERS ===========================\n\nfunction [login password] = loginPrompt()\n % Prompt for password\n [login password] = basicPrompt();\n \n if isempty(login) || isempty(password)\n login = []; password = [];\n end\nend\n\n\nfunction [login password] = basicPrompt()\n login = input('Login (Email address): ', 's');\n password = input('Password: ', 's');\nend\n\nfunction [login password] = quickLogin(login,password)\n disp(['You are currently logged in as ' login '.']);\n cont_token = input('Is this you? (y/n - type n to reenter password)','s');\n if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')\n return;\n else\n [login password] = loginPrompt();\n end\nend\n\nfunction [str] = challengeResponse(email, passwd, challenge)\n str = sha1([challenge passwd]);\nend\n\n% =============================== SHA-1 ================================\n\nfunction hash = sha1(str)\n \n % Initialize variables\n h0 = uint32(1732584193);\n h1 = uint32(4023233417);\n h2 = uint32(2562383102);\n h3 = uint32(271733878);\n h4 = uint32(3285377520);\n \n % Convert to word array\n strlen = numel(str);\n\n % Break string into chars and append the bit 1 to the message\n mC = [double(str) 128];\n mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];\n \n numB = strlen * 8;\n if exist('idivide')\n numC = idivide(uint32(numB + 65), 512, 'ceil');\n else\n numC = ceil(double(numB + 65)/512);\n end\n numW = numC * 16;\n mW = zeros(numW, 1, 'uint32');\n \n idx = 1;\n for i = 1:4:strlen + 1\n mW(idx) = bitor(bitor(bitor( ...\n bitshift(uint32(mC(i)), 24), ...\n bitshift(uint32(mC(i+1)), 16)), ...\n bitshift(uint32(mC(i+2)), 8)), ...\n uint32(mC(i+3)));\n idx = idx + 1;\n end\n \n % Append length of message\n mW(numW - 1) = uint32(bitshift(uint64(numB), -32));\n mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));\n\n % Process the message in successive 512-bit chs\n for cId = 1 : double(numC)\n cSt = (cId - 1) * 16 + 1;\n cEnd = cId * 16;\n ch = mW(cSt : cEnd);\n \n % Extend the sixteen 32-bit words into eighty 32-bit words\n for j = 17 : 80\n ch(j) = ch(j - 3);\n ch(j) = bitxor(ch(j), ch(j - 8));\n ch(j) = bitxor(ch(j), ch(j - 14));\n ch(j) = bitxor(ch(j), ch(j - 16));\n ch(j) = bitrotate(ch(j), 1);\n end\n \n % Initialize hash value for this ch\n a = h0;\n b = h1;\n c = h2;\n d = h3;\n e = h4;\n \n % Main loop\n for i = 1 : 80\n if(i >= 1 && i <= 20)\n f = bitor(bitand(b, c), bitand(bitcmp(b), d));\n k = uint32(1518500249);\n elseif(i >= 21 && i <= 40)\n f = bitxor(bitxor(b, c), d);\n k = uint32(1859775393);\n elseif(i >= 41 && i <= 60)\n f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));\n k = uint32(2400959708);\n elseif(i >= 61 && i <= 80)\n f = bitxor(bitxor(b, c), d);\n k = uint32(3395469782);\n end\n \n t = bitrotate(a, 5);\n t = bitadd(t, f);\n t = bitadd(t, e);\n t = bitadd(t, k);\n t = bitadd(t, ch(i));\n e = d;\n d = c;\n c = bitrotate(b, 30);\n b = a;\n a = t;\n \n end\n h0 = bitadd(h0, a);\n h1 = bitadd(h1, b);\n h2 = bitadd(h2, c);\n h3 = bitadd(h3, d);\n h4 = bitadd(h4, e);\n\n end\n\n hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);\n \n hash = lower(hash);\n\nend\n\nfunction ret = bitadd(iA, iB)\n ret = double(iA) + double(iB);\n ret = bitset(ret, 33, 0);\n ret = uint32(ret);\nend\n\nfunction ret = bitrotate(iA, places)\n t = bitshift(iA, places - 32);\n ret = bitshift(iA, places);\n ret = bitor(ret, t);\nend\n\n% =========================== Base64 Encoder ============================\n% Thanks to Peter John Acklam\n%\n\nfunction y = base64encode(x, eol)\n%BASE64ENCODE Perform base64 encoding on a string.\n%\n% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending\n% sequence to use; it is optional and defaults to '\\n' (ASCII decimal 10).\n% The returned encoded string is broken into lines of no more than 76\n% characters each, and each line will end with EOL unless it is empty. Let\n% EOL be empty if you do not want the encoded string broken into lines.\n%\n% STR and EOL don't have to be strings (i.e., char arrays). The only\n% requirement is that they are vectors containing values in the range 0-255.\n%\n% This function may be used to encode strings into the Base64 encoding\n% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The\n% Base64 encoding is designed to represent arbitrary sequences of octets in a\n% form that need not be humanly readable. A 65-character subset\n% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per\n% printable character.\n%\n% Examples\n% --------\n%\n% If you want to encode a large file, you should encode it in chunks that are\n% a multiple of 57 bytes. This ensures that the base64 lines line up and\n% that you do not end up with padding in the middle. 57 bytes of data fills\n% one complete base64 line (76 == 57*4/3):\n%\n% If ifid and ofid are two file identifiers opened for reading and writing,\n% respectively, then you can base64 encode the data with\n%\n% while ~feof(ifid)\n% fwrite(ofid, base64encode(fread(ifid, 60*57)));\n% end\n%\n% or, if you have enough memory,\n%\n% fwrite(ofid, base64encode(fread(ifid)));\n%\n% See also BASE64DECODE.\n\n% Author: Peter John Acklam\n% Time-stamp: 2004-02-03 21:36:56 +0100\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n if isnumeric(x)\n x = num2str(x);\n end\n\n % make sure we have the EOL value\n if nargin < 2\n eol = sprintf('\\n');\n else\n if sum(size(eol) > 1) > 1\n error('EOL must be a vector.');\n end\n if any(eol(:) > 255)\n error('EOL can not contain values larger than 255.');\n end\n end\n\n if sum(size(x) > 1) > 1\n error('STR must be a vector.');\n end\n\n x = uint8(x);\n eol = uint8(eol);\n\n ndbytes = length(x); % number of decoded bytes\n nchunks = ceil(ndbytes / 3); % number of chunks/groups\n nebytes = 4 * nchunks; % number of encoded bytes\n\n % add padding if necessary, to make the length of x a multiple of 3\n if rem(ndbytes, 3)\n x(end+1 : 3*nchunks) = 0;\n end\n\n x = reshape(x, [3, nchunks]); % reshape the data\n y = repmat(uint8(0), 4, nchunks); % for the encoded data\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Split up every 3 bytes into 4 pieces\n %\n % aaaaaabb bbbbcccc ccdddddd\n %\n % to form\n %\n % 00aaaaaa 00bbbbbb 00cccccc 00dddddd\n %\n y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)\n\n y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)\n y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)\n\n y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)\n y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)\n\n y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Now perform the following mapping\n %\n % 0 - 25 -> A-Z\n % 26 - 51 -> a-z\n % 52 - 61 -> 0-9\n % 62 -> +\n % 63 -> /\n %\n % We could use a mapping vector like\n %\n % ['A':'Z', 'a':'z', '0':'9', '+/']\n %\n % but that would require an index vector of class double.\n %\n z = repmat(uint8(0), size(y));\n i = y <= 25; z(i) = 'A' + double(y(i));\n i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));\n i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));\n i = y == 62; z(i) = '+';\n i = y == 63; z(i) = '/';\n y = z;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Add padding if necessary.\n %\n npbytes = 3 * nchunks - ndbytes; % number of padding bytes\n if npbytes\n y(end-npbytes+1 : end) = '='; % '=' is used for padding\n end\n\n if isempty(eol)\n\n % reshape to a row vector\n y = reshape(y, [1, nebytes]);\n\n else\n\n nlines = ceil(nebytes / 76); % number of lines\n neolbytes = length(eol); % number of bytes in eol string\n\n % pad data so it becomes a multiple of 76 elements\n y = [y(:) ; zeros(76 * nlines - numel(y), 1)];\n y(nebytes + 1 : 76 * nlines) = 0;\n y = reshape(y, 76, nlines);\n\n % insert eol strings\n eol = eol(:);\n y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));\n\n % remove padding, but keep the last eol string\n m = nebytes + neolbytes * (nlines - 1);\n n = (76+neolbytes)*nlines - neolbytes;\n y(m+1 : n) = '';\n\n % extract and reshape to row vector\n y = reshape(y, 1, m+neolbytes);\n\n end\n\n % output is a character array\n y = char(y);\n\nend\n"} +{"plateform": "github", "repo_name": "CourseAce/Stanford-MachineLearning-master", "name": "submitWeb.m", "ext": ".m", "path": "Stanford-MachineLearning-master/mlclass-ex4-008/mlclass-ex4/submitWeb.m", "size": 807, "source_encoding": "utf_8", "md5": "a53188558a96eae6cd8b0e6cda4d478d", "text": "% submitWeb Creates files from your code and output for web submission.\n%\n% If the submit function does not work for you, use the web-submission mechanism.\n% Call this function to produce a file for the part you wish to submit. Then,\n% submit the file to the class servers using the \"Web Submission\" button on the \n% Programming Exercises page on the course website.\n%\n% You should call this function without arguments (submitWeb), to receive\n% an interactive prompt for submission; optionally you can call it with the partID\n% if you so wish. Make sure your working directory is set to the directory \n% containing the submitWeb.m file and your assignment files.\n\nfunction submitWeb(partId)\n if ~exist('partId', 'var') || isempty(partId)\n partId = [];\n end\n \n submit(partId, 1);\nend\n\n"} +{"plateform": "github", "repo_name": "shenjianbing/Accurate-normal-and-reflectance-recovery-using-energy-optimization-master", "name": "calibrated_photometric_stereo.m", "ext": ".m", "path": "Accurate-normal-and-reflectance-recovery-using-energy-optimization-master/calibrated_photometric_stereo.m", "size": 1486, "source_encoding": "utf_8", "md5": "bcf4095cd0ff945b798f2c857cd61627", "text": "% Computes the facet vector (surface normal times albedo) at each pixel given a set of images\n% illuminated by a varying point light source and the light source directions / intensities.\n%\n% function [B,S] = calibrated_photometric_stereo(I,S,mask)\n%\n% I : NxM Image data; N is the number of pixels per image, M is the number of images.\n% S : 3xM Light source directions/intensities. The ith column corresponds to the light source\n% for the ith image. The direction of the vector specifies the light source direction and\n% the magnitude represents the light source intensity.\n% mask : Nx1 Mask image, specifying which pixels to operate on - for points not\n% in the mask, behavior is undefined\n% B : Nx3 Facet matrix (N=W*H). Each row corresponds to the surface normal times the albedo of the ith pixel.\n%\n% OR\n%\n% function [B,S] = calibrated_photometric_stereo(ims,S,mask)\n%\n% where ims is a cell array of grayscale images and output B is a Nx3 matrix with N=H*W\n%\n% ============\n% Neil Alldrin\n%\nfunction [B,S] = calibrated_photometric_stereo(I,S,mask)\n\n% Note: mask isn't used for this version of PS, since the solution is purely\n% local and very little overhead is incurred by computing a solution at\n% every pixel.\n\nif iscell(I)\n\tIvec = cell2mat(cellfun(@(x)(x(:)),I(:)','UniformOutput',false));\n\t[B,S] = calibrated_photometric_stereo(Ivec, S);\n\t%B = reshape(B,[size(I{1}),3]);\nelse\n\t% I = B*S ==> B = I*pinv(S)\n\tB = I*pinv(S);\nend\n"} +{"plateform": "github", "repo_name": "shenjianbing/Accurate-normal-and-reflectance-recovery-using-energy-optimization-master", "name": "uncalibrated_photometric_stereo.m", "ext": ".m", "path": "Accurate-normal-and-reflectance-recovery-using-energy-optimization-master/uncalibrated_photometric_stereo.m", "size": 4850, "source_encoding": "utf_8", "md5": "b6f9ffe4ccc0b886abf879ca1f8bacf5", "text": "% function [B,S] = uncalibrated_photometric_stereo(Icell,mask,gbrinit)\n%\n% An implementation of the uncalibrated photometric stereo technique described in \n% \"Shape and Albedo from Multple Images using Integrability\" by Yuille and Snow.\n%\n% I : NxM Image data; N is the number of pixels per image, M is the number of images.\n% OR\n% Mx1 Cell array of HxW grayscale images\n% Isize : 1x2 Size of a single image.\n% Imask : WxH Mask image to exclude pixels from being considered.\n% B : Nx3 Facet matrix (N=W*H). Each row corresponds to the surface normal times the albedo of the ith pixel.\n% S : 3xM Light source directions/intensities. The ith column corresponds to the light source\n% for the ith image. The direction of the vector specifies the light source direction and\n% the magnitude represents the light source intensity.\n%\n% ============\n% Neil Alldrin\n%\nfunction [B,S] = uncalibrated_photometric_stereo(I,mask,gbrinit)\n\nIsize = size(mask);\nif ~exist('gbrinit','var') gbrinit = [1 1 1]; end;\n\nif iscell(I)\n\tI = cell2mat(cellfun(@(x)(x(:)),I(:)','UniformOutput',false)); % NxM\nend\n\nI = im2double(I); % I is required to be of type double for later operations to work\n\nIinds = find(mask(:)>0); % indices of non-masked pixels\nM = size(I,2); % # of images / illuminations\nN = size(I,1); % # of non-masked pixels\n\n% Transpose I so that it's consistent with the yuille and snow paper\nI_ = I'; % non-masked\nI = I_(:,Iinds); % masked\n\n% We should have the following relation at the end\n% I_' = B*S;\n\n% get the 4 most significant singular values\n% note: we are using the notation in the paper\n% note 2: need 4 singular values b/c of ambient term\n[f D e] = svds(I,4);\ne_ = I_' * pinv(D*f');\n\n% f : Mx4\n% e : Nx4\n% D : 4x4 diagonal matrix\n\n% We now need to restrict f and e by enforcing integrability\n\n% compute de/dx and de/dy\nsmooth_kernel = fspecial('gaussian',[25 25],2.5);\n%smooth_kernel = fspecial('disk',3.0);\n%smooth_kernel = 1;\nfor i = 1:4\n e_smooth = imfilter(reshape(e_(:,i).*mask(:),Isize),smooth_kernel,'same');\n [dedx_ dedy_] = gradient(e_smooth);\n dedy_ = -dedy_;\n dedx(:,i) = dedx_(Iinds);\n dedy(:,i) = dedy_(Iinds);\nend\n\n% solve the following system of equations for x_ij and y_ij\n% sum_{j=2:4} sum_{i=1:j-1} ( a_ij*x_ij - b_ij*y_ij) = 0\n% where,\n% a_ij = e(i)*dedx(j)-e(j)*dedx(i)\n% c_ij = P_3i*P_2j - P_2i*P_3j\n% b_ij = e(i)*dedy(j)-e(j)*dedy(i)\n% d_ij = P_3i*P_1j - P_1i*P_3j\n\na12 = e(:,1).*dedx(:,2) - e(:,2).*dedx(:,1);\na13 = e(:,1).*dedx(:,3) - e(:,3).*dedx(:,1);\na23 = e(:,2).*dedx(:,3) - e(:,3).*dedx(:,2);\na14 = e(:,1).*dedx(:,4) - e(:,4).*dedx(:,1);\na24 = e(:,2).*dedx(:,4) - e(:,4).*dedx(:,2);\na34 = e(:,3).*dedx(:,4) - e(:,4).*dedx(:,3);\n\nb12 = e(:,1).*dedy(:,2) - e(:,2).*dedy(:,1);\nb13 = e(:,1).*dedy(:,3) - e(:,3).*dedy(:,1);\nb23 = e(:,2).*dedy(:,3) - e(:,3).*dedy(:,2);\nb14 = e(:,1).*dedy(:,4) - e(:,4).*dedy(:,1);\nb24 = e(:,2).*dedy(:,4) - e(:,4).*dedy(:,2);\nb34 = e(:,3).*dedy(:,4) - e(:,4).*dedy(:,3);\n\n% Solve the system A*x = 0 (terms with index of 4 correspond to ambient term)\n% A = [a12 a13 a23 -b12 -b13 -b23 a14 a24 a34 -b14 -b24 -b34]\n% x = [c12 c13 c23 d12 d13 d23 c14 c24 c34 d14 d24 d34];\nA = [a12 a13 a23 -b12 -b13 -b23 a14 a24 a34 -b14 -b24 -b34];\n%[AU AS AV] = svds(A,12);\n%x = AV(:,12);\n[AU,AS,AV] = svd(A(:,1:6),0);\nx = AV(:,size(AV,2));\n\n% construct the \"co-factor matrix\" (eqn 12) from the paper\n% P3inv = [-c23 d23 ???;\n% c13 -d13 ???;\n% -c12 d12 ???];\nP3inv = [-x(3) x(6) gbrinit(1); ...\n\t x(2) -x(5) gbrinit(2); ...\n\t -x(1) x(4) gbrinit(3)];\n\n% invert P3inv to get P3 (up to GBR)\nP3 = inv(P3inv);\n\n% solve for Q3 using the relation P3'*Q3 = D3\n%Q3 = (inv(P3')*D(1:3,1:3));\nQ3 = (P3') \\ D(1:3,1:3);\n\n% % compute the remaining portions of P4 / Q4\n% w = sum(f,1)';\n% % set up linear system to solve p4 using the remaining cross-product terms\n% % A*p4 = b\n% % p4 = [P14 P24 P34]'\n% % b = [c14 c24 c34 d14 d24 d34]'\n% A = [ 0 P3(3,1) -P3(2,1);\n% 0 P3(3,2) -P3(2,2);\n% 0 P3(3,3) -P3(2,3);\n% P3(3,1) 0 -P3(1,1);\n% P3(3,2) 0 -P3(1,2);\n% P3(3,3) 0 -P3(1,3)];\n% b = x(7:12);\n% p4 = pinv(A)*b;\n\n% Compute the B and S matrices from P3 and Q3\nB = e_(:,1:3)*P3';\nS = Q3*f(:,1:3)';\n\n% Adjust the sign so that nz is positive\nif mean(B(mask(:),3))<0\n B = B*[1 0 0; 0 1 0; 0 0 -1];\n S = [1 0 0; 0 1 0; 0 0 -1]*S;\nend\n\n% Remove pixels in shadow / highlight by estimating a visibility matrix V\n\n% I = B*S; [Nx4] = [Nx3]*[3x4]\n\n% [I1; I2; I3; I4] = [B*S1; B*S2; B*S3; B*S4]\n% [I1; I2; I3; I4] = [(V1.*B)*S1; (V2.*B)*S2; (V3.*B)*S3; (V4.*B)*S4]\n% [I1; I2; I3; I4] = [(V1.*B); (V2.*B); (V3.*B); (V4.*B)] * S_\n% [4*Nx1] = [4*Nx3]*[]\n\n% What constitutes an outlier???\n% [1x1] = [1x3]*[3x1]; A single surface point with one light source\n"} +{"plateform": "github", "repo_name": "shenjianbing/Accurate-normal-and-reflectance-recovery-using-energy-optimization-master", "name": "B2normals.m", "ext": ".m", "path": "Accurate-normal-and-reflectance-recovery-using-energy-optimization-master/B2normals.m", "size": 391, "source_encoding": "utf_8", "md5": "820d73ac4c83dfe48122f6e6715d2ef4", "text": "% Converts an Nx3 facet matrix into unit normal and albedo images\n% \n% function [nx,ny,nz,a] = B2normals(B,sizeI)\n%\n% ============\n% Neil Alldrin\n%\nfunction [nx,ny,nz,a] = B2normals(B,sizeI)\n\ndim=size(B,1);\n\n\nB = reshape(B,dim,3);\n\na = reshape(sqrt(sum(B.^2,2)),sizeI);\nnx = reshape(B(:,1),sizeI)./(a+(a==0));\nny = reshape(B(:,2),sizeI)./(a+(a==0));\nnz = reshape(B(:,3),sizeI)./(a+(a==0));\n"} +{"plateform": "github", "repo_name": "shenjianbing/Accurate-normal-and-reflectance-recovery-using-energy-optimization-master", "name": "Poisson.m", "ext": ".m", "path": "Accurate-normal-and-reflectance-recovery-using-energy-optimization-master/Poisson.m", "size": 8235, "source_encoding": "utf_8", "md5": "27f5aedcd5010abdb7248c26018e8169", "text": "classdef Poisson < handle\n \n methods(Static)\n function [I_y I_x] = get_gradients(I)\n % Get the vertical (derivative-row) and horizontal (derivative-column) gradients\n % of an image. (or multiple images)\n \n I_y = diff(I,1,1);\n I_y = padarray(I_y, [1 0], 0, 'pre');\n I_x = diff(I,1,2);\n I_x = padarray(I_x, [0 1], 0, 'pre');\n end\n \n function [I] = solve(t_y, t_x, mask, t_y_weights, t_x_weights)\n % Solve for the image which best matches the target vertical gradients\n % t_y and horizontal gradients t_x, e.g. the one which minimizes sum of squares\n % of the residual\n % \n % sum of (I[i,j] - I[i-1,j] - t_y[i,j])^2 + (I[i,j] - I[i,j-1] - t_x[i,j])^2\n % \n % Only considers the target gradients lying entirely within the mask.\n % The first row of t_y and the first column of t_x are ignored. \n % Optionally, you may pass in an array with the weights corresponding to each target\n % gradient. The solution is unique up to a constant added to each of the pixels.\n \n if nargin < 5\n t_x_weights = [];\n end\n if nargin < 4\n t_y_weights = [];\n end\n \n if isempty(t_y_weights)\n t_y_weights = ones(size(t_y));\n end\n if isempty(t_x_weights)\n t_x_weights = ones(size(t_x));\n end\n [M, N] = size(mask);\n numbers = get_numbers(mask);\n A = get_A(mask, t_y_weights, t_x_weights);\n b = get_b(t_y, t_x, mask, t_y_weights, t_x_weights);\n \n % The solution is unique up to a constant added to each of the pixels.\n % We can reset the range of x to start from 0.\n warning off;\n x = A\\b;\n x = x - min(x);\n warning on;\n \n % test x within a precision\n if max(abs(A*x-b)) > 1e-10\n fprintf('x = A\\\\b is not accurate.\\n');\n end\n \n I = zeros(size(mask));\n for i = 1:M\n for j = 1:N\n if mask(i,j)\n I(i,j) = x(numbers(i,j));\n end\n end\n end\n end\n \n function [I] = solve_L1(t_y, t_x, mask)\n % Same as solve(), except using an L1 penalty rather than least squares.\n \n EPSILON = 0.0001;\n \n % We minimize the L1-norm of the residual\n %\n % sum of |r_i|\n % r = Ax - b\n %\n % by alternately minimizing the variational upper bound\n %\n % |r_i| <= a_i * r_i^2 + 1 / (4 * a_i)\n %\n % with respect to x and a. When r is fixed, this bound is tight for a = 1 / (2 * r).\n % When a is fixed, we optimize for x by solving a weighted\n % least-squares problem.\n \n I = Poisson.solve(t_y, t_x, mask);\n for i = 1:20\n [I_y I_x] = Poisson.get_gradients(I);\n t_y_err = mask .* abs(I_y - t_y);\n t_x_err = mask .* abs(I_x - t_x);\n \n t_y_weights = 1. ./ (2. * max(t_y_err, EPSILON));\n t_x_weights = 1. ./ (2. * max(t_x_err, EPSILON));\n \n try\n I = Poisson.solve(t_y, t_x, mask, t_y_weights, t_x_weights);\n catch ME\n % Occasionally the solver fails when the weights get very large\n % or small. In that case, we just return the previous iteration's\n % estimate, which is hopefully close enough.\n return;\n end\n end\n end\n \n end % method(Static)\n \nend\n\nfunction [numbers] = get_numbers(mask)\n [M N] = size(mask);\n numbers = zeros(size(mask));\n count = 0;\n for i = 1:M\n for j = 1:N\n if mask(i,j)\n count = count + 1;\n numbers(i,j) = count;\n end\n end\n end\nend\n\nfunction [b] = get_b(t_y, t_x, mask, t_y_weights, t_x_weights)\n [M N] = size(mask);\n t_y = t_y(2:end,:);\n t_y_weights = t_y_weights(2:end,:);\n t_x = t_x(:,2:end);\n t_x_weights = t_x_weights(:,2:end);\n numbers = get_numbers(mask);\n K = max(numbers(:));\n b = zeros(K,1);\n\n % horizontal derivatives\n for i = 1:M\n for j = 1:N-1\n if mask(i,j) && mask(i,j+1)\n n1 = numbers(i,j);\n n2 = numbers(i,j+1);\n\n % row (i,j): -x_{i,j+1} + x_{i,j} + t\n b(n1) = b(n1) - t_x(i,j) * t_x_weights(i,j);\n\n % row (i,j+1): x_{i,j+1} - x_{i,j} - t\n b(n2) = b(n2) + t_x(i,j) * t_x_weights(i,j);\n end\n end\n end\n\n % vertical derivatives\n for i = 1:M-1\n for j = 1:N\n if mask(i,j) && mask(i+1,j)\n n1 = numbers(i,j);\n n2 = numbers(i+1,j);\n\n % row (i,j): -x_{i+1,j} + x_{i,j} + t\n b(n1) = b(n1) - t_y(i,j) * t_y_weights(i,j);\n\n % row (i,j+1): x_{i+1,j} - x_{i,j} - t\n b(n2) = b(n2) + t_y(i,j) * t_y_weights(i,j);\n end\n end\n end\nend\n \nfunction [A] = get_A(mask, t_y_weights, t_x_weights)\n [M N] = size(mask);\n numbers = get_numbers(mask);\n K = max(numbers(:));\n\n t_y_weights = t_y_weights(2:end,:);\n t_x_weights = t_x_weights(:,2:end);\n\n % herizontal derivatives\n count = 0;\n for i = 1:M\n for j = 1:N-1\n if mask(i,j) && mask(i,j+1)\n count = count + 1;\n end\n end\n end\n data = zeros(4*count,1);\n row = zeros(4*count,1);\n col = zeros(4*count,1);\n count = 0;\n for i = 1:M\n for j = 1:N-1\n if mask(i,j) && mask(i,j+1)\n n1 = numbers(i,j);\n n2 = numbers(i,j+1);\n\n % row (i,j): -x_{i,j+1} + x_{i,j} + t\n row(4*count+1) = n1;\n col(4*count+1) = n2;\n data(4*count+1) = -t_x_weights(i,j);\n\n row(4*count+2) = n1;\n col(4*count+2) = n1;\n data(4*count+2) = t_x_weights(i,j);\n\n % row (i, j+1): x_{i,j+1} - x_{i,j} - t\n row(4*count+3) = n2;\n col(4*count+3) = n2;\n data(4*count+3) = t_x_weights(i,j);\n\n row(4*count+4) = n2;\n col(4*count+4) = n1;\n data(4*count+4) = -t_x_weights(i,j);\n \n count = count + 1;\n end\n end\n end\n\n data1 = data;\n row1 = row;\n col1 = col;\n\n % vertical derivatives\n count = 0;\n for i = 1:M-1\n for j = 1:N\n if mask(i,j) && mask(i+1,j)\n count = count + 1;\n end\n end\n end\n data = zeros(4*count,1);\n row = zeros(4*count,1);\n col = zeros(4*count,1);\n count = 0;\n for i = 1:M-1\n for j = 1:N\n if mask(i,j) && mask(i+1,j)\n n1 = numbers(i,j);\n n2 = numbers(i+1,j);\n\n % row (i,j): -x_{i+1,j} + x_{i,j} + t\n row(4*count+1) = n1;\n col(4*count+1) = n2;\n data(4*count+1) = -t_y_weights(i,j);\n\n row(4*count+2) = n1;\n col(4*count+2) = n1;\n data(4*count+2) = t_y_weights(i,j);\n\n % row (i, j+1): x_{i+1,j} - x_{i,j} - t\n row(4*count+3) = n2;\n col(4*count+3) = n2;\n data(4*count+3) = t_y_weights(i,j);\n\n row(4*count+4) = n2;\n col(4*count+4) = n1;\n data(4*count+4) = -t_y_weights(i,j);\n \n count = count + 1;\n end\n end\n end\n\n data2 = data;\n row2 = row;\n col2 = col;\n\n data = [data1; data2];\n row = [row1; row2];\n col = [col1; col2];\n\n A = sparse(row, col, data, K, K);\nend\n"} +{"plateform": "github", "repo_name": "shenjianbing/Accurate-normal-and-reflectance-recovery-using-energy-optimization-master", "name": "Auxiliary.m", "ext": ".m", "path": "Accurate-normal-and-reflectance-recovery-using-energy-optimization-master/Auxiliary.m", "size": 3562, "source_encoding": "utf_8", "md5": "1f65382aece9af0e1ade52c913060d68", "text": "classdef Auxiliary < handle\n \n methods(Static)\n function showR(r, mask, ims, ti, padding)\n if nargin < 4\n ti = 'reflectance';\n end\n if nargin < 5\n padding = 0;\n end\n \n show(rMap(r, mask, ims, padding), ti);\n end\n \n function showN(n, mask, ti, padding)\n if nargin < 3\n ti = 'normal';\n end\n if nargin < 4\n padding = 0;\n end\n \n show(nMap(n, mask, padding), ti);\n end\n \n function saveR(r, mask, ims, fname, padding, margin)\n if nargin < 5\n padding = 0;\n margin = 0;\n end\n \n refl = rMap(r, mask, ims, padding);\n if margin > 0\n refl = Auxiliary.clip(refl, mask, margin);\n end\n imwrite(refl, fname);\n end\n \n function saveN(n, mask, fname, padding, margin)\n if nargin < 4\n padding = 0;\n margin = 0;\n end\n \n normal = nMap(n, mask, padding);\n if margin > 0\n normal = Auxiliary.clip(normal, mask, margin);\n end\n imwrite(normal, fname);\n end\n \n function [clipped] = clip(im, mask, margin)\n if nargin < 3\n margin = 3;\n end\n [row, col] = ind2sub(size(mask), find(mask));\n [h, w] = size(mask);\n \n row_start = max(1, min(row)-margin);\n row_end = min(h, max(row)+margin);\n col_start = max(1, min(col)-margin);\n col_end = min(w, max(col)+margin);\n clipped = im(row_start:row_end, col_start:col_end, :);\n end\n \n function saveSR(est_s, est_r, tag, prefix, estimatorName)\n if ~exist(prefix, 'dir')\n mkdir(prefix);\n end\n mask = load_object(tag, 'mask'); \n [ims] = load_multiple(tag, mask);\n \n est_s(mask) = mat2gray(est_s(mask));\n est_s(~mask) = 1;\n shad = Auxiliary.clip(est_s, mask);\n s_name = [prefix tag '_' estimatorName 's.png'];\n imwrite(shad, s_name);\n \n est_r(mask) = mat2gray(est_r(mask));\n img_chroma = sum(ims, 4);\n img_chroma = img_chroma ./ repmat(max(eps,mean(img_chroma,3)),[1,1,size(img_chroma,3)]);\n albedo = repmat(est_r,[1 1 3]).*img_chroma;\n albedo( repmat(~mask,[1 1 3]) ) = 1;\n \n refl = Auxiliary.clip(albedo, mask);\n r_name = [prefix tag '_' estimatorName 'r.png'];\n imwrite(refl, r_name);\n end\n \n function [score] = score_image(gt_s, gt_r, est_s, est_r, mask)\n ncorr = Metric.ncorr(gt_s, gt_r, est_s, est_r, mask);\n score = 0.5*(ncorr(1)+ncorr(2));\n end\n \n end\nend\n\nfunction show(im, ti)\n figure, imshow(im), title(ti);\nend\n\nfunction [n_map] = nMap(n, mask, padding)\n [h w] = size(mask);\n n = normr( reshape(n, [h*w 3]) );\n n_map = uint8((n+1)*128);\n n_map(~mask,:) = 255*padding;\n n_map = reshape(n_map, [h w 3]);\nend\n\nfunction [r_map] = rMap(r, mask, ims, padding)\n chroma = sum(ims,4);\n chroma = chroma ./ repmat(max(eps, mean(chroma,3)), [1 1 size(chroma,3)]);\n r_map = repmat(r, [1 1 3]) .* chroma;\n r_map( repmat(~mask,[1 1 3]) ) = padding;\nend\n\n\n"} +{"plateform": "github", "repo_name": "shenjianbing/Accurate-normal-and-reflectance-recovery-using-energy-optimization-master", "name": "Metric.m", "ext": ".m", "path": "Accurate-normal-and-reflectance-recovery-using-energy-optimization-master/Metric.m", "size": 6437, "source_encoding": "utf_8", "md5": "8e384e3f3ea49bb6b0fa9b2969d54295", "text": "classdef Metric < handle\n methods(Static)\n function [mean_angle, angle] = angularN(gt_n, est_n, mask)\n est_n = normr(est_n(mask,:));\n gt_n = normr(gt_n(mask,:));\n \n inner = abs(sum(est_n.*gt_n,2));\n inner(inner > 1) = 1;\n angle = acosd(inner);\n angle(isnan(angle)) = 0;\n mean_angle = mean(angle);\n \n tmp = zeros(size(mask));\n tmp(mask) = angle;\n angle = tmp;\n end\n \n function [mean_angle, angle] = angularL(gt_l, est_l)\n gt_l = normc(gt_l);\n est_l = normc(est_l);\n inner = abs(sum(gt_l.*est_l, 1));\n inner(inner > 1) = 1;\n angle = acosd(inner);\n mean_angle = mean(angle);\n end\n \n function err = mse(gt, est, mask)\n ssq = ssq_error(gt, est, mask);\n total = sum(mask(:) .* gt(:) .^ 2);\n assert(total > eps);\n err = ssq / total;\n end\n \n function [err] = lmse(gt_s, gt_r, est_s, est_r, mask)\n window_size = 20;\n s_err = local_error(gt_s, est_s, mask, window_size, floor(window_size/2));\n r_err = local_error(gt_r, est_r, mask, window_size, floor(window_size/2));\n err = [s_err r_err];\n end\n \n function [err] = almse(gt_s, gt_r, est_s, est_r, mask)\n window_size = 20;\n s_err = alocal_error(gt_s, est_s, mask, window_size, floor(window_size/2));\n r_err = alocal_error(gt_r, est_r, mask, window_size, floor(window_size/2));\n err = [s_err r_err];\n end\n \n function [err] = bothmse(gt_s, gt_r, est_s, est_r, mask)\n ssq_s = ssq_error(gt_s, est_s, mask);\n total_s = sum(mask(:) .* gt_s(:) .^ 2);\n ssq_r = ssq_error(gt_r, est_r, mask);\n total_r = sum(mask(:) .* gt_r(:) .^ 2);\n \n assert(total_s > eps && total_r > eps);\n % err = 0.5*ssq_s/total_s + 0.5*ssq_r/total_r;\n s_err = ssq_s/total_s;\n r_err = ssq_r/total_r;\n err = [s_err r_err];\n end\n \n function [err] = ncorr(gt_s, gt_r, est_s, est_r, mask)\n s_err = 1 - corr2(gt_s(mask), est_s(mask));\n r_err = 1 - corr2(gt_r(mask), est_r(mask));\n err = [s_err r_err];\n % cor = 0.5*corr2(gt_s(mask), est_s(mask)) + 0.5*corr2(gt_r(mask), est_r(mask));\n end\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% the following functions are error metrics defined in:\n%\n% Ground truth dataset and baseline evaluations for intrinsic image algorithms.\n% Roger Grosse et. al. iccv 2009 \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [score] = score_image(true_shading, true_refl, estimate_shading, estimate_refl, mask, window_size)\n if nargin < 6\n window_size = 20;\n end\n score = 0.5 * local_error(true_shading, estimate_shading, mask, window_size, floor(window_size/2)) + ...\n 0.5 * local_error(true_refl, estimate_refl, mask, window_size, floor(window_size/2));\nend\n\nfunction [error_val] = local_error(correct, estimate, mask, window_size, window_shift)\n% Returns the sum of the local sum-squared-errors, where the estimate may\n% be rescaled within each local region to minimize the error. The windows are\n% window_size x window_size, and they are spaced by window_shift.\n M = size(correct,1);\n N = size(correct,2);\n\n ssq = 0;\n total = 0;\n for i = 1:window_shift:(M - window_size + 1)\n for j = 1:window_shift:(N - window_size + 1)\n correct_curr = correct(i:i+window_size-1, j:j+window_size-1);\n estimate_curr = estimate(i:i+window_size-1, j:j+window_size-1);\n mask_curr = mask(i:i+window_size-1, j:j+window_size-1);\n ssq = ssq + ssq_error(correct_curr, estimate_curr, mask_curr);\n total = total + sum(mask_curr(:) .* correct_curr(:) .^ 2);\n end\n end\n\n assert(~isnan(ssq/total));\n error_val = ssq / total;\nend\n\nfunction [error_val] = ssq_error(correct, estimate, mask)\n% Compute the sum-squared-error for an image, where the estimate is\n% multiplied by a scalar which minimizes the error. Sums over all pixels\n% where mask is True. If the inputs are color, each color channel can be\n% rescaled independently.\n assert(ndims(correct) == 2);\n correct = correct(:); estimate = estimate(:); mask = mask(:);\n\n if sum(estimate.^2 .* mask) > 1e-5\n alpha = sum(correct .* estimate .* mask) / sum(estimate.^2 .* mask);\n else\n alpha = 0.;\n end\n error_val = sum(mask .* (correct - alpha*estimate).^2);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% the following functions are error metrics defined in:\n%\n% Correlation-based Intrinsic Image Extraction from a Single Image.\n% Xiaoyue Jiang et. al. eccv 2010 \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [ascore] = ascore_image(true_shading, true_refl, estimate_shading, estimate_refl, mask, window_size)\n if nargin < 6\n window_size = 20;\n end\n ascore = 0.5 * alocal_error(true_shading, estimate_shading, mask, window_size, floor(window_size/2)) + ...\n 0.5 * alocal_error(true_refl, estimate_refl, mask, window_size, floor(window_size/2));\nend\n\nfunction [error_val] = alocal_error(correct, estimate, mask, window_size, window_shift)\n M = size(correct,1);\n N = size(correct,2);\n\n assq = 0;\n total = 0;\n for i = 1:window_shift:(M - window_size + 1)\n for j = 1:window_shift:(N - window_size + 1)\n correct_curr = correct(i:i+window_size-1, j:j+window_size-1);\n estimate_curr = estimate(i:i+window_size-1, j:j+window_size-1);\n mask_curr = mask(i:i+window_size-1, j:j+window_size-1);\n assq = assq + assq_error(correct_curr, estimate_curr, mask_curr);\n total = total + sum(mask_curr(:) .* correct_curr(:) .^ 2);\n end\n end\n\n assert(~isnan(assq/total));\n error_val = assq / total;\nend\n\nfunction [error_val] = assq_error(correct, estimate, mask)\n correct = correct - mean(correct(:));\n estimate = estimate - mean(estimate(:));\n error_val = ssq_error(correct, estimate, mask);\nend"} +{"plateform": "github", "repo_name": "shenjianbing/Accurate-normal-and-reflectance-recovery-using-energy-optimization-master", "name": "solve_gbr.m", "ext": ".m", "path": "Accurate-normal-and-reflectance-recovery-using-energy-optimization-master/MinimizeEntropy/solve_gbr.m", "size": 943, "source_encoding": "utf_8", "md5": "6f06e3da54e04515628f4dc508b6aee7", "text": "% Given an uncalibrated photometric stereo output, uB and uS, solve for the GBR transformation\n% that transforms uB and uS into the true B and S. The transformation has the form,\n% B = uB*G\n% S = inv(G)*uS\n%\n% ============\n% Neil Alldrin\n%\nfunction [mu,nu,lambda,e] = solve_gbr(uB,uS,lb,ub,stepSize)\n\n% Specify an initial feasible region for mu,nu,lambda\nif ~exist('lb') lb = [-4 -4 1/4]; end;\nif ~exist('ub') ub = [ 4 4 4]; end;\nif ~exist('stepSize') stepSize = [.5 .5 .5]; end;\ntol = [.01 .01 .01];\n\n% Specify a cost function\nrange = @(x)(max(x(:))-min(x(:)));\nbinWidth = range(sqrt(sum(uB.^2,2)))/128;\ncost_function = @(x)(cost_entropy(x,uB,binWidth));\n\n% Call a specialized solver to do the work for us\n%[mu,nu,lambda] = solve_gbr_bruteforce(cost_function,lb,ub,stepSize);\n[mu,nu,lambda] = solve_gbr_coarse_to_fine(cost_function,lb,ub,stepSize,tol);\n\n% Compute the energy for this set of parameters\ne = cost_function([mu nu lambda]);\n"} +{"plateform": "github", "repo_name": "shenjianbing/Accurate-normal-and-reflectance-recovery-using-energy-optimization-master", "name": "solve_gbr_coarse_to_fine.m", "ext": ".m", "path": "Accurate-normal-and-reflectance-recovery-using-energy-optimization-master/MinimizeEntropy/solve_gbr_coarse_to_fine.m", "size": 1034, "source_encoding": "utf_8", "md5": "48c1d43849bb62de41892f9f435d23e3", "text": "% Performs a coarse-to-fine search over a 3D grid of (mu,nu,lambda) values.\n%\n% ============\n% Neil Alldrin\n%\nfunction [mu,nu,lambda] = solve_gbr_coarse_to_fine(cost_function,lb,ub,stepSize,tol)\n\nif ~exist('stepSize') stepSize = (ub-lb)/20; end;\nif ~exist('tol') tol = stepSize/5; end;\n\nlb_orig = lb; ub_orig = ub;\n\nstepRatio = stepSize./(ub-lb);\ne = inf; mu=0; nu=0; lambda=1;\nwhile true\n \n% fprintf('\\n **stepSize = [%f %f %f]**\\n',stepSize);\n% fprintf(' **lb = [%f %f %f]**\\n',lb);\n% fprintf(' **ub = [%f %f %f]**\\n',ub);\n \n % perform brute-force search\n [mu_,nu_,lambda_] = solve_gbr_bruteforce(cost_function,lb,ub,stepSize);\n e_ = cost_function([mu_,nu_,lambda_]);\n if (e_ < e)\n e = e_; mu = mu_; nu = nu_; lambda = lambda_;\n end\n \n if (all(stepSize <= tol)) break; end;\n \n % set new boundaries\n lb = [mu,nu,lambda]-1.5*stepSize;\n ub = [mu,nu,lambda]+1.5*stepSize;\n stepSize = stepSize/1.5;\n %stepSize = stepSize/1.5;\n %stepSize = stepRatio.*(ub-lb);\n\n lb = max(lb,lb_orig);\n ub = min(ub,ub_orig);\nend\n"} +{"plateform": "github", "repo_name": "shenjianbing/Accurate-normal-and-reflectance-recovery-using-energy-optimization-master", "name": "solve_gbr_bruteforce.m", "ext": ".m", "path": "Accurate-normal-and-reflectance-recovery-using-energy-optimization-master/MinimizeEntropy/solve_gbr_bruteforce.m", "size": 903, "source_encoding": "utf_8", "md5": "ff436c35ec5318d28d862e1e2fad9530", "text": "% Performs a brute-force discrete search over a 3D grid of (mu,nu,lambda) values.\n%\n% ============\n% Neil Alldrin\n%\nfunction [mu,nu,lambda] = solve_gbr_bruteforce(cost_function,lb,ub,stepSize)\n\nif ~exist('stepSize') stepSize = (ub-lb)/20; end;\n\nmus = lb(1):stepSize(1):ub(1);\nnus = lb(2):stepSize(2):ub(2);\nlambdas = lb(3):stepSize(3):ub(3);\n\ne_min = inf;\ni_min = 1; j_min = 1; k_min = 1;\nfor i = 1:length(mus)\n for j = 1:length(nus)\n for k = 1:length(lambdas)\n \n mu = mus(i); nu = nus(j); lambda = lambdas(k);\n e = cost_function([mu nu lambda]);\n \n % check if this is the best found so far\n if any( e < e_min )\n\te_min = e; i_min = i; j_min = j; k_min = k;\n% \tfprintf('entropy=%f, mu=%f,nu=%f,l=%f\\n',e_min,mus(i_min),nus(j_min),lambdas(k_min));\n end\n \n end % for i\n end % for j\nend % for k\n\nmu = mus(i_min);\nnu = nus(j_min);\nlambda = lambdas(k_min);\n"} +{"plateform": "github", "repo_name": "shenjianbing/Accurate-normal-and-reflectance-recovery-using-energy-optimization-master", "name": "cost_entropy.m", "ext": ".m", "path": "Accurate-normal-and-reflectance-recovery-using-energy-optimization-master/MinimizeEntropy/cost_entropy.m", "size": 607, "source_encoding": "utf_8", "md5": "f3f1971c83992dfb1f9316ac4f949ff9", "text": "% Takes in a vector x = [mu, nu, lambda] and returns the entropy.\n%\n% ============\n% Neil Alldrin\n%\nfunction e = cost_entropy(x,uB,binWidth,showHist)\n\nG = [1 0 0; 0 1 0; x(1) x(2) x(3)];\n\nif ~exist('binWidth') binWidth = range(sqrt(sum(uB.^2,2)))/128; end;\nif ~exist('showHist') showHist = false; end;\n\nrhoG = sqrt(sum((uB*G).^2,2));\nrhoG = rhoG./mean(rhoG);\n\n%[p bins] = hist(rhoG,256);\n[p bins] = hist(rhoG,min(rhoG):binWidth:max(rhoG));\np = p/length(rhoG); % probability density\nind = find(p~=0); \nplogp = p(ind).*log2(p(ind));\ne = -sum(plogp);% + log2(bins(2)-bins(1));\n\nif (showHist) bar(bins,p); end;\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "flowpathapp.m", "ext": ".m", "path": "topotoolbox-master/flowpathapp.m", "size": 34896, "source_encoding": "utf_8", "md5": "734cc80dd560b49bdaa6670114a8d62f", "text": "function flowpathapp(FD,DEM,S)\n\n%FLOWPATHAPP Map, visualize and export flowpaths that start at manually set channelheads\n%\n% Syntax\n% \n% flowpathapp\n% flowpathapp(FD,DEM)\n% flowpathapp(FD,DEM,S)\n%\n% Description\n%\n% flowpathapp provides an interactive tool to visualize and generate\n% flow paths on a digital elevation model based on single flow direction\n% (FLOWobj). If an instance of STREAMobj derived from FD is supplied as\n% third argument, channelheads are automatically snapped to the\n% existing stream network, so that a subset of the latter can be\n% generated.\n%\n% The stream network constructed by manually setting channelheads can\n% be exported to the workspace as new instance of STREAMobj. In\n% addition, the stream network can be exported to Excel, as text file\n% or as shapefile (requires Mapping Toolbox).\n%\n% Tools are found in the menu bar of the main window. \n%\n%\n% Notes on export to .xls or .txt\n%\n% The mapped stream network can be exported as xls or txt file. Note\n% that individual streams are listed in the order at which they were\n% mapped. Streams that are tributary to a previously mapped stream\n% terminate at the confluence of both so it may make sense to map\n% higher order stream first before mapping their tributaries. The data\n% is exported in a columnar format that include following fields:\n%\n% ID unique stream identifier.\n% X x coordinates of the stream vertices\n% \t Y y coordinates\n% upstream_distance distance from the outlet\n% elevation elevation of the stream vertices\n% upslope_area drainage area of each stream vertice in map units \n% (nr of upstream cells x cellsize^2)\n% slope channel gradient in tangens [m/m]. Note that the\n% slope is calculated along the drainage network\n% and may differ from the slope returned by the\n% function gradient8. If the DEM was not\n% hydrologically conditioned, negative slope values\n% (upward directed) may occur. \n%\n%\n% Input arguments\n%\n% FD FLOWobj\n% DEM Digital elevation model (GRIDobj)\n% S STREAMobj derived from FD\n%\n% \n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 5. April, 2018\n\n\n%% include variable selection dialogue\nif nargin == 0 \n VARS = uigetvariables({'DEM [GRIDobj]','Flow directions [FLOWobj]','Stream network [STREAMobj] (optional)'},...\n 'ValidationFcn',{@(x) isa(x,'GRIDobj'),@(x) isa(x,'FLOWobj'),@(x) isa(x,'STREAMobj')});\n \n if isempty(VARS)\n disp('No variables selected.')\n return\n end\n \n DEM = VARS{1};\n FD = VARS{2};\n if ~isempty(VARS{3})\n % snap to streamnetwork\n snp = true;\n S = VARS{3};\n else\n snp = false;\n end\n \n if isempty(DEM) || isempty(FD)\n error('TopoToolbox:flowpathapp','DEM and flow directions must be supplied')\n end\nelseif nargin == 2\n snp = false;\nelse\n snp = true;\nend\n\n%% Check input arguments\nvalidatealignment(FD,DEM);\nif snp\n validatealignment(S,DEM);\n if ~issubgraph(S,FD)\n error('The STREAMobj S must have been derived from the FLOWobj.')\n end\nend\n\n%%\n\n% Default line color\nprops.linecolor = 'k';\n\n\n% If you set fastindexing to true then downstream processing is much faster\n% for tools that do computations along single flow paths such as\n% flowpathextract\nFD.fastindexing = true;\n\n% create figure\nscrsz = get(0,'ScreenSize');\n% pos = [left, bottom, width, height]\nhFig = figure('OuterPosition',[1/4*scrsz(3) 1/3*scrsz(4) 3/4*scrsz(3) 2/3*scrsz(4)],...\n 'MenuBar','none',...\n 'NumberTitle','off',...\n 'Name','Main');\n \n% create menu\nhMenuView = uimenu(hFig,'Label','View'); \nhButtonMenuColor = uimenu(hMenuView,'Label','Line Color'); \ncolors = 'kbgyr';\nhButtonColors(1) = uimenu(hButtonMenuColor,'Label','black','Checked','on','Callback',@(src,event) changelinecolor(src,event)); \nhButtonColors(2) = uimenu(hButtonMenuColor,'Label','blue','Checked','off','Callback',@(src,event) changelinecolor(src,event));\nhButtonColors(3) = uimenu(hButtonMenuColor,'Label','green','Checked','off','Callback',@(src,event) changelinecolor(src,event));\nhButtonColors(4) = uimenu(hButtonMenuColor,'Label','yellow','Checked','off','Callback',@(src,event) changelinecolor(src,event));\nhButtonColors(5) = uimenu(hButtonMenuColor,'Label','red','Checked','off','Callback',@(src,event) changelinecolor(src,event));\n\n\nhButtonClear = uimenu(hMenuView,'Label','Clear','Callback',@(src,event) clearvectorplots); \n\nhMenuExport = uimenu(hFig,'Label','Export'); \nhButtonExport = uimenu(hMenuExport,'Label','Export STREAMobj to workspace','Callback',@(src,event) exporttoworkspace); \nhButtonExportXLS = uimenu(hMenuExport,'Label','Export streams to Excel','Callback',@(src,event) writetoexcel); \nhButtonExportTXT = uimenu(hMenuExport,'Label','Export streams to ASCII','Callback',@(src,event) writetotxtfile);\nhButtonExportSHP = uimenu(hMenuExport,'Label','Export streams to Shapefile','Callback',@(src,event) writetoshape);\n\n% calculate hillshade\n\nhs = true;\nif hs\n RGB = imageschs(DEM,DEM,'colormap',[1 1 1]);\nelse\n RGB = DEM.Z;\nend\n% create empty axes in figure\n% hAx = axes('parent',hFig);\nhAx = imgca(hFig);\n\nif exist('S','var')\n WW = false(DEM.size);\n WW(S.IXgrid) = true;\n [rr,cc] = ind2sub(DEM.size,S.IXgrid);\n [~,~,rr,cc] = STREAMobj2XY(S,rr,cc);\n% RGB(repmat(WW,[1 1 3])) = 150; \n [~,SNAPRASTER] = bwdist(WW,'q');\n \n FD.ixcix(~WW) = 0;\n snap = true;\nelse\n snap = false;\nend\n\n% show hillshade using imshow\nhIm = imagesc(RGB,'parent',hAx);\n% create an instance of imscrollpanel and use the API\nhPanel = imscrollpanel(hFig,hIm);\napi = iptgetapi(hPanel);\n% set to initial magnification\nmag = api.findFitMag();\napi.setMagnification(mag);\n\n% create magnification box in another window\nhMagBox = immagbox(hFig,hIm);\npos = get(hMagBox,'Position');\nset(hMagBox,'Position',[0 0 pos(3) pos(4)])\nimoverview(hIm)\n\n% create figure for profiles\n[hFigProfiles,hAxProfiles] = getprofilefig;\n\nif nargin == 3\n hold(hAx,'on')\n plot(hAx,cc,rr,'color',[.7 .7 .7]);\n hold(hAx,'off')\nend\n\n\n%% add callbacks\nenterFcn = @(figHandle, currentPoint)...\n set(hFig, 'Pointer','crosshair');\niptSetPointerBehavior(hIm,enterFcn);\niptPointerManager(hFig);\n\nxlim = get(hIm,'XData');\nylim = get(hIm,'YData');\nX = 1:xlim(2);\nY = 1:ylim(2);\n\nset(hFig,'WindowButtonDownFcn',@PressLeftButton);\n\n%% Predefine variables\nIXchannelhead = 0;\ncounter = 0;\nLOGgrid = zeros(DEM.size,'uint16');\nIXchannel = {};\ndistance = {};\nhPlot = [];\nhPlotProfiles = [];\n\n\n\n function PressLeftButton(src,evt)\n \n % get the axis position\n p = get(hAx,'CurrentPoint');\n \n % check if current point is located inside axis\n p = p(1,1:2);\n \n pixelx = round(axes2pix(xlim(2), xlim, p(1)));\n pixely = round(axes2pix(ylim(2), ylim, p(2)));\n \n if pixelx < xlim(1) || pixelx > xlim(2) ...\n || pixely < ylim(1) || pixely > ylim(2)\n % do nothing\n else\n % call function\n IXchannelhead(:) = sub2ind(DEM.size,pixely,pixelx);\n counter = counter + 1;\n \n % snap to stream\n if snap\n IXchannelhead(:) = SNAPRASTER(IXchannelhead);\n end\n \n PlotProfiles\n end\n \n \n end\n\n\n\n function PlotProfiles\n % get coordinates of mouse click\n \n % get indices of flow path\n [IXchannel{counter},distance{counter}] = flowpathextract(FD,IXchannelhead);\n % set values in the ixcix raster (see FD.fastindexing) to zero\n % where the channel has been identified. This will ensure that\n % these locations are not visited again and thus for fast execution\n if LOGgrid(IXchannel{counter}(end)) == 0;\n LOGgrid(IXchannel{counter}) = counter;\n distance{counter} = distance{counter}(end) - distance{counter};\n else\n tribIX = LOGgrid(IXchannel{counter}(end));\n LOGgrid(IXchannel{counter}(1:end-1)) = counter;\n I = IXchannel{tribIX} == IXchannel{counter}(end);\n distance{counter} = distance{tribIX}(I)+(distance{counter}(end)-distance{counter});\n end\n \n FD.ixcix(IXchannel{counter}) = 0;\n % plot flow path\n hold(hAx,'on')\n [r,c] = ind2sub(DEM.size,IXchannel{counter});\n hPlot(counter) = plot(hAx,X(c),Y(r),props.linecolor,'LineWidth',2);\n hold(hAx,'off');\n drawnow\n\n hold(hAxProfiles,'on')\n\n hPlotProfiles(counter) = plot(hAxProfiles,distance{counter},DEM.Z(IXchannel{counter}),props.linecolor);\n hold(hAxProfiles,'off');\n drawnow\n \n end\n\n function clearvectorplots\n delete(hPlot);\n hPlot = [];\n delete(hPlotProfiles)\n hPlotProfiles = [];\n counter = 0;\n FD.fastindexing = true;\n \n if snap\n FD.ixcix(~WW) = 0;\n end\n \n LOGgrid = zeros(DEM.size,'uint16');\n IXchannel = {};\n distance = {};\n \n end\n\n function exporttoworkspace\n W = DEM;\n W.Z = LOGgrid>0;\n \n if any(W.Z(:))\n S = STREAMobj(FD,W);\n \n prompt = {'Enter variable name:'};\n title = 'Export';\n lines = 1;\n def = {'S'};\n answer = inputdlg(prompt, title, lines, def);\n if ~isempty(answer) && isvarname(answer{1})\n assignin('base',answer{1},S);\n else\n return\n end\n else\n warndlg('No streams available for export.');\n end\n\n end\n\n function writetoexcel(src,event)\n \n \n if isempty(IXchannel)\n warndlg('No streams available for export.');\n else\n [D,header] = makedataset(IXchannel,distance);\n D = [header; num2cell(D)];\n \n [FileName,PathName] = uiputfile({'*.xlsx';'*.xls'},'Write to Excel');\n \n if FileName == 0\n return\n end\n \n xlswrite([PathName FileName],D);\n \n end\n end\n\n function writetotxtfile(src,event)\n \n if isempty(IXchannel)\n warndlg('No streams available for export.');\n \n else\n [D,header] = makedataset(IXchannel,distance); \n [FileName,PathName] = uiputfile({'*.txt'},'Write to text file');\n \n if FileName == 0\n return\n end\n \n fid = fopen([PathName FileName], 'w');\n \n for r = 1:numel(header);\n fprintf(fid, header{r});\n if r < numel(header)\n fprintf(fid, '\\t');\n end \n end\n fprintf(fid, '\\n');\n\n for row=1:size(D,1);\n fprintf(fid, '%d\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n', D(row,:));\n end\n\n fclose(fid);\n \n end\n end\n\n function writetoshape(src,event)\n if isempty(IXchannel)\n warndlg('No streams available for export.');\n elseif ~(exist('shapewrite','file')==2);\n warndlg('The function shapewrite is not available. Shapewrite is part of the Mapping Toolbox.');\n else\n \n \n for r = 1:numel(IXchannel);\n SHP(r).Geometry = 'Line';\n [SHP(r).X SHP(r).Y] = ind2coord(DEM,IXchannel{r}(:)); \n SHP(r).X = SHP(r).X';\n SHP(r).Y = SHP(r).Y';\n SHP(r).ID = r;\n SHP(r).minZ = double(min(DEM.Z(IXchannel{r})));\n SHP(r).maxZ = double(max(DEM.Z(IXchannel{r})));\n SHP(r).length = double(max(distance{r})-min(distance{r}));\n SHP(r).tribtoID = double(LOGgrid(IXchannel{r}(end)));\n if SHP(r).tribtoID == SHP(r).ID;\n SHP(r).tribtoID = 0;\n end\n end\n [FileName,PathName] = uiputfile('*.shp','Write to Shapefile');\n \n if FileName == 0\n return\n end\n \n shapewrite(SHP,[PathName FileName]);\n end\n \n end\n\n function changelinecolor(src,event)\n \n \n I = src == hButtonColors;\n\n props.linecolor = colors(I);\n\n \n h = findobj(hButtonColors,'Checked','on');\n set(h,'Checked','off');\n set(src,'Checked','on');\n end\n \n\n function [D,header] = makedataset(IXchannel,distance)\n \n A = flowacc(FD);\n G = gradient(FD,DEM);\n D = cell(numel(IXchannel),1);\n for r = 1:numel(IXchannel);\n D{r}(1:numel(IXchannel{r}),1) = repmat(r,numel(IXchannel{r}),1);\n [D{r}(:,2) D{r}(:,3)] = ind2coord(DEM,IXchannel{r}(:)); \n D{r}(:,4) = distance{r}(:);\n D{r}(:,5) = DEM.Z(IXchannel{r}(:));\n D{r}(:,6) = A.Z(IXchannel{r}(:)).*(DEM.cellsize).^2;\n D{r}(:,7) = G.Z(IXchannel{r}(:));\n end\n \n D = cell2mat(D);\n header = {'ID' 'X' 'Y' 'upstream_distance' 'elevation' 'upslope_area' 'slope'};\n \n end\n \n function [hFigProfiles,hAxProfiles] = getprofilefig\n % create figure for profiles\n hFigProfiles = figure('OuterPosition',[1/4*scrsz(3) 50 3/4*scrsz(3) 1/3*scrsz(4)-50],...\n 'NumberTitle','off',...\n 'Name','Profiles') ;\n hAxProfiles = axes('Parent',hFigProfiles,'Xscale','linear','Yscale','linear','box','on');\n xlabel(hAxProfiles,'distance from outlet');\n ylabel(hAxProfiles,'elevation');\n end \n\n \nend\n \n\n\n%% -----------------------------------------------------\n% -----------------------------------------------------\n% -----------------------------------------------------\n% -----------------------------------------------------\n% -----------------------------------------------------\n% -----------------------------------------------------\n% -----------------------------------------------------\n\n\nfunction [varout,varoutnames] = uigetvariables(prompts,varargin)\n% uigetvariables Open variable selection dialog box\n%\n% VARS = uigetvariables(PROMPTS) creates a dialog box that returns\n% variables selected from the base workspace. PROMPTS is a cell array of\n% strings, with one entry for each variable you would like the user to\n% select. VARS is a cell array containing the selected variables. Each\n% element of VARS corresponds with the selection for the same element of\n% PROMPTS.\n%\n% If the user hits CANCEL, dismisses the dialog, or doesn't select a value\n% for any of the variables, VARS is an empty cell array. If the user does\n% not select a variable for a given prompt (but not all promptes), the\n% value in VARS for that prompt is an empty array.\n%\n% [VARS, VARNAMES] = uigetvariables(PROMPTS) also returns the names of the\n% selected variables. VARNAMES is a cell string the same length as VARS,\n% with empty strings corresponding to empty values of VARS.\n%\n% VARS = uigetvariables(PROMPTS,'ParameterName',ParameterValue) specifies an\n% optional parameter value. Enter parameters as one or more name-value\n% pairs. \n%\n% Specify zero or more of the following name/value pairs when calling\n% uigetvariables:\n%\n% 'Introduction' Introductory String. Default: No introduction (empty)\n%\n% A string of introductory text to guide the user in making selections in\n% the dialog. The text is wrapped automatically to fit in the dialog.\n%\n%\n% 'InputTypes' Restrict variable types. Default: No restrictions ('any')\n%\n% A cell array of strings of the same length as PROMPTS, each entry\n% specifies the allowable type of variables for each prompt. InputTypes\n% restricts the types of the variables which can be selected for each\n% prompt. \n%\n% The elements of TYPES may be any of the following:\n% any Any type. Use this if you don't care.\n% numeric Any numeric type, as determined by isnumeric\n% logical Logical\n% string String or cell array of strings\n%\n%\n% 'InputDimensions' Restrict variable dimensionality. Default: No restrictions (Inf)\n%\n% A numeric array of the same length as PROMPTS, with each element specifying the\n% required dimensionality of the variables for the corresponding element of\n% PROMPTS. NDIMENSIONS works a little different from ndims, in that it\n% allows you to distinguish among scalars, vectors, and matrices.\n% \n% Allowable values are:\n%\n% Value Meaning\n% ------------ ----------\n% Inf Any size. Use this if you don't care, or want more than one allowable size\n% 0 Scalar (1x1)\n% 1 Vector (1xN or Nx1)\n% 2 Matrix (NxM)\n% 3 or higher Specified number of dimensions\n%\n%\n% 'SampleData' Sample data. Default: No sample data\n%\n% A cell array of the same length as PROMPTS, with each element specifying\n% the value of sample data for the corresponding prompt. When SampleData is\n% specified, the dialog includes a button that allows the user to use your\n% sample data instead of having to provide their own data. This can make\n% it easier for users to get a feel for how to use your app. \n%\n%\n% 'ValidationFcn' Validation function, to restrict allowed variables. Default: No restrictions\n%\n% ValidationFcn is a cell array of function handles of the same length as\n% PROMPTS, or a single function handle. If VALFCN is a single function\n% handle, it is applied to every prompt. Use a cell array of function\n% handles to specify a unique validation function for each prompt. The\n% validation function handles are used to validation functions which are\n% used to determine which variables are valid for each prompt. The\n% validation functions must return true if a variable passes the validation\n% or false if the variable does not. Syntax of the validation functions\n% must be: TF = VALFCN(variable)\n%\n%\n% Examples\n%\n% % Put some sample data in your base workspace:\n% scalar1 = 1;\n% str1 = 'a string';\n% cellstr1 = {'a string';'in a cell'};cellstr2 = {'another','string','in','a','cell'}; \n% cellstr3 = {'1','2';,'3','4'}\n% vector1 = rand(1,10); vector2 = rand(5,1);\n% array1 = rand(5,5); array2 = rand(5,5); array3 = rand(10,10);\n% threed1 = rand(3,4,5);\n% fourd1 = rand(1,2,3,4);\n%\n% % Select any two variables from entire workspace\n% tvar = uigetvariables({'Please select any variable','And another'});\n%\n% % Return the names of the selected variables, too.\n% [tvar, tvarnames] = uigetvariables({'Please select any variable','And another'});\n% \n% % Include introductory text\n% tvar = uigetvariables({'Please select any variable','And another'}, ...\n% 'Introduction',['Here are some very detailed directions about '...\n% 'how you should use this dialog. Pick some variables.']);\n% \n% % Control type of variables\n% tvar = uigetvariables({'Pick a number:','Pick a string:','Pick another number:'}, ...\n% 'InputTypes',{'numeric','string','numeric'});\n% \n% % Control size of variables.\n% tvar = uigetvariables({'Pick a scalar:','Pick a vector:','Pick a matrix:'}, ...\n% 'InputDimensions',[0 1 2]);\n% \n% % Control type and size of variables\n% tvar = uigetvariables({'Pick a scalar:','Pick a string','Pick a 4D array'}, ...\n% 'InputTypes',{'numeric','string','numeric'}, ...\n% 'InputDimensions',[0 Inf 4]);\n%\n% tvar = uigetvariables({'Pick a scalar:','Pick a string vector','Pick a 3D array'}, ...\n% 'InputTypes',{'numeric','string','numeric'}, ...\n% 'InputDimensions',[0 1 3]);\n% \n% % Include sample data\n% sampleX = 1:10;\n% sampleY = 10:-1:1;\n% tvar = uigetvariables({'x:','y:'}, ...\n% 'SampleData',{sampleX,sampleY});\n%\n% % Custom validation functions (Advanced)\n% tvar = uigetvariables({'Pick a number:','Any number:','One more, please:'}, ...\n% 'Introduction','Use a custom validation function to require every input to be numeric', ...\n% 'ValidationFcn',@isnumeric);\n%\n% tvar = uigetvariables({'Pick a number:','Pick a cell string:','Pick a 3D array:'}, ...\n% 'ValidationFcn',{@isnumeric,@iscellstr,@(x) ndims(x)==3});\n% \n% % No variable found\n% tvar = uigetvariables('Pick a 6D numeric array:','What if there is no valid data?','ValidationFcn',@(x) isnumeric(x)&&ndims(x)==6);\n%\n% % Specify defaults\n% x = 2;\n% y = 3;\n% tvar = uigetvariables({'Please select any variable','And another'}', ...\n% 'SampleData',{x,y});\n\n% Michelle Hirsch\n% Michelle.Hirsch@mathworks.com\n\n\n% Input parsing\n% Use inputParser to:\n% * Manage Name-Value Pairs\n% * Do some first-pass input validation\nisStringOrCellString = @(c) iscellstr(c)||ischar(c);\np = inputParser;\np.CaseSensitive = false;\naddRequired(p,'prompts',isStringOrCellString);\naddParamValue(p,'Introduction','',@ischar);\naddParamValue(p,'InputTypes',[],isStringOrCellString);\naddParamValue(p,'InputDimensions',[],@isnumeric);\naddParamValue(p,'ValidationFcn',[],@(c) iscell(c)|| isa(c,'function_handle'));\naddParamValue(p,'SampleData',[])\n\nparse(p,prompts,varargin{:})\n\nintro = p.Results.Introduction;\ntypes = p.Results.InputTypes;\nndimensions = p.Results.InputDimensions;\nsampleData = p.Results.SampleData;\nvalfcn = p.Results.ValidationFcn;\n\n% Allow for single prompt as string\nif ~iscell(prompts)\n prompts = {prompts};\nend\nnPrompts = length(prompts);\n\n% Default ndimensions is Inf\nif isempty(ndimensions)\n % User didn't specify any dimensions\n ndimensions = inf(1,nPrompts);\nend\n\n% Did user specify SampleData\nif ~isempty(sampleData)\n \n % Allow for single prompt case as not cell\n if ~iscell(sampleData)\n sampleData = {sampleData};\n end\n includeSampleData = true;\nelse\n includeSampleData = false;\nend\n\n\n%% Process Validation functions\n% Three options:\n% * Nothing\n% * Convenience string\n% * Function handle\nif isempty(types) && isempty(valfcn)\n % User didn't specify any validation\n\n types = cellstr(repmat('any',nPrompts,1)); % This will get converted later\n\n specifiedValidationFcn = false;\nelseif ~isempty(types)\n % User specified types. Assume didn't specify valfcn\n\n % Allow for single prompt with single type as a string\n if ischar(types) \n types = {types};\n end\n \n specifiedValidationFcn = false;\nelseif ~isempty(valfcn)\n % User specified validation function\n\n % If specified as a single function handle, repeat for each input\n if ~iscell(valfcn)\n temp = cell(nPrompts,1);\n temp = cellfun(@(f) valfcn,temp,'UniformOutput',false);\n valfcn = temp;\n end\n \n specifiedValidationFcn = true;\nend\n\n\n\n\n%% \n% If the user didn't specify the validation function, we will build it for them. \nif ~specifiedValidationFcn\n \n % Base validation functions to choose from:\n isscalarfcn = @(var) numel(var)==1;\n isvectorfcn = @(var) length(size(var))==2&&any(size(var)==1)&&~isscalarfcn(var);\n isndfcn = @(var,dim) ndims(var)==dim && ~isscalar(var) && ~isvectorfcn(var);\n \n isanyfcn = @(var) true; % What an optimistic function! :)\n isnumericfcn = @(var) isnumeric(var);\n islogicalfcn = @(var) islogical(var);\n isstringfcn = @(var) ischar(var) | iscellstr(var);\n istablefcn = @(var) istable(var);\n\n valfcn = cell(1,nPrompts);\n \n for ii=1:nPrompts\n \n switch types{ii}\n case 'any'\n valfcn{ii} = isanyfcn;\n case 'numeric'\n valfcn{ii} = isnumericfcn;\n case 'logical'\n valfcn{ii} = islogicalfcn;\n case 'string'\n valfcn{ii} = isstringfcn;\n case 'table'\n valfcn{ii} = istablefcn;\n otherwise\n valfcn{ii} = isanyfcn;\n end\n \n switch ndimensions(ii)\n case 0 % 0 - scalar\n valfcn{ii} = @(var) isscalarfcn(var) & valfcn{ii}(var);\n case 1 % 1 - vector\n valfcn{ii} = @(var) isvectorfcn(var) & valfcn{ii}(var);\n case Inf % Inf - Any shape\n valfcn{ii} = @(var) isanyfcn(var) & valfcn{ii}(var);\n otherwise % ND\n valfcn{ii} = @(var) isndfcn(var,ndimensions(ii)) & valfcn{ii}(var);\n end\n end\nend\n\n\n%% Get list of variables in base workspace\nallvars = evalin('base','whos');\nnVars = length(allvars);\nvarnames = {allvars.name};\nvartypes = {allvars.class};\nvarsizes = {allvars.size};\n\n\n% Convert variable sizes from numbers:\n% [N M], [N M P], ... etc\n% to text:\n% NxM, NxMxP\nvarsizes = cellfun(@mat2str,varsizes,'UniformOutput',false);\n%too lazy for regexp. Strip off brackets\nvarsizes = cellfun(@(s) s(2:end-1),varsizes,'UniformOutput',false);\n% replace blank with x\nvarsizes = strrep(varsizes,' ','x');\n\nvardisplay = strcat(varnames,' (',varsizes,{' '},vartypes,')');\n\n%% Build list of variables for each prompt\n% Also include one that's prettied up a bit for display, which has an extra\n% first entry saying '(select one)'. This allows for no selection, for\n% optional input arguments.\nvalidVariables = cell(nPrompts,1);\nvalidVariablesDisplay = cell(nPrompts,1); \n\nfor ii=1:nPrompts\n % turn this into cellfun once I understand what I'm doing.\n assignin('base','validationfunction_',valfcn{ii})\n validVariables{ii} = cell(nVars,1);\n validVariablesDisplay{ii} = cell(nVars+1,1);\n t = false(nVars,1);\n for jj = 1:nVars\n t(jj) = evalin('base',['validationfunction_(' varnames{jj} ');']);\n end\n if any(t) % Found at least one variable\n validVariables{ii} = varnames(t);\n validVariablesDisplay{ii} = vardisplay(t);\n validVariablesDisplay{ii}(2:end+1) = validVariablesDisplay{ii};\n validVariablesDisplay{ii}{1} = '(select one)';\n else\n validVariables{ii} = '(no valid variables)';\n validVariablesDisplay{ii} = '(no valid variables)';\n end\n \n evalin('base','clear validationfunction_')\nend\n\n\n%% Compute layout\nvoffset = 1; % Vertical offset\nhoffset = 2; % Horizontal offset\nnudge = .1;\nmaxStringLength = max(cellfun(@(s) length(s),prompts));\ncomponentWidth = max([maxStringLength, 50]);\ncomponentHeight = 1;\n\n% Buttons\nbuttonHeight = 1.8;\nbuttonWidth = 16;\n\n\n% Wrap intro string. Need to do this now to include height in dialog.\n% Could use textwrap, which comes with MATLAB, instead of linewrap. This would just take a\n% bit more shuffling around with the order I create and size things.\nif ~isempty(intro)\n intro = linewrap(intro,componentWidth);\n introHeight = length(intro); % Intro is now an Nx1 cell string\nelse\n introHeight = 0;\nend\n\n\ndialogWidth = componentWidth + 2*hoffset;\ndialogHeight = 2*nPrompts*(componentHeight+voffset) + buttonHeight + voffset + introHeight;\n\nif includeSampleData % Make room for the use sample data button\n dialogHeight = dialogHeight + 2*voffset*buttonHeight;\nend\n\n\n% Component positions, starting from bottom of figure\npopuppos = [hoffset 2*voffset+buttonHeight componentWidth componentHeight];\ntextpos = popuppos; textpos(2) = popuppos(2)+componentHeight+nudge;\n\n%% Build figure\nhFig = dialog('Units','Characters','WindowStyle','modal','Name','Select variable(s)','CloseRequestFcn',@nestedCloseReq);\n \npos = get(hFig,'Position');\nset(hFig,'Position',[pos(1:2) dialogWidth dialogHeight])\nuicontrol('Parent',hFig,'style','Pushbutton','Callback',@nestedCloseReq,'String','OK', 'Tag','OK','Units','characters','Position',[dialogWidth-2*hoffset-2*buttonWidth .5*voffset buttonWidth buttonHeight]);\nuicontrol('Parent',hFig,'style','Pushbutton','Callback',@nestedCloseReq,'String','Cancel','Tag','Cancel','Units','characters','Position',[dialogWidth-hoffset-buttonWidth .5*voffset buttonWidth buttonHeight]);\n\n\nfor ii=nPrompts:-1:1\n uicontrol('Parent',hFig,'Style','text', 'Units','char','Position',textpos, 'String',prompts{ii},'HorizontalAlignment','left');\n hPopup(ii) = uicontrol('Parent',hFig,'Style','popupmenu','Units','char','Position',popuppos,'String',validVariablesDisplay{ii},'UserData',validVariables{ii});\n \n % Set up positions for next go round\n popuppos(2) = popuppos(2) + 1.5*voffset + 2*componentHeight;\n textpos(2) = textpos(2) + 1.5*voffset + 2*componentHeight;\nend\n\nif includeSampleData\n uicontrol('Parent',hFig, ...\n 'style','Pushbutton', ...\n 'Callback',@nestedCloseReq, ... \n 'String','Use Sample Data', ...\n 'Tag','UseSampleData', ...\n 'Units','characters', ...\n 'Position',[hoffset popuppos(2) dialogWidth-2*hoffset buttonHeight]); % Steal the vertical position from popup position settign.\nend\n\nif ~isempty(intro)\n intropos = [hoffset dialogHeight-introHeight-1 componentWidth introHeight+.5];\n uicontrol('Parent',hFig,'Style','text','Units','Characters','Position',intropos, 'String',intro,'HorizontalAlignment','left');\nend\n\nuiwait(hFig)\n\n\n function nestedCloseReq(obj,~)\n % How did I get here?\n % If pressed OK, get variables. Otherwise, don't.\n \n if strcmp(get(obj,'type'),'uicontrol') && strcmp(get(obj,'Tag'),'OK')\n \n for ind=1:nPrompts\n str = get(hPopup(ind),'UserData'); % Store real variable name here\n val = get(hPopup(ind),'Value')-1; % Remove offset to account for '(select one)' as initial entry\n \n if val==0 % User didn't select anything\n varout{ind} = [];\n varoutnames{ind} = '';\n elseif strcmp(str,'(no valid variables)')\n varout{ind} = [];\n varoutnames{ind} = '';\n else\n varout{ind} = evalin('base',str{val});\n varoutnames{ind} = str{val}; % store name of selected workspace variable\n end\n \n \n end\n \n % if user clicked OK, but didn't select any variable, give same\n % return as if hit cancel\n if all(cellfun(@isempty,varout))\n varout = {};\n varoutnames = {};\n end\n elseif strcmp(get(obj,'type'),'uicontrol') && strcmp(get(obj,'Tag'),'UseSampleData')\n % Put sample data in return. Return empty names\n varout = sampleData;\n varoutnames = cell(size(sampleData)); varoutnames(:) = {''};\n \n else % Cancel - return empty\n varout = {};\n varoutnames = {};\n end\n \n delete(hFig)\n \n end\nend\n\n\n\n\nfunction c = linewrap(s, maxchars)\n%LINEWRAP Separate a single string into multiple strings\n% C = LINEWRAP(S, MAXCHARS) separates a single string into multiple\n% strings by separating the input string, S, on word breaks. S must be a\n% single-row char array. MAXCHARS is a nonnegative integer scalar\n% specifying the maximum length of the broken string. C is a cell array\n% of strings.\n%\n% C = LINEWRAP(S) is the same as C = LINEWRAP(S, 80).\n%\n% Note: Words longer than MAXCHARS are not broken into separate lines.\n% This means that C may contain strings longer than MAXCHARS.\n%\n% This implementation was inspired a blog posting about a Java line\n% wrapping function:\n% http://joust.kano.net/weblog/archives/000060.html\n% In particular, the regular expression used here is the one mentioned in\n% Jeremy Stein's comment.\n%\n% Example\n% s = 'Image courtesy of Joe and Frank Hardy, MIT, 1993.'\n% c = linewrap(s, 40)\n%\n% See also TEXTWRAP.\n\n% Steven L. Eddins\n% $Revision: 1.7 $ $Date: 2006/02/08 16:54:51 $\n\n% http://www.mathworks.com/matlabcentral/fileexchange/9909-line-wrap-a-string\n% Copyright (c) 2009, The MathWorks, Inc.\n% All rights reserved.\n% \n% Redistribution and use in source and binary forms, with or without \n% modification, are permitted provided that the following conditions are \n% met:\n% \n% * Redistributions of source code must retain the above copyright \n% notice, this list of conditions and the following disclaimer.\n% * Redistributions in binary form must reproduce the above copyright \n% notice, this list of conditions and the following disclaimer in \n% the documentation and/or other materials provided with the distribution\n% * Neither the name of the The MathWorks, Inc. nor the names \n% of its contributors may be used to endorse or promote products derived \n% from this software without specific prior written permission.\n% \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n% POSSIBILITY OF SUCH DAMAGE.\n\nnarginchk(1, 2);\n\nbad_s = ~ischar(s) || (ndims(s) > 2) || (size(s, 1) ~= 1); %#ok\nif bad_s\n error('S must be a single-row char array.');\nend\n\nif nargin < 2\n % Default value for second input argument.\n maxchars = 80;\nend\n\n% Trim leading and trailing whitespace.\ns = strtrim(s);\n\n% Form the desired regular expression from maxchars.\nexp = sprintf('(\\\\S\\\\S{%d,}|.{1,%d})(?:\\\\s+|$)', maxchars, maxchars);\n\n% Interpretation of regular expression (for maxchars = 80):\n% '(\\\\S\\\\S{80,}|.{1,80})(?:\\\\s+|$)'\n%\n% Match either a non-whitespace character followed by 80 or more\n% non-whitespace characters, OR any sequence of between 1 and 80\n% characters; all followed by either one or more whitespace characters OR\n% end-of-line.\n\ntokens = regexp(s, exp, 'tokens').';\n\n% Each element if the cell array tokens is single-element cell array \n% containing a string. Convert this to a cell array of strings.\nget_contents = @(f) f{1};\nc = cellfun(get_contents, tokens, 'UniformOutput', false);\n\n% Remove trailing whitespace characters from strings in c. This can happen\n% if multiple whitespace characters separated the last word on a line from\n% the first word on the following line.\nc = deblank(c);\n\nend\n\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "mappingapp.m", "ext": ".m", "path": "topotoolbox-master/mappingapp.m", "size": 14821, "source_encoding": "utf_8", "md5": "ffe073ffbfeb9ca660c30b6d55805d19", "text": "function mappingapp(DEM,S,varargin)\n\n% map knickpoints combining planform and profile view\n%\n% Syntax\n%\n% mappingapp(DEM,S)\n%\n% Description\n%\n% This light-weight tool enables mapping points in planform and profile\n% view simultaneously based on a digital elevation model (DEM) and a\n% stream network (S). Points are stored as a table and can be exported.\n% Note that this tool is still beta and quite rudimentary.\n%\n% Input arguments\n%\n% DEM Digital elevation model (GRIDobj)\n% S Stream network (STREAMobj)\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',1000);\n% mappingapp(DEM,S) \n%\n%\n% See also: STREAMobj, flowpathapop\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 7. November, 2018\n\n\n% Add the GUI components\nhs = addcomponents;\n\n% Add data to GUI\n% calculate hillshade\nRGB = imageschs(DEM,DEM,'colormap',landcolor(255));\n% create empty axes in figure\nax.main = axes('Units','normalized', ...\n 'Position', [0 0 1 1], ...\n 'Parent', hs.main, ...\n 'Clipping', 'off', ...\n 'ActivePositionProperty','position');\n\n% After adding all components make figure visible\nhs.fig.Visible = 'on'; \n% % set axis to image\n% axis(ax.main,'image');\n% show hillshade using imshow\nhIm = imshow(RGB,'parent',ax.main);\n\n% create an instance of imscrollpanel and use the API\nhPanel = imscrollpanel(hs.main,hIm);\nset(hPanel,'Units','normalized','Position',[0 0 1 1])\napi = iptgetapi(hPanel);\n\nhs.Menu.ZoomIn.ClickedCallback = @callbackZoomIn;\nhs.Menu.ZoomOut.ClickedCallback = @callbackZoomOut;\n\nhImOverview = imoverviewpanel(hs.overview,hIm); \n \n% get s\n[x,y,d,z] = STREAMobj2XY(S,S.distance,DEM);\n[r,c] = coord2sub(DEM,x,y);\n\nhold(ax.main,'on')\nls.main = plot(ax.main,c,r,'k');\nhold(ax.main,'off')\n\n% profile\nax.profile = axes('parent',hs.profiles,...\n 'Position',[0 0 1 1],...\n 'TickLength',[0.005 0.005]);\nls.profile = plot(ax.profile,d,z,'Color',[.2 .2 .2]);\n\nix = [];\npoint = [];\nactiverow = 1;\nactivecolor = 'b';\ninactivecolor = 'w';\n\n% set the first row\nhs.table.Data = cell(1,4);\nsetnewpoints;\n\nhs.Menu.Add.ClickedCallback = @callbackAdd;\nhs.Menu.Export.ClickedCallback = @callbackExport;\n\n%% Table utilities\nfunction setnewpoints(pos)\n if nargin == 0\n point.main = impoint(ax.main,'PositionConstraintFcn',@getnearestmain);\n else\n point.main = impoint(ax.main,pos,'PositionConstraintFcn',@getnearestmain);\n end\n setColor(point.main,activecolor)\n setPosition(point.main,getPosition(point.main))\n\n point.profile = impoint(ax.profile,[d(ix) z(ix)],'PositionConstraintFcn',@getnearestprofile);\n setColor(point.profile,activecolor)\nend\n\nfunction callbackAdd(varargin) \n % Add row\n hs.table.Data = [hs.table.Data;cell(1,4)];\n activerow = activerow + 1;\n hold(ax.profile,'on');\n data = hs.table.Data;\n nrEntries = size(data,1);\n inactiverows = setdiff(1:nrEntries,activerow);\n [~,I] = ismember(cell2mat(data(inactiverows,1:2)),[x y],'rows');\n hold(ax.main,'on');\n plot(ax.main,c(I),r(I),'ok','MarkerFaceColor',inactivecolor);\n hold(ax.main,'off');\n \n hold(ax.profile,'on');\n plot(ax.profile,d(I),z(I),'ok','MarkerFaceColor',inactivecolor);\n hold(ax.profile,'off');\n \n % Now move the mobile point a bit downstream because otherwise it is\n % difficult to grab\n setnewpoints(getPosition(point.main))\n% setPosition(point.main,getPosition(point.main))\n% setPosition(point.profile,getPosition(point.profile));\nend\n\n\n\nfunction callbackZoomIn(varargin)\n % Zoom in\n api.setMagnification(api.getMagnification() + 1);\nend\n\nfunction callbackZoomOut(varargin)\n % Zoom out\n mag = api.findFitMag();\n api.setMagnification(max(api.getMagnification() - 1,mag));\nend\n\nfunction callbackExport(varargin)\n % Create table\n T = cell2table(hs.table.Data,'VariableNames',hs.table.ColumnName);\n \n if iscell(T.X(end))\n T = cell2table(hs.table.Data(1:end-1,:),'VariableNames',hs.table.ColumnName);\n end\n \n % get linear indices\n [~,locb] = ismember([T.X T.Y],[S.x S.y],'rows');\n T.IXgrid = S.IXgrid(locb); \n\n prompt = {'Enter variable name:'};\n title = 'Export';\n lines = 1;\n def = {'T'};\n answer = inputdlg(prompt, title, lines, def);\n if ~isempty(answer) && isvarname(answer{1})\n assignin('base',answer{1},T);\n else\n return\n end\n\nend\n\nfunction posn = getnearestmain(pos)\n % GETNEAREST snap to nearest location on stream network\n [~,ix] = min((c-pos(1)).^2 + (r-pos(2)).^2);\n posn= [c(ix) r(ix)]; \n if isfield(point,'profile') \n setPosition(point.profile,[d(ix) z(ix)]);\n end \n hs.table.Data{activerow,1} = x(ix);\n hs.table.Data{activerow,2} = y(ix);\n hs.table.Data{activerow,3} = z(ix);\nend\n\nfunction posn = getnearestprofile(pos)\n % GETNEAREST snap to nearest location on stream network profile\n [~,ix] = min((d-pos(1)).^2 + (z-pos(2)).^2);\n posn= [d(ix) z(ix)];\n setPosition(point.main,[c(ix) r(ix)]);\n hs.table.Data{activerow,1} = x(ix);\n hs.table.Data{activerow,2} = y(ix);\n hs.table.Data{activerow,3} = z(ix);\nend\n\nend\n\n\nfunction hs = addcomponents\n% create figure with panels\nhs.fig = figure('Name','MappingApp',...\n 'NumberTitle','off',...\n 'Toolbar','none',...\n 'MenuBar','none',...\n 'Visible','off');\n\nhs.toolbar = uitoolbar(hs.fig);\niconin = createIcon('in');\nhs.Menu.ZoomIn = uipushtool(hs.toolbar,...\n 'TooltipString','Zoom In',...\n 'Cdata',iconin);\n\niconout = createIcon('out');\nhs.Menu.ZoomOut = uipushtool(hs.toolbar,...\n 'TooltipString','Zoom Out',...\n 'Cdata',iconout);\n\niconadd = createIcon('add');\nhs.Menu.Add = uipushtool(hs.toolbar,...\n 'TooltipString','Add row',...\n 'Cdata',iconadd,...\n 'Separator','on');\n\n% icondel = createIcon('del');\n% hs.Menu.Del = uipushtool(hs.toolbar,...\n% 'TooltipString','Delete row',...\n% 'Cdata',icondel);\n\n\niconexport = createIcon('export');\nhs.Menu.Export = uipushtool(hs.toolbar,...\n 'TooltipString','Export to workspace',...\n 'Cdata',iconexport);\n\n\n% main panel with hillshade\nhs.main = uipanel('BackgroundColor','white',...\n 'Position',[.25 .25 .75 .75]);\n \n% overview panel to help navigation\nhs.overview = uipanel('Position',[0 0.75 0.25 0.25]); \n\n% table panel\nhs.features = uipanel('Position',[0 0.25 0.25 0.50]);\n\n% Column names and column format\nfcolumnname = {'X','Y','Z','Name'};\nfcolumnformat = {'numeric','numeric','numeric','char'};\nhs.table = uitable('Parent',hs.features,...\n 'ColumnName', fcolumnname,...\n 'ColumnFormat', fcolumnformat,...\n 'ColumnEditable', [false false false true],...\n 'Units','normalize',...\n 'Position',[0 0 1 1]);\n \n% profile panel\nhs.profiles = uipanel('Position',[0 0 1 .25]);\n\nend\n \n\nfunction c = createIcon(type)\n\nswitch type\n case 'in' \n c = [...\n 0 0 2 84 173 215 214 170 78 1 0 0 0 0 0 0\n 0 18 187 252 253 253 253 253 252 178 14 0 0 0 0 0\n 5 193 253 248 154 87 89 160 250 253 182 2 0 0 0 0\n 102 252 245 65 3 181 181 3 75 248 252 88 0 0 0 0\n 198 253 135 0 3 237 237 3 0 148 253 182 1 0 0 0\n 245 253 58 179 210 251 251 210 179 71 253 229 2 0 0 0\n 249 253 51 228 252 253 253 252 229 63 253 233 2 0 0 0\n 212 253 111 8 16 237 237 16 8 125 253 196 1 0 0 0\n 127 253 230 30 0 219 219 0 37 236 253 114 2 0 0 0\n 17 222 253 226 98 45 47 104 231 254 254 209 151 14 0 0\n 0 45 225 253 253 253 253 253 253 254 254 254 253 194 14 0\n 0 0 20 139 227 252 252 224 134 183 254 255 254 253 194 15\n 0 0 0 1 2 18 17 1 2 100 253 254 255 254 253 175\n 0 0 0 0 0 0 0 0 0 1 139 253 254 255 254 249\n 0 0 0 0 0 0 0 0 0 0 1 139 253 254 253 196\n 0 0 0 0 0 0 0 0 0 0 0 1 118 213 177 31];\n case 'out'\n c = [...\n 0 0 2 84 173 215 214 170 78 1 0 0 0 0 0 0\n 0 18 187 252 253 253 253 253 252 178 14 0 0 0 0 0\n 5 193 253 248 153 86 87 159 250 253 182 2 0 0 0 0\n 102 252 245 65 1 0 0 1 75 248 252 88 0 0 0 0\n 198 253 135 2 2 1 1 2 2 148 253 182 1 0 0 0\n 245 253 58 179 209 209 209 209 179 71 253 229 2 0 0 0\n 249 253 51 228 252 252 252 252 229 63 253 233 2 0 0 0\n 212 253 111 8 15 15 15 15 8 125 253 196 1 0 0 0\n 127 253 230 30 1 0 0 1 37 236 253 114 2 0 0 0\n 17 222 253 226 97 30 32 103 231 254 254 209 151 14 0 0\n 0 45 225 253 253 253 253 253 253 254 254 254 253 194 14 0\n 0 0 20 139 227 252 252 224 134 183 254 255 254 253 194 15\n 0 0 0 1 2 18 17 1 2 100 253 254 255 254 253 175\n 0 0 0 0 0 0 0 0 0 1 139 253 254 255 254 249\n 0 0 0 0 0 0 0 0 0 0 1 139 253 254 253 196\n 0 0 0 0 0 0 0 0 0 0 0 1 118 213 177 31];\n case 'add'\n c = [ ...\n 0 0 0 0 0 12 178 251 251 178 12 0 0 0 0 0\n 0 0 0 0 0 105 253 254 254 253 105 0 0 0 0 0\n 0 0 0 0 1 126 253 255 255 253 126 1 0 0 0 0\n 0 0 0 0 1 127 253 255 255 253 127 1 0 0 0 0\n 0 0 1 1 2 127 254 255 255 254 127 2 1 1 0 0\n 12 105 126 127 127 191 254 255 255 254 191 127 127 126 105 12\n 178 253 253 253 254 254 254 255 255 254 254 254 253 253 253 178\n 251 254 255 255 255 255 255 255 255 255 255 255 255 255 254 251\n 251 254 255 255 255 255 255 255 255 255 255 255 255 255 254 251\n 178 253 253 253 254 254 254 255 255 254 254 254 253 253 253 178\n 12 105 126 127 127 191 254 255 255 254 191 127 127 126 105 12\n 0 0 1 1 2 127 254 255 255 254 127 2 1 1 0 0\n 0 0 0 0 1 127 253 255 255 253 127 1 0 0 0 0\n 0 0 0 0 1 126 253 255 255 253 126 1 0 0 0 0\n 0 0 0 0 0 105 253 254 254 253 105 0 0 0 0 0\n 0 0 0 0 0 12 178 251 251 178 12 0 0 0 0 0];\n \n case 'del'\n c = [...\n 1 65 217 248 166 13 0 0 0 0 13 166 248 217 66 1\n 65 243 254 254 253 190 12 0 0 12 190 253 254 254 244 66\n 217 254 254 255 254 253 190 13 13 190 253 254 255 254 254 217\n 248 254 255 255 255 254 253 191 191 253 254 255 255 255 254 248\n 166 253 254 255 255 255 254 254 254 254 255 255 255 254 253 166\n 13 190 253 254 255 255 255 255 255 255 255 255 254 253 190 13\n 0 12 190 253 254 255 255 255 255 255 255 254 253 190 12 0\n 0 0 13 191 254 255 255 255 255 255 255 254 191 13 0 0\n 0 0 13 191 254 255 255 255 255 255 255 254 191 13 0 0\n 0 12 190 253 254 255 255 255 255 255 255 254 253 190 12 0\n 13 190 253 254 255 255 255 255 255 255 255 255 254 253 190 13\n 166 253 254 255 255 255 254 254 254 254 255 255 255 254 253 166\n 248 254 255 255 255 254 253 191 191 253 254 255 255 255 254 248\n 217 254 254 255 254 253 190 13 13 190 253 254 255 254 254 217\n 66 244 254 254 253 190 12 0 0 12 190 253 254 254 244 66\n 1 66 217 248 166 13 0 0 0 0 13 166 248 217 66 1];\n case 'export'\n c = [ ...\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 96 255 255 255 255 255 255 255 0\n 0 0 0 0 0 0 0 0 96 255 255 255 255 255 255 0\n 0 0 0 0 0 0 0 0 0 191 255 255 255 255 255 0\n 63 255 255 255 255 255 175 16 159 255 255 255 255 255 255 0\n 255 255 255 255 255 239 64 159 255 255 255 255 255 255 255 0\n 255 255 63 0 0 16 207 255 255 255 255 255 159 255 255 0\n 255 255 0 0 16 207 255 255 255 255 255 96 0 96 255 0\n 255 255 0 0 80 255 255 255 255 255 96 0 0 0 80 0\n 255 255 0 0 0 96 255 255 255 96 96 64 0 0 0 0\n 255 255 0 0 0 0 96 255 96 80 255 255 0 0 0 0\n 255 255 0 0 0 0 0 0 0 0 255 255 0 0 0 0\n 255 255 0 0 0 0 0 32 0 0 255 255 0 0 0 0\n 255 255 63 0 0 0 0 0 0 63 255 255 0 0 0 0\n 255 255 255 255 255 255 255 255 255 255 255 255 0 0 0 0\n 63 255 255 255 255 255 255 255 255 255 255 63 0 0 0 0];\n\n \nend\nc(c<=18) = nan;\nc = double(c)/255;\nc(c==0) = nan;\nc = 1-c;\n\nc = repmat(c,1,1,3);\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "STREAMobj2cell.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/STREAMobj2cell.m", "size": 11145, "source_encoding": "utf_8", "md5": "2c3e536a80b6350646f0a5c4f1e78576", "text": "function [CS,locS,order] = STREAMobj2cell(S,ref,n)\n\n%STREAMOBJ2CELL convert instance of STREAMobj to cell array of stream objects\n%\n% Syntax\n%\n% CS = STREAMobj2cell(S)\n% CS = STREAMobj2cell(S,'outlets')\n% CS = STREAMobj2cell(S,'tributaries')\n% CS = STREAMobj2cell(S,'channelheads')\n% CS = STREAMobj2cell(S,'segments')\n% CS = STREAMobj2cell(S,'outlets',n)\n% CS = STREAMobj2cell(S,'segments',seglength)\n% CS = STREAMobj2cell(S,'labels',labels)\n% CS = STREAMobj2cell(S,'split',ix)\n% CS = STREAMobj2cell(S,'split',P)\n% [CS,locS] = ...\n% [CS,locS,order] = STREAMobj2cell(S,'tributaries');\n%\n% Description\n%\n% STREAMobj2cell divides a STREAMobj into a number of STREAMobj stored\n% in a cell array. \n%\n% STREAMobj2cell(S,'outlets') divides a STREAMobj into its strongly\n% connected components. This means that individual STREAMobjs are\n% derived as individual trees of the stream network, i.e. individual\n% drainage basins. This is the default. In this case, CS has as many\n% elements as there are outlets in the stream network. \n%\n% STREAMobj2cell(S,'outlets',n) takes the n largest connected \n% components and stores these in the cell array CS. In this case, CS\n% has n elements.\n% \n% STREAMobj2cell(S,'channelheads') derives individual STREAMobj as\n% single streams emanating from each channelhead. In this case, CS has\n% as many elements as there are channelheads in the stream network.\n%\n% STREAMobj2cell(S,'tributaries') derives individual STREAMobj as\n% tributaries. A stream is a tributary until it reaches a stream with a \n% longer downstream flow distance. \n%\n% STREAMobj2cell(S,'segments') splits the stream network into\n% individual reaches. By default, the maximum reach length is 20 the\n% cellsize. A third arguments controls the segment length. Note that\n% the network is always split at river junctions.\n%\n% STREAMobj2cell(S,'labels',labels) takes a node-attribute list with\n% labels as third input argument. Nodes with common labels will be\n% placed into the same element in CS.\n%\n% STREAMobj2cell(S,'split',ix) splits the stream network at cells with\n% the linear index ix. \n%\n% STREAMobj2cell(S,'split',P) takes an instance of PPS and splits the\n% stream network S at points stored in P. Ideally, the underlying\n% stream network in P should be S.\n% \n% Input arguments\n%\n% S instance of STREAMobj\n% ref reference for deriving individual STREAMobj. Either \n% 'outlets' (default) or 'channelheads', or 'tributaries', \n% or 'segments'.\n% n if ref is 'outlets', n determines the number of n largest \n% trees to be placed in elements of CS.\n% seglength maximum segment length if ref is 'segments'\n% ix linear index at which the stream network is split. The\n% cells with the linear index ix must be part of the stream\n% network\n%\n% Output arguments\n%\n% CS cell array with elements of CS being instances of STREAMobj\n% locS cell array with linear indices into node attribute lists of S\n% order output argument only if ref is set to 'tributaries'. Vector\n% with numel(CS) elements where each element refers to an order \n% of the tributaries. \n%\n% Example 1: Place stream networks of individual basins into a cell array\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','carve');\n% S = STREAMobj(FD,'minarea',1000);\n% z = getnal(S,DEM);\n% [CS,locS] = STREAMobj2cell(S);\n% plotdz(CS{21},z(locS{21}))\n%\n% Example 2: Create random river segments and place them in a cell array\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S,1);\n% P = PPS(S,'rpois',0.0001,'z',DEM);\n% plot(P)\n% CS = STREAMobj2cell(S,'split',P);\n% figure;\n% hold on; cellfun(@plot,CS)\n%\n% See also: FLOWobj2cell, STREAMobj/split, PPS\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 11. March, 2022\n\nif nargin == 1\n ref = 'outlets';\n getall = true;\n n = inf;\nelseif nargin == 2\n ref = validatestring(ref,{'outlets','channelheads','tributaries','segments'},'STREAMobj2cell','ref',2);\n getall = true;\n n = inf;\n seglength = 20.*S.cellsize;\nelseif nargin == 3\n ref = validatestring(ref,{'outlets','segments','labels','split'},'STREAMobj2cell','ref',2);\n switch ref\n case {'outlets','segments'}\n validateattributes(n,{'numeric'},{'>',1},'STREAMobj2cell','n',3);\n case 'labels'\n if ~isnal(S,n)\n error('Array must be a node attribute list')\n end\n end\n getall = false;\n seglength = n;\nend\n\nswitch lower(ref)\n case 'outlets'\n \n nrc = numel(S.x);\n M = sparse(double(S.ix),double(S.ixc),true,nrc,nrc);\n \n [~,p,~,r] = dmperm(M | M' | speye(nrc));\n \n nc = length(r) - 1;\n if getall || nc < n\n % label matrix\n L = zeros(nrc,1);\n for tt = 1:nc\n L(p(r(tt):r(tt+1)-1)) = tt;\n end\n else\n nc = n;\n L = zeros(nrc,1)+nc;\n \n [~,dd] = sort(diff(r),'descend');\n \n counter = 1;\n\n for tt = dd(1:nc) %1:min(nc,k);\n L(p(r(tt):r(tt+1)-1)) = counter;\n counter = counter + 1;\n end\n \n end\n \n % put each individual tree into an own element in CS.\n CS = cell(1,nc);\n \n % adapt new STREAMobj to the reduced network\n LL = L;\n \n if nargout == 2\n locS = cell(1,nc);\n end\n \n for r = 1:nc\n CS{r} = S;\n L = LL==r;\n I = L(CS{r}.ix);\n CS{r}.ix = CS{r}.ix(I);\n CS{r}.ixc = CS{r}.ixc(I);\n \n IX = cumsum(L);\n CS{r}.ix = IX(CS{r}.ix);\n CS{r}.ixc = IX(CS{r}.ixc);\n \n CS{r}.x = CS{r}.x(L);\n CS{r}.y = CS{r}.y(L);\n CS{r}.IXgrid = CS{r}.IXgrid(L);\n \n if nargout == 2\n locS{r} = find(L);\n end\n \n \n end\n \n \n \n case 'channelheads'\n ch = streampoi(S,'channelheads','logical');\n ixcix = zeros(numel(S.IXgrid),1);\n ixcix(S.ix) = 1:numel(S.ix);\n \n ixchannel = find(ch);\n nc = numel(ixchannel);\n \n CS = cell(1,nc);\n if nargout == 2\n locS = cell(1,nc);\n end\n for r = 1:nc\n IX = ixchannel(r);\n \n c = 1;\n while ixcix(IX) ~= 0\n c = c+1;\n IX(c) = S.ixc(ixcix(IX(end)));\n end\n \n L = false(size(S.IXgrid));\n L(IX) = true;\n \n % adapt new STREAMobj to the reduced network\n \n CS{r} = S;\n I = L(CS{r}.ix);\n CS{r}.ix = CS{r}.ix(I);\n CS{r}.ixc = CS{r}.ixc(I);\n \n IX = cumsum(L);\n CS{r}.ix = IX(CS{r}.ix);\n CS{r}.ixc = IX(CS{r}.ixc);\n \n CS{r}.x = CS{r}.x(L);\n CS{r}.y = CS{r}.y(L);\n CS{r}.IXgrid = CS{r}.IXgrid(L);\n \n if nargout == 2\n locS{r} = find(L);\n end\n \n \n \n end\n \n case 'tributaries'\n if nargout < 3\n CS = tributaries(S);\n else\n CS = tributariesinclorder(S);\n order = CS(2:2:end);\n order = horzcat(order{:});\n CS = CS(1:2:end);\n end\n \n if nargout >= 2\n locS = cell(size(CS));\n for r = 1:numel(CS)\n [~,locS{r}] = ismember(CS{r}.IXgrid,S.IXgrid);\n end\n end\n \n return\n \n case {'segments','labels'}\n \n switch ref\n case 'segments'\n lab = labelreach(S,'seglength',seglength);\n case 'labels'\n [~,~,lab] = unique(seglength);\n end\n nc = max(lab);\n CS = cell(1,nc);\n if nargout == 1\n parfor r = 1:numel(CS)\n CS{r} = subgraphix(S,lab==r);\n end\n else\n locS = cell(1,nc);\n parfor r = 1:numel(CS)\n [CS{r},locS{r}] = subgraphix(S,lab==r);\n end\n end\n \n case 'split'\n \n if isa(n,'PPS')\n n = n.S.IXgrid(n.PP);\n end\n \n \n ix = n;\n ix = unique(ix);\n [I,locb] = ismember(S.IXgrid,ix);\n \n % Remove outlet pixels if they are set to true\n outlets = streampoi(S,'outlet','logical');\n I(outlets) = false;\n \n I2 = false(size(I));\n I2(S.ix) = I(S.ixc);\n \n I = I2;\n\n I(outlets) = true;\n I(streampoi(S,'chan','logical')) = false;\n \n label = zeros(size(S.x));\n label(I) = 1:nnz(I);\n \n for r = numel(S.ix):-1:1\n if label(S.ix(r)) == 0\n label(S.ix(r)) = label(S.ixc(r));\n end\n end\n \n if nargout == 1\n CS = STREAMobj2cell(S,'label',label);\n else\n [CS,locS] = STREAMobj2cell(S,'label',label);\n end\n return \nend\n\n% check for validity of Ss\nvalid = true(1,nc);\nfor r = 1:nc\n if numel(CS{r}.x) == 1\n valid(r) = false;\n end\nend\nCS = CS(valid);\n\nif nargout == 2\n locS = locS(valid);\nend\nend\n\n\n%% Recursively scan for tributaries\nfunction Ctribs = tributaries(S)\n% Recursive extraction of tributaries\n\n\nC = STREAMobj2cell(S);\nCtribs = cell(0);\n\nfor r = 1:numel(C)\n St = trunk(C{r});\n S2 = modify(C{r},'tributaryto2',St);\n if isempty(S2.ix)\n % do nothing\n Ctribs = [Ctribs {St}];\n else\n Ctribs = [Ctribs {St} tributaries(S2)];\n end\nend\nend\n\n\n\nfunction Ctribs = tributariesinclorder(S,orderin)\n% Recursive extraction of tributaries with order\n\n\nC = STREAMobj2cell(S);\nCtribs = cell(0);\n\nif nargin == 1\n orderin = 1;\nend\n \n\nfor r = 1:numel(C)\n St = trunk(C{r});\n S2 = modify(C{r},'tributaryto2',St);\n if isempty(S2.ix)\n % do nothing\n Ctribs = [Ctribs {St orderin}];\n else\n Ctribs = [Ctribs {St orderin} tributariesinclorder(S2, orderin+1)];\n end\nend\nend\n\nfunction [S,locb] = subgraphix(S,nal)\n\n\nif all(nal)\n % do nothing\n return\nend\n\nif nargout == 2\n IXgrid_old = S.IXgrid;\nend\n\nI = nal(S.ix);\n\nS.ix = S.ix(I);\nS.ixc = S.ixc(I);\n\n% nal = nal;\nnal(S.ixc) = true;\nIX = cumsum(nal);\n\nS.ix = IX(S.ix);\nS.ixc = IX(S.ixc);\n\nS.x = S.x(nal);\nS.y = S.y(nal);\nS.IXgrid = S.IXgrid(nal);\n\nif nargout == 2\n [~,locb] = ismember(S.IXgrid,IXgrid_old);\nend\n\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "crsapp.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/crsapp.m", "size": 9021, "source_encoding": "utf_8", "md5": "2e3923689f7f7f669f2e50fc615f2557", "text": "function crsapp(S,DEM)\n\n%CRSAPP interactive smoothing of river long profiles\n%\n% Syntax\n%\n% crsapp(S,DEM)\n%\n% Description\n%\n% CRSAPP is an interactive tool to visually assess the results of the\n% function STREAMobj/crs. You can export the results and the parameters\n% to the workspace.\n%\n% The graphical user interface allows you to adjust the crs-parameter\n% K, tau, and mingradient with a number of sliders. The K-slider\n% adjusts the degree of smoothing and uses a logarithmic scaling.\n% Common values range between 1 and 10. mingradient adjust the minimum\n% gradient that a profile must go downward in downstream directions.\n% Choose values so that they do not exceed the true downstream\n% gradients. tau-values range between 0.0001 and 0.9999 and refer to\n% the quantile along which the smoothed profile should run along the\n% measured profile.\n%\n% Input parameters\n%\n% S STREAMobj\n% DEM digital elevation model (GRIDobj)\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','carve');\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S);\n% crsapp(S,DEM); \n%\n% References\n%\n% Schwanghart, W., Scherler, D., 2017. Bumps in river profiles: \n% uncertainty assessment and smoothing using quantile regression \n% techniques. Earth Surface Dynamics, 5, 821-839. \n% [DOI: 10.5194/esurf-5-821-2017]\n%\n% See also: STREAMobj/crs, STREAMobj/quantcarve, STREAMobj/smooth\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 17. August, 2017\n\n% get node attribute list with elevation values\nif isa(DEM,'GRIDobj')\n validatealignment(S,DEM);\n z = getnal(S,DEM);\nelseif isnal(S,DEM)\n z = DEM;\nelse\n error('Imcompatible format of second input argument.')\nend\n\nparams = struct();\n\nfhandle = figure('Name','crsapp');\n\n%% Controls\nhp = uipanel('FontSize',12,...\n 'BackgroundColor','white',...\n 'Position',[0 0 0.3 1]);\nmt = uicontrol(hp,'Style','text',...\n 'String','controls',...\n 'HorizontalAlignment','left',...\n 'String','Controls',...\n 'Units','normalized',...\n 'FontWeight','bold',...\n 'Position',[0 .96 1 .04]);\n%% K \ns = sprintf('Larger K will increasingly smooth the profiles.'); \ncKtext = uicontrol(hp,'Style','text',...\n 'HorizontalAlignment','left',...\n 'String','K = 1',...\n 'Units','normalized',...\n 'Position',[0 .85 1 .05],...\n 'TooltipString',s);\ncK = uicontrol(hp,'Style','slider',...\n 'Units','normalized',...\n 'Position',[0 .9 1 .045],...\n 'Min',-1,...\n 'Max',4,...\n 'Value',0,...\n 'SliderStep',[0.01 0.1],...\n 'Callback',@display_Kslider_value,...\n 'TooltipString',s); \n\n%% Gradient \ns = sprintf('Activate downstream monotonicity constraint.'); \ncng = uicontrol(hp,'Style','checkbox',...\n 'String','Activate downstream monotonicity constraint',...\n 'Units','normalized',...\n 'Position',[0 .8 1 .045],...\n 'TooltipString',s,...\n 'Value',1,...\n 'Callback',@activateGradientMonotinicity); \ns = sprintf('Imposes a minimum downstream gradient to the profile.'); \ncmgtext = uicontrol(hp,'Style','text',...\n 'HorizontalAlignment','left',...\n 'String','Minimum gradient = 0',...\n 'Units','normalized',... \n 'Position',[0 .7 1 .05],...\n 'TooltipString',s);\ncmg = uicontrol(hp,'Style','slider',...\n 'Units','normalized',...\n 'Min',0,...\n 'Max',0.04,...\n 'Value',0,...\n 'SliderStep',[0.0001 0.001],...\n 'Position',[0 .75 1 .045],...\n 'Callback',@display_MGslider_value,...\n 'TooltipString',s); \n%% Tau \ns = sprintf('Choose Tau (Quantile between 0 and 1).'); \ncTautext = uicontrol(hp,'Style','text',...\n 'HorizontalAlignment','left',...\n 'String','Tau = 0.5',...\n 'Units','normalized',...\n 'Position',[0 .6 1 .05],...\n 'TooltipString',s);\ncTau = uicontrol(hp,'Style','slider',...\n 'Units','normalized',...\n 'Position',[0 .65 1 .045],...\n 'Min',0.0001,...\n 'Max',0.9999,...\n 'Value',0.5,...\n 'SliderStep',[0.001 0.1],...\n 'Callback',@display_Tauslider_value,...\n 'TooltipString',s); \n\ns = sprintf('Remove curvature penalty at tributary junctions.'); \ncnst = uicontrol(hp,'Style','checkbox',...\n 'String','Knicks at tributary junctions',...\n 'Units','normalized',...\n 'Position',[0 .55 1 .045],...\n 'TooltipString',s); \n \n%% Controls \n% Push button \ns = sprintf('Push to smooth profile.'); \npbh = uicontrol(hp,'Style','pushbutton','String','Calculate now',...\n 'Units','normalized',...\n 'Position',[0 .40 1 .05],...\n 'Callback',@smoothnetwork,...\n 'TooltipString',s); \n%% Plot\nha = uipanel('FontSize',12,...\n 'BackgroundColor','white',...\n 'Position',[.3 0 0.7 1]);\nax = axes('Parent',ha);\nbox(ax,'on');\nhold(ax,'on')\nhlorig = plotdz(S,z,'color',[.4 .4 .4]);\n\nhlsmooth = plot(0,min(z));\nzs = [];\n\n%% Push\n% Push button\ns = sprintf('Export smoothed elevations to the base workspace.'); \npexp = uicontrol(hp,'Style','pushbutton','String','Export node attribute list',...\n 'Units','normalized',...\n 'Position',[0 .35 1 .05],...\n 'Callback',@exportnal,...\n 'Enable','off',...\n 'TooltipString',s); \n% Push button \ns = sprintf('Export parameter settings to the base workspace.'); \npexpp = uicontrol(hp,'Style','pushbutton','String','Export parameters',...\n 'Units','normalized',...\n 'Position',[0 .30 1 .05],...\n 'Callback',@exportparams,...\n 'Enable','off',...\n 'TooltipString',s); \n\nfunction display_MGslider_value(hObject,callbackdata)\n newval = num2str(hObject.Value);\n set(cmgtext,'String',['Minimum gradient = ' newval]);\nend\nfunction display_Kslider_value(hObject,callbackdata)\n newval = num2str(10.^(hObject.Value));\n set(cKtext,'String',['K = ' newval]);\nend\nfunction display_Tauslider_value(hObject,callbackdata)\n newval = num2str(hObject.Value);\n set(cTautext,'String',['Tau = ' newval]);\nend\nfunction activateGradientMonotinicity(hObject,callbackdata)\n newval = hObject.Value;\n if ~newval\n set(cmg,'Enable','off');\n else\n set(cmg,'Enable','on');\n end\nend\nfunction smoothnetwork(hObject,callbackdata)\n set(pbh,'Enable','off','String','Please wait ...');\n set(pexp,'Enable','off')\n set(pexpp,'Enable','off')\n drawnow\n \n params.nonstifftribs = get(cnst,'Value');\n params.K = 10.^get(cK,'Value');\n params.mingradient = get(cmg,'Value');\n params.Tau = get(cTau,'Value');\n \n if ~get(cng,'Value')\n params.mingradient = nan;\n end\n \n assignin('base','params',params);\n \n zs = crs(S,z,params,'split',isempty(gcp('nocreate')));\n if exist('hlsmooth','var')\n delete(hlsmooth)\n end\n hlsmooth = plotdz(S,zs,'color',[1 0 0]);\n drawnow\n \n set(pbh,'Enable','on','String','Calculate now');\n set(pexp,'Enable','on')\n set(pexpp,'Enable','on')\nend\n\nfunction exportnal(hObject,callbackdata)\n \n if ~isempty(zs)\n \n prompt = {'Enter variable name:'};\n title = 'Export';\n lines = 1;\n def = {'zs'};\n answer = inputdlg(prompt, title, lines, def);\n if ~isempty(answer) && isvarname(answer{1})\n assignin('base',answer{1},zs);\n else\n return\n end\n else\n warndlg('No node attribute list available for export.');\n end\nend\n\nfunction exportparams(hObject,callbackdata)\n if isfield(params,'Tau')\n \n \n prompt = {'Enter variable name:'};\n title = 'Export';\n lines = 1;\n def = {'p'};\n answer = inputdlg(prompt, title, lines, def);\n if ~isempty(answer) && isvarname(answer{1})\n assignin('base',answer{1},params);\n else\n return\n end\n else\n warndlg('No node parameters available for export.');\n end\nend\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "knickpointfinder.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/knickpointfinder.m", "size": 9830, "source_encoding": "utf_8", "md5": "0874c8247d46fd1a27df15a28216ed92", "text": "function [zs,kp] = knickpointfinder(S,DEM,varargin)\n\n%KNICKPOINTFINDER find knickpoints in river profiles\n%\n% Syntax\n%\n% [zk,kp] = knickpointfinder(S,DEM)\n% [zk,kp] = knickpointfinder(S,z)\n% [zk,kp] = knickpointfinder(...,pn,pv,...)\n%\n% Description\n%\n% Rivers that adjust to changing base levels or have diverse\n% lithologies often feature knickzones, i.e. pronounced convex sections\n% that separate the otherwise concave equilibrium profile. The profile\n% should be monotoneously decreasing (see imposemin, quantcarve, crs).\n%\n% This function extracts knickpoints, i.e. sharp convex sections in the\n% river profile. This is accomplished by an algorithm that adjusts a\n% strictly concave upward profile to an actual profile in the DEM or\n% node-attribute list z. The algorithm iteratively relaxes the\n% concavity constraint at those nodes in the river profile that have\n% the largest elevation offsets between the strictly concave and actual\n% profile until the offset falls below a user-defined tolerance.\n%\n% The function returns the idealized profile zk and outputs the\n% locations of the knickpoints in a structure array kp.\n%\n% Input parameters\n%\n% S STREAMobj\n% DEM Digital elevation model (GRIDobj)\n% z node-attribute list with elevations\n% \n% Parameter name/value pairs {default}\n%\n% 'split' {true} or false. If set to true, quantcarve will\n% split the network into individual drainage basins and \n% process them in parallel.\n% 'tol' tolerance (scalar or node attribute list). Setting \n% tol to inf will return a lower concave envelope of \n% river profile elevations\n% 'verbose' {true} or false. Toggle verbose output to the command\n% window\n% 'plot' {false} or true. Plots the process. Only possible if\n% 'split' is set to false.\n%\n% Output parameters\n%\n% zk node attribute list of river profile elevations fitted to \n% the actual profile\n% kp structure array \n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','carve');\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S);\n% zs = quantcarve(S,DEM,.5,'split',false);\n% figure\n% [zk,kp] = knickpointfinder(S,zs,'split',false,'plot',true,'tol',20);\n% hold on\n% scatter(kp.distance,kp.z,kp.dz,'sk','MarkerFaceColor','r')\n% hold off\n%\n% See also: STREAMobj/quantcarve, STREAMobj/crs\n% \n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 25. February, 2018\n\n% check and parse inputs\nnarginchk(2,inf)\n\np = inputParser;\np.FunctionName = 'STREAMobj/knickpointfinder';\naddParameter(p,'split',1);\naddParameter(p,'knickpoints',[]);\naddParameter(p,'plot',true);\naddParameter(p,'tol',100);\naddParameter(p,'verbose',true);\naddParameter(p,'toltype','range');\nparse(p,varargin{:});\n\nif p.Results.split \n plt = false;\n verbose = false;\nelse\n plt = p.Results.plot;\n verbose = p.Results.verbose;\nend\n\n% get node attribute list with elevation values\nif isa(DEM,'GRIDobj')\n validatealignment(S,DEM);\n z = getnal(S,DEM);\nelseif isnal(S,DEM)\n z = DEM;\nelse\n error('Imcompatible format of second input argument')\nend\n\nif any(isnan(z))\n error('DEM or z may not contain any NaNs')\nend\nz = double(z);\n\n% ensure downstream decreasing profiles\nz = imposemin(S,z);\n\n\n%% Run in parallel ------------------------------------------------------\n% The code can run in parallel by distributing individual catchments to\n% workers. This involves some work.\n\nif p.Results.split\n params = p.Results;\n params.split = false;\n params.plot = false;\n [CS,locS] = STREAMobj2cell(S);\n \n tol = params.tol;\n TOL = cell(numel(CS),1);\n if ~isscalar(tol) \n for r = 1:numel(CS)\n TOL{r} = tol(locS{r},:);\n end\n else\n [TOL{:}] = deal(tol);\n end\n params = rmfield(params,'tol');\n \n Cz = cellfun(@(ix) z(ix),locS,'UniformOutput',false);\n Czs = cell(size(CS));\n Ckp = cell(size(CS));\n n = numel(CS);\n\n parfor r = 1:n\n [Czs{r},Ckp{r}] = knickpointfinder(CS{r},Cz{r},'tol',TOL{r},params);\n end\n \n zs = nan(size(z));\n kp.n = 0;\n kp.x = [];\n kp.y = [];\n kp.distance = [];\n kp.z = [];\n kp.IXgrid = [];\n kp.order = [];\n kp.dz = []; \n kp.nal = false(size(z));\n \n for r = 1:numel(CS)\n zs(locS{r}) = Czs{r};\n if Ckp{r}.n > 0\n kp.nal(locS{r}) = Ckp{r}.nal;\n \n kp.n = Ckp{r}.n+kp.n;\n kp.x = [kp.x; Ckp{r}.x];\n kp.y = [kp.y; Ckp{r}.y];\n kp.distance = [kp.distance; Ckp{r}.distance];\n kp.z = [kp.z; Ckp{r}.z];\n kp.IXgrid = [kp.IXgrid; Ckp{r}.IXgrid];\n kp.order = [kp.order; Ckp{r}.order];\n kp.dz = [kp.dz; Ckp{r}.dz];\n end\n\n end\n return\nend\n\n% Parallel computing goes until here. ------------------------------------\n\n%% Knickpoint identification starts here\n\n% upstream distance\nd = S.distance;\n% nr of nodes\nnr = numel(S.IXgrid);\n\n%% Structure array with output\nif isempty(p.Results.knickpoints)\n kp.n = 0;\n kp.x = [];\n kp.y = [];\n kp.distance = [];\n kp.z = [];\n kp.IXgrid = [];\n kp.order = [];\n kp.dz = [];\n kp.nal = [];\nelse\n kp = p.Results.knickpoints;\nend\n\n%% Find knickpoints\nCC = sparse(S.ix,S.ixc,true,nr,nr);\nCC = speye(nr,nr) | CC | CC';\n\nkeepgoing = true;\ncounter = 0;\n\nif plt\n hh = plotdz(S,z,'color',[.6 .6 .6],'LineWidth',1.5);drawnow\n set(gcf,'color','w')\n hold on\n drawnow\n %if counter == 0\n %gif('knickpointfinder.gif','DelayTime',0.5,'LoopCount',inf,'frame',gcf)\n %end\n \nend\n\nif verbose\n disp([datestr(now) ' -- Starting']);\nend\n\ntoltype = validatestring(p.Results.toltype,{'range','lowerbound'});\n\n\nwhile keepgoing\n \n counter = counter+1;\n \n zs = lowerenv(S,z,kp.nal);\n\n if ~isscalar(p.Results.tol) && strcmp(toltype,'lowerbound')\n II = zs < p.Results.tol(:,1);\n else\n II = true(size(zs));\n end\n \n if counter == 1\n \n [dz,ix] = max((z-zs).*II);\n if ~isscalar(p.Results.tol)\n I = dz>0;\n else\n I = dz >= p.Results.tol;\n end\n \n else\n % calculate connected components separated by knickpoints\n CC(ix,:) = 0;\n CC(:,ix) = 0;\n CC = CC | speye(nr,nr);\n [~,pp,~,r] = dmperm(CC);\n nc = length(r) - 1;\n \n % find maximum in each connected component\n dztemp = zeros(nc,1);\n ixtemp = zeros(nc,1);\n for tt = 1:nc\n ixx = pp(r(tt):r(tt+1)-1);\n \n [dztemp(tt),ixtt] = max((z(ixx)-zs(ixx)).*II(ixx));\n ixtemp(tt) = ixx(ixtt);\n end\n \n switch p.Results.toltype\n case 'lowerbound'\n I = dztemp > 0;\n otherwise \n if isscalar(p.Results.tol)\n I = dztemp >= p.Results.tol;\n\n else\n I = dztemp >= p.Results.tol(ixtemp);\n end\n end\n dz = dztemp(I);\n ix = ixtemp(I); \n end\n \n if ~(any(I))\n break\n \n end\n \n IX = S.IXgrid(ix);\n \n kp.n = kp.n + numel(IX);\n kp.x = [kp.x;S.x(ix)];\n kp.y = [kp.y;S.y(ix)];\n kp.z = [kp.z; z(ix)];\n kp.distance = [kp.distance; d(ix)];\n kp.IXgrid = [kp.IXgrid;IX];\n kp.order = [kp.order; repmat(counter,numel(IX),1)];\n kp.dz = [kp.dz;dz];\n kp.nal = ismember(S.IXgrid,kp.IXgrid);\n \n % plot\n if plt\n if exist('hh2','var')\n delete(hh2)\n end\n hh2 = plotdz(S,zs,'color','k');\n drawnow\n %gif\n end\n if verbose\n disp([datestr(now) ' -- Iteration: ' num2str(counter) ', ' num2str(kp.n) ' knickpoints, max dz: ' num2str(max(dz))]);\n end\nend\n\nif plt\n hold off\nend\n\nend \n\n%% Subfunctions \n \nfunction z = lowerenv(S,z,ix)\n\n% lower envelope of a channel length profile\n%\n% Syntax\n%\n% zl = lowerenv(S,z)\n% zl = lowerenv(S,z,kn)\n%\n% Description\n%\n% lowerenv returns the lower envelope, i.e. the lower convex hull of a\n% length profile given by the stream network S and elevation z.\n%\n% Input arguments\n%\n% S STREAMobj\n% z elevation (node attribute list)\n% kn logical vector (node attribute list) with knickpoints\n%\n% \n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 10. March, 2017\n\n\n\nkn = false(size(S.x));\nif nargin == 3;\n if isempty(ix);\n elseif islogical(ix);\n kn = ix;\n else\n kn(ix) = true;\n end\nend\n\n% nals\nd = distance(S);\ntrib = streampoi(S,'confl','logical');\n\nnrc = numel(S.x);\nix = S.ix;\nixc = S.ixc;\n\nixcix = zeros(nrc,1);\nixcix(ix) = 1:numel(ix);\n\nonenvelope = true(nrc,1);\n\nfor r = numel(S.ixc):-1:1;\n s = ix(r);\n ss = ixc(r);\n \n if onenvelope(s) || trib(ss)\n IX = allpred(ix,ixc,s,nrc,kn,r);\n s = ss;\n if isempty(IX)\n continue\n end\n gg = z(IX)-z(s);\n dd = d(IX)-d(s);\n gg = gg./dd;\n [~,ii] = sortrows([gg dd],[1 -2]); \n IX = IX(ii(1));\n g = gg(ii(1));\n \n t = IX;\n ixcix(ss) = 0;\n while ixcix(t) ~= 0\n t2 = ixc(ixcix(t));\n z(t2) = z(t)-g.*(d(t)-d(t2));\n onenvelope(t2) = false;\n ixcix(t) = 0;\n t = t2;\n \n end\n end\n \nend\n\nend\n\n\n function IX = allpred(ix,ixc,s,nr,kn,startix) \n I = false(nr,1);\n I(s) = true;\n for r = startix:-1:1\n I(ix(r)) = (I(ix(r)) | I(ixc(r))) & ~kn(ixc(r)) ;\n end\n IX = find(I);\n end\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "modify.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/modify.m", "size": 20160, "source_encoding": "utf_8", "md5": "5c159852f8d743dab916ca0ed4cc47f7", "text": "function [Sout,nalix] = modify(S,varargin)\n\n%MODIFY modify instance of STREAMobj to meet user-defined criteria\n%\n% Syntax\n%\n% S2 = modify(S,pn,pv)\n% [S2,nalix] = ...\n%\n% Description\n%\n% The function modify changes the geometry of a stream network to meet\n% different user-defined criteria. See\n%\n% demo_modifystreamnet\n%\n% for an (incomplete) overview of the function's scope. See input\n% arguments below for an overview on the functionality of the function.\n%\n% Input arguments\n%\n% S instance of stream object\n%\n% Parameter name/value pairs (one pn/pv pair is required to run the\n% function)\n%\n% 'streamorder' scalar or string\n% scalar: if you supply a scalar integer x as parameter value, S2\n% contains only streams with order x.\n% string: a string allows you to define a simple relational statement,\n% e.g. '>=3' returns the stream network with streams of streamorder\n% greater or equal than 3. Other commands may be '==5', '<5', etc.\n%\n% 'distance' scalar or [2x1] vector\n% lets you define a minimum and maximum distance from which the stream \n% network starts and ends based on the distances given in S. A scalar is\n% interpreted as minimum upstream distance and a two element vector is\n% interpreted as minimum and maximum upstream distance to which the\n% stream network is cut.\n%\n% 'maxdsdistance' scalar\n% modifies the stream network that only the portion of the network is\n% retained that is within downstream distance of the the channelheads.\n%\n% 'upstreamto' logical GRIDobj, nal or linear index in GRIDobj\n% returns the stream network upstream to true pixels in the logical\n% raster of GRIDobj. Note that, if the grid contains linear features\n% (e.g. a fault), the line should be 4 connected. Use\n% bwmorph(I.Z,'diag') to establish 4-connectivity in a logical raster\n% I.\n%\n% 'downstreamto' logical GRIDobj, nal or linear index in GRIDobj\n% returns the stream network downstream to true pixels in the logical\n% raster of GRIDobj. Note that, if the grid contains linear features\n% (e.g. a fault), the foreground (true pixels) should be 4 connected.\n% Use bwmorph(I.Z,'diag') to establish 4-connectivity in a logical\n% raster I.\n%\n% 'rmconncomps' scalar\n% removes connected components (individual stream 'trees') of the\n% entire network with a maximum distance in map units less than the \n% specified value.\n%\n% 'rmconncomps_ch' scalar\n% removes connected components (individual stream 'trees') that have\n% less or equal the number of channel heads \n%\n% 'rmupstreamtoch' STREAMobj\n% removes nodes from S that are upstream to the channelheads of the\n% supplied STREAMobj.\n%\n% 'rmnodes' STREAMobj \n% removes nodes in S that belong to another stream network S2.\n%\n% 'tributaryto' instance of STREAMobj\n% returns the stream network that is tributary to a stream (network) \n%\n% 'tributaryto2' instance of STREAMobj\n% same as 'tributaryto' but tributaries include the pixel of the\n% receiving stream.\n%\n% 'lefttrib' instance of STREAMobj\n% returns the stream network that is tributary to a stream from the\n% left. For example, modify(S,'lefttrib',trunk(S)) selects the streams\n% in S that are left tributaries to the trunk stream of S.\n%\n% 'righttrib' instance of STREAMobj\n% returns the stream network that is tributary to a stream from the\n% right.\n%\n% 'shrinkfromtop' scalar distance\n% removes parts of the stream network that are within the specified\n% distance from the channelheads.\n%\n% 'clip' n*2 matrix or logical GRIDobj\n% retains those parts of the network that are inside the polygon\n% with vertices defined by the n*2 matrix with x values in the first\n% column and y values in the second column. The function automatically\n% closes the polygon if the first and the last row in the matrix\n% differ.\n%\n% 'interactive' string\n% 'polyselect': plots the stream network and starts a polygon tool \n% to select the stream network of interest.\n% 'outletselect': select a basin based on a manually selected\n% outlet.\n% 'reachselect': select a reach based on two locations on the network\n% 'channelheadselect': select a number of channel heads and derive \n% stream network from them.\n% 'rectselect': like 'polyselect', but with a rectangle\n% 'ellipseselect': like 'polyselect', but with an ellipse\n%\n%\n% Output arguments\n%\n% S2 modified stream network (class: STREAMobj)\n% nalix index into node attribute list nal of S, so that nal2 =\n% nal(nalix)\n%\n% Examples\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','carve');\n% S = STREAMobj(FD,flowacc(FD)>1000);\n%\n% % Extract the stream network that is tributary to the main trunk\n% St = modify(S,'tributaryto',trunk(S));\n% plot(S)\n% hold on\n% plot(St,'r')\n% holf off\n%\n% % Split the stream network into the network downslope and upslope to\n% % the 1200 m contour\n% C = dilate(DEM-1200,ones(3)) > 0 & erode(DEM-1200,ones(3)) < 0;\n% C.Z = bwmorph(C.Z,'skel',inf);\n% C.Z = bwmorph(C.Z,'diag');\n% Su = modify(S,'upstreamto',C);\n% Sl = modify(S,'downstreamto',C);\n% plot(Su)\n% hold on\n% plot(Sl,'r')\n% hold off\n%\n% \n% See also: STREAMobj, STREAMobj/trunk, STREAMobj/subgraph, \n% demo_modifystreamnet\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 4. June, 2019\n\nnarginchk(3,3)\n\n% Parse Inputs\np = inputParser; \np.FunctionName = 'modify';\naddRequired(p,'S',@(x) isa(x,'STREAMobj'));\n\naddParamValue(p,'streamorder',[]);\naddParamValue(p,'distance',[],@(x) isnumeric(x) && numel(x)<=2);\naddParamValue(p,'maxdsdistance',[],@(x) isscalar(x) && x>0);\naddParamValue(p,'interactive',[],@(x) ischar(validatestring(x,{'polyselect','reachselect',...\n 'channelheadselect','rectselect',...\n 'ellipseselect','outletselect'})));\naddParamValue(p,'tributaryto',[],@(x) isa(x,'STREAMobj'));\naddParamValue(p,'tributaryto2',[],@(x) isa(x,'STREAMobj'));\naddParamValue(p,'righttrib',[],@(x) isa(x,'STREAMobj'));\naddParamValue(p,'lefttrib',[],@(x) isa(x,'STREAMobj'));\naddParamValue(p,'shrinkfromtop',[],@(x) isnumeric(x) && isscalar(x) && x>0);\naddParamValue(p,'upstreamto',[],@(x) isa(x,'GRIDobj') || isnumeric(x) || isnal(S,x));\naddParamValue(p,'downstreamto',[],@(x) isa(x,'GRIDobj') || isnumeric(x) || isnal(S,x));\naddParamValue(p,'rmconncomps',[],@(x) isnumeric(x) && x>0 && isscalar(x));\naddParamValue(p,'rmconncomps_ch',[],@(x) isnumeric(x) && x>=0 && isscalar(x));\naddParamValue(p,'rmupstreamtoch',[],@(x) isa(x,'STREAMobj'));\n%addParamValue(p,'between',[],@(x) isnumeric(x) && size(x,2) == 2);\naddParamValue(p,'fromch2IX',[]);\naddParamValue(p,'rmnodes',[]);\naddParamValue(p,'clip',[],@(x) (isnumeric(x) && size(x,2)==2 && size(x,1)>2) || isa(x,'GRIDobj'));\naddParamValue(p,'nal',[],@(x) isnal(S,x));\n\nparse(p,S,varargin{:});\nS = p.Results.S;\n\n\nif ~isempty(p.Results.streamorder)\n%% streamorder \n so = streamorder(S);\n if isnumeric(p.Results.streamorder)\n validateattributes(p.Results.streamorder,{'numeric'},...\n {'scalar','integer','>',0,'<=',max(so)});\n I = so == p.Results.streamorder;\n else\n try\n % expecting relational operator\n sothres = nan;\n counter = 1;\n while isnan(sothres)\n sothres = str2double(p.Results.streamorder(counter+1:end));\n relop = p.Results.streamorder(1:counter);\n counter = counter+1;\n end\n catch ME\n rethrow(ME)\n end\n\n relop = str2func(relop);\n I = relop(so,sothres);\n \n end\n\n\nelseif ~isempty(p.Results.distance)\n%% distance \n d = S.distance;\n maxdist = max(d);\n distrange = p.Results.distance;\n \n \n validateattributes(distrange,{'numeric'},...\n {'>=',0,'<=',maxdist});\n \n if isscalar(distrange)\n distrange(2) = maxdist;\n end\n \n if distrange(2) <= distrange(1)\n error('TopoToolbox:wronginput',...\n 'The minimum distance must not be equal to or greater than the maximum distance');\n end\n \n \n I = d>=distrange(1) & d<=distrange(2); % + norm([S.cellsize S.cellsize]);\n \nelseif ~isempty(p.Results.maxdsdistance)\n%% maximmum downstream distance \n d = distance(S,'min_from_ch');\n I = d <= p.Results.maxdsdistance;\n \nelseif ~isempty(p.Results.upstreamto)\n%% upstream to \n \n II = p.Results.upstreamto;\n \n if isa(II,'GRIDobj')\n \n II = getnal(S,II);\n elseif isnal(S,II)\n II = logical(II); \n else \n % II contains linear indices into the DEM from which S was derived\n [II,locb] = ismember(S.IXgrid,II);\n% if ~all(locb)\n% warning('TopoToolbox:modify','Some linear indices are not located on the stream network') \n% end\n end\n \n% I = false(size(S.x));\n I = II;\n for r = numel(S.ix):-1:1\n I(S.ix(r)) = II(S.ixc(r)) || I(S.ixc(r)) || I(S.ix(r));\n end\n% elseif ~isempty(p.Results.between)\n% %% between\n% M = sparse(S.ix,S.ixc,1,numel(S.x),numel(S.x));\n% G = graph(M,T);\n% ix = p.Results.between;\n% [II,ixs] = ismember(ix,S.IXgrid);\n% if any(II==0)\n% error('All cells must be on the network.')\n% end\n% % sort indices\n% [~,temp] = sort(S.distance(ixs),1,'ascend');\n% ixs = ixs()\n% \n% I = logical(getnal(S));\n% for r = 1:size(ix,1)\n% [II,ixs] = ismember(S.IXgrid,ix(r,:));\n% \n% I(shortestpath(G,ixs))\n% end\n \nelseif ~isempty(p.Results.rmupstreamtoch)\n \n S2 = p.Results.rmupstreamtoch;\n ch = streampoi(S2,'channelhead','logical');\n ch = nal2nal(S,S2,ch,false);\n \n I = ch;\n \n for r = numel(S.ix):-1:1\n I(S.ix(r)) = I(S.ix(r)) || I(S.ixc(r));\n end\n \n I = ~I;\n % retain channelheads in the list\n I(ch) = true;\n \n \nelseif ~isempty(p.Results.downstreamto)\n%% downstream to \n \n II = p.Results.downstreamto;\n \n if isa(II,'GRIDobj')\n \n II = getnal(S,II);\n elseif isnal(S,II)\n II = logical(II); \n else \n % II contains linear indices into the DEM from which S was derived\n [II,locb] = ismember(S.IXgrid,II);\n% if ~all(locb)\n% warning('TopoToolbox:modify','Some linear indices are not located on the stream network') \n% end\n end\n \n \n I = II;\n for r = 1:numel(S.ix)\n I(S.ixc(r)) = II(S.ix(r)) || I(S.ix(r)) || I(S.ixc(r));\n end\n\nelseif ~isempty(p.Results.tributaryto) || ~isempty(p.Results.tributaryto2)\n%% tributary to\n if ~isempty(p.Results.tributaryto)\n Strunk = p.Results.tributaryto;\n else\n Strunk = p.Results.tributaryto2;\n end\n \n II = ismember(S.IXgrid,Strunk.IXgrid);\n I = false(size(S.x));\n \n for r = numel(S.ix):-1:1\n I(S.ix(r)) = (II(S.ixc(r)) || I(S.ixc(r))) && ~II(S.ix(r));\n end\n\n if ~isempty(p.Results.tributaryto2)\n % add trunk stream pixels\n I(S.ixc(II(S.ixc) & ~II(S.ix))) = true;\n end\n\nelseif ~isempty(p.Results.righttrib) || ~isempty(p.Results.lefttrib)\n%% select tributaries from a specified direction \n % calculate directions\n direc = tribdir(S);\n \n if ~isempty(p.Results.righttrib)\n St = p.Results.righttrib;\n val = 1;\n else\n St = p.Results.lefttrib;\n val = -1;\n end\n II = STREAMobj2GRIDobj(St);\n ii = II.Z(S.IXgrid(S.ixc)) & ~II.Z(S.IXgrid(S.ix)) & (direc(S.ix) == val);\n \n I = false(size(S.x));\n for r = numel(S.ix):-1:1\n I(S.ix(r)) = I(S.ixc(r)) || ii(r);\n end\n \nelseif ~isempty(p.Results.shrinkfromtop)\n%% shrink from top\n d = distance(S,'max_from_ch');\n I = d > p.Results.shrinkfromtop;\nelseif ~isempty(p.Results.fromch2IX)\n ch = streampoi(S,'channelhead','logical');\n en = ismember(S.IXgrid,p.Results.fromch2IX);\n \n pp = en;\n for r = numel(S.ix):-1:1\n if pp(S.ixc(r))\n pp(S.ix(r)) = true;\n end\n end\n \n for r = 1:numel(S.ix)\n if ch(S.ix(r)) && ~en(S.ixc(r)) && pp(S.ix(r))\n ch(S.ixc(r)) = true;\n end\n end\n \n I = ch;\n \nelseif ~isempty(p.Results.rmconncomps)\n%% remove connected conn comps\n cc = conncomps(S);\n d = S.distance;\n md = find(accumarray(cc,d,[max(cc) 1],@max) > p.Results.rmconncomps);\n I = ismember(cc,md);\n\nelseif ~isempty(p.Results.rmconncomps_ch)\n%% remove connected conn comps\n cc = conncomps(S);\n d = distance(S,'nr_of_ch');\n md = find(accumarray(cc,d,[max(cc) 1],@max) > p.Results.rmconncomps_ch);\n I = ismember(cc,md);\n \nelseif ~isempty(p.Results.rmnodes)\n % check if empty S is supplied\n if isempty(p.Results.rmnodes.IXgrid)\n I = getnal(S) == 0;\n else\n I = ~ismember(S.IXgrid,p.Results.rmnodes.IXgrid);\n end\n\nelseif ~isempty(p.Results.nal)\n I = p.Results.nal;\n\nelseif ~isempty(p.Results.clip)\n if isa(p.Results.clip,'GRIDobj')\n mask = p.Results.clip;\n I = mask.Z(S.IXgrid) > 0;\n else\n pos = p.Results.clip;\n if ~isequal(pos(end,:),pos(1,:))\n pos(end+1,:) = pos(1,:);\n end\n I = inpolygon(S.x,S.y,pos(:,1),pos(:,2));\n end\n\nelseif ~isempty(p.Results.interactive)\n%% interactive \n% figure\n plot(S,'k'); axis equal\n ax = gca;\n % expand axes\n lims = axis;\n xlim(ax,[lims(1)-(lims(2)-lims(1))/20 lims(2)+(lims(2)-lims(1))/20])\n ylim(ax,[lims(3)-(lims(4)-lims(3))/20 lims(4)+(lims(4)-lims(3))/20])\n \n meth = validatestring(p.Results.interactive,...\n {'polyselect','reachselect','channelheadselect',...\n 'rectselect','ellipseselect','outletselect'});\n switch meth\n case 'outletselect'\n title('map outlet and press key to finalize')\n hold on\n htemp = plot(ax,[],[]);\n hp = impoint('PositionConstraintFcn',@getnearest);\n addNewPositionCallback(hp,@drawbasin);\n setPosition(hp,getPosition(hp));\n set(gcf,'WindowKeyPressFcn',@(k,l) uiresume);\n pos = wait(hp);\n% pos = getPosition(hp);\n% \n hold off\n delete(hp);\n I = S.x==pos(1) & S.y==pos(2);\n for r = numel(S.ixc):-1:1\n I(S.ix(r)) = I(S.ixc(r)) || I(S.ix(r));\n end\n \n \n case 'channelheadselect'\n title('map channel heads and enter any key to finalize')\n hold on\n xy = streampoi(S,'channelhead','xy');\n scatter(xy(:,1),xy(:,2));\n hold off\n set(gcf,'WindowKeyPressFcn',@(k,l) uiresume);\n xys = [];\n while true\n try\n hpstart = impoint('PositionConstraintFcn',@getnearestchanhead); \n setColor(hpstart,[0 1 0])\n setPosition(hpstart,getPosition(hpstart))\n xys = [xys; getPosition(hpstart)]; %#ok\n catch\n break\n end\n end\n \n if ~isempty(xys)\n I = ismember([S.x S.y],xys,'rows');\n else\n error('You must choose at least one channelhead')\n end\n \n for r = 1:numel(S.ix)\n I(S.ixc(r)) = I(S.ix(r)) || I(S.ixc(r));\n end\n \n case {'polyselect', 'rectselect', 'ellipseselect'}\n switch meth\n case 'polyselect'\n title('create a polygon and double-click to finalize')\n try\n hp = drawpolygon;\n pos = hp.Position;\n catch\n hp = impoly;\n pos = wait(hp);\n end\n pos(end+1,:) = pos(1,:);\n case 'ellipseselect'\n title('create a ellipse and double-click to finalize')\n try\n hp = drawellipse;\n pos = hp.Vertices;\n catch\n hp = imellipse;\n pos = wait(hp);\n pos = getVertices(hp);\n end\n \n pos(end+1,:) = pos(1,:);\n case 'rectselect'\n title('create a rectangle and double-click to finalize')\n hp = imrect;\n pos = wait(hp);\n pos = [pos(1) pos(2); ...\n pos(1)+pos(3) pos(2); ...\n pos(1)+pos(3) pos(2)+pos(4);...\n pos(1) pos(2)+pos(4);...\n pos(1) pos(2)];\n end\n\n I = inpolygon(S.x,S.y,pos(:,1),pos(:,2));\n hold on\n plot(pos(:,1),pos(:,2),'-');\n hold off\n delete(hp);\n case 'reachselect'\n ix = [];\n hpath = [];\n ixpath = [];\n ixend = 0;\n ixcix = zeros(numel(S.x),1);\n ixcix(S.ix) = 1:numel(S.ix);\n title('set upper (green) reach location')\n hpstart = impoint('PositionConstraintFcn',@getnearest);\n setColor(hpstart,[0 1 0])\n idstart = addNewPositionCallback(hpstart,@drawpath);\n setPosition(hpstart,getPosition(hpstart))\n \n title('set lower (red) reach location')\n hpend = impoint('PositionConstraintFcn',@getnearestend); \n setColor(hpend, [1 0 0])\n idend = addNewPositionCallback(hpend,@drawpath);\n setPosition(hpend,getPosition(hpend))\n \n title('move reach locations and press any key to extract reach')\n set(gcf,'WindowKeyPressFcn',@(k,l) uiresume);\n uiwait\n \n I = false(size(S.x));\n I(ixpath) = true;\n \n delete(hpstart)\n delete(hpend);\n\n\n end\nend\n\n%% clean up\nif exist('I','var')\n\n Sout = subgraph(S,I);\n Sout = clean(Sout);\n \n if nargout == 2\n [~,nalix] = ismember(Sout.IXgrid,S.IXgrid); \n end\n\nend\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% SUBFUNCTIONS %%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%\nfunction posn = getnearest(pos)\n % GETNEAREST snap to nearest location on stream network\n [~,ix] = min((S.x-pos(1)).^2 + (S.y-pos(2)).^2);\n posn= [S.x(ix) S.y(ix)];\n\nend\n\nfunction posn = getnearestchanhead(pos)\n % GETNEAREST snap to nearest location on stream network\n [~,ix] = min((xy(:,1)-pos(1)).^2 + (xy(:,2)-pos(2)).^2);\n posn= xy(ix,:);\n\nend\n\nfunction posn = getnearestend(pos)\n % GETNEAREST snap to nearest location on stream network\n [~,ixend] = min((S.x-pos(1)).^2 + (S.y-pos(2)).^2);\n posn= [S.x(ixend) S.y(ixend)];\n\nend\n\nfunction drawpath(pos)\n % DRAWPATH \n \n % bring hpstart and hpend to top\n\n ixcc = ix;\n ixpath = ix;\n while ixcix(ixcc) ~= 0 && ixcc ~= ixend %S.ixc(ixcix(ixcc)) ~= ixend;\n ixpath(end+1) = S.ixc(ixcix(ixcc));\n ixcc = ixpath(end);\n end\n\n if ishandle(hpath)\n set(hpath,'Xdata',S.x(ixpath),'Ydata',S.y(ixpath));\n else\n hold on\n hpath = plot(S.x(ixpath),S.y(ixpath),'r','LineWidth',1.5);\n hold off\n end\nend \n\n function II = drawbasin(pos)\n II = S.x==pos(1) & S.y==pos(2);\n IX = S.IXgrid(II);\n Stemp = modify(S,'upstreamto',IX);\n delete(htemp)\n try\n htemp = plot(Stemp,'r');\n end\n \n end\n \nend\n \n \n "} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "plot.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/plot.m", "size": 3874, "source_encoding": "utf_8", "md5": "100b5f9ed345a98e7bd8bd286eba6fc4", "text": "function h = plot(S,varargin)\n\n%PLOT plot instance of STREAMobj\n%\n% Syntax\n%\n% plot(S)\n% plot(S,...)\n% h = ...;\n%\n% Description\n%\n% plot overloads the builtin plot command and graphically outputs the\n% stream network in S. Additional plot options can be set in the same\n% way as with the builtin plot command.\n%\n% Input arguments\n%\n% S\n%\n% Parameter name/value pairs\n%\n% 'cdc' {false} or true. If true, a customized data cursor will be \n% constructed so that upstream distance will be displayed in \n% addition to x and y coordinates. However, this will result in\n% an error when data cursor is used to underlying images.\n% \n% 'labeldist' place distance indicators on the stream network.\n% Value can be either a numeric array with distance values or a\n% cell array. The cell array must have two elements where the \n% first element contains a numeric array with distances and the\n% second element contains a string with a line specification\n% syntax (e.g., '+r' will draw ret crosses). If you specify\n% 'text' as second element, than text labels will be drawn at\n% the distance locations. When called with one output argument,\n% h will contain several handles to line and text objects.\n%\n% other pn/pv pairs same as plot command\n%\n% Output arguments\n%\n% h handle to line object\n%\n% Example\n% \n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% S = STREAMobj(FD,'minarea',1000);\n% plot(S)\n% \n% % plot with distance indicators at 10000 and 50000 m from outlets\n% % with default distance indicators\n% plot(S,'labeldist',[10000 50000])\n% % with red squares\n% plot(S,'labeldist',{[10000 50000] 'sr'})\n% % or with text labels\n% plot(S,'labeldist',{[10000 30000] 'text'})\n%\n%\n% See also: STREAMobj, STREAMobj/plotdz\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 30. January, 2013\n \n\n% go through varargin to find 'exaggerate'\nTF = strcmpi('cdc',varargin);\nix = find(TF);\nif ~isempty(ix)\n cdc = varargin{ix+1};\n varargin([ix ix+1]) = [];\nelse\n cdc = false;\nend\n\nTF = strcmpi('labeldist',varargin);\nix = find(TF);\nif ~isempty(ix)\n labeldist = varargin{ix+1};\n varargin([ix ix+1]) = [];\nelse\n labeldist = [];\nend\n\n\nif cdc || ~isempty(labeldist)\n [x,y,d] = STREAMobj2XY(S,S.distance);\nelse\n [x,y] = STREAMobj2XY(S);\nend\n\nht = plot(x,y,varargin{:});\n\n%%%\nif cdc\n dcm_obj = datacursormode();\n set(dcm_obj,'UpdateFcn',{@myupdatefcn,d})\nend\n%%%\nif ~isempty(labeldist)\n xyd = [];\n % find nan separators\n ixnansep = [0; find(isnan(d))];\n if iscell(labeldist);\n linestyle = labeldist{2};\n labeldist = labeldist{1};\n else\n linestyle = '+b';\n end\n labeldist = double(labeldist(:));\n for r = 1:numel(ixnansep)-1;\n ix = ixnansep(r)+1:ixnansep(r+1)-1;\n xy = interp1(d(ix),[x(ix) y(ix)],labeldist,'linear',nan);\n inan = ~isnan(xy(:,1));\n if any(inan);\n xyd = [xyd;[xy(inan,:) labeldist(inan)]]; \n end\n end\n ih = ishold;\n hold on;\n if ~strcmpi(linestyle,'text');\n ht(2) = plot(xyd(:,1),xyd(:,2),linestyle);\n else\n h(2) = plot(xyd(:,1),xyd(:,2),'.k');\n htext = text(xyd(:,1),xyd(:,2),num2str(xyd(:,3)),'verticalalignment','baseline');\n h = [h htext(:)'];\n end\n if ~ih;\n hold off;\n end\nend\n\nif nargout == 1\n h = ht;\nend\n\n\n\nfunction txt = myupdatefcn(~,event_obj,d)\n% Customizes text of data tips\npos = get(event_obj,'Position');\ntry\nI = get(event_obj, 'DataIndex');\ntxt = {['X: ',num2str(pos(1))],...\n ['Y: ',num2str(pos(2))],...\n ['Distance: ',num2str(d(I))]};\ncatch\nend\n \n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "labelreach.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/labelreach.m", "size": 4399, "source_encoding": "utf_8", "md5": "e9ed777e70d697c79be738a328f49925", "text": "function [label,varargout] = labelreach(S,varargin)\n\n%LABELREACH create node-attribute list with labelled reaches\n%\n% Syntax\n%\n% label = labelreach(S)\n% label = labelreach(S,pn,pv,...)\n% [label,ix] = ...\n% [label,x,y] = ...\n%\n% Description\n%\n% labelreach creates a node attribute list where each element refers to\n% a label of a reach. A reach is defined as a section of the river\n% network between two confluences. An additional criteria for labelling\n% can be reach distance so that reaches do not exceed a specified length\n% (see option seglength).\n%\n% Input arguments\n%\n% S STREAMobj\n% Parameter name value pairs\n% 'seglength' segment (label) length\n% 'shuffle' randomize labels\n%\n% Output arguments\n%\n% label node-attribute list with labels\n% ix linear index into GRIDobj of split locations\n% x,y coordinates of split locations\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','carve');\n% S = STREAMobj(FD,'minarea',1000);\n% [l,x,y] = labelreach(S,'seglength',1000,'shuffle',true);\n% plotc(S,l)\n% hold on\n% plot(x,y,'k+')\n%\n% See also: STREAMobj\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 17. August, 2017\n\np = inputParser;\np.FunctionName = 'STREAMobj/labelreach';\naddParamValue(p,'seglength',inf,@(x) isscalar(x) && x>0);\naddParamValue(p,'shuffle',false,@(x) isscalar(x));\naddParamValue(p,'exact',false,@(x) isscalar(x));\nparse(p,varargin{:});\n\n\nif ~p.Results.exact\n % The first approach will label all nodes in the stream network.\n % It will split reaches according to segment length but also at\n % confluences. This will result in segment lengths that are not exactly\n % the provided value seglength.\n label = streampoi(S,{'bconfl','out'},'logical');\n label = cumsum(label).*label;\n \n ix = S.ix;\n ixc = S.ixc;\n for r = numel(ix):-1:1\n if label(ix(r)) == 0\n label(ix(r)) = label(ixc(r));\n end\n end\n \n % there may be nodes that are neither receivers or givers. These nodes\n % still have the label zero.\n maxlabel = max(label);\n iszero = label==0;\n label(iszero) = (1:nnz(iszero))+maxlabel;\n \n \n if ~isinf(p.Results.seglength)\n maxdist = p.Results.seglength;\n cs = S.cellsize;\n dist = S.distance;\n label2 = accumarray(label,(1:numel(S.x))',[max(label) 1],@(x) {split(x)});\n labeltemp = zeros(size(label));\n for r = 1:max(label)\n labeltemp(label2{r}(:,2)) = label2{r}(:,1);\n end\n [~,~,label] = unique([label labeltemp],'rows');\n end\nelse\n % If we choose the exact approach, then labelreach will not split at\n % confluences. Parts close to channelheads that have length less than\n % the value of seglength will get the label zero.\n [CS,locS] = STREAMobj2cell(S,'tributaries');\n labeltrib = zeros(size(S.x));\n for r = 1:numel(locS)\n labeltrib(locS{r}) = r;\n end\n \n label = zeros(size(S.x));\n Clabel = cell(size(CS));\n \n for iter = 1:numel(CS)\n d = CS{iter}.distance;\n d = mod(d,p.Results.seglength);\n I = double(gradient(CS{iter},d) < 0);\n I(streampoi(CS{iter},'outlet','logical')) = 1;\n \n ix = CS{iter}.ix;\n ixc = CS{iter}.ixc;\n \n for r = numel(ix):-1:1\n I(ix(r)) = I(ixc(r)) + I(ix(r));\n end\n Clabel{iter} = I;\n end\n \n for r = numel(CS):-1:1\n label(locS{r}) = Clabel{r};\n end\n \n % get unique labels\n [~,~,label] = unique([label labeltrib],'rows');\n \nend\n \n\n\n%% Shuffle labels\nif p.Results.shuffle\n [uniqueL,~,ix] = unique(label);\n uniqueLS = randperm(numel(uniqueL));\n label = uniqueLS(ix);\nend\n\nlabel = label(:);\n\nif nargout >= 2\n I = label(S.ix)~=label(S.ixc);\n \n if nargout == 2\n varargout{1} = S.IXgrid(S.ixc(I));\n else\n varargout{1} = S.x(S.ixc(I));\n varargout{2} = S.y(S.ixc(I));\n end\nend\n \n\n%% Split function\nfunction sp = split(ix)\n\nix = ix(:);\nd = dist(ix)-min(dist(ix));\nmaxd = max(d);\nif maxd < maxdist\n sp = [ones(size(ix)) ix];\nelse\n nrsegs = ceil(maxd./maxdist);\n edges = (0:maxd/nrsegs:(maxd+cs/100));\n [~,~,sp] = histcounts(d,edges);\n sp = [sp(:) ix];\nend\nend\n\nend \n \n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "binarize.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/binarize.m", "size": 2128, "source_encoding": "utf_8", "md5": "5624f214e918f9062c23dcc030fb7918", "text": "function S = binarize(S,a)\n%BINARIZE Make a stream network a strictly binary tree\n%\n% Syntax\n%\n% S2 = binarize(S)\n% S2 = binarize(S,a)\n%\n% Description\n%\n% Stream networks are commonly binary trees. This means that, when\n% moving upstream, a stream branches into a two streams. However, there\n% are cases where the stream network branches into three or more\n% streams which might be unwanted in some analysis.\n%\n% The function binarize removes tributaries in confluences so that\n% there is a maximum of two tributaries. Tributaries to be removed are\n% the ones that have the smallest downstream distance, or those having\n% the smallest upstream area supplied as GRIDobj or node attribute list\n% a.\n%\n% Input arguments\n%\n% S STREAMobj\n% a upstream area (GRIDobj or node-attribute list)\n%\n% Output arguments\n%\n% S2 STREAMobj\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',50);\n% S2 = binarize(S);\n% plot(S,'b')\n% hold on\n% plot(S2,'r')\n% hold off\n%\n% See also: STREAMobj/streamorder, STREAMobj/modify\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 22. May, 2021\n \n\nif nargin == 1\n a = distance(S,'max_from_ch');\nelse\n if isa(a,'GRIDobj')\n a = getnal(S,a);\n else\n if ~isnal(S,a)\n error('TopoToolbox:binarize',...\n 'The second input argument must be a valid node-attribute list.')\n end\n end\nend\n\n% Calculate the number of upstream pixels\nn = numel(S.x);\n\nix = accumarray(S.ixc,S.ix,[n 1],@(ix)getnonbinaryneighbors(ix));\nix = vertcat(ix{:});\n\nI = streampoi(S,'outl','logical');\nII = ismember(S.ix,ix);\nS.ix(II) = [];\nS.ixc(II) = [];\n\n\nfor r = numel(S.ix):-1:1\n I(S.ix(r)) = I(S.ixc(r));\nend\n\nS = subgraph(S,I);\n\n% M = sparse(S.ix,S.ixc,1,n,n);\n% nupstreamneighbors = sum(M,2);\n% I = nupstreamneighbors>=3;\n\nfunction ix = getnonbinaryneighbors(ix)\n\nif numel(ix) <= 2\n ix = {[]};\n return\nend\n\n[~,ixx] = sort(a(ix),'descend');\nix = {ix(ixx(3:end))};\nend\n\nend\n\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "getlocation.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/getlocation.m", "size": 6678, "source_encoding": "utf_8", "md5": "a21f2338872b1a7706f3c06f49b42e97", "text": "function varargout = getlocation(S,d0,varargin)\n\n%GETLOCATION Get locations along a stream network\n%\n% Syntax\n% \n% [x,y,value] = getlocation(S,val)\n% [x,y,value] = getlocation(S,val,'value',S.distance)\n% [P,value] = getlocation(...,'output','PPS','z',DEM)\n% [xc,yc,value] = getlocation(...,'output','xcyc')\n% [ix,value] = getlocation(...,'output','ix')\n% MS = getlocation(...,'output','mapstruct')\n% MP = getlocation(...,'output','mappoint')\n% GP = getlocation(...,'output','geopoint')\n% [x,y,value] = getlocation(...,'output','cell')\n%\n% Description\n%\n% getlocation returns the coordinates (or a data model that stores \n% coordinates) where values measured along a stream network S have a\n% specified value val. For example, the command\n% [x,y,value] = getlocation(S,val) or \n% getlocation(S,val,'value',S.distance)\n% returns the coordinates x and y at which the stream network has a\n% distance val from the outlet. Alternatively, the command\n% [x,y,value] = getlocation(S,1000,'value',DEM) \n% returns the coordinates where elevations along a stream network are\n% 1000 m.\n% \n% Input arguments\n%\n% S STREAMobj\n% val scalar or vector of values (e.g. distance from the outlet or \n% elevation), or anonymous function\n% 'value' can also be a function such as @mean.\n% The command \n% [x,y,value] = getlocation(S,@mean,'value',DEM)\n% returns the locations where the stream network attains the mean \n% elevation along the stream network.\n% \n% Parameter name/value pairs\n%\n% 'value' node-attribute list or GRIDobj\n% By default, 'value' is S.distance, i.e. the distance from\n% the outlet. \n% 'output' {'xy'},'xcyc','ix','PPS','mappoint','geopoint','mapstruct'\n% 'xy' exact coordinates (linearly interpolated)\n% 'xcyc' coordinates at cell centers\n% 'ix' linear indices of cells\n% 'PPS' instance of PPS\n% 'mappoint' mappoint\n% 'geopoint' geopoint (if S has a projected coordinate\n% system)\n% 'mapstruct' mapping structure array\n% 'cell' a cell array of points is returned for each\n% value in val.\n% 'z' adds an elevation attribute to PPS (only applicable if\n% output is PPS)\n%\n% Output arguments\n%\n% ... see 'output'\n% value same as val, but repeated for each location\n%\n% Example 1: Create map with points equally spaced from the outlet\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S,1);\n% [x,y,val] = getlocation(S,[0:5000:max(S.distance)]);\n% plot(S)\n% hold on\n% scatter(x,y,20,val/1000,'filled')\n% h = colorbar;\n% h.Label.String = 'Distance from outlet [km]';\n%\n% Example 2: Create a map with points where streams intersect with contour\n% lines\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',1000);\n% [xcon,ycon,zcon] = contour(DEM,10);\n% plot(xcon,ycon,'color',[.7 .7 .7])\n% P = getlocation(S,unique(zcon),'value',DEM,'output','PPS');\n% [x,y] = getlocation(S,unique(zcon),'value',DEM,'output','xy');\n% hold on\n% plot(P)\n% plot(x,y,'.','color',[.7 .7 .7])\n% hold off\n%\n% Example 3: Animation of upstream migrating knickpoints\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S,1);\n% A = flowacc(FD);\n% c = chitransform(S,A,'mn',0.4);\n% [xc,yc,val] = getlocation(S,linspace(min(c),max(c),500),...\n% 'value',c,'output','cell');\n% plot(S,'color',[.6 .6 .6])\n% axis image\n% hold on\n% h = plot(xc{1},yc{1},'ok','MarkerFaceColor',[.6 .6 .6]);\n% for r = 1:numel(val)\n% set(h,'XData',xc{r},'YData',yc{r});\n% drawnow\n% end\n% hold off\n% \n% \n% See also: STREAMobj, STREAMobj/distance, STREAMobj/getvalue\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 21. November, 2020\n\n% Valid output\nvalidoutput = {'xy','xcyc','ix','PPS','mappoint',...\n 'geopoint','mapstruct','cell'};\n\n% Parse input\np = inputParser;\naddParameter(p,'value',S.distance,@(x) isa(x,'GRIDobj') || isnal(S,x));\naddParameter(p,'output','xy')\naddParameter(p,'z',[])\nparse(p,varargin{:});\n\n% Validate output\noutput = validatestring(p.Results.output,validoutput);\n\n% Handle value grid or node-attribute list\nd = p.Results.value;\nif isa(d,'GRIDobj')\n d = getnal(S,d); \nend\n\n% Is val an function handle?\nif isa(d0,'function_handle')\n d0 = d0(d);\nend\n\n% Outlets need special treatment\noutlet = streampoi(S,'outlet','logical');\n\n% Call getlocation_sub for all elements in d0\n[x,y,c] = cellfun(@getlocation_sub, num2cell(d0),'UniformOutput',false);\n\n\nswitch lower(output)\n case 'cell'\n otherwise \n x = vertcat(x{:});\n y = vertcat(y{:});\n c = vertcat(c{:});\nend\n\n% Prepare output\nswitch lower(output)\n case {'xy','xcyc'}\n varargout{1} = x;\n varargout{2} = y;\n varargout{3} = c;\n case 'ix'\n ix = coord2ind(GRIDobj(S,'logical'),x,y);\n \n varargout{1} = ix;\n varargout{2} = c;\n case 'mapstruct'\n varargout{1} = struct('Geometry','Point',...\n 'X',num2cell(x),'Y',num2cell(y),'value',num2cell(c));\n case 'pps'\n if isempty(p.Results.z)\n varargout{1} = PPS(S,'PP',[x y]);\n else\n varargout{1} = PPS(S,'PP',[x y],'z',p.Results.z);\n end\n varargout{2} = c;\n \n case 'mappoint'\n varargout{1} = mappoint(x,y,'value',c);\n case 'geopoint'\n [lat,lon] = minvtran(S.georef.mstruct,x,y);\n varargout{1} = ygeopoint(lat,lon,'value',c);\n case 'cell'\n varargout{1} = x;\n varargout{2} = y;\n varargout{3} = cellfun(@(x) x(1),c,'UniformOutput',true);\nend\n%% --------------------------------------\nfunction [x,y,c] = getlocation_sub(d0)\nf = (d0-d(S.ixc)) ./ (d(S.ix)-d(S.ixc));\nI = (f>0) & (f <=1) | (outlet(S.ixc) & (f == 0));\n\nswitch lower(output)\n case {'xcyc','ix','pps'} \n f = round(f);\nend\nx = S.x(S.ixc(I)) + f(I).*(S.x(S.ix(I))-S.x(S.ixc(I)));\ny = S.y(S.ixc(I)) + f(I).*(S.y(S.ix(I))-S.y(S.ixc(I)));\n\nc = repmat(d0,size(x));\nend\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "crslin.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/crslin.m", "size": 12568, "source_encoding": "utf_8", "md5": "2fd3709790684c8985bf919a1f0899da", "text": "function [zs,exitflag,output] = crslin(S,DEM,varargin)\n\n%CRSLIN constrained regularized smoothing of the channel length profile\n%\n% Syntax\n%\n% zs = crslin(S,DEM)\n% zs = crslin(S,DEM,pn,pv,...)\n%\n% Description\n%\n% Elevation values along stream networks are frequently affected by\n% large scatter, often as a result of data artifacts or errors. This\n% function returns a node attribute list of elevations calculated by\n% regularized smoothing. This function requires the Optimization \n% Toolbox. \n%\n% Input parameters\n%\n% S STREAMobj\n% DEM Digital elevation model (GRIDobj)\n% \n% Parameter name/value pairs {default}\n%\n% 'K' positive scalar that dictates the degree of stiffness\n% {1}\n% 'mingradient' positive scalar {0}. Minimum downward gradient. \n% Choose carefully, because length profile may dip to\n% steeply. Set this parameter to nan if you do not wish\n% to have a monotonous dowstream elevation decrease.\n% 'imposemin' preprocesses the stream elevations using downstream\n% minima imposition. {false} or true. Setting this\n% parameter to true avoids that obviously wrong\n% elevation values exert a strong effect on the result.\n% 'nonstifftribs' {true} or false. true enables sharp concave knicks at\n% confluences\n% 'attachtomin' true or {false}. Smoothed elevations will not exceed\n% local minima along the downstream path. (only\n% applicable if 'mingradient' is not nan).\n% 'attachheads' true or {false}. If true, elevations of channelheads \n% are fixed. (only applicable if 'mingradient' is not \n% nan). Note that for large K, setting attachheads to\n% true can result in excessive smoothing and\n% underestimation of elevation values directly \n% downstream to channelheads. \n% 'discardflats' true or {false}. If true, elevations of flat sections\n% are discarded from the analysis.\n% 'knickpoints' nx2 matrix with x and y coordinates of locations\n% where the stiffness penalty should be relaxed (e.g. \n% at knickpoints, waterfalls, weirs, dams, ...).\n% The locations should be as exact as possible but are\n% snapped to the closest node in the stream network.\n% 'precisecoords' nx3 matrix that contains the xyz coordinates of n \n% points whose elevations must be matched by the\n% smoothed profile. \n% 'maxcurvature' maximum convex curvature at any of the vertices along\n% the profile (default: []). Setting this value to zero\n% inhibits any convexities and the smoothed profile is \n% the lower concave envelope of the actual profile.\n% This option is mainly used for the function\n% profilesimplify, but may also be useful if the\n% profile is strictly concave.\n% 'plot' {false} or true\n%\n%\n% Output parameters\n%\n% zs node attribute list with smoothed elevation values\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','carve');\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S);\n% zs = crslin(S,DEM,'K',10,'attachtomin',true);\n% zs2 = crslin(S,DEM,'K',10);\n% plotdz(S,DEM,'color',[0.6 0.6 0.6]) \n% hold on\n% plotdz(S,zs,'color','k')\n% plotdz(S,zs2,'color','r')\n% hold off\n% legend('original data',...\n% 'K=10, attached to minima',...\n% 'K=10, not attached to minima')\n%\n% Algorithm\n%\n% This algorithm uses linear nonparametric constrained regression to\n% smooth the data. The algorithm is described in Schwanghart and\n% Scherler (2017) (Eq. A6-A11).\n% \n% References\n%\n% Schwanghart, W., Scherler, D., 2017. Bumps in river profiles: \n% uncertainty assessment and smoothing using quantile regression \n% techniques. Earth Surface Dynamics, 5, 821-839. \n% [DOI: 10.5194/esurf-5-821-2017]\n%\n% See also: STREAMobj/mincosthydrocon, quadprog, STREAMobj/crs, \n% STREAMobj/quantcarve, STREAMobj/smooth\n% \n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 11. May, 2016\n\n\n% check and parse inputs\nnarginchk(2,inf)\n\np = inputParser;\np.FunctionName = 'STREAMobj/crslin';\naddParameter(p,'K',1,@(x) (isscalar(x) && x>0) || isa(x,'GRIDobj'));\naddParameter(p,'imposemin',false,@(x) isscalar(x));\naddParameter(p,'attachtomin',false,@(x) isscalar(x));\naddParameter(p,'attachheads',false,@(x) isscalar(x));\naddParameter(p,'nonstifftribs',true,@(x) isscalar(x));\naddParameter(p,'mingradient',0,@(x) (isscalar(x) && (x>=0 || isnan(x))));\naddParameter(p,'maxcurvature',inf);\naddParameter(p,'discardflats',false);\naddParameter(p,'knickpoints',[]);\naddParameter(p,'precisecoords',[]);\naddParameter(p,'plot',false);\naddParameter(p,'weights','none',@(x) ischar(x));\naddParameter(p,'nocr',false);\nparse(p,varargin{:});\n\n% get node attribute list with elevation values\nif isa(DEM,'GRIDobj')\n validatealignment(S,DEM);\n z = getnal(S,DEM);\nelseif isnal(S,DEM)\n z = DEM;\nelse\n error('Imcompatible format of second input argument')\nend\n\nif any(isnan(z))\n error('DEM or z may not contain any NaNs')\nend\n\n% get weights\nwtype = lower(p.Results.weights);\nswitch wtype\n case 'positive'\n zimp = imposemin(S,z);\n w = z-zimp;\n w = exp(-0.5 * w.^2);\n case 'mincost'\n zmincost = mincosthydrocon(S,z,'minmax');\n w = abs(z-zmincost);\n w = exp(-0.5 * w.^2);\n case 'interp'\n zmincost = mincosthydrocon(S,z,'interp');\n w = abs(z-zmincost);\n w = exp(-0.5 * w.^2);\n otherwise\n w = ones(size(z));\nend\n \n% minimum imposition\nif p.Results.imposemin\n if ~exist('zimp','var')\n z = imposemin(S,z);\n else\n z = zimp;\n end\nend\n\n% upstream distance\nd = S.distance;\n% nr of nodes\nnr = numel(S.IXgrid);\n\n%% Fidelity matrix\n%\n% This matrix is an identity matrix, since we are only interested in \n% predicting values at the node locations of the network.\nif ~p.Results.discardflats\n Afid = speye(nr,nr);\n tf = false(nr,1);\nelse\n\n % include code to allow for linear interpolation of elevations with\n % apparently wrong z values (e.g. positive residuals following carving)\n [tf,s] = identifyflats(S,imposemin(S,z));\n tf(s>0) = true;\n poi = ... %streampoi(S,'confluences','logical') | ...\n streampoi(S,'outlets','logical') | ...\n streampoi(S,'channelheads','logical');\n tf(poi) = false;\n \n % create sparse adjacency matrices weighted by the inverse distance between\n % nodes\n A = sparse(double(S.ix(tf(S.ix))),double(S.ixc(tf(S.ix))),...\n 1./(d(S.ix(tf(S.ix)))-d(S.ixc(tf(S.ix)))),nr,nr); \n\n A2 = sparse(double(S.ixc(tf(S.ixc))),double(S.ix(tf(S.ixc))),...\n 1./(d(S.ix(tf(S.ixc)))-d(S.ixc(tf(S.ixc)))),nr,nr); \n\n % since there may be more than 1 upstream neighbor, A2 is normalized such\n % that the sum of upstream weights equals the downstream weight. \n s = 1./(sum(spones(A2),2));\n s(~tf) = 0;\n A2 = spdiags(s,0,nr,nr)*A2;\n\n % add A and A2\n A = A+A2;\n % and normalize again such that rows sum to one\n s = 1./(sum(A,2));\n s(~tf) = 0;\n A = spdiags(s,0,nr,nr)*A;\n\n % fill main diagonal with ones\n Afid = speye(nr)-A;\n \nend\n \n\n%% Second-derivate matrix\n%\n% This matrix contains the finite central differences \n[I,loc] = ismember(S.ixc,S.ix);\n\n% i-1 i i+1\ncolix = [S.ixc(loc(I)) S.ixc(I) S.ix(I)];\n\n% Set user-supplied knickpoints to non-stiff\nif ~isempty(p.Results.knickpoints)\n xy = p.Results.knickpoints;\n [~,~,IX] = snap2stream(S,xy(:,1),xy(:,2));\n I = ismember(S.IXgrid,IX);\n I = I(colix(:,2));\n colix(I,:) = [];\nend\n\n\nval = [2./((d(colix(:,2))-d(colix(:,1))).*(d(colix(:,3))-d(colix(:,1)))) ...\n -2./((d(colix(:,3))-d(colix(:,2))).*(d(colix(:,2))-d(colix(:,1)))) ...\n 2./((d(colix(:,3))-d(colix(:,2))).*(d(colix(:,3))-d(colix(:,1))))];\n \n% matrix for maximum curvature constraint \nif ~isinf(p.Results.maxcurvature)\n nrrows = size(colix,1);\n rowix = repmat((1:nrrows)',1,3);\n Asdc = sparse(rowix(:),colix(:),val(:),nrrows,nr);\nend\n\n% Set tributaries to non-stiff\nif p.Results.nonstifftribs\n dd = distance(S,'max_from_ch');\n I = (dd(colix(:,2)) - dd(colix(:,3)))>=(sqrt(2*S.cellsize.^2)+S.cellsize/2);\n colix(I,:) = [];\n val(I,:) = [];\nend\n\n% second-derivative matrix\nnrrows = size(colix,1);\nrowix = repmat((1:nrrows)',1,3);\nAsd = sparse(rowix(:),colix(:),val(:),nrrows,nr);\n\n%% Setup linear system\n% balance stiffness and fidelity\n% F = p.Results.K * sqrt(size(Afid,1)/nrrows);\nif ~p.Results.nocr\n F = p.Results.K * S.cellsize^2 * sqrt(size(Afid,1)/nrrows); %norm(Afid,1)/norm(Asd,1);\n Asd = F*Asd;\n % new with weighted scheme\n W = spdiags(w,0,nr,nr);\n Afid = W*Afid;\n zw = W*z;\n C = [Afid;Asd];\n % right hand side of equation\n b = [zw.*(~tf);zeros(nrrows,1)]; % convex -> negative values\nelse\n C = Afid;\n b = z.*(~tf);\nend\n\nif isnan(p.Results.mingradient)\n % no minimum gradient imposition involves only solving the\n % overdetermined system of equations. \n zs = C\\b;\n exitflag = [];\n output = [];\n \nelse\n % with additional constraints we reformulate the problem for using\n % quadratic programming\n d = 1./(d(S.ix)-d(S.ixc));\n A = (sparse(S.ix,S.ixc,d,nr,nr)-sparse(S.ix,S.ix,d,nr,nr));\n e = zeros(nr,1);\n if p.Results.mingradient ~= 0\n e(S.ix) = -p.Results.mingradient;\n end\n \n if ~isinf(p.Results.maxcurvature)\n A = [A;-Asdc];\n e = [e;repmat(p.Results.maxcurvature,size(Asdc,1),1)];\n end\n\n % reformulate for quadprog\n H = 2*(C'*C);\n c = -2*C'*b;\n \n lb = [];\n if p.Results.attachtomin\n ub = double(z);\n else\n ub = double([]);\n end\n \n if p.Results.attachheads\n channelheads = streampoi(S,'channelheads','logical');\n Aeq = spdiags(+channelheads,0,nr,nr);\n eeq = zeros(nr,1);\n eeq(channelheads) = z(channelheads);\n else\n Aeq = [];\n eeq = [];\n end\n \n if ~isempty(p.Results.precisecoords)\n % Settings to force profiles to run through a prescribed set of \n % elevations\n [~,~,IXp] = snap2stream(S,...\n p.Results.precisecoords(:,1),...\n p.Results.precisecoords(:,2));\n [~,locb] = ismember(IXp,S.IXgrid);\n precise = zeros(nr,1);\n precise(locb) = 1;\n \n eeqb = zeros(nr,1);\n eeqb(locb) = double(p.Results.precisecoords(:,3));\n inan = isnan(eeqb);\n eeqb(inan) = 0;\n precise(inan) = 0;\n Aeqb = spdiags(precise,0,nr,nr);\n \n if isempty(Aeq)\n Aeq = Aeqb;\n eeq = eeqb;\n else\n Aeq = Aeq+Aeqb;\n eeq = eeq + eeqb;\n end\n end\n \n % solve\n if verLessThan('optim','6.3')\n options = optimset('Display','off','Algorithm','interior-point-convex');\n else\n options = optimoptions('quadprog','Display','off');\n end\n \n % call to quadratic programming\n [zs,~,exitflag,output] = quadprog(H,c,A,e,Aeq,eeq,lb,ub,z,options);\n\nend\n\nif p.Results.plot\n tf = ishold(gca);\n plotdz(S,z,'color',[.6 .6 .6]);\n hold on\n plotdz(S,zs,'color','r');\n \n if ~isempty(p.Results.precisecoords)\n d = S.distance(locb);\n plot(d,p.Results.precisecoords(:,3),'s');\n end\n \n if ~tf\n hold off\n end\nend\n\n\nend\n\n\n\nfunction [fs,s] = identifyflats(S,DEM,varargin)\n\n\nif isa(DEM,'GRIDobj')\n validatealignment(S,DEM);\n z = getnal(S,DEM);\nelseif isnal(S,DEM)\n z = DEM;\nelse\n error('Imcompatible format of second input argument')\nend\n\nfs = false(size(S.IXgrid));\ns = zeros(size(S.IXgrid));\n\nfor r=1:numel(S.ix)\n if z(S.ixc(r)) == z(S.ix(r))\n% fs(S.ix(r)) = true;\n fs(S.ixc(r)) = true;\n elseif fs(S.ix(r)) && z(S.ixc(r))< z(S.ix(r))\n s(S.ixc(r)) = 1;\n end\nend\n\nI = streampoi(S,'channelheads','logical');\nfs(I) = false;\nI = streampoi(S,'outlets','logical');\nfs(I) = false;\ns(I) = 0;\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "STREAMobj2mapstruct.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/STREAMobj2mapstruct.m", "size": 18292, "source_encoding": "utf_8", "md5": "6f517eed0d2304432b7f2490e393475c", "text": "function [GS,x,y] = STREAMobj2mapstruct(S,varargin)\n\n%STREAMOBJ2MAPSTRUCT convert instance of STREAMobj to mapstruct\n%\n% Syntax\n%\n% MS = STREAMobj2mapstruct(S)\n% MS = STREAMobj2mapstruct(S,type)\n% MS = STREAMobj2mapstruct(S,'seglength',length,...\n% 'attributes',{'fieldname1' var1 aggfunction1 ...\n% 'fieldname2' var2 aggfunction2})\n% [MS,x,y] = ...\n% \n%\n% Description\n%\n% A mapstruct is a structure array that contains vector geographic\n% data. STREAMobj2mapstruct converts an instance of STREAMobj to a\n% mapstruct MS. MS can be exported to a shapefile using the function\n% shapewrite available with the Mapping Toolbox. It can be plotted with\n% the function mapshow.\n%\n% When called with following syntax\n% MS = STREAMobj2mapstruct(S)\n% then\n% MS contains individual line features for each river reach with unique\n% streamorder and contains following fields:\n%\n% Geometry: 'Line'\n% X: vector with vertices of x-coordinates\n% Y: vector with vertices of y-coordinates\n% streamorder: stream order (Strahler)\n% IX: stream id\n% tribtoIX: tributary to stream with id IX\n%\n% When called with following syntax\n% MS = STREAMobj2mapstruct(S,'seglength',length,...\n% 'attributes',{'fieldname1' var1 aggfunction1 ...\n% 'fieldname2' var2 aggfunction2})\n%\n% the streamnetwork is subdivided in reaches with approximate length in\n% map units defined by the parameter value pair 'seglength'-length. In\n% addition, a number of additional variables (instance of GRIDobjs or\n% node attributes (e.g. as returned by STREAMobj/streamorder,\n% STREAMobj/gradient, etc.) can be defined to be written as attributes\n% into the structure array. Since the values associated with one line\n% segment must be scalars, an aggregation function must be defined that\n% takes a vector and returns a scalar (e.g. @mean, @max, @std).\n%\n% Note that the segment length in the output structure array is\n% variable since the function tries to evenly distribute the segments\n% between confluences, confluences and outlets, and confluences and\n% channelheads.\n%\n% The additional output arguments x and y are nan-separated vectors\n% that can be used to plot the line features. Note that the order of x\n% and y is different from the output of STREAMobj2XY. \n%\n% Input arguments\n%\n% S STREAMobj\n% type {'strahler'} or 'shreve'\n%\n% Parameter name/value pairs\n%\n% 'seglength' approximate segment length (scalar, map units)\n% 'attributes' 1 x n*3 cell array where n is the number of attributes,\n% and elements refer repeatively to\n% {'fieldname' var aggfunction ...}\n% where fieldname is the field name in the attribute\n% table\n% var is a GRIDobj associated with the STREAMobj or a\n% node attribute list\n% aggfunction is a anonymous function that takes a vector\n% and returns a scalar\n% *** This might not be easy to understand so check the \n% example below ***\n% 'parallel' {false} or true. Requires the Parallel Computing\n% Toolbox. If set to true, the function will split the\n% stream network into its connected components and\n% process each individually in parallel. Mostly, there\n% will not be a gain in speed as there is a significant\n% computational overhead to split the network. Running in \n% may be more efficient if network is very large with \n% numerous connected components. \n% 'latlon' {false} or true. If true, the function will attempt to\n% transform coordinates to geographic coordinates. This\n% works only if S contains a valid projection. \n% \n% Output arguments\n%\n% MS mapstruct\n% x x coordinate vector\n% y y coordinate vector\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% A = flowacc(FD);\n% S = STREAMobj(FD,A>1000);\n% DEM = imposemin(FD,DEM);\n% g = gradient(S,DEM);\n% MS = STREAMobj2mapstruct(S,'seglength',300,...\n% 'attributes',{'flowacc' A @mean 'gradient' g @mean});\n%\n% % then export MS as shapefile using shapewrite\n% \n% See also: shapewrite, STREAMobj2XY\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 27. September, 2021\n\n\n\n\nif nargin == 1\n type = 'strahler';\nelseif nargin == 2\n type = validatestring(varargin{1},{'strahler','shreve'},'STREAMobj/streamorder','type',2);\nend\n\nif nargin <= 2\n % get streamorder\n s = streamorder(S,type);\n % get outlets\n outlets = streampoi(S,'outlets','logical');\n \n % channel index counter\n chc = 1;\n CHN = zeros(size(outlets));\n \n % create empty mapstruct\n GS = struct('Geometry',{},...\n 'X',{},...\n 'Y',{},...\n 'streamorder',{},...\n 'IX',{},...\n 'tribtoIX',{});\n \n \n for r = numel(S.ix):-1:1\n \n if CHN(S.ixc(r)) == 0\n CHN(S.ixc(r)) = chc;\n GS(CHN(S.ixc(r))).Geometry = 'Line';\n GS(CHN(S.ixc(r))).X = S.x(S.ixc(r));\n GS(CHN(S.ixc(r))).Y = S.y(S.ixc(r));\n GS(CHN(S.ixc(r))).streamorder = s(S.ixc(r));\n GS(CHN(S.ixc(r))).IX = chc;\n \n chc = chc+1;\n end\n \n if s(S.ixc(r)) == s(S.ix(r))\n CHN(S.ix(r)) = CHN(S.ixc(r));\n \n GS(CHN(S.ix(r))).X(end+1) = S.x(S.ix(r));\n GS(CHN(S.ix(r))).Y(end+1) = S.y(S.ix(r));\n \n CHN(S.ixc(r)) = CHN(S.ix(r));\n \n elseif s(S.ixc(r)) ~= s(S.ix(r))\n \n \n CHN(S.ix(r)) = chc;\n GS(CHN(S.ix(r))).Geometry = 'Line';\n GS(CHN(S.ix(r))).X = S.x(S.ixc(r));\n GS(CHN(S.ix(r))).Y = S.y(S.ixc(r));\n \n GS(CHN(S.ix(r))).X(end+1) = S.x(S.ix(r));\n GS(CHN(S.ix(r))).Y(end+1) = S.y(S.ix(r));\n \n GS(CHN(S.ix(r))).IX = CHN(S.ix(r));\n GS(CHN(S.ix(r))).streamorder = s(S.ix(r));\n GS(CHN(S.ix(r))).tribtoIX = CHN(S.ixc(r));\n \n chc = chc+1;\n end\n end\n \n for r = 1:numel(GS)\n GS(r).X = [GS(r).X(end:-1:1) nan];\n GS(r).Y = [GS(r).Y(end:-1:1) nan];\n if isempty(GS(r).tribtoIX)\n GS(r).tribtoIX = 0;\n end\n \n end\nelse\n \n % do the first series of input argument checking\n p = inputParser;\n p.FunctionName = 'STREAMobj2mapstruct';\n addRequired(p,'S',@(x) isa(x,'STREAMobj'));\n addParameter(p,'seglength',S.cellsize*10,@(x) isscalar(x) && x>=S.cellsize*3);\n addParameter(p,'attributes',{},@(x) iscell(x)); \n addParameter(p,'checkattributes',true,@(x) isscalar(x))\n addParameter(p,'parallel',false)\n addParameter(p,'latlon',false)\n parse(p,S,varargin{:});\n \n % check the attributes\n attributes = p.Results.attributes;\n nrattributes = numel(attributes)/3;\n runinpar = p.Results.parallel;\n seglength = p.Results.seglength;\n \n % make valid and unique field names if required\n if p.Results.checkattributes\n attributes(1:3:end) = matlab.lang.makeValidName(attributes(1:3:end));\n attributes(1:3:end) = matlab.lang.makeUniqueStrings(attributes(1:3:end));\n end\n \n % convert strings to functions, if necessary\n for r = 1:nrattributes\n ix = ((r-1)*3)+3;\n if ischar(attributes{ix})\n attributes{ix} = str2func(attributes{ix});\n end\n end\n \n % convert attributes to node attribute lists\n for r = 1:nrattributes\n ix = ((r-1)*3)+2;\n if isa(attributes{ix},'GRIDobj')\n attributes{ix} = getnal(S,attributes{ix});\n elseif isnal(S,attributes{ix})\n % everything's fine here\n else\n error('TopoToolbox:incompatibleformat',...\n ['Incompatible format of attribute. Attribute is expected to\\n'...\n 'be either a GRIDobj or a node attribute list (nal) of S']);\n end\n end\n \n %% Parallel computing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if runinpar\n % Place each connected component in an individual cell\n [CS,locS] = STREAMobj2cell(S);\n \n % Derive a cell array of attributes\n CATT = cell(numel(CS),nrattributes*3);\n for r = 1:numel(CS)\n for r2 = 1:nrattributes\n CATT{r,(r2-1)*3 + 1} = attributes{(r2-1)*3 + 1}; \n CATT{r,(r2-1)*3 + 3} = attributes{(r2-1)*3 + 3}; \n CATT{r,(r2-1)*3 + 2} = attributes{(r2-1)*3 + 2}(locS{r});\n end\n end\n \n % Preallocate cell array\n GS = cell(numel(CS),1);\n \n parfor r = 1:numel(CS) \n GS{r} = STREAMobj2mapstruct(CS{r},'seglength',seglength,...\n 'attributes',CATT(r,:),...\n 'parallel',false);\n end\n \n GS = vertcat(GS{:});\n if nargout>1\n x = [GS.X]';\n y = [GS.Y]';\n end\n return\n \n end\n %% Parallel computing ends here %%%%%%%%%%%%%%%%%%%%%%%%\n % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n \n \n % write stream segments\n confluences = streampoi(S,'confl','logical');\n \n % preallocate cell array with attributes\n attr = cell(1,nrattributes);\n \n % get nan-punctuated vectors\n [x,y,confluences,attr{:}] = STREAMobj2XY(S,confluences,attributes{2:3:end});\n \n % in addition to existing nan-separators, separate vectors at confluences\n % the confluences which are followed by nan can be neglegted\n confluences(circshift(isnan(confluences),-1) & confluences==1) = 0;\n \n % doublicate nodes at remaining confluences (insert rows)\n ind = find(confluences == 1);\n x = insertrows(x,x(ind),ind);\n y = insertrows(y,y(ind),ind);\n confluences = insertrows(confluences,0,ind);\n for r = 1:numel(attr)\n attr{r} = insertrows(attr{r},attr{r}(ind),ind);\n end\n \n % insert nans\n ind = find(confluences == 1);\n x = insertrows(x,nan,ind);\n y = insertrows(y,nan,ind);\n for r = 1:numel(attr)\n attr{r} = insertrows(attr{r},nan,ind);\n end\n \n % get additional separators to segment lines further according to\n % segment length\n % calculate the distance within each individual segment\n sep = isnan(x);\n d = zeros(size(x));\n for r = 2:numel(d)\n if sep(r-1)\n d(r) = 0;\n elseif sep(r)\n d(r) = nan;\n else\n d(r) = d(r-1)+sqrt((x(r)-x(r-1)).^2 + (y(r)-y(r-1)).^2);\n end\n end\n \n % try to get equal length segments being equally distributed over an\n % existing segment.\n % Use equal quantiles\n ixsep = find(sep);\n nrsep = numel(ixsep);\n ixsep = [0;ixsep];\n newsep = zeros(size(d));\n for r = 1:nrsep\n dd = d(ixsep(r)+1 : ixsep(r+1)-1);\n ddmax = max(dd);\n nrnewsegs = max(round(ddmax/p.Results.seglength),1);\n \n if nrnewsegs > 1\n [~,segtemp] = histc(dd,linspace(0,ddmax + S.cellsize*.01,nrnewsegs));\n segtemp = [0;diff(segtemp)];\n newsep(ixsep(r)+1 : ixsep(r+1)-1) = segtemp;\n end\n \n end\n \n % now set new separators according to newsep\n ind = find(newsep > 0);\n x = insertrows(x,x(ind),ind);\n y = insertrows(y,y(ind),ind);\n newsep = insertrows(newsep,0,ind);\n for r = 1:numel(attr)\n attr{r} = insertrows(attr{r},attr{r}(ind),ind);\n end\n \n % insert nans\n ind = find(newsep > 0);\n x = insertrows(x,nan,ind);\n y = insertrows(y,nan,ind);\n for r = 1:numel(attr)\n attr{r} = insertrows(attr{r},nan,ind);\n end\n \n \n % Now, finally, create the mapstruct\n ix = find(isnan(x));\n nrlines = numel(ix);\n % make attributes a row (cell) vector\n attributes = attributes(:)';\n cc = [attributes(1:3:end);\n repmat({cell(nrlines,1)},1,nrattributes)];\n \n GS = struct('Geometry','Line',...\n 'X',cell(nrlines,1),...\n 'Y',cell(nrlines,1),... \n cc{:});\n \n IXs = [1;ix(1:end-1)+1];\n IXe = ix-1;\n \n \n for r = 1:nrlines\n GS(r).X = x(IXs(r):IXe(r));\n GS(r).Y = y(IXs(r):IXe(r));\n \n for r2 = 1:nrattributes\n GS(r).(attributes{((r2-1)*3)+1}) = attributes{((r2-1)*3)+3}(attr{r2}(IXs(r):IXe(r)-1));\n end\n \n end\n \nend\n \n% Convert to lat lon if requested\nif exist('p', 'var')\nif p.Results.latlon\n for r = 1:numel(GS)\n [GS(r).Y,GS(r).X] = minvtran(S.georef.mstruct,GS(r).X,GS(r).Y);\n end\nend\nend\n\nif nargout>1\n x = [GS.X]';\n y = [GS.Y]';\nend\n\n\n\n\nend\n\n\n\n%% INSERTROWS by JOS\n% http://www.mathworks.com/matlabcentral/fileexchange/9984-insertrows-v2-0-may-2008\nfunction [C,RA,RB] = insertrows(A,B,ind)\n% INSERTROWS - Insert rows into a matrix at specific locations\n% C = INSERTROWS(A,B,IND) inserts the rows of matrix B into the matrix A at\n% the positions IND. Row k of matrix B will be inserted after position IND(k)\n% in the matrix A. If A is a N-by-X matrix and B is a M-by-X matrix, C will\n% be a (N+M)-by-X matrix. IND can contain non-integers.\n%\n% If B is a 1-by-N matrix, B will be inserted for each insertion position\n% specified by IND. If IND is a single value, the whole matrix B will be\n% inserted at that position. If B is a single value, B is expanded to a row\n% vector. In all other cases, the number of elements in IND should be equal to\n% the number of rows in B, and the number of columns, planes etc should be the\n% same for both matrices A and B. \n%\n% Values of IND smaller than one will cause the corresponding rows to be\n% inserted in front of A. C = INSERTROWS(A,B) will simply append B to A.\n%\n% If any of the inputs are empty, C will return A. If A is sparse, C will\n% be sparse as well. \n%\n% [C, RA, RB] = INSERTROWS(...) will return the row indices RA and RB for\n% which C corresponds to the rows of either A and B.\n%\n% Examples:\n% % the size of A,B, and IND all match\n% C = insertrows(rand(5,2),zeros(2,2),[1.5 3]) \n% % the row vector B is inserted twice\n% C = insertrows(ones(4,3),1:3,[1 Inf]) \n% % matrix B is expanded to a row vector and inserted twice (as in 2)\n% C = insertrows(ones(5,3),999,[2 4])\n% % the whole matrix B is inserted once\n% C = insertrows(ones(5,3),zeros(2,3),2)\n% % additional output arguments\n% [c,ra,rb] = insertrows([1:4].',99,[0 3]) \n% c.' % -> [99 1 2 3 99 4] \n% c(ra).' % -> [1 2 3 4] \n% c(rb).' % -> [99 99] \n%\n% Using permute (or transpose) INSERTROWS can easily function to insert\n% columns, planes, etc:\n%\n% % inserting columns, by using the transpose operator:\n% A = zeros(2,3) ; B = ones(2,4) ;\n% c = insertrows(A.', B.',[0 2 3 3]).' % insert columns\n% % inserting other dimensions, by using permute:\n% A = ones(4,3,3) ; B = zeros(4,3,1) ; \n% % set the dimension on which to operate in front\n% C = insertrows(permute(A,[3 1 2]), permute(B,[3 1 2]),1) ;\n% C = ipermute(C,[3 1 2]) \n%\n% See also HORZCAT, RESHAPE, CAT\n\n% for Matlab R13\n% version 2.0 (may 2008)\n% (c) Jos van der Geest\n% email: jos@jasen.nl\n\n% History:\n% 1.0, feb 2006 - created\n% 2.0, may 2008 - incorporated some improvements after being selected as\n% \"Pick of the Week\" by Jiro Doke, and reviews by Tim Davis & Brett:\n% - horizontal concatenation when two arguments are provided\n% - added example of how to insert columns\n% - mention behavior of sparse inputs\n% - changed \"if nargout\" to \"if nargout>1\" so that additional outputs are\n% only calculated when requested for\n\nnarginchk(2,3);\n\nif nargin==2,\n % just horizontal concatenation, suggested by Tim Davis\n ind = size(A,1) ;\nend\n\n% shortcut when any of the inputs are empty\nif isempty(B) || isempty(ind), \n C = A ; \n if nargout > 1,\n RA = 1:size(A,1) ;\n RB = [] ;\n end\n return\nend\n\nsa = size(A) ;\n\n% match the sizes of A, B\nif numel(B)==1,\n % B has a single argument, expand to match A\n sb = [1 sa(2:end)] ;\n B = repmat(B,sb) ;\nelse\n % otherwise check for dimension errors\n if ndims(A) ~= ndims(B),\n error('insertrows:DimensionMismatch', ...\n 'Both input matrices should have the same number of dimensions.') ;\n end\n sb = size(B) ;\n if ~all(sa(2:end) == sb(2:end)),\n error('insertrows:DimensionMismatch', ...\n 'Both input matrices should have the same number of columns (and planes, etc).') ;\n end\nend\n\nind = ind(:) ; % make as row vector\nni = length(ind) ;\n\n% match the sizes of B and IND\nif ni ~= sb(1),\n if ni==1 && sb(1) > 1,\n % expand IND\n ind = repmat(ind,sb(1),1) ;\n elseif (ni > 1) && (sb(1)==1),\n % expand B\n B = repmat(B,ni,1) ;\n else\n error('insertrows:InputMismatch',...\n 'The number of rows to insert should equal the number of insertion positions.') ;\n end\nend\n\nsb = size(B) ;\n\n% the actual work\n% 1. concatenate matrices\nC = [A ; B] ;\n% 2. sort the respective indices, the first output of sort is ignored (by\n% giving it the same name as the second output, one avoids an extra \n% large variable in memory)\n[~,abi] = sort([[1:sa(1)].' ; ind(:)]) ;\n% 3. reshuffle the large matrix\nC = C(abi,:) ;\n% 4. reshape as A for nd matrices (nd>2)\nif ismatrix(A),\n sc = sa ;\n sc(1) = sc(1)+sb(1) ;\n C = reshape(C,sc) ;\nend\n\nif nargout > 1,\n % additional outputs required\n R = [zeros(sa(1),1) ; ones(sb(1),1)] ;\n R = R(abi) ;\n RA = find(R==0) ;\n RB = find(R==1) ;\nend\nend\n\n\n\n\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "union.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/union.m", "size": 3666, "source_encoding": "utf_8", "md5": "37cb7faf4b6966748f4eaee363a5f96b", "text": "function S = union(varargin)\n\n%UNION merge different instances of STREAMobj into a new instance\n%\n% Syntax\n%\n% S = union(S1,S2,...)\n% S = union(S1,S2,...,FD)\n%\n% Description\n%\n% union combines different instances of STREAMobj into a new STREAMobj.\n%\n% union(S1,S2,...) combines all instances into a new STREAMobj. The\n% networks might be subset of each others. All networks must have been\n% derived from the same flow direction object (FLOWobj). If this is not the case, the function might have an\n% unexpected behavior. \n%\n% union(S1,S2,...,FD) takes in addition an instance of FLOWobj as last input\n% variable and it is assumed that all STREAMobjs have been derived\n% from this FLOWobj (e.g., all STREAMobjs are subgraphs of the\n% FLOWobj). This syntax reestablishes the connectivity between adjacent\n% nodes that are connected in the FLOWobj but not in the STREAMobjs.\n%\n% Input arguments\n%\n% S1, S2, ... several instances of STREAMobj\n% FD instance of FLOWobj\n%\n% Output arguments\n%\n% S STREAMobj\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% A = flowacc(FD);\n% S = STREAMobj(FD,A>1000);\n% CS = STREAMobj2cell(split(S));\n% S2 = union(CS{:});\n% ax = subplot(2,1,1);\n% plot(S2)\n% S3 = union(CS{:},FD);\n% ax(2) = subplot(2,1,2);\n% plot(S3);\n% linkaxes(ax,'xy')\n%\n% See also: STREAMobj, FLOWobj, STREAMobj/modify, STREAMobj/trunk\n% STREAMobj/STREAMobj2cell, STREAMobj/intersect\n% \n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 5. October, 2013\n\nnarginchk(2,inf)\n\n% are instances spatially aligned?\nfor r = 1:numel(varargin);\n validatealignment(varargin{1},varargin{r})\nend\n\n% is the last input argument a FLOWobj\nif isa(varargin{end},'FLOWobj')\n \n % empty GRIDobj\n G = GRIDobj([]);\n % find common properties of F and G and from F to G\n pg = properties(G);\n pf = properties(varargin{end});\n p = intersect(pg,pf);\n for r = 1:numel(p);\n G.(p{r}) = varargin{end}.(p{r});\n end\n G.Z = false(G.size);\n \n % create a stream raster\n for r = 1:(numel(varargin)-1);\n G.Z(varargin{r}.IXgrid) = true;\n end\n \n % use stream raster to create a new STREAMobj\n S = STREAMobj(varargin{end},G);\n \n \nelse\n \n \n % vertical concatenate indices\n IXgrid = [];\n ix = [];\n ixc = [];\n nnodes = 0;\n for r = 1:numel(varargin)\n IXgrid = [IXgrid;varargin{r}.IXgrid];\n ix = [ix; varargin{r}.ix + nnodes];\n ixc = [ixc; varargin{r}.ixc + nnodes];\n nnodes = nnodes + numel(varargin{r}.IXgrid);\n end\n \n [IXgrid,~,ic] = unique(IXgrid,'stable');\n \n IX = (1:numel(IXgrid))';\n IX = IX(ic);\n ix = IX(ix);\n ixc = IX(ixc);\n \n ixixc = unique([ix(:) ixc(:)],'rows','stable');\n ix = ixixc(:,1);\n ixc = ixixc(:,2);\n \n [ix,ixc] = updatetoposort(nnodes,ix,ixc);\n \n S = varargin{r};\n S.ix = ix;\n S.ixc = ixc;\n S.IXgrid = IXgrid;\n \n [r,c] = ind2sub(S.size,S.IXgrid);\n xy = double([r c ones(numel(S.IXgrid),1)])*S.refmat;\n S.x = xy(:,1);\n S.y = xy(:,2);\n \nend\nend \n\nfunction [ix,ixc] = updatetoposort(nnodes,ix,ixc)\n\n nr= nnodes;\n D = digraph(ix,ixc);\n p = toposort(D);\n \n IX = zeros(nr,1,'uint32');\n IX(ix) = ix;\n IXC = zeros(nr,1,'uint32');\n IXC(ix) = ixc;\n \n p = p(:);\n IX = IX(p);\n IXC = IXC(p);\n IX = nonzeros(IX);\n IXC = nonzeros(IXC);\n ix = double(IX(:));\n ixc = double(IXC(:));\nend\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "netdist.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/netdist.m", "size": 3816, "source_encoding": "utf_8", "md5": "fa9cee81d7efe936d657212e04678a0e", "text": "function d = netdist(S,a,varargin)\n\n%NETDIST distance transform on a stream network\n%\n% Syntax\n%\n% d = netdist(S,a)\n% d = netdist(S,ix)\n% d = netdist(S,I)\n% d = netdist(S,c)\n% d = netdist(...,pn,pv,...)\n% \n% Description\n%\n% netdist computes the distance along a stream network S. It calculates\n% the distance of each node in the network from the nearest non-zero\n% node in the node-attribute list a.\n%\n% Input arguments\n%\n% S STREAMobj\n% a logical node-attribute list\n% ix index into GRIDobj\n% I logical GRIDobj\n% c all strings accepted by the function streampoi. For example,\n% d = netdist(S,'outlet','dir','up') is the same as S.distance.\n%\n% Parameter name/value pairs\n%\n% 'dir' 'both' (default) calculates the distance in upstream and\n% downstream direction. 'up' calculates distances only in\n% upstream direction and 'down' in downstream direction.\n% \n% 'split' false (default) or true. If true, netdist will do the\n% computation in parallel on each drainage basin. If the\n% Parallel Computing Toolbox is available, that may be \n% faster. However, splitting the network in its connected\n% components produces some considerable computational\n% overhead.\n%\n% 'distance' By default, distance is S.distance, the distance from the \n% outlet. Yet, any other continuous increasing function can\n% be used, e.g. chi (see chitransform).\n%\n% Output arguments\n%\n% d node-attribute list with distances. Nodes that cannot be\n% reached will have a distance of inf. \n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',500);\n% IX = randlocs(S,100);\n% [x,y] = ind2coord(DEM,IX);\n% d = netdist(S,IX);\n% plotc(S,d)\n% hold on\n% plot(x,y,'ok');\n%\n%\n%\n% See also: STREAMobj/distance, \n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 31. March, 2022\n\n% Check input arguments\np = inputParser;\np.FunctionName = 'STREAMobj/netdist';\naddParameter(p,'split',false,@(x) isscalar(x));\naddParameter(p,'dir','both');\naddParameter(p,'distance',S.distance);\nparse(p,varargin{:});\n\n% validate direction\ndirection = validatestring(p.Results.dir,{'both','up','down'});\n\n% distance\ndist = p.Results.distance;\n\n% handle input\nif isa(a,'GRIDobj')\n a = logical(getnal(S,a));\nelseif ischar(a)\n a = streampoi(S,a,'logical');\nelseif ~isnal(S,a)\n a = ismember(S.IXgrid,a);\nelseif isnal(S,a)\n a = logical(a);\nend\n\n% run in parallel\nif ~p.Results.split\n % computations are done in netdistsub\n d = netdistsub(S,a,direction,dist);\nelse\n [CS,locb] = STREAMobj2cell(S);\n nrbasins = numel(CS);\n if nrbasins == 1\n d = netdistsub(S,a,direction,dist);\n else\n DIST = cellfun(@(ix) dist(ix),locb,'UniformOutput',false);\n D = cell(nrbasins,1);\n A = cellfun(@(ix) a(ix),locb,'UniformOutput',false);\n parfor r = 1:nrbasins\n D{r} = netdistsub(CS{r},A{r},direction,DIST{r});\n end\n d = zeros(size(a));\n for r = 1:nrbasins\n d(locb{r}) = D{r};\n end\n \n end\nend\nend\n\nfunction d = netdistsub(S,a,direction,dist)\n\nix = S.ix;\nixc = S.ixc;\ndd = abs(dist(S.ix) - dist(S.ixc));\n% dd = hypot(S.x(ix)-S.x(ixc),S.y(ix)-S.y(ixc));\nd = inf(size(a));\nd(logical(a)) = 0;\n\nswitch direction\n case {'down','both'}\n for r = 1:numel(S.ix)\n d(ixc(r)) = min(d(ix(r))+dd(r),d(ixc(r)));\n end\nend\n\nswitch direction\n case {'up','both'}\n \n for r = numel(ix):-1:1\n d(ix(r)) = min(d(ixc(r))+dd(r),d(ix(r)));\n end\nend\n \nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "loessksn.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/loessksn.m", "size": 3693, "source_encoding": "utf_8", "md5": "70fdb9e5b80407ffc3b3f64ce980280b", "text": "function [k,zhat] = loessksn(S,DEM,A,varargin)\n\n%LOESSKSN Loess-smoothed river steepness\n%\n% Syntax\n%\n% k = loessksn(S,DEM,A)\n% k = loessksn(S,DEM,A,'pn',pv,...)\n%\n% Description\n%\n% loessksn calculates the chitransformation of the horizontal river\n% coordinate. Based on the transformed coordinate, it then calculates\n% river gradient based on a loess regression (locally estimated\n% scatterplot smoothing). The loess regression performs a locally\n% weighted linear regression and returns the regression slope as\n% estimate of ksn. The weights are derived from a tricubic weight\n% function. Note that only downstream pixels are included in the\n% estimate.\n% \n% Input parameters\n%\n% S STREAMobj\n% DEM Digital elevation model (GRIDobj or nal)\n% A Upslope area (GRIDobj or nal) as returned by flowacc\n% \n% Parameter name/value pairs\n% \n% 'a0' Reference area {1 m^2}\n% 'mn' river concavity (theta) {0.45}\n% 'ws' window size {11}\n% 'parallel' run in parallel {true} or false\n%\n% Output arguments\n%\n% k node-attribute list (nal) with smoothed ksn values\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% A = flowacc(FD);\n% S = STREAMobj(FD,A>1000);\n% S = klargestconncomps(S);\n% DEM = imposemin(S,DEM);\n% k = loessksn(S,DEM,A,'parallel',false);\n% plotc(S,k)\n%\n% See also: chitransform, ksn, smooth\n% \n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 11. May, 2022\n\n\np = inputParser;\naddParameter(p,'mn',0.45);\naddParameter(p,'a0',1);\naddParameter(p,'ws',11,@(x) validateattributes(x,{'single','double'},{'scalar','positive','integer'}))\naddParameter(p,'parallel',true)\nparse(p,varargin{:})\n\n% get node attribute list with elevation values\nif isa(DEM,'GRIDobj')\n validatealignment(S,DEM);\n z = getnal(S,DEM);\nelseif isnal(S,DEM)\n z = DEM;\nelse\n error('Imcompatible format of second input argument')\nend\n\n% get node attribute list with upstream area values\nif isa(A,'GRIDobj')\n validatealignment(S,A);\n a = getnal(S,A);\nelseif isnal(S,A)\n a = A;\nelse\n error('Imcompatible format of second input argument')\nend\n\n% ------ run in parallel -------\nif p.Results.parallel\n [CS,locb] = STREAMobj2cell(S);\n Cz = cellfun(@(ix) z(ix),locb,'UniformOutput',false);\n Ca = cellfun(@(ix) a(ix),locb,'UniformOutput',false);\n\n Ck = cell(numel(CS),1);\n params = p.Results;\n params.parallel = false;\n\n parfor r = 1:numel(CS)\n Ck{r} = loessksn(CS{r},Cz{r},Ca{r},params);\n end\n\n k = getnal(S);\n for r = 1:numel(CS)\n k(locb{r}) = Ck{r};\n end\n return\nend\n\n% ------- parallel ends here -----------\n \nn = numel(S.x);\nM = sparse(S.ix,S.ixc,1,n,n);\nM = M+speye(n);\nM = M^p.Results.ws;\n\nd = chitransform(S,a,'a0',p.Results.a0,'mn',p.Results.mn);\n% d = S.distance;\n\n[i,j] = find(M);\nNEIGHS = accumarray(i,j,[n 1],@(x){x});\n\nif nargout == 1\n k = cellfun(@(i,j) wregress(i,j),num2cell((1:n)'),NEIGHS);\nelse\n [k,zhat] = cellfun(@(i,j) wregress(i,j),num2cell((1:n)'),NEIGHS);\nend\n\nfunction [b,zhat] = wregress(ix,ixc)\n dij = d(ixc);\n if numel(dij)<=2\n b = 0;\n zhat = z(ix);\n return\n end\n\n wij = d(ixc)-d(ix);\n wij = wij / max(abs(wij));\n % calculate tricubic weight function\n wij = (1-abs(wij).^3).^3;\n wij = max(wij,0);\n% wij(abs(dij)>1) = 0;\n wij = wij/sum(wij);\n\n zij = z(ixc);\n nr = numel(ixc);\n W = spdiags(sqrt(wij),0,nr,nr);\n b = (W*[ones(nr,1) dij])\\(W*zij);\n% if nargout == 2\n zhat = [1 d(ix)]*b;\n% end\n\n b = b(2);\n\nend\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "intersect.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/intersect.m", "size": 2384, "source_encoding": "utf_8", "md5": "bfb31c873cc2737ec5302fb066bd8081", "text": "function S = intersect(varargin)\n\n%INTERSECT intersect different instances of STREAMobj \n%\n% Syntax\n%\n% S = intersect(S1,S2,...)\n%\n% Description\n%\n% intersect combines different instances of STREAMobj into a new STREAMobj.\n% All STREAMobjs must have been derived\n% from the same FLOWobj (e.g., all STREAMobjs are subgraphs of the\n% FLOWobj). If this is not the case, the function might have an\n% unexpected behavior. In terms of set theory, the functions produces\n% an intersection of the nodes in all instances of S.\n%\n% Input arguments\n%\n% S1, S2, ... several instances of STREAMobj\n%\n% Output arguments\n%\n% S STREAMobj\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% A = flowacc(FD);\n% S = STREAMobj(FD,A>1000);\n% % get trunk streams of streamorder 3\n% Sn = intersect(trunk(S),modify(S,'streamorder',3));\n% plot(S,'r')\n% hold on\n% plot(Sn,'b')\n% legend('Stream network','Trunk rivers with streamorder = 3')\n% \n%\n% See also: STREAMobj, FLOWobj, STREAMobj/modify, STREAMobj/trunk\n% STREAMobj/STREAMobj2cell, STREAMobj/union\n% \n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 5. October, 2013\n\n\n% are instances spatially aligned?\nfor r = 1:numel(varargin);\n validatealignment(varargin{1},varargin{r})\nend\n\nn = numel(varargin);\nnrc = prod(varargin{1}.size);\nM = sparse(nrc,nrc);\nfor r = 1:n\n ix = varargin{r}.IXgrid(varargin{r}.ix);\n ixc = varargin{r}.IXgrid(varargin{r}.ixc);\n M = M + sparse(ix,ixc,ones(size(ix)),nrc,nrc);\nend\n\nI = M==n;\n[ix,ixc] = find(I);\n[IXgrid,~,ic] = unique([ix;ixc]);\nix = ic(1 : numel(ix))';\nixc = ic((numel(ixc)+1) : end)';\n\n[ix,ixc] = updatetoposort(numel(IXgrid),ix,ixc);\n\nS = varargin{1};\n\nS.ix = ix;\nS.ixc = ixc;\nS.IXgrid = IXgrid;\n\n[r,c] = ind2sub(S.size,S.IXgrid);\nxy = double([r c ones(numel(S.IXgrid),1)])*S.refmat;\nS.x = xy(:,1);\nS.y = xy(:,2);\n\n\n\n\n\nend\n\nfunction [ix,ixc] = updatetoposort(nnodes,ix,ixc)\n\n nr= nnodes;\n D = digraph(ix,ixc);\n p = toposort(D);\n \n IX = zeros(nr,1,'uint32');\n IX(ix) = ix;\n IXC = zeros(nr,1,'uint32');\n IXC(ix) = ixc;\n \n p = p(:);\n IX = IX(p);\n IXC = IXC(p);\n IX = nonzeros(IX);\n IXC = nonzeros(IXC);\n ix = double(IX(:));\n ixc = double(IXC(:));\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "densify.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/densify.m", "size": 2449, "source_encoding": "utf_8", "md5": "4b475448dfd27966658ecbfe4ca50e58", "text": "function varargout = densify(S,spacing)\n\n%DENSIFY Increase number of vertices in stream network using splines\n%\n% Syntax\n%\n% [x,y] = densify(S,spacing)\n% MS = densify(S,spacing)\n%\n% Description\n%\n% This function increases the number of vertices in a stream network\n% (STREAMobj) using spline interpolation. The function returns either\n% nan-separated lists of x- and y-coordinates or a mapstruct (MS) which\n% can be exported to a shapefile using the function shapewrite\n% (requires the mapping toolbox).\n%\n% Input arguments\n%\n% S STREAMobj\n% spacing spacing of vertices in the resampled network (e.g. 5 [m])\n%\n% Output arguments\n%\n% x,y nan-separated coordinate vectors\n% MS mapstruct\n%\n%\n% See also: STREAMobj\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 16. Octobre, 2014\n\n\n\nif nargout == 2\n I = streampoi(S,'co','logical');\n [x,y,d,i] = STREAMobj2XY(S,S.distance,I);\n \n ixe = find(isnan(x)) - 1;\n ixe = ixe(:);\n ixs = [1; ixe(1:end-1)+2];\n \n xn = [];\n yn = [];\n for r = 1:numel(ixs);\n % vector with interpolation locations\n dmax = d(ixs(r));\n dmin = d(ixe(r));\n \n dd = linspace(dmin,dmax,max(ceil((dmax-dmin)/spacing),2));\n \n % vector with confluence locations\n dc = d(ixs(r):ixe(r));\n ii = i(ixs(r):ixe(r));\n dc = dc(logical(ii));\n \n dd = unique([dd(:);dc(:)],'sorted');\n \n xxyy = splinedensify(d(ixs(r):ixe(r)),x(ixs(r):ixe(r)),y(ixs(r):ixe(r)),dd);\n \n xn = [xn; xxyy(:,1); nan];\n yn = [yn; xxyy(:,2); nan];\n \n end\n varargout{1} = xn;\n varargout{2} = yn;\n \n \nelse\n \n MS = STREAMobj2mapstruct(S);\n \n for r = 1:numel(MS);\n x = MS(r).X;\n y = MS(r).Y;\n \n x = x(1:end-1);\n y = y(1:end-1);\n \n x = x(:);\n y = y(:);\n d = [0; cumsum(sqrt(diff(x).^2 + diff(y).^2))]';\n \n dd = 0:spacing:d(end);\n \n if dd(end) ~= d(end);\n dd(end+1) = d(end);\n end\n \n xxyy = splinedensify(d(:),x(:),y(:),dd(:));\n MS(r).X = [xxyy(:,1);nan];\n MS(r).Y = [xxyy(:,2);nan];\n \n end\n varargout{1} = MS;\nend\n \n \n \n\nend\n\n\n\n\n\nfunction xxyy = splinedensify(d,x,y,dd)\n\nxxyy = spline(d,[x y]',dd);\nxxyy = xxyy';\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "mnoptim.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/mnoptim.m", "size": 7461, "source_encoding": "utf_8", "md5": "367778c000e27de046274a6a31e5aca0", "text": "function [mn,results] = mnoptim(S,DEM,A,varargin)\n\n%MNOPTIM Bayesian optimization of the mn ratio\n%\n% Syntax\n% \n% [mn,results] = mnoptim(S,DEM,A)\n% [mn,results] = mnoptim(S,z,a)\n% [mn,results] = mnoptim(...,pn,pv,...)\n%\n% Description\n%\n% mnoptim uses Bayesian optimization to find an optimal mn-ratio by\n% minimizing a cross-validation loss. Cross-validation is performed\n% using repeated 2-fold validation on individual stream networks\n%\n% Input arguments\n%\n% S STREAMobj\n% DEM Digital elevation model (GRIDobj)\n% A upstream area (in pixels) as returned by the function flowacc\n% (GRIDobj)\n% z node-attribute list of elevations\n% a node-attribute list of upstream areas (nr of upstream pixels)\n%\n% Parameter-name value pairs\n%\n% 'optvar' {'mn'},'m','n','m&n'\n% The variable to be optimized. 'mn' optimizes the mn ratio,\n% 'm' finds an optimal value of m for a given value of n.\n% 'n' finds an optimal value of n for a given value of m.\n% 'm&n' find an optimal value of m and n.\n% 'n' value of n, only applicable if 'optvar' is 'm'. Default\n% value is 1.\n% 'm' value of m, only applicable if 'optvar' is 'n'. Default\n% value is 0.5. \n% 'nrange' search range of 'n'. Only applicable if 'optvar' is 'n' or\n% 'm&n'. Default is [0.8 1.5].\n% 'mrange' search range of 'm'. Only applicable if 'optvar' is 'm'.\n% 'm&n'.Default is [0.3 1].\n% 'mnrange' search range of 'mn'. Only applicable if 'optvar' is 'm'.\n% Default is [.1 1].\n% 'a0' reference area (see chitransform). Default is 1e6 m^2.\n% 'lossfun' function to be minimized. Default is 'rmse'. Others are\n% 'linear' and 'coeffdeterm'.\n% 'UseParallel' {true} or false.\n% 'crossval' {true} or false. \n%\n% Other bayesopt parameter name/value pairs (see help bayesopt for details)\n%\n% 'MaxObjectiveEvaluations'\n%\n%\n% Output arguments\n%\n% mn table with results (best point)\n% results BayesianOptimization object. Continue with optimization\n% with the command resultsnew = resume(results).\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% A = flowacc(FD);\n% S = STREAMobj(FD,'minarea',1e6,'unit','map');\n% S = removeedgeeffects(S,FD,DEM);\n% [mn,results] = mnoptim(S,DEM,A,'optvar','mn','crossval',true);\n% \n% See also: chiplot, chitransform, slopearea\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 24. October, 2017\n\np = inputParser; \np.FunctionName = 'STREAMobj/mnoptim';\naddRequired(p,'S',@(x) isa(x,'STREAMobj'));\naddRequired(p,'DEM',@(x) isa(x,'GRIDobj') || isnal(S,x));\naddRequired(p,'A', @(x) isa(x,'GRIDobj') || isnal(S,x));\n\naddParamValue(p,'mnrange',[.1 1],@(x) numel(x)==2);\naddParamValue(p,'optvar','mn');\naddParamValue(p,'n',1);\naddParamValue(p,'m',0.5);\naddParamValue(p,'nrange',[0.8 1.5]);\naddParamValue(p,'mrange',[0.3 1]);\naddParamValue(p,'a0',1e6,@(x) isscalar(x) && isnumeric(x));\naddParamValue(p,'lossfun','rmse',@(x) ischar(x) || isa(x,'function_handle'));\naddParamValue(p,'plot',false);\naddParamValue(p,'crossval',true);\naddParamValue(p,'verbose',0);\naddParamValue(p,'UseParallel',true);\naddParamValue(p,'MaxObjectiveEvaluations',30);\n\n\n\nparse(p,S,DEM,A,varargin{:});\na0 = p.Results.a0;\n\n% get node attribute list with elevation values\nif isa(DEM,'GRIDobj')\n validatealignment(S,DEM);\n z = getnal(S,DEM);\nelseif isnal(S,DEM)\n z = DEM;\nelse\n error('Imcompatible format of second input argument')\nend\n\n% get node attribute list with flow accumulation values\nif isa(A,'GRIDobj')\n validatealignment(S,A);\n a = getnal(S,A);\nelseif isnal(S,A)\n a = A;\nelse\n error('Imcompatible format of second input argument')\nend\nclear A DEM\n\n% set the base level of all streams to zero\nzbase = z;\nfor r = numel(S.ixc):-1:1\n zbase(S.ix(r)) = zbase(S.ixc(r));\nend\nz = z-zbase;\n\n%% ----- beta ------------------------------------------------------------\n% set all rivers to have the same gradient \n\n\n\n\n\n%% -----------------------------------------------------------------------\n\nif p.Results.crossval\n [~,locb] = STREAMobj2cell(S);\n cv = true;\n % Number of connected components\n nrcc = numel(locb);\n if nrcc == 1\n cv = false;\n error('TopoToolbox:mnoptim',['Cross-validation not possible. There is only \\n' ...\n 'one connected component in the stream network.\\n' ...\n 'Set option ''crossval'' to false.']);\n end\nelse\n cv = false;\nend\n\n% get lossfunction\nif ischar(p.Results.lossfun)\n switch p.Results.lossfun\n case 'rmse'\n lossfun = @(x,xhat)mean(sum((x-xhat).^2));\n case 'linear'\n lossfun = @(x,xhat)var((x+1)./(xhat+1));\n case 'linearcc'\n cc = conncomps(S);\n lossfun = @(x,xhat) sum(accumarray(cc,(x+1)./(xhat+1),[],@std)).^2;\n% lossfun = @(x,xhat)var((x+1)./(xhat+1));\n \n case 'coeffdeterm'\n take2elem = @(x) x(2);\n lossfun = @(x,xhat)1-(take2elem(corrcoef(x,xhat))).^2;\n otherwise\n error('unknown loss function')\n end\nelse\n lossfun = p.Results.lossfun;\nend\n\n% Bayes\noptvar = p.Results.optvar;\nisdeterm = ~cv;\npp = gcp('nocreate');\nopts = {'IsObjectiveDeterministic', isdeterm, ...\n 'Verbose', p.Results.verbose,...\n 'UseParallel',~(isempty(pp) & ~p.Results.UseParallel),...\n 'MaxObjectiveEvaluations',p.Results.MaxObjectiveEvaluations,...\n };\n \nswitch optvar\n case 'mn'\n mn = optimizableVariable('mn',p.Results.mnrange); \n results = bayesopt(@(x) fun(x),mn,opts{:});\n case 'm'\n m = optimizableVariable('m',p.Results.mrange);\n n = p.Results.n;\n results = bayesopt(@(x) fun(x),m,opts{:}); \n case 'n'\n n = optimizableVariable('n',p.Results.nrange);\n m = p.Results.m;\n results = bayesopt(@(x) fun(x),n,opts{:});\n case 'm&n'\n m = optimizableVariable('m',p.Results.mrange);\n n = optimizableVariable('n',p.Results.nrange);\n results = bayesopt(@(x) fun(x),[m n],opts{:});\n \nend\n\nmn = bestPoint(results);\n\n\n\n% loss function\nfunction lss = fun(x)\n\n\nswitch optvar\n case 'mn'\n c = chitransform(S,a,'mn',x.mn,'a0',a0); \n case 'm'\n c = chitransform(S,a,'mn',x.m/n,'a0',a0); \n case 'n'\n c = chitransform(S,a,'mn',m/x.n,'a0',a0); \n case 'm&n'\n c = chitransform(S,a,'mn',x.m/x.n,'a0',a0); \nend\n\nif ~cv \n % no cross-validation\n b = z\\c;\n zhat = b*c;\n lss = lossfun(z/max(z),zhat/max(zhat));\nelse\n % cross validation\n LSS = zeros(5,1);\n for iter = 1:numel(LSS)\n conncomptrain = randperm(nrcc,ceil(nrcc/2));\n CC = false(nrcc,1);\n CC(conncomptrain) = true;\n ixtrain = vertcat(locb{CC});\n b = z(ixtrain)\\c(ixtrain);\n ixval = vertcat(locb{~CC});\n zhat = b*c(ixval);\n zt = z(ixval);\n LSS(iter) = lossfun(zt/max(zt),zhat/max(zhat));\n% LSS(iter) = lossfun(zt/prctile(zt,75),zhat/prctile(zhat,75));\n end\n lss = mean(LSS);\nend\n \n\nend\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "sinuosity.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/sinuosity.m", "size": 1689, "source_encoding": "utf_8", "md5": "c99b8b777c1a1ad9d0192eb994281fa0", "text": "function s = sinuosity(S,seglength)\n\n%SINUOSITY sinuosity coefficient \n%\n% Syntax\n%\n% s = sinuosity(S,seglength)\n%\n% Description\n%\n% The sinuosity is the actual river length divided by the shortest path\n% length. This function calculates the sinuosity for a streamnetwork S\n% along segments of the network with length seglength. seglength is the\n% distance in map units and should be large enough (e.g. 10000 m)\n% depending on the spatial scale of the study.\n%\n% Input arguments\n%\n% S STREAMobj\n% seglength segment length\n%\n% Output arguments\n%\n% s node-attribute list with sinuosity\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S);\n% S = trunk(S);\n% s = sinuosity(S,5000);\n% imageschs(DEM,[],'colormap',[1 1 1],'colorbar',false)\n% hold on\n% plotc(S,s);\n% h = colorbar;\n% h.Label.String = 'Sinuosity';\n%\n% See also: STREAMobj, STREAMobj/labelreach\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 21. March, 2018\n\n\nif seglength < (S.cellsize*3)\n error('Choose a larger value of seglength');\nend\n\nlabel = labelreach(S,'seglength',seglength);\nd = S.distance;\nx = S.x;\ny = S.y;\nix = (1:numel(x))';\n\ns = accumarray(label,ix,[max(label) 1],@(ix) sinuosub(ix));\ns = s(label);\n\n\nfunction sval = sinuosub(ix)\n\ndd = d(ix);\nxx = x(ix);\nyy = y(ix);\n\n% Euclidean distance\n[~,ixmin] = min(dd);\n[~,ixmax] = max(dd);\nelength = hypot(xx(ixmin)-xx(ixmax),yy(ixmin)-yy(ixmax));\n\n% curvilinear length\nclength = dd(ixmax)-dd(ixmin);\n\n% sinuosity\nsval = clength/elength; \n\nend\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "chiplot.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/chiplot.m", "size": 11938, "source_encoding": "utf_8", "md5": "da692b7baad4c58c35a3f12d7501079f", "text": "function OUT = chiplot(S,DEM,A,varargin)\n\n%CHIPLOT CHI analysis for bedrock river analysis\n%\n% Syntax\n%\n% C = chiplot(S,DEM,A)\n% C = chiplot(S,z,a)\n% C = chiplot(S,DEM,A,pn,pv,...)\n%\n% Description\n%\n% CHI plots are an alternative to slope-area plots for bedrock river\n% analysis. CHI plots are based on a transformation of the horizontal\n% coordinate that converts a steady-state river profile into a straight\n% line with a slope that is related to the ratio of the uplift rate to\n% the erodibility (Perron and Royden 2012).\n%\n% Input arguments\n%\n% S instance of STREAMobj. The stream network must consist of only \n% one connected component (only one outlet may exist!)\n% DEM digital elevation model (GRIDobj)\n% A flow accumulation as calculated by flowacc (GRIDobj)\n% z elevation values for each node in S (node attribute list)\n% a flowaccumulation values for each node in S (node attribute list)\n%\n% Parameter name/value pairs {default}\n%\n% 'a0': {1e6}\n% reference area in m^2\n%\n% 'mn': {[]}, scalar \n% mn is the ratio of m and n in the stream power equation. The value\n% ranges usually for bedrock rivers between 0.1 and 0.5. If empty, it\n% is automatically found by a least squares approach.\n%\n% 'mnoptim': {'fminsearch'}, 'nlinfit'\n% chiplot finds an optimal value of mn that linearizes the relation\n% between chi and elevation. By default, fminsearch is used. nlinfit\n% requires the statistics and machine learning toolbox but additionally\n% returns 95% confidence intervals of mn. These bounds must, however,\n% be taken with care since their determination violates the assumption\n% of an independent and identically distributed (i.i.d.) variable. Note \n% also that the standard deviation of beta (betase) is determined\n% independently from mn.\n% \n% 'color': color of river profiles, e.g. 'b' or [.4 .4 .6]\n%\n% 'trunkstream': {[]}, STREAMobj\n% instance of STREAMobj that must be a subset of S, e.g. the main river\n% in the network S. The main trunk is highlighted in the plot and can\n% be used to fit the mn ratio (see pn/pv pair 'fitto'). Note that the\n% trunkstream must end at the river network's root (outlet).\n%\n% 'colorMainTrunk': color of the trunk stream, e.g. 'b' or [.4 .4 .6].\n% Applies only if 'trunkstream' (see above) is supplied.\n%\n% 'fitto': {'all'},'ts', \n% choose which data should be used for fitting the mn ratio.\n% 'all' fits mn to all streams in S\n% 'ts' fits mn only to the trunkstream which must be provided with the\n% pn-pv pair trunkstream.\n%\n% 'plot': {true}, false\n% plot the CHIplot.\n%\n% 'mnplot': {false}, true\n% plot data for various values of mn [.1:.1:.9]\n%\n% Output arguments\n%\n% C structure array that contains\n% .mn ratio of m and n\n% .mnci 95% intervals of mn (empty if 'mnoptim' is set to\n% fminsearch)\n% .beta slope of the best fit line\n% .betase standard error of beta\n% .a0 reference area\n% .ks channel steepness index\n% .chi CHI values \n% .elev elevation\n% .elevbl elevation above baselevel\n% .distance distance from outlet\n% .pred predicted elevation\n% .res residual elevation\n%\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','carve');\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S);\n% c = chiplot(S,DEM,flowacc(FD));\n%\n% See also: flowpathapp, STREAMobj, FLOWobj/flowacc, STREAMobj/trunk,\n% STREAMobj/modify, STREAMobj/getnal, STREAMobj/chitransform\n%\n% References:\n% \n% Perron, J. & Royden, L. (2013): An integral approach to bedrock river \n% profile analysis. Earth Surface Processes and Landforms, 38, 570-576.\n% [DOI: 10.1002/esp.3302]\n% \n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de) and \n% % Karina Marques (https://github.com/karina-marques)\n% Date: 30. June, 2022\n\n% update 11. June, 2014\n% supports node attribute lists as input data (DEM,A)\n% update 4. October, 2016\n% lets you choose the algorithm to find the optimal value of mn. \n% update 30. June, 2022\n% added options to color the output by Karina Marques \n\nax = gca;\n\nif verLessThan('matlab','8.4')\n % For MATLAB versions before 2014b\n clr = 'b';\nelse\n % For MATLAB versions with the new graphics engine\n colororderindex = mod(ax.ColorOrderIndex, size(ax.ColorOrder,1));\n if colororderindex==0; colororderindex=size(ax.ColorOrder,1); end\n clr = ax.ColorOrder(colororderindex,:);\nend\n\n% Parse Inputs\np = inputParser; \np.FunctionName = 'chiplot';\naddRequired(p,'S',@(x) isa(x,'STREAMobj'));\naddRequired(p,'DEM', @(x) isa(x,'GRIDobj') || isequal(size(S.IXgrid),size(x)));\naddRequired(p,'A', @(x) isa(x,'GRIDobj') || isequal(size(S.IXgrid),size(x)))\n\naddParamValue(p,'color',clr);\naddParamValue(p,'colorMainTrunk',clr);\naddParamValue(p,'mn',[],@(x) isscalar(x) || isempty(x));\naddParamValue(p,'trunkstream',[],@(x) isa(x,'STREAMobj') || isempty(x));\naddParamValue(p,'plot',true,@(x) isscalar(x));\naddParamValue(p,'mnplot',false,@(x) isscalar(x));\naddParamValue(p,'fitto','all');\naddParamValue(p,'mnoptim','fminsearch');\naddParamValue(p,'a0',1e6,@(x) isscalar(x) && isnumeric(x));\naddParamValue(p,'betamethod','ls',@(x) ischar(validatestring(x,{'ls','lad'})));\naddParamValue(p,'mnmethod','ls',@(x) ischar(validatestring(x,{'ls','lad'})));\n\nparse(p,S,DEM,A,varargin{:});\nS = p.Results.S;\nDEM = p.Results.DEM;\nA = p.Results.A;\nfitto = p.Results.fitto;\ncolor = p.Results.color;\ncolorMainTrunk = p.Results.colorMainTrunk;\nbetamethod = validatestring(p.Results.betamethod,{'ls','lad'});\nmnmethod = validatestring(p.Results.mnmethod,{'ls','lad'});\n\n% to which stream should the data be fitted? Trunkstream or all streams?\nif ischar(fitto)\n fitto = validatestring(fitto,{'all','ts'}); \n if strcmpi(fitto,'ts') && isempty(p.Results.trunkstream)\n error('TopoToolbox:wronginput',...\n ['You must supply a trunkstream, if you use the parameter \\n'...\n 'fitto together with the option ts']);\n end\nend\n\n% nr of nodes in the entire stream network\noutlet = streampoi(S,'outlet','logical');\nif nnz(outlet)>1\n % there must not be more than one outlet (constraint could be removed\n % in the future).\n error('TopoToolbox:chiplot',...\n 'The stream network must not have more than one outlet');\nend\n\n% reference drainage area\na0 = p.Results.a0; % m^2\n% elevation values at nodes\nif isa(DEM,'GRIDobj')\n zx = double(getnal(S,DEM));\n % elevation at outlet\n zb = zx(outlet);\nelse\n zx = double(DEM);\n zb = double(DEM(outlet));\nend\n\nif isa(A,'GRIDobj');\n % a is the term inside the brackets of equation 6b \n a = double(a0./(A.Z(S.IXgrid)*(A.cellsize.^2)));\nelse\n a = double(a0./(double(A) .* S.cellsize.^2));\nend\n\n% x is the cumulative horizontal distance in upstream direction\nx = S.distance;\n\n% use trunkstream for fitting and display\nswitch fitto\n case 'all'\n SFIT = S;\n Lib = true(size(x));\n\n case 'ts'\n SFIT = p.Results.trunkstream;\n [Lia,Lib] = ismember(SFIT.IXgrid,S.IXgrid);\n if any(~Lia)\n error('TopoToolbox:chiplot',...\n ['The main trunk stream must be a subset of the stream network.\\n'...\n 'Map a trunk stream with flowpathtool and use the STREAMobj as \\n'...\n '3rd input argument ( flowpathtool(FD,DEM,S) ).']) ;\n end\nend\n\n% find values of the ratio of m and n that generate a linear Chi plot\n% uses fminsearch\nif isempty( p.Results.mn );\n mn0 = 0.5; % initial value\n % fminsearch is a nonlinear optimization procedure that doesn't require\n % the statistics toolbox\n switch p.Results.mnoptim\n case 'fminsearch'\n mn = fminsearch(@mnfit,mn0);\n ci = [];\n case 'nlinfit'\n ztest = zx(Lib)-zb;\n ztest = ztest./max(ztest);\n [mn0,R,J,CovB,MSE,ErrorModelInfo] = nlinfit(a,ztest,@mnfit,mn0);\n ci = nlparci(mn0,R,'jacobian',J)\n end\nelse\n % or use predefined mn ratio.\n mn = p.Results.mn;\n ci = [];\nend\n\n% plot different values of mn\nif p.Results.mnplot\n mntest = .1:.1:.9;\n cvec = jet(numel(mntest));\n figure('DefaultAxesColorOrder',cvec);\n chitest = zeros(numel(Lib),numel(mntest));\n \n for r = 1:numel(mntest)\n chitest(:,r) = cumtrapz(S,a.^mntest(r));\n end\n plot(chitest,zx(Lib)-zb,'x');\n xlabel('\\chi [m]')\n ylabel('elevation [m]');\n title('\\chi plots for different values of mn')\n legnames = cellfun(@(x) num2str(x),num2cell(mntest),'uniformoutput',false);\n legend(legnames);\nend\n\n% calculate chi\nchi = cumtrapz(S,a.^mn);\n% now use chi to fit beta\nswitch betamethod\n case 'ls'\n % least squares\n beta = chi(Lib)\\(zx(Lib)-zb);\n case 'lad'\n % least absolute deviations\n beta = fminsearch(@(b) sum(abs(b*chi(Lib) - (zx(Lib)-zb))),0.0334);\nend\n\nn = nnz(Lib);\nSSE = sum((chi(Lib)*beta - (zx(Lib)-zb)).^2);\nSSZ = sum((zx(Lib)-mean(zx(Lib))).^2);\nR2 = 1-(SSE/SSZ);\n\nbetase = sqrt((SSE/(n-2))./(sum((chi(Lib)-mean(chi(Lib))).^2)));\n\n\nif p.Results.plot\n figure\n % plot results\n order = S.orderednanlist;\n I = ~isnan(order);\n c = nan(size(order));\n c(I) = chi(order(I));\n zz = nan(size(order));\n zz(I) = zx(order(I));\n \n plot(c,zz,'-','color', color);\n hold on\n\n if ~isempty( p.Results.trunkstream )\n switch p.Results.fitto\n case 'all'\n % check trunkstream\n \n ST = p.Results.trunkstream;\n [Lia,Lib] = ismember(ST.IXgrid,S.IXgrid);\n \n if any(~Lia)\n error('TopoToolbox:chiplot',...\n ['The main trunk stream must be a subset of the stream network.\\n'...\n 'Map a trunk stream with flowpathtool and use the STREAMobj as \\n'...\n '3rd input argument ( flowpathtool(FD,DEM,S) ).']) ;\n end\n case 'ts'\n ST = SFIT;\n end\n \n order = ST.orderednanlist; \n I = ~isnan(order);\n c = nan(size(order));\n chifit = chi(Lib);\n zxfit = zx(Lib);\n c(I) = chifit(order(I));\n zz = nan(size(order));\n zz(I) = zxfit(order(I));\n\n plot(c,zz,'color', colorMainTrunk,'LineWidth',2);\n end\n \n refline(beta,zb);\n hold off\n xlabel('\\chi [m]')\n ylabel('elevation [m]');\nend\n\n% write to output array\nif nargout == 1\n \n OUT.mn = mn;\n OUT.mnci = ci;\n OUT.beta = beta;\n OUT.betase = betase;\n OUT.a0 = a0;\n OUT.ks = beta*a0^mn;\n OUT.R2 = R2;\n OUT.x_nal = S.x;\n OUT.y_nal = S.y;\n OUT.chi_nal = chi;\n OUT.d_nal = S.distance;\n \n [OUT.x,...\n OUT.y,...\n OUT.chi,...\n OUT.elev,...\n OUT.elevbl,...\n OUT.distance,...\n OUT.pred,...\n OUT.area] = STREAMobj2XY(S,chi,DEM,zx-zb,S.distance,beta*chi,A.*(S.cellsize^2));\n OUT.res = OUT.elevbl-OUT.pred;\n\nend\n \n\n\n%% fitting function\nfunction sqres = mnfit(varargin)\n \n if nargin == 1;\n mn = varargin{1};\n elseif nargin == 2;\n mn = varargin{1};\n a = varargin{2};\n end\n\n% calculate chi with a given mn ratio\n% and integrate in upstream direction\nCHI = cumtrapz(SFIT,a(Lib).^mn);\n% normalize both variables\nCHI = CHI ./ max(CHI);\n\nif nargin == 2;\n sqres = CHI;\n return\nend\n\nz = zx(Lib)-zb;\nz = z./max(z);\n% calculate the residuals and minimize their squared sums\n\nswitch mnmethod\n case 'ls'\n sqres = sum((CHI - z).^2);\n case 'lad'\n sqres = sum(sqrt(abs(CHI-z)));\nend \n\nend\n\nend\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "mnoptimvar.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/mnoptimvar.m", "size": 5058, "source_encoding": "utf_8", "md5": "5b0db0503d47a7470bccd2d10d0abf32", "text": "function [mn,cm,zm,zsd] = mnoptimvar(S,DEM,A,varargin)\n\n%MNOPTIMVAR optimize the mn ratio using minimum variance method\n%\n% Syntax\n%\n% mn = mnoptimvar(S,DEM,A)\n% mn = mnoptimvar(S,z,a)\n% mn = mnoptimvar(...,pn,pv,...)\n% [mn,cm,zm,zsd] = ...\n%\n% Description\n%\n% mnoptimvar finds an optimal value of the mn-ratio by minimizing the\n% variance of elevation values conditional on chi. The procedure places\n% nodes of the river network into chi-distance bins and calculates the\n% variance of elevation values in each bin. The objective function is\n% the weighted mean of these variances.\n%\n% Input arguments\n%\n% S STREAMobj\n% DEM Digital elevation model\n% A Flow accumulation grid \n% z node-attribute list of elevations\n% a node-attribute list of flow accumulation\n%\n% Parameter name/value pairs\n%\n% 'varfun' function to calculate elevation variability in chi-distance \n% bins. Default is the interquartile range (@iqr), but any \n% other measure of variability may be suitable, e.g. @var,\n% @std, @mad, @robustcov, @range.\n% 'mn0' starting value for mn {0.5}.\n% 'distbins' nr of distance bins {100}.\n% 'minstream' minimum number of streams that should be included in\n% calculation a variance value {2}.\n% 'funoptim' {'fminsearch'} (so far only choice)\n% 'optimize' {true} or false. If false, then the function won't perform\n% an optimization, but will use mn0 as mn-ratio.\n% 'plot' {true} or false\n% 'zerobaselevel' {false} or true. Set all outlet elevations to zero.\n% 'a0' reference area {1e6}\n% \n% Output arguments\n%\n% mn mn-ratio\n% cm binned chi values\n% zm average elevation in chi bins\n% zsd standard deviation of elevations in chi bins\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% A = flowacc(FD);\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S);\n% mn = mnoptimvar(S,DEM,A);\n% \n%\n% See also: STREAMobj, STREAMobj/mnoptim\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 29. January, 2020\n\n% parse inputs\np = inputParser;\naddParameter(p,'varfun',@iqr,@(x) isa(x,'function_handle'));\naddParameter(p,'distbins',100,@(x) isscalar(x) && x > 1);\naddParameter(p,'minstreams',2,@(x) isscalar(x) && x > 1);\naddParameter(p,'mn0',0.5,@(x) isscalar(x) && x > 0);\naddParameter(p,'funoptim','fminsearch')\naddParameter(p,'plot',true)\naddParameter(p,'optimize',true);\naddParameter(p,'zerobaselevel',false);\naddParameter(p,'a0',1e6);\nparse(p,varargin{:});\n\n% get parameters\nvarfun = p.Results.varfun;\ndistbins = p.Results.distbins;\nminstreams = p.Results.minstreams;\na0 = p.Results.a0;\n \n\n% get node attribute list with flow accumulation values\nif isa(A,'GRIDobj')\n validatealignment(S,A);\n a = getnal(S,A);\nelseif isnal(S,A)\n a = A;\nelse\n error('Imcompatible format of second input argument')\nend\n\n% get node attribute list with elevation values\nif isa(DEM,'GRIDobj')\n validatealignment(S,DEM);\n z = getnal(S,DEM);\nelseif isnal(S,DEM)\n z = DEM;\nelse\n error('Imcompatible format of second input argument')\nend\n\n% z must be double precision\nz = double(z);\nif p.Results.zerobaselevel\n z = zerobaselevel(S,z);\nend\ncopyz = z;\nz = z - min(z) + 1;\n\nif p.Results.optimize\n% calculate stream \nlabel = labelreach(S);\n\n% choose optimizer\nswitch lower(p.Results.funoptim)\n case 'fminsearch'\n mn = fminsearch(@(mn) chivar(mn), log(p.Results.mn0));\n mn = exp(mn);\nend\nelse \n mn = p.Results.mn0;\nend\n\nif nargout > 1 || p.Results.plot\n c = chitransform(S,a,'mn',mn,'a0',a0);\n [~,~,bin] = histcounts(c,distbins);\n zm = accumarray(bin,copyz,[],@mean,0);\n zsd = accumarray(bin,copyz,[],@std,0);\n cm = accumarray(bin,c,[],@mean,0);\n \nend\n\nif p.Results.plot\n plotdz(S,copyz,'distance',c,'color',[.7 .7 .7])\n hold on\n errorbar(cm,zm,zsd,'k.')\n plot(cm,zm,'ks-');\n hold off\n xlabel('\\chi [m]')\nend\n \n\n%% objective function\nfunction v = chivar(mn)\n \n % calculate chitransform\n c = chitransform(S,a,'mn',exp(mn),'a0',a0);\n % bin c values into distance bins.\n [~,~,bin] = histcounts(c,distbins);\n \n % calculate the average values within each bin and tributary label\n melev = accumarray([label bin],z,[],@mean,0,true);\n \n % calculate cross-tributary variability using varfun\n n = sum(spones(melev))';\n [~,j,melev] = find(melev);\n v = accumarray(j(n(j)>=minstreams),melev(n(j)>=minstreams),...\n [numel(n) 1],varfun,nan);\n \n % exclude those variances that have less than minstreams values \n I = n < minstreams;\n v(I) = [];\n n(I) = [];\n \n % calculate the weighted average of all variances. The weighting is\n % according to the number of streams used to calculate the variance in\n % each bin.\n n = n/sum(n);\n v = n'*v;\nend\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "extractconncomps.m", "ext": ".m", "path": "topotoolbox-master/@STREAMobj/extractconncomps.m", "size": 3753, "source_encoding": "utf_8", "md5": "97cbe0629081a02fb8b9da18f269a4d0", "text": "function extractconncomps(S)\n\n%EXTRACTCONNCOMPS interactive stream network selection\n%\n% Syntax\n%\n% extractconncomps(S)\n%\n% Description\n%\n% extractconncomps displays a figure and plots the stream network S.\n% Here you can mouse-select individual connected components and export\n% them to the workspace.\n%\n% Input arguments\n%\n% S instance of a STREAMobj\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% S = STREAMobj(FD,A>1000);\n% extractconncomps(S)\n%\n% See also: STREAMobj/klargestconncomps\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 17. August, 2017 \n\n\nCS = STREAMobj2cell(S);\nfx = figure;\n\n% Create push button\nbtn1 = uicontrol('Style', 'pushbutton', 'String', 'Export to workspace',...\n 'Position', [20 20 150 20],...\n 'Callback', @exporttoworkspace); \nbtn1 = uicontrol('Style', 'pushbutton', 'String', 'Switch selection',...\n 'Position', [170 20 150 20],...\n 'Callback', @switchselection); \n\n\nax = axes('parent',fx);\nhold on\nnc = numel(CS);\nclr_nonsel = [.6 .7 .7];\nclr_sel = [0 0 0];\nsel = false(nc,1);\nfor r = 1:nc\n h(r) = plot(CS{r},'color',clr_nonsel);\n h(r).ButtonDownFcn = @highlight;\nend\nbox on\naxis image\ntitle('Click network to select/unselect.')\n\n\n%% --- Highlight function ----\nfunction highlight(h,~)\n\nif isequal(h.Color,clr_nonsel)\n h.Color = clr_sel;\nelse\n h.Color = clr_nonsel;\nend\nend\n\n%% --- Switch selection ----\nfunction switchselection(hh,~)\n for r2 = 1:numel(h)\n if isequal(h(r2).Color,clr_sel)\n h(r2).Color = clr_nonsel;\n else\n h(r2).Color = clr_sel;\n end\n end\nend\n\n%% --- Export to workspace ----\nfunction exporttoworkspace(hh,~)\n\n I = false(nc,1);\n for r2 = 1:numel(h);\n I(r2) = isequal(h(r2).Color,clr_sel);\n end\n n = nnz(I);\n if n==0\n warndlg('No streams available for export.');\n return\n elseif n == 1\n S2 = CS{I};\n else\n CSS = CS(I);\n S2 = union(CSS{:});\n end\n\n prompt = {'Enter variable name:'};\n ptitle = 'Export';\n plines = 1;\n pdef = {'S'};\n answer = inputdlg(prompt, ptitle, plines, pdef);\n if ~isempty(answer) && isvarname(answer{1})\n assignin('base',answer{1},S2);\n else\n return\n end\n\n\n end\n\nend\n\n\n\n\n \n% \n% \n% nrc = numel(S.x);\n% M = sparse(double(S.ix),double(S.ixc),true,nrc,nrc);\n% \n% [L,nc] = conncomps(S);\n% \n% \n% if nargin == 1;\n% \n% hFig = figure('Units','normalized','OuterPosition',[0 0 1 1]);\n% hAx = axes('Parent',hFig);\n% cmap = jet(nc);\n% \n% for r = 1:nc;\n% M2 = spdiags(L==r,0,nrc,nrc)*double(M);\n% [x,y] = gplot(M2,[S.x S.y]);\n% outlet = find((sum(M2,1)' > 0) & (sum(M2,2) == 0));\n% \n% plot(hAx,x,y,'Color',cmap(r,:));\n% hold on\n% plot(hAx,S.x(outlet),S.y(outlet),'*','Color',cmap(r,:));\n% text(S.x(outlet),S.y(outlet),[' ' num2str(r)]);\n% end\n% \n% axis image\n% set(hAx,'Xtick',[],'Ytick',[]);\n% \n% prompt = {'Enter comma separated list of component indices to extract:'};\n% \n% dlg_title = 'Extract connected components';\n% num_lines = 1;\n% options.Resize='on';\n% answer = inputdlg(prompt,dlg_title,num_lines,{''},options);\n% \n% % evaluate answer\n% c = regexp(answer,'(?:\\d*)','match');\n% c = str2double(c{1});\n% else\n% c = cc;\n% if c > nc;\n% error('TopoToolbox:wronginput','The supplied number exceeds the number of components');\n% end\n% end\n% \n% % adapt new STREAMobj to the reduced network\n% L = ismember(L,c);\n% I = L(S.ix);\n% S.ix = S.ix(I);\n% S.ixc = S.ixc(I);\n% \n% IX = cumsum(L);\n% S.ix = IX(S.ix);\n% S.ixc = IX(S.ixc);\n% \n% S.x = S.x(L);\n% S.y = S.y(L);\n% S.IXgrid = S.IXgrid(L);\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "funerosion_impnlin_par.m", "ext": ".m", "path": "topotoolbox-master/ttlem/private/funerosion_impnlin_par.m", "size": 2828, "source_encoding": "utf_8", "md5": "75783ec5ffdbd652177ac64e859f9fc5", "text": "function Z = funerosion_impnlin_par(p,Z,dt, A, S,upl)\n\n% Implicit solution for nonlinear river incision (parallel)\n%\n% Syntax\n%\n% Z = funerosion_impnlin_par(n,Z,dt, A, i,k,dx_ik)\n%\n%\n% Description\n%\n% Implicit solution for nonlinear river incision, calculated by\n% solving the Stream Power Law. This scheme uses a newton rhapson\n% iteration and is unconditionally stable. The function runs in\n% parallel and requires the parallel processing toolbox.\n%\n% Input\n%\n% n slope exponent\n% Z digital elevation model (matrix)\n% dt time step\n% A velocity field\n% S STREAMobj\n%\n% Output\n%\n% Z digital elevation model with adapted river elevation\n%\n% Example\n%\n%\n% See also:\n%\n% Authors: Benjamin Campforts (benjamin.campforts[at]ees.kuleuven.be)\n% Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n%\n% Date: 28. Januari, 2015\n\nif isa(S,'STREAMobj');\n CS = STREAMobj2cell(S,'o',20);\nelse\n S = STREAMobj(S,'minarea',0);\n CS = STREAMobj2cell(S,'o',20);\nend\nCZ = cellfun(@(S) Z(S.IXgrid),CS,'UniformOutput',false);\nCA = cellfun(@(S) A(S.IXgrid),CS,'UniformOutput',false);\n\nparfor iterpar = 1:numel(CS);\n dx_ik = sqrt((CS{iterpar}.x(CS{iterpar}.ix)-CS{iterpar}.x(CS{iterpar}.ixc)).^2 ...\n + ...\n (CS{iterpar}.y(CS{iterpar}.ix)-CS{iterpar}.y(CS{iterpar}.ixc)).^2);\n CZ{iterpar} = funerosion_impnlin_par_sub(p.n,CZ{iterpar},dt,CA{iterpar},CS{iterpar}.ix,CS{iterpar}.ixc,dx_ik);\n \nend\nfor iter2 = 1:numel(CS);\n Z(CS{iter2}.IXgrid) = CZ{iter2};\nend\nend\n\n\nfunction z = funerosion_impnlin_par_sub(n,z,dt,a,i,k,dx_ik)\n\nif p.implCFL\n nrtsteps = ceil(dt/(min(dx_ik)/max(A(:))));\nelse\n nrtsteps=1;\nend\n\n% explicit time step\ndte = dt/nrtsteps;\ntime=dt;\n\n\nwhile time>0\n time=time-dte;\n if time<0\n dte=dte+time;\n time=0;\n end\n Z=Z+dte.*upl;\n for r = numel(i):-1:1;\n \n tt = a(i(r))*dte/(dx_ik(r));\n % z_t\n zt = z(i(r));\n % z_(t+dt) of downstream neighbor\n ztp1d = z(k(r));\n % dx\n dx = dx_ik(r);\n \n % initial value for finding root\n if ztp1d < zt;\n ztp1 = newtonraphson(zt,ztp1d,dx,tt,n);\n else\n ztp1 = zt;\n end\n \n if ~isreal(ztp1) || isnan(ztp1)\n disp('Non real solutions converted to real')\n ztp1=real(ztp1);\n end\n z(i(r))=ztp1;\n end\nend\nend\n\nfunction ztp1 = newtonraphson(zt,ztp1d,dx,tt,n)\n\ntempz = zt;\ntol = inf;\n\nwhile tol > 1e-3;\n % iteratively approximated value\n ztp1 = tempz - (tempz-zt + ...\n (tt*dx) * ...\n ((tempz-ztp1d)./dx)^n) / ...\n (1+n*tt*((tempz-ztp1d)./dx)^(n-1));\n tol = abs(ztp1-tempz);\n tempz = ztp1;\nend\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "linearDiffusion.m", "ext": ".m", "path": "topotoolbox-master/ttlem/private/linearDiffusion.m", "size": 1066, "source_encoding": "utf_8", "md5": "a46308e5bb228e8e7802b4197c983afd", "text": "function DEM=linearDiffusion(DEM,EYE,p,dx2,C,nrc,L,dt)\n% Calcualte linear diffusion using a Crank-Nicolson method\n%\n% Syntax\n%\n% DEM_D=linearDiffusion(DEM,EYE,p,dx2,C,nrc,L,dt)\n%\n% Description\n%\n% Calcualte linear diffusion using a Crank-Nicholson method\n%\n% Input\n%\n% DEM DEM (digital elevation model) (GRIDobj)\n% EYE Identity Matrix\n% p structure array with parameter definitions (see ttlemset)\n% dx2 dx^2\n% C location of river cells\n% nrc number of cells in H1.Z\n% L laplacian\n% dt time step \n% \n% Output\n%\n% DEM DEM, updated for diffusion (GRIDobj)\n%\n% Example\n\nif p.AreaThresh > 0;\n D = EYE + p.D*dt/(2*dx2)*spdiags(~C.Z(:),0,nrc,nrc)*L;\nelse\n D = EYE + p.D*dt/(2*dx2)*L;\nend\n% and solve linear system of equations\n% DEM_D = D\\DEM.Z(:);\nDEM.Z =reshape( pcg_quiet(D,DEM.Z(:),p.DiffTol),DEM.size(1),DEM.size(2));\n\nfunction [x,flag,relres,iter,resvec] = pcg_quiet(varargin)\n[x,flag,relres,iter,resvec] = pcg(varargin{:});\nend\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "get1up1down.m", "ext": ".m", "path": "topotoolbox-master/ttlem/private/get1up1down.m", "size": 547, "source_encoding": "utf_8", "md5": "7f144c307f5574263fd607040a1b3888", "text": "function [ii,kk] = get1up1down(i,k,A)\n% get receiver of receiver and giver of giver...\n% ii and kk will have nans where neighbors do not exist, % either because, there is none % or because the upstream node has a smaller % contribution area.\n\ni = double(i);\nk = double(k);\n\nnrc = numel(A);\n\n% Downstream neighbor\nkk = nan(nrc,1);\nkk(i) = k;\nkk(i) = kk(k);\nkk = kk(i);\n\n% Upstream neighbor\nii = accumarray(k,i,[nrc 1],@getindexwithlargerarea,nan); ii = ii(i);\n\n\nfunction ix = getindexwithlargerarea(ix)\n\n[~,mix] = max(A(ix));\nix = ix(mix);\nend\n\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "preparegui.m", "ext": ".m", "path": "topotoolbox-master/ttlem/private/preparegui.m", "size": 2542, "source_encoding": "utf_8", "md5": "10288e915c28ef730d714cbaddb6ddef", "text": "function hGUI = preparegui(H1)\n\n% prepare GUI for TTLEM\n%\n% Syntax\n%\n% hGui = preparegui(H1)\n%\n%\n\n\n% create figure with panels\nhGUI.fig = figure('Name','TTLEM',...\n 'NumberTitle','off',...\n 'Toolbar','none',...\n 'MenuBar','none',...\n 'Visible','off');\n\nhGUI.main = uipanel('BackgroundColor','white',...\n 'Position',[.25 .25 .75 .75],...\n 'BorderType','none');\n\nhGUI.ax.main = axes('Units','normalized', ...\n 'Position', [0 0 1 1], ...\n 'Parent', hGUI.main, ...\n 'Clipping', 'off', ...\n 'ActivePositionProperty','position',...\n 'XLimMode','auto',...\n 'YLimMode','auto',... \n 'PlotBoxAspectRatio',[1 1 1],...\n 'PlotBoxAspectRatioMode','manual',...\n 'DataAspectRatio',[1 1 1],...\n 'DataAspectRatioMode','manual');%,...\ndaspect(hGUI.ax.main,[1 1 1]); \nhGUI.hIm = imagesc(H1.Z); \n\n% hold on\n% xl = xlim(hGUI.ax.main);\n% yl = ylim(hGUI.ax.main);\n\n\nhGUI.main.SizeChangedFcn = @(varargin) FigSizeHasChanged; %set(hGUI.ax.main,'Position',[0 0 1 1]);\naxis(hGUI.ax.main,'off')\n\n\n% control panel\nhGUI.control = uipanel('Position',[0 0.25 0.25 0.75],...\n 'BorderType','none');\nhGUI.timedisp = uicontrol('Style', 'text', 'String', '0',...\n 'units','normalized',...\n 'Position', [0 .8 1 .1],...\n 'Parent',hGUI.control);\nhGUI.stopbutton = uicontrol('Style', 'togglebutton', 'String', 'Stop',...\n 'units','normalized',...\n 'Position', [0 .7 1 .1],...\n 'Min',false,'Max',true,'value',false,...\n 'Parent',hGUI.control);\n\n\n\n\nhGUI.time = uipanel('Position',[0 0 1 0.25],...\n 'BackgroundColor','white',...\n 'BorderType','line');\nhGUI.ax.time = axes('Parent',hGUI.time);\nhold(hGUI.ax.time,'on');\nxy = get(hGUI.ax.main,'clim');\nhGUI.tsmin = plot(hGUI.ax.time,0,xy(1),'o-','Color',[.5 .5 .5],'MarkerSize',3);\nhGUI.tsmean = plot(hGUI.ax.time,0,mean(H1.Z(~isnan(H1.Z(:)))),'ko-','MarkerSize',3);\nhGUI.tsmax = plot(hGUI.ax.time,0,xy(2),'o-','Color',[.5 .5 .5],'MarkerSize',3);\nlegend([hGUI.tsmin; hGUI.tsmean],'min/max elevation','mean elevation');\n\nxlabel('Time [y]');\nylabel('Elevation [m]');\nset(hGUI.ax.time,'FontSize',8);\n\nbox on;\n\nhGUI.fig.Visible = 'on';\n\n\nfunction FigSizeHasChanged\ndaspect(hGUI.ax.main,[1 1 1]);\n% xl = xlim(hGUI.ax.main);\n% yl = ylim(hGUI.ax.main);\n\n\n\n \nend\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "BC_Disturbance.m", "ext": ".m", "path": "topotoolbox-master/ttlem/LateralDisplacement/BC_Disturbance.m", "size": 847, "source_encoding": "utf_8", "md5": "09c6b42e1aae00bfdf74fae8b2672974", "text": "%TODO define seperate BCs for edges (eg. combination of Neuman and Dirichlet etc. )\n\nfunction u_g= BC_Disturbance(u_g,distSites,BC)\n\nif any(strcmp(distSites,{'l','lr','tl','bl','tblr'}))\n u_g(BC.BC_indices.leftRow)=u_g(BC.BC_indices.leftRow).*rand(size(u_g(BC.BC_indices.leftRow)))*BC.BC_dir_Dist_Value;\nend\nif any(strcmp(distSites,{'r','lr','tr','br','tblr'}))\n u_g(BC.BC_indices.rightRow)=u_g(BC.BC_indices.rightRow).*rand(size(u_g(BC.BC_indices.rightRow)))*BC.BC_dir_Dist_Value;\nend\nif any(strcmp(distSites,{'t','tr','tl','bt','tblr'}))\n u_g(BC.BC_indices.topRow)=u_g(BC.BC_indices.topRow).*rand(size(u_g(BC.BC_indices.topRow)))*BC.BC_dir_Dist_Value;\nend\nif any(strcmp(distSites,{'b','br','tb','bl','tblr'}))\n u_g(BC.BC_indices.botRow)=u_g(BC.BC_indices.botRow).*rand(size(u_g(BC.BC_indices.botRow)))*BC.BC_dir_Dist_Value; \nend\n\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "dpsimplify.m", "ext": ".m", "path": "topotoolbox-master/utilities/dpsimplify.m", "size": 6439, "source_encoding": "utf_8", "md5": "520039e696aaacc7377a4ba3f7f12ebe", "text": "function [ps,ix] = dpsimplify(p,tol)\n\n% Recursive Douglas-Peucker Polyline Simplification, Simplify\n%\n% [ps,ix] = dpsimplify(p,tol)\n%\n% dpsimplify uses the recursive Douglas-Peucker line simplification \n% algorithm to reduce the number of vertices in a piecewise linear curve \n% according to a specified tolerance. The algorithm is also know as\n% Iterative Endpoint Fit. It works also for polylines and polygons\n% in higher dimensions.\n%\n% In case of nans (missing vertex coordinates) dpsimplify assumes that \n% nans separate polylines. As such, dpsimplify treats each line\n% separately.\n%\n% For additional information on the algorithm follow this link\n% http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm\n%\n% Input arguments\n%\n% p polyline n*d matrix with n vertices in d \n% dimensions.\n% tol tolerance (maximal euclidean distance allowed \n% between the new line and a vertex)\n%\n% Output arguments\n%\n% ps simplified line\n% ix linear index of the vertices retained in p (ps = p(ix))\n%\n% Examples\n%\n% 1. Simplify line \n%\n% tol = 1;\n% x = 1:0.1:8*pi;\n% y = sin(x) + randn(size(x))*0.1;\n% p = [x' y'];\n% ps = dpsimplify(p,tol);\n%\n% plot(p(:,1),p(:,2),'k')\n% hold on\n% plot(ps(:,1),ps(:,2),'r','LineWidth',2);\n% legend('original polyline','simplified')\n%\n% 2. Reduce polyline so that only knickpoints remain by \n% choosing a very low tolerance\n%\n% p = [(1:10)' [1 2 3 2 4 6 7 8 5 2]'];\n% p2 = dpsimplify(p,eps);\n% plot(p(:,1),p(:,2),'k+--')\n% hold on\n% plot(p2(:,1),p2(:,2),'ro','MarkerSize',10);\n% legend('original line','knickpoints')\n%\n% 3. Simplify a 3d-curve\n% \n% x = sin(1:0.01:20)'; \n% y = cos(1:0.01:20)'; \n% z = x.*y.*(1:0.01:20)';\n% ps = dpsimplify([x y z],0.1);\n% plot3(x,y,z);\n% hold on\n% plot3(ps(:,1),ps(:,2),ps(:,3),'k*-');\n%\n%\n%\n% Author: Wolfgang Schwanghart, 13. July, 2010.\n% w.schwanghart[at]unibas.ch\n\n\nif nargin == 0\n help dpsimplify\n return\nend\n\nerror(nargchk(2, 2, nargin))\n\n% error checking\nif ~isscalar(tol) || tol<0;\n error('tol must be a positive scalar')\nend\n\n\n% nr of dimensions\nnrvertices = size(p,1); \ndims = size(p,2);\n\n% anonymous function for starting point and end point comparision\n% using a relative tolerance test\ncompare = @(a,b) abs(a-b)/max(abs(a),abs(b)) <= eps;\n\n% what happens, when there are NaNs?\n% NaNs divide polylines.\nInan = any(isnan(p),2);\n% any NaN at all?\nInanp = any(Inan);\n\n% if there is only one vertex\nif nrvertices == 1 || isempty(p);\n ps = p;\n ix = 1;\n\n% if there are two \nelseif nrvertices == 2 && ~Inanp;\n % when the line has no vertices (except end and start point of the\n % line) check if the distance between both is less than the tolerance.\n % If so, return the center.\n if dims == 2;\n d = hypot(p(1,1)-p(2,1),p(1,2)-p(2,2));\n else\n d = sqrt(sum((p(1,:)-p(2,:)).^2));\n end\n \n if d <= tol;\n ps = sum(p,1)/2;\n ix = 1;\n else\n ps = p;\n ix = [1;2];\n end\n \nelseif Inanp;\n \n % case: there are nans in the p array\n % --> find start and end indices of contiguous non-nan data\n Inan = ~Inan;\n sIX = strfind(Inan',[0 1])' + 1; \n eIX = strfind(Inan',[1 0])'; \n \n if Inan(end)==true;\n eIX = [eIX;nrvertices];\n end\n \n if Inan(1);\n sIX = [1;sIX];\n end\n \n % calculate length of non-nan components\n lIX = eIX-sIX+1; \n % put each component into a single cell\n c = mat2cell(p(Inan,:),lIX,dims);\n \n % now call dpsimplify again inside cellfun. \n if nargout == 2;\n [ps,ix] = cellfun(@(x) dpsimplify(x,tol),c,'uniformoutput',false);\n ix = cellfun(@(x,six) x+six-1,ix,num2cell(sIX),'uniformoutput',false);\n else\n ps = cellfun(@(x) dpsimplify(x,tol),c,'uniformoutput',false);\n end\n \n % write the data from a cell array back to a matrix\n ps = cellfun(@(x) [x;nan(1,dims)],ps,'uniformoutput',false); \n ps = cell2mat(ps);\n ps(end,:) = [];\n \n % ix wanted? write ix to a matrix, too.\n if nargout == 2;\n ix = cell2mat(ix);\n end\n \n \nelse\n \n\n% if there are no nans than start the recursive algorithm\nixe = size(p,1);\nixs = 1;\n\n% logical vector for the vertices to be retained\nI = true(ixe,1);\n\n% call recursive function\np = simplifyrec(p,tol,ixs,ixe);\nps = p(I,:);\n\n% if desired return the index of retained vertices\nif nargout == 2;\n ix = find(I);\nend\n\nend\n\n% _________________________________________________________\nfunction p = simplifyrec(p,tol,ixs,ixe)\n \n % check if startpoint and endpoint are the same \n % better comparison needed which included a tolerance eps\n \n c1 = num2cell(p(ixs,:));\n c2 = num2cell(p(ixe,:)); \n \n % same start and endpoint with tolerance\n sameSE = all(cell2mat(cellfun(compare,c1(:),c2(:),'UniformOutput',false)));\n\n \n if sameSE; \n % calculate the shortest distance of all vertices between ixs and\n % ixe to ixs only\n if dims == 2;\n% d = abs(p(ixs,2)-p(ixs+1:ixe-1,2));\n d = hypot(p(ixs,1)-p(ixs+1:ixe-1,1),p(ixs,2)-p(ixs+1:ixe-1,2));\n else\n d = sqrt(sum(bsxfun(@minus,p(ixs,:),p(ixs+1:ixe-1,:)).^2,2));\n end\n else \n % calculate shortest distance of all points to the line from ixs to ixe\n % subtract starting point from other locations\n pt = bsxfun(@minus,p(ixs+1:ixe,:),p(ixs,:));\n\n % end point\n a = pt(end,:)';\n\n beta = (a' * pt')./(a'*a);\n b = pt-bsxfun(@times,beta,a)';\n if dims == 2;\n % if line in 2D use the numerical more robust hypot function\n% d = abs(b(:,2));\n d = hypot(b(:,1),b(:,2));\n else\n d = sqrt(sum(b.^2,2));\n end\n end\n \n % identify maximum distance and get the linear index of its location\n [dmax,ixc] = max(d);\n ixc = ixs + ixc; \n \n % if the maximum distance is smaller than the tolerance remove vertices\n % between ixs and ixe\n if dmax <= tol;\n if ixs ~= ixe-1;\n I(ixs+1:ixe-1) = false;\n end\n % if not, call simplifyrec for the segments between ixs and ixc (ixc\n % and ixe)\n else \n p = simplifyrec(p,tol,ixs,ixc);\n p = simplifyrec(p,tol,ixc,ixe);\n\n end\n\nend\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "ylinerel.m", "ext": ".m", "path": "topotoolbox-master/utilities/ylinerel.m", "size": 2150, "source_encoding": "utf_8", "md5": "1ae474bcc6273835c08434daf19f2ece", "text": "function ht = ylinerel(values,rel,varargin)\n\n%YLINEREL Plot vertical lines with constant y values and relative length\n%\n% Syntax\n%\n% ylinerel(y)\n% ylinerel(y, fraction, pn, pv)\n%\n% Description\n%\n% ylinerel plots vertical lines at the values y with length (or\n% positions) relative to the limits of the x-axis. \n%\n% Input arguments\n%\n% y values of y\n% fraction fraction of x-axis limits. If fraction is a scalar, then\n% the function plots the lines starting on the x-axis. If\n% you specify fraction as two-element vector with values\n% between 0 and 1, then the lines will be plotted within\n% these fractions of the x-axis. For example, [0.95 1] will\n% plot lines in the right 5% of the axis. By default,\n% fraction is 0.05.\n% pn,pv all arguments accepted by the plot function.\n%\n% Output arguments\n%\n% h handle to line function\n% \n% Example\n%\n% plot([0 16],[0 5],'k')\n% hold on\n% ylinerel([0:pi/2:5*pi],[.95 1],'r','LineWidth',2);\n%\n% See also: xline, yline, xlinerel\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 26. August, 2021\n\nif nargin == 1\n rel = 0.05;\nend\nif isempty(rel)\n rel = 0.05;\nend\n\nif isscalar(rel)\n rel = [0; rel];\nelse\n rel = sort(rel,'ascend');\nend\n\nif any(rel > 1 | rel < 0)\n error('The fraction must be within the range of 0 and 1')\nend\n\nax = gca;\nxl = xlim(ax);\n\nn = numel(values);\ny = values(:)';\ny = [y;y];\n\nxlow = xl(1) + (xl(2)-xl(1))*rel(1);\nxhigh = xl(1) + (xl(2)-xl(1))*rel(2);\n\nx = repmat([xlow; xhigh],1,n);\n\ny = [y;nan(1,n)];\nx = [x;nan(1,n)];\n\nh = plot(x(:),y(:),varargin{:});\nxlim(ax,xl);\n\nhlist = addlistener(ax,'XLim','PostSet',@(src,evnt)updatedata);\nh.DeleteFcn = @(src,evt)upondelete(src,evt,hlist);\n\nif nargout == 1\n ht = h;\nend\n\nfunction updatedata\n xl = xlim(ax);\n xlow = xl(1) + (xl(2)-xl(1))*rel(1);\n xhigh = xl(1) + (xl(2)-xl(1))*rel(2);\n h.XData(1:3:end) = xlow;\n h.XData(2:3:end) = xhigh;\n\nend\nfunction upondelete(scr,evt,hlist)\n\n delete(hlist)\n\n end\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "subplotlabel.m", "ext": ".m", "path": "topotoolbox-master/utilities/subplotlabel.m", "size": 12326, "source_encoding": "utf_8", "md5": "077a645d7d8efbb60675636ae7c7066e", "text": "classdef subplotlabel < handle\n \n%SUBPLOTLABEL Label subplots (works only for 2D plots so far)\n%\n% Syntax\n%\n% h = subplotlabel(ax,letter)\n% h = subplotlabel(fig,letter)\n% h = subplotlabel(...,pn,pv,...)\n%\n% Description\n%\n% subplotlabel adds labels to the corner of each panel of a composite\n% figure.\n%\n% subplotlabel(ax,'c') assigns the letter 'c' to the axis ax.\n%\n% subplotlabel(fig,'A') assigns the letters 'A','B',... to the axes in\n% the figure with the handle fig. letter must be 'A','a', 'I', 'i', \n% or '1'.\n% \n% Input arguments\n% \n% ax axes handle (e.g. gca)\n% fig figure handle (e.g. gcf)\n%\n% Parameter name/value pairs\n% \n% 'Location' one of the following values: {'northwest'}, 'southwest', \n% 'northeast', 'southeast', 'northwestoutside'\n% 'FontSize' 14\n% 'FontWeight' {'normal'} or 'bold'\n% 'FontAngle' {'normal'} or 'italic'\n% 'Color' Font color. {'k'}\n% 'BackgroundColor' {'none'} or any other way to define colors\n% 'Prefix' ''. Character before the enumeral.\n% 'Postfix' ''. Character behind the enumeral.\n% 'offset' offset in x and y direction from the corner in\n% normalized axis units. By default, the offset is 0.01. \n% offset can be a scalar or a two-element vector with an \n% x and y offset. The direction of the offset depends on\n% the location with positiv values towards the interior\n% of the axes.\n%\n% Applicable if called with fig handle only\n%\n% 'order' direction of labelling {'rightdown'} or 'downright'\n%\n% Output arguments\n%\n% h instance of subplotlabel\n%\n% Methods for class subplotlabel\n%\n% bigger(h,s) increases the font size by s. Default is 1.\n% smaller(h,s) decreases the font size by s. Default is 1.\n% resetposition(h) resets the position. \n% upper(h) sets all labels to upper case\n% lower(h) sets all labels to lower case\n% italic(h) sets all labels to italic\n% bold(h) sets all labels to bold\n% normal(h) sets all labels to normal\n% delete(h) removes all labels\n%\n% Example 1\n%\n% for r = 1:6; subplot(2,3,r); plot(rand(5)); end\n% h = subplotlabel(gcf,'a','location','southwest','order','downright');\n%\n% Example 2 (requires TopoToolbox)\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% ax = subplot(1,2,1);\n% imageschs(DEM)\n% h = subplotlabel(ax,'A','location','northwest','color','w');\n% ax(2) = subplot(1,2,2);\n% imageschs(DEM,gradient8(DEM))\n% h(2) = subplotlabel(ax(2),'B','location','southeast','color','w');\n% bigger(h,5)\n%\n% See also: text\n%\n% Note: roman numericals are computed using Francois Beauducel function\n% NUM2ROMAN (https://github.com/beaudu/romanum)\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 15. November, 2022\n\n properties\n label\n LIMIX\n offset\n end\n \n methods\n function h = subplotlabel(varargin)\n \n \n p = inputParser;\n addRequired(p,'ax')\n addRequired(p,'value')\n addParameter(p,'location','northwest');\n addParameter(p,'order','rightdown');\n addParameter(p,'FontSize',14);\n addParameter(p,'Margin',1);\n addParameter(p,'EdgeColor','none');\n addParameter(p,'BackgroundColor','none');\n addParameter(p,'FontWeight','normal');\n addParameter(p,'FontAngle','normal');\n addParameter(p,'postfix','');\n addParameter(p,'prefix','')\n addParameter(p,'Color','k');\n addParameter(p,'offset',0.01,@(x) numel(x) <= 2)\n % addParameter(p,'Clipping','on');\n parse(p,varargin{:})\n \n if isa(p.Results.ax,'matlab.ui.Figure')\n hax = findall(gcf,'Type','axes');\n \n if isempty(hax)\n error('Figure must contain at least one axis')\n end\n \n switch p.Results.value\n case 'A'\n letters = ('A':'Z')';\n letters = cellstr(letters);\n case 'a'\n letters = ('a':'z')';\n letters = cellstr(letters);\n case '1'\n letters = num2cell(1:numel(hax));\n letters = cellfun(@num2str,letters,'UniformOutput',false);\n case {'i' 'I'}\n letters = cellfun(@roman,num2cell(1:numel(hax)),'UniformOutput',false);\n switch p.Results.value\n case 'i'\n letters = lower(letters);\n end\n \n otherwise\n error('TopoToolbox:subplotlabel',...\n ['If the first argument is a handle to a figure, letter \\newline' ...\n 'must be ''A'', ''a'', ''I'' ''i'' or ''1''.']);\n end\n \n % Sort axes from top-left to bottom-right\n pos = zeros(numel(hax),2);\n % Left upper corner of axes\n for r = 1:numel(hax)\n pos(r,1) = hax(r).Position(1);\n pos(r,2) = sum(hax(r).Position([2 4])); \n end\n \n switch lower(p.Results.order)\n case 'rightdown'\n [~,ix] = sortrows(pos,[-2 1]);\n case 'downright'\n [~,ix] = sortrows(pos,[1 -2]);\n otherwise \n error('unknown ordering')\n end \n \n hax = hax(ix);\n Results = p.Results;\n Results = rmfield(Results,{'ax','value'});\n \n for r = 1:numel(hax)\n hh(r) = subplotlabel(hax(r),letters{r},Results);\n end\n \n h = hh;\n return\n else\n ax = p.Results.ax;\n letter = p.Results.value;\n offset = p.Results.offset;\n \n if numel(offset) == 1\n offset = [offset offset];\n else\n offset = offset(:)';\n end\n\n xl = [0 1]; %xlim(ax);\n yl = [0 1]; %ylim(ax);\n loc = validatestring(p.Results.location,...\n {'northwest','southeast','northeast','southwest',...\n 'nw','se','ne','sw',...\n 'northwestoutside','nwo'});\n switch lower(loc)\n case {'northeast','ne'}\n IXX = 2;\n IXY = 2;\n\n offset = offset .* [-1 -1];\n\n valign = 'top';\n halign = 'right';\n case {'northwest','nw'}\n IXX = 1;\n IXY = 2;\n offset = offset .* [1 -1];\n\n valign = 'top';\n halign = 'left';\n case {'southwest','sw'}\n IXX = 1;\n IXY = 1;\n offset = offset .* [1 1];\n valign = 'bottom';\n halign = 'left';\n case {'southeast','se'}\n IXX = 2;\n IXY = 1;\n offset = offset .* [1 -1];\n\n valign = 'bottom';\n halign = 'right';\n case {'northwestoutside','nwo'}\n \n IXX = 1;\n IXY = 2;\n offset = offset .* [1 1];\n\n valign = 'bottom';\n halign = 'left';\n end\n \n locx = xl(IXX) + offset(IXX);\n locy = yl(IXY) + offset(IXY);\n \n \n if ishold(ax)\n ihold = true;\n else\n ihold = false;\n end\n \n hold(ax,'on');\n h.label = text(ax,locx,locy,...\n [p.Results.prefix letter p.Results.postfix],...\n 'VerticalAlignment',valign,...\n 'HorizontalAlignment',halign,...\n 'Color',p.Results.Color,...\n 'FontSize',p.Results.FontSize,...\n 'Margin',p.Results.Margin,...\n 'BackgroundColor',p.Results.BackgroundColor,...\n 'EdgeColor',p.Results.EdgeColor,...\n 'FontAngle',p.Results.FontAngle,...\n 'FontWeight',p.Results.FontWeight,...\n 'Units','normalized',...\n 'Clipping','on');\n h.offset = offset;\n \n if ~ihold\n hold(ax,'off');\n end\n \n h.LIMIX = [IXX, IXY];\n \n end\n end\n function resetposition(h)\n % Set subplot labels to initial position\n for r = 1:numel(h)\n xl = [0 1]; \n yl = [0 1];\n h(r).label.Position = ...\n [xl(h(r).LIMIX(1))+h(r).offset(1) ...\n yl(h(r).LIMIX(2))+h(r).offset(2)];\n end\n end\n function upper(h)\n % Upper case letters\n for r = 1:numel(h)\n set(h(r).label,'String',upper(h(r).label.String));\n end\n end\n function lower(h)\n % Lower case letters\n for r = 1:numel(h)\n set(h(r).label,'String',lower(h(r).label.String));\n end\n end\n function bigger(h,val)\n % Increase font size\n if nargin == 1\n val = 1;\n end\n for r = 1:numel(h)\n h(r).label.FontSize = h(r).label.FontSize + val;\n end\n end\n function smaller(h,val)\n % Decrease font size\n if nargin == 1\n val = 1;\n end\n for r = 1:numel(h)\n h(r).label.FontSize = h(r).label.FontSize - val;\n end\n end\n function italic(h)\n % Italic font\n for r = 1:numel(h)\n h(r).label.FontAngle = 'italic';\n end\n end\n function bold(h)\n % Bold font\n for r = 1:numel(h)\n h(r).label.FontWeight = 'bold';\n end\n end\n function normal(h)\n % Normal font\n for r = 1:numel(h)\n h(r).label.FontWeight = 'normal';\n h(r).label.FontAngle = 'normal';\n end\n end\n function delete(h)\n % Delete subplot labels\n \n for r = 1:numel(h)\n % set(h(r).label.Parent.Parent,'SizeChangedFcn',[]);\n delete(h.label) \n \n end\n end\n \n end\n \n \nend\n\nfunction x=roman(n)\n% this subfunction converts numbers up to 4999\nr = reshape('IVXLCDM ',2,5);\t% the 3 last blank chars are to avoid error for n >= 1000\nx = '';\nm = floor(log10(n)) + 1;\t% m is the number of digit\n% n is processed sequentially for each digit\nfor i = m:-1:1\n\tii = fix(n/10^(i-1));\t% ii is the digit (0 to 9)\n\t% Roman numeral is a concatenation of r(1:2,i) and r(1,i+1)\n\t% combination with regular rules (exception for 4000 = MMMM)\n\t% Note: the expression uses REPMAT behavior which returns empty\n\t% string for N <= 0\n\tx = [x,repmat(r(1,i),1,ii*(ii < 4 | (ii==4 & i==4)) + (ii == 9) + (ii==4 & i < 4)), ...\n\t\t repmat([r(2,i),repmat(r(1,i),1,ii-5)],1,(ii >= 4 & ii <= 8 & i ~= 4)), ...\n\t\t repmat(r(1,i+1),1,(ii == 9))];\n\tn = n - ii*10^(i-1);\t% substract the most significant digit\nend\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "ginputc.m", "ext": ".m", "path": "topotoolbox-master/utilities/ginputc.m", "size": 14143, "source_encoding": "utf_8", "md5": "a450a3853eafb56c18eae28bedda2956", "text": "\nfunction [x, y, button, ax] = ginputc(varargin)\n%GINPUTC Graphical input from mouse.\n% GINPUTC behaves similarly to GINPUT, except you can customize the\n% cursor color, line width, and line style.\n%\n% [X,Y] = GINPUTC(N) gets N points from the current axes and returns\n% the X- and Y-coordinates in length N vectors X and Y. The cursor\n% can be positioned using a mouse. Data points are entered by pressing\n% a mouse button or any key on the keyboard except carriage return,\n% which terminates the input before N points are entered.\n% Note: if there are multiple axes in the figure, use mouse clicks\n% instead of key presses. Key presses may not select the axes\n% where the cursor is.\n%\n% [X,Y] = GINPUTC gathers an unlimited number of points until the return\n% key is pressed.\n%\n% [X,Y] = GINPUTC(N, PARAM, VALUE) and [X,Y] = GINPUTC(PARAM, VALUE)\n% specifies additional parameters for customizing. Valid values for PARAM\n% are:\n% 'FigHandle' : Handle of the figure to activate. Default is gcf.\n% 'Color' : A three-element RGB vector, or one of the MATLAB\n% predefined names, specifying the line color. See\n% the ColorSpec reference page for more information\n% on specifying color. Default is 'k' (black).\n% 'LineWidth' : A scalar number specifying the line width.\n% Default is 0.5.\n% 'LineStyle' : '-', '--', '-.', ':'. Default is '-'.\n% 'ShowPoints' : TRUE or FALSE specifying whether to show the\n% points being selected. Default is false.\n% 'ConnectPoints' : TRUE or FALSE specifying whether to connect the\n% points as they are being selected. This only\n% applies when 'ShowPoints' is set to TRUE. Default\n% is true.\n%\n% [X,Y,BUTTON] = GINPUTC(...) returns a third result, BUTTON, that\n% contains a vector of integers specifying which mouse button was used\n% (1,2,3 from left) or ASCII numbers if a key on the keyboard was used.\n%\n% [X,Y,BUTTON,AX] = GINPUTC(...) returns a fourth result, AX, that\n% contains a vector of axes handles for the data points collected.\n%\n% Requires MATLAB R2007b or newer.\n%\n% Examples:\n% [x, y] = ginputc;\n%\n% [x, y] = ginputc(5, 'Color', 'r', 'LineWidth', 3);\n%\n% [x, y, button] = ginputc(1, 'LineStyle', ':');\n%\n% subplot(1, 2, 1); subplot(1, 2, 2);\n% [x, y, button, ax] = ginputc;\n%\n% [x, y] = ginputc('ShowPoints', true, 'ConnectPoints', true);\n%\n% See also GINPUT, GTEXT, WAITFORBUTTONPRESS.\n\n% Jiro Doke\n% October 19, 2012\n% Copyright 2012 The MathWorks, Inc.\n\ntry\n if verLessThan('matlab', '7.5')\n error('ginputc:Init:IncompatibleMATLAB', ...\n 'GINPUTC requires MATLAB R2007b or newer');\n end\ncatch %#ok\n error('ginputc:Init:IncompatibleMATLAB', ...\n 'GINPUTC requires MATLAB R2007b or newer');\nend\n\n% Check input arguments\np = inputParser();\n\naddOptional(p, 'N', inf, @(x) validateattributes(x, {'numeric'}, ...\n {'scalar', 'integer', 'positive'}));\naddParamValue(p, 'FigHandle', [], @(x) numel(x)==1 && ishandle(x));\naddParamValue(p, 'Color', 'k', @colorValidFcn);\naddParamValue(p, 'LineWidth', 0.5 , @(x) validateattributes(x, ...\n {'numeric'}, {'scalar', 'positive'}));\naddParamValue(p, 'LineStyle', '-' , @(x) ischar(validatestring(x, ...\n{'-', '--', '-.', ':'}))); \naddParamValue(p, 'ShowPoints', false, @(x) validateattributes(x, ...\n {'logical'}, {'scalar'}));\naddParamValue(p, 'ConnectPoints', true, @(x) validateattributes(x, ...\n {'logical'}, {'scalar'}));\n\nparse(p, varargin{:});\n\nN = p.Results.N;\nhFig = p.Results.FigHandle;\ncolor = p.Results.Color;\nlinewidth = p.Results.LineWidth;\nlinestyle = p.Results.LineStyle;\nshowpoints = p.Results.ShowPoints;\nconnectpoints = p.Results.ConnectPoints;\n\n%--------------------------------------------------------------------------\n function tf = colorValidFcn(in)\n % This function validates the color input parameter\n \n validateattributes(in, {'char', 'double'}, {'nonempty'});\n if ischar(in)\n validatestring(in, {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'});\n else\n assert(isequal(size(in), [1 3]) && all(in>=0 & in<=1), ...\n 'ginputc:InvalidColorValues', ...\n 'RGB values for \"Color\" must be a 1x3 vector between 0 and 1');\n % validateattributes(in, {'numeric'}, {'size', [1 3], '>=', 0, '<=', 1})\n end\n tf = true;\n end\n%--------------------------------------------------------------------------\n\nif isempty(hFig)\n hFig = gcf;\nend\n\n% Try to get the current axes even if it has a hidden handle.\nhAx = get(hFig, 'CurrentAxes');\nif isempty(hAx)\n allAx = findall(hFig, 'Type', 'axes');\n if ~isempty(allAx)\n hAx = allAx(1);\n else\n hAx = axes('Parent', hFig);\n end\nend\n\n% Handle interactive properites of HG objects. Save the current settings so\n% that they can be restored later\nallHG = findall(hFig);\npropsToChange = {...\n 'WindowButtonUpFcn', ...\n 'WindowButtonDownFcn', ...\n 'WindowButtonMotionFcn', ...\n 'WindowKeyPressFcn', ...\n 'WindowKeyReleaseFcn', ...\n 'ButtonDownFcn', ...\n 'KeyPressFcn', ...\n 'KeyReleaseFcn', ...\n 'ResizeFcn'};\nvalidObjects = false(length(allHG), length(propsToChange));\ncurCallbacks = cell(1, length(propsToChange));\n\n% Save current properties and set them to ''\nfor id = 1:length(propsToChange)\n validObjects(:, id) = isprop(allHG, propsToChange{id});\n curCallbacks{id} = get(allHG(validObjects(:, id)), propsToChange(id));\n set(allHG(validObjects(:, id)), propsToChange{id}, '');\nend\n\n% Save current pointer\ncurPointer = get(hFig, 'Pointer');\ncurPointerShapeCData = get(hFig, 'PointerShapeCData');\n\n% Change window functions\nset(hFig, ...\n 'WindowButtonDownFcn', @mouseClickFcn, ...\n 'WindowButtonMotionFcn', @mouseMoveFcn, ...\n 'KeyPressFcn', @keyPressFcn, ...\n 'ResizeFcn', @resizeFcn, ...\n 'Pointer', 'custom', ...\n 'PointerShapeCData', nan(16, 16));\n\n% Create an invisible axes for displaying the full crosshair cursor\nhInvisibleAxes = axes(...\n 'Parent', hFig, ...\n 'Units', 'normalized', ...\n 'Position', [0 0 1 1], ...\n 'XLim', [0 1], ...\n 'YLim', [0 1], ...\n 'HitTest', 'off', ...\n 'HandleVisibility', 'off', ...\n 'Visible', 'off');\n\n% Create line object for the selected points\nif showpoints\n if connectpoints\n pointsLineStyle = '-';\n else\n pointsLineStyle = 'none';\n end\n \n selectedPoints = [];\n hPoints = line(nan, nan, ...\n 'Parent', hInvisibleAxes, ...\n 'HandleVisibility', 'off', ...\n 'HitTest', 'off', ...\n 'Color', [1 0 0], ...\n 'Marker', 'o', ...\n 'MarkerFaceColor', [1 .7 .7], ...\n 'MarkerEdgeColor', [1 0 0], ...\n 'LineStyle', pointsLineStyle);\nend\n\n% Create tooltip for displaying selected points\n% hTooltipControl = text(0, 1, 'HIDE', ...\n% 'Parent', hInvisibleAxes, ...\n% 'HandleVisibility', 'callback', ...\n% 'FontName', 'FixedWidth', ...\n% 'VerticalAlignment', 'top', ...\n% 'HorizontalAlignment', 'left', ...\n% 'BackgroundColor', [.5 1 .5]);\n% hTooltip = text(0, 0, 'No points', ...\n% 'Parent', hInvisibleAxes, ...\n% 'HandleVisibility', 'off', ...\n% 'HitTest', 'off', ...\n% 'FontName', 'FixedWidth', ...\n% 'VerticalAlignment', 'top', ...\n% 'HorizontalAlignment', 'left', ...\n% 'BackgroundColor', [1 1 .5]);\n\n% Call resizeFcn to update tooltip location\nresizeFcn();\n\n% Create full crosshair lines\nhCursor = line(nan, nan, ...\n 'Parent', hInvisibleAxes, ...\n 'Color', color, ...\n 'LineWidth', linewidth, ...\n 'LineStyle', linestyle, ...\n 'HandleVisibility', 'off', ...\n 'HitTest', 'off');\n\n% Prepare results\nx = [];\ny = [];\nbutton = [];\nax = [];\n\n% Wait until enter is pressed.\nuiwait(hFig);\n\n\n%--------------------------------------------------------------------------\n function mouseMoveFcn(varargin)\n % This function updates cursor location based on pointer location\n \n cursorPt = get(hInvisibleAxes, 'CurrentPoint');\n \n set(hCursor, ...\n 'XData', [0 1 nan cursorPt(1) cursorPt(1)], ...\n 'YData', [cursorPt(3) cursorPt(3) nan 0 1]);\n end\n%--------------------------------------------------------------------------\n\n%--------------------------------------------------------------------------\n function mouseClickFcn(varargin)\n % This function captures mouse clicks.\n % If the tooltip control is clicked, then toggle tooltip display.\n % If anywhere else is clicked, record point.\n\n% if isequal(gco, hTooltipControl)\n% tooltipClickFcn();\n% else\n updatePoints(get(hFig, 'SelectionType'));\n% end\n end\n%--------------------------------------------------------------------------\n\n%--------------------------------------------------------------------------\n function keyPressFcn(obj, edata) %#ok\n % This function captures key presses.\n % If \"return\", then exit.\n % If \"delete\" (or \"backspace\"), then delete previous point.\n % If any other key, record point.\n \n key = double(edata.Character);\n if isempty(key)\n return;\n end\n \n switch key\n case 13 % return\n exitFcn();\n \n case {8, 127} % delete or backspace\n if ~isempty(x)\n x(end) = [];\n y(end) = [];\n button(end) = [];\n ax(end) = [];\n \n if showpoints\n selectedPoints(end, :) = [];\n set(hPoints, ...\n 'XData', selectedPoints(:, 1), ...\n 'YData', selectedPoints(:, 2));\n end\n \n% displayCoordinates();\n end\n \n otherwise\n updatePoints(key);\n \n end\n end\n%--------------------------------------------------------------------------\n\n%--------------------------------------------------------------------------\n function updatePoints(clickType)\n % This function captures the information for the selected point\n \n hAx = gca;\n pt = get(hAx, 'CurrentPoint');\n x = [x; pt(1)];\n y = [y; pt(3)];\n ax = [ax; hAx];\n\n if ischar(clickType) % Mouse click\n switch lower(clickType)\n case 'open'\n clickType = 1;\n case 'normal'\n clickType = 1;\n case 'extend'\n clickType = 2;\n case 'alt'\n clickType = 3;\n end\n end\n button = [button; clickType];\n \n% displayCoordinates();\n \n if showpoints\n cursorPt = get(hInvisibleAxes, 'CurrentPoint');\n selectedPoints = [selectedPoints; cursorPt([1 3])];\n set(hPoints, ...\n 'XData', selectedPoints(:, 1), ...\n 'YData', selectedPoints(:, 2));\n end\n \n % If captured all points, exit\n if length(x) == N\n exitFcn();\n end\n end\n%--------------------------------------------------------------------------\n\n%--------------------------------------------------------------------------\n% function tooltipClickFcn()\n% % This function toggles the display of the tooltip\n% \n% if strcmp(get(hTooltipControl, 'String'), 'SHOW')\n% set(hTooltipControl, 'String', 'HIDE');\n% set(hTooltip, 'Visible', 'on');\n% else\n% set(hTooltipControl, 'String', 'SHOW');\n% set(hTooltip, 'Visible', 'off');\n% end\n% end\n%--------------------------------------------------------------------------\n\n%--------------------------------------------------------------------------\n% function displayCoordinates()\n% % This function updates the coordinates display in the tooltip\n% \n% if isempty(x)\n% str = 'No points';\n% else\n% str = sprintf('%d: %0.3f, %0.3f\\n', [1:length(x); x'; y']);\n% str(end) = '';\n% end\n% set(hTooltip, ...\n% 'String', str);\n% end\n%--------------------------------------------------------------------------\n\n%--------------------------------------------------------------------------\n function resizeFcn(varargin)\n % This function adjusts the position of tooltip when the figure is\n % resized\n \n% sz = get(hTooltipControl, 'Extent');\n% set(hTooltip, 'Position', [0 sz(2)]);\n end\n%--------------------------------------------------------------------------\n\n%--------------------------------------------------------------------------\n function exitFcn()\n % This function exits GINPUTC and restores previous figure settings\n \n for idx = 1:length(propsToChange)\n set(allHG(validObjects(:, idx)), propsToChange(idx), curCallbacks{idx});\n end\n \n % Restore window functions and pointer\n % set(hFig, 'WindowButtonDownFcn', curWBDF);\n % set(hFig, 'WindowButtonMotionFcn', curWBMF);\n % set(hFig, 'WindowButtonUpFcn', curWBUF);\n % set(hFig, 'KeyPressFcn', curKPF);\n % set(hFig, 'KeyReleaseFcn', curKRF);\n % set(hFig, 'ResizeFcn', curRF);\n \n % Restore pointer\n set(hFig, 'Pointer', curPointer);\n set(hFig, 'PointerShapeCData', curPointerShapeCData);\n\n % Delete invisible axes and return control\n delete(hInvisibleAxes);\n uiresume(hFig);\n end\n%--------------------------------------------------------------------------\n\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "label2poly.m", "ext": ".m", "path": "topotoolbox-master/utilities/label2poly.m", "size": 3316, "source_encoding": "utf_8", "md5": "b33b9f4de3cb8d7c5dab5a3e1535c89d", "text": "function [xy,Adj] = label2poly(L,X,Y,c)\n\n% plot region outlines with polyline\n%\n% Syntax\n%\n% label2poly(L)\n% label2poly(L,X,Y)\n% [xy,Adj] = label2poly(...)\n%\n% Description\n%\n% label2poly extracts the outlines of regions in a label matrix and \n% plots them. The outlines are drawn along the pixel edges. Without\n% output arguments, the function plots the outlines.\n%\n% Input arguments:\n%\n% L label matrix as returned by bwlabel or labelmatrix. \n% A logical matrix can be supplied, too.\n% X,Y coordinate matrices as returned by meshgrid\n%\n% Output arguments:\n%\n% xy coordinates\n% Adj adjacency matrix as used for gplot\n%\n% Example:\n%\n% [X,Y,P] = peaks(100);\n% L = bwlabel(P<-0.5);\n% subplot(1,2,1);\n% imagesc(X(1,:),Y(:,1),L);\n% axis image; axis xy\n% [xy,Adj] = label2poly(L,X,Y);\n% subplot(1,2,2);\n% gplot(Adj,xy,'k'); axis image\n%\n% see also: ixneighbors, bwlabel, labelmatrix, gplot\n%\n% Date: 3. August, 2011\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n\n\n\nif nargin == 1 || isempty(X) || isempty(Y);\n [X,Y] = meshgrid(1:size(L,2),1:size(L,1));\nend\nif nargin<4;\n c = 'k';\nend\n\n% set nans in label matrix to zero\nL(isnan(L)) = 0;\n\n% general values needed later on\ncs = abs(Y(1)-Y(2));\ncs2 = cs/2;\nminX = min(X(1,:));\nminY = min(Y(:,1));\nmaxX = max(X(1,:));\nmaxY = max(Y(:,1));\n\n% identify border pixels\nNHOOD = ones(3);\nI = (imdilate(L,NHOOD) ~= L) | (imerode(L,NHOOD) ~= L);\nL = double(L);\n\n% set non-border pixel to nan\nL(~I) = nan;\n\n% call ixneighbor, which will connect all border pixels within an\n% 8-neighborhood\n[neighb(:,1) neighb(:,2)] = ixneighbors(L,I,8);\n\n% remove double edges \nneighb = unique(sort(neighb,2),'rows');\n\n% remove edges to neighbors with the same label\nneighb(L(neighb(:,1))==L(neighb(:,2)),:) = [];\n\n% calculate the coordinates of the labelgrid by averaging the coordinates\n% along the neighbor edges\nxy = [(X(neighb(:,1))+X(neighb(:,2)))/2 (Y(neighb(:,1))+Y(neighb(:,2)))/2];\n\n% again remove double entries\nxy = unique(xy,'rows');\n\n% create coordinates of the label polygons along the boundaries of L \nxgr = (minX-cs2:cs2:maxX+cs2)'; \nnrx = numel(xgr);\nygr = (minY-cs2:cs2:maxY+cs2)'; \nnry = numel(ygr);\nxy = [xy; ...\n [xgr repmat(minY-cs2,nrx,1)]; ...\n [xgr repmat(maxY+cs2,nrx,1)]; ...\n [repmat(minX-cs2,nry,1) ygr]; ...\n [repmat(maxX+cs2,nry,1) ygr]];\n\n% number of label polygon coordinates\nnrxy = size(xy,1);\n\n% round coordinates to integer values to avoid floating point problems with ismember\nij = [round((xy(:,1)-min(xy(:,1)))/cs2)+1 round((xy(:,2)-min(xy(:,2)))/cs2)+1];\n\n% Construct node adjacency\n[I1,loc1] = ismember(bsxfun(@minus,ij,[0 1]),ij,'rows');\n[I2,loc2] = ismember(bsxfun(@minus,ij,[1 0]),ij,'rows');\ni = [find(I1);find(I2)];\nj = [loc1(I1);loc2(I2)];\nAdj = sparse(i,j,1,nrxy,nrxy);\n\n% if no output arguments, plot using gplot\nif nargout == 0;\n label2polygplot(Adj,xy,gca,c);\n clear xy\nelseif nargout == 1;\n xy = label2polygplot(Adj,xy);\nend\n\nend\n\n\n\nfunction h = label2polygplot(Adj,xy,ax,c)\n\n\n[i,j] = find(Adj);\n[~, p] = sort(max(i,j));\ni = i(p);\nj = j(p);\n\nX = [ xy(i,1) xy(j,1)]';\nY = [ xy(i,2) xy(j,2)]';\nX = [X; NaN(size(i))'];\nY = [Y; NaN(size(i))'];\n\nh = plot(ax,X(:),Y(:),[c '-']);\n\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "niceticks.m", "ext": ".m", "path": "topotoolbox-master/utilities/niceticks.m", "size": 2608, "source_encoding": "utf_8", "md5": "34d0f23a2cc44119e26ffca9e835359e", "text": "function niceticks(ax,varargin)\n\n%NICETICKS Makes nice ticks in a 2D plot\n%\n% Syntax\n%\n% niceticks\n% niceticks(ax)\n% niceticks(ax,pn,pv,...) \n%\n% Description\n%\n% Coordinate values are often quite large numbers which are displayed\n% with an exponent along the graphics axes. This function identifies\n% the best location for axis ticks and labels the first and last one\n% without exponents.\n%\n% Input arguments\n%\n% ax axis handle (e.g. gca)\n% \n% Parameter name/value pairs\n%\n% 'degree' {false} or true. If true, tick labels will be appended\n% with °E and °N. Note that currently, °W is not\n% supported.\n% 'twoticks' {true} or false. If true, two ticks per axis.\n% 'precision' Numbers behind the decimal. Default = 0\n% 'exponent' Exponent. Default = 0%\n%\n% See also: imageschs\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 13. May, 2020\n\nif nargin == 0\n ax = gca;\nend\n\np = inputParser;\np.FunctionName = 'niceticks';\naddParameter(p,'degree',false)\naddParameter(p,'twoticks',true)\naddParameter(p,'precision',0)\naddParameter(p,'exponent',0)\naddParameter(p,'rotateylabel',true)\nparse(p,varargin{:})\n\nprec = ['% .' num2str(p.Results.precision) 'f'];\n\nxticks(ax,'auto')\nyticks(ax,'auto')\nxticklocs = get(ax,'XTick');\nyticklocs = get(ax,'YTick');\n\nnx = numel(xticklocs);\nny = numel(yticklocs);\n\n% xticks\nix = find(round(xticklocs,p.Results.precision) == xticklocs);\nif p.Results.twoticks\n if nnz(ix) >= 2 \n xticklocs = xticklocs(ix([1 end]));\n end\nelse\n if any(ix)\n xticklocs = xticklocs(ix);\n end\nend\nset(ax,'XTick',xticklocs)\n\n% yticks\nix = find(round(yticklocs,p.Results.precision) == yticklocs);\nif p.Results.twoticks\n if nnz(ix) >= 2 \n yticklocs = yticklocs(ix([1 end]));\n end\nelse\n if any(ix)\n yticklocs = yticklocs(ix);\n end\nend\nset(ax,'YTick',yticklocs)\n\nif p.Results.degree\n xtickformat([prec '°E'])\n ytickformat([prec '°N'])\nelse\n xtickformat(prec)\n ytickformat(prec)\nend\n\nax.XAxis.Exponent = p.Results.exponent;\nax.YAxis.Exponent = p.Results.exponent;\n\n% rotate tick labels if matlab 2014b or newer available\nif ~verLessThan('matlab','8.4') && p.Results.rotateylabel\n set(ax,'YTickLabelRotation',90);\nend\n\n% if p.Results.degree\n% setlabelstodeg(ax)\n% end\nend\n\nfunction setlabelstodeg(ax)\nxt = xticklabels;\nxt = cellfun(@(x) [x '°E'],xt,'UniformOutput',false);\nset(ax,'XTickLabel',xt)\n\nyt = yticklabels;\nyt = cellfun(@(y) [y '°N'],yt,'UniformOutput',false);\nset(ax,'YTickLabel',yt)\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "xlinerel.m", "ext": ".m", "path": "topotoolbox-master/utilities/xlinerel.m", "size": 2174, "source_encoding": "utf_8", "md5": "37a9fd9de56f5f3d40109d94423c8a13", "text": "function ht = xlinerel(values,rel,varargin)\n\n%XLINEREL Plot vertical lines with constant x values and relative length\n%\n% Syntax\n%\n% xlinerel(x)\n% xlinerel(x, fraction, pn, pv)\n%\n% Description\n%\n% xlinerel plots vertical lines at the values x with length (or\n% positions) relative to the limits of the y-axis. \n%\n% Input arguments\n%\n% x values of x\n% fraction fraction of y-axis limits. If fraction is a scalar, then\n% the function plots the lines starting on the y-axis. If\n% you specify fraction as two-element vector with values\n% between 0 and 1, then the lines will be plotted within\n% these fractions of the y-axis. For example, [0.95 1] will\n% plot lines in the upper 5% of the axis. By default,\n% fraction is 0.05.\n% pn,pv all arguments accepted by the plot function.\n%\n% Output arguments\n%\n% h handle to line function\n% \n% Example\n%\n% plot(linspace(0,5*pi),sin(linspace(0,5*pi)))\n% hold on\n% xlinerel([0:pi/2:5*pi],[.95 1],'r','LineWidth',2);\n%\n% See also: xline, yline, ylinerel\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 26. August, 2021\n\nif nargin == 1\n rel = 0.05;\nend\nif isempty(rel)\n rel = 0.05;\nend\n\nif isscalar(rel)\n rel = [0; rel];\nelse\n rel = sort(rel,'ascend');\nend\n\nif any(rel > 1 | rel < 0)\n error('The fraction must be within the range of 0 and 1')\nend\n\nax = gca;\nyl = ylim(ax);\n\nn = numel(values);\nx = values(:)';\nx = [x;x];\n\nylow = yl(1) + (yl(2)-yl(1))*rel(1);\nyhigh = yl(1) + (yl(2)-yl(1))*rel(2);\n\ny = repmat([ylow; yhigh],1,n);\n\nx = [x;nan(1,n)];\ny = [y;nan(1,n)];\n\nh = plot(x(:),y(:),varargin{:});\nylim(ax,yl);\n\nhlist = addlistener(ax,'YLim','PostSet',@(src,evnt)updatedata);\nh.DeleteFcn = @(src,evt)upondelete(src,evt,hlist);\n\nif nargout == 1\n ht = h;\nend\n\nfunction updatedata\n yl = ylim(ax);\n ylow = yl(1) + (yl(2)-yl(1))*rel(1);\n yhigh = yl(1) + (yl(2)-yl(1))*rel(2);\n h.YData(1:3:end) = ylow;\n h.YData(2:3:end) = yhigh;\n\nend\n function upondelete(scr,evt,hlist)\n delete(hlist)\n end\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "ScaleBar.m", "ext": ".m", "path": "topotoolbox-master/utilities/ScaleBar.m", "size": 14766, "source_encoding": "utf_8", "md5": "f427b2f29039b6551befa3179d811c51", "text": "classdef ScaleBar < handle\n \n%ScaleBar A dynamic scalebar\n%\n% Syntax\n%\n% SB = ScaleBar\n% SB = ScaleBar(pn,pv,...)\n%\n% Description\n%\n% ScaleBar plots a dynamic scale bar in the 2D-axis. The function is\n% currently beta and only supports axis with projected coordinate\n% systems (no geographic coordinates). ScaleBar refers to the x-axis of\n% a plot and may be used for plots with different axis aspect ratios.\n%\n% Once the ScaleBar SB is created, you can make changes by directly\n% setting the properties, e.g.\n%\n% SB = ScaleBar;\n% SB.location = 'northwest';\n%\n% In addition, there are functions to increase or decrease the font\n% size.\n%\n% smaller(SB)\n% bigger(SB)\n% \n% Input arguments\n%\n% 'ax' axes handle {gca}\n% 'color' color of text and scalebar {'k'}\n% 'xyunit' unit of coordinates {'m'} or 'km' or 'none'\n% 'displayunit' unit shown by scale bar label {'auto'}, 'm', 'km' or\n% 'none'. If set to 'auto', then the label switch\n% automatically between 'm' and 'km'.\n% 'rellength' length of the scale bar relative to the length of the\n% x axis. This property controls the length of the scale\n% bar. It should range between 0.1 and 0.5.\n% 'location' placement of scalebar inside the axes {'southeast'},\n% 'southwest','northeast', or 'northwest'.\n% 'backgroundcolor' background color of the text box {'none'}.\n% 'fontsize' Fontsize {10}\n%\n% Output arguments\n%\n% SB handle to scale bar\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% imageschs(DEM)\n% SB = ScaleBar;\n% SB.location = 'northeast';\n% SB.color = 'w';\n% smaller(SB,2)\n%\n% References: The function uses plotboxpos by Kelly Kearney. The function\n% is available here: https://github.com/kakearney/plotboxpos-pkg\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 8. September, 2021\n\n properties(SetAccess = 'private')\n scale\n scaletext\n ax\n el\n end\n \n properties(GetAccess = 'public', SetAccess = 'public')\n color = 'k'\n displayunit = 'auto'\n xyunit = 'm'\n rellength = 0.2;\n location = 'southeast'\n backgroundcolor = 'none'\n fontsize = 10; \n end\n \n methods\n \n function SB = ScaleBar(varargin)\n \n % Parse inputs\n p = inputParser;\n addParameter(p,'parent',gca);\n addParameter(p,'xyunit','m');\n addParameter(p,'displayunit','auto');\n addParameter(p,'color','k');\n addParameter(p,'rellength',0.2);\n addParameter(p,'backgroundcolor','none');\n addParameter(p,'fontsize',10);\n addParameter(p,'location','southeast',@(x) ischar(validatestring(x,{'northwest','southwest','northeast','southeast'})));\n parse(p,varargin{:});\n \n params = p.Results;\n \n % set initial location of scalebar\n x1 = 0;\n x2 = 1;\n y1 = 0;\n y2 = 0;\n \n SB.scaletext = annotation('textbox','EdgeColor','none',...\n 'BackgroundColor',params.backgroundcolor,...\n 'Position',[y1 y2 1 0.05],...\n 'String','1',...\n 'HorizontalAlignment','center',...\n 'VerticalAlignment','bottom',...\n 'FitBoxToText','on',...\n 'Fontsize',params.fontsize,...\n 'Margin',3,...\n 'Color',params.color);\n SB.scale = annotation('line',[x1 x2], [y1 y2],'Color',params.color,'LineWidth',2);\n SB.ax = params.parent;\n SB.xyunit = params.xyunit;\n SB.displayunit = params.displayunit;\n SB.location = params.location;\n SB.rellength = params.rellength;\n \n %% Create listeners\n hfig = SB.ax.Parent;\n SB.el = addlistener(SB.ax,{'XLim','YLim', 'Position', 'OuterPosition'},'PostSet',@(src,evnt)placescalebar(SB));\n hfig.SizeChangedFcn = @(src,evnt) placescalebar(SB); \n end\n \n function set.color(SB,c)\n colorize(SB,'color',c)\n end\n function set.backgroundcolor(SB,c)\n colorize(SB,'backgroundcolor',c)\n end\n function set.location(SB,location)\n location = validatestring(location,{'northwest','southwest','northeast','southeast'});\n SB.location = location;\n placescalebar(SB)\n end\n function set.rellength(SB,l)\n validateattributes(l,'numeric',{'>',0,'<',0.8})\n SB.rellength = l;\n placescalebar(SB)\n end\n function set.xyunit(SB,unit)\n unit = validatestring(unit,{'m','km','none'});\n SB.xyunit = unit;\n placescalebar(SB)\n end\n function set.displayunit(SB,unit)\n unit = validatestring(unit,{'m','km','none','auto'});\n SB.displayunit = unit;\n placescalebar(SB)\n end\n function set.fontsize(SB,fs)\n textchange(SB,'FontSize',fs);\n end\n \n function delete(SB)\n % Delete ScaleBar\n \n delete(SB.el)\n delete(SB.scale)\n delete(SB.scaletext)\n try\n hfig = SB.ax.Parent; \n hfig.SizeChangedFcn = [];\n end\n \n end\n \n function bigger(SB,val)\n % Increase font size of scale bar text\n if nargin == 1\n textchange(SB,'Bigger',1)\n else\n textchange(SB,'Bigger',val)\n end\n end\n function smaller(SB,val)\n % Decrease font size of scale bar text\n if nargin == 1\n textchange(SB,'Smaller',1)\n else\n textchange(SB,'Smaller',val)\n end\n end\n \n function textchange(SB,type,val)\n switch type\n case 'FontSize'\n SB.scaletext.FontSize = val;\n case 'Bigger'\n SB.scaletext.FontSize = SB.scaletext.FontSize + val;\n case 'Smaller'\n SB.scaletext.FontSize = SB.scaletext.FontSize - val;\n end\n placescalebar(SB)\n end\n \n function colorize(SB,type,c)\n switch type\n case 'color'\n SB.scale.Color = c;\n SB.scaletext.Color = c;\n case 'backgroundcolor'\n SB.scaletext.BackgroundColor = c;\n end\n end\n \n \n function placescalebar(SB)\n \n lims = axis(SB.ax);\n \n units_former = SB.ax.Units;\n SB.ax.Units = 'normalized';\n pos = plotboxpos(SB.ax);\n \n xext = lims(2)-lims(1);\n scalefactor = pos(3)/xext;\n sblengthnorm = SB.rellength; % scalebar should have about 1/10 of the x-axis extent\n sblength = xext*sblengthnorm;\n sblengthvalues = [0.1 0.25 .5 1] * 10.^(ceil(log10(sblength)));\n % find nearest value\n [~,ix] = min(abs(sblengthvalues-sblength));\n sblength = sblengthvalues(ix);\n \n switch SB.xyunit\n case 'none'\n sblengthtext = num2str(sblength);\n case 'm' \n switch SB.displayunit\n case 'm'\n sblengthtext = [num2str(sblength) ' m'];\n case 'km'\n sblengthtext = [num2str(sblength/1000) ' km'];\n case 'auto'\n if sblength > 1000\n sblengthtext = [num2str(sblength/1000) ' km'];\n else\n sblengthtext = [num2str(sblength) ' m'];\n end\n case 'none'\n sblengthtext = num2str(sblength);\n end\n case 'km'\n switch SB.displayunit\n case 'm'\n sblengthtext = [num2str(sblength*1000) ' m'];\n case 'km'\n sblengthtext = [num2str(sblength) ' km'];\n case 'auto'\n if sblength > 1000\n sblengthtext = [num2str(sblength) ' km'];\n else\n sblengthtext = [num2str(sblength*1000) ' m'];\n end\n case 'none'\n sblengthtext = num2str(sblength);\n end\n end\n \n sblength = sblength*scalefactor;\n \n % nearest values\n switch SB.location\n case 'southeast'\n x1 = pos(1) + pos(3)*0.95;\n y1 = pos(2) + pos(4)*0.05;\n x2 = x1-sblength;\n y2 = y1;\n x = [x2 x1];\n y = [y1 y2];\n case 'northeast'\n x1 = pos(1) + pos(3)*0.95;\n y1 = pos(2) + pos(4)*0.85;\n x2 = x1-sblength;\n y2 = y1;\n x = [x2 x1];\n y = [y1 y2];\n case 'northwest'\n x1 = pos(1) + pos(3)*0.05;\n y1 = pos(2) + pos(4)*0.85;\n x2 = x1+sblength;\n y2 = y1;\n x = [x1 x2];\n y = [y1 y2];\n case 'southwest'\n x1 = pos(1) + pos(3)*0.05;\n y1 = pos(2) + pos(4)*0.05;\n x2 = x1+sblength;\n y2 = y1;\n x = [x1 x2];\n y = [y1 y2];\n \n end\n \n SB.scale.X = [x1 x2];\n SB.scale.Y = [y1 y2];\n SB.scaletext.FitBoxToText = 'on';\n textheight = SB.scaletext.Position(4);\n SB.scaletext.Position = [min(x) y(1) sblength textheight];\n pr = SB.scaletext.Units;\n SB.scaletext.Units = 'Points';\n SB.scaletext.Position(4) = SB.scaletext.FontSize + SB.scaletext.Margin*2;\n SB.scaletext.Units = pr;\n SB.scaletext.String = sblengthtext;\n \n SB.ax.Units = units_former;\n \n end\n \n \n end\n\nend\n\nfunction pos = plotboxpos(h)\n%PLOTBOXPOS Returns the position of the plotted axis region\n%\n% pos = plotboxpos(h)\n%\n% This function returns the position of the plotted region of an axis,\n% which may differ from the actual axis position, depending on the axis\n% limits, data aspect ratio, and plot box aspect ratio. The position is\n% returned in the same units as the those used to define the axis itself.\n% This function can only be used for a 2D plot. \n%\n% Input variables:\n%\n% h: axis handle of a 2D axis (if ommitted, current axis is used).\n%\n% Output variables:\n%\n% pos: four-element position vector, in same units as h\n\n% Copyright 2010 Kelly Kearney\n\n% Check input\n\nif nargin < 1\n h = gca;\nend\n\nif ~ishandle(h) || ~strcmp(get(h,'type'), 'axes')\n error('Input must be an axis handle');\nend\n\n% Get position of axis in pixels\n\ncurrunit = get(h, 'units');\naxisPos = getpixelposition(h);\n\n% Calculate box position based axis limits and aspect ratios\n\ndarismanual = strcmpi(get(h, 'DataAspectRatioMode'), 'manual');\npbarismanual = strcmpi(get(h, 'PlotBoxAspectRatioMode'), 'manual');\n\nif ~darismanual && ~pbarismanual\n \n pos = axisPos;\n \nelse\n\n xlim = get(h, 'XLim');\n ylim = get(h, 'YLim');\n \n % Deal with axis limits auto-set via Inf/-Inf use\n \n if any(isinf([xlim ylim]))\n hc = get(h, 'Children');\n hc(~arrayfun( @(h) isprop(h, 'XData' ) & isprop(h, 'YData' ), hc)) = [];\n xdata = get(hc, 'XData');\n if iscell(xdata)\n xdata = cellfun(@(x) x(:), xdata, 'uni', 0);\n xdata = cat(1, xdata{:});\n end\n ydata = get(hc, 'YData');\n if iscell(ydata)\n ydata = cellfun(@(x) x(:), ydata, 'uni', 0);\n ydata = cat(1, ydata{:});\n end\n isplotted = ~isinf(xdata) & ~isnan(xdata) & ...\n ~isinf(ydata) & ~isnan(ydata);\n xdata = xdata(isplotted);\n ydata = ydata(isplotted);\n if isempty(xdata)\n xdata = [0 1];\n end\n if isempty(ydata)\n ydata = [0 1];\n end\n if isinf(xlim(1))\n xlim(1) = min(xdata);\n end\n if isinf(xlim(2))\n xlim(2) = max(xdata);\n end\n if isinf(ylim(1))\n ylim(1) = min(ydata);\n end\n if isinf(ylim(2))\n ylim(2) = max(ydata);\n end\n end\n\n dx = diff(xlim);\n dy = diff(ylim);\n dar = get(h, 'DataAspectRatio');\n pbar = get(h, 'PlotBoxAspectRatio');\n\n limDarRatio = (dx/dar(1))/(dy/dar(2));\n pbarRatio = pbar(1)/pbar(2);\n axisRatio = axisPos(3)/axisPos(4);\n\n if darismanual\n if limDarRatio > axisRatio\n pos(1) = axisPos(1);\n pos(3) = axisPos(3);\n pos(4) = axisPos(3)/limDarRatio;\n pos(2) = (axisPos(4) - pos(4))/2 + axisPos(2);\n else\n pos(2) = axisPos(2);\n pos(4) = axisPos(4);\n pos(3) = axisPos(4) * limDarRatio;\n pos(1) = (axisPos(3) - pos(3))/2 + axisPos(1);\n end\n elseif pbarismanual\n if pbarRatio > axisRatio\n pos(1) = axisPos(1);\n pos(3) = axisPos(3);\n pos(4) = axisPos(3)/pbarRatio;\n pos(2) = (axisPos(4) - pos(4))/2 + axisPos(2);\n else\n pos(2) = axisPos(2);\n pos(4) = axisPos(4);\n pos(3) = axisPos(4) * pbarRatio;\n pos(1) = (axisPos(3) - pos(3))/2 + axisPos(1);\n end\n end\nend\n\n% Convert plot box position to the units used by the axis\n\nhparent = get(h, 'parent');\nhfig = ancestor(hparent, 'figure'); % in case in panel or similar\ncurrax = get(hfig, 'currentaxes');\n\ntemp = axes('Units', 'Pixels', 'Position', pos, 'Visible', 'off', 'parent', hparent);\nset(temp, 'Units', currunit);\npos = get(temp, 'position');\ndelete(temp);\n\nset(hfig, 'currentaxes', currax);\nend\n\n\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "ttcmap.m", "ext": ".m", "path": "topotoolbox-master/colormaps/ttcmap.m", "size": 7409, "source_encoding": "utf_8", "md5": "f69ae3172e6256ac1df5fa16898e307e", "text": "function [cmap,zlimits] = ttcmap(zlimits,varargin)\n\n%TTCMAP create elevation color map optimized for elevation range\n%\n% Syntax\n% \n% [cmap,zlimits] = ttcmap(zlimits)\n% [cmap,zlimits] = ttcmap(DEM)\n% [cmap,zlimits] = ttcmap(...,pn,pv,...)\n% ttcmap\n% t = ttcmap\n%\n% Description\n%\n% TTCMAP has a functionality similar to the Mapping Toolbox function\n% demcmap. The function creates a colormap for displaying digital\n% elevation models, in particularly if topography and bathymetry are to\n% be displayed in the same map. ttcmap returns a colormap so that\n% negative values in the DEM are distinct from positive values. To\n% ensure that the color transition is exactly at the value 0, the color\n% limits (e.g. via the command clim) in the displayed map must be set to \n% zlimits. \n%\n% ttcmap without in- and output arguments shows available colormaps and\n% their elevation range.\n%\n% t = ttcmap with one output argument but no input arguments returns\n% available colormaps and their elevation range as table.\n%\n% Input arguments\n%\n% zlimits two element vector with maximum and minimum elevation\n% DEM GRIDobj from which zlimits will be calculated\n% \n% Parameter name/value pairs\n%\n% 'n' number of colors (default = 255).\n% 'cmap' colormap to be used. Default is 'gmtrelief'. For an overview\n% of available colormaps call ttcmap with no input arguments\n% 'zero' 'land' or 'sea'. Determines whether the value zero will be\n% displayed as 'land' (default) or as 'sea'.\n% \n% \n% Output arguments\n%\n% cmap n*3 colormap\n% zlimits adjusted elevation range \n% t table with available colormaps and their elevation ranges\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% % Let's pretend that the lower 300 m of the DEM\n% % are submerged\n% DEM = DEM-min(DEM)-300;\n% \n% [clr,zlimits] = ttcmap(DEM,'cmap','gmtglobe');\n% imageschs(DEM,DEM,'colormap',clr,'caxis',zlimits);\n%\n% % If you want to plot with imagesc\n% figure\n% imagesc(DEM);\n% colormap(clr)\n% caxis(zlimits)\n%\n%\n% References: Colormaps available through ttcmap are obtained from \n% following website:\n% http://soliton.vm.bytemark.co.uk/pub/cpt-city/views/totp-svg.html\n%\n% See also: IMAGESCHS\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 5. February, 2018\n\nallowedcmaps = {'gmtrelief','france','mby','gmtglobe','etopo1'};\nif nargin == 0\n ncmaps = numel(allowedcmaps);\n Min_Elevation = zeros(ncmaps,1);\n Max_Elevation = zeros(ncmaps,1);\n for r = 1:numel(allowedcmaps)\n elev = getcolormap(allowedcmaps{r}); \n Min_Elevation(r) = min(elev);\n Max_Elevation(r) = max(elev);\n end\n\n Colormap_Name = allowedcmaps(:);\n cmap = table(Colormap_Name,Min_Elevation,Max_Elevation);\n \n if nargout == 2\n zlimits = [];\n elseif nargout == 0\n disp(cmap);\n clear cmap\n return\n end\n \n return\nend\n\np = inputParser;\np.FunctionName = 'ttcmap';\n% optional\naddParamValue(p,'n',255,@(x)isnumeric(x) && x>=1);\naddParamValue(p,'cmap','gmtrelief');\naddParamValue(p,'zero','land');\nparse(p,varargin{:});\n\ncmaptype = validatestring(p.Results.cmap,allowedcmaps);\n\nif isa(zlimits,'GRIDobj')\n zlimits = [min(zlimits) max(zlimits)];\nend\n\nnr = 255;\n[elev,clr] = getcolormap(cmaptype);\n\n\n% Problem: the color map should \nelevmap = linspace(min(zlimits(:)),max(zlimits(:)),nr);\n% which of the entries is closest to zero\nif zlimits(1)<0 && zlimits(2)>0\n ix = find(elev==0);\n \n if ~isempty(ix)\n \n switch lower(p.Results.zero)\n case 'land'\n elev = [elev(1:ix-1);elev(ix-1)./1000; elev(ix:end)];\n clr = [clr(1:ix-1,:);clr(ix-1,:); clr(ix:end,:)];\n case 'water'\n elev = [elev(1:ix);elev(ix)./1000; elev(ix+1:end)];\n clr = [clr(1:ix,:);clr(ix,:); clr(ix+1:end,:)];\n end\n end\n \n [~,ix] = min(abs(elevmap));\n elevmap = elevmap-elevmap(ix);\n zlimits = [elevmap(1) elevmap(end)];\nelse\n zlimits = [min(zlimits) max(zlimits)];\nend\n\ncmap = interp1(elev,clr,elevmap);\n\n% if the elevation range in zlimits extends beyond the limits of the\n% colormap, interp1 will return nans in the colormap\nI = isnan(cmap);\nif all(I(:,1))\n error('The zlimits are outside the range of the colormap')\nend\nif any(I(:,1))\n I = ~I(:,1);\n ix = find(I,1,'first');\n for r = 1:3; cmap(1:ix,r) = cmap(ix,r);end\n ix = find(I,1,'last');\n for r = 1:3; cmap(ix:end,r) = cmap(ix,r);end\nend\n \n\n\nend\n\nfunction [elev,clr] = getcolormap(type)\n\nswitch lower(type)\n \n %% gmtglobe\n case 'gmtglobe'\n \ndata = ...\n[-10000\t153\t0\t255\n-9500\t153\t0\t255\n-9000\t153\t0\t255\n-8500\t136\t17\t255 \n-8000\t119\t34\t255\n-7500\t102\t51\t255\n-7000\t85\t68\t255\n-6500\t68\t85\t255\n-6000\t51\t102\t255\n-5500\t34\t119\t255 \n-5000\t17\t136\t255\n-4500\t0\t153\t255\n-4000\t27\t164\t255\n-3500\t54\t175\t255\n-3000\t81\t186\t255\n-2500\t108\t197\t255\n-2000\t134\t208\t255\n-1500\t161\t219\t255\n-1000\t188\t230\t255\n-500\t215\t241\t255\n-200\t241\t252\t255\n0\t51\t102\t0\n100\t51\t204\t102\n200\t187\t228\t146\n500\t255\t220\t185\n1000\t243\t202\t137\n1500\t230\t184\t88\n2000\t217\t166\t39\n2500\t168\t154\t31\n3000\t164\t144\t25\n3500\t162\t134\t19\n4000\t159\t123\t13\n4500\t156\t113\t7\n5000\t153\t102\t0\n5500\t162\t89\t89\n6000\t178\t118\t118\n6500\t183\t147\t147\n7000\t194\t176\t176\n7500\t204\t204\t204\n8000\t229\t229\t229\n8500\t242\t242\t242\n9000\t255\t255\t255\n9500\t255\t255\t255];\n case 'france'\n %% france\ndata = [...\n-5000 113 171 216\n-4500 121 178 222\n-3500 132 185 227\n-2500 141 193 234\n-2000 150 201 240\n-1500 161 210 247\n-1000 172 219 251\n-500 185 227 255\n-200 198 236 255\n-100 216 242 254\n0 172 208 165\n100 148 191 139\n250 189 204 150\n500 225 228 181\n750 239 235 192\n1000 222 214 163\n1500 202 185 130\n2000 172 154 124\n2500 186 174 154\n3000 202 195 184\n3500 224 222 216\n4000 245 244 242];\n case 'gmtrelief'\n data = [...\n-8000\t0\t0\t0\t\n-7000\t0\t5\t25\t\n-6000\t0\t10\t50\t\n-5000\t0\t80\t125\t\n-4000\t0\t150\t200\t\n-3000\t86\t197\t184\t\n-2000\t172\t245\t168\t\n-1000\t211\t250\t211\t\n0\t70\t120\t50\n500\t120\t100\t50\n1000\t146\t126\t60\t\n2000\t198\t178\t80\t\n3000\t250\t230\t100\t\n4000\t250\t234\t126\t\n5000\t252\t238\t152\t\n6000\t252\t243\t177\t\n7000\t253\t249\t216\t];\n case 'mby'\ndata = [...\n-8000 0 0\t80 \n-6000 0 30 100 \n-4000 0 50 102 \n-2500\t19 108 160\t\n-150\t24 140 205\t\n-50 135 206 250 \n-10\t 176 226\t255\t\n0 0 97\t71 \n50\t16 123\t48\n500\t232 214\t125\t\n1200\t163 68 0\t\n1800\t130 30 30\t\n2800\t161 161 161\t\n4000\t206 206 206\t];\n\n case 'etopo1'\ndata = ...\n[-11000\t10\t0\t121\n-10500\t26\t0\t137\n-10000\t38\t0\t152\n-9500\t27\t3\t166\n-9000\t16\t6\t180\n-8500\t5\t9\t193\n-8000\t0\t14\t203\n-7500\t0\t22\t210\n-7000\t0\t30\t216\n-6500\t0\t39\t223\n-6000\t12\t68\t231\n-5500\t26\t102\t240\n-5000\t19\t117\t244\n-4500\t14\t133\t249\n-4000\t21\t158\t252\n-3500\t30\t178\t255\n-3000\t43\t186\t255\n-2500\t55\t193\t255\n-2000\t65\t200\t255\n-1500\t79\t210\t255\n-1000\t94\t223\t255\n-500\t138\t227\t255\n0.00\t51\t102\t0\n100\t 51\t204\t102\n200\t 187\t228\t146\n500\t 255\t220\t185\n1000\t243\t202\t137\n1500\t230\t184\t88\n2000\t217\t166\t39\n2500\t168\t154\t31\n3000\t164\t144\t25\n3500\t162\t134\t19\n4000\t159\t123\t13\n4500\t156\t113\t7\n5000\t153\t102\t0\n5500\t162\t89\t89\n6000\t178\t118\t118\n6500\t183\t147\t147\n7000\t194\t176\t176\n7500\t204\t204\t204\n8000\t229\t229\t229];\n\n otherwise\n error('unknown colormap');\nend\n\nelev = data(:,1);\nclr = data(:,2:end)/255;\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "demprofile.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/demprofile.m", "size": 2234, "source_encoding": "utf_8", "md5": "ad3eb1effcb69999451ce63954a9ac00", "text": "function [dn,z,x,y] = demprofile(DEM,n,x,y)\n\n%DEMPROFILE get profile along path\n%\n% Syntax\n%\n% [d,z] = demprofile(DEM)\n% [d,z] = demprofile(DEM,n)\n% [d,z,x,y] = demprofile(DEM,n,x,y)\n% p = demprofile(DEM,...)\n% p = demprofile(DEM,p)\n%\n% Description\n%\n% demprofile enables to interactively or programmetically derive\n% elevation profiles from DEMs.\n%\n% Input arguments\n%\n% DEM digital elevation model (class: GRIDobj)\n% n number of points along profile\n% x,y coordinate vectors of profile vertices\n% p structure array (struct) returned by demprofile\n%\n% Output arguments\n%\n% d distance along profile\n% z elevation values interpolated (linear) onto profile\n% x,y coordinate vectors of profile \n%\n% p If only one output argument is used than demprofile returns\n% a scalar structure array with fieldnames that refer to above \n% listed output arguments.\n% \n% See also: GRIDobj/interp, GRIDobj/measure\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 2. September, 2020\n\n\n% interactive\nif nargin <= 2\n \n if nargin == 2 && isstruct(n)\n x = n.x;\n y = n.y;\n dn = getdistance(x,y);\n else\n \n h = imagesc(DEM);\n ax = get(h,'Parent');\n\n [x, y] = getline(ax);\n do = getdistance(x,y);\n \n if nargin == 1\n n = ceil(do(end)/DEM.cellsize)*2;\n end\n \n dn = linspace(0,do(end),n);\n dn = dn(:);\n xy = interp1(do,[x y],dn,'linear');\n \n x = xy(:,1);\n y = xy(:,2);\n end\n \nelse\n if n ~= numel(x);\n x = x(:);\n y = y(:);\n do = getdistance(x,y);\n dn = linspace(0,do(end),n);\n dn = dn(:);\n xy = interp1(do,[x y],dn,'linear');\n \n x = xy(:,1);\n y = xy(:,2);\n else\n \n dn = getdistance(x,y);\n end\nend\n\nz = double(interp(DEM,x,y));\n\nif nargout == 1\n \n out.d = dn;\n out.z = z;\n out.x = x;\n out.y = y;\n \n dn = out;\nend\n\nend\n \n\n\nfunction cumdxy = getdistance(x,y)\n x = x(:);\n y = y(:);\n\n dx = diff(x);\n dy = diff(y);\n dxy = hypot(dx, dy); % square root of sum of squares\n cumdxy = [0; cumsum(dxy,1)];\nend % "} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "line2GRIDobj.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/line2GRIDobj.m", "size": 2452, "source_encoding": "utf_8", "md5": "fdf709803da04db01e146056e52b242f", "text": "function L = line2GRIDobj(DEM,varargin)\n\n%LINE2GRIDOBJ convert line to a grid\n%\n% Syntax\n%\n% L = line2GRIDobj(DEM,x,y)\n% L = line2GRIDobj(DEM,MS)\n%\n% Description\n%\n% line2GRIDobj grids a polyline defined by a set of x and y\n% coordinates. x and y can be nan-punctuated vectors. Alternatively,\n% the polyline can be defined by a mapping structure MS that has the\n% fields X and Y.\n% \n% Input arguments\n%\n% DEM grid \n% x,y coordinate vectors that define the vertices of a polyline.\n% Segments of the line can be separated by nans\n% MS mapstruct of a polyline as imported by shaperead. Must have\n% the fields X and Y.\n%\n% Output arguments\n%\n% L gridded line (GRIDobj). Grid has the same extent and cellsize\n% as DEM.\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% x = [381819 406059];\n% y = [3792813 3803583];\n% L = line2GRIDobj(DEM,x,y);\n% L = dilate(L,ones(5));\n% imageschs(DEM,L)\n%\n% See also: GRIDobj/coord2ind, GRIDobj/sub2coord, GRIDobj/getcoordinates\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 26. August, 2018\n\n% 26/8/2018 line2GRIDobj now deals with lines that have their start and end\n% points outside the grid borders.\n\n\nnarginchk(1,3)\n\nif nargin==2\n x = [varargin{1}.X];\n y = [varargin{1}.Y];\nelse\n x = varargin{1};\n y = varargin{2};\nend\n\n%%\n[X,Y] = refmat2XY(DEM.refmat,DEM.size);\nX = X(:);\nY = Y(:);\n\n% force column vectors\nx = x(:);\ny = y(:);\n\ndx = X(2)-X(1);\ndy = Y(2)-Y(1);\n\nIX1 = (x-X(1))./dx + 1;\nIX2 = (y-Y(1))./dy + 1;\n\ncols = round(IX1);\nrows = round(IX2);\n\n%%\nsiz = DEM.size;\n\nL = GRIDobj(DEM,'logical');\n\nsubs = [];\n\n\nfor r = 2:numel(rows)\n if any(isnan(rows([r r-1])))\n continue\n end\n \n p1 = [rows(r-1) cols(r-1)];\n p2 = [rows(r) cols(r) ];\n \n subs = [subs;getline(p1,p2)]; %#ok\nend\n\nif isempty(subs)\n return\nend\n\n% Remove cells that are outside the grid borders\noutsidegrid = subs(:,1) < 1 | subs(:,1) > siz(1) | ...\n subs(:,2) < 1 | subs(:,2) > siz(2);\n \nsubs(outsidegrid,:) = [];\n\nif isempty(subs)\n return\nend\n\nIX = sub2ind(siz,subs(:,1),subs(:,2));\nL.Z(IX) = true;\nL.name = 'line2GRIDobj';\n \n\nfunction subs = getline(p1,p2)\n\np = p1;\nd = p2-p1;\nN = max(abs(d));\ns = d/N;\n\nsubs = zeros(N,2);\nsubs(1,:) = p1;\n\nfor ii=2:N+1\n p = p+s;\n subs(ii,:) = round(p);\nend\nend\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "GRIDobj.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/GRIDobj.m", "size": 16757, "source_encoding": "utf_8", "md5": "6ea7e6581d8a6516a18fa590e970ada9", "text": "classdef GRIDobj\n \n%GRIDobj Create instance of a GRIDobj\n%\n% Syntax\n%\n% DEM = GRIDobj(X,Y,dem)\n% DEM = GRIDobj('ESRIasciiGrid.txt')\n% DEM = GRIDobj('GeoTiff.tif')\n% DEM = GRIDobj();\n% DEM = GRIDobj([]);\n% DEM = GRIDobj(FLOWobj or GRIDobj or STREAMobj,class)\n%\n%\n% Description\n%\n% GRIDobj creates an instance of the grid class, which contains a\n% numerical or logical matrix and information on georeferencing. When a\n% GRIDobj is created from a file, the number format of the data in\n% GRIDobj is either single or double. Unsigned and signed integers are\n% converted to single. For unsigned integers, missing values are\n% assumed to be denoted as intmax(class(input)). For signed integers,\n% missing values are assumed to be intmin(class(input)). Please check,\n% that missing values in your data have been identified correctly\n% before further analysis.\n%\n% Note that while throughout this help text GRIDobj is associated with\n% gridded digital elevation models, instances of GRIDobj can contain\n% other gridded, single band, datasets such as flow accumulation grids, \n% gradient grids etc.\n%\n% DEM = GRIDobj(X,Y,dem) creates a DEM object from the coordnate\n% matrices or vectors X and Y and the matrix dem. The elements of dem\n% refer to the elevation of each pixel. \n%\n% DEM = GRIDobj('ESRIasciiGrid.txt') creates a DEM object from an ESRI \n% Ascii grid exported from other GI systems. \n%\n% DEM = GRIDobj('GeoTiff.tif') creates a DEM object from a Geotiff.\n%\n% DEM = GRIDobj() opens a dialog box to read either an ESRI Ascii Grid\n% or a Geotiff.\n%\n% DEM = GRIDobj([]) creates an empty instance of GRIDobj\n%\n% DEM = GRIDobj(FLOWobj or GRIDobj or STREAMobj,class) creates an\n% instance of GRIDobj with all common properties (e.g., spatial\n% referencing) inherited from another instance of a FLOWobj, GRIDobj \n% or STREAMobj class. DEM.Z is set to all zeros where class can be\n% integer classes or double or single. By default, class is double.\n%\n% Example\n%\n% % Load DEM\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% % Display DEM\n% imageschs(DEM)\n%\n% See also: FLOWobj, STREAMobj, GRIDobj/info\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 17. August, 2017\n\n \n properties\n %Public properties\n \n%Z matrix with elevation values\n% The Z property contains the elevation values in a 2D matrix.\n%\n% See also GRIDobj\n Z \n \n%CELLSIZE cellsize of the grid (scalar)\n% The cellsize property specifies the spacing of the grid in x and y\n% directions. Note that TopoToolbox requires grids to have square cells,\n% e.g., dx and dy are the same.\n%\n% See also GRIDobj \n cellsize \n \n%REFMAT 3-by-2 affine transformation matrix\n% The refmat property specifies a 3-by-2 affine transformation matrix as\n% used by the mapping toolbox. \n%\n% See also GRIDobj, makerefmat\n refmat \n \n%SIZE size of the grid (two element vector)\n% The cellsize property is a two element vector that contains the number\n% of rows and columns of the Z matrix.\n%\n% See also GRIDobj, size\n size \n \n%NAME optional name (string)\n% The name property allows to specify a name of the grid. By default and\n% if the constructor is called with a filename, the name property is set\n% to the name of the file.\n%\n% See also GRIDobj\n name \n \n%ZUNIT unit of grid values (string)\n% The zunit is optional and is used to store the physical unit (e.g. m)\n% of an instance of GRIDobj. This property is currently not fully\n% supported and TopoToolbox functions usually assume that the unit is in\n% meters and equals the xyunit property.\n%\n% See also GRIDobj\n zunit \n \n%XYUNIT unit of the coordinates (string)\n% The xyunit is optional and is used to store the physical unit (e.g. m)\n% of the coordinates. This property is currently not fully\n% supported and TopoToolbox functions usually assume that the unit is in\n% meters and equals the zunit property.\n%\n% See also GRIDobj \n xyunit \n \n%GEOREF additional information on spatial referencing (structure array)\n% The georef property stores an instance of map.rasterref.MapCellsReference, \n% a structure array GeoKeyDirectoryTag, and a mapping structure\n% (mstruct).\n%\n% See also GRIDobj, geotiffinfo \n georef \n \n end\n \n methods\n function DEM = GRIDobj(varargin)\n % GRIDobj constructor\n \n if nargin == 3 \n %% GRIDobj is created from three matrices\n % GRIDobj(X,Y,dem)\n X = varargin{1};\n Y = varargin{2};\n \n if min(size(X)) > 1\n X = X(1,:);\n end\n if min(size(Y)) > 1\n Y = Y(:,1);\n end\n \n DEM.Z = varargin{3};\n DEM.size = size(DEM.Z);\n \n if numel(X) ~= DEM.size(2) || numel(Y) ~= DEM.size(1)\n error('TopoToolbox:GRIDobj',...\n ['Coordinate matrices/vectors don''t fit the size of the \\n'...\n 'the grid']);\n end\n \n if (Y(2)-Y(1)) > 0\n % the y coordinate vector must be monotonically\n % decreasing, so that the left upper edge of the DEM is\n % north-west (on the northern hemisphere).\n DEM.Z = flipud(DEM.Z);\n Y = Y(end:-1:1);\n end\n \n dy = Y(2)-Y(1);\n dx = X(2)-X(1);\n \n if abs(abs(dx)-abs(dy))>1e-9\n error('TopoToolbox:GRIDobj',...\n 'The resolution in x- and y-direction must be the same');\n end\n \n \n DEM.refmat = double([0 dy;...\n dx 0;...\n X(1)-dx Y(1)-dy]);\n \n DEM.cellsize = dx;\n DEM.georef = [];\n DEM.name = [];\n \n \n elseif nargin <= 2\n \n \n if nargin == 0\n %% No input arguments. File dialog box will open and ask\n % for a txt or tiff file as input\n FilterSpec = {'*.txt;*.asc;*.tif;*.tiff','supported file types (*.txt,*.asc,*.tif,*.tiff)';...\n '*.txt', 'ESRI ASCII grid (*.txt)';...\n '*.asc', 'ESRI ASCII grid (*.asc)';...\n '*.tif', 'GeoTiff (*.tif)';...\n '*.tiff', 'GeoTiff (*.tiff)';...\n '*.*', 'all files (*.*)'};\n \n DialogTitle = 'Select ESRI ASCII grid or GeoTiff';\n [FileName,PathName] = uigetfile(FilterSpec,DialogTitle);\n \n if FileName == 0\n error('TopoToolbox:incorrectinput',...\n 'no file was selected')\n end\n \n filename = fullfile(PathName, FileName);\n \n elseif nargin > 0\n % One input argument\n if isempty(varargin{1})\n % if empty array than return empty GRIDobj\n return\n elseif isa(varargin{1},'GRIDobj') || ...\n isa(varargin{1},'FLOWobj') || ...\n isa(varargin{1},'STREAMobj') \n % empty GRIDobj\n DEM = GRIDobj([]);\n % find common properties of F and G and from F to G\n pg = properties(DEM);\n pf = properties(varargin{1});\n p = intersect(pg,pf);\n for r = 1:numel(p)\n DEM.(p{r}) = varargin{1}.(p{r});\n end\n if nargin == 1\n cl = 'double';\n else\n cl = varargin{2};\n end\n \n if strcmp(cl,'logical')\n DEM.Z = false(DEM.size);\n else\n DEM.Z = zeros(DEM.size,cl);\n end\n DEM.name = '';\n \n return\n end\n \n % GRIDobj is created from a file\n filename = varargin{1};\n end\n \n % check if file exists\n if exist(filename,'file')~=2\n error('File doesn''t exist')\n end\n \n \n % separate filename into path, name and extension\n [pathstr,DEM.name,ext] = fileparts(filename);\n \n\n if any(strcmpi(ext,{'.tif', '.tiff'}))\n % it is a GeoTiff\n try \n % try to read using geotiffread (requires mapping\n % toolbox)\n [DEM.Z, DEM.refmat, ~] = geotiffread(filename);\n gtiffinfo = geotiffinfo(filename);\n DEM.georef.SpatialRef = gtiffinfo.SpatialRef; \n DEM.georef.GeoKeyDirectoryTag = gtiffinfo.GeoTIFFTags.GeoKeyDirectoryTag;\n georef_enabled = true;\n \n catch ME\n \n % mapping toolbox is not available. Will try to\n % read the tif file together with the tfw file\n georef_enabled = false;\n \n % the tfw file has the same filename but a tfw\n % extension\n tfwfile = fullfile(pathstr,[DEM.name '.tfw']);\n \n % check whether file exists. If it exists then read\n % it using worldfileread or own function\n tfwfile_exists = exist(tfwfile,'file');\n if tfwfile_exists\n try \n % prefer builtin worldfileread, if\n % available\n DEM.refmat = worldfileread(tfwfile);\n catch ME\n W = dlmread(tfwfile);\n \n DEM.refmat(2,1) = W(1,1);\n DEM.refmat(1,2) = W(4,1);\n DEM.refmat(3,1) = W(5,1)-W(1);\n DEM.refmat(3,2) = W(6,1)-W(4);\n end\n \n DEM.Z = imread(filename);\n else\n if ~tfwfile_exists\n error('TopoToolbox:GRIDobj:read',...\n 'GRIDobj cannot read the TIF-file because it does not have a tfw-file.');\n else\n throw(ME)\n end\n \n end\n end\n \n \n % Unless any error occurred, we now attempt to generate\n % an mapping projection structure. This will not work\n % if the DEM is in a geographic coordinate system or if\n % the projection is not supported by mstruct.\n if georef_enabled\n try\n DEM.georef.mstruct = geotiff2mstruct(gtiffinfo);\n catch\n DEM.georef.mstruct = [];\n warning('TopoToolbox:GRIDobj:projection',...\n ['GRIDobj cannot derive a map projection structure. This is either\\n' ...\n 'because the grid is in a geographic coordinate system or because\\n' ...\n 'geotiff2mstruct cannot identify the projected coordinate system used.\\n' ...\n 'TopoToolbox assumes that horizontal and vertical units of DEMs are \\n'...\n 'the same. It is recommended to use a projected coordinate system,\\n' ...\n 'preferably UTM WGS84. Use the function GRIDobj/reproject2utm\\n' ...\n 'to reproject your grid.'])\n end\n end\n \n % Finally, check whether no_data tag is available. This tag is\n % not accessible using geotiffinfo (nice hack by Simon\n % Riedl)\n tiffinfo = imfinfo(filename);\n if isfield(tiffinfo,'GDAL_NODATA')\n nodata_val = str2double(tiffinfo.GDAL_NODATA);\n end\n \n else\n [DEM.Z,R] = rasterread(filename);\n DEM.refmat = R;\n DEM.georef = [];\n end\n \n DEM.size = size(DEM.Z);\n DEM.cellsize = abs(DEM.refmat(2));\n \n % remove nans\n demclass = class(DEM.Z);\n nodata_val_exists = exist('nodata_val','var');\n \n switch demclass\n case {'uint8','uint16','uint32'}\n % unsigned integer\n DEM.Z = single(DEM.Z);\n \n if nodata_val_exists\n nodata_val = single(nodata_val);\n DEM.Z(DEM.Z == nodata_val) = nan;\n else \n DEM.Z(DEM.Z==intmax(demclass)) = nan;\n end\n \n case {'int8','int16','int32'}\n % signed integer\n DEM.Z = single(DEM.Z);\n if nodata_val_exists\n nodata_val = single(nodata_val);\n DEM.Z(DEM.Z == nodata_val) = nan;\n else \n DEM.Z(DEM.Z==intmin(demclass)) = nan;\n end\n \n case {'double','single'}\n if nodata_val_exists\n DEM.Z(DEM.Z == cast(nodata_val,class(DEM.Z))) = nan;\n end\n case 'logical'\n otherwise\n error('TopoToolbox:GRIDobj','unrecognized class')\n end\n \n \n end \n end\n \n end\n \nend\n \n\n\n\n% Subfunction for ASCII GRID import\nfunction [Z,refmat] = rasterread(file)\n\nfid=fopen(file,'r');\n% loop through header\n\nheader = struct('ncols',[],...\n 'nrows',[],...\n\t\t\t\t'xllcorner',[],...\n\t\t\t\t'yllcorner',[],...\n\t\t\t\t'cellsize',[],...\n\t\t\t\t'nodata',[]);\n\t\t\t\t\nnames = fieldnames(header);\nnrnames = numel(names);\n\ntry\n fseek(fid,0,'bof');\n for r = 1:nrnames ;\n headertext = fgetl(fid);\n [headertext, headernum] = strtok(headertext,' ');\n I = cellfun(@(x,y) strcmpi(x(1:4),y(1:4)),names,repmat({headertext},nrnames,1));\n header.(names{I}) = str2double(headernum);\n end\ncatch ME1\n error('header can not be read')\nend\n\n\n% read raster data\nZ = fscanf(fid,'%lg',[header.ncols header.nrows]);\nfclose(fid);\nZ(Z==header.nodata) = NaN;\nZ = Z';\n% create X and Y using meshgrid\nrefmat = [0 -header.cellsize;...\n header.cellsize 0;...\n header.xllcorner+(0.5*header.cellsize) - header.cellsize ...\n (header.yllcorner+(0.5*header.cellsize))+((header.nrows)*header.cellsize)];\n\nend\n\n\n\n \n \n \n\n \n "} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "surf.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/surf.m", "size": 6852, "source_encoding": "utf_8", "md5": "45f9744f3f0139f3ecfa42461f63f7f0", "text": "function ht = surf(DEM,varargin)\n\n%SURF surface plot for GRIDobj\n%\n% Syntax\n%\n% surf(DEM)\n% surf(DEM,A)\n% surf(...,pn,pv,...)\n% h = ...\n%\n% Description\n%\n% surf for GRIDobj overloads the surf command and thus provides fast\n% access to 3D visualization of digital elevation models. Note that\n% GRIDobj/surf automatically resamples the DEM so that the maximum of\n% rows or columns does not exceed 1000. This ensures that the surface\n% is efficiently drawn.\n%\n% Input arguments\n%\n% DEM digital elevation model (GRIDobj)\n% A grid to define color (GRIDobj) \n%\n% Parameter name/values\n%\n% 'exaggerate' height exaggeration, default = 1\n% \n% and all property name/value pairs allowed by surface objects.\n%\n% Example 1\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% surf(DEM)\n% camlight\n%\n% Example 2\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% surf((DEM-800)*2,'block',true,'baselevel',-900*2,'sea',true,'exaggerate',1); camlight; colormap(ttcmap((DEM-800)*2,'cmap','france'))\n% ax = gca;\n% ax.Clipping = 'off';\n% axis off\n% ax.Projection = 'perspective';\n%\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',1000);\n% S = modify(S,'upstreamto',(DEM-800)>0);\n% hold on\n% plot3(S,DEM-800,'b');\n%\n% See also: imageschs\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 30. January, 2013\n\n\n\n%% Parse inputs\np = inputParser;\np.KeepUnmatched = true;\naddOptional(p,'A',[]);\naddParameter(p,'maxrowsorcols',2000)\naddParameter(p,'exaggerate',1);\naddParameter(p,'block',false);\naddParameter(p,'baselevel',[]);\naddParameter(p,'sea',false);\naddParameter(p,'sealevel',0);\naddParameter(p,'seaalpha',0.5);\n\n% Parse\nparse(p,varargin{:});\n\n% create variables\nmaxrowsorcols = p.Results.maxrowsorcols;\nexagg = p.Results.exaggerate;\nblock = p.Results.block;\nbaselevel = p.Results.baselevel;\n\nif block\n minz = min(DEM);\n maxz = max(DEM);\n if isempty(baselevel)\n baselevel = minz-(maxz-minz)*0.2;\n end\nend \nsea = p.Results.sea;\nsealevel = p.Results.sealevel;\nseaalpha = p.Results.seaalpha;\n%%\n\nif max(DEM.size)>maxrowsorcols\n \n resamplecellsize = max(DEM.size)/(maxrowsorcols-1) * DEM.cellsize;\n DEM = resample(DEM,resamplecellsize);\n \n if ~isempty(p.Results.A)\n A = p.Results.A;\n A = resample(A,DEM);\n overlay = true;\n else\n overlay = false;\n end\n \n \nelse\n if ~isempty(p.Results.A)\n A = p.Results.A;\n validatealignment(DEM,A);\n overlay = true;\n else\n overlay = false;\n end\nend\n\n\n[x,y] = refmat2XY(DEM.refmat,DEM.size);\n\n% Create cellarray from p.Unmatched\npn = fieldnames(p.Unmatched);\npv = struct2cell(p.Unmatched);\n\npnpv = [pn pv];\npnpv = pnpv';\npnpv = pnpv(:)';\n\nif overlay\n h = surf(x,y,double(DEM.Z),double(A.Z),pnpv{:});\nelse\n h = surf(x,y,double(DEM.Z),pnpv{:});\nend\n\nexaggerate(gca,exagg);\nshading interp\n% camlight\n\nif block \n \n if any(isnan(DEM))\n error('TopoToolbox:wronginput','DEM must not have NaNs')\n end\n facecolor = [.6 .6 .6];\n facecolordark = brighten(facecolor,-0.2);\n \n xp = x(:);\n xp = [xp(1); xp; xp(end:-1:1)];\n yp = repmat(y(1),size(xp));\n zp = DEM.Z(1,:);\n zp = zp(:);\n zp = [baselevel;zp;repmat(baselevel,size(zp))];\n pa(1) = patch(xp,yp,zp,facecolor,'EdgeColor','none','FaceColor',facecolor);\n \n yp = repmat(y(end),size(xp));\n zp = DEM.Z(end,:);\n zp = zp(:);\n zp = [baselevel;zp;repmat(baselevel,size(zp))];\n pa(2) = patch(xp,yp,zp,facecolor,'EdgeColor','none','FaceColor',facecolor);\n \n yp = y(:);\n yp = [yp(1); yp; yp(end:-1:1)];\n xp = repmat(x(1),size(yp));\n zp = DEM.Z(:,1);\n zp = zp(:);\n zp = [baselevel;zp;repmat(baselevel,size(zp))];\n pa(3) = patch(xp,yp,zp,facecolordark,'EdgeColor','none','FaceColor',facecolordark);\n \n xp = repmat(x(end),size(yp));\n zp = DEM.Z(:,end);\n zp = zp(:);\n zp = [baselevel;zp;repmat(baselevel,size(zp))];\n pa(4) = patch(xp,yp,zp,facecolordark,'EdgeColor','none','FaceColor',facecolordark);\n \n set(pa,'FaceLighting','none')\n \n \n axislim = axis;\n if baselevel < min(DEM)\n axislim(5) = baselevel;\n end\n axis(axislim)\nend\n \n\nif sea \n \n if any(isnan(DEM))\n error('TopoToolbox:wronginput','DEM must not have NaNs')\n end\n facecolor = [1 1 1];\n facecolordark = [0.8 .8 .8];\n \n xp = x(:);\n xp = [xp(1); xp; xp(end:-1:1)];\n yp = repmat(y(1),size(xp));\n zp = DEM.Z(1,:);\n zp = min(zp(:),0);\n zp = double([sealevel;zp;repmat(sealevel,size(zp))]);\n pa(1) = patch(xp,yp,zp,facecolor,'EdgeColor','none','FaceColor',facecolor,'FaceAlpha',seaalpha);\n \n yp = repmat(y(end),size(xp));\n zp = DEM.Z(end,:);\n zp = min(zp(:),0);\n zp = double([sealevel;zp;repmat(sealevel,size(zp))]);\n pa(2) = patch(xp,yp,zp,facecolor,'EdgeColor','none','FaceColor',facecolor,'FaceAlpha',seaalpha);\n \n yp = y(:);\n yp = [yp(1); yp; yp(end:-1:1)];\n xp = repmat(x(1),size(yp));\n zp = DEM.Z(:,1);\n zp = min(zp(:),0);\n zp = double([sealevel;zp;repmat(sealevel,size(zp))]);\n pa(3) = patch(xp,yp,zp,facecolordark,'EdgeColor','none','FaceColor',facecolordark,'FaceAlpha',seaalpha);\n \n xp = repmat(x(end),size(yp));\n zp = DEM.Z(:,end);\n zp = min(zp(:),0);\n zp = double([sealevel;zp;repmat(sealevel,size(zp))]);\n pa(4) = patch(xp,yp,zp,facecolordark,'EdgeColor','none','FaceColor',facecolordark,'FaceAlpha',seaalpha);\n \n I = DEM.Z>0;\n% H = zeros(DEM.size);\n% H(I) = nan;\n% % Texturemap\n% I = ~I;\n% TM = repmat(I,1,1,3);\n\n hold on\n h = surf(x,y,+I,'FaceAlpha',0.5,'FaceColor',facecolor,'EdgeColor','none');\n hold off\n \n \n set(pa,'FaceLighting','none')\n \n if ~isempty(baselevel)\n axislim = axis;\n axislim(5) = baselevel;\n axis(axislim)\n end\n \n \n \n\nend\n \nif nargout == 1\n ht = h;\nend\n\n\nfunction exaggerate(axes_handle,exagfactor)\n\n% elevation exaggeration in a 3D surface plot\n%\n% Syntax\n%\n% exaggerate(axes_handle,exagfactor)\n%\n% Description\n%\n% exaggerate is a simple wrapper for calling set(gca...). It controls\n% the data aspect ratio in a 3D plot and enables elevation\n% exaggeration. \n%\n% Input\n%\n% axes_handle digital elevation model\n% exagfactor exaggeration factor (default = 1)\n%\n% Example\n%\n% load exampledem\n% for r = 1:4;\n% subplot(2,2,r);\n% surf(X,Y,dem); exaggerate(gca,r);\n% title(['exaggeration factor = ' num2str(r)]);\n% end\n%\n% \n% See also: SURF\n%\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]unibas.ch)\n% Date: 6. September, 2010\n\nif nargin == 1\n exagfactor = 1;\nend\naxis(axes_handle,'image');\nset(axes_handle,'DataAspectRatio',[1 1 1/exagfactor]);\n\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "createmask.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/createmask.m", "size": 1576, "source_encoding": "utf_8", "md5": "e6f1a75f902357fa601bca1fd25fc8a2", "text": "function MASK = createmask(DEM,usehillshade)\n\n%CREATEMASK create a binary mask using polygon mapping\n%\n% Syntax\n%\n% MASK = createmask(DEM)\n% MASK = createmask(DEM,usehillshade)\n%\n% Description\n%\n% createmask is an interactive tool to create a mask based on an\n% interactively mapped polygon.\n%\n% Input arguments\n%\n% DEM GRIDobj\n% usehillshade use hillshade as background image ({false} or true)\n%\n% Output arguments\n%\n% MASK GRIDobj with logical mask\n%\n%\n% See also: imroi, GRIDobj\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 17. August, 2017\n\nif nargin == 1\n usehillshade = false;\nend\n\nfigure\nif usehillshade\n imageschs(DEM);\nelse\n imagesc(DEM);\nend\ntitle('Create polygon');\nusedrawpolygon = ~verLessThan('matlab','9.5');\nif usedrawpolygon\n ext = getextent(DEM); \n\n h = drawpolygon('DrawingArea',...\n [ext(1) ext(3) ext(2)-ext(1) ext(4)-ext(3)]);\n pos = customWait(h);\nelse\n h = impoly; \n pos = wait(h);\nend\n\nMASK = DEM;\nMASK.name = 'mask';\nMASK.Z = createMask(h);\n\nif usedrawpolygon\n pos = h.Position;\nelse\n pos = getPosition(h);\nend\ndelete(h);\nhold on\nplot(pos([1:end 1],1),pos([1:end 1],2));\nhold off\ntitle('done');\n\n\nend\n\n\nfunction pos = customWait(hROI)\n\n% Listen for mouse clicks on the ROI\nl = addlistener(hROI,'ROIClicked',@clickCallback);\n\n% Block program execution\nuiwait;\n\n% Remove listener\ndelete(l);\n\n% Return the current position\npos = hROI.Position;\n\nend\n\nfunction clickCallback(~,evt)\n\nif strcmp(evt.SelectionType,'double')\n uiresume;\nend\n\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "inpaintnans.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/inpaintnans.m", "size": 11428, "source_encoding": "utf_8", "md5": "140920973e65c125e2266bcc64542930", "text": "function DEM = inpaintnans(DEM,varargin)\n\n%INPAINTNANS Interpolate or fill missing values in a grid (GRIDobj)\n%\n% Syntax\n%\n% DEMf = inpaintnans(DEM,type)\n% DEMf = inpaintnans(DEM,type,k)\n% DEMf = inpaintnans(DEM,type,k,conn)\n% DEMf = inpaintnans(DEM,DEM2)\n% DEMf = inpaintnans(DEM,DEM2,method)\n% DEMf = inpaintnans(DEM,DEM2,'tt','fit',1,'eps',20)\n%\n% Description\n% \n% inpaintnans fills gaps in a grid (GRIDobj) generated by measurement\n% errors or missing values. The user may choose between different\n% techniques to fill the gaps. Note that the algorithm fills only\n% pixels not connected to the DEM grid boundaries.\n%\n% inpaintnans(DEM,type) or inpaintnans(DEM,type,k) fills missing values\n% in the DEM by interpolating inward from the pixels surrounding the\n% void. There are different ways to interpolate with 'laplace'\n% interpolation being the default (see also regionfill). \n%\n% inpaintnans(DEM,DEM2) or inpaintnans(DEM,DEM2,method) fills missing\n% values using interpolation from another grid. An example is that \n% missing values in a SRTM DEM could be filled with values derived from\n% an ASTER GDEM. This technique is also referred to as the Fill and\n% Feather method (Grohman et al., 2006).\n%\n% inpaintnans(DEM,DEM2,'tt') uses a hybrid method that uses both\n% laplacian interpolation and filling using a second DEM. The methods\n% accounts for potential vertical offsets between both DEMs by fitting\n% a regression surface to the boundary pixels which is used to adjust \n% the second DEM. Missing values are then calculated by the weighted \n% average of both techniques whereas higher weights are assigned to \n% the laplacian technique if pixels are close to the boundaries of the\n% voids. Note that this technique will not fill voids connected to the\n% DEM boundaries. The technique is similar to the Delta Surface Fill\n% Method (DSF) described by Grohman et al. (2006).\n%\n% inpaintnans(DEM,'interactive') starts an interactive tool to map a\n% region to be filled by laplacian interpolation.\n%\n% Input\n%\n% DEM digital elevation model with missing values\n% indicated by nans (GRIDobj)\n% type fill algorithm \n% 'laplace' (default): laplace interpolation \n% as implemented in regionfill\n% 'fill': elevate all values in each connected\n% region of missing values to the minimum\n% value of the surrounding pixels (same as \n% the function nibble in ArcGIS Spatial Analyst)\n% 'nearest': nearest neighbor interpolation \n% using bwdist\n% 'neighbors': this option does not close all nan-regions. It\n% adds a one-pixel wide boundary to the valid values in\n% the DEM and derives values for these pixels by a\n% distance-weighted average from the valid neighbor\n% pixels. This approach does not support the third input \n% argument k.\n% 'interactive' (no further arguments): opens new figure and\n% enables drawing a polygon which is going to be\n% filled. The resulting DEM will be again displayed as\n% hillshade.\n% k if supplied, only connected components with \n% less or equal number of k pixels are filled. Others\n% remain nan. Set to inf if all pixels enclosed by non-nan\n% pixels should be filled.\n% conn Connectivity, specified as scalar 4 or 8\n% DEM2 if the second input argument is a GRIDobj, inpaintnans will\n% interpolate from DEM2 to locations of missing values in\n% DEM. \n% method interpolation method if second input argument is a GRIDobj.\n% {'linear'},'nearest','spline','pchip', 'cubic', or 'tt'.\n% \n% if method is 'tt' then several parameters can be applied\n%\n% 'eps' parameter of the gaussian radial basis function (pixels). \n% Larger values will give higher weight to the Laplacian\n% interpolation near the boundaries.\n% 'fit' 0, 1, or 2. If 1, the function will resolve a potential \n% elevation bias between DEM and DEM2 by raising/lowering\n% DEM2 to the elevations of the rim of nan-regions. If 2, the\n% function will fit a linear least squares model between the\n% two DEMs which will balance potential vertical offsets and\n% mismatches in inclination.\n%\n% Note that unlike the other interpolation methods (as defined by the \n% option 'method', 'tt' will not fill nan-regions connected to the DEM \n% boundaries.\n%\n% Output\n%\n% DEM processed digital elevation model (GRIDobj)\n%\n% Example 1\n% \n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% DEM.Z(300:400,300:400) = nan;\n% subplot(1,2,1)\n% imageschs(DEM,[],'colorbar',false)\n% DEMn = inpaintnans(DEM);\n% subplot(1,2,2);\n% imageschs(DEMn,[],'colorbar',false)\n%\n% \n% See also: ROIFILL, FILLSINKS, BWDIST, STREAMobj/inpaintnans\n%\n% References: Grohman, Greg, George Kroenung, and John Strebeck. \"Filling \n% SRTM voids: The delta surface fill method.\" Photogrammetric \n% Engineering and Remote Sensing 72.3 (2006): 213-216.\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 27. January, 2023\n\nif nargin == 1\n DEM.Z = deminpaint(DEM.Z,varargin{:});\nelseif ischar(varargin{1})\n if strcmpi(varargin{1},'neighbors')\n DEM = interpneighborpixels(DEM);\n return\n elseif strcmpi(varargin{1},'interactive')\n MASK = createmask(DEM,true);\n DEM.Z(MASK.Z) = nan;\n DEM = inpaintnans(DEM);\n DEM.Z(isnan(DEM.Z) & (~MASK.Z)) = nan;\n imageschs(DEM)\n return\n end\n DEM.Z = deminpaint(DEM.Z,varargin{:});\nelseif isa(varargin{1},'GRIDobj')\n if nargin == 2\n method = 'linear';\n else\n method = varargin{2};\n method = validatestring(method,...\n {'linear','nearest','spline','pchip','cubic','tt'},'GRIDobj/inpaintnans','method',3);\n end\n \n switch method\n case 'tt'\n p = inputParser;\n addRequired(p,'DEM2',@(x) isa(x,'GRIDobj'))\n addRequired(p,'method',@(x) strcmpi(x,'tt'))\n addParameter(p,'fit',1)\n addParameter(p,'eps',20);\n parse(p,varargin{:})\n DEM = ttinpaint(DEM,varargin{1},p.Results.eps,p.Results.fit);\n otherwise\n INAN = isnan(DEM);\n IX = find(INAN.Z);\n [x,y] = ind2coord(DEM,IX);\n znew = interp(varargin{1},x,y,method);\n DEM.Z(IX) = znew;\n end\n \nend\n\nend\n\nfunction dem = deminpaint(dem,type,k,conn)\nif nargin == 1\n type = 'laplace';\n k = inf;\n conn = 8;\nelseif nargin == 2\n k = inf;\n conn = 8;\nelseif nargin == 3\n conn = 8;\nend\n \n% error checking \n% clean boundary\nI = isnan(dem);\n% imclearborder\n% I = imclearborder(I,conn);\nmarker = I;\nmarker(2:end-1,2:end-1) = false;\nI = ~imreconstruct(marker,I) & I; \nclear marker\n\n\nif ~isinf(k)\n I = xor(bwareaopen(I,k+1,conn),I);\nend\n\n% \nif numel(dem) < 10000^2 || ~strcmpi(type,'laplace')\n\n% interpolation\nswitch lower(type)\n case 'nearest'\n % nearest neighbor interpolation\n [~,L] = bwdist(~I);\n dem = dem(L);\n case 'laplace'\n % -- use roifill (Code before 2015a) \n % dem = roifill(dem,imdilate(I,ones(3)));\n % -- use regionfill (Code after and including 2015a)\n dem = regionfill(dem,I);\n case 'fill'\n % fill to lowest surrounding neighbor\n marker = inf(size(dem),class(dem));\n markerpixels = imdilate(I,ones(3)) & ~I;\n marker(markerpixels) = dem(markerpixels);\n mask = dem;\n mask(I | isnan(dem)) = -inf;\n marker = -marker;\n mask = -mask;\n demrec = imreconstruct(marker,mask,conn);\n dem(I) = -demrec(I);\n otherwise\n error('type unknown')\nend\n\nelse\n CC = bwconncomp(I,conn);\n STATS = regionprops(CC,'SubarrayIdx','Image');\n \n for r = 1:numel(STATS)\n rows = STATS(r).SubarrayIdx{1};\n rows = [min(rows)-1 max(rows)+1];\n cols = STATS(r).SubarrayIdx{2};\n cols = [min(cols)-1 max(cols)+1];\n \n demtemp = dem(rows(1):rows(2),cols(1):cols(2));\n inatemp = padarray(STATS(r).Image,[1 1],false);\n % -- Code before 2015a \n % demtemp = roifill(demtemp,imdilate(inatemp,ones(3))); \n % -- Code after and including 2015a\n demtemp = regionfill(demtemp,inatemp); \n dem(rows(1):rows(2),cols(1):cols(2)) = demtemp;\n end\nend\nend\n\n\n\nfunction DEM = ttinpaint(DEM,DEM2,shapeparam,fit)\n\nINAN = isnan(DEM);\nINAN.Z = imclearborder(INAN.Z);\n\nD = bwdist(~INAN.Z,'euclidean');\nD = exp(-(D/shapeparam).^2);\n\ndem = DEM.Z;\n[X,Y] = getcoordinates(DEM,'matrix');\n\nDEM2res = resample(DEM2,DEM);\ndemres = DEM2res.Z;\n\nCC = bwconncomp(INAN.Z,8);\nSTATS = regionprops(CC,'SubarrayIdx','Image');\n\nfor r = 1:numel(STATS)\n % Extract subimage\n rows = STATS(r).SubarrayIdx{1};\n rows = [min(rows)-1 max(rows)+1];\n cols = STATS(r).SubarrayIdx{2};\n cols = [min(cols)-1 max(cols)+1];\n\n z = dem(rows(1):rows(2),cols(1):cols(2));\n z2 = demres(rows(1):rows(2),cols(1):cols(2));\n x = X(rows(1):rows(2),cols(1):cols(2));\n y = Y(rows(1):rows(2),cols(1):cols(2));\n d = D(rows(1):rows(2),cols(1):cols(2));\n\n\n % Get subimage of the nan-area\n I = padarray(STATS(r).Image,[1 1],false);\n\n % Predict in nan area using laplacian interpolation\n zlaplace = regionfill(z,I);\n\n % fit DEM2 to remove potential offsets\n if fit > 0\n % Get subimage with valid boundary\n B = bwperim(imdilate(I,ones(3)));\n % number of boundary pixels\n n = nnz(B);\n\n if fit == 1\n % Adjust the mean value\n b = ones(n,1)\\(double(z(B)-z2(B)));\n z(I) = b + z2(I);\n elseif fit == 2\n % Fit a LS-surface to the boundary pixels\n b = [ones(n,1) x(B) y(B)]\\(double(z(B)-z2(B)));\n z(I) = b(1) + b(2)*x(I) + b(3)*y(I) + z2(I);\n end\n\n else\n z(I) = z2(I);\n end\n % Calculate weighted average of the both\n z(I) = d(I).*zlaplace(I) + (1-d(I)).*z(I);\n \n % Write back to DEM\n dem(rows(1):rows(2),cols(1):cols(2)) = cast(z,class(dem));\nend\nDEM.Z = dem;\nend\n\n\nfunction DEM = interpneighborpixels(DEM)\n\n%INTERPNEIGHBORPIXELS Interpolate pixels from their neighbor pixels\n%\n% Syntax\n%\n% DEMi = interpneighborpixels(DEM)\n%\n% Description\n%\n% INTERPNEIGHBORPIXELS uses distance weighted averages to calculate\n% missing values (nans) for pixels that border pixels with valid\n% values. \n%\n% Input arguments\n%\n% DEM GRIDobj\n%\n% Output arguments\n%\n% DEMi GRIDobj with\n%\n\n\nI = isnan(DEM.Z);\nsq2 = sqrt(2);\nw = 1./[sq2 1 sq2; ...\n 1 0 1; ...\n sq2 1 sq2];\nw = w(:);\n\nZ = nlfilter(DEM.Z,[3 3],@fun);\nDEM.Z = Z;\n\nfunction b = fun(a)\n\na = a(:); \nif ~isnan(a(5))\n b = a(5);\n return\nend\n\nI = isnan(a);\nif all(I)\n b = nan;\n return\nend\n\nI = ~I;\nb = sum(a(I).*(w(I)./sum(w(I))));\nend\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "gradient8.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/gradient8.m", "size": 3766, "source_encoding": "utf_8", "md5": "f749aa581aad377ab3f0fc89799f1c82", "text": "function G = gradient8(DEM,unit,varargin)\n\n%GRADIENT8 8-connected neighborhood gradient of a digital elevation model\n%\n% Syntax\n%\n% G = gradient8(DEM)\n% G = gradient8(DEM,unit)\n% G = gradient8(DEM,unit,pn,pv,...)\n%\n% Description\n%\n% gradient8 returns the numerical steepest downward gradient of a\n% digital elevation model using an 8-connected neighborhood. \n%\n% Input\n%\n% DEM digital elevation model (class: GRIDobj)\n% unit 'tan' --> tangent (default)\n% 'rad' --> radian\n% 'deg' --> degree\n% 'sin' --> sine\n% 'per' --> percent\n%\n% Parameter name value/pairs (pn,pv,...)\n% \n% 'useblockproc' true or {false}: use block processing \n% (see function blockproc)\n% 'useparallel' true or {false}: use parallel computing toolbox\n% 'blocksize' blocksize for blockproc (default: 5000)\n% \n% Output\n%\n% G gradient (class: GRIDobj)\n% \n% Example\n% \n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% G = gradient8(DEM,'degree');\n% subplot(2,1,1)\n% imagesc(DEM)\n% subplot(2,1,2)\n% imagesc(G)\n%\n%\n% See also: GRIDobj, GRIDobj/CURVATURE, GRIDobj/ASPECT, GRIDobj/arcslope\n% \n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 18. August, 2017\n\nif nargin == 1;\n unit = 'tangent';\nelse\n unit = validatestring(unit,{'tangent' 'degree' 'radian' 'percent' 'sine'},'gradient8','unit',2);\nend\n\np = inputParser;\np.FunctionName = 'GRIDobj/gradient8';\naddParamValue(p,'useblockproc',false,@(x) isscalar(x));\naddParamValue(p,'blocksize',5000,@(x) isscalar(x));\naddParamValue(p,'useparallel',false,@(x) isscalar(x));\nparse(p,varargin{:});\n\n\n% create a copy of the DEM instance\nG = DEM;\nc = class(DEM.Z);\nswitch c\n case 'double'\n G.Z = double.empty(0,0);\n otherwise\n G.Z = single.empty(0,0);\n c = 'single';\nend\n\n% I found Large matrix support using blockproc inefficient for gradient8.\n% Matrix dimensions have thus been increased to an out-of-range value to\n% avoid calling blockproc.\n% Large matrix support. Break calculations in chunks using blockproc.\n\nif p.Results.useblockproc\n blksiz = bestblk(size(DEM.Z),p.Results.blocksize);\n c = class(DEM.Z);\n \n switch c\n case {'double', 'single'}\n padval = inf;\n case 'logical'\n padval = true;\n otherwise\n padval = intmax(c);\n end\n cs = G.cellsize;\n fun = @(x) steepestgradient(x,cs,c);\n G.Z = blockproc(DEM.Z,blksiz,fun,...\n 'BorderSize',[1 1],...\n 'Padmethod',padval,...\n 'UseParallel',p.Results.useparallel);\nelse\n G.Z = steepestgradient(DEM.Z,G.cellsize,c);\nend\n\nG.name = 'gradient';\nG.zunit = unit;\n\nswitch unit\n case 'tangent'\n % do nothing\n case 'degree'\n G.Z = atand(G.Z);\n case 'radian'\n G.Z = atan(G.Z);\n case 'sine'\n G.Z = sin(atan(G.Z));\n case 'percent'\n G.Z = G.Z*100;\nend\nend\n\n\n\n\nfunction G = steepestgradient(z,cellsize,c)\n\nif isstruct(z);\n z = z.data;\nend\n \n\n% check for nans;\nI = isnan(z);\nflagnan = any(I(:));\nif flagnan\n z(I) = inf;\nend\n\nNEIGH = false(3);\n% calculate along orthogonal neighbors\nNEIGH(2,:) = true;\nNEIGH(:,2) = true;\n\nswitch c\n case 'double'\n G = (z-imerode(z,NEIGH))/cellsize;\n case 'single'\n G = single(z-imerode(z,NEIGH))/cellsize;\nend\n\n% calculate along diagonal neighbors\nNEIGH(:,:) = false;\nNEIGH([1 5 9 3 7]) = true;\n\nswitch c\n case 'double'\n G = max(G,(z-imerode(z,NEIGH))/norm([cellsize cellsize]));\n case 'single'\n G = max(G,single(z-imerode(z,NEIGH))/single(norm([cellsize cellsize])));\nend\n\nif flagnan\n G(I) = nan;\nend\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "acv.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/acv.m", "size": 2639, "source_encoding": "utf_8", "md5": "e7dab97e537450d261af006db317e472", "text": "function DEM = acv(DEM)\n\n%ACV Anisotropic coefficient of variation (ACV) \n%\n% Syntax\n%\n% C = acv(DEM)\n%\n% Description\n% \n% The anisotropic coefficient of variation describes the general\n% geometry of the local land surface and can be used to distinguish\n% elongated from oval landforms.\n%\n% Input\n%\n% DEM digital elevation model (GRIDobj)\n%\n% Output\n%\n% C Anisotropic coefficient of variation (ACV) (GRIDobj)\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% A = acv(DEM);\n% imageschs(DEM,A)\n%\n% References\n%\n% Olaya, V. 2009: Basic land-surface parameters. In: Geomorphometry. \n% Concepts, Software, Applications, Hengl, T. & Reuter, H. I. (Eds.),\n% Elsevier, 33, 141-169.\n% \n% See also: CONV2, FILTER2, BWDIST\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 17. August, 2017\n\nDEM.Z = acvfun(DEM.Z);\nDEM.name = 'ACV';\n\n\n\n%% %%%%%%%%%%%%%%%%%%%%%%%\n% subfunction\nfunction C = acvfun(dem)\nsiz = size(dem);\n\ndem = padarray(dem,[2 2],nan);\ninanpad = isnan(dem);\n[~,L] = bwdist(~inanpad);\ndem = dem(L);\n\n\nk = [ 1 0 1 0 1; ...\n 0 0 0 0 0; ...\n 1 0 0 0 -1; ...\n 0 0 0 0 0; ...\n -1 0 -1 0 -1];\n \ndz_AVG = conv2(dem,k,'valid')/4;\n\nF = { [ 0 0 0 0 0; ...\n 0 0 0 0 0; ...\n 1 0 0 0 -1; ...\n 0 0 0 0 0; ...\n 0 0 0 0 0];...\n ...\n [ 1 0 0 0 0; ...\n 0 0 0 0 0; ...\n 0 0 0 0 0; ...\n 0 0 0 0 0; ...\n 0 0 0 0 -1];\n ...\n [ 0 0 -1 0 0; ...\n 0 0 0 0 0; ...\n 0 0 0 0 0; ...\n 0 0 0 0 0; ...\n 0 0 -1 0 0];\n ...\n [ 0 0 0 0 -1; ...\n 0 0 0 0 0; ...\n 0 0 0 0 0; ...\n 0 0 0 0 0; ...\n 1 0 0 0 0];...\n };\n \nACV = zeros(siz);\n \nfor r = 1:4;\n ACV = ACV + (conv2(dem,F{r},'valid') - dz_AVG).^2;\nend\n\ndem = dem(2:end-1,2:end-1);\n\nF = { [ 0 0 0;...\n 1 0 -1;...\n 0 0 0];...\n ...\n [ 1 0 0;...\n 0 0 0;...\n 0 0 -1];...\n ...\n [ 0 1 0;...\n 0 0 0;...\n 0 -1 0];...\n ...\n [ 0 0 1;...\n 0 0 0;...\n -1 0 0];...\n };\n\nfor r = 1:4;\n ACV = ACV + (conv2(dem,F{r},'valid') - dz_AVG).^2;\nend\n\ndz_AVG = max(abs(dz_AVG),0.001);\n\nC = log(1 + sqrt(ACV./8)./dz_AVG);\n \n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "curvature.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/curvature.m", "size": 5257, "source_encoding": "utf_8", "md5": "1ebd8990d90725b19fea8704f28e916c", "text": "function C = curvature(DEM,ctype,varargin)\n\n%CURVATURE 8-connected neighborhood curvature of a digital elevation model \n%\n% Syntax\n%\n% C = curvature(DEM)\n% C = curvature(DEM,type)\n% C = curvature(DEM,type,pn,pv,...)\n%\n% Description\n% \n% curvature returns the second numerical derivative (curvature) of a\n% digital elevation model. By default, curvature returns the profile\n% curvature (profc). \n%\n% Input arguments\n%\n% DEM digital elevation model (GRIDobj)\n% type 'profc' (default) : profile curvature [m^(-1)]\n% 'planc' : planform curvature or contour curvature [m^(-1)]\n% 'tangc' : tangential curvature [m^(-1)]\n% 'meanc' : mean curvature [m^(-1)]\n% 'total' : total curvature [m^(-2)]\n%\n% Parameter name value/pairs\n% \n% 'useblockproc' true or {false}: use block processing \n% (see function blockproc)\n% 'useparallel' true or {false}: use parallel computing toolbox\n% 'blocksize' blocksize for blockproc (default: 5000)\n% 'meanfilt' true or {false}: if true, preprocess DEM with \n% [3x3] mean filter. \n%\n% Output arguments\n%\n% C curvature (GRIDobj)\n%\n% Remarks\n% \n% Please note that curvature is not defined for cells with zero \n% gradient. Here, curvature is set to zero.\n%\n% All formulas are according to Schmidt et al. (2003) on page 800.\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% DEM = filter(DEM);\n% C = curvature(DEM,'planc');\n% imageschs(DEM,C,'percentclip',0.1)\n%\n% Reference\n%\n% Schmidt, J., Evans, I.S., Brinkmann, J., 2003. Comparison of\n% polynomial models for land surface curvature calculation.\n% International Journal of Geographical Information Science 17,\n% 797-814. doi:10.1080/13658810310001596058\n%\n% See also: GRIDobj/gradient8\n% \n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 17. August, 2017\n\n\n% check input arguments\nnarginchk(1,inf);\nif nargin == 1\n ctype = 'profc';\nelse\n ctype = validatestring(ctype,{'profc','planc','tangc','meanc','total'});\nend\n\np = inputParser;\np.FunctionName = 'GRIDobj/curvature';\naddParamValue(p,'useblockproc',false,@(x) isscalar(x));\naddParamValue(p,'blocksize',5000,@(x) isscalar(x));\naddParamValue(p,'useparallel',false,@(x) isscalar(x));\naddParamValue(p,'meanfilt',false,@(x) isscalar(x));\nparse(p,varargin{:});\n\nif p.Results.meanfilt\n DEM = filter(DEM);\nend\n\n% create a copy of the DEM instance\nC = DEM;\nc = class(DEM.Z);\nswitch c\n case 'double'\n C.Z = double.empty(0,0);\n otherwise\n C.Z = single.empty(0,0);\nend\n\n% Large matrix support. Break calculations in chunks using blockproc\n% Parallisation for large grids using blockproc does in my experience with\n% four cores hardly increase the speed. \nif p.Results.useblockproc\n blksiz = bestblk(size(DEM.Z),p.Results.blocksize); \n cs = C.cellsize;\n fun = @(x) curvaturesub(x,cs,ctype); \n C.Z = blockproc(DEM.Z,blksiz,fun,...\n 'BorderSize',[1 1],...\n 'Padmethod','symmetric',...\n 'UseParallel',p.Results.useparallel);\nelse\n C.Z = curvaturesub(DEM.Z,C.cellsize,ctype);\nend\n\nC.name = ctype;\n\nend\n% subfunction\n\nfunction curv = curvaturesub(dem,cs,ctype)\n\nif isstruct(dem)\n dem = dem.data;\n % DEM has already been padded\n correctedges = false;\n shape = 'same';\nelse\n correctedges = true;\n shape = 'valid';\nend\n\nif correctedges\n dem = padarray(dem,[1 1],'symmetric');\nend\n\n% First-order partial derivatives:\n% kernel for dz/dx\nkernel = [-1 0 1; -1 0 1; -1 0 1]./(6*cs);\nfx = conv2(dem,kernel,shape);\n% kernel for dz/dy\nkernel = [1 1 1; 0 0 0; -1 -1 -1]./(6*cs);\nfy = conv2(dem,kernel,shape);\n\n% Second order derivatives according to Evans method (see Olaya 2009)\n%\n% z1 z2 z3\n% z4 z5 z6\n% z7 z8 z9\n\n% kernel for d2z/dx2\nkernel = [1 -2 1; 1 -2 1; 1 -2 1]./(3*cs.^2);\nfxx = conv2(dem,kernel,shape);\n% kernel for d2z/dy2\nkernel = kernel';\nfyy = conv2(dem,kernel,shape);\n% kernel for d2z/dxy\nkernel = [-1 0 1; 0 0 0; 1 0 -1]./(4*cs.^2);\nfxy = conv2(dem,kernel,shape);\n\n\n%% Other options to calculate Second-order partial derivatives:\n% r = gradient(p,cs);\n% t = gradient(q',cs)';\n% % Second-order mixed partial derivative:\n% s = gradient(p',cs)';\n\n\nswitch ctype\n case 'profc'\n curv = - (fx.^2 .* fxx + 2*fx.*fy.*fxy + fy.^2.*fyy)./((fx.^2 + fy.^2).*(1 + fx.^2 + fy.^2).^(3/2));\n case 'tangc'\n curv = - (fy.^2 .* fxx - 2*fx.*fy.*fxy + fx.^2.*fyy)./((fx.^2 + fy.^2).*(1 + fx.^2 + fy.^2).^(1/2));\n case 'planc'\n curv = - (fy.^2 .* fxx - 2*fx.*fy.*fxy + fx.^2.*fyy)./((fx.^2 + fy.^2).^(3/2));\n case 'meanc'\n curv = - ((1+fy.^2).*fxx - 2.*fxy.*fx.*fy + (1+fx.^2).*fyy)./ ...\n (2.* (fx.^2+fy.^2+1).^(3/2));\n% curv = (fx.^2 .* fxx + 2*fx.*fy.*fxy + fy.^2.*fyy)./((fx.^2 + fy.^2).*(1 + fx.^2 + fy.^2)) ...\n% - ((1+fy).^2 .* fxx + 2*fx.*fy.*fxy + (1+fx).^2.*fyy)./(2.*(1 + fx.^2 + fy.^2).^(3/2));\n case 'total'\n curv = fxx.^2 + 2*fxy.^2+fyy.^2;\nend\n\nif correctedges\n dem = dem(2:end-1,2:end-1);\nend\ncurv(isinf(curv) | isnan(curv)) = 0;\ncurv(isnan(dem)) = nan;\ncurv = reshape(curv,size(dem));\n\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "dist2line.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/dist2line.m", "size": 2592, "source_encoding": "utf_8", "md5": "66b36b67a419b02a052eaa562c892eff", "text": "function [D] = dist2line(DEM,x0,y0,alpha)\n%DIST2LINE labels pixels in a GRIDobj by their distance to a straight line\n%\n% Syntax\n% D = dist2line(DEM,x0,y0,alpha)\n%\n% Description\n%\n% dist2line(DEM,x0,y0,alpha) computes the orthogonal distance of each \n% pixel in a GRIDobj to a line that goes through the point(s) at \n% (x0,y0) and has an angle alpha from north (or the y-axis). Distances\n% are computed using the function 'distancePointLine' by David Legland,\n% which is part of the geom2d library, available at Matlab Central file\n% exchange. The function is included here.\n%\n% Input\n%\n% DEM GRIDobj\n% x0 x coordinate of point (scalar)\n% y0 y coordinate of point (scalar)\n% alpha angle in degrees from north, clockwise (scalar)\n%\n% Output\n%\n% D GRIDobj\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% [x,y] = getcoordinates(DEM);\n% D = dist2line(DEM,mean(x),mean(y),45);\n% imagesc(D), colorbar\n%\n% See also: GRIDobj\n%\n% Author: Dirk Scherler (scherler[at]gfz-potsdam.de)\n% Date: 25. June, 2014, updated 30. March, 2017;\n\n[x,y] = getcoordinates(DEM);\n[X,Y] = meshgrid(x,y);\nx = X(:);\ny = Y(:);\n\nD = DEM;\nD.Z(:) = 0;\n\n% Create line \ndx = 1;\ndy = dx/tand(alpha);\nLINE = [x0 y0 dx dy];\n\nD.Z(:) = distancePointLine([x,y],LINE);\n\nend\n\n\nfunction dist = distancePointLine(point, line)\n%DISTANCEPOINTLINE Minimum distance between a point and a line\n%\n% D = distancePointLine(POINT, LINE)\n% Return the euclidean distance between line LINE and point POINT. \n%\n% LINE has the form : [x0 y0 dx dy], and POINT is [x y].\n%\n% If LINE is N-by-4 array, result is N-by-1 array computes for each line.\n%\n% If POINT is N-by-2, then result is computed for each point.\n%\n% If both POINT and LINE are array, result is N-by-1, computed for each\n% corresponding point and line.\n%\n%\n% See also:\n% lines2d, points2d, distancePoints, distancePointEdge\n%\n% \n% ---------\n% author : David Legland \n% INRA - CEPIA URPOI - MIA MathCell\n% created the 24/06/2005\n%\n\n% HISTORY :\n\n\nif size(line, 1)==1 && size(point, 1)>1\n line = repmat(line, [size(point, 1) 1]);\nend\n\nif size(point, 1)==1 && size(line, 1)>1\n point = repmat(point, [size(line, 1) 1]);\nend\n\ndx = line(:, 3);\ndy = line(:, 4);\n\n% compute position of points projected on line\ntp = ((point(:, 2) - line(:, 2)).*dy + (point(:, 1) - line(:, 1)).*dx) ./ (dx.*dx+dy.*dy);\np0 = line(:, 1:2) + [tp tp].*[dx dy];\n\n\n% compute distances between points and their projections\ndx = point - p0;\ndist = sqrt(sum(dx.*dx, 2));\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "hillshade.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/hillshade.m", "size": 4823, "source_encoding": "utf_8", "md5": "717524829e593728e878154bb56ea185", "text": "function OUT2 = hillshade(DEM,varargin)\n\n%HILLSHADE create hillshading from a digital elevation model (GRIDobj)\n%\n% Syntax\n% \n% H = hillshade(DEM)\n% H = hillshade(DEM,'pn','pv',...)\n%\n% Description\n%\n% Hillshading is a very powerful tool for relief depiction.\n% hillshade calculates a shaded relief for a digital elevation model \n% based on the angle between the surface and the incoming light beams.\n% If no output arguments are defined, the hillshade matrix will be\n% plotted with a gray colormap. The hillshading algorithm follows the\n% logarithmic approach to shaded relief representation of Katzil and\n% Doytsher (2003).\n%\n% Input\n%\n% DEM Digital elevation model (class: GRIDobj)\n%\n% Parameter name/value pairs\n%\n% 'azimuth' azimuth angle, (default=315)\n% 'altitude' altitude angle, (default=60)\n% 'exaggerate' elevation exaggeration (default=1). Increase to\n% pronounce elevation differences in flat terrain\n% 'useblockproc' true or {false}: use block processing \n% (see function blockproc)\n% 'useparallel' true or {false}: use parallel computing toolbox\n% 'blocksize' blocksize for blockproc (default: 5000)\n% 'method' 'surfnorm' (default) or 'mdow'\n%\n%\n% Output\n%\n% H shaded relief (ranges between 0 and 1)\n%\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% hillshade(DEM)\n% \n% References\n%\n% Katzil, Y., Doytsher, Y. (2003): A logarithmic and sub-pixel approach\n% to shaded relief representation. Computers & Geosciences, 29,\n% 1137-1142.\n%\n% See also: SURFNORM, IMAGESCHS\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 18. August, 2017\n\n\n\n% Parse inputs\np = inputParser;\np.StructExpand = true;\np.KeepUnmatched = false;\np.FunctionName = 'hillshade'; \naddParamValue(p,'azimuth',315,@(x) isscalar(x) && x>= 0 && x<=360);\naddParamValue(p,'altitude',60,@(x) isscalar(x) && x>= 0 && x<=90);\naddParamValue(p,'exaggerate',1,@(x) isscalar(x) && x>0);\naddParamValue(p,'useparallel',true);\naddParamValue(p,'blocksize',2000);\naddParamValue(p,'useblockproc',true,@(x) isscalar(x));\naddParamValue(p,'method','default');\nparse(p,varargin{:});\n\nOUT = DEM;\nOUT.Z = [];\n\ncs = DEM.cellsize;\nazimuth = p.Results.azimuth;\naltitude = p.Results.altitude;\nexaggerate = p.Results.exaggerate;\nmethod = validatestring(p.Results.method,{'default','surfnorm','mdow'});\n\n% Large matrix support. Break calculations in chunks using blockproc\nif numel(DEM.Z)>(10001*10001) && p.Results.useblockproc\n blksiz = bestblk(size(DEM.Z),p.Results.blocksize); \n padval = 'symmetric';\n Z = DEM.Z;\n % The anonymous function must be defined as a variable: see bug 1157095\n fun = @(x) hsfun(x,cs,azimuth,altitude,exaggerate,method);\n HS = blockproc(Z,blksiz,fun,...\n 'BorderSize',[1 1],...\n 'padmethod',padval,...\n 'UseParallel',p.Results.useparallel);\n OUT.Z = HS;\nelse\n OUT.Z = hsfun(DEM.Z,cs,azimuth,altitude,exaggerate,method);\nend\n\nOUT.name = 'hillshade';\nOUT.zunit = '';\n\nif nargout == 0\n OUT.Z = uint8(OUT.Z*255);\n imagesc(OUT);\n colormap(gray)\nelse\n OUT2 = OUT;\nend\n\nend\n%% Subfunction\nfunction H = hsfun(Z,cs,azimuth,altitude,exaggerate,method)\n\nif isstruct(Z)\n Z = Z.data; \nend\n\nswitch method\n case {'default','surfnorm'}\n\n % correct azimuth so that angles go clockwise from top\n azid = azimuth-90;\n \n % use radians\n altsource = altitude/180*pi;\n azisource = azid/180*pi;\n \n % calculate solar vector\n [sx,sy,sz] = sph2cart(azisource,altsource,1);\n \n % calculate surface normals\n [Nx,Ny,Nz] = surfnorm(Z/cs*exaggerate);\n \n % calculate cos(angle)\n % H = [Nx(:) Ny(:) Nz(:)]*[sx;sy;sz];\n % % reshape\n % H = reshape(H,size(Nx));\n \n H = Nx*sx + Ny*sy + Nz*sz;\n \n % % usual GIS approach\n % H = acos(H);\n % % force H to range between 0 and 1\n % H = H-min(H(:));\n % H = H/max(H(:));\n\n case 'mdow'\n\n \n % correct azimuth so that angles go clockwise from top\n azid = [360 315 225 270] - 90;\n azisource = azid/180*pi;\n \n altsource = 30/180*pi;\n altsource = repmat(altsource,size(azisource));\n \n % calculate solar vector\n [sx,sy,sz] = sph2cart(azisource,altsource,1);\n \n % calculate surface normals\n [Nx,Ny,Nz] = surfnorm(Z/cs*exaggerate);\n \n \n H = bsxfun(@times,Nx(:),sx) + bsxfun(@times,Ny(:),sy) + bsxfun(@times,Nz(:),sz);\n H = max(H,0);\n H = sum(H,2)./3;\n H = reshape(H,size(Z));\nend\n\n\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "GRIDobj2polygon.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/GRIDobj2polygon.m", "size": 7552, "source_encoding": "utf_8", "md5": "2ecdf8e4bbde4f680c75082f2320b19b", "text": "function [MS,x,y] = GRIDobj2polygon(DB,varargin)\n\n%GRIDobj2polygon Conversion from drainage basin grid to polygon or polyline\n%\n% Syntax\n%\n% MS = GRIDobj2polygon(DB)\n% MS = GRIDobj2polygon(DB,pn,pv,...)\n% [MS,x,y] = ...\n%\n% Description\n%\n% GRIDobj2polygon converts a GRIDobj (label grid) to a mapstruct\n% that contains individual basins (or regions) as polygon or polyline\n% features. The polygone outlines or polylines run along pixel edges\n% and not pixel centers which differs from other Matlab functions to \n% derive outlines (e.g. bwboundaries, bwperim, bwtraceboundary).\n%\n% DB should be a grid of integers. Regions are those that have values\n% unequal to zero. If DB is a floating grid (single or double), then\n% GRIDobj2polygon finds unique values but discards NaNs and zero\n% values. In this case, GRIDobj2polygon returns MS with an additional\n% field 'gridval' that indicates the original value of the grid in each\n% region.\n%\n% Input arguments\n%\n% DB GRIDobj with drainage basins \n% \n% Parameter name/value pairs\n%\n% simplify true or {false}. Douglas-Peuker simplification. Note\n% that for tol>0 (see tol parameter) adjacent polygons\n% may overlap. Note that using no simplification may\n% result in many nodes for each polygon. Use tolerance of\n% zero if you wish that the shape is unchanged but\n% redundant nodes are dismissed. \n% tol tolerance for line simplification. Zero tolerance\n% reduces the number of nodes but leaves the geometry \n% unchanged. Values between 0.5 and 2 will lead to\n% simplier shapes but usually destroy the spatial \n% topology of neighboring polygons.\n% minarea scalar indicating the minimum number of pixels\n% for a drainage basins to be included in the output.\n% geometry 'Polygon' or 'PolyLine' (or 'Line')\n% multipart true or {false}. Enables multipart features.\n% holes true or {false}. Enables holes. Multipart must be set\n% to true to enable features with holes. Note that holes\n% are currently not supported well by the algorithm.\n% waitbar true or {false}. True will show a waitbar.\n%\n% Output arguments\n%\n% MS mapstruct with polygons or polylines\n% x,y nan-separated list of coordinate vectors\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% D = drainagebasins(FD);\n% [MS,x,y] = GRIDobj2polygon(D,'Geometry','Line','simplify',true,'tol',0);\n% imageschs(DEM,DEM,'colormap','landcolor')\n% hold on\n% plot(x,y,'-r')\n%\n% See also: bwboundaries, bwtraceboundary, regionprops\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 14. June, 2022\n\n\n\n% check input arguments\nnarginchk(1,inf)\np = inputParser;\np.FunctionName = 'GRIDobj/GRIDobj2polygon';\nvalidgeoms = {'Polygon','PolyLine','Line'};\naddRequired(p,'DB');\naddParamValue(p,'simplify',false, @(x) isscalar(x));\naddParamValue(p,'tol',0, @(x) isnumeric(x) && isscalar(x) && x>=0);\naddParamValue(p,'minarea',0, @(x) isnumeric(x) && isscalar(x) && x>=0);\naddParamValue(p,'geometry','Polygon',@(x) ischar(validatestring(x,validgeoms)));\naddParamValue(p,'multipart',false,@(x) isscalar(x));\naddParamValue(p,'holes',false,@(x) isscalar(x));\naddParamValue(p,'waitbar',false,@(x) isscalar(x));\nparse(p,DB,varargin{:});\n\n% read parsed arguments\nsimp = logical(p.Results.simplify);\ntol = p.Results.tol;\nminarea = p.Results.minarea;\ngeom = validatestring(p.Results.geometry,validgeoms);\nmp = p.Results.multipart;\nholes = p.Results.holes;\nwaitb = p.Results.waitbar;\n\n% check underlying class of the grid\nif isfloat(DB.Z)\n writevalue = true;\n DB2 = GRIDobj(DB,'uint32');\n I = ~(isnan(DB.Z) | DB.Z == 0);\n [uniquevals,~,DB2.Z(I)] = unique(DB.Z(I));\n DB = DB2;\nelse\n writevalue = false;\nend\n\n% identify regions and number of regions\nif islogical(DB.Z)\n STATS = regionprops(DB.Z,'Area','PixelIdxList');\nelse\n STATS = regionprops(uint32(DB.Z),'Area','PixelIdxList');\nend\nndb = numel(STATS); \n\n% go through all regions\nif waitb; h = waitbar(0,'please wait'); end\n \ncounter = 0;\nfor r = 1:ndb;\n % show waitbar\n if waitb; waitbar(r/ndb,h); end\n \n % check if Area is larger than minimum area\n if STATS(r).Area <= minarea;\n continue\n else\n counter = counter+1;\n end\n \n % get subscripts of basin\n [row,col] = ind2sub(DB.size,STATS(r).PixelIdxList);\n % bw2poly returns the coordinates of the boundary\n C = bw2poly([row col],mp,holes);\n \n % simplify line if wanted\n if simp\n if tol>0\n C = cellfun(@(x) dpsimplify(x,tol),C,'UniformOutput',false);\n else\n C = cellfun(@(x) simplify(x),C,'UniformOutput',false);\n end\n end\n \n % add nans at the end of coordinate vectors\n if numel(C)>1\n C = cellfun(@(x) [x;[nan nan]],C,'UniformOutput',false);\n end\n C = cell2mat(C);\n \n % write data to mapstruct\n MS(counter).Geometry = geom;\n [x,y] = sub2coord(DB,C(:,1),C(:,2));\n MS(counter).X = x;\n MS(counter).Y = y;\n MS(counter).ID = double(DB.Z(STATS(r).PixelIdxList(1)));\n \n if writevalue\n MS(counter).gridval = double(uniquevals(r));\n end\n \nend\n\n% create coordinate vectors if more than one output\nif nargout > 1;\n for r=1:numel(MS);\n if ~isnan(MS(r).X(end))\n MS(r).X(end+1) = nan;\n MS(r).Y(end+1) = nan;\n end\n end\n \n x = {MS.X}';\n y = {MS.Y}';\n x = cell2mat(x);\n y = cell2mat(y);\nend\n\n% close waitbar\nif waitb; close(h); end\n\nend\n\n\nfunction C = bw2poly(BW,mp,holes)\n\nif islogical(BW);\n [r,c] = find(BW);\nelse\n r = BW(:,1);\n c = BW(:,2);\nend\n \nrc = bsxfun(@plus,r,[0 -.5 0 .5 .5 .5 0 -.5 -.5]);\ncc = bsxfun(@plus,c,[0 -.5 -.5 -.5 0 .5 .5 .5 0 ]);\nrc = rc(:);\ncc = cc(:);\n\nrc = rc*2;\ncc = cc*2;\n\n\nminrc = min(rc)-1;\nmaxrc = max(rc)-1;\nif mp\n mincc = min(cc)-1;\nelse\n [mincc,ix] = min(cc);\n mincc = mincc-1;\nend\nmaxcc = max(cc)-1;\n\nrc = rc-minrc;\ncc = cc-mincc;\n\nsiz = [maxrc-minrc+1 maxcc-mincc+1];\n\nIX = sub2ind(siz,rc,cc);\nB = false(siz);\nB(IX) = true;\n\nif mp \n if ~holes\n C = bwboundaries(B,4,'noholes');\n C = cellfun(@(x) modifynodelist(x),C,'UniformOutput',false);\n else\n [C,~,N] = bwboundaries(B,4,'holes');\n for iter2=1:numel(C);\n if iter2<=N\n C{iter2} = modifynodelist(C{iter2});\n else\n C{iter2} = bsxfun(@plus,C{iter2},[minrc mincc]);\n C{iter2} = C{iter2}/2;\n end\n end\n \n end\n C = C(:);\nelse\n C = bwtraceboundary(B,[rc(ix) cc(ix)],'S',4,inf,'counterclockwise');\n C = {modifynodelist(C)};\nend\n \n\n\nfunction nl = modifynodelist(nl)\n% modify node list so that only nodes remain on pixel corners \nnl(any(mod(nl,2)==0,2),:) = [];\nnl = bsxfun(@plus,nl,[minrc mincc]);\nnl = nl/2;\nend\nend\n\nfunction C = simplify(C)\n\n% reduce number of polygon or polyline vertices\n%\n% This function simplifies a polyline by removing vertices whose removal\n% doesn't affect the shape of the polyline. In order to work, the vertices\n% must be arranged on a rectangular grid with equal dx,dy spacing.\n\ndc = C-circshift(C,1);\nddc = dc-circshift(dc,-1);\nI = any(ddc,2);\n\nC = C(I,:);\n\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "GRIDobj2geotiff.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/GRIDobj2geotiff.m", "size": 3485, "source_encoding": "utf_8", "md5": "8ccb99afc25d3673f746f67381243357", "text": "function GRIDobj2geotiff(A,file)\n\n%GRIDobj2geotiff Exports an instance of GRIDobj to a geotiff file\n%\n% Syntax\n% \n% GRIDobj2geotiff(DEM)\n% GRIDobj2geotiff(DEM,filename)\n%\n% Description\n%\n% GeoTIFF is a common image file format that stores coordinates and\n% projection information to be read by most GIS software.\n% GRIDobj2geotiff writes an instance of GRIDobj to a GeoTIFF file. \n%\n% GRIDobj2geotiff requires the function geotiffwrite available with \n% the Mapping Toolbox. If geotiffwrite does not exist on the search\n% path, the function will write a standard tif together with a\n% '.tfw'-file (worldfile, http://en.wikipedia.org/wiki/World_file ) to\n% the disk. \n%\n% GRIDobj2geotiff(DEM) opens a dialogue box to save the GeoTIFF\n%\n% GRIDobj2geotiff(DEM,filename) saves the DEM to the specified \n% filename\n%\n% Input arguments\n%\n% DEM instance of GRIDobj\n% filename absolute or relative path and filename\n%\n% See also: GRIDobj\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 17. August, 2017\n\nnarginchk(1,2)\n\n% if only 1 argument, open file dialog box\nif nargin == 1\n [FileName,PathName] = uiputfile({'*.tif'});\n if FileName == 0\n disp(' no output written to disk')\n return\n end\n file = [PathName FileName];\nend\n\n% try to use geotiffwrite, which comes with the Mapping Toolbox\ntry\n if isempty(A.georef);\n geotiffwrite(file,A.Z,A.refmat);\n else\n geotiffwrite(file,A.Z,A.georef.SpatialRef,...\n 'GeoKeyDirectoryTag',A.georef.GeoKeyDirectoryTag);\n end\ncatch ME\n warning('TopoToolbox:GRIDobj',...\n ['GRIDobj2geotiff is unable to write a geotiff. Either you don''t \\n'...\n 'have the mapping toolbox, or there was another issue with geotiffwrite. \\n'...\n 'GRIDobj2geotiff instead writes a tif-image together with a world \\n'...\n 'file (*.tfw) which contains data on spatial referencing of the \\n' ...\n 'image, yet which lacks information on the type of projection used.']); \n \n \n % if geotiffwrite is not available or any other error occurs\n % a tif file will be written to the disk together with a worldfile\n % .tfw-file.\n [pathstr, name, ~] = fileparts(file);\n k = refmat2worldfile(A.refmat);\n dlmwrite(fullfile(pathstr,[name '.tfw']),k,'precision', '%.10f');\n A = A.Z;\n \n \n siz = size(A);\n cla = class(A);\n \n switch cla;\n case 'double'\n BpS = 64;\n TSF = Tiff.SampleFormat.IEEEFP;\n case 'single'\n BpS = 32;\n TSF = Tiff.SampleFormat.IEEEFP;\n otherwise\n if islogical(A);\n A = uint32(A);\n cla = 'uint32';\n end\n BpS = round(log2(double(intmax(cla))));\n TSF = Tiff.SampleFormat.UInt;\n \n end\n \n t = Tiff(file,'w');\n tagstruct.ImageLength = siz(1);\n tagstruct.ImageWidth = siz(2);\n tagstruct.BitsPerSample = BpS;\n tagstruct.SampleFormat = TSF;\n tagstruct.SamplesPerPixel = 1;\n tagstruct.RowsPerStrip = 16;\n tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky;\n tagstruct.Software = 'MATLAB';\n tagstruct.Photometric = 0;\n \n t.setTag(tagstruct);\n t.write(A);\n t.close;\nend\n\nend\n\nfunction k = refmat2worldfile(r)\n% does not support rotation\n\nk(1,1) = r(2,1);\nk(4,1) = r(1,2);\nk(5,1) = r(3,1)+k(1);\nk(6,1) = r(3,2)+k(4);\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "reclassify.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/reclassify.m", "size": 8418, "source_encoding": "utf_8", "md5": "5c51382b064b1b7f66f23e7b2b8a582b", "text": "function DEM = reclassify(DEM,varargin)\n\n%RECLASSIFY generate univariate class intervals for an instance of GRIDobj\n%\n% Syntax\n%\n% C = reclassify(DEM);\n% C = reclassify(DEM,'method',value)\n%\n% Description\n%\n% reclassify bins continous values of an instance of GRIDobj by setting\n% class intervals based on different classification methods. The\n% default method is equal interval classification with 10 classes.\n%\n% Input Arguments\n%\n% DEM Grid (class = GRIDobj)\n% \n% 'Methods' and [values]\n%\n% 'equalintervals' [number of classes]\n% 'definedintervals' [vector of class breaks]\n% 'equalquantiles' [number of classes]\n% 'definedquantiles' [vector of quantiles] \n% e.g. [0.1 0.9] results in three classes \n% 'kmeans' [number of classes]\n% uses the k_means algorithm of Yi Cao\n% FEX submission 19344 included in this function\n% ! may take a while for large grids !\n% 'std' [s = scale of standard deviation, e.g. 2]\n% equal intervals with a width of std/s. Bins are\n% centered around sample mean\n% 'otsu' [number of classes, must be between 2 and 5] \n% \n%\n% Output argument\n%\n% C Classified grid (class = GRIDobj)\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% C = reclassify(DEM,'equalquantiles',10);\n% imageschs(DEM,C)\n%\n% See also: k_means, graythresh\n% \n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 28. March, 2023\n\nnarginchk(1,3)\n\nallowedmethods = {'equalintervals',...\n 'definedintervals',...\n 'definedquantiles',...\n 'equalquantiles',...\n 'kmeans',...\n 'standarddeviation',...\n 'std',...\n 'otsu'...\n };\n% nr of classes\nif nargin == 1\n method = 'equalinterval';\n num = 10;\nelse\n method = validatestring(varargin{1},allowedmethods);\n \n if nargin==3\n num = varargin{2};\n end\nend\n\nINAN = isnan(DEM.Z) | isinf(DEM.Z);\nDEM.Z(INAN) = nan;\ninan = any(INAN(:));\n\nswitch method\n case 'equalintervals'\n validateattributes(num,{'numeric'},{'scalar'});\n \n if inan\n DEM.Z(~INAN) = mat2gray(DEM.Z(~INAN));\n DEM.Z = grayslice(DEM.Z,num);\n if num == 256;\n DEM.Z = double(DEM.Z) + 1;\n DEM.Z(INAN) = nan;\n elseif num < 256;\n DEM.Z = DEM.Z + 1;\n DEM.Z(INAN) = 0;\n else\n DEM.Z(INAN) = nan;\n end\n \n else\n DEM.Z = mat2gray(DEM.Z);\n DEM.Z = grayslice(DEM.Z,num);\n \n if num <= 255\n DEM.Z = DEM.Z + 1;\n elseif num == 256\n DEM.Z = double(DEM.Z) + 1;\n end\n end\n case 'definedintervals'\n validateattributes(num,{'numeric'},{'vector'});\n num(end+1) = inf;\n num = [-inf; num(:)];\n siz = size(DEM.Z);\n [~,DEM.Z] = histc(DEM.Z(:),num);\n DEM.Z = reshape(DEM.Z,siz);\n case 'equalquantiles'\n validateattributes(num,{'numeric'},{'scalar','integer','>',1});\n z = DEM.Z(~INAN);\n z = z(:);\n z = sort(z,'ascend');\n q = (1:num)/num;\n q = ceil(q*numel(z));\n edges = z(q);\n edges(end) = inf;\n [~,DEM.Z] = histc(DEM.Z(:),[-inf; edges]);\n DEM.Z = reshape(DEM.Z,DEM.size);\n DEM.Z(INAN) = nan;\n case 'definedquantiles'\n validateattributes(num,{'numeric'},{'vector','>',0,'<=',1});\n p = num(:);\n if p(end) < 1\n p(end+1) = 1;\n end\n \n z = DEM.Z(~INAN);\n z = z(:);\n n = numel(z);\n edges = interp1((0:n-1).'/(n-1), sort(z), p);\n \n edges(end) = inf;\n [~,DEM.Z] = histc(DEM.Z(:),[-inf; edges]);\n DEM.Z = reshape(DEM.Z,DEM.size);\n DEM.Z(INAN) = nan;\n \n case {'standarddeviation','std'}\n validateattributes(num,{'numeric'},{'vector','>',0,'<=',1});\n z = DEM.Z(~INAN);\n z = z(:);\n s = std(z(:));\n s = s*num;\n mz = mean(z);\n minz = min(z);\n maxz = max(z);\n \n edges1 = mz-s/2 :-s: minz;\n if edges1(end) > minz\n edges1(end+1) = -inf;\n else\n edges1(end) = -inf;\n end\n edges2 = mz+s/2 :s: maxz;\n \n edges2(end) = inf;\n \n [~,DEM.Z] = histc(DEM.Z(:),[edges1(end:-1:1) edges2]);\n DEM.Z = reshape(DEM.Z,DEM.size);\n DEM.Z(INAN) = nan;\n \n case 'kmeans'\n \n validateattributes(num,{'numeric'},{'scalar','integer','>',1});\n z = DEM.Z(~INAN);\n z = z(:);\n \n IX = k_means(z,num);\n \n DEM.Z(:,:) = nan;\n DEM.Z(~INAN) = IX;\n case 'otsu' \n validateattributes(num,{'numeric'},{'scalar','integer','>',1});\n \n z = DEM.Z(~isnan(DEM.Z));\n z = z(:);\n [N,edges] = histcounts(z);\n zbins = edges(1:end-1) + (edges(2)-edges(1))/2;\n thresholds = multilevel_otsu(N,num,zbins);\n DEM = reclassify(DEM,'definedintervals',thresholds);\n % DEM.Z(INAN) = cast(otsu(z,num),class(DEM.Z));\nend\n\nend\n\n\n\n\n% subfunctions\n\nfunction [gIdx,c]=k_means(X,k)\n% K_MEANS k-means clustring\n% IDX = k_means(X, K) partititions the N x P data matrix X into K\n% clusters through a fully vectorized algorithm, where N is the number of\n% data points and P is the number of dimensions (variables). The\n% partition minimizes the sum of point-to-cluster-centroid Euclidean\n% distances of all clusters. The returned N x 1 vector IDX contains the\n% cluster indices of each point.\n%\n% IDX = k_means(X, C) works with the initial centroids, C, (K x P).\n%\n% [IDX, C] = k_means(X, K) also returns the K cluster centroid locations\n% in the K x P matrix, C.\n%\n% See also kmeans\n\n% Version 2.0, by Yi Cao at Cranfield University on 27 March 2008.\n\n% Example 1: small data set\n%{\nN=200;\nX = [randn(N,2)+ones(N,2); randn(N,2)-ones(N,2)];\n[cidx, ctrs] = k_means(X, 2);\nplot(X(cidx==1,1),X(cidx==1,2),'r.',X(cidx==2,1),X(cidx==2,2),'b.', ctrs(:,1),ctrs(:,2),'kx');\n%}\n\n% Example 2: large data set\n%{\nN=20000;\nX = [randn(N,2)+ones(N,2); randn(N,2)-ones(N,2)];\ntic\n[cidx, ctrs] = k_means(X, 2);\ntoc\nplot(X(cidx==1,1),X(cidx==1,2),'r.',X(cidx==2,1),X(cidx==2,2),'b.', ctrs(:,1),ctrs(:,2),'kx');\n%}\n\n% Example 3: large data set with 5 centroids \n%{\nN=20000;\nX = [randn(N,2)+ones(N,2); randn(N,2)-ones(N,2)];\ntic\n[cidx, ctrs] = k_means(X, 5);\ntoc\nplot(X(cidx==1,1),X(cidx==1,2),'.',...\nX(cidx==2,1),X(cidx==2,2),'.',...\nX(cidx==3,1),X(cidx==3,2),'.',...\nX(cidx==4,1),X(cidx==4,2),'.',...\nX(cidx==5,1),X(cidx==5,2),'.',...\nctrs(:,1),ctrs(:,2),'+','linewidth',2)\n%}\n\n% Example 4: Comparison with kmeans in Statistics Toolbox\n%{\nN=20000;\nX = [randn(N,2)+ones(N,2); randn(N,2)-ones(N,2)];\nrand('state',0);\ntic\ncidx = k_means(X, 20);\ntoc\n% Compare with kmeans in Statistis Toolbox\nrand('state',0);\ntic,\ncidx1 = kmeans(X, 20, 'Option', statset('MaxIter',200));\ntoc\n%}\n\n% Check input and output\nnarginchk(2,2);\n\n[n,m]=size(X);\n\n% Check if second input is centroids\nif ~isscalar(k)\n c=k;\n k=size(c,1);\nelse\n c=X(ceil(rand(k,1)*n),:);\nend\n\n% allocating variables\ng0=ones(n,1);\ngIdx=zeros(n,1);\nD=zeros(n,k);\n\n% Main loop converge if previous partition is the same as current\nwhile any(g0~=gIdx)\n% disp(sum(g0~=gIdx))\n g0=gIdx;\n % Loop for each centroid\n for t=1:k\n d=zeros(n,1);\n % Loop for each dimension\n for s=1:m\n d=d+(X(:,s)-c(t,s)).^2;\n end\n D(:,t)=d;\n end\n % Partition data to closest centroids\n [~,gIdx]=min(D,[],2);\n % Update centroids using means of partitions\n for t=1:k\n c(t,:)=mean(X(gIdx==t,:));\n end\n% for t=1:m\n% c(:,t)=accumarray(gIdx,X(:,t),[],@mean);\n% end\nend\n\nend\n\n\nfunction ix = otsu(x,n)\n\nif mod(n,2)~=0\n error('number of classes is odd');\nend\n\nI = x >= graythresh(x);\nix = I*n/2;% + 1;\n% do until all classes are \nif n > 2\nix(I) = otsu(x(I),n/2) + ix(I); \nix(~I) = otsu(x(~I),n/2) + ix(~I);\nelse\n ix = ix+1;\n \nend\n\nend\n\n\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "polygon2GRIDobj.m", "ext": ".m", "path": "topotoolbox-master/@GRIDobj/polygon2GRIDobj.m", "size": 6658, "source_encoding": "utf_8", "md5": "966dfbe54ab8836d023cd3326ee7daf2", "text": "function P = polygon2GRIDobj(DEM,MS,varargin)\n\n%POLYGON2GRIDobj convert polygon to a grid\n%\n% Syntax\n%\n% P = polygon2GRIDobj(DEM,MS)\n% P = polygon2GRIDobj(DEM,MS,field)\n% P = polygon2GRIDobj(DEM,MS,'pn',pv)\n%\n% Description\n%\n% polygon2GRIDobj maps polygons in the mapping structure MS to a \n% GRIDobj with the same extent and resolution as the GRIDobj DEM.\n%\n% Note that polygon2GRIDobj uses polyshape methods that have been\n% released with MATLAB 2017b. The function runs for older versions,\n% too, but may return different results if polygons in MS extend beyond\n% the boundaries of DEM and contain holes.\n% \n% Input arguments\n%\n% DEM grid \n% MS mapstruct of a polyline as imported by shaperead. Must have\n% the fields X and Y.\n% field field name of the numeric data to be mapped. If not\n% provided, polygon2GRIDobj will map logical values.\n%\n% Parameter name/value pairs\n%\n% 'field' field name of the numeric data to be mapped. If empty (the\n% default), polygon2GRIDobj will map logical values. \n% 'waitbar' {true} or false. false will suppress a waitbar.\n%\n% Output arguments\n%\n% P grid (GRIDobj). Grid has the same extent and cellsize\n% as DEM.\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','carve');\n% D = drainagebasins(FD);\n% MS = GRIDobj2polygon(D);\n% P = polygon2GRIDobj(D,MS,'ID');\n%\n%\n% Note: This function has not yet been fully tested. Please report bugs.\n%\n%\n% See also: GRIDobj/coord2ind, GRIDobj/sub2coord, GRIDobj/getcoordinates,\n% GRIDobj/createmask, line2GRIDobj, GRIDobj2polygon\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 22. September, 2022\n\n\n% 2 or 3 input arguments?\nnarginchk(2,inf)\n\nif nargin == 2\n\n P = GRIDobj(DEM,'logical');\n writelogical = true;\n writeclass = @logical;\n waitb = true;\n\nelseif nargin > 2\n if nargin == 3\n field = varargin{1};\n waitb = true;\n else\n % Use input parser\n p = inputParser;\n p.FunctionName = 'polygon2GRIDobj';\n addParameter(p,'field','',@(x) isfield(MS,x) || isempty(x))\n addParameter(p,'waitbar',true)\n parse(p,varargin{:})\n\n field = p.Results.field;\n waitb = p.Results.waitbar;\n end\n\n if isempty(field)\n\n P = GRIDobj(DEM,'logical');\n writelogical = true;\n writeclass = @logical;\n \n else\n\n % check the class of the field\n cl = class(MS(1).(field));\n P = GRIDobj(DEM,cl);\n\n writelogical = false;\n switch cl\n case {'double','single'}\n % If double or single, start out with all values in the raster\n % set to nan\n P = P*nan(1,cl);\n case 'logical'\n % If logical, then all pixels are false\n writelogical = true;\n end\n writeclass = @(x) cast(x,cl);\n end\n\nend\n\n% get DEM coordinates\n[X,Y] = getcoordinates(DEM);\nsiz = DEM.size;\n\nIX_hole = [];\n\n%which matlab version do we have. If MATLAB 9,3\nif ~verLessThan('matlab','9.3')\n [xx,yy] = getoutline(DEM);\n poutline = polyshape(xx,yy);\n poutline = polybuffer(poutline,DEM.cellsize/4);\n warning off\n for r = 1:numel(MS)\n \n psh = polyshape(MS(r).X,MS(r).Y);\n psh = intersect(psh,poutline);\n \n if isempty(psh.Vertices)\n % The feature is completely outside the DEM boundaries\n MS(r).X = [];\n MS(r).Y = [];\n continue\n end\n \n pshhole = holes(psh);\n psh = rmholes(psh);\n % Are the polygons multipart?\n psh = regions(psh);\n \n % loop through regions\n for r2 = 1:numel(psh)\n if r2 == 1\n nrnew = r;\n else\n nrnew = numel(MS);\n nrnew = nrnew + 1;\n end\n xy = psh(r2).Vertices;\n MS(nrnew).X = xy(:,1);\n MS(nrnew).Y = xy(:,2);\n \n if ~writelogical\n MS(nrnew).(field) = MS(r).(field);\n end\n end\n \n % then loop through holes\n for r2 = 1:numel(pshhole)\n xy = pshhole(r2).Vertices;\n nrnew = numel(MS);\n nrnew = nrnew + 1;\n MS(nrnew).X = xy(:,1);\n MS(nrnew).Y = xy(:,2);\n IX_hole = [IX_hole nrnew]; %#ok\n\n end \n end\n warning on\nelse\n IX_hole = [];\nend\n\nis_hole = false(size(MS));\nis_hole(IX_hole) = true;\n\n% loop through features of mapping structure MS\nif waitb\n h = waitbar(0);\nend\n\nfor r = 1:numel(MS)\n\n if waitb\n waitbar(r/numel(MS),h,...\n ['Please wait (' num2str(r) '/' num2str(numel(MS)) ')']);\n end\n \n % get coordinates\n x = MS(r).X;\n y = MS(r).Y;\n \n if isempty(x)\n continue\n end\n \n I = isnan(x) | isnan(y);\n x(I) = [];\n y(I) = [];\n \n \n % if the value of that attribute should be written to the grid, this\n % value is extracted here.\n if ~writelogical\n \n if ~is_hole(r)\n val = single([MS(r).(field)]);\n else\n val = single(0);\n end\n else\n if is_hole(r) \n val = false;\n else\n val = true;\n end\n \n end\n \n % convert coordinates to rows and columns\n [row,col] = coord2pixel(x,y,X,Y);\n % and extract a subset of the image and apply poly2mask to that subset.\n % That is much faster than calling poly2mask for the whole image\n [BW,ext] = getmask(row,col,siz);\n % Then, write that data back to the main grid P\n FillMat = P.Z(ext(1):ext(2),ext(3):ext(4)); \n FillMat(BW) = writeclass(val);\n \n P.Z(ext(1):ext(2),ext(3):ext(4)) = FillMat;\n\nend\n\n% Close waitbar\nif waitb\n close(h)\nend\nend\n\nfunction [BW,ext] = getmask(r,c,siz)\next = getextent(r,c);\next = [max(floor(ext(1)),1) min(ceil(ext(2)),siz(1)) ...\n max(floor(ext(3)),1) min(ceil(ext(4)),siz(2))];\nsizcrop = [ext(2)-ext(1)+1 ext(4)-ext(3)+1];\nrcrop = r - ext(1) + 1;\nrcrop = max(rcrop,1);\nrcrop = min(rcrop,sizcrop(1));\n\nccrop = c - ext(3) + 1;\nccrop = max(ccrop,1);\nccrop = min(ccrop,sizcrop(2));\n\nBW = poly2mask(ccrop,rcrop,sizcrop(1),sizcrop(2));\nend\n \n \n \n\nfunction [r,c] = coord2pixel(x,y,X,Y)\n\n% force column vectors\nx = x(:);\ny = y(:);\n\ndx = X(2)-X(1);\ndy = Y(2)-Y(1);\n\nc = (x-X(1))./dx + 1;\nr = (y-Y(1))./dy + 1;\nend\n\n\nfunction ext = getextent(x,y)\n\next = [min(x) max(x) min(y) max(y)];\nend\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "idw.m", "ext": ".m", "path": "topotoolbox-master/@PPS/idw.m", "size": 3105, "source_encoding": "utf_8", "md5": "76959699a63701038e6ac2f02a7fe4c6", "text": "function c = idw(P,marks,varargin)\n\n%IDW Inverse distance weighted interpolation on stream networks\n%\n% Syntax\n%\n% c = idw(P,marks)\n% c = idw(P,marks,pn,pv,...)\n%\n% Description\n%\n% idw computes an inverse distance weighted interpolation on a stream\n% network. Distances are calculated as geodesic distances on the\n% network (see graph/distances).\n%\n% Note that idw is probably rarely a good choice as an interpolator on\n% a network. Better use STREAMobj/inpaintnans\n%\n% Input arguments\n%\n% P PPS object\n% marks point attributes\n% \n% Parameter name/value pairs\n%\n% 'beta' {2}. Exponent in the IDW equation\n% 'chunksize' Breaks computation into chunks so that the distance \n% matrix becomes not too large. A value of 1000 may be\n% appropriate.\n% 'extrap' {false} or true. Don't extrapolate using idw. Hence, by\n% default this option is set to false.\n%\n% Output arguments\n%\n% c node attribute list with interpolated values\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% S = STREAMobj(FD,'minarea',1000);\n% S = removeshortstreams(S,100);\n% S = clean(S);\n% P = PPS(S,'rpois',0.001,'z',DEM);\n% marks = rand(npoints(P),1);\n% c = idw(P,marks);\n% plot(P.S,'k');\n% hold on\n% plotc(P,c)\n% hold off\n% \n% See also: PPS, STREAMobj/inpaintnans, STREAMobj/crs, STREAMobj/smooth\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 11. March, 2020\n\ndistmatsize = 1000;\n\np = inputParser;\np.FunctionName = 'PPS/idw';\naddRequired(p,'P',@(x) isa(x,'PPS'));\naddRequired(p,'marks',@(x) numel(x) == npoints(P));\n\n% Add elevation\naddParameter(p,'beta',2,@(x) isscalar(x) && x > 0);\naddParameter(p,'chunksize',round(distmatsize/npoints(P)*distmatsize));\naddParameter(p,'extrap',false);\n\n% Parse\nparse(p,P,marks,varargin{:});\n\nbeta = p.Results.beta;\nchunksize = p.Results.chunksize;\nextrap = p.Results.extrap;\n\nc = getnal(P.S);\nc(:) = nan;\nc(P.PP) = marks;\n\n[CS,locb] = STREAMobj2cell(P.S);\n\n% if there is only one drainage basin\nif numel(CS) == 1\n c = networkidw(P.S,c,beta,chunksize);\nelse\n % if there are multiple drainage basins\n cc = cellfun(@(ix) c(ix),locb,'UniformOutput',false);\n for r = 1:numel(CS)\n cc{r} = networkidw(CS{r},cc{r},beta,chunksize);\n end\n \n % map back to actual nal\n for r = 1:numel(cc)\n c(locb{r}) = cc{r};\n end\nend\n\nif ~extrap\n I = isinf(netdist(P,'dir','up')) | isinf(netdist(P,'dir','down'));\n c(I) = nan;\nend\n \n\nend\n\nfunction c = networkidw(S,c,beta,chunksize)\nI = isnan(c);\ntn = find(I);\nsn = find(~I);\n\nif isempty(sn)\n c(:) = nan;\n return\nend\n\nd = S.distance;\nnode_distance = abs(d(S.ix)-d(S.ixc));\nG = graph(S.ix,S.ixc,node_distance);\n\nn = numel(tn);\nbins = ceil((1:n)'/chunksize);\nix = accumarray(bins,(1:numel(tn))',[],@(x) {tn(x)});\nfor r = 1:numel(ix)\n d = distances(G,sn,ix{r});\n d = d.^beta;\n w = 1./d;\n w = w./sum(w);\n c(ix{r}) = sum(c(sn).*w);\nend\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "plotdz.m", "ext": ".m", "path": "topotoolbox-master/@PPS/plotdz.m", "size": 4600, "source_encoding": "utf_8", "md5": "781e021368981a4095294e1dc6360978", "text": "function varargout = plotdz(P,varargin)\n\n%PLOTDZ plot upstream distance version elevation or covariate of a PPS\n%\n% Syntax\n%\n% plotdz(P)\n%\n% Description\n%\n% plot distance versus elevation of points and stream network in an\n% instance of PPS.\n%\n% Input arguments\n%\n% P instance of PPS (needs z-property unless parameter z is set\n% to different node-attribute list)\n%\n% Parameter name/value pairs\n%\n% For the river profile, all parameters that work for STREAMobj/plotdz \n% can be used except 'color'. Use 'LineColor' instead to define the\n% color of the line. If the line should not be visible, use\n% 'LineColor','none'.\n%\n% For the points, all parameters that work for scatter or bubblechart \n% if you have MATLAB 2020b or higher. Note that using bubblechart does\n% not allow you to set the parameter 'marker'.\n%\n% For versions older than 2020b, the function uses scatter to plot\n% points. If you supply SizeData, then you can additionally control the\n% range of sizes used for plotting by following arguments.\n%\n% 'MinSize' see 'SizeData' (default = 5)\n% 'MaxSize' see 'SizeData' (default = 75)\n%\n% Additional arguments are\n%\n% 'z' default is the node-attribute of elevation values stored \n% in the PPS object. Takes any other node-attribute list.\n% 'SizeData' data (GRIDobj, node-attribute list, or attributes (marks) \n% for each point.\n% 'ColorData' data (GRIDobj, node-attribute list, or attributes (marks) \n% for each point. \n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S,1);\n% P = PPS(S,'runif',30,'z',DEM);\n% plotdz(P,'SizeData',P.S.distance,'ColorData',DEM)\n%\n% See also: PPS, PPS/npoints, bubblechart, bubblelegend, bubblesize \n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 28. September, 2020\n\n% Check version because 2020b onwards will use bubblechart\nolderthan2020b = verLessThan('matlab','9.9');\nif olderthan2020b\n minsi = 5;\n maxsi = 75;\nelse\n minsi = 1;\n maxsi = 10;\nend\n\n%% Input parameter parsing\np = inputParser;\np.KeepUnmatched = true;\n\n% Custom river elevations and distance\naddParameter(p,'z','z');\naddParameter(p,'distance',[],@(x) isnal(P.S,x));\naddParameter(p,'LineColor',[.7 .7 .7])\n\n% Point properties\nif olderthan2020b\naddParameter(p,'Marker','o');\nend\naddParameter(p,'MarkerEdgeColor','k');\naddParameter(p,'MarkerFaceAlpha',0.5);\naddParameter(p,'MinSize',minsi);\naddParameter(p,'MaxSize',maxsi);\n\naddParameter(p,'SizeData',20); \naddParameter(p,'ColorData','w');\n\n% Parse\nparse(p,varargin{:});\n\nUnMatched = p.Unmatched;\nUnMatched.distance = p.Results.distance;\n\ntf = ishold;\n\n% Get line color\nlc = p.Results.LineColor;\n\n% Get elevations\nzz = getcovariate(P,p.Results.z);\n\nif isempty(p.Results.distance)\n d = P.S.distance;\nelse\n d = p.Results.distance;\nend\n\n%% Handle additional arguments\nResults = p.Results;\nsz = p.Results.SizeData;\n\n% -- SizeData\nif isnal(P.S,sz) || isa(sz,'GRIDobj')\n sz = getmarks(P,sz);\nelseif numel(sz) == npoints(P)\n % great, go on\nend\n\n% If scatter is used, we will adjust the size range of the data between the\n% arguments MinSize and MaxSize\nif olderthan2020b && ~isscalar(sz)\n % normalize sz between 0 and 1\n sz = sz - min(sz);\n sz = sz./max(sz);\n sz = sz*(Results.MaxSize - Results.MinSize) + Results.MinSize;\nelse\n maxsz = Results.MaxSize;\n minsz = Results.MinSize;\nend\n\n% -- ColorData\ncols = Results.ColorData;\nif isnal(P.S,cols) || isa(cols,'GRIDobj')\n cols = getmarks(P,cols);\nend\n\n% -- Remove additional arguments from the Results structure\nResults = rmfield(Results,{'distance' 'z' 'SizeData' 'ColorData' ...\n 'MaxSize' 'MinSize' 'LineColor'});\n\n% Does the field 'dunit' exist\nif isfield(UnMatched,'dunit')\n switch UnMatched.dunit\n case 'km'\n d = d/1000;\n end\nend\npnpv = expandstruct(Results);\n\n%% Plotting\n% Plot line\nhl = plotdz(P.S,zz,UnMatched,'Color',lc);\nhold on\n\nif olderthan2020b || isscalar(sz) \n hs = scatter(d(P.PP),zz(P.PP),sz,cols,'filled',pnpv{:});\nelse\n hs = bubblechart(d(P.PP),zz(P.PP),sz,cols,pnpv{:});\n bubblesize([minsz maxsz])\nend\n\nif ~tf\n hold off\nend\n\nif nargout >= 1\n varargout{1} = hl;\nend\nif nargout == 2\n varargout{2} = hs;\nend\nend\n\nfunction pnpv = expandstruct(s)\n\npn = fieldnames(s);\npv = struct2cell(s);\n\npnpv = [pn pv];\npnpv = pnpv';\npnpv = pnpv(:)';\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "plotpoints.m", "ext": ".m", "path": "topotoolbox-master/@PPS/plotpoints.m", "size": 3644, "source_encoding": "utf_8", "md5": "a234be892ec75fab1559dc1bb596a2d8", "text": "function h = plotpoints(P,varargin)\n\n%PLOTPOINTS plot points of PPS\n%\n% Syntax\n%\n% plotpoints(P)\n% plotpoints(P,'pn',pv,...)\n% h = plotpoints(...)\n%\n% Description\n%\n% plotpoints plots the points of an instance of PPS. The function uses\n% the build-in function scatter. Thus, it accepts all parameter\n% name/value pairs that are accepted by scatter.\n% \n% Input arguments\n%\n% P instance of PPS\n%\n% Parameter name/value pairs (see scatter)\n%\n% 'Marker' Marker type (see scatter)\n% 'MarkerEdgeColor' Marker edge color (see scatter) (default = 'k')\n% 'MarkerFaceColor' Marker face color (see scatter) (default = 'w')\n% 'LineWidth' Width of the marker edge\n% 'SizeData' Default=20. If scalar, then markers will be plotted\n% using this size (see scatter). If vector, then marker \n% size will vary according to the values in this vector. \n% Marker size will be automatically scaled to vary within\n% the bounds set by 'MinSize' and 'MaxSize' if used in\n% versions of MATLAB older than 2020b.\n% 'MinSize' see 'SizeData' (default = 5)\n% 'MaxSize' see 'SizeData' (default = 75)\n% 'MarkerFaceAlpha' Transparency (default = 0.5). 0 is completely \n% transparent and 1 is fully opaque. (see scatter)\n% 'ColorData' Default='w'. Alternatively, a vector with values for \n% each point. \n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% S = STREAMobj(FD,'minarea',1000);\n% S = removeshortstreams(S,100);\n% S = clean(S);\n% P = PPS(S,'rpois',0.001,'z',DEM);\n% plot(S,'k')\n% hold on\n% plotpoints(P,'colordata',DEM,'sizedata',distance(S,'max'))\n%\n%\n% See also: PPS/plot, PPS/plotdz, STREAMobj/plot, STREAMobj/plotc\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 26. November, 2020\n\n\np = inputParser;\np.KeepUnmatched = true;\nif verLessThan('matlab','9.9')\naddParameter(p,'Marker','o');\nend\naddParameter(p,'MarkerEdgeColor','k');\naddParameter(p,'MarkerEdgeAlpha',0.5);\naddParameter(p,'MarkerFaceAlpha',0.5);\n\naddParameter(p,'LineWidth',1)\naddParameter(p,'SizeData',20);\naddParameter(p,'ColorData','w');\naddParameter(p,'MinSize',5);\naddParameter(p,'MaxSize',75);\n\n% Parse\nparse(p,varargin{:});\n\nResults = p.Results;\n\ncols = Results.ColorData;\n% Get colordata\nif isnal(P.S,cols) || isa(cols,'GRIDobj')\n cols = getmarks(P,cols);\nend\n\n\nif isscalar(Results.SizeData) && ~isa(Results.SizeData,'GRIDobj')\n % all good. All points have the same size\nelse\n if numel(Results.SizeData) == npoints(P)\n else\n Results.SizeData = getmarks(P,Results.SizeData);\n end\nend\n\nif verLessThan('matlab','9.9')\n % scale between 1 and 20\n Results.SizeData = Results.SizeData - min(Results.SizeData);\n Results.SizeData = Results.SizeData./max(Results.SizeData);\n Results.SizeData = Results.SizeData*(Results.MaxSize - Results.MinSize) + Results.MinSize;\nelse\n sz = Results.SizeData;\n Results = rmfield(Results,'SizeData');\nend\n \nResults = rmfield(Results,{'MaxSize','MinSize','ColorData'});\n\nxy = P.ppxy;\n\npnpv = expandstruct(Results);\n\nif verLessThan('matlab','9.9') || isscalar(sz)\n % Use scatter\n ht = scatter(xy(:,1),xy(:,2),[],cols,'filled',pnpv{:});\nelse\n ht = bubblechart(xy(:,1),xy(:,2),sz,cols,pnpv{:});\n bubblesize([1 10])\nend\n \n\nif nargout == 1\n h = ht;\nend\n\nend\n\nfunction pnpv = expandstruct(s)\n\npn = fieldnames(s);\npv = struct2cell(s);\n\npnpv = [pn pv];\npnpv = pnpv';\npnpv = pnpv(:)';\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "aggregate.m", "ext": ".m", "path": "topotoolbox-master/@PPS/aggregate.m", "size": 5971, "source_encoding": "utf_8", "md5": "9e0fbc15cca218f657f3f1eb53de4631", "text": "function [P,locb] = aggregate(P,c,varargin)\n\n%AGGREGATE Aggregate points in PPS to new point pattern\n%\n% Syntax\n%\n% P2 = aggregate(P,c)\n% P2 = aggregate(P,c,pn,pv,...)\n%\n% Description\n%\n% aggregate merges points in a PPS object to a new PPS object based on\n% the labels in the marks c. The labels can be generated by the\n% function PPS/cluster. Equal labels in c must not occur in different\n% drainage basins. Moreover, the edges of a shortest path tree between\n% points with a specific label must not lie on shortest path trees\n% of other labels.\n%\n% Input arguments\n%\n% P instance of PPS\n% c npoints(P)x1 label vector\n%\n% Parameter name/value pairs\n%\n% 'type' 'centroid' (default) finds the location in the network\n% that has the least squared distance to all points\n% with the same label. Distances are calculated along\n% the stream network.\n% 'euclideancentroid' calculates the centroid of all\n% points with the same label and snaps the location of\n% the centroid to the stream network. \n% 'nearesttocentroid' calculates the centroid and then\n% chooses the point that is nearest to this centroid.\n%\n% Output arguments\n%\n% P2 PPS object\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',500);\n% S = klargestconncomps(S,1);\n% P = PPS(S,'runif',200,'z',DEM);\n% c = cluster(P,'cutoff',2000);\n% convhull(P,'groups',c,'bufferwidth',200)\n% P2 = aggregate(P,c);\n% hold on\n% plotpoints(P2,'Size',30,'MarkerFaceColor','b')\n% hold off\n% axis equal\n% box on\n%\n% See also: PPS, PPS/cluster, PPS/convhull\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 29. June, 2020\n\n\np = inputParser;\np.KeepUnmatched = true;\naddRequired(p,'P');\naddRequired(p,'c',@(x) numel(x) == npoints(P));\naddParameter(p,'type','centroid');\naddParameter(p,'useparallel',true);\n\n% Parse\nparse(p,P,c,varargin{:});\n\ntype = validatestring(p.Results.type,...\n {'centroid','euclideancentroid',...\n 'nearesttocentroid','mostupstream','mostdownstream'});\n\n% make sure that one label does not occur in multiple drainage basins.\nconcom = conncomps(P.S);\nconcom = getmarks(P,concom);\ntf = accumarray(c,concom,[],@(x) numel(unique(x)));\nif any(tf>1)\n error('Labels span across more than one drainage basin.')\nend\n\nswitch lower(type)\n case {'mostupstream','mostdownstream'}\n [uniquec,~,locb] = unique(c);\n d = P.S.distance;\n d = getmarks(P,d);\n switch lower(type)\n case 'mostdownstream'\n d = 1./d;\n end\n d = sparse((1:numel(locb))',locb,d,numel(locb),max(locb));\n [~,ix] = max(d);\n P.PP = P.PP(ix);\n \n case 'nearesttocentroid'\n % Calculate centroids\n [Pc,locb] = aggregate(P,c,'useparallel',p.Results.useparallel);\n % Nearest to centroid\n G = as(P,'graph');\n d = distances(G,P.PP,Pc.PP);\n % get distance from each point to centroid of its group\n ix = sub2ind(size(d),(1:size(d,1))',locb);\n I = true(size(d));\n I(ix) = false;\n d(I) = inf; \n \n [~,ix] = min(d);\n \n P.PP = P.PP(ix);\n \n case 'euclideancentroid'\n % Euclidean distance is easy. \n [uniquec,~,locb] = unique(c); \n nc = numel(uniquec);\n [x,y] = points(P);\n % calculate centroids for each label\n xc = accumarray(locb,x,[nc 1],@mean);\n yc = accumarray(locb,y,[nc 1],@mean);\n \n % snap centroids back to the stream network\n [~,~,IX] = snap2stream(P.S,xc,yc);\n % and update the point pattern in P\n [~,P.PP] = ismember(IX,P.S.IXgrid);\n \n case 'centroid'\n \n % The network centroid is a bit more tricky\n G = as(P,'graph');\n % This line returns for each label the edges that belong to the\n % minimum spanning tree that connects the points\n [~,~,c] = unique(c);\n locb = c;\n G.Nodes.group = zeros(size(P.S.x));\n G.Nodes.group(P.PP) = c;\n\n E = accumarray(c,P.PP,[max(c) 1],@(x) {spedges(x)});\n % list the edges\n E = vertcat(E{:});\n\n if numel(unique(E)) ~= numel(E)\n error('Overlapping shortest path trees');\n end\n \n % Edges that should be removed from the graph\n E = setdiff(1:size(G.Edges,1),E);\n G = rmedge(G,E');\n % Also remove nodes with zero degree\n G = rmnode(G,find(degree(G) == 0)); \n % Calculate the connected components of the remaining network\n cc = conncomp(G,'outputform','cell');\n \n % Go through the individual connected components\n ix = zeros(size(cc));\n cl = zeros(size(cc));\n% pp = cell(size(cc));\n parfor r = 1:numel(cc)\n % Extract the subgraph that contains each connected component\n GSUB = subgraph(G,cc{r});\n % Calculate distances from each point to all nodes \n d = distances(GSUB,find(GSUB.Nodes.ispoint));\n % Calculate the sum of squares\n d = sum(d.^2,1);\n % Find the node with the minimum sum of squares\n [~,ixx] = min(d);\n ix(r) = GSUB.Nodes.pts(ixx);\n cl(r) = GSUB.Nodes.group(find(GSUB.Nodes.ispoint,1,'first'));\n \n end\n I = accumarray(c,1) > 1;\n I = I(c);\n % gr = locb(P.PP);\n P.PP(I) = [];\n P.PP = [P.PP;ix(:)];\n locb = c;\n \nend\n\n\nfunction E = spedges(nodes)\n\nnodes = unique(nodes); \nif numel(nodes) == 1\n E = [];\n return\nend\n[~,~,E] = shortestpathtree(G,nodes(1),nodes(2:end));\nE = find(E);\n\nend\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "convhull.m", "ext": ".m", "path": "topotoolbox-master/@PPS/convhull.m", "size": 3641, "source_encoding": "utf_8", "md5": "7dd0ac9cd40bcda35dd6d612617bb046", "text": "function h = convhull(P,varargin)\n\n%CONVHULL Convex hull around points in PPS\n%\n% Syntax\n%\n% psh = convhull(P)\n% psh = convhull(P,'groups',c,'bufferwidth',bw);\n% convhull(P,...)\n%\n% Description\n%\n% convhull returns the convex hull around all or groups of points in P\n% as polyshape object. Without output arguments, convhull plots the\n% convex hull(s).\n%\n% Input arguments\n%\n% P instance of PPS\n%\n% Parameter name/value pairs\n%\n% 'groups' vector of group assignments of each point (e.g. as\n% returned by PPS/cluster.\n% 'bufferwidth' default is the maximum extent of the stream network\n% divided by 100\n% 'useparallel' true (default) or false. \n% 'text' false (default) or true (only applicable if plotted)\n% 'textcolor' color of text (if 'text', true)\n% 'backgroundcolor background color of text (if 'text', true)\n% 'onlynonzero' encircle only groups with non-zero values \n%\n%\n% Output arguments\n%\n% psh polyshape object\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM);\n% S = STREAMobj(FD,'minarea',500);\n% S = klargestconncomps(S,1);\n% P = PPS(S,'runif',200,'z',DEM);\n% c = cluster(P,'cutoff',2000);\n% convhull(P,'groups',c,'bufferwidth',200)\n%\n%\n% See also: PPS, PPS/cluster, PPS/aggregate\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 11. February, 2020\n\nbbox = info(P.S,'boundingbox');\nmaxext = max(bbox(2)-bbox(1),bbox(4)-bbox(3));\n\np = inputParser;\np.FunctionName = 'PPS/convhull';\naddParameter(p,'groups',ones(npoints(P),1),@(x) (numel(x) == npoints(P)) | isa(x,'GRIDobj'));\naddParameter(p,'bufferwidth',maxext/100,@(x) isscalar(x) && x>0);\naddParameter(p,'useparallel',true);\naddParameter(p,'plotall',true);\naddParameter(p,'text',false);\naddParameter(p,'textcolor','k');\naddParameter(p,'backgroundcolor','w');\naddParameter(p,'onlynonzero',false);\nparse(p,varargin{:});\n\ngroups = p.Results.groups;\nif isa(groups,'GRIDobj')\n groups = groups.Z(P.S.IXgrid(P.PP));\nend\n\nif p.Results.onlynonzero\n I = groups == 0;\n groups(I) = [];\n xy = P.ppxy(~I,:);\n \nelse\n xy = P.ppxy;\nend\n\n[v,~,ixb] = unique(groups);\nn = numel(v);\n\n% assemble points in cell array\nix = accumarray(ixb,(1:numel(ixb))',[n 1],@(x) {x});\nxy = cellfun(@(ix) xy(ix,:),ix,'UniformOutput',false);\n\n\nbw = p.Results.bufferwidth;\n\nwarning off\nif p.Results.useparallel\n parfor r = 1:numel(xy)\n psh(r) = convhullsub(xy{r},bw);\n end \nelse\n psh = cellfun(@(xy) convhullsub(xy,bw),xy,'UniformOutput',true);\nend\nwarning on\n\nif nargout == 0\n if p.Results.plotall\n tf = ishold;\n hold on\n plot(P);\n end\n plot(psh)\n \n if p.Results.text\n [xt,yt] = centroid(psh);\n hold on\n text(xt,yt,num2cell(v),'color',p.Results.textcolor,...\n 'EdgeColor','none','Backgroundcolor',p.Results.backgroundcolor)\n end\n \n if ~tf\n hold off\n end\nelse\n h = psh;\nend\nend\n\nfunction h = convhullsub(xy,bw)\n\n% check whether points are unique\nxy = unique(xy,'rows');\n\nif size(xy,1) == 1\n h = polybuffer(xy(1,:),'points',bw);\nelseif size(xy,1) == 2\n h = polybuffer(xy,'lines',bw);\nelse\n try\n % try, but may not work if points are collinear\n c = convhull(xy);\n poly = polyshape(xy(c,1),xy(c,2),...\n 'SolidBoundaryOrientation','ccw',...\n 'Simplify',false,...\n 'KeepCollinearPoints',true);\n h = polybuffer(poly,bw);\n catch\n h = polybuffer(xy,'lines',bw);\n end\nend\nend\n \n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "bayesloglinear.m", "ext": ".m", "path": "topotoolbox-master/@PPS/bayesloglinear.m", "size": 3435, "source_encoding": "utf_8", "md5": "c7b83ddd36f61b9142262c276bc748c0", "text": "function [mdl,int,intci,predstats,rank] = bayesloglinear(P,c,varargin)\n\n%BAYESLOGLINEAR Bayesian analysis of a loglinear point process model \n%\n% Syntax\n%\n% [mdl,int,intci,predstats] = bayesloglinear(P,c,pn,pv,...)\n%\n% Description\n%\n% Loglinear models embrace numerous models that can be fitted to\n% homogeneous and inhomogeneous Poisson processes on river networks. \n% bayesloglinear uses bayesreg, a toolbox for fitting and evaluating \n% Bayesian penalized regression models with continuous shrinkage prior \n% densities.\n%\n% Input arguments\n%\n% P instance of PPS\n% c covariates (node-attribute lists)\n% \n% Parameter name/value pairs\n% \n% 'verbose' true\n% 'prior' {'horseshoe'}. Other options are 'g','ridge','lasso',\n% 'horseshoe+' \n% 'predci' [5 95]. prediction confidence intervals\n% 'nsamples' 1000. number of posterior samples\n% 'thin' 5. level of thinning\n% 'varnames' {}. cell array of variable names\n% 'sortrank' false. display variables in rank order\n%\n% Output arguments\n%\n% mdl model (GeneralizedLinearModel)\n% int node-attribute list with modelled intensities\n% intc credible intervals (5 and 95%) of intensities\n% predstats see bayesreg\n% \n% Example \n% \n% See also: PPS, PPS/random, PPS/fitloglinear, bayesreg\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 11. February, 2019\n\n% Check, whether bayesreg is available\nif exist('bayesreg','file') ~= 2\n url = 'https://in.mathworks.com/matlabcentral/fileexchange/60823-bayesian-penalized-regression-with-continuous-shrinkage-prio';\n error('TopoToolbox:bayesloglinear',...\n ['BayesReg Toolbox must be on the search path. The toolbox\\n'...\n 'can be downloaded from the File Exchange.'])\nend\n\np = inputParser;\np.KeepUnmatched = true;\naddParameter(p,'distribution','binomial');\naddParameter(p,'verbose',true);\naddParameter(p,'prior','horseshoe');\naddParameter(p,'predci',[5 95],@(x) (numel(x) == 2));\naddParameter(p,'nsamples',1000)\naddParameter(p,'thin', 5)\naddParameter(p,'varnames',{})\naddParameter(p,'sortrank',false)\nparse(p,varargin{:});\n\n% Options for fitglm and stepwise\nbayesregopts = p.Unmatched;\nbayesregopts = expandstruct(bayesregopts);\n\n% Get covariates\nX = getcovariate(P,c);\n% Get response variable\ny = zeros(numel(P.S.x),1);\ny(P.PP) = 1;\n\n% [b,FitInfo] = lassoglm(zscore(X),y,'binomial');\n\n[mdl.beta,mdl.beta0,mdl.retval] = ...\n bayesreg(X,y,p.Results.distribution,p.Results.prior,...\n 'display',p.Results.verbose,...\n 'nsamples',p.Results.nsamples,...\n 'thin',p.Results.thin,...\n 'varnames',p.Results.varnames,...\n 'sortrank',p.Results.sortrank,...\n bayesregopts{:});\n \n[pred, predstats] = br_predict(X, mdl.beta, mdl.beta0, mdl.retval, ...\n 'CI',p.Results.predci,...\n 'ytest', y, ...\n 'display',p.Results.verbose);\n \nrank = bfr(mdl.beta);\n\n% modelled intensities\nd = distance(P.S,'node_to_node');\nd = mean(d);\nint = pred.prob_1./d;\nintci = [pred.prob_1_CI5_./d pred.prob_1_CI95_./d];\n\n\nend\n\nfunction pnpv = expandstruct(s)\n\npn = fieldnames(s);\npv = struct2cell(s);\n\npnpv = [pn pv];\npnpv = pnpv';\npnpv = pnpv(:)';\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "fitloglinear.m", "ext": ".m", "path": "topotoolbox-master/@PPS/fitloglinear.m", "size": 6916, "source_encoding": "utf_8", "md5": "3bbc96894fc95c86395f330888cf3b04", "text": "function [mdl,int,rts,rtssigma,ismx,sigmapred] = fitloglinear(P,c,varargin)\n\n%FITLOGLINEAR fit loglinear model to point pattern\n%\n% Syntax\n%\n% [mdl,int] = fitloglinear(P,c)\n% [mdl,int] = fitloglinear(P,c,pn,pv,...)\n% [mdl,int,mx,sigmamx,ismx,sigmapred] = ...\n% fitloglinear(P,c,'modelspec','poly2',...)\n%\n% Description\n%\n% Loglinear models embrace numerous models that can be fitted to\n% homogeneous and inhomogeneous Poisson processes on river networks. \n% fitloglinear fits a model via logistic regression. Note that this\n% requires that no duplicate points exist. fitloglinear uses fitglm\n% to fit the logistic regression model.\n%\n% Input arguments\n%\n% P instance of PPS\n% c covariates (node-attribute lists)\n% \n% Parameter name/value pairs\n% \n% 'stepwise' {false} or true. If true, fitloglinear uses stepwiseglm\n% to fit the model.\n% 'modelspec' see fitglm. For example, for fitting a forth-order\n% polynomial: 'poly4'\n% \n% In addition, fitloglinear accepts parameter name/value pairs of\n% fitglm or stepwiseglm.\n%\n% Output arguments\n%\n% mdl model (GeneralizedLinearModel)\n% int node-attribute list with modelled intensities\n%\n% If (and only if) 'modelspec' is 'poly2', then additional output \n% arguments are returned\n%\n% mx for second-order polynomials of a single-variable model, \n% mx returns the location of maximum in the intensity \n% function.\n% sigmamx the standard error of the location of the maximum\n% ismx true or false. True, if mx is a maximum, and false\n% otherwise.\n% sigmapred the +/- range in which 66% of points will lie, corrected \n% for the abundance of the covariate.\n% \n% Example 1: Create an inhomogeneous Poisson process with the intensity\n% being a function of elevation. Simulate a random point pattern\n% and fit the model.\n% \n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S,1);\n% P = PPS(S,'PP',[],'z',DEM);\n% P = simulate(P,'intensity',getnal(S,DEM)/1e6);\n% subplot(1,2,1)\n% plot(P)\n% subplot(1,2,2)\n% plotdz(P)\n% [mdl,int] = fitloglinear(P,DEM,'model','poly1');\n% figure\n% subplot(1,2,1)\n% plotc(P,int)\n% subplot(1,2,2)\n% ploteffects(P,mdl,1)\n%\n% Example 2: Model the distribution of knickpoints as a second-order\n% loglinear model.\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% S = STREAMobj(FD,'minarea',1000);\n% S = klargestconncomps(S,1);\n% \n% % Find knickpoints\n% [~,kp] = knickpointfinder(S,DEM,'tol',30,...\n% 'split',false,...\n% 'verbose',false,...\n% 'plot',false);\n% P = PPS(S,'PP',kp.IXgrid,'z',DEM);\n% P.PP(~(DEM.Z(S.IXgrid(P.PP)) < 1000)) = [];\n%\n% % also try\n% % P.PP(~(DEM.Z(S.IXgrid(P.PP)) < 1000 & ...\n% % DEM.Z(S.IXgrid(P.PP)) > 800)) = [];\n% \n% A = flowacc(FD);\n% c = chitransform(S,A,'mn',0.4);\n% \n% [mdl,int,mx,sigmamx,ismx,sigmapred] = ...\n% fitloglinear(P,c,'modelspec','poly2');\n%\n% plotdz(P,'distance',c,'ColorData','k')\n% yyaxis right\n% ploteffects(P,mdl,'patch',true)\n% xline([mx-sigmapred mx+sigmapred],':')\n% xline([mx-sigmamx mx+sigmamx],'--')\n% xline(mx)\n% \n%\n% See also: PPS, PPS/random, fitglm, stepwiseglm\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 9. September, 2022 \n\np = inputParser;\np.KeepUnmatched = true;\naddParameter(p,'stepwise',false,@(x) isscalar(x));\naddParameter(p,'modelspec','linear');\naddParameter(p,'distribution','binomial');\naddParameter(p,'weights',getnal(P.S)+1);\nparse(p,varargin{:});\n\n% Get covariates\nX = getcovariate(P,c);\n% Get response variable\ny = zeros(numel(P.S.x),1);\ny(P.PP) = 1;\n\n% Options for fitglm and stepwise\nglmopts = p.Unmatched;\nglmopts = expandstruct(glmopts);\n\n% Handle weights\nfllopts = p.Results;\nvalidateattributes(fllopts.weights,{'single','double'},{'>',0,'nonnan','finite'});\nif ~isnal(P.S,fllopts.weights)\n % weights should have as many entries as there are points\n if numel(fllopts.weights) ~= npoints(P)\n error('TopoToolbox:fitloglinear','Wrong number of elements in the weights vector')\n end\n w = getnal(P.S)+mean(fllopts.weights);\n w(P.PP) = fllopts.weights;\n fllopts.weights = w;\nend\n\n\n% Covariates can be supplied as table. This needs some handling.\nif istable(X)\n tbl = [X table(y,'variablenames',{'response'})];\n inp = {tbl};\nelse\n inp = {X y};\nend\n\n\nif ~p.Results.stepwise\n \n mdl = fitglm(inp{:},fllopts.modelspec,...\n 'Distribution',fllopts.distribution,'weights',fllopts.weights,glmopts{:});\n \nelse\n\n % Use stepwise GLM\n mdl = stepwiseglm(inp{:},fllopts.modelspec,...\n 'Distribution',fllopts.distribution,'weights',fllopts.weights,glmopts{:});\n \nend\n\n% modelled intensities\np = predict(mdl,X);\nd = distance(P.S,'node_to_node');\nd = mean(d);\nint = p./d; %.cellsize;\n\n% --- The following section applies only to second-order loglinear models\n% that have been obtained with 'modelspec','poly2'\nif nargout >= 3\n switch lower(fllopts.modelspec) \n case 'poly2'\n otherwise\n rts = [];\n rtssigma = [];\n ismax = [];\n sigmapred = [];\n warning('TopoToolbox:fitloglinear',...\n ['Third to sixth output only available if\\n' ...\n 'model has one variable and modelspec is poly2.'])\n return\n end\n\n % Coefficient of x\n b1 = mdl.Coefficients.Estimate(2);\n\t% Coefficient of x^2\n b2 = mdl.Coefficients.Estimate(3);\n\t% Covariance matrix\n C = mdl.CoefficientCovariance(2:3,2:3);\n\n % Location of the maximum\n\t% b1 + 2*b2*x = 0\n rts = -0.5*b1/b2;\n \n\t% Standard errors of coefficients\n sb1 = mdl.Coefficients.SE(2);\n sb2 = mdl.Coefficients.SE(3);\n\t% \n rtssigma = sqrt(((sb1/b1)^2 + (sb2/b2)^2 - 2*C(2,1)/(b1*b2)))*rts;\n %\n ismx = b2 < 0;\n\n % Find standard deviation of predictions\n % Can be found be finding the inflection points (zeros of the second\n % derivative of the exponential function\n \n % Let's swap parameter names (so that they are compatible with equations\n % from Wolfram Alpha ;-)\n b3 = b2;\n b2 = b1;\n val1 = (-b2*b3 - sqrt(2)*sqrt(-b3^3))/(2*b3^2);\n % val2 = (sqrt(2)*sqrt(-b3^3) - b2*b3)/(2*b3^2);\n sigmapred = abs(val1-rts);\n\nend\nend\n \n% ---------------- some helper functions -------------------------------\nfunction pnpv = expandstruct(s)\n\npn = fieldnames(s);\npv = struct2cell(s);\n\npnpv = [pn pv];\npnpv = pnpv';\npnpv = pnpv(:)';\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "ploteffects.m", "ext": ".m", "path": "topotoolbox-master/@PPS/ploteffects.m", "size": 8245, "source_encoding": "utf_8", "md5": "eca174b26bf80832cf1bf27946b7502d", "text": "function h = ploteffects(P,mdl,varargin)\n\n%PLOTEFFECTS Plot of slices through a loglinear point process model\n%\n% Syntax\n%\n% ploteffects(P,mdl)\n% ploteffects(P,mdl,covariate)\n% ploteffects(p,mdl,covariate,pn,pv,...)\n% h = ...\n%\n% Description\n%\n% ploteffects plots the individual effects of a loglinear point process\n% model fitted with PPS/fitloglinear.\n%\n% Input arguments\n%\n% P PPS object\n% mdl object of 'GeneralizedLinearModel'\n% covariate number of covariate to be plotted. For example, if there\n% are two predictor variables in the model mdl, then \n% covariate can be 1 or 2, or [1 2].\n%\n% Parameter name value\n%\n% 'plot' {true} or false\n% 'n' number of values linear spaced for a covariate {100}\n% 'fixedvars' fixed values (by default, this is the mean of each\n% covariate).\n% 'plotintensity' true or {false}. Plots a horizontal line with the\n% intensity of the point pattern\n% 'indicators' {false} or true. If true, lines indicating point\n% locations at the bottom of the plot\n% 'bounds' plot confidence bounds {true} or false\n%\n% If confidence bounds true then following parameters apply\n% 'alpha' significance level of confidence bounds (default = 0.05)\n% 'simultaneous' {false} or true\n% 'patch' {false} or true\n%\n% If 'patch' is true then several patch properties can be applied\n% ('facealpha', 'facecolor', 'edgecolor', 'linestyle').\n%\n% Output arguments\n%\n% h Structure array with predictions and handles to graphics\n%\n% Example: see second example in PPS/fitloglinear\n%\n%\n% See also: PPS, PPS/fitloglinear, PPS/roc\n%\n% Note: The function includes the numSubplots by Rob Campbell (2022). \n% https://www.mathworks.com/matlabcentral/fileexchange/26310-numsubplots-neatly-arrange-subplots \n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 28. December, 2022\n\n%% Parse inputs\np = inputParser;\np.FunctionName = 'PPS/ploteffects';\n% Add elevation\naddRequired(p,'P');\naddRequired(p,'mdl',@(x) isa(x,'GeneralizedLinearModel'));\naddOptional(p,'covariate',1,@(x) numel(x) >= 1 && numel(x) <= (size(mdl.Variables,2)-1));\naddParameter(p,'plot',true);\naddParameter(p,'n',1000);\naddParameter(p,'fixedvars',mean(mdl.Variables{:,1:end-1}));\naddParameter(p,'bounds',true)\naddParameter(p,'plotintensity',false);\naddParameter(p,'alpha',0.05)\naddParameter(p,'simultaneous',false)\naddParameter(p,'indicators',false);\naddParameter(p,'varnames','');\naddParameter(p,'patch',false);\naddParameter(p,'facecolor',[0.5059 0.8471 0.8157]);\naddParameter(p,'edgecolor','none')\naddParameter(p,'facealpha',0.5)\naddParameter(p,'edgealpha',1)\naddParameter(p,'linestyle',':')\n\n% Parse\nparse(p,P,mdl,varargin{:});\n\ncovariate = p.Results.covariate;\nnvars = numel(covariate);\n\n% find a nice layout of subplots;\nif nvars > 1\n nn = numSubplots(nvars);\n nrows = nn(1);\n ncols = nn(2);\nend\n\nfixedvars = p.Results.fixedvars;\nfixedvars = repmat(fixedvars,p.Results.n,1);\n\n% deal with categorical predictors\nt = mdl.VariableInfo;\n% Linear index of categorical variables\nIsCat = find(t.IsCategorical);\nif ~isempty(IsCat)\n for r = 1:numel(IsCat)\n % Values of categorical variables\n catval = t.Range(IsCat(r));\n % Take the first value\n catval = catval{1};\n % and write it to the column of fixed vars\n fixedvars(:,IsCat(r)) = catval(1);\n end\nend\n\n\nd = distance(P.S,'node_to_node');\nd = mean(d);\n\n\nfor r = 1:nvars\n\n if ~ismember(covariate(r),IsCat)\n % Variable is numerical\n\n if nvars > 1\n subplot(nrows,ncols,r);\n end\n predictor = linspace(min(mdl.Variables{:,covariate(r)}),...\n max(mdl.Variables{:,covariate(r)}),...\n p.Results.n)';\n preds = fixedvars;\n\n preds(:,covariate(r)) = predictor;\n [int,ci] = predict(mdl,preds,'alpha',p.Results.alpha,...\n 'simultaneous',p.Results.simultaneous);\n int = int/d;\n ci = ci/d;\n\n out(r).predictor = preds;\n out(r).int = int;\n out(r).ci = ci;\n\n if p.Results.plot\n ax = gca;\n box(ax,'on')\n\n if ishold(ax)\n keephold = true;\n else\n keephold = false;\n end\n\n if p.Results.bounds\n if p.Results.patch\n\n out(r).hp = patch([predictor; flipud(predictor)],...\n [ci(:,1);flipud(ci(:,2))],...\n p.Results.facecolor,...\n 'EdgeColor',p.Results.edgecolor,...\n 'FaceAlpha',p.Results.facealpha,...\n 'EdgeAlpha',p.Results.edgealpha,...\n 'LineStyle',p.Results.linestyle,...\n 'parent',ax);\n else\n out(r).hci = plot(ax,predictor,ci,'k--');\n end\n hold(ax,'on')\n end\n out(r).hl = plot(ax,predictor,int,'k');\n hold(ax,'on')\n if p.Results.plotintensity\n ii = intensity(P);\n out(r).hint = plot(ax,xlim,[ii ii],':','color',[.5 .5 .5]);\n end\n\n if p.Results.indicators\n xl = mdl.Variables{:,covariate(r)}(P.PP);\n out(r).hxline = xlinerel(xl,0.03);\n end\n\n if ~keephold\n hold(ax,\"off\")\n end\n\n if isempty(p.Results.varnames)\n lab = ['x_{' num2str(covariate(r)) '}'];\n else\n lab = [p.Results.varnames{r}];\n end\n xlabel(ax,lab);\n ylabel(ax,['\\lambda(' lab ')']);\n\n end\n\n else\n\n % variable is categorical\n if nvars > 1\n subplot(nrows,ncols,r);\n end\n catvals = t.Range(covariate(r));\n catvals = catvals{1};\n\n ncatvals = numel(catvals);\n\n for rr = 1:ncatvals\n\n predictor = catvals(rr);\n preds = fixedvars(1,:);\n\n preds(:,covariate(r)) = predictor;\n [int,ci] = predict(mdl,preds,'alpha',p.Results.alpha,...\n 'simultaneous',p.Results.simultaneous);\n int = int/d;\n ci = ci/d;\n\n out(r).predictor(rr) = {preds};\n out(r).int(rr) = int;\n out(r).ci(rr,[1 2]) = ci;\n\n end\n\n % plot\n if p.Results.plot\n\n ax = gca;\n box(ax,'on')\n\n errorbar(ax,1:ncatvals,out(r).int(:),out(r).int(:) - out(r).ci(:,1),...\n out(r).ci(:,2) - out(r).int(:),'s');\n set(ax,'XTick',1:ncatvals)\n set(ax,'XTickLabel',catvals)\n set(ax,'Xlim',[.5 ncatvals+0.5])\n\n if isempty(p.Results.varnames)\n lab = ['x_{' num2str(covariate(r)) '}'];\n else\n lab = [p.Results.varnames{r}];\n end\n xlabel(ax,lab);\n ylabel(ax,['\\lambda(' lab ')']);\n\n end\n end\n\nend\n\nif nargout == 1\n h = out;\nend\nend\n\n\nfunction [p,n]=numSubplots(n)\n% function [p,n]=numSubplots(n)\n%\n% Purpose\n% Calculate how many rows and columns of sub-plots are needed to\n% neatly display n subplots.\n%\n% Inputs\n% n - the desired number of subplots.\n%\n% Outputs\n% p - a vector length 2 defining the number of rows and number of\n% columns required to show n plots.\n% [ n - the current number of subplots. This output is used only by\n% this function for a recursive call.]\n%\n%\n%\n% Example: neatly lay out 13 sub-plots\n% >> p=numSubplots(13)\n% p =\n% 3 5\n% for i=1:13; subplot(p(1),p(2),i), pcolor(rand(10)), end\n%\n%\n% Rob Campbell - January 2010\n\n\nwhile isprime(n) && n>4\n n=n+1;\nend\np=factor(n);\nif length(p)==1\n p=[1,p];\n return\nend\nwhile length(p)>2\n if length(p)>=4\n p(1)=p(1)*p(end-1);\n p(2)=p(2)*p(end);\n p(end-1:end)=[];\n else\n p(1)=p(1)*p(2);\n p(2)=[];\n end\n p=sort(p);\nend\n%Reformat if the column/row ratio is too large: we want a roughly\n%square design\nwhile p(2)/p(1)>2.5\n N=n+1;\n [p,n]=numSubplots(N); %Recursive!\nend\n\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "dpsimplify.m", "ext": ".m", "path": "topotoolbox-master/GIStools/dpsimplify.m", "size": 6439, "source_encoding": "utf_8", "md5": "520039e696aaacc7377a4ba3f7f12ebe", "text": "function [ps,ix] = dpsimplify(p,tol)\n\n% Recursive Douglas-Peucker Polyline Simplification, Simplify\n%\n% [ps,ix] = dpsimplify(p,tol)\n%\n% dpsimplify uses the recursive Douglas-Peucker line simplification \n% algorithm to reduce the number of vertices in a piecewise linear curve \n% according to a specified tolerance. The algorithm is also know as\n% Iterative Endpoint Fit. It works also for polylines and polygons\n% in higher dimensions.\n%\n% In case of nans (missing vertex coordinates) dpsimplify assumes that \n% nans separate polylines. As such, dpsimplify treats each line\n% separately.\n%\n% For additional information on the algorithm follow this link\n% http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm\n%\n% Input arguments\n%\n% p polyline n*d matrix with n vertices in d \n% dimensions.\n% tol tolerance (maximal euclidean distance allowed \n% between the new line and a vertex)\n%\n% Output arguments\n%\n% ps simplified line\n% ix linear index of the vertices retained in p (ps = p(ix))\n%\n% Examples\n%\n% 1. Simplify line \n%\n% tol = 1;\n% x = 1:0.1:8*pi;\n% y = sin(x) + randn(size(x))*0.1;\n% p = [x' y'];\n% ps = dpsimplify(p,tol);\n%\n% plot(p(:,1),p(:,2),'k')\n% hold on\n% plot(ps(:,1),ps(:,2),'r','LineWidth',2);\n% legend('original polyline','simplified')\n%\n% 2. Reduce polyline so that only knickpoints remain by \n% choosing a very low tolerance\n%\n% p = [(1:10)' [1 2 3 2 4 6 7 8 5 2]'];\n% p2 = dpsimplify(p,eps);\n% plot(p(:,1),p(:,2),'k+--')\n% hold on\n% plot(p2(:,1),p2(:,2),'ro','MarkerSize',10);\n% legend('original line','knickpoints')\n%\n% 3. Simplify a 3d-curve\n% \n% x = sin(1:0.01:20)'; \n% y = cos(1:0.01:20)'; \n% z = x.*y.*(1:0.01:20)';\n% ps = dpsimplify([x y z],0.1);\n% plot3(x,y,z);\n% hold on\n% plot3(ps(:,1),ps(:,2),ps(:,3),'k*-');\n%\n%\n%\n% Author: Wolfgang Schwanghart, 13. July, 2010.\n% w.schwanghart[at]unibas.ch\n\n\nif nargin == 0\n help dpsimplify\n return\nend\n\nerror(nargchk(2, 2, nargin))\n\n% error checking\nif ~isscalar(tol) || tol<0;\n error('tol must be a positive scalar')\nend\n\n\n% nr of dimensions\nnrvertices = size(p,1); \ndims = size(p,2);\n\n% anonymous function for starting point and end point comparision\n% using a relative tolerance test\ncompare = @(a,b) abs(a-b)/max(abs(a),abs(b)) <= eps;\n\n% what happens, when there are NaNs?\n% NaNs divide polylines.\nInan = any(isnan(p),2);\n% any NaN at all?\nInanp = any(Inan);\n\n% if there is only one vertex\nif nrvertices == 1 || isempty(p);\n ps = p;\n ix = 1;\n\n% if there are two \nelseif nrvertices == 2 && ~Inanp;\n % when the line has no vertices (except end and start point of the\n % line) check if the distance between both is less than the tolerance.\n % If so, return the center.\n if dims == 2;\n d = hypot(p(1,1)-p(2,1),p(1,2)-p(2,2));\n else\n d = sqrt(sum((p(1,:)-p(2,:)).^2));\n end\n \n if d <= tol;\n ps = sum(p,1)/2;\n ix = 1;\n else\n ps = p;\n ix = [1;2];\n end\n \nelseif Inanp;\n \n % case: there are nans in the p array\n % --> find start and end indices of contiguous non-nan data\n Inan = ~Inan;\n sIX = strfind(Inan',[0 1])' + 1; \n eIX = strfind(Inan',[1 0])'; \n \n if Inan(end)==true;\n eIX = [eIX;nrvertices];\n end\n \n if Inan(1);\n sIX = [1;sIX];\n end\n \n % calculate length of non-nan components\n lIX = eIX-sIX+1; \n % put each component into a single cell\n c = mat2cell(p(Inan,:),lIX,dims);\n \n % now call dpsimplify again inside cellfun. \n if nargout == 2;\n [ps,ix] = cellfun(@(x) dpsimplify(x,tol),c,'uniformoutput',false);\n ix = cellfun(@(x,six) x+six-1,ix,num2cell(sIX),'uniformoutput',false);\n else\n ps = cellfun(@(x) dpsimplify(x,tol),c,'uniformoutput',false);\n end\n \n % write the data from a cell array back to a matrix\n ps = cellfun(@(x) [x;nan(1,dims)],ps,'uniformoutput',false); \n ps = cell2mat(ps);\n ps(end,:) = [];\n \n % ix wanted? write ix to a matrix, too.\n if nargout == 2;\n ix = cell2mat(ix);\n end\n \n \nelse\n \n\n% if there are no nans than start the recursive algorithm\nixe = size(p,1);\nixs = 1;\n\n% logical vector for the vertices to be retained\nI = true(ixe,1);\n\n% call recursive function\np = simplifyrec(p,tol,ixs,ixe);\nps = p(I,:);\n\n% if desired return the index of retained vertices\nif nargout == 2;\n ix = find(I);\nend\n\nend\n\n% _________________________________________________________\nfunction p = simplifyrec(p,tol,ixs,ixe)\n \n % check if startpoint and endpoint are the same \n % better comparison needed which included a tolerance eps\n \n c1 = num2cell(p(ixs,:));\n c2 = num2cell(p(ixe,:)); \n \n % same start and endpoint with tolerance\n sameSE = all(cell2mat(cellfun(compare,c1(:),c2(:),'UniformOutput',false)));\n\n \n if sameSE; \n % calculate the shortest distance of all vertices between ixs and\n % ixe to ixs only\n if dims == 2;\n% d = abs(p(ixs,2)-p(ixs+1:ixe-1,2));\n d = hypot(p(ixs,1)-p(ixs+1:ixe-1,1),p(ixs,2)-p(ixs+1:ixe-1,2));\n else\n d = sqrt(sum(bsxfun(@minus,p(ixs,:),p(ixs+1:ixe-1,:)).^2,2));\n end\n else \n % calculate shortest distance of all points to the line from ixs to ixe\n % subtract starting point from other locations\n pt = bsxfun(@minus,p(ixs+1:ixe,:),p(ixs,:));\n\n % end point\n a = pt(end,:)';\n\n beta = (a' * pt')./(a'*a);\n b = pt-bsxfun(@times,beta,a)';\n if dims == 2;\n % if line in 2D use the numerical more robust hypot function\n% d = abs(b(:,2));\n d = hypot(b(:,1),b(:,2));\n else\n d = sqrt(sum(b.^2,2));\n end\n end\n \n % identify maximum distance and get the linear index of its location\n [dmax,ixc] = max(d);\n ixc = ixs + ixc; \n \n % if the maximum distance is smaller than the tolerance remove vertices\n % between ixs and ixe\n if dmax <= tol;\n if ixs ~= ixe-1;\n I(ixs+1:ixe-1) = false;\n end\n % if not, call simplifyrec for the segments between ixs and ixc (ixc\n % and ixe)\n else \n p = simplifyrec(p,tol,ixs,ixc);\n p = simplifyrec(p,tol,ixc,ixe);\n\n end\n\nend\nend\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "zonalstats.m", "ext": ".m", "path": "topotoolbox-master/GIStools/zonalstats.m", "size": 8482, "source_encoding": "utf_8", "md5": "53cb779cf9fd2ddfaa01d6a5fcbb1d18", "text": "function MS = zonalstats(MS,attributes,varargin)\n\n%ZONALSTATS Zonal statistics\n%\n% Syntax\n%\n% MS = zonalstats(MS)\n% MS = zonalstats(MS,{varname1, vargrid1, varfun1, ...\n% varname2, vargrid1, varfun2, ...})\n% MS = zonalstats(MS,{varname1, vargrid1, varfun1, ...\n% varname2, vargrid1, varfun2, ...},...\n% pn,pv,...)\n%\n% Description\n%\n% MS = zonalstats(MS) will add a new field 'area' to the mapping \n% structure MS that includes the area (calculated by the function \n% polyarea). \n%\n% MS = zonalstats(MS,{varname1, vargrid1, varfun1, ...\n% varname2, vargrid2, varfun2, ...}) calculates\n% zonal statistics for GRIDobjs vargrid1, vargrid2, ... using the\n% anonymous functions varfun1, ... and returns the values to a new\n% field in MS entitled varname1, ... . If varfunX is empty, zonalstats\n% will return several fields for the respective vargridX calculated by\n% numerous functions (mean, std, median, percentiles, skewness,\n% kurtosis, etc.).\n%\n% MS = zonalstats(...,pn,pv) allows setting a number of options (see\n% below)\n% \n% Note: The function adds a field 'TTID' (TopoToolbox ID) to the output\n% mapping structure.\n%\n% Input parameters\n%\n% MS polygon mapping structure (e.g. shapefile imported by the\n% function shaperead). The coordinate system must be equal to\n% the grids' projections and should be a projected coordinate\n% system with metric units.\n% {varname1, vargrid1, varfun1, ...} cell array with triplets of\n% variable names, grids and aggregation functions. E.g.\n% {'z' DEM @mean} will create a new field MS.z in MS that \n% contains the averages of values in DEM within the polygons \n% defined by MS. If you provide an empty array as varfun1, \n% zonalstats will calculate several aggregating functions for\n% the respective grid. In this case, zonalstats will create \n% multiple new fields in MS whose naming starts with varname1\n% followed by underscore _ and abbreviations of the aggregating\n% functions (e.g. z_mean, z_std, z_min, etc.).\n%\n% Parameter name/value functions\n%\n% 'overlapping' true or {false}. Set to false if polygons in MS are not\n% overlapping. This will signicantly increase the speed\n% of the function.\n% 'centroid' true or {false}. True will add the fields xc and yc to \n% MS that contain the x and y coordinates of the\n% centroids, respectively.\n% Note that centroid is currently calculated based on\n% the vertex coordinates. Nonuniform spacing between\n% vertices will bias the centroid.\n% 'area' true or {false}. True will calculate the area of the\n% polygons in MS in horizontal units of MS.\n% 'perimeter' true or {false}. True will calculate the perimeter of \n% the polygons in MS in horizontal units of MS.\n% 'bbox' true or {false}. True will add eight attributes to the\n% resulting structure array: lucornerx, lucornery,\n% llcornerx, llcornery, ...\n% 'lucorner' true or {false} calculates the coordinates of the left \n% upper corner of the axis-aligned bounding box of the\n% region. Same can be used for llcorner, rucorner, etc.\n% 'waitbar' {true} or false. \n%\n% Output arguments\n%\n% MS mapping structure with zonal statistics\n%\n% \n% See also: polygon2GRIDobj\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 22. September, 2022\n\nif nargin == 1\n a = cellfun(@(x,y) getarea(x,y),{MS.X},{MS.Y},'UniformOutput',false);\n [MS.area] = a{:};\n return\nend\n\n% check attributes\nif mod(numel(attributes),3) ~= 0\n error('additional arguments must come in triplets')\nend\n\n% check the attributes\nattname = attributes(1:3:end);\nattgrid = attributes(2:3:end);\nattfun = attributes(3:3:end);\nnrattributes = numel(attributes)/3;\n\np = inputParser;\naddParameter(p,'overlapping',false)\naddParameter(p,'centroid',false)\naddParameter(p,'area',false)\naddParameter(p,'perimeter',false)\naddParameter(p,'bbox',false);\naddParameter(p,'lucorner',false);\naddParameter(p,'llcorner',false);\naddParameter(p,'rucorner',false);\naddParameter(p,'rlcorner',false);\naddParameter(p,'waitbar',false)\n\nparse(p,varargin{:});\n \n% convert strings to functions, if necessary\nfor r = 1:nrattributes\n if ischar(attfun{r}) && ~isempty(attfun{r})\n attfun{r} = str2func(attfun{r});\n elseif isempty(attfun{r})\n % do nothing\n end\n \n if r > 2\n validatealignment(attgrid{r},attgrid{1});\n end\n \nend\n\nif p.Results.area\n a = cellfun(@(x,y) getarea(x,y),{MS.X},{MS.Y},'UniformOutput',false);\n [MS.area] = a{:};\nend\nif p.Results.centroid\n [xc,yc] = cellfun(@(x,y) getcentroid(x,y),{MS.X},{MS.Y},'UniformOutput',false);\n [MS.xc] = xc{:};\n [MS.yc] = yc{:};\nend\nif p.Results.perimeter\n per = cellfun(@(x,y) getperimeter(x,y),{MS.X},{MS.Y},'UniformOutput',false);\n [MS.perimeter] = per{:};\nend\n\nif p.Results.lucorner || p.Results.bbox\n xc = cellfun(@(x) min(x),{MS.X},'UniformOutput',false);\n yc = cellfun(@(y) max(y),{MS.Y},'UniformOutput',false);\n [MS.lucornerx] = xc{:};\n [MS.lucornery] = yc{:};\nend\n\nif p.Results.rucorner || p.Results.bbox\n xc = cellfun(@(x) max(x),{MS.X},'UniformOutput',false);\n yc = cellfun(@(y) max(y),{MS.Y},'UniformOutput',false);\n [MS.rucornerx] = xc{:};\n [MS.rucornery] = yc{:};\nend\n \nif p.Results.llcorner || p.Results.bbox\n xc = cellfun(@(x) min(x),{MS.X},'UniformOutput',false);\n yc = cellfun(@(y) min(y),{MS.Y},'UniformOutput',false);\n [MS.llcornerx] = xc{:};\n [MS.llcornery] = yc{:};\nend\n\nif p.Results.rlcorner || p.Results.bbox\n xc = cellfun(@(x) max(x),{MS.X},'UniformOutput',false);\n yc = cellfun(@(y) min(y),{MS.Y},'UniformOutput',false);\n [MS.rlcornerx] = xc{:};\n [MS.rlcornery] = yc{:};\nend\n\nif ~p.Results.overlapping\n TTID = num2cell(uint32(1:numel(MS)));\n [MS.TTID] = TTID{:};\n label = polygon2GRIDobj(attributes{2},MS,'field','TTID','waitbar',false);\n TTID = num2cell((1:numel(MS)));\n [MS.TTID] = TTID{:};\n stats = regionprops(label.Z,'PixelIdxList');\nend\n\n\n\nnr = numel(MS);\n\nif nr >= 2 && p.Results.waitbar\nh = waitbar(0,['0 processed, ' num2str(nr) ' remaining']);\nwb = true;\nelse\nwb = false;\nend\nfor r = 1:nr\n \n if p.Results.overlapping\n II = polygon2GRIDobj(attgrid{1},MS(r),'waitbar',false);\n I = II.Z;\n else\n I = stats(r).PixelIdxList;\n end\n \n for r2 = 1:nrattributes\n if ~isempty(attfun{r2})\n MS(r).(attname{r2}) = attfun{r2}(double(attgrid{r2}.Z(I))); \n else\n z = attgrid{r2}.Z(I);\n z = double(z(:));\n z(isnan(z)) = [];\n MS(r).([attname{r2} '_mean']) = mean(z);\n MS(r).([attname{r2} '_std']) = std(z);\n minz = min(z);\n maxz = max(z);\n if isempty(minz); minz = nan; end\n if isempty(maxz); maxz = nan; end\n MS(r).([attname{r2} '_min']) = minz;\n MS(r).([attname{r2} '_max']) = maxz;\n MS(r).([attname{r2} '_median']) = median(z);\n prc = quantile(z,[.01 .05 .33 .66 .95 .99]);\n MS(r).([attname{r2} '_prc01']) = prc(1);\n MS(r).([attname{r2} '_prc05']) = prc(2);\n MS(r).([attname{r2} '_prc33']) = prc(3);\n MS(r).([attname{r2} '_prc66']) = prc(4);\n MS(r).([attname{r2} '_prc95']) = prc(5);\n MS(r).([attname{r2} '_prc99']) = prc(6);\n MS(r).([attname{r2} '_skew']) = skewness(z);\n MS(r).([attname{r2} '_kurt']) = kurtosis(z);\n end\n end\n if wb\n waitbar(r/nr,h,[num2str(r) ' processed, ' num2str(nr-r) ' remaining']);\n end\nend\n\nif wb\nclose(h)\nend\n\n\n\n\nend\n\nfunction a = getarea(x,y)\nI = ~isnan(x);\na = double(polyarea(x(I),y(I)));\nend\n\nfunction [xc,yc] = getcentroid(x,y)\n\nI = ~isnan(x);\n[xc,yc] = centroid(polyshape(x(I),y(I)));\n\n% xc = double(mean(x(I)));\n% yc = double(mean(y(I)));\nend\n\nfunction p = getperimeter(x,y)\nI = ~isnan(x);\nxd = diff(x(I));\nyd = diff(y(I));\n\np = double(sum(hypot(xd,yd)));\n\nend"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "readopentopo.m", "ext": ".m", "path": "topotoolbox-master/IOtools/readopentopo.m", "size": 10992, "source_encoding": "utf_8", "md5": "d96ec589591c68696b47acb6acc3f01d", "text": "function DEM = readopentopo(varargin)\n\n%READOPENTOPO Read DEM using the opentopography.org API\n%\n% Syntax\n%\n% DEM = readopentopo(pn,pv,...)\n%\n% Description\n%\n% readopentopo reads DEMs from opentopography.org using the API\n% described on:\n% http://www.opentopography.org/developers\n% The DEM comes in geographic coordinates (WGS84) and should be\n% projected to a projected coordinate system (use reproject2utm) before\n% analysis in TopoToolbox.\n%\n% NOTE: Starting on January 1st, 2022, an API authorization key will be \n% required for this API. Users can request an API key via myOpenTopo in \n% the OpenTopography portal (https://opentopography.org/developers).\n%\n% Input arguments\n%\n% Parameter name values\n% 'interactive' {true} or false. If true, readopentopo will open a\n% GUI that enables interactive selection. If true,\n% then any given extent options will be ignored.\n% 'filename' provide filename. By default, the function will save\n% the DEM to a temporary file in the system's temporary \n% folder. The option 'deletefile' controls whether the\n% file is kept on the hard drive.\n% 'extent' GRIDobj or four element vector with geographical \n% coordinates in the order [west east south north].\n% If a GRIDobj is supplied, readopentopo uses the\n% function GRIDobj/getextent to obtain the bounding\n% box in geographical coordinates. If extent is set,\n% then the following parameter names 'north',\n% 'south', ... are ignored.\n% 'addmargin' Expand the extent derived from 'extent',GRIDobj by a\n% scalar value in °. Default is 0.01. The option is\n% only applicable if extent is provided by a GRIDobj.\n% 'north' northern boundary in geographic coordinates (WGS84).\n% The option is ignored if the option 'extent' is\n% provided or if 'interactive', true.\n% 'south' southern boundary\n% 'west' western boundary\n% 'east' eastern boundary\n% 'demtype' The global raster dataset *\n% {'SRTMGL3'}: SRTM GL3 (90m) (default)\n% 'SRTMGL1': SRTM GL1 (30m) \n% 'SRTMGL1_E': SRTM GL1 (Ellipsoidal) \n% 'AW3D30': ALOS World 3D 30m \n% 'AW3D30_E': ALOS World 3D (Ellipsoidal)\n% 'SRTM15Plus': Global Bathymetry SRTM15+ V2.1 (only \n% mediterranean area so far)\n% 'NASADEM': NASADEM Global DEM \n% 'COP30': Copernicus Global DSM 30m \n% 'COP90': Copernicus Global DSM 90m \n% 'EU_DTM: Continental Europe Digital Terrain \n% Model \n% 'GEDI_L3': Global Ecosystem Dynamics \n% Investigation 1x1 km DTM\n% \n% * requires API Key (see option 'apikey').\n%\n% 'apikey' char or string. Users can request an API key via \n% myOpenTopo in the OpenTopography portal. You can\n% also create a text file in the folder IOtools named\n% opentopography.apikey which must contain the API\n% Key. If there is a file that contains the key, there \n% is no need to provide it here.\n% 'verbose' {true} or false. If true, then some information on\n% the process is shown in the command window.\n% 'checkrequestlimit' {true} or false. Opentopography implements\n% request limits. If the chose extent exceeds the \n% request limit, readopentopo will issue an error. If\n% this option is set to false, readopentopo will try\n% to download.\n% 'deletefile' {true} or false. True, if file should be deleted\n% after it was downloaded and added to the workspace.\n% \n% Output arguments\n%\n% DEM Digital elevation model in geographic coordinates\n% (GRIDobj)\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% DEM2 = readopentopo('extent',DEM);\n% DEM2 = reproject2utm(DEM2,90);\n% imagesc(DEM2)\n% hold on\n% getoutline(DEM)\n% hold off\n%\n% See also: GRIDobj, websave, roipicker\n%\n% Reference: http://www.opentopography.org/developers\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 13. February, 2023\n\n\np = inputParser;\naddParameter(p,'filename',[tempname '.tif']);\naddParameter(p,'interactive',true);\naddParameter(p,'extent',[]);\naddParameter(p,'addmargin',0.01);\naddParameter(p,'north',37.091337);\naddParameter(p,'south',36.738884);\naddParameter(p,'west',-120.168457);\naddParameter(p,'east',-119.465576);\naddParameter(p,'demtype','SRTMGL3');\naddParameter(p,'deletefile',true);\naddParameter(p,'verbose',true);\naddParameter(p,'apikey',[]);\naddParameter(p,'checkrequestlimit',true)\nparse(p,varargin{:});\n\nvaliddems = {'SRTMGL3','SRTMGL1','SRTMGL1_E',...\n 'AW3D30','AW3D30_E','SRTM15Plus',...\n 'NASADEM','COP30','COP90',...\n 'EU_DTM','GEDI_L3'};\n\ndemtype = validatestring(p.Results.demtype,...\n validdems,'readopentopo');\n\n% Access global topographic datasets including SRTM GL3 (Global 90m), \n% GL1 (Global 30m), ALOS World 3D and SRTM15+ V2.1 (Global Bathymetry 500m). \n% Note: Requests are limited to 125,000,000 km2 for SRTM15+ V2.1, \n% 4,050,000 km2 for SRTM GL3, COP90 and 450,000 km2 for all other data.\nrequestlimits = [4.05e6, 0.45e6, 0.45e6, ...\n 0.45e6, 0.45e6, 125e6,...\n 0.45e6, 0.45e6, 4.05e6, ...\n 0.45e6 50e7]; % km^2\nrequestlimit = requestlimits(strcmp(demtype,validdems));\n\n% API URL\nurl = 'https://portal.opentopography.org/API/globaldem?';\n\n% create output file\nf = fullfile(p.Results.filename);\n\n% check api\n\nif isempty(p.Results.apikey)\n % check whether file opentopography.apikey is available\n if exist('opentopography.apikey','file')\n fid = fopen('opentopography.apikey');\n apikey = textscan(fid,'%c');\n apikey = apikey{1}';\n % Remove trailing blanks, if there are any\n apikey = deblank(apikey);\n else\n error('Readopentopo requires an API Key. Please read the help.')\n end\nelse\n apikey = p.Results.apikey;\nend\n\n\n% save to drive\noptions = weboptions('Timeout',100000);\n\n% get extent\nif ~isempty(p.Results.extent)\n if isa(p.Results.extent,'GRIDobj')\n ext = getextent(p.Results.extent,true);\n west = ext(1) - p.Results.addmargin;\n east = ext(2) + p.Results.addmargin;\n south = ext(3) - p.Results.addmargin;\n north = ext(4) + p.Results.addmargin;\n \n elseif numel(p.Results.extent) == 4\n west = p.Results.extent(1);\n east = p.Results.extent(2);\n south = p.Results.extent(3);\n north = p.Results.extent(4);\n else\n error('Unknown format of extent')\n end\nelse\n west = p.Results.west;\n east = p.Results.east;\n south = p.Results.south;\n north = p.Results.north;\nend\n\n% now we have an extent. Or did the user request interactively choosing\n% the extent.\nif any([isempty(west) isempty(east) isempty(south) isempty(north)]) || p.Results.interactive\n if p.Results.interactive == 2\n wm = webmap;\n % get dialog box\n messagetext = ['Zoom and resize the webmap window to choose DEM extent. ' ...\n 'Click the close button when you''re done.'];\n d = waitdialog(messagetext);\n uiwait(d);\n [latlim,lonlim] = wmlimits(wm);\n west = lonlim(1);\n east = lonlim(2);\n south = latlim(1);\n north = latlim(2);\n else\n ext = roipicker('requestlimit',requestlimit);\n if isempty(ext)\n DEM = [];\n return\n end\n west = ext(2);\n east = ext(4);\n south = ext(1);\n north = ext(3);\n end\nend\n\n% Check request limit\na = areaint([south south north north],...\n [west east east west],...\n almanac('earth','radius','kilometers'));\n\nif p.Results.checkrequestlimit && (a > requestlimit)\n error('TopoToolbox:readopentopo',...\n ['Request limit (' num2str(requestlimit) ' km^2) exceeded.\\n'...\n 'Your extent is ' num2str(a,1) ' km^2. Choose a smaller area.' ])\nend\n\nif p.Results.verbose\n\n disp('-------------------------------------')\n disp('readopentopo process:')\n disp(['DEM type: ' demtype])\n disp(['API url: ' url])\n disp(['Local file name: ' f])\n disp(['Area: ' num2str(a,2) ' sqkm'])\n disp('-------------------------------------')\n disp(['Starting download: ' datestr(now)])\nend\n\n% Download with websave\nif isempty(apikey)\n outfile = websave(f,url,'west',west,...\n 'east',east,...\n 'north',north,...\n 'south',south,...\n 'outputFormat', 'GTiff', ...\n 'demtype', demtype, ...\n options);\nelse\n outfile = websave(f,url,'west',west,...\n 'east',east,...\n 'north',north,...\n 'south',south,...\n 'outputFormat', 'GTiff', ...\n 'demtype', demtype, ...\n 'API_Key',apikey,...\n options);\nend\n\nif p.Results.verbose\n disp(['Download finished: ' datestr(now)])\n disp(['Reading DEM: ' datestr(now)])\nend\n\ntry\n warning off\n DEM = GRIDobj(f);\n warning on\n \n msg = lastwarn;\n if ~isempty(msg)\n disp(' ')\n disp(msg)\n disp(' ')\n end\n \n DEM.name = demtype;\n if p.Results.verbose\n disp(['DEM read: ' datestr(now)])\n end\n \ncatch\n % Something went wrong. See whether we can derive some information.\n fid = fopen(outfile);\n in = textscan(fid,'%c');\n disp('Could not retrieve DEM. This is the message returned by opentopography API:')\n disp([in{1}]')\n disp('readopentopo returns empty array')\n fclose(fid);\n DEM = [];\nend\n \n\nif p.Results.deletefile\n delete(f);\n if p.Results.verbose\n disp('Temporary file deleted')\n end\nend\n\nif p.Results.verbose\n disp(['Done: ' datestr(now)])\n disp('-------------------------------------')\nend\nend\n\nfunction d = waitdialog(messagetext)\n d = dialog('Position',[300 300 250 150],'Name','Choose rectangle region',...\n 'WindowStyle','normal');\n\n txt = uicontrol('Parent',d,...\n 'Style','text',...\n 'Position',[20 80 210 40],...\n 'String',messagetext);\n\n btn = uicontrol('Parent',d,...\n 'Position',[85 20 70 25],...\n 'String','Close',...\n 'Callback','delete(gcf)');\nend\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "FLOWobj2cell.m", "ext": ".m", "path": "topotoolbox-master/@FLOWobj/FLOWobj2cell.m", "size": 1882, "source_encoding": "utf_8", "md5": "71c4541d170224c2ef6dc4d5e647e544", "text": "function [CFD,D,A,cfix] = FLOWobj2cell(FD,IX)\n\n%FLOWOBJ2CELL return cell array of FLOWobjs for individual drainage basins\n%\n% Syntax\n%\n% CF = FLOWobj2cell(FD)\n% [CF,D,a] = FLOWobj2cell(FD)\n% [CF,D,a,cfix] = FLOWobj2cell(FD,IX)\n%\n% Description\n%\n% FLOWobj2cell derives a cell array of FLOWobjs for each individual\n% drainage basin. This may be required if computations on individual\n% drainage basins should be run in parallel.\n%\n% Input arguments\n%\n% FD FLOWobj\n% IX linear index in GRIDobj from which FD was derived. If IX is\n% provided, the function returns a forth output argument that\n% indicates in which of the flow networks (FLOWobjs) in the\n% output cell array IX is located.\n%\n% Output arguments\n%\n% CF cell array of FLOWobjs\n% D GRIDobj with drainage basins\n% a area of drainage basins (unit = nr of pixels)\n% cfix (see input argument IX)\n%\n% Example\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% [CFD,~,a] = FLOWobj2cell(FD);\n% [~,ix] = max(a);\n% A = flowacc(CFD{ix});\n% imageschs(DEM,log(A))\n%\n% See also: FLOWobj, STREAMobj/STREAMobj2cell\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]geo.uni-potsdam.de)\n% Date: 9. January, 2015\n\nD = drainagebasins(FD);\nnrd = max(D);\ndix = D.Z(FD.ix);\n[dix,I] = sort(dix,'ascend');\n\nif nargin == 2\n cfix = D.Z(IX);\nend\n\nif nargin == 1 && nargout == 4\n error('a forth output argument is only allowed for two input arguments');\nend\n\n\n\nFDcopy = FD;\nFDcopy.ix = [];\nFDcopy.ixc = [];\n\nIX = (1:numel(FD.ix))';\n\nCFD = accumarray(dix,IX(I),[nrd 1],@distribute2FLOWobj);\nif nargout > 2\n A = cellfun(@(FD) numel(FD.ix)+1,CFD);\nend\n\nfunction FO = distribute2FLOWobj(IX)\n\nFO = FDcopy;\nFO.ix = FD.ix(IX);\nFO.ixc = FD.ixc(IX);\nFO = {FO};\nend\nend\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "flow_matrix.m", "ext": ".m", "path": "topotoolbox-master/@FLOWobj/private/flow_matrix.m", "size": 10451, "source_encoding": "utf_8", "md5": "7ad31c1c00660f3f2280acc9832bdce9", "text": "function T = flow_matrix(E, R, d1, d2)\n%flow_matrix System of linear equations representing pixel flow\n%\n% T = flow_matrix(E, R) computes a sparse linear system representing flow from\n% pixel to pixel in the DEM represented by the matrix of height values, E. R\n% is the matrix of pixel flow directions as computed by dem_flow. T is\n% numel(E)-by-numel(E). The value T(i,j) is the negative of the fractional\n% flow from pixel j to pixel i, where pixels are numbered columnwise. For\n% example, if E is 15-by-10, then T is 150-by-150, and T(17,18) is the\n% negative of the fractional flow from pixel 18 (row 3, column 2) to pixel 17\n% (row 2, column 2).\n%\n% d1 is the horizontal pixel spacing. d2 is the vertical pixel spacing. d1\n% and d2 are optional; if omitted, a value of 1.0 is assumed.\n%\n% Note: Connected groups of NaN pixels touching the border are treated as\n% having no contribution to flow.\n%\n% Reference: Tarboton, \"A new method for the determination of flow\n% directions and upslope areas in grid digital elevation models,\" Water\n% Resources Research, vol. 33, no. 2, pages 309-319, February 1997. \n%\n% Example\n% -------\n%\n% E = peaks;\n% R = dem_flow(E);\n% T = flow_matrix(E, R);\n% spy(T)\n%\n% See also dem_flow, dependency_map, influence_map, upslope_area.\n\n% Steven L. Eddins\n% Copyright 2007 The MathWorks, Inc.\n% $Revision: 1.4 $ $Date: 2008/02/14 15:49:21 $\n\nif nargin < 4\n d1 = 1;\n d2 = 1;\nend\n\n[M, N] = size(R);\nnrc = numel(R);\n\n% Label the pixels.\npixel_labels = reshape(1:numel(R), M, N);\n\n% What are the rows and columns of the pixels that have a north neighbor?\nhave_neighbor.north.rows = 2:M;\nhave_neighbor.north.cols = 1:N;\n\n% What are the rows and columns of the pixels that have a northeast\n% neighbor?\nhave_neighbor.northeast.rows = 2:M;\nhave_neighbor.northeast.cols = 1:N-1;\n\n% And so on...\nhave_neighbor.east.rows = 1:M;\nhave_neighbor.east.cols = 1:N-1;\n\nhave_neighbor.southeast.rows = 1:M-1;\nhave_neighbor.southeast.cols = 1:N-1;\n\nhave_neighbor.south.rows = 1:M-1;\nhave_neighbor.south.cols = 1:N;\n\nhave_neighbor.southwest.rows = 1:M-1;\nhave_neighbor.southwest.cols = 2:N;\n\nhave_neighbor.west.rows = 1:M;\nhave_neighbor.west.cols = 2:N;\n\nhave_neighbor.northwest.rows = 2:M;\nhave_neighbor.northwest.cols = 2:N;\n\n% What are the linear index offsets corresponding to each of the neighbors?\noffset.north = -1;\noffset.northeast = M - 1;\noffset.east = M;\noffset.southeast = M + 1;\noffset.south = 1;\noffset.southwest = -M + 1;\noffset.west = -M;\noffset.northwest = -M - 1;\n\ndirections = {'north', 'northeast', 'east', 'southeast', ...\n 'south', 'southwest', 'west', 'northwest'};\n\n% Initialize the index and value vectors that will be used to construct the\n% sparse array.\nii = [];\njj = [];\nvv = [];\n\nfor k = 1:numel(directions)\n direction = directions{k};\n \n i = pixel_labels(have_neighbor.(direction).rows, ...\n have_neighbor.(direction).cols);\n j = i + offset.(direction);\n p = -directional_weight(direction, R(j), d1, d2);\n \n non_zero_weight = p ~= 0;\n \n ii = [ii; i(non_zero_weight)]; %#ok\n jj = [jj; j(non_zero_weight)]; %#ok\n vv = [vv; p(non_zero_weight)]; %#ok\nend\n \n% Filter out weights calculated for border NaN pixels.\nborder_mask = border_nans(E);\nborder_labels = pixel_labels(border_mask);\ndelete_mask = ismember(ii, border_labels) | ...\n ismember(jj, border_labels);\nii(delete_mask) = [];\njj(delete_mask) = [];\nvv(delete_mask) = [];\n\n% The weight for the pixel itself is 1.\n% ii = [ii; pixel_labels(:)];\n% jj = [jj; pixel_labels(:)];\n% vv = [vv; ones(numel(R), 1)];\n\n[ip, jp, vp] = plateau_flow_weights(E, R, border_mask);\n\nii = [ii; ip];\njj = [jj; jp];\nvv = [vv; vp];\n\n% Construct the sparse array representing the system of linear pixel flow\n% equations.\n\nT = sparse(ii, jj, double(vv),nrc,nrc);\n\n%==========================================================================\nfunction [ip, jp, vp] = plateau_flow_weights(E, R, border_mask)\n%\n% For the pixels with no assigned flow direction (marked in R with NaN), compute\n% how their flow is to be distributed to their neighbors. The output vectors\n% (ip, jp, and vp) are intended to be used in the formation of a sparse linear\n% system. T(i, j) = v indicates that the fraction -v of the flow from pixel j\n% should be directed to pixel i.\n%\n% Pixels with no flow direction that are part of regional minima do not\n% distribute any flow to their neighbors.\n%\n% The algorithm was inspired by the \"arrowing\" algorithm described in\n% F. Meyer, \"Skeletons and Perceptual Graphs,\" Signal Processing 16 (1989)\n% 335-363. See Appendix A.2, Arrowing, on pages 360-361.\n%\n% Flow allocations are computed iteratively. In each iteration, find all the\n% pixels that have no computed flow, and that have equal-valued neighbors\n% with a previously computed flow. Distribute pixel flow equally among these\n% neighbors. Continue until all pixels have been assigned a flow\n% distribution, except for those belonging to regional minima.\n\nS = size(R);\n\n% Replace border NaNs with Inf. imregionalmin, used below, doesn't like\n% NaNs in its input.\nE(border_mask) = Inf;\n\n% Initialize list of pixels whose flow is marked NaN. Don't include pixels\n% that belong to regional minima, and don't include pixels that are\n% border NaNs in E.\n[nan_list_r, nan_list_c] = find(isnan(R) & ~imregionalmin(E) & ...\n ~border_mask);\n\ndone = false;\n\nnum_nans = numel(nan_list_r);\nip = zeros(8*num_nans, 1);\njp = zeros(8*num_nans, 1);\nvp = zeros(8*num_nans, 1);\ntotal_count = 0;\n\nwhile ~done\n done = true;\n\n % Use this variable to keep track of pixels that won't need to be visited\n % in the next iteration of the while loop.\n delete_from_list = false(numel(nan_list_r), 1);\n\n % Use rr and cc to track the locations in R that should be set to 0 at\n % the end of this loop iteration.\n rr = zeros(numel(nan_list_r), 1);\n cc = zeros(numel(nan_list_c), 1);\n \n % Use ww and zz to track the set of neighbors that should receive\n % flow from a given pixel.\n ww = zeros(8,1);\n zz = zeros(8,1);\n nan_count = 0;\n for k = 1:numel(nan_list_r)\n r = nan_list_r(k);\n c = nan_list_c(k);\n\n % Find all neighbors (w,z) of (r,c) for which R(w,z) is not NaN, and\n % for which E(w,z) = E(r,c). Count how many there are and record\n % their locations. Pixel flow will be distributed to all such\n % neighbors equally.\n neighbor_count = 0;\n for w = max(1, r-1) : min(S(1), r+1)\n for z = max(1, c-1) : min(S(2), c+1)\n if ~isnan(R(w,z)) && (E(r,c) == E(w,z))\n neighbor_count = neighbor_count + 1;\n ww(neighbor_count) = w;\n zz(neighbor_count) = z;\n end\n end\n end\n \n if neighbor_count > 0\n % We haven't converged. At least one more execution of the while\n % loop will be required.\n done = false;\n \n nan_count = nan_count + 1;\n rr(nan_count) = r;\n cc(nan_count) = c;\n\n % Compute indices and values to be added to ip, jp, and vp. i\n % contains the linear indices of the neigbhors of (r,c). j\n % contains the linear index of (r,c), copied neighbor_count\n % times. v is calculated so that each neighbor gets an equal\n % share of the pixel flow from (r,c).\n i = (zz(1:neighbor_count) - 1)*S(1) + ww(1:neighbor_count);\n j = ((c - 1)*S(1) + r) * ones(neighbor_count, 1);\n v = -ones(neighbor_count, 1) / neighbor_count;\n \n slots = total_count + (1:neighbor_count);\n ip(slots) = i;\n jp(slots) = j;\n vp(slots) = v;\n total_count = total_count + neighbor_count;\n \n delete_from_list(k) = true;\n end\n end\n rr = rr(1:nan_count);\n cc = cc(1:nan_count);\n \n if ~done\n nan_list_r(delete_from_list) = [];\n nan_list_c(delete_from_list) = [];\n \n R((cc - 1)*S(1) + rr) = 0;\n end\nend\n\nip = ip(1:total_count);\njp = jp(1:total_count);\nvp = vp(1:total_count);\n%--------------------------------------------------------------------------\n\n%==========================================================================\nfunction w = directional_weight(direction, R, d1, d2)\n%\n% Given a direction (from pixel to neighbor), and an array of neighbor flow\n% directions, R, compute the corresponding pixel flow weights.\n%\n% See column 1, page 313 of the Tarboton paper.\n\n% Arrange the angles from a pixel to its neighbor in a counterclockwise\n% (increasing angle) sequence.\ntheta_d = atan2(d2, d1);\nangles = [0, theta_d, pi/2, pi-theta_d, pi, -pi+theta_d, -pi/2, -theta_d];\ndirection_indices = struct('east', 1, 'northeast', 2, 'north', 3, ...\n 'northwest', 4, 'west', 5, 'southwest', 6, ...\n 'south', 7, 'southeast', 8);\n\n\ninward_direction_index = mod(direction_indices.(direction) + 3, 8) + 1;\ninward_direction_index_plus_1 = mod(inward_direction_index, 8) + 1;\ninward_direction_index_minus_1 = mod(inward_direction_index - 2, 8) + 1;\n\ninward_angle = angles(inward_direction_index);\nnext_inward_angle = angles(inward_direction_index_plus_1);\nprev_inward_angle = angles(inward_direction_index_minus_1);\n\ninterp_table_x = [-angular_difference(inward_angle, prev_inward_angle), ...\n 0, ...\n angular_difference(next_inward_angle, inward_angle)];\ninterp_table_y = [0 1 0];\n\nw = interp1(interp_table_x, interp_table_y, angular_difference(R, inward_angle));\nw(isnan(w)) = 0;\n%--------------------------------------------------------------------------\n\n%==========================================================================\nfunction d = angular_difference(theta1, theta2)\n%\n% Given arrays of angles in radians, calculate the absolute angular differences\n% between the values in theta1 and the values in theta2. Return the difference\n% values in the half-open interval [-pi, pi).\n%\n% Remove multiples of 2*pi in the difference calculation. In other words,\n% angular_difference(0,4*pi) returns 0, and angular_difference(0,2*pi + pi/4)\n% returns -pi/4.\n\nd = mod(theta1 - theta2 + pi, 2*pi) - pi;\n%--------------------------------------------------------------------------\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "routeflats.m", "ext": ".m", "path": "topotoolbox-master/@FLOWobj/private/routeflats.m", "size": 5974, "source_encoding": "utf_8", "md5": "411ad344f47b1cadb9c82e6c107a56eb", "text": "function [IXf,IXn] = routeflats(dem,type)\n\n% route through flats of a digital elevation model\n%\n% Syntax\n%\n% [IXf,IXn] = routeflats(dem,type)\n%\n% Description\n%\n% routeflats is a subroutine used by some of the flowdirection \n% algorithms in the toolbox. routeflats recursively creates flow paths\n% through flat terrain. The user may choose between single and multiple\n% flow routing. The output are vectors containing linear indices of\n% connected cells along the flow direction. IXn are the downstream\n% neighbors of IXf.\n%\n% Input\n% \n% dem digital elevation model\n% type string for flow routing method ('single' (default) or\n% 'multi')\n%\n% Output\n% \n% IXf vector containing linear indices of cells in flats\n% IXn vector containing linear indices of downstream neighbors\n% of IXf\n%\n%\n% See also: CROSSFLATS\n%\n%\n% Author: Wolfgang Schwanghart (w.schwanghart[at]unibas.ch)\n% Date: 17. June, 2010\n\n\n\n% type: 'single' or 'multi'\ntype = lower(type);\n\n% floating-point relative accuracy\nfpra = eps(dem) * 2;\nfillval = min(dem(:))-max(fpra(:));\n\n% kernel (8-Neighborhood)\nnhood = ones(3,3);\nsiz = size(dem);\n\n% handle NaNs\nlog_nans = isnan(dem);\nif any(log_nans(:));\n flag_nans = true;\nelse\n flag_nans = false;\nend\n\n% if there are nans.\nif flag_nans \n dem(log_nans) = -inf;\nend\n\n% identify flats\n% flats: logical matrix with true where cells don't have lower neighbors\nif flag_nans\n flats = imerode(dem,nhood) == dem & ~log_nans;\nelse\n flats = imerode(dem,nhood) == dem;\nend\n\n% remove regional minima\nflats(imregionalmin(dem)) = false;\n\n% if there are nans.\nif flag_nans \n dem(log_nans) = fillval;\nend\n\n% remove flats at the border\nflats(:,[1 2 end-1 end]) = false;\nflats([1 2 end-1 end],:) = false;\n\n% any flats there? If yes, start recursive flat routing\nif any(flats(:));\n II = true;\n \n switch type\n case 'single'\n [IXf,IXn] = routeflatssingle(flats);\n \n case 'multi' \n [IXf,IXn] = routeflatsmulti(flats);\n \n otherwise\n IXf = [];\n IXn = [];\n end\n \n if flag_nans\n IXf(log_nans(IXn)) = [];\n IXn(log_nans(IXn)) = [];\n end\nelse\n IXf = [];\n IXn = [];\nend \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions\nfunction [ic,icd] = routeflatssingle(flats)\n% recursive routing through flats using single flow direction\n%\n% [ic,icd] = routeflatssingle(flats)\n\n\n% linear indices of flat cells\nic = find(flats);\n% number of flat cells\nnrcf = numel(ic);\n% create nan array that will be filled with downstream\n% neigbors of indices in ic in\n% the subsequent lines of codes \nicd = nan(nrcf,1);\n\n% inner border in flats\n% finline = bwmorph(flats,'remove',8); \nfinline = bwperim(flats,8); \n\n% first create connectivity to downstream cells \nIgive = finline(ic);\nIXgive = find(Igive);\n\n% find neighbors of \nIXn = neighs(ic(Igive));\nI2 = ~ismember(IXn,ic(Igive)) & ~flats(IXn) & bsxfun(@le,dem(IXn),dem(ic(Igive)));\n% cells to which an flow direction can be assigned\n% do have at least one downstream neighbor (I2)\nIgive(IXgive(~any(I2,2))) = false;\n\nI2 = I2';\nI2 = I2 & cumsum(I2,1) == 1;\n\nIXn = IXn';\n\nicd(Igive) = IXn(I2(:));\n\n% indicate the cells as nonflat\nflats(ic(Igive)) = false;\n\n% another logical array that indicates if a flat cell receives from\n% upstream neighbor\nIreceive = false(nrcf,1);\n\n% iteratively remove non-giving cells\nwhile any(~Igive)\n \n % find cells that give but not receive\n Itemp = Igive & ~Ireceive;\n IXn = ic(Itemp);\n \n % find neighbors of these cells\n IXf = neighs(IXn);\n % which of these neighbors are flat cells\n I2 = flats(IXf);\n % which IXn do have flat neighbors at all\n \n II = any(I2,2);\n \n IXn = IXn(II);\n IXf = IXf(II,:);\n I2 = I2(II,:);\n \n IXn = repmat(IXn,1,8)';\n \n IXf = IXf';\n I2 = I2';\n \n IXn = IXn(I2(:));\n IXf = IXf(I2(:));\n \n [IXf,m] = unique(IXf);\n IXn = IXn(m); \n \n I = ismembc(ic,IXf);\n Igive(I) = true;\n icd(I) = IXn;\n Ireceive(Itemp) = true;\n \n flats(IXf) = false; \n \nend\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [ic,icd] = routeflatsmulti(flats)\n% recursive routing through flats using multiple flow direction\n%\n% [ic,icd] = routeflatsmulti(flats)\n%\n%\n%\nnrflats = sum(flats(:));\n\nic = cell(nrflats,1);\nicd = cell(nrflats,1);\n\ncounter = 1;\n% recursive routing through flats\nwhile II\n \n % inner border in flats\n finline = bwmorph(flats,'remove',8);\n % outline around flats\n outline = imdilate(flats,nhood) & ~flats;\n \n % outline\n IXn = find(outline);\n IXf = neighs(IXn);\n I = finline(IXf) & bsxfun(@le,dem(IXn),dem(IXf));\n sI = sum(I,2);\n I2 = sI>0 & sI<8;\n \n % inner border cells that don't have neighbors of\n % equal or lower elevation are sinks\n flats(IXf(sI==8,:)) = false;\n \n IXf = IXf(I2,:);\n IXn = IXn(I2);\n I = I(I2,:);\n \n IXn = spdiags(IXn,0,numel(IXn),numel(IXn))*I;\n IXn = IXn(I);\n IXf = IXf(I);\n \n flats(IXf(:)) = false;\n \n ic{counter} = full(IXf(:));\n icd{counter} = full(IXn(:));\n \n if any(flats(:))\n counter = counter+1;\n else\n II = false;\n ic = cell2mat(ic);\n icd = cell2mat(icd);\n end\nend\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction IXn = neighs(IXf)\n% get neighbors of a cell in a matrix\n\n ix = randperm(8);\n IXn = zeros(size(IXf,1),8);\n IXn(:,ix(1)) = IXf+1;\n IXn(:,ix(2)) = IXf-1;\n IXn(:,ix(3)) = IXf+siz(1);\n IXn(:,ix(4)) = IXf-siz(1);\n\n IXn(:,ix(5)) = IXf+1+siz(1);\n IXn(:,ix(6)) = IXf-1+siz(1);\n IXn(:,ix(7)) = IXf-1-siz(1);\n IXn(:,ix(8)) = IXf+1-siz(1);\nend\n\n\nend\n"} +{"plateform": "github", "repo_name": "wschwanghart/topotoolbox-master", "name": "jctcon.m", "ext": ".m", "path": "topotoolbox-master/@DIVIDEobj/jctcon.m", "size": 3625, "source_encoding": "utf_8", "md5": "07d3aab34aad2e41e9ca2f7232a14b26", "text": "function [CJ,varargout] = jctcon(D,varargin)\n%JCTCON compute junction connectivity\n%\n% Syntax\n%\n% CJ = jctcon(D)\n% CJ = jctcon(D,maxdist)\n% [CJ,x,y] = jctcon(D)\n% \n% \n% Description\n% \n% JCTCON computes the junction connectivity for junctions provided by\n% the linear indices in ixjct. The junction connectivity is defined to\n% be the sum of the ratios of the Euclidean distance, d , and the \n% divide distance, d_d , of all divide edges, n, within a specified \n% maximum divide distance, d_{d,max}. See Scherler and Schwanghart\n% (2020) for more details.\n% \n%\n% Input arguments\n%\n% D instance of DIVIDEobj\n% ixjct linear index of junction(s)\n% maxdist maximum divide distance (default = 5000)\n% \n% \n% Output arguments\n%\n% CJ Junction connectivity values\n% x,y x,y coordinates of junctions \n%\n% Examples\n%\n% DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');\n% FD = FLOWobj(DEM,'preprocess','c');\n% ST = STREAMobj(FD,flowacc(FD)>1000);\n% D = DIVIDEobj(FD,ST);\n% D = divorder(D,'topo');\n% [CJ,x,y] = jctcon(D);\n% plot(D,'color',[.7 .7 .7])\n% hold on\n% scatter(x,y,50,CJ,'filled')\n% hc = colorbar;\n% hc.Label.String = 'Junction connectivity';\n%\n%\n% See also: DIVIDEobj\n%\n% Author: Dirk Scherler (scherler[at]gfz-potsdam.de)\n% Date: April 2020\n\n\nmaxdist = 5e3;\n\nif nargin==3\n maxdist = varargin{1};\nend\n\n\n\nCJ = nan(size(D.jct));\n\nfor i = 1 : length(D.jct) \n \n D2 = resortdivide(D,D.jct(i),maxdist*2);\n D2 = divdist(D2);\n \n [x0,y0] = ind2coord(D,D.jct(i));\n [x,y] = ind2coord(D2,D2.IX);\n dist = hypot(x-x0,y-y0); % euclidean distance\n dd = D2.distance; % divide distance\n [dd,six] = sort(dd,'ascend');\n dist = dist(six);\n\n ix = dd0 & dd>0;\n r = d(ix)./dd(ix);\n CJ(i) = sum(r).*D.cellsize./maxdist;\n\nend\n\nif nargout>1\n [x,y] = ind2coord(D,D.jct);\n varargout{1} = x;\n varargout{2} = y;\nend\n\n\nend\n\n\nfunction DOUT = resortdivide(DIN,ixep,distpenality)\n\nDOUT = DIN;\nDOUT.ep = ixep;\n\nM = onl2struct(DIN.IX);\n[M.flag] = deal(true);\n[M.maxdist] = deal(nan);\nsegments = struct;\nia = max(ismember(vertcat(M.st),ixep),[],2);\n[M(ia).dist] = deal(0);\n\nmaxdist = zeros(size(ixep));\n\nct = 0;\nwhile ~isempty(ixep) \n \n [ia,ib] = ismember(vertcat(M.st),ixep);\n [locr,locc] = find(ia);\n \n % flip segments, if needed\n ix = find(locc==2);\n for i = 1 : length(ix) \n thisr = locr(ix(i));\n M(thisr).IX = [flipud(M(thisr).IX(1:end-1));NaN];\n M(thisr).st = fliplr(M(thisr).st);\n end\n \n % update distance\n for i = 1 : length(locr) \n thisr = locr(i);\n thisc = locc(i);\n M(thisr).dist = maxdist(ib(thisr,thisc)) + (numel(M(thisr).IX)-2).*DIN.cellsize;\n end\n \n % loop over segments \n ixep = [];\n maxdist = [];\n for i = 1 : length(locr)\n thisr = locr(i);\n if M(thisr).flag && M(thisr).dist500);\n% D = DIVIDEobj(FD,ST);\n% D = divorder(D,'topo');\n% DX = flowdistance(FD,ST);\n% DZ = vertdistance2stream(FD,ST,DEM);\n% DZ.Z(DZ.Z<0) = 0;\n% DZ.Z(isinf(DZ.Z)) = nan;\n% % create mapping structure\n% MS = DIVIDEobj2mapstruct(D,DEM,1000,...\n% {'hr_mean' DZ 'mean'},{'hr_diff' DZ 'diff'},...\n% {'fdist_mean' DX 'mean'},{'fdist_diff' DX 'diff'});\n% for i = 1 : length(MS)\n% MS(i).dai = MS(i).hr_diff./MS(i).hr_mean./2;\n% end\n% % visualize\n% do = [MS.order];\n% dai = [MS.dai];\n% symbolspec = makesymbolspec('Line',...\n% {'order',[2 max(do)],'Linewidth',[0.5 6]},...\n% {'dai',[0 1],'Color',flip(hot)});\n% figure\n% imageschs(DEM,DEM)\n% hc = colorbar;\n% hc.Label.String = 'Elevation (m)';\n% hold on\n% ix = do>1 & not(isnan(dai));\n% mapshow(MS(ix),'SymbolSpec',symbolspec);\n% title('Divide asymmetry index: white=low -> red=high')\n% % export as shapefile, if needed: \n% % shapewrite(MS,'big_tujunga_drainage_divides.shp')\n% \n%\n% See also: FLOWobj, divides\n%\n% Author: Dirk Scherler (scherler[at]gfz-potsdam.de)\n% Date: April 2020\n\n\nif not(D.issorted)\n error('Divide object not sorted. Use function SORT first.')\nend\n\nif isempty(D.distance)\n warning('Divide object has no distance. Comnputing distance now.')\n D = divdist(D);\nend\nif isempty(D.distance)\n warning('Divide object has no ordertype. Comnputing Topo-order now.')\n D = divorder(D,'topo');\nend\n\n\n% Get vectors \n[x,y] = ind2coord(D,vertcat(D.IX));\ndo = D.order;\ndist = D.distance;\n\n% Adjust segment length \nif seglen>0 && not(isnan(seglen))\n % (copied from function STREAMobj2mapstruct)\n sep = isnan(x);\n d = zeros(size(x));\n for r = 2:numel(d) \n if sep(r-1)\n d(r) = 0;\n elseif sep(r)\n d(r) = nan;\n else\n d(r) = d(r-1)+sqrt((x(r)-x(r-1)).^2 + (y(r)-y(r-1)).^2);\n end\n end\n % try to get equal length segments being equally distributed over an\n % existing segment.\n % Use equal quantiles\n ixsep = find(sep);\n nrsep = numel(ixsep);\n ixsep = [0;ixsep];\n newsep = zeros(size(d));\n for r = 1:nrsep\n dd = d(ixsep(r)+1 : ixsep(r+1)-1);\n ddmax = max(dd);\n nrnewsegs = max(round(ddmax/seglen),1);\n if nrnewsegs > 1\n [~,segtemp] = histc(dd,...\n linspace(0,ddmax + DEM.cellsize*.01,nrnewsegs));\n segtemp = [0;diff(segtemp)];\n newsep(ixsep(r)+1 : ixsep(r+1)-1) = segtemp;\n end\n end\n % now set new separators according to newsep\n ind = find(newsep > 0);\n x = insertrows(x,x(ind),ind);\n y = insertrows(y,y(ind),ind);\n do = insertrows(do,do(ind),ind);\n dist = insertrows(dist,dist(ind),ind);\n newsep = insertrows(newsep,0,ind);\n % insert nans\n ind = find(newsep > 0);\n x = insertrows(x,nan,ind);\n y = insertrows(y,nan,ind);\n do = insertrows(do,nan,ind);\n dist = insertrows(dist,nan,ind);\nend\n\n\n% Calculate across divide attributes \nnvar = length(varargin);\nVAR = cell(1,3+nvar);\nvarname = cell(1,3+nvar);\n\n% Find pixels on either side of ridgeline\nx1 = [NaN; x(1:end-1)];\nx2 = [NaN; x(2:end)];\ny1 = [NaN; y(1:end-1)];\ny2 = [NaN; y(2:end)];\ndx = x1-x2;\ndy = y1-y2;\nhcs = DEM.cellsize/2;\nix = dx==0; % vertical link\niy = dy==0; % horizontal link\nmeanx = (x1+x2)./2;\nmeany = (y1+y2)./2;\npx = meanx + hcs.*ix;\nqx = meanx - hcs.*ix;\npy = meany + hcs.*iy;\nqy = meany - hcs.*iy;\npix = coord2ind(DEM,px,py);\nqix = coord2ind(DEM,qx,qy);\n\n% allocate space\npx1 = nan(size(pix));\npx2 = px1;\nnx = ~isnan(pix) & ~isnan(qix);\n\n% get elevation\npx1(nx) = DEM.Z(pix(nx));\npx2(nx) = DEM.Z(qix(nx));\nminpx = min([px1,px2],[],2);\nmaxpx = max([px1,px2],[],2);\nVAR{1} = min([minpx maxpx],[],2);\nvarname{1} = 'z_min';\nVAR{2} = max([minpx maxpx],[],2);\nvarname{2} = 'z_max';\nVAR{3} = mean([minpx maxpx],2);\nvarname{3} = 'z_mean';\nct = 3;\n\n\n% get other grid values\nif ~isempty(varargin)\n for i = 1 : nvar\n GRID = varargin{i}{2};\n if isa(GRID,'GRIDobj')\n \n px1(nx) = GRID.Z(pix(nx));\n px2(nx) = GRID.Z(qix(nx));\n switch varargin{i}{3}\n case 'mean'\n v = nanmean([px1,px2],2);\n case 'max'\n v = nanmax([px1,px2],[],2);\n case 'min'\n v = nanmin([px1,px2],[],2);\n case 'diff'\n v = abs(diff([px1,px2],1,2));\n end\n else\n if length(GRID)==length(D.IX)\n v = GRID;\n else\n error('Attribute variable size does not match DIVIDEobj length');\n end\n end\n ct = ct+1;\n VAR{ct} = v;\n varname{ct} = varargin{i}{1};\n end\nend\nM = cell2mat(VAR);\n\n\n% Create the mapping structure \nix = find(isnan(x));\nnrlines = numel(ix);\n\nMS = struct('Geometry','Line',...\n 'X',cell(nrlines,1),...\n 'Y',cell(nrlines,1));\n\nIXs = [1;ix(1:end-1)+1];\nIXe = ix-1;\n\nfor r = 1:nrlines\n MS(r).ID = r;\n MS(r).X = [x(IXs(r):IXe(r));NaN];\n MS(r).Y = [y(IXs(r):IXe(r));NaN];\n if not(isempty(do))\n MS(r).order = unique(do(IXs(r):IXe(r))); % if not unique, something wrong\n end\n if not(isempty(dist))\n MS(r).distance = mean(dist(IXs(r):IXe(r)));\n end\n MS(r).length = max(getdistance(MS(r).X,MS(r).Y));\n % calculate orientation\n dx = MS(r).X(end-1)-MS(r).X(1);\n dy = MS(r).Y(end-1)-MS(r).Y(1);\n alpha = atand(dx./dy);\n if alpha<0; alpha = alpha+180; end\n MS(r).azimuth = alpha;\n for k = 1 : ct\n MS(r).(varname{k}) = double(nanmean(M(IXs(r):IXe(r),k)));\n end\nend\n\nend % main function\n\n\n%% INSERTROWS by JOS \n% www.mathworks.com/matlabcentral/fileexchange/9984-insertrows-v2-0-may-2008\nfunction [C,RA,RB] = insertrows(A,B,ind)\n% INSERTROWS - Insert rows into a matrix at specific locations\n% C = INSERTROWS(A,B,IND) inserts the rows of matrix B into the matrix A at\n% the positions IND. Row k of matrix B will be inserted after position IND(k)\n% in the matrix A. If A is a N-by-X matrix and B is a M-by-X matrix, C will\n% be a (N+M)-by-X matrix. IND can contain non-integers.\n%\n% If B is a 1-by-N matrix, B will be inserted for each insertion position\n% specified by IND. If IND is a single value, the whole matrix B will be\n% inserted at that position. If B is a single value, B is expanded to a row\n% vector. In all other cases, the number of elements in IND should be equal to\n% the number of rows in B, and the number of columns, planes etc should be the\n% same for both matrices A and B. \n%\n% Values of IND smaller than one will cause the corresponding rows to be\n% inserted in front of A. C = INSERTROWS(A,B) will simply append B to A.\n%\n% If any of the inputs are empty, C will return A. If A is sparse, C will\n% be sparse as well. \n%\n% [C, RA, RB] = INSERTROWS(...) will return the row indices RA and RB for\n% which C corresponds to the rows of either A and B.\n%\n% Examples:\n% % the size of A,B, and IND all match\n% C = insertrows(rand(5,2),zeros(2,2),[1.5 3]) \n% % the row vector B is inserted twice\n% C = insertrows(ones(4,3),1:3,[1 Inf]) \n% % matrix B is expanded to a row vector and inserted twice (as in 2)\n% C = insertrows(ones(5,3),999,[2 4])\n% % the whole matrix B is inserted once\n% C = insertrows(ones(5,3),zeros(2,3),2)\n% % additional output arguments\n% [c,ra,rb] = insertrows([1:4].',99,[0 3]) \n% c.' % -> [99 1 2 3 99 4] \n% c(ra).' % -> [1 2 3 4] \n% c(rb).' % -> [99 99] \n%\n% Using permute (or transpose) INSERTROWS can easily function to insert\n% columns, planes, etc:\n%\n% % inserting columns, by using the transpose operator:\n% A = zeros(2,3) ; B = ones(2,4) ;\n% c = insertrows(A.', B.',[0 2 3 3]).' % insert columns\n% % inserting other dimensions, by using permute:\n% A = ones(4,3,3) ; B = zeros(4,3,1) ; \n% % set the dimension on which to operate in front\n% C = insertrows(permute(A,[3 1 2]), permute(B,[3 1 2]),1) ;\n% C = ipermute(C,[3 1 2]) \n%\n% See also HORZCAT, RESHAPE, CAT\n\n% for Matlab R13\n% version 2.0 (may 2008)\n% (c) Jos van der Geest\n% email: jos@jasen.nl\n\n% History:\n% 1.0, feb 2006 - created\n% 2.0, may 2008 - incorporated some improvements after being selected as\n% \"Pick of the Week\" by Jiro Doke, and reviews by Tim Davis & Brett:\n% - horizontal concatenation when two arguments are provided\n% - added example of how to insert columns\n% - mention behavior of sparse inputs\n% - changed \"if nargout\" to \"if nargout>1\" so that additional outputs are\n% only calculated when requested for\n\nnarginchk(2,3);\n\nif nargin==2,\n % just horizontal concatenation, suggested by Tim Davis\n ind = size(A,1) ;\nend\n\n% shortcut when any of the inputs are empty\nif isempty(B) || isempty(ind), \n C = A ; \n if nargout > 1,\n RA = 1:size(A,1) ;\n RB = [] ;\n end\n return\nend\n\nsa = size(A) ;\n\n% match the sizes of A, B\nif numel(B)==1,\n % B has a single argument, expand to match A\n sb = [1 sa(2:end)] ;\n B = repmat(B,sb) ;\nelse\n % otherwise check for dimension errors\n if ndims(A) ~= ndims(B),\n error('insertrows:DimensionMismatch', ...\n 'Both input matrices should have the same number of dimensions.') ;\n end\n sb = size(B) ;\n if ~all(sa(2:end) == sb(2:end)),\n error('insertrows:DimensionMismatch', ...\n 'Both input matrices should have the same number of columns (and planes, etc).') ;\n end\nend\n\nind = ind(:) ; % make as row vector\nni = length(ind) ;\n\n% match the sizes of B and IND\nif ni ~= sb(1),\n if ni==1 && sb(1) > 1,\n % expand IND\n ind = repmat(ind,sb(1),1) ;\n elseif (ni > 1) && (sb(1)==1),\n % expand B\n B = repmat(B,ni,1) ;\n else\n error('insertrows:InputMismatch',...\n 'The number of rows to insert should equal the number of insertion positions.') ;\n end\nend\n\nsb = size(B) ;\n\n% the actual work\n% 1. concatenate matrices\nC = [A ; B] ;\n% 2. sort the respective indices, the first output of sort is ignored (by\n% giving it the same name as the second output, one avoids an extra \n% large variable in memory)\n[~,abi] = sort([[1:sa(1)].' ; ind(:)]) ;\n% 3. reshuffle the large matrix\nC = C(abi,:) ;\n% 4. reshape as A for nd matrices (nd>2)\nif ismatrix(A),\n sc = sa ;\n sc(1) = sc(1)+sb(1) ;\n C = reshape(C,sc) ;\nend\n\nif nargout > 1,\n % additional outputs required\n R = [zeros(sa(1),1) ; ones(sb(1),1)] ;\n R = R(abi) ;\n RA = find(R==0) ;\n RB = find(R==1) ;\nend\nend\n\n\n\n"} +{"plateform": "github", "repo_name": "lampo808/Fit-master", "name": "ex_GFS_multipressure_Voigt.m", "ext": ".m", "path": "Fit-master/examples/ex_GFS_multipressure_Voigt.m", "size": 2420, "source_encoding": "utf_8", "md5": "bf622f2e9b4d0aa5e7620ab9f6a029f6", "text": "% Example for the global fit class (GlobalFitSimple)\n\n% Fit a set of Voigt profiles that represent the same absorption line\n% measured at different pressures.\n\nclear all\nclose all\n\naddpath('./fadf')\n\nrng(1) % Set a seed for the random number generation (for reproducibility)\n\n% The model represents a pressure-boradened line\n% p(1) -> Line amplitude\n% p(2) -> pressure (not a fitting parameter, must be held fixed)\n% p(3) -> Doppler width\n% p(4) -> line center frequency (at zero pressure)\n% p(5) -> pressure shift coefficient\n% p(6) -> pressure broadening coefficient\nmodel = @(x, p) pressureDependentVoigtProfile(x, p(1), p(2), p(3), p(4), p(5), p(6));\n\n% Pressures [atm]\np = [0.1, 1, 10, 20, 50, 200, 500]/760;\n\n% Parameters for the simulated datasets\nfor i=1:length(p)\n pars(i,:) = [1+0.2*randn(1,1), p(i), 0.7, 0, 0.225, 2.2];\nend\n\nN = 300; % Points per curve\nnoise = 0.005; % Absolute noise level\n\n% Generate and plot data\nfigure()\nhold on\nfor i=1:size(pars, 1)\n xData{i} = linspace(-5, 5, N);\n yData{i} = model(xData{i}, pars(i,:)) + noise*randn(size(xData{i}));\n plot(xData{i}, yData{i}, '.')\nend\nhold off\n\n% Define the marices for upper and lower bounds, and for the fixed\n% parameters. NaN means no bound/fix\nfor i=1:length(p)\n ub(i,:) = [1.5, Inf, 0.8, 0.1, 0.5, 5];\n lb(i,:) = [0.1, -Inf, 0.6, -0.1, 0.1, 1];\n fixed(i,:) = [NaN, p(i), NaN, NaN, NaN, NaN];\nend\n\ngf = GlobalFitSimple(); % Instantiate the class\ngf.setData(xData, yData); % Set the data to fit\n\n% Set the model\ngf.setModel(model, 6, [0 0 1 1 1 1])\ngf.setStart(pars.*(1+0.1*randn(size(pars)))) % Set start point\n\n% Set upper/lower bounds, and fixed parameters. For this kind of complicate\n% fitting, it's necessary to set bounds to guide the fitting routine\ngf.setUb(ub);\ngf.setLb(lb);\ngf.fixParameters(fixed);\ngf.fit() % Run the fit!\nfit_pars = gf.getFittedParameters(); % Retrieve the fitted parameters...\nfit_errs = gf.getParamersErrors(); % ...and their errors\n\n% Print the difference between the original and the retrieved parameters\ndisp(pars - fit_pars);\n\n% Evaluate and plot the fit\nhold on\nfor i=1:size(pars, 1)\n yData{i} = model(xData{i}, fit_pars(i,:));\n plot(xData{i}, yData{i}, '-')\nend\nhold off\n\nfunction y = pressureDependentVoigtProfile(x, A, p, s, x0, d0, g0)\nx_p = x0 + p.*d0; % Pressure-dependent shift\ng_p = p.*g0; % Pressure-dependent Lorentzian width\n\ny = A.*voigt(x - x_p, s, g_p);\nend"} +{"plateform": "github", "repo_name": "lampo808/Fit-master", "name": "hessdiag.m", "ext": ".m", "path": "Fit-master/DERIVESTsuite/hessdiag.m", "size": 2034, "source_encoding": "utf_8", "md5": "ff31ada116a5b893f0b1b7ad4ef6336f", "text": "function [HD,err,finaldelta] = hessdiag(fun,x0)\n% HESSDIAG: diagonal elements of the Hessian matrix (vector of second partials)\n% usage: [HD,err,finaldelta] = hessdiag(fun,x0)\n%\n% When all that you want are the diagonal elements of the hessian\n% matrix, it will be more efficient to call HESSDIAG than HESSIAN.\n% HESSDIAG uses DERIVEST to provide both second derivative estimates\n% and error estimates. fun needs not be vectorized.\n% \n% arguments: (input)\n% fun - SCALAR analytical function to differentiate.\n% fun must be a function of the vector or array x0.\n% \n% x0 - vector location at which to differentiate fun\n% If x0 is an nxm array, then fun is assumed to be\n% a function of n*m variables. \n%\n% arguments: (output)\n% HD - vector of second partial derivatives of fun.\n% These are the diagonal elements of the Hessian\n% matrix, evaluated at x0.\n% HD will be a row vector of length numel(x0).\n%\n% err - vector of error estimates corresponding to\n% each second partial derivative in HD.\n%\n% finaldelta - vector of final step sizes chosen for\n% each second partial derivative.\n%\n%\n% Example usage:\n% [HD,err] = hessdiag(@(x) x(1) + x(2)^2 + x(3)^3,[1 2 3])\n% HD =\n% 0 2 18\n%\n% err =\n% 0 0 0\n%\n%\n% See also: derivest, gradient, gradest\n%\n%\n% Author: John D'Errico\n% e-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 2/9/2007\n\n% get the size of x0 so we can reshape\n% later.\nsx = size(x0);\n\n% total number of derivatives we will need to take\nnx = numel(x0);\n\nHD = zeros(1,nx);\nerr = HD;\nfinaldelta = HD;\nfor ind = 1:nx\n [HD(ind),err(ind),finaldelta(ind)] = derivest( ...\n @(xi) fun(swapelement(x0,ind,xi)), ...\n x0(ind),'deriv',2,'vectorized','no');\nend\n\nend % mainline function end\n\n% =======================================\n% sub-functions\n% =======================================\nfunction vec = swapelement(vec,ind,val)\n% swaps val as element ind, into the vector vec\nvec(ind) = val;\n\nend % sub-function end\n\n\n\n"} +{"plateform": "github", "repo_name": "lampo808/Fit-master", "name": "hessian.m", "ext": ".m", "path": "Fit-master/DERIVESTsuite/hessian.m", "size": 5157, "source_encoding": "utf_8", "md5": "8e0bddd9a2df4151adbee6e016f767cf", "text": "function [hess,err] = hessian(fun,x0)\n% hessian: estimate elements of the Hessian matrix (array of 2nd partials)\n% usage: [hess,err] = hessian(fun,x0)\n%\n% Hessian is NOT a tool for frequent use on an expensive\n% to evaluate objective function, especially in a large\n% number of dimensions. Its computation will use roughly\n% O(6*n^2) function evaluations for n parameters.\n% \n% arguments: (input)\n% fun - SCALAR analytical function to differentiate.\n% fun must be a function of the vector or array x0.\n% fun does not need to be vectorized.\n% \n% x0 - vector location at which to compute the Hessian.\n%\n% arguments: (output)\n% hess - nxn symmetric array of second partial derivatives\n% of fun, evaluated at x0.\n%\n% err - nxn array of error estimates corresponding to\n% each second partial derivative in hess.\n%\n%\n% Example usage:\n% Rosenbrock function, minimized at [1,1]\n% rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2;\n% \n% [h,err] = hessian(rosen,[1 1])\n% h =\n% 842 -420\n% -420 210\n% err =\n% 1.0662e-12 4.0061e-10\n% 4.0061e-10 2.6654e-13\n%\n%\n% Example usage:\n% cos(x-y), at (0,0)\n% Note: this hessian matrix will be positive semi-definite\n%\n% hessian(@(xy) cos(xy(1)-xy(2)),[0 0])\n% ans =\n% -1 1\n% 1 -1\n%\n%\n% See also: derivest, gradient, gradest, hessdiag\n%\n%\n% Author: John D'Errico\n% e-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 2/10/2007\n\n% parameters that we might allow to change\nparams.StepRatio = 2.0000001;\nparams.RombergTerms = 3;\n\n% get the size of x0 so we can reshape\n% later.\nsx = size(x0);\n\n% was a string supplied?\nif ischar(fun)\n fun = str2func(fun);\nend\n\n% total number of derivatives we will need to take\nnx = length(x0);\n\n% get the diagonal elements of the hessian (2nd partial\n% derivatives wrt each variable.)\n[hess,err] = hessdiag(fun,x0);\n\n% form the eventual hessian matrix, stuffing only\n% the diagonals for now.\nhess = diag(hess);\nerr = diag(err);\nif nx<2\n % the hessian matrix is 1x1. all done\n return\nend\n\n% get the gradient vector. This is done only to decide\n% on intelligent step sizes for the mixed partials\n[grad,graderr,stepsize] = gradest(fun,x0);\n\n% Get params.RombergTerms+1 estimates of the upper\n% triangle of the hessian matrix\ndfac = params.StepRatio.^(-(0:params.RombergTerms)');\nfor i = 2:nx\n for j = 1:(i-1)\n dij = zeros(params.RombergTerms+1,1);\n for k = 1:(params.RombergTerms+1)\n dij(k) = fun(x0 + swap2(zeros(sx),i, ...\n dfac(k)*stepsize(i),j,dfac(k)*stepsize(j))) + ...\n fun(x0 + swap2(zeros(sx),i, ...\n -dfac(k)*stepsize(i),j,-dfac(k)*stepsize(j))) - ...\n fun(x0 + swap2(zeros(sx),i, ...\n dfac(k)*stepsize(i),j,-dfac(k)*stepsize(j))) - ...\n fun(x0 + swap2(zeros(sx),i, ...\n -dfac(k)*stepsize(i),j,dfac(k)*stepsize(j)));\n \n end\n dij = dij/4/prod(stepsize([i,j]));\n dij = dij./(dfac.^2);\n \n % Romberg extrapolation step\n [hess(i,j),err(i,j)] = rombextrap(params.StepRatio,dij,[2 4]);\n hess(j,i) = hess(i,j);\n err(j,i) = err(i,j);\n end\nend\n\n\nend % mainline function end\n\n% =======================================\n% sub-functions\n% =======================================\nfunction vec = swap2(vec,ind1,val1,ind2,val2)\n% swaps val as element ind, into the vector vec\nvec(ind1) = val1;\nvec(ind2) = val2;\n\nend % sub-function end\n\n\n% ============================================\n% subfunction - romberg extrapolation\n% ============================================\nfunction [der_romb,errest] = rombextrap(StepRatio,der_init,rombexpon)\n% do romberg extrapolation for each estimate\n%\n% StepRatio - Ratio decrease in step\n% der_init - initial derivative estimates\n% rombexpon - higher order terms to cancel using the romberg step\n%\n% der_romb - derivative estimates returned\n% errest - error estimates\n% amp - noise amplification factor due to the romberg step\n\nsrinv = 1/StepRatio;\n\n% do nothing if no romberg terms\nnexpon = length(rombexpon);\nrmat = ones(nexpon+2,nexpon+1);\nswitch nexpon\n case 0\n % rmat is simple: ones(2,1)\n case 1\n % only one romberg term\n rmat(2,2) = srinv^rombexpon;\n rmat(3,2) = srinv^(2*rombexpon);\n case 2\n % two romberg terms\n rmat(2,2:3) = srinv.^rombexpon;\n rmat(3,2:3) = srinv.^(2*rombexpon);\n rmat(4,2:3) = srinv.^(3*rombexpon);\n case 3\n % three romberg terms\n rmat(2,2:4) = srinv.^rombexpon;\n rmat(3,2:4) = srinv.^(2*rombexpon);\n rmat(4,2:4) = srinv.^(3*rombexpon);\n rmat(5,2:4) = srinv.^(4*rombexpon);\nend\n\n% qr factorization used for the extrapolation as well\n% as the uncertainty estimates\n[qromb,rromb] = qr(rmat,0);\n\n% the noise amplification is further amplified by the Romberg step.\n% amp = cond(rromb);\n\n% this does the extrapolation to a zero step size.\nne = length(der_init);\nrombcoefs = rromb\\(qromb'*der_init);\nder_romb = rombcoefs(1,:)';\n\n% uncertainty estimate of derivative prediction\ns = sqrt(sum((der_init - rmat*rombcoefs).^2,1));\nrinv = rromb\\eye(nexpon+1);\ncov1 = sum(rinv.^2,2); % 1 spare dof\nerrest = s'*12.7062047361747*sqrt(cov1(1));\n\nend % rombextrap\n\n\n"} +{"plateform": "github", "repo_name": "lampo808/Fit-master", "name": "jacobianest.m", "ext": ".m", "path": "Fit-master/DERIVESTsuite/jacobianest.m", "size": 5850, "source_encoding": "utf_8", "md5": "eb3dd9ff0c56b1eb7316f8237dbee253", "text": "function [jac,err] = jacobianest(fun,x0)\n% gradest: estimate of the Jacobian matrix of a vector valued function of n variables\n% usage: [jac,err] = jacobianest(fun,x0)\n%\n% \n% arguments: (input)\n% fun - (vector valued) analytical function to differentiate.\n% fun must be a function of the vector or array x0.\n% \n% x0 - vector location at which to differentiate fun\n% If x0 is an nxm array, then fun is assumed to be\n% a function of n*m variables.\n%\n%\n% arguments: (output)\n% jac - array of first partial derivatives of fun.\n% Assuming that x0 is a vector of length p\n% and fun returns a vector of length n, then\n% jac will be an array of size (n,p)\n%\n% err - vector of error estimates corresponding to\n% each partial derivative in jac.\n%\n%\n% Example: (nonlinear least squares)\n% xdata = (0:.1:1)';\n% ydata = 1+2*exp(0.75*xdata);\n% fun = @(c) ((c(1)+c(2)*exp(c(3)*xdata)) - ydata).^2;\n%\n% [jac,err] = jacobianest(fun,[1 1 1])\n%\n% jac =\n% -2 -2 0\n% -2.1012 -2.3222 -0.23222\n% -2.2045 -2.6926 -0.53852\n% -2.3096 -3.1176 -0.93528\n% -2.4158 -3.6039 -1.4416\n% -2.5225 -4.1589 -2.0795\n% -2.629 -4.7904 -2.8742\n% -2.7343 -5.5063 -3.8544\n% -2.8374 -6.3147 -5.0518\n% -2.9369 -7.2237 -6.5013\n% -3.0314 -8.2403 -8.2403\n%\n% err =\n% 5.0134e-15 5.0134e-15 0\n% 5.0134e-15 0 2.8211e-14\n% 5.0134e-15 8.6834e-15 1.5804e-14\n% 0 7.09e-15 3.8227e-13\n% 5.0134e-15 5.0134e-15 7.5201e-15\n% 5.0134e-15 1.0027e-14 2.9233e-14\n% 5.0134e-15 0 6.0585e-13\n% 5.0134e-15 1.0027e-14 7.2673e-13\n% 5.0134e-15 1.0027e-14 3.0495e-13\n% 5.0134e-15 1.0027e-14 3.1707e-14\n% 5.0134e-15 2.0053e-14 1.4013e-12\n%\n% (At [1 2 0.75], jac should be numerically zero)\n%\n%\n% See also: derivest, gradient, gradest\n%\n%\n% Author: John D'Errico\n% e-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 3/6/2007\n\n% get the length of x0 for the size of jac\nnx = numel(x0);\n\nMaxStep = 100;\nStepRatio = 2.0000001;\n\n% was a string supplied?\nif ischar(fun)\n fun = str2func(fun);\nend\n\n% get fun at the center point\nf0 = fun(x0);\nf0 = f0(:);\nn = length(f0);\nif n==0\n % empty begets empty\n jac = zeros(0,nx);\n err = jac;\n return\nend\n\nrelativedelta = MaxStep*StepRatio .^(0:-1:-25);\nnsteps = length(relativedelta);\n\n% total number of derivatives we will need to take\njac = zeros(n,nx);\nerr = jac;\nfor i = 1:nx\n x0_i = x0(i);\n if x0_i ~= 0\n delta = x0_i*relativedelta;\n else\n delta = relativedelta;\n end\n \n % evaluate at each step, centered around x0_i\n % difference to give a second order estimate\n fdel = zeros(n,nsteps);\n for j = 1:nsteps\n fdif = fun(swapelement(x0,i,x0_i + delta(j))) - ...\n fun(swapelement(x0,i,x0_i - delta(j)));\n \n fdel(:,j) = fdif(:);\n end\n \n % these are pure second order estimates of the\n % first derivative, for each trial delta.\n derest = fdel.*repmat(0.5 ./ delta,n,1);\n \n % The error term on these estimates has a second order\n % component, but also some 4th and 6th order terms in it.\n % Use Romberg exrapolation to improve the estimates to\n % 6th order, as well as to provide the error estimate.\n \n % loop here, as rombextrap coupled with the trimming\n % will get complicated otherwise.\n for j = 1:n\n [der_romb,errest] = rombextrap(StepRatio,derest(j,:),[2 4]);\n \n % trim off 3 estimates at each end of the scale\n nest = length(der_romb);\n trim = [1:3, nest+(-2:0)];\n [der_romb,tags] = sort(der_romb);\n der_romb(trim) = [];\n tags(trim) = [];\n \n errest = errest(tags);\n \n % now pick the estimate with the lowest predicted error\n [err(j,i),ind] = min(errest);\n jac(j,i) = der_romb(ind);\n end\nend\n\nend % mainline function end\n\n% =======================================\n% sub-functions\n% =======================================\nfunction vec = swapelement(vec,ind,val)\n% swaps val as element ind, into the vector vec\nvec(ind) = val;\n\nend % sub-function end\n\n% ============================================\n% subfunction - romberg extrapolation\n% ============================================\nfunction [der_romb,errest] = rombextrap(StepRatio,der_init,rombexpon)\n% do romberg extrapolation for each estimate\n%\n% StepRatio - Ratio decrease in step\n% der_init - initial derivative estimates\n% rombexpon - higher order terms to cancel using the romberg step\n%\n% der_romb - derivative estimates returned\n% errest - error estimates\n% amp - noise amplification factor due to the romberg step\n\nsrinv = 1/StepRatio;\n\n% do nothing if no romberg terms\nnexpon = length(rombexpon);\nrmat = ones(nexpon+2,nexpon+1);\n% two romberg terms\nrmat(2,2:3) = srinv.^rombexpon;\nrmat(3,2:3) = srinv.^(2*rombexpon);\nrmat(4,2:3) = srinv.^(3*rombexpon);\n\n% qr factorization used for the extrapolation as well\n% as the uncertainty estimates\n[qromb,rromb] = qr(rmat,0);\n\n% the noise amplification is further amplified by the Romberg step.\n% amp = cond(rromb);\n\n% this does the extrapolation to a zero step size.\nne = length(der_init);\nrhs = vec2mat(der_init,nexpon+2,ne - (nexpon+2));\nrombcoefs = rromb\\(qromb'*rhs);\nder_romb = rombcoefs(1,:)';\n\n% uncertainty estimate of derivative prediction\ns = sqrt(sum((rhs - rmat*rombcoefs).^2,1));\nrinv = rromb\\eye(nexpon+1);\ncov1 = sum(rinv.^2,2); % 1 spare dof\nerrest = s'*12.7062047361747*sqrt(cov1(1));\n\nend % rombextrap\n\n\n% ============================================\n% subfunction - vec2mat\n% ============================================\nfunction mat = vec2mat(vec,n,m)\n% forms the matrix M, such that M(i,j) = vec(i+j-1)\n[i,j] = ndgrid(1:n,0:m-1);\nind = i+j;\nmat = vec(ind);\nif n==1\n mat = mat';\nend\n\nend % vec2mat\n\n\n\n"} +{"plateform": "github", "repo_name": "lampo808/Fit-master", "name": "gradest.m", "ext": ".m", "path": "Fit-master/DERIVESTsuite/gradest.m", "size": 2374, "source_encoding": "utf_8", "md5": "8164711b2f9bdaae657fae039afd34f0", "text": "function [grad,err,finaldelta] = gradest(fun,x0)\n% gradest: estimate of the gradient vector of an analytical function of n variables\n% usage: [grad,err,finaldelta] = gradest(fun,x0)\n%\n% Uses derivest to provide both derivative estimates\n% and error estimates. fun needs not be vectorized.\n% \n% arguments: (input)\n% fun - analytical function to differentiate. fun must\n% be a function of the vector or array x0.\n% \n% x0 - vector location at which to differentiate fun\n% If x0 is an nxm array, then fun is assumed to be\n% a function of n*m variables. \n%\n% arguments: (output)\n% grad - vector of first partial derivatives of fun.\n% grad will be a row vector of length numel(x0).\n%\n% err - vector of error estimates corresponding to\n% each partial derivative in grad.\n%\n% finaldelta - vector of final step sizes chosen for\n% each partial derivative.\n%\n%\n% Example:\n% [grad,err] = gradest(@(x) sum(x.^2),[1 2 3])\n% grad =\n% 2 4 6\n% err =\n% 5.8899e-15 1.178e-14 0\n%\n%\n% Example:\n% At [x,y] = [1,1], compute the numerical gradient\n% of the function sin(x-y) + y*exp(x)\n%\n% z = @(xy) sin(diff(xy)) + xy(2)*exp(xy(1))\n%\n% [grad,err ] = gradest(z,[1 1])\n% grad =\n% 1.7183 3.7183\n% err =\n% 7.537e-14 1.1846e-13\n%\n%\n% Example:\n% At the global minimizer (1,1) of the Rosenbrock function,\n% compute the gradient. It should be essentially zero.\n%\n% rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2;\n% [g,err] = gradest(rosen,[1 1])\n% g =\n% 1.0843e-20 0\n% err =\n% 1.9075e-18 0\n%\n%\n% See also: derivest, gradient\n%\n%\n% Author: John D'Errico\n% e-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 2/9/2007\n\n% get the size of x0 so we can reshape\n% later.\nsx = size(x0);\n\n% total number of derivatives we will need to take\nnx = numel(x0);\n\ngrad = zeros(1,nx);\nerr = grad;\nfinaldelta = grad;\nfor ind = 1:nx\n [grad(ind),err(ind),finaldelta(ind)] = derivest( ...\n @(xi) fun(swapelement(x0,ind,xi)), ...\n x0(ind),'deriv',1,'vectorized','no', ...\n 'methodorder',2);\nend\n\nend % mainline function end\n\n% =======================================\n% sub-functions\n% =======================================\nfunction vec = swapelement(vec,ind,val)\n% swaps val as element ind, into the vector vec\nvec(ind) = val;\n\nend % sub-function end\n\n\n"} +{"plateform": "github", "repo_name": "lampo808/Fit-master", "name": "derivest.m", "ext": ".m", "path": "Fit-master/DERIVESTsuite/derivest.m", "size": 23018, "source_encoding": "utf_8", "md5": "3198e9636b2275d707eec59dbb9b8a2f", "text": "function [der,errest,finaldelta] = derivest(fun,x0,varargin)\n% DERIVEST: estimate the n'th derivative of fun at x0, provide an error estimate\n% usage: [der,errest] = DERIVEST(fun,x0) % first derivative\n% usage: [der,errest] = DERIVEST(fun,x0,prop1,val1,prop2,val2,...)\n%\n% Derivest will perform numerical differentiation of an\n% analytical function provided in fun. It will not\n% differentiate a function provided as data. Use gradient\n% for that purpose, or differentiate a spline model.\n%\n% The methods used by DERIVEST are finite difference\n% approximations of various orders, coupled with a generalized\n% (multiple term) Romberg extrapolation. This also yields\n% the error estimate provided. DERIVEST uses a semi-adaptive\n% scheme to provide the best estimate that it can by its\n% automatic choice of a differencing interval.\n%\n% Finally, While I have not written this function for the\n% absolute maximum speed, speed was a major consideration\n% in the algorithmic design. Maximum accuracy was my main goal.\n%\n%\n% Arguments (input)\n% fun - function to differentiate. May be an inline function,\n% anonymous, or an m-file. fun will be sampled at a set\n% of distinct points for each element of x0. If there are\n% additional parameters to be passed into fun, then use of\n% an anonymous function is recommended.\n%\n% fun should be vectorized to allow evaluation at multiple\n% locations at once. This will provide the best possible\n% speed. IF fun is not so vectorized, then you MUST set\n% 'vectorized' property to 'no', so that derivest will\n% then call your function sequentially instead.\n%\n% Fun is assumed to return a result of the same\n% shape as its input x0.\n%\n% x0 - scalar, vector, or array of points at which to\n% differentiate fun.\n%\n% Additional inputs must be in the form of property/value pairs.\n% Properties are character strings. They may be shortened\n% to the extent that they are unambiguous. Properties are\n% not case sensitive. Valid property names are:\n%\n% 'DerivativeOrder', 'MethodOrder', 'Style', 'RombergTerms'\n% 'FixedStep', 'MaxStep'\n%\n% All properties have default values, chosen as intelligently\n% as I could manage. Values that are character strings may\n% also be unambiguously shortened. The legal values for each\n% property are:\n%\n% 'DerivativeOrder' - specifies the derivative order estimated.\n% Must be a positive integer from the set [1,2,3,4].\n%\n% DEFAULT: 1 (first derivative of fun)\n%\n% 'MethodOrder' - specifies the order of the basic method\n% used for the estimation.\n%\n% For 'central' methods, must be a positive integer\n% from the set [2,4].\n%\n% For 'forward' or 'backward' difference methods,\n% must be a positive integer from the set [1,2,3,4].\n%\n% DEFAULT: 4 (a second order method)\n%\n% Note: higher order methods will generally be more\n% accurate, but may also suffere more from numerical\n% problems.\n%\n% Note: First order methods would usually not be\n% recommended.\n%\n% 'Style' - specifies the style of the basic method\n% used for the estimation. 'central', 'forward',\n% or 'backwards' difference methods are used.\n%\n% Must be one of 'Central', 'forward', 'backward'.\n%\n% DEFAULT: 'Central'\n%\n% Note: Central difference methods are usually the\n% most accurate, but sometiems one must not allow\n% evaluation in one direction or the other.\n%\n% 'RombergTerms' - Allows the user to specify the generalized\n% Romberg extrapolation method used, or turn it off\n% completely.\n%\n% Must be a positive integer from the set [0,1,2,3].\n%\n% DEFAULT: 2 (Two Romberg terms)\n%\n% Note: 0 disables the Romberg step completely.\n%\n% 'FixedStep' - Allows the specification of a fixed step\n% size, preventing the adaptive logic from working.\n% This will be considerably faster, but not necessarily\n% as accurate as allowing the adaptive logic to run.\n%\n% DEFAULT: []\n%\n% Note: If specified, 'FixedStep' will define the\n% maximum excursion from x0 that will be used.\n%\n% 'Vectorized' - Derivest will normally assume that your\n% function can be safely evaluated at multiple locations\n% in a single call. This would minimize the overhead of\n% a loop and additional function call overhead. Some\n% functions are not easily vectorizable, but you may\n% (if your matlab release is new enough) be able to use\n% arrayfun to accomplish the vectorization.\n%\n% When all else fails, set the 'vectorized' property\n% to 'no'. This will cause derivest to loop over the\n% successive function calls.\n%\n% DEFAULT: 'yes'\n%\n%\n% 'MaxStep' - Specifies the maximum excursion from x0 that\n% will be allowed, as a multiple of x0.\n%\n% DEFAULT: 100\n%\n% 'StepRatio' - Derivest uses a proportionally cascaded\n% series of function evaluations, moving away from your\n% point of evaluation. The StepRatio is the ratio used\n% between sequential steps.\n%\n% DEFAULT: 2.0000001\n%\n% Note: use of a non-integer stepratio is intentional,\n% to avoid integer multiples of the period of a periodic\n% function under some circumstances.\n%\n%\n% See the document DERIVEST.pdf for more explanation of the\n% algorithms behind the parameters of DERIVEST. In most cases,\n% I have chosen good values for these parameters, so the user\n% should never need to specify anything other than possibly\n% the DerivativeOrder. I've also tried to make my code robust\n% enough that it will not need much. But complete flexibility\n% is in there for your use.\n%\n%\n% Arguments: (output)\n% der - derivative estimate for each element of x0\n% der will have the same shape as x0.\n%\n% errest - 95% uncertainty estimate of the derivative, such that\n%\n% abs(der(j) - f'(x0(j))) < erest(j)\n%\n% finaldelta - The final overall stepsize chosen by DERIVEST\n%\n%\n% Example usage:\n% First derivative of exp(x), at x == 1\n% [d,e]=derivest(@(x) exp(x),1)\n% d =\n% 2.71828182845904\n%\n% e =\n% 1.02015503167879e-14\n%\n% True derivative\n% exp(1)\n% ans =\n% 2.71828182845905\n%\n% Example usage:\n% Third derivative of x.^3+x.^4, at x = [0,1]\n% derivest(@(x) x.^3 + x.^4,[0 1],'deriv',3)\n% ans =\n% 6 30\n%\n% True derivatives: [6,30]\n%\n%\n% See also: gradient\n%\n%\n% Author: John D'Errico\n% e-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 12/27/2006\n\npar.DerivativeOrder = 1;\npar.MethodOrder = 4;\npar.Style = 'central';\npar.RombergTerms = 2;\npar.FixedStep = [];\npar.MaxStep = 100;\n% setting a default stepratio as a non-integer prevents\n% integer multiples of the initial point from being used.\n% In turn that avoids some problems for periodic functions.\npar.StepRatio = 2.0000001;\npar.NominalStep = [];\npar.Vectorized = 'yes';\n\nna = length(varargin);\nif (rem(na,2)==1)\n error 'Property/value pairs must come as PAIRS of arguments.'\nelseif na>0\n par = parse_pv_pairs(par,varargin);\nend\npar = check_params(par);\n\n% Was fun a string, or an inline/anonymous function?\nif (nargin<1)\n help derivest\n return\nelseif isempty(fun)\n error 'fun was not supplied.'\nelseif ischar(fun)\n % a character function name\n fun = str2func(fun);\nend\n\n% no default for x0\nif (nargin<2) || isempty(x0)\n error 'x0 was not supplied'\nend\npar.NominalStep = max(x0,0.02);\n\n% was a single point supplied?\nnx0 = size(x0);\nn = prod(nx0);\n\n% Set the steps to use.\nif isempty(par.FixedStep)\n % Basic sequence of steps, relative to a stepsize of 1.\n delta = par.MaxStep*par.StepRatio .^(0:-1:-25)';\n ndel = length(delta);\nelse\n % Fixed, user supplied absolute sequence of steps.\n ndel = 3 + ceil(par.DerivativeOrder/2) + ...\n par.MethodOrder + par.RombergTerms;\n if par.Style(1) == 'c'\n ndel = ndel - 2;\n end\n delta = par.FixedStep*par.StepRatio .^(-(0:(ndel-1)))';\nend\n\n% generate finite differencing rule in advance.\n% The rule is for a nominal unit step size, and will\n% be scaled later to reflect the local step size.\nfdarule = 1;\nswitch par.Style\n case 'central'\n % for central rules, we will reduce the load by an\n % even or odd transformation as appropriate.\n if par.MethodOrder==2\n switch par.DerivativeOrder\n case 1\n % the odd transformation did all the work\n fdarule = 1;\n case 2\n % the even transformation did all the work\n fdarule = 2;\n case 3\n % the odd transformation did most of the work, but\n % we need to kill off the linear term\n fdarule = [0 1]/fdamat(par.StepRatio,1,2);\n case 4\n % the even transformation did most of the work, but\n % we need to kill off the quadratic term\n fdarule = [0 1]/fdamat(par.StepRatio,2,2);\n end\n else\n % a 4th order method. We've already ruled out the 1st\n % order methods since these are central rules.\n switch par.DerivativeOrder\n case 1\n % the odd transformation did most of the work, but\n % we need to kill off the cubic term\n fdarule = [1 0]/fdamat(par.StepRatio,1,2);\n case 2\n % the even transformation did most of the work, but\n % we need to kill off the quartic term\n fdarule = [1 0]/fdamat(par.StepRatio,2,2);\n case 3\n % the odd transformation did much of the work, but\n % we need to kill off the linear & quintic terms\n fdarule = [0 1 0]/fdamat(par.StepRatio,1,3);\n case 4\n % the even transformation did much of the work, but\n % we need to kill off the quadratic and 6th order terms\n fdarule = [0 1 0]/fdamat(par.StepRatio,2,3);\n end\n end\n case {'forward' 'backward'}\n % These two cases are identical, except at the very end,\n % where a sign will be introduced.\n\n % No odd/even trans, but we already dropped\n % off the constant term\n if par.MethodOrder==1\n if par.DerivativeOrder==1\n % an easy one\n fdarule = 1;\n else\n % 2:4\n v = zeros(1,par.DerivativeOrder);\n v(par.DerivativeOrder) = 1;\n fdarule = v/fdamat(par.StepRatio,0,par.DerivativeOrder);\n end\n else\n % par.MethodOrder methods drop off the lower order terms,\n % plus terms directly above DerivativeOrder\n v = zeros(1,par.DerivativeOrder + par.MethodOrder - 1);\n v(par.DerivativeOrder) = 1;\n fdarule = v/fdamat(par.StepRatio,0,par.DerivativeOrder+par.MethodOrder-1);\n end\n \n % correct sign for the 'backward' rule\n if par.Style(1) == 'b'\n fdarule = -fdarule;\n end\n \nend % switch on par.style (generating fdarule)\nnfda = length(fdarule);\n\n% will we need fun(x0)?\nif (rem(par.DerivativeOrder,2) == 0) || ~strncmpi(par.Style,'central',7)\n if strcmpi(par.Vectorized,'yes')\n f_x0 = fun(x0);\n else\n % not vectorized, so loop\n f_x0 = zeros(size(x0));\n for j = 1:numel(x0)\n f_x0(j) = fun(x0(j));\n end\n end\nelse\n f_x0 = [];\nend\n\n% Loop over the elements of x0, reducing it to\n% a scalar problem. Sorry, vectorization is not\n% complete here, but this IS only a single loop.\nder = zeros(nx0);\nerrest = der;\nfinaldelta = der;\nfor i = 1:n\n x0i = x0(i);\n h = par.NominalStep(i);\n\n % a central, forward or backwards differencing rule?\n % f_del is the set of all the function evaluations we\n % will generate. For a central rule, it will have the\n % even or odd transformation built in.\n if par.Style(1) == 'c'\n % A central rule, so we will need to evaluate\n % symmetrically around x0i.\n if strcmpi(par.Vectorized,'yes')\n f_plusdel = fun(x0i+h*delta);\n f_minusdel = fun(x0i-h*delta);\n else\n % not vectorized, so loop\n f_minusdel = zeros(size(delta));\n f_plusdel = zeros(size(delta));\n for j = 1:numel(delta)\n f_plusdel(j) = fun(x0i+h*delta(j));\n f_minusdel(j) = fun(x0i-h*delta(j));\n end\n end\n \n if ismember(par.DerivativeOrder,[1 3])\n % odd transformation\n f_del = (f_plusdel - f_minusdel)/2;\n else\n f_del = (f_plusdel + f_minusdel)/2 - f_x0(i);\n end\n elseif par.Style(1) == 'f'\n % forward rule\n % drop off the constant only\n if strcmpi(par.Vectorized,'yes')\n f_del = fun(x0i+h*delta) - f_x0(i);\n else\n % not vectorized, so loop\n f_del = zeros(size(delta));\n for j = 1:numel(delta)\n f_del(j) = fun(x0i+h*delta(j)) - f_x0(i);\n end\n end\n else\n % backward rule\n % drop off the constant only\n if strcmpi(par.Vectorized,'yes')\n f_del = fun(x0i-h*delta) - f_x0(i);\n else\n % not vectorized, so loop\n f_del = zeros(size(delta));\n for j = 1:numel(delta)\n f_del(j) = fun(x0i-h*delta(j)) - f_x0(i);\n end\n end\n end\n \n % check the size of f_del to ensure it was properly vectorized.\n f_del = f_del(:);\n if length(f_del)~=ndel\n error 'fun did not return the correct size result (fun must be vectorized)'\n end\n\n % Apply the finite difference rule at each delta, scaling\n % as appropriate for delta and the requested DerivativeOrder.\n % First, decide how many of these estimates we will end up with.\n ne = ndel + 1 - nfda - par.RombergTerms;\n\n % Form the initial derivative estimates from the chosen\n % finite difference method.\n der_init = vec2mat(f_del,ne,nfda)*fdarule.';\n\n % scale to reflect the local delta\n der_init = der_init(:)./(h*delta(1:ne)).^par.DerivativeOrder;\n \n % Each approximation that results is an approximation\n % of order par.DerivativeOrder to the desired derivative.\n % Additional (higher order, even or odd) terms in the\n % Taylor series also remain. Use a generalized (multi-term)\n % Romberg extrapolation to improve these estimates.\n switch par.Style\n case 'central'\n rombexpon = 2*(1:par.RombergTerms) + par.MethodOrder - 2;\n otherwise\n rombexpon = (1:par.RombergTerms) + par.MethodOrder - 1;\n end\n [der_romb,errors] = rombextrap(par.StepRatio,der_init,rombexpon);\n \n % Choose which result to return\n \n % first, trim off the \n if isempty(par.FixedStep)\n % trim off the estimates at each end of the scale\n nest = length(der_romb);\n switch par.DerivativeOrder\n case {1 2}\n trim = [1 2 nest-1 nest];\n case 3\n trim = [1:4 nest+(-3:0)];\n case 4\n trim = [1:6 nest+(-5:0)];\n end\n \n [der_romb,tags] = sort(der_romb);\n \n der_romb(trim) = [];\n tags(trim) = [];\n errors = errors(tags);\n trimdelta = delta(tags);\n \n [errest(i),ind] = min(errors);\n \n finaldelta(i) = h*trimdelta(ind);\n der(i) = der_romb(ind);\n else\n [errest(i),ind] = min(errors);\n finaldelta(i) = h*delta(ind);\n der(i) = der_romb(ind);\n end\nend\n\nend % mainline end\n\n% ============================================\n% subfunction - romberg extrapolation\n% ============================================\nfunction [der_romb,errest] = rombextrap(StepRatio,der_init,rombexpon)\n% do romberg extrapolation for each estimate\n%\n% StepRatio - Ratio decrease in step\n% der_init - initial derivative estimates\n% rombexpon - higher order terms to cancel using the romberg step\n%\n% der_romb - derivative estimates returned\n% errest - error estimates\n% amp - noise amplification factor due to the romberg step\n\nsrinv = 1/StepRatio;\n\n% do nothing if no romberg terms\nnexpon = length(rombexpon);\nrmat = ones(nexpon+2,nexpon+1);\nswitch nexpon\n case 0\n % rmat is simple: ones(2,1)\n case 1\n % only one romberg term\n rmat(2,2) = srinv^rombexpon;\n rmat(3,2) = srinv^(2*rombexpon);\n case 2\n % two romberg terms\n rmat(2,2:3) = srinv.^rombexpon;\n rmat(3,2:3) = srinv.^(2*rombexpon);\n rmat(4,2:3) = srinv.^(3*rombexpon);\n case 3\n % three romberg terms\n rmat(2,2:4) = srinv.^rombexpon;\n rmat(3,2:4) = srinv.^(2*rombexpon);\n rmat(4,2:4) = srinv.^(3*rombexpon);\n rmat(5,2:4) = srinv.^(4*rombexpon);\nend\n\n% qr factorization used for the extrapolation as well\n% as the uncertainty estimates\n[qromb,rromb] = qr(rmat,0);\n\n% the noise amplification is further amplified by the Romberg step.\n% amp = cond(rromb);\n\n% this does the extrapolation to a zero step size.\nne = length(der_init);\nrhs = vec2mat(der_init,nexpon+2,max(1,ne - (nexpon+2)));\nrombcoefs = rromb\\(qromb.'*rhs); \nder_romb = rombcoefs(1,:).';\n\n% uncertainty estimate of derivative prediction\ns = sqrt(sum((rhs - rmat*rombcoefs).^2,1));\nrinv = rromb\\eye(nexpon+1);\ncov1 = sum(rinv.^2,2); % 1 spare dof\nerrest = s.'*12.7062047361747*sqrt(cov1(1));\n\nend % rombextrap\n\n\n% ============================================\n% subfunction - vec2mat\n% ============================================\nfunction mat = vec2mat(vec,n,m)\n% forms the matrix M, such that M(i,j) = vec(i+j-1)\n[i,j] = ndgrid(1:n,0:m-1);\nind = i+j;\nmat = vec(ind);\nif n==1\n mat = mat.';\nend\n\nend % vec2mat\n\n\n% ============================================\n% subfunction - fdamat\n% ============================================\nfunction mat = fdamat(sr,parity,nterms)\n% Compute matrix for fda derivation.\n% parity can be\n% 0 (one sided, all terms included but zeroth order)\n% 1 (only odd terms included)\n% 2 (only even terms included)\n% nterms - number of terms\n\n% sr is the ratio between successive steps\nsrinv = 1./sr;\n\nswitch parity\n case 0\n % single sided rule\n [i,j] = ndgrid(1:nterms);\n c = 1./factorial(1:nterms);\n mat = c(j).*srinv.^((i-1).*j);\n case 1\n % odd order derivative\n [i,j] = ndgrid(1:nterms);\n c = 1./factorial(1:2:(2*nterms));\n mat = c(j).*srinv.^((i-1).*(2*j-1));\n case 2\n % even order derivative\n [i,j] = ndgrid(1:nterms);\n c = 1./factorial(2:2:(2*nterms));\n mat = c(j).*srinv.^((i-1).*(2*j));\nend\n\nend % fdamat\n\n\n\n% ============================================\n% subfunction - check_params\n% ============================================\nfunction par = check_params(par)\n% check the parameters for acceptability\n%\n% Defaults\n% par.DerivativeOrder = 1;\n% par.MethodOrder = 2;\n% par.Style = 'central';\n% par.RombergTerms = 2;\n% par.FixedStep = [];\n\n% DerivativeOrder == 1 by default\nif isempty(par.DerivativeOrder)\n par.DerivativeOrder = 1;\nelse\n if (length(par.DerivativeOrder)>1) || ~ismember(par.DerivativeOrder,1:4)\n error 'DerivativeOrder must be scalar, one of [1 2 3 4].'\n end\nend\n\n% MethodOrder == 2 by default\nif isempty(par.MethodOrder)\n par.MethodOrder = 2;\nelse\n if (length(par.MethodOrder)>1) || ~ismember(par.MethodOrder,[1 2 3 4])\n error 'MethodOrder must be scalar, one of [1 2 3 4].'\n elseif ismember(par.MethodOrder,[1 3]) && (par.Style(1)=='c')\n error 'MethodOrder==1 or 3 is not possible with central difference methods'\n end\nend\n\n% style is char\nvalid = {'central', 'forward', 'backward'};\nif isempty(par.Style)\n par.Style = 'central';\nelseif ~ischar(par.Style)\n error 'Invalid Style: Must be character'\nend\nind = find(strncmpi(par.Style,valid,length(par.Style)));\nif (length(ind)==1)\n par.Style = valid{ind};\nelse\n error(['Invalid Style: ',par.Style])\nend\n\n% vectorized is char\nvalid = {'yes', 'no'};\nif isempty(par.Vectorized)\n par.Vectorized = 'yes';\nelseif ~ischar(par.Vectorized)\n error 'Invalid Vectorized: Must be character'\nend\nind = find(strncmpi(par.Vectorized,valid,length(par.Vectorized)));\nif (length(ind)==1)\n par.Vectorized = valid{ind};\nelse\n error(['Invalid Vectorized: ',par.Vectorized])\nend\n\n% RombergTerms == 2 by default\nif isempty(par.RombergTerms)\n par.RombergTerms = 2;\nelse\n if (length(par.RombergTerms)>1) || ~ismember(par.RombergTerms,0:3)\n error 'RombergTerms must be scalar, one of [0 1 2 3].'\n end\nend\n\n% FixedStep == [] by default\nif (length(par.FixedStep)>1) || (~isempty(par.FixedStep) && (par.FixedStep<=0))\n error 'FixedStep must be empty or a scalar, >0.'\nend\n\n% MaxStep == 10 by default\nif isempty(par.MaxStep)\n par.MaxStep = 10;\nelseif (length(par.MaxStep)>1) || (par.MaxStep<=0)\n error 'MaxStep must be empty or a scalar, >0.'\nend\n\nend % check_params\n\n\n% ============================================\n% Included subfunction - parse_pv_pairs\n% ============================================\nfunction params=parse_pv_pairs(params,pv_pairs)\n% parse_pv_pairs: parses sets of property value pairs, allows defaults\n% usage: params=parse_pv_pairs(default_params,pv_pairs)\n%\n% arguments: (input)\n% default_params - structure, with one field for every potential\n% property/value pair. Each field will contain the default\n% value for that property. If no default is supplied for a\n% given property, then that field must be empty.\n%\n% pv_array - cell array of property/value pairs.\n% Case is ignored when comparing properties to the list\n% of field names. Also, any unambiguous shortening of a\n% field/property name is allowed.\n%\n% arguments: (output)\n% params - parameter struct that reflects any updated property/value\n% pairs in the pv_array.\n%\n% Example usage:\n% First, set default values for the parameters. Assume we\n% have four parameters that we wish to use optionally in\n% the function examplefun.\n%\n% - 'viscosity', which will have a default value of 1\n% - 'volume', which will default to 1\n% - 'pie' - which will have default value 3.141592653589793\n% - 'description' - a text field, left empty by default\n%\n% The first argument to examplefun is one which will always be\n% supplied.\n%\n% function examplefun(dummyarg1,varargin)\n% params.Viscosity = 1;\n% params.Volume = 1;\n% params.Pie = 3.141592653589793\n%\n% params.Description = '';\n% params=parse_pv_pairs(params,varargin);\n% params\n%\n% Use examplefun, overriding the defaults for 'pie', 'viscosity'\n% and 'description'. The 'volume' parameter is left at its default.\n%\n% examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world')\n%\n% params = \n% Viscosity: 10\n% Volume: 1\n% Pie: 3\n% Description: 'Hello world'\n%\n% Note that capitalization was ignored, and the property 'viscosity'\n% was truncated as supplied. Also note that the order the pairs were\n% supplied was arbitrary.\n\nnpv = length(pv_pairs);\nn = npv/2;\n\nif n~=floor(n)\n error 'Property/value pairs must come in PAIRS.'\nend\nif n<=0\n % just return the defaults\n return\nend\n\nif ~isstruct(params)\n error 'No structure for defaults was supplied'\nend\n\n% there was at least one pv pair. process any supplied\npropnames = fieldnames(params);\nlpropnames = lower(propnames);\nfor i=1:n\n p_i = lower(pv_pairs{2*i-1});\n v_i = pv_pairs{2*i};\n \n ind = strmatch(p_i,lpropnames,'exact');\n if isempty(ind)\n ind = find(strncmp(p_i,lpropnames,length(p_i)));\n if isempty(ind)\n error(['No matching property found for: ',pv_pairs{2*i-1}])\n elseif length(ind)>1\n error(['Ambiguous property name: ',pv_pairs{2*i-1}])\n end\n end\n p_i = propnames{ind};\n \n % override the corresponding default in params\n params = setfield(params,p_i,v_i); %#ok\n \nend\n\nend % parse_pv_pairs\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "jacenfox/sun-moon-Positions-master", "name": "LunarCalendar.m", "ext": ".m", "path": "sun-moon-Positions-master/3rd_party/LunarCalendar.m", "size": 5732, "source_encoding": "utf_8", "md5": "3d0ffddf382c0f40ca2ea0a47b249076", "text": "function xx = LunarCalendar(y,m,d)\r\n%  function xx = LunarCalendar(y,m,d)\r\n%  \r\n%\r\nif nargin==0;\r\n cccc=clock;\r\n y=cccc(1);m=cccc(2);d=cccc(3);\r\nelse if ischar(y)\r\n y = str2num(y); m = str2num(m); d = str2num(d);\r\n end\r\nend\r\n\r\n% Animals={'鼠','牛','虎','兔','龙','蛇','马','羊','猴','鸡','狗','猪'};\r\n% CnDayStr={'初一', '初二', '初三', '初四', '初五', ...\r\n% '初六', '初七', '初八', '初九', '初十', ...\r\n% '十一', '十二', '十三', '十四', '十五', ...\r\n% '十六', '十七', '十八', '十九', '二十', ...\r\n% '廿一', '廿二', '廿三', '廿四', '廿五', ...\r\n% '廿六', '廿七', '廿八', '廿九', '三十'};\r\nCnDayStr={'LD01', 'LD02', 'LD03', 'LD04', 'LD05', ...\r\n 'LD06', 'LD07', 'LD08', 'LD09', 'LD10', ...\r\n 'LD11', 'LD12', 'LD13', 'LD14', 'LD15', ...\r\n 'LD16', 'LD17', 'LD18', 'LD19', 'LD20', ...\r\n 'LD21', 'LD22', 'LD23', 'LD24', 'LD25', ...\r\n 'LD26', 'LD27', 'LD28', 'LD29', 'LD30'};\r\n% CnMonthStr= { '正', '二', '三', '四', '五', '六', '七', '八', '九', '十', '冬', '腊'};\r\nCnMonthStr= { 'LM01', 'LM02', 'LM03', 'LM04', 'LM05', 'LM06', ...\r\n 'LM07', 'LM08', 'LM09', 'LM10', 'LM11', 'LM12'};\r\n\r\nmonthName = {'JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'}; \r\nlunarInfo=[19416,19168,42352,21717,53856,55632,91476,22176,39632,21970, ...\r\n 19168,42422,42192,53840,119381,46400,54944,44450,38320,84343, ...\r\n 18800,42160,46261,27216,27968,109396,11104,38256,21234,18800, ...\r\n 25958,54432,59984,28309,23248,11104,100067,37600,116951,51536, ...\r\n 54432,120998,46416,22176,107956,9680,37584,53938,43344,46423, ...\r\n 27808,46416,86869,19872,42448,83315,21200,43432,59728,27296, ...\r\n 44710,43856,19296,43748,42352,21088,62051,55632,23383,22176, ...\r\n 38608,19925,19152,42192,54484,53840,54616,46400,46496,103846, ...\r\n 38320,18864,43380,42160,45690,27216,27968,44870,43872,38256, ...\r\n 19189,18800,25776,29859,59984,27480,21952,43872,38613,37600, ...\r\n 51552,55636,54432,55888,30034,22176,43959,9680,37584,51893, ...\r\n 43344,46240,47780,44368,21977,19360,42416,86390,21168,43312, ...\r\n 31060,27296,44368,23378,19296,42726,42208,53856,60005,54576, ...\r\n 23200,30371,38608,19415,19152,42192,118966,53840,54560,56645, ...\r\n 46496,22224,21938,18864,42359,42160,43600,111189,27936,44448]; \r\nlYearDays=[384,354,355,383,354,355,384,354,355,384, ...\r\n 354,384,354,354,384,354,355,384,355,384, ...\r\n 354,354,384,354,354,385,354,355,384,354, ...\r\n 383,354,355,384,355,354,384,354,384,354, ...\r\n 354,384,355,354,385,354,354,384,354,384, ...\r\n 354,355,384,354,355,384,354,383,355,354, ...\r\n 384,355,354,384,355,353,384,355,384,354, ...\r\n 355,384,354,354,384,354,384,354,355,384, ...\r\n 355,354,384,354,384,354,354,384,355,355, ...\r\n 384,354,354,383,355,384,354,355,384,354, ...\r\n 354,384,354,355,384,354,385,354,354,384, ...\r\n 354,354,384,355,384,354,355,384,354,354, ...\r\n 384,354,355,384,354,384,354,354,384,355, ...\r\n 354,384,355,384,354,354,384,354,354,384, ...\r\n 355,355,384,354,384,354,354,384,354,355]; \r\nleapDays=[29,0,0,29,0,0,30,0,0,29, ...\r\n 0,29,0,0,30,0,0,29,0,30, ...\r\n 0,0,29,0,0,30,0,0,29,0, ...\r\n 29,0,0,29,0,0,30,0,30,0, ...\r\n 0,30,0,0,30,0,0,29,0,29, ...\r\n 0,0,30,0,0,30,0,29,0,0, ...\r\n 29,0,0,29,0,0,29,0,29,0, ...\r\n 0,29,0,0,29,0,29,0,0,30, ...\r\n 0,0,29,0,29,0,0,29,0,0, ...\r\n 29,0,0,29,0,29,0,0,29,0, ...\r\n 0,29,0,0,29,0,29,0,0,29, ...\r\n 0,0,29,0,29,0,0,30,0,0, ...\r\n 29,0,0,29,0,29,0,0,29,0, ...\r\n 0,29,0,29,0,0,30,0,0,29, ...\r\n 0,0,29,0,29,0,0,30,0,0]; \r\nleapMonth=[8,0,0,5,0,0,4,0,0,2, ...\r\n 0,6,0,0,5,0,0,2,0,7, ...\r\n 0,0,5,0,0,4,0,0,2,0, ...\r\n 6,0,0,5,0,0,3,0,7,0, ...\r\n 0,6,0,0,4,0,0,2,0,7, ...\r\n 0,0,5,0,0,3,0,8,0,0, ...\r\n 6,0,0,4,0,0,3,0,7,0, ...\r\n 0,5,0,0,4,0,8,0,0,6, ...\r\n 0,0,4,0,10,0,0,6,0,0, ...\r\n 5,0,0,3,0,8,0,0,5,0, ...\r\n 0,4,0,0,2,0,7,0,0,5, ...\r\n 0,0,4,0,9,0,0,6,0,0, ...\r\n 4,0,0,2,0,6,0,0,5,0, ...\r\n 0,3,0,7,0,0,6,0,0,5, ...\r\n 0,0,2,0,7,0,0,5,0,0];\r\n \r\noffset=datenum(y,m,d)-datenum(1900,1,31)+1; \r\ndayCyl = offset + 40;\r\nmonCyl = 14; \r\n\r\ncumLYearDays=cumsum([0,lYearDays]);\r\nLunarYear=find(offset>cumLYearDays);\r\nLunarYear=LunarYear(end);\r\nmonCyl=monCyl+(LunarYear-1)*12;yearCyl = LunarYear+36; \r\noffset=offset-cumLYearDays(LunarYear); \r\nmonthDays=[29,30];\r\nmonthDays=monthDays((bitand(lunarInfo(LunarYear),bitshift (65536,-(1:12)))~=0)+1); \r\nleap = leapMonth(LunarYear);\r\nif leap,\r\n monthDays=[monthDays(1:leap),leapDays(LunarYear),monthDays(leap+1:end)];\r\nend\r\ncumMonthDays=cumsum([0,monthDays]);\r\nLunarMonth=find(offset>cumMonthDays);LunarMonth=LunarMonth(end);\r\noffset=offset-cumMonthDays(LunarMonth);\r\nch_run_ch='';\r\nif leap \r\n if LunarMonth==(leap+1)\r\n ch_run_ch='loop'; \r\n end\r\n if (LunarMonth>leap)\r\n LunarMonth=LunarMonth-1;\r\n end\r\nend\r\nmonCyl=monCyl+LunarMonth;\r\nxx=['LunarDate:',CnMonthStr{LunarMonth},':',CnDayStr{offset},''];\r\n% xx=['农历',Animals{rem(yearCyl-1,12)+1},'年',ch_run_ch,CnMonthStr{LunarMonth},'月',CnDayStr{offset}];\r\n% xx={xx;[cyclical(yearCyl),'年  ',cyclical(monCyl),'月  ',cyclical(dayCyl),'日']};\r\nreturn \r\n\r\nfunction ganzhi=cyclical(num)\r\nGan={'甲','乙','丙','丁','戊','己','庚','辛','壬','癸'};\r\nZhi={'子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥'};\r\nganzhi=[Gan{rem(num-1,10)+1},Zhi{rem(num-1,12)+1}];\r\n \r\n"} +{"plateform": "github", "repo_name": "jacenfox/sun-moon-Positions-master", "name": "LunarAzEl.m", "ext": ".m", "path": "sun-moon-Positions-master/3rd_party/LunarAzEl.m", "size": 8768, "source_encoding": "utf_8", "md5": "304d78148bef528f612a5b76a8be0430", "text": "function [Az h] = LunarAzEl(UTC,Lat,Lon,Alt)\r\n\r\n% Programed by Darin C. Koblick 2/14/2009\r\n%\r\n% Updated on 03/04/2009 to clean up code and add quadrant check to Azimuth\r\n% Thank you Doug W. for your help with the test code to find the quadrant check \r\n% error.\r\n%\r\n% Updated on 04/13/2009 to add Lunar perturbation offsets (this will\r\n% increase the accuracy of calculations)\r\n%\r\n% Updated on 08/17/2010 to make use of the site altitude (this will affect\r\n% the elevation angle)\r\n\r\n% External Function Call Sequence:\r\n% [Az El] = LunarAzEl('1991/05/19 13:00:00',50,10,0)\r\n\r\n\r\n% Function Description:\r\n% LunarAzEl will ingest a Universal Time, and specific site location on earth\r\n% it will then output the lunar Azimuth and Elevation angles relative to that\r\n% site.\r\n\r\n% External Source References:\r\n\r\n% Basics of Positional Astronomy and Ephemerides\r\n% http://jgiesen.de/elevazmoon/basics/index.htm\r\n\r\n% Computing planetary positions - a tutorial with worked examples\r\n% http://stjarnhimlen.se/comp/tutorial.html\r\n\r\n%Input Description:\r\n% UTC (Coordinated Universal Time YYYY/MM/DD hh:mm:ss)\r\n% Lat (Site Latitude in degrees -90:90 -> S(-) N(+))\r\n% Lon (Site Longitude in degrees -180:180 W(-) E(+))\r\n% Altitude of the site above sea level (km)\r\n\r\n%Output Description:\r\n%Az (Azimuth location of the moon in degrees)\r\n%El (Elevation location of the moon in degrees)\r\n\r\n%Verified output by comparison with the following source data:\r\n%http://aa.usno.navy.mil/data/docs/AltAz.php\r\n\r\n% Code Sequence\r\n%--------------------------------------------------------------------------\r\n%Do initial Longitude Latitude check\r\n\r\nwhile Lon > 180\r\n Lon = Lon - 360;\r\nend\r\nwhile Lon < -180\r\n Lon = Lon + 360; \r\nend\r\nwhile Lat > 90\r\n Lat = Lat - 360;\r\nend\r\nwhile Lat < -90\r\n Lat = Lat + 360; \r\nend\r\n\r\n\r\n%Declare Earth Equatorial Radius Measurements in km\r\nEarthRadEq = 6378.1370;\r\n\r\n%Convert Universal Time to Ephemeris Time\r\njd = juliandate(UTC,'yyyy/mm/dd HH:MM:SS');\r\n\r\n%Find the Day Number\r\nd = jd - 2451543.5;\r\n\r\n%Keplerian Elements of the Moon\r\n%This will also account for the Sun's perturbation\r\n N = 125.1228-0.0529538083.*d; % (Long asc. node deg)\r\n i = 5.1454; % (Inclination deg)\r\n w = 318.0634 + 0.1643573223.*d; % (Arg. of perigee deg)\r\n a = 60.2666;% (Mean distance (Earth's Equitorial Radii)\r\n e = 0.054900;% (Eccentricity)\r\n M = mod(115.3654+13.0649929509.*d,360);% (Mean anomaly deg)\r\n \r\n LMoon = mod(N + w + M,360); %(Moon's mean longitude deg)\r\n FMoon = mod(LMoon - N,360); %(Moon's argument of latitude)\r\n\r\n %Keplerian Elements of the Sun\r\n wSun = mod(282.9404 + 4.70935E-5.*d,360); % (longitude of perihelion)\r\n MSun = mod(356.0470 + 0.9856002585.*d,360); % (Sun mean anomaly)\r\n LSun = mod(wSun + MSun,360); % (Sun's mean longitude)\r\n \r\n DMoon = LMoon - LSun; % (Moon's mean elongation) \r\n\r\n\r\n %Calculate Lunar perturbations in Longitude\r\n LunarPLon = [ -1.274.*sin((M - 2.*DMoon).*(pi/180)); ...\r\n .658.*sin(2.*DMoon.*(pi/180)); ...\r\n -0.186.*sin(MSun.*(pi/180)); ...\r\n -0.059.*sin((2.*M-2.*DMoon).*(pi/180)); ...\r\n -0.057.*sin((M-2.*DMoon + MSun).*(pi/180)); ...\r\n .053.*sin((M+2.*DMoon).*(pi/180)); ...\r\n .046.*sin((2.*DMoon-MSun).*(pi/180)); ...\r\n .041.*sin((M-MSun).*(pi/180)); ...\r\n -0.035.*sin(DMoon.*(pi/180)); ... \r\n -0.031.*sin((M+MSun).*(pi/180)); ...\r\n -0.015.*sin((2.*FMoon-2.*DMoon).*(pi/180)); ...\r\n .011.*sin((M-4.*DMoon).*(pi/180))];\r\n \r\n %Calculate Lunar perturbations in Latitude \r\n LunarPLat = [ -0.173.*sin((FMoon-2.*DMoon).*(pi/180)); ...\r\n -0.055.*sin((M-FMoon-2.*DMoon).*(pi/180)); ...\r\n -0.046.*sin((M+FMoon-2.*DMoon).*(pi/180)); ...\r\n +0.033.*sin((FMoon+2.*DMoon).*(pi/180)); ...\r\n +0.017.*sin((2.*M+FMoon).*(pi/180))];\r\n\r\n%Calculate perturbations in Distance\r\n LunarPDist = [ -0.58*cos((M-2.*DMoon).*(pi/180)); ...\r\n -0.46.*cos(2.*DMoon.*(pi/180))];\r\n\r\n% Compute E, the eccentric anomaly\r\n\r\n%E0 is the eccentric anomaly approximation estimate \r\n%(this will initially have a relativly high error)\r\nE0 = M+(180./pi).*e.*sin(M.*(pi/180)).*(1+e.*cos(M.*(pi/180)));\r\n\r\n%Compute E1 and set it to E0 until the E1 == E0\r\nE1 = E0-(E0-(180/pi).*e.*sin(E0.*(pi/180))-M)./(1-e*cos(E0.*(pi/180)));\r\nwhile E1-E0 > .000005\r\n E0 = E1;\r\n E1 = E0-(E0-(180/pi).*e.*sin(E0.*(pi/180))-M)./(1-e*cos(E0.*(pi/180))); \r\nend\r\nE = E1;\r\n\r\n%Compute rectangular coordinates (x,y) in the plane of the lunar orbit\r\nx = a.*(cos(E.*(pi/180))-e);\r\ny = a.*sqrt(1-e.*e).*sin(E.*(pi/180));\r\n\r\n%convert this to distance and true anomaly\r\nr = sqrt(x.*x + y.*y);\r\nv = atan2(y.*(pi/180),x.*(pi/180)).*(180/pi);\r\n\r\n%Compute moon's position in ecliptic coordinates\r\nxeclip = r.*(cos(N.*(pi/180)).*cos((v+w).*(pi/180))-sin(N.*(pi/180)).*sin((v+w).*(pi/180)).*cos(i.*(pi/180)));\r\nyeclip = r.*(sin(N.*(pi/180)).*cos((v+w).*(pi/180))+cos(N.*(pi/180))*sin(((v+w).*(pi/180)))*cos(i.*(pi/180)));\r\nzeclip = r.*sin((v+w).*(pi/180)).*sin(i.*(pi/180));\r\n\r\n%Add the calculated lunar perturbation terms to increase model fidelity\r\n[eLon eLat eDist] = cart2sph(xeclip,yeclip,zeclip);\r\n[xeclip yeclip zeclip] = sph2cart(eLon + sum(LunarPLon).*(pi/180), ...\r\n eLat + sum(LunarPLat).*(pi/180), ...\r\n eDist + sum(LunarPDist));\r\nclear eLon eLat eDist;\r\n \r\n%convert the latitude and longitude to right ascension RA and declination\r\n%delta\r\nT = (jd-2451545.0)/36525.0;\r\n\r\n%Generate a rotation matrix for ecliptic to equitorial\r\n%RotM=rotm_coo('E',jd);\r\n%See rotm_coo.m for obl and rotational matrix transformation\r\nObl = 23.439291 - 0.0130042.*T - 0.00000016.*T.*T + 0.000000504.*T.*T.*T;\r\nObl = Obl.*(pi/180);\r\nRotM = [1 0 0; 0 cos(Obl) sin(Obl); 0 -sin(Obl) cos(Obl)]';\r\n\r\n%Apply the rotational matrix to the ecliptic rectangular coordinates\r\n%Also, convert units to km instead of earth equatorial radii\r\nsol = RotM*[xeclip yeclip zeclip]'.*EarthRadEq;\r\n\r\n%Find the equatorial rectangular coordinates of the location specified\r\n[xel yel zel] = sph2cart(Lon.*(pi/180),Lat.*(pi/180),Alt+EarthRadEq);\r\n\r\n%Find the equatorial rectangular coordinates of the location @ sea level\r\n[xsl ysl zsl] = sph2cart(Lon.*(pi/180),Lat.*(pi/180),EarthRadEq);\r\n\r\n%Find the Angle Between sea level coordinate vector and the moon vector\r\ntheta1 = 180 - acosd(dot([xsl ysl zsl],[sol(1)-xsl sol(2)-ysl sol(3)-zsl]) ...\r\n ./(sqrt(xsl.^2 + ysl.^2 + zsl.^2) ...\r\n .*sqrt((sol(1)-xsl).^2 + (sol(2)-ysl).^2 + (sol(3)-zsl).^2)));\r\n\r\n%Find the Angle Between the same coordinates but at the specified elevation\r\ntheta2 = 180 - acosd(dot([xel yel zel],[sol(1)-xel sol(2)-yel sol(3)-zel]) ...\r\n ./(sqrt(xel.^2 + yel.^2 + zel.^2) ...\r\n .*sqrt((sol(1)-xel).^2 + (sol(2)-yel).^2 + (sol(3)-zel).^2)));\r\n \r\n%Find the Difference Between the two angles (+|-) is important\r\nthetaDiff = theta2 - theta1;\r\n\r\n% equatorial to horizon coordinate transformation\r\n [RA,delta] = cart2sph(sol(1),sol(2),sol(3));\r\n delta = delta.*(180/pi);\r\n RA = RA.*(180/pi);\r\n \r\n%Following the RA DEC to Az Alt conversion sequence explained here:\r\n%http://www.stargazing.net/kepler/altaz.html\r\n\r\n%Find the J2000 value\r\nJ2000 = jd - 2451545.0;\r\nhourvec = datevec(UTC,'yyyy/mm/dd HH:MM:SS');\r\nUTH = hourvec(4) + hourvec(5)/60 + hourvec(6)/3600;\r\n\r\n%Calculate local siderial time\r\nLST = mod(100.46+0.985647.*J2000+Lon+15*UTH,360);\r\n\r\n%Replace RA with hour angle HA\r\nHA = LST-RA;\r\n\r\n%Find the h and AZ at the current LST\r\nh = asin(sin(delta.*(pi/180)).*sin(Lat.*(pi/180)) + cos(delta.*(pi/180)).*cos(Lat.*(pi/180)).*cos(HA.*(pi/180))).*(180/pi);\r\nAz = acos((sin(delta.*(pi/180)) - sin(h.*(pi/180)).*sin(Lat.*(pi/180)))./(cos(h.*(pi/180)).*cos(Lat.*(pi/180)))).*(180/pi);\r\n\r\n%Add in the angle offset due to the specified site elevation\r\nh = h + thetaDiff;\r\n\r\nif sin(HA.*(pi/180)) >= 0\r\n Az = 360-Az; \r\nend\r\n\r\n%Apply Paralax Correction if we are still on earth\r\nif Alt < 100\r\n horParal = 8.794/(r*6379.14/149.59787e6);\r\n p = asin(cos(h.*(pi/180))*sin((horParal/3600).*(pi/180))).*(180/pi);\r\n h = h-p;\r\nend\r\n\r\nfunction jd = juliandate(varargin)\r\n% This sub function is provided in case juliandate does not come with your \r\n% distribution of Matlab\r\n\r\n[year month day hour min sec] = datevec(datenum(varargin{:}));\r\n\r\nfor k = length(month):-1:1\r\n if ( month(k) <= 2 ) % january & february\r\n year(k) = year(k) - 1.0;\r\n month(k) = month(k) + 12.0;\r\n end\r\nend\r\n\r\njd = floor( 365.25*(year + 4716.0)) + floor( 30.6001*( month + 1.0)) + 2.0 - ...\r\n floor( year/100.0 ) + floor( floor( year/100.0 )/4.0 ) + day - 1524.5 + ...\r\n (hour + min/60 + sec/3600)/24;\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "checkNumericalGradient.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 1/ex2/checkNumericalGradient.m", "size": 1982, "source_encoding": "utf_8", "md5": "689a352eb2927b0838af5dc508f6374d", "text": "function [] = checkNumericalGradient()\n% This code can be used to check your numerical gradient implementation \n% in computeNumericalGradient.m\n% It analytically evaluates the gradient of a very simple function called\n% simpleQuadraticFunction (see below) and compares the result with your numerical\n% solution. Your numerical gradient implementation is incorrect if\n% your numerical solution deviates too much from the analytical solution.\n \n% Evaluate the function and gradient at x = [4; 10]; (Here, x is a 2d vector.)\nx = [4; 10];\n[value, grad] = simpleQuadraticFunction(x);\n\n% Use your code to numerically compute the gradient of simpleQuadraticFunction at x.\n% (The notation \"@simpleQuadraticFunction\" denotes a pointer to a function.)\nnumgrad = computeNumericalGradient(@simpleQuadraticFunction, x);\n\n% Visually examine the two gradient computations. The two columns\n% you get should be very similar. \ndisp([numgrad grad]);\nfprintf('The above two columns you get should be very similar.\\n(Left-Your Numerical Gradient, Right-Analytical Gradient)\\n\\n');\n\n% Evaluate the norm of the difference between two solutions. \n% If you have a correct implementation, and assuming you used EPSILON = 0.0001 \n% in computeNumericalGradient.m, then diff below should be 2.1452e-12 \ndiff = norm(numgrad-grad)/norm(numgrad+grad);\ndisp(diff); \nfprintf('Norm of the difference between numerical and analytical gradient (should be < 1e-9)\\n\\n');\nend\n\n\n \nfunction [value,grad] = simpleQuadraticFunction(x)\n% this function accepts a 2D vector as input. \n% Its outputs are:\n% value: h(x1, x2) = x1^2 + 3*x1*x2\n% grad: A 2x1 vector that gives the partial derivatives of h with respect to x1 and x2 \n% Note that when we pass @simpleQuadraticFunction(x) to computeNumericalGradients, we're assuming\n% that computeNumericalGradients will use only the first returned value of this function.\n\nvalue = x(1)^2 + 3*x(1)*x(2);\n\ngrad = zeros(2, 1);\ngrad(1) = 2*x(1) + 3*x(2);\ngrad(2) = 3*x(1);\n\nend\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "sparseAutoencoderCost.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 1/ex2/sparseAutoencoderCost.m", "size": 4010, "source_encoding": "utf_8", "md5": "c24c49e3e21c0749cd4c5e1ab880bf38", "text": "function [cost,grad] = sparseAutoencoderCost(theta, visibleSize, hiddenSize, ...\n lambda, sparsityParam, beta, data)\n\n% visibleSize: the number of input units (probably 64) \n% hiddenSize: the number of hidden units (probably 25) \n% lambda: weight decay parameter\n% sparsityParam: The desired average activation for the hidden units (denoted in the lecture\n% notes by the greek alphabet rho, which looks like a lower-case \"p\").\n% beta: weight of sparsity penalty term\n% data: Our 64x10000 matrix containing the training data. So, data(:,i) is the i-th training example. \n \n% The input theta is a vector (because minFunc expects the parameters to be a vector). \n% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this \n% follows the notation convention of the lecture notes. \n\nW1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);\nW2 = reshape(theta(hiddenSize*visibleSize+1:2*hiddenSize*visibleSize), visibleSize, hiddenSize);\nb1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);\nb2 = theta(2*hiddenSize*visibleSize+hiddenSize+1:end);\n\n% Cost and gradient variables (your code needs to compute these values). \n% Here, we initialize them to zeros. \ncost = 0;\nW1grad = zeros(size(W1)); \nW2grad = zeros(size(W2));\nb1grad = zeros(size(b1)); \nb2grad = zeros(size(b2));\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Compute the cost/optimization objective J_sparse(W,b) for the Sparse Autoencoder,\n% and the corresponding gradients W1grad, W2grad, b1grad, b2grad.\n%\n% W1grad, W2grad, b1grad and b2grad should be computed using backpropagation.\n% Note that W1grad has the same dimensions as W1, b1grad has the same dimensions\n% as b1, etc. Your code should set W1grad to be the partial derivative of J_sparse(W,b) with\n% respect to W1. I.e., W1grad(i,j) should be the partial derivative of J_sparse(W,b) \n% with respect to the input parameter W1(i,j). Thus, W1grad should be equal to the term \n% [(1/m) \\Delta W^{(1)} + \\lambda W^{(1)}] in the last block of pseudo-code in Section 2.2 \n% of the lecture notes (and similarly for W2grad, b1grad, b2grad).\n% \n% Stated differently, if we were using batch gradient descent to optimize the parameters,\n% the gradient descent update to W1 would be W1 := W1 - alpha * W1grad, and similarly for W2, b1, b2. \n% \n\nnum = size(data,2);\n\na2 = sigmoid(W1*data + repmat(b1,1,num));\na3 = sigmoid(W2*a2 + repmat(b2,1,num));\n\nrho = (1/num)*sum(a2,2);\n%rho2 = zeros(hiddenSize,1);\n%KL = 0;\n%for i=1:hiddenSize\nKL = sum((sparsityParam*log(sparsityParam./rho)) + (1-sparsityParam)*log((1-sparsityParam)./(1-rho)));\nrho2 = -sparsityParam./rho + (1-sparsityParam)./(1-rho);\n%end\n\ncost = (0.5/num)*sum(sum((a3 - data).^2)) + (lambda/2)*(sum(sum(W1.^2)) + sum(sum(W2.^2))) + beta*KL;\n\nerror3 = -(data - a3).*(a3.*(1-a3));\nerror2 = ((W2')*error3 + beta*(repmat(rho2,1,num))).*(a2.*(1-a2));\n\n%W1grad = error2*(data');\n%W2grad = error3*(a2');\n%b1grad = sum(error2,2);\n%b2grad = sum(error3,2);\n\nW1grad = (1/num)*(error2*(data')) + lambda*W1;\nW2grad = (1/num)*(error3*(a2')) + lambda*W2;\nb1grad = (1/num)*(sum(error2,2));\nb2grad = (1/num)*(sum(error3,2));\n\n%size(W1grad)\n%size(W2grad)\n%size(b1grad)\n%size(b2grad)\n\n%-------------------------------------------------------------------\n% After computing the cost and gradient, we will convert the gradients back\n% to a vector format (suitable for minFunc). Specifically, we will unroll\n% your gradient matrices into a vector.\n\ngrad = [W1grad(:) ; W2grad(:) ; b1grad(:) ; b2grad(:)];\n\nend\n\n%-------------------------------------------------------------------\n% Here's an implementation of the sigmoid function, which you may find useful\n% in your computation of the costs and the gradients. This inputs a (row or\n% column) vector (say (z1, z2, z3)) and returns (f(z1), f(z2), f(z3)). \n\nfunction sigm = sigmoid(x)\n \n sigm = 1 ./ (1 + exp(-x));\nend\n\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "sampleIMAGES.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 1/ex2/sampleIMAGES.m", "size": 2165, "source_encoding": "utf_8", "md5": "df015d16283096f395df05efdeb24b05", "text": "function patches = sampleIMAGES()\n% sampleIMAGES\n% Returns 10000 patches for training\naddpath ../data/\naddpath ../mnist/\nload IMAGES; % load images from disk \n\npatchsize = 8; % we'll use 8x8 patches \nnumpatches = 10000;\n\n% Initialize patches with zeros. Your code will fill in this matrix--one\n% column per patch, 10000 columns. \npatches = zeros(patchsize*patchsize, numpatches);\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Fill in the variable called \"patches\" using data \n% from IMAGES. \n% \n% IMAGES is a 3D array containing 10 images\n% For instance, IMAGES(:,:,6) is a 512x512 array containing the 6th image,\n% and you can type \"imagesc(IMAGES(:,:,6)), colormap gray;\" to visualize\n% it. (The contrast on these images look a bit off because they have\n% been preprocessed using using \"whitening.\" See the lecture notes for\n% more details.) As a second example, IMAGES(21:30,21:30,1) is an image\n% patch corresponding to the pixels in the block (21,21) to (30,30) of\n% Image 1\n\nfor i=1:10000\n img_num = randi(10);\n x_start = randi(505);\n y_start = randi(505);\n x_end = x_start+7;\n y_end = y_start+7; \n patches(:,i) = reshape(IMAGES(x_start:x_end,y_start:y_end,img_num),patchsize*patchsize, 1);\nend\n\n\n\n\n\n\n\n\n\n\n%% ---------------------------------------------------------------\n% For the autoencoder to work well we need to normalize the data\n% Specifically, since the output of the network is bounded between [0,1]\n% (due to the sigmoid activation function), we have to make sure \n% the range of pixel values is also bounded between [0,1]\npatches = normalizeData(patches);\n\nend\n\n\n%% ---------------------------------------------------------------\nfunction patches = normalizeData(patches)\n\n% Squash data to [0.1, 0.9] since we use sigmoid as the activation\n% function in the output layer\n\n% Remove DC (mean of images). \npatches = bsxfun(@minus, patches, mean(patches));\n\n% Truncate to +/-3 standard deviations and scale to -1 to 1\npstd = 3 * std(patches(:));\npatches = max(min(patches, pstd), -pstd) / pstd;\n\n% Rescale from [-1,1] to [0.1,0.9]\npatches = (patches + 1) * 0.4 + 0.1;\n\nend\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "feedForwardAutoencoder.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 1/ex4/feedForwardAutoencoder.m", "size": 1297, "source_encoding": "utf_8", "md5": "2c3b46b1ca573b264b8bc8392003e2d2", "text": "function [activation] = feedForwardAutoencoder(theta, hiddenSize, visibleSize, data)\n\n% theta: trained weights from the autoencoder\n% visibleSize: the number of input units (probably 64) \n% hiddenSize: the number of hidden units (probably 25) \n% data: Our matrix containing the training data as columns. So, data(:,i) is the i-th training example. \n \n% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this \n% follows the notation convention of the lecture notes. \n\nW1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);\nb1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Compute the activation of the hidden layer for the Sparse Autoencoder.\n\nactivation = sigmoid(W1*data + repmat(b1,1,size(data,2)));\n\n\n%-------------------------------------------------------------------\n\nend\n\n%-------------------------------------------------------------------\n% Here's an implementation of the sigmoid function, which you may find useful\n% in your computation of the costs and the gradients. This inputs a (row or\n% column) vector (say (z1, z2, z3)) and returns (f(z1), f(z2), f(z3)). \n\nfunction sigm = sigmoid(x)\n sigm = 1 ./ (1 + exp(-x));\nend\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "checkNumericalGradient.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 1/ex1/checkNumericalGradient.m", "size": 1982, "source_encoding": "utf_8", "md5": "689a352eb2927b0838af5dc508f6374d", "text": "function [] = checkNumericalGradient()\n% This code can be used to check your numerical gradient implementation \n% in computeNumericalGradient.m\n% It analytically evaluates the gradient of a very simple function called\n% simpleQuadraticFunction (see below) and compares the result with your numerical\n% solution. Your numerical gradient implementation is incorrect if\n% your numerical solution deviates too much from the analytical solution.\n \n% Evaluate the function and gradient at x = [4; 10]; (Here, x is a 2d vector.)\nx = [4; 10];\n[value, grad] = simpleQuadraticFunction(x);\n\n% Use your code to numerically compute the gradient of simpleQuadraticFunction at x.\n% (The notation \"@simpleQuadraticFunction\" denotes a pointer to a function.)\nnumgrad = computeNumericalGradient(@simpleQuadraticFunction, x);\n\n% Visually examine the two gradient computations. The two columns\n% you get should be very similar. \ndisp([numgrad grad]);\nfprintf('The above two columns you get should be very similar.\\n(Left-Your Numerical Gradient, Right-Analytical Gradient)\\n\\n');\n\n% Evaluate the norm of the difference between two solutions. \n% If you have a correct implementation, and assuming you used EPSILON = 0.0001 \n% in computeNumericalGradient.m, then diff below should be 2.1452e-12 \ndiff = norm(numgrad-grad)/norm(numgrad+grad);\ndisp(diff); \nfprintf('Norm of the difference between numerical and analytical gradient (should be < 1e-9)\\n\\n');\nend\n\n\n \nfunction [value,grad] = simpleQuadraticFunction(x)\n% this function accepts a 2D vector as input. \n% Its outputs are:\n% value: h(x1, x2) = x1^2 + 3*x1*x2\n% grad: A 2x1 vector that gives the partial derivatives of h with respect to x1 and x2 \n% Note that when we pass @simpleQuadraticFunction(x) to computeNumericalGradients, we're assuming\n% that computeNumericalGradients will use only the first returned value of this function.\n\nvalue = x(1)^2 + 3*x(1)*x(2);\n\ngrad = zeros(2, 1);\ngrad(1) = 2*x(1) + 3*x(2);\ngrad(2) = 3*x(1);\n\nend\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "sparseAutoencoderCost.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 1/ex1/sparseAutoencoderCost.m", "size": 4010, "source_encoding": "utf_8", "md5": "c24c49e3e21c0749cd4c5e1ab880bf38", "text": "function [cost,grad] = sparseAutoencoderCost(theta, visibleSize, hiddenSize, ...\n lambda, sparsityParam, beta, data)\n\n% visibleSize: the number of input units (probably 64) \n% hiddenSize: the number of hidden units (probably 25) \n% lambda: weight decay parameter\n% sparsityParam: The desired average activation for the hidden units (denoted in the lecture\n% notes by the greek alphabet rho, which looks like a lower-case \"p\").\n% beta: weight of sparsity penalty term\n% data: Our 64x10000 matrix containing the training data. So, data(:,i) is the i-th training example. \n \n% The input theta is a vector (because minFunc expects the parameters to be a vector). \n% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this \n% follows the notation convention of the lecture notes. \n\nW1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);\nW2 = reshape(theta(hiddenSize*visibleSize+1:2*hiddenSize*visibleSize), visibleSize, hiddenSize);\nb1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);\nb2 = theta(2*hiddenSize*visibleSize+hiddenSize+1:end);\n\n% Cost and gradient variables (your code needs to compute these values). \n% Here, we initialize them to zeros. \ncost = 0;\nW1grad = zeros(size(W1)); \nW2grad = zeros(size(W2));\nb1grad = zeros(size(b1)); \nb2grad = zeros(size(b2));\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Compute the cost/optimization objective J_sparse(W,b) for the Sparse Autoencoder,\n% and the corresponding gradients W1grad, W2grad, b1grad, b2grad.\n%\n% W1grad, W2grad, b1grad and b2grad should be computed using backpropagation.\n% Note that W1grad has the same dimensions as W1, b1grad has the same dimensions\n% as b1, etc. Your code should set W1grad to be the partial derivative of J_sparse(W,b) with\n% respect to W1. I.e., W1grad(i,j) should be the partial derivative of J_sparse(W,b) \n% with respect to the input parameter W1(i,j). Thus, W1grad should be equal to the term \n% [(1/m) \\Delta W^{(1)} + \\lambda W^{(1)}] in the last block of pseudo-code in Section 2.2 \n% of the lecture notes (and similarly for W2grad, b1grad, b2grad).\n% \n% Stated differently, if we were using batch gradient descent to optimize the parameters,\n% the gradient descent update to W1 would be W1 := W1 - alpha * W1grad, and similarly for W2, b1, b2. \n% \n\nnum = size(data,2);\n\na2 = sigmoid(W1*data + repmat(b1,1,num));\na3 = sigmoid(W2*a2 + repmat(b2,1,num));\n\nrho = (1/num)*sum(a2,2);\n%rho2 = zeros(hiddenSize,1);\n%KL = 0;\n%for i=1:hiddenSize\nKL = sum((sparsityParam*log(sparsityParam./rho)) + (1-sparsityParam)*log((1-sparsityParam)./(1-rho)));\nrho2 = -sparsityParam./rho + (1-sparsityParam)./(1-rho);\n%end\n\ncost = (0.5/num)*sum(sum((a3 - data).^2)) + (lambda/2)*(sum(sum(W1.^2)) + sum(sum(W2.^2))) + beta*KL;\n\nerror3 = -(data - a3).*(a3.*(1-a3));\nerror2 = ((W2')*error3 + beta*(repmat(rho2,1,num))).*(a2.*(1-a2));\n\n%W1grad = error2*(data');\n%W2grad = error3*(a2');\n%b1grad = sum(error2,2);\n%b2grad = sum(error3,2);\n\nW1grad = (1/num)*(error2*(data')) + lambda*W1;\nW2grad = (1/num)*(error3*(a2')) + lambda*W2;\nb1grad = (1/num)*(sum(error2,2));\nb2grad = (1/num)*(sum(error3,2));\n\n%size(W1grad)\n%size(W2grad)\n%size(b1grad)\n%size(b2grad)\n\n%-------------------------------------------------------------------\n% After computing the cost and gradient, we will convert the gradients back\n% to a vector format (suitable for minFunc). Specifically, we will unroll\n% your gradient matrices into a vector.\n\ngrad = [W1grad(:) ; W2grad(:) ; b1grad(:) ; b2grad(:)];\n\nend\n\n%-------------------------------------------------------------------\n% Here's an implementation of the sigmoid function, which you may find useful\n% in your computation of the costs and the gradients. This inputs a (row or\n% column) vector (say (z1, z2, z3)) and returns (f(z1), f(z2), f(z3)). \n\nfunction sigm = sigmoid(x)\n \n sigm = 1 ./ (1 + exp(-x));\nend\n\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "sampleIMAGES.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 1/ex1/sampleIMAGES.m", "size": 2165, "source_encoding": "utf_8", "md5": "df015d16283096f395df05efdeb24b05", "text": "function patches = sampleIMAGES()\n% sampleIMAGES\n% Returns 10000 patches for training\naddpath ../data/\naddpath ../mnist/\nload IMAGES; % load images from disk \n\npatchsize = 8; % we'll use 8x8 patches \nnumpatches = 10000;\n\n% Initialize patches with zeros. Your code will fill in this matrix--one\n% column per patch, 10000 columns. \npatches = zeros(patchsize*patchsize, numpatches);\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Fill in the variable called \"patches\" using data \n% from IMAGES. \n% \n% IMAGES is a 3D array containing 10 images\n% For instance, IMAGES(:,:,6) is a 512x512 array containing the 6th image,\n% and you can type \"imagesc(IMAGES(:,:,6)), colormap gray;\" to visualize\n% it. (The contrast on these images look a bit off because they have\n% been preprocessed using using \"whitening.\" See the lecture notes for\n% more details.) As a second example, IMAGES(21:30,21:30,1) is an image\n% patch corresponding to the pixels in the block (21,21) to (30,30) of\n% Image 1\n\nfor i=1:10000\n img_num = randi(10);\n x_start = randi(505);\n y_start = randi(505);\n x_end = x_start+7;\n y_end = y_start+7; \n patches(:,i) = reshape(IMAGES(x_start:x_end,y_start:y_end,img_num),patchsize*patchsize, 1);\nend\n\n\n\n\n\n\n\n\n\n\n%% ---------------------------------------------------------------\n% For the autoencoder to work well we need to normalize the data\n% Specifically, since the output of the network is bounded between [0,1]\n% (due to the sigmoid activation function), we have to make sure \n% the range of pixel values is also bounded between [0,1]\npatches = normalizeData(patches);\n\nend\n\n\n%% ---------------------------------------------------------------\nfunction patches = normalizeData(patches)\n\n% Squash data to [0.1, 0.9] since we use sigmoid as the activation\n% function in the output layer\n\n% Remove DC (mean of images). \npatches = bsxfun(@minus, patches, mean(patches));\n\n% Truncate to +/-3 standard deviations and scale to -1 to 1\npstd = 3 * std(patches(:));\npatches = max(min(patches, pstd), -pstd) / pstd;\n\n% Rescale from [-1,1] to [0.1,0.9]\npatches = (patches + 1) * 0.4 + 0.1;\n\nend\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "WolfeLineSearch.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 1/minFunc/WolfeLineSearch.m", "size": 11478, "source_encoding": "utf_8", "md5": "d10187f2fedfa4143ebd6300537b6be4", "text": "function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(...\r\n x,t,d,f,g,gtd,c1,c2,LS,maxLS,tolX,debug,doPlot,saveHessianComp,funObj,varargin)\r\n%\r\n% Bracketing Line Search to Satisfy Wolfe Conditions\r\n%\r\n% Inputs:\r\n% x: starting location\r\n% t: initial step size\r\n% d: descent direction\r\n% f: function value at starting location\r\n% g: gradient at starting location\r\n% gtd: directional derivative at starting location\r\n% c1: sufficient decrease parameter\r\n% c2: curvature parameter\r\n% debug: display debugging information\r\n% LS: type of interpolation\r\n% maxLS: maximum number of iterations\r\n% tolX: minimum allowable step length\r\n% doPlot: do a graphical display of interpolation\r\n% funObj: objective function\r\n% varargin: parameters of objective function\r\n%\r\n% Outputs:\r\n% t: step length\r\n% f_new: function value at x+t*d\r\n% g_new: gradient value at x+t*d\r\n% funEvals: number function evaluations performed by line search\r\n% H: Hessian at initial guess (only computed if requested\r\n\r\n% Evaluate the Objective and Gradient at the Initial Step\r\nif nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\nelse\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\nend\r\nfunEvals = 1;\r\ngtd_new = g_new'*d;\r\n\r\n% Bracket an Interval containing a point satisfying the\r\n% Wolfe criteria\r\n\r\nLSiter = 0;\r\nt_prev = 0;\r\nf_prev = f;\r\ng_prev = g;\r\ngtd_prev = gtd;\r\ndone = 0;\r\n\r\nwhile LSiter < maxLS\r\n\r\n %% Bracketing Phase\r\n if ~isLegal(f_new) || ~isLegal(g_new)\r\n if 0\r\n if debug\r\n fprintf('Extrapolated into illegal region, Bisecting\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n continue;\r\n else\r\n if debug\r\n fprintf('Extrapolated into illegal region, switching to Armijo line-search\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n % Do Armijo\r\n if nargout == 5\r\n [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n else\r\n [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n end\r\n funEvals = funEvals + armijoFunEvals;\r\n return;\r\n end\r\n end\r\n\r\n\r\n if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev)\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n elseif abs(gtd_new) <= -c2*gtd\r\n bracket = t;\r\n bracketFval = f_new;\r\n bracketGval = g_new;\r\n done = 1;\r\n break;\r\n elseif gtd_new >= 0\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n end\r\n temp = t_prev;\r\n t_prev = t;\r\n minStep = t + 0.01*(t-temp);\r\n maxStep = t*10;\r\n if LS == 3\r\n if debug\r\n fprintf('Extending Braket\\n');\r\n end\r\n t = maxStep;\r\n elseif LS ==4\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep);\r\n else\r\n t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot);\r\n end\r\n \r\n f_prev = f_new;\r\n g_prev = g_new;\r\n gtd_prev = gtd_new;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\nend\r\n\r\nif LSiter == maxLS\r\n bracket = [0 t];\r\n bracketFval = [f f_new];\r\n bracketGval = [g g_new];\r\nend\r\n\r\n%% Zoom Phase\r\n\r\n% We now either have a point satisfying the criteria, or a bracket\r\n% surrounding a point satisfying the criteria\r\n% Refine the bracket until we find a point satisfying the criteria\r\ninsufProgress = 0;\r\nTpos = 2;\r\nLOposRemoved = 0;\r\nwhile ~done && LSiter < maxLS\r\n\r\n % Find High and Low Points in bracket\r\n [f_LO LOpos] = min(bracketFval);\r\n HIpos = -LOpos + 3;\r\n\r\n % Compute new trial value\r\n if LS == 3 || ~isLegal(bracketFval) || ~isLegal(bracketGval)\r\n if debug\r\n fprintf('Bisecting\\n');\r\n end\r\n t = mean(bracket);\r\n elseif LS == 4\r\n if debug\r\n fprintf('Grad-Cubic Interpolation\\n');\r\n end\r\n t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d\r\n bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot);\r\n else\r\n % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n nonTpos = -Tpos+3;\r\n if LOposRemoved == 0\r\n oldLOval = bracket(nonTpos);\r\n oldLOFval = bracketFval(nonTpos);\r\n oldLOGval = bracketGval(:,nonTpos);\r\n end\r\n t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n end\r\n\r\n\r\n % Test that we are making sufficient progress\r\n if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1\r\n if debug\r\n fprintf('Interpolation close to boundary');\r\n end\r\n if insufProgress || t>=max(bracket) || t <= min(bracket)\r\n if debug\r\n fprintf(', Evaluating at 0.1 away from boundary\\n');\r\n end\r\n if abs(t-max(bracket)) < abs(t-min(bracket))\r\n t = max(bracket)-0.1*(max(bracket)-min(bracket));\r\n else\r\n t = min(bracket)+0.1*(max(bracket)-min(bracket));\r\n end\r\n insufProgress = 0;\r\n else\r\n if debug\r\n fprintf('\\n');\r\n end\r\n insufProgress = 1;\r\n end\r\n else\r\n insufProgress = 0;\r\n end\r\n\r\n % Evaluate new point\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n\r\n if f_new > f + c1*t*gtd || f_new >= f_LO\r\n % Armijo condition not satisfied or not lower than lowest\r\n % point\r\n bracket(HIpos) = t;\r\n bracketFval(HIpos) = f_new;\r\n bracketGval(:,HIpos) = g_new;\r\n Tpos = HIpos;\r\n else\r\n if abs(gtd_new) <= - c2*gtd\r\n % Wolfe conditions satisfied\r\n done = 1;\r\n elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0\r\n % Old HI becomes new LO\r\n bracket(HIpos) = bracket(LOpos);\r\n bracketFval(HIpos) = bracketFval(LOpos);\r\n bracketGval(:,HIpos) = bracketGval(:,LOpos);\r\n if LS == 5\r\n if debug\r\n fprintf('LO Pos is being removed!\\n');\r\n end\r\n LOposRemoved = 1;\r\n oldLOval = bracket(LOpos);\r\n oldLOFval = bracketFval(LOpos);\r\n oldLOGval = bracketGval(:,LOpos);\r\n end\r\n end\r\n % New point becomes new LO\r\n bracket(LOpos) = t;\r\n bracketFval(LOpos) = f_new;\r\n bracketGval(:,LOpos) = g_new;\r\n Tpos = LOpos;\r\n end\r\n\r\n if ~done && abs((bracket(1)-bracket(2))*gtd_new) < tolX\r\n if debug\r\n fprintf('Line Search can not make further progress\\n');\r\n end\r\n break;\r\n end\r\n\r\nend\r\n\r\n%%\r\nif LSiter == maxLS\r\n if debug\r\n fprintf('Line Search Exceeded Maximum Line Search Iterations\\n');\r\n end\r\nend\r\n\r\n[f_LO LOpos] = min(bracketFval);\r\nt = bracket(LOpos);\r\nf_new = bracketFval(LOpos);\r\ng_new = bracketGval(:,LOpos);\r\n\r\n\r\n\r\n% Evaluate Hessian at new point\r\nif nargout == 5 && funEvals > 1 && saveHessianComp\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n funEvals = funEvals + 1;\r\nend\r\n\r\nend\r\n\r\n\r\n%%\r\nfunction [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot);\r\nalpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep);\r\nalpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep);\r\nif alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1)\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\nelse\r\n if debug\r\n fprintf('Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\nend\r\nend\r\n\r\n%%\r\nfunction [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n\r\n% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nnonTpos = -Tpos+3;\r\n\r\ngtdT = bracketGval(:,Tpos)'*d;\r\ngtdNonT = bracketGval(:,nonTpos)'*d;\r\noldLOgtd = oldLOGval'*d;\r\nif bracketFval(Tpos) > oldLOFval\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot);\r\n if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval)\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Mixed Quad/Cubic Interpolation\\n');\r\n end\r\n t = (alpha_q + alpha_c)/2;\r\n end\r\nelseif gtdT'*oldLOgtd < 0\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) sqrt(-1) gtdT],doPlot);\r\n if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Quad Interpolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\nelseif abs(gtdT) <= abs(oldLOgtd)\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n if alpha_c > min(bracket) && alpha_c < max(bracket)\r\n if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Bounded Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n\r\n if bracket(Tpos) > oldLOval\r\n t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n else\r\n t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n end\r\nelse\r\n t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\nend\r\nend"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "minFunc_processInputOptions.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 1/minFunc/minFunc_processInputOptions.m", "size": 3704, "source_encoding": "utf_8", "md5": "dc74c67d849970de7f16c873fcf155bc", "text": "\r\nfunction [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,...\r\n corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,...\r\n HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...\r\n DerivativeCheck,Damped,HvFunc,bbType,cycle,...\r\n HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ...\r\n minFunc_processInputOptions(o)\r\n\r\n% Constants\r\nSD = 0;\r\nCSD = 1;\r\nBB = 2;\r\nCG = 3;\r\nPCG = 4;\r\nLBFGS = 5;\r\nQNEWTON = 6;\r\nNEWTON0 = 7;\r\nNEWTON = 8;\r\nTENSOR = 9;\r\n\r\nverbose = 1;\r\nverboseI= 1;\r\ndebug = 0;\r\ndoPlot = 0;\r\nmethod = LBFGS;\r\ncgSolve = 0;\r\n\r\no = toUpper(o);\r\n\r\nif isfield(o,'DISPLAY')\r\n switch(upper(o.DISPLAY))\r\n case 0\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FINAL'\r\n verboseI = 0;\r\n case 'OFF'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'NONE'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FULL'\r\n debug = 1;\r\n case 'EXCESSIVE'\r\n debug = 1;\r\n doPlot = 1;\r\n end\r\nend\r\n\r\n\r\nLS_init = 0;\r\nc2 = 0.9;\r\nLS = 4;\r\nFref = 1;\r\nDamped = 0;\r\nHessianIter = 1;\r\nif isfield(o,'METHOD')\r\n m = upper(o.METHOD);\r\n switch(m)\r\n case 'TENSOR'\r\n method = TENSOR;\r\n case 'NEWTON'\r\n method = NEWTON;\r\n case 'MNEWTON'\r\n method = NEWTON;\r\n HessianIter = 5;\r\n case 'PNEWTON0'\r\n method = NEWTON0;\r\n cgSolve = 1;\r\n case 'NEWTON0'\r\n method = NEWTON0;\r\n case 'QNEWTON'\r\n method = QNEWTON;\r\n Damped = 1;\r\n case 'LBFGS'\r\n method = LBFGS;\r\n case 'BB'\r\n method = BB;\r\n LS = 2;\r\n Fref = 20;\r\n case 'PCG'\r\n method = PCG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'SCG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 4;\r\n case 'CG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'CSD'\r\n method = CSD;\r\n c2 = 0.2;\r\n Fref = 10;\r\n LS_init = 2;\r\n case 'SD'\r\n method = SD;\r\n LS_init = 2;\r\n end\r\nend\r\n\r\nmaxFunEvals = getOpt(o,'MAXFUNEVALS',1000);\r\nmaxIter = getOpt(o,'MAXITER',500);\r\ntolFun = getOpt(o,'TOLFUN',1e-5);\r\ntolX = getOpt(o,'TOLX',1e-9);\r\ncorrections = getOpt(o,'CORR',100);\r\nc1 = getOpt(o,'C1',1e-4);\r\nc2 = getOpt(o,'C2',c2);\r\nLS_init = getOpt(o,'LS_INIT',LS_init);\r\nLS = getOpt(o,'LS',LS);\r\ncgSolve = getOpt(o,'CGSOLVE',cgSolve);\r\nqnUpdate = getOpt(o,'QNUPDATE',3);\r\ncgUpdate = getOpt(o,'CGUPDATE',2);\r\ninitialHessType = getOpt(o,'INITIALHESSTYPE',1);\r\nHessianModify = getOpt(o,'HESSIANMODIFY',0);\r\nFref = getOpt(o,'FREF',Fref);\r\nuseComplex = getOpt(o,'USECOMPLEX',0);\r\nnumDiff = getOpt(o,'NUMDIFF',0);\r\nLS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1);\r\nDerivativeCheck = getOpt(o,'DERIVATIVECHECK',0);\r\nDamped = getOpt(o,'DAMPED',Damped);\r\nHvFunc = getOpt(o,'HVFUNC',[]);\r\nbbType = getOpt(o,'BBTYPE',0);\r\ncycle = getOpt(o,'CYCLE',3);\r\nHessianIter = getOpt(o,'HESSIANITER',HessianIter);\r\noutputFcn = getOpt(o,'OUTPUTFCN',[]);\r\nuseMex = getOpt(o,'USEMEX',1);\r\nuseNegCurv = getOpt(o,'USENEGCURV',1);\r\nprecFunc = getOpt(o,'PRECFUNC',[]);\r\nend\r\n\r\nfunction [v] = getOpt(options,opt,default)\r\nif isfield(options,opt)\r\n if ~isempty(getfield(options,opt))\r\n v = getfield(options,opt);\r\n else\r\n v = default;\r\n end\r\nelse\r\n v = default;\r\nend\r\nend\r\n\r\nfunction [o] = toUpper(o)\r\nif ~isempty(o)\r\n fn = fieldnames(o);\r\n for i = 1:length(fn)\r\n o = setfield(o,upper(fn{i}),getfield(o,fn{i}));\r\n end\r\nend\r\nend"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "sparseAutoencoderCost.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 2/revant_kumar/sparseAutoencoderCost.m", "size": 4010, "source_encoding": "utf_8", "md5": "c24c49e3e21c0749cd4c5e1ab880bf38", "text": "function [cost,grad] = sparseAutoencoderCost(theta, visibleSize, hiddenSize, ...\n lambda, sparsityParam, beta, data)\n\n% visibleSize: the number of input units (probably 64) \n% hiddenSize: the number of hidden units (probably 25) \n% lambda: weight decay parameter\n% sparsityParam: The desired average activation for the hidden units (denoted in the lecture\n% notes by the greek alphabet rho, which looks like a lower-case \"p\").\n% beta: weight of sparsity penalty term\n% data: Our 64x10000 matrix containing the training data. So, data(:,i) is the i-th training example. \n \n% The input theta is a vector (because minFunc expects the parameters to be a vector). \n% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this \n% follows the notation convention of the lecture notes. \n\nW1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);\nW2 = reshape(theta(hiddenSize*visibleSize+1:2*hiddenSize*visibleSize), visibleSize, hiddenSize);\nb1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);\nb2 = theta(2*hiddenSize*visibleSize+hiddenSize+1:end);\n\n% Cost and gradient variables (your code needs to compute these values). \n% Here, we initialize them to zeros. \ncost = 0;\nW1grad = zeros(size(W1)); \nW2grad = zeros(size(W2));\nb1grad = zeros(size(b1)); \nb2grad = zeros(size(b2));\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Compute the cost/optimization objective J_sparse(W,b) for the Sparse Autoencoder,\n% and the corresponding gradients W1grad, W2grad, b1grad, b2grad.\n%\n% W1grad, W2grad, b1grad and b2grad should be computed using backpropagation.\n% Note that W1grad has the same dimensions as W1, b1grad has the same dimensions\n% as b1, etc. Your code should set W1grad to be the partial derivative of J_sparse(W,b) with\n% respect to W1. I.e., W1grad(i,j) should be the partial derivative of J_sparse(W,b) \n% with respect to the input parameter W1(i,j). Thus, W1grad should be equal to the term \n% [(1/m) \\Delta W^{(1)} + \\lambda W^{(1)}] in the last block of pseudo-code in Section 2.2 \n% of the lecture notes (and similarly for W2grad, b1grad, b2grad).\n% \n% Stated differently, if we were using batch gradient descent to optimize the parameters,\n% the gradient descent update to W1 would be W1 := W1 - alpha * W1grad, and similarly for W2, b1, b2. \n% \n\nnum = size(data,2);\n\na2 = sigmoid(W1*data + repmat(b1,1,num));\na3 = sigmoid(W2*a2 + repmat(b2,1,num));\n\nrho = (1/num)*sum(a2,2);\n%rho2 = zeros(hiddenSize,1);\n%KL = 0;\n%for i=1:hiddenSize\nKL = sum((sparsityParam*log(sparsityParam./rho)) + (1-sparsityParam)*log((1-sparsityParam)./(1-rho)));\nrho2 = -sparsityParam./rho + (1-sparsityParam)./(1-rho);\n%end\n\ncost = (0.5/num)*sum(sum((a3 - data).^2)) + (lambda/2)*(sum(sum(W1.^2)) + sum(sum(W2.^2))) + beta*KL;\n\nerror3 = -(data - a3).*(a3.*(1-a3));\nerror2 = ((W2')*error3 + beta*(repmat(rho2,1,num))).*(a2.*(1-a2));\n\n%W1grad = error2*(data');\n%W2grad = error3*(a2');\n%b1grad = sum(error2,2);\n%b2grad = sum(error3,2);\n\nW1grad = (1/num)*(error2*(data')) + lambda*W1;\nW2grad = (1/num)*(error3*(a2')) + lambda*W2;\nb1grad = (1/num)*(sum(error2,2));\nb2grad = (1/num)*(sum(error3,2));\n\n%size(W1grad)\n%size(W2grad)\n%size(b1grad)\n%size(b2grad)\n\n%-------------------------------------------------------------------\n% After computing the cost and gradient, we will convert the gradients back\n% to a vector format (suitable for minFunc). Specifically, we will unroll\n% your gradient matrices into a vector.\n\ngrad = [W1grad(:) ; W2grad(:) ; b1grad(:) ; b2grad(:)];\n\nend\n\n%-------------------------------------------------------------------\n% Here's an implementation of the sigmoid function, which you may find useful\n% in your computation of the costs and the gradients. This inputs a (row or\n% column) vector (say (z1, z2, z3)) and returns (f(z1), f(z2), f(z3)). \n\nfunction sigm = sigmoid(x)\n \n sigm = 1 ./ (1 + exp(-x));\nend\n\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "stackedAEPredict.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 2/revant_kumar/stackedAEPredict.m", "size": 1601, "source_encoding": "utf_8", "md5": "26a168f67dac4800fdf4ac363cb78db1", "text": "function [pred] = stackedAEPredict(theta, inputSize, hiddenSize, numClasses, netconfig, data)\n \n% stackedAEPredict: Takes a trained theta and a test data set,\n% and returns the predicted labels for each example.\n \n% theta: trained weights from the autoencoder\n% visibleSize: the number of input units\n% hiddenSize: the number of hidden units *at the 2nd layer*\n% numClasses: the number of categories\n% data: Our matrix containing the training data as columns. So, data(:,i) is the i-th training example. \n\n% Your code should produce the prediction matrix \n% pred, where pred(i) is argmax_c P(y(c) | x(i)).\n \n%% Unroll theta parameter\n\n% We first extract the part which compute the softmax gradient\nsoftmaxTheta = reshape(theta(1:hiddenSize*numClasses), numClasses, hiddenSize);\n\n% Extract out the \"stack\"\nstack = params2stack(theta(hiddenSize*numClasses+1:end), netconfig);\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Compute pred using theta assuming that the labels start \n% from 1.\n\nactivation1 = sigmoid(stack{1}.w*data + repmat(stack{1}.b,1,size(data,2)));\nactivation2 = sigmoid(stack{2}.w*activation1 + repmat(stack{2}.b,1,size(data,2)));\nMat = softmaxTheta*activation2;\nMat = bsxfun(@minus, Mat, max(Mat, [], 1));\nMat = exp(Mat);\nMat = bsxfun(@rdivide, Mat, sum(Mat));\n[Max, pred] = max(Mat);\n\n% -----------------------------------------------------------\n\nend\n\n\n% You might find this useful\nfunction sigm = sigmoid(x)\n sigm = 1 ./ (1 + exp(-x));\nend\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "feedForwardAutoencoder.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 2/revant_kumar/feedForwardAutoencoder.m", "size": 1297, "source_encoding": "utf_8", "md5": "2c3b46b1ca573b264b8bc8392003e2d2", "text": "function [activation] = feedForwardAutoencoder(theta, hiddenSize, visibleSize, data)\n\n% theta: trained weights from the autoencoder\n% visibleSize: the number of input units (probably 64) \n% hiddenSize: the number of hidden units (probably 25) \n% data: Our matrix containing the training data as columns. So, data(:,i) is the i-th training example. \n \n% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this \n% follows the notation convention of the lecture notes. \n\nW1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);\nb1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: Compute the activation of the hidden layer for the Sparse Autoencoder.\n\nactivation = sigmoid(W1*data + repmat(b1,1,size(data,2)));\n\n\n%-------------------------------------------------------------------\n\nend\n\n%-------------------------------------------------------------------\n% Here's an implementation of the sigmoid function, which you may find useful\n% in your computation of the costs and the gradients. This inputs a (row or\n% column) vector (say (z1, z2, z3)) and returns (f(z1), f(z2), f(z3)). \n\nfunction sigm = sigmoid(x)\n sigm = 1 ./ (1 + exp(-x));\nend\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "stackedAECost.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 2/revant_kumar/stackedAECost.m", "size": 3883, "source_encoding": "utf_8", "md5": "2b6f8b14e7d998bf8bc26b2d5c4c346c", "text": "function [ cost, grad ] = stackedAECost(theta, inputSize, hiddenSize, ...\r\n numClasses, netconfig, ...\r\n lambda, data, labels)\r\n \r\n% stackedAECost: Takes a trained softmaxTheta and a training data set with labels,\r\n% and returns cost and gradient using a stacked autoencoder model. Used for\r\n% finetuning.\r\n \r\n% theta: trained weights from the autoencoder\r\n% visibleSize: the number of input units\r\n% hiddenSize: the number of hidden units *at the 2nd layer*\r\n% numClasses: the number of categories\r\n% netconfig: the network configuration of the stack\r\n% lambda: the weight regularization penalty\r\n% data: Our matrix containing the training data as columns. So, data(:,i) is the i-th training example. \r\n% labels: A vector containing labels, where labels(i) is the label for the\r\n% i-th training example\r\n\r\n\r\n%% Unroll softmaxTheta parameter\r\n\r\n% We first extract the part which compute the softmax gradient\r\nsoftmaxTheta = reshape(theta(1:hiddenSize*numClasses), numClasses, hiddenSize);\r\n\r\n% Extract out the \"stack\"\r\nstack = params2stack(theta(hiddenSize*numClasses+1:end), netconfig);\r\n\r\n% You will need to compute the following gradients\r\nsoftmaxThetaGrad = zeros(size(softmaxTheta));\r\nstackgrad = cell(size(stack));\r\nfor d = 1:numel(stack)\r\n stackgrad{d}.w = zeros(size(stack{d}.w));\r\n stackgrad{d}.b = zeros(size(stack{d}.b));\r\nend\r\n\r\ncost = 0; % You need to compute this\r\n\r\n% You might find these variables useful\r\nM = size(data, 2);\r\ngroundTruth = full(sparse(labels, 1:M, 1));\r\n\r\n\r\n%% --------------------------- YOUR CODE HERE -----------------------------\r\n% Instructions: Compute the cost function and gradient vector for \r\n% the stacked autoencoder.\r\n%\r\n% You are given a stack variable which is a cell-array of\r\n% the weights and biases for every layer. In particular, you\r\n% can refer to the weights of Layer d, using stack{d}.w and\r\n% the biases using stack{d}.b . To get the total number of\r\n% layers, you can use numel(stack).\r\n%\r\n% The last layer of the network is connected to the softmax\r\n% classification layer, softmaxTheta.\r\n%\r\n% You should compute the gradients for the softmaxTheta,\r\n% storing that in softmaxThetaGrad. Similarly, you should\r\n% compute the gradients for each layer in the stack, storing\r\n% the gradients in stackgrad{d}.w and stackgrad{d}.b\r\n% Note that the size of the matrices in stackgrad should\r\n% match exactly that of the size of the matrices in stack.\r\n%\r\n\r\na2 = sigmoid(stack{1}.w*data + repmat(stack{1}.b,1,M));\r\na3 = sigmoid(stack{2}.w*a2 + repmat(stack{2}.b,1,M));\r\nMat = softmaxTheta*a3;\r\nMat = bsxfun(@minus, Mat, max(Mat, [], 1));\r\nMat = exp(Mat);\r\nMat = bsxfun(@rdivide, Mat, sum(Mat));\r\ncost = (-1/M)*(sum(sum((groundTruth).*log(Mat)))) + (lambda/2)*sum(sum(softmaxTheta.^2)) + (lambda/2)*(sum(sum((stack{1}.w).^2)) + sum(sum((stack{2}.w).^2)));\r\n\r\nsoftmaxThetaGrad = (-1/M)*(a3*(groundTruth - Mat)')' + lambda*softmaxTheta;\r\n\r\nerror3 = ((-1)*(softmaxTheta'*(groundTruth - Mat))).*(a3.*(1-a3));\r\nerror2 = ((stack{2}.w')*error3).*(a2.*(1-a2));\r\n\r\nstackgrad{1}.w = (1/M)*(error2*(data')) + lambda*stack{1}.w;\r\nstackgrad{2}.w = (1/M)*(error3*(a2')) + lambda*stack{2}.w;\r\nstackgrad{1}.b = (1/M)*(sum(error2,2));\r\nstackgrad{2}.b = (1/M)*(sum(error3,2));\r\n\r\n\r\n\r\n\r\n\r\n% -------------------------------------------------------------------------\r\n\r\n%% Roll gradient vector\r\ngrad = [softmaxThetaGrad(:) ; stack2params(stackgrad)];\r\n\r\nend\r\n\r\n\r\n% You might find this useful\r\nfunction sigm = sigmoid(x)\r\n sigm = 1 ./ (1 + exp(-x));\r\nend\r\n"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "WolfeLineSearch.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 2/minFunc/WolfeLineSearch.m", "size": 11478, "source_encoding": "utf_8", "md5": "d10187f2fedfa4143ebd6300537b6be4", "text": "function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(...\r\n x,t,d,f,g,gtd,c1,c2,LS,maxLS,tolX,debug,doPlot,saveHessianComp,funObj,varargin)\r\n%\r\n% Bracketing Line Search to Satisfy Wolfe Conditions\r\n%\r\n% Inputs:\r\n% x: starting location\r\n% t: initial step size\r\n% d: descent direction\r\n% f: function value at starting location\r\n% g: gradient at starting location\r\n% gtd: directional derivative at starting location\r\n% c1: sufficient decrease parameter\r\n% c2: curvature parameter\r\n% debug: display debugging information\r\n% LS: type of interpolation\r\n% maxLS: maximum number of iterations\r\n% tolX: minimum allowable step length\r\n% doPlot: do a graphical display of interpolation\r\n% funObj: objective function\r\n% varargin: parameters of objective function\r\n%\r\n% Outputs:\r\n% t: step length\r\n% f_new: function value at x+t*d\r\n% g_new: gradient value at x+t*d\r\n% funEvals: number function evaluations performed by line search\r\n% H: Hessian at initial guess (only computed if requested\r\n\r\n% Evaluate the Objective and Gradient at the Initial Step\r\nif nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\nelse\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\nend\r\nfunEvals = 1;\r\ngtd_new = g_new'*d;\r\n\r\n% Bracket an Interval containing a point satisfying the\r\n% Wolfe criteria\r\n\r\nLSiter = 0;\r\nt_prev = 0;\r\nf_prev = f;\r\ng_prev = g;\r\ngtd_prev = gtd;\r\ndone = 0;\r\n\r\nwhile LSiter < maxLS\r\n\r\n %% Bracketing Phase\r\n if ~isLegal(f_new) || ~isLegal(g_new)\r\n if 0\r\n if debug\r\n fprintf('Extrapolated into illegal region, Bisecting\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n continue;\r\n else\r\n if debug\r\n fprintf('Extrapolated into illegal region, switching to Armijo line-search\\n');\r\n end\r\n t = (t + t_prev)/2;\r\n % Do Armijo\r\n if nargout == 5\r\n [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n else\r\n [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(...\r\n x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,...\r\n funObj,varargin{:});\r\n end\r\n funEvals = funEvals + armijoFunEvals;\r\n return;\r\n end\r\n end\r\n\r\n\r\n if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev)\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n elseif abs(gtd_new) <= -c2*gtd\r\n bracket = t;\r\n bracketFval = f_new;\r\n bracketGval = g_new;\r\n done = 1;\r\n break;\r\n elseif gtd_new >= 0\r\n bracket = [t_prev t];\r\n bracketFval = [f_prev f_new];\r\n bracketGval = [g_prev g_new];\r\n break;\r\n end\r\n temp = t_prev;\r\n t_prev = t;\r\n minStep = t + 0.01*(t-temp);\r\n maxStep = t*10;\r\n if LS == 3\r\n if debug\r\n fprintf('Extending Braket\\n');\r\n end\r\n t = maxStep;\r\n elseif LS ==4\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep);\r\n else\r\n t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot);\r\n end\r\n \r\n f_prev = f_new;\r\n g_prev = g_new;\r\n gtd_prev = gtd_new;\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\nend\r\n\r\nif LSiter == maxLS\r\n bracket = [0 t];\r\n bracketFval = [f f_new];\r\n bracketGval = [g g_new];\r\nend\r\n\r\n%% Zoom Phase\r\n\r\n% We now either have a point satisfying the criteria, or a bracket\r\n% surrounding a point satisfying the criteria\r\n% Refine the bracket until we find a point satisfying the criteria\r\ninsufProgress = 0;\r\nTpos = 2;\r\nLOposRemoved = 0;\r\nwhile ~done && LSiter < maxLS\r\n\r\n % Find High and Low Points in bracket\r\n [f_LO LOpos] = min(bracketFval);\r\n HIpos = -LOpos + 3;\r\n\r\n % Compute new trial value\r\n if LS == 3 || ~isLegal(bracketFval) || ~isLegal(bracketGval)\r\n if debug\r\n fprintf('Bisecting\\n');\r\n end\r\n t = mean(bracket);\r\n elseif LS == 4\r\n if debug\r\n fprintf('Grad-Cubic Interpolation\\n');\r\n end\r\n t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d\r\n bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot);\r\n else\r\n % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n nonTpos = -Tpos+3;\r\n if LOposRemoved == 0\r\n oldLOval = bracket(nonTpos);\r\n oldLOFval = bracketFval(nonTpos);\r\n oldLOGval = bracketGval(:,nonTpos);\r\n end\r\n t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n end\r\n\r\n\r\n % Test that we are making sufficient progress\r\n if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1\r\n if debug\r\n fprintf('Interpolation close to boundary');\r\n end\r\n if insufProgress || t>=max(bracket) || t <= min(bracket)\r\n if debug\r\n fprintf(', Evaluating at 0.1 away from boundary\\n');\r\n end\r\n if abs(t-max(bracket)) < abs(t-min(bracket))\r\n t = max(bracket)-0.1*(max(bracket)-min(bracket));\r\n else\r\n t = min(bracket)+0.1*(max(bracket)-min(bracket));\r\n end\r\n insufProgress = 0;\r\n else\r\n if debug\r\n fprintf('\\n');\r\n end\r\n insufProgress = 1;\r\n end\r\n else\r\n insufProgress = 0;\r\n end\r\n\r\n % Evaluate new point\r\n if ~saveHessianComp && nargout == 5\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n else\r\n [f_new,g_new] = feval(funObj, x + t*d, varargin{:}); \r\n end\r\n funEvals = funEvals + 1;\r\n gtd_new = g_new'*d;\r\n LSiter = LSiter+1;\r\n\r\n if f_new > f + c1*t*gtd || f_new >= f_LO\r\n % Armijo condition not satisfied or not lower than lowest\r\n % point\r\n bracket(HIpos) = t;\r\n bracketFval(HIpos) = f_new;\r\n bracketGval(:,HIpos) = g_new;\r\n Tpos = HIpos;\r\n else\r\n if abs(gtd_new) <= - c2*gtd\r\n % Wolfe conditions satisfied\r\n done = 1;\r\n elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0\r\n % Old HI becomes new LO\r\n bracket(HIpos) = bracket(LOpos);\r\n bracketFval(HIpos) = bracketFval(LOpos);\r\n bracketGval(:,HIpos) = bracketGval(:,LOpos);\r\n if LS == 5\r\n if debug\r\n fprintf('LO Pos is being removed!\\n');\r\n end\r\n LOposRemoved = 1;\r\n oldLOval = bracket(LOpos);\r\n oldLOFval = bracketFval(LOpos);\r\n oldLOGval = bracketGval(:,LOpos);\r\n end\r\n end\r\n % New point becomes new LO\r\n bracket(LOpos) = t;\r\n bracketFval(LOpos) = f_new;\r\n bracketGval(:,LOpos) = g_new;\r\n Tpos = LOpos;\r\n end\r\n\r\n if ~done && abs((bracket(1)-bracket(2))*gtd_new) < tolX\r\n if debug\r\n fprintf('Line Search can not make further progress\\n');\r\n end\r\n break;\r\n end\r\n\r\nend\r\n\r\n%%\r\nif LSiter == maxLS\r\n if debug\r\n fprintf('Line Search Exceeded Maximum Line Search Iterations\\n');\r\n end\r\nend\r\n\r\n[f_LO LOpos] = min(bracketFval);\r\nt = bracket(LOpos);\r\nf_new = bracketFval(LOpos);\r\ng_new = bracketGval(:,LOpos);\r\n\r\n\r\n\r\n% Evaluate Hessian at new point\r\nif nargout == 5 && funEvals > 1 && saveHessianComp\r\n [f_new,g_new,H] = feval(funObj, x + t*d, varargin{:}); \r\n funEvals = funEvals + 1;\r\nend\r\n\r\nend\r\n\r\n\r\n%%\r\nfunction [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot);\r\nalpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep);\r\nalpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep);\r\nif alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1)\r\n if debug\r\n fprintf('Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\nelse\r\n if debug\r\n fprintf('Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\nend\r\nend\r\n\r\n%%\r\nfunction [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\r\n\r\n% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nnonTpos = -Tpos+3;\r\n\r\ngtdT = bracketGval(:,Tpos)'*d;\r\ngtdNonT = bracketGval(:,nonTpos)'*d;\r\noldLOgtd = oldLOGval'*d;\r\nif bracketFval(Tpos) > oldLOFval\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot);\r\n if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval)\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Mixed Quad/Cubic Interpolation\\n');\r\n end\r\n t = (alpha_q + alpha_c)/2;\r\n end\r\nelseif gtdT'*oldLOgtd < 0\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\n alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) sqrt(-1) gtdT],doPlot);\r\n if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Cubic Interpolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Quad Interpolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\nelseif abs(gtdT) <= abs(oldLOgtd)\r\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd\r\n bracket(Tpos) bracketFval(Tpos) gtdT],...\r\n doPlot,min(bracket),max(bracket));\r\n if alpha_c > min(bracket) && alpha_c < max(bracket)\r\n if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos))\r\n if debug\r\n fprintf('Bounded Cubic Extrapolation\\n');\r\n end\r\n t = alpha_c;\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n else\r\n if debug\r\n fprintf('Bounded Secant Extrapolation\\n');\r\n end\r\n t = alpha_s;\r\n end\r\n\r\n if bracket(Tpos) > oldLOval\r\n t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n else\r\n t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\r\n end\r\nelse\r\n t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT\r\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\r\nend\r\nend"} +{"plateform": "github", "repo_name": "revantkumar/Deep-Learning-master", "name": "minFunc_processInputOptions.m", "ext": ".m", "path": "Deep-Learning-master/Assignments/Assignment 2/minFunc/minFunc_processInputOptions.m", "size": 3704, "source_encoding": "utf_8", "md5": "dc74c67d849970de7f16c873fcf155bc", "text": "\r\nfunction [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,...\r\n corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,...\r\n HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...\r\n DerivativeCheck,Damped,HvFunc,bbType,cycle,...\r\n HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ...\r\n minFunc_processInputOptions(o)\r\n\r\n% Constants\r\nSD = 0;\r\nCSD = 1;\r\nBB = 2;\r\nCG = 3;\r\nPCG = 4;\r\nLBFGS = 5;\r\nQNEWTON = 6;\r\nNEWTON0 = 7;\r\nNEWTON = 8;\r\nTENSOR = 9;\r\n\r\nverbose = 1;\r\nverboseI= 1;\r\ndebug = 0;\r\ndoPlot = 0;\r\nmethod = LBFGS;\r\ncgSolve = 0;\r\n\r\no = toUpper(o);\r\n\r\nif isfield(o,'DISPLAY')\r\n switch(upper(o.DISPLAY))\r\n case 0\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FINAL'\r\n verboseI = 0;\r\n case 'OFF'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'NONE'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FULL'\r\n debug = 1;\r\n case 'EXCESSIVE'\r\n debug = 1;\r\n doPlot = 1;\r\n end\r\nend\r\n\r\n\r\nLS_init = 0;\r\nc2 = 0.9;\r\nLS = 4;\r\nFref = 1;\r\nDamped = 0;\r\nHessianIter = 1;\r\nif isfield(o,'METHOD')\r\n m = upper(o.METHOD);\r\n switch(m)\r\n case 'TENSOR'\r\n method = TENSOR;\r\n case 'NEWTON'\r\n method = NEWTON;\r\n case 'MNEWTON'\r\n method = NEWTON;\r\n HessianIter = 5;\r\n case 'PNEWTON0'\r\n method = NEWTON0;\r\n cgSolve = 1;\r\n case 'NEWTON0'\r\n method = NEWTON0;\r\n case 'QNEWTON'\r\n method = QNEWTON;\r\n Damped = 1;\r\n case 'LBFGS'\r\n method = LBFGS;\r\n case 'BB'\r\n method = BB;\r\n LS = 2;\r\n Fref = 20;\r\n case 'PCG'\r\n method = PCG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'SCG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 4;\r\n case 'CG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'CSD'\r\n method = CSD;\r\n c2 = 0.2;\r\n Fref = 10;\r\n LS_init = 2;\r\n case 'SD'\r\n method = SD;\r\n LS_init = 2;\r\n end\r\nend\r\n\r\nmaxFunEvals = getOpt(o,'MAXFUNEVALS',1000);\r\nmaxIter = getOpt(o,'MAXITER',500);\r\ntolFun = getOpt(o,'TOLFUN',1e-5);\r\ntolX = getOpt(o,'TOLX',1e-9);\r\ncorrections = getOpt(o,'CORR',100);\r\nc1 = getOpt(o,'C1',1e-4);\r\nc2 = getOpt(o,'C2',c2);\r\nLS_init = getOpt(o,'LS_INIT',LS_init);\r\nLS = getOpt(o,'LS',LS);\r\ncgSolve = getOpt(o,'CGSOLVE',cgSolve);\r\nqnUpdate = getOpt(o,'QNUPDATE',3);\r\ncgUpdate = getOpt(o,'CGUPDATE',2);\r\ninitialHessType = getOpt(o,'INITIALHESSTYPE',1);\r\nHessianModify = getOpt(o,'HESSIANMODIFY',0);\r\nFref = getOpt(o,'FREF',Fref);\r\nuseComplex = getOpt(o,'USECOMPLEX',0);\r\nnumDiff = getOpt(o,'NUMDIFF',0);\r\nLS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1);\r\nDerivativeCheck = getOpt(o,'DERIVATIVECHECK',0);\r\nDamped = getOpt(o,'DAMPED',Damped);\r\nHvFunc = getOpt(o,'HVFUNC',[]);\r\nbbType = getOpt(o,'BBTYPE',0);\r\ncycle = getOpt(o,'CYCLE',3);\r\nHessianIter = getOpt(o,'HESSIANITER',HessianIter);\r\noutputFcn = getOpt(o,'OUTPUTFCN',[]);\r\nuseMex = getOpt(o,'USEMEX',1);\r\nuseNegCurv = getOpt(o,'USENEGCURV',1);\r\nprecFunc = getOpt(o,'PRECFUNC',[]);\r\nend\r\n\r\nfunction [v] = getOpt(options,opt,default)\r\nif isfield(options,opt)\r\n if ~isempty(getfield(options,opt))\r\n v = getfield(options,opt);\r\n else\r\n v = default;\r\n end\r\nelse\r\n v = default;\r\nend\r\nend\r\n\r\nfunction [o] = toUpper(o)\r\nif ~isempty(o)\r\n fn = fieldnames(o);\r\n for i = 1:length(fn)\r\n o = setfield(o,upper(fn{i}),getfield(o,fn{i}));\r\n end\r\nend\r\nend"} +{"plateform": "github", "repo_name": "CognitiveRobotics/pcl-master", "name": "plot_camera_poses.m", "ext": ".m", "path": "pcl-master/gpu/kinfu/tools/plot_camera_poses.m", "size": 3403, "source_encoding": "utf_8", "md5": "097aaeb35920a12acfe6320b3e4f498b", "text": "% Copyright (c) 2014-, Open Perception, Inc.\n% All rights reserved.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions\n% are met:\n%\n% * Redistributions of source code must retain the above copyright\n% notice, this list of conditions and the following disclaimer.\n% * Redistributions in binary form must reproduce the above\n% copyright notice, this list of conditions and the following\n% disclaimer in the documentation and/or other materials provided\n% with the distribution.\n% * Neither the name of the copyright holder(s) nor the names of its\n% contributors may be used to endorse or promote products derived\n% from this software without specific prior written permission.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n% \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n% COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n% POSSIBILITY OF SUCH DAMAGE.\n% Author: Marco Paladini \n\n% sample octave script to load camera poses from file and plot them\n% example usage: run 'pcl_kinfu_app -save_pose camera.csv' to save\n% camera poses in a 'camera.csv' file\n% run octave and cd into the directory where this script resides\n% and call plot_camera_poses('')\n\nfunction plot_camera_poses(filename)\nposes=load(filename);\n%% show data on a 2D graph\nh=figure();\nplot(poses,'*-');\nlegend('x','y','z','qw','qx','qy','qz');\n\n%% show data as 3D axis\nh=figure();\nfor n=1:size(poses,1)\n t=poses(n,1:3);\n q=poses(n,4:7);\n r=q2rot(q);\n coord(h,r,t);\nend\noctave_axis_equal(h);\n\n%% prevent Octave from quitting if called from the command line\ninput('Press enter to continue'); \nend\n\nfunction coord(h,r,t)\nfigure(h);\nhold on;\nc={'r','g','b'};\np=0.1*[1 0 0;0 1 0;0 0 1];\nfor n=1:3 \n a=r*p(n,:)';\n plot3([t(1),t(1)+a(1)], [t(2),t(2)+a(2)], [t(3),t(3)+a(3)], 'color', c{n});\nend\n\nfunction R=q2rot(q)\n% conversion code from http://en.wikipedia.org/wiki/Rotation_matrix%Quaternion\t\nNq = q(1)^2 + q(2)^2 + q(3)^2 + q(4)^2;\nif Nq>0; s=2/Nq; else s=0; end\nX = q(2)*s; Y = q(3)*s; Z = q(4)*s;\nwX = q(1)*X; wY = q(1)*Y; wZ = q(1)*Z;\nxX = q(2)*X; xY = q(2)*Y; xZ = q(2)*Z;\nyY = q(3)*Y; yZ = q(3)*Z; zZ = q(4)*Z;\nR=[ 1.0-(yY+zZ) xY-wZ xZ+wY ;\n xY+wZ 1.0-(xX+zZ) yZ-wX ;\n xZ-wY yZ+wX 1.0-(xX+yY) ];\nend\n\nfunction octave_axis_equal(h)\n% workaround for axis auto not working in 3d\n% tanks http://octave.1599824.n4.nabble.com/axis-equal-help-tp1636701p1636702.html\nfigure(h);\nxl = get (gca, \"xlim\");\nyl = get (gca, \"ylim\");\nzl = get (gca, \"zlim\");\nspan = max ([diff(xl), diff(yl), diff(zl)]);\nxlim (mean (xl) + span*[-0.5, 0.5])\nylim (mean (yl) + span*[-0.5, 0.5])\nzlim (mean (zl) + span*[-0.5, 0.5])\nend\n\n"} +{"plateform": "github", "repo_name": "steflee/MCL_Caffe-master", "name": "prepare_batch.m", "ext": ".m", "path": "MCL_Caffe-master/matlab/caffe/prepare_batch.m", "size": 1298, "source_encoding": "utf_8", "md5": "68088231982895c248aef25b4886eab0", "text": "% ------------------------------------------------------------------------\nfunction images = prepare_batch(image_files,IMAGE_MEAN,batch_size)\n% ------------------------------------------------------------------------\nif nargin < 2\n d = load('ilsvrc_2012_mean');\n IMAGE_MEAN = d.image_mean; \nend\nnum_images = length(image_files);\nif nargin < 3\n batch_size = num_images;\nend\n\nIMAGE_DIM = 256;\nCROPPED_DIM = 227;\nindices = [0 IMAGE_DIM-CROPPED_DIM] + 1;\ncenter = floor(indices(2) / 2)+1;\n\nnum_images = length(image_files);\nimages = zeros(CROPPED_DIM,CROPPED_DIM,3,batch_size,'single');\n\nparfor i=1:num_images\n % read file\n fprintf('%c Preparing %s\\n',13,image_files{i});\n try\n im = imread(image_files{i});\n % resize to fixed input size\n im = single(im);\n im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');\n % Transform GRAY to RGB\n if size(im,3) == 1\n im = cat(3,im,im,im);\n end\n % permute from RGB to BGR (IMAGE_MEAN is already BGR)\n im = im(:,:,[3 2 1]) - IMAGE_MEAN;\n % Crop the center of the image\n images(:,:,:,i) = permute(im(center:center+CROPPED_DIM-1,...\n center:center+CROPPED_DIM-1,:),[2 1 3]);\n catch\n warning('Problems with file',image_files{i});\n end\nend"} +{"plateform": "github", "repo_name": "steflee/MCL_Caffe-master", "name": "matcaffe_demo_vgg.m", "ext": ".m", "path": "MCL_Caffe-master/matlab/caffe/matcaffe_demo_vgg.m", "size": 3036, "source_encoding": "utf_8", "md5": "f836eefad26027ac1be6e24421b59543", "text": "function scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file)\n% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file)\n%\n% Demo of the matlab wrapper using the networks described in the BMVC-2014 paper \"Return of the Devil in the Details: Delving Deep into Convolutional Nets\"\n%\n% INPUT\n% im - color image as uint8 HxWx3\n% use_gpu - 1 to use the GPU, 0 to use the CPU\n% model_def_file - network configuration (.prototxt file)\n% model_file - network weights (.caffemodel file)\n% mean_file - mean BGR image as uint8 HxWx3 (.mat file)\n%\n% OUTPUT\n% scores 1000-dimensional ILSVRC score vector\n%\n% EXAMPLE USAGE\n% model_def_file = 'zoo/VGG_CNN_F_deploy.prototxt';\n% model_file = 'zoo/VGG_CNN_F.caffemodel';\n% mean_file = 'zoo/VGG_mean.mat';\n% use_gpu = true;\n% im = imread('../../examples/images/cat.jpg');\n% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file);\n% \n% NOTES\n% the image crops are prepared as described in the paper (the aspect ratio is preserved)\n%\n% PREREQUISITES\n% You may need to do the following before you start matlab:\n% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda/lib64\n% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6\n% Or the equivalent based on where things are installed on your system\n\n% init caffe network (spews logging info)\nmatcaffe_init(use_gpu, model_def_file, model_file);\n\n% prepare oversampled input\n% input_data is Height x Width x Channel x Num\ntic;\ninput_data = {prepare_image(im, mean_file)};\ntoc;\n\n% do forward pass to get scores\n% scores are now Width x Height x Channels x Num\ntic;\nscores = caffe('forward', input_data);\ntoc;\n\nscores = scores{1};\n% size(scores)\nscores = squeeze(scores);\n% scores = mean(scores,2);\n\n% [~,maxlabel] = max(scores);\n\n% ------------------------------------------------------------------------\nfunction images = prepare_image(im, mean_file)\n% ------------------------------------------------------------------------\nIMAGE_DIM = 256;\nCROPPED_DIM = 224;\n\nd = load(mean_file);\nIMAGE_MEAN = d.image_mean;\n\n% resize to fixed input size\nim = single(im);\n\nif size(im, 1) < size(im, 2)\n im = imresize(im, [IMAGE_DIM NaN]);\nelse\n im = imresize(im, [NaN IMAGE_DIM]);\nend\n\n% RGB -> BGR\nim = im(:, :, [3 2 1]);\n\n% oversample (4 corners, center, and their x-axis flips)\nimages = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');\n\nindices_y = [0 size(im,1)-CROPPED_DIM] + 1;\nindices_x = [0 size(im,2)-CROPPED_DIM] + 1;\ncenter_y = floor(indices_y(2) / 2)+1;\ncenter_x = floor(indices_x(2) / 2)+1;\n\ncurr = 1;\nfor i = indices_y\n for j = indices_x\n images(:, :, :, curr) = ...\n permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :)-IMAGE_MEAN, [2 1 3]);\n images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);\n curr = curr + 1;\n end\nend\nimages(:,:,:,5) = ...\n permute(im(center_y:center_y+CROPPED_DIM-1,center_x:center_x+CROPPED_DIM-1,:)-IMAGE_MEAN, ...\n [2 1 3]);\nimages(:,:,:,10) = images(end:-1:1, :, :, curr);\n"} +{"plateform": "github", "repo_name": "steflee/MCL_Caffe-master", "name": "matcaffe_demo.m", "ext": ".m", "path": "MCL_Caffe-master/matlab/caffe/matcaffe_demo.m", "size": 3344, "source_encoding": "utf_8", "md5": "669622769508a684210d164ac749a614", "text": "function [scores, maxlabel] = matcaffe_demo(im, use_gpu)\n% scores = matcaffe_demo(im, use_gpu)\n%\n% Demo of the matlab wrapper using the ILSVRC network.\n%\n% input\n% im color image as uint8 HxWx3\n% use_gpu 1 to use the GPU, 0 to use the CPU\n%\n% output\n% scores 1000-dimensional ILSVRC score vector\n%\n% You may need to do the following before you start matlab:\n% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64\n% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6\n% Or the equivalent based on where things are installed on your system\n%\n% Usage:\n% im = imread('../../examples/images/cat.jpg');\n% scores = matcaffe_demo(im, 1);\n% [score, class] = max(scores);\n% Five things to be aware of:\n% caffe uses row-major order\n% matlab uses column-major order\n% caffe uses BGR color channel order\n% matlab uses RGB color channel order\n% images need to have the data mean subtracted\n\n% Data coming in from matlab needs to be in the order \n% [width, height, channels, images]\n% where width is the fastest dimension.\n% Here is the rough matlab for putting image data into the correct\n% format:\n% % convert from uint8 to single\n% im = single(im);\n% % reshape to a fixed size (e.g., 227x227)\n% im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');\n% % permute from RGB to BGR and subtract the data mean (already in BGR)\n% im = im(:,:,[3 2 1]) - data_mean;\n% % flip width and height to make width the fastest dimension\n% im = permute(im, [2 1 3]);\n\n% If you have multiple images, cat them with cat(4, ...)\n\n% The actual forward function. It takes in a cell array of 4-D arrays as\n% input and outputs a cell array. \n\n\n% init caffe network (spews logging info)\nif exist('use_gpu', 'var')\n matcaffe_init(use_gpu);\nelse\n matcaffe_init();\nend\n\nif nargin < 1\n % For demo purposes we will use the peppers image\n im = imread('peppers.png');\nend\n\n% prepare oversampled input\n% input_data is Height x Width x Channel x Num\ntic;\ninput_data = {prepare_image(im)};\ntoc;\n\n% do forward pass to get scores\n% scores are now Width x Height x Channels x Num\ntic;\nscores = caffe('forward', input_data);\ntoc;\n\nscores = scores{1};\nsize(scores)\nscores = squeeze(scores);\nscores = mean(scores,2);\n\n[~,maxlabel] = max(scores);\n\n% ------------------------------------------------------------------------\nfunction images = prepare_image(im)\n% ------------------------------------------------------------------------\nd = load('ilsvrc_2012_mean');\nIMAGE_MEAN = d.image_mean;\nIMAGE_DIM = 256;\nCROPPED_DIM = 227;\n\n% resize to fixed input size\nim = single(im);\nim = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');\n% permute from RGB to BGR (IMAGE_MEAN is already BGR)\nim = im(:,:,[3 2 1]) - IMAGE_MEAN;\n\n% oversample (4 corners, center, and their x-axis flips)\nimages = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');\nindices = [0 IMAGE_DIM-CROPPED_DIM] + 1;\ncurr = 1;\nfor i = indices\n for j = indices\n images(:, :, :, curr) = ...\n permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :), [2 1 3]);\n images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);\n curr = curr + 1;\n end\nend\ncenter = floor(indices(2) / 2)+1;\nimages(:,:,:,5) = ...\n permute(im(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:), ...\n [2 1 3]);\nimages(:,:,:,10) = images(end:-1:1, :, :, curr);\n"} +{"plateform": "github", "repo_name": "steflee/MCL_Caffe-master", "name": "matcaffe_demo_vgg_mean_pix.m", "ext": ".m", "path": "MCL_Caffe-master/matlab/caffe/matcaffe_demo_vgg_mean_pix.m", "size": 3069, "source_encoding": "utf_8", "md5": "04b831d0f205ef0932c4f3cfa930d6f9", "text": "function scores = matcaffe_demo_vgg_mean_pix(im, use_gpu, model_def_file, model_file)\n% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file)\n%\n% Demo of the matlab wrapper based on the networks used for the \"VGG\" entry\n% in the ILSVRC-2014 competition and described in the tech. report \n% \"Very Deep Convolutional Networks for Large-Scale Image Recognition\"\n% http://arxiv.org/abs/1409.1556/\n%\n% INPUT\n% im - color image as uint8 HxWx3\n% use_gpu - 1 to use the GPU, 0 to use the CPU\n% model_def_file - network configuration (.prototxt file)\n% model_file - network weights (.caffemodel file)\n%\n% OUTPUT\n% scores 1000-dimensional ILSVRC score vector\n%\n% EXAMPLE USAGE\n% model_def_file = 'zoo/deploy.prototxt';\n% model_file = 'zoo/model.caffemodel';\n% use_gpu = true;\n% im = imread('../../examples/images/cat.jpg');\n% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file);\n% \n% NOTES\n% mean pixel subtraction is used instead of the mean image subtraction\n%\n% PREREQUISITES\n% You may need to do the following before you start matlab:\n% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda/lib64\n% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6\n% Or the equivalent based on where things are installed on your system\n\n% init caffe network (spews logging info)\nmatcaffe_init(use_gpu, model_def_file, model_file);\n\n% mean BGR pixel\nmean_pix = [103.939, 116.779, 123.68];\n\n% prepare oversampled input\n% input_data is Height x Width x Channel x Num\ntic;\ninput_data = {prepare_image(im, mean_pix)};\ntoc;\n\n% do forward pass to get scores\n% scores are now Width x Height x Channels x Num\ntic;\nscores = caffe('forward', input_data);\ntoc;\n\nscores = scores{1};\n% size(scores)\nscores = squeeze(scores);\n% scores = mean(scores,2);\n\n% [~,maxlabel] = max(scores);\n\n% ------------------------------------------------------------------------\nfunction images = prepare_image(im, mean_pix)\n% ------------------------------------------------------------------------\nIMAGE_DIM = 256;\nCROPPED_DIM = 224;\n\n% resize to fixed input size\nim = single(im);\n\nif size(im, 1) < size(im, 2)\n im = imresize(im, [IMAGE_DIM NaN]);\nelse\n im = imresize(im, [NaN IMAGE_DIM]);\nend\n\n% RGB -> BGR\nim = im(:, :, [3 2 1]);\n\n% oversample (4 corners, center, and their x-axis flips)\nimages = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');\n\nindices_y = [0 size(im,1)-CROPPED_DIM] + 1;\nindices_x = [0 size(im,2)-CROPPED_DIM] + 1;\ncenter_y = floor(indices_y(2) / 2)+1;\ncenter_x = floor(indices_x(2) / 2)+1;\n\ncurr = 1;\nfor i = indices_y\n for j = indices_x\n images(:, :, :, curr) = ...\n permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :), [2 1 3]);\n images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);\n curr = curr + 1;\n end\nend\nimages(:,:,:,5) = ...\n permute(im(center_y:center_y+CROPPED_DIM-1,center_x:center_x+CROPPED_DIM-1,:), ...\n [2 1 3]);\nimages(:,:,:,10) = images(end:-1:1, :, :, curr);\n\n% mean BGR pixel subtraction\nfor c = 1:3\n images(:, :, c, :) = images(:, :, c, :) - mean_pix(c);\nend\n"} +{"plateform": "github", "repo_name": "HosseinAbedi/FCM-master", "name": "euclidean.m", "ext": ".m", "path": "FCM-master/fcm/euclidean.m", "size": 296, "source_encoding": "utf_8", "md5": "957d8f1a16b24a66be0f58412f5867b7", "text": "% A function for calculation of euclidean distance of a point x(e.g. [3, 2, 1, 1]) from... \n% ...a set of points in matrix format Y(e.g. [3, 2, 1, 2; 4, 3, 2, 1])\nfunction [d] = euclidean(x, Y)\n S = size(Y);\n d = sum((repmat(x, [S(1),1])-Y).^2, 2);\n d = sqrt(d);\nend"} +{"plateform": "github", "repo_name": "HosseinAbedi/FCM-master", "name": "fcm.m", "ext": ".m", "path": "FCM-master/fcm/fcm.m", "size": 1345, "source_encoding": "utf_8", "md5": "ffc7c4736bf2a26bc8197dfe39a1b014", "text": "%Fuzzy C-means Algorithm in GnuOctave (V.3.6.4)\n%Fuzzy type 1 C-means algorithm\n%Inputs:\n%******c: Number of clusters\n%******X: Data Matrix N_samples*N_features\n%******U_up: U updating function \n%******m: Fuzzifier as a real number\n%******metric: Distance metric as a function (by default Euclidean)\n%******Max: Maximum number of iterations\n%******tol: Tolerance \n%***********************************************\n%Outputs: \n%******prediction: Predicted labels of data\n%******v: Center of clusters as a matrix c*N_features\n%***********************************************\nfunction [prediction v] = fcm(c, X, m, metric, Max, tol)\n[n, no] = size(X);\nU = zeros([c, n]);\nv = repmat(max(X), c, 1).*rand([c, no]);\nU = rand([c, n]);\n\nfor j = 1:n\n U(:, j) = U(:, j)./sum(U(:, j)); \nend \n\nfor i = 1:c\n v(i, :) = sum((X(:, :).*repmat(U(i, :)'.^m, 1, no)),1)./sum(U(i, :).^m);\nend\n\nv_old = v;\ndelta = 1e4;\nk = 0;\nwhile (ktol)\n for i = 1:c\n for j = 1:n\n U(i, j) = 1/sum((metric(X(j, :), v(i, :))./metric(X(j, :), v)).^(2/(m-1)));\n end\n end\n for i = 1:c\n v(i, :) = sum((X(:, :).*repmat(U(i, :)'.^m, 1, no)), 1)./sum(U(i, :).^m); \n end\nv_new = v;\ndelta = max(max(abs(v_new-v_old)));\nv_old = v;\n\nk = k+1;\nend\nprediction = zeros([1, n]);\nfor i = 1:n\n [M, prediction(i)]=max(U(:, i));\nend\n\nend"} +{"plateform": "github", "repo_name": "hailongfeng/huiyin-master", "name": "echo_diagnostic.m", "ext": ".m", "path": "huiyin-master/第三方完整APP源码/mogutt/TTAndroidClient/mgandroid-teamtalk/jni/libspeex/echo_diagnostic.m", "size": 2076, "source_encoding": "utf_8", "md5": "8d5e7563976fbd9bd2eda26711f7d8dc", "text": "% Attempts to diagnose AEC problems from recorded samples\n%\n% out = echo_diagnostic(rec_file, play_file, out_file, tail_length)\n%\n% Computes the full matrix inversion to cancel echo from the \n% recording 'rec_file' using the far end signal 'play_file' using \n% a filter length of 'tail_length'. The output is saved to 'out_file'.\nfunction out = echo_diagnostic(rec_file, play_file, out_file, tail_length)\n\nF=fopen(rec_file,'rb');\nrec=fread(F,Inf,'short');\nfclose (F);\nF=fopen(play_file,'rb');\nplay=fread(F,Inf,'short');\nfclose (F);\n\nrec = [rec; zeros(1024,1)];\nplay = [play; zeros(1024,1)];\n\nN = length(rec);\ncorr = real(ifft(fft(rec).*conj(fft(play))));\nacorr = real(ifft(fft(play).*conj(fft(play))));\n\n[a,b] = max(corr);\n\nif b > N/2\n b = b-N;\nend\nprintf (\"Far end to near end delay is %d samples\\n\", b);\nif (b > .3*tail_length)\n printf ('This is too much delay, try delaying the far-end signal a bit\\n');\nelse if (b < 0)\n printf ('You have a negative delay, the echo canceller has no chance to cancel anything!\\n');\n else\n printf ('Delay looks OK.\\n');\n end\n end\nend\nN2 = round(N/2);\ncorr1 = real(ifft(fft(rec(1:N2)).*conj(fft(play(1:N2)))));\ncorr2 = real(ifft(fft(rec(N2+1:end)).*conj(fft(play(N2+1:end)))));\n\n[a,b1] = max(corr1);\nif b1 > N2/2\n b1 = b1-N2;\nend\n[a,b2] = max(corr2);\nif b2 > N2/2\n b2 = b2-N2;\nend\ndrift = (b1-b2)/N2;\nprintf ('Drift estimate is %f%% (%d samples)\\n', 100*drift, b1-b2);\nif abs(b1-b2) < 10\n printf ('A drift of a few (+-10) samples is normal.\\n');\nelse\n if abs(b1-b2) < 30\n printf ('There may be (not sure) excessive clock drift. Is the capture and playback done on the same soundcard?\\n');\n else\n printf ('Your clock is drifting! No way the AEC will be able to do anything with that. Most likely, you''re doing capture and playback from two different cards.\\n');\n end\n end\nend\nacorr(1) = .001+1.00001*acorr(1);\nAtA = toeplitz(acorr(1:tail_length));\nbb = corr(1:tail_length);\nh = AtA\\bb;\n\nout = (rec - filter(h, 1, play));\n\nF=fopen(out_file,'w');\nfwrite(F,out,'short');\nfclose (F);\n"} +{"plateform": "github", "repo_name": "hailongfeng/huiyin-master", "name": "echo_diagnostic.m", "ext": ".m", "path": "huiyin-master/第三方完整APP源码/mogutt/TTWinClient/3rdParty/src/libspeex/libspeex/echo_diagnostic.m", "size": 2076, "source_encoding": "utf_8", "md5": "8d5e7563976fbd9bd2eda26711f7d8dc", "text": "% Attempts to diagnose AEC problems from recorded samples\n%\n% out = echo_diagnostic(rec_file, play_file, out_file, tail_length)\n%\n% Computes the full matrix inversion to cancel echo from the \n% recording 'rec_file' using the far end signal 'play_file' using \n% a filter length of 'tail_length'. The output is saved to 'out_file'.\nfunction out = echo_diagnostic(rec_file, play_file, out_file, tail_length)\n\nF=fopen(rec_file,'rb');\nrec=fread(F,Inf,'short');\nfclose (F);\nF=fopen(play_file,'rb');\nplay=fread(F,Inf,'short');\nfclose (F);\n\nrec = [rec; zeros(1024,1)];\nplay = [play; zeros(1024,1)];\n\nN = length(rec);\ncorr = real(ifft(fft(rec).*conj(fft(play))));\nacorr = real(ifft(fft(play).*conj(fft(play))));\n\n[a,b] = max(corr);\n\nif b > N/2\n b = b-N;\nend\nprintf (\"Far end to near end delay is %d samples\\n\", b);\nif (b > .3*tail_length)\n printf ('This is too much delay, try delaying the far-end signal a bit\\n');\nelse if (b < 0)\n printf ('You have a negative delay, the echo canceller has no chance to cancel anything!\\n');\n else\n printf ('Delay looks OK.\\n');\n end\n end\nend\nN2 = round(N/2);\ncorr1 = real(ifft(fft(rec(1:N2)).*conj(fft(play(1:N2)))));\ncorr2 = real(ifft(fft(rec(N2+1:end)).*conj(fft(play(N2+1:end)))));\n\n[a,b1] = max(corr1);\nif b1 > N2/2\n b1 = b1-N2;\nend\n[a,b2] = max(corr2);\nif b2 > N2/2\n b2 = b2-N2;\nend\ndrift = (b1-b2)/N2;\nprintf ('Drift estimate is %f%% (%d samples)\\n', 100*drift, b1-b2);\nif abs(b1-b2) < 10\n printf ('A drift of a few (+-10) samples is normal.\\n');\nelse\n if abs(b1-b2) < 30\n printf ('There may be (not sure) excessive clock drift. Is the capture and playback done on the same soundcard?\\n');\n else\n printf ('Your clock is drifting! No way the AEC will be able to do anything with that. Most likely, you''re doing capture and playback from two different cards.\\n');\n end\n end\nend\nacorr(1) = .001+1.00001*acorr(1);\nAtA = toeplitz(acorr(1:tail_length));\nbb = corr(1:tail_length);\nh = AtA\\bb;\n\nout = (rec - filter(h, 1, play));\n\nF=fopen(out_file,'w');\nfwrite(F,out,'short');\nfclose (F);\n"} +{"plateform": "github", "repo_name": "hailongfeng/huiyin-master", "name": "FMSearchTokenField.m", "ext": ".m", "path": "huiyin-master/第三方完整APP源码/mogutt/TTMacClient/TeamTalk/interface/mainWindow/FMSearchTokenField.m", "size": 4519, "source_encoding": "utf_8", "md5": "2a89df28133e0c91280b5daf58944c94", "text": "//\n// FMSearchTokenField.m\n// Duoduo\n//\n// Created by zuoye on 13-12-23.\n// Copyright (c) 2013年 zuoye. All rights reserved.\n//\n\n#import \"FMSearchTokenField.h\"\n#import \"FMSearchTokenFieldCell.h\"\n\n@implementation FMSearchTokenField\n@synthesize sendActionWhenEditing=_sendActionWhenEditing;\n@synthesize alwaysSendActionWhenPressEnter=_alwaysSendActionWhenPressEnter;\n\n\n+(void)initialize {\n [FMSearchTokenField setCellClass:[FMSearchTokenFieldCell class]];\n}\n\n- (id)initWithFrame:(NSRect)frame\n{\n self = [super initWithFrame:frame];\n if (self) {\n self.sendActionWhenEditing = NO;\n self.alwaysSendActionWhenPressEnter = NO;\n self.m_tokenizingChar = 0x2c;\n /*\n var_32 = rdi;\n var_40 = *0x1002c3b58;\n rax = [[&var_32 super] initWithFrame:edx];\n if (rax != 0x0) {\n rbx.sendActionWhenEditing = 0x0;\n rbx.alwaysSendActionWhenPressEnter = 0x0;\n rax = [NSMutableString alloc];\n rax = [rax init];\n rbx.m_untokenizedStringValue = rax;\n rbx.m_tokenizingChar = 0x2c; //44\n }\n rax = rbx;\n return rax;\n\n */\n }\n return self;\n}\n\n-(void)setTokenizingChars:(NSString *) chars{\n self.m_tokenizingChar = [chars characterAtIndex:0];\n [self setTokenizingCharacterSet:[NSCharacterSet characterSetWithCharactersInString:chars]];\n}\n\n/*\nfunction methImpl_FMSearchTokenField_tokenCount {\n rbx = rdi;\n rax = [rdi tokenStyle];\n rcx = rax;\n rax = 0x1;\n if (rcx == 0x1) goto loc_0x100111ce7;\n goto loc_100111c3f;\n \nloc_100111ce7:\n return rax;\n \nloc_100111c3f:\n rax = [rbx currentEditor];\n if (rax == 0x0) goto loc_0x100111cf6;\n goto loc_100111c58;\n \nloc_100111cf6:\n rax = [rbx attributedStringValue];\n rax = [rax length];\n \nloc_100111c58:\n rax = [rax attributedString];\n rax = [rax length];\n r13 = 0x0;\n if (rax != 0x0) {\n rbx = 0x0;\n r13 = 0x0;\n do {\n rax = [r14 attribute:**NSAttachmentAttributeName atIndex:rbx effectiveRange:0x0];\n r13 = r13 - 0xff + CARRY(CF);\n rax = [r14 length];\n } while (rbx + 0x1 < rax);\n }\n rax = [r14 length];\n rax = ((rax != r13 ? 0xff : 0x0) & 0xff) + r13;\n goto loc_100111ce7;\n}\n*/\n\n/*\n $rdi == arg0 (ObjC: self)\n $rsi == arg1 (ObjC: op, or _cmd)\n $rdx == arg2 (ObjC: first arg of method)\n $rcx == arg3 (ObjC: second arg of method) cell\n $r8 == arg4 第三个参数\n $r9 == arg5 第四个\n */\n- (void)drawRect:(NSRect)dirtyRect{\n \n if([[self subviews] count]>0){\n NSView *view = [[self subviews] objectAtIndex:0];\n if ([view isKindOfClass:[FMSearchTokenFieldCell class]]) {\n NSRect cellRect ;\n if ([self cell]) {\n cellRect = [[self cell] bounds];\n }\n NSRect imageRect ;\n NSRect textRect;\n \n [(FMSearchTokenFieldCell *)view divideFrame:cellRect ToImageRect:&imageRect textRect:&textRect buttonRect:nil callFromView:YES];\n [view setFrame:cellRect];\n }\n }\n \n /*\n r12 = rdi;\n rax = [rdi subviews];\n rax = [rax count];\n if (rax != 0x0) {\n rax = [rbx objectAtIndex:0x0];\n r14 = rax;\n rax = [*0x1002c29e8 class];\n rax = [r14 isKindOfClass:rax];\n if (rax != 0x0) {\n rax = [r12 cell];\n r15 = rax;\n if (r12 != 0x0) {\n var_80 = [r12 bounds];\n }\n else {\n }\n rbx = *objc_msgSend;\n rdx = 0x0;\n (*objc_msgSend)(r15, @selector(divideFrame:ToImageRect:textRect:buttonRect:callFromView:), rdx, &var_112, 0x0, 0x1);\n var_72 = var_136;\n var_64 = var_128;\n var_56 = var_120;\n var_48 = var_112;\n [r14 setFrame:rdx];\n }\n }\n rax = &arg_0;\n var_32 = r12;\n var_40 = *0x1002c3b58;\n rax = [[&var_32 super] drawRect:edx];\n return rax;\n */\n \n\t[super drawRect:dirtyRect];\n\t\n}\n\n\n\n/*\n function methImpl_FMSearchTokenField_dealloc {\n rbx = rdi;\n r14 = objc_msg_release;\n [rbx.m_buttonTrackingArea release];\n [rbx.m_untokenizedStringValue release];\n var_0 = rbx;\n var_8 = *0x1002c3b58;\n rax = [[&var_0 super] dealloc];\n return rax;\n }\n */\n\n-(void)mouseDown:(NSEvent *)theEvent{\n \n}\n\n-(void)mouseUp:(NSEvent *)theEvent{\n \n}\n\n-(void)mouseEntered:(NSEvent *)theEvent{\n \n}\n\n-(void)mouseExited:(NSEvent *)theEvent{\n \n}\n\n-(BOOL)isFlipped{\n return NO;\n}\n\n@end\n\n"} +{"plateform": "github", "repo_name": "hailongfeng/huiyin-master", "name": "DDNinePartImage.m", "ext": ".m", "path": "huiyin-master/第三方完整APP源码/mogutt/TTMacClient/TeamTalk/interface/mainWindow/searchField/DDNinePartImage.m", "size": 6722, "source_encoding": "utf_8", "md5": "6dac0c29b80d07b31ccfd0b48ec932de", "text": "//\n// DDNinePartImage.m\n// Duoduo\n//\n// Created by zuoye on 14-1-20.\n// Copyright (c) 2014年 zuoye. All rights reserved.\n//\n\n#import \"DDNinePartImage.h\"\n\n@implementation DDNinePartImage\n\n-(id)initWithNSImage:(NSImage *)image leftPartWidth:(CGFloat)leftWidth rightPartWidth:(CGFloat)rightWidth topPartHeight:(CGFloat)topHeight bottomPartHeight:(CGFloat)bottomHeight{\n return [self initWithNSImage:image leftPartWidth:leftWidth rightPartWidth:rightWidth topPartHeight:topHeight bottomPartHeight:bottomHeight flipped:NO];\n}\n\n-(id)initWithNSImage:(NSImage *)image leftPartWidth:(CGFloat)leftWidth rightPartWidth:(CGFloat)rightWidth topPartHeight:(CGFloat)topHeight bottomPartHeight:(CGFloat)bottomHeight flipped:(BOOL)flipped{\n self = [super init];\n if (self) {\n \n //size 是指块图片的大小.\n // topLeftCornerImage = [DDNinePartImage getPartImage:image withSize:<#(NSSize)#> fromRect:<#(NSRect)#>]\n }\n return self;\n}\n\n\n\n\n/*\n \n function meth_TXNinePartImage_dealloc {\n edi = arg_0;\n [*(edi + 0x1c) release]; //topLeftCornerImage\n [*(edi + 0x20) release]; //topEdgeImage\n [*(edi + 0x24) release]; //topRightCornerImage\n [*(edi + 0x28) release]; //leftEdgeImage\n [*(edi + 0x2c) release]; //centerImage\n [*(edi + 0x30) release]; //rightEdgeImage\n [*(edi + 0x34) release]; //bottomLeftCornerImage\n [*(edi + 0x38) release]; //bottomEdgeImage\n [*(edi + 0x3c) release]; //bottomRightCornerImage\n var_8 = edi;\n var_12 = *0xca2ce4;\n eax = [[&var_8 super] dealloc];\n return eax;\n }\n */\n\n\n\n-(void)drawInRect:(NSRect)rect fromRect:(NSRect)fromRect operation:(NSCompositingOperation)op fraction:(CGFloat)delta{\n [self drawInRect:rect compositingOperation:op alphaFraction:delta flipped:NO];\n}\n\n-(void)drawInRect:(NSRect)rect compositingOperation:(NSCompositingOperation)op alphaFraction:(CGFloat)alphaFraction flipped:(BOOL)isFlipped{\n NSGraphicsContext *context = [NSGraphicsContext currentContext];\n [context saveGraphicsState];\n [context setShouldAntialias:YES];\n NSDrawNinePartImage(rect, topLeftCornerImage, topEdgeImage, topRightCornerImage, leftEdgeImage, centerImage, rightEdgeImage, bottomLeftCornerImage, bottomEdgeImage, bottomRightCornerImage, op, alphaFraction, isFlipped);\n [context restoreGraphicsState];\n}\n\n+(NSImage *)getPartImage:(NSImage *)image withSize:(NSSize)size fromRect:(NSRect)rect{\n NSImage *im = [[NSImage alloc] initWithSize:size];\n [im lockFocus];\n [image drawInRect:NSMakeRect(0, 0, size.width, size.height) fromRect:rect operation:NSCompositeCopy fraction:1];\n [im unlockFocus];\n return im;\n}\n\n\n/*\n $rdi == arg0 (ObjC: self)\n $rsi == arg1 (ObjC: op, or _cmd)\n $rdx == arg2 (ObjC: first arg of method)\n $rcx == arg3 (ObjC: second arg of method) cell\n $r8 == arg4 第三个参数\n $r9 == arg5 第四个\n */\n/*\nfunction meth_TXNinePartImage_initWithNSImage_leftPartWidth_rightPartWidth_topPartHeight_bottomPartHeight_flipped_ {\n var_240 = arg_0;\n var_244 = *0xca2ce4;\n eax = [[&var_240 super] init];\n if (eax != 0x0) {\n ecx = arg_8;\n edi = ecx;\n eax = [ecx size];\n var_48 = eax;\n [edi size];\n floorf(edx);\n asm{ fstp tword [ss:ebp-0x108+var_60] };\n floorf(arg_14);\n asm{ fstp dword [ss:ebp-0x108+var_80] };\n asm{ fld tword [ss:ebp-0x108+var_60] };\n asm{ fstp dword [ss:ebp-0x108+var_92] };\n floorf(arg_C);\n asm{ fstp dword [ss:ebp-0x108+var_72] };\n xmm3 = var_80;\n var_52 = xmm3;\n xmm0 = var_92 - xmm3;\n var_60 = xmm0;\n var_224 = 0x0;\n var_228 = xmm0;\n xmm0 = var_72;\n var_56 = xmm0;\n var_232 = xmm0;\n var_236 = xmm3;\n eax = [TXNinePartImage getPartImage:edi withSize:xmm0 fromRect:xmm3];\n eax = [eax retain];\n *(esi + 0x1c) = eax;\n floorf(var_48);\n var_36 = esi;\n var_208 = var_56;\n asm{ fstp dword [ss:ebp-0x108+var_88] };\n floorf(arg_10);\n asm{ fstp dword [ss:ebp-0x108+var_76] };\n var_212 = var_60;\n xmm0 = var_88;\n var_48 = xmm0;\n xmm1 = var_76;\n var_44 = xmm1;\n xmm0 = xmm0 - var_56 - xmm1;\n var_40 = xmm0;\n var_216 = xmm0;\n xmm3 = var_52;\n var_220 = xmm3;\n esi = var_36;\n eax = [TXNinePartImage getPartImage:edi withSize:xmm0 fromRect:xmm3];\n eax = [eax retain];\n *(esi + 0x20) = eax;\n xmm0 = var_44;\n xmm1 = var_48 - xmm0;\n var_48 = xmm1;\n var_192 = xmm1;\n var_196 = var_60;\n var_200 = xmm0;\n xmm3 = var_52;\n var_204 = xmm3;\n eax = [TXNinePartImage getPartImage:edi withSize:xmm0 fromRect:xmm3];\n eax = [eax retain];\n *(esi + 0x24) = eax;\n floorf(arg_18);\n asm{ fstp dword [ss:ebp-0x108+var_84] };\n var_176 = 0x0;\n xmm1 = var_84;\n var_52 = xmm1;\n var_180 = xmm1;\n xmm2 = var_56;\n var_184 = xmm2;\n xmm0 = var_60 - xmm1;\n var_60 = xmm0;\n var_188 = xmm0;\n eax = [TXNinePartImage getPartImage:edi withSize:xmm2 fromRect:xmm0];\n eax = [eax retain];\n *(esi + 0x28) = eax;\n var_160 = var_56;\n var_164 = var_52;\n xmm2 = var_40;\n var_168 = xmm2;\n xmm3 = var_60;\n var_172 = xmm3;\n eax = [TXNinePartImage getPartImage:edi withSize:xmm2 fromRect:xmm3];\n eax = [eax retain];\n *(esi + 0x2c) = eax;\n var_144 = var_48;\n var_148 = var_52;\n xmm2 = var_44;\n var_152 = xmm2;\n xmm3 = var_60;\n var_156 = xmm3;\n eax = [TXNinePartImage getPartImage:edi withSize:xmm2 fromRect:xmm3];\n eax = [eax retain];\n *(esi + 0x30) = eax;\n var_128 = 0x0;\n var_132 = 0x0;\n xmm2 = var_56;\n var_136 = xmm2;\n xmm3 = var_52;\n var_140 = xmm3;\n eax = [TXNinePartImage getPartImage:edi withSize:xmm2 fromRect:xmm3];\n eax = [eax retain];\n *(esi + 0x34) = eax;\n var_112 = var_56;\n var_116 = 0x0;\n xmm3 = var_40;\n var_120 = xmm3;\n xmm2 = var_52;\n var_124 = xmm2;\n eax = [TXNinePartImage getPartImage:edi withSize:xmm3 fromRect:xmm2];\n eax = [eax retain];\n *(esi + 0x38) = eax;\n var_96 = var_48;\n var_100 = 0x0;\n xmm2 = var_44;\n var_104 = xmm2;\n xmm3 = var_52;\n var_108 = xmm3;\n eax = [TXNinePartImage getPartImage:edi withSize:xmm2 fromRect:xmm3];\n eax = [eax retain];\n *(esi + 0x3c) = eax;\n *(int8_t *)(esi + 0x40) = arg_1C;\n }\n eax = esi;\n return eax;\n}\n*/\n@end\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "publish_meta_analysis_report.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/publish_meta_analysis_report.m", "size": 2717, "source_encoding": "utf_8", "md5": "2e567ddc4ed722a5ad177fde06b32bc0", "text": "% Runs batch analyses and publishes HTML report with figures and stats to\r\n% results/published_output in local study-specific analysis directory.\r\n\r\n% Run this from the main mediation results directory (basedir)\r\n\r\nclose all\r\nwarning off, clear all, warning on \r\n\r\nresultsdir = pwd;\r\n\r\nfprintf('Creating HTML report for results in:\\n%s\\n', resultsdir);\r\n\r\n% ------------------------------------------------------------------------\r\n% Check that we have a valid MKDA Meta_activationFWE results dir\r\n% ------------------------------------------------------------------------\r\n\r\nis_mediation_dir = exist(fullfile(resultsdir, 'MC_Info.mat'));\r\n%is_run = exist(fullfile(resultsdir, 'X-M-Y_effect.img'));\r\n\r\nif ~is_mediation_dir\r\n fprintf('%s\\nis not a MKDA meta-analysis directory because MC_Info.mat is missing.\\nSkipping report.\\n', resultsdir);\r\n return\r\nend\r\n\r\n% if ~is_run\r\n% fprintf('Mediation does not appear to have run correctly because X-M-Y_effect.img is missing.\\nSkipping report.\\n');\r\n% return\r\n% end\r\n\r\n% ------------------------------------------------------------------------\r\n% Set HTML report filename and options\r\n% ------------------------------------------------------------------------\r\n\r\npubdir = fullfile(resultsdir, 'published_output');\r\nif ~exist(pubdir, 'dir'), mkdir(pubdir), end\r\n\r\npubfilename = ['MKDA_meta_analysis_report_' scn_get_datetime];\r\n\r\np = struct('useNewFigure', false, 'maxHeight', 800, 'maxWidth', 1600, ...\r\n 'format', 'html', 'outputDir', fullfile(pubdir, pubfilename), 'showCode', false);\r\n\r\n % move old reports to 'older' dir\r\n move_old_reports(pubdir, pubfilename)\r\n\r\n% ------------------------------------------------------------------------\r\n% Run and report status\r\n% ------------------------------------------------------------------------\r\n\r\npublish('Meta_results_batch_script.m', p);\r\n\r\nmyhtmlfile = fullfile(pubdir, pubfilename, 'Meta_results_batch_script.html');\r\n\r\nif exist(myhtmlfile, 'file')\r\n \r\n fprintf('Saved HTML report:\\n%s\\n', myhtmlfile);\r\n \r\n web(myhtmlfile);\r\n \r\nelse\r\n \r\n fprintf('Failed to create HTML report:\\n%s\\n', myhtmlfile);\r\n \r\nend\r\n\r\n\r\n\r\n\r\n\r\n\r\nfunction move_old_reports(pubdir, pubfilename)\r\n\r\nolddir = fullfile(pubdir, 'OLDER_REPORTS');\r\nif ~exist(olddir, 'dir'), mkdir(olddir); end\r\n\r\nmyreportwildcard = [pubfilename(1:end - 17) '*'];\r\n\r\noldfiles = dir(fullfile(pubdir, myreportwildcard));\r\n\r\nif length(oldfiles) > 1\r\n fprintf('Moving old reports named %s to OLDER_REPORTS folder.\\n', myreportwildcard);\r\nend\r\n\r\nfor i = 1:length(oldfiles)\r\n \r\n myfile = fullfile(pubdir, oldfiles(i).name);\r\n [SUCCESS,MESSAGE,MESSAGEID] = movefile(myfile, olddir);\r\n \r\nend\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Specificity.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Specificity.m", "size": 6851, "source_encoding": "utf_8", "md5": "84d871e62043140571dbd0a5ad060018", "text": "function OUT = whole_brain_ptask_givena(OUT,varargin)\n% OUT = whole_brain_ptask_givena(OUT,verbose level, mask image or threshold value(for pa_overall) )\n%\n% OUT = whole_brain_ptask_givena(OUT,2,.001)\n% OUT = whole_brain_ptask_givena(OUT,2,'Activation_thresholded.img')\n\n% verbose flag\nif length(varargin) > 0, vb = varargin{1};, else, vb = 1;, end\n\nP = OUT.PP;\ntask_indicator = OUT.allcondindic;\nfield = OUT.testfield;\nnames = OUT.allcondnames;\n\n% image dimensions, etc.\nV = spm_vol(P(1,:));\nVall = spm_vol(P);\n\nglobal dims\nglobal cols\n\ndims = V.dim(1:3);\n\nif vb > 0, fprintf(1,'\\n\\t\\tNew image dims: %3.0f %3.0f %3.0f %3.0f ',dims(1), dims(2), dims(3), cols),end\n\n% ---------------------------------------\n% brain masking\n% ---------------------------------------\n\nmask = []; \nif length(varargin) > 1, \n mask = varargin{2};, \n if vb > 0, fprintf(1,'\\nFound mask: %s', mask);, end\n if isstr(mask), Vm = spm_vol(mask);, mask = spm_read_vols(Vm);,\n % if a mask file, then load it\n elseif length(mask) == 1\n % if a number, treat this as threshold value for pa_overall\n % I recommend .001, which is a 0.1% chance of activating across all\n % tasks\n Vm = spm_vol('Activation.img'); maskimg = spm_read_vols(Vm);,\n mask = real(maskimg > mask); % threshold \n end\nend\nif isempty(mask), mask = ones(dims);,end\n\n\n% -------------------------------------------------------------------\n% * define output image names\n% -------------------------------------------------------------------\nfor i = 1:length(names)\n names{i} = [field '_' names{i}];\nend\n\n\n \n% -------------------------------------------------------------------\n% * for each slice...\n% -------------------------------------------------------------------\n\nfor slicei = 1:dims(3)\n \n if vb > 1, t1 = clock;, fprintf(1,'\\nSlice %3.0f \\n------------>\\n ',slicei),end\n \n % returns image names\n [x2,x2p,eff,z,p] = process_slice(slicei,Vall,task_indicator,field,names,vb,mask(:,:,slicei));\n\n if ~isempty(x2), x2f = x2;, end % final versions\n if ~isempty(x2p), x2pf = x2p;, end \n if ~isempty(eff), efff = eff;, end \n if ~isempty(z), zf = z;, end\n if ~isempty(p), pf = p;, end \n \n if vb > 1, fprintf(1,'\\t%6.0f s for slice',etime(clock,t1)),end\nend\n\nOUT.x2 = x2f;\nOUT.x2p = x2pf;\nOUT.eff = efff;\nOUT.z = zf;\nOUT.p = pf;\n\nstr = ['save STATS_VARS_' field ' OUT'];\neval(str)\n\nreturn\n\n\n\n\n\n\n\n% -------------------------------------------------------------------\n%\n%\n%\n%\n% * SUB-FUNCTIONS\n%\n%\n%\n%\n% ------------------------------------------------------------------- \n \n \nfunction [x2,x2p,eff,z,p] = process_slice(slicei,Vall,task_indicator,field,names,vb,varargin)\n\nx2 = []; x2p = []; eff = []; z = []; p = [];\nmask = []; if length(varargin) > 0, mask = varargin{1};, end\nsl = []; if length(varargin) > 1, sl = varargin{1};, end\n\nglobal dims\nglobal cols\n\n% -------------------------------------------------------------------\n% * load the slice\n% -------------------------------------------------------------------\n\nif isempty(sl)\n \nif vb > 0, fprintf(1,'\\tLoading data >'), end \net = clock;\nif ~isempty(mask) & ~(sum(sum(sum(mask))) > 0)\n % skip it\n fbetas = NaN * zeros([dims(1:2) cols]);\n ntrimmed = NaN;\n if vb > 1, fprintf(1,'...Empty slice...'), end\n return\nelse\n sl = timeseries_extract_slice(Vall,slicei);\nend\n\nif vb > 1, fprintf(1,'loaded in %3.2f s.',etime(clock,et)),end\n\nelse\n % we've already loaded the slice!\n \nend\n\nif ~isempty(mask), sl(:,:,1) = sl(:,:,1) .* mask;, end\n\n\n% -------------------------------------------------------------------\n% * find in-mask voxels\n% -------------------------------------------------------------------\n\nsumsl = sum(sl,3); % sum of all contrasts\n\n% find indices i and j for all in-mask voxels\nwvox = find(sumsl ~= 0 & ~isnan(sumsl));\n[i,j] = ind2sub(size(sl(:,:,1)),wvox);\n\nfprintf(1,'\\n\\tCalculating P(Task|Activity) for %3.0f voxels > ',length(i))\n\n\n% -------------------------------------------------------------------\n% * compute p(T|A) for each in-mask voxel\n% -------------------------------------------------------------------\nnsize = size(sl); \nnsize = [nsize(1:2) size(task_indicator,2)]; % vox x vox x task condition\n\n% output images -- initialize\nx2field = zeros(nsize(1:2)); % chi2 overall for test field\npfield = zeros(nsize(1:2)); % p-value\n\nlevels = zeros(nsize); % effect size for each level\nlevelz = zeros(nsize); % z-score \nlevelp = zeros(nsize); % p-value\n\net = clock;\nfor k = 1:length(i)\n\n y = squeeze(sl(i(k),j(k),:)); \n \n % could use optional arg here to use %, but now treats everything as\n % activated or not\n [pt_given_a,eff,z,p,stat] = p_task_given_activation(task_indicator,y);\n \n x2field(i(k),j(k)) = stat.x2;\n pfield(i(k),j(k)) = stat.x2p;\n \n levels(i(k),j(k),:) = eff';\n levelz(i(k),j(k),:) = z';\n levelp(i(k),j(k),:) = p';\n \n if k == 1000, fprintf(1,'%3.0f s per 1000 vox.',etime(clock,et)), end\nend\n\n\nclear sl\n\n\n\n% -------------------------------------------------------------------\n% * write output images\n% ------------------------------------------------------------------- \n\nemptyimg = zeros(dims); % in case we need to create a new volume, used later as well\n \nwarning off\nif vb > 1, fprintf(1,'\\n\\tWriting f (filtered) plane > '), end\n\nx2 = write_beta_slice(slicei,Vall(1),x2field,emptyimg,[field '_chi2_']);\nx2p = write_beta_slice(slicei,Vall(1),pfield,emptyimg,[field '_chi2p_']);\neff = write_beta_slice(slicei,Vall(1),levels,emptyimg,[field '_p(t|a)_eff_'],names);\nz = write_beta_slice(slicei,Vall(1),levelz,emptyimg,[field '_p(t|a)_z_'],names);\np = write_beta_slice(slicei,Vall(1),levelp,emptyimg,[field '_p(t|a)_p_'],names);\n\nwarning on\n\n \n \nreturn\n\n\n\n\n\n\n\nfunction Pw = write_beta_slice(slicei,V,betas,emptyimg,varargin)\n% Pw = write_beta_slice(sliceindex,V,data,empty,prefix)\n% Slice-a-metric version\nwarning off % due to NaN to int16 zero conversions\nV.dim(4) = 16; % set to float to preserve decimals\n\nprefix = 'check_program_';\nnames = {''}; % for field only\nif length(varargin) > 0, prefix = varargin{1};,end % field name\nif length(varargin) > 1, names = varargin{2};,end % level names\n\nfor voli = 1:size(betas,3) % for each image/beta series point\n %if voli < 10, myz = '000';, elseif voli < 100, myz = '00';, else myz = '000';,end\n V.fname = [prefix names{voli} '.img'];\n V.descrip = ['Created by whole_brain_ptask_givena '];\n\n % create volume, if necessary\n if ~(exist(V.fname) == 2), spm_write_vol(V,emptyimg);,end\n \n spm_write_plane(V,betas(:,:,voli),slicei);\n \n if ~(exist('Pw')==1), Pw = which(V.fname);, \n else Pw = str2mat(Pw,which(V.fname));\n end\n \nend\n\n\n\nwarning on\nreturn\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Setup.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Setup.m", "size": 11506, "source_encoding": "utf_8", "md5": "a577bd786ca6fc8594713550d606edf3", "text": "% DB = Meta_Setup(DB, [radius_mm], [con_dens_images])\n% Set up Meta-analysis dataset\n%\n% use after read_database.m\n% See the Manual for more complete information.\n%\n% Special Fields\n%\n% Subjects or N : sample size\n% FixedRandom : fixed or random effects\n% SubjectiveWeights : weighting vector based on FixedRandom and whatever\n% else you want to weight by; e.g., study reporting threshold\n% x, y, z : coordinates\n% study or Study : name of study\n% Contrast : unique indices (e.g., 1:k) for each independent\n% contrast\n\nfunction DB = Meta_Setup(DB, varargin)\n\n diary ANALYSIS_INFORMATION.txt\n\n write_contrast_image_flag = 0; % flag to write contrast images;\n % Contrast images are not needed for Meta_Activation_FWE\n\n %P = ['brain_avg152T1.img']; % 2 mm voxels\n P = 'scalped_avg152T1_graymatter_smoothed.img';\n\n if length(varargin) > 0\n radius_mm = varargin{1};\n else\n radius_mm = 10;\n end\n disp(['Radius is ' num2str(radius_mm) ' mm.']);\n\n %mask_file = P;\n t1 = clock;\n fprintf(1,'Setup. ')\n\n % -----------------------------------------------------\n % * load standard brain\n % -----------------------------------------------------\n\n switch spm('Ver')\n case 'SPM2'\n % spm_defaults is a script\n disp('WARNING: spm defaults not set for spm2. Make sure your defaults are set correctly');\n\n case 'SPM5'\n % spm_defaults is a function\n spm_defaults()\n\n case 'SPM8'\n % spm_defaults is a function\n spm_defaults()\n\n case 'SPM12'\n spm('defaults','fmri');\n \n otherwise\n % unknown SPM\n disp('Unknown version of SPM!');\n spm_defaults()\n end\n \n defaults.analyze.flip = 0;\n\n P = which(P);\n if isempty(P), disp('Error: Cannot find mask image on path: scalped_avg152T1_graymatter_smoothed.img. Nothing done.'); return; end\n\n V = spm_vol(P);\n mask = zeros(V.dim(1:3));\n\n voxsize = diag(V(1).mat)';\n voxsize = voxsize(1:3);\n radius = radius_mm ./ mean(abs(voxsize));\n sphere_vol = 4 * pi * radius_mm ^ 3 / 3;\n\n DB.radius_mm = radius_mm;\n DB.radius = radius;\n\n % mask image -- gray matter\n DB.maskname = P;\n DB.maskV = V;\n DB.sphere_vol = sphere_vol;\n DB.voxsize = voxsize;\n DB.maskzeros = mask;\n\n\n % -----------------------------------------------------\n % identify field info to save with each contrast image in DB struct\n % later saved in SETUP.mat\n % -----------------------------------------------------\n N = fieldnames(DB); fieldn = {};\n for i = 1:length(N)\n str = ['tmp = DB.' N{i} ';'];\n eval(str)\n if length(tmp) == length(DB.x) % if this field has all info for each peak\n fieldn(end+1) = N(i);\n end\n end\n\n\n\n\n % -----------------------------------------------------\n % Make sure we have some things that are often mis-labeled\n % -----------------------------------------------------\n\n % Special Fields\n %\n % Subjects or N : sample size\n % FixedRandom : fixed or random effects\n % Subjective Weights : weighting vector based on FixedRandom and whatever\n % else you want to weight by; e.g., study reporting threshold\n % x, y, z : coordinates\n % study or Study : name of study\n % Contrast : unique indices (e.g., 1:k) for each independent\n % contrast\n\n if ~isfield(DB,'Subjects') && isfield(DB,'N')\n disp('Cannot find Subjects field. Copying from N.')\n DB.Subjects = DB.N;\n end\n\n\n if ~isfield(DB,'study') && isfield(DB,'Study')\n disp('Cannot find study field. Copying from Study.')\n DB.study = DB.Study;\n end\n\n if ~isfield(DB,'x') && isfield(DB,'X')\n disp('Cannot find x field. Copying from X.')\n DB.x = DB.X;\n end\n\n if ~isfield(DB,'y') && isfield(DB,'Y')\n disp('Cannot find y field. Copying from Y.')\n DB.y = DB.Y;\n end\n\n if ~isfield(DB,'z') && isfield(DB,'Z')\n disp('Cannot find z field. Copying from Z.')\n DB.z = DB.Z;\n end\n\n if ~isfield(DB,'xyz')\n disp('No xyz field in DB. Creating from x, y, z.');\n DB.xyz = [DB.x DB.y DB.z];\n end\n\n if ~isfield(DB,'Subjects'), error('Enter Subjects or N field.'); end\n\n % -----------------------------------------------------\n % identify independent contrasts and get sqrt(N)\n % -----------------------------------------------------\n\n\n % kludgy fix if you haven't entered indices of independent contrasts in\n % Contrast. You should never use this with the new meta-analyses.\n % -----------------------------------------------------\n if ~isfield(DB,'Contrast')\n disp('No DB.Contrast field. You can create one using unique levels of a variable,')\n disp('or create one in the text file and re-run.')\n\n disp('Run: get_contrast_indicator_improved')\n disp('Store results: DB.Contrast = contrasts; DB.pointind = first_peak_in_each_con;');\n\n % [contrasts, first_peak_in_each_con] = get_contrast_indicator_improved(DB, {'Memtype' 'Control' 'Design' 'Feature' 'Material'});\n % DB.Contrast = contrasts;\n % DB.pointind = first_peak_in_each_con';\n %\n %\n %\n % testfield = input('Enter field name to use: ','s');\n %\n % OUT = get_contrast_indicator(DB,testfield);\n %\n % pointind = OUT.conindex';\n % DB.pointind = pointind;\n % for i = 1:length(pointind),\n % ind = pointind; ind(ind <= pointind(i)) = []; nextlargest = min(ind);\n % DB.Contrast(pointind(i):nextlargest-1) = i;\n % end\n %\n % [DB.connumbers,DB.pointind] = unique(DB.Contrast);\n % DB.rootn = OUT.rootn';\n %\n % disp('Warning!!! This part probably has bugs!!!')\n % DB.connumbers(DB.connumbers == 0) = max(DB.connumbers)+1;\n % DB.Contrast(end+1) = DB.Contrast(end);\n\n\n else\n % we have unique contrasts\n % you have entered them in the Contrast variable\n % this is the right thing to do.\n % -----------------------------------------------------\n\n DB.rootn = sqrt(DB.Subjects);\n [DB.connumbers,DB.pointind] = unique(DB.Contrast);\n DB.rootn = DB.rootn(DB.pointind);\n\n end\n\n % -----------------------------------------------------\n % Make sure contrast weights are sorted\n % Needed later for Meta_Select_Contrasts and Log. Design\n % Note: this should not actually affect order of contrasts, which\n % should still be in order of entry in dataset. Other functions should\n % respect this order, however. See programmers' notes in\n % Meta_Activation_FWE\n % -----------------------------------------------------\n [DB.pointind,ii] = sort(DB.pointind);\n DB.rootn = DB.rootn(ii);\n DB.connumbers = DB.connumbers(ii);\n\n % -----------------------------------------------------\n % get Final contrast weights\n % -----------------------------------------------------\n\n if isfield(DB,'SubjectiveWeights')\n disp('Scaling by SubjectiveWeights');\n w = DB.rootn .* DB.SubjectiveWeights(DB.pointind);\n else\n w = DB.rootn;\n end\n\n % make sure no NaNs or zeros; impute mean\n whbad = find(isnan(w) | w == 0);\n if ~isempty(whbad)\n disp(['Warning! ' num2str(length(whbad)) ' contrasts have bad or missing weights. Imputing mean. ']);\n wok = w; wok(whbad)=[];\n w(whbad) = mean(wok);\n end\n\n % these must sum to 1 !\n DB.studyweight = w ./ sum(w);\n\n\n % -----------------------------------------------------\n % plot studies with weights\n % -----------------------------------------------------\n DB.connames = DB.study(DB.pointind);\n\n figure('Color', 'w');\n set(gca, 'FontSize', 14);\n plot(DB.rootn, 'k:.', 'LineWidth', 2);\n hold on;\n plot(zscore(DB.studyweight)*2+max(DB.rootn)*1.5, 'k.-','LineWidth', 2);\n set(gca, 'XTick', 1:length(DB.pointind), 'XTickLabel', DB.connames);\n try\n legend({'Sqrt(N)' 'Study weights (scaled for display)'})\n catch\n disp('Failed to make legend...Matlab 2010b bug?');\n end\n \n drawnow\n\n\n % save input variables in this directory\n disp('DB structure saved in SETUP.mat');\n save SETUP DB\n diary off\n\n\n % -----------------------------------------------------\n % for each contrast, make a density image\n % -----------------------------------------------------\n PP = []; % image names\n if length(varargin) > 1, PP = varargin{2}; end\n\n if write_contrast_image_flag\n DB = write_contrast_images(DB, t1, PP);\n else\n disp('Contrast image writing is OFF. Use Meta_Activation_FWE for analysis.');\n end\n\n disp('DB struct output of Meta_Setup saved in SETUP.mat');\n disp('Use info in this file to run next step');\n save SETUP DB\nend\n\n\n% ====================================================================\n% --------------------------------------------------------------------\n%\n% subfunctions\n%\n% --------------------------------------------------------------------\n% ====================================================================\n\nfunction str = remove_special_chars(str)\n wh = (str == '''' | str=='\"' | str == '&' | str == '~' | str == '/' | str == '\\');\n wh = find(wh);\n str(wh) = [];\nend\n\n\n\nfunction DB = write_contrast_images(DB,t1,varargin)\n\n PP = []; % image names\n if length(varargin) > 0, PP = varargin{1}; end % load input filenames here!!\n\n\n if isempty(PP)\n\n % normalize density maps so that 1 activation = value of 1 in map\n\n % Try to find images first, and if they don't exist in current dir,\n % create.\n fprintf(1,'Creating images.')\n\n DB.XYZmm = {};\n\n for i = 1:length(DB.pointind)\n\n % peaks in this study, this contrast\n wh = find(DB.Contrast == DB.Contrast(DB.pointind(i)));\n\n studyname = DB.study{wh(1)};\n\n studyname = remove_special_chars(studyname);\n\n XYZmm = DB.xyz(wh,:);\n\n DB.XYZmm{i} = XYZmm;\n\n str = [studyname '_contrast_' num2str(DB.connumbers(i)) '.img']; % name of image\n if exist(str,'file'), disp(['Found existing: ' str])\n\n else\n % doesn't exist yet; create it\n % NOTE: CHANGED 1/3/05 TO NOT WEIGHT BY STUDYWEIGHT HERE.\n % Weights are added later, in Meta_Activation and Meta_Logistic\n % This ensures that if you select a subset of studies with\n % Meta_Select_Contrasts, the weights will be recomputed and\n % reapplied correctly.\n % -------------------------------------------------\n %xyz2density(XYZmm,mask,DB.maskV,str,DB.radius,DB.studyweight(i));\n xyz2density(XYZmm,DB.maskzeros,DB.maskV,str,DB.radius,1);\n\n end % if find existing\n\n PP = str2mat(PP,str);\n\n end % loop thru contrasts\n PP = PP(2:end,:);\n else\n % we have filenames already created\n end\n\n fprintf(1, 'Done %3.0f images in %3.0f s\\n', length(DB.pointind), etime(clock, t1))\n\n DB.PP = PP;\n DB.PP = [repmat([pwd filesep], size(DB.PP, 1), 1) DB.PP];\nend\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Analysis_gui.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Analysis_gui.m", "size": 20892, "source_encoding": "utf_8", "md5": "32cef756c1c6ebeb67d03a28a19a2ef7", "text": "%\n%\n% Tor Wager & Brencho\n%\n% Thanks to Tom Nichols for the excellent GUI shell!\n\n%-----------------------------functions-called------------------------\n%\n%-----------------------------functions-called------------------------\n\nfunction varargout = Meta_Analysis_gui(Action,varargin)\n % global variables we need for this shell\n\n global DB\n global cl\n\n %-Format arguments\n %-----------------------------------------------------------------------\n if nargin == 0, Action='Init'; end\n\n\n switch lower(Action)\n\n case lower('Init')\n %=======================================================================\n\n %clc\n %BrainVowager_defaults;\n Meta_Analysis_gui('AsciiWelcome')\n Meta_Analysis_gui('CreateMenuWin')\n\n % load DB\n\n if(~isempty(DB))\n disp('Using DB already in memory.');\n elseif(exist('DB.mat', 'file'))\n disp('loading DB.mat: Database structure in this file (in current dir) is available.');\n load DB;\n elseif(exist('SETUP.mat', 'file'))\n disp('loading SETUP.mat: Database structure in this file (in current dir) is available.');\n load SETUP;\n else\n disp('You need to go to the directory containing meta-analysis files or results');\n disp('this directory should have information about the analysis stored in the file DB.mat or SETUP.mat')\n disp('No DB file in current directory.');\n DB = [];\n fprintf(1,'\\n')\n end\n \n if(exist('MC_Info.mat', 'file'))\n load('MC_Info');\n set_FWE_results_options(MC_Setup);\n end\n\n varargout{1} = DB;\n\n case lower('AsciiWelcome')\n %=======================================================================\n disp( 'Welcome to the imaging meta-analysis gui. Written by Tor Wager, Jan 2006')\n fprintf('\\n')\n\n case lower('Ver')\n %=======================================================================\n varargout = {'SCNlab Meta-Analysis Menu'};\n\n\n\n case lower('CreateMenuWin')\n %=======================================================================\n close(findobj(get(0,'Children'),'Tag','Meta_Analysis_gui Menu'))\n\n\n %-Initialize Meta_Analysis_gui menu window\n %-----------------------------------------------------------------------\n [F, winwid, winh] = Meta_Analysis_gui('initFigure');\n\n\n % default button sizes and positions, etc.\n\n topbutton = winh-100; % y location of top button\n butspace = 30; % y spacing of buttons\n\n fullbutxy = [160 25]; % full-length button width and height\n halfbutxy = [80 25]; % (left-hand) half-width button w and h\n rightbutxy = halfbutxy;\n rightbutx = 110+halfbutxy(1)+5; % right-hand button start x\n\n\n\n\n\n %-Frames and text\n %-----------------------------------------------------------------------\n axes('Position',[0 0 80/winwid winh/winh],'Visible','Off')\n text(0.5,0.475,'Meta-Analysis Toolbox',...\n 'FontName','Times','FontSize',36,...\n 'Rotation',90,...\n 'VerticalAlignment','middle','HorizontalAlignment','center',...\n 'Color',[1 1 1]*.6);\n\n text(0.2,0.96,'SCN Lab',...\n 'FontName','Times','FontSize',16,'FontAngle','Italic',...\n 'FontWeight','Bold',...\n 'Color',[1 1 1]*.6);\n\n uicontrol(F,'Style','Frame','Position',[095 005 winwid-100 winh - 30],...\n 'BackgroundColor',Meta_Analysis_gui('Color')); % colored frame\n uicontrol(F,'Style','Frame','Position',[105 015 winwid-120 winh - 50]); % inner gray frame\n\n %-Buttons to launch Meta_Analysis_gui functions\n %-----------------------------------------------------------------------\n\n % -------------------------------------------\n % Section - Random Effects Analysis\n uicontrol(F,'Style','Text',...\n 'String','Setup','FontSize',14,...\n 'HorizontalAlignment','Center',...\n 'Position',[115 topbutton+30 fullbutxy],...\n 'ForegroundColor','y','FontWeight','b');\n % -------------------------------------------\n\n % Read txt\n str = 'read_database;'; % callback function\n str = Meta_Analysis_gui('ExpandString',str); % display then execute\n uicontrol(F,'String','Read txt',...\n 'Position',[110 topbutton-(1-1)*butspace halfbutxy],...\n 'CallBack',str,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n % Load\n spmg = 'P = spm_get(1,''*mat'',''Select DB or SETUP mat file:'');';\n str = [spmg ',load(P);']; % callback function\n str = Meta_Analysis_gui('ExpandString',str); % display then execute\n uicontrol(F,'String','Load',...\n 'Position',[rightbutx topbutton-(1-1)*butspace halfbutxy],...\n 'CallBack',str,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n % Meta_Setup\n str = 'DB = Meta_Setup(DB);'; % callback function\n str = Meta_Analysis_gui('ExpandString', str); % display then execute\n uicontrol(F,'String','Meta Setup',...\n 'Position',[110 topbutton-(2-1)*butspace halfbutxy],...\n 'CallBack',str,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n % Meta FWE Setup\n uicontrol(F,'String','Meta FWE Setup',...\n 'Position',[rightbutx topbutton-(2-1)*butspace halfbutxy],...\n 'CallBack', @FWE_setup,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n % Select Contrasts\n str = 'DB = Meta_Select_Contrasts(DB);'; % callback function\n str = Meta_Analysis_gui('ExpandString', str); % display then execute\n uicontrol(F,'String','Select Contrasts',...\n 'Position',[110 topbutton-(3-1)*butspace fullbutxy],...\n 'CallBack',str,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n\n % -------------------------------------------\n % Next section - Analysis\n uicontrol(F,'Style','Text',...\n 'String','Analysis','FontSize',14,...\n 'HorizontalAlignment','Center',...\n 'Position',[115 topbutton-(4-1)*butspace fullbutxy],...\n 'ForegroundColor','y','FontWeight','b');\n % -------------------------------------------\n\n\n% % Activation\n% str = 'DB = Meta_Activation(DB);'; % callback function\n% str = Meta_Analysis_gui('ExpandString',str); % display then execute\n% uicontrol(F,'String','Activation',...\n% 'Position',[110 topbutton-(5-1)*butspace fullbutxy],...\n% 'CallBack',str,...\n% 'Interruptible','on',...\n% 'ForegroundColor','k','FontWeight','b');\n% \n % Monte Carlo\n str = 'Meta_Activation_FWE(''mc'',15000);'; % callback function\n str = Meta_Analysis_gui('ExpandString',str); % display then execute\n uicontrol(F,'String','FWE Monte Carlo',...\n 'Position',[110 topbutton-(5-1)*butspace fullbutxy],...\n 'CallBack',str,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n % Logistic\n % spmg = 'maskimg = spm_get(1,''*img'',''Select mask image file:''); ';\n % str1 = 'DB = Meta_Logistic(DB,2,maskimg);'; % callback function\n % str = [spmg str1];\n % str = Meta_Analysis_gui('ExpandString',str); % display then execute\n % uicontrol(F,'String','Logistic',...\n % 'Position',[110 topbutton-(6-1)*butspace fullbutxy],...\n % 'CallBack',str,...\n % 'Interruptible','on',...\n % 'ForegroundColor','k','FontWeight','b');\n\n % Chi-square\n spmg = 'maskimg = spm_get(1,''*img'',''Select mask image file:''); ';\n str1 = 'DB = Meta_Chisq(DB,2,maskimg);'; % callback function\n str = [spmg str1];\n str = Meta_Analysis_gui('ExpandString',str); % display then execute\n uicontrol(F,'String','Chi-square',...\n 'Position',[110 topbutton-(6-1)*butspace fullbutxy],...\n 'CallBack',str,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n % Specificity - IN PROGRESS\n str = 'DB = Meta_Specificity(DB)' ; % callback function\n str = Meta_Analysis_gui('ExpandString', str); % display then execute\n uicontrol(F,'String','Specificity',...\n 'Position',[110 topbutton-(7-1)*butspace fullbutxy],...\n 'CallBack',str,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n\n % -------------------------------------------\n % Next section - Results\n uicontrol(F,'Style','Text',...\n 'String','Results','FontSize',14,...\n 'HorizontalAlignment','Center',...\n 'Position',[115 topbutton-(8-1)*butspace fullbutxy],...\n 'ForegroundColor','y','FontWeight','b');\n % -------------------------------------------\n\n % Get blobs\n %str1 = ['pimg = spm_get(1,''*img'',''Select p-value image.'',pwd);'];\n %str = 'cl = pmap_threshold; bar_interactive;';\n\n str = Meta_Analysis_gui('setupResultsView');\n %str = Meta_Analysis_gui('ExpandString', str); % set up display then execute string for callback\n uicontrol(F,'String','Get Blobs',...\n 'Position',[110 topbutton-(9-1)*butspace fullbutxy],...\n 'CallBack',str,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n % Blob Display\n if exist('scn_roi_gui', 'file')\n str = 'scn_roi_gui;'; % callback function\n else\n str1 = 'if isempty(cl), disp([''Load a clusters cl.mat file first!'']), return, end;';\n str2 = 'cluster_orthviews(cl,{[1 0 0]}); set(gcf,''WindowButtonUpFcn'',''Meta_interactive_table;'')';\n str = [str1 str2];\n end\n\n str = Meta_Analysis_gui('ExpandString', str); % display then execute\n uicontrol(F,'String','Blob Display Tool',...\n 'Position',[110 topbutton-(10-1)*butspace fullbutxy],...\n 'CallBack',str,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n % FWE results\n% str = 'Meta_Activation_FWE(''results'');';\n% str = Meta_Analysis_gui('ExpandString', str); % display then execute\n uicontrol(F,'String','FWE Results',...\n 'Position',[110 topbutton-(11-1)*butspace fullbutxy],...\n 'CallBack', @FWE_results_callback,...\n 'Interruptible','on',...\n 'ForegroundColor','k','FontWeight','b');\n\n if(exist('MC_Setup', 'var'))\n dropdown_options = FWE_results_dropdown_options(MC_Setup);\n else\n dropdown_options = {'Run Meta FWE Setup'};\n end\n uicontrol(F,'String',dropdown_options,...\n 'Position',[110 topbutton-(12-1)*butspace fullbutxy],...\n 'Style', 'popupmenu', ...\n 'Tag', 'FWE results popup', ...\n 'ForegroundColor','k','FontWeight','b');\n \n \n checkbox_indent = 20;\n uicontrol(F, 'String', 'Height', ...\n 'Style', 'checkbox', ...\n 'Tag', 'FWE results checkbox', ...\n 'UserData', 'height', ...\n 'Value', 1, ...\n 'Position',[(110+checkbox_indent) topbutton-(13-1)*butspace (fullbutxy(1)-checkbox_indent) fullbutxy(2)]);\n uicontrol(F, 'String', 'Cluster 95/.05', ...\n 'Style', 'checkbox', ...\n 'Tag', 'FWE results checkbox', ...\n 'UserData', 'lenient', ...\n 'Value', 1, ...\n 'Position',[(110+checkbox_indent) topbutton-(14-1)*butspace (fullbutxy(1)-checkbox_indent) fullbutxy(2)]);\n uicontrol(F, 'String', 'Cluster 99/.01', ...\n 'Style', 'checkbox', ...\n 'Tag', 'FWE results checkbox', ...\n 'UserData', 'medium', ...\n 'Value', 1, ...\n 'Position',[(110+checkbox_indent) topbutton-(15-1)*butspace (fullbutxy(1)-checkbox_indent) fullbutxy(2)]);\n uicontrol(F, 'String', 'Cluster 99.9/.001', ...\n 'Style', 'checkbox', ...\n 'Tag', 'FWE results checkbox', ...\n 'UserData', 'stringent', ...\n 'Value', 1, ...\n 'Position',[(110+checkbox_indent) topbutton-(16-1)*butspace (fullbutxy(1)-checkbox_indent) fullbutxy(2)]);\n \n\n set(F,'Pointer','Arrow','Visible','on')\n\n\n\n case lower('Color')\n %=======================================================================\n % Meta_Analysis_gui('Color')\n %-----------------------------------------------------------------------\n % %-Developmental livery\n % varargout = {[0.7,1.0,0.7], 'Lime Green'};\n %-Distribution livery\n varargout = {[.8 0.5 .2], 'Purple'};\n\n\n case lower('ExpandString')\n %=======================================================================\n % Meta_Analysis_gui('ExpandString')\n % Expand an action button callback string (a command string to be\n % evaluated)\n % so that it first displays the command, and then executes it\n %-----------------------------------------------------------------------\n str = varargin{1}; str2 = [];\n for i = 1:length(str)\n if str(i) == ''''\n str2(end+1) = '''';\n str2(end+1) = '''';\n else\n str2(end+1) = str(i);\n end\n end\n\n %str = ['disp(''' char(str2) '''), ' str ]; % display then execute\n\n str = ['Meta_Analysis_gui(''executeCommand'',''' str2 ''');'];\n varargout = {str};\n\n\n case lower('initFigure')\n %=======================================================================\n % [F, winwid, winh] = Meta_Analysis_gui('initFigure')\n %-----------------------------------------------------------------------\n % Get the position of the main BrainVowager menu, or if\n % not available, default screen pos.\n\n % default sizes, etc.\n S = get(0,'ScreenSize');\n\n winwid = 300; % window width\n winh = 580; % window height\n pos = [S(3)/2+150,S(4)/2-140,winwid,winh]; % default\n\n h = findobj('Tag','BrainVowager_gui Menu');\n if ~isempty(h),\n pos = get(h,'Position');\n winwid = pos(3); winh = pos(4);\n pos(1) = pos(1) + winwid; % put next to main figure\n end\n\n %-Open Meta_Analysis_gui menu window\n %----------------------------------------------------------------------\n\n F = figure('Color',[1 1 1]*.8,...\n 'Name',Meta_Analysis_gui('Ver'),...\n 'NumberTitle','off',...\n 'Position',pos,...\n 'Resize','off',...\n 'Tag','Meta_Analysis_gui Menu',...\n 'Pointer','Watch',...\n 'MenuBar','none',...\n 'Visible','off');\n\n varargout{1} = F; varargout{2} = winwid; varargout{3} = winh;\n\n\n case lower('executeCommand')\n %=======================================================================\n % Meta_Analysis_gui('executeCommand',str)\n %-----------------------------------------------------------------------\n % Display a text header highlighting the command to be run\n\n fprintf(1,'\\n______________________________________________\\n')\n fprintf(1,'Meta Analysis tool c 2006 Tor Wager\\n');\n fprintf(1,'Executing command string:\\n');\n fprintf(1,'%s\\n',varargin{1});\n fprintf(1,'______________________________________________\\n')\n eval(varargin{1});\n\n\n\n\n case lower('setupResultsView')\n %=======================================================================\n % callbackstr = Meta_Analysis_gui('setupResultsView')\n %-----------------------------------------------------------------------\n % Set up callback string for results view 'wizard'\n\n str1 = sprintf('class_avg_images = []; Xinms = [];\\n');\n str2 = sprintf('try, load SETUP class_avg_images Xinms, \\n disp(class_avg_images);,disp(Xinms),\\ncatch,\\nend\\n');\n str3 = sprintf('cl = pmap_threshold;\\nbar_interactive(class_avg_images,Xinms);\\n');\n varargout{1} = [str1 str2 str3];\n\n otherwise\n %=======================================================================\n error('Unknown action string')\n %======================================================================\n end\nend\n\n%=======================================================================\n% Callbacks\n%-----------------------------------------------------------------------\nfunction FWE_results_callback(src, eventdata)\n useparams = {};\n \n checkboxes = findobj('Tag', 'FWE results checkbox');\n for i=1:length(checkboxes)\n if(get(checkboxes(i), 'Value') == 1)\n useparams{end+1} = get(checkboxes(i), 'UserData');\n end\n end\n \n popuph = findobj('Tag', 'FWE results popup');\n [maptype, contrast_num] = parse_results(popuph)\n if(~strcmp(maptype, 'act'))\n useparams{end+1} = maptype;\n end\n if(~isempty(contrast_num))\n useparams{end+1} = 'contrast';\n useparams{end+1} = contrast_num;\n end\n \n Meta_Activation_FWE('results', 1, useparams{:});\nend\n\nfunction FWE_setup(src, eventdata)\n global DB; % no getting around this without refactoring whole file... DB is not initialized when callback is setup\n MC_Setup = Meta_Activation_FWE('setup', DB);\n set_FWE_results_options(MC_Setup);\nend\n\n%=======================================================================\n% Local functions\n%-----------------------------------------------------------------------\nfunction set_FWE_results_options(MC_Setup)\n popuph = findobj('Tag', 'FWE results popup');\n set(popuph, 'String', FWE_results_dropdown_options(MC_Setup));\nend\n\nfunction result_options = FWE_results_dropdown_options(MC_Setup)\n result_options = cell(1, 1 + 2*length(MC_Setup.connames));\n result_options{1} = 'Overall';\n for i = 1:length(MC_Setup.connames)\n result_options{2*i} = [MC_Setup.connames{i} '-pos'];\n result_options{(2*i)+1} = [MC_Setup.connames{i} '-neg'];\n end\nend\n\nfunction [maptype, contrast_num] = parse_results(popuph)\n selected = get(popuph, 'Value');\n if(selected == 1)\n maptype = 'act';\n contrast_num = [];\n else\n popup_options = get(popuph, 'String');\n selected_contrast_string = popup_options{selected};\n if(~isempty(strfind(selected_contrast_string, 'pos')))\n maptype = 'poscon';\n else\n maptype = 'negcon';\n end\n \n contrast_num = floor(selected / 2);\n end\nend"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Select_Contrasts.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Select_Contrasts.m", "size": 5138, "source_encoding": "utf_8", "md5": "a9c2518ebf81a206895917a47667bf09", "text": "function [DB] = Meta_Select_Contrasts(DB)\n% [DB] = Meta_Select_Contrasts(DB)\n%\n% Set up logistic regression design matrix from DB\n%\n% needs to set up design:\n%DB.(fields) % lists of fields containing task conditions for each coordinate point\n%DB.pointind % indices of which coord points are in which unique\n% contrast\n%DB.x % x coordinates, just to get # of points\n\nglobal dolist\ndolist = 1;\n\ntestfield = 'xxx';\nX = []; Xnms = {};\n\nwhile ~isempty(testfield)\n \n % get field name\n testfield = getfield(DB);\n \n if isempty(testfield), \n % done\n else\n \n testfield1 = testfield;\n \n % check to see if each contrast has only one level\n meta_check_contrasts(DB,testfield)\n \n % get unique levels\n levels = getlevels(DB,testfield);\n\n % plot image of contrasts\n meta_plot_contrasts(DB,testfield,levels);\n title('Before database pruning');\n \n % get indicators for these levels\n [ti,tasknms] = string2indicator(DB.(testfield),levels);\n\n X = [X ti];\n Xnms = [Xnms tasknms];\n end\n \nend\n\nfprintf(1,'\\n'); fprintf(1,'\\n');\n\n\n% -----------------------------------------------------\n% Prune database based on in-analysis points (contrasts)\n% -----------------------------------------------------\n\n% get only unique contrast entries\ninclude = sum(X,2);\n\nDB = Meta_Prune(DB,include); % this excludes contrast-wise\n\nmeta_plot_contrasts(DB,testfield1,levels);\ntitle('After pruning (valid contrasts)');\n\n\n% -----------------------------------------------------\n% Re-do Final contrast weights\n% -----------------------------------------------------\n\nif isfield(DB,'SubjectiveWeights'),\n w = DB.rootn .* DB.SubjectiveWeights(DB.pointind);\nelse\n w = DB.rootn;\nend\n\n% these must sum to 1 !\nDB.studyweight = w ./ sum(w);\n\n\nend\n\n\n\n\n\nfunction testfield = getfield(DB)\n% Empty or field name from DB\nglobal dolist\n\n% list field names\nfprintf(1,'Database field names\\n---------------------------\\n')\nN = fieldnames(DB);\nif dolist\n for i = 1:length(N),\n tmp = DB.(N{i}); len = length(tmp);\n if len == length(DB.x), fprintf(1,'%s\\n',N{i});,end\n end\n\n fprintf(1,'\\n');\n dolist = 0;\nend\n\ngook = [];\nwhile isempty(gook)\n testfield = input('Enter field name or end if finished: ','s');\n\n if isempty(testfield),\n gook = 1;\n else\n gook = strmatch(testfield,N);\n end\n if isempty(gook), fprintf(1,'Not a field name.'); pause(1); fprintf('\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b');, end\nend\n\nend\n\n\n\n\n\nfunction levels = getlevels(DB,testfield);\n\neval(['levels = DB.' testfield ';']);\nlevels = levels(DB.pointind);\n[pts,ind] = unique(levels);\n\nfprintf(1,'Unique values of this variable:\\n');\n\nfor i = 1:size(pts,1), fprintf(1,'%3.0f\\t%s\\n',i,pts{i}); end\nwh = input('Enter vector of levels to use: ');\nlevels = pts(wh);\n\nend\n\n\n\n\nfunction DB = prune(DB,include,inc_con)\n% Empty or field name from DB\n\nN = fieldnames(DB);\nwhp = find(include);\nwhc = find(inc_con);\n\n% special for DB.pointind\n%pind = zeros(size(DB.x)); pind(DB.pointind) = 1;\n%pind = pind(whp);\n\nfor i = 1:length(N),\n \n tmp = DB.(N{i}); len = length(tmp);\n if ismatrix(tmp), len = size(tmp,1);,end\n \n if len == length(include), \n DB.(N{i}) = tmp(whp);\n elseif len == length(inc_con), \n if ismatrix(tmp),\n DB.(N{i}) = tmp(whc,:);\n else\n DB.(N{i}) = tmp(whc);\n end\n end\n \nend\n\n%DB.pointind = find(pind)';\n%[DB.connumbers,DB.pointind] = unique(DB.Contrast);\n\n% re-make pointind\nfor i = 1:length(DB.connumbers)\n wh = find(DB.Contrast == DB.connumbers(i));\n DB.pointind(i) = wh(1);\nend\n\nend\n\n\n\n\nfunction meta_plot_contrasts(DB,testfield,levels)\n\n % get unique levels\n if isempty(levels), levels = getlevels(DB,testfield);, end\n\n % get indicators for these levels\n [ti,tasknms] = string2indicator(DB.(testfield),levels);\n\n\n tor_fig; s = get(0,'ScreenSize'); set(gcf,'Position',[s(3).*.5 s(4).*.5 600 600]); \n tmp = [ti*100 DB.Contrast]; tmp(tmp == 0) = NaN;\n imagesc(tmp); set(gca,'XTick',1:size(tmp,2),'XTickLabel',[tasknms {'Contrast'}]); colormap prism\n cm = colormap(jet(size(tmp,1))); cm = cm(randperm(length(cm))',:);\n cm(1,:) = [1 1 1]; cm(2,:) = [1 0 0];\n colormap(cm); hold on; \n for i = 1:length(DB.Contrast),wh1 = find(DB.Contrast==i);, \n if ~isempty(wh1)\n wh1 = wh1(end)+.5; plot([0 size(tmp,2)+.5], [wh1 wh1],'k');, \n end\n end\n set(gca,'YDir','Reverse'); ylabel('Peak Coordinate index');\n\n % print names\n for i = 1:size(ti,2)\n tmp = unique(DB.study(find(ti(:,i))))';\n fprintf(1,'\\nVariable: %s Level: %s %3.0f studies\\n',testfield,tasknms{i},length(tmp))\n fprintf(1,'%s\\t',tmp{:})\n fprintf(1,'\\n');\n end\n \nend\n\n\n\n% ISMATRIX: Returns 1 if the input matrix is 2+ dimensional, 0 if it is a scalar \n% or vector.\n%\n% Usage ismat = ismatrix(X)\n%\n% RE Strauss, 5/19/00\n\nfunction ismat = ismatrix(X)\n [r,c] = size(X);\n if (r>1 && c>1)\n ismat = 1;\n else\n ismat = 0;\n end\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Activation_FWE.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Activation_FWE.m", "size": 38042, "source_encoding": "utf_8", "md5": "0399062ab3617ffc65421f8786e3b484", "text": "% Meta_Activation_FWE(meth)\n%\n% This function sets up an MKDA analysis, starts or adds iterations, and\n% retrieves and plots results. It has four modes, specified by the first input argument:\n%\n% 'setup' : Create activation map and save MC_SETUP file in current directory\n% 'mc' : Add iterations and save in MC_Info in current dir\n% 'results' : Get results\n% 'all' : Do all of the above in sequence\n%\n% Optional inputs: \n% Enter these only AFTER obligatory inputs specified below:\n% 'nocontrasts' : Do not specify contrasts across conditions, and do not\n% prompt user (non-interactive mode)\n% 'noverbose' : Do not print output showing progress updates during mc\n% iteration\n%\n% See below for specific formatting strings:\n% \n% ALL\n% ----------------------------------------------------------------------\n% Meta_Activation_FWE('all', DB, iterations, [other inputs]) [default]\n% > Run all of the commands below in sequence\n%\n% SETUP\n% ----------------------------------------------------------------------\n% MC_Setup = Meta_Activation_FWE('setup', DB)\n% > Create activation map .img and MC_Setup structure; save MC_Info\n% Optional argument: 'nocontrasts' avoids interactive query and skips\n% contrats step\n%\n% MC\n% ----------------------------------------------------------------------\n% Meta_Activation_FWE('mc', iterations)\n% > Create or add null hypothesis iterations to MC_Info\n%\n% RESULTS\n% ----------------------------------------------------------------------\n% Meta_Activation_FWE('results')\n% > Get and plot results\n%\n% See also: Meta_results_batch_script, publish_meta_analysis_report\n% These use the newer object-oriented functions to create and show results\n% in a different way.\n%\n% Examples:\n% For contrasts, positive contrast values. The 1 below indicates to make plots.\n% cl = Meta_Activation_FWE('results', 1, 'poscon')\n% Negative contrast values\n% cl = Meta_Activation_FWE('results', 1, 'negcon')\n% Which thresholds to use:\n% Meta_Activation_FWE('results', 1, 'height', 'stringent', 'medium', 'lenient') [default]\n% Meta_Activation_FWE('results', 1, 'height', 'stringent') <- only use height and most stringent extent\n% Meta_Activation_FWE('results', 1, 'negcon', 'height', 'stringent') <- only use height and most stringent extent and neg con values\n% Which contrast to use:\n% Meta_Activation_FWE('results', 1, 'negcon', 'contrast', 3) <- negative con values for contrast 3\n%\n% Enter colors:\n% Meta_Activation_FWE('results','colors',[1 1 0;1 .5 0;1 .3 .3;.8 .4 .4])\n% Meta_Activation_FWE('results','grayscale');\n%\n% Plot surfaces as well:\n% Meta_Activation_FWE('results','surface');\n%\n% Save slices showing each cluster center:\n% Meta_Activation_FWE('results','slices');\n% Meta_Activation_FWE('results', 1, 'negcon','contrast',8,'slices');\n%\n% Add different colors to an existing plot\n% cl_posneg = Meta_Activation_FWE('results', 1, 'height', 'stringent', 'medium', 'poscon'); \n% cl_negpos = Meta_Activation_FWE('results', 1, 'height', 'stringent', 'medium', 'negcon', 'add', 'colors', { [0 0 1] [0 .5 1] [.3 .3 1] });\n%\n% by Tor Wager, May 2006. See Programmers' notes in function for more details.\n%\n% See also: \n% Meta_results_batch_script, publish_meta_analysis_report\n\n% Programmers' notes:\n% ------------------------------------------------------------------------\n% by Tor Wager, May 2006.\n% edited by Matthew Davidson June 2006\n% modified: tor, Aug 2006\n% tor: Sept, 2009: add cl output to \"results\" mode (minor)\n% tor: march 2010, to add bivalent colors 'add' option\n% tor: june 2016, added 'nocontrasts' option and a bit of documentation\n\n% 4.7.2013 There was a bug in Meta_Activation_FWE that made it not robust to using \n% non-ascending numerical order of contrasts in DB.Contrast. \n% The function meta_prob_activation was reconstructing the maps in ascending order of \n% contrasts, returning maps in ascending sorted contrast order in \n% MC_Setup.unweighted_study_data. MC_Setup.Xi, the indicators for task type, are \n% sorted in the order of contrasts entered in the database, which respects the order \n% in DB.pointind and DB.connumbers from Meta_Setup. Tor changed the sort order in \n% meta_prob_activation to use DB.connumbers. \n% \n% This affects MKDA difference analyses (contrasts) when contrast numbers are not \n% entered in ascending numerical order in your database. It also affects classification \n% with Meta_NBC_from_mkda, but not Meta_SVM_from_mkda.\n%\n% 2.23.2017 There was a bug in results display when using only selected\n% thresholds, rather than the full set of \"stringent\" \"medium\" \"lenient\"\n% (which gave correct values). Tor fixed this, and added functionality to\n% save separate results masks for each threshold you select.\n\nfunction varargout = Meta_Activation_FWE(meth, varargin)\n\n doverbose = true;\n if any(strcmp(varargin, 'noverbose')), doverbose = false; end\n \n varargout = {};\n\n switch lower(meth)\n \n case 'all'\n \n if length(varargin) > 2\n extra_args = varargin(3:end);\n else\n extra_args = {};\n end\n\n MC_Setup = Meta_Activation_FWE('setup', varargin{1}, extra_args{:});\n Meta_Activation_FWE('mc', varargin{2}, extra_args{:})\n Meta_Activation_FWE('results')\n \n case 'setup'\n % ------------------------------------------------\n % Setup and write activation probability map\n % ------------------------------------------------\n DB = meta_check_dbsetup(varargin{1});\n\n if any(strcmp(varargin, 'nocontrasts'))\n docons = false;\n else\n docons = input('Compute contrasts across conditions also? (1/0)');\n end\n \n if docons\n \n [X,connames, DB, Xi, Xinms, condf, testfield, contrasts] = Meta_Logistic_Design(DB);\n [MC_Setup, activation_proportions] = meta_prob_activation(DB, Xi, contrasts, connames, Xinms);\n \n else\n \n [MC_Setup, activation_proportions] = meta_prob_activation(DB);\n if doverbose, disp('Activation map written: Activation_proportion.img'); end\n \n end\n\n % THE CODE BELOW IS REQUIRED FOR BLOB-SHUFFLING ONLY\n % ------------------------------------------------\n % set up blobs for all studies\n % ------------------------------------------------\n if doverbose\n str = sprintf('Getting blobs for all studies');\n fprintf(1, str);\n end\n \n s = size(MC_Setup.unweighted_study_data, 2);\n MC_Setup.cl = cell(1,s);\n for i = 1:s\n MC_Setup.cl{i} = iimg_indx2contiguousxyz(MC_Setup.unweighted_study_data(:,i),MC_Setup.volInfo,1);\n end\n \n if doverbose\n erase_string(str);\n end\n \n % ------------------------------------------------\n % Save setup info\n % ------------------------------------------------\n if exist(fullfile(pwd, 'MC_Info.mat'),'file')\n save MC_Info -append MC_Setup activation_proportions\n if doverbose, disp('Appended info to existing MC_Info.mat.'); end\n else\n save MC_Info MC_Setup activation_proportions\n if doverbose, disp('Created new MC_Info.'); end\n end\n \n if exist(fullfile(pwd, 'SETUP.mat'),'file')\n save SETUP -append DB\n if doverbose, disp('Appended DB to existing SETUP.mat.'); end\n else\n save SETUP DB\n if doverbose, disp('Created new SETUP.mat file and saved DB in it.'); end\n end\n \n varargout{1} = MC_Setup;\n\n case 'mc'\n % ------------------------------------------------\n % Monte Carlo iterations (create or add to existing)\n % ------------------------------------------------\n tic\n iter = varargin{1}; % iterations to create or add\n\n [MC_Setup, maxprop, uncor_prop, maxcsize, startat] = setup_mc_vars(iter);\n\n last = length(maxprop.act);\n\n if doverbose, fprintf(1,'Iteration '); end\n\n for i = startat:last\n\n if doverbose, fprintf(1,'%05d ',i); end\n\n %[maxprop(i),uncor_prop(i,:),maxcsize(i,:)] = meta_stochastic_activation(MC_Setup);\n\n [mp,up,cs] = meta_stochastic_activation_blobs(MC_Setup);\n\n maxprop.act(i) = mp.act;\n uncor_prop.act(i,:) = up.act;\n maxcsize.act(i,:) = cs.act;\n if isfield(mp,'poscon')\n maxprop.poscon(i,:) = mp.poscon;\n maxprop.negcon(i,:) = mp.negcon;\n\n nconds = size(MC_Setup.ctxtxi,1);\n for j = 1:nconds\n\n uncor_prop.poscon{j}(i,:) = up.poscon(j,:);\n maxcsize.poscon{j}(i,:) = cs.poscon(j,:);\n\n uncor_prop.negcon{j}(i,:) = up.negcon(j,:);\n maxcsize.negcon{j}(i,:) = cs.negcon(j,:);\n end\n end\n\n if mod(i,10) == 0 || i == last\n if doverbose\n str = sprintf('Saving results in MC_Info'); \n fprintf(1,str);\n end\n \n save MC_Info -append maxprop uncor_prop maxcsize\n \n if doverbose, erase_string(str); end\n end\n\n if doverbose, fprintf(1,'\\b\\b\\b\\b\\b\\b'); end\n\n end\n\n if doverbose, fprintf(1,'Done!\\n'); end\n toc\n\n case 'results'\n % ------------------------------------------------\n % Get results, threshold, and display\n % ------------------------------------------------\n maptype = 'act';\n conidx = [];\n\n doplots = 1;\n useheight = 1;\n usestringent = 1;\n usemedium = 1;\n uselenient = 1;\n colors = [1 1 0;1 .5 0;1 .3 .3;.8 .4 .4]; % for activation maps [default]\n dosurface = 0;\n doslices = 0;\n using_defaults = 1;\n dotables = 1;\n addstr = 'noadd';\n\n read_results_inputs(); % sets up defaults for surfaces, slices, etc.\n\n % load Setup and prepare thresholds and data vectorized image\n [MC_Setup, statmap, imgprefix, maxprop, uncor_prop, maxcsize, conidx] = setup_results_vars(maptype, conidx);\n\n % get and plot thresholds\n [maxthr,uncor_thr,maxcthr] = get_thresholds(maxprop, uncor_prop, maxcsize, maptype, doplots, conidx);\n\n % thresholds to save, based on input; (Tor - fix, Feb 2017)\n whomsave = logical([uselenient usemedium usestringent]);\n\n \n % plot proportions or contrast in statmap\n if doplots\n subplot(1,3,3);\n plot_act_prop(statmap,maxthr,uncor_thr,whomsave);\n end\n\n % get rid of thresholds we're not interested in seeing in\n % figures - NOTE: Cannot remove because code below assumes same\n % order\n% uncor_thr = uncor_thr(whomsave);\n% maxcthr = maxcthr(whomsave);\n \n % Height threshold -- whole brain FWE corrected\n if(useheight)\n i1 = statmap >= maxthr;\n wh = find(i1);\n \n fprintf(1, '\\np <= .05 Corrected: Thresh = %3.4f, %3.0f voxels\\n\\n', maxthr, length(wh));\n\n % Write results image\n indic2mask(i1, statmap, MC_Setup, [imgprefix '_FWE_height.img']);\n else\n i1 = 0;\n end\n\n % get clusters to save; old plotting functions\n %cl = mask2clusters([imgprefix '_FWE_height.img']);\n %if doplots, cluster_orthviews(cl); end\n\n if(usestringent || usemedium || uselenient)\n e1 = 0;\n e2 = 0;\n e3 = 0;\n\n % Extent threshold -- corrected based on cluster size\n if(usestringent)\n \n e1 = meta_cluster_extent_threshold(MC_Setup.volInfo.xyzlist', statmap, uncor_thr(3), maxcthr(3));\n % Write results image\n indic2mask(e1, statmap, MC_Setup, [imgprefix '_FWE_extent_stringent.img']);\n \n end\n \n if(usemedium)\n e2 = meta_cluster_extent_threshold(MC_Setup.volInfo.xyzlist', statmap, uncor_thr(2), maxcthr(2));\n % Write results image\n indic2mask(e2, statmap, MC_Setup, [imgprefix '_FWE_extent_medium.img']);\n \n end\n \n if(uselenient)\n \n e3 = meta_cluster_extent_threshold(MC_Setup.volInfo.xyzlist', statmap, uncor_thr(1), maxcthr(1));\n % Write results image\n indic2mask(e3, statmap, MC_Setup, [imgprefix '_FWE_extent_lenient.img']);\n \n end\n\n e = e1 | e2 | e3;\n % Write results image\n indic2mask(e, statmap, MC_Setup, [imgprefix '_FWE_extent.img']);\n else\n e = 0;\n end\n % any of the above\n indic = i1 | e;\n\n % Write results image\n indic2mask(indic, statmap, MC_Setup, [imgprefix '_FWE_all.img']);\n\n % plot if asked for\n %cl = mask2clusters('Activation_FWE_all.img');\n if doplots\n\n % multi-threshold view\n [cl,dat] = iimg_multi_threshold(statmap, ...\n 'thresh', [maxthr sort(uncor_thr(whomsave),'descend')], ...\n 'size', [1 sort(maxcthr(whomsave))], ...\n 'volInfo', MC_Setup.volInfo,'colors',colors, addstr);\n\n disp(['Saving clusters as cl variable in ' imgprefix '_clusters.mat']);\n eval(['save ' imgprefix '_clusters cl dat']);\n\n %cluster_orthviews(cl);\n end\n\n if exist('cl', 'var'), varargout{1} = cl; end\n \n if doslices\n \n %overlay = which('scalped_single_subj_T1.img');\n overlay = which('spm2_single_subj_T1_scalped.img');\n \n if ~isempty(cl{1})\n cluster_orthviews_showcenters(cl{1},'coronal',overlay,0,1);\n saveas(gcf,[imgprefix '_act_coronal_slices'],'fig');\n saveas(gcf,[imgprefix '_act_coronal_slices'],'png');\n cluster_orthviews_showcenters(cl{1},'sagittal',overlay,0,1);\n saveas(gcf,[imgprefix '_act_sag_slices'],'fig');\n saveas(gcf,[imgprefix '_act_sag_slices'],'png');\n cluster_orthviews_showcenters(cl{1},'axial',overlay,0,1);\n saveas(gcf,[imgprefix '_act_axial_slices'],'fig');\n saveas(gcf,[imgprefix '_act_axial_slices'],'png');\n end\n\n if length(cl) > 1 && ~isempty(cl{2})\n cluster_orthviews_showcenters(cl{2},'coronal',overlay,0,1);\n saveas(gcf,[imgprefix '_extent1_coronal_slices'],'fig');\n saveas(gcf,[imgprefix '_extent1_coronal_slices'],'png');\n cluster_orthviews_showcenters(cl{2},'sagittal',overlay,0,1);\n saveas(gcf,[imgprefix '_extent1_sag_slices'],'fig');\n saveas(gcf,[imgprefix '_extent1_sag_slices'],'png');\n cluster_orthviews_showcenters(cl{2},'axial',overlay,0,1);\n saveas(gcf,[imgprefix '_extent1_axial_slices'],'fig');\n saveas(gcf,[imgprefix '_extent1_axial_slices'],'png');\n end\n \n end\n \n if dosurface\n\n% % % lateral surfaces in orthviews\n% % create_figure('Lateral surface');\n% % surfhan = make_surface([],cl{1},cl(2:end),3,colors);\n% % %\n% % \n% % saveas(gcf,[imgprefix '_surf'],'png');\n% % \n% % [hh1,hh2,hh3,hl,a1,a2,a3] = make_figure_into_orthviews;\n% % view(180,-90); [az,el]=view; h = lightangle(az,el);\n% % scn_export_papersetup(500)\n% % \n% % saveas(gcf,[imgprefix '_orth_surf'],'fig');\n% % saveas(gcf,[imgprefix '_orth_surf'],'png');\n\n \n% % % left and right medial\n% % create_figure('Medial surfaces', 1, 2);\n% % surfhan = make_surface('hires left',cl{1},cl(2:end),3,colors);\n% % subplot(1,2,2);\n% % surfhan = make_surface('hires right',cl{1},cl(2:end),3,colors);\n% % \n % limbic surfaces\n create_figure('Limbic surface');\n surfhan = make_surface('brainstem',cl{1},cl(2:end),3,colors);\n surfhan = make_surface('cerebellum',cl{1},cl(2:end),3,colors);\n surfhan = make_surface('amygdala',cl{1},cl(2:end),3,colors);\n surfhan = make_surface('nucleus accumbens',cl{1},cl(2:end),3,colors);\n surfhan = make_surface('hippocampus',cl{1},cl(2:end),3,colors);\n surfhan = make_surface('left',cl{1},cl(2:end),3,colors);\n scn_export_papersetup(500)\n\n saveas(gcf,[imgprefix '_limbic_surf'],'fig');\n saveas(gcf,[imgprefix '_limbic_surf'],'png');\n \n % Note: to replace colored backgrounds with gray, try\n % this:\n %f = findobj(gcf,'Type', 'patch'); set(f, 'FaceColor', 'interp')\n %for i = 1:length(f), set(f(i), 'FaceVertexCData', repmat([.5 .5 .5], size(get(f(i), 'FaceVertexCData'), 1), 1)); cluster_surf(f(i),cl{1},10,{[1 1 0]}); end\n \n\n end\n \n if dotables\n cluster_table_successive_threshold(cl,10);\n end\n \n \n otherwise\n error('Unknown method.');\n end % switch Method\n\n\n % --------------------------------------------------------------------\n %\n % IN-line functions: These have access to all vars in main function\n % Needs matlab 2006a or later\n %\n % --------------------------------------------------------------------\n\n function read_results_inputs()\n if(length(varargin) > 0), doplots = varargin{1}; end\n if(length(varargin) > 1)\n args = varargin(1:end); % edited 9/1/2009; do not force first input to be doplots only\n for i=1:length(args)\n if ischar(args{i}) % fixed bug, 9/1/2009\n switch(args{i})\n case {'negcon', 'poscon'}\n maptype = args{i};\n\n case {'height', 'stringent', 'medium', 'lenient'}\n if(using_defaults)\n useheight = 0;\n usestringent = 0;\n usemedium = 0;\n uselenient = 0;\n using_defaults = 0;\n end\n\n switch(args{i})\n case 'height'\n useheight = 1;\n case 'stringent'\n usestringent = 1;\n case 'medium'\n usemedium = 1;\n case 'lenient'\n uselenient = 1;\n end\n case 'contrast'\n conidx = args{i+1};\n\n case 'surface'\n dosurface = 1;\n\n case 'colors'\n colors = args{i+1};\n\n case 'grayscale'\n colors = [0 0 0; .25 .25 .25; .4 .4 .4; .7 .7 .7];\n\n case 'slices'\n doslices = 1;\n \n case 'add'\n addstr = 'add';\n \n end\n end\n end\n end\n end\nend % Main function\n\n\n\n% ====================================================================\n% --------------------------------------------------------------------\n%\n% Monte Carlo subfunctions\n%\n% --------------------------------------------------------------------\n% ====================================================================\n\nfunction [MC_Setup, maxprop, uncor_prop, maxcsize,startat] = setup_mc_vars(iter)\n\n % These should be loaded in file\n MC_Setup = []; maxprop = []; uncor_prop = []; maxcsize = [];\n\n if ~exist('MC_Info.mat','file')\n error('You must have an MC_Info file in the current dir that contains MC_Setup.');\n else\n load MC_Info\n end\n\n if isempty(maxprop) % no existing results; initialize\n fprintf(1,'No MC iterations found yet. Creating maxprop, uncor_prop, maxcsize\\n');\n\n maxprop.act = zeros(iter,1);\n uncor_prop.act = zeros(iter,3);\n maxcsize.act = zeros(iter,3);\n\n if isfield(MC_Setup,'ctxtxi') % do by-conditions also\n nconds = size(MC_Setup.ctxtxi,1);\n\n maxprop.poscon = zeros(iter, nconds);\n maxprop.negcon = zeros(iter, nconds);\n\n for i = 1:nconds\n uncor_prop.poscon{i} = zeros(iter,3);\n maxcsize.poscon{i} = zeros(iter,3);\n\n uncor_prop.negcon{i} = zeros(iter,3);\n maxcsize.negcon{i} = zeros(iter,3);\n end\n end\n else\n % existing iterations; append\n % check for empty (incomplete) iterations and remove them\n [maxprop, uncor_prop, maxcsize] = remove_incomplete_iterations(maxprop, uncor_prop, maxcsize);\n\n fprintf(1,'MC iterations found: %3.0f. Appending new: %3.0f iterations\\n', length(maxprop.act), iter);\n\n maxprop.act = [maxprop.act; zeros(iter,1)];\n uncor_prop.act = [uncor_prop.act; zeros(iter,3)];\n maxcsize.act = [maxcsize.act; zeros(iter,3)];\n\n if isfield(MC_Setup,'ctxtxi') % do by-conditions also\n\n nconds = size(MC_Setup.ctxtxi,1);\n\n maxprop.poscon = [maxprop.poscon; zeros(iter, nconds)];\n maxprop.negcon = [maxprop.negcon; zeros(iter, nconds)];\n\n for i = 1:nconds\n uncor_prop.poscon{i} = [uncor_prop.poscon{i}; zeros(iter,3)];\n maxcsize.poscon{i} = [maxcsize.poscon{i}; zeros(iter,3)];\n\n uncor_prop.negcon{i} = [uncor_prop.negcon{i}; zeros(iter,3)];\n maxcsize.negcon{i} = [maxcsize.negcon{i}; zeros(iter,3)];\n\n end\n end\n end\n\n startat = find(maxprop.act == 0); startat = startat(1);\nend % setup mc vars\n\n\n\n\n\n% ====================================================================\n% --------------------------------------------------------------------\n%\n% Results subfunctions\n%\n% --------------------------------------------------------------------\n% ====================================================================\n\n\n% SUBFUNCTION:\n% --------------------------------------------------------------------\n% Load some key variables for getting results\n% --------------------------------------------------------------------\nfunction [MC_Setup, statmap, imgprefix, maxprop, uncor_prop, maxcsize, conidx] = setup_results_vars(maptype, conidx)\n\n % should be loaded in file\n % MC_Setup = []; maxprop = []; uncor_prop = []; maxcsize = [];\n\n [MC_Setup, statmap, imgprefix, maxprop, uncor_prop, maxcsize, conidx] = deal([]);\n \n % load file\n % ------------\n if ~exist('MC_Info.mat','file')\n \n error('You must have an MC_Info file in the current dir that contains MC_Setup.');\n \n else\n \n load(fullfile(pwd, 'MC_Info.mat'));\n\n end\n\n % check mc iterations\n % ------------\n if isempty(maxprop)\n % no existing results; error\n fprintf(1,'No MC iterations found in MC_Info. You must create using Meta_Activation_FWE(''mc'',num_iterations)\\n');\n end\n\n % check for empty (incomplete) iterations and remove them\n [maxprop, uncor_prop, maxcsize] = remove_incomplete_iterations(maxprop, uncor_prop, maxcsize);\n\n\n % Set up statistic image data to be thresholded\n % ------------\n switch maptype\n case 'act'\n % overall activation\n % use existing props, or set up empty to read from file\n if ~(exist('activation_proportions', 'var')), activation_proportions = []; end\n % get activation proportions indicator or just check it\n statmap = setup_activation_proportions(activation_proportions, MC_Setup);\n\n imgprefix = 'Activation';\n \n otherwise\n % contrast across conditions\n % statmap = MC_Setup.con_data;\n\n if ~isfield(MC_Setup, 'con_data')\n disp('Warning: You have asked to view contrast results, but there are no contrasts across studies in MC_Setup.');\n error('Exiting');\n return\n end\n \n if(~exist('conidx', 'var') || isempty(conidx))\n num_contrasts = size(MC_Setup.con_data, 2);\n if num_contrasts > 1\n conidx = input(['Choose contrast number (1 thru ' num2str(num_contrasts) '): ']);\n else\n conidx = 1;\n end\n end\n statmap = MC_Setup.con_data(:,conidx);\n\n % check for correct field names\n switch maptype\n case 'poscon'\n imgprefix = [MC_Setup.connames{conidx} '_Pos'];\n case 'negcon'\n % flip sign so thresholding will work the same way\n statmap = -statmap;\n\n imgprefix = [MC_Setup.connames{conidx} '_Neg'];\n otherwise\n error('Unknown maptype: %s - must be ''act'', ''poscon'', or ''negcon''', maptype);\n end\n end\nend % setup_results_vars\n\n% SUBFUNCTION:\n% --------------------------------------------------------------------\n% Check that we have activations loaded, or load them from image\n% --------------------------------------------------------------------\n\nfunction activation_proportions = setup_activation_proportions(activation_proportions, MC_Setup)\n % check/load true meta activations\n % ------------\n if isempty(activation_proportions)\n name = 'Activation_proportion.img';\n str = sprintf('Loading %s', name);fprintf(1,str);\n if ~exist(name,'file')\n error('You must have an Activation_proportion.img file in the current dir, or run ''all'' option to create.');\n end\n\n mask = MC_Setup.volInfo.fname;\n if ~exist(mask,'file')\n error(['Cannot find mask image: ' mask]);\n end\n\n % switch maptype\n % case 'poscon'\n % imgprefix = [MC_Setup.connames(conidx) '_Pos'];\n % case 'negcon'\n % % flip sign so thresholding will work the same way\n % statmap = -statmap; %*****\n %\n % imgprefix = [MC_Setup.connames(conidx) '_Neg'];\n % otherwise\n % error('map type (3rd arg.) must be ''act'', ''poscon'', or ''negcon''');\n % end\n activation_proportions = meta_read_image(name,mask);\n erase_string(str);\n end\n\n % check length\n len = size(MC_Setup.volInfo.xyzlist, 1);\n if len ~= length(activation_proportions)\n error('activation image and results have different numbers of in-analysis voxels. Has the mask image changed??');\n end\nend\n\n% SUBFUNCTION:\n% --------------------------------------------------------------------\n% Get significance thresholds and plot histograms\n% --------------------------------------------------------------------\n\nfunction [maxthr,uncor_thr,maxcthr] = get_thresholds(maxprop, uncor_prop, maxcsize, maptype, doplots, conidx)\n\n % flip signs of thresholds for negative contrast so code will work generically\n % cell only if maptype is poscon or negcon (not act)\n switch(maptype)\n case 'act'\n current_maxprop = maxprop.(maptype);\n current_uncor_prop = uncor_prop.(maptype);\n current_maxcsize = maxcsize.(maptype);\n case 'poscon'\n current_maxprop = maxprop.(maptype)(:,conidx);\n current_uncor_prop = uncor_prop.(maptype){conidx};\n current_maxcsize = maxcsize.(maptype){conidx};\n case 'negcon'\n current_maxprop = -maxprop.(maptype)(:,conidx);\n current_uncor_prop = -uncor_prop.(maptype){conidx};\n current_maxcsize = maxcsize.(maptype){conidx};\n end\n\n maxthr = prctile(current_maxprop, 95);\n uncor_thr = mean(current_uncor_prop);\n maxcthr = prctile(current_maxcsize, 95);\n\n if doplots\n create_figure('densities', 1, 3);\n\n [h,x] = prepare_histogram(current_maxprop);\n\n plot(x,h,'k','LineWidth',2);\n title('Null hypothesis activation proportion');\n yl = get(gca,'YLim');\n plot([maxthr maxthr],yl,'Color',[.5 .5 .5],'LineWidth',2);\n sym = {'--' '.-' ':'};\n\n for i = 1:3\n plot([uncor_thr(i) uncor_thr(i)],yl,sym{i},'Color',[.5 .5 .5],'LineWidth',2);\n end\n legend({'Max whole-brain density' 'p < .05 corrected' 'p < .05' 'p < .01' 'p < .001'});\n drawnow\n\n subplot(1,3,2);\n [h,x] = prepare_histogram(current_maxcsize);\n\n plot(x,h,'LineWidth',2);\n colors = {'b' 'g' 'r'};\n yl = get(gca,'YLim');\n title('Null hypothesis cluster sizes');\n\n for i = 1:3\n plot([maxcthr(i) maxcthr(i)],yl,sym{i},'Color',colors{i},'LineWidth',2);\n end\n legend({'p < .05' 'p < .01' 'p < .001'});\n drawnow\n end\nend\n\n% --------------------------------------------------------------------\n% Plot activation proportions with thresholds\n% --------------------------------------------------------------------\nfunction plot_act_prop(activation_proportions,maxthr,uncor_thr,whomsave)\n\n if nargin < 4, whomsave = [1 1 1]; end % all thresholds\n [h,x] = prepare_histogram(activation_proportions);\n\n plot(x,h,'k','LineWidth',2);\n title('Observed activation proportions');\n yl = get(gca,'YLim');\n plot([maxthr maxthr],yl,'Color',[.5 .5 .5],'LineWidth',2);\n sym = {'--' '.-' ':'};\n\n for i = 1:3\n if whomsave(i)\n plot([uncor_thr(i) uncor_thr(i)],yl,sym{i},'Color',[.5 .5 .5],'LineWidth',2);\n end\n end\n \n legstr = {'Observed proportions' 'p < .05 corrected' 'p < .05' 'p < .01' 'p < .001'};\n legstr = legstr(find([1 1 whomsave]));\n legend(legstr);\n drawnow\n\nend\n\n\n% SUBFUNCTION:\n% --------------------------------------------------------------------\n% Get significant regions based on extent\n% --------------------------------------------------------------------\n\nfunction indic = meta_cluster_extent_threshold(xyzlist,data,thr1,sizethr)\n\n\n norig = size(xyzlist,2);\n indic = zeros(norig,1);\n\n meet_primary = data > thr1;\n wh1 = find(meet_primary); % voxels that do meet primary\n\n\n % consider only vox that meet primary\n wh = find(~meet_primary); % voxels that do not meet primary threshold\n xyzlist(:,wh) = [];\n clear wh\n\n % check size OK\n n = size(xyzlist,2);\n\n if n > Inf %50000 % Bug in SPM has been fixed, Tor removed limitation - 2/2017\n% disp('Too many voxels meet primary threshold. Cannot perform cluster-based thresholding.');\n% return\n elseif n == 0\n disp('Warning! No voxels meet primary threshold; this is unusual...');\n return\n else\n\n % cluster\n clid = spm_clusters(xyzlist);\n end\n\n csize = zeros(norig,1); % in Original (full voxel) index\n\n u = unique(clid);\n for i = 1:length(u)\n wh = find(clid == i); % voxels in this cluster\n csize(wh1(wh)) = length(wh); % put cluster size there; translate to full index\n end\n\n indic = csize > sizethr;\n\n % results display stuff\n sigvox = find(indic);\n\n fprintf(1,'\\nThresh = %3.4f, size threshold = %3.0f: %3.0f sig. voxels.\\n',thr1,sizethr,length(sigvox));\n\n if isempty(sigvox)\n return\n else\n rg = [min(csize(sigvox)) max(csize(sigvox))];\n end\n fprintf(1,'Cluster sizes range from %3.0f to %3.0f\\n\\n', rg(1), rg(2));\n\n\nend\n\n% SUBFUNCTION:\n% --------------------------------------------------------------------\n% Quick way to write a mask image for significant data\n% --------------------------------------------------------------------\n\nfunction indic2mask(indic, activation_proportions, MC_Setup, name)\n disp(['Writing image: ' name])\n wh = find(indic);\n\n data = zeros(size(activation_proportions));\n data(wh) = activation_proportions(wh);\n meta_reconstruct_mask(data, MC_Setup.volInfo.xyzlist, MC_Setup.volInfo.dim(1:3), 1, MC_Setup.volInfo,name);\nend\n\n\n% SUBFUNCTION:\n% --------------------------------------------------------------------\n% Surface plots at multiple thresholds\n% --------------------------------------------------------------------\n\nfunction surfhan = make_surface(typestr,cl,morecl,mydistance,color)\n % NOTE: this is the same as in cluster_surf_batch, except for input\n % type for color\n\n if isempty(typestr), typestr = mydistance; end % kludgy fix to avoid error on empty input\n\n surfhan = []; %cluster_surf(cl,mydistance,color{1});\n for i = length(morecl):-1:1\n if i == length(morecl)\n surfhan = cluster_surf(surfhan,morecl{i},mydistance,{color(i+1,:)},typestr);\n else\n cluster_surf(surfhan,morecl{i},mydistance,{color(i+1,:)});\n end\n %surfhan = [surfhan sh];\n end\n\n surfhan = cluster_surf(surfhan,cl,mydistance,{color(1,:)}, typestr);\n %surfhan = [surfhan sh];\n\nend\n\n\n% ====================================================================\n% --------------------------------------------------------------------\n%\n% Other utility functions\n%\n% --------------------------------------------------------------------\n% ====================================================================\n\nfunction erase_string(str)\n fprintf(1,repmat('\\b',1,length(str))); % erase string\n %fprintf(1,'\\n');\nend\n\n\nfunction h = makeColumn(h)\n if length(h) > size(h,1) && size(h,1)==1, h = h'; end\nend\n\n\n% SUBFUNCTION:\nfunction [h,x,nbins] = prepare_histogram(data)\n\n nbins = min(length(data)./5,100);\n\n [h,x] = hist(data,nbins);\n\n % pad to make nice display\n if length(x)>1, firstx = 2*x(1) - x(2); else firstx = 0; end\n lastx = 2*x(end) - x(end-1);\n\n % make column\n h = makeColumn(h);\n x = makeColumn(x);\n\n z = zeros(1,size(h,2));\n\n h = [z;h;z]; x = [firstx;x;lastx];\n\n h = h ./ repmat(sum(h),size(h,1),1);\n\nend\n\n\n\n% SUBFUNCTION:\nfunction DB = meta_check_dbsetup(DB)\n % runs Meta_Setup if necessary\n\n % needs to set up design:\n %DB.(fields) % lists of fields containing task conditions for each coordinate point\n %DB.pointind % indices of which coord points are in which unique\n % contrast\n %DB.x % x coordinates, just to get # of points\n % DB.maskname\n % DB.radius\n % DB.Contrast (study ID number; contrast within study)\n % DB.x, DB.y DB.z\n % DB.studyweight\n\n if isempty(DB), error('No DB structure! Create by reading from text file using read_database.m or create manually.'); end\n\n DBfields = fieldnames(DB);\n reqfields = {'maskname' 'radius' 'Contrast' 'x' 'y' 'z' 'studyweight' 'pointind'};\n\n for i = 1:length(reqfields)\n field_exists(i) = any(~(cellfun(@isempty, strfind(DBfields, 'maskname'))));\n if ~field_exists(i), fprintf(1,'DB.%s does not exist yet.\\n', reqfields{i}); end\n end\n\n if ~all(field_exists)\n fprintf(1,'Running Meta_Setup to set up DB structure.\\n');\n DB = Meta_Setup(DB);\n end\n\nend\n\n\n% SUBFUNCTION:\nfunction [maxprop, uncor_prop, maxcsize] = remove_incomplete_iterations(maxprop, uncor_prop, maxcsize)\n %\n % check for empty (incomplete) iterations and remove them\n if any(maxprop.act == 0)\n wh = find(sum(maxprop.act,2) == 0); % empty iterations\n fprintf(1,'Warning! %3.0f Empty iteration results: Removing from all iteration variables.\\n',length(wh));\n maxprop.act(wh) = [];\n uncor_prop.act(wh,:) = [];\n maxcsize.act(wh,:) = [];\n\n if isfield(uncor_prop,'poscon') % do by-conditions also\n\n nconds = size(maxprop.poscon,2);\n\n maxprop.poscon(wh,:) = [];\n maxprop.negcon(wh,:) = [];\n\n for i = 1:nconds\n wh = find(sum(uncor_prop.poscon{i},2) == 0); % empty iterations\n % do separately because of potential for mismatch between\n % poscon and act\n uncor_prop.poscon{i}(wh,:) = [];\n maxcsize.poscon{i}(wh,:) = [];\n\n wh = find(sum(uncor_prop.negcon{i},2) == 0); % empty iterations\n uncor_prop.negcon{i}(wh,:) = [];\n maxcsize.negcon{i}(wh,:) = [];\n end\n end\n end\n\nend\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_cluster_tools.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_cluster_tools.m", "size": 16271, "source_encoding": "utf_8", "md5": "e048c639895cb328e19867acf729fa67", "text": "function varargout = Meta_cluster_tools(meth,varargin)\n% varargout = Meta_cluster_tools(meth,varargin)\n%\n% This function contains multiple tools for working with clusters\n% derived from Meta_Activation_FWE and Meta_SOM tools\n%\n%\n% ------------------------------------------------------\n% extract data and print a table for a set of meta-analysis clusters\n%\n% cl = Meta_cluster_tools('make_table', cl, MC_Setup, ['plot'],['successive'])\n%\n% Example:\n% load Valence_Neg-Pos_Pos_clusters; load MC_Info\n%\n% cl1 = Meta_cluster_tools('make_table',cl{1},MC_Setup);\n% cl = Meta_cluster_tools('make_table', cl, MC_Setup, 'successive');\n%\n% ------------------------------------------------------\n%\n% Print tables of which contrasts in DB database activate within clusters\n% with full contrast/database information:\n% Meta_cluster_tools('activation_table', DB, MC_Setup, cl, [testfield1], [testfield2]);\n% Meta_cluster_tools('activation_table', DB, MC_Setup, cl(1), 'Modality2', 'PosNeg');\n%\n% DB should be database, after Meta_Setup.m has been run.\n% MC_Setup should be structure from Meta_Activation_FWE.m with setup info\n% cl is clusters structure of results, e.g., from chi-square, etc.\n% testfield1 and 2 are optional names of fields to calculate percentage\n% activation for\n% a contingency table is made if two fields are entered.\n%\n% ------------------------------------------------------\n% get data for studies within rois\n% studybyroi is studies activating in each cluster in cl. operator is \"any\" voxel in cluster counts\n% [studybyroi,studybyset] = Meta_cluster_tools('getdata',cl,dat,[volInfo])\n% [studybyroi,studybyset] = Meta_cluster_tools('getdata',cl,MC_Setup.unweighted_study_data,MC_Setup.volInfo)\n% ------------------------------------------------------\n%\n% ------------------------------------------------------\n% count studies by condition and plot [optional]\n%\n% [prop_by_condition,se,num_by_condition,n, table_obj] = Meta_cluster_tools('count_by_condition',dat,Xi,w,doplot,[xnames],[seriesnames], [colors])\n%\n% [prop_by_condition,se,num_by_condition,n, table_obj] = Meta_cluster_tools('count_by_condition',studybyset,MC_Setup.Xi,MC_Setup.wts,1)\n%\n% [prop_by_condition,se,num_by_condition,n, table_obj] = ...\n% Meta_cluster_tools('count_by_condition',studybyroi,MC_Setup.Xi,MC_Setup.wts,1, ...\n% {'Right' 'Left'},MC_Setup.connames(1:5),{[1 0 0] [0 1 0] [1 0 1] [1 1 0] [0 0 1]});\n%\n% Xi = SOMResults.Xi(:,9:13);\n% nms = SOMResults.alltasknms(9:13)\n% w = SOMResults.w;\n% colors = {[1 0 0] [0 1 0] [1 0 1] [1 1 0] [0 0 1]};\n% [prop_by_condition,se,num_by_condition,n, table_obj] = ...\n% Meta_cluster_tools('count_by_condition',studybyroi,Xi,w,1, ...\n% {'Right' 'Left'},nms,colors);\n%\n% ------------------------------------------------------\n%\n% Example:\n% ------------------------------------------------------\n% Run an analysis with Meta_Chisq_new, and then use these tools to get\n% plots of regions. The lines below run the entire analysis.\n% R = Meta_Chisq_new('compute',MC_Setup,'mask',mask);\n% R = Meta_Chisq_new('write',R);\n% [studybyroi,studybyset] = Meta_cluster_tools('getdata',cl,R.dat,R.volInfo);\n% [prop_by_condition,se,num_by_condition,n, table_obj] = Meta_cluster_tools('count_by_condition',studybyset,R.Xi,R.w,1);\n% ------------------------------------------------------\n\nswitch meth\n \n case 'make_table'\n \n % cl = make_table(cl,MC_Setup,[doplot],[successiveflag])\n %\n doplot = 0; dosuccessive = 0;\n if any(strcmp(varargin,'successive')), dosuccessive = 1; end\n if any(strcmp(varargin,'plot')), doplot = 1; end\n \n varargout{1} = make_table(varargin{1},varargin{2},doplot,dosuccessive);\n \n case 'getdata'\n \n %[studybyroi,studybyset] = Meta_cluster_tools('getdata',cl,MC_Setup.unweighted_study_data)\n %[studybyroi,studybyset] = getdata(cl,inputdata)\n \n if length(varargin) < 3\n [varargout{1},varargout{2},varargout{3}] = getdata(varargin{1},varargin{2});\n else\n [varargout{1},varargout{2},varargout{3}] = getdata(varargin{1},varargin{2},varargin{3});\n end\n \n case 'count_by_condition'\n %[prop_by_condition,se,num_by_condition,n, table_obj] = Meta_cluster_tools('count_by_condition',dat,Xi,w,doplot,[regionnames],[seriesnames], [colors])\n %[prop_by_condition,se,num_by_condition,n, table_obj] = count_by_condition(dat,Xi,w,doplot)\n \n if length(varargin) < 4, varargin{4} = 0; end\n if length(varargin) < 5, varargin{5} = []; end\n if length(varargin) < 6, varargin{6} = []; end\n if length(varargin) < 7, varargin{7} = []; end %colors\n [varargout{1},varargout{2},varargout{3},varargout{4}, varargout{5}] = count_by_condition(varargin{1},varargin{2},varargin{3},varargin{4},varargin{5},varargin{6},varargin{7});\n \n \n case 'activation_table'\n activation_table(varargin{:});\n \n otherwise\n disp('unknown method string. doing nothing.');\n \nend\n\n\nend\n\n\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n% Get data within rois\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n\nfunction cl = make_table(cl, MC_Setup, doplot, dosuccessive)\n\n% uses Xi and Xinms to get differences among conditions\n% if there is no Xi field, we don't have differences among\n% conditions, so create a dummy one to get overall proportion\n\nif ~isfield(MC_Setup,'Xi')\n MC_Setup.Xi = ones(size(MC_Setup.wts));\n MC_Setup.Xinms = {'Act'};\nend\n\nif dosuccessive\n for i = 1:length(cl)\n disp(['Cluster cell ' num2str(i)])\n cl{i} = get_props_subfcn(cl{i},MC_Setup,doplot);\n end\nelse\n cl = get_props_subfcn(cl,MC_Setup,doplot);\nend\n\n\n% build table function call\nif dosuccessive\n estr = 'cl = cluster_table_successive_threshold(cl,5';\nelse\n estr = 'cluster_table(cl,1,0';\nend\n\nfnames = MC_Setup.Xinms;\nfor i = 1:length(fnames), fnames{i} = [fnames{i} '_prop']; end\nnconds = length(fnames);\n\nfor i = 1:nconds\n estr = [estr ',''' fnames{i} ''''];\nend\nestr = [estr ');'];\n\n% run table\neval(estr)\n\nend\n\n% dependent on above:\nfunction cl = get_props_subfcn(cl,MC_Setup,doplot)\ndisp(['getting clusters for local maxima at least 10 mm apart']);\ncl = subclusters_from_local_max(cl,10);\ncl = merge_nearby_clusters(cl,10,'recursive');\n\n% get proportion of points activating in each condition in each region\ndisp('Getting studies that activated in each region.')\n[studybyroi,studybyset] = Meta_cluster_tools('getdata',cl,MC_Setup.unweighted_study_data,MC_Setup.volInfo);\n\ndisp('Counting studies by condition')\n[prop_by_condition,se,num_by_condition,n, table_obj] = Meta_cluster_tools('count_by_condition',studybyroi,MC_Setup.Xi,MC_Setup.wts,doplot);\n\n% get field names for conditions\nfnames = MC_Setup.Xinms;\nfor i = 1:length(fnames), fnames{i} = [fnames{i} '_prop']; end\nnconds = length(fnames);\n\nfprintf(1,'Adding field to cl: %s\\n',fnames{:});\n\n% store proportions in clusters for table printout and posterity\nfor i = 1:length(cl)\n for j = 1:nconds\n cl(i).(fnames{j}) = 100 * prop_by_condition(i,j);\n end\nend\n\nend\n\n\nfunction [studybyroi,studybyset, cl] = getdata(cl,inputdata,varargin)\n\nif isa(cl, 'region')\n % If region, convert to clusters structure so we can add ad hoc fields\n cl = region2struct(cl);\nend\n\nif length(varargin) > 0\n volInfo = varargin{1};\n %maskname = volInfo.fname;\nelse\n disp('Using default mask. if your data has a different set of voxels, enter volInfo as input.')\n maskname = which('scalped_avg152T1_graymatter_smoothed.img');\n volInfo = iimg_read_img(maskname);\nend\n\nn_inmask_in = size(inputdata, 1);\nif n_inmask_in ~= volInfo.n_inmask\n fprintf('*****************************\\nWARNING\\n*****************************\\n')\n fprintf('Voxels in input data set: %3.0f\\nVoxels in volInfo: %3.0f\\n', n_inmask_in, volInfo.n_inmask);\n fprintf('These must match!\\n*****************************\\n');\nend\n\nnrois = length(cl);\nnstudies = size(inputdata,2);\n\nstudybyroi = false(nstudies,nrois);\n\nfor i = 1:nrois\n [imgvec,maskvec] = iimg_clusters2indx(cl(i),volInfo); %maskname);\n \n dat = inputdata(maskvec,:);\n \n cl(i).Z = sum(full(dat'));\n cl(i).Z_descrip = 'Unweighted sum of activating studies';\n \n studybyroi(:, i) = any(dat,1)';\n \n cl(i).activating_comparisons = studybyroi(:, i);\n \nend\n\n[imgvec,maskvec] = iimg_clusters2indx(cl,volInfo); %maskname);\ndat = inputdata(maskvec,:);\nstudybyset = full(any(dat)');\n\nstudybyroi = full(studybyroi);\n\nend\n\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n% Count studies in each region by condition and plot if asked for\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\nfunction [prop_by_condition,se,num_by_condition,n, table_obj] = count_by_condition(dat,Xi,w,doplot,varargin)\n\nif nargin < 4, doplot = 0; end\n\n[nstudies,ntasks] = size(Xi);\nif size(dat,1) ~= nstudies, dat = dat'; end\nif size(dat,1) ~= nstudies, error('data size does not match Xi'); end\nnregions = size(dat,2);\n\n% get stats for the entire matrix of SOMs\n[icon,ctxtxi,betas,num_by_condition,prop_by_condition] = meta_apply_contrast(dat', ...\n Xi,w,ones(1,ntasks));\n\nn = sum(Xi);\nn = repmat(n,nregions,1);\nse = ( (prop_by_condition .* (1-prop_by_condition) ) ./ n ).^.5;\n\nif doplot\n \n xnames = repmat({'Region'}, 1, size(prop_by_condition, 1));\n seriesnames = repmat({'Cond'}, 1, size(prop_by_condition, 2));\n mycolors = scn_standard_colors(size(prop_by_condition, 2));\n \n if length(varargin) > 0 && ~isempty(varargin{1}), xnames = varargin{1}; end\n if length(varargin) > 1 && ~isempty(varargin{2}), seriesnames = varargin{2}; end\n if length(varargin) > 2 && ~isempty(varargin{3}), mycolors = varargin{3}; end\n \n create_figure('barplot');\n fprintf('Sample size is %3.0f\\n', size(Xi, 1));\n \n barplot_grouped(prop_by_condition, se, xnames, seriesnames, 'inputmeans', 'colors', mycolors);\n \n ylabel('Proportion of studies activating');\n \nend\n\n% Table of contrast data\ntable_obj = table();\n \npropdat = mat2cell(prop_by_condition, size(prop_by_condition, 1), ones(1, length(seriesnames)));\nsedat = mat2cell(se, size(prop_by_condition, 1), ones(1, length(seriesnames)));\n\nsenames = cellfun(@(x) ['SE_' x], seriesnames, 'UniformOutput', false);\ntable_obj = table(xnames', propdat{:}, sedat{:}, 'Variablenames', [{'Region'} seriesnames senames]);\n\nend\n\n\n\n\n\n\n\n\nfunction activation_table(DB, MC_Setup, cl, testfield, testfield2)\n% Table header\n\n%cl = database2clusters(DB, cl, DB.radius_mm);\n\n% Get list of activating studies\n[studybyroi, studybyset] = Meta_cluster_tools('getdata', cl, MC_Setup.unweighted_study_data,MC_Setup.volInfo);\n\n% Get which fields are valid to use\nN = fieldnames(DB);\n\nfor i = 1:length(N)\n if length(size(DB.(N{i}))) == 2 && all(size(DB.(N{i})) == size(DB.x))\n include(i, 1) = true;\n else\n include(i, 1) = false;\n end\nend\n\nN = N(include);\nmyz = '=======================================================';\n\nfor r = 1:length(cl)\n \n if ~isfield(cl(r), 'shorttitle') || isempty(cl(r).shorttitle)\n cl(r).shorttitle = sprintf('%3.0f', r);\n end\n \n fprintf('%s\\nRegion %s\\n%s\\n%s\\n', myz, cl(r).shorttitle, cl(r).title, myz);\n \n % Header\n for f = 1:length(N)\n fprintf('%s\\t', N{f});\n end\n fprintf('\\n');\n \n whcons = DB.pointind(logical(studybyroi(:, 1)));\n n = length(whcons);\n \n for s = 1:n\n \n for f = 1:length(N)\n \n myval = DB.(N{f})(whcons(s));\n \n if iscell(myval)\n fprintf('%s\\t', myval{1});\n elseif myval == round(myval)\n fprintf('%3.0f\\t', myval);\n else\n fprintf('%3.2f\\t', myval);\n end\n \n % % save data for contingencies\n % if iscell(myval)\n % mydata{s, f} = myval{1};\n % else\n % mydata{s, f} = myval;\n % end\n \n end % f = field\n \n fprintf('\\n');\n \n end % s = study/contrast\n \n fprintf('\\n_________________________________________________________\\n');\n \n \n % now contingency table if we have it\n if exist('testfield', 'var')\n \n mydata = DB.(testfield)(DB.pointind);\n names = unique(mydata');\n \n actcons = logical(studybyroi(:, 1));\n \n fprintf('%s\\t%s\\t%s\\t%s\\n', 'Condition', 'Total Cons', 'ACtive Cons', '% Active');\n \n for c = 1:length(names)\n mytotal = sum(strcmp(mydata, names{c}));\n myactive = sum(strcmp(mydata(actcons), names{c}));\n \n fprintf('%s\\t%3.0f\\t%3.0f\\t%3.0f%%\\n', names{c}, mytotal, myactive, 100*myactive/mytotal);\n \n end\n \n end\n \n if exist('testfield2', 'var')\n \n fprintf('\\n');\n \n mydata = DB.(testfield2)(DB.pointind);\n names = unique(mydata');\n \n actcons = logical(studybyroi(:, 1));\n \n fprintf('%s\\t%s\\t%s\\t%s\\n', 'Condition', 'Total Cons', 'Active Cons', '% Active');\n \n for c = 1:length(names)\n mytotal = sum(strcmp(mydata, names{c}));\n myactive = sum(strcmp(mydata(actcons), names{c}));\n \n fprintf('%s\\t%3.0f\\t%3.0f\\t%3.0f%%\\n', names{c}, mytotal, myactive, 100*myactive/mytotal);\n \n end\n \n \n % two-way table of percentages\n fprintf('\\nContingency table of proportions of activating studies in combined categories\\n');\n \n mydata = DB.(testfield)(DB.pointind);\n \n mydata2 = DB.(testfield2)(DB.pointind);\n \n [indx, names] = string2indicator(mydata);\n [indx2, names2] = string2indicator(mydata2);\n mytotal = indx' * indx2; % total contrasts in each combo\n \n clear indx\n for j = 1:length(names)\n indx(:, j) = double(strcmp(mydata(actcons), names{j}));\n end\n \n clear indx2\n for j = 1:length(names2)\n indx2(:, j) = double(strcmp(mydata2(actcons), names2{j}));\n end\n \n myactive = indx' * indx2; % total activating contrasts in each combo\n \n myperc = myactive ./ mytotal;\n \n print_matrix(myperc, names2, names)\n \n \n create_figure('contingency');\n imagesc(100 .* myperc)\n colorbar\n cm = colormap_tor([.3 0 .7], [1 1 0]);\n colormap(cm)\n title('Percentage of studies activating by category');\n set(gca, 'XTick', 1:length(names2), 'XTickLabel', names2);\n set(gca, 'YTick', 1:length(names), 'YTickLabel', names);\n snapnow\n \n end\n \n \n \nend % r = cl\n\nend % function\n\n\n\n\n\nfunction [N,con,testfield] = check_fields(DB,testfield)\nif isfield(DB,'N'), N = DB.N;, elseif isfield(DB,'Subjects'), N = DB.Subjects; else, N = NaN*zeros(size(DB.x));, end\nif isfield(DB,'Contrast'), con = DB.Contrast;,\nelse, con = NaN*zeros(size(DB.x));,\n disp('Warning! You must have a field called DB.Contrasts for the table function to work properly.');\nend\n\nif ~isfield(DB,'connumbers'),\n error('No DB.connumbers field, which is required. See Meta_Setup to create this field and set up analysis.');\nend\n\n% Define testfield (field to display in table)\nif isempty(testfield), try load SETUP testfield, catch, testfield = input('Cannot load testfield from SETUP. Type name of field in DB to display: ','s'), go = 1;, end, end\n\nif isempty(testfield), testfield = input('Cannot load testfield from SETUP. Type name of field in DB to display: ','s'), go = 1;, end,\n\nwhile ~isfield(DB,testfield), disp(['NO field called ' testfield]);\n disp(DB), testfield = input('Type field name: ','s');\nend\nend\n\n\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Study_Table.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Study_Table.m", "size": 5017, "source_encoding": "utf_8", "md5": "28b9f8f7d50425980d19eeaa29bd031f", "text": "function Meta_Study_Table(DB,varargin)\n% function Meta_Study_Table(DB,['study'])\n%\n% Prints text table of all independent contrasts for export\n%\n% looks for Study or study field in DB (also takes clusters, cl)\n% determines length, and looks for other fields of the same length\n% uses specified fields in a particular order, then other fields\n%\n% Similar to dbcluster point table, but prints one row per contrast\n\ndostudy = 0;\nfor i = 1:length(varargin)\n if isstr(varargin{i})\n switch varargin{i}\n \n % functional commands\n case 'study', dostudy = 1;\n \n otherwise, warning(['Unknown input string option:' varargin{i}]);\n end\n end\nend\n\nN = fieldnames(DB(1));\n\n% reorder field names - reverse order, bottom rows are top of list\n\nwh = find(strcmp(N,'alltask')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N]; end\nwh = find(strcmp(N,'Subjects')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N]; end\nwh = find(strcmp(N,'t_Value')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N]; end\nwh = find(strcmp(N,'Zscore')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N]; end\nwh = find(strcmp(N,'Z')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N]; end\n%wh = find(strcmp(N,'distance')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N]; end\n%wh = find(strcmp(N,'z')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N]; end\n%wh = find(strcmp(N,'y')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N]; end\n%wh = find(strcmp(N,'x')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N]; end\n\n% these variables are created in this script from study or Study and are\n% the first two\nN = ['year'; N];\nN = ['Studynames'; N];\n\n\nif ~isfield(DB,'pointind')\n disp('You need DB.pointind field. Try Meta_Setup first')\n return; \nend\n \n% DB can be clusters or single-element structure. DO for each element\n% (structure)\nfor i = 1:length(DB)\n \n % setup: get names and years with nice formatting\n % -----------------------------------------------\n wh = find(strcmp(N,'Study')); if ~isempty(wh), Studynames = DB(i).Study; end %tmp = N(wh);N(wh) = []; N = [tmp;N]; end\n wh = find(strcmp(N,'study')); if ~isempty(wh), Studynames = DB(i).study; end %tmp = N(wh);N(wh) = []; N = [tmp;N]; end\n L = length(Studynames);\n DB.Studynames = cell(L,1);\n DB.year = cell(L,1);\n \n % print coordinates for DB or cluster\n % -----------------------------------------------\n if isfield(DB,'mm_center')\n % this is a clusters struct, print center\n fprintf(1,'Coordinate: %3.0f %3.0f %3.0f\\n',DB(i).mm_center(1), DB(i).mm_center(2),DB(i).mm_center(3));\n end\n \n if isfield(DB,'Study'),study = DB(i).Study; L = length(DB(i).Study); end\n if isfield(DB,'study'),study = DB(i).Study; L = length(DB(i).Study); end\n \n if ~(exist('L')==1), disp('No Study or study variable in DB.'), return; end\n \n % print header\n % -----------------------------------------------\n for k = 1:length(N)\n \n % figure out if this field is the right length\n eval(['x = DB(i).' N{k} ';']);\n go = 0;\n if iscell(x), if length(x) == L, go = 1; tmp = x{i}; end \n elseif size(x,1) == L, go = 1; tmp = x(i,1);\n end\n \n % print, if it is\n if go\n print_f(N,k,length(N));\n end\n end\n fprintf(1,'\\n')\n \n % get indices of rows: contrasts or studies\n % -----------------------------------------------\n if dostudy\n [tmp,DB.studyind] = unique(DB.Study);\n myfield = 'studyind';\n else\n myfield = 'pointind';\n end\n \n % print body rows\n % -----------------------------------------------\n conindx = DB.(myfield);\n if size(conindx,1) ~= 1, conindx = conindx'; end\n \n for j = conindx\n\n % get name and year with nice formatting\n [DB(i).Studynames{j},DB(i).year{j}] = sep_name_year(Studynames{j});\n \n for k = 1:length(N)\n eval(['tmp = DB(i).' N{k} ';'])\n print_f(tmp,j,L);\n end\n fprintf(1,'\\n')\n end\n fprintf(1,'\\n')\n \nend\n\n\n\n\nfunction print_f(x,i,L)\n\ngo = 0;\nif iscell(x), if length(x) == L, go = 1; tmp = x{i}; end\nelseif size(x,1) == L, go = 1; tmp = x(i,1);\nend\n\nif go\n \n if ~isstr(tmp), tmp = sprintf('%3.2f',tmp); end\n \n fprintf(1,'%s\\t',tmp);\nend\n\nreturn\n\n\n\n\nfunction [study,yr] = sep_name_year(studyname)\n \n yr = 'missing'; \n study = studyname;\n [nums,whnums] = nums_from_text(studyname);\n if isnan(nums), return, end\n \n yr = nums(1);\n \n study = studyname;\n study(whnums) = [];\n \n if isempty(study) %% all numbers? assume not year...\n yr = 0;\n else\n % capitalize and format\n study(1) = upper(study(1));\n end\n \n if yr < 1900\n if yr > 80 && yr <= 99\n yr = yr + 1900;\n elseif yr < 20\n yr = yr + 2000;\n end\n end\n \n yr = sprintf('%04d',yr);\n \n\n return\n "} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Logistic_Design.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Logistic_Design.m", "size": 10343, "source_encoding": "utf_8", "md5": "2aa4e4681ab54e540c9b11f0e93cf967", "text": "function [X,Xnms,DB,Xi,alltasknms,condf,testfield,conweights] = Meta_Logistic_Design(DB,varargin)\n% [X,Xnms,DB,Xi,Xinms,condf,testfield,conweights] = Meta_Logistic_Design(DB,[control strings])\n%\n% Set up logistic regression design matrix from DB\n%\n% needs to set up design:\n%DB.(fields) % lists of fields containing task conditions for each coordinate point\n%DB.pointind % indices of which coord points are in which unique\n% contrast\n%DB.x % x coordinates, just to get # of points\n%\n% Optional 'control strings'\n% {'empty'} : to specify empty contrasts for each condition\n%\n% Outputs:\n% X, design matrix\n% Xnms, names\n% DB, database, \n% ... modified weights (w) to reflect new contrasts included\n% ... added fields to mark included points and contrasts in original list\n% Xi, indicator matrix of which contrasts are in which conditions in the\n% analysis\n% Xinms, names if Xi\n%\n% tor wager\n% Modified: 1/22/06\n\nglobal dolist\ndolist = 1;\ndoempty = 0;\n\nif length(varargin) > 0,\n controlflags = varargin{1};\n for i = 1:length(controlflags)\n if strcmp(controlflags{i},'empty'), doempty = 1; end\n end\nend\n\n% -----------------------------------------------------\n% Select conditions and build design matrix\n% -----------------------------------------------------\n\ntestfield = 'xxx';\nX = []; Xnms = {}; allti = []; alltasknms = [];\n\nwhile ~isempty(testfield)\n \n % get field name and save for later display (image)\n testfield = getfield(DB); \n \n if isempty(testfield), \n % done\n else\n \n testfield1 = testfield;\n \n % check to see if each contrast has only one level\n meta_check_contrasts(DB,testfield)\n \n % get unique levels\n levels = getlevels(DB,testfield);\n\n % get indicators for these levels\n [ti,tasknms] = string2indicator(DB.(testfield),levels);\n\n % get contrast coded regressors (getcontrast subfunction is\n % replaced by meta_enter_contrasts)\n [con,conname,contype,conweights] = meta_enter_contrasts(ti,tasknms);\n\n % plot image of contrasts\n meta_plot_contrasts(DB,testfield,levels);\n title('Before database pruning');\n \n for i = 1:length(conname), conname{i} = [testfield '_' conname{i}]; end\n \n allti = [allti ti];\n alltasknms = [alltasknms tasknms];\n \n X = [X con];\n Xnms = [Xnms conname];\n end\n \nend\nfprintf(1,'\\n'); fprintf(1,'\\n');\n\n% -----------------------------------------------------\n% Prune database based on in-analysis points (contrasts)\n% -----------------------------------------------------\n\n% get only unique contrast entries\ninclude = sum(allti,2);\n%inc_con = include(DB.pointind);\n\n\n%DB = prune(DB,include,inc_con); % makes new pointind; this excludes\n%point-wise\n\nDB = Meta_Prune(DB,include); % this excludes contrast-wise\n\nmeta_plot_contrasts(DB,testfield1,levels);\ntitle('After pruning (valid contrasts)');\n \n% -----------------------------------------------------\n% Prune design matrix\n% -----------------------------------------------------\nXpts = X; % original\n\n% get rid of excluded points based on incomplete/multi-level contrasts\nX = X(find(DB.included_from_original),:);\n\n% select unique contrasts\nX = X(DB.pointind,:);\n\n \n% prune indicator matrix\nXi = allti;\nXi = Xi(find(DB.included_from_original),:);\n\n% select unique contrasts\nXi = Xi(DB.pointind,:);\n\n% add empty contrasts if specified\nif doempty\n if strcmp(contype,'contrast')\n X = add_empty_cons(X,Xnms);\n elseif strcmp(contype,'dummy')\n Xi = add_empty_cons(Xi,alltasknms);\n end\nend\n\n% image design matrix\n tor_fig(1,2); s = get(0,'ScreenSize'); set(gcf,'Position',[s(3).*.5 s(4).*.5 600 600]); \n tmp = X; set(gca,'YDir','Reverse');\n imagesc(tmp); colormap gray; title('Design matrix'); ylabel('Contrast'); xlabel('Regressors') \n subplot(1,2,2); tmp = Xi; \n set(gca,'YDir','Reverse');\n imagesc(tmp); colormap gray; title('Indicators'); ylabel('Contrast'); xlabel('Regressors') \n drawnow\n \n% end condition function (dummy codes) for chi-square test\n[i,j] = find(Xi);\n[i,s] = sort(i); \ncondf = j(s);\n\n% -----------------------------------------------------\n% Re-do Final contrast weights\n% -----------------------------------------------------\n\nif isfield(DB,'SubjectiveWeights'),\n w = DB.rootn .* DB.SubjectiveWeights(DB.pointind);\nelse\n w = DB.rootn;\nend\n\n% if we have empty contrasts\n% if empty images specified, ncontrasts will be greater than nimgs\nif doempty\n addtow = zeros(size(Xi,1) - length(w),1);\n w = [w; addtow];\nend\n\n% these must sum to 1 ! (they will be re-normed in Meta_Logistic, but\n% summing to 1 is the standard weighting used in other parts of the\n% software.)\nDB.studyweight = w ./ sum(w);\n\n\n\ndiary DESIGN_REPORT.txt\n\nfprintf(1,'\\nDesign Reporting\\n---------------------------\\nRegressors:\\n')\nfor i = 1:length(Xnms), fprintf(1,'%3.0f\\t%s\\t%3.0f Contrasts (rows)\\n',i,Xnms{i},sum(X(:,i)));end\n\nempty = length(find(~sum(X,2)));\nfprintf(1,'Intercept: %3.0f Contrast (sum of rows)\\n',empty);\n\nc = cond(X);\nfprintf(1,'\\nOrthogonality: \\n\\nCondition number (1 is good, higher is worse): %3.2f\\n', c);\n\nfprintf(1,'\\nDependence (X''X) Matrix\\n');\ntry\n print_matrix(X'*X,Xnms);\ncatch\nend\nfprintf(1,'\\n')\n\ndiary off\n\n\nend\n\n\n\n\n\nfunction testfield = getfield(DB)\n% Empty or field name from DB\nglobal dolist\n\n% list field names\nfprintf(1,'Database field names\\n---------------------------\\n')\nN = fieldnames(DB);\nif dolist\n for i = 1:length(N),\n tmp = DB.(N{i}); len = length(tmp);\n if len == length(DB.x), fprintf(1,'%s\\n',N{i});end\n end\n\n fprintf(1,'\\n');\n dolist = 0;\nend\n\ngook = [];\nwhile isempty(gook)\n testfield = input('Enter field name or end if finished: ','s');\n\n if isempty(testfield),\n gook = 1;\n else\n gook = strmatch(testfield,N);\n end\n if isempty(gook), fprintf(1,'Not a field name.'); pause(1); fprintf('\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b'); end\nend\n\nend\n\n\n\n\n\nfunction levels = getlevels(DB,testfield);\n\neval(['levels = DB.' testfield ';']);\nlevels = levels(DB.pointind);\n[pts,ind] = unique(levels);\n\nfprintf(1,'Unique values of this variable:\\n');\n\nfor i = 1:size(pts,1), \n [num] = meta_count_contrasts(DB,testfield,pts{i});\n fprintf(1,'%3.0f\\t%s\\t%3.0f Contrasts\\n',i,pts{i},num);\nend\nwh = input('Enter vector of levels to use: ');\nlevels = pts(wh);\n\nend\n\n\n\n\n\n\n%function [con,conname,type] = getcontrasts(ti,tasknms)\n\n\n% type = 'contrast';\n% \n% if size(ti,2) == 1\n% % simple predictor\n% con = ti(:,1);\n% conname = tasknms(1);\n% elseif size(ti,2) == 2\n% % 2 levels, simple contrast\n% con = ti(:,1) - ti(:,2);\n% conname = {[tasknms{2} '-' tasknms{1}]};\n% elseif size(ti,2) > 2\n% \n% if size(ti,2) == 3\n% type = input('Enter coding type: contrast vs. dummy:','s');\n% else\n% type = 'dummy';\n% end\n% \n% switch type\n% case 'contrast'\n% c = [1 -2 1; 1 1 -2]';\n% con = ti * c;\n% conname = {[tasknms{1} '+' tasknms{3} '-' tasknms{2}] [tasknms{1} '+' tasknms{2} '-' tasknms{3}]};\n% case 'dummy'\n% con = ti(:,1:end-1);\n% conname = tasknms(1:end-1);\n% \n% %wh = find(ti(:,end)); % unnecessary for dummy coding\n% %con(wh,:) = -1;\n% for i = 1:length(conname),conname{i} = [conname{i} '-' tasknms{end}];end\n% otherwise\n% error('type contrast or dummy!')\n% end\n% else\n% % This should never happen.\n% %h = hadamard(4);\n% %error('only two or three levels allowed until program is expanded.');\n% % just treat this like a set of preds; don't re-parameterize\n% %con = ti(:,1:end-1);\n% %conname = tasknms(1:end-1);\n% %for i = 1:length(conname),conname{i} = [conname{i} '-' tasknms{end}];end\n% end\n% \n\n\nfunction DB = prune(DB,include,inc_con)\n% Empty or field name from DB\n\nN = fieldnames(DB);\nwhp = find(include);\nwhc = find(inc_con);\n\n% special for DB.pointind\n%pind = zeros(size(DB.x)); pind(DB.pointind) = 1;\n%pind = pind(whp);\n\nfor i = 1:length(N),\n \n tmp = DB.(N{i}); len = length(tmp);\n if ismatrix(tmp), len = size(tmp,1);end\n \n if len == length(include), \n DB.(N{i}) = tmp(whp);\n elseif len == length(inc_con), \n if ismatrix(tmp),\n DB.(N{i}) = tmp(whc,:);\n else\n DB.(N{i}) = tmp(whc);\n end\n end\n \nend\n\n%DB.pointind = find(pind)';\n%[DB.connumbers,DB.pointind] = unique(DB.Contrast);\n\n% re-make pointind\nfor i = 1:length(DB.connumbers)\n wh = find(DB.Contrast == DB.connumbers(i));\n DB.pointind(i) = wh(1);\nend\n\nend\n\n\n\n\n\nfunction meta_plot_contrasts(DB,testfield,levels)\n\n % get unique levels\n if isempty(levels), levels = getlevels(DB,testfield); end\n\n % get indicators for these levels\n [ti,tasknms] = string2indicator(DB.(testfield),levels);\n\n\n tor_fig; s = get(0,'ScreenSize'); set(gcf,'Position',[s(3).*.5 s(4).*.5 600 600]); \n tmp = [ti*100 DB.Contrast]; tmp(tmp == 0) = NaN;\n imagesc(tmp); set(gca,'XTick',1:size(tmp,2),'XTickLabel',[tasknms {'Contrast'}]); colormap prism\n cm = colormap(jet(size(tmp,1))); cm = cm(randperm(length(cm))',:);\n cm(1,:) = [1 1 1]; cm(2,:) = [1 0 0];\n colormap(cm); hold on; \n for i = 1:length(DB.Contrast),wh1 = find(DB.Contrast==i); \n if ~isempty(wh1)\n wh1 = wh1(end)+.5; plot([0 size(tmp,2)+.5], [wh1 wh1],'k'); \n end\n end\n set(gca,'YDir','Reverse'); ylabel('Peak Coordinate index');\n\n % print names\n for i = 1:size(ti,2)\n tmp = unique(DB.study(find(ti(:,i))))';\n fprintf(1,'\\nVariable: %s Level: %s %3.0f studies\\n',testfield,tasknms{i},length(tmp))\n fprintf(1,'%s\\t',tmp{:})\n fprintf(1,'\\n');\n end\n \nend\n\n\nfunction Xi = add_empty_cons(Xi,alltasknms)\n[m,k]=size(Xi);\nfor i = 1:k\n n = input(['Enter number of empty contrasts for ' num2str(alltasknms{i}) ': ']);\n z = zeros(n,k); z(:,i) = 1;\n Xi = [Xi; z];\nend\nend\n\n\n\n% ISMATRIX: Returns 1 if the input matrix is 2+ dimensional, 0 if it is a scalar \n% or vector.\n%\n% Usage ismat = ismatrix(X)\n%\n% RE Strauss, 5/19/00\n\nfunction ismat = ismatrix(X)\n [r,c] = size(X);\n if (r>1 && c>1)\n ismat = 1;\n else\n ismat = 0;\n end\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Chisq.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Chisq.m", "size": 10564, "source_encoding": "utf_8", "md5": "615773d81f72496057c6095494e7be4d", "text": "function DB = Meta_Chisq(DB,varargin)\n% DB = Meta_Chisq(DB,[verbose],[mask image name],[control strings])\n% \n% NEEDS:\n%\n% to set up design:\n%DB.(fields) % lists of fields containing task conditions for each coordinate point\n%DB.pointind % indices of which coord points are in which unique\n% contrast\n%DB.X\n%\n% to run analysis:\n% DB.PP % list of contrast image names\n% DB.studyweight % weights\n% 'Activation.img' or a mask input argument (2nd arg).\n%\n% 3rd to nth arguments are optional 'control strings'\n% 'load' : load from SETUP.mat file; do not recreate\n% 'empty' : to specify empty contrasts for each condition\n%\n% Examples:\n% run chi-sq with mask image Activation.img thresholded at 0.05\n% DB = Meta_Chisq(DB,2,.05) \n%\n% To load already-created SETUP.mat and run:\n% DB = Meta_Chisq(DB,2,[],'load')\n% DB = Meta_Chisq(DB,2,'../Disgust/Activation_thresholded.img','load');\n%\n% To run, specifying empty contrasts\n% DB = Meta_Chisq(DB,1,DB.maskname,'empty');\n\nglobal dims\nglobal cols\n\nspm_defaults; defaults.analyze.flip = 0;\ndoload = 0; doempty = 0;\n\ncontrolflags = varargin; % to pass into subfunctions\nif length(varargin) > 0, vb = varargin{1};, else, vb = 1;, end\n% mask is varargin{2}\nif length(varargin) > 2,\n for i = 3:length(varargin)\n if strcmp(varargin{i},'load'), doload = 1;, end\n if strcmp(varargin{i},'empty'), doempty = 1;, end\n end\nend\n\n% ---------------------------------------\n% Set up design matrix\n% names = contrast names, also output image names\n% prunes DB\n% ---------------------------------------\nif doload\n load SETUP\nelse\n [X,names,DB,Xi,Xinms,condf,testfield] = Meta_Logistic_Design(DB,controlflags);\nend\n\ncols = size(X,2);\n\nw = DB.studyweight;\nw = w ./ mean(w); \n% weights should be mean 1 for logistic regression\n% also preserve relative weighting\n\nDB.X = X; DB.Xnames = names;\n \n% Save names of contrast images to use\nDB.PP = check_valid_imagename(DB.PP);\n\ncontrast_images_used = DB.PP;\n\nif ~doload\n save SETUP contrast_images_used X names DB w Xi Xinms condf testfield\nend\n\n% ---------------------------------------\n% Set up images\n% ---------------------------------------\n\n% image dimensions, etc.\nV = spm_vol(DB.PP(1,:));\nVall = spm_vol(DB.PP);\n\ndims = V.dim(1:3);\n\nif vb > 0, fprintf(1,'\\nNew image dims: %3.0f %3.0f %3.0f %3.0f ',dims(1), dims(2), dims(3), cols),end\n\n\n% ---------------------------------------\n% brain masking\n% e.g., could mask with overall activation image\n% ---------------------------------------\n\nmask = []; \nif length(varargin) > 1, \n mask = varargin{2};, \n if isstr(mask), Vm = spm_vol(mask);, \n if vb > 0, fprintf(1,'\\nMask is: %s\\n');, end\n mask = spm_read_vols(Vm);,\n % if a mask file, then load it\n elseif length(mask) == 1\n % if a number, treat this as threshold value for pa_overall\n % I recommend .001, which is a 0.1% chance of activating across all\n % tasks\n\n if ~(exist('Activation.img') == 2),\n try\n Vm = spm_vol('../Activation.img'); \n catch\n P = spm_get(1,'Select Activation.img');\n Vm = spm_vol(P);\n end\n else\n Vm = spm_vol('Activation.img');\n end\n maskimg = spm_read_vols(Vm);,\n mask = real(maskimg > mask); % threshold \n end\nend\nif isempty(mask), if vb > 0, fprintf(1,'\\nNo mask. Running all voxels!\\n');, end, mask = ones(dims);,end\n\nnvox = mask(:); nvox = sum(nvox>0);\nfprintf(1,'\\nVoxels in mask: %3.2f\\n',nvox);\n\n\n\n\n\n% -------------------------------------------------------------------\n% * for each slice...\n% -------------------------------------------------------------------\n\nfprintf(1,'\\nRunning Chi-square Slice %03d',0)\n\nfor slicei = 1:dims(3)\n \n if vb > 1, t1 = clock;, fprintf(1,'\\b\\b\\b%03d',slicei),end\n \n %if vb > 0, fprintf(1,' '); , end % to offset Load prompt\n \n % returns image names\n process_slice(slicei,Vall,X,w,names,vb,mask(:,:,slicei),[],Xi,Xinms,condf);\n\n\n %if vb > 1, fprintf(1,'\\t%6.0f s for slice',etime(clock,t1)),end\nend\n\n\n\n\n\nreturn\n\n\n\n\n\n\n\n% -------------------------------------------------------------------\n%\n%\n%\n%\n% * SUB-FUNCTIONS\n%\n%\n%\n%\n% ------------------------------------------------------------------- \n \n \nfunction process_slice(slicei,Vall,X,w,names,vb,varargin)\n\nmask = []; if length(varargin) > 0, mask = varargin{1};, end\nsl = []; if length(varargin) > 1, sl = varargin{2};, end\n\n% set up weighted average calc\nXi = []; \nif length(varargin) > 2, \n Xi = varargin{3};, Xinms = varargin{4};, \n W = diag(w); % ./ sum(w));\n Xi = Xi' * W; % multiply this by data to get weighted avgs\n sumxi = sum(Xi,2);\nend\n\ncondf = []; if length(varargin) > 4, condf = varargin{5};, end\n\nglobal dims\nglobal cols\n\nnimgs = length(Vall);\nncontrasts = size(Xi,2);\n\n% if empty images specified, ncontrasts will be greater than nimgs\ndoempty = ncontrasts - nimgs;\nif doempty > 0\n addtoy = zeros(doempty,1);\nend\n\n% output images -- initialize\n% --------------------------------------------\n\nomnchi2 = NaN * zeros([dims(1:2)]);\nchi2pmap = ones([dims(1:2)]);\nchi2warn = omnchi2;\nchi2nonp = omnchi2;\nemptyimg = NaN .* zeros(dims); % in case we need to create a new volume, used later as well\n\nif ~isempty(Xi), avgs = NaN * zeros([dims(1:2) size(Xi,1)]);, end\n\n\n\n% -------------------------------------------------------------------\n% * load the slice\n% -------------------------------------------------------------------\net = clock;\n\nif isempty(sl)\n\n if vb > 0, fprintf(1,'Load >'), end\n\n if ~isempty(mask) && ~(sum(sum(sum(mask))) > 0)\n % skip it; write only\n % -------------------------------------------------------------------\n % * write output images\n % -------------------------------------------------------------------\n\n warning off\n write_beta_slice(slicei,Vall(1),omnchi2,emptyimg,'chi2_',{'map'});\n write_beta_slice(slicei,Vall(1),chi2pmap,emptyimg,'chi2p_',{'map'});\n write_beta_slice(slicei,Vall(1),chi2warn,emptyimg,'chi2_warning_',{'map'});\n write_beta_slice(slicei,Vall(1),chi2nonp,emptyimg,'chi2_nonpar_',{'map'});\n\n if ~isempty(Xi)\n class_avg_images = write_beta_slice(slicei,Vall(1),avgs,emptyimg,'avgs_',Xinms);\n save SETUP -append class_avg_images\n end\n \n return\n else\n sl = timeseries_extract_slice(Vall,slicei);\n end\n\n if vb > 0, fprintf(1,'\\b\\b\\b\\b\\b\\b');,end\n\nelse\n % we've already loaded the slice!\n\nend\n\n\n\nif ~isempty(mask), sl(:,:,1) = sl(:,:,1) .* mask;, end\n\n\n% -------------------------------------------------------------------\n% * find in-mask voxels\n% -------------------------------------------------------------------\n\nsumsl = sum(sl,3); % sum of all contrasts\n\n% find indices i and j for all in-mask voxels\nwvox = find(sumsl ~= 0 & ~isnan(sumsl));\n[i,j] = ind2sub(size(sl(:,:,1)),wvox);\n\n%fprintf(1,[repmat('\\b',1,19) '%3.0f voxels > '],length(i))\nif vb > 0, \n if slicei > 1, fprintf(1,'\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b');, end\n str = sprintf(' elapsed: %3.0f s vox:%04d fitting',etime(clock,et),length(i));\n fprintf(1,str);\nend\n\n% -------------------------------------------------------------------\n% * compute regression for each in-mask voxel\n% -------------------------------------------------------------------\n\n\n\n% loop through voxels\n% --------------------------------------------\net = clock;\nwarning off % because of iteration limit\n \nfprintf(1,'%04d',0);\n\nfor k = 1:length(i)\n\n y = squeeze(sl(i(k),j(k),:)); \n \n if doempty > 0 % empty contrasts\n y = [y; addtoy];\n end\n \n % convert from weighted to indicator (on/off)\n % only works for spherical convolution!!\n % * no longer necessary, because images are no longer weighted.\n y = double(y>0);\n\n % chi-square test, weighted\n % last argument is nonparametric flag to test close results more\n % carefully\n % --------------------------------------------\n [chi2,df,chi2p,sig,warn,tab,e,isnonpar] = chi2test([y condf],'obs',w,1);\n \n omnchi2(i(k),j(k)) = chi2;\n chi2pmap(i(k),j(k)) = chi2p; \n chi2warn(i(k),j(k)) = warn;\n chi2nonp(i(k),j(k)) = isnonpar;\n \n % --------------------------------------------\n \n % weighted average probability images\n % --------------------------------------------\n if ~isempty(Xi)\n avg = Xi * y; avg = avg ./ sumxi;\n avgs(i(k),j(k),:) = avg;\n end\n \n \n \n if mod(k,10)==0, fprintf(1,'\\b\\b\\b\\b%04d',k);,end\n %if k == 1000, fprintf(1,'%3.0f s per 1000 vox.',etime(clock,et)), end\nend\nfprintf(1,'\\b\\b\\b\\b');\n\nwarning on\n\nif vb > 1, fprintf(1,[repmat('\\b',1,14+9) ' elapsed: %3.0f s'],etime(clock,et));, end\n\nclear sl\n\n\n\n% -------------------------------------------------------------------\n% * write output images\n% ------------------------------------------------------------------- \n\nwarning off\n\nwrite_beta_slice(slicei,Vall(1),omnchi2,emptyimg,'chi2_',{'map'});\nwrite_beta_slice(slicei,Vall(1),chi2pmap,emptyimg,'chi2p_',{'map'});\nwrite_beta_slice(slicei,Vall(1),chi2warn,emptyimg,'chi2_warning_',{'map'});\nwrite_beta_slice(slicei,Vall(1),chi2nonp,emptyimg,'chi2_nonpar_',{'map'});\n\nif ~isempty(Xi)\n class_avg_images = write_beta_slice(slicei,Vall(1),avgs,emptyimg,'avgs_',Xinms);\n save SETUP -append class_avg_images\nend\n\nif length(i) > 0, save SETUP -append df, end\n\nwarning on\n\nif vb > 0, fprintf(1,[repmat('\\b',1,14+9+1)]);, end\n \n \nreturn\n\n\n\n\n\n\n\nfunction Pw = write_beta_slice(slicei,V,betas,emptyimg,varargin)\n% Pw = write_beta_slice(sliceindex,V,data,empty,prefix)\n% Slice-a-metric version\nwarning off % due to NaN to int16 zero conversions\nV.dim(4) = 16; % set to float to preserve decimals\n\nprefix = 'check_program_';\nnames = {''}; % for field only\nif length(varargin) > 0, prefix = varargin{1};,end % field name\nif length(varargin) > 1, names = varargin{2};,end % level names\n\nfor voli = 1:size(betas,3) % for each image/beta series point\n %if voli < 10, myz = '000';, elseif voli < 100, myz = '00';, else myz = '000';,end\n V.fname = [prefix names{voli} '.img'];\n V.descrip = ['Created by Meta_Logistic'];\n\n % create volume, if necessary\n if ~(exist(V.fname) == 2), spm_write_vol(V,emptyimg);,end\n \n spm_write_plane(V,betas(:,:,voli),slicei);\n \n if ~(exist('Pw')==1), Pw = which(V.fname);, \n else Pw = str2mat(Pw,which(V.fname));\n end\n \nend\n\n\n\nwarning on\nreturn"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Chisq_new.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Chisq_new.m", "size": 10950, "source_encoding": "utf_8", "md5": "a45864bb28584fb860ccb0f44481a6b7", "text": "% Multi-mode function for performing voxel-wise chi-squared analysis on\n% meta-analysis data (peak activations)\n%\n% R = Meta_Chisq_new('compute', MC_Setup, ['mask', maskimg])\n% cl = Meta_Chisq_new('write', R);\n%\n% Note: Meta_Chisq works with list of image names for all study maps\n% Meta_Chisq_new works with output of 'setup' function in\n% Meta_Activation_FWE, and does not require writing study contrast maps as\n% image files (all info is contained in MC_Setup struct)\n%\n% new: October 2008: \n% if there are two conditions in the chi-square analysis, this function can\n% write maps and return clusters for \"A greater than B\" effects--areas in \n% which the proportion of activations for the first condition entered is greater\n% than for the second one--and vice versa. \n% Get clusters for directional effects by typing:\n% [cl, clavsb, clbvsa] = Meta_Chisq_new('write', R);\n% clavsb and clbvsa are the \"A>B\" and \"B>A\" regions, respectively\n% \n% To get plots of activation proportions in each region, use the following\n% code (This is done automatically if you have an MC_Info.mat file in the chi2 directory!):\n% load MC_Info\n% [studybyroi,studybyset] = Meta_cluster_tools('getdata', clavsb, MC_Setup.unweighted_study_data, MC_Setup.volInfo);\n% [prop_by_condition,se,num_by_condition,n] = Meta_cluster_tools('count_by_condition',studybyroi, R.Xi, R.w, 1, {'Diff'}, MC_Setup.Xinms, {[0 0 1] [1 1 0]});\n%\n% [studybyroi,studybyset] = Meta_cluster_tools('getdata', clbvsa, MC_Setup.unweighted_study_data, MC_Setup.volInfo);\n% [prop_by_condition,se,num_by_condition,n] = Meta_cluster_tools('count_by_condition',studybyroi, R.Xi, R.w, 1, {'Diff'}, MC_Setup.Xinms, {[0 0 1] [1 1 0]});\n%\n% cluster_orthviews(clavsb, {[.1 .1 1]}, 'solid');\n% cluster_orthviews(clbvsa, {[1 1 0]}, 'solid', 'add');\n% \n% Then you can use the point slice plotter to visualize actual peaks:\n% Meta_interactive_point_slice_plot(MC_Setup, DB);\n%\n% tor wager\n%\n%\n% Example:\n% ------------------------------------------------------\n% Run an analysis with Meta_Chisq_new, and then use these tools to make bar\n% plots of regions. The lines below run the entire analysis.\n% mask = which('Activation_FWE_all.img')\n% R = Meta_Chisq_new('compute', MC_Setup, 'mask', mask);\n% R = Meta_Chisq_new('write', R);\n% [studybyroi, studybyset] = Meta_cluster_tools('getdata', cl(1), R.dat, R.volInfo);\n% [prop_by_condition, se, num_by_condition, n] = Meta_cluster_tools('count_by_condition', studybyset, R.Xi, R.w, 1);\n% set(gca, 'XTickLabel', MC_Setup.Xinms)\n% ------------------------------------------------------\n%\n% Example 2: start from the beginning, all steps\n% DB = Meta_Setup(DB);\n% mask = DB.maskname;\n% MC_Setup = Meta_Activation_FWE('setup', DB);\n% % ***note: You must 'add a contrast' and select the studies you want to\n% % do chi-sq analysis on, and some arbitrary contrast over those studies.\n% % this function will use the MC_Setup.Xi field, which has indicators for\n% % the different categories of study you're analyzing with chi-sq.\n% R = Meta_Chisq_new('compute', MC_Setup, 'mask', mask); save Meta_Chisq_R R\n\n% Programmers' notes\n% cosmetic edits/minor edits, tor wager, july 2011\n\nfunction varargout = Meta_Chisq_new(meth, varargin)\n R = [];\n maskimg = 'Activation_FWE_all.img';\n\n spm_defaults;\n \n for i = 1:length(varargin)\n if isstruct(varargin{i})\n switch meth\n case 'compute'\n MC_Setup = varargin{i};\n case 'write'\n R = varargin{i};\n otherwise\n error('Unknown method. Could create problems!!')\n end\n elseif ischar(varargin{i})\n switch varargin{i}\n\n % functional commands\n case 'mask', maskimg = varargin{i+1}; varargin{i+1} = [];\n case 'data', dat = varargin{i+1};\n\n case 'MC_Setup', MC_Setup = varargin{i + 1}; varargin{i + 1} = [];\n \n otherwise, warning(['Unrecognized input string option:' varargin{i}]);\n end\n end\n end\n\n switch meth\n case 'compute'\n % do first just to make sure no errs after running!\n Rtmp = [];\n Rtmp.contrastname = input('Enter contrast name for this analysis (no spaces or special chars) ', 's');\n\n\n disp('Preparing data.')\n if ~exist('dat', 'var'), dat = MC_Setup.unweighted_study_data; end\n\n % Get only in-mask voxels\n volInfo = iimg_read_img(maskimg, 2);\n is_significant = volInfo.image_indx(MC_Setup.volInfo.wh_inmask);\n\n dat = full(double(dat(is_significant,:)));\n\n fprintf(' %3.0f valid voxels.\\n', size(dat, 1));\n \n disp('Preparing task indicators and weights.')\n % task and weights\n Xi = MC_Setup.Xi;\n\n w = MC_Setup.wts;\n w = w ./ mean(w);\n\n [nvox, nstudies] = size(dat);\n ntasks = size(Xi, 2);\n\n disp('Getting proportion activations for each condition.')\n % get proportions for the entire matrix\n [icon, ctxtxi, betas, num_by_condition, prop_by_condition] = meta_apply_contrast(dat, Xi, w, MC_Setup.contrasts);\n\n disp('Running chi-square with nonparametric options for each in-mask voxel.')\n % run nonparametric chi2 test\n [chi2, df, p, sig, warn, tab, expected, isnonpar] = meta_analyze_data(dat', 'X', Xi, 'chi2', 'w', w);\n\n R = struct('volInfo', volInfo, 'in_mask', is_significant, 'contrastname', Rtmp.contrastname, ...\n 'dat', sparse(logical(dat)), 'Xi', Xi, 'w', w, 'prop_by_condition', prop_by_condition, ...\n 'num_by_condition', num_by_condition, 'chi2', chi2, 'df', df, 'p', p, 'sig', sig, 'warn', warn, ...\n 'isnonpar', isnonpar);\n\n varargout{1} = R;\n\n case 'write'\n disp('Meta_Chisq: Getting and saving results');\n pvals = [.05 .01 .005 .001 Inf];\n str = cell(length(pvals), 1);\n sig_vector = zeros(length(R.p), length(pvals));\n for i = 1:length(pvals)\n [nsig, str{i}, sig_vector(:,i)] = get_sig_vector(pvals(i), R.p);\n\n fprintf(1, '%3.0f\\tP < %3.4f %s\\t%3.0f\\n', i, pvals(i), str{i}, nsig);\n end\n fprintf(1, '\\n');\n\n % tor added july 2011 to fix bug with out-of-mask voxels and sizes\n sig_vector = zeroinsert(~R.in_mask, sig_vector);\n R.chi2 = zeroinsert(~R.in_mask, R.chi2')';\n R.prop_by_condition = zeroinsert(~R.in_mask, R.prop_by_condition);\n \n wh = input('Enter index of map to write: ');\n\n % p-value image\n name = [R.contrastname '_' num2str(pvals(wh)) '_' str{wh} '_chi2p'];\n name(name == '.') = '_';\n name = [name '.img'];\n iimg_reconstruct_vols(sig_vector(:,wh), R.volInfo, 'outname', name, 'descrip', 'Created by Meta_Chisq_new.m');\n fprintf(1, 'Written: %s\\n', name);\n\n % chi2 image\n name = [R.contrastname '_' num2str(pvals(wh)) '_' str{wh} '_chi2'];\n name(name == '.') = '_';\n name = [name '.img'];\n chi2dat = R.chi2' .* (sig_vector(:,wh) > 0);\n iimg_reconstruct_vols(chi2dat, R.volInfo, 'outname', name, 'descrip', 'Created by Meta_Chisq_new.m');\n fprintf(1, 'Written: %s\\n', name);\n\n % save chi-square values in clusters\n cl = mask2clusters(name);\n varargout{1} = cl;\n\n if size(R.prop_by_condition, 2) == 2\n % two conditions. Write pos and neg results\n avsb = -1 * diff(R.prop_by_condition')';\n\n % A > B\n chi2dat = R.chi2' .* (sig_vector(:,wh) > 0) .* (avsb > 0);\n name = [R.contrastname '_AgreaterthanB_' num2str(pvals(wh)) '_' str{wh} '_chi2'];\n name(name == '.') = '_';\n name = [name '.img'];\n\n iimg_reconstruct_vols(chi2dat, R.volInfo, 'outname', name, 'descrip', 'Created by Meta_Chisq_new.m');\n clavsb = mask2clusters(name);\n varargout{2} = clavsb;\n fprintf(1, 'Written: %s\\n', name);\n\n % B > A\n chi2dat = R.chi2' .* (sig_vector(:,wh) > 0) .* (avsb < 0);\n name = [R.contrastname '_BgreaterthanA_' num2str(pvals(wh)) '_' str{wh} '_chi2'];\n name(name == '.') = '_';\n name = [name '.img'];\n\n iimg_reconstruct_vols(chi2dat, R.volInfo, 'outname', name, 'descrip', 'Created by Meta_Chisq_new.m');\n clbvsa = mask2clusters(name);\n varargout{3} = clbvsa;\n fprintf(1, 'Written: %s\\n', name);\n\n % Extent threshold\n if ~isempty(clbvsa), clbvsa(cat(1, clbvsa.numVox) < 3) = []; end\n if ~isempty(clavsb), clavsb(cat(1, clavsb.numVox) < 3) = []; end\n\n % Make plots\n if exist('MC_Setup', 'var')\n elseif exist(fullfile(pwd, 'MC_Info.mat'), 'file')\n load MC_Info MC_Setup\n end\n \n if exist('MC_Setup', 'var')\n [studybyroi,studybyset] = Meta_cluster_tools('getdata', clavsb, MC_Setup.unweighted_study_data, MC_Setup.volInfo);\n [prop_by_condition,se,num_by_condition,n] = Meta_cluster_tools('count_by_condition',studybyroi, R.Xi, R.w, 1, {'Diff'}, MC_Setup.Xinms, {[0 0 1] [1 1 0]});\n\n [studybyroi,studybyset] = Meta_cluster_tools('getdata', clbvsa, MC_Setup.unweighted_study_data, MC_Setup.volInfo);\n [prop_by_condition,se,num_by_condition,n] = Meta_cluster_tools('count_by_condition',studybyroi, R.Xi, R.w, 1, {'Diff'}, MC_Setup.Xinms, {[0 0 1] [1 1 0]});\n\n cluster_orthviews(clavsb, {[.1 .1 1]}, 'solid');\n cluster_orthviews(clbvsa, {[1 1 0]}, 'solid', 'add');\n else\n disp('MC_Info.mat file not found in the current directory. Skipping plots.');\n cluster_orthviews(clavsb, {[.1 .1 1]}, 'solid');\n cluster_orthviews(clbvsa, {[1 1 0]}, 'solid', 'add');\n end\n\n else\n varargout{2} = [];\n varargout{3} = [];\n\n disp('More than two conditions: Omitting writing of results images containing directional effects.');\n\n end\n \n otherwise\n error('Unknown method.')\n end\n \nend % Main function\n\n\n% sub-functions\n\nfunction [nsig, str, sig_vector] = get_sig_vector(p, chi2p)\n if isinf(p)\n str = 'FDR';\n p = FDR(chi2p, .05);\n if isempty(p), p = -Inf; end\n else\n str = 'Unc';\n end\n sig_vector = (chi2p .* (chi2p < p))';\n nsig = sum(sig_vector > 0);\nend\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Logistic.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Logistic.m", "size": 11335, "source_encoding": "utf_8", "md5": "21b6cd0028815afac8d86e99093ac0b1", "text": "function DB = Meta_Logistic(DB,varargin)\n% DB = Meta_Logistic(DB,[verbose],[mask image name],[control strings])\n% \n% NEEDS:\n%\n% to set up design:\n%DB.(fields) % lists of fields containing task conditions for each coordinate point\n%DB.pointind % indices of which coord points are in which unique\n% contrast\n%DB.X\n%\n% to run analysis:\n% DB.PP % list of contrast image names\n% DB.studyweight % weights\n% 'Activation.img' or a mask input argument (2nd arg).\n%\n% 3rd to nth arguments are optional 'control strings'\n% 'load' : load from SETUP.mat file; do not recreate\n%\n% Examples:\n% DB = Meta_Logistic(DB,2,.05)\n%\n% DB = Meta_Logistic(DB,2,[],'load')\n\ndisp('WARNING: LOGISTIC REGRESSION IS NOT THAT STABLE UNLESS THERE ARE HIGH NUMBERS OF OBSERVATIONS')\ndisp('in each level of each factor. Recommended: use Meta_Chisq.m instead.');\n\nglobal dims\nglobal cols\n\nspm_defaults; defaults.analyze.flip = 0;\ndoload = 0;\n\nif length(varargin) > 0, vb = varargin{1};, else, vb = 1;, end\n% mask is varargin{2}\nif length(varargin) > 2,\n for i = 3:length(varargin)\n if strcmp(varargin{i},'load'), doload = 1;, end\n\n end\nend\n\n% ---------------------------------------\n% Set up design matrix\n% names = contrast names, also output image names\n% prunes DB\n% ---------------------------------------\nif doload\n load SETUP\nelse\n [X,names,DB,Xi,Xinms,condf,testfield] = Meta_Logistic_Design(DB);\nend\n\ncols = size(X,2);\n\nw = DB.studyweight;\nw = w ./ mean(w); \n% weights should be mean 1 for logistic regression\n% also preserve relative weighting\n\nDB.X = X; DB.Xnames = names;\n \n% Save names of contrast images to use\nDB.PP = check_valid_imagename(DB.PP);\n\ncontrast_images_used = DB.PP;\n\nif ~doload\n save SETUP contrast_images_used X names DB w Xi Xinms condf testfield\nend\n\n% ---------------------------------------\n% Set up images\n% ---------------------------------------\n\n% image dimensions, etc.\nV = spm_vol(DB.PP(1,:));\nVall = spm_vol(DB.PP);\n\ndims = V.dim(1:3);\n\nif vb > 0, fprintf(1,'\\n\\t\\tNew image dims: %3.0f %3.0f %3.0f %3.0f ',dims(1), dims(2), dims(3), cols),end\n\n\n% ---------------------------------------\n% brain masking\n% e.g., could mask with overall activation image\n% ---------------------------------------\n\nmask = []; \nif length(varargin) > 1, \n mask = varargin{2};, \n if isstr(mask), Vm = spm_vol(mask);, \n if vb > 0, fprintf(1,'\\nMask is: %s\\n');, end\n mask = spm_read_vols(Vm);,\n % if a mask file, then load it\n elseif length(mask) == 1\n % if a number, treat this as threshold value for pa_overall\n % I recommend .001, which is a 0.1% chance of activating across all\n % tasks\n\n if ~(exist('Activation.img') == 2),\n try\n Vm = spm_vol('../Activation.img'); \n catch\n P = spm_get(1,'Select Activation.img');\n Vm = spm_vol(P);\n end\n else\n Vm = spm_vol('Activation.img');\n end\n maskimg = spm_read_vols(Vm);,\n mask = real(maskimg > mask); % threshold \n end\nend\nif isempty(mask), if vb > 0, fprintf(1,'\\nNo mask. Running all voxels!\\n');, end, mask = ones(dims);,end\n\nnvox = mask(:); nvox = sum(nvox>0);\nfprintf(1,'\\nVoxels in mask: %3.2f\\n',nvox);\n\n\n\n\n\n% -------------------------------------------------------------------\n% * for each slice...\n% -------------------------------------------------------------------\n\nfprintf(1,'\\nRunning Logistic Regression Slice %02d',0)\n\nfor slicei = 1:dims(3)\n \n if vb > 1, t1 = clock;, fprintf(1,'\\b\\b%02d',slicei),end\n \n %if vb > 0, fprintf(1,' '); , end % to offset Load prompt\n \n % returns image names\n process_slice(slicei,Vall,X,w,names,vb,mask(:,:,slicei),[],Xi,Xinms,condf);\n\n\n %if vb > 1, fprintf(1,'\\t%6.0f s for slice',etime(clock,t1)),end\nend\n\n\n\n\n\nreturn\n\n\n\n\n\n\n\n% -------------------------------------------------------------------\n%\n%\n%\n%\n% * SUB-FUNCTIONS\n%\n%\n%\n%\n% ------------------------------------------------------------------- \n \n \nfunction process_slice(slicei,Vall,X,w,names,vb,varargin)\n\nmask = []; if length(varargin) > 0, mask = varargin{1};, end\nsl = []; if length(varargin) > 1, sl = varargin{2};, end\n\n% set up weighted average calc\nXi = []; \nif length(varargin) > 2, \n Xi = varargin{3};, Xinms = varargin{4};, \n W = diag(w); % ./ sum(w));\n Xi = Xi' * W; % multiply this by data to get weighted avgs\n sumxi = sum(Xi,2);\nend\n\ncondf = []; if length(varargin) > 4, condf = varargin{5};, end\n\nglobal dims\nglobal cols\n\n% -------------------------------------------------------------------\n% * load the slice\n% -------------------------------------------------------------------\net = clock;\n\nif isempty(sl)\n \n if vb > 0, fprintf(1,'Load >'), end \n \n if ~isempty(mask) & ~(sum(sum(sum(mask))) > 0)\n % skip it\n betas = NaN * zeros([dims(1:2) cols]);\n t = NaN * zeros([dims(1:2) cols]);\n p = NaN * zeros([dims(1:2) cols]);\n\n if vb > 0, fprintf(1,'\\b\\b\\b\\b\\b\\b');,end\n return\n else\n sl = timeseries_extract_slice(Vall,slicei);\n end\n\nelse\n % we've already loaded the slice!\n \nend\n\nif ~isempty(mask), sl(:,:,1) = sl(:,:,1) .* mask;, end\n\n\n% -------------------------------------------------------------------\n% * find in-mask voxels\n% -------------------------------------------------------------------\n\nsumsl = sum(sl,3); % sum of all contrasts\n\n% find indices i and j for all in-mask voxels\nwvox = find(sumsl ~= 0 & ~isnan(sumsl));\n[i,j] = ind2sub(size(sl(:,:,1)),wvox);\n\n%fprintf(1,[repmat('\\b',1,19) '%3.0f voxels > '],length(i))\nif vb > 0, fprintf(1,'\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b elapsed: %3.0f s vox:%04d fitting',etime(clock,et),length(i)),end\n\n% -------------------------------------------------------------------\n% * compute regression for each in-mask voxel\n% -------------------------------------------------------------------\n\n% output images -- initialize\n% --------------------------------------------\nbetas = NaN * zeros([dims(1:2) cols]);\nt = betas;\np = ones([dims(1:2) cols]);\n\nFmap = NaN * zeros([dims(1:2)]);\nomnp = ones([dims(1:2)]);\n\nomnchi2 = NaN * zeros([dims(1:2)]);\nchi2pmap = omnp;\nchi2warn = Fmap;\n\nif ~isempty(Xi), avgs = NaN * zeros([dims(1:2) size(Xi,1)]);, end\n\n\n% loop through voxels\n% --------------------------------------------\net = clock;\nwarning off % because of iteration limit\n \nfprintf(1,'%04d',0);\n\nfor k = 1:length(i)\n\n y = squeeze(sl(i(k),j(k),:)); \n \n % convert from weighted to indicator (on/off)\n % only works for spherical convolution!!\n % * no longer necessary, because images are no longer weighted.\n y = double(y>0);\n\n % chi-square test, weighted\n % last argument is nonparametric flag to test close results more\n % carefully\n % --------------------------------------------\n [chi2,df,chi2p,sig,warn,tab] = chi2test([y condf],'obs',w,1);\n \n omnchi2(i(k),j(k)) = chi2;\n chi2pmap(i(k),j(k)) = chi2p; \n chi2warn(i(k),j(k)) = warn;\n % --------------------------------------------\n \n % weighted average probability images\n % --------------------------------------------\n if ~isempty(Xi)\n avg = Xi * y; avg = avg ./ sumxi;\n avgs(i(k),j(k),:) = avg;\n end\n \n \n % logistic regression\n % --------------------------------------------\n\n if any(tab(:) == 0)\n % We can't run Logistic for this voxel; it won't be meaningful.\n \n % Logistic regression does not return accurate results if the\n % proportions are 100% (i.e., if some cells in tab table are empty)\n % If so, shrink values a bit so that we can estimate regression\n \n y(y==0) = 0+.01;\n y(y==1) = 1-.01;\n end\n \n %else\n [b,dev,stats]=glmfit(X,[y ones(size(y))],'binomial','logit','off',[],w); % pvals are more liberal than Fisher's Exact!\n\n % omnibus test - R^2 change test\n % --------------------------------------------------------\n sstot = y'*y;\n r2full = (sstot - (stats.resid' * stats.resid)) ./ sstot;\n dffull = stats.dfe;\n\n [br,devr,statsr]=glmfit(ones(size(y)),[y ones(size(y))],'binomial','logit','off',[],w,'off');\n r2red = (sstot - (statsr.resid' * statsr.resid)) ./ sstot;\n dfred = statsr.dfe;\n\n if r2full < r2red, fprintf(1,'Warning!'); r2red = r2full;,drawnow; fprintf(1,'\\b\\b\\b\\b\\b\\b\\b\\b'); end\n [F,op,df1,df2] = compare_rsquare_noprint(r2full,r2red,dffull,dfred);\n % --------------------------------------------------------\n \n % save output from voxel\n % --------------------------------------------\n betas(i(k),j(k),:) = b(2:end);\n t(i(k),j(k),:) = stats.t(2:end);\n p(i(k),j(k),:) = stats.p(2:end);\n\n Fmap(i(k),j(k)) = F;\n omnp(i(k),j(k)) = op;\n %end\n \n \n if mod(k,10)==0, fprintf(1,'\\b\\b\\b\\b%04d',k);,end\n %if k == 1000, fprintf(1,'%3.0f s per 1000 vox.',etime(clock,et)), end\nend\nfprintf(1,'\\b\\b\\b\\b');\n\nwarning on\n\nif vb > 1, fprintf(1,[repmat('\\b',1,14+9) ' elapsed: %3.0f s'],etime(clock,et));, end\n\nclear sl\n\n\n\n% -------------------------------------------------------------------\n% * write output images\n% ------------------------------------------------------------------- \n\nemptyimg = NaN .* zeros(dims); % in case we need to create a new volume, used later as well\n \nwarning off\n%if vb > 1, fprintf(1,'\\n\\tWriting output > '), end\n\n%for i = 1:cols\n\nwrite_beta_slice(slicei,Vall(1),betas,emptyimg,'beta_',names);\nwrite_beta_slice(slicei,Vall(1),t,emptyimg,'t_',names);\nwrite_beta_slice(slicei,Vall(1),p,emptyimg,'p_',names);\n \n%end\n\nwrite_beta_slice(slicei,Vall(1),Fmap,emptyimg,'F_',{'Omnibus'});\nwrite_beta_slice(slicei,Vall(1),omnp,emptyimg,'p_',{'Omnibus'});\n\nwrite_beta_slice(slicei,Vall(1),omnchi2,emptyimg,'chi2_',{'Omnibus'});\nwrite_beta_slice(slicei,Vall(1),chi2pmap,emptyimg,'chi2p_',{'Omnibus'});\nwrite_beta_slice(slicei,Vall(1),chi2warn,emptyimg,'chi2_warning_',{'Omnibus'});\n\nif ~isempty(Xi)\n class_avg_images = write_beta_slice(slicei,Vall(1),avgs,emptyimg,'avgs_',Xinms);\n save SETUP -append class_avg_images\nend\n\nif length(i) > 0, save SETUP -append df, end\n\nwarning on\n\nif vb > 0, fprintf(1,[repmat('\\b',1,14+9+1)]);, end\n \n \nreturn\n\n\n\n\n\n\n\nfunction Pw = write_beta_slice(slicei,V,betas,emptyimg,varargin)\n% Pw = write_beta_slice(sliceindex,V,data,empty,prefix)\n% Slice-a-metric version\nwarning off % due to NaN to int16 zero conversions\nV.dim(4) = 16; % set to float to preserve decimals\n\nprefix = 'check_program_';\nnames = {''}; % for field only\nif length(varargin) > 0, prefix = varargin{1};,end % field name\nif length(varargin) > 1, names = varargin{2};,end % level names\n\nfor voli = 1:size(betas,3) % for each image/beta series point\n %if voli < 10, myz = '000';, elseif voli < 100, myz = '00';, else myz = '000';,end\n V.fname = [prefix names{voli} '.img'];\n V.descrip = ['Created by Meta_Logistic'];\n\n % create volume, if necessary\n if ~(exist(V.fname) == 2), spm_write_vol(V,emptyimg);,end\n \n spm_write_plane(V,betas(:,:,voli),slicei);\n \n if ~(exist('Pw')==1), Pw = which(V.fname);, \n else Pw = str2mat(Pw,which(V.fname));\n end\n \nend\n\n\n\nwarning on\nreturn"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_plot_points_on_slices.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_plot_points_on_slices.m", "size": 4404, "source_encoding": "utf_8", "md5": "33fce4f7291f828753137d7023ea7633", "text": "function Meta_plot_points_on_slices(DB, MC_Setup)\n % Meta_plot_points_on_slices(DB, MC_Setup)\n %\n % This function plots points on multiple slices. It can do it either on\n % solid slices or \"outline\" contours. Right now, it's hard-coded for\n % contours, but the main function it runs, plot_points_on_slice.m, has\n % input options for either, so this can be easily changed.\n %\n % If you're using the densityUtility3 toolbox, you need two structures\n % created with those tools:\n % DB, created using Meta_Setup.m, stored in the file SETUP.mat in your analysis directory\n % MC_Info, created using Meta_Activation_FWE.m, stored in the file MC_Info.mat in your analysis directory\n %\n % Once you run an analysis, you'll have both of those available, and can\n % run this function.\n %\n % NOTE: This function will color-code points according to the first\n % contrast you set up in Meta_Activation_FWE('setup'...).\n % If you did not specify contrasts, you will have to modify your MC_Setup\n % structure to add them:\n % MC_Setup.connames = {'EmoType'}; % this is the column in DB you want to use to color-code points on the plot\n% MC_Setup.Xinms = {'Cog_Motor' 'Emotion'}; % these are the names of the\n% fields in the column you specified above to identify the points of different types\n%\n % However, you can also run this as a stand-alone function, as shown by\n % the example below:\n %\n % Example: Running this as a stand-alone function\n % You would create \"dummy\" DB and MC_Setup fields with all the inputs this\n % program needs, and pass those in\n %\n% xyz = [18 8 8; -34 0 -6; 12 14 14; 18 8 6; 28 24 -2; 6 -16 6];\n% %vec = [1 1 2 2 2]; % 1 early pain placebo reductions, 2 intxn with nalox during early\n% DB.xyz = xyz; img = which('avg152T1.nii'); DB.maskV = spm_vol(img);\n% MC_Setup.Xinms = {'er' 'inx'}; % arbitrary labels for colors\n% DB.conditionlist = {'er' 'er' 'inx' 'inx' 'inx' 'inx'}' % list of labels for each point (should be entries in MC_Setup.Xinms)\n% MC_Setup.connames = {'conditionlist'}; % name of the column with labels\n% DB.radius_mm = 10; % close enough\n%\n% Tor Wager, Sept 1, 2009\n\norientflag = 'sagg'; \n\nDB.x = DB.xyz(:, 1); DB.y = DB.xyz(:, 2); DB.z = DB.xyz(:, 3);\n\n img = which('avg152T1.nii'); % overlay\nspm_image('init', img);\n\nMeta_interactive_point_slice_plot(MC_Setup, DB);\n\n% montage\n\ncolors = {'b' 'r' 'g' 'y' 'm' 'k'}; % these match Meta_interactive_point_slice_plot\n\n[axh, whsl] = setup_montage(DB.xyz, DB.maskV, orientflag);\n\ncondition_list = DB.(MC_Setup.connames{1}); % condition list\nfor i = 1:length(whsl)\n\n drawflag = 'draw';\n axes(axh(i))\n pointhandles = plot_points_on_slice(DB.xyz(strcmp(condition_list, MC_Setup.Xinms{1}), :), 'slice', whsl(i), 'color', colors{1}, 'marker', 'o', ...\n 'close_enough',DB.radius_mm, 'markersize', 4, orientflag);\n\n for j = 2:length(MC_Setup.Xinms)\n\n if ~isempty(pointhandles), drawflag = 'nodraw'; end\n pth = plot_points_on_slice(DB.xyz(strcmp(condition_list, MC_Setup.Xinms{j}), :), 'slice', whsl(i), 'color', colors{j}, 'marker', 'o', ...\n 'close_enough',DB.radius_mm, 'markersize', 4, orientflag);\n\n pointhandles = [pointhandles pth];\n\n end\n\nend\n\n\nend\n\nfunction [axh, whsl] = setup_montage(XYZmm, V, orientflag)\n \n % how many slices, which ones\n\n XYZ = mm2voxel(XYZmm, V, 1)'; % 1 no re-ordering, allows repeats \n \n switch orientflag\n case 'axial'\n whsl = unique(XYZ(3, :)); % which slices to show\n case 'sagg'\n whsl = unique(XYZ(1, :)); % which slices to show\n otherwise\n error('Orientflag, hard-coded in this function, must be either ''axial'' or ''sagg''')\n end\n \n nsl = length(whsl) + 1;\n rc = ceil(sqrt(nsl)); % rows and columns for plot\n h = [];\n\n f1 = create_figure('SCNlab_Montage', rc, rc);\n colormap gray;\n set(f1, 'Color', [1 1 1], 'MenuBar', 'none')\n \n axh = findobj(f1, 'Type', 'axes');\n axh = sort(axh);\n \n % make axes look nice (this still needs work)\n for i = 1:length(axh)\n p = get(axh(i), 'Position');\n \n set(axh(i), 'Position', [p(1) - p(1)*.05 p(2)+p(2)*.05 p(3) - p(3)*.05 p(4)+p(4)*.05]);\n \n end\n \n if length(axh) > length(whsl)\n for i = length(whsl) + 1 : length(axh)\n delete(axh(i));\n end\n end\nend"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Parcel.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Meta_Parcel.m", "size": 4096, "source_encoding": "utf_8", "md5": "755684e4f35b451de4155bcc40ca8d47", "text": "% [parcels, SVDinfo, parcel_stats] = Meta_Parcel(MC_Setup, varargin)\n%\n% documentation goes here.\n%\n%\n% Example: use your own analysis mask:\n% [parcels, SVDinfo, parcel_stats] = Meta_Parcel(MC_Setup, 'analysis_mask_name', 'acc_roi_mask.img');\n\nfunction [parcels, SVDinfo, parcel_stats] = Meta_Parcel(MC_Setup, varargin)\n\nglobal defaults\nspm_defaults\n\n%% user params: defaults\n\ndata_prctile = 90; % save top xx % of voxels\nn_components = 50; % SVD components to use in parcellation\nparcel_extent_thresh = 10; % min # of contiguous voxels\nanalysis_mask_name = [];\ndosave = 0;\n\nmask = MC_Setup.volInfo.fname;\nvolInfo = MC_Setup.volInfo;\n\n%% Optional inputs\n\nfor i = 1:length(varargin)\n if ischar(varargin{i})\n switch varargin{i}\n \n % functional commands\n case 'data_prctile', data_prctile = varargin{i+1};\n case 'n_components', n_components = varargin{i+1};\n case 'parcel_extent_thresh', parcel_extent_thresh = varargin{i+1};\n case 'analysis_mask_name', analysis_mask_name = varargin{i+1};\n case {'dosave', 'save'}, dosave = 1;\n \n otherwise, warning(['Unknown input string option:' varargin{i}]);\n end\n end\n end\n%%\n\ndat = MC_Setup.unweighted_study_data;\n\n% get which voxels we care about\ns = full(sum(dat'));\n\nif ~isempty(analysis_mask_name)\n maskdat = scn_map_image(analysis_mask_name, mask);\n is_significant = find(maskdat(volInfo.wh_inmask));\nelse\n % Use top n%\n is_significant = find(s > prctile(s, data_prctile));\nend\n\nfprintf('Every voxel has at least %3.0f active contrasts\\n', min(s(is_significant)));\n\nfprintf('There are %3.0f voxels in the analysis area.\\n', length(is_significant));\n\n\ndat = dat(is_significant,:);\ncreate_figure('# of Activating Contrasts'); plot(s); drawnow\n\n%% singlar value D\n\ndat = full(dat');\n[U, S, V] = svd(dat, 'econ');\nU = U(:,1:n_components); S = S(1:n_components, 1:n_components); V = V(:,1:n_components);\nrec = U * S * V';\n\n\n%% get parcels: max loading on SVs\n\nnvox = size(dat, 2);\nclass = zeros(1, nvox);\n\nfor i = 1:nvox\n [taumtx] = correlation('tau', U, repmat(dat(:,i), 1, n_components));\n wh = find(taumtx == max(taumtx)); wh = wh(1);\n \n class(i) = wh;\n \n if mod(i, 100) == 0, fprintf('%3.0f ', i); end\n \nend\n\n%%\nif dosave\n save SVD_data U S V dat class\nend\n\n%% Break into contiguous clusters\n\nvolInfo_sig = volInfo;\nvolInfo_sig.wh_inmask = volInfo_sig.wh_inmask(is_significant);\nvolInfo_sig.n_inmask = nvox;\nvolInfo_sig.xyzlist = volInfo_sig.xyzlist(is_significant, :);\n\n%% Get parcels (cl structure) of contiguous voxels with same loading\n\nparcels = {};\nfor i = 1:n_components\n myvec = class == i;\n parcels{i} = iimg_indx2clusters(myvec', volInfo_sig, .5, parcel_extent_thresh);\n\nend\n\nparcels = cat(2,parcels{:});\n\nif dosave\n save SVD_data -append parcels volInfo_sig\nend\n\n%%\n\n% get contrasts x 1 data indicator vector for each cluster \n% that specifies whether each contrast activated anywhere within cluster\n\n[studybyparcel,studybyset] = Meta_cluster_tools('getdata',parcels, dat',volInfo_sig);\n\nfor i = 1:length(parcels), parcels(i).contrast_activation_dat = studybyparcel(:, i); end\n\n[taumtx, t, p] = correlation('tau', studybyparcel);\np(p == 0) = 100*eps;\n\nif dosave\n save SVD_data -append parcels studybyparcel studybyset taumtx t p\nend\n\n%% Threshold to get significance matrix - FDR\n\npsq = p; psq(find(eye(size(p,1)))) = 0;\npsq = squareform(psq);\npthr = FDR(p,.05);\nif isempty(pthr), pthr = 0; end\n\nsig = sign(t) .* (p < pthr);\n\nsig(isnan(sig)) = 0;\n\n\n%%\nparcels(1).volInfo_sig = volInfo_sig;\n\nSVDinfo = struct('U', U, 'S', S, 'V', V, 'class', class);\nparcel_stats = struct('taumtx', taumtx, 't', t, 'p', p, 'sig', sig, 'fdr_threshold', pthr, 'studybyparcel', studybyparcel, 'studybyset', studybyset);\n\n%% Make figures\n\ntry\n [parcel_stats, all_surf_handles] = Meta_Parcel_results(parcels, parcel_stats);\ncatch\n disp('Error displaying results');\nend\n \n\nend\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_interactive_table_vox.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/Meta_interactive_table_vox.m", "size": 11061, "source_encoding": "utf_8", "md5": "a5860b18f5d5d1ea2568e4b4e76cd5de", "text": "function Meta_interactive_table_vox(compareflag,varargin)\n% Meta_interactive_table_vox(compareflag,[data matrix, volInfo struct])\n% Make table output when you click on a voxel in orthviews.\n%\n% This version uses fields in DB.PP and computes voxel-based distances\n% for consistency with Meta_Setup and other meta-analysis voxel-based\n% functions.\n%\n% the compareflag option\n% compares the computation from DB against saved images in DB.PP and Xi\n% use in a Meta_Logistic directory; for debugging purposes\n\n\n\nglobal DB\nglobal testfield\n\nvargs = {};\nif length(varargin) > 0, vargs = varargin; end\n\n% get mm and voxel coordinates for current spm_orthviews position\n[VOL,coord,mm] = get_current_coords(DB);\n\n\n\n% Set up required variables for table\n[N,con,testfield] = check_fields(DB,testfield);\n\n\n\n% get data from activated contrasts\n% USE DB.PP images, or if data and volInfo are entered above, use those\n[dat2,conindex,whcontrasts] = get_data_at_coordinate(DB,coord,vargs);\n\n\n% run comparison from saved images\n% must be in Meta_Logistic results directory\nif compareflag\n compare_from_saved(dat2,DB,coord,testfield);\nend\n\n\n\n% Table header\n\nfprintf(1,'Studies activating within %3.0f voxels of \\t%3.0f\\t%3.0f\\t%3.0f\\t\\n',DB.radius,mm(1),mm(2),mm(3));\n\nfprintf(1,'Study\\tx\\ty\\tz\\t%s\\tN\\tContrast #\\tpoint index\\tvox. dist\\tmm dist\\n',testfield);\n\n% for summary table\nvalues = DB.(testfield);\nlevels = unique(values);\nw = DB.studyweight;\nw = w ./ mean(w);\nlevelcnt = zeros(1,length(levels)); conwts = 0;\n\nfor i=1:length(whcontrasts)\n\n whpts = find(con == whcontrasts(i)); % indices in DB.point lists for this contrast\n\n whcon = conindex(i); % index in DB.contrast lists for this contrast\n\n xyzmm = [DB.x(whpts) DB.y(whpts) DB.z(whpts)];\n\n % convert to voxels for voxel distance\n % transpose so that 3-voxel lists are not reoriented (produces wrong\n % transform otherwise!)\n xyz = mm2voxel(xyzmm',VOL(1),1);\n\n % voxel distances\n d = distance(coord,xyz);\n whinradius = find(d <= DB.radius); % indices relative to this pt list of points for this contrast w/i radius\n\n % overall DB indices of points for this contrast w/i radius\n whpts2 = whpts(whinradius);\n\n if isempty(whpts2), \n \n disp('Warning! Size or database mismatch. Contrast is in-radius, but no points within contrast are in-radius. Using closest:');, \n disp(['check: ' DB.PP(whcon,:)])\n whinradius = find(d==min(d)); whinradius = whinradius(1);\n whpts2 = whpts(whinradius);\n keyboard\n \n end\n\n\n % save summary information\n for j = 1:length(levels)\n levelcnt(i,j) = double(any(strcmp(levels{j},values(whpts2)))); % any values of this level for this contrast\n conwts(i,1) = w(whcon);\n end\n\n for j = 1:length(whpts2)\n pt = whpts2(j);\n fprintf(1,'%s\\t%3.0f\\t%3.0f\\t%3.0f\\t%s\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.2f\\t%3.2f\\t\\n', ...\n DB.study{pt},DB.x(pt),DB.y(pt),DB.z(pt),DB.(testfield){pt},N(pt),con(pt),pt,d(whinradius(j)),distance(mm',xyzmm(whinradius(j),:)));\n end\n\n\nend\n\nfprintf(1,'\\n');\n\n\n\n\n% summary table\n\nfor i = 1:length(levels)\n [total(1,i),indic,wtotal(1,i),conindic(:,i)] = meta_count_contrasts(DB,testfield,levels{i});\n % returns total and weighted total\n\nend\n\nn = size(levelcnt,1);\ncnt = sum(levelcnt,1); % contrast count\nprc = 100.*sum(levelcnt)./total; % percentage of contrasts in each condition\n\nwcnt = (levelcnt' * conwts)'; %weighted contrast counts\n%./ sum(conwts); % weighted percentage of contrasts\n%wcnt = wprc .* total; % weighted contrast counts\nwprc = 100.*wcnt ./ wtotal; % weighted percentage of contrasts\n\n\n\ntabledat = [cnt;total;prc;wcnt;wtotal; wprc];\ntablenms = {'Count' 'Total contrasts' 'Percentage' 'Wtd. count' 'Wtd. total' 'Wtd. perc.'};\n\n% table header\nfprintf(1,'Measure\\tLevel\\t\\n\\t\\t');\nfor i = 1:length(levels)\n fprintf(1,'%s\\t',levels{i});\nend\nfprintf(1,'\\n');\n\nfor i = 1:length(tablenms)\n fprintf(1,'%s\\t',tablenms{i});\n for j = 1:length(levels)\n fprintf(1,'%3.2f\\t',tabledat(i,j));\n end\n fprintf(1,'\\n');\n if i == 3, fprintf(1,'\\n');, end\nend\nfprintf(1,'\\n');\n\ndisp('Chi-square analyses based on frequency tables')\ndat = tabledat(1:2,:);\n% nos must be total minus yesses\ndat(2,:) = dat(2,:) - dat(1,:);\nwstrings = {'' ', Warning: expected counts < 5: P-value may be inaccurate; mapwise p-values use nonparametric test.'};\n[chi2,df,p,sig,warn,freq_tableu,e,warn2] = chi2test(dat,'table'); warnstr = wstrings{warn+1};\nfprintf(1,'Unweighted: chi2(%3.0f) = %3.2f, p = %3.4f %s\\n',df,chi2,p,warnstr);\n\ndat = tabledat(4:5,:);\n% nos must be total minus yesses\ndat(2,:) = dat(2,:) - dat(1,:);\n[chi2,df,p,sig,warn,freq_tablew,e,warn2] = chi2test(dat,'table'); warnstr = wstrings{warn+1};\nfprintf(1,'Weighted: chi2(%3.0f) = %3.2f, p = %3.4f %s\\n',df,chi2,p,warnstr);\n\n% nonparametric \nif exist('dat2','var')\n condf = indic2condf(conindic);\n %condf = condf(DB.connumbers);\n [chi2,df,p,sig,warn,freq_table,e,nonpar] = chi2test(full([dat2 condf]),'obs',w,1); \n fprintf(1,'Weighted: chi2(%3.0f) = %3.2f, p = %3.4f %s Did nonpar: %3.0f\\n',df,chi2,p,'Weighted with nonpar option.',nonpar);\nend\n\n% not completed, and won't work for weighted\n%p = fishers_exact(freq_tableu);\n%fprintf(1,'\\nUnweighted: Fisher''s exact test: p = %3.4f\\n',p);\n\nreturn\n\n\n\n\n\n\n% sub-functions\n\n\n\n\nfunction [VOL,coord,mm] = get_current_coords(DB)\n% get mm and voxel coordinates for current spm_orthviews position\nif ~isfield(DB,'maskV'),\n error('No DB.maskV field, which is required. See Meta_Setup to create this field and set up analysis.');\nend\n\nVOL = DB.maskV; VOL.M = VOL.mat;\ncoord = spm_orthviews('Pos');\nmm = coord;\ncoord = mm2voxel(coord',VOL(1));\nreturn\n\n\n\n\n\n\nfunction [N,con,testfield] = check_fields(DB,testfield)\nif isfield(DB,'N'), N = DB.N;, elseif isfield(DB,'Subjects'), N = DB.Subjects; else, N = NaN*zeros(size(DB.x));, end\nif isfield(DB,'Contrast'), con = DB.Contrast;,\nelse, con = NaN*zeros(size(DB.x));,\n disp('Warning! You must have a field called DB.Contrasts for the table function to work properly.');\nend\n\nif ~isfield(DB,'connumbers'),\n error('No DB.connumbers field, which is required. See Meta_Setup to create this field and set up analysis.');\nend\n\n% Define testfield (field to display in table)\nif isempty(testfield), try load SETUP testfield, catch, testfield = input('Cannot load testfield from SETUP. Type name of field in DB to display: ','s'), go = 1;, end, end\n\nif isempty(testfield), testfield = input('Cannot load testfield from SETUP. Type name of field in DB to display: ','s'), go = 1;, end,\n\nwhile ~isfield(DB,testfield), disp(['NO field called ' testfield]);\n disp(DB), testfield = input('Type field name: ','s');\nend\nreturn\n\n\n\nfunction [dat2,conindex,whcontrasts] = get_data_at_coordinate(DB,coord,vargs)\n\nif ~isempty(vargs)\n dat = vargs{1};\n volInfo = vargs{2};\n tmp = sub2ind(volInfo.dim(1:3),coord(1),coord(2),coord(3));\n whcol = find(volInfo.wh_inmask == tmp);\n if isempty(whcol)\n disp(['Coordinate is not in mask in volInfo.'])\n dat2 = []; conindex = []; whcontrasts = [];\n return\n else\n dat2 = dat(whcol,:)';\n end\n \nelse\n P2 = check_valid_imagename(DB.PP);\n dat2 = spm_get_data(P2,coord');\nend\nconindex = find(dat2);\nwhcontrasts = DB.connumbers(conindex);\n\nreturn\n\n\n\n\nfunction compare_from_saved(dat2,DB,coord,testfield)\ntry\n load SETUP Xi Xinms X names \ncatch\n disp('Warning: compare will not work right unless you are the dir with SETUP.mat, which contains Xi and Xinms variables');\n disp('See Meta_Logistic for creating Xi and Xinms variables');\nend\n\n% if empty images specified, ncontrasts will be greater than nimgs\nncontrasts = size(Xi,2); nimgs = size(dat2,1);\ndoempty = ncontrasts - nimgs;\nif doempty > 0\n addtoy = zeros(doempty,1);\nend\n\nfprintf(1,'\\nFROM SAVED IMAGES:\\nTotal count: %3.0f\\n',sum(dat2))\ncnt = Xi' * dat2; for i=1:length(Xinms), fprintf(1,'%s\\t%3.0f\\n',Xinms{i},cnt(i));, end\nfprintf(1,'\\n');\nwh = DB.pointind(find(dat2)); %disp(DB.Study(wh))\n\nfor i=1:length(wh)\n mydist = coord;\n fprintf(1,'%s\\t%3.0f\\t%s\\t\\n',DB.Study{wh(i)},DB.Contrast(wh(i)),DB.(testfield){wh(i)});\nend\nfprintf(1,'\\n');\n\ny = dat2;\n\n[b,stats,F,p,df1,df2] = meta_analyze_data(y,'X',Xi,'chi2',DB.studyweight,'table','names',Xinms);\n[b,stats,F,p,df1,df2] = meta_analyze_data(y,'X',DB.X,'logistic',DB.studyweight,'table','names',names);\n\n%print_matrix([y condf]);\n% try\n% load SETUP condf\n% [chi2,chi2p,sig,df,tab] = nonparam_chi2(y,condf);\n% fprintf(1,'%s\\t%3.2f\\t%3.2f\\t\\n','nonparametric chi2: ',chi2,chi2p);\n% catch\n% end\n\n% % set up weighted average calc\n% w = DB.studyweight;\n% w = w ./ mean(w);\n% W = diag(w); % ./ sum(w));\n% w(find(dat2)) % weights\n% \n% sumxiu = sum(Xi,1);\n% cnt = (Xi'*y)';\n% Xi = Xi' * W; % multiply this by data to get weighted avgs\n% sumxi = sum(Xi,2);\n% wcnt = (Xi*y)';\n% \n% avg = wcnt; avg = avg ./ sumxi';\n% \n% fprintf(1,'Unweighted counts and totals\\n');\n% for i =1:length(Xinms), fprintf(1,'%s\\t',Xinms{i});, end,fprintf(1,'\\n');\n% for i =1:length(Xinms), fprintf(1,'%3.2f\\t',cnt(i));, end,fprintf(1,'\\n');\n% for i =1:length(Xinms), fprintf(1,'%3.2f\\t',sumxiu(i));, end,fprintf(1,'\\n');\n% \n% fprintf(1,'\\nWeighted counts, totals, percentage\\n');\n% for i =1:length(Xinms), fprintf(1,'%s\\t',Xinms{i});, end,fprintf(1,'\\n');\n% for i =1:length(Xinms), fprintf(1,'%3.2f\\t',wcnt(i));, end,fprintf(1,'\\n');\n% for i =1:length(Xinms), fprintf(1,'%3.2f\\t',sumxi(i));, end,fprintf(1,'\\n');\n% for i =1:length(Xinms), fprintf(1,'%3.4f\\t',100 .* avg(i));, end,fprintf(1,'\\n');\n% fprintf(1,'\\n');\n\n% \n% % from Meta_Logistic\n% \n% [b,dev,stats]=glmfit(X,[y ones(size(y))],'binomial','logit','off',[],w); % pvals are more liberal than Fisher's Exact!\n% \n% % omnibus test - R^2 change test\n% % --------------------------------------------------------\n% sstot = y'*y;\n% r2full = (sstot - (stats.resid' * stats.resid)) ./ sstot;\n% dffull = stats.dfe;\n% \n% [br,devr,statsr]=glmfit(ones(size(y)),[y ones(size(y))],'binomial','logit','off',[],w,'off');\n% r2red = (sstot - (statsr.resid' * statsr.resid)) ./ sstot;\n% dfred = statsr.dfe;\n% \n% if r2full < r2red, fprintf(1,'Warning!'); r2red = r2full;,drawnow; fprintf(1,'\\b\\b\\b\\b\\b\\b\\b\\b'); end\n% [F,op,df1,df2] = compare_rsquare_noprint(r2full,r2red,dffull,dfred);\n% \n% fprintf(1,'Name\\tBeta\\tt-value\\tp\\t\\n');\n% \n% names = [{'Intercept'} names];\n% for i = 1:length(b)\n% \n% fprintf(1,'%s\\t%3.2f\\t%3.2f\\t%3.4f\\t\\n', ...\n% names{i},b(i),stats.t(i),stats.p(i));\n% \n% end\n% \n% % create condf - from meta_logistic_design\n% % return condition function (dummy codes) for chi-square test\n% [i,j] = find(Xi');\n% [i,s] = sort(i); \n% condf = j(s);\n% \n% [chi2,df,chi2p,sig,warn,tab,e,isnonpar] = chi2test([y condf],'obs',w,1);\n% \n% % print table\n% wstrings = {'' ', Warning: expected counts < 5, used nonparametric p-value.'};\n% warnstr = wstrings{isnonpar+1};\n% fprintf(1,'Weighted: chi2(%3.0f) = %3.2f, p = %3.4f %s\\n',df,chi2,chi2p,warnstr);\n% fprintf(1,'\\n');\n\nreturn\n\n\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "get_contrast_indicator.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/get_contrast_indicator.m", "size": 9176, "source_encoding": "utf_8", "md5": "854063a26010ad065d235a26e52abff9", "text": "function OUT = get_contrast_indicator(DB,testfield,varargin)\n% OUT = get_contrast_indicator(DB,testfield,varargin)\n% OUT = get_contrast_indicator(DB,'Method','create')\n% OUT = get_contrast_indicator(DB,'valence','load',OUT)\n% OUT = get_contrast_indicator(DB,'valence','create',[],{'pos' 'neg'})\n% OUT = get_contrast_indicator(DB,'method','load',OUT,{'visual' 'auditory' 'recall' 'imagery'});\n% Gets a structure with indicators and other stuff for density2 analysis\n% Used in dbcontrast2density\n%\n% There are 2 modes this function runs in: 'load' and 'create'\n% Specify this with a 3rd optional input argument\n% Default is create, which creates a new set of contrast images and stores\n% info in *info.mat files\n%\n% 'Load' looks for existing info.mat files and loads info about task\n% conditions, etc. from those. That way, you can use the same set of\n% contrast images to conduct tesets on other variables, or compare\n% specificity across different variables\n% requires OUT as 2nd var argument; saved from dbcontrast2density\n%\n% This function returns sample sizes in indicator matrix\n% -----------------------------------------------------\n% identify independent contrasts\n% -----------------------------------------------------\n\naction = 'create';\nif length(varargin) > 0, action = varargin{1};,end\n\nswitch action\n \n \n case 'load'\n %-Load function\n %----------------------------------------------------------------------- \n OUT = varargin{2};\n [allconditions,pointcounts,studynames,allcondindic,allcondnames,conindex,PP] = loadindic(DB,OUT,testfield); \n \n case 'create'\n %-Create function\n %-----------------------------------------------------------------------\n\n% weight by sample size (opt input); requires Subjects field\n% conindex contains indices for unique contrasts in vector of all peaks\n% we need this to save variable info about each contrast\n[allconditions,pointcounts,studynames,allcondindic,allcondnames,conindex] = dbcluster2indic(DB,DB,{testfield},1);\n\n\n otherwise\n %-Bad input\n %-----------------------------------------------------------------------\n error('Enter load or create')\nend\n\n\n\nfprintf(1,'Test variable is %s\\n',testfield)\n% number each independent contrast -- use to index contrast .img filenames\n% throughout\nconnumbers = 1:length(studynames); \n\n\n\n%-----------------------------------------------------------------------\n% Remove levels (columns) that were not specified, so we don't make maps\n% for those\n% This step does not remove contrasts from the analysis\n% Just means we won't look for specificity for removed levels\n% always remove NaN levels\n%-----------------------------------------------------------------------\n\nif length(varargin) > 2, \n savelevels = varargin{3};,\n whsave = zeros(size(allcondnames));\nelse, % save everything but NaNs\n savelevels = [];, \n whsave = ones(size(allcondnames));\nend\n\nfor i = 1:length(allcondnames), \n if strcmp('NaN',allcondnames{i}), whomit(i)=1;, else,whomit(i)=0;,end, \n\n if ~isempty(savelevels)\n for j = 1:length(savelevels)\n if strcmp(savelevels{j},allcondnames{i}), whsave(i)=1;,end, \n end\n end\nend\nwhsave(find(whomit)) = 0;\nwhsave = find(whsave);\nallcondnames = allcondnames(whsave);\nallcondindic = allcondindic(:,whsave);\n% we would remove contrasts with none of the tasks here if we wanted to\n% depends if you want to compute probs over all contrasts or only eligible\n% ones\nwh = find(all(allcondindic==0,2));\nallconditions(wh) = [];\nstudynames(wh) = [];\npointcounts(wh,:) = [];\nallcondindic(wh,:) = [];\nconnumbers(wh) = [];\nconindex(wh) = [];\nif exist('PP') == 1, PP(wh,:) = [];, OUT.PP = PP; end\nfprintf(1,'%3.0f Contrasts are not eligible tasks: Removing these.\\n',length(wh))\nwh = [];\n\nif size(studynames,1) == 1, studynames = studynames';, end\n\n% this should now be redundant\n% remove NaN contrasts\n%wh = [];\n%for i = 1:length(allconditions)\n% if isnan(allconditions{i}) | strcmp(allconditions{i},'NaN'),\n% wh(end+1) = i;\n% end\n%end\n%allconditions(wh) = [];\n%studynames(wh) = [];\n%pointcounts(wh,:) = [];\n%allcondindic(wh,:) = [];\n%connumbers(wh) = [];\n%conindex(wh) = [];\n%fprintf(1,'%3.0f Contrasts have NaN values for test field: Removing these.\\n',length(wh))\n%wh = [];\n%for i = 1:length(allcondnames)\n% if isnan(allconditions{i}),\n% wh(end+1) = i;\n% end\n%end\n%allcondnames(wh) = [];\n\n\nxyz = [DB.x DB.y DB.z];\neval(['allcond = DB.' testfield ';']); \ntry, study = DB.Study;, catch, study = DB.study;, end\n\nfprintf(1,'%3.0f Independent contrasts.\\n',length(studynames))\nfprintf(1,'\\n');\n\nOUT.allconditions = allconditions; \nOUT.pointcounts = pointcounts;\nOUT.studynames = studynames;\nOUT.allcondindic = allcondindic;\nOUT.allcondnames = allcondnames;\nOUT.testfield = testfield;\nOUT.connumbers = connumbers;\nOUT.conindex = conindex;\n\n\n% -----------------------------------------------------\n% Sample size weighting stuff (mostly output)\n% -----------------------------------------------------\n\nfprintf(1,'Weighting by sqrt of sample size is ON.\\n');\nfprintf(1,'Sample size statistics:\\n');\nfprintf(1,'\\tTask frequencies\\t');\n\ntask_count = sum(allcondindic > 0); % number of contrasts for each task type\nstr = [repmat('%3.0f\\t',1,size(allcondindic,2))];\nfprintf(1,str,task_count)\nfprintf(1,'\\n')\navgn = nansum(allcondindic) ./ task_count;\nfprintf(1,'\\tAverage N\\t');\nstr = [repmat('%3.2f\\t',1,size(allcondindic,2))];\nfprintf(1,str,avgn)\nfprintf(1,'\\n');\nmaxn = max(allcondindic);\nfprintf(1,'\\t Max N\\t');\nstr = [repmat('%3.0f\\t',1,size(allcondindic,2))];\nfprintf(1,str,maxn)\nfprintf(1,'\\n');\nminn = min(allcondindic(allcondindic>0));\nfprintf(1,'\\tMin N\\t');\nfprintf(1,str,minn)\nfprintf(1,'\\n');\nfprintf(1,'\\n');\n\n% take square root for weighting\n% get avg sqrt(n) to normalize scaling so relative sample sizes are used\nallcondindic = allcondindic .^ .5;\navgn = nansum(allcondindic) ./ task_count;\n\nfor i = 1:length(studynames)\n n = max(allcondindic(i,:)); % sqrt(number of subjects in this contrast)\n wh_task = find(strcmp(allconditions{i},allcondnames));\n rootn(i) = n;\n try\n studyweight(i) = n ./ avgn(wh_task); % sample size weighting by relative sample size\n catch\n studyweight(i) = NaN; % if NaN allconditions\n end\nend\n\n% save sqrt(n) and weight value to apply to contrasts\n% weight is sqrt(n) / avg n within task class\nOUT.rootn = rootn;\nOUT.studyweight = studyweight;\n\n\npause(3)\n\nfprintf(1,'Contrasts and task levels (entries are sqrt of sample size)\\n');\ntask_indicator_table(studynames,allconditions,allcondindic,allcondnames)\n\nreturn\n\n\n\n\n\n\n\n\n\nfunction [allconditions,pointcounts,studynames,allcondindic,allcondnames,conindex,PP] = loadindic(DB,OUT,testfield)\n\nstr = ['[levels,i3,j] = unique(DB.' testfield ');']; eval(str)\n\n% preserve order\n[i2,wh]=sort(i3); levels=levels(wh);\n\nallcondnames = levels';\n\n% -----------------------------------------------------\n% get and check mat file names\n% -----------------------------------------------------\ndisp('Loading *info.mat files: Loading file names');\n% studynames = OUT.studynames; don't do this, rather, re-build study names\n% from ALL mat files; some studynames could be eliminated in some OUT\n% structures.\n\n % d has ALL mat files, sorted\n d = dir(['*info.mat']);\n d = str2mat(d.name);\n d = sort_image_filenames(d);\n \nfor i = 1:size(d,1)\n \n % find name before first _ -- that's studyname\n %wh = find(d(i,:) == '_'); wh = wh(1);\n \n %studynames{i} = d(i:wh-1);\n \n %if findstr(studynames{i},d(i,:))\n % we're OK\n \n %else\n % disp(['Warning!!! ' studynames{i} ' does not appear to be in correct order in file list.'])\n %end\n\nend\n \n% -----------------------------------------------------\n% load mat files and return info\n% -----------------------------------------------------\nfor i = 1:size(d,1)\n \n load(d(i,:))\n \n % find name before first _ -- that's studyname\n wh = find(d(i,:) == '_'); wh = wh(1);\n studynames{i} = d(i,1:wh-1);\n \n str = ['mycon = CONTRAST.' testfield '{1};']; eval(str);\n \n allconditions{i,1} = mycon;\n \n allcondindic(i,1:length(levels)) = 0;\n wh = find(strcmp(mycon,levels));\n allcondindic(i,wh) = CONTRAST.Subjects;\n \n % contrast number\n tmp = nums_from_text(d(i,:));\n tmp(tmp ~= real(tmp)) = [];\n conindex(i,1) = tmp(end);\n \n % point counts (we lose this info)\n pointcounts(i,1) = 1;\n \n % image file name \n str = [studynames{i} '_contrast_' num2str(conindex(i)) '.img']; % name of image\n if ~(exist(str) == 2), \n fprintf(1,['Warning! Image %s does not exist.\\n'],str);,\n \n % try to look for 2nd blank\n wh = find(d(i,:) == '_'); wh = wh(2);\n studynames{i} = d(i,1:wh-1);\n str = [studynames{i} '_contrast_' num2str(conindex(i)) '.img']; % name of image\n disp(['Trying ' str ' instead.'])\n if ~(exist(str) == 2), \n fprintf(1,['Warning! Image %s does not exist.\\n'],str);,\n end\n \n end\n if ~(exist('PP')==1), PP = str;, else, PP = str2mat(PP,str);,end\n \nend\n\nreturn\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "meta_simulate_nonparamchi2.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/meta_simulate_nonparamchi2.m", "size": 1925, "source_encoding": "utf_8", "md5": "ba275fef60ce0f11f1d5e0c20c502c42", "text": "function [p_ste_avg,iterations] = meta_simulate_nonparamchi2(respfreq,numconds,N)\n% [p_ste_avg,iterations] = meta_simulate_nonparamchi2(respfreq,numconds,N)\n%\n% Perform tests on made-up data to determine what the variability in\n% nonparametric chi2 p-value estimates is as a function of the number\n% of iterations in the nonparam_chi2 test.\n%\n% tor wager\n%\n% e.g., to set up data\n%\n%respfreq = .2; % frequency of 'hits' (yesses)\n%numconds = 2; % number of conditions (nominal)\n%N = 50; % number of observations\n\n\n[y,condf] = generate_data(respfreq,numconds,N);\n\n\n% repeat to get STEs\n\niterations = [50 100 200 400 800 1600 3200 6400 12800]; %[500 1000 5000 10000]; %50000];\n\nreps_within_dataset = 30;\ndataset_reps = 30;\n\nfor i = 1:length(iterations)\n\n iter = iterations(i);\n\n e1 = clock;\n fprintf(1,'\\nIterations: %3.0f rep %03d',iter,0);\n\n dataindex = 1; % keeps track of indices of reps that belong to the same dataset\n\n for dataindex = 1:dataset_reps\n\n for j = 1:reps_within_dataset\n\n\n [realchi2,chi2p(j,1)] = nonparam_chi2(y,condf,iter);\n\n fprintf(1,'\\b\\b\\b%03d',reps_within_dataset.*(dataindex-1) + j );\n end\n\n [y,condf] = generate_data(respfreq,numconds,N);\n pste(dataindex,i) = std(chi2p);\n\n\n\n end\n\n p_ste_avg = mean(pste);\n\n p_ste_ste = ste(pste); % std. error across datasets (realizations)\n \n e2 = etime(clock,e1);\n\n fprintf(1,' Time: %3.0f s \\n',e2);\n\nend\n\n% plot data\n\n%tor_fig; plot(iterations,p_ste_avg,'ko-','LineWidth',2); hold on;\n\ntor_fig;\ntor_fill_steplot(pste,'k');\n\nreturn\n\n\n\n\n\nfunction [y,condf] = generate_data(respfreq,numconds,N)\n\nnum_ones = round(N.*respfreq);\ny = zeros(N,1); % data\n\nindx = randperm(N)';\ny(indx(1:num_ones)) = 1;\n\n% equal frequencies in each condition\nnpercond = ceil(N./numconds);\ncondf = [];\nfor i=1:numconds\n\n condf = [condf; i*ones(npercond,1)];\n\nend\n\nreturn\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "nonparam_specificity.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/nonparam_specificity.m", "size": 1480, "source_encoding": "utf_8", "md5": "211be41f3a4d0641c629e04c30701d2d", "text": "function [eff,p,sig,pt_given_a,pt,success,yp] = nonparam_specificity(y,X,iter,varargin)\n% [eff,p,sig,pt_given_a,pt,success,yp] = nonparam_specificity(y,X,iter,[w])\n%\n% weights should be mean = 1\n\nif length(varargin) > 0, w=varargin{1};, else, w=ones(size(y));, end\n\n[n,k] = size(X); % number of obs. and tasks\n\n% weights\ny = y .* w;\n\n[eff,pt,pt_given_a,success] = ptask(y,X,n);\n\n\n% initialize output\nnulleff = zeros(iter,k);\nyp = zeros(size(y,1),iter);\n\nfor i = 1:iter\n yp(:,i) = y(randperm(n));\n \n nulleff(i,:) = ptask(yp(:,i),X,n);\nend\n\np = 1 - (sum(repmat(eff,iter,1) > nulleff) ./ iter);\n \nsig = p <= .05;\n\n\nreturn\n\n\n\nfunction [eff,pt,pt_given_a,success] = ptask(activ_indicator,task_indicator,n)\n\n% activ_indicator can be weighted\n\ntask_count = sum(task_indicator > 0); % number of contrasts for each task type\npt = task_count ./ n; % prob of task x overall -- a fixed quantity depending on studies included\n\n\na = sum(activ_indicator); % activation count\nsuccess = activ_indicator' * task_indicator; % actual number of activations for each task, weighted or not\n % joint p(task, activ) *\n % activ\n\npt_given_a = success ./ a; % prob of task x given activity in region i\n\neff = pt_given_a - pt; % effect size for specificity info given activation\n\nreturn\n "} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "meta_analyze_data.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/meta_analyze_data.m", "size": 8391, "source_encoding": "utf_8", "md5": "99febf8c4567c740dc1c69cc31e35a40", "text": "function varargout = Meta_analyze_data(y,varargin)\n % varargout = Meta_analyze_data(y,varargin)\n %\n % Inputs\n % =========================================================================\n % Weights:\n %'w' % followed by weights\n % Analysis types:\n %'chi2' % weighted chi-square\n %'logistic' % weighted logistic regression\n %\n % Output strings:\n %'table' % print table(s)\n % 'names' % followed by names of regressors for table (logistic)\n %\n % Input types (for chi-square):\n %'X' % followed by indicator matrix for chi2, design matrix for\n % logistic\n %'condf' % followed by integer vector of cell assignments, for chi2\n %\n % by Tor Wager, May 2006\n %\n % Examples\n % =========================================================================\n % y = spm_get_data(DB.PP,[36 24 36]'); % get some data\n % load SETUP names % get regresor names\n %[b,stats,F,p,df1,df2] = meta_analyze_data(y,'X',DB.X,'logistic',DB.studyweight,'table','names',names);\n %\n % load SETUP Xi % get indicator matrix\n % [b,stats,F,p,df1,df2] = meta_analyze_data(y,'X',Xi,'chi2',DB.studyweight,'table');\n %\n % [chi2,df,p,sig,warn,tab,expected,isnonpar] = meta_analyze_data(dat(1:5,:)','X',Xi,'chi2','w',w,'table');\n \n % Programmers' notes\n % Tor Edited July 2011 to remove predictor rows that are zero in all conditions,\n % if any, during chi2 analysis. rare.\n %\n % Edited chi2 on Dec 2011 (tor) to check for full/double matrices and\n % enforce data type.\n \n \n dotable = 0;\n\n for i = 1:length(varargin)\n if isstr(varargin{i})\n switch lower(varargin{i})\n % reserved keywords\n case 'table', dotable = 1;\n case 'chi2', analysistype = 'chi2';\n case 'logistic', analysistype = 'logistic';\n case 'x', inputtype = 'X';, X = varargin{i+1};\n case 'condf', inputtype = 'condf';, condf = varargin{i+1};\n\n % functional commands\n case 'w', w = varargin{i+1};\n case 'names', names = varargin{i+1};\n\n otherwise, warning(['Unknown input string option:' varargin{i}]);\n end\n end\n end\n\n if ~(exist('w')==1), w = ones(size(y, 1), 1); end\n w = w ./ mean(w);\n\n switch analysistype\n case 'chi2'\n % ========================================================\n % Chi-squared\n % ========================================================\n\n switch inputtype\n case 'X'\n % create condf - from meta_logistic_design\n % return condition function (dummy codes) for chi-square test\n [i,j] = find(X);\n [i,s] = sort(i);\n condf = zeros(size(X, 1), 1); % tor edited july 2011 to handle zeros\n condf(i) = j(s);\n wh = condf ~= 0; % wh to include; usually all...\n \n if size(condf,1) ~= size(y,1), error('Condition function does not match data. Design matrix X is probably not a suitable indicator matrix.');, end\n\n if dotable && exist('names')==1\n frequency_tables(y,w,X,names);\n elseif dotable\n disp('Frequency table omitted: no names.');\n end\n\n case 'condf'\n % do nothing\n if dotable,\n disp('Frequency table omitted: Enter indicator matrix to get this.');\n end\n\n otherwise\n disp('Unknown input type. Must be ''X'' or ''condf''');\n end\n\n nvars = size(y,2);\n doupdate = 0;\n if nvars > 100\n doupdate = 1;\n progressbar('init');\n fprintf(1,'Running %3.0f tests: 00000',nvars);\n\n end\n\n [chi2, chi2p, sig, warn, isnonpar] = deal(zeros(1, nvars));\n tab = cell(1, nvars);\n e = cell(1, nvars);\n \n for i = 1:nvars\n %[chi2(i),df,chi2p(i),sig(i),warn(i),tab{i},e{i},isnonpar(i)] = chi2test([y(:,i) condf],'obs',w,1);\n % tor edited july 2011 to omit condf == 0\n \n inputdat = double([y(wh,i) condf(wh)]);\n if issparse(inputdat), inputdat = full(inputdat); end\n \n [chi2(i),df,chi2p(i),sig(i),warn(i),tab{i},e{i},isnonpar(i)] = chi2test(inputdat,'obs',w(wh),1);\n \n if doupdate && mod(i,10)==0, \n fprintf('\\b\\b\\b\\b\\b%05d',i); \n progressbar('update',100*i./nvars);\n end\n\n end\n\n if doupdate\n fprintf('\\b\\b\\b\\b\\b%05d: Done!',nvars);\n end\n \n varargout{1} = chi2; varargout{2} = df; varargout{3} = chi2p; varargout{4} = sig;\n varargout{5} = warn; varargout{6} = tab; varargout{7} = e; varargout{8} = isnonpar;\n\n if dotable\n % print table\n disp('Chi-square table for first data vector')\n wstrings = {'' ', Warning: expected counts < 5.'};\n warnstr = wstrings{warn(1)+1};\n fprintf(1,'Weighted: chi2(%3.0f) = %3.2f, p = %3.4f %s\\n',df(1),chi2(1),chi2p(1),warnstr);\n fprintf(1,'\\n');\n end\n\n case 'logistic'\n % ========================================================\n % Logistic Regression\n % ========================================================\n\n [b,dev,stats]=glmfit(X,[y ones(size(y))],'binomial','logit','off',[],w); % pvals are more liberal than Fisher's Exact!\n\n % omnibus test - R^2 change test\n % --------------------------------------------------------\n sstot = y'*y;\n r2full = (sstot - (stats.resid' * stats.resid)) ./ sstot;\n dffull = stats.dfe;\n\n [br,devr,statsr]=glmfit(ones(size(y)),[y ones(size(y))],'binomial','logit','off',[],w,'off');\n r2red = (sstot - (statsr.resid' * statsr.resid)) ./ sstot;\n dfred = statsr.dfe;\n\n if r2full < r2red, fprintf(1,'Warning!'); r2red = r2full;,drawnow; fprintf(1,'\\b\\b\\b\\b\\b\\b\\b\\b'); end\n [F,op,df1,df2] = compare_rsquare_noprint(r2full,r2red,dffull,dfred);\n\n if dotable\n fprintf(1,'Name\\tBeta\\tt-value\\tp\\t\\n');\n\n names = [{'Intercept'} names];\n for i = 1:length(b)\n\n fprintf(1,'%s\\t%3.2f\\t%3.2f\\t%3.4f\\t\\n', ...\n names{i},b(i),stats.t(i),stats.p(i));\n\n end\n end\n\n varargout{1} = b; varargout{2} = stats; varargout{3} = F; varargout{4} = op;\n varargout{5} = df1; varargout{6} = df2;\n\n\n otherwise\n % ========================================================\n % ???\n % ========================================================\n disp('Unknown analysis type.');\n end\n\n return\n\n\n\n\n\nfunction frequency_tables(y,w,Xi,Xinms)\n\n w = w ./ mean(w);\n W = diag(w); % ./ sum(w));\n %%w(find(y), :); % weights\n\n sumxiu = sum(Xi,1);\n cnt = (Xi'*y)';\n Xi = Xi' * W; % multiply this by data to get weighted avgs\n sumxi = sum(Xi,2);\n wcnt = (Xi*y)';\n\n avg = wcnt; avg = avg ./ sumxi';\n\n fprintf(1,'Unweighted counts and totals\\n');\n for i =1:length(Xinms), fprintf(1,'%s\\t',Xinms{i});, end,fprintf(1,'\\n');\n for i =1:length(Xinms), fprintf(1,'%3.2f\\t',cnt(i));, end,fprintf(1,'\\n');\n for i =1:length(Xinms), fprintf(1,'%3.2f\\t',sumxiu(i));, end,fprintf(1,'\\n');\n\n fprintf(1,'\\nWeighted counts, totals, percentage\\n');\n for i =1:length(Xinms), fprintf(1,'%s\\t',Xinms{i});, end,fprintf(1,'\\n');\n for i =1:length(Xinms), fprintf(1,'%3.2f\\t',wcnt(i));, end,fprintf(1,'\\n');\n for i =1:length(Xinms), fprintf(1,'%3.2f\\t',sumxi(i));, end,fprintf(1,'\\n');\n for i =1:length(Xinms), fprintf(1,'%3.0f\\t',100 .* avg(i));, end,fprintf(1,'\\n');\n fprintf(1,'\\n');\n\n return\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "mask2density.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/mask2density.m", "size": 6660, "source_encoding": "utf_8", "md5": "a32e052314f9961dc1a7726bac60960a", "text": "function dm = mask2density(mask,radius,varargin)\r\n% function dm = mask2density(mask,radius,[opt] searchmask, [opt] sphere_vol)\r\n%\r\n% mask is the mask with ones where activation points are\r\n% radius is in voxels\r\n%\r\n% optional arguments:\r\n% 1 searchmask\r\n% searchmask is the whole brain search space [optional]\r\n% Mask and searchmask must be in same space, with same voxel sizes and dimensions!\r\n% If empty, search mask is ones(size(mask))\r\n%\r\n% 2 sphere_vol\r\n% sphere_vol is optional argument that translates count mask into density mask\r\n% by dividing the number of counts by this value.\r\n%\r\n% structure of functions:\r\n% \t\tvoxel2mask.m\t\t\tlist of coordinates -> mask\r\n%\t\tmask2density.m\t\t\tmask of coords -> density map\r\n%\r\n% for null hypothesis distribution generation:\r\n%\t\tgenerate_rdms.m\tgiven: no. to generate, no. of points, mask size\r\n%\t get_random_mask.m\tgenerate random list of coords\r\n%\t\t\tvoxel2mask.m \r\n%\t\t\tmask2density.m\t\t\tdensity map of null distribution\r\n%\t\t\tspm_write_vol.m\t\twrite output analyze image\r\n%\r\n%\t\tdensity_npm_p.m\t\t\tcluster p-value, and critical k \r\n%\t\t\t\t\t\t\t\t\t\tgiven list of rdm images and threshold u\t\t\t\r\n%\t\t\tcount_clusters.m\t\tdensity map -> no. of points, clusters \r\n%\t\t\t\t\t\t\t\t\t\tat density threshold u\r\n%\t\t\t\t\t\t\t\t\t\tat a range of thresholds (input)\r\n%\t\t\t\t\t\t\t\t\t\treturns the number and avg. size of clusters\r\n%\t\t\tthen finds p value based on distribution and 95% level\r\n\r\nverbose = 0;\r\nif verbose, t1 = clock;, end\r\n\r\nif length(varargin) > 1\r\n sphere_vol = varargin{2};\r\nelse \r\n sphere_vol = 0;\r\nend\r\n\r\nif length(varargin) > 0\r\n searchmask = varargin{1};\r\n if isempty(searchmask), searchmask = ones(size(mask));, end\r\nelse\r\n searchmask = ones(size(mask));\r\nend\r\n\r\nif any(size(mask) - size(searchmask))\r\n error('Mask and searchmask must be of the same dimensions and have the same voxel sizes!')\r\nend\r\n\r\nfmethod = 2;\r\nswitch fmethod\r\ncase 1\r\n% --------------------------------------------------------------------------------------\r\n% * define sphere to convolve with mask\r\n% --------------------------------------------------------------------------------------\r\n% MUCH slower.\r\nsph = get_sphere(radius);\r\ndm2 = convn(mask,sph,'same');\r\n\r\ncase 2\r\n\r\n% --------------------------------------------------------------------------------------\r\n% * define search space: coordinate list of whole mask\r\n% --------------------------------------------------------------------------------------\r\nif verbose, fprintf(1,'defining search space ... '), end\r\n% [x,y,z] = ind2sub(size(searchmask),find(searchmask)); % find coords of values > 0 in mask\r\n[x,y,z] = ind2sub(size(mask),find(searchmask > 0)); % find coords of values > 0 in mask\r\nvindex = [x y z]';\r\n\r\n% old way: slower\r\n% vindex = build_voxel_index(mask);\r\n\r\nQ = ones(1,size(vindex,2));\r\ndm = zeros(size(mask));\r\nslices = vindex(3,:); % used to pass only certain slices to subfunctions\r\n\n\r\n% --------------------------------------------------------------------------------------\r\n% * locate coordinates in mask to make spheres around\r\n% --------------------------------------------------------------------------------------\r\n[x,y,z] = ind2sub(size(mask),find(mask)); % find coordinates of values > 0 in mask\r\nvr = [x y z]';\r\n\r\nif verbose, fprintf(1,'\\nrestricting to spheres around %3.0f points ... ',size(vr,2)), end\r\n\r\n% the idea here is to pass into add_density_sphere only coordinates\r\n% that are in slices that could possibly be within the sphere, to speed things up.\r\n% this next line tells us when we need to update to new slices\r\n% when the slice changes, we need a new set of slices to pass to add_density_sphere\r\n% vr should already be sorted ascending wrt slices, so no need to sort again.\r\nupd = [1 diff(vr(3,:)) > 0];\r\n\r\nfor i = 1:size(vr,2) % for each reported point...\r\n \r\n if upd(i)\r\n vin = vindex(:,slices <= vr(3,i) + radius & slices > vr(3,i) - radius); % these are coordinates that may be in-sphere\r\n end\r\n \r\n count = mask(vr(1,i),vr(2,i),vr(3,i)); \r\t\t\t\t\t\t\t\t\t\t% get count at this point\n dm = add_density_sphere(vr(:,i),vin,Q,count,dm,radius); % add density to sphere around this point\r\nend\r\n\r\n% --------------------------------------------------------------------------------------\r\n% * turn into density -> count per unit area of sphere \r\n% --------------------------------------------------------------------------------------\r\nif sphere_vol\r\n dm = dm ./ sphere_vol;\r\nend\r\n\r\nif verbose, \r\n t2 = clock;\r\n fprintf(1,'\\ndone in %3.0f s!',etime(t2,t1))\r\nend\r\n\r\nend\r\n\r\nreturn\r\n\r\n\r\n\r\n\r\n\r\n% Sub-functions\r\n% --------------------------------------------------------------------------------------\r\nfunction vindex = build_voxel_index(mask)\r\n% NOT USED\r\nrows = size(mask,1);\r\ncols = size(mask,2);\r\na = []; b = []; c = []; vindex = [];\r\nfor i = 1:cols\r\n a = [a 1:rows];\r\n b = [b i * ones(1,rows)];\r\nend\r\nc = [a;b];\r\nfor i = 1:size(mask,3)\r\n c(3,:) = i;\r\n vindex = [vindex c];\r\nend\r\nreturn\r\n\r\n\r\nfunction [dens,j] = get_density(coord,vindex,Q,mask,radius,sphere_vol)\r\n % NOT USED\r\n % j is index numbers of in-sphere coordinates\r\n % this line is slow for big vindexes (1 mil). 4.17 s\r\n j = find(sum((vindex - coord*Q).^2) <= radius2);\r\n\r\n %\ttotal = length(j) * voxel_vol;\r\n count = sum(mask(j) > 0);\r\n dens = count / sphere_vol;\r\nreturn\r\n\r\n\r\nfunction [dm,j] = add_density_sphere(coord,vindex,Q,count,dm,radius)\r\n % j is index numbers of in-sphere coordinates\r\n % coord is coordinate of sphere center\r\n % vindex is XYZ index of all slices in the vicinity\r\n % Q is ones of (3,length vindex)\r\n % count is the number of counts at the sphere center\r\n \r\n j = find(sum((vindex - coord*Q(:,1:size(vindex,2))).^2) <= radius^2);\r\n\r\n % turn index of restricted vindex space back to whole-mask coordinates\r\n XYZ = vindex(:,j);\r\n ind = sub2ind(size(dm),XYZ(1,:),XYZ(2,:),XYZ(3,:));\r\n \r\n % add the mask value at the point to voxels in sphere; mask may be > 1\r\n % do not divide by sphere_vol - instead, do this at the end.\r\n dm(ind) = dm(ind) + count;\r\n \r\n \r\nreturn\r\n\r\n\r\nfunction sph_mask = get_sphere(radius)\r\n % returns spherical mask in 3-d array, with unit density in elements\r\n % NOT USED\r\n sph_mask = zeros(2*radius+1,2*radius+1,2*radius+1);\r\n vindex = build_voxel_index(sph_mask);\r\n Q = ones(1,size(vindex,2));\r\n sph_mask(radius,radius,radius) = 1;\r\n [dens,j] = get_density([radius;radius;radius],vindex,Q,sph_mask,radius);\r\n sph_mask(j) = dens;\r\nreturn\r\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Task_Indicator.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/Meta_Task_Indicator.m", "size": 4270, "source_encoding": "utf_8", "md5": "97f534f1e8359a2453f84bc20b886ea1", "text": "function [Xi,alltasknms,condf,allti,testfield,prop_by_condition,num_by_condition] = Meta_Task_Indicator(DB,varargin)\n% [Xi,alltasknms,condf,allti,testfield,prop_by_condition,num_by_condition] = Meta_Task_Indicator(DB,[data])\n%\n% Get task indicators and number / proportion of activating contrasts from DB\n%\n% needs to set up design:\n%DB.(fields) % lists of fields containing task conditions for each coordinate point\n%DB.Contrast\n%DB.connumbers\n%\n% Example:\n% [Xi,alltasknms,condf,allti,testfield,prop_by_condition,num_by_condition]\n% ... = Meta_Task_Indicator(DB,MC_Setup.unweighted_study_data);\n%\n% tor wager\n% Created: 8/23/06\n\nglobal dolist\ndolist = 1;\n\nif length(varargin) > 0,\n data = varargin{1};\nend\n\n% -----------------------------------------------------\n% Select conditions and build design matrix\n% -----------------------------------------------------\n\ntestfield = 'xxx';\nX = []; Xnms = {}; allti = []; alltasknms = [];\n\nwhile ~isempty(testfield)\n \n % get field name and save for later display (image)\n testfield = getfield(DB); \n \n if isempty(testfield), \n % done\n else\n \n testfield1 = testfield;\n \n % check to see if each contrast has only one level\n meta_check_contrasts(DB,testfield)\n \n % get unique levels\n levels = getlevels(DB,testfield);\n\n % get indicators for these levels\n [ti,tasknms] = string2indicator(DB.(testfield),levels); \n \n allti = [allti ti];\n alltasknms = [alltasknms tasknms];\n\n end\n \nend\nfprintf(1,'\\n'); fprintf(1,'\\n');\n\n% -----------------------------------------------------\n% allti is coords x tasks. Convert to contrasts x tasks\n% -----------------------------------------------------\n\nntasks = size(allti,2);\nncons = length(DB.connumbers);\nXi = zeros(ncons,ntasks);\n\nfor i = 1:ncons\n % which points in this contrast\n wh = DB.Contrast == DB.connumbers(i); \n\n % indicators for this study\n ti = allti(wh,:);\n \n % resolve conflicts by taking the modal values\n % conflicts may be a sign of probs with database\n Xi(i,:) = mode(ti);\n\nend\n\n \n% return condition function (dummy codes) for chi-square test\n[i,j] = find(Xi);\n[i,s] = sort(i); \ncondf = j(s);\n\n% -----------------------------------------------------\n% Re-do Final contrast weights\n% -----------------------------------------------------\n\nif isfield(DB,'SubjectiveWeights'),\n w = DB.rootn .* DB.SubjectiveWeights(DB.pointind);\nelse\n w = DB.rootn;\nend\n\n% these must sum to 1 ! (they will be re-normed in Meta_Logistic, but\n% summing to 1 is the standard weighting used in other parts of the\n% software.)\nDB.studyweight = w ./ sum(w);\n\n\n% -----------------------------------------------------\n% Get proportions by condition\n% -----------------------------------------------------\nprop_by_condition = [];\nif exist('data','var')\n [icon,ctxtxi,betas,num_by_condition,prop_by_condition] = meta_apply_contrast(data,Xi,w,ones(1,size(Xi,2)));\nend\n\n\n\nreturn\n\n\n\n\n\n\nfunction testfield = getfield(DB)\n% Empty or field name from DB\nglobal dolist\n\n% list field names\nfprintf(1,'Database field names\\n---------------------------\\n')\nN = fieldnames(DB);\nif dolist\n for i = 1:length(N),\n tmp = DB.(N{i}); len = length(tmp);\n if len == length(DB.x), fprintf(1,'%s\\n',N{i});end\n end\n\n fprintf(1,'\\n');\n dolist = 0;\nend\n\ngook = [];\nwhile isempty(gook)\n testfield = input('Enter field name or return if finished: ','s');\n\n if isempty(testfield)\n gook = 1;\n else\n gook = strmatch(testfield,N);\n if ~isempty(gook)\n gook = strcmp(testfield,N{gook}); \n if ~gook, gook = []; end\n end %exact match\n end\n if isempty(gook), fprintf(1,'Not a field name.'); pause(1); fprintf('\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b'); end\nend\n\nreturn\n\n\n\n\n\nfunction levels = getlevels(DB,testfield);\n\neval(['levels = DB.' testfield ';']);\nlevels = levels(DB.pointind);\n[pts,ind] = unique(levels);\n\nfprintf(1,'Unique values of this variable:\\n');\n\nfor i = 1:size(pts,1), \n [num] = meta_count_contrasts(DB,testfield,pts{i});\n fprintf(1,'%3.0f\\t%s\\t%3.0f Contrasts\\n',i,pts{i},num);\nend\nwh = input('Enter vector of levels to use: ');\nlevels = pts(wh);\n\nreturn\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "meta_count_contrasts.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/meta_count_contrasts.m", "size": 1072, "source_encoding": "utf_8", "md5": "13344e2c45dc1e1751b1778d6a67020a", "text": "% [num, wh, weighted_num, conindx] = meta_count_contrasts(DB, testfield, fieldvalue)\n%\n% e.g., testfield = 'Stimuli'\n% fieldvalue = 'faces';\n% [num, wh] = meta_count_contrasts(DB, testfield, fieldvalue)\n\nfunction [num, wh, weighted_num, conindx] = meta_count_contrasts(DB, testfield, fieldvalue)\n\n wh = strcmp(DB.(testfield), fieldvalue);\n [u, i] = unique(DB.Contrast(wh));\n num = length(u);\n\n conindx = zeros(length(DB.connumbers), 1);\n %conindx(i) = 1;\n\n if nargout > 2\n % weighted total\n for i = 1:length(u)\n tmp = find(DB.connumbers == u(i)); % the index in contrast list for this con number\n if isempty(tmp), disp('Warning! No contrast-list entry for existing contrast number. Was DB modified?');, end\n whcons(i) = tmp;\n\n % save list of indices\n conindx(tmp) = 1; %DB.connumbers(tmp)) = 1;\n end\n\n if isempty(u), weighted_num = 0;, return, end\n\n w = DB.studyweight;\n w = w ./ mean(w);\n w = w(whcons);\n weighted_num = sum(w);\n end\nend"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "xyz2density.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/xyz2density.m", "size": 2991, "source_encoding": "utf_8", "md5": "57225e0fc112e28248438a648c1cefa1", "text": "function conmask = xyz2density(XYZmm,mask,V,str,radius,studyweight,varargin)\n% conmask = xyz2density(XYZmm,mask,V,str,radius,studyweight,[enter vox xyz flag] AND [no write image])\n% \n% Take a list of xyz mm coordinates and turn it into a density mask\n% with spherical convolution.\n% \n% XYZmm: n x 3, mask = zeros of correct dims, V = mapped volume (SPM),\n% str = name of output image\n% radius: sphere radius in voxels\n%\n% last args: enter anything are to enter coords in voxels and suppress write output\n% for p0_monte_carlo_FWE, to construct a fast density map of random\n% coordinates\n\nXYZmm(any(isnan(XYZmm),2),:) = [];\n\nif isempty(XYZmm)\n conmask = mask;\n \n \nelse\n if length(varargin) > 0\n XYZvox = XYZmm;\n else\n XYZvox = mm2vox(XYZmm,V.mat); % get voxel coordinates\n end\n \n conmask = xyz2mask(mask,XYZvox); % put points in mask - could weight by Z-scores here, if desired.\n \n % -----------------------------------------------------\n % * convert to density mask\n % * write density mask before thresholding\n % -----------------------------------------------------\n conmask = mask2density(conmask,radius);\n\n conmask(conmask > 1) = 1; % limit to max of 1, in case multiple nearby points in same contrast\n % max activation for a single\n % contrast is 1.\n\n conmask = conmask .* studyweight; % sample size weighting by sqrt relative sample size\nend\n \nif length(varargin) > 0\n return\nelse\n V.fname = str;\n warning off, spm_write_vol(V,conmask);, warning on\nend\n\n\nreturn\n\n\n\n\n\n% -----------------------------------------------------\n% * sub-functions\n% -----------------------------------------------------\n\nfunction XYZout = mm2vox(XYZ,M)\n% converts a list of coordinates\n% XYZ should be 3-column vector [x y z]\n% calls tal2vox\n\nXYZ = XYZ';\nfor i = 1:size(XYZ,2), \n\tXYZout(i,:) = tal2vox(XYZ(:,i),M); \nend\n\nXYZout = round(XYZout);\n\nreturn\n\n\n\n% -----------------------------------------------------\nfunction vox=tal2vox(tal,M)\n% converts from talairach coordinate to voxel coordinate\n% based on variables from SPM.M (passed here for \n% faster operation)\n% e.g., foo=tal2vox([-30 28 -30], VOL)\n% from Russ Poldrack's spm ROI utility \n\nvox=[0 0 0];\nvox(1)=(tal(1)-M(1,4))/M(1,1);\nvox(2)=(tal(2)-M(2,4))/M(2,2);\nvox(3)=(tal(3)-M(3,4))/M(3,3);\n\nreturn\n\n\n\n\nfunction mask = xyz2mask(mask,XYZ)\n\n% -----------------------------------------------------\n% * make a mask out of XYZ, in space of P\n% * deal with repeated coordinates by adding\n% -----------------------------------------------------\n\ntry\n ind = sub2ind(size(mask),XYZ(:,1),XYZ(:,2),XYZ(:,3));\ncatch\n warning('FOUND POINTS OUTSIDE OF IMAGE? RETURNING EMPTY MASK.');\n XYZ\n ind = [];\nend\n\nmask(ind) = 1;\n\nind = sort(ind);\nrepeats = ind(find(~diff(ind))); % index values that are repeated\nfor i = 1:length(repeats)\n mask(repeats(i)) = mask(repeats(i)) + 1;\nend\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "chi2test.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/chi2test.m", "size": 5080, "source_encoding": "utf_8", "md5": "c1c3372e63d347f6744cbf34b5cc2908", "text": "% [chi2,df,p,sig,warn,freq_table,expected_table,isnonparametric] = chi2test(counts,datatype,[obs. weights],[nonpar flag])\n%\n% Weighted or unweighted Chi-square test \n% from frequency (contingency) table or rows of observations\n% Optional nonparametric estimation for questionable results\n%\n%\n% Takes either tabular (frequency) data or rows of observations\n% (integer data, i.e., 1s and 0s or dummy codes for categories)\n% Makes table:\n% rows are No (top) then Yes (bottom)\n% columns are variables in counts\n%\n% Datatype: is 'table' or 'obs' for tabular data or rows of observations\n% if obs, then 1st column is response (1/0 for yes/no) and 2nd col. is\n% condition assignment (coded by intergers)\n%\n% Table:\n% rows are conditions\n% columns are measures\n% e.g., rows are students/nonstudents, columns are number reading and\n% number watching TV\n% OR\n% rows are tasks, columns are \"Yesses\" and \"Nos\"\n%\n% Weights option: Weights should have a mean of one to retain\n% interpretation of weighted counts\n% Weights option only works for 'obs' datatype right now!\n%\n% % nonparametric option: if chi2 assumptions violated (any expected < 5)\n% and p < .2, do nonparametric chi2\n%\n% WARNING:\n% Weighted chi-square alpha level is not correct without nonparametric\n% test; degrees of freedom adjustment due to weights is not made.\n%\n% E.g.\n% Two columns in counts, each is either 0 or 1\n% Runs chi-sq test for independence between v1 and v2\n%\n% Two columns in counts, one is response (0 or 1), one is dummy coded (1 2\n% 3)\n% Runs chi-sq test for homogeneity in the response across levels of the\n% dummy-coded variable.\n%\n% tor wager\n% tested simple examples against SPSS, Jan 23, 06\n%\n% [chi2,df,chi2p,sig,warn,tab,e] = chi2test([y condf],'obs'); \n% \n% Example of nonparametric chi2:\n% [chi2,df,p,sig,warn,counts,e,isnonparametric] = chi2test([1 1 1 1 0 0 0 0; 1 2 1 1 2 2 2 2]', 'obs', [], 1);\n%\n% another example, with text print-out of results:\n% [chi2,df,p,sig,warn,counts,e,isnonparametric] = chi2test([x diso], 'obs', w, 1);\n% fprintf('Chi2 output: chi2: \\t%3.2f\\t df \\t%3.2f\\t p \\t%3.6f\\t \\n', chi2, df, p);\n\n\n% SIMULATION CODE\n% -------------------------------------------------------------------------\n% nonparametric option: if chi2 assumptions violated (any expected < 5) or\n% p < .15, do nonparametric chi2\n\n% Simulations: Test FPR\n% %%\n% p = .2; n = 50;\n% \n% niter = 1000;\n% pp = zeros(niter, 1);\n% \n% sig = zeros(niter, 1);\n% \n% \n% for i = 1:niter\n% data = binornd(1, p, n, 2);\n% [chi2,df,pp(i),sig(i)] = chi2test(data,'obs',[],0);\n% \n% end\n% \n% sum(sig) ./ niter\n% \n% %%\n% p = .2; n = 50;\n% \n% niter = 1000;\n% pp = zeros(niter, 1);\n% ppols = zeros(niter, 1);\n% \n% sig = zeros(niter, 1);\n% sigols = zeros(niter, 1);\n% \n% for i = 1:niter\n% data = binornd(1, p, n, 2);\n% w = rand(n, 1);\n% w = w ./ repmat(mean(w), n, 1);\n% \n% [chi2,df,ppols(i),sigols(i)] = chi2test(data,'obs',w,0);\n% \n% [chi2,df,pp(i),sig(i)] = chi2test(data,'obs',w,1);\n% \n% end\n\nfunction [chi2,df,p,sig,warn,counts,e,isnonparametric] = chi2test(counts,datatype,varargin)\n\nw = [];\ndononpar = 0;\nif length(varargin) > 0\n w = varargin{1}; \n \nend % weights for observations; optional\n\nif length(varargin) > 1, dononpar = varargin{2}; end\n\n% This warning cannot be done here because chi2test is called recursively\n% during nonparam_chi2.m\n%if ~dononpar, warning('Weighted chi-square alpha level is not correct without nonparametric test; degrees of freedom adjustment due to weights is not made.'); end\n \nif isempty(w)\n % Only used for 'obs' below\n w = ones(size(counts(:,1)));\nend\n \n% cross-tabulate, if necessary\nswitch datatype\n case 'obs'\n\n u1 = unique(counts(:,1));\n u2 = unique(counts(:,2));\n for i = 1:length(u1) % rows are 0 then 1 on the first var, \"Nos\" then \"Yesses\"\n for j = 1:length(u2) % for each column\n tab(i,j) = sum( (counts(:,1) == u1(i) & counts(:,2) == u2(j)) .* w );\n end\n end\n \n % save original data if nonparametric option is asked for\n if dononpar, y = counts(:,1); condf = counts(:,2); end\n \n counts = tab;\n\n case 'table'\n % do nothing, counts already == crosstabs table\n if dononpar, error('Nonparametric option only works with datatype ''obs'''); end\n\n otherwise\n error('Datatype must be ''obs'' or ''table''');\nend\n\n\ns = sum(counts(:));\n\nrowmarg = sum(counts,2) ./ s; % marginal proportions for rows\ncolmarg = sum(counts,1) ./ s; % marginal proportions for columns\n\ne = rowmarg * colmarg .* s; % expected counts\n\nd = (counts - e).^2 ./ e;\nchi2 = sum(d(:));\n\nif nargout > 1\n\n warn = 0; % warning for low expected counts (< 5)\n\n df = (size(counts,1)-1) .* (size(counts,2)-1);\n if any(e(:) < 5), warn = 1; end\n\n p = 1 - chi2cdf(chi2,df);\n sig = p < .05;\n\n isnonparametric = 0;\n if dononpar && p < .15 %% && warn && p < .15\n [chi2,p,sig] = nonparam_chi2(y,condf,1000,w);\n isnonparametric = 1;\n end\n \nend\n\nreturn"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_Prune.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/Meta_Prune.m", "size": 2115, "source_encoding": "utf_8", "md5": "aa7f1868008aadb6c3fae1f7a820fa25", "text": "function DB = Meta_Prune(DB,include)\n% DB = Meta_Prune(DB,include)\n% \n% Prunes database given an indicator vector of points (peaks) to include\n% Includes only contrasts for which ALL peaks are included!\n% Thus, if any peaks are excluded, the whole contrast is excluded.\n%\n% Called in Meta_Select_Contrasts and Meta_Logistic_Design\n%\n% Used\n\n\n% exclude any contrast with 1 or more points that are excluded.\n\n\nexclude_points = include < 1;\n\n% get contrast numbers to exclude\nex_connums = unique(DB.Contrast(exclude_points));\n\n\n% get larger set of exclude points that excludes contrast-by-contrast\nexclude_points = [];\nfor i = 1:length(ex_connums)\n wh = find(DB.Contrast == ex_connums(i));\n exclude_points = [exclude_points; wh];\nend\n \n% get indices in pointind to exclude\n% exclude these indices in anything of length CONTRASTS\nex_conind = [];\nfor i = 1:length(ex_connums)\n wh = find(DB.connumbers == ex_connums(i));\n ex_conind = [ex_conind; wh];\nend\n\n% include indices\ninclude_points = ones(size(include)); include_points(exclude_points) = 0;\ninclude_cons = ones(size(DB.connumbers)); include_cons(ex_conind) = 0;\n\nDB = prunedb(DB,include_points,include_cons);\n\nDB.included_from_original = include_points;\nDB.included_cons = include_cons;\n\nfprintf(1,'Selected: %3.0f points, %3.0f contrasts, %3.0f studies.\\n',length(DB.x),length(DB.connumbers),length(unique(DB.study)));\n\n\nreturn\n\n\n\n\n\nfunction DB = prunedb(DB,include,inc_con)\n% Empty or field name from DB\n\nN = fieldnames(DB);\nwhp = find(include);\nwhc = find(inc_con);\n\n% special for DB.pointind\npind = zeros(size(DB.x)); pind(DB.pointind) = 1;\npind = pind(whp);\n\nfor i = 1:length(N)\n \n tmp = DB.(N{i}); len = length(tmp);\n if isnumeric(tmp), len = size(tmp,1); end\n \n if len == length(include), \n DB.(N{i}) = tmp(whp);\n elseif len == length(inc_con)\n if isnumeric(tmp)\n DB.(N{i}) = tmp(whc,:);\n else\n DB.(N{i}) = tmp(whc);\n end\n end\n \nend\n\n% re-make pointind\nfor i = 1:length(DB.connumbers)\n wh = find(DB.Contrast == DB.connumbers(i));\n DB.pointind(i) = wh(1);\nend\n\n\nreturn"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "meta_chi2_matrix.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/meta_chi2_matrix.m", "size": 2102, "source_encoding": "utf_8", "md5": "e89010ab138b590ac39d5a9644337c7c", "text": "function out = meta_chi2_matrix(dat,w)\n\nw = w ./ mean(w);\nmyalpha = .05;\n\n [N,npairs] = size(dat);\n\n\n [rows,cols,ncorr] = corrcoef_indices(npairs);\n \n str = sprintf('Computing differences among correlations %04d',0); fprintf(1,str);\n\n chi2 = zeros(ncorr,1);\n chi2p = zeros(ncorr,1);\n diffr = zeros(ncorr,1);\n asym = zeros(ncorr,1);\n %sig = zeros(ncorr,2);\n\n for cc = 1:ncorr\n\n fprintf(1,'\\b\\b\\b\\b%04d',cc);\n\n d = [dat(:,rows(cc)) dat(:,cols(cc))];\n [chi2(cc),df,chi2p(cc),sig,warn,tab,e] = chi2test(d,'obs',w,1);\n\n % weighted # activations for each column\n rsum = sum(tab);\n csum = sum(tab,2);\n yesses = [csum(2) rsum(2)];\n\n % signed measure of association; diff from expected\n diffr(cc) = (tab(2,2) - e(2,2)) ./ (min(yesses) - e(2,2)); \n \n % asymmetry: \n a = [tab(2,1) tab(1,2)] ./ yesses; % proportion unique (nonshared) in each col\n asym(cc) = diff(a) ./ sum(a);\n end\n\n erase_string(str);\n\n\n chi2 = reconstruct(chi2,npairs,ncorr,rows,cols);\n p = reconstruct(chi2p,npairs,ncorr,rows,cols);\n\n diffr = reconstruct(diffr,npairs,ncorr,rows,cols);\n asym = reconstruct(asym,npairs,ncorr,rows,cols);\n \n sig = (p <= myalpha - eye(size(p))) .* sign(diffr);\n\n % FDR corrected\n pthr = FDR(chi2p,.05);\n if isempty(pthr), pthr = 0; end\n\n sigfdr = (p <= pthr) .* sign(diffr);\n\n out = struct('alpha',myalpha,'diffr',diffr,'asym',asym,'chi2',chi2, ...\n 'p',p,'sig',sig,'pthr',pthr,'sigfdr',sigfdr);\n \n \n \n \n \nfunction [rows,cols,ncorr] = corrcoef_indices(npairs)\n % upper triangle only\n tmp = triu(ones(npairs));\n tmp = tmp - eye(npairs);\n [rows,cols] = find(tmp);\n ncorr = length(rows);\n return\n \n \n \nfunction valmat = reconstruct(vals,npairs,ncorr,rows,cols)\n\n valmat = zeros(npairs);\n for i = 1:ncorr\n valmat(rows(i),cols(i)) = vals(i);\n end\n valmat = valmat + valmat';\n\n return\n\n\n\nfunction erase_string(str1)\n fprintf(1,repmat('\\b',1,length(str1))); % erase string\n return\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "chi2test_massive.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/chi2test_massive.m", "size": 5580, "source_encoding": "utf_8", "md5": "a3bf795f3ded356e5d3ed47bc091c458", "text": "% [chi2,df,p,sig,warn,isnonparametric] = chi2test_massive(seedcounts, counts,[obs. weights],[nonpar flag])\n%\n% Weighted or unweighted Chi-square test\n% from observations\n% Optional nonparametric estimation for questionable results\n% SEE CHI2TEST.M\n% THE PURPOSE OF THIS FUNCTION IS TO IMPLEMENT A CHI2 TEST EFFICIENTLY WITH\n% A MASSIVE NUMBER OF OUTCOME VARIABLES\n%\n% Inputs:\n% seedcounts = a vector of 1's and 0's, N obs x 1, for yes and no counts from seed variable.\n% counts = a vector of 1's and 0's for N obs x k variables (e.g., brain voxels)\n%\n% Takes rows of observations\n% (integer data, i.e., 1s and 0s or dummy codes for categories)\n% Makes table:\n% rows are No (top) then Yes (bottom) in \"seed counts\" data vector\n% columns are variables in counts\n%\n% Weights option: Weights should have a mean of one to retain\n% interpretation of weighted counts\n%\n% % nonparametric option: if chi2 assumptions violated (any expected < 5)\n% and p < .2, do nonparametric chi2\n%\n% WARNING:\n% Weighted chi-square alpha level is not correct without nonparametric\n% test; degrees of freedom adjustment due to weights is not made.\n%\n% E.g.\n% Two columns in counts, each is either 0 or 1\n% Runs chi-sq test for independence between v1 and v2\n%\n% Two columns in counts, one is response (0 or 1), one is dummy coded (1 2\n% 3)\n% Runs chi-sq test for homogeneity in the response across levels of the\n% dummy-coded variable.\n%\n% tor wager\n%\n% Examples:\n% [chi2,df,chi2p,sig,warn,tab,e] = chi2test([y condf],'obs');\n%\n% Example of nonparametric chi2:\n% [chi2,df,p,sig,warn,counts,e,isnonparametric] = chi2test([1 1 1 1 0 0 0 0; 1 2 1 1 2 2 2 2]', 'obs', [], 1);\n%\n% another example, with text print-out of results:\n% [chi2,df,p,sig,warn,counts,e,isnonparametric] = chi2test([x diso], 'obs', w, 1);\n% fprintf('Chi2 output: chi2: \\t%3.2f\\t df \\t%3.2f\\t p \\t%3.6f\\t \\n', chi2, df, p);\n\n\n% SIMULATION CODE\n% -------------------------------------------------------------------------\n% nonparametric option: if chi2 assumptions violated (any expected < 5) or\n% p < .15, do nonparametric chi2\n\n% Simulations: Test FPR\n% %%\n% p = .2; n = 50;\n%\n% niter = 1000;\n% pp = zeros(niter, 1);\n%\n% sig = zeros(niter, 1);\n%\n%\n% for i = 1:niter\n% data = binornd(1, p, n, 2);\n% [chi2,df,pp(i),sig(i)] = chi2test(data,'obs',[],0);\n%\n% end\n%\n% sum(sig) ./ niter\n%\n% %%\n% p = .2; n = 50;\n%\n% niter = 1000;\n% pp = zeros(niter, 1);\n% ppols = zeros(niter, 1);\n%\n% sig = zeros(niter, 1);\n% sigols = zeros(niter, 1);\n%\n% for i = 1:niter\n% data = binornd(1, p, n, 2);\n% w = rand(n, 1);\n% w = w ./ repmat(mean(w), n, 1);\n%\n% [chi2,df,ppols(i),sigols(i)] = chi2test(data,'obs',w,0);\n%\n% [chi2,df,pp(i),sig(i)] = chi2test(data,'obs',w,1);\n%\n% end\n\nfunction [chi2,df,p,sig,warn,isnonparametric] = chi2test_massive(seedcounts, counts,varargin)\n\nw = [];\ndononpar = 0;\nif length(varargin) > 0\n w = varargin{1};\n \nend % weights for observations; optional\n\nif length(varargin) > 1, dononpar = varargin{2}; end\n\n% This warning cannot be done here because chi2test is called recursively\n% during nonparam_chi2.m\n%if ~dononpar, warning('Weighted chi-square alpha level is not correct without nonparametric test; degrees of freedom adjustment due to weights is not made.'); end\n\nif isempty(w)\n % Only used for 'obs' below\n w = ones(size(counts(:,1)));\nend\n\ndisp('Checking data')\nn = size(seedcounts, 1);\nif n < length(seedcounts), error('seed variable must be column vector'); end\n\nif length(unique(seedcounts)) > 2, error('Seed counts must be 1 or 0 values'); end\nif length(unique(counts(:))) > 2, error('Data matrix counts must be 1 or 0 values'); end\n\n% data\n% rows are 0 then 1 on the first var, \"Nos\" then \"Yesses\"\n\ndisp('Getting counts')\n\nmydat = counts(seedcounts == 0, :);\nnono = sum(mydat == 0);\nnoyes = sum(mydat == 1);\n\nmydat = counts(seedcounts == 1, :);\nyesno = sum(mydat == 0);\nyesyes = sum(mydat == 1);\n\n%totalcount = nono + noyes + yesno + yesyes; = n\n\n% expectations\ndisp('Calculating expectations')\n\nseedpropno = 1 - (sum(seedcounts) ./ n);\nseedpropyes = sum(seedcounts) ./ n;\n\npropno = sum(counts == 0) ./ n;\npropyes = sum(counts == 1) ./ n;\n\nexpnono = seedpropno .* propno .* n; %expected value for all 4 cells of indepndence chi-sq\nexpnoyes = seedpropno .* propyes .* n;\n\nexpyesno = seedpropyes .* propno .* n;\nexpyesyes = seedpropyes .* propyes .* n;\n\n% chi-square\ndisp('Calculating chi-square stats')\n\nchinono = (nono - expnono) .^ 2 ./ expnono;\nchinoyes = (noyes - expnoyes) .^ 2 ./ expnoyes;\nchiyesno = (yesno - expyesno) .^ 2 ./ expyesno;\nchiyesyes = (yesyes - expyesyes) .^ 2 ./ expyesyes;\n\nchi2 = sum([chinono; chinoyes; chiyesno; chiyesyes]);\nchi2 = full(chi2);\n\nif nargout > 1\n \n df = ones(1, size(counts, 2));\n \n warn = full(any([expnono; expnoyes; expyesno; expyesyes] < 5));\n \n p = 1 - chi2cdf(chi2, df);\n sig = p < .05;\n \n isnonparametric = zeros(1, size(counts, 2));\n badchi2 = warn & p < .15;\n \n fprintf('Variables with close to sig chi-square that violate assumptions: %3.0f\\n', sum(badchi2));\n \n if dononpar && any(badchi2)\n \n fprintf('Calculating nonparametric values for variables that violate assumptions: 00000\\n');\n wh = find(badchi2);\n \n for i = 1:length(wh)\n \n v = badchi2(i);\n \n [chi2(v),p(v),sig(v)] = nonparam_chi2(y,condf,1000,w);\n isnonparametric(v) = 1;\n \n fprintf('\\b\\b\\b\\b\\b%3.5f', i);\n \n end\n \n fprintf('\\n')\n end\n \nend % if nargout > 1\n\nreturn"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "fishers_exact.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/fishers_exact.m", "size": 1475, "source_encoding": "utf_8", "md5": "a5858286293f09391bfb7ceecb955ec6", "text": "function [p,pobs] = fishers_exact(tab)\n%\n% m x n generalization of Fisher's exact test\n%\n% See Agresti, 1992. Exact inference for contingency tables. Statistical\n% Science\n%\n% Eric W. Weisstein. \"Fisher's Exact Test.\" From MathWorld--A Wolfram Web\n% Resource. http://mathworld.wolfram.com/FishersExactTest.html\n%\n% Input: contingency table\n% Output: p-value for Fisher's exact test\n%\n% This was abandoned in development because listing possibilities for more than 2 x 2 tables\n% with even modest sample sizes seems computationally infeasible.\n%\n% see nonparam_chi2.m\n% Tor Wager, May 2006\n\np = [];\n\nrowsum = sum(tab,2); colsum = sum(tab,1);\nN = sum(colsum);\n\npobs = get_observed_p(tab,N,rowsum,colsum);\n\n\n% now we need to find tables whose chi2 values are at least as high as the\n% observed one, and sum pobs for these tables.\n\n%tables = list_possible_tables(tab,rowsum,colsum);\n\n\n\n\n\nfunction p = get_observed_p(tab,N,rowsum,colsum)\n% hypergeometric distribution given a parameter value of 1 (independence)\n\nnumer = prod([factorial(rowsum') factorial(colsum)]);\n\ndenom = prod([factorial(N) factorial(tab(:)')]);\np = numer/denom;\n\nreturn\n\n\n\nfunction tables = list_possible_tables(tab,rowsum,colsum);\n\n[r,c] = size(tab);\n\ntotaln = prod(rowsum);\nfor i = 1:r\n % for each row, get possible values\n % num values = rowsum\n c = [0:rowsum(i); rowsum(i):-1:0]'; % combinations of this row, assuming 2 columns only!\n \n % fill in 2nd row, holding constant\n \nend\n\n\n\nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "meta_SOMclusters.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions/meta_SOMclusters.m", "size": 27199, "source_encoding": "utf_8", "md5": "d6babfd9f8dfa9ed8a3a58b56ae06e2c", "text": "function varargout = meta_SOMclusters(meth,SOMResults,varargin)\n % varargout = meta_SOMclusters(meth,SOMResults,varargin)\n %\n % Multi-function toolbox for working with sets of clusters,\n % particularly those extracted from SOM parcellation\n %\n % [cl,anyStudy,studyByCluster] = meta_SOMclusters(SOMResults,theData,whSOM,meth,[Xi])\n %\n % Make clusters and indicator matrices for SOM results\n %\n % Methods:\n % -----------------------------------------------------------------------\n % 'clusters'\n % SOMResults = meta_SOMclusters('clusters',SOMResults,theData)\n % Displays SOM Results on brain orthviews\n % adds names, colors, and clusters (cl) fields to SOMResults\n % Uses existing names and colors if already present\n % Returns anyStudy field -> studies x SOMs, does any study activate in\n % the SOM cluster?\n % -----------------------------------------------------------------------\n % 'single'\n % [cl,anyStudy,studyByCluster] = meta_SOMclusters('single',SOMResults,theData,whSOM)\n % Gets anyStudy and studyByCluster for a single SOM cluster\n %\n % -----------------------------------------------------------------------\n % 'mca'\n % SOMResults = meta_SOMclusters('mca',SOMResults,[whdata])\n % Uses nometric MDS to get coordinate space\n % Uses permutation test testclust to get classes (superclusters)\n % Returns new region colors in SOMResults.MCA.colors\n % whdata can be 'som' (default) to run on SOM averages\n % or 'cluster' to run on individual cluster data (SOMs may have\n % multiple contiguous clusters).\n % -----------------------------------------------------------------------\n % 'stats'\n % SOMResults = meta_SOMclusters('stats',SOMResults,niterations,[whdata])\n % Uses permutation test to test for significant relationships among\n % regions. Returns uncorrected and fdr-corrected p-values and\n % signficance matrices.\n % % whdata can be 'som' (default) to run on SOM averages\n % or 'cluster' to run on individual cluster data (SOMs may have\n % multiple contiguous clusters).\n % output returned in SOMResults.stats\n % -----------------------------------------------------------------------\n % 'names'\n % SOMResults = meta_SOMclusters('names',SOMResults,[addflag])\n % Assign text names to SOMs\n %\n % -----------------------------------------------------------------------\n % 'xfig'\n % f1 = meta_SOMclusters('xfig',SOMResults,[colors])\n % Make a graph (nmdsfig.m) of regions; no lines\n % Uses SOMResults.colors if not entered separately\n % -----------------------------------------------------------------------\n % 'surface'\n % surfhandle = meta_SOMclusters('surface',SOMResults,keywd,radius)\n % Make a surface plot of regions on any surface\n % keywd can be any of the keywords used by addbrain\n % i.e., empty for surface, 'left', 'right', 'thalamus','brainstem',\n % etc.\n % Uses SOMResults.MCA.colors if present, or SOMResults.colors\n % otherwise\n %\n % ----------------------------------------------------------------------\n % 'somstats'\n % SOMResults = meta_SOMclusters('somstats',SOMResults,[whfield])\n % Needs fields: Xi, w, anyStudy (default; or other field of your choice)\n % Creates fields: prop_by_som, matrix of proportion of activations for SOM x task\n % upper_ci, binomial upper confidence half-length\n %\n % To run for SOM-task associations, use:\n % SOMResults = meta_SOMclusters('somstats',SOMResults);\n %\n % To run for cluster-task associations, use:\n % SOMResults = meta_SOMclusters('somstats',SOMResults,'studyByCluster');\n %\n %\n % ----------------------------------------------------------------------\n % 'sombar'\n % [SOMResults,han] = meta_SOMclusters('sombar',SOMResults,[tasks,soms])\n % Needs fields: prop_by_som, upper_ci, alltasknms, names\n % Creates barplot of activation proportions for selected SOMs and\n % selected tasks\n % ----------------------------------------------------------------------\n % 'somcontrast'\n % meta_SOMclusters('somcontrast',SOMResults,[tasks])\n % Uses chi-square analysis to find SOMs that differ across conditions.\n % Show bar plot and brain slice plots of the significant SOMs.\n %\n % If no tasks are entered, gives you a menu to choose them.\n %\n % Data used:\n % Matrix sizes: uses SOMResults.prop_by_som\n % Activation data: default: .anyStudy; backup: .studyByCluster\n % Tasks: .Xi\n % Weights: .w\n %\n % To switch from using anyStudy to StudyByCluster, run somstats\n % subfunction (see above) with that field first.\n %\n % tor wager, Aug. 06\n\n cl = []; anyStudy = []; studyByCluster = [];\n\n if ~(exist('meth') == 1) || isempty(meth), meth = 'group';, end\n\n switch meth\n case 'clusters'\n\n theData = varargin{1};\n SOMResults = group_orthviews(SOMResults,theData);\n\n varargout{1} = SOMResults;\n\n\n case 'single'\n\n % [cl,anyStudy,studyByCluster] =\n % meta_SOMclusters(SOMResults,theData,whSOM,meth,Xi\n\n theData = varargin{1};\n whSOM = varargin{2};\n [cl,anyStudy,studyByCluster] = get_single_som(SOMResults,theData,whSOM);\n\n varargout{1} = cl;\n varargout{2} = anyStudy;\n varargout{3} = studyByCluster;\n\n\n case 'mca'\n\n if length(varargin) == 0, whdata = 'som'; else whdata = varargin{1}; end\n\n switch lower(whdata)\n case 'som'\n whfield = 'anyStudy';\n case 'cluster'\n whfield = 'studyByCluster';\n otherwise error('whdata must be som or cluster');\n end\n\n if ~isfield(SOMResults,whfield) || isempty(SOMResults.(whfield))\n error(['You must have ' whfield ' field in SOMResults. Try ''clusters'' first.'])\n end\n\n fprintf(1,'Performing multiple correspondence (MCA) on clusters.\\n');\n data = double(SOMResults.(whfield));\n SOMResults.MCA = tor_mca(data,'phi',[],[],'nmds'); % changed from 'correspondence', May 5, 2007; n flag changed from 1 to []\n varargout{1} = SOMResults;\n\n case 'stats'\n\n niter = varargin{1};\n whdata = 'som';\n if length(varargin) > 1, whdata = varargin{2}; end\n\n switch lower(whdata)\n case 'som'\n whfield = 'anyStudy';\n case 'cluster'\n whfield = 'studyByCluster';\n otherwise error('whdata must be som or cluster');\n end\n\n disp(['Getting data from ' whfield ])\n if ~isfield(SOMResults,whfield) || isempty(SOMResults.(whfield))\n error(['You must have ' whfield ' field in SOMResults. Try ''clusters'' first.'])\n end\n\n if ~isfield(SOMResults,'Xi') || isempty(SOMResults.Xi)\n error('You must include task indic matrix Xi as a field in SOMResults. Try ''Meta_Task_Indicator'' first.')\n end\n\n dat = full(double(SOMResults.(whfield)));\n nbrain = size(dat,2);\n dat = [dat SOMResults.Xi];\n SOMResults.stats = permute_mtx(dat,'ss',1,niter,nbrain);\n varargout{1} = SOMResults;\n\n\n\n case 'names'\n if length(varargin) > 0,addflag = varargin{1}; else, addflag = 0; end\n SOMResults.names = som_names(SOMResults.cl,addflag);\n varargout{1} = SOMResults;\n\n\n\n case 'xfig'\n %nmdsfig(MCA.score(:,1:2),ones(size(MCA.score,1),1),OUT.names,OUT.sigbonf);\n n = size(SOMResults.MCA.coords,1);\n\n if length(varargin) > 0\n disp('Using custom input colors.')\n colors = varargin{1};\n elseif isfield(SOMResults,'MCA') && isfield(SOMResults.MCA,'colors')\n disp('Using MCA colors.')\n colors = SOMResults.MCA.colors;\n else\n disp('Using initial random region colors.')\n colors = SOMResults.colors;\n end\n\n names = SOMResults.names;\n sig = zeros(n);\n if isfield(SOMResults,'stats') && size(SOMResults.stats.sigfdr,1) == n\n sig = SOMResults.stats.sigfdr;\n else\n disp(['SOMResults.stats is either missing or does not seem to match this data.'])\n disp(['Point sizes will not be based on stats'])\n end\n\n if length(names) == n\n f1 = nmdsfig(SOMResults.MCA.coords(:,1:2),'classes',(1:n)','names',SOMResults.names,'sig',sig, ...\n 'sizescale',[4 16],'nolines','colors',colors); axis off;\n else\n disp(['SOMResults.names is wrong length for this plot. Omitting names.']);\n f1 = nmdsfig(SOMResults.MCA.coords(:,1:2),'classes',(1:n)','sig',sig, ...\n 'sizescale',[4 16],'nolines','colors',colors); axis off;\n end\n\n % this would use default colors\n %f1 = nmdsfig(SOMResults.MCA.coords(:,1:2),'classes',MCA.ClusterSolution.classes,'names',SOMResults.names,'sig',SOMResults.stats.sigfdr, ...\n %'sizescale',[4 16],'nolines'); axis off;\n\n varargout{1} = f1;\n\n\n case 'somstats'\n\n whfield = 'anyStudy';\n if length(varargin) > 0, whfield = varargin{1}; end\n SOMResults = som_task_stats(SOMResults,whfield);\n varargout{1} = SOMResults;\n\n case 'sombar'\n\n tasks = []; soms = [];\n if length(varargin) > 0, tasks = varargin{1}; end\n if length(varargin) > 1, soms = varargin{2}; end\n\n [SOMResults,han] = som_barplot(SOMResults,tasks,soms);\n varargout{1} = SOMResults;\n varargout{2} = han;\n\n case 'somcontrast'\n tasks = []; soms = [];\n if length(varargin) > 0, tasks = varargin{1}; end\n SOM_contrast(SOMResults,tasks);\n\n case 'surface'\n keywd = varargin{1};\n if length(varargin) > 1, r = varargin{2}; else r = 2; end\n sh = make_surface(SOMResults,keywd,r);\n varargout{1} = sh;\n\n otherwise\n error('Unknown method. see help file for choices.');\n end\n\n\n return\n\n\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n% Subfunction\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n\n\n\nfunction [cl,anyStudy,studyByCluster] = get_single_som(SOMResults,theData,whSOM)\n %whSOM = 1;\n\n hdr = SOMResults.header;\n vol = zeros(hdr.dim(1:3));\n ii = find(SOMResults.IDX == whSOM);\n vol(SOMResults.iMask(ii)) = SOMResults.WTS(ii);\n cl = mask2clusters(vol,hdr.mat);\n\n % view clusters\n %cluster_orthviews(cl,'unique');\n\n % figure out whether any study produced a non-zero value in the SOM area\n x = theData(ii,:);\n anyStudy = (sum(x,1) > 0)';\n\n if nargout > 2\n % figure out whether any study produced a non-zero value in each contiguous\n % cluster within the SOM\n [x,y,z]=ind2sub(hdr.dim(1:3),SOMResults.iMask(ii));\n indx = spm_clusters([x y z]');\n\n for i = 1:max(indx)\n wh = ii(indx == i); % which points in cluster\n x = theData(wh,:); % pts by studies\n studyByCluster(:,i) = (sum(x,1) > 0)';\n end\n studyByCluster = double(studyByCluster);\n\n %burt = double(studyByCluster)' * double(studyByCluster);\n end\n\n return\n\n\n\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n% Subfunction\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n\nfunction SOMResults = group_orthviews(SOMResults,theData)\n % Displays SOM Results on brain orthviews\n % adds names, colors, and clusters (cl) fields to SOMResults\n\n fprintf(1,'meta_SOMclusters: Getting and plotting all SOMs. 000');\n cl = {};\n\n % names and sizes\n n = size(SOMResults.SOM,2);\n\n % names\n if ~isfield(SOMResults,'names') || isempty(SOMResults.names)\n for i=1:n\n SOMResults.names{i}=[num2str(i)];\n end\n end\n % colors\n if ~isfield(SOMResults,'colors') || isempty(SOMResults.colors)\n for i=1:n\n SOMResults.colors{i} = rand(1,3);\n end\n end\n\n for i = 1:n\n fprintf(1,'\\b\\b\\b%03d',i);\n [cltmp,anyStudy(:,i),studyByCluster{i}] = get_single_som(SOMResults,theData,i);\n cltmp = rmfield(cltmp,'P');\n\n % remove small clusters (less than 20)\n wh = cat(1,cltmp.numVox) < 20;\n cltmp(wh) = [];\n studyByCluster{i}(:,wh) = [];\n\n % save soms by cluster\n sombycl{i} = repmat(i,1,length(cltmp));\n\n cl{i} = cltmp;\n nvox(i) = sum(cat(1,cl{i}.numVox));\n\n if i == 1, cluster_orthviews(cl{i},SOMResults.colors(i),'solid');\n else cluster_orthviews(cl{i},SOMResults.colors(i),'add','solid');\n end\n end\n\n SOMResults.cl = cl;\n SOMResults.anyStudy = anyStudy;\n\n SOMResults.studyByCluster = cat(2,studyByCluster{:});\n SOMResults.sombycl = cat(2,sombycl{:});\n\n return\n\n\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n% Subfunction\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n\nfunction names = som_names(cl,addflag)\n % function names = cluster_names(cl,[addflag])\n %\n % Assign names to cl(x).shorttitle\n % Do not use spaces or underscores or special chars for best results\n %\n % Addflag is optional; if 1, uses current orthview display\n\n spm_orthviews('Xhairs','on');\n\n\n for i = 1:length(cl)\n if addflag\n % don't create new figure\n else\n cluster_orthviews(cl{i},{[1 0 0]});\n end\n\n % show centers\n for j = 1:length(cl{i})\n spm_orthviews('Reposition',cl{i}(j).mm_center);\n end\n\n names{i} = input('Enter short name for this SOM set: ','s');\n\n end\n\n\n return\n\n\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n% Subfunction\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n\nfunction SOMResults = som_task_stats(SOMResults,whfield)\n % SOMResults = meta_SOMclusters('somstats',SOMResults)\n % Needs fields: Xi, w, anyStudy\n % Creates fields: prop_by_som, matrix of proportion of activations for SOM x task\n % upper_ci, binomial upper confidence half-length\n\n if nargin < 2, whfield = 'anyStudy'; end\n\n nvars = size(SOMResults.(whfield),2);\n ntasks = size(SOMResults.Xi,2);\n\n % get stats for the entire matrix of SOMs\n [icon,ctxtxi,betas,num_by_condition,prop_by_condition] = meta_apply_contrast(full(double(SOMResults.(whfield)')), ...\n SOMResults.Xi,SOMResults.w,ones(1,ntasks));\n\n % hyp test: just an example, not valid\n %pvals = binomcdf(num_by_condition,repmat(sum(Xi),nvars,1),.5);\n\n % get confidence intervals based on estimated proportions\n % shrink towards .5 if proportion-hat is very extreme\n % ub is upper bound\n\n mytotals = repmat(sum(SOMResults.Xi),nvars,1);\n ub = binoinv(.975,mytotals,min(.9,max(prop_by_condition,.1)));\n ub = ub ./ mytotals;\n ub = ub - prop_by_condition;\n\n SOMResults.prop_by_som = prop_by_condition;\n SOMResults.upper_ci = ub;\n\n return\n\n\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n% Subfunction\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n\nfunction [SOMResults,han] = som_barplot(SOMResults,tasks,soms)\n\n if ~isfield(SOMResults,'prop_by_som')\n SOMResults = meta_SOMclusters('somstats',SOMResults);\n end\n\n if nargin < 2 || isempty(tasks)\n for i = 1:length(SOMResults.alltasknms)\n fprintf(1,'%3.0f\\t%s\\n',i,SOMResults.alltasknms{i});\n end\n tasks = input('Enter indices of tasks to plot: ');\n end\n\n if nargin < 3 || isempty(soms)\n for i = 1:length(SOMResults.names)\n fprintf(1,'%3.0f\\t%s\\n',i,SOMResults.names{i});\n end\n soms = input('Enter indices of SOMs to plot: ');\n end\n\n tasknames = SOMResults.alltasknms(tasks);\n\n nvars = size(SOMResults.prop_by_som,1);\n names = get_somnames(SOMResults,nvars);\n\n somnames = names(soms);\n\n myprops = SOMResults.prop_by_som(soms,tasks);\n myci = SOMResults.upper_ci(soms,tasks);\n\n tor_fig;\n han = barplot_grouped(myprops,myci,[],tasknames,'inputmeans');\n set(gca,'XTickLabel',somnames);\n ylabel('Proportion of studies activating');\n\n scn_export_papersetup(300)\n return\n\nfunction names = get_somnames(SOMResults,nvars)\n % get names of vars we're interested in\n %if we're using clusters instead of SOMs,\n % length will not match; create names with numbers\n names = SOMResults.names;\n\n if length(names) ~= nvars\n disp(['SOMResults.names does not match. Assuming you''re using clusters.'])\n for i = 1:nvars\n names{i} = num2str(i);\n end\n end\n return\n\n \n \n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n% Subfunction\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n\nfunction SOM_contrast(SOMResults,tasks)\n\n if nargin < 2 || isempty(tasks)\n for i = 1:length(SOMResults.alltasknms)\n fprintf(1,'%3.0f\\t%s\\n',i,SOMResults.alltasknms{i});\n end\n tasks = input('Enter indices of tasks to compare with chi-square analysis: ');\n end\n conname = input('Name this contrast (no spaces/special chars): ','s');\n\n \n % Matrix sizes: uses SOMResults.prop_by_som\n % Activation data: default: .anyStudy; backup: .studyByCluster\n % Tasks: .Xi\n % Weights: .w\n \n % names and sizes\n % ---------------------------------------------------------------------\n\n nvars = size(SOMResults.prop_by_som,1);\n ntasks = length(tasks);\n tasknames = SOMResults.alltasknms(tasks);\n somnames = get_somnames(SOMResults,nvars);\n\n % figure out which data field to use based on sizes of prop_by_som\n % get data and cell array of all clusters (based on cl or soms) to use\n % for display\n % ---------------------------------------------------------------------\n\n if nvars == size(SOMResults.SOM,2)\n whfield = 'anyStudy';\n disp(['Testing based on whether studies activated in SOMs.']);\n cl = SOMResults.cl;\n elseif nvars == size(SOMResults.studyByCluster,2)\n whfield = 'studyByCluster';\n disp(['Testing based on whether studies activated in individual clusters (parcels).']);\n % put in cell array form for compatibility\n cltmp = cat(2,SOMResults.cl{:});\n for i = 1:length(cltmp)\n cl{i} = cltmp(i);\n end\n else\n error('I can''t figure out where the data in prop_by_som came from. It doesn''t match either clusters or SOMs.')\n end\n disp(['Getting data from ' whfield]);\n dat = double(full(SOMResults.(whfield)));\n\n\n % do Chi-sq analyses\n % ---------------------------------------------------------------------\n\n condf = SOMResults.Xi(:,tasks) .* repmat(1:ntasks,size(SOMResults.Xi,1),1);\n wh = sum(condf,2) - max(condf,[],2);\n if any(wh), warning('Task categories compared are not mutually exclusive.'), condf(wh,:) = 0; end\n condf = sum(condf,2);\n % eliminate empty rows\n wh = condf == 0;\n\n w = SOMResults.w;\n w = w./mean(w);\n w(wh) = [];\n sig = [];\n\n for som = 1:nvars\n y = [dat(:,som) condf];\n y(wh,:) = [];\n [chi2(som),df(som),chi2p(som),sig(som),warn(som),tab] = chi2test(y,'obs',w,1);\n\n % these should match what's in SOMResults.props_by_som, but we\n % don't need them because they do.\n %props(som,:) = tab(2,:) ./ sum(tab);\n\n if ntasks == 2 && size(tab,1) > 1\n % positive or negative; + means 1st col is greater, neg means\n % 2nd col is greater\n sig(som) = sig(som) .* -sign(diff(tab(2,:) ./ sum(tab)));\n end\n\n end\n\n % barplot\n % ---------------------------------------------------------------------\n sigsoms = find(sig);\n if isempty(sigsoms), disp('No significant results.'), return, end\n \n [SOMResults,han] = meta_SOMclusters('sombar',SOMResults,tasks,sigsoms);\n name = [conname '_barplot'];\n scn_export_papersetup(300);\n saveas(gcf,name,'png');\n\n % show clusters\n % ---------------------------------------------------------------------\n sigsoms = find(sig>0);\n addstr = 'noadd';\n if ~isempty(sigsoms)\n mycl = cat(2,cl{sigsoms});\n cluster_orthviews(mycl,{[0 0 0]},'solid');\n addstr = 'add';\n end\n\n sigsoms = find(sig<0);\n if ~isempty(sigsoms)\n mycl = cat(2,cl{sigsoms});\n cluster_orthviews(mycl,{[1 1 1]},addstr,'solid');\n end\n\n sigsoms = find(sig);\n mycl = cat(2,cl{sigsoms});\n %sigcl = mycl(sigsoms);\n\n \n % tables\n dotables = input('Print tables? (1 or 0) ');\n if dotables\n prop = SOMResults.prop_by_som(:,tasks) ;\n\n % header\n fprintf(1,'SOMcl\\tX\\tY\\tZ\\tVox\\t');\n for j = 1:ntasks, fprintf(1,'%s\\t',tasknames{j}); end\n fprintf(1,'Chi2\\tp\\t\\n');\n \n % body\n mycl = cat(2,SOMResults.cl{:});\n ncl = length(cl);\n for i = 1:ncl\n if chi2p(i) < .005, sigstr = '***';\n elseif chi2p(i) < .01; sigstr = '**';\n elseif chi2p(i) < .05, sigstr = '*';\n else, sigstr = '';\n end\n \n if ~isfield(mycl(i),'shorttitle') || isempty(mycl(i).shorttitle), mycl(i).shorttitle = ['Cl ' num2str(i)]; end\n \n fprintf(1,'%s\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.0f\\t',mycl(i).shorttitle,mycl(i).mm_center(1),mycl(i).mm_center(2),mycl(i).mm_center(3),mycl(i).numVox);\n for j = 1:ntasks, fprintf(1,'%3.0f\\t',100.*prop(i,j)); end\n fprintf(1,'%3.2f\\t%3.4f%s\\t\\n',chi2(i),chi2p(i),sigstr);\n end\n \n end\n\n\n \n\n dofigs = input('Save brain slices and surfaces? (1 or 0) ');\n if ~isempty(sigsoms) && dofigs\n\n % get list of color indices (1 or 2) for each cluster\n % we need to do this for the SOM option only\n if nvars == size(SOMResults.SOM,2)\n sig2 = [];\n for i = 1:length(sigsoms)\n len = length(cl{sigsoms(i)});\n sig2 = [sig2 repmat(sig(sigsoms(i)),1,len)];\n end\n sig = sig2;\n end\n\n % surface: lateral\n colorindx = (sig(find(sig)) > 0) + 1;\n colors = {[1 1 1] [0 0 0]}; % neg then pos\n tor_fig; sh = cluster_surf(mycl(1),colors(colorindx(1)));\n for i = 2:length(mycl(sigsoms))\n cluster_surf(mycl(sigsoms(i)),2,colors(colorindx(i)),sh);\n end\n\n name = [conname '_lat_surf'];\n saveas(gcf,name,'fig');\n saveas(gcf,name,'png');\n\n % surface: brainstem\n tor_fig; sh = cluster_surf(mycl(1),2,colors(colorindx(1)),'brainstem');\n for i = 2:length(mycl)\n cluster_surf(mycl(i),colors(colorindx(i)),sh);\n end\n\n name = [conname '_brainstem_surf'];\n saveas(gcf,name,'fig');\n saveas(gcf,name,'png');\n\n % surface: left\n tor_fig; sh = cluster_surf(mycl(1),2,colors(colorindx(1)),'left');\n for i = 2:length(mycl)\n cluster_surf(mycl(i),colors(colorindx(i)),sh);\n end\n\n name = [conname '_left_surf'];\n saveas(gcf,name,'fig');\n saveas(gcf,name,'png');\n\n name = [conname '_left_lat'];\n view(270,5);\n lighting gouraud; lightRestoreSingle(gca)\n saveas(gcf,name,'png');\n\n % surface: right\n tor_fig; sh = cluster_surf(mycl(1),2,colors(colorindx(1)),'right');\n for i = 2:length(mycl)\n cluster_surf(mycl(i),colors(colorindx(i)),sh);\n end\n\n name = [conname '_right_surf'];\n saveas(gcf,name,'fig');\n saveas(gcf,name,'png');\n\n\n name = [conname '_right_lat'];\n view(90,5);\n lighting gouraud; lightRestoreSingle(gca)\n saveas(gcf,name,'png');\n\n\n overlay = which('scalped_single_subj_T1.img');\n\n % slices\n name = [conname '_axial'];\n cluster_orthviews_showcenters(mycl,'axial',overlay,0);\n scn_export_papersetup(800);\n saveas(gcf,name,'png')\n\n name = [conname '_saggital'];\n cluster_orthviews_showcenters(mycl,'saggital',overlay,0);\n scn_export_papersetup(800);\n saveas(gcf,name,'png')\n\n name = [conname '_coronal'];\n cluster_orthviews_showcenters(mycl,'coronal',overlay,0);\n scn_export_papersetup(800);\n saveas(gcf,name,'png')\n end\n\n\n % % get largest cluster in each significant SOM and image it\n % clplot = [];\n % for i = 1:length(sigsoms)\n % mycl = SOMResults.cl{sigsoms(i)};\n % vs = cat(1,mycl.numVox);\n % wh = vs == max(vs);\n % if isempty(clplot), clplot = mycl(wh); else clplot = merge_clusters(clplot,mycl(wh)); end\n % end\n\n return\n\n\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n% Subfunction\n\n% -------------------------------------------------------------------------\n% -------------------------------------------------------------------------\n\n\nfunction sh = make_surface(SOMResults,keywd,radmm)\n\n if isempty(keywd)\n sh = addbrain;\n else\n sh = addbrain(keywd);\n end\n\n colors = SOMResults.colors;\n if isfield(SOMResults,'MCA')\n colors = SOMResults.MCA.colors;\n disp('Using MCA colors')\n else\n disp('Using SOM random colors');\n end\n\n set(sh,'FaceAlpha',1)\n lightRestoreSingle(gca)\n %sh = cluster_surf(SOMResults.cl{1},SOMResults.colors{1},2);\n for i = 1:length(SOMResults.cl)\n cluster_surf(SOMResults.cl{i},colors(i),radmm,sh);\n end\n\n axis image; lighting gouraud; axis vis3d\n lightRestoreSingle(gca)\n\n return\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "plot_points_on_slice.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/plotting_functions/plot_points_on_slice.m", "size": 12962, "source_encoding": "utf_8", "md5": "46d7cbf45163ac8a9f6d4c709c1889da", "text": "function [handles, wh_slice, my_z] = plot_points_on_slice(xyz, varargin)\n% [handles, wh_slice, my_coords, texthandles] = plot_points_on_slice(xyz, varargin)\n%\n% Usage:\n% handles = plot_points_on_slice(xyz, 'nodraw', 'color', [0 0 1], 'marker', 'o','close_enough',8);\n%\n% Optional inputs:\n% {'noslice', 'nodraw'}, drawslice = 0;\n%\n% 'color', color = varargin{i+1}; varargin{i+1} = [];\n%\n% 'marker', marker = varargin{i+1}; varargin{i + 1} = [];\n%\n% {'slice', 'wh_slice'}, wh_slice = varargin{i+1};\n%\n% {'close', 'closeenough', 'close_enough'}, close_enough = varargin{i+1};\n%\n% {'sagg','saggital','sagittal'}, orientation = 'sagittal';\n%\n% {'MarkerSize', 'markersize'}, markersize = varargin{i+1};\n%\n% {'MarkerFaceColor', 'markerfacecolor'}, facecolor = varargin{i+1};\n%\n% 'solid', disptype = 'solid';\n%\n% 'overlay', ovl = varargin{i + 1};\n%\n% {'text', 'textcodes'}, textcodes = varargin{i + 1}; varargin{i + 1} = [];\n%\n% {'condf' 'colorcond'}, condf = varargin{i + 1};\n%\n% 'points', plot flat points, which is faster. default is 'spheres'\n%\n% sagittal plot:\n% figure; [handles, wh_slice, my_z] = plot_points_on_slice(xyz,'slice',45,'sagg','close',8,'markersize',10);\n%\n% Tor Wager, March 2007\n% Documentation not complete; refer to code for input options, etc.\n% Updated Jan 2011\n% Updated Feb 2013 - tor - default is spheres rather than points\n% Updated Dec 2013 - tor - handle condition function\n%\n% wh_slice is in voxels\n% close enough is in mm\n%\n% Example:\n% create_figure('Slice view'); [handles, wh_slice, my_z] = plot_points_on_slice(DB.xyz(strcmp(DB.Valence, 'neg'), :), 'slice', 23, 'color', [0 0 1], 'marker', 'o','close_enough',8);\n% [handles2, wh_slice, my_z] = plot_points_on_slice(DB.xyz(strcmp(DB.Valence, 'pos'), :), 'slice', 23, 'color', [1 1 0], 'marker', 'o','close_enough',8);\n%\n% Parent function example:\n% newax2 = plot_points_on_montage(DB.xyz, 'condf', DB.condf, 'color', DB.color2, 'contrast', DB.contrast, 'axial', 'slice_range', [-40 40], 'solid', 'spacing', 10, 'close_enough', 8, 'onerow');\n%\n% More examples:\n% plot_points_on_slice(PLOTINFO{1}.xyz, 'solid', 'wh_slice', 50, 'condf', PLOTINFO{1}.condf, 'MarkerSize', 6, 'color', PLOTINFO{1}.colors);\n% plot_points_on_slice(PLOTINFO{1}.xyz, 'solid', 'wh_slice', 50, 'condf', PLOTINFO{1}.condf, 'MarkerSize', 6, 'color', PLOTINFO{1}.colors, 'points', 'MarkerFaceColor', PLOTINFO{1}.colors);\n% plot_points_on_slice(PLOTINFO{1}.xyz, 'solid', 'wh_slice', 40, 'condf', PLOTINFO{1}.condf, 'MarkerSize', 6, 'color', PLOTINFO{1}.colors, 'MarkerFaceColor', PLOTINFO{1}.colors, 'saggital');\n\n% defaults\n% ------------------------------------------------------\n\ncolor = 'k';\nfacecolor = 'k';\nmarker = 'o';\ndrawslice = 1;\nclose_enough = 10; % in mm\nmarkersize = 12;\norientation = 'axial';\ndisptype = 'contour';\novl = which('SPM8_colin27T1_seg.img'); % which('scalped_avg152T1.img');\ntextcodes = [];\ntexthandles = [];\ncondf = []; % color codes\npointtype = 'spheres';\ndocondf = 0;\n\n% ------------------------------------------------------\n% parse inputs\n% ------------------------------------------------------\n\nfor i = 1:length(varargin)\n if ischar(varargin{i})\n switch varargin{i}\n % reserved keywords\n case {'noslice', 'nodraw'}, drawslice = 0;\n \n case 'color', color = varargin{i+1}; varargin{i+1} = [];\n \n case 'marker', marker = varargin{i+1}; varargin{i + 1} = [];\n \n case {'slice', 'wh_slice'}, wh_slice = varargin{i+1};\n \n case {'spacing', 'close', 'closeenough', 'close_enough'}, close_enough = varargin{i+1};\n \n case {'sagg','saggital','sagittal'}, orientation = 'sagittal';\n \n case {'MarkerSize', 'markersize'}, markersize = varargin{i+1};\n \n case {'MarkerFaceColor', 'markerfacecolor'}, facecolor = varargin{i+1};\n \n case 'solid', disptype = 'solid';\n \n case 'overlay', ovl = varargin{i + 1};\n \n case {'text', 'textcodes'}, textcodes = varargin{i + 1}; varargin{i + 1} = [];\n \n case {'condf' 'colorcond'}, condf = varargin{i + 1}; docondf = 1;\n \n case {'slice_range' 'onerow' 'draw'}\n % also not used here, but passed in by default from calling\n % function plot_points_on_montage.m\n % so no warning...\n \n case 'axial'\n % default; not used\n \n case 'points'\n % plot points; default is now spheres\n pointtype = 'points';\n \n otherwise, warning(['Unknown input string option:' varargin{i}]);\n end\n end\nend\n\n% Check and set a few more things\n\nif ~docondf\n condf = ones(size(xyz, 1), 1); \n color = {color}; \n facecolor = {facecolor};\nelse\n if ~iscell(facecolor), facecolor = repmat({facecolor}, 1, length(color)); end\nend\n\n% textcodes: enforce cell of strings\nif ~iscell(textcodes)\n textcodes = mat2cell(textcodes, ones(size(textcodes, 1), 1), 1);\nend\n\nfor i = 1:length(textcodes)\n if ~ischar(textcodes{i})\n textcodes{i} = num2str(textcodes{i});\n end\nend\n\n% ------------------------------------------------------\n% get other info\n% ------------------------------------------------------\n\n\novlV = spm_vol(ovl);\n\nif ~exist('wh_slice', 'var') || isempty(wh_slice)\n xyzvox = mm2voxel(xyz, ovlV.mat, 1);\n modes = mode(xyzvox, 1);\n wh_slice = modes(3);\n fprintf(1,'No slice entered. Picking slice with most points: z = %3.0f\\n', wh_slice);\nend\n\nfprintf(1,'Plotting points within %3.0f mm of slice\\n', close_enough);\n\n% ------------------------------------------------------\n% draw brain slice\n% ------------------------------------------------------\n\n\nif drawslice\n \n v = spm_read_vols(ovlV);\n \n mm = voxel2mm([1 1 1; size(v)]', ovlV.mat);\n xcoords = linspace(mm(1,1), mm(1,2), size(v, 1));\n ycoords = linspace(mm(2,1), mm(2,2), size(v, 2));\n %zcoords = linspace(mm(3,1), mm(3,2), size(v, 3));\n \n switch orientation\n case 'axial'\n [X, Y] = meshgrid(xcoords, ycoords); Z = v(:,:,wh_slice)';\n %figure;\n switch disptype\n case 'contour'\n contour(X, Y, Z);\n case 'solid'\n hh = imagesc(xcoords, ycoords, Z);\n \n otherwise\n error('unknown display type. check code.');\n end\n \n colormap(gray);\n \n case 'sagittal'\n zcoords = linspace(mm(3,1), mm(3,2), size(v, 3));\n [X, Y] = meshgrid(ycoords, zcoords); Z = squeeze(v(wh_slice,:,:))';\n %figure;\n switch disptype\n case 'contour'\n h = contour(X, Y, Z);\n \n case 'solid'\n hh = imagesc(ycoords, zcoords, Z);\n \n otherwise\n error('unknown display type. check code.');\n end\n \n colormap(gray);\n h = findobj(gca,'Type','hggroup');\n set(h,'LineWidth',1.5);\n set(gca,'XDir','Reverse')\n \n \n otherwise, error('Unknown orientation.');\n \n end\n \n axis image\n \n switch disptype\n case 'solid'\n % set transparent value for clear axes\n myAlphaData = double(abs(Z) > 0);\n \n % If we set alphadata to clear for BG and axis color to none, we get clear\n % axes\n set(hh, 'AlphaDataMapping', 'scaled', 'AlphaData', myAlphaData)\n set(gca, 'Color', 'none')\n end\n \nend\n\n% ------------------------------------------------------\n% put points on slice\n% ------------------------------------------------------\n\nswitch orientation\n case 'sagittal'\n % get z coord in mm of this slice\n tmp_xyzmm = voxel2mm([wh_slice 1 1]', ovlV.mat);\n my_z = tmp_xyzmm(1);\n \n wh = find(abs(xyz(:,1) - my_z) <= close_enough);\n hold on;\n \n% if strcmp(pointtype, 'points')\n% handles = plot(xyz(wh,2), xyz(wh,3), marker, 'Color', color, 'MarkerFaceColor',facecolor, 'MarkerSize', markersize);\n% \n% elseif strcmp(pointtype, 'spheres')\n% xyztoplot = [xyz(wh,2), xyz(wh,3) zeros(length(wh), 1)];\n% handles = cluster_image_sphere(xyztoplot, 'color', color, 'radius', round(markersize/3)+1);\n% end\n% \n% if ~isempty(textcodes)\n% texthandles = plottext(xyz(wh, 2), xyz(wh, 3), textcodes(wh), color, orientation);\n% end\n\n \n % set coords\n xtoplot = xyz(wh,2);\n ytoplot = xyz(wh,3);\n condftoplot = condf(wh); % ok even if no condf (see above)\n \n if ~isempty(textcodes)\n textcodestoplot = textcodes(wh);\n else\n textcodestoplot = [];\n end\n \n [handles, texthandles] = plot_coords(xtoplot, ytoplot, condftoplot, color, facecolor, pointtype, marker, markersize, textcodestoplot, orientation);\n \n \n \n case 'axial'\n \n % get z coord in mm of this slice\n tmp_xyzmm = voxel2mm([1 1 wh_slice]', ovlV.mat);\n my_z = tmp_xyzmm(3);\n \n wh = find(abs(xyz(:,3) - my_z) <= close_enough);\n hold on;\n \n % set coords\n xtoplot = xyz(wh,1);\n ytoplot = xyz(wh,2);\n condftoplot = condf(wh); % ok even if no condf (see above)\n \n if ~isempty(textcodes)\n textcodestoplot = textcodes(wh);\n else\n textcodestoplot = [];\n end\n \n [handles, texthandles] = plot_coords(xtoplot, ytoplot, condftoplot, color, facecolor, pointtype, marker, markersize, textcodestoplot, orientation);\n \n \n \n \n otherwise, error('Unknown orientation.');\n \nend\n\nif strcmp(disptype, 'solid')\n set(gca, 'YDir', 'normal');\n white_colormap;\nend\n\n% set sphere lighting\nif strcmp(pointtype, 'spheres')\n lighting gouraud\n switch orientation\n case 'axial'\n [az, el] = view; el = el - 45;\n lh = lightangle(az, el);\n case 'sagittal'\n lightangle(0, -135);\n lightangle(0, -135);\n lightangle(0, -135);\n end\n set(handles, 'FaceAlpha', .6,'SpecularColorReflectance', .7);\nend\n\nend % function\n\n\nfunction texthandles = plottext(x, y, textcodes, color, orientation)\n\n% adjust for font placement\nswitch orientation\n case 'sagittal'\n xshift = 6;\n case 'axial'\n xshift = -6;\n \nend\n\n\ntexthandles = [];\nfor j = 1:length(textcodes)\n % text labels\n \n \n if ischar(color)\n \n texthandles(j) = text(x(j) + xshift, y(j), textcodes{j},'Color',color,'FontSize',12,'FontWeight','bold');\n \n else\n texthandles(j) = text(x(j) + xshift, y(j), textcodes{j},'Color',color,'FontSize',12,'FontWeight','bold');\n \n end\n \nend\n\nend % plottext\n\n\nfunction white_colormap\n\ncm = colormap;\nwh = find(all(cm < .01, 2));\nwh = all(cm < .01, 2);\ncm(wh, :) = repmat([1 1 1], sum(wh), 1);\ncolormap(cm)\n\nend\n\n\n% function [color, facecolor] = parse_condf(condf, color, facecolor)\n%\n% origcolor = color;\n% [color, facecolor] = deal(cell(length(condf), 1));\n%\n% u = unique(condf);\n%\n% for i = 1:length(u)\n%\n% wh = condf == i;\n% color(wh) = origcolor(i);\n%\n% if ischar(origcolor{i})\n% myc = origcolor{i}(1); % color = 1st (hopefully)\n% facecolor(wh) = {myc};\n% else\n% facecolor(wh) = origcolor(i);\n% end\n%\n% end\n%\n% end % subfunction\n\nfunction [handles, texthandles] = plot_coords(xtoplot, ytoplot, condftoplot, color, facecolor, pointtype, marker, markersize, textcodes, orientation)\n\n% xtoplot, ytoplot are in reference to figure dims, and are diferent for\n% different orientations.\n\n[handles, texthandles] = deal([]);\n\nu = unique(condftoplot);\n\nfor i = 1:length(u)\n \n % set color\n colortoplot = color{i};\n facectoplot = facecolor{i};\n \n wh = condftoplot == u(i);\n \n if strcmp(pointtype, 'points')\n \n handles = plot(xtoplot(wh), ytoplot(wh), marker, 'Color', colortoplot, 'MarkerFaceColor',facectoplot, 'MarkerSize', markersize);\n \n elseif strcmp(pointtype, 'spheres')\n xyztoplot = [xtoplot(wh), ytoplot(wh) zeros(sum(wh), 1)];\n handles = cluster_image_sphere(xyztoplot, 'color', colortoplot, 'radius', round(markersize/3)+1);\n \n end\n \n if ~isempty(textcodes)\n texthandles = plottext(xtoplot(wh), ytoplot(wh), textcodes(wh), colortoplot, orientation);\n end\n \nend\n\nend % subfunction\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "plot_points_on_brain.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/plotting_functions/plot_points_on_brain.m", "size": 8541, "source_encoding": "utf_8", "md5": "6dc643d8032261bb1f1db95be7894882", "text": "function h = plot_points_on_brain(XYZ,varargin)\n% function handles = plot_points_on_brain(XYZ,varargin)\n%\n% This function plots a 3-column vector of xyz points (coordinates from\n% studies) or text labels for each point.\n%\n% - option to plot on a glass brain. Four different views are created in 2 figures.\n% - same options as in plot_points_on_surface2.m, but does not extract\n% (move) coordinates to surface\n% - can also plot on existing surfaces/figures; used in\n% plot_points_on_subcortex\n%\n% Usage:\n% --------------------------------\n% plot_points_on_brain(XYZ,[{color(s)}, colorclasses, {textmarkers/contrastcodes}, suppresstextdisplayflag, addbrainsurf])\n%\n% An optional 2nd argument is a color, or list of colors.\n% An optional 3rd argument is a vector of integers to classify the points\n% into groups. Each group gets a color in the colors vector.\n% An optional 4th argument is a cell array of text markers to plot\n% instead of points. Points will be averaged within 12 mm if they have\n% the same text label -- the idea is that text labels code unique\n% contrasts within studies.\n% 5th arg: do the averaging, but suppress text display; plot points\n% instead.\n%\n% Note: You may not always be able to see text on the figure automatically;\n% try addbrain\n%\n% examples:\n% --------------------------------\n% plot_points_on_brain(saddecrease,{'go'});\n% plot_points_on_brain(sadpts,{'bo' 'rs' 'gv'},methi);\n% plot_points_on_brain(saddecrease,{cell vec of all colors});\n% plot_points_on_brain(saddecrease,{'go'},[],1);\n%\n% h = plot_points_on_brain(DB.xyz, {'bo'}, DB.Contrast, DB.textcodes);\n%\n% by tor wager\n%\n% Modified aug 06 by tor wager to add option to not add brain surface\n\n% Modified Jan 11 by tor to add text label plotting.\n\nh = [];\naddbrainsurface = 0;\n\n\nif size(XYZ, 2) ~= 3, error('XYZ must have n rows and 3 columns.'); end\nif isempty(XYZ)\n disp('No points to plot. Doing nothing.');\n return\nend\n\n% --------------------------------\n% set up colors\n% --------------------------------\n\n[colors, classes] = setup_colors(XYZ, varargin{:});\n\n% --------------------------------\n% set up text\n% --------------------------------\n\n[textcodes, XYZ, colors, classes] = setup_text_and_average(XYZ, colors, classes, varargin{:});\n\n\n%\n%\n%\n% colors = {'ro' 'go' 'bo' 'yo' 'co' 'mo' 'ko' 'r^' 'g^' 'b^' 'y^' 'c^' 'm^' 'k^'};\n%\n% if length(varargin) > 0, colors = varargin{1}; end\n% if length(varargin) > 1, classes = varargin{2}; else classes = ones(size(XYZ,1),1); end\n% if length(varargin) > 2, addbrainsurface = varargin{3}; end\n%\n% if isempty(classes), classes = ones(size(XYZ,1),1); end\n% if ~iscell(colors), colors = {colors}; end\n% if isempty(colors), colors = {'ro' 'go' 'bo' 'yo' 'co' 'mo' 'ko' 'r^' 'g^' 'b^' 'y^' 'c^' 'm^' 'k^'};, end\n%\n% % if we enter a vector of colors for each point, set up classes and colors\n% if length(colors) == size(XYZ,1)\n% classes = zeros(size(colors));\n% coltmp = unique(colors);\n%\n% for i = 1:length(coltmp)\n% wh = find(strcmp(colors,coltmp{i}));\n% classes(wh) = i;\n% end\n% colors = coltmp';\n% end\n\nif addbrainsurface\n f1 = figure('Color','w'); set(gca,'FontSize',18),hold on\nend\n\nu = unique(classes);\nif length(colors) < length(u)\n colors = repmat(colors, 1, length(u));\nend\n\n\n% Plot points and/or text\n% ---------------------------------------------------------------\nif isempty(textcodes)\n % No text codes - points only\n \n fprintf('Plotting %3.0f points\\n', size(XYZ, 1));\n \n for clas = 1:length(u)\n \n whpoints = classes==u(clas);\n myxyz = [XYZ(whpoints, 1), XYZ(whpoints, 2), XYZ(whpoints, 3)];\n \n mycolor = colors{clas};\n mylinecolor = 'wo';\n myfacecolor = mycolor;\n \n if ischar(mycolor)\n myfacecolor = myfacecolor(1);\n if length(mycolor) > 1\n mylinecolor(2) = mycolor(2);\n end\n end\n \n h = plot3(myxyz(:, 1), myxyz(:, 2), myxyz(:, 3), ...\n mylinecolor, 'MarkerFaceColor', myfacecolor, 'MarkerSize', 8);\n \n hold on\n end\n \nelse % We have text labels\n \n % Plot text labels\n fprintf('Plotting %3.0f text labels\\n', size(XYZ, 1));\n fprintf(1, 'Class\\tx\\ty\\tz\\tCode\\t\\n')\n \n for j = 1:length(textcodes)\n % text labels\n myclass = classes(j);\n wh = u == myclass;\n \n myxyz = [XYZ(j,1),XYZ(j,2),XYZ(j,3)];\n \n if ischar(colors{wh}) % colors is a text string\n \n pt(j) = text(myxyz(1), myxyz(2), myxyz(3),...\n textcodes{j},'Color',colors{wh}(1),'FontSize',12,'FontWeight','bold');\n \n else % colors is a 3-element vector\n \n pt(j) = text(myxyz(1), myxyz(2), myxyz(3), ...\n textcodes{j},'Color',colors{wh},'FontSize',12,'FontWeight','bold');\n \n end\n \n % Print table along with points\n\n fprintf(1, '%3.0f\\t%3.0f\\t%3.0f\\t%3.0f\\t%s\\n', myclass, myxyz(1), myxyz(2), myxyz(3), textcodes{j});\n \n end\n \nend\n\n\n\nif addbrainsurface\n \n addbrain;\n drawnow;\n \n % Add white filling to prevent see-through\n \n y = [-105 70 70 -105]; z = [-60 -60 78 78]; x = [0 0 0 0];\n hold on; hh = fill3(x,y,z,[.9 .9 .9]); set(hh,'EdgeColor','none','FaceAlpha',1)\n \n \n view(90,0)\n [az,el] = view;\n h = lightangle(az,el); set(gca,'FontSize',18)\n \n \n [hh1,hh2,hh3,hl,a1,a2,a3] = make_figure_into_orthviews;\n \nend\n\nend % main function\n\n\n\n\n\n% ---------------------------------------------------------------------\n% ---------------------------------------------------------------------\n\n% Sub-functions\n\n% ---------------------------------------------------------------------\n% ---------------------------------------------------------------------\n\n\nfunction [colors, classes] = setup_colors(XYZ, varargin)\n\ncolors = {'ro' 'go' 'bo' 'yo' 'co' 'mo' 'ko' 'r^' 'g^' 'b^' 'y^' 'c^' 'm^' 'k^'};\n\nif length(varargin) > 0, colors = varargin{1}; end\nif length(varargin) > 1, classes = varargin{2}; else classes = []; end\n\n%if isempty(classes), classes = ones(size(XYZ,1),1); end\nif ~iscell(colors), colors = {colors}; end\nif isempty(colors), colors = {'ro' 'go' 'bo' 'yo' 'co' 'mo' 'ko' 'r^' 'g^' 'b^' 'y^' 'c^' 'm^' 'k^'}; end\n\n% if we have entered a vector of colors for each point, set up classes and colors\n\nif length(colors) == size(XYZ,1) && isempty(classes)\n classes = zeros(size(colors));\n coltmp = unique(colors);\n \n for i = 1:length(coltmp)\n wh = find(strcmp(colors,coltmp{i}));\n classes(wh) = i;\n end\n colors = coltmp';\n \nelse % Do some checks\n nclasses = length(unique(classes(classes~=0)));\n \n if length(colors) == 1\n disp('Using single color for all point classes because you input a single color');\n colors = repmat(colors, 1, nclasses);\n \n elseif length(colors) < nclasses\n \n disp('There seem to be too few colors in your input. Using standard colors')\n colors = scn_standard_colors(length(unique(classes(classes~=0))));\n end\n \nend\n\nend\n\n\nfunction [textcodes, XYZ, colors, classes] = setup_text_and_average(XYZ, colors, classes, varargin)\n\nif length(varargin) > 3\n disp(['Not plotting text codes.'])\n textcodes = [];\n \nelseif length(varargin) > 2\n textcodes = varargin{3};\nend\n\n% make textcodes into cell, if not\n% This is for averaging nearby by textcode, if the study/contrast\n% grping is not a cell array of strings.\nif ~iscell(textcodes), tmp={};\n for i = 1:size(textcodes,1), tmp{i} = num2str(textcodes(i)); end\n textcodes = tmp';\nend\n\n% if plotting text codes, make white\nif length(varargin) < 4 && ~isempty(textcodes)\n for i = 1:length(colors)\n if ischar(colors{i})\n colors{i}(2) = '.';\n else\n % no need to do anything... colors{i} = [1 1 1];\n end\n end\nend\n\ndisp(['Averaging nearby points within 12 mm with the same text code.']);\n\nif size(XYZ, 1) > 1 && ~isempty(textcodes)\n \n % average nearby coordinates together! 12 mm\n [XYZ,textcodes,order] = average_nearby_xyz(XYZ,12,textcodes);\n classes = classes(order);\n \n % second pass, 8 mm\n [XYZ,textcodes,order] = average_nearby_xyz(XYZ,8,textcodes);\n classes = classes(order);\n\nelseif ~isempty(textcodes)\n % one point; leave as-is\n \nelse\n textcodes = [];\n disp('Plotting all peaks; no averaging.');\nend\n\n\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "plot_points_on_subcortex.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/plotting_functions/plot_points_on_subcortex.m", "size": 5636, "source_encoding": "utf_8", "md5": "47e5ed11cbddf191880c0b259d75d377", "text": "function [cl,han,surfhan] = plot_points_on_subcortex(DB,name,colors,condf, varargin)\n% [cl,han,surfhan] = plot_points_on_subcortex(DB,name,colors,condf, varargin)\n% \n% Extract and plot points for specific structure/structures.\n%\n% name input specifies structure to extract and plot on. Can be:\n% - 'brainstem-thalamus', 'limbic', brainstem, thalamus, hypothalamus, caudate, putamen, or other names\n% recognized by addbrain\n% - a mask image name of your choosing\n% - already-defined clusters\n%\n% classes is\n% a vector of integers (condf) or empty\n%\n% colors is\n% a cell array with one color specification\n% or one for each integer in classes\n%\n% condf is\n% a vector of integers with points to plot in different colors; one\n% integer per color entry\n%\n% textcodes is an optional input after condf\n% a cell array of unique text labels to use instead of points\n%\n% an optional input after textcodes is an integer for how close is close_enough to target structure, in mm\n%\n% Examples:\n% [ind,nms,condf] = string2indicator(DB.Mode);\n% wh = [1 3];\n% condf = indic2condf(ind(:,wh)); colors = {'ro' 'b^'};\n% tor_fig; [cl,han] = plot_points_on_subcortex(DB,name,colors,condf)\n%\n% DB has xyz field with coordinates\n% DB.Contrast is a vector of integers\n% DB.textcodes is a cell array of text labels\n% [cl, pointhan, surfhan] = plot_points_on_subcortex(DB,'limbic', {'ro'}, DB.Contrast, DB.textcodes);\n% [cl, pointhan, surfhan] = plot_points_on_subcortex(DB,'limbic', {'ro'}, DB.Contrast);\n\nglobal textcodes % i used a global because i'm lazy...\nglobal close_enough\n\ntextcodes = [];\nclose_enough = 2;\n\nif length(varargin) > 0\n textcodes = varargin{1};\nend\n\nif length(varargin) > 1\n close_enough = varargin{2};\nend\n\nhold on;\n\nswitch name\n case 'brainstem-thalamus'\n [cl,han{1},surfhan{1}] = show_cl(DB,'brainstem',colors,condf);\n [c,h,surfhan{end+1}] = show_cl(DB,'thalamus',colors,condf);\n cl = merge_clusters(cl,c);\n han{end+1} = h;\n \n [c,h,surfhan{end+1}] = show_cl(DB,'hypothalamus',colors,condf);\n cl = merge_clusters(cl,c);\n han{end+1} = h;\n case 'limbic'\n [cl,han{1},surfhan{1}] = show_cl(DB,'brainstem',colors,condf);\n [c,h,surfhan{end+1}] = show_cl(DB,'thalamus',colors,condf);\n cl = merge_clusters(cl,c);\n han{end+1} = h;\n \n [c,h,surfhan{end+1}] = show_cl(DB,'hypothalamus',colors,condf);\n cl = merge_clusters(cl,c);\n han{end+1} = h;\n \n [c,h,surfhan{end+1}] = show_cl(DB,'caudate',colors,condf);\n cl = merge_clusters(cl,c);\n han{end+1} = h;\n \n [c,h,surfhan{end+1}] = show_cl(DB,'amygdala',colors,condf);\n cl = merge_clusters(cl,c);\n han{end+1} = h;\n \n [c,h,surfhan{end+1}] = show_cl(DB,'nac',colors,condf);\n cl = merge_clusters(cl,c);\n han{end+1} = h;\n otherwise\n [cl,han,surfhan{1}] = show_cl(DB,name,colors,condf);\n \nend\n\naxis image; axis off; axis vis3d; view(90,10); lighting gouraud\nscn_export_papersetup(400);\n\nend % main function\n\n\nfunction [cl,han,surfhan] = show_cl(DB,name,colors,condf)\n\nglobal textcodes\nglobal close_enough\n\nsurfhan = [];\nhan = [];\n\nif isstr(name)\n switch name\n case 'brainstem'\n pname = which('spm2_brainstem.img');\n surfhan = addbrain(name);\n case 'thalamus'\n pname = which('spm2_thal.img');\n surfhan = addbrain(name);\n case 'hypothalamus'\n pname = which('spm2_hythal.img');\n surfhan = addbrain(name);\n case 'caudate'\n pname = which('spm2_caudate.img');\n surfhan = addbrain(name);\n case 'amygdala'\n load amy_clusters\n cl = amy;\n surfhan = addbrain(name);\n \n case {'hipp', 'hippocampus'}\n pname = which('spm2_hipp.img');\n surfhan = addbrain(name);\n \n case 'brainstem'\n\n pname = 'spm2_brainstem.mat';\n surfhan = addbrain(name);\n \n case 'pag'\n pname = which('spm5_pag.img');\n surfhan = addbrain(name);\n \n case 'left'\n pname = which('spm2_left.img');\n surfhan = addbrain(name);\n \n case 'right'\n pname = which('spm2_right.img');\n surfhan = addbrain(name);\n \n case {'nac' 'nucleus accumbens'}\n P = which('NucAccumb_clusters.mat');\n load(P)\n cl = cl(1:2);\n surfhan = addbrain('nacc');\n \n cl = rmfield(cl, 'descrip'); % so we can use descrip field later if data is entered there\n \n case 'putamen'\n P = which('carmack_more_clusters.mat'); load(P)\n cl = put;\n surfhan= addbrain(name);\n otherwise\n pname = name;\n end\n \n if ~exist('cl','var')\n cl = mask2clusters(pname);\n end\n \nelseif isstruct(name)\n cl = name;\nend\n\n% get rid of small clusters\nwh = cat(1,cl.numVox);\nwh = find(wh < 50);\ncl(wh) = [];\n\nhan = [];\nif isempty(cl)\n disp('No clusters > 50 voxels');\nelse\n \n cl = database2clusters(DB, cl, close_enough);\n \n for i = 1:length(cl)\n \n if isempty(textcodes)\n mytextcodes = [];\n else\n mytextcodes = textcodes(cl(i).wh_points);\n end\n \n mycondf = condf(cl(i).wh_points);\n mycolors = colors(unique(mycondf));\n \n h = plot_points_on_brain(cl(i).XYZmm', mycolors, mycondf, mytextcodes);\n han = [han h];\n end\n \n drawnow\nend\n\nend % show_cl function\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "plot_points_on_medial_surface.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/plotting_functions/plot_points_on_medial_surface.m", "size": 11086, "source_encoding": "utf_8", "md5": "9374d5e4017b1d41d91d0f620c6970c0", "text": "function plot_points_on_medial_surface(coords,colors,varargin)\n % plot_points_on_medial_surface(coords,colors,varargin)\n % plot_points_on_medial_surface(coords,colors,[factor variable],[factor levels],[newfig],[mytextlabels])\n %\n % examples:\n % plot_points_on_medial_surface([EMDB.x EMDB.y EMDB.z],{'ro'});\n %\n % plot_points_on_medial_surface([EMDB.x EMDB.y EMDB.z],{'bs' 'yo'},EMDB.valence,{'pos' 'neg'});\n %\n % plot_points_on_medial_surface([INHDB.x INHDB.y INHDB.z], ...\n % {'gs' 'ro' 'b^' 'mo' 'yv' 'cs' 'c^'},INHDB.Task);\n %\n %LTMDB.Memtype(find(strcmp(LTMDB.Memtype,'Autobiog'))) = {'Autobiographical'};\n %LTMDB.Memtype(find(strcmp(LTMDB.Memtype,'encoding'))) = {'Encoding'};\n %LTMDB.y(abs(LTMDB.y) > 100) = NaN;\n % plot_points_on_medial_surface([LTMDB.x LTMDB.y LTMDB.z], ...\n %{'ro' 'ys' 'bv' 'cs' 'mo' 'g^'},{'Autobiographical' 'Encoding' 'Recall' 'Recognition' 'Retrieval' 'Source'});\n %\n % plot_points_on_medial_surface([PAINDB3.x PAINDB3.y PAINDB3.z] ...\n %,{'go' 'rs' 'bv' 'cs' 'yo' 'g^' 'mo'},{'Cutaneous' 'Electric_shock' 'Intramuscular' 'Laser' 'Thermal' 'Vestibular' 'Visceral'});\n %\n % plot_points_on_medial_surface([PAINDB3.x PAINDB3.y PAINDB3.z],{'ro' 'bs'},PAINDB3.Right_vs_Left,{'Left' 'Right'});\n %\n % plot_points_on_medial_surface(XYZ,{'bo' 'go' 'ro' 'rd' 'rs'},color, ...\n %{'bo' 'go' 'ro' 'rd' 'rs'},1,letter);\n % plot_points_on_medial_surface(XYZ,{'bo' 'go' 'gs' 'r^' 'ro' 'rd'\n % 'rs'},color,{'bo' 'go' 'gs' 'r^' 'ro' 'rd' 'rs'},1,letter);\n\n % see also plot_points_on_surface, plot_points_on_surface2 (best)\n % tor wager\n newmethod = 0; % needs to be developed\n\n surfacecutoff = 16; % plot points this distance or less from surface, in mm.\n mymarkersize = 8;\n plottext = 0;\n mytext = []; % would be cell array of text strings\n colordefi = [];\n levelnames = [];\n\n newfig = 1;\n\n\n if ~exist('coords'), coords = [0 0 0]; end\n if ~exist('colors'), colors = {'ko'}; end\n\n if length(varargin)>0, colordefi = varargin{1}; end\n if length(varargin)>1, levelnames = varargin{2}; end\n if length(varargin)>2, newfig = varargin{3}; end\n if length(varargin)>3, plottext = 1; mytext = varargin{4}; end\n\n %if length(colors) == size(coords,1)\n\n [colorout,coords,colornames,whomit] = get_colors(colors,colordefi,levelnames,coords);\n\n\n % add 5 to Z value to adjust origin\n disp('WARNING! ADDING 5 TO Z VALUES TO MATCH WHAT I THINK IS CAUSED BY SHIFT IN ORIGIN.')\n coords(:,3) = coords(:,3) + 6;\n\n\n coords(:,2) = -coords(:,2);\n coordscopy = coords;\n\n %if length(colors) < size(coords,1), colors = repmat(colors,size(coords,1),1); end\n\n [D,hdr,origin] = read_image_data;\n\n\n % average coords together, if study-unique text labels are entered\n if ~isempty(mytext)\n mytext(find(whomit)) = [];\n\n fprintf(1,'Averaging nearby coords at 12 mm ... starting with %3.0f coords. ',size(coords,1));\n % average nearby coordinates together! 12 mm\n [coords,mytext,order] = average_nearby_xyz(coords,12,mytext);\n colorout = colorout(order);\n coordscopy = coordscopy(order,:);\n\n % second pass, 8 mm\n [coords,mytext,order] = average_nearby_xyz(coords,8,mytext);\n colorout = colorout(order);\n coordscopy = coordscopy(order,:);\n\n fprintf(1,'finished with %3.0f.\\n ',size(coords,1));\n else\n for i = 1:size(coords,1), mytext(i,1) = 'x'; end\n end\n\n\n % ===================================================================\n % * Left Medial *\n % ===================================================================\n disp('Plotting left medial coordinates.');drawnow\n\n coords = coordscopy;\n\n\n disp(' Adjusting coordiates from mm to brain voxels');drawnow\n % coordinates entered in mm should be scaled to voxels\n\n coords(:,1) = round(coords(:,1) / hdr.xsize);\n coords(:,2) = round(coords(:,2) / hdr.ysize);\n coords(:,3) = round(coords(:,3) / hdr.zsize);\n\n % express all coordinates in voxel space, converting from distance from the origin\n for i = 1:size(coords,1)\n coords(i,:) = coords(i,:) + origin;\n end\n\n\n % --- make figure ----------------------------------------------\n plothandle = create_figure('Medial point plot', 1, 2, ~newfig);\n \n% % %if newfig, plothandle = tor_fig(1,2); ,end\nsubplot(1,2,1); plothandle = gca; subplot(1,2,2); plothandle(2) = gca;\nsubplot(1,2,1);\n plotorigin(origin,D)\n\n % ---- select based on laterality ------------------------------\n wh = coordscopy(:,1) >= -(surfacecutoff) & coordscopy(:,1) <= 0;\n pcoords = coords(wh,:);\n pcolors = colorout(wh,:);\t\t% svert is coordinates to plot\n\n\n plot_points(pcoords,pcolors,colors,plottext,mytext(wh,:),mymarkersize)\n\n % ---- plot medial surface ----\n if newmethod && newfig\n addbrain('left');\n else\n E = D;\n if newfig\n D(:,1:48,:) = [];\n D(:,:,77:end) = [];\n make_surface(D)\n D = E;\n end\n end\n\n % ===================================================================\n % * Right Medial *\n % ===================================================================\n disp('Plotting right medial coordinates.');drawnow\n\n disp('Right Medial')\n coords = coordscopy;\n\n origin = hdr.origin(1:3,1)';\n D = E;\n % adjust origin because you removed voxels\n %origin(1) = origin(1) + -48;\n % origin is spec from top, matlab plots from bottom. reverse y\n origin(2) = size(E,1) - origin(2);\n\n % coordinates entered in mm should be scaled to voxels\n coords(:,1) = round(coords(:,1) / hdr.xsize);\n coords(:,2) = round(coords(:,2) / hdr.ysize);\n coords(:,3) = round(coords(:,3) / hdr.zsize);\n\n disp(' Adjusting coordiates from mm to brain voxels');drawnow\n % adjust coords because you removed voxels\n % coords(:,1) = coords(:,1) + -48;\n % express all coordinates in voxel space, converting from distance from the origin\n for i = 1:size(coords,1)\n coords(i,:) = coords(i,:) + origin;\n end\n\n\n % --- make figure ----------------------------------------------\n if ~isempty(plothandle), axes(plothandle(2))\n else tor_fig;\n end\n hold on\n\n origin\n % plot origin\n plot3([origin(1)+5 origin(1)+5],[origin(2) origin(2)],[1 size(D,3)],'k')\n plot3([origin(1)+5 origin(1)+5],[1 size(D,1)],[origin(3) origin(3)],'k')\n hold on; drawnow\n\n % ---- select based on laterality ------------------------------\n wh = coordscopy(:,1) <= surfacecutoff & coordscopy(:,1) >= 0;\n pcoords = coords(wh,:);\n pcolors = colorout(wh,:);\n\n disp(['plotting ' num2str(size(pcoords,1)) ' points.'])\n\n legh = plot_points(pcoords,pcolors,colors,plottext,mytext(wh,:),mymarkersize,80);\n hold on;\n\n\n\n % ---- plot medial surface ----\n\n if newmethod && newfig\n addbrain('left');\n elseif newfig\n D = E;\n D(:,45:end,:) = [];\n D(:,:,77:end) = [];\n disp(' Plotting surface');drawnow\n p1 = patch(isosurface(D, 50),'FaceColor',[1,.75,.65], ...\n 'EdgeColor','none');\n p2 = patch(isocaps(D, 50),'FaceColor','interp', ...\n 'EdgeColor','none');\n %view(75,10);\n view(90,5)\n axis tight; axis image; axis off\n colormap(gray(100));camzoom(1.4);\n camlight; camlight right; lighting gouraud\n isonormals(D,p1)\n drawnow\n end\n\n h = findobj('Type','light'); delete(h)\n subplot(1,2,1); camlight left; subplot(1,2,2); camlight left;\n subplot(1,2,1); camlight right; subplot(1,2,2); camlight right;\n\n if length(varargin) > 0\n legend(legh,colornames)\n end\n\n% subplot(1,2,1)\n% camzoom(.8)\n% subplot(1,2,2)\n% camzoom(1.1)\n\n return\n\n\n\n\n\nfunction [D,hdr,origin] = read_image_data\n\n basename = 'scalped_single_subj_T1';\n [array,hdr] = readim2(basename);\n\n clear D\n for i = 1:size(array,3)\n E(:,:,i) = rot90(array(:,:,i));\n end\n\n origin = hdr.origin(1:3,1)';\n D = E;\n % adjust origin because you removed voxels\n origin(1) = origin(1) - 48;\n % origin is spec from top, matlab plots from bottom. reverse y\n origin(2) = size(E,1) - origin(2);\n\n return\n\n\n\n\n\nfunction [colorout,coords,colornames,whomit] = get_colors(colors,colordef,levelnames,coords)\n % process colors, if a varargin string is entered\n % make new colors string with one color per point, defined by colordef\n % cell string to define colors = colordef\n\n colornames = [];\n\n if isempty(levelnames), levelnames = unique(colordef); end\n\n if isempty(colordef)\n colorout = repmat(colors,size(coords,1),1)';\n else\n [indic,colornames] = string2indicator(colordef,levelnames);\n\n for i =1:size(indic,2)\n colorout(find(indic(:,i))) = colors(i);\n end\n\n end\n\n % get rid of nonselected levels\n whomit = [];\n for i = 1:length(colorout)\n if isempty(colorout{i}), whomit(i) = 1; else, whomit(i) = 0; end\n end\n colorout(find(whomit)) = [];\n coords(find(whomit),:) = [];\n\n colorout = colorout';\n return\n\n\n\n\nfunction plotorigin(origin,D)\n %origin\n % plot origin\n plot3([origin(1)-5 origin(1)-5],[origin(2) origin(2)],[1 size(D,3)],'k')\n plot3([origin(1)-5 origin(1)-5],[1 size(D,2)],[origin(3) origin(3)],'k')\n hold on; drawnow\n return\n\n\n\n\n\n\nfunction legh = plot_points(pcoords,pcolors,colornames,plottext,mytext,mymarkersize,varargin)\n\n legh = [];\n \n if length(varargin), add2x = varargin{1}; else, add2x = 0; end\n\n hold on\n disp(['plotting ' num2str(size(pcoords,1)) ' points.'])\n\n if plottext\n legh = plot3(0,0,0,colornames{1},'MarkerFaceColor',colornames{1}(1),'MarkerSize',mymarkersize);\n set(legh,'Visible','off');\n\n for i = 1:length(mytext)\n text(0+add2x,pcoords(i,2),pcoords(i,3),...\n mytext{i},'Color',pcolors{i}(1),'FontSize',12,'FontWeight','bold');\n end\n else\n\n for i = 1:length(colornames)\n % ---- select based on color group -------------------------\n plotcolors = pcolors(strcmp(pcolors,colornames{i}) == 1,:);\n svert = pcoords(strcmp(pcolors,colornames{i}) == 1,:);\n\n % ---- plot the points -------------------------------------\n hold on\n\n if ~isempty(svert)\n legh(i) = plot3(zeros(size(svert,1),1)+add2x,svert(:,2),svert(:,3),colornames{i},'MarkerSize',mymarkersize,'MarkerFaceColor',colornames{i}(1));\n end\n end\n end\n drawnow\n return\n\n\n\n\n\nfunction make_surface(D)\n disp(' Plotting surface');drawnow\n p1 = patch(isosurface(D, 50),'FaceColor',[1,.75,.65],...,...\n 'EdgeColor','none');\n p2 = patch(isocaps(D, 50),'FaceColor','interp',...\n 'EdgeColor','none');\n view(269,5); axis tight; axis image; axis off\n colormap(gray(100)); camzoom(1.35);\n camlight left; camlight; camlight left; lighting gouraud\n isonormals(D,p1)\n drawnow\n hold on\n return\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_interactive_point_slice_plot.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/plotting_functions/Meta_interactive_point_slice_plot.m", "size": 3451, "source_encoding": "utf_8", "md5": "7841a5b77d7ed22b39caa2d58c87b042", "text": "function Meta_interactive_point_slice_plot(MC_Setup, DB)\n % Meta_interactive_point_slice_plot(MC_Setup, DB)\n %\n % Set up interactive point plotting on slice\n %\n % tor wager, nov 2007\n%\n% Simple example for checking points manually, rather than setting up the interactive plotter:\n% load SETUP\n% V = DB.maskV;\n% DB.xyz = [DB.x DB.y DB.z];\n% \n% dd = DB.direction(strcmp(DB.disorder, 'SP'), :);\n% coords = DB.xyz(strcmp(DB.disorder, 'SP'), :);\n% \n% pos = spm_orthviews('Pos')\n% xyzvox = mm2voxel(pos, V.mat);\n% z = round(xyzvox(3));\n% x = round(xyzvox(1));\n% create_figure('points'); plot_points_on_slice(coords(strcmp(dd, 'ptmore'), :), 'slice', z, 'close_enough', 10, 'markerfacecolor', [1 0 0]);\n% plot_points_on_slice(coords(strcmp(dd, 'ctrmore'), :), 'slice', z, 'close_enough', 10, 'markerfacecolor', [0 0 1], 'nodraw');\n\n\n disp('Setting up Meta point plot')\n\n\n conditions = MC_Setup.Xinms;\n colors = {'b' 'r' 'g' 'y' 'm' 'k'};\n maxdistance = DB.radius_mm;\n\n wh = find(MC_Setup.connames{1} == '_'); \n if ~isempty(wh)\n wh = wh(1);\n fieldname = MC_Setup.connames{1}(1:wh-1);\n else\n fieldname = MC_Setup.connames{1};\n end\n \n myxyz = [DB.x DB.y DB.z];\n V = DB.maskV;\n\n disp('Setting graphics callback')\n\n callback_handle = @(str, pos, reg, hReg) point_plot_callback_wrapper(str, pos, reg, hReg);\n\n hSpmFig = spm_figure('GetWin', 'Graphics');\n\n hReg = uicontrol(hSpmFig, 'Style', 'Text', 'String', 'InteractiveViewer hReg', ...\n 'Position', [100 200 100 025], 'Visible', 'Off', ...\n 'FontName', 'Times', 'FontSize', 14, 'FontWeight', 'Bold', ...\n 'HorizontalAlignment', 'Center');\n hReg = spm_XYZreg('InitReg', hReg, V.mat, V.dim(1:3)');\n spm_XYZreg('Add2Reg', hReg, 0, callback_handle);\n spm_orthviews('Register', hReg);\n\n\n disp('Ready!')\n\n\n % inline\n\n function point_plot_callback_wrapper(str, pos, reg, hReg)\n\n switch str\n case 'SetCoords'\n plot_callback(pos, DB, fieldname, myxyz, conditions, colors, maxdistance, V)\n\n otherwise\n disp('Unknown callback command from spm_XYZreg');\n end\n\n end\n\nend % main function\n\n\n\nfunction plot_callback(pos, DB, fieldname, myxyz, conditions, colors, maxdistance, V)\n\n\n xyzvox = mm2voxel(pos, V.mat);\n z = round(xyzvox(3));\n x = round(xyzvox(1));\n \n create_figure('Slice view', 1, 2);\n\n subplot(1, 2, 1);\n\n for i = 1:length(conditions)\n\n xyz_to_plot = myxyz(strcmp(DB.(fieldname), conditions{i}), :);\n \n [handles, wh_slice, my_z] = plot_points_on_slice(xyz_to_plot, 'slice', z, 'markerfacecolor', colors{i}, 'marker', 'o', 'close_enough', maxdistance);\n\n left_right_counts(i, 1) = sum(xyz_to_plot(:,1) < 0 & xyz_to_plot(:, 3) >= pos(3) - maxdistance & xyz_to_plot(:, 3) <= pos(3) + maxdistance);\n left_right_counts(i, 2) = sum(xyz_to_plot(:,1) > 0 & xyz_to_plot(:, 3) >= pos(3) - maxdistance & xyz_to_plot(:, 3) <= pos(3) + maxdistance);\n \n end\n\n\n subplot(1, 2, 2);\n\n for i = 1:length(conditions)\n\n [handles, wh_slice, my_x] = plot_points_on_slice(myxyz(strcmp(DB.(fieldname), conditions{i}), :), 'slice', x, 'markerfacecolor', colors{i}, 'marker', 'o', 'close_enough', maxdistance, 'sagg');\n\n\n end\n \n\n print_matrix(left_right_counts, {'Left' 'Right'}, conditions);\n assignin('base', 'left_right_counts', left_right_counts);\n \nend "} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "bar_interactive.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/plotting_functions/bar_interactive.m", "size": 2717, "source_encoding": "utf_8", "md5": "daa6fe813508338093f4e8a909f7622a", "text": "function bar_interactive(images, xnames)\n% bar_interactive(images, xnames)\n%\n% create interactive bar-plot that pops up in spm_orthviews window\n%\n% tor wager\n%\n% 2006.05.02 - Modified by Matthew Davidson\n\n\n% find the spm window, or make one from a p-image\nspm_handle = findobj('Tag','Graphics');\nif isempty(spm_handle) || ~ishandle(spm_handle)\n cl = pmap_threshold;\n spm_handle = gcf();\nend\n\n% setup images\nif ~exist('images', 'var') || isempty(images)\n images = spm_get(Inf,'*img','Select images for bar plot');\nend\nV_images = spm_vol(images);\ndata_images = spm_read_vols(V_images);\n\n\n% setup tick names\nif exist('xnames', 'var') && ~isempty(xnames)\n % we have it\n \nelseif (~exist('xnames', 'var') || isempty(xnames)) && exist('Xinms.mat', 'file')\n load('Xinms');\n xnames = Xinms;\nelse\n xnames = [];\n %xnames = images;\n fprintf('xnames not defined. Not displaying tick names.\\n');\nend\n\n% setup figure to draw to\nbarplot_handle = findobj('Tag', mfilename);\nif(isempty(barplot_handle))\n barplot_handle = init_bar_window();\nend\n\n% set(gcf,'WindowButtonUpFcn','dat = bar_interactive_btnupfcn;')\nset(spm_handle,'WindowButtonUpFcn', {@bar_interactive_callback, barplot_handle, V_images, data_images, xnames})\n\nreturn\n\n\nfunction barplot_handle = init_bar_window()\nbarplot_handle = tor_fig();\nset(barplot_handle, 'Tag', mfilename);\n%axes('Position',[.52 .08 .45 .38]);\nreturn\n\n\n% -------------------------------------------------------------------\n% Callback\n% -------------------------------------------------------------------\n\nfunction bar_interactive_callback(spm_handle, event_data, barplot_handle, V_images, data_images, xnames) \n% the first two params (the source handle and event-related data) are\n% required by all callbacks - see documentation\n% they may be ignored if preferred; the event data may be empty\n\n\n\n% if no images selected, don't display anything.\nif isempty(V_images)\n fprintf('No images selected. Displaying nothing.\\n');\n return\nend\n\n% activate window\nif isempty(barplot_handle) || ~ishandle(barplot_handle)\n barplot_handle = init_bar_window();\nelse\n figure(barplot_handle);\nend\nset(gca,'FontSize',16);\n\n% get coordinate\nmm_coord = spm_orthviews('Pos');\nvox_coord = mm2voxel(mm_coord',V_images(1));\nmm_coord = round(mm_coord');\n\ndat = squeeze(data_images(vox_coord(1),vox_coord(2),vox_coord(3),:));\n\nhold off;\nbar_handles = bar(dat);\nset(bar_handles,'FaceColor',[.7 .7 .7]);\n\nif ~isempty(xnames), set(gca,'XTickLabel',xnames);, end\ntitle(sprintf('[x,y,z] = %3.0f, %3.0f, %3.0f',mm_coord(1),mm_coord(2),mm_coord(3)),'FontSize',16);\n\n\n% table output\n% ----------------------------------------\n%Meta_interactive_table;\nMeta_interactive_table_vox(0);\n\nreturn"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "plot_points_on_surface2.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/plotting_functions/plot_points_on_surface2.m", "size": 14495, "source_encoding": "utf_8", "md5": "7e0bd5a23c6a200b529b7a01aeb79583", "text": "function [h, pt, p] = plot_points_on_surface2(XYZ,varargin)\n% function [axishan, pointhan, surfhan] = plot_points_on_surface2(XYZ,[{color(s)}, colorclasses, {textmarkers/contrastcodes}, varargin)\n%\n% This function plots a 3-column vector of xyz points (coordinates from\n% studies) on a glass brain. Four different views are created in 2\n% figures.\n%\n% Optional inputs:\n% ------------------------------------------------------------------------\n% color: Cell array of colors, one per colorclass, or single color if all points should be same color\n% colorclasses: a vector of integers to classify the points into color categories. Each group gets a color in the colors vector.\n% textmarkers: a cell array of letter/number codes to use as markers\n% - peaks within 12 mm with the same text code are averaged together for clarity of display\n% - the idea is that textcodes identify unique contrasts from the same study\n% - 'notext': suppresses the use of text labels, but leaves the averaging\n%\n% Notes:\n% This function may not plot as many points as you enter, if they are a)\n% not near enough the surface, b) contain exactly duplicated coordinates,\n% or c) contain peaks within 12 mm with the same text code (treated as\n% same-contrast).\n% \n% Examples:\n% ------------------------------------------------------------------------\n% plot_points_on_surface2(XYZ,color);\n% plot_points_on_surface2(XYZ,color,[],letter); % plot letters!! (letter is cell array; averages nearby points with same letter code)\n%\n% Plot spheres, then set the material type on the spheres to 'default':\n% [axishan, pointhan, surfhan] = plot_points_on_surface2(DB.xyz, DB.color, DB.condf);\n% material(cat(2, pointhan{:}), 'default');\n%\n% Plot text codes:\n% [axishan, pointhan, surfhan] = plot_points_on_surface2(DB.xyz, DB.color, DB.condf, DB.textcodes, 'nospheres');\n%\n% Suppress text codes and plot points:\n% [axishan, pointhan, surfhan] = plot_points_on_surface2(DB.xyz, DB.color, DB.condf, DB.textcodes, 'notext', 'nospheres');\n%\n% Add text to existing plot, without re-rendering brain surfaces\n% [axishan, pointhan, surfhan] = plot_points_on_surface2(DB.xyz, DB.color, DB.condf, DB.textcodes, 'nospheres', 'nobrains');\n%\n%\n% Do nearby-averaging based on study ID; xyzem = [x y z]\n% plot_points_on_surface2(xyzem,{'ro'},[],EMDB.Study,1);\n%\n% Select only some Emotions, and plot those in different colors\n% [ind,nms,condf] = string2indicator(DB.Emotion);\n% condf = indic2condf(ind(:,[2 3 4 5 7])); colors = {'ro' 'gv' 'md' 'ys' 'b^'};\n% plot_points_on_surface2(DB.xyz,colors,condf,DB.Contrast,1);\n% myp = findobj(gcf,'Type','Patch');\n% set(myp,'FaceColor',[.85 .6 .5])\n% for i = 1:6, subplot(3,2,i); axis off; end\n%\n% Make a legend for this figure\n% nms = nms([2 3 4 5 7]);\n% makelegend(nms,colors,1);\n% scn_export_papersetup(200);\n% saveas(gcf,'all_surf_emotion_pts_legend','png')\n% \n% SEE ALSO: plot_points_on_subcortex.m, plot_points_on_brain.m\n\n% Edited: Tor Wager, Jan 2011, for text plotting enhancement\n% Dec 2012: Default behavior is spheres. Use 'nospheres' to use points.\n%\n% Dec 2012: Tor : Fixed bug found by Luka with color assignment when some\n% classes are empty in some plots. Affected spheres and points, but not\n% text plots. \n% - Fixed handle return\n\n%f1 = figure('Color', 'w'); \n\n\nh = [];\npt = {};\np = [];\n\nsurfdist = 22; % distance from surface to extract\ndospheres = 1;\nsuppresstext = 0;\nsuppressbrains = 0;\n\nif any(strcmp(varargin, 'nospheres')), dospheres = 0; end\nif any(strcmp(varargin, 'suppresstext')), suppresstext = 1; end\nif any(strcmp(varargin, 'notext')), suppresstext = 1; end\nif any(strcmp(varargin, 'nobrains')), suppressbrains = 1; end\n\nif suppressbrains\n % skip this\n f1 = gcf;\nelse\n f1 = create_figure('Surface Point Plot');\nend\n\ncurrent_position = get(f1, 'Position');\nset(f1, 'Position', [current_position(1:2) 1024 1280]);\nset(gca,'FontSize',18);\nhold on;\n\n\n% --------------------------------\n% set up colors\n% --------------------------------\n\n[colors, classes] = setup_colors(XYZ, varargin{:});\n\n% --------------------------------\n% set up text\n% --------------------------------\n\n[textcodes, XYZ, colors, classes] = setup_text_and_average(XYZ, colors, classes, varargin{:});\n\nif suppresstext, textcodes = []; end\n \n% --------------------------------\n% make figures -- plot points\n% --------------------------------\n\nXYZ_orig = XYZ; % original;\ntextcodes_orig = textcodes;\nclasses_orig = classes;\n\nfor i = 1:6 % for each view\n subplot(3,2,i);\n hold on\n \n h(i) = gca;\n \n XYZ = XYZ_orig;\n textcodes = textcodes_orig;\n classes = classes_orig;\n \n switch i\n case 1\n % top view, add to z\n wh = find(XYZ(:,3) <= 0);\n XYZ(wh,:) = [];\n XYZ(:,3) = XYZ(:,3) + surfdist;\n if ~isempty(textcodes), textcodes(wh) = []; end\n classes(wh) = [];\n case 2\n % bottom view\n wh = find(XYZ(:,3) >= 0);\n XYZ(wh,:) = [];\n XYZ(:,3) = XYZ(:,3) - surfdist;\n if ~isempty(textcodes), textcodes(wh) = []; end\n classes(wh) = [];\n case 3\n % left view\n wh = find(XYZ(:,1) >= 0);\n XYZ(wh,:) = [];\n XYZ(:,1) = XYZ(:,1) - surfdist;\n if ~isempty(textcodes), textcodes(wh) = []; end\n classes(wh) = [];\n case 4\n % right view\n wh = find(XYZ(:,1) <= 0);\n XYZ(wh,:) = [];\n XYZ(:,1) = XYZ(:,1) + surfdist;\n if ~isempty(textcodes), textcodes(wh) = []; end\n classes(wh) = [];\n case 5\n % front view\n %wh = find(XYZ(:,2) <= 0);\n %XYZ(wh,:) = [];\n %XYZ(:,2) = XYZ(:,2) + surfdist;\n %if ~isempty(textcodes), textcodes(wh) = []; end\n %classes(wh) = [];\n \n % right medial\n wh = find(~(XYZ(:,1) >= 0 & XYZ(:,1) <= 16));\n\n XYZ(wh,:) = [];\n XYZ(:,1) = XYZ(:,1) - 2.*surfdist;\n if ~isempty(textcodes), textcodes(wh) = []; end\n classes(wh) = [];\n case 6 \n % back view\n %wh = find(XYZ(:,2) >= 0);\n %XYZ(wh,:) = [];\n %XYZ(:,2) = XYZ(:,2) - surfdist;\n %if ~isempty(textcodes), textcodes(wh) = []; end\n %classes(wh) = [];\n \n % left medial\n wh = find(~(XYZ(:,1) <= 0 & XYZ(:,1) >= -16));\n XYZ(wh,:) = [];\n XYZ(:,1) = XYZ(:,1) + 2.*surfdist;\n if ~isempty(textcodes), textcodes(wh) = []; end\n classes(wh) = [];\n end\n \n hold on;\n if isempty(textcodes)\n % plot points, no text labels\n \n u = unique(classes);\n u(u == 0) = [];\n \n for clas = 1:length(u) % 1:max(classes)\n \n if ischar(colors{clas})\n % Text specification of color\n if dospheres\n % SPHERES\n pthan{clas} = cluster_image_sphere(XYZ(classes==u(clas), 1:3), 'color', colors{u(clas)}(1), 'radius', 4);\n \n else\n % POINTS\n if length(colors{clas}) < 2\n error('You must enter symbol and color, e.g., ''go''');\n end\n \n pthan{clas} = plot3(XYZ(classes==u(clas),1),XYZ(classes==u(clas),2),XYZ(classes==u(clas),3), ...\n ['w' colors{clas}(2)],'MarkerFaceColor',colors{u(clas)}(1),'MarkerSize',8);\n end\n \n else\n % 3-element color vector\n if dospheres\n % SPHERES\n pthan{clas} = cluster_image_sphere(XYZ(classes==u(clas), 1:3), 'color', colors{u(clas)}, 'radius', 4);\n \n else\n % POINTS\n pthan{clas} = plot3(XYZ(classes==u(clas),1),XYZ(classes==u(clas),2),XYZ(classes==u(clas),3), ...\n ['wo'],'MarkerFaceColor',colors{u(clas)},'MarkerSize',8);\n end\n end\n \n end % class\n \n pt{i} = cat(2, pthan{:}); % may break if empty? fix if so...\n \n else\n % plot text labels instead\n \n u = unique(classes);\n u(u == 0) = [];\n \n for j = 1:length(textcodes)\n % text labels\n myclass = classes(j);\n wh = u == myclass;\n \n if ischar(colors{wh})\n \n pt{j} = text(XYZ(j,1),XYZ(j,2),XYZ(j,3),...\n textcodes{j},'Color',colors{wh}(1),'FontSize',12,'FontWeight','bold');\n \n else\n pt{j} = text(XYZ(j,1),XYZ(j,2),XYZ(j,3),...\n textcodes{j},'Color',colors{wh},'FontSize',12,'FontWeight','bold');\n \n \n end\n \n end\n end\n\n drawnow\nend % for each view\n\n\n% --------------------------------\n% make figures -- add brains\n% --------------------------------\nif suppressbrains\n return\nend\n\nfor i = 1:6 % for each view\n subplot(3,2,i);\n \n \n \n switch i\n case 1\n % top view, add to z\n p(i) = addbrain('hires'); set(p,'FaceAlpha',1); drawnow;\n view(0,90); [az,el] = view; \n lh(i) = lightangle(az,el); \n set(gca,'FontSize',18)\n material dull\n case 2\n % bottom view\n p(i) = addbrain('hires'); set(p,'FaceAlpha',1); drawnow;\n view(0,-90); [az,el] = view; \n% lh(i) = lightangle(az,el); \n set(gca,'FontSize',18)\n set(gca,'YDir','Reverse')\n material dull\n %lightRestoreSingle;\n% hh(1) = lightangle(90,0);\n% hh(2) = lightangle(0,0);\n \n hh = findobj(gca, 'Type', 'light');\n delete(hh)\n camlight(180, 0)\n\n\n case 3\n % left view\n p(i) = addbrain('hires'); set(p,'FaceAlpha',1); drawnow;\n view(270,0); [az,el] = view; \n lh(i) = lightangle(az,el); \n set(gca,'FontSize',18)\n material dull\n case 4\n % right view\n p(i) = addbrain('hires'); set(p,'FaceAlpha',1); drawnow;\n view(90,0); [az,el] = view; \n lh(i) = lightangle(az,el); \n set(gca,'FontSize',18)\n material dull\n case 5\n % front view\n %view(180,0); [az,el] = view; h(i) = lightangle(az,el); set(gca,'FontSize',18)\n\n % right medial\n p(i) = addbrain('hires right'); set(p,'FaceAlpha',1, 'FaceColor', [.5 .5 .5]); drawnow;\n view(270,0); [az,el] = view; \n %lh(i) = lightangle(az,el); \n set(gca,'FontSize',18)\n material dull\n set(p(i),'FaceColor',[.5 .5 .5])\n %camzoom(.9)\n lightRestoreSingle(gca);\n\n case 6 \n % back view\n %view(0,0); [az,el] = view; h(i) = lightangle(az,el); set(gca,'FontSize',18)\n \n % left medial\n view(90,0); [az,el] = view; \n lh(i) = lightangle(az,el); set(gca,'FontSize',18)\n p(i) = addbrain('hires left'); \n set(p(i),'FaceAlpha',1, 'FaceColor', [.5 .5 .5]); drawnow;\n material dull\n camzoom(1.04)\n \n end\n \n camzoom(1.3)\n axis image;\n axis off\n %lightRestoreSingle(gca);\n scn_export_papersetup(900);\n \nend\n\n\nend % main function\n\n% ---------------------------------------------------------------------\n% ---------------------------------------------------------------------\n\n% Sub-functions\n\n% ---------------------------------------------------------------------\n% ---------------------------------------------------------------------\n\n\nfunction [colors, classes] = setup_colors(XYZ, varargin)\n\ncolors = {'ro' 'go' 'bo' 'yo' 'co' 'mo' 'ko' 'r^' 'g^' 'b^' 'y^' 'c^' 'm^' 'k^'};\n\nif length(varargin) > 0, colors = varargin{1}; end\nif length(varargin) > 1, classes = varargin{2}; else classes = ones(size(XYZ,1),1); end\n\nif isempty(classes), classes = ones(size(XYZ,1),1); end\nif ~iscell(colors), colors = {colors}; end\nif isempty(colors), colors = {'ro' 'go' 'bo' 'yo' 'co' 'mo' 'ko' 'r^' 'g^' 'b^' 'y^' 'c^' 'm^' 'k^'}; end\n\n% if we enter a vector of colors for each point, set up classes and colors\n\nif length(colors) == size(XYZ,1)\n classes = zeros(size(colors));\n coltmp = unique(colors);\n \n for i = 1:length(coltmp)\n wh = find(strcmp(colors,coltmp{i}));\n classes(wh) = i;\n end\n colors = coltmp';\nelse\n nclasses = length(unique(classes(classes~=0)));\n \n if length(colors) == 1\n disp('Using single color for all point classes because you input a single color');\n colors = repmat(colors, 1, nclasses);\n \n elseif length(colors) < nclasses\n \n disp('There seem to be too few colors in your input. Using standard colors')\n colors = scn_standard_colors(length(unique(classes(classes~=0))));\n end\n \nend\n\nend\n\n\n\n\n\nfunction [textcodes, XYZ, colors, classes] = setup_text_and_average(XYZ, colors, classes, varargin)\n\nif length(varargin) < 3\n disp(['Not plotting text codes.'])\n textcodes = [];\n \nelseif length(varargin) > 2\n textcodes = varargin{3};\nend\n\n% make textcodes into cell, if not\n% This is for averaging nearby by textcode, if the study/contrast\n% grping is not a cell array of strings.\nif ~iscell(textcodes), tmp={};\n for i = 1:size(textcodes,1), tmp{i} = num2str(textcodes(i)); end\n textcodes = tmp';\nend\n\n% if plotting text codes, make white\nif length(varargin) < 4 && ischar(colors{1}) && ~isempty(textcodes)\n for i = 1:length(colors), colors{i}(2) = '.'; end\nend\n\nif size(XYZ, 1) > 1 && ~isempty(textcodes)\n \n disp(['Averaging nearby points within 12 mm with the same text code.']);\n\n % average nearby coordinates together! 12 mm\n [XYZ,textcodes,order] = average_nearby_xyz(XYZ,12,textcodes);\n classes = classes(order);\n \n % second pass, 8 mm\n [XYZ,textcodes,order] = average_nearby_xyz(XYZ,8,textcodes);\n classes = classes(order);\n\nelseif ~isempty(textcodes)\n % one point; leave as-is\n \nelse\n textcodes = [];\n disp('Plotting all peaks; no averaging.');\nend\n\n\n\nend\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "plot_points_on_montage.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/plotting_functions/plot_points_on_montage.m", "size": 10714, "source_encoding": "utf_8", "md5": "bc4c6fbd7ee380ac51a7166712b3b4bd", "text": "function [newax, pointhandles] = plot_points_on_montage(xyz, varargin)\n% [newax, pointhandles] = plot_points_on_montage(xyz, varargin)\n%\n% Plots points on montage of slices\n% - Solid brain slices or contour outlines\n% - Points or text labels or both\n% - Flexible slice spacing, colors, marker sizes/styles, axis layout (one row/standard square)\n% - axial or saggital orientation\n% - Multiple different sets of points can be plotted in different colors/text labels\n% - if 'contrast' vector is entered, will average nearby points (12 mm) within same contrast\n%\n% Takes all inputs of plot_points_on_slice. See help for additional\n% documentation of options. In addition:\n% 'onerow' : arrange axes in one row\n% 'slice_range' : [min max] values in mm for slices to plot\n% 'colorcond' or 'condf' : vector of integers that defines colors to use\n% if used, colors should be a cell array\n% 'color' : cell array of colors for each unique (ordered) value of condf\n% 'contrast' : unique contrast numbers for each set of points, integers \n% - will average nearby points (12 mm) within same contrast\n%\n% also valid:\n% 'marker', 'points', 'MarkerSize', etc.\n% see help plot_points_on_slice.m\n%\n% Examples:\n%\n% plot_points_on_montage(DB.xyz)\n% plot_points_on_montage(xyz, 'text', DB.textcodes);\n% plot_points_on_montage(xyz, 'text', DB.textcodes, 'color', [.2 .2 1], 'onerow');\n% plot_points_on_montage(xyz, 'text', DB.textcodes, 'color', [.2 .2 1], 'onerow', 'sagittal');\n% plot_points_on_montage(xyz, 'text', DB.textcodes, 'color', [.2 .2 1], 'sagittal', 'slice_range', [-50 50]);\n% plot_points_on_montage(xyz, 'text', DB.textcodes, 'color', [.2 .2 1], 'sagittal', 'slice_range', [-40 40], 'solid', 'spacing', 20, 'close_enough', 10, 'onerow');\n\npointhandles = {};\n\nmyview = 'axial';\ndoonerow = 0;\nspacing = 8; % slice spacing, in mm\novl = which('SPM8_colin27T1_seg.img'); % which('scalped_avg152T1.img');\ntextcodes = [];\ntexthandles = [];\nslice_range = 'auto';\ncondf = [];\ncontrastvals = [];\n\ncolor = 'k';\n% facecolor = 'k';\n% marker = 'o';\n% drawslice = 1;\n% markersize = 12;\n% orientation = 'axial';\n% disptype = 'contour';\n\n\n % ------------------------------------------------------\n % parse inputs\n % ------------------------------------------------------\n\n for i = 1:length(varargin)\n if ischar(varargin{i})\n switch varargin{i}\n % reserved keywords\n \n case {'onerow'}, doonerow = 1;\n \n case 'slice_range', slice_range = varargin{i + 1};\n \n case {'spacing'}, spacing = varargin{i+1}; \n\n case {'text', 'textcodes'} % do not pass on to slice plot... \n textcodes = varargin{i + 1};\n varargin{i+1} = [];\n varargin{i} = [];\n \n case {'sag', 'sagg','saggital','sagittal'}, myview = 'sagittal';\n \n case {'condf' 'colorcond'}, condf = varargin{i + 1};\n \n % From plot_points_on_slice\n \n% case {'noslice', 'nodraw'}, drawslice = 0;\n\n case 'color' % do not pass on...\n color = varargin{i+1}; \n varargin{i+1} = [];\n varargin{i} = [];\n \n case 'contrast'\n contrastvals = varargin{i+1};\n varargin{i+1} = [];\n varargin{i} = [];\n% \n% These are redundant here, but will be passed into plot_points_on_slice\n% and are OK.\n% case 'marker', marker = varargin{i+1}; \n% \n% case {'slice', 'wh_slice'}, wh_slice = varargin{i+1};\n% \n% \n \n% \n% case {'MarkerSize', 'markersize'}, markersize = varargin{i+1};\n% \n% case {'MarkerFaceColor', 'markerfacecolor'}, facecolor = varargin{i+1};\n% \n% case 'solid', disptype = 'solid';\n% \n% case 'overlay', ovl = varargin{i + 1};\n \n %otherwise, warning(['Unknown input string option:' varargin{i}]);\n end\n end\n end\n \n% SETUP\n% -----------------------------------------------\n\nsetup_axes();\n\nif isempty(condf)\n condf = ones(size(xyz, 1), 1);\n \n if iscell(color)\n error('Color should not be a cell array.');\n end\n color = {color};\n\nelse\n if ~iscell(color)\n error('When entering condf, enter colors cell with same number of entries.');\n end\nend\n\nif ~isempty(contrastvals)\n [contrastvals, xyz, color, condf, textcodes] = setup_contrasts_and_average(xyz, color, contrastvals, textcodes, condf, varargin);\nend\n\nu = unique(condf);\nn = length(u);\n\n% Do the work for each slice\n% -----------------------------------------------\n\nfigure(slices_fig_h)\n\nfor i = 1:length(slice_vox_coords)\n axes(newax(i));\n \n drawstr = 'draw';\n \n % Dec 2013: Tor modified to handle conditions (condf) in plot_points_on_slice\n \n if ~isempty(textcodes)\n pointhandles{i} = plot_points_on_slice(xyz, 'color', color, 'MarkerFaceColor', color, myview, drawstr, 'text', textcodes, 'slice', slice_vox_coords(i), varargin{:});\n \n title(sprintf('%s%3.0f', textbase, slice_mm_coords(i)));\n \n delete(pointhandles{i});\n \n else\n pointhandles{i} = plot_points_on_slice(xyz, 'color', color, 'MarkerFaceColor', color, myview, drawstr, 'slice', slice_vox_coords(i), varargin{:});\n end\n \n drawstr = 'nodraw';\n \n% for j = 1:n % For each color code\n% \n% wh = condf == u(j);\n% \n% if ~isempty(textcodes)\n% pointhandles{i} = plot_points_on_slice(xyz(wh, :), 'color', color{j}, 'MarkerFaceColor', color{j}, myview, drawstr, 'text', textcodes(wh), 'slice', slice_vox_coords(i), varargin{:});\n% \n% title(sprintf('%s%3.0f', textbase, slice_mm_coords(i)));\n% \n% delete(pointhandles{i});\n% \n% else\n% pointhandles{i} = plot_points_on_slice(xyz(wh, :), 'color', color{j}, 'MarkerFaceColor', color{j}, myview, drawstr, 'slice', slice_vox_coords(i), varargin{:});\n% end\n% \n% drawstr = 'nodraw';\n% \n% end\n \nend\n\n% not necessary?\n%equalize_axes(newax);\n\n\n\n\n% ------------------------------------------------------\n% INLINE FUNCTIONS\n% ------------------------------------------------------\n\nfunction setup_axes\n\noverlay = which('SPM8_colin27T1_seg.img');\n[volInfo, dat] = iimg_read_img(overlay, 2);\n\nmyviews = {'axial' 'coronal' 'sagittal'}; % for selecting SPM window\nwhview = find(strcmp(myviews, myview));\nif isempty(whview), error('myview must be axial, coronal, or sagittal.'); end\n\nswitch whview\n case 1\n if strcmp(slice_range, 'auto')\n slice_range = [-45 70];\n end\n \n cen = [slice_range(1):spacing:slice_range(2)]';\n slice_mm_coords = cen;\n cen = [zeros(length(cen), 2) cen];\n xyzvox = mm2voxel(cen, volInfo.mat);\n slice_vox_coords = xyzvox(:, 3);\n case 2\n if strcmp(slice_range, 'auto')\n slice_range = [-100 65];\n end\n \n cen = [slice_range(1):spacing:slice_range(2)]';\n slice_mm_coords = cen;\n cen = [zeros(length(cen),1) cen zeros(length(cen),1)];\n xyzvox = mm2voxel(cen, volInfo.mat);\n slice_vox_coords = xyzvox(:, 2);\n case 3\n if strcmp(slice_range, 'auto')\n slice_range = [-70 70];\n end\n \n cen = [slice_range(1):spacing:slice_range(2)]';\n slice_mm_coords = cen;\n cen = [ cen zeros(length(cen), 2)];\n xyzvox = mm2voxel(cen, volInfo.mat);\n slice_vox_coords = xyzvox(:, 1);\nend\n\n\nmyviews2 = {'sagittal' 'coronal' 'axial' }; % for selecting coord\nwhcoord = strmatch(myview, myviews2) ;\n\n% get text string base\nmystr = {'x = ' 'y = ' 'z = '};\ntextbase = mystr{whcoord};\n\n% get optimal number of axes\nnum_axes = size(cen, 1);\nrc = ceil(sqrt(num_axes));\n\nslices_fig_h = figure; %create_figure(myview);\nset(slices_fig_h, 'Color', 'w');\n\nif doonerow\n ss = get(0, 'ScreenSize');\n set(gcf, 'Position', [round(ss(3)/12) round(ss(4)*.9) round(ss(3)*.9) round(ss(4)/7) ])\nend\n\nfor i = 1:num_axes\n \n if doonerow\n newax(i) = subplot(1, num_axes, i);\n else\n newax(i) = subplot(rc, rc, i);\n end\n \n axis off;\nend\n\nend % setup axes\n\nend % main function\n\n\n\n\n%[contrastvals, xyz, color, condf, textcodes] = setup_contrasts_and_average(XYZ, color, condf, varargin);\n\n\nfunction [contrastvals, xyz, color, condf, textcodes] = setup_contrasts_and_average(xyz, color, contrastvals, textcodes, condf, varargin)\n\n% if length(varargin) < 3\n% disp(['Not plotting text codes.'])\n% textcodes = [];\n% \n% elseif length(varargin) > 2\n% textcodes = varargin{3};\n% end\n\n% % make textcodes into cell, if not\n% % This is for averaging nearby by textcode, if the study/contrast\n% % grping is not a cell array of strings.\n% if ~iscell(textcodes), tmp={};\n% for i = 1:size(textcodes,1), tmp{i} = num2str(textcodes(i)); end\n% textcodes = tmp';\n% end\n% \n% % if plotting text codes, make white\n% if length(varargin) < 4 && ischar(color{1}) && ~isempty(textcodes)\n% for i = 1:length(color), color{i}(2) = '.'; end\n% end\n\ncontrasttext = mat2cell(contrastvals, ones(size(contrastvals, 1), 1), 1);\nfor i = 1:length(contrastvals)\n contrasttext{i} = num2str(contrasttext{i});\nend\n\ndisp(['Averaging nearby points within 12 mm with the same contrast value.']);\n\nif size(xyz, 1) > 1 && ~isempty(contrastvals)\n \n \n % average nearby coordinates together! 12 mm\n n = size(xyz, 1);\n [xyz,contrasttext,order] = average_nearby_xyz(xyz,12,contrasttext);\n if ~isempty(contrastvals) && length(contrastvals) == n, contrastvals = contrastvals(order); end\n if ~isempty(textcodes) && length(textcodes) == n, textcodes = textcodes(order); end\n if ~isempty(condf) && length(condf) == n, condf = condf(order); end\n \n % second pass, 8 mm\n n = size(xyz, 1);\n [xyz,contrasttext,order] = average_nearby_xyz(xyz,8,contrasttext);\n if ~isempty(contrastvals) && length(contrastvals) == n, contrastvals = contrastvals(order); end\n if ~isempty(textcodes) && length(textcodes) == n, textcodes = textcodes(order); end\n if ~isempty(condf) && length(condf) == n, condf = condf(order); end\n\nelseif ~isempty(textcodes)\n % one point; leave as-is\n \nelse\n textcodes = [];\n disp('Plotting all peaks; no averaging.');\nend\n\nend % setup contrasts...\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "meta_prob_activation.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions_density/meta_prob_activation.m", "size": 6553, "source_encoding": "utf_8", "md5": "25226cc6c7844bff299b6934aefbabbc", "text": "function [MC_Setup,activation_proportions,icon] = meta_prob_activation(DB,Xi,contrasts,connames,Xinms)\n% [MC_Setup,activation_proportions,icon] = meta_prob_activation(DB,[X indicator mtx],[contrasts],[con. names],[Xinms])\n%\n% This function writes 'Activation_proportion.img'\n% --a weighted map of the proportion of independent contrasts activating\n% each voxel in the brain --\n%\n% ...And it returns MC_Setup setup information for the whole-brain FWE\n% corrected Monte Carlo\n%\n% Additional input arguments Xi...contrasts...etc will create maps by\n% condition, and contrasts across conditions\n% This is a SECOND KIND of contrast: contrasts across study types\n% Use Meta_Logistic_Design to set up these inputs\n%\n% This function is part of Meta_Activation_Fwe\n%\n% uses:\n% DB.maskname\n% DB.radius\n% DB.Contrast (study ID number; contrast within study)\n% DB.x, DB.y DB.z\n% DB.studyweight\n%\n% Tor Wager, May 2006\n\n% Programmers' notes:\n% 4.7.2013 There was a bug in Meta_Activation_FWE that made it not robust to using \n% non-ascending numerical order of contrasts in DB.Contrast. \n% The function meta_prob_activation was reconstructing the maps in ascending order of \n% contrasts, returning maps in ascending sorted contrast order in \n% MC_Setup.unweighted_study_data. MC_Setup.Xi, the indicators for task type, are \n% sorted in the order of contrasts entered in the database, which respects the order \n% in DB.pointind and DB.connumbers from Meta_Setup. Tor changed the sort order in \n% meta_prob_activation to use DB.connumbers. \n% \n% This affects MKDA difference analyses (contrasts) when contrast numbers are not \n% entered in ascending numerical order in your database. It also affects classification \n% with Meta_NBC_from_mkda, but not Meta_SVM_from_mkda.\n\n\nif ~isfield(DB, 'maskname'), error('Missing DB.maskname. Try running Meta_Setup.'); end\nif ~isfield(DB, 'radius'), error('Missing DB.radius. Try running Meta_Setup.'); end\nif ~isfield(DB, 'Contrast'), error('Missing DB.Contrast. Try running Meta_Setup.'); end\nif ~isfield(DB, 'x'), error('Missing DB.x,y,z. Try running Meta_Setup.'); end\nif ~isfield(DB, 'studyweight'), error('Missing DB.studyweight. Try running Meta_Setup.'); end\n\n% set up mask\nstr1 = sprintf('Reading mask data'); \nfprintf(1,str1);\n\n%[maskdata,xyzlist,V] = meta_read_mask(DB.maskname);\n\n% the line above works, but this has the extra fields we need.\n[V, maskdata] = iimg_read_img(DB.maskname, 1);\nxyzlist = V.xyzlist;\n%maskdata = iimg_reconstruct_3dvol(maskdata, V);\nmaskdata = iimg_reconstruct_vols(maskdata, V);\n\nerase_string(str1);\n\nstr1 = sprintf('Setting up contrasts and initializing output'); fprintf(1,str1);\n\n% ---------------------------------------\n% set up contrasts and sizes\n% ---------------------------------------\n% cons = unique(DB.Contrast, 'stable'); % contrasts (studies)\n% tor: 4/7/2013: added 'stable' : to match order returned in Meta_Logistic_Design\n% but this does not always return same order as DB.connumbers\ncons = DB.connumbers;\n\nnc = length(cons); % number of contrasts\nv = size(xyzlist, 1); % voxels in mask\nr = DB.radius; % radius in voxels\n\n%ivectors = zeros(v,nc,'uint8'); % initialize output\nivectors = sparse(v, nc);\nn = zeros(1, nc);\n\n% set up weights (returns empty if no weights, or wt values for each con)\nwts = setup_weights(DB, nc);\n\nerase_string(str1);\n\n% ---------------------------------------\n% Convolve activation images with kernel\n% ---------------------------------------\nstr1 = sprintf('Convolving %03d contrast maps: %03d',nc,0);\nfprintf(1,str1);\n\nfor c = 1:nc\n\n fprintf(1,'\\b\\b\\b%03d', c);\n % get actual voxel coords for study (in-mask only)\n xyzvox = meta_get_voxel_coords(DB, cons(c), V, maskdata);\n\n % save number for Monte Carlo\n n(c) = size(xyzvox, 1);\n\n % get convolved indicator function\n %ivectors(:,c) = meta_fast_sphere_conv(xyzlist,xyzvox,r); OLD, not\n %used.\n ivectors(:,c) = iimg_xyz2spheres(xyzvox, xyzlist, r);\nend\n\nerase_string(str1);\n\nMC_Setup.unweighted_study_data = ivectors;\n\n% ---------------------------------------\n% apply weights (fastest method)\n% ---------------------------------------\n\nstr1 = sprintf('Applying weights'); fprintf(1, str1);\n\nfor i=1:nc, ivectors(:,i) = ivectors(:,i) .* wts(i); end\n\nerase_string(str1);\n\n% ---------------------------------------\n% get summary map and reconstruct into 3D\n% ---------------------------------------\nstr1 = sprintf('Constructing average map.'); fprintf(1,str1);\nactivation_proportions = sum(ivectors, 2);\nerase_string(str1);\nmaskdata = meta_reconstruct_mask(activation_proportions, xyzlist, V.dim(1:3), 1, V, 'Activation_proportion.img');\n\n% ---------------------------------------\n% Contrasts across conditions\n% (Apply weights in process of contrast computation\n% for compatibility with MC)\n% ---------------------------------------\nif nargin > 1\n\n if nargin < 5, Xinms = define_Xinms(Xi); end\n \n if nargin < 4, [contrasts,connames] = meta_enter_contrasts(Xi); end\n str1 = sprintf('Computing contrast maps.'); fprintf(1,str1);\n \n [icon,ctxtxi,prop_by_condition] = meta_apply_contrast(MC_Setup.unweighted_study_data, Xi, wts, contrasts);\n\n for i = 1:size(prop_by_condition,2) % for each condition, write map\n meta_reconstruct_mask(prop_by_condition(:,i), xyzlist, V.dim(1:3), 1, V, [Xinms{i} '.img']);\n end\n \n for i = 1:size(icon,2) % for each contrast, write map\n meta_reconstruct_mask(icon(:,i), xyzlist, V.dim(1:3), 1, V, [connames{i} '.img']);\n end\n \n erase_string(str1);\nend\n\n% ---------------------------------------\n% save output for MC simulation\n% ---------------------------------------\n%MC_Setup.xyzlist = xyzlist;\nMC_Setup.volInfo = V;\nMC_Setup.n = n;\nMC_Setup.wts = wts;\nMC_Setup.r = r;\n\nif nargin > 1\n MC_Setup.contrasts = contrasts;\n MC_Setup.connames = connames;\n MC_Setup.Xi = Xi;\n MC_Setup.Xinms = Xinms;\n MC_Setup.ctxtxi = ctxtxi;\n MC_Setup.con_data = icon;\nend\n\n\n\n\nreturn\n\n\n\n\n\nfunction wts = setup_weights(DB,nc)\nif isfield(DB,'studyweight') && ~isempty(DB.studyweight)\n wts = DB.studyweight;\n if length(wts) ~= nc\n error('Length of study weight vector DB.studyweight does not match number of contrasts.');\n end\nend\nreturn\n\n\nfunction erase_string(str1)\nfprintf(1,repmat('\\b',1,length(str1))); % erase string\n%fprintf(1,'\\n');\nreturn\n\n\nfunction define_Xinms(Xi)\nn = size(Xi,2);\nXinms = cell(1,n);\nfor i = 1:n\n Xinms{i} = input(['Enter name for condition ' num2str(i)],'s');\nend\nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "meta_stochastic_activation_blobs.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions_density/meta_stochastic_activation_blobs.m", "size": 3948, "source_encoding": "utf_8", "md5": "cf8f7de39e8c0b4ad27fd216f91c5493", "text": "function [maxprop,uncor_prop,maxcsize] = meta_stochastic_activation_blobs(MC_Setup)\n% MC_Setup = meta_stochastic_activation_blobs(DB)\n%\n% This function randomizes n contiguous blobs for each study within analysis mask\n% and computes null-hypothesis weighted proportion of activated studies\n% (contrasts)\n% for whole-brain FWE corrected Monte Carlo\n%\n% If we have ctxtxi field describing contrasts (set up in meta_prob_activation),\n% save summary stats by condition as well\n%\n% This function is part of Meta_Activation_FWE\n%\n% Requesting uncor_prop and maxcsize slows processing.\n%\n% Tor Wager, May 2006\n\n% Checks\nif any(isnan(MC_Setup.wts))\n error('MC_Setup.wts has NaNs. Fix before running');\nend\n\n% If we have ctxtxi field describing contrasts, save summary stats by\n% condition as well\ndo_by_condition = isfield(MC_Setup,'ctxtxi');\n\nnc = length(MC_Setup.n);\nv = size(MC_Setup.volInfo.xyzlist,1);\n\nivectors = zeros(v,1); % initialize output\n\nif do_by_condition, ivectors2 = sparse(v,nc); end % for contrasts\n\nstr1 = sprintf('Shuffling blob centers: %03d',0); fprintf(1,str1);\n\nfor c = 1:nc\n \n if mod(c,10) == 0, fprintf(1,'\\b\\b\\b%03d',c); end\n \n % Make image with random blob locations for each study\n % ------------------------------------------------\n indic = meta_stochastic_mask_blobs(MC_Setup.volInfo,MC_Setup.cl{c});\n \n if do_by_condition, ivectors2(:,c) = indic; end\n \n % weight and add to summed image vector (for speed)\n indic = indic .* MC_Setup.wts(c);\n ivectors = ivectors + indic;\n \n \nend\n\n% Get contrast values\n% ------------------------------------------------\nif do_by_condition\n % contrasts x voxels\n contrast_est = (MC_Setup.ctxtxi * ivectors2')';\nend\n\nerase_string(str1);\n\n% ------------------------------------------------\n% save summary info from this map only\n% ------------------------------------------------\nstr1 = sprintf('Saving summary info'); fprintf(1,str1);\n\nmaxprop.act = max(ivectors);\nif do_by_condition\n maxprop.poscon = max(contrast_est);\n maxprop.negcon = min(contrast_est);\nend\n\nif nargout > 1\n uncor_prop.act = prctile(ivectors,[95 99 99.9]);\n \n if do_by_condition\n uncor_prop.poscon = prctile(contrast_est,[95 99 99.9]);\n uncor_prop.negcon = prctile(contrast_est,[5 1 .1]);\n \n ncons = size(contrast_est,2);\n % transpose if multiple contrasts entered -- prctile returns col\n % vectors for multiple columns\n if ncons > 1\n uncor_prop.poscon = uncor_prop.poscon';\n uncor_prop.negcon = uncor_prop.negcon';\n end\n end\n \n if nargout > 2\n for i = 1:length(uncor_prop.act)\n \n maxcsize.act(i) = get_max_cluster_size(ivectors, MC_Setup.volInfo.xyzlist,uncor_prop.act(i));\n \n if do_by_condition\n % uncor.prop.poscon : rows are contrasts, cols are\n % different thresholds\n \n for j = 1:ncons\n maxcsize.poscon(j,i) = get_max_cluster_size(contrast_est(:,j), MC_Setup.volInfo.xyzlist,uncor_prop.poscon(j,i));\n maxcsize.negcon(j,i) = get_max_cluster_size(-contrast_est(:,j), MC_Setup.volInfo.xyzlist,-uncor_prop.negcon(j,i));\n end\n end\n end\n end\nend\n\nerase_string(str1);\n\n\nreturn\n\n\nfunction maxcsize = get_max_cluster_size(ivectors,xyzlist,prop)\n\n% save max cluster size info\nwh = find(ivectors >= prop);\n\n% If empty, no voxels above threshold\nif isempty(wh), maxcsize = 0; return, end\n\nif length(wh) > 50000, maxcsize = Inf; end\n\nxyz = xyzlist(wh,:)';\nclust = spm_clusters(xyz);\nu = unique(clust);\n\nclsize = []; % init to avoid error in Matlab 2013/csize is a function\nfor i = 1:length(u)\n clsize(i) = sum(clust == i);\nend\n\nmaxcsize = max(clsize);\n\nreturn\n\n\n\nfunction erase_string(str1)\nfprintf(1,repmat('\\b',1,length(str1))); % erase string\n%fprintf(1,'\\n');\nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "meta_reconstruct_mask.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions_density/meta_reconstruct_mask.m", "size": 1472, "source_encoding": "utf_8", "md5": "5f0af7cd563f4f0271fe30ff9777087f", "text": "% reconstruct mask for a study, given indicator\n% v2 = meta_reconstruct_mask(indic, xyzlist, V.dim(1:3), [use values], [V], [imagename]);\n%\n% This function returns 3D mask values and optionally writes an image file\n% if V and imagename are entered as additional arguments\n%\n% dims are mask dimensions; V is spm_vol structure\n% indic: see meta_fast_sphere_conv\n% xyzlist: see meta_read_mask\n%\n% [use values]: optional; use indic values in voxels (for saving count\n% values)\n\nfunction v2 = meta_reconstruct_mask(indic, xyzlist, dims, varargin)\n\n if length(varargin) > 0, valueflag = varargin{1}; else valueflag = 0; end\n\n wh = find(indic); % which indices, in in-mask XYZ list\n\n % reconstruct mask\n v2 = zeros(dims);\n wh2 = sub2ind(dims, xyzlist(wh,1), xyzlist(wh,2), xyzlist(wh,3));\n\n if valueflag\n v2(wh2) = indic(wh);\n else\n v2(wh2) = 1; % faster\n end\n\n % write image file only if additional arguments are entered\n if length(varargin) > 1\n V = varargin{2};\n else\n return\n end\n\n if length(varargin) > 2\n V.fname = varargin{3};\n end\n\n warning off Matlab:DivideByZero % turn off in case of empty image\n warning off MATLAB:intConvertNaN\n str1 = sprintf('Writing: %s', V.fname);\n fprintf(1, str1);\n spm_write_vol(V, v2);\n\n erase_string(str1);\nend\n\n\n\nfunction erase_string(str1)\n fprintf(1, repmat('\\b', 1, length(str1))); % erase string\n %fprintf(1,'\\n');\nend\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "meta_stochastic_activation.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility3/Support_functions_density/meta_stochastic_activation.m", "size": 1879, "source_encoding": "utf_8", "md5": "b40531780448226cd3ad5baddfbe00f1", "text": "function [maxprop,uncor_prop,maxcsize] = meta_stochastic_activation(MC_Setup)\n% MC_Setup = meta_stochastic_activation(DB)\n%\n% This function randomizes n locations for each study within analysis mask\n% and computes null-hypothesis weighted proportion of activated studies\n% (contrasts)\n% for whole-brain FWE corrected Monte Carlo\n% \n% This function is part of Meta_Activation_Fwe\n%\n% Requesting uncor_prop and maxcsize slows processing.\n%\n% Tor Wager, May 2006\n\n\nnc = length(MC_Setup.n);\nv = size(MC_Setup.xyzlist,1);\n\nivectors = zeros(v,1); % initialize output\n\nstr1 = sprintf('Convolving: %03d',0);,fprintf(1,str1);\n\nfor c = 1:nc\n\n fprintf(1,'\\b\\b\\b%03d',c);\n \n % get convolved, randomized coords for this study\n indic = meta_stochastic_mask(MC_Setup.xyzlist,MC_Setup.n(c),MC_Setup.r);\n\n % weight and add to summed image vector\n indic = indic .* MC_Setup.wts(c);\n ivectors = ivectors + indic;\n \nend\n\nerase_string(str1);\n\n% ------------------------------------------------\n% save summary info from this map only\n% ------------------------------------------------\nstr1 = sprintf('Saving summary info');,fprintf(1,str1);\n\nmaxprop = max(ivectors);\n\nif nargout > 1\n uncor_prop = prctile(ivectors,[95 99 99.9]);\n\n if nargout > 2\n for i = 1:length(uncor_prop)\n\n maxcsize(i) = get_max_cluster_size(ivectors, MC_Setup.xyzlist,uncor_prop(i));\n\n end\n end\nend\n\nerase_string(str1);\n\n\nreturn\n\n\nfunction maxcsize = get_max_cluster_size(ivectors,xyzlist,prop)\n% save max cluster size info\nwh = find(ivectors >= prop);\n\nif length(wh) > 50000, maxcsize = Inf;, end\n\nxyz = xyzlist(wh,:)';\nclust = spm_clusters(xyz);\nu = unique(clust);\nfor i = 1:length(u)\n csize(i) = sum(clust == i);\nend\nmaxcsize = max(csize);\nreturn\n\n\n\nfunction erase_string(str1)\nfprintf(1,repmat('\\b',1,length(str1))); % erase string\n%fprintf(1,'\\n');\nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "density_results_table.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility/density_plots_tables/density_results_table.m", "size": 2263, "source_encoding": "utf_8", "md5": "542088f71cfc205e577af1b3fd986ac7", "text": "function density_results_table(OUT)\n% density_results_table(OUT)\n% \n% prints table of results for density_pdf or density_diff_pdf\n% Tor Wager\n\n\nfprintf(1,'Density results for %s\\n',OUT.fname)\nfprintf(1,'Brain mask file: %s with %3.2f x %3.2f x %3.2f mm voxels',OUT.mask_file,OUT.voxsize(1),OUT.voxsize(2),OUT.voxsize(3))\nfprintf(1,'\\nAlpha = %3.3f\\n',OUT.crit_p)\nfprintf(1,'\\n--------------------------------------------------------------------------------\\n')\n\nfprintf(1,'Main effect results for mask 1, %3.0f points\\n',OUT.n)\nsub_table(OUT.u, OUT.th, OUT.cls, OUT.sz_u,OUT.cl_u)\n\nif isfield(OUT,'cl_u2') % check for a field made only by density_diff_pdf\n \n fprintf(1,'Main effect results for mask 2, %3.0f points\\n',OUT.n2)\n sub_table(OUT.u2, OUT.th, OUT.cls, OUT.sz_u2,OUT.cl_u2)\n \n fprintf(1,'Difference effect for mask 1-2\\n')\n sub_table(OUT.du, OUT.th, OUT.cls, OUT.sz_du,OUT.cl_du)\n \n fprintf(1,'Difference effect for mask 2-1\\n')\n sub_table(OUT.du2, OUT.th, OUT.cls, OUT.sz_du2,OUT.cl_du2)\n \nend\n\nfprintf(1,'\\nSize threshold: %3.0f%% of the time, under Ho, no cluster will exceed this number of voxels',100*(1-OUT.crit_p))\nfprintf(1,'\\nNum threshold: %3.0f%% of the time, under Ho, there will be fewer than this number of \\n\\t\\t\\t\\t clusters of this size',100*(1-OUT.crit_p))\n\n\n\nfunction sub_table(u,th,cls,sz,numc)\n% numc : matrix of number of clusters\n% rows index density thresholds\n% columns index cluster size thresholds\n% with (th x cls) elements\n%\n% sz and numc are threshold values - not the original OUT.numc\n% so they're the 95% random pdf value of numc and cl_size\n\nfprintf(1,'\\tCritical height threshold for any density\\t%3.4f\\n',u)\nfprintf(1,'\\tAt prespecified threshold')\nfor i = 1:length(th)\n fprintf(1,'\\t%3.4f',th(i))\nend\nfprintf(1,'\\n\\t\\t ---------------------------------\\n')\nfprintf(1,'\\tSize threshold ')\n\nfor i = 1:length(th)\n fprintf(1,'\\t%3.0f\\t',sz(i))\nend\n\nfor j = 1:length(cls)\nfprintf(1,'\\n\\tNum. of sz > %3.0f \\t',cls(j))\n \n for i = 1:length(th)\n fprintf(1,'\\t%3.0f\\t',numc(i,j))\n end\n \nend\n\nfprintf(1,'\\n--------------------------------------------------------------------------------\\n')\n\nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "whole_brain_ptask_givena.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility/density2_calculations/whole_brain_ptask_givena.m", "size": 6722, "source_encoding": "utf_8", "md5": "960019afe1f0029c338b1d2d61acad07", "text": "function OUT = whole_brain_ptask_givena(OUT,varargin)\n% OUT = whole_brain_ptask_givena(OUT,verbose level, mask image or threshold value(for pa_overall) )\n% OUT = whole_brain_ptask_givena(OUT,2,.001)\n% verbose flag\nif length(varargin) > 0, vb = varargin{1};, else, vb = 1;, end\n\nP = OUT.PP;\ntask_indicator = OUT.allcondindic;\nfield = OUT.testfield;\nnames = OUT.allcondnames;\n\n% image dimensions, etc.\nV = spm_vol(P(1,:));\nVall = spm_vol(P);\n\nglobal dims\nglobal cols\n\ndims = V.dim(1:3);\n\nif vb > 0, fprintf(1,'\\n\\t\\tNew image dims: %3.0f %3.0f %3.0f %3.0f ',dims(1), dims(2), dims(3), cols),end\n\n% ---------------------------------------\n% brain masking\n% ---------------------------------------\n\nmask = []; \nif length(varargin) > 1, \n mask = varargin{2};, \n if isstr(mask), Vm = spm_vol(mask);, mask = spm_read_vols(Vm);,\n % if a mask file, then load it\n elseif length(mask) == 1\n % if a number, treat this as threshold value for pa_overall\n % I recommend .001, which is a 0.1% chance of activating across all\n % tasks\n Vm = spm_vol('pa_overall.img'); maskimg = spm_read_vols(Vm);,\n mask = real(maskimg > mask); % threshold \n end\nend\nif isempty(mask), mask = ones(dims);,end\n\n\n% -------------------------------------------------------------------\n% * define output image names\n% -------------------------------------------------------------------\nfor i = 1:length(names)\n names{i} = [field '_' names{i}];\nend\n\n\n \n% -------------------------------------------------------------------\n% * for each slice...\n% -------------------------------------------------------------------\n\nfor slicei = 1:dims(3)\n \n if vb > 1, t1 = clock;, fprintf(1,'\\nSlice %3.0f \\n------------>\\n ',slicei),end\n \n % returns image names\n [x2,x2p,eff,z,p] = process_slice(slicei,Vall,task_indicator,field,names,vb,mask(:,:,slicei));\n\n if ~isempty(x2), x2f = x2;, end % final versions\n if ~isempty(x2p), x2pf = x2p;, end \n if ~isempty(eff), efff = eff;, end \n if ~isempty(z), zf = z;, end\n if ~isempty(p), pf = p;, end \n \n if vb > 1, fprintf(1,'\\t%6.0f s for slice',etime(clock,t1)),end\nend\n\nOUT.x2 = x2f;\nOUT.x2p = x2pf;\nOUT.eff = efff;\nOUT.z = zf;\nOUT.p = pf;\n\nstr = ['save STATS_VARS_' field ' OUT'];\neval(str)\n\nreturn\n\n\n\n\n\n\n\n% -------------------------------------------------------------------\n%\n%\n%\n%\n% * SUB-FUNCTIONS\n%\n%\n%\n%\n% ------------------------------------------------------------------- \n \n \nfunction [x2,x2p,eff,z,p] = process_slice(slicei,Vall,task_indicator,field,names,vb,varargin)\n\nx2 = []; x2p = []; eff = []; z = []; p = [];\nmask = []; if length(varargin) > 0, mask = varargin{1};, end\nsl = []; if length(varargin) > 1, sl = varargin{1};, end\n\nglobal dims\nglobal cols\n\n% -------------------------------------------------------------------\n% * load the slice\n% -------------------------------------------------------------------\n\nif isempty(sl)\n \nif vb > 0, fprintf(1,'\\tLoading data >'), end \net = clock;\nif ~isempty(mask) & ~(sum(sum(sum(mask))) > 0)\n % skip it\n fbetas = NaN * zeros([dims(1:2) cols]);\n ntrimmed = NaN;\n if vb > 1, fprintf(1,'...Empty slice...'), end\n return\nelse\n sl = timeseries_extract_slice(Vall,slicei);\nend\n\nif vb > 1, fprintf(1,'loaded in %3.2f s.',etime(clock,et)),end\n\nelse\n % we've already loaded the slice!\n \nend\n\nif ~isempty(mask), sl(:,:,1) = sl(:,:,1) .* mask;, end\n\n\n% -------------------------------------------------------------------\n% * find in-mask voxels\n% -------------------------------------------------------------------\n\nsumsl = sum(sl,3); % sum of all contrasts\n\n% find indices i and j for all in-mask voxels\nwvox = find(sumsl ~= 0 & ~isnan(sumsl));\n[i,j] = ind2sub(size(sl(:,:,1)),wvox);\n\nfprintf(1,'\\n\\tCalculating P(Task|Activity) for %3.0f voxels > ',length(i))\n\n\n% -------------------------------------------------------------------\n% * compute p(T|A) for each in-mask voxel\n% -------------------------------------------------------------------\nnsize = size(sl); \nnsize = [nsize(1:2) size(task_indicator,2)]; % vox x vox x task condition\n\n% output images -- initialize\nx2field = zeros(nsize(1:2)); % chi2 overall for test field\npfield = zeros(nsize(1:2)); % p-value\n\nlevels = zeros(nsize); % effect size for each level\nlevelz = zeros(nsize); % z-score \nlevelp = zeros(nsize); % p-value\n\net = clock;\nfor k = 1:length(i)\n\n y = squeeze(sl(i(k),j(k),:)); \n \n % could use optional arg here to use %, but now treats everything as\n % activated or not\n [pt_given_a,eff,z,p,stat] = p_task_given_activation(task_indicator,y);\n \n x2field(i(k),j(k)) = stat.x2;\n pfield(i(k),j(k)) = stat.x2p;\n \n levels(i(k),j(k),:) = eff';\n levelz(i(k),j(k),:) = z';\n levelp(i(k),j(k),:) = p';\n \n if k == 1000, fprintf(1,'%3.0f s per 1000 vox.',etime(clock,et)), end\nend\n\n\nclear sl\n\n\n\n% -------------------------------------------------------------------\n% * write output images\n% ------------------------------------------------------------------- \n\nemptyimg = zeros(dims); % in case we need to create a new volume, used later as well\n \nwarning off\nif vb > 1, fprintf(1,'\\n\\tWriting f (filtered) plane > '), end\n\nx2 = write_beta_slice(slicei,Vall(1),x2field,emptyimg,[field '_chi2_']);\nx2p = write_beta_slice(slicei,Vall(1),pfield,emptyimg,[field '_chi2p_']);\neff = write_beta_slice(slicei,Vall(1),levels,emptyimg,[field '_p(t|a)_eff_'],names);\nz = write_beta_slice(slicei,Vall(1),levelz,emptyimg,[field '_p(t|a)_z_'],names);\np = write_beta_slice(slicei,Vall(1),levelp,emptyimg,[field '_p(t|a)_p_'],names);\n\nwarning on\n\n \n \nreturn\n\n\n\n\n\n\n\nfunction Pw = write_beta_slice(slicei,V,betas,emptyimg,varargin)\n% Pw = write_beta_slice(sliceindex,V,data,empty,prefix)\n% Slice-a-metric version\nwarning off % due to NaN to int16 zero conversions\nV.dim(4) = 16; % set to float to preserve decimals\n\nprefix = 'check_program_';\nnames = {''}; % for field only\nif length(varargin) > 0, prefix = varargin{1};,end % field name\nif length(varargin) > 1, names = varargin{2};,end % level names\n\nfor voli = 1:size(betas,3) % for each image/beta series point\n %if voli < 10, myz = '000';, elseif voli < 100, myz = '00';, else myz = '000';,end\n V.fname = [prefix names{voli} '.img'];\n V.descrip = ['Created by whole_brain_ptask_givena '];\n\n % create volume, if necessary\n if ~(exist(V.fname) == 2), spm_write_vol(V,emptyimg);,end\n \n spm_write_plane(V,betas(:,:,voli),slicei);\n \n if ~(exist('Pw')==1), Pw = which(V.fname);, \n else Pw = str2mat(Pw,which(V.fname));\n end\n \nend\n\n\n\nwarning on\nreturn\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "dbcontrast2density.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility/density2_calculations/dbcontrast2density.m", "size": 12544, "source_encoding": "utf_8", "md5": "1e6e65bfc3d58df6c4b01e3bc2771353", "text": "function [dmt,clusters,dm,OUT] = dbcontrast2density(DB,u,varargin)\n% function [dmt,clusters,dm,OUT] = dbcontrast2density(DB,u,[radius_mm],[testfieldname],[contrast over levels],[con_dens_images])\n% \n% XYZ is 3-column vector of coordinates\n%\n% Tor Wager 11/20/04\n%\n% step 1: read database\n% step 2: database2clusters -- get database structure (don't use clusters; can enter any clusters here)\n% \n%\n% examples:\n% [dmt,clusters,dm,OUT] = dbcontrast2density(EMDB,.05,10,'valence');\n%\n% load meta_analysis_master_file\n% dbcontrast2density(PAINDB3,.05,15,'Right_vs_Left');\n% dbcontrast2density(PAINDB3,.05,15,'Right_vs_Left',[1 1 0]); % for r vs l\n%\n\ndiary ANALYSIS_INFORMATION.txt\n\nP = ['brain_avg152T1.img']; % 2 mm voxels\nP = 'scalped_avg152T1_graymatter_smoothed.img';\n\nif length(varargin) > 0, radius_mm = varargin{1}; \nelse, radius_mm = 10;\nend\ndisp(['Radius is ' num2str(radius_mm) ' mm.'])\n\nmask_file = P;\nt1 = clock;\nfprintf(1,'Setup. ')\n\n% -----------------------------------------------------\n% * load standard brain\n% -----------------------------------------------------\nP = which(P);\nV = spm_vol(P);\nmask = zeros(V.dim(1:3));\n\nvoxsize = diag(V(1).mat)';\nvoxsize = voxsize(1:3);\nradius = radius_mm ./ mean(voxsize);\nsphere_vol = 4 * pi * radius_mm ^ 3 / 3;\n\n\n\n% -----------------------------------------------------\n% identify field info to save with each contrast image in a .mat file\n% -----------------------------------------------------\n% IN FUTURE, SAVE ONLY VARIABLES OF INTEREST, ENTERED IN VAR LIST?\nN = fieldnames(DB); fieldn = {};\nfor i = 1:length(N)\n str = ['tmp = DB.' N{i} ';'];\n eval(str)\n if length(tmp) == length(DB.x) % if this field has all info for each peak\n fieldn(end+1) = N(i);\n end\nend\n\n\n\n% -----------------------------------------------------\n% identify independent contrasts\n% -----------------------------------------------------\ntestfield = 'valence';\nif length(varargin) > 1, testfield = varargin{2};,end\n\nOUT = get_contrast_indicator(DB,testfield);\n\n% critical test condition names for each point\neval(['OUT.allcond = DB.' testfield ';']);\nOUT.study = DB.study;\nOUT.xyz = [DB.x DB.y DB.z];\nOUT.radius = radius_mm;\n\n% mask image -- gray matter\nOUT.maskV = V;\n\n% deal OUT structure back to variables\nN = fieldnames(OUT);\nfor i = 1:length(N)\n str = [N{i} ' = OUT.' N{i} ';'];\n eval(str)\nend\n\n% save input variables in this directory\ndisp('input variables saved in all_input_variables.mat');\nsave ALL_INPUT_VARIABLES DB u varargin\n\ndiary off\n\n% -----------------------------------------------------\n% for each contrast, make a density image\n% -----------------------------------------------------\n\n\nPP = []; % image names\nif length(varargin) > 3, PP = varargin{4}; ,end % load input filenames here!!\n \nif isempty(PP)\n \n % normalize density maps so that 1 activation = value of 1 in map\n % the code below sets the normalization factor based on the smoothing kernel \n tmp = mask; tmp2 = round(size(mask)./2);\n tmp(tmp2(1),tmp2(2),tmp2(3)) = 1;\n spm_smooth(tmp,tmp,radius); % in vox if not a mapped vol! \n normby = max(tmp(:));\n\n\n % Try to find images first, and if they don't exist in current dir,\n % create.\n fprintf(1,'Creating images.')\n \n \n for i = 1:length(studynames)\n \n wh = find(strcmp(study,studynames{i}) & strcmp(allcond,allconditions{i})); % peaks in this study, this contrast\n XYZmm = xyz(wh,:);\n XYZmm(any(isnan(XYZmm),2),:) = [];\n \n str = [studynames{i} '_contrast_' num2str(connumbers(i)) '.img']; % name of image\n if exist(str) == 2, disp(['Found existing: ' str])\n \n else\n % doesn't exist yet; create it\n if isempty(XYZmm)\n conmask = mask;\n else\n XYZvox = mm2vox(XYZmm,V.mat); % get voxel coordinates\n \n conmask = xyz2mask(mask,XYZvox); % put points in mask - could weight by Z-scores here, if desired.\n spm_smooth(conmask,conmask,radius) %_mm); % smooth it! radius in voxels if no header info is given.\n \n conmask = conmask ./ normby; % normalize so center of study activation = 1 \n conmask(conmask > 1) = 1; % limit to max of 1, in case multiple nearby points in same contrast\n % max activation for a single\n % contrast is 1.\n \n conmask = conmask .* studyweight(i); % sample size weighting by sqrt relative sample size\n end\n \n V.fname = str;\n warning off, spm_write_vol(V,conmask);, warning on\n \n end % if find existing \n \n % Also create a .mat file containing values of all variables\n matstr = [studynames{i} '_contrast_' num2str(connumbers(i)) '_info.mat'];\n if exist(matstr) == 2, \n disp(['Found existing: ' matstr])\n else\n for j = 1:length(fieldn)\n str2 = ['CONTRAST.' fieldn{j} ' = DB.' fieldn{j} '(connumbers(i));']; %'(conindex(i));'];\n eval(str2)\n end\n str2 = ['save ' matstr(1:end-4) ' CONTRAST'];\n eval(str2)\n end\n \n\n PP = str2mat(PP,str);\n \n end % loop thru contrasts\n PP = PP(2:end,:);\nelse\n % we have filenames already created\nend\n\nfprintf(1,'Done %3.0f images in %3.0f s',length(studynames),etime(clock,t1))\n \nOUT.PP = PP;\n\n% -----------------------------------------------------\n% across all density images, compute prob(activation), p(a)\n% -----------------------------------------------------\ntor_spm_mean_ui(PP,'pa_overall.img');\n\nOUT.allcond = allcond;\nOUT.study = study;\n\ndisp('outputs of dbcontrast2density saved in all_input_variables.mat');\ndisp('Use info in this file to run next step');\nsave ALL_INPUT_VARIABLES DB u varargin OUT\n\n\n% END SETUP\n\n\n% -----------------------------------------------------\n% across images for each cond., compute prob(activation) given condition,\n% p(a)|task\n% get FDR-corrected clusters\n% -----------------------------------------------------\ncl = threshold_pa_overall(OUT);\n\n\n\n% -----------------------------------------------------\n% compute p(task|activation) for each level of the variable\n% save .img files with chi2 overall, p maps for factor as a whole\n% and effect, z, and p maps for each level.\n% positive values for eff are an increase in p(t|a) by x% over\n% the base-rate for the task (p(t)). \n% negative values mean that the task is LESS likely than expected\n% from the base rate by x%\n%\n% saves OUT in STATS_VARS_testname.mat\n% -----------------------------------------------------\n\nOUT = whole_brain_ptask_givena(OUT,2,.001);\n\n[OUT.zthresh_pos] = threshold_imgs(OUT.z,norminv(1-.01),3,'pos');\nfor i = 1:size(OUT.zthresh_pos,1)\n cl{i} = mask2clusters(OUT.zthresh_pos(i,:),OUT.z(i,:));\nend\nOUT.clusters = cl; % clusters showing task specificity\n\n% display results\ncolors = {[1 0 0] [0 1 0] [0 0 1] [1 1 0] [0 1 1] [1 0 1]};\ncluster_orthviews(cl{1},colors(1));\nfor i = 2:length(cl)\n if ~isempty(cl{i})\n cluster_orthviews(cl{i},colors(i),'add');\n end\nend\n\nmeth = zeros(size(DB.method));\nmeth(find(strcmp(DB.method,'auditory'))) = 1;\nmeth(find(strcmp(DB.method,'imagery'))) = 2;\nmeth(find(strcmp(DB.method,'recall'))) = 3;\nmeth(find(strcmp(DB.method,'visual'))) = 4;\nplot_points_on_brain([DB.x DB.y DB.z],{'ro' 'gs' 'b^' 'yv'},meth);\n\nplot_points_on_medial_surface([DB.x DB.y DB.z],{'ro' 'gs' 'b^' 'yv'},DB.method,{'auditory' 'imagery' 'recall' 'visual'});\n\n\n% -----------------------------------------------------\n% Load another variable and test that one\n% -----------------------------------------------------\ndiary ANALYSIS_INFORMATION.txt\ndisp('RUNNING NEW ANALYSIS ON SAME CONTRAST IMAGES')\nOUT = get_contrast_indicator(DB,'method','load',OUT)\ndiary off\n\n\n% NOW WORK ON THE CHI2 VALUES FOR DIFFS AMONG CONDITIONS\n% COMPUTE CHI2 VALUE AT EACH VOXEL\n% WE NEED ROWS = VOXELS, COLUMNS = P(ACT|TASK X), OR % STUDIES IN TASK X\n\n% -----------------------------------------------------\n% across images for each cond., compute prob(activation) given condition,\n% p(a)|task\n% -----------------------------------------------------\n\n% select conditions to test across\nif length(varargin) > 2, contrast = varargin{3}; ,\nelse\n contrast = ones(length(OUT.allcondindic));\nend\n \n\nallcondindic = OUT.allcondindic(:,find(contrast));\nallcondnames = OUT.allcondnames(find(contrast));\n\n\n% number of contrasts in each map\nnumcons = sum(allcondindic);\n \nfor i = 1:size(allcondindic,2) % for each level\n names = OUT.PP(find(allcondindic(:,i)),:);\n nstr = ['pa_given_' allcondnames{i} '.img'];\n tor_spm_mean_ui(names,nstr);\n \n % convert probability scores to count for chi2 test\n V = spm_vol(nstr); v = spm_read_vols(V);\n v = v .* numcons(i); % counts!\n ncstr = ['counts_given_' allcondnames{i} '.img'];\n V.fname = ncstr;\n spm_write_vol(V,v);\n \n if i == 1,\n OUT.cntimgnames = ncstr;\n else\n OUT.cntimgnames = str2mat(OUT.cntimgnames,ncstr);\n end\nend\n\n% load images and make voxels x conditions matrix countdat\nV = spm_vol(OUT.cntimgnames); v = spm_read_vols(V);\n\nVmask = spm_vol(which(mask_file)); vm = spm_read_vols(Vmask);\nwh = find(vm>0); % wh contains indices in mask, for use later to convert back to voxels!\n \nclear countdat\nfor i = 1:size(v,4) % for each condition\n vtmp = v(:,:,:,i);\n countdat(:,i) = vtmp(wh);\nend\n\n% eliminate voxels w/ zeros in all conds\nwhzero = find(all(countdat mask\n%\t\tmask2density.m\t\t\tmask of coords -> density map\n%\n% for null hypothesis distribution generation:\n%\t\tgenerate_rdms.m\tgiven: no. to generate, no. of points, mask size\n%\t get_random_mask.m\tgenerate random list of coords\n%\t\t\tvoxel2mask.m \n%\t\t\tmask2density.m\t\t\tdensity map of null distribution\n%\t\t\tspm_write_vol.m\t\twrite output analyze image\n%\n%\t\tdensity_npm_p.m\t\t\tcluster p-value, and critical k \n%\t\t\t\t\t\t\t\t\t\tgiven list of rdm images and threshold u\t\t\t\n%\t\t\tcount_clusters.m\t\tdensity map -> no. of points, clusters \n%\t\t\t\t\t\t\t\t\t\tat density threshold u\n%\t\t\t\t\t\t\t\t\t\tat a range of thresholds (input)\n%\t\t\t\t\t\t\t\t\t\treturns the number and avg. size of clusters\n%\t\t\tthen finds p value based on distribution and 95% level\n\nverbose = 0;\nif verbose, t1 = clock;, end\n\nif length(varargin) > 1\n sphere_vol = varargin{2};\nelse \n sphere_vol = 0;\nend\n\nif length(varargin) > 0\n searchmask = varargin{1};\n if isempty(searchmask), searchmask = ones(size(mask));, end\nelse\n searchmask = ones(size(mask));\nend\n\nif any(size(mask) - size(searchmask))\n error('Mask and searchmask must be of the same dimensions and have the same voxel sizes!')\nend\n\nfmethod = 0;\nswitch fmethod\n \n \ncase 0\n % GAUSSIAN CONVOLUTION \n \n % get weight function for distance (gaussian)\n % this is how much a point of distance x will contribute\n %--------------------------------------------------------------------------\n % convert FWHM to stand dev (sigma)\n %---------------------------------------------------------------------------\n global weightfun\n sx = radius;\n \n if isempty(weightfun)\n % sx is in voxels at this point.\n sx = sx/sqrt(8*log(2)) + eps;\n [lx] = max(size(mask));\n Ex = min([ceil(3*sx) lx]);\n x = [-Ex:Ex];\n\n % distance weighting kernel\n kx = exp(-x.^2/(2*sx^2)) ; \n\n % normalize kernel so that sum is 1 over 3-d convolution space\n normby = sum(kx); % for 1-D\n normby = 4 ./ 3 * pi * sum(kx).^3; % for 3-D\n kx= kx ./ normby;\n\n weightfun = kx;\n end\n \n %dm = spm_conv_vol(mask,zeros(size(mask)),weightfun,weightfun,weightfun,[0 0 0]); \n \n %mask = zeros(64);\n %xyz = round(randn(20,3).^2 * 20);\n %xyz(xyz == 0) = 1;\n x%yz(xyz > 64) = 5;\n %mask(xyz(:,1),xyz(:,2),xyz(:,3)) = 1;\n dm = zeros(size(mask));\n spm_smooth(mask,dm,radius);\n \n \n \ncase 1\n% NOT USED\n\n% --------------------------------------------------------------------------------------\n% * define sphere to convolve with mask\n% --------------------------------------------------------------------------------------\n% MUCH slower.\nsph = get_sphere(radius);\ndm2 = convn(mask,sph,'same');\n\ncase 2\n% SPHERES\n\n\n% --------------------------------------------------------------------------------------\n% * define search space: coordinate list of whole mask\n% --------------------------------------------------------------------------------------\nif verbose, fprintf(1,'defining search space ... '), end\n% [x,y,z] = ind2sub(size(searchmask),find(searchmask)); % find coords of values > 0 in mask\n[x,y,z] = ind2sub(size(mask),find(searchmask > 0)); % find coords of values > 0 in mask\nvindex = [x y z]';\n\n% old way: slower\n% vindex = build_voxel_index(mask);\n\nQ = ones(1,size(vindex,2));\ndm = zeros(size(mask));\nslices = vindex(3,:); % used to pass only certain slices to subfunctions\n\n\n% --------------------------------------------------------------------------------------\n% * locate coordinates in mask to make spheres around\n% --------------------------------------------------------------------------------------\n[x,y,z] = ind2sub(size(mask),find(mask)); % find coordinates of values > 0 in mask\nvr = [x y z]';\n\nif verbose, fprintf(1,'\\nrestricting to spheres around %3.0f points ... ',size(vr,2)), end\n\n% the idea here is to pass into add_density_sphere only coordinates\n% that are in slices that could possibly be within the sphere, to speed things up.\n% this next line tells us when we need to update to new slices\n% when the slice changes, we need a new set of slices to pass to add_density_sphere\n% vr should already be sorted ascending wrt slices, so no need to sort again.\nupd = [1 diff(vr(3,:)) > 0];\n\nfor i = 1:size(vr,2) % for each reported point...\n \n if upd(i)\n vin = vindex(:,slices <= vr(3,i) + radius & slices > vr(3,i) - radius); % these are coordinates that may be in-sphere\n end\n \n count = mask(vr(1,i),vr(2,i),vr(3,i)); \n\t\t\t\t\t\t\t\t\t\t% get count at this point\n dm = add_density_sphere(vr(:,i),vin,Q,count,dm,radius); % add density to sphere around this point\nend\n\n% --------------------------------------------------------------------------------------\n% * turn into density -> count per unit area of sphere \n% --------------------------------------------------------------------------------------\nif sphere_vol\n dm = dm ./ sphere_vol;\nend\n\nif verbose, \n t2 = clock;\n fprintf(1,'\\ndone in %3.0f s!',etime(t2,t1))\nend\n\nend\n\nreturn\n\n\n\n\n\n% Sub-functions\n% --------------------------------------------------------------------------------------\nfunction vindex = build_voxel_index(mask)\n% NOT USED\nrows = size(mask,1);\ncols = size(mask,2);\na = []; b = []; c = []; vindex = [];\nfor i = 1:cols\n a = [a 1:rows];\n b = [b i * ones(1,rows)];\nend\nc = [a;b];\nfor i = 1:size(mask,3)\n c(3,:) = i;\n vindex = [vindex c];\nend\nreturn\n\n\nfunction [dens,j] = get_density(coord,vindex,Q,mask,radius,sphere_vol)\n % NOT USED\n % j is index numbers of in-sphere coordinates\n % this line is slow for big vindexes (1 mil). 4.17 s\n j = find(sum((vindex - coord*Q).^2) <= radius2);\n\n %\ttotal = length(j) * voxel_vol;\n count = sum(mask(j) > 0);\n dens = count / sphere_vol;\nreturn\n\n\nfunction [dm,j] = add_density_sphere(coord,vindex,Q,count,dm,radius)\n % j is index numbers of in-sphere coordinates\n % coord is coordinate of sphere center\n % vindex is XYZ index of all slices in the vicinity\n % Q is ones of (3,length vindex)\n % count is the number of counts at the sphere center\n \n j = find(sum((vindex - coord*Q(:,1:size(vindex,2))).^2) <= radius^2);\n\n % turn index of restricted vindex space back to whole-mask coordinates\n XYZ = vindex(:,j);\n ind = sub2ind(size(dm),XYZ(1,:),XYZ(2,:),XYZ(3,:));\n \n % add the mask value at the point to voxels in sphere; mask may be > 1\n % do not divide by sphere_vol - instead, do this at the end.\n dm(ind) = dm(ind) + count;\n \n \nreturn\n\n\nfunction sph_mask = get_sphere(radius)\n % returns spherical mask in 3-d array, with unit density in elements\n % NOT USED\n sph_mask = zeros(2*radius+1,2*radius+1,2*radius+1);\n vindex = build_voxel_index(sph_mask);\n Q = ones(1,size(vindex,2));\n sph_mask(radius,radius,radius) = 1;\n [dens,j] = get_density([radius;radius;radius],vindex,Q,sph_mask,radius);\n sph_mask(j) = dens;\nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "pa_overall_threshold.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility/density2_calculations/pa_overall_threshold.m", "size": 1679, "source_encoding": "utf_8", "md5": "1857b8594ebbaad08cbaf2948a04016e", "text": "\nfunction pa_overall_threshold(studynames,allconditions,xyz,radius_mm,normby,mask)\n%\n% gets uncorrected and corrected p-values for prob of activation\n%\n% [allconditions,pointcounts,studynames,allcondindic,allcondnames] =\n% dbcluster2indic(DB,DB,{testfield});\n%\n%\n\nfor i = 1:length(studynames)\n \n wh = find(strcmp(study,studynames{i}) & strcmp(allcond,allconditions{i}));\n XYZmm = xyz(wh,:);\n XYZmm(any(isnan(XYZmm),2),:) = [];\n \n if isempty(XYZmm)\n conmask = mask;\n else\n XYZvox = mm2vox(XYZmm,V.mat); % get voxel coordinates\n \n conmask = xyz2mask(mask,XYZvox); % put points in mask - could weight by Z-scores here, if desired.\n spm_smooth(conmask,conmask,radius_mm); % smooth it!\n \n conmask = conmask ./ normby; % normalize so center of study activation = 1\n conmask(conmask > 1) = 1; % limit to max of 1, in case multiple nearby points in same contrast\n % max activation for a single\n % contrast is 1.\n \n end\n \n str = [studynames{i} '_' testfield '_' allconditions{i} '.img'];\n V.fname = str;\n \n V.descrip = allconditions{i};\n %str = ['V.' testfield ' = ''' allconditions{i} ''';'];\n %eval(str)\n \n \n warning off, spm_write_vol(V,conmask);, warning on\n PP = str2mat(PP,str);\n end % loop thru contrasts\n PP = PP(2:end,:);\nelse\n % we have filenames already created\nend\n\nfprintf(1,'Done %3.0f images in %3.0f s',length(studynames),etime(clock,t1))\n \nOUT.PP = PP;"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "dbcontrast2density copy.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility/density2_calculations/dbcontrast2density copy.m", "size": 11887, "source_encoding": "utf_8", "md5": "066a36e14fdae153fe69a51ce1c70958", "text": "function [dmt,clusters,dm,OUT] = dbcontrast2density(DB,u,varargin)\n% function [dmt,clusters,dm,OUT] = dbcontrast2density(DB,u,[radius_mm],[testfieldname],[contrast over levels],[con_dens_images])\n% \n% XYZ is 3-column vector of coordinates\n%\n% Tor Wager 11/20/04\n%\n% step 1: read database\n% step 2: database2clusters -- get database structure (don't use clusters; can enter any clusters here)\n% \n%\n% examples:\n% [dmt,clusters,dm,OUT] = dbcontrast2density(EMDB,.05,10,'valence');\n%\n% load meta_analysis_master_file\n% dbcontrast2density(PAINDB3,.05,15,'Right_vs_Left');\n% dbcontrast2density(PAINDB3,.05,15,'Right_vs_Left',[1 1 0]); % for r vs l\n%\n\nP = ['brain_avg152T1.img']; % 2 mm voxels\nP = 'scalped_avg152T1_graymatter_smoothed.img';\n\nif length(varargin) > 0, radius_mm = varargin{1}; \nelse, radius_mm = 10;\nend\ndisp(['Radius is ' num2str(radius_mm) ' mm.'])\n\n\n%if(length(fname) <= 4), error('Enter longer file name or type filename.img'),end\n%if ~strcmp(fname(end-4:end), '.img'), [d fname] = fileparts(fname);, fname = [fname '.img'], end\n\nmask_file = P;\nt1 = clock;\nfprintf(1,'Setup. ')\n\n% -----------------------------------------------------\n% * load standard brain\n% -----------------------------------------------------\nP = which(P);\nV = spm_vol(P);\nmask = zeros(V.dim(1:3));\n\nvoxsize = diag(V(1).mat)';\nvoxsize = voxsize(1:3);\nradius = radius_mm ./ mean(voxsize);\nsphere_vol = 4 * pi * radius_mm ^ 3 / 3;\n\n\n\n% -----------------------------------------------------\n% identify independent contrasts\n% -----------------------------------------------------\ntestfield = 'valence';\nif length(varargin) > 1, testfield = varargin{2};,end\n\n% weight by sample size; field is Subjects\n[allconditions,pointcounts,studynames,allcondindic,allcondnames] = dbcluster2indic(DB,DB,{testfield},1);\n\nxyz = [DB.x DB.y DB.z];\neval(['allcond = DB.' testfield ';']); \ntry, study = DB.Study;, catch, study = DB.study;, end\n\nfprintf(1,'%3.0f Independent contrasts.',length(studynames))\n\nOUT.allconditions = allconditions; \nOUT.pointcounts = pointcounts;\nOUT.studynames = studynames;\nOUT.allcondindic = allcondindic;\nOUT.allcondnames = allcondnames;\n\n% -----------------------------------------------------\n% for each contrast, make a density image\n% -----------------------------------------------------\n\n\nPP = []; % image names\nif length(varargin) > 3, PP = varargin{4}; ,end % load input filenames here!!\n \nif isempty(PP)\n \n % normalize density maps so that 1 activation = value of 1 in map\n tmp = mask; tmp2 = round(size(mask)./2);\n tmp(tmp2(1),tmp2(2),tmp2(3)) = 1;\n spm_smooth(tmp,tmp,radius); % in vox if not a mapped vol! \n normby = max(tmp(:));\n\n\n % Try to find images first, and if they don't exist in current dir,\n % create.\n fprintf(1,'Creating images.')\n \n for i = 1:length(studynames)\n \n wh = find(strcmp(study,studynames{i}) & strcmp(allcond,allconditions{i}));\n XYZmm = xyz(wh,:);\n XYZmm(any(isnan(XYZmm),2),:) = [];\n \n str = [studynames{i} '_' testfield '_' allconditions{i} '.img'];\n if exist(str) == 2, disp(['Found existing: ' str])\n \n else\n % doesn't exist yet\n if isempty(XYZmm)\n conmask = mask;\n else\n XYZvox = mm2vox(XYZmm,V.mat); % get voxel coordinates\n \n conmask = xyz2mask(mask,XYZvox); % put points in mask - could weight by Z-scores here, if desired.\n spm_smooth(conmask,conmask,radius) %_mm); % smooth it! radius in voxels if no header info is given.\n \n conmask = conmask ./ normby; % normalize so center of study activation = 1\n conmask(conmask > 1) = 1; % limit to max of 1, in case multiple nearby points in same contrast\n % max activation for a single\n % contrast is 1.\n \n end\n \n \n V.fname = str;\n warning off, spm_write_vol(V,conmask);, warning on\n \n end % if find existing\n PP = str2mat(PP,str);\n end % loop thru contrasts\n PP = PP(2:end,:);\nelse\n % we have filenames already created\nend\n\nfprintf(1,'Done %3.0f images in %3.0f s',length(studynames),etime(clock,t1))\n \nOUT.PP = PP;\n\n% -----------------------------------------------------\n% across all density images, compute prob(activation), p(a)\n% -----------------------------------------------------\ntor_spm_mean_ui(PP,'pa_overall.img');\n\n% -----------------------------------------------------\n% compute prob(task) for each allcondition\n% -----------------------------------------------------\n\n\n\n%%% THRESHOLD THE OVERALL P(ACTIVATION) IMAGE\n% ----------------------------------------------------\n% * get list of all coordinates; \n% ----------------------------------------------------\n for i = 1:length(studynames)\n \n wh = find(strcmp(study,studynames{i}) & strcmp(allcond,allconditions{i}));\n XYZmm = xyz(wh,:);\n XYZmm(any(isnan(XYZmm),2),:) = [];\n \n XYZmm_all{i} = XYZmm;\n end\n \n \n % ----------------------------------------------------\n% * get list of all coordinates; select n at random\n% vol: row, col, array = x, y, z\n% ----------------------------------------------------\nvol = spm_read_vols(V);\n[x,y,z] = ind2sub(size(vol),find(vol)); % find values > 0 in vol\nallXYZ = [x y z]; % XYZ is in 3 columns in this function\n\niterations = 5000;\ntestp = [32 24 32]; % ignores edge effects!\n\n% make convolution kernel -- weighting function for distance\ns = radius/sqrt(8*log(2)); % kernel st. dev in VOXEL distance\nm = ceil(4*s); % limit of kernel -- 4 std. deviations\n % kernel for positive distances\ny = normpdf([0:m],0,s); y = y ./ max(y);\n\nfor i = 1:length(XYZmm_all), if isempty(XYZmm_all{i}), whom(i)=1;,else, whom(i)=0;,end,end\nXYZmm_all(find(whom)) = [];\n\ndisp('Iterating null hypothesis for overall density.')\nfor it = 1:iterations\n \n for i = 1:length(XYZmm_all)\n \n % select random coordinates for each study\n % n is coords for this study, whichv indexes n random in-brain-mask\n % coords\n n = size(XYZmm_all{i},1);\n whichv = ceil(rand(1,n) * size(allXYZ,1));\n XYZ = allXYZ(whichv,:);\n\n % euclidean distance from test point, in voxel space (coords) \n d = distance(testp,XYZ);\n \n % weight distances by gaussian function\n % to get sum of weighted distances from fixed test point\n d(d>m-1) = []; % more than 4 stds\n \n dstudy(i) = sum(y(round(d)+1)); % this is the weighted sum, the statistic value of interest\n \n end\n \n dstudy(dstudy > 1) == 1; % cap at 1, because no study can exceed 1 \n % for z-score weighting, cap would be\n % z(study)\n pa_h0(it) = mean(dstudy); % weighted p(a) overall, by chance. save this distribution.\n \n \nend\n \n\n\n% threshold the overall density image\ncl = dens_fdr_thresh('pa_overall.img',pa_h0,1);\n\nsave pa_overall_cl cl\n\n\n\n\n% NOW WORK ON THE CHI2 VALUES FOR DIFFS AMONG CONDITIONS\n% COMPUTE CHI2 VALUE AT EACH VOXEL\n% WE NEED ROWS = VOXELS, COLUMNS = P(ACT|TASK X), OR % STUDIES IN TASK X\n\n% -----------------------------------------------------\n% across images for each cond., compute prob(activation) given condition,\n% p(a)|task\n% -----------------------------------------------------\n\n% select conditions to test across\nif length(varargin) > 2, contrast = varargin{3}; ,\nelse\n contrast = ones(length(OUT.allcondindic));\nend\n \n\nallcondindic = OUT.allcondindic(:,find(contrast));\nallcondnames = OUT.allcondnames(find(contrast));\n\n\n% number of contrasts in each map\nnumcons = sum(allcondindic);\n \nfor i = 1:size(allcondindic,2) % for each level\n names = OUT.PP(find(allcondindic(:,i)),:);\n nstr = ['pa_given_' allcondnames{i} '.img'];\n tor_spm_mean_ui(names,nstr);\n \n % convert probability scores to count for chi2 test\n V = spm_vol(nstr); v = spm_read_vols(V);\n v = v .* numcons(i); % counts!\n ncstr = ['counts_given_' allcondnames{i} '.img'];\n V.fname = ncstr;\n spm_write_vol(V,v);\n \n if i == 1,\n OUT.cntimgnames = ncstr;\n else\n OUT.cntimgnames = str2mat(OUT.cntimgnames,ncstr);\n end\nend\n\n% load images and make voxels x conditions matrix countdat\nV = spm_vol(OUT.cntimgnames); v = spm_read_vols(V);\n\nVmask = spm_vol(which(mask_file)); vm = spm_read_vols(Vmask);\nwh = find(vm>0); % wh contains indices in mask, for use later to convert back to voxels!\n \nclear countdat\nfor i = 1:size(v,4) % for each condition\n vtmp = v(:,:,:,i);\n countdat(:,i) = vtmp(wh);\nend\n\n% eliminate voxels w/ zeros in all conds\nwhzero = find(all(countdat 0, radius_mm = varargin{1}; \nelse, radius_mm = 10;\nend\ndisp(['Radius is ' num2str(radius_mm) ' mm.'])\n\nif length(varargin) > 1, fname = varargin{2}; \nelse, fname = input('Enter file name for the output image ','s');\nend\n\nif length(varargin) > 2,\n zscores = varargin{3};\n if length(zscores) ~= size(XYZ,1), error('Length of z-scores does not match number of points');,end\nelse\n zscores = 1;\nend\n\nif(length(fname) <= 4), error('Enter longer file name or type filename.img'),end\nif ~strcmp(fname(end-4:end), '.img'), [d fname] = fileparts(fname);, fname = [fname '.img'], end\n\nmask_file = P;\nt1 = clock;\n\n% -----------------------------------------------------\n% * load standard brain\n% -----------------------------------------------------\nP = which(P);\nV = spm_vol(P);\nmask = zeros(V.dim(1:3));\n\nvoxsize = diag(V(1).mat)';\nvoxsize = voxsize(1:3);\nradius = radius_mm ./ mean(voxsize);\nsphere_vol = 4 * pi * radius_mm ^ 3 / 3;\nXYZ = mm2vox(XYZ,V.mat);\n\n% -----------------------------------------------------\n% * make a mask out of XYZ, in space of P\n% * deal with repeated coordinates by adding\n% -----------------------------------------------------\n\nind = sub2ind(size(mask),XYZ(:,1),XYZ(:,2),XYZ(:,3));\nmask(ind) = zscores; % = 1 if no zscores entered, otherwise vector\n\nind = sort(ind);\nrepeats = ind(find(~diff(ind))); % index values that are repeated\nif length(zscores) > 1\n repeatz = zscores(find(~diff(ind))); % z=scores of index values that are repeated\nelse\n repeatz = 1;\nend\nmask(repeats) = mask(repeats) + repeatz;\n\n% -----------------------------------------------------\n% * convert to density mask\n% * write density mask before thresholding\n% -----------------------------------------------------\ndm = mask2density(mask,radius,[],sphere_vol);\n%dm2 = mask2density(mask,radius);\n\n%figure; subplot 211; imagesc(mask(:,:,33)); subplot 212; imagesc(dm(:,:,33))\n%figure; subplot 211; imagesc(mask(:,:,33)); subplot 212; imagesc(dm(:,:,33).*sphere_vol)\n\nV.fname = ['dens_' fname];\nspm_write_vol(V,dm);\n\nfigure; hist(dm(dm>0),50)\nif ~isempty(u),hold on; plot([u u],get(gca,'YLim'),'r','LineWidth',2),end\n\n% -----------------------------------------------------\n% * make and write filtered density mask\n% -----------------------------------------------------\ndmt = maskImg(dm,u,Inf); \n[d,fname,ext] = fileparts(fname);\nV.fname = ['dens_' fname '_filtered' ext];\nspm_write_vol(V,dmt);\n\n% -----------------------------------------------------\n% * get clusters from density mask for imaging\n% -----------------------------------------------------\nCLU = mask2struct(V.fname,u,0);\nclusters = tor_extract_rois([],CLU,CLU);\neval(['save ' fname '_clusters CLU clusters'])\n\nreturn\n\n\n\n% -----------------------------------------------------\n% * sub-functions\n% -----------------------------------------------------\n\nfunction XYZout = mm2vox(XYZ,M)\n% converts a list of coordinates\n% XYZ should be 3-column vector [x y z]\n% calls tal2vox\n\nXYZ = XYZ';\nfor i = 1:size(XYZ,2), \n\tXYZout(i,:) = tal2vox(XYZ(:,i),M); \nend\n\nXYZout = round(XYZout);\n\nreturn\n\n% -----------------------------------------------------\nfunction vox=tal2vox(tal,M)\n% converts from talairach coordinate to voxel coordinate\n% based on variables from SPM.M (passed here for \n% faster operation)\n% e.g., foo=tal2vox([-30 28 -30], VOL)\n% from Russ Poldrack's spm ROI utility \n\nvox=[0 0 0];\nvox(1)=(tal(1)-M(1,4))/M(1,1);\nvox(2)=(tal(2)-M(2,4))/M(2,2);\nvox(3)=(tal(3)-M(3,4))/M(3,3);\n\nreturn\n\n\n\n\n\nfunction dm = mask2density(mask,radius,varargin)\n% function dm = mask2density(mask,radius,[opt] searchmask, [opt] sphere_vol)\n%\n% mask is the mask with ones where activation points are\n% radius is in voxels\n%\n% optional arguments:\n% 1 searchmask\n% searchmask is the whole brain search space [optional]\n% Mask and searchmask must be in same space, with same voxel sizes and dimensions!\n% If empty, search mask is ones(size(mask))\n%\n% 2 sphere_vol\n% sphere_vol is optional argument that translates count mask into density mask\n% by dividing the number of counts by this value.\n%\n% structure of functions:\n% \t\tvoxel2mask.m\t\t\tlist of coordinates -> mask\n%\t\tmask2density.m\t\t\tmask of coords -> density map\n%\n% for null hypothesis distribution generation:\n%\t\tgenerate_rdms.m\tgiven: no. to generate, no. of points, mask size\n%\t get_random_mask.m\tgenerate random list of coords\n%\t\t\tvoxel2mask.m \n%\t\t\tmask2density.m\t\t\tdensity map of null distribution\n%\t\t\tspm_write_vol.m\t\twrite output analyze image\n%\n%\t\tdensity_npm_p.m\t\t\tcluster p-value, and critical k \n%\t\t\t\t\t\t\t\t\t\tgiven list of rdm images and threshold u\t\t\t\n%\t\t\tcount_clusters.m\t\tdensity map -> no. of points, clusters \n%\t\t\t\t\t\t\t\t\t\tat density threshold u\n%\t\t\t\t\t\t\t\t\t\tat a range of thresholds (input)\n%\t\t\t\t\t\t\t\t\t\treturns the number and avg. size of clusters\n%\t\t\tthen finds p value based on distribution and 95% level\n\nverbose = 0;\nif verbose, t1 = clock;, end\n\nif length(varargin) > 1\n sphere_vol = varargin{2};\nelse \n sphere_vol = 0;\nend\n\nif length(varargin) > 0\n searchmask = varargin{1};\n if isempty(searchmask), searchmask = ones(size(mask));, end\nelse\n searchmask = ones(size(mask));\nend\n\nif any(size(mask) - size(searchmask))\n error('Mask and searchmask must be of the same dimensions and have the same voxel sizes!')\nend\n\nfmethod = 1;\nswitch fmethod\ncase 1\n% --------------------------------------------------------------------------------------\n% * define sphere to convolve with mask\n% --------------------------------------------------------------------------------------\n% MUCH slower.\nsph = get_sphere(radius);\ndm = convn(mask,sph,'same');\n\ncase 2\n\n% --------------------------------------------------------------------------------------\n% * define search space: coordinate list of whole mask\n% --------------------------------------------------------------------------------------\nif verbose, fprintf(1,'defining search space ... '), end\n% [x,y,z] = ind2sub(size(searchmask),find(searchmask)); % find coords of values > 0 in mask\n[x,y,z] = ind2sub(size(mask),find(searchmask > 0)); % find coords of values > 0 in mask\nvindex = [x y z]';\n\n% old way: slower\n% vindex = build_voxel_index(mask);\n\nQ = ones(1,size(vindex,2));\ndm = zeros(size(mask));\nslices = vindex(3,:); % used to pass only certain slices to subfunctions\n\n\n% --------------------------------------------------------------------------------------\n% * locate coordinates in mask to make spheres around\n% --------------------------------------------------------------------------------------\n[x,y,z] = ind2sub(size(mask),find(mask)); % find coordinates of values > 0 in mask\nvr = [x y z]';\n\nif verbose, fprintf(1,'\\nrestricting to spheres around %3.0f points ... ',size(vr,2)), end\n\n% the idea here is to pass into add_density_sphere only coordinates\n% that are in slices that could possibly be within the sphere, to speed things up.\n% this next line tells us when we need to update to new slices\n% when the slice changes, we need a new set of slices to pass to add_density_sphere\n% vr should already be sorted ascending wrt slices, so no need to sort again.\nupd = [1 diff(vr(3,:)) > 0];\n\nnpts = size(vr,2);\nstr = fprintf(1,'Computing %3.0f points: %03d',npts,0);\n\nfor i = 1:npts % for each reported point...\n \n fprintf(1,'\\b\\b\\b%03d',i);\n \n if upd(i)\n vin = vindex(:,slices <= vr(3,i) + radius & slices > vr(3,i) - radius); % these are coordinates that may be in-sphere\n end\n \n count = mask(vr(1,i),vr(2,i),vr(3,i)); \n\t\t\t\t\t\t\t\t\t\t% get count at this point\n dm = add_density_sphere(vr(:,i),vin,Q,count,dm,radius); % add density to sphere around this point\nend\n\nerase_string(str);\n\n% --------------------------------------------------------------------------------------\n% * turn into density -> count per unit area of sphere \n% --------------------------------------------------------------------------------------\nif sphere_vol\n dm = dm ./ sphere_vol;\nend\n\nif verbose, \n t2 = clock;\n fprintf(1,'\\ndone in %3.0f s!',etime(t2,t1))\nend\n\nend\n\nreturn\n\n\n\n\n\n% Sub-functions\n% --------------------------------------------------------------------------------------\nfunction vindex = build_voxel_index(mask)\n% NOT USED\nrows = size(mask,1);\ncols = size(mask,2);\na = []; b = []; c = []; vindex = [];\nfor i = 1:cols\n a = [a 1:rows];\n b = [b i * ones(1,rows)];\nend\nc = [a;b];\nfor i = 1:size(mask,3)\n c(3,:) = i;\n vindex = [vindex c];\nend\nreturn\n\n\nfunction [dens,j] = get_density(coord,vindex,Q,mask,radius,sphere_vol)\n % NOT USED\n % j is index numbers of in-sphere coordinates\n % this line is slow for big vindexes (1 mil). 4.17 s\n j = find(sum((vindex - coord*Q).^2) <= radius);\n\n %\ttotal = length(j) * voxel_vol;\n count = sum(mask(j) > 0);\n dens = count / sphere_vol;\nreturn\n\n\nfunction [dm,j] = add_density_sphere(coord,vindex,Q,count,dm,radius)\n % j is index numbers of in-sphere coordinates\n % coord is coordinate of sphere center\n % vindex is XYZ index of all slices in the vicinity\n % Q is ones of (3,length vindex)\n % count is the number of counts at the sphere center\n \n j = find(sum((vindex - coord*Q(:,1:size(vindex,2))).^2) <= radius^2);\n\n % turn index of restricted vindex space back to whole-mask coordinates\n XYZ = vindex(:,j);\n ind = sub2ind(size(dm),XYZ(1,:),XYZ(2,:),XYZ(3,:));\n \n % add the mask value at the point to voxels in sphere; mask may be > 1\n % do not divide by sphere_vol - instead, do this at the end.\n dm(ind) = dm(ind) + count;\n \n \nreturn\n\n\nfunction sph_mask = get_sphere(radius)\n % returns spherical mask in 3-d array, with unit density in elements\n % NOT USED\n sph_mask = zeros(2*radius+1,2*radius+1,2*radius+1);\n vindex = build_voxel_index(sph_mask);\n Q = ones(1,size(vindex,2));\n sph_mask(radius,radius,radius) = 1;\n [dens,j] = get_density([radius;radius;radius],vindex,Q,sph_mask,radius,1);\n sph_mask(j) = dens;\nreturn\n\n\nfunction erase_string(str)\n fprintf(1,repmat('\\b',1,length(str))); % erase string\n %fprintf(1,'\\n');\nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "density_diff.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility/density_analysis_calculations/density_diff.m", "size": 5465, "source_encoding": "utf_8", "md5": "82db7c55027ba8f18bcc25df184730d8", "text": "function [cl1,cl2,dmt,dmt2,d1,d2,mask,mask2] = density_diff(XYZ,u,XYZ2,u2,varargin)\n% function [cl1,cl2,dmt,dmt2,d1,d2,mask,mask2] = density_diff(XYZ,u,XYZ2,u2,[radius_mm],[first outfile name],[2nd outfile name])\n% \n% function gets density from a list of XYZ coordinates\n% in one condition of a meta-analysis\n% and makes and saves clusters\n%\n% XYZ is 3-column vector of coordinates\n%\n% Tor Wager 2/18/02\n\nP = ['brain_avg152T1.img']; % 2 mm voxels\nP = 'scalped_avg152T1_graymatter_smoothed.img';\n%radius_mm = 10;\n\nif length(varargin) > 0, radius_mm = varargin{1}; \nelse, radius_mm = 10;\nend\ndisp(['Radius is ' num2str(radius_mm) ' mm.'])\n\nif length(varargin) > 1, fname = varargin{2}; \nelse, fname = input('Enter text string tag for first set of XYZ ','s');\nend\n\nif length(varargin) > 2, fname2 = varargin{3}; \nelse, fname2 = input('Enter text string tag for second set of XYZ ','s');\nend\n\nmask_file = P;\nt1 = clock;\n%fname = input('Enter text string tag for first set of XYZ ','s');\n%fname2 = input('Enter text string tag for second set of XYZ ','s');\nf1 = [fname '-' fname2];\nf2 = [fname2 '-' fname];\n[d f1] = fileparts(f1);, f1 = [f1 '.img'];\n[d f2] = fileparts(f2);, f2 = [f2 '.img'];\nfprintf(1,'\\tdensity_diff.m writing: \\n\\t%s\\n\\t%s\\n',f1,f2)\n\n% -----------------------------------------------------\n% * load standard brain\n% -----------------------------------------------------\nP = which(P);\nV = spm_vol(P);\nmask = zeros(V.dim(1:3));\nmask2= mask;\n\nvoxsize = diag(V(1).mat)';\nvoxsize = voxsize(1:3);\nradius = radius_mm ./ mean(voxsize);\nsphere_vol = 4 * pi * radius_mm ^ 3 / 3;\nXYZ = mm2vox(XYZ,V.mat);\nXYZ2 = mm2vox(XYZ2,V.mat);\n\n% -----------------------------------------------------\n% * make a mask out of XYZ, in space of P\n% * deal with repeated coordinates by adding\n% -----------------------------------------------------\n\nind = sub2ind(size(mask),XYZ(:,1),XYZ(:,2),XYZ(:,3));\nmask(ind) = 1;\n\nind = sort(ind);\nrepeats = ind(find(~diff(ind))); % index values that are repeated\nfor i = 1:length(repeats)\n mask(repeats(i)) = mask(repeats(i)) + 1;\nend\n\nind = sub2ind(size(mask2),XYZ2(:,1),XYZ2(:,2),XYZ2(:,3));\nmask2(ind) = 1;\n\nind = sort(ind);\nrepeats = ind(find(~diff(ind))); % index values that are repeated\nfor i = 1:length(repeats)\n mask2(repeats(i)) = mask2(repeats(i)) + 1;\nend\n\n% -----------------------------------------------------\n% * convert to density mask\n% * write density mask before thresholding\n% -----------------------------------------------------\ndm = mask2density(mask,radius,[],sphere_vol);\ndm2 = mask2density(mask2,radius,[],sphere_vol);\n\nd1 = dm - dm2;\nd2 = dm2 - dm;\nclear dm, clear dm2\n\nV.fname = ['dens_' f1];\nspm_write_vol(V,d1);\n\nV.fname = ['dens_' f2];\nspm_write_vol(V,d2);\n\n%figure; hist(d1(d1>0),50)\n%if ~isempty(u),hold on; plot([u u],get(gca,'YLim'),'r','LineWidth',2),end\n\n%figure; hist(d2(d2>0),50)\n%if ~isempty(u2),hold on; plot([u2 u2],get(gca,'YLim'),'r','LineWidth',2),end\n\n% -----------------------------------------------------\n% * make and write filtered density mask\n% -----------------------------------------------------\ndmt = maskImg(d1,u,Inf); \n[d,fname,ext] = fileparts(f1);\nV.fname = ['dens_' fname '_filtered' ext];\nspm_write_vol(V,dmt);\n\n% -----------------------------------------------------\n% * get clusters from density mask for imaging\n% -----------------------------------------------------\nCLU = mask2struct(V.fname,u,0);\nif size(CLU.XYZ,2) > 0\n clusters = tor_extract_rois([],CLU,CLU);\nelse\n disp(['1st XYZ: no significant results. max is ' num2str(max(max(max(d1))))])\n clusters = [];\nend\neval(['save ' fname '_clusters CLU clusters'])\ncl1 = clusters;\n\n% -----------------------------------------------------\n% * make and write filtered density mask\n% -----------------------------------------------------\ndmt2 = maskImg(d2,u2,Inf); \n[d,fname,ext] = fileparts(f2);\nV.fname = ['dens_' fname '_filtered' ext];\nspm_write_vol(V,dmt2);\n\n% -----------------------------------------------------\n% * get clusters from density mask for imaging\n% -----------------------------------------------------\nCLU = mask2struct(V.fname,u2,0);\nif size(CLU.XYZ,2) > 0\n clusters = tor_extract_rois([],CLU,CLU);\nelse\n disp(['2nd XYZ: no significant results. max is ' num2str(max(max(max(d2))))])\n clusters = [];\nend\neval(['save ' fname '_clusters CLU clusters'])\ncl2 = clusters;\n\n\n%try\n% P = spm_get(1,'*img','Select overlay');\n% if ~isempty(cl1)\n% cluster_table(cl1)\n% montage_clusters(P,cl1)\n% end\n% if ~isempty(cl2)\n% cluster_table(cl2)\n% montage_clusters(P,cl2)\n% end\n%catch\n% disp('Problem making montages...skipping.')\n%end\n\nreturn\n\n\n\n% -----------------------------------------------------\n% * sub-functions\n% -----------------------------------------------------\n\nfunction XYZout = mm2vox(XYZ,M)\n% converts a list of coordinates\n% XYZ should be 3-column vector [x y z]\n% calls tal2vox\n\nXYZ = XYZ';\nfor i = 1:size(XYZ,2), \n\tXYZout(i,:) = tal2vox(XYZ(:,i),M); \nend\n\nXYZout = round(XYZout);\n\nreturn\n\n% -----------------------------------------------------\nfunction vox=tal2vox(tal,M)\n% converts from talairach coordinate to voxel coordinate\n% based on variables from SPM.M (passed here for \n% faster operation)\n% e.g., foo=tal2vox([-30 28 -30], VOL)\n% from Russ Poldrack's spm ROI utility \n\nvox=[0 0 0];\nvox(1)=(tal(1)-M(1,4))/M(1,1);\nvox(2)=(tal(2)-M(2,4))/M(2,2);\nvox(3)=(tal(3)-M(3,4))/M(3,3);\n\nreturn\n\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "mask2density.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility/density_analysis_calculations/mask2density.m", "size": 6660, "source_encoding": "utf_8", "md5": "a32e052314f9961dc1a7726bac60960a", "text": "function dm = mask2density(mask,radius,varargin)\r\n% function dm = mask2density(mask,radius,[opt] searchmask, [opt] sphere_vol)\r\n%\r\n% mask is the mask with ones where activation points are\r\n% radius is in voxels\r\n%\r\n% optional arguments:\r\n% 1 searchmask\r\n% searchmask is the whole brain search space [optional]\r\n% Mask and searchmask must be in same space, with same voxel sizes and dimensions!\r\n% If empty, search mask is ones(size(mask))\r\n%\r\n% 2 sphere_vol\r\n% sphere_vol is optional argument that translates count mask into density mask\r\n% by dividing the number of counts by this value.\r\n%\r\n% structure of functions:\r\n% \t\tvoxel2mask.m\t\t\tlist of coordinates -> mask\r\n%\t\tmask2density.m\t\t\tmask of coords -> density map\r\n%\r\n% for null hypothesis distribution generation:\r\n%\t\tgenerate_rdms.m\tgiven: no. to generate, no. of points, mask size\r\n%\t get_random_mask.m\tgenerate random list of coords\r\n%\t\t\tvoxel2mask.m \r\n%\t\t\tmask2density.m\t\t\tdensity map of null distribution\r\n%\t\t\tspm_write_vol.m\t\twrite output analyze image\r\n%\r\n%\t\tdensity_npm_p.m\t\t\tcluster p-value, and critical k \r\n%\t\t\t\t\t\t\t\t\t\tgiven list of rdm images and threshold u\t\t\t\r\n%\t\t\tcount_clusters.m\t\tdensity map -> no. of points, clusters \r\n%\t\t\t\t\t\t\t\t\t\tat density threshold u\r\n%\t\t\t\t\t\t\t\t\t\tat a range of thresholds (input)\r\n%\t\t\t\t\t\t\t\t\t\treturns the number and avg. size of clusters\r\n%\t\t\tthen finds p value based on distribution and 95% level\r\n\r\nverbose = 0;\r\nif verbose, t1 = clock;, end\r\n\r\nif length(varargin) > 1\r\n sphere_vol = varargin{2};\r\nelse \r\n sphere_vol = 0;\r\nend\r\n\r\nif length(varargin) > 0\r\n searchmask = varargin{1};\r\n if isempty(searchmask), searchmask = ones(size(mask));, end\r\nelse\r\n searchmask = ones(size(mask));\r\nend\r\n\r\nif any(size(mask) - size(searchmask))\r\n error('Mask and searchmask must be of the same dimensions and have the same voxel sizes!')\r\nend\r\n\r\nfmethod = 2;\r\nswitch fmethod\r\ncase 1\r\n% --------------------------------------------------------------------------------------\r\n% * define sphere to convolve with mask\r\n% --------------------------------------------------------------------------------------\r\n% MUCH slower.\r\nsph = get_sphere(radius);\r\ndm2 = convn(mask,sph,'same');\r\n\r\ncase 2\r\n\r\n% --------------------------------------------------------------------------------------\r\n% * define search space: coordinate list of whole mask\r\n% --------------------------------------------------------------------------------------\r\nif verbose, fprintf(1,'defining search space ... '), end\r\n% [x,y,z] = ind2sub(size(searchmask),find(searchmask)); % find coords of values > 0 in mask\r\n[x,y,z] = ind2sub(size(mask),find(searchmask > 0)); % find coords of values > 0 in mask\r\nvindex = [x y z]';\r\n\r\n% old way: slower\r\n% vindex = build_voxel_index(mask);\r\n\r\nQ = ones(1,size(vindex,2));\r\ndm = zeros(size(mask));\r\nslices = vindex(3,:); % used to pass only certain slices to subfunctions\r\n\n\r\n% --------------------------------------------------------------------------------------\r\n% * locate coordinates in mask to make spheres around\r\n% --------------------------------------------------------------------------------------\r\n[x,y,z] = ind2sub(size(mask),find(mask)); % find coordinates of values > 0 in mask\r\nvr = [x y z]';\r\n\r\nif verbose, fprintf(1,'\\nrestricting to spheres around %3.0f points ... ',size(vr,2)), end\r\n\r\n% the idea here is to pass into add_density_sphere only coordinates\r\n% that are in slices that could possibly be within the sphere, to speed things up.\r\n% this next line tells us when we need to update to new slices\r\n% when the slice changes, we need a new set of slices to pass to add_density_sphere\r\n% vr should already be sorted ascending wrt slices, so no need to sort again.\r\nupd = [1 diff(vr(3,:)) > 0];\r\n\r\nfor i = 1:size(vr,2) % for each reported point...\r\n \r\n if upd(i)\r\n vin = vindex(:,slices <= vr(3,i) + radius & slices > vr(3,i) - radius); % these are coordinates that may be in-sphere\r\n end\r\n \r\n count = mask(vr(1,i),vr(2,i),vr(3,i)); \r\t\t\t\t\t\t\t\t\t\t% get count at this point\n dm = add_density_sphere(vr(:,i),vin,Q,count,dm,radius); % add density to sphere around this point\r\nend\r\n\r\n% --------------------------------------------------------------------------------------\r\n% * turn into density -> count per unit area of sphere \r\n% --------------------------------------------------------------------------------------\r\nif sphere_vol\r\n dm = dm ./ sphere_vol;\r\nend\r\n\r\nif verbose, \r\n t2 = clock;\r\n fprintf(1,'\\ndone in %3.0f s!',etime(t2,t1))\r\nend\r\n\r\nend\r\n\r\nreturn\r\n\r\n\r\n\r\n\r\n\r\n% Sub-functions\r\n% --------------------------------------------------------------------------------------\r\nfunction vindex = build_voxel_index(mask)\r\n% NOT USED\r\nrows = size(mask,1);\r\ncols = size(mask,2);\r\na = []; b = []; c = []; vindex = [];\r\nfor i = 1:cols\r\n a = [a 1:rows];\r\n b = [b i * ones(1,rows)];\r\nend\r\nc = [a;b];\r\nfor i = 1:size(mask,3)\r\n c(3,:) = i;\r\n vindex = [vindex c];\r\nend\r\nreturn\r\n\r\n\r\nfunction [dens,j] = get_density(coord,vindex,Q,mask,radius,sphere_vol)\r\n % NOT USED\r\n % j is index numbers of in-sphere coordinates\r\n % this line is slow for big vindexes (1 mil). 4.17 s\r\n j = find(sum((vindex - coord*Q).^2) <= radius2);\r\n\r\n %\ttotal = length(j) * voxel_vol;\r\n count = sum(mask(j) > 0);\r\n dens = count / sphere_vol;\r\nreturn\r\n\r\n\r\nfunction [dm,j] = add_density_sphere(coord,vindex,Q,count,dm,radius)\r\n % j is index numbers of in-sphere coordinates\r\n % coord is coordinate of sphere center\r\n % vindex is XYZ index of all slices in the vicinity\r\n % Q is ones of (3,length vindex)\r\n % count is the number of counts at the sphere center\r\n \r\n j = find(sum((vindex - coord*Q(:,1:size(vindex,2))).^2) <= radius^2);\r\n\r\n % turn index of restricted vindex space back to whole-mask coordinates\r\n XYZ = vindex(:,j);\r\n ind = sub2ind(size(dm),XYZ(1,:),XYZ(2,:),XYZ(3,:));\r\n \r\n % add the mask value at the point to voxels in sphere; mask may be > 1\r\n % do not divide by sphere_vol - instead, do this at the end.\r\n dm(ind) = dm(ind) + count;\r\n \r\n \r\nreturn\r\n\r\n\r\nfunction sph_mask = get_sphere(radius)\r\n % returns spherical mask in 3-d array, with unit density in elements\r\n % NOT USED\r\n sph_mask = zeros(2*radius+1,2*radius+1,2*radius+1);\r\n vindex = build_voxel_index(sph_mask);\r\n Q = ones(1,size(vindex,2));\r\n sph_mask(radius,radius,radius) = 1;\r\n [dens,j] = get_density([radius;radius;radius],vindex,Q,sph_mask,radius);\r\n sph_mask(j) = dens;\r\nreturn\r\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "fast_max_density.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/densityUtility/density_analysis_calculations/fast_max_density.m", "size": 5547, "source_encoding": "utf_8", "md5": "0fdac3c733d29ff1fed8e5a5bf4484bc", "text": "function [u,maxd,usum,maxsum] = fast_max_density(n,iterations,radius_mm,varargin)\n% [u,maxd,usum,maxsum] = fast_max_density(n,iterations,radius_mm,[brain_mask_name])\n%\n% Improved faster algorithm for null-hypothesis monte carlo simulation\n% Same results as density_pdf.m\n%\n% u = critical threshold at alpha = .05\n% maxd = distribution of maximum density values under Ho\n%\n% tor wager\n% Feb 4,2003\n%\n% t1 = clock; [u,maxd]=fast_max_density(10,100,20); t2 = etime(clock,t1) \\\n% takes about 80 s on my 1.3 PIII, or 7:20 for n = 100\n% estimated 6 hrs 20 mins for 5000 iterations at n = 100\n\nif length(varargin) > 0\n P = varargin{1};\nelse\n P = ['brain_avg152T1.img']; % 2 mm voxels\n P = 'scalped_avg152T1_graymatter_smoothed.img';\nend\n\nif length(n) > 1\n % we have z-scores, so use them\n zscores = n;\n n = length(zscores);\nend\n \n% ----------------------------------------------------\n% * read the input brain mask image\n% ----------------------------------------------------\nif isempty(P)\n P = spm_get(1,'*.img','Select brain or gray matter mask');\nend\nif ischar(P)\n P = which(P);\n V = spm_vol(P);\n vol = spm_read_vols(V);\n voxsize = diag(V(1).mat)';\n voxsize = voxsize(1:3);\nelse\n vol = P;\n voxsize = NaN;\nend\n\nvox_radius = radius_mm ./ mean(voxsize);\nsphere_vol = 4 * pi * radius_mm ^ 3 / 3;\ndiam = 2 * vox_radius; % diameter of sphere in voxels\n\n% ----------------------------------------------------\n% * get list of all coordinates in brain mask\n% set up stuff for computing density \n% as in mask2density.m, but faster\n% vol: row, col, array = x, y, z\n% ----------------------------------------------------\n[x,y,z] = ind2sub(size(vol),find(vol)); % find values > 0 in vol\nallXYZ = [x y z]; % XYZ is in 3 columns in this function\nQ = ones(1,size(allXYZ,1));\nslices = allXYZ(:,3)'; % used to pass only certain slices to subfunctions\n\n\n% ----------------------------------------------------\n% * set up the gui figure\n% ----------------------------------------------------\nf = figure('Color','w');\ntmp = get(gcf,'Position') .* [1 1 .5 .1];\nset(gcf,'Position',tmp)\nset(gcf,'MenuBar','none','NumberTitle','off')\nfigure(f), set(gca,'Xlim',[0 100])\n\n\n\n% ----------------------------------------------------\n% * do the pdf\n% ----------------------------------------------------\n\nfor i = 1:iterations\n\n % select n coordinates at random\n whichv = ceil(rand(1,n) * size(allXYZ,1));\n XYZ = allXYZ(whichv,:);\n \n % get distances to all units (neural network toolbox function)\n d = dist(XYZ');\n\n % threshold the distances at 2 * radius (within-sphere diameter)\n d2 = d; d2(d2 <= diam) = 1; d2(d2 > diam) = 0;\n\n if exist('zscores') == 1\n % weight each row by z-scores for each point, if entered\n zmat = repmat(zscores',size(d2,1),1);\n d2 = d2 .* zmat;\n end\n \n % find the point that has the maximal number of other within-sphere points\n s = sum(d2,2); % sum across columns = z-score weighted sum if zscores entered\n wh = find(s == max(s));\n wh = wh(1);\n\n % restrict set of XYZ coordinates\n vr = XYZ(find(d2(wh,:)),:)';\n [vr,si] = sortrows(vr',3);\n vr = vr';\n \n if exist('zscores') == 1\n z2 = zscores(find(d2(wh,:)),:);\n z2 = z2(si); % sort z-scores to match vr (restricted voxels)\n end\n \n % compute density\n upd = [1 diff(vr(3,:)) > 0]; % points where slice changes\n dm = zeros(size(vol));\n \n for j = 1:size(vr,2) % for each reported point...\n \n if upd(j)\n vin = allXYZ(slices <= vr(3,j) + vox_radius & slices > vr(3,j) - vox_radius,:)'; % these are coordinates that may be in-sphere\n end\n \n if exist('zscores') ~= 1\n % count of number of peaks at this exact voxel center\n count = sum(vr(1,:) - vr(1,j) == 0 & vr(2,:) - vr(2,j) == 0 & vr(3,:) - vr(3,j) == 0);\n else\n % we have z-scores\n % sum z-scores for each point at this exact voxel center\n yesses = (vr(1,:) - vr(1,j) == 0 & vr(2,:) - vr(2,j) == 0 & vr(3,:) - vr(3,j) == 0);\n count = sum(yesses .* z2'); \n end\n \n dm = add_density_sphere(vr(:,j),vin,Q,count,dm,vox_radius); % add density to sphere around this point\n end\n \n mymax = max(dm(:));\n maxd(i) = mymax(1);\n\n \n if rem(i,10) == 0\n figure(f), try,barh(100*i / iterations),catch,end\n set(gca,'Xlim',[0 100]),set(gca,'YTickLabel',i),drawnow\n end\n \nend\n \nmaxn = maxd;\nmaxsum = maxd;\nmaxd = maxd ./ sphere_vol;\nu = prctile(maxd,95);\nusum = prctile(maxsum,95);\n \nclose \n \n \n \nreturn\n\n\n\n\nfunction [dm,j] = add_density_sphere(coord,vindex,Q,count,dm,radius)\n % j is index numbers of in-sphere coordinates\n % coord is coordinate of sphere center\n % vindex is XYZ index of all slices in the vicinity\n % Q is ones of (3,length vindex)\n % count is the number of counts at the sphere center\n \n j = find(sum((vindex - coord*Q(:,1:size(vindex,2))).^2) <= radius^2);\n\n % turn index of restricted vindex space back to whole-mask coordinates\n XYZ = vindex(:,j);\n ind = sub2ind(size(dm),XYZ(1,:),XYZ(2,:),XYZ(3,:));\n \n % add the mask value at the point to voxels in sphere; mask may be > 1\n % do not divide by sphere_vol - instead, do this at the end.\n dm(ind) = dm(ind) + count;\n \n \nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "rotateByEigen.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/confidence_volume/rotateByEigen.m", "size": 1214, "source_encoding": "utf_8", "md5": "6b7f567170f4b0c81df66c49300a7d6a", "text": "\n\n% \n% function to rotate a 3d object to a new orientation defined\n% by an eigenvalue problem.\n%\n% inputs are either:\n% X, Y, Z matrices defining points to rotate\n% n x 3 pointlist of [X Y Z] values, with 2nd and 3rd args empty\n%\n% returns: structure with X Y Z rotated, and XYZ rotated pointlist\n%\n% results = rotateByEigen(X,Y,Z,V)\n% results = rotateByEigen(X,[],[],V)\n%\n% Robert Welsh, 11/11/01\n% Modified by Tor Wager to take point list as well.\n\nfunction results = rotateByEigen(X,Y,Z,V)\n\nxP = 0*X;\nyP = 0*Y;\nzP = 0*Z;\n\nif isempty(Y) & isempty(Z)\n xP = [];\n nX = 1;\n nY = size(X,1);\nelse\n [nX nY] = size(X);\nend\n\nfor iX = 1:nX\n for iY = 1:nY\n if isempty(Y) & isempty(Z)\n xOld = X(iY,:)';\n else\n xOld = [X(iX,iY);Y(iX,iY);Z(iX,iY)];\n end\n \n xNew = V*xOld; \n \n if isempty(Y) & isempty(Z)\n XYZ(iY,:) = xNew';\n else\n xP(iX,iY) = xNew(1);\n yP(iX,iY) = xNew(2);\n zP(iX,iY) = xNew(3);\n end\n \n \n end\nend\n\nif isempty(Y) & isempty(Z)\n results.XYZ = XYZ;\nelse\n results.xP = xP;\n results.yP = yP;\n results.zP = zP;\nend\n\n%\n% all done\n%\n\nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_tables_of_variables.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/Miscellaneous_Functions/Meta_tables_of_variables.m", "size": 7451, "source_encoding": "utf_8", "md5": "efe1e518fc81d95c5c5f3a6fad3c2338", "text": "function DB = Meta_tables_of_variables(DB)\n% Constructs some tables for each variable, saved in DB.TABLES, so that we can easily see the levels and numbers of points & contrasts for each variable\n%\n% DB = Meta_tables_of_variables(DB)\n%\n% - Must run Meta_Setup.m first\n% - Assumes each study has one and only one unique text string assigned\n% (no variation in capitalization, punctuation, etc. within a study)\n%\n% - Also extracts and adds Year field; if it doesn't exist yet, attempts to\n% extract from .study\n%\n% - This function enforces some naming regularity not previously enforced,\n% so is a good idea to run. e.g., .study, .Year.\n%\n% Afterwards, you can do this kind of thing:\n% N_by_year_table = varfun(@mean, DB.TABLES.study_table, 'GroupingVariables','Year', 'InputVariables', 'mean_Subjects', 'OutputFormat','table');\n% ste_table = varfun(@ste, DB.TABLES.study_table, 'GroupingVariables','Year', 'InputVariables', 'mean_Subjects', 'OutputFormat','table');\n% \n% N_by_year_table = join(N_by_year_table, ste_table);\n% \n% create_figure('Sample size'); \n% plot(DB.TABLES.study_table.Year, DB.TABLES.study_table.mean_Subjects, 'ko');\n% plot(N_by_year_table.Year, N_by_year_table.mean_mean_Subjects, 'LineWidth', 3, 'Color', 'b');\n% \n% xlabel('Year')\n% ylabel('Mean sample size per contrast')\n%\n% See also:\n% [num, wh, weighted_num, conindx] = meta_count_contrasts(DB, testfield, fieldvalue)\n%\n\n% Tor Wager, 5/7/2022\n\n% initialize tables, in case we have selected levels/variables in DB,\n% so that we want to re-start.\n\nDB.TABLES = [];\n\n% Check study var and fix if needed\nif ~isfield(DB, 'study')\n if isfield(DB, 'Study')\n DB.study = DB.Study;\n\n else\n error('Enter DB.study or DB.Study');\n end\nend\n\nnames = fieldnames(DB);\n\n% exclude a few uninteresting variables\nnames(strcmp(names, 'x')) = [];\nnames(strcmp(names, 'y')) = [];\nnames(strcmp(names, 'z')) = [];\nnames(strcmp(names, 'xyz')) = [];\n\nlen = length(DB.x); % number of points\n\nfor i = 1:length(names)\n\n fieldn = names{i};\n\n if size(DB.(fieldn), 1) == len % for variables with point annotations...\n\n DB.TABLES.(fieldn) = create_variable_table(DB, fieldn);\n\n % assume some vars not of interest for printing tables,\n % if n levels >= n contrasts\n\n if size(DB.TABLES.(fieldn), 1) < length(DB.pointind)\n\n disp(fieldn)\n disp(DB.TABLES.(fieldn))\n\n % check\n np = sum(DB.TABLES.(fieldn).NumPoints);\n nc = sum(DB.TABLES.(fieldn).NumContrasts);\n ns = sum(DB.TABLES.(fieldn).NumStudies);\n\n tt = table(np, nc, ns, 'VariableNames', {'TotalPoints' 'TotalContrasts' 'TotalStudies'});\n disp(tt);\n\n fprintf('Compare to: Total %3.0f points, %3.0f contrasts, and %3.0f studies in DB\\n', length(DB.x), length(DB.pointind), length(unique(DB.study)));\n disp('(Studies may report multiple contrasts total may be > than num of unique studies.)')\n disp(' ')\n\n end % print\n\n end % add table\n\nend % add all tables\n\n%% Add Year\n\nDB = add_Year_field_and_table(DB);\n\ndisp('Added variable tables to DB.TABLES')\ndisp('For final study table see DB.TABLES.study_table, and DB.TABLES.ccontrast_table')\n\nend % function\n\n\n\n% ----------------------------------------------------------\n% ----------------------------------------------------------\n\n%% Subfunctions\n\n% ----------------------------------------------------------\n% ----------------------------------------------------------\n\n\n\nfunction t = create_variable_table(DB, fieldn)\n% input: DB and field name (fieldn)\n% output: table summarizing levels, points, and contrasts\n\nif iscell(DB.(fieldn))\n % if cell array with text entries\n u = unique(DB.(fieldn));\n\nelse\n % assume numeric vector or matrix of column vectors\n u = unique(DB.(fieldn), 'rows');\n\nend\n\n\nclear npts ncons nstudies\n\nfor i = 1:size(u, 1)\n\n if iscell(DB.(fieldn))\n % if text\n wh = strcmp(DB.(fieldn), u{i});\n else\n % assume numeric vector or matrix of column vectors\n wh = ismember(DB.(fieldn), u(i, :), 'rows');\n end\n\n % count points\n npts(i, 1) = sum(wh);\n\n % count contrasts\n ncons(i, 1) = sum(wh(DB.pointind));\n\n\n % count studies\n study_list = DB.study(wh);\n\n nstudies(i, 1) = length(unique(study_list));\n\nend\n\nt = table(u, npts, ncons, nstudies, 'VariableNames', {'Level' 'NumPoints' 'NumContrasts' 'NumStudies'});\n\nt.Properties.Description = fieldn;\n\n\n\nend\n\n\n\nfunction DB = add_Year_field_and_table(DB)\n\nDB = enforce_DB_Year_field(DB);\n% Enforce that if we have a year field, it's DB.Year, and numeric\n\nDB = enforce_DB_Study_field(DB);\n% Enforce that if we have a study field, it's DB.study, lower-case s\n \n[study, studyindx] = unique(DB.study, 'stable');\n\nif ~isfield(DB, 'Year')\n\n disp('Extracting DB.Year from DB.study')\n\n % old way: regexp\n % yr = zeros(size(DB.study));\n % for i = 1:length(DB.study)\n % yr(i, 1) = nums_from_text(DB.study{i});\n % end\n\n % Assume we have 2-digit or 4-digit years, and want to include only these in your match:\n S = regexp(DB.study, '\\d{2,4}', 'match', 'once', 'forceCellOutput');\n S(cellfun(@isempty, S)) = {'NaN'};\n yr = cellfun(@str2num, S);\n\n % now add 1900 to any years > 80 & < 99, assuming this is 2-digit entry\n wh = yr > 80 & yr < 99;\n yr(wh) = yr(wh) + 1900;\n\n % add 2000 to early numbers assuming 2-digit in 2000s\n wh = yr >= 0 & yr < 50; % good till 2050\n yr(wh) = yr(wh) + 2000;\n\n DB.Year = yr;\n\n % yeartable = table(study, yr(wh), 'VariableNames', {'Study' 'Year'});\n % disp(yeartable)\n\nend\n\n\n% Custom overall Contrast table\n\nDB.TABLES.contrast_table = table(DB.study(DB.pointind), DB.Year(DB.pointind), DB.Subjects(DB.pointind), DB.Contrast(DB.pointind), 'VariableNames', {'study' 'Year' 'Subjects' 'Contrast'});\n\n% Add sample size to study table: Mean subjects per contrast\nmean_N = varfun(@mean, DB.TABLES.contrast_table, 'GroupingVariables','study', 'InputVariables', 'Subjects', 'OutputFormat','table');\nmean_N.Properties.VariableNames{2} = 'Num_Contrasts';\n\n% Custom overall study table\n% note: rows are in different order from contrast table, so we must use\n% join method\n\nDB.TABLES.study_table = table(DB.study(studyindx), DB.Year(studyindx), 'VariableNames', {'study' 'Year'});\n\nDB.TABLES.study_table = join(DB.TABLES.study_table, mean_N);\n\nend\n\n\nfunction DB = enforce_DB_Study_field(DB)\n% Enforce that if we have a study field, it's DB.study\n% Also add DB.studyindx\n\nif ~isfield(DB, 'study') && isfield(DB, 'Study')\n\n DB.study = DB.Study;\n\nend\n\n[~, DB.studyindx] = unique(DB.study, 'stable'); % first entry in each study\n\nend\n\n\nfunction DB = enforce_DB_Year_field(DB)\n% Enforce that if we have a year field, it's DB.Year, and numeric\n\n\nif ~isfield(DB, 'Year') && isfield(DB, 'year')\n\n DB.Year = enforce_numeric_year(DB.year);\n\nelseif isfield(DB, 'Year')\n\n DB.Year = enforce_numeric_year(DB.Year);\n\nend\n\nend\n\nfunction year = enforce_numeric_year(year)\nif isnumeric(year)\n % do nothing\n\nelse\n % convert\n year = cellfun(@str2num, year, 'UniformOutput', false);\n\n % if we have missing/other text values, need to further convert:\n if iscell(year)\n wh = ~cellfun(@isnumeric, year) | cellfun(@isempty, year);\n year(wh) = {NaN};\n year = [year{:}]';\n end\n\n if ~iscolumn(year), year = year'; end\n\nend\nend\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "dbcluster_point_table.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/Miscellaneous_Functions/dbcluster_point_table.m", "size": 2622, "source_encoding": "utf_8", "md5": "f3473d24efd4b40b63582c60f9784f91", "text": "function dbcluster_point_table(cl)\n% function dbcluster_point_table(cl)\n% looks for Study or study field in clusters\n% determines length, and looks for other fields of the same length\n% uses specified fields in a particular order, then other fields\n\nN = fieldnames(cl(1));\n\n% reorder - reverse order, bottom rows are top of list\n\nwh = find(strcmp(N,'alltask')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\nwh = find(strcmp(N,'Subjects')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\nwh = find(strcmp(N,'t_Value')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\nwh = find(strcmp(N,'Zscore')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\nwh = find(strcmp(N,'Z')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\nwh = find(strcmp(N,'distance')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\nwh = find(strcmp(N,'z')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\nwh = find(strcmp(N,'y')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\nwh = find(strcmp(N,'x')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\nwh = find(strcmp(N,'Study')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\nwh = find(strcmp(N,'study')); if ~isempty(wh),tmp = N(wh);N(wh) = []; N = [tmp;N];,end\n\n\nfor i = 1:length(cl)\n \n % print coordinates\n fprintf(1,'Coordinate: %3.0f %3.0f %3.0f\\n',cl(i).mm_center(1), cl(i).mm_center(2),cl(i).mm_center(3));\n \n if isfield(cl,'Study'),study = cl(i).Study; L = length(cl(i).Study); end\n if isfield(cl,'study'),study = cl(i).Study; L = length(cl(i).Study); end\n \n if ~(exist('L')==1), disp('No Study or study variable in clusters.'), return; end\n \n % print header\n for k = 1:length(N)\n \n % figure out if this field is the right length\n eval(['x = cl(i).' N{k} ';']);\n go = 0;\n if iscell(x), if length(x) == L, go = 1; end %tmp = x{i}; end\n elseif size(x,1) == L, go = 1; % tmp = x(i,1);\n end\n \n % print, if it is\n if go\n print_f(N,k,length(N));\n end\n end\n fprintf(1,'\\n')\n \n \n \n % print body rows\n \n for j = 1:L\n\n for k = 1:length(N)\n eval(['tmp = cl(i).' N{k} ';'])\n print_f(tmp,j,L);\n end\n fprintf(1,'\\n')\n end\n fprintf(1,'\\n')\n \nend\n\n\n\n\nfunction print_f(x,i,L,varargin)\n\ngo = 0;\nif iscell(x), if length(x) == L, go = 1; tmp = x{i}; end\nelseif size(x,1) == L, go = 1; tmp = x(i,1);\nend\n\nif go\n if ~isstr(tmp), tmp = sprintf('%3.2f',tmp);,end\n \n fprintf(1,'%s\\t',tmp);\nend\n\nreturn\n\n\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "cluster_overlap_npm.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/cluster_overlap_monte_carlo/cluster_overlap_npm.m", "size": 5965, "source_encoding": "utf_8", "md5": "74a1313743f86d67b7b07ea94cad5813", "text": "function [OUT] = cluster_overlap_npm(cl1,cl2,varargin)\n% function [OUT] = cluster_overlap_npm(cl1,cl2,[mask_fname],[iterations])\n% tor wager\n% takes 2 clusters structures and determines overlap\n% - then runs Monte Carlo simulation randomizing cluster\n% centers within a mask\n%\n% Mask and input files must have the same voxel sizes and dimensions!\n% They must be in the same space!\n%\n% OUT has stuff for stats and overlapping voxels\n% see overlap_table.m\n\n% ----------------------------------------------------\n% * optional argument setup\n% ----------------------------------------------------\n\nif length(varargin) > 0\n\tP = varargin{1};\nelse\n P = ['brain_avg152T1.img']; % 2 mm voxels\nend\n\nif length(varargin) > 0, niter = varargin{2}; else niter = 5000; end\n\n% ----------------------------------------------------\n% * get list of all coordinates in brain mask\n% vol: row, col, array = x, y, z\n% ----------------------------------------------------\nP = which(P);\n V = spm_vol(P);\n vol = spm_read_vols(V);\n voxsize = diag(V(1).mat)';\n voxsize = voxsize(1:3);\n \n[x,y,z] = ind2sub(size(vol),find(vol)); % find values > 0 in vol\nallXYZ = [x y z]; % XYZ is in 3 columns in this function\n%Q = ones(1,size(allXYZ,1));\n%slices = allXYZ(:,3)'; % used to pass only certain slices to subfunctions\n\n% ----------------------------------------------------\n% * prepare cluster info for faster iteration\n% strip clusters of extraneous fields\n% calculate the amount of overlap\n% ----------------------------------------------------\nl1 = length(cl1); l2 = length(cl2);\nv1 = [];\nfor i = 1:length(cl1), \n cla1(i).XYZ = cl1(i).XYZ;\n cla1(i).center = mean(cl1(i).XYZ,2)';\n cla1(i).mm_center = cl1(i).mm_center;\n v1 = [v1 i .* ones(1,size(cla1(i).XYZ,2))];, \nend\ncl1 = cla1; clear cla1;\n\nv2 = [];\nfor i = 1:length(cl2), \n cla2(i).XYZ = cl2(i).XYZ;\n cla2(i).center = mean(cl2(i).XYZ,2)';\n cla2(i).mm_center = cl2(i).mm_center;\n v2 = [v2 i .* ones(1,size(cla2(i).XYZ,2))];, \nend \ncl2 = cla2; clear cla2;\nOUT.cl1 = cl1; OUT.cl2 = cl2;\n[OUT.obs_o1,OUT.obs_ovec1,OUT.obs_ovec2,OUT.xyzo,OUT.cent1,OUT.cent2] = overlap(cl1,cl2,v1,v2);\n\n% change voxel centers to mm centers\nfor i = 1:size(OUT.cent1,1), if ~isnan(OUT.cent1(i,1)),OUT.cent1(i,:)=voxel2mm(OUT.cent1(i,:)',V.mat);,end,end\nfor i = 1:size(OUT.cent2,1), if ~isnan(OUT.cent2(i,1)),OUT.cent2(i,:)=voxel2mm(OUT.cent2(i,:)',V.mat);,end,end\n\n% get BAs\nwarning off\nfor i = 1:size(OUT.cent1,1), if ~isnan(OUT.cent1(i,1)),tmp=mni2BA(OUT.cent1(i,:)');,OUT.ba1{i} = tmp;,end,end\nfor i = 1:size(OUT.cent2,1), if ~isnan(OUT.cent2(i,1)),tmp=mni2BA(OUT.cent2(i,:)');,OUT.ba2{i} = tmp;,end,end\nwarning on\n\n\nt1 = clock;\nfor i = 1:niter\n\n % ----------------------------------------------------\n % * pick random voxel coords\n % * adjust each cluster to centers\n % * get overlap (els are overlap for each cluster)\n % ----------------------------------------------------\n \n [c1,c2] = getcenters(l1,l2,allXYZ);\n [cla1,cla2] = movecenters(cl1,cl2,c1,c2);\n [o1(i),ovec1(i,:),ovec2(i,:)] = overlap(cla1,cla2);\n \n if mod(i,500)==0, fprintf(1,'.'), end\nend\n\nfprintf(1,' done (in %4.0f s)!\\n',etime(clock,t1))\nOUT.o1 = o1; OUT.ovec1 = ovec1; OUT.ovec2 = ovec2;\n\n% ----------------------------------------------------\n% * print table of results\n% ----------------------------------------------------\n\noverlap_table(OUT)\n\n\nreturn\n\n\n% ----------------------------------------------------\n% * \n% * Sub-functions\n% * \n% ----------------------------------------------------\n \n\nfunction [c1,c2] = getcenters(l1,l2,XYZ)\n\ntmp = ceil(rand(l1,1) .* size(XYZ,1));\nc1 = XYZ(tmp,:);\n\ntmp = ceil(rand(l2,1) .* size(XYZ,1));\nc2 = XYZ(tmp,:);\n\nreturn\n\n\n\n\nfunction [cla1,cla2] = movecenters(cl1,cl2,c1,c2)\n\nfor i = 1:length(cl1)\n tmp = cl1(i).XYZ' - repmat(cl1(i).center,size(cl1(i).XYZ,2),1);\n cla1(i).XYZ = round(tmp + repmat(c1(i,:),size(tmp,1),1))';\nend\n\nfor i = 1:length(cl2)\n tmp = cl2(i).XYZ' - repmat(cl2(i).center,size(cl2(i).XYZ,2),1);\n cla2(i).XYZ = round(tmp + repmat(c2(i,:),size(tmp,1),1))';\nend \n\nreturn\n\n \n\nfunction [o1,ovec1,ovec2,xyzo,cent1,cent2] = overlap(cla1,cla2,varargin)\n% function [o1,o2,ovec1,ovec2,xyzo,centers1,centers2] = overlap(cla1,cla2,[v1,v2])\n%\n% tor wager\n% o1 and o2 are overall measures of overlap\n% ovec1 and 2 are for each cluster\n% cla1 and 2 are the clusters structures\n% v1 and v2 are optional vectors indicating cluster memberships:\n% integers code which cluster, for all clusters strung together\n% e.g., [1 1 1 1 1 1 2 2 2 2 3 3 3 3 3 ... etc]\n% if not included, they will be created\n% include them to save time in simulation\n\nif length(varargin) > 0\n\tv1 = varargin{1}; v2 = varargin{2};\nelse\n v1 = [];\n for i = 1:length(cla1), v1 = [v1 i .* ones(1,size(cla1(i).XYZ,2))];, end\n v2 = [];\n for i = 1:length(cla2), v2 = [v2 i .* ones(1,size(cla2(i).XYZ,2))];, end \nend\n \nxyz1 = cat(2,cla1.XYZ)'; xyz2 = cat(2,cla2.XYZ)';\n\n[xyzo,i1,i2] = intersect(xyz1,xyz2,'rows');\no1 = size(xyzo,1);\n\n% individual clusters\n\nvv1 = v1(i1); vv2 = v2(i2);\nif ~isempty(vv1),\n for i = 1:length(cla1), ovec1(i) = sum(vv1 == i);, end \nelse\n ovec1 = zeros(1,length(cla1));\nend\n\nif ~isempty(vv2),\n for i = 1:length(cla2), ovec2(i) = sum(vv2 == i);, end\nelse\n ovec2 = zeros(1,length(cla2));\nend\n\n\n\n if nargout > 4 % save overlap centers\n for i = 1:length(cla1),\n [tmp,i1,i2] = intersect(cla1(i).XYZ',xyz2,'rows');\n cent = mean(tmp); if isempty(cent), cent = [NaN NaN NaN];,end\n cent1(i,:) = cent;\n end\n end\n \n if nargout > 4 % save overlap centers\n for i = 1:length(cla2),\n [tmp,i1,i2] = intersect(cla2(i).XYZ',xyz1,'rows');\n cent = mean(tmp); if isempty(cent), cent = [NaN NaN NaN];,end\n cent2(i,:) = cent;\n end\n end\n \n\nreturn\n\n \n\n "} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "title_keywords.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/citation_plotter/title_keywords.m", "size": 2738, "source_encoding": "utf_8", "md5": "edc8720ccf7205c7b9e581be80cbf4f9", "text": "function [indic,scount,su,words] = title_keywords(titles2)\n% [indic,scount,su,words] = title_keywords(titles2)\n%\n% given a string matrix, stores individual words in each row, and finds the most frequent words.\n% Then stores a matrix of which rows have which of the most frequent words.\n\nt = titles2;\n\n% get all words in titles\n\nfor i = 1:size(t,1)\n ti = titles2(i,:);\n \n try\n w1 = find(ti == ')'); w1 = w1(1); w2 = find(ti == '.'); w2 = w2(w2 > w1); w3 = w2(end-1)-1; w2 = w2(1)+1;\n % w2 is first period following ), w3 is 2nd to last period\n\n ti2 = ti(w2:w3);\n words{i} = getwords(ti2);\n catch\n words{i} = {'Cannot_parse_title.'};\n disp(['title keywords.m, problem at row ' num2str(i) ': probably not a title with two periods, one after year one at end.'])\n end\nend\n\nfor i = 1:length(words), if isempty(words{i}), wh(i) = 1;, else, wh(i) = 0;, end, end\nwh = find(wh);\nwords1 = words;\nwords(wh) = [];\n\n% concatenate\nallw = str2mat(words{1});\nfor i = 2:length(words)\n allw = str2mat(allw,str2mat(words{i}));\nend\n\n[u,a,b] = unique(allw,'rows'); % elements of b are counts for each word\nfor i = 1:length(u),cnt(i) = sum(b==i);,end % frequency of each word\n[scount,wh] = sort(1./cnt);\nsu = u(wh,:); % sorted words in terms of frequency\nscount = cnt(wh); \n\n% check accuracy of above code\n%c = 0;for i=1:length(allw),if strcmp(deblank(allw(i,:)),'of'),c = c+1;,end,end\n\n\n% save top n words - you pick\nn = 25;\n\nsu = su(1:n,:); scount = scount(1:n);\nfor i = 1:n\n fprintf(1,'%3.0f %3.0f %s\\n',i,scount(i),su(i,:))\nend\n\nwh = input('Enter vector of numbers of words to save: ');\nsu = su(wh,:); scount = scount(wh);\n\n% indicator matrix\nindic = make_indicator(words1,su);\n \n\nreturn\n\n\nfunction w = getwords(ti)\n\nw4 = find(ti == ' ');\nfor j = 1:length(w4)-1, \n w{j} = lower(deblank(ti(w4(j)+1:w4(j+1))));, \n \n % exclude uninteresting characters\n w{j}([findstr(w{j},'(') findstr(w{j},')') findstr(w{j},'.') findstr(w{j},',') findstr(w{j},'''') findstr(w{j},':')]) = [];\n \n % exclude uninteresting words\n if strcmp(w{j},'a') | strcmp(w{j},'to') | strcmp(w{j},'and') | strcmp(w{j},'then') | strcmp(w{j},'for') | ...\n strcmp(w{j},'by') | strcmp(w{j},'then') | strcmp(w{j},'in') | strcmp(w{j},'the') | strcmp(w{j},'of') | ...\n strcmp(w{j},'activation') | strcmp(w{j},'responses') | strcmp(w{j},'central') | ...\n strcmp(w{j},'with') | strcmp(w{j},'an') | strcmp(w{j},'study') | strcmp(w{j},'during') | strcmp(w{j},'on') \n\n w{j} = [];\n end\n \nend\nw = w';\nfor i = 1:length(w), if isempty(w{i}), wh(i) = 1;, else, wh(i) = 0;, end, end\nwh = find(wh);\nw(wh) = [];\n\nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_NBC.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/Meta_NBC/Meta_NBC.m", "size": 2617, "source_encoding": "utf_8", "md5": "7e1ebd3a39242a10fecad032a2a7c12c", "text": "function [nbc, data, group_data] = Meta_NBC(MC_Setup, terms, test_images)\n% [nbc, data, group_data] = Meta_NBC(MC_Setup, terms, test_images)\n%\n% You will need:\n% Inputs: a folder of text files with term labels\n%\n% MC_Setup = a database saved from an MKDA meta-analysis\n% terms = {'pain', 'working.memory', 'emotion'};\n% test_images = 'pain_test_data.img'\n%\n\n% Load group data up front, so we know if OK...\n% --------------------------------------------------\nif nargin > 2\n group_data = load_test_data(MC_Setup, test_images);\nelse\n group_data = [];\nend\n\n% Set up data object with default parameters\n% --------------------------------------------------\ndata = meta_dataset('MC_Setup', MC_Setup);\nclear MC_Setup\n\n% Choose terms and restrict dataset\n% --------------------------------------------------\ndata = setup_data(data, terms);\n\n% Train classifier on all data\n% --------------------------------------------------\nnbc = train(meta_nbc, data);\n\n% Test on same data to get apparent misclass rate\n% --------------------------------------------------\nnbc = test(nbc, data.dat);\nnbc = get_error(nbc, data.classes);\n\n% Display apparent correct classification rate\nfprintf('\\nApparent classification accuracy:\\n---------------------------------------------\\n')\nnbc = report(nbc);\n\n% Cross-validate and get cv error rate\n% --------------------------------------------------\nnbc = cv(nbc, data);\n\nfprintf('\\nCross-validated accuracy for meta-analysis dataset:\\n---------------------------------------------\\n')\nnbc = report(nbc);\n\n% Test on new image data -- if entered\n% --------------------------------------------------\n\nif nargin > 2\n \n nbc = test(nbc, group_data.dat(:, data.include_vox)', 1);\n \n test_class = ones(size(group_data.dat, 1), 1);\n \n nbc = get_error(nbc, test_class);\n \n fprintf('\\nAccuracy for test data:\\n---------------------------------------------\\n')\n nbc = report(nbc);\nend\n\nend % main function\n\n\n\n\nfunction group_data = load_test_data(MC_Setup, test_images)\n\n\nt1 = tic;\ndisp('Loading mask from MC_Setup')\n[discard, maskname, ee] = fileparts(MC_Setup.volInfo.fname);\nmaskname = [maskname ee];\n\nif exist(maskname, 'file')\n mask = fmri_mask_image(which(maskname));\nelse\n error('Mask %s is not on path.', maskname);\nend\n\n\ndisp('Reading data in mask space')\ngroup_data = fmri_data(test_images, mask, 'sample2mask');\n\n\nfprintf('Loaded in %3.0f sec\\n', toc(t1)); \n\nend\n\n% methods(group_data)\n% plot(group_data);\n\n% % RESAMPLE TEST DATA TO NEW SPACE\n% \n% group_data = resample_space(group_data, volInfo);\n% \n% fprintf('Resampled in %3.0f sec\\n', toc(t1)); t1 = tic;\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "Meta_SVM_from_mkda.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/Meta_NBC/Meta_SVM_from_mkda.m", "size": 21231, "source_encoding": "utf_8", "md5": "07ec00d1f2470853e576730b0dd27c3d", "text": "function PRED = Meta_SVM_from_mkda(DB, fieldname, names_cell, varargin)\n% Take output from Meta_Setup (DB) and\n% runs a one-vs-one nonlinear SVM classifier, on labels of your choice.\n%\n% [nbc, data] = meta_SVM_from_mkda(MC_Setup, DB, fieldname, names_cell)\n%\n% Note: You need the spider package on your matlab path.\n%\n% Inputs:\n% DB: Meta-analysis (MKDA) database structure \n% - required fields: DB.x, y, z, Contrast, Study, named field to classify (cell array of strings)\n% - see Meta_Setup and read_database.m\n% fieldname : Field in database to use for classification\n%\n% Optional inputs:\n% -----------------------------------------------------------------\n% Enter variable name in quotes followed by new value for any of the options below:\n% nfolds = 10; % 'nfolds' followed by number of folds\n% rbf_sigma = 15; % 'rbf_sigma' followed by st dev in mm\n% balanced_ridge = 8; % arbitrary; 0 is no penalty for unbalanced classes\n% holdout_meth = 'kfold'; % or 'study' for leave one study out\n% test_method = 'distance'; % 'vote' or 'distance'; method for multi-class classifications\n% % vote picks lowest class # in case of ties so\n% is less preferred, but very similar to\n% 'distance' in practice.\n% % 'distance' sums the dist from hyperplane\n% across all pairs to end up with a dist measure\n% for each class, and the max is selected.\n%\n% Examples:\n% -----------------------------------------------------------------\n% [nbc, data] = Meta_SVM_from_mkda(DB, MC_Setup, 'Valence', {'positive' 'negative'})\n%\n% fieldname = 'Stimuli';\n% [nms, contrastcounts] = meta_explore_field(DB, fieldname);\n% labels = nms(contrastcounts > 20)';\n% [nbc, data] = Meta_SVM_from_mkda(DB, MC_Setup, fieldname, labels);\n%\n% fieldname = 'Emotion';\n% names_cell = {'sad' 'happy' 'anger' 'fear' 'disgust'};\n% PRED = Meta_SVM_from_mkda(DB, fieldname, names_cell, 'balanced_ridge', balridgeval, 'holdout_meth', 'study');\n%\n%PRED = Meta_SVM_from_mkda(DB, fieldname, names_cell, 'balanced_ridge', 8, 'holdout_meth', 'study');\n%PRED = Meta_SVM_from_mkda(DB, fieldname, names_cell, 'balanced_ridge', balridgeval, 'nfolds', 3);\n%\n% Tor Wager, Feb 2013\n\n% Parameters -- hard-coded\n% ---------------------------------------------------------------------\n\nnfolds = 10;\nrbf_sigma = 15; % in mm\nbalanced_ridge = 8; % arbitrary; 0 is no penalty for unbalanced classes\nholdout_meth = 'kfold'; % or 'study' for leave one study out\ntest_method = 'distance'; % 'vote' or 'distance'; method for multi-class classifications\n\n% Optional inputs\n% ---------------------------------------------------------------------\nfor opt_args = {'balanced_ridge' 'nfolds' 'rbf_sigma' 'holdout_meth' 'test_method'}\n \n wh = strcmp(varargin, opt_args{1});\n if any(wh)\n wh = find(wh); wh = wh(1);\n eval([varargin{wh} ' = varargin{wh+1};']);\n end\n \nend\n\n% set up empty svm object for training\n% need spider package!\n% svmobj = svm({kernel('rbf', rbf_sigma), 'C=1', 'optimizer=\"andre\"'});\n% balanced ridge=1 only shifts things a little bit...\nsvmobj = svm({kernel('rbf', rbf_sigma), 'C=1', 'optimizer=\"andre\"', ['balanced_ridge=' sprintf('%d', balanced_ridge)]});\n\n% GET RELEVANT DATA\n% Get list of coords matching each category of input\n% ---------------------------------------------------------------------\n\ncfun = @(name) strcmp(DB.(fieldname), name);\nwh = cellfun(cfun, names_cell, 'UniformOutput', 0);\n\n% wh : which coordinates to include\nwh = cat(2, wh{:});\nwh = any(wh, 2);\n\noutcome = DB.(fieldname);\noutcome = outcome(wh);\nxyz = [DB.x DB.y DB.z];\nxyz = xyz(wh, :);\n\ncontrastnum = DB.Contrast;\ncontrastnum = contrastnum(wh);\n\nPRED.PARAMS = struct('nfolds', nfolds, 'rbf_sigma', rbf_sigma, 'svmobj', svmobj);\n\nPRED.DATA = struct('wh_coords', wh, 'outcome', {outcome}, 'xyz', xyz, 'contrastnum', contrastnum);\nPRED.DATA.outcome = PRED.DATA.outcome{1};\n\nnclasses = length(names_cell);\n\n% ---------------------------------------------------------------------\n% true outcomes, by contrast\n% ---------------------------------------------------------------------\n\nu = unique(contrastnum);\n\nfor i = 1:length(u)\n truevals = outcome(contrastnum == u(i));\n true_val(i, 1) = truevals(1);\n \n % check for errors in data entry\n if any(~strcmp(truevals, truevals{1}))\n warning(['CONTRAST ' num2str(i) ' VALUES DO NOT ALL HAVE SAME OUTCOME VALUE.']);\n end\n \nend\n\n% Point counts\ncn = PRED.DATA.contrastnum;\nfor i = 1:length(u)\n npoints(i, 1) = sum(cn == u(i));\nend\n\nPRED.CONTRASTDATA = struct('u', u, 'u_descrip', 'unique contrast numbers');\nPRED.CONTRASTDATA.outcome = true_val;\nPRED.CONTRASTDATA.point_counts = npoints;\n\n% ---------------------------------------------------------------------\n% holdout sets:\n% ---------------------------------------------------------------------\nswitch holdout_meth\n case 'kfold'\n % stratified partition, leave out whole contrasts\n [trIdx, teIdx] = define_holdout_sets(true_val, nfolds, outcome, contrastnum);\n \n case 'study'\n [indic, nms, condf] = string2indicator(DB.Study(wh));\n nfolds = size(indic, 2);\n \n fprintf('Leave one Study out cross-val: %d folds\\n', nfolds);\n for i = 1:nfolds\n trIdx{i} = ~indic(:, i);\n teIdx{i} = logical(indic(:, i));\n end\n \n otherwise\n error('invalid entry for holdout set.');\nend\n\n% ---------------------------------------------------------------------\n% ONE VS. ONE CLASSIFICATION\n% ---------------------------------------------------------------------\n\n% will classify each test COORDINATE\n% then we aggregate the coordinates using a voting (or distance) method,\n% by taking the sum of distance from the hyperplane across coodinates\n% within each contrastnum, to obtain a classification and confidence for each\n% contrastnum.\n\n% initialize vars\n% ---------------------------------------------------------------------\n\n[cv_class_est, cv_class_weights, cv_wh_teIdx] = deal(cell(nclasses)); % for each pair of classes\n\nfor emo1 = 1:nclasses-1\n \n for emo2 = emo1+1:nclasses\n \n [cv_class_est{emo1, emo2}, cv_class_weights{emo1, emo2}] = deal(NaN .* zeros(size(outcome)));\n \n \n end\nend\n\n% ---------------------------------------------------------------------\n% ---------------------------------------------------------------------\n% TRAIN/TEST: Loop through folds and pairs\n% ---------------------------------------------------------------------\n% ---------------------------------------------------------------------\n\nfor fold = 1:nfolds\n \n fprintf('Fold %d\\n', fold)\n \n % X and Y: all observations for this fold\n \n [~, nms, Y] = string2indicator(outcome(trIdx{fold}),names_cell);\n X = xyz(trIdx{fold}, :);\n \n [~, nms, Yt] = string2indicator(outcome(teIdx{fold}),names_cell);\n Xt = xyz(teIdx{fold}, :);\n \n % train each pair, one vs. one\n % Select data for pair\n % x and y: observations relevant for a specific pair\n \n % Loop through pairs and train/test\n % ------------------------------------------------------------------\n for emo1 = 1:nclasses-1\n \n for emo2 = emo1+1:nclasses\n \n fprintf('%s vs. %s\\t', names_cell{emo1}, names_cell{emo2});\n \n % Get pair data\n % ----------------------------------------------------------\n y = zeros(size(Y));\n y(Y == emo1) = 1;\n y(Y == emo2) = -1;\n \n if all(y == 0)\n % no train points in this comparison\n fprintf('No training points.\\n')\n continue\n end\n \n % wh_omit: points not part of this specific comparison emo1, emo2\n wh_omit = y == 0;\n y(wh_omit) = [];\n \n x = X;\n x(wh_omit, :) = [];\n \n dat = data(x, y); %<- for input into spider package\n \n \n y = zeros(size(Yt));\n y(Yt == emo1) = 1;\n y(Yt == emo2) = -1;\n \n % Now: Test ALL points in test set for every classifier.\n % We do not know for the test set what the true class is...\n % so we cannot compare only on the decisions involving the true\n % class.\n % if all(y == 0)\n % no test points in this comparison\n % fprintf('No test points.\\n')\n % continue\n % end\n %\n % wh_omit = y == 0;\n % y(wh_omit) = [];\n %\n x = Xt;\n % x(wh_omit, :) = [];\n \n dattest = data(x, y); %<- for input into spider package\n \n wh_teIdx = find(teIdx{fold});\n % wh_teIdx(wh_omit) = [];\n \n \n % Train\n % ----------------------------------------------------------\n \n [restrain, svmtrained] = train(svmobj, dat);\n \n % Test and get loss <- res.X is predicted class\n % ----------------------------------------------------------\n \n res = test(svmtrained,dattest);\n \n % Save results in array\n % ----------------------------------------------------------\n %L = loss(res2, 'class_loss')\n cv_class_est{emo1, emo2}(wh_teIdx) = res.X;\n \n \n % NOTE: try to get weights for class probability estimates and better\n % voting of contrastnum emotion type based on points. RBF is a really good idea here.\n % but i think we can do it using use_signed_output = 0\n \n svmtrained.use_signed_output = 0;\n res = test(svmtrained,dattest);\n \n cv_class_weights{emo1, emo2}(wh_teIdx) = res.X; % <- useful for multi-way classification\n \n %cv_wh_teIdx{emo1, emo2} = wh_teIdx;\n \n % cv_wh_teIdx\n % Save which estimates are directly relevant for classification\n % i.e., class1-2 or class2-3 for class 2. class 4-5 is not\n % relevant. Using this to estimate accuracy supposes that you\n % know something about the test class, i.e., that it's either 2\n % or something else, so is circular in straight-up multiclass\n % classification.\n % wh_omit = y == 0;\n % wh_teIdx(wh_omit) = [];\n % cv_wh_teIdx{emo1, emo2} = wh_teIdx;\n \n end\n end\n \nend % folds\n\nPRED.PAIRS = [];\nPRED.PAIRS.cv_class_est = cv_class_est;\nPRED.PAIRS.cv_class_weights = cv_class_weights;\nPRED.PAIRS.cv_wh_teIdx = cv_wh_teIdx;\n\n% ---------------------------------------------------------------------\n% Get accuracy and cv weights (distances) by contrast (in contrastnum)\n% ---------------------------------------------------------------------\n\n% First, get list of cross-val classifier weights by contrast\n% then, figure out whether sign of weights for each contrast matches true\n% category\n% 'weights' here is really distance from hyperplane\n\ndisp(' ');\n[cvweights, cvN, cvstd] = deal(cell(nclasses));\n\nfor emo1 = 1:nclasses-1\n \n for emo2 = emo1+1:nclasses\n \n % initialize\n cvweights{emo1, emo2} = NaN .* zeros(size(u)); % <- cvweights is per contrast\n \n testw = cv_class_weights{emo1, emo2}; % <- testw is per peak coord\n \n % to select only relevant comparisons:\n % this would replicate earlier biased multiclass method for testing\n % purposes\n % comment out after testing. BUT THIS IS NOT WORKING RIGHT...DEBUG\n % IF TESTING IS NEEDED\n % testw2 = NaN .* zeros(size(cv_class_weights{emo1, emo2}));\n % testw2(cv_wh_teIdx{emo1, emo2}) = testw(cv_wh_teIdx{emo1, emo2});\n % testw = testw2;\n \n wh = ~isnan(testw);\n \n numcons = length(unique(contrastnum(wh)));\n fprintf('%s vs. %s\\t:\\t%3.0f coords, %3.0f contrasts\\n', names_cell{emo1}, names_cell{emo2}, sum(wh), numcons);\n \n for c = 1:length(u)\n \n this_con = contrastnum == u(c);\n \n this_con = this_con & wh; % this contrastnum AND this pair\n \n if ~any(this_con)\n % empty\n [cvw, cvs] = deal(NaN);\n cvnum = 0;\n else\n % average weights for this contrastnum across peaks\n con_weights = testw(this_con);\n \n cvw = sum(con_weights);\n cvnum = length(con_weights);\n cvs = std(con_weights);\n end\n \n cvweights{emo1, emo2}(c, 1) = cvw; % average weight (distance from hyperplane)\n cvN{emo1, emo2}(c, 1) = cvnum; % number of peaks\n cvstd{emo1, emo2}(c, 1) = cvs; % weight sd\n \n end % contrastnum\n end\n \nend\n\nPRED.CONTRASTPAIRS = [];\nPRED.CONTRASTPAIRS.cvweights = cvweights;\nPRED.CONTRASTPAIRS.cvN = cvN;\nPRED.CONTRASTPAIRS.cvstd = cvstd;\n\n% ---------------------------------------------------------------------\n% Pairwise accuracy overall\n% ---------------------------------------------------------------------\n\n[cvtrue, cvcorrect] = deal(cell(nclasses));\ncvaccuracy = zeros(nclasses);\n\nfor emo1 = 1:nclasses-1\n \n for emo2 = emo1+1:nclasses\n \n [cvtrue{emo1, emo2}, cvcorrect{emo1, emo2}] = deal(NaN .* zeros(size(true_val)));\n \n cvtrue{emo1, emo2}(strcmp(true_val, names_cell{emo1})) = 1;\n cvtrue{emo1, emo2}(strcmp(true_val, names_cell{emo2})) = -1;\n \n cvcorrect{emo1, emo2} = double(cvtrue{emo1, emo2} == sign(cvweights{emo1, emo2}));\n %cvcorrect{emo1, emo2}(isnan(cvtrue{emo1, emo2})) = NaN;\n \n % cvaccuracy is pairwise acc. \n % cvtrue has NaNs where truth is neither of two classes being\n % compared.\n cvaccuracy(emo1, emo2) = sum(cvcorrect{emo1, emo2}) ./ sum(~isnan(cvtrue{emo1, emo2}));\n \n end\n \nend\n\nPRED.CONTRASTPAIRS.cvtrue = cvtrue;\nPRED.CONTRASTPAIRS.cvcorrect = cvcorrect;\nPRED.CONTRASTPAIRS.cvaccuracy = cvaccuracy;\nPRED.CONTRASTPAIRS.cvaccuracy_descrip = 'Pairwise CV accuracy';\n\n% ---------------------------------------------------------------------\n% ---------------------------------------------------------------------\n% get class estimates\n% PRED.class_est\n% ---------------------------------------------------------------------\n% ---------------------------------------------------------------------\n\n% 'vote': vote method to get predicted class in k-way classification\n% for confusion matrix\n% Max wins voting method: j friedman. Another approach to polychotomous classification. Tech report, Stanford U, 1996\n% One vs one: knerr, dreyfus, 1990 \"Single-layer learning revisited\" Neurocomputing\n% ---------------------------------------------------------------------\n\n% ---------------------------------------------------------------------\n% 'distance': Sum distance from hyperplane method to get predicted class\n% in k-way classification for confusion matrix\n% Introduced for one-against-all in Vapnik 1998\n% Vapnik, V. (1998). Statistical Learning Theory. Wiley-Interscience, NY.\n%\n% For one vs. one, could use \"tournament method\" or DAGSVM, but not\n% necessarily better\n% Kijsirikul, B. & Ussivakul, N. (2002) Multiclass support vector machines using adaptive directed acyclic graph. Proceedings of International Joint Conference on Neural Networks (IJCNN 2002), 980-985.\n%\n% ---------------------------------------------------------------------\n\n\n% 2 vote methods: mode of pairwise, or count votes for vs. against\n% should produce identical results (tor tested 3/2013, yes)\n[votesbyclass, class_dist] = deal(zeros(length(u), nclasses));\n\nindx = 1;\n\nfor emo1 = 1:nclasses-1\n \n for emo2 = emo1+1:nclasses\n \n w = cvweights{emo1, emo2}; % dist from hyplane really\n \n yesno = sign(w);\n \n % emo1 (row) is \"on\" class, emo2 is \"off\" class\n votesbyclass(:, emo1) = votesbyclass(:, emo1) + yesno;\n votesbyclass(:, emo2) = votesbyclass(:, emo2) - yesno;\n \n % convert to class number\n yesno(yesno == 1) = emo1;\n yesno(yesno == -1) = emo2;\n \n class_est(:, indx) = yesno; % contrast x class, vote method\n \n % emo1 (row) is \"on\" class, emo2 is \"off\" class\n class_dist(:, emo1) = class_dist(:, emo1) + w;\n class_dist(:, emo2) = class_dist(:, emo2) - w;\n \n indx = indx + 1;\n\n end\n \nend\n\n% Final class estimates and confusion matrix\n% ---------------------------------------------------------------------\nif size(class_est, 2) > 1\n class_est1 = mode(class_est')';\nelse\n class_est1 = class_est;\nend\n\n[~, class_est2] = max(votesbyclass, [], 2); % <- should be identical to est1 above\n[~, class_est3] = max(class_dist, [], 2); % <- distance method\n\nswitch test_method\n case 'vote'\n PRED.class_est = class_est1;\n case 'distance'\n PRED.class_est = class_est3;\n otherwise error('unknown test method.')\nend\n\nPRED.class_est_pairwise = class_est;\nPRED.class_est_pairwise_descrip = 'Estimated class, contrasts x pairs';\n\n% ---------------------------------------------------------------------\n% Print output\n% ---------------------------------------------------------------------\n\n[PRED.true_indic, PRED.true_names, PRED.true_class] = string2indicator(true_val, names_cell);\n\nfprintf('\\nPairwise SVM accuracy:\\n');\nprint_matrix(cvaccuracy, PRED.true_names, PRED.true_names, '%3.2f');\npairacc = cvaccuracy(:);\nmeanpairacc = mean(pairacc(pairacc ~= 0));\n\nfprintf('Mean pairwise SVM accuracy: %3.2f\\n', meanpairacc);\n\nfprintf('\\nMulticlass SVM accuracy:\\n');\n\n[m,dprime,corr,far,misclass, mprop] = confusion_matrix(PRED.true_class, PRED.class_est);\n\nPRED.confusion_mat = m;\nPRED.confusion_mat_prop = mprop;\nPRED.acc = corr;\n\ndisp('Accuracy by class')\nprint_matrix(PRED.acc, PRED.true_names, PRED.true_names, '%3.2f');\n\ndisp('Confusion matrix - counts')\nprint_matrix(PRED.confusion_mat, PRED.true_names, PRED.true_names, '%3.0f');\n\nfprintf('\\n')\ndisp('Confusion matrix - proportions')\nprint_matrix(PRED.confusion_mat_prop, PRED.true_names, PRED.true_names, '%3.2f');\n\nfprintf('Mean balanced accuracy: %3.2f\\n', mean(PRED.acc))\n\n% n points x accuracy\n\n% [h, hc] = hist(npoints, 7);\n% n = length(h);\n% hc = [-Inf hc]; % should adjust to get proper bin edges\n% for i = 1:n\n% wh = npoints >= hc(i) & npoints < hc(i+1);\n% acc(i, 1) = 1 - mean(misclass(wh));\n% end\n\n\n%% Point maps:\n% We need to generate point-by-point estimates for every coordinate in the\n% brain, and its contribution to the decision.\n%\n% this could yield two maps: A MLC (most likely class; analogue of maximum\n% a posteriori probability)\n% ...and a weight map for each point.\n\n\nend % function\n\n\n\nfunction [trIdx, teIdx] = define_holdout_sets(true_val, nfolds, outcome, contrastnum)\n\n% holdout sets\n% ---------------------------------------------------------------------\n% stratified partition\n% cvpartition preserves the proportions in each class in train/test\n% but does not force the number of training obs to be equal.\n%\n% Need to stratify by CONTRAST, so that an entire contrastnum at a time is\n% left out.\n% ---------------------------------------------------------------------\n\nu = unique(contrastnum);\n\n[trIdx, teIdx] = deal(cell(1, nfolds));\n\ncvpart = cvpartition(true_val,'k',nfolds); % <- do this first in contrast space\n\n% display\n%print_matrix([], [{'Fold'} names_cell])\n\nfor i = 1:cvpart.NumTestSets\n \n trIdx{i} = cvpart.training(i);\n teIdx{i} = cvpart.test(i);\n \n % display\n % [indic,nms] = string2indicator(outcome(trIdx{i}),names_cell);\n % print_matrix(sum(indic), [], {['Train Fold ' num2str(i)]});\n %\n % [indic,nms] = string2indicator(outcome(teIdx{i}),names_cell);\n % print_matrix(sum(indic), [], {['Test Fold ' num2str(i)]});\n \n \nend\n\n% Now re-assign trIdx and teIdx in coordinate space, leaving out whole\n% contrasts\nfor i = 1:cvpart.NumTestSets\n \n [coord_trIdx{i}, coord_teIdx{i}] = deal(false(size(outcome)));\n \n whtrain = find(trIdx{i});\n whtest = find(teIdx{i});\n \n for c = 1:length(whtrain)\n \n wh = contrastnum == u(whtrain(c));\n \n coord_trIdx{i}(wh) = true;\n \n end\n \n for c = 1:length(whtest)\n wh = contrastnum == u(whtest(c));\n \n coord_teIdx{i}(wh) = true;\n \n end\n \n \nend\n\ntrIdx = coord_trIdx;\nteIdx = coord_teIdx;\n\nfprintf('Cross-validated prediction with SVM, %3.0f folds\\n', nfolds)\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "plot.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/Meta_NBC/@meta_dataset/plot.m", "size": 8248, "source_encoding": "utf_8", "md5": "0ca444a45ef723b542c04792710b9469", "text": "function plot(metaobj, plotmethod)\n% plot(metaobj, [plotmethod])\n%\n% Plot methods:\n% ----------------------------------------\n% Plot data matrix\n% plot(fmri_data_object)\n%\n% Plot means by condition\n% plot(fmri_data_object, 'means_for_unique_Y')\n%\n%\nif nargin < 2\n plotmethod = 'data';\nend\n\n\nswitch plotmethod\n % ==============================================================\n case 'data'\n % ==============================================================\n \n if isempty(metaobj.dat)\n warning('No data in .dat field.');\n return\n end\n \n create_figure('fmri data matrix', 2, 2);\n imagesc(metaobj.dat');\n colorbar; colormap gray\n axis tight; set(gca, 'YDir', 'Reverse')\n title('meta-analysis .dat Data matrix');\n xlabel('Voxels'); ylabel('Images');\n drawnow\n \n if ~isempty(metaobj.classes)\n p = get(gca, 'Position'); ystart = p(2); ylen = p(4);\n \n axh = axes('Position', [.05 ystart .03 ylen]);\n imagesc(metaobj.classes);\n title('Classes');\n axis tight;\n end\n drawnow\n \n % Centering\n % datc = scale(scale(metaobj.dat, 1)', 1)';\n % datc = scale(scale(metaobj.dat)')';\n \n \n % ---------------------------------------------------------------\n % Histogram\n % ---------------------------------------------------------------\n dattmp = metaobj.dat(:);\n subplot(2, 2, 2);\n [h, x] = hist(dattmp, 100);\n han = bar(x, h);\n set(han, 'FaceColor', [.3 .3 .3], 'EdgeColor', 'none');\n axis tight;\n xlabel('Values'); ylabel('Frequency');\n title('Histogram of values');\n drawnow\n \n clear dattmp\n \n \n % ---------------------------------------------------------------\n % Covariance\n % ---------------------------------------------------------------\n covmtx = cov(metaobj.dat);\n subplot(2, 2, 3);\n imagesc(covmtx);\n axis tight; set(gca, 'YDir', 'Reverse')\n title('cov(dat''), cov(rows of dat)');\n colorbar\n drawnow\n \n if ~isempty(metaobj.classes)\n p = get(gca, 'Position'); ystart = p(2); ylen = p(4);\n \n axh = axes('Position', [.05 ystart .03 ylen]);\n imagesc(metaobj.classes);\n title('Y');\n axis tight;\n \n end\n drawnow\n \n subplot(2, 2, 4);\n \n globalmean = nanmean(metaobj.dat); % global mean of each obs\n globalstd = nanstd(metaobj.dat); % global mean of each obs\n \n nobs = length(globalmean);\n \n Y = metaobj.classes;\n Yname = 'Y values in fmri data obj';\n if isempty(Y)\n Y = 1:nobs;\n Yname = 'Case number';\n end\n \n sz = rescale_range(globalstd, [4 14]); % marker size related to global std\n sz(sz < .5) = .5;\n \n for i = 1:nobs\n plot(Y(i), globalmean(i), 'ko', 'MarkerSize', sz(i), 'LineWidth', 1);\n end\n ylabel('Global mean');\n xlabel(Yname);\n title('Globals for each case (size = spatial std)')\n drawnow\n \n % [coeff, score, latent] = princomp(metaobj.dat, 'econ');\n % %d2 = mahal(score, score);\n % plot(latent)\n \n \n % ---------------------------------------------------------------\n % Orthviews\n % ---------------------------------------------------------------\n % check to be sure:\n metaobj.dat(isnan(metaobj.dat)) = 0;\n \n m = mean(metaobj.dat')';\n s = std(metaobj.dat')';\n d = m./s; \n d(m == 0 | s == 0) = 0;\n vecs_to_reconstruct = [m s d];\n \n if isempty(metaobj.volInfo)\n disp('.volInfo is empty. Skipping orthviews and other brain plots.');\n else\n create_orthviews(vecs_to_reconstruct, metaobj);\n spm_orthviews_name_axis('Mean data', 1);\n spm_orthviews_name_axis('STD of data', 2);\n spm_orthviews_name_axis('Mean / STD', 3);\n set(gcf, 'Name', 'Orthviews_fmri_data_mean_and_std');\n end\n \n % ==============================================================\n case 'means_for_unique_Y'\n % ==============================================================\n \n u = unique(metaobj.classes);\n \n [v, n] = size(metaobj.dat);\n nu = length(u);\n \n if nu > 20\n error('More than 20 unique values of Y. For means_by_condition, Y should be discrete integer-valued.');\n end\n \n [means, stds] = deal(zeros(nu, v));\n \n for i = 1:nu\n means(i, :) = nanmean(metaobj.dat(:, metaobj.classes == u(i))');\n stds(i, :) = nanstd(metaobj.dat(:, metaobj.classes == u(i))');\n end\n \n create_figure('means by condition (unique Y values)', 2, 1);\n imagesc(means);\n colorbar\n axis tight; set(gca, 'YDir', 'Reverse')\n title('Means by condition');\n xlabel('Voxels');\n if iscell(metaobj.classes_names) && ~isempty(metaobj.classes_names)\n set(gca, 'YTick', u, 'YTickLabel', metaobj.classes_names);\n else\n ylabel('Unique Y values');\n end\n \n drawnow\n \n subplot(2, 1, 2)\n imagesc(stds);\n colorbar\n axis tight; set(gca, 'YDir', 'Reverse')\n title('Standard deviations by condition');\n xlabel('Voxels');\n if iscell(metaobj.classes_names) && ~isempty(metaobj.classes_names)\n set(gca, 'YTick', u, 'YTickLabel', metaobj.classes_names);\n else\n ylabel('Unique Y values');\n end\n drawnow\n \n % ---------------------------------------------------------------\n % Orthviews\n % ---------------------------------------------------------------\n if ~isempty(metaobj.volInfo)\n vecs_to_reconstruct = means';\n create_orthviews(vecs_to_reconstruct, metaobj);\n n = size(vecs_to_reconstruct, 2);\n for i = 1:n\n \n if iscell(metaobj.classes_names) && ~isempty(metaobj.classes_names)\n spm_orthviews_name_axis(metaobj.classes_names{i}, i);\n end\n \n end\n set(gcf, 'Name', 'Orthviews_means_by_unique_Y');\n \n \n % ---------------------------------------------------------------\n % Montage: variance across conditions\n % ---------------------------------------------------------------\n vecs_to_reconstruct = std(means)';\n fig_handle = create_montage(vecs_to_reconstruct, metaobj);\n set(fig_handle, 'Name', 'Montage_cariability_across_conditions')\n end\n \n \n otherwise\n error('Unknown plot method');\nend\n\nend\n\n\nfunction create_orthviews(vecs_to_reconstruct, metaobj)\n\nn = size(vecs_to_reconstruct, 2);\noverlay = which('SPM8_colin27T1_seg.img');\nspm_check_registration(repmat(overlay, n, 1));\n\nfor i = 1:n\n \n cl{i} = iimg_indx2clusters(vecs_to_reconstruct(:, i), metaobj.volInfo);\n cluster_orthviews(cl{i}, 'add', 'handle', i);\n \n spm_orthviews_change_colormap([0 0 1], [1 1 0], [0 1 1], [.5 .5 .5], [1 .5 0]);\n \nend\n\nend\n\n\nfunction fig_handle = create_montage(vecs_to_reconstruct, metaobj)\n\nn = size(vecs_to_reconstruct, 2);\noverlay = which('SPM8_colin27T1_seg.img');\n\nfor i = 1:n\n \n dat = vecs_to_reconstruct(:, i);\n % top and bottom 10%\n dat(dat > prctile(dat, 10) & dat < prctile(dat, 90)) = 0;\n \n cl{i} = iimg_indx2clusters(dat, metaobj.volInfo);\n \n fig_handle(i) = montage_clusters(overlay, cl{i}, [2 2]);\n \n set(fig_handle, 'Name', sprintf('Montage %3.0f', i), 'Tag', sprintf('Montage %3.0f', i))\n \nend\n\nend\n\n\nfunction rx = rescale_range(x, y)\n% re-scale x to range of y\nm = range(y)./range(x);\n\nif isinf(m)\n % no range/do not rescale\n rx = x;\nelse\n b = y(1) - m * x(1);\n rx = m*x + b;\nend\nend\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "test.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/Meta_NBC/@meta_nbc/test.m", "size": 6032, "source_encoding": "utf_8", "md5": "b978f8b3fa176f4b8bec3f508ab72a21", "text": "function obj = test(obj, test_data, varargin)\n% obj = test(obj, test_data, varargin)\n%\n% test_data should be voxels x maps matrix of test data\n% can be either binary (i.e., meta-analysis peaks) \n% or continuous (e.g., single-subject t- or contrast maps)\n% Different methods are used for each data type.\n%\n% \n\ndobinarize = 0;\nif nargin > 2, dobinarize = varargin{1}; end\n\nif isempty(obj.train_pprobs_act)\n fprintf('You must train the nbc object first: train(nbc_obj, data_obj)\\n')\n error('Exiting');\nend\n\n% -----------------------------------------------------------------------\n% Sum of log posterior probabilities of each study \n% predictions for the test set\n% -----------------------------------------------------------------------\n\nif islogical(test_data) || length(unique(test_data(:))) < 3\n % we have a binary map\n fprintf('Predicting binary test data\\n')\n [class_pred, posterior_probs] = predict_binary_images(logical(test_data), obj);\n \nelse\n % assume continuous-valued images unless 'binarize' is set, in\n % which case, use a threshold of p < .05 and a minimum cut-off of 1%\n % of voxels\n if dobinarize\n thresh = 1.65;\n min_sig = 0.01;\n nvox = size(test_data,1);\n for i=1:size(test_data,2)\n active = zeros(nvox, 1);\n sig_vox = (test_data(:,i) >= thresh);\n nsig = sum(sig_vox)/nvox;\n [sor, sindex] = sort(test_data(:,i), 1, 'descend');\n if nsig < min_sig, nsig = min_sig; end\n active(sindex(1:(round(nsig*nvox))))=1;\n test_data(:,i) = active;\n\n end\n fprintf('Binarizing continuous-valued test data\\n') \n [class_pred, posterior_probs] = predict_binary_images(logical(test_data), obj);\n else\n fprintf('Predicting continuous-valued test data\\n') \n [class_pred, posterior_probs] = predict_continuous_images(test_data, obj);\n end\n \nend\n\nobj.class_pred = class_pred;\nobj.posterior_probs = posterior_probs;\n\nfprintf('Updated class_pred, posterior_probs in meta_nbc object.\\n');\n\n\nend % function\n\n\n\n\n\nfunction [class_pred, posterior_probs] = predict_binary_images(test_data, obj)\n\n[n_vox, n_maps] = size(test_data);\nn_classes = obj.n_classes;\n \nif isempty(n_classes), error('obj.n_classes is empty.'); end\n\nposterior_probs = zeros(n_maps, n_classes);\n\nfprintf('Map %3.0f', 0);\nfor ii = 1:n_maps\n fprintf('\\b\\b\\b%3.0f', ii);\n \n % construct weights for voxels, based on two parameters\n% nbc.params.w_act_noact: weight for activation vs. lack of activation, 0-1 \n% if overall prob(activation) varies among classes, we can\n% get strange results (always classifying as the least activating\n% class) unless we downweight no-act. \n% nbc.params.w_prior_vs_like: weight for priors vs. likelihood; 0 is\n% standard NBC classifier, 1 divides likelihood by # voxels, so weights\n% priors and likelihood equally\n\n w = ones(n_vox, 1, 'single');\n w(test_data(:, ii)) = 2 * obj.params.w_act_noact; % scale so that param .5 gives standard sum log like (w all ones)\n w(~test_data(:, ii)) = 2 * (1 - obj.params.w_act_noact);\n \n % scale so that weighted sum gives something between standard log like\n % and normalization by number of voxels\n w = w ./ (1 + (obj.params.w_prior_vs_like * (n_vox - 1)));\n \n % post prob map: voxels x classes matrix of posterior probabilities\n % given either activation or lack thereof\n [p_c_map, p_no_c_map] = deal(zeros(size(obj.p_a_given_c), 'single'));\n\n p_c_map(test_data(:, ii), :) = obj.p_a_given_c(test_data(:, ii), :);\n p_c_map(~test_data(:, ii), :) = obj.p_noa_given_c(~test_data(:, ii), :);\n \n p_no_c_map(test_data(:, ii), :) = obj.p_a_given_no_c(test_data(:, ii), :);\n p_no_c_map(~test_data(:, ii), :) = obj.p_noa_given_no_c(~test_data(:, ii), :);\n\n %posterior_probs(ii, :) = sum(log(p_c_map./p_no_c_map)); % divide in log space for numerical stability\n pp = log(p_c_map) - log(p_no_c_map);\n posterior_probs(ii, :) = w' * pp; % weighted sum\nend\nfprintf('\\n');\n\n[discard, class_pred] = max(posterior_probs');\nclass_pred = class_pred';\n\n% Now, the thing is that posterior probs are not scaled nicely because of\n% the assumption of independence across voxels. I'm not sure how to correct\n% for this -- but we do want to do that if we want interpretable\n% probability numbers. This also might be useful for defining a\n% posterior probability-based error metric, which should be better than\n% the misclassification rate for model/parameter selection.\n\nn_vox = size(test_data, 1);\npp = exp(posterior_probs ./ n_vox);\npp = pp ./ repmat(sum(pp, 2), 1, size(pp, 2)); % sum to 1 across classes (this may mainly fix rounding error??)\nposterior_probs = pp; % this produces the same class prob estimates as before.\n% these all tend to be very close to the base rate, which may be a product\n% of the fact that the base rate goes into the post. prob calc at each\n% voxel. may not matter for picking most likely class?\n\nend\n\n\n\nfunction [class_pred, posterior_probs] = predict_continuous_images(test_data, obj)\n\n% now we have to make predictions about new images.\n% using z-scores based on p(class | activation) provides a natural\n% weighting. images that we're classifying might be z-scores from\n% individual subjects, or they might be something else.\n% so, rather than binarizing the test image (and thus ignoring information\n% about de-activations, and imposing an arbitrary threshold, etc.)\n% let's just take a weighted sum over the cross-products of probabilities\n% and normed test images\n% \n% using this norm: (sum(test_data .^ 2)) .^ .5 == 1\nfor ii = 1:size(test_data, 2)\n test_data(:, ii) = test_data(:, ii) ./ norm(test_data(:, ii));\nend\n\n% test images x classes matrix of class posterior_probs -\n% this is not scaled correctly, but should have relative rank info...\n% ideas about how to improve??\nposterior_probs = (obj.train_pprobs_act' * test_data)';\n\n[discard, class_pred] = max(posterior_probs');\nclass_pred = class_pred';\n\nend\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "study_table2.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/studyplotUtility/study_table2.m", "size": 2119, "source_encoding": "utf_8", "md5": "3e04f44fd0e7c109647ce98a7f7b48e7", "text": "function out = study_table(study,varargin)\n% function out = study_table(study,varargin)\n%\n% prints a table of studies; input the study variable, and input columns, in order\n% columns with ones and zeros are converted to X's or blanks.\n% (not implemented yet; everything must be cell arrays of strings now)\n%\n% study is assumed to be author name followed by 2-letter year code, e.g., 01 for 2001\n%\n\n% define vector of unique studies and initial stuff\n[ustudy,wh] = unique(study);\n[year,study] = getYear(study);\nstr = [repmat('%s\\t',1,length(varargin)+2) '\\n']; % would be more elegant\n\n% print header row\nfprintf(1,'Author\\tYear\\t');\nfor i = 1:length(varargin),\n names{i} = inputname(i+1);, fprintf(1,'%s\\t',names{i});, \n \n % get unique\n %varargin{i} = varargin{i}(wh);\n \n if ~iscell(varargin{i}),\n varargin{i} = mat2cell(varargin{i},ones(length(varargin{i})),1);, \n for j = 1:length(varargin{i}), varargin{i}{j} = num2str(varargin{i}{j});, end\n end \n \n varargin{i}(strcmp(varargin{i},'nan')) = {'N/A'};\n \n % change 1's and 0's to X's, put in cell array\n % skip the 1's thing for now. \n \nend\nfprintf(1,'\\n')\n\nout = cell(1);\n% print rows\nfor i = 1:length(study)\n out{i} = sprintf('%s\\t%s\\t',study{i},year{i});\n for j = 1:length(varargin)\n out{i} = [out{i} sprintf('%s\\t',varargin{j}{i})];\n end\n %out{i} = [out{i} sprintf('\\n')];\nend\n \nout = unique(out);\nfor i = 1:length(out), fprintf(1,'%s\\n',out{i});,end\n\nout = str2mat(out);\n \nreturn\n\n\nfunction [b,a] = getYear(ustudy)\n% b is year, a is study\nclear a, clear b\nfor i = 1:length(ustudy)\n a{i} = ustudy{i}(1:end-2);\n b{i} = ustudy{i}(end-2:end);\n \n if strcmp(b{i}(end-1:end),'00') | strcmp(b{i}(end-1:end),'01') | strcmp(b{i}(end-1:end),'02') | ...\n strcmp(b{i}(end-2:end-1),'00') | strcmp(b{i}(end-2:end-1),'01') | strcmp(b{i}(end-2:end-1),'02')\n c = '20';\n else\n c = '19';\n end\n \n if ~(strcmp(b{i}(end),'a') | strcmp(b{i}(end),'b') | strcmp(b{i}(end),'c'))\n b{i} = b{i}(end-1:end);\n end\n b{i} = [c b{i}];\nend\n\nreturn\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "contingency_table.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/studyplotUtility/contingency_table.m", "size": 2943, "source_encoding": "utf_8", "md5": "c2695b0f30a645c27fc0af6306ba9525", "text": "function [pt,st] = contingency_table(varargin)\n% function [pt,st] = contingency_table(varargin)\n% \n% makes 2-way contingency tables for pairs of variables\n% varargin arguments are variables\n% vars must be column cell array vectors containing strings\n%\n% pt: Table of point (coordinate) counts\n% st: Table of unique study counts\n%\n% rows represent levels of first varable, columns 2nd input variable\n%\n% Examples:\n% global study\n% study = DB.Study;\n% [pt, st] = contingency_table(DB.Method, DB.Stimuli);\n\nfor i = 1:length(varargin)\n\n % convert to string, then to cell array, if necessary\n if ~iscell(varargin{i})\n elseif ~ischar(varargin{i}{1})\n varargin{i} = num2str(cat(1,varargin{i}));\n end\n \n if ~iscell(varargin{i})\n varargin{i} = mat2cell(varargin{i},ones(size(varargin{i})),1);\n end\n \n % define categories (unique values) of a variable\n cats{i} = unique(varargin{i});\nend\n\n\nfor i = 1:length(cats)-1\n \n % make a new table for each input variable\n \n % define unique values (categories) for each pair of variables\n cat1 = cats{i};\n cat2 = cats{i+1};\n \n for j = 1:length(cat1)\n for k = 1:length(cat2)\n \n % pointcount, studylist, studycount\n [pc,sl,sc] = countemstudies(varargin{i},cat1{j},varargin{i+1},cat2{k});\n \n % pointtable, studytable\n pt{i}(j,k) = pc;\n st{i}(j,k) = sc;\n \n end\n end\nend\n\n% for SINGLE input only\nif length(cats) == 1\n cat1 = cats{1};\n for j = 1:length(cat1)\n % pointcount, studansylist, studycount\n [pc,sl,sc] = countemstudies(varargin{1},cat1{j});\n \n % pointtable, studytable\n pt{1}(j,1) = pc;\n st{1}(j,1) = sc;\n end\n \n % print table\n fprintf(1,'\\nCounting peaks\\n')\n fstr1 = repmat('%s',1,length(cats{1}));\n for j = 1:length(cats{1})\n fprintf(1,'%s\\t', cats{1}{j})\n fprintf(1,'%4.0f\\t',pt{1}(j,1))\n fprintf(1,'\\n')\n end\n \n fprintf(1,'\\nCounting studies\\n')\n fstr1 = repmat('%s',1,length(cats{1}));\n for j = 1:length(cats{1})\n fprintf(1,'%s\\t', cats{1}{j})\n fprintf(1,'%4.0f\\t',st{1}(j,1))\n fprintf(1,'\\n')\n end\n \nelse\n % for MULTIPLE inputs \n % print output tables\n\n print_table(pt,cats)\n print_table(st,cats)\n\nend\n\nreturn\n\n\n\n\n\nfunction print_table(pt,cats)\n\nfor i = 1:length(pt)\n \n fstr1 = repmat('%s',1,length(cats{i}));\n fstr2 = repmat('%s',1,length(cats{i+1}));\n \n % header row\n fprintf(1,'\\n\\t')\n for j = 1:length(cats{i+1})\n fprintf(1,'%s\\t',cats{i+1}{j})\n end\n fprintf(1,'\\n')\n \n % header col and lines of data\n for j = 1:length(cats{i})\n fprintf(1,'%s\\t', cats{i}{j})\n \n for k = 1:length(cats{i+1})\n fprintf(1,'%4.0f\\t',pt{i}(j,k))\n end\n \n fprintf(1,'\\n')\n end\nend \nreturn"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "study_table.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/studyplotUtility/study_table.m", "size": 2824, "source_encoding": "utf_8", "md5": "2e142d6579edd0402d7f1d7ad4c7fb64", "text": "function study_table(study,varargin)\n% function study_table(study,varargin)\n%\n% prints a table of studies; input the study variable, and input columns, in order\n% columns with ones and zeros are converted to X's or blanks.\n% (not implemented yet; everything must be cell arrays of strings now)\n%\n% study is assumed to be author name followed by 2-letter year code, e.g., 01 for 2001\n%\n\n% define vector of unique studies and initial stuff\n[ustudy,wh] = unique(study);\n[year,ustudy] = getYear(ustudy);\nstr = [repmat('%s\\t',1,length(varargin)+2) '\\n']; % would be more elegant\n\n% print header row\nfprintf(1,'Author\\tYear\\t');\nfor i = 1:length(varargin),\n names{i} = inputname(i+1);, fprintf(1,'%s\\t',names{i});, \n \n % get unique\n varargin{i} = varargin{i}(wh);\n \n if ~iscell(varargin{i}),\n varargin{i} = mat2cell(varargin{i},ones(length(varargin{i})),1);, \n for j = 1:length(varargin{i}), varargin{i}{j} = num2str(varargin{i}{j});, end\n end \n \n varargin{i}(strcmp(varargin{i},'nan')) = {'N/A'};\n \n % change 1's and 0's to X's, put in cell array\n % skip the 1's thing for now. \n \nend\nfprintf(1,'\\n')\n\n% print rows\nfor i = 1:length(ustudy)\n fprintf(1,'%s\\t%s\\t',ustudy{i},year{i})\n for j = 1:length(varargin)\n fprintf(1,'%s\\t',varargin{j}{i})\n end\n fprintf(1,'\\n')\nend\n \n \nreturn\n\n\nfunction [b,a] = getYear(ustudy)\n% b is year, a is study\nclear a, clear b\nfor i = 1:length(ustudy)\n a{i} = ustudy{i}(1:end-2);\n b{i} = ustudy{i}(end-2:end);\n \n if strcmp(b{i}(end-1:end),'00') | strcmp(b{i}(end-1:end),'01') | strcmp(b{i}(end-1:end),'02') | ...\n strcmp(b{i}(end-2:end-1),'00') | strcmp(b{i}(end-2:end-1),'01') | strcmp(b{i}(end-2:end-1),'02')\n c = '20';\n else\n c = '19';\n end\n \n if ~(strcmp(b{i}(end),'a') | strcmp(b{i}(end),'b') | strcmp(b{i}(end),'c'))\n b{i} = b{i}(end-1:end);\n end\n b{i} = [c b{i}];\nend\n\nreturn\n\n\n\n % gender and stuff\n gen = unique(gender(strcmp(study,ustudy{i})));\n if any(strcmp(gen,'f')), c7 = 'X';, else c7 = ' ';,end\n if any(strcmp(gen,'m')), c8 = 'X';, else c8 = ' ';,end\n if any(strcmp(gen,'b')), c9 = 'X';, else c9 = ' ';,end\n \n val = unique(valence(strcmp(study,ustudy{i})));\n if any(strcmp(val,'pos')), c1 = 'X';, else c1 = ' ';,end\n if any(strcmp(val,'neg')), c2 = 'X';, else c2 = ' ';,end\n if any(strcmp(val,'mix')), c3 = 'X';, else c3 = ' ';,end\n \n app = unique(aav(strcmp(study,ustudy{i})));\n if any(strcmp(app,'approach')), c4 = 'X';, else c4 = ' ';,end\n if any(strcmp(app,'avoid')), c5 = 'X';, else c5 = ' ';,end\n if any(strcmp(app,'mix')), c6 = 'X';, else c6 = ' ';,end\n \n fprintf(1,'%s\\t%s%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t\\n',a{i},c,b{i}, ...\n c1,c2,c3,c4,c5,c6,c7,c8,c9)\nend\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "pt_given_a_plot.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/plotting_functions/pt_given_a_plot.m", "size": 2685, "source_encoding": "utf_8", "md5": "f7e981d383f9b11a34aa43069eb49e74", "text": "function [ind,colors] = pt_given_a_plot(eff,p,legstr,varnamecode,regionnames)\n% [indices, colors] = pt_given_a_plot(studycount,totalstudycount,code,varnamecode,regionnames)\n%\n% tmp =\n% pt_given_a_plot(clnew.COUNTS.effpt_given_a,clnew.COUNTS.Ppt_given_a,levels,'PTplot_',clnew.COUNTS(1).clusternames);\n%\n% given counts, does barplot and CHI2 analysis\n% easy to use with output from dbcluster_contrast_table.m\n%\n% perc : counts or percent studies to plot; row is region, column is\n% condition\n% code : cell string of legend for conditions\n\ncolors = {'bo' 'gs' 'r^' 'yv' 'cs' 'mo'};\n\nyoffset = 20; % start plot at this + 50\nxoffset = -.4; % start x at 0 - this\n\nformat compact\n\n\nif iscell(eff)\n eff = cat(1,eff{:});\nend\n\nif iscell(p)\n p = cat(1,p{:});\nend\n\np = p < .05;\n\nyvals = 50;\nfor i = 2:size(eff,2)\n yvals = [yvals yvals(end) + 5];\nend\nyvals = yvals + yoffset;\n\n% get start coordinates x and y for each box\n[x,y] = find(p);\neff = eff(find(p));\nind = x;\n\nx = x + xoffset;\ncols = colors(y);\ny = yvals(y);\n\nif isempty(y),\n % no results\n y = 70;\nend\n\nset(gca,'YLim',[0 max(y)+10])\nfill([0 size(p,1) size(p,1) 0],[min(y)-5 min(y)-5 max(y)+10 max(y)+10],[.7 .7 .7],'FaceAlpha',.5)\ntitle('Increase in likelihood of task given activation')\n\nfor i = 1:length(eff)\n \n % x start, y start, color, text string\n h(i) = drawbox(x(i),y(i),cols{i}(1),sprintf('%3.2f',eff(i)),sign(eff(i)));\n\nend\n\n\n\n\n\nreturn\n\n\n\nfunction h1 = drawbox(xoffset,yoffset,color,txt,posneg);\ndur = .8; % how long box is in x\nheight = 4; % how high box is in y\n\nx = [0 1 1 0]; x = x * dur + xoffset;\ny = [0 0 1 1]; y = y * height + yoffset;\n\nif posneg > 0\n h1 = fill(x,y,color,'FaceAlpha',.5);\nelse\n h1 = fill(x,y,[1 1 1]);\n set(h1,'EdgeColor',color,'LineWidth',2);\nend\n\ntext(xoffset+.1*dur,yoffset+.5*height,txt,'FontSize',16,'FontWeight','b');\n\nreturn\n\n\n\n\n\nmytitle = [];\nmyylabel = ['Percentage of studies'];\nmylegend = legstr; %{'Spatial','Object','Verbal'};\n\nfor i = 1:length(mylegend), mylegend{i}(mylegend{i} == '_') = ' ';,end\n\ndisp('--- --- --- --- --- --- --- --- ---')\n\n% make color map for bar graphs\n% ======================================================\nfigure;\nfor i = 1:length(colors)\n h = plot(0,0,colors{i});\n cmap(i,:) = get(h,'Color');\nend\ncmap = cmap(1:length(code),:);\nclose\n\n\nfig2 = figure('Position',[122.0000 610.0000 921.0000 369.0000]);\nset(gca,'FontSize',18)\nmyplot2 = subplot(1,1,1);\nplotbarcounts(perc,1,regionnames,'title',mytitle,'ylabel',myylabel,'legend',mylegend,'plothandle',myplot2,'overallcounts',totalstudycount,'arealabels',0);\nxlabel('')\n%ylabel('% of total studies','FontSize',16)\ncolormap(cmap)\ndrawnow\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "meta_add_spheres_in_rois.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/plotting_functions/meta_add_spheres_in_rois.m", "size": 3073, "source_encoding": "utf_8", "md5": "2654f006860a1ab832a4693132f8184a", "text": "function meta_add_spheres_in_rois(DB, varargin)\n% Add spheres to selected ROIs\n%\n% [p, mesh_struct] = brainstem_slices_3d;\n% meta_add_spheres_in_rois(PLOTINFO{1}, 'brainstem');\n% colormap gray\n%\n% DB must be a DB or PLOTINFO struct with these fields:\n% - colors\n% - xyz\n% - condf\n%\n% (for table)\n% - nums\n% - descrip\n% - study\n%\n% (to save in diary)\n% - diaryname\n\nclear cl\n\ncolors = DB.colors;\n\nindx = 0;\n\nfor i = 1:length(varargin)\n switch varargin{i}\n \n case 'brainstem'\n indx = indx + 1;\n cl{indx} = mask2clusters(which('spm8_brainstem.img'));\n cl{indx} = database2clusters(DB, cl{indx}, 5);\n cl{indx}(1).title = varargin{i};\n \n case 'amygdala'\n indx = indx + 1;\n cl{indx} = mask2clusters(which('spm2_amy.img'));\n cl{indx} = database2clusters(DB, cl{indx}, 5);\n cl{indx}(1).title = varargin{i};\n \n case 'hippocampus'\n indx = indx + 1;\n cl{indx} = mask2clusters(which('spm2_hipp.img'));\n cl{indx} = database2clusters(DB, cl{indx}, 5);\n cl{indx}(1).title = varargin{i};\n \n otherwise\n % not entered yet\n end\nend\n\n% Compile XYZ list\n% -----------------------------------------------------------------\n\n% Print diary if required field entered\nif isfield(DB, 'diaryname') && ~isempty(DB.diaryname)\n diary(DB.diaryname)\nend\n\n \nclear xyzcut condfcut\nfor i = 1:length(cl)\n\n fprintf('\\n---------------------------------\\n%s\\n---------------------------------\\n', cl{i}(1).title);\n \n print_table(cl{i}, DB);\n \n fprintf('\\n');\n \n for j = 1:length(cl{i})\n %whin = cat(1, cl{i}.wh_points);\n whin = cl{i}(j).wh_points;\n \n xyzcut{i}{j} = cl{i}(j).xyz(whin, :);\n condfcut{i}{j} = cl{i}(j).condf(whin);\n \n end\n \n xyzcut{i} = cat(1, xyzcut{i}{:});\n condfcut{i} = cat(1, condfcut{i}{:});\n \nend\n\nxyzcutaway = cat(1, xyzcut{:});\ncondfcutaway = cat(1, condfcut{:});\n\nif isfield(DB, 'diaryname') && ~isempty(DB.diaryname)\n diary off\nend\n\n% Plot\n% -----------------------------------------------------------------\n\nu = unique(condfcutaway);\nu(u == 0) = []; % remove out-of-scope points\n\nfor clas = 1:length(u)\n pthan{clas} = cluster_image_sphere(xyzcutaway(condfcutaway==u(clas), 1:3), 'color', colors{u(clas)}, 'radius', 3);\nend\n\nfor i = 1:length(pthan)\n set(pthan{i}, 'SpecularColorReflectance', .7)\nend\n\nlighting gouraud % re-set for points\n\n\nend % function\n\n\n\n% Table\nfunction print_table(cl, PLOTINFO)\nfor i = 1:length(cl)\n \n mynums = cl(i).nums(cl(i).wh_points);\n mydescrip = cl(i).descrip(cl(i).wh_points);\n mystudy = cl(i).study(cl(i).wh_points);\n \n mycolors = PLOTINFO.colors(cl(i).condf(cl(i).wh_points));\n \n for j = 1:length(mynums)\n if ~ischar(mycolors{j}), mycolors{j} = num2str(mycolors{j}); end\n \n fprintf('%3.0f\\t%s\\t%s\\t%s\\n', mynums(j), mycolors{j}, mystudy{j}, mydescrip{j});\n end\n \nend\nend % function"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "dbcluster_contrast_table_xyz.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/cluster_multivariate/dbcluster_contrast_table_xyz.m", "size": 6393, "source_encoding": "utf_8", "md5": "f9323ee68547219c8d89c0e626d9a12d", "text": "function OUT = db_cluster_table(clusters,DB,varargin)\n% function OUT = db_cluster_table(clusters,DB,varargin)\n%\n% tor wager\n% counts studies and contrasts in each cluster\n%\n% clusters is a struct in which XYZmm field has list of points\n% --should be output of database2clusters, which contains all fields\n% DB is database output of database2clusters\n%\n% Prints one row per coordinate in any cluster, along with study names,\n% cluster ID, and values in fields you specify in fnames\n%\n% optional arguments:\n% fnames is a cell array that has names of all fields in clusters to use\n% first cell is which factor, following cells are levels to include\n% enter one argument per factor:\n%\n% example:\n% OUT = dbcluster_contrast_table(PAIN,PAINDB,{'Right_vs_Left' 'Right' 'Left'})\n% perc_barplot(OUT.cond_by_cl_counts,OUT.conditioncounts,OUT.levels{1},'test',OUT.clusternames)\n%\n% see also db_cluster_table.m \n\n% do taskindicators\ndotaskindic = 0;\n\n\n% enter input arguments\n\nfor i = 1:length(varargin), \n fnames{i} = varargin{i}{1};\n if length(varargin{i}) > 1\n levels{i} = varargin{i}(2:end);\n else\n eval(['levels{i} = unique(DB. ' varargin{i}{1} ');'])\n end\nend\n\n\n% get indicator for all levels\n\n[fmatx,rmatx,ustudyout,taskindic,tasknms,allsuni] = dbcluster2indic(clusters,DB,fnames);\n\nfprintf(1,'%3.0f Unique contrasts\\n',length(ustudyout))\n\n% select only levels of interest\nnewti = []; newnames = {};\n\nfor i = 1:length(fnames)\n for j = 1:length(levels{i})\n wh = find(strcmp(tasknms,levels{i}{j}));\n \n newti = [newti taskindic(:,wh)];\n newnames = [newnames tasknms(wh)];\n end\nend\n \n\n% select only contrasts that show within_cluster activation\n% this differentiates this function from the other dbcluster_contrast_table\nwh = find(sum(rmatx,2) > 0);\nustudyout = ustudyout(wh);\nnewti = newti(wh,:);\nrmatx = rmatx(wh,:);\n\n\n% Display header\n\nfprintf(1,'Study\\t')\nif dotaskindic\nfor i = 1:length(newnames)\n fprintf(1,'%s\\t',newnames{i})\nend\nend\n\n for i = 1:size(fnames,2)\n fprintf(1,['%s\\t'],fnames{i})\n end\n \n for i = 1:size(rmatx,2)\n if ~isfield(clusters,'shorttitle')\n fprintf(1,['Clust%3.0f\\t'],num2str(i))\n else\n fprintf(1,['%s\\t'],clusters(i).shorttitle)\n end\n end\n \nfprintf(1,'\\n')\n\n\n% Display table body\n[yr,ustudyout] = getYear(ustudyout);\n\nfor i = 1:length(ustudyout)\n \n \n % print study name, task values, and number of peaks in each cluster\n fprintf(1,'%s\\t',[ustudyout{i} ' ' yr{i}]);\n \n if dotaskindic\n for j = 1:size(newti,2)\n fprintf(1,['%3.0f\\t'],newti(i,j))\n end\n end\n\n for j = 1:size(fmatx,2)\n fprintf(1,['%s\\t'],fmatx{i,j})\n end\n \n for j = 1:size(rmatx,2)\n fprintf(1,['%3.0f\\t'],rmatx(i,j))\n end\n \n fprintf(1,'\\n')\n \nend\n\n% Summary and percentages for columns\n\ntotals = sum(newti > 0);\nclustertotals = sum(rmatx > 0);\n\nif ~dotaskindic % repeat headers to avoid confusion\n fprintf(1,'\\n\\t\\t') % task indicator totals\n for i = 1:length(newnames)\n fprintf(1,'%s\\t',newnames{i})\n end\n fprintf(1,'\\n\\t') % cluster count totals\n fprintf(1,['Total\\t' repmat('%3.0f\\t',1,size(totals,2))],totals);\n fprintf(1,'\\n\\t\\t')\n for i = 1:size(rmatx,2)\n if ~isfield(clusters,'shorttitle')\n fprintf(1,['Clust%3.0f\\t'],num2str(i))\n else\n fprintf(1,['%s\\t'],clusters(i).shorttitle)\n end\n end\n fprintf(1,'\\n\\t\\t') \n fprintf(1,[repmat('%3.0f\\t',1,size(clustertotals,2))],clustertotals);\nelse \n\n fprintf(1,'\\n')\n fprintf(1,['Total\\t' repmat('%3.0f\\t',1,size(totals,2))],totals);\n for i = 1:size(fnames,2), fprintf(1,'\\t'),end\n\n fprintf(1,[repmat('%3.0f\\t',1,size(clustertotals,2))],clustertotals);\nend\n\n\nperc = 100* sum(newti > 0) ./ length(ustudyout);\nclusterperc = 100 * sum(rmatx > 0) ./ length(ustudyout);\n\nfprintf(1,'\\n')\nfprintf(1,['Percentage\\t' repmat('%3.0f\\t',1,size(perc,2))],perc);\nfor i = 1:size(fnames,2), fprintf(1,'\\t'),end\n\nif ~dotaskindic % line break if no task indicator\n fprintf(1,'\\n')\nend\n\nfprintf(1,[repmat('%3.2f\\t',1,size(clusterperc,2))],clusterperc);\n\nfprintf(1,'\\n')\nfprintf(1,'\\n')\n\n% Summary and percentages by condition\n\n\nfor j = 1:size(newti,2)\n \n for k = 1:size(rmatx,2)\n \n clcondtotal(j,k) = sum(rmatx(:,k) > 0 & newti(:,j));\n clcondperc(j,k) = 100 * clcondtotal(j,k) / totals(j); % % of studies in condition\n \n end\n \nend\n\nfprintf(1,'Totals by condition and cluster\\n')\n\n% header\n\nfprintf(1,'\\t')\n for i = 1:size(rmatx,2)\n if ~isfield(clusters,'shorttitle')\n fprintf(1,['Clust%3.0f\\t'],num2str(i))\n else\n fprintf(1,['%s\\t'],clusters(i).shorttitle)\n end\n end\n fprintf(1,'\\n')\n \nfor j = 1:size(newti,2)\n \n fprintf(1,'%s\\t',newnames{j})\n \n str = [repmat('%3.0f\\t',1,size(clcondtotal,2))];\n fprintf(1,str,clcondtotal(j,:))\n fprintf(1,'\\n')\n \nend\n\n\nfprintf(1,'Percentages by condition and cluster\\n')\nfor j = 1:size(newti,2)\n \n fprintf(1,'%s\\t',newnames{j})\n \n str = [repmat('%3.0f\\t',1,size(clcondperc,2))];\n fprintf(1,str,clcondperc(j,:))\n fprintf(1,'\\n')\n \nend\n\nOUT.cond_by_cl_counts = clcondtotal;\nOUT.clustercounts = clustertotals;\nOUT.conditioncounts = totals;\nOUT.ustudyout = ustudyout;\nOUT.fmatx = fmatx;\nOUT.rmatx = rmatx;\nOUT.factornames = fnames;\nOUT.levels = levels;\n\nfor i = 1:length(clusters),\n if isfield(clusters,'shorttitle')\n OUT.clusternames{i} = clusters(i).shorttitle;,\n else\n OUT.clusternames{i} = ['CL' num2str(i)];\n end\nend\n\n%perc_barplot(OUT.cond_by_cl_counts,OUT.conditioncounts,OUT.levels{1},'test',OUT.clusternames)\n \nreturn\n \n \n \n\nfunction [b,a] = getYear(ustudy)\n% b is year, a is study\nclear a, clear b\nfor i = 1:length(ustudy)\n a{i} = ustudy{i}(1:end-2);\n b{i} = ustudy{i}(end-2:end);\n \n if strcmp(b{i}(end-1:end),'00') | strcmp(b{i}(end-1:end),'01') | strcmp(b{i}(end-1:end),'02') | ...\n strcmp(b{i}(end-2:end-1),'00') | strcmp(b{i}(end-2:end-1),'01') | strcmp(b{i}(end-2:end-1),'02')\n c = '20';\n else\n c = '19';\n end\n \n if ~(strcmp(b{i}(end),'a') | strcmp(b{i}(end),'b') | strcmp(b{i}(end),'c'))\n b{i} = b{i}(end-1:end);\n end\n b{i} = [c b{i}];\nend\n\n\n\nreturn\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "maxcor_npm.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/cluster_multivariate/maxcor_npm.m", "size": 2364, "source_encoding": "utf_8", "md5": "2d44088afe3abc999ab01b0bd254a7a8", "text": "function [mc,stats] = maxcor_npm(X,perms,varargin);\n% [mc,stats] = maxcor_npm(X,perms,[c],[MCD robust outlier removal])\n%\n% X data matrix, columns are variables, rows observations\n% c contrast matrix for rotation of X prior to correlation\n% contrasts should be rows\n\n\n\n% ----------------------------------------------------------\n% outliers\n% ----------------------------------------------------------\n\nif length(varargin) > 1\n [res]=fastmcd_noplot(X);\n \n % remove n most extreme outliers and recompute correlation\n wh = res.flag==0; nout = sum(res.flag==0);\n \n %res = fastmcd(X);\n %stats.rdthresh = input('Enter robust distance threshold for outliers:');\n %wh = res.robdist > stats.rdthresh;\n %nout = sum(wh);\n \n X(wh,:) = [];\n stats.nout = nout;\n fprintf(1,'Removing %3.0f outliers\\n',stats.nout)\nend\n\n% ----------------------------------------------------------\n% max cor\n% ----------------------------------------------------------\nif length(varargin) > 0, c = varargin{1};,else, c=eye(size(X,2));,end\nmc = maxcor(X,c);\nstats.n = size(X,1);\nstats.cor = corrcoef(X*c');\n\nfor i = 1:perms, % permute columns and test H0: no relation\n \n xtst=X;\n for j = 1:size(X,2)\n xtst(:,j) = getRandom(X(:,j));\n end\n [cctst(i,:),ccall(i,:)] = maxcor(xtst,c);\n\nend\n\nstats.mc = mc;\n\nif perms\n stats.cctst = cctst;\n stats.perms = perms;\n stats.thresh = prctile(cctst(:,1),95);\n stats.thresh(2) = prctile(cctst(:,2),5);\n stats.bias = squareform(mean(ccall));\n stats.allupper = prctile(ccall,95);\n stats.alllower = prctile(ccall,5);\n \n \n % table and sig\n l = squareform(stats.alllower);\n u = squareform(stats.allupper);\n stats.sig = ~(stats.cor==1) & (stats.cor > u | stats.cor < l);\n stats.adjcor = stats.cor - stats.bias;\n \n str = sprintf(['Adjusted correlations\\n']);\n for i = 1:size(stats.cor,1),\n for j=1:size(stats.cor,2) %i,\n if stats.sig(i,j),t='*';,\n else,t='';,\n end,\n str=[str sprintf('%3.2f%s\\t',stats.adjcor(i,j),t)];,\n end,\n str=[str sprintf('\\n')];,\n end\n\n disp(str) \nend\n\nreturn\n\n\n\n\n\n\nfunction [mc,c] = maxcor(X,c)\n\nX = X * c';\nc = tril(corrcoef(X)); c(c==0 | c==1) = [];\nmc = [max(c) min(c)];\n\nreturn\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "permute_mtx.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/cluster_multivariate/permute_mtx.m", "size": 12244, "source_encoding": "utf_8", "md5": "52252cf12cf037300ef2220cbcac2d57", "text": "function [OUT] = permute_mtx(data,varargin)\n % [OUT] = permute_mtx(data,[meth],[verbose],[niter],[separator])\n %\n % tor wager\n %\n % PERMUTATION TEST FOR STOCHASTIC ASSOCIATION BETWEEN COLUMNS\n % OF DATA (Ho)\n %\n % This function takes as input two matrices,\n % an actual matrix of data\n % and an expected / null hypothesis\n % covariance or correlation matrix.\n %\n % the algorithm provides significance levels for\n % the cov / correlation of the columns of data,\n % based on the expected correlation e\n %\n % it computes a test statistic, which is the\n % average squared deviation from the expected\n % values, element by element, over the matrix.\n % This statistic provides an \"omnibus\" test\n % of whether there are deviations from the\n % expected values in the matrix.\n %\n % for each element, a statistic is also computed -\n % the squared deviation from the expected -\n % which provides a test of significance for each\n % element.\n %\n % a permutation test is used to create an Ho\n % distribution. Columns of the matrix are\n % randomly permuted (independently), and the test\n % statistics assessed over iterations.\n %\n % R2 is average squared off-diagonal value in\n % lower triangular matrix\n %\n % called in db_cluster_burt_table.m\n %\n % example:\n % data = bmatx1(:,1:5); ss = data'*data; e = diag(diag(ss));\n % OUT = permute_mtx(bmatx1(:,1:5),e,'ss',1,1000);\n %\n % data = bmatx1(:,length(fnames)+1:end); ss = data'*data; e = diag(diag(ss));\n % OUT = permute_mtx(data,'ss',1,1000);\n %\n % If we scale rows of data so that they sum to 0, we can remove\n % the effects of some rows having higher values overall than others\n % Since columns are permuted, there's no problem with those in the stats,\n % but we may want to scale to make visualization more interpretable (less\n % misleading)\n %\n % for Multiple Correspondence Analysis (MCA)\n % enter a Separator value as the last argument\n % - this is an integer that tells it how to partition the matrix\n % - indicates number of columns in primary partition\n % - works only for two variables, with 2 sets of indicator columns\n % - tests omnibus, 1st part, 2nd part, and covariance between 1 and 2\n %\n % Example:\n % bmatx1 is a dataset with 2 sets of indicator variables\n %\n % data = bmatx1; ss = data'*data; e = diag(diag(ss));\n % OUT = permute_mtx(data,'ss',1,1000,length(fnames));\n\n if length(varargin) > 0, meth = varargin{1};, else, meth = 'corr';, end\n if length(varargin) > 1, verbose = varargin{2};, else, verbose = 1;, end\n if length(varargin) > 2, niter = varargin{3};, else, niter = 5000;, end\n\n switch meth\n case 'cov', m = cov(data);\n case 'ss', m = data'*data;\n case 'corr', m = corrcoef(data);\n otherwise, error('Unknown method! OK methods are cov, ss, and corr')\n end\n\n if length(varargin) > 3\n% ----------------------------------------------------------------------- \n % Data is partitioned into two sets; run on each set\n% -----------------------------------------------------------------------\n sep = varargin{4};\n\n disp(' ');disp('RESULTS FOR FIRST PARTITION')\n OUT.part1 = do_permute(m(1:sep,1:sep),data(:,1:sep),meth,verbose,niter);\n disp(' ');disp('RESULTS FOR SECOND PARTITION')\n OUT.part2 = do_permute(m(sep+1:end,sep+1:end),data(:,sep+1:end),meth,verbose,niter);\n disp(' ');disp('RESULTS FOR CROSS-CORRESPONDENCE')\n OUT.part12 = do_permute(m,data,meth,verbose,niter,sep);\n\n OUT.sep = sep;\n OUT.sep_descrip = 'Last column in first data partition.';\n OUT.p = combine_parts(OUT,'p2');\n OUT.p_descrip = 'p-vals for correspondence between each pair in superindicator';\n\n OUT.sign_matrix = sign(combine_parts(OUT,'actual_vs_expected'));\n OUT.sig05 = OUT.p < .05 .* OUT.sign_matrix;\n [OUT.fdr_pthr,OUT.sigfdr] = fdr_correct_pvals(OUT.p,OUT.sign_matrix);\n\n else\n% ----------------------------------------------------------------------- \n % No data partition\n% -----------------------------------------------------------------------\n % for regular MCA, do it with the whole matrix\n OUT = do_permute(m,data,meth,verbose,niter);\n\n end\n\n\n return\n\n\n\n\n\nfunction OUT = do_permute(m,data,meth,verbose,niter,varargin)\n % if varargin is entered, this function takes the cross-product part of MCA\n % where the first set of vars is defined by the integer n in varargin{1}\n %\n % permutes only the SECOND set of columns, after sep, to preserve the\n % row structure of the first set, assumed to represent tasks.\n % the second set, after sep, is assumed to represent brain regions\n\n if verbose,\n fprintf(1,'\\nPermute_mtx.m\\n--------------------------\\n')\n fprintf(1,'Test that columns of data have no systematic relationship\\n')\n fprintf(1,'\\nActual %s matrix for data',meth),m,\n end\n\n\n % mask: which elements of cov matrix to use\n %\n % for MCA: take cov ones\n if length(varargin) > 0\n % ----------------------------------------------------------------------- \n % Data is partitioned into two sets; Entering sep means we're\n % asking for the correlations/covs between sets only\n % -----------------------------------------------------------------------\n sep = varargin{1}; % separator\n mm = ones(size(m)); % full mtx size\n rows = 1:sep;\n nrows = sep;\n cols = sep+1:size(m,1);\n ncols = length(cols);\n mm(rows,cols) = 0; maskind = find(mm==0);\n disp('Mask matrix: Elements with zeros are used in computation of stats'),mm\n else\n % ----------------------------------------------------------------------- \n % Setup for both separate partitions A and B, and single matrix\n % -----------------------------------------------------------------------\n %regular correspondence\n % get index of lower triangular matrix\n % to compute stats only on these values.\n rows = 1:size(m,1);\n cols = rows;\n disp('Using lower triangular matrix for stats computation')\n mask = triu(Inf*eye(size(m,2))); maskind = find(mask==0);\n end\n\n % ----------------------------------------------------------------------- \n % s1 and s2 are statistics for the correct permutation\n % -----------------------------------------------------------------------\n [s1,s2] = getstats(m,maskind);\n\n % ----------------------------------------------------------------------- \n % Iterate and get null hypothesis stats\n % -----------------------------------------------------------------------\n for i = 1:niter\n\n if mod(i,1000) == 1, fprintf(1,'.');, end\n\n if length(varargin) > 0\n [mi] = getcov(data,meth,sep); % get Ho realization permuting columns AFTER sep index\n else\n [mi] = getcov(data,meth); % get Ho realization\n end\n [s1n(i),s2n(i,:)] = getstats(mi,maskind); % Ho R-square values\n meanmi(:,:,i) = mi;\n\n end\n fprintf(1,'\\n')\n meanmi = mean(meanmi,3);\n\n % ----------------------------------------------------------------------- \n % Get p-values\n % -----------------------------------------------------------------------\n p = 2 * min(sum(s1 >= s1n) ./ niter,sum(s1 <= s1n) ./ niter);\n for i = 1:length(s2), p2(i) = sum(s2(i) < s2n(:,i))./ niter;, end\n p2c = p2 .* length(p2);\n\n % ----------------------------------------------------------------------- \n % Print output\n % -----------------------------------------------------------------------\n if verbose\n fprintf(1,'\\nExpected (Mean Ho) %s matrix\\n',meth),meanmi\n fprintf(1,'\\nOmnibus test for differences from expected on %s\\n',meth)\n fprintf(1,'Obs. R2 %3.3f, Expected (Ho) R2 = %3.3f, p = %3.4f\\n',s1,mean(s1n),p)\n %fprintf(1,'\\nSignificant individual tests for differences from expected on %s\\n',meth)\n sig = find(p2 <= .05);\n %for i = 1:length(sig)\n %[row,col] = ind2sub(size(m),maskind(sig(i)));\n %fprintf(1,'[%3.0f,%3.0f], R2 = %3.3f, Ho R2 = %3.3f, p = %3.4f, bonf_p = %3.4f\\n',row,col,s2(sig(i)),nanmean(s2n(:,sig(i))),p2(sig(i)),p2c(sig(i)))\n %figure; hist(s2n(:,sig(i)))\n %end\n if isempty(sig), disp('No significant results.'), end\n end\n\n % ----------------------------------------------------------------------- \n % Save output vars in structure\n % -----------------------------------------------------------------------\n OUT.actual_vs_expected = m(rows,cols) - meanmi(rows,cols);\n if strcmp('meth','ss')\n signvals = sign(OUT.actual_vs_expected);\n else\n signvals = sign(m(rows,cols));\n end\n\n OUT.m = m; OUT.s1 = s1; OUT.s2 = s2;\n OUT.p = p; OUT.p2 = p2; OUT.p2c = p2c;OUT.meanmi = meanmi;\n OUT.sig = sig; OUT.niter = niter; OUT.meth = meth; OUT.s1n = s1n; OUT.s2n = s2n;\n\n % add fnames, and fnames for 2nd set!\n\n % ----------------------------------------------------------------------- \n % Get indicator matrices for corrected/uncorrected significance\n % -----------------------------------------------------------------------\n % matrices of significant results\n if exist('sep','var')\n\n OUT.sig05 = reshape(OUT.p2 <= .05,nrows,ncols) .* signvals;\n\n OUT.bonf_pthr = .05 ./ length(OUT.p2);\n OUT.sigbonf = reshape(OUT.p2 <= OUT.bonf_pthr,nrows,ncols) .* signvals;\n\n [OUT.fdr_pthr,OUT.sigfdr] = fdr_correct_pvals(OUT.p2,signvals(:)');\n OUT.sigfdr = reshape(OUT.sigfdr,nrows,ncols) .* signvals;\n\n else\n OUT.sig05 = (squareform(OUT.p2) <= .05);\n OUT.sig05 = double(OUT.sig05 - eye(size(OUT.sig05)) .* signvals);\n\n OUT.sigbonf = (squareform(OUT.p2) <= (.05 ./ length(OUT.p2)));\n OUT.sigbonf = double(OUT.sigbonf - eye(size(OUT.sigbonf)) .* signvals);\n end\n\n return\n\n\n\n\n\nfunction [m] = getcov(data,meth,varargin)\n\n % this would be a bootstrap\n % resample data - tested to evenly sample rows\n %len = size(data,1);\n %wh = ceil(rand(len,1) .* len);\n %d2 = data(wh,:);\n\n startat = 1;\n if length(varargin) > 0\n startat = varargin{1}+1;\n d2(:,1:varargin{1}) = data(:,1:varargin{1});\n end\n\n % permute columns\n for i = startat:size(data,2)\n d2(:,i) = getRandom(data(:,i));\n end\n\n switch meth\n case 'cov', m = cov(d2);\n case 'ss', m = d2'*d2;\n case 'corr', m = corrcoef(d2);\n otherwise, error('Unknown method! OK methods are cov, ss, and corr')\n end\n\n return\n\n\n\nfunction [s1,s2] = getstats(m,maskind)\n % input is cov matrix of whatever form - corr, ss, cov\n\n % this is for MCA, with separator integer indicating last col. in 1st set\n %if length(varargin) > 0,\n % sep = varargin{1};,\n % m2 = m(1:sep,sep+1:end);\n % s2 = (m2 .^ 2)';\n % s1 = nanmean(ssep2);\n %else\n\n m = m(maskind); m = m(:);\n\n s2 = (m .^ 2)';\n s1 = nanmean(s2);\n %end\n\n return\n\n\nfunction [s1,s2] = getvec(m,maskind)\n % input is cov matrix of whatever form - corr, ss, cov\n\n m = m(maskind); m = m(:);\n\n s2 = m';\n s1 = nanmean(s2);\n\n return\n\n\n\nfunction [pthr,sig] = fdr_correct_pvals(p,r)\n\n % if p is a square correlation matrix, vectorize\n if diff(size(p)) == 0\n psq = p; psq(find(eye(size(p,1)))) = 0;\n psq = squareform(psq);\n end\n pthr = FDR(p,.05);\n if isempty(pthr), pthr = 0; end\n\n sig = sign(r) .* (p < pthr);\n\n return\n\n\n\nfunction outmtx = combine_parts(OUT,myfield)\n nrows = length(1:OUT.sep);\n ncols = size(OUT.part2.m,2);\n\n a = OUT.part1.(myfield);\n if any(size(a) - nrows)\n a = squareform(a);\n end\n\n b = OUT.part2.(myfield);\n if any(size(b) - ncols)\n b = squareform(b);\n end\n\n c = OUT.part12.(myfield);\n if any(size(c) - [nrows ncols])\n c = reshape(c,nrows,ncols);\n end\n outmtx = [a c; c' b];\n\n return\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "dbcluster_contrast_table.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/cluster_multivariate/dbcluster_contrast_table.m", "size": 8463, "source_encoding": "utf_8", "md5": "e961e1c10ed0d30b2738bbee69b78166", "text": "function OUT = db_cluster_table(clusters,DB,varargin)\n% function OUT = db_cluster_table(clusters,DB,varargin)\n%\n% tor wager\n% counts studies and contrasts in each cluster\n%\n% clusters is a struct in which XYZmm field has list of points\n% --should be output of database2clusters, which contains all fields\n% DB is database output of database2clusters\n%\n% Prints one row per coordinate in any cluster, along with study names,\n% cluster ID, and values in fields you specify in fnames\n%\n% optional arguments:\n% fnames is a cell array that has names of all fields in clusters to use\n% first cell is which factor, following cells are levels to include\n% enter one argument per factor:\n%\n% example:\n% OUT = dbcluster_contrast_table(PAIN,PAINDB,{'Right_vs_Left' 'Right' 'Left'})\n% perc_barplot(OUT.cond_by_cl_counts,OUT.conditioncounts,OUT.levels{1},'test',OUT.clusternames)\n%\n% see also db_cluster_table.m \n\n% do taskindicators\ndotaskindic = 0;\n\n\n% enter input arguments\n\nfor i = 1:length(varargin), \n fnames{i} = varargin{i}{1};\n if length(varargin{i}) > 1\n levels{i} = varargin{i}(2:end);\n else\n eval(['levels{i} = unique(DB. ' varargin{i}{1} ');'])\n end\nend\n\n\n% get indicator for all levels\n% Sample Size weighting ON\n[fmatx,rmatx,ustudyout,taskindic,tasknms,allsuni] = dbcluster2indic(clusters,DB,fnames,1);\n\nfprintf(1,'%3.0f Unique contrasts\\n',length(ustudyout))\n\n% select only levels of interest\nnewti = []; newnames = {};\n\nfor i = 1:length(fnames)\n for j = 1:length(levels{i})\n wh = find(strcmp(tasknms,levels{i}{j}));\n \n newti = [newti taskindic(:,wh)];\n newnames = [newnames tasknms(wh)];\n end\nend\n \n\n% Display header\n\nfprintf(1,'Study\\t')\nif dotaskindic\nfor i = 1:length(newnames)\n fprintf(1,'%s\\t',newnames{i})\nend\nend\n\n for i = 1:size(fnames,2)\n fprintf(1,['%s\\t'],fnames{i})\n end\n \n for i = 1:size(rmatx,2)\n if ~isfield(clusters,'shorttitle')\n fprintf(1,['Clust%3.0f\\t'],num2str(i))\n else\n fprintf(1,['%s\\t'],clusters(i).shorttitle)\n end\n end\n \nfprintf(1,'\\n')\n\n\n% Display table body\n[yr,ustudyout] = getYear(ustudyout);\n\nfor i = 1:length(ustudyout)\n \n \n % print study name, task values, and number of peaks in each cluster\n fprintf(1,'%s\\t',[ustudyout{i} ' ' yr{i}]);\n \n if dotaskindic\n for j = 1:size(newti,2)\n fprintf(1,['%3.0f\\t'],newti(i,j))\n end\n end\n\n for j = 1:size(fmatx,2)\n fprintf(1,['%s\\t'],fmatx{i,j})\n end\n \n for j = 1:size(rmatx,2)\n fprintf(1,['%3.0f\\t'],rmatx(i,j))\n end\n \n fprintf(1,'\\n')\n \nend\n\n% Summary and percentages for columns (brain regions)\n\ntotals = sum(newti > 0); % task totals\nclustertotals = sum(rmatx > 0); % overall activation in each region\n\nif ~dotaskindic % repeat headers to avoid confusion\n fprintf(1,'\\n\\t\\t') % task indicator totals\n for i = 1:length(newnames)\n fprintf(1,'%s\\t',newnames{i})\n end\n fprintf(1,'\\n\\t') % cluster count totals\n fprintf(1,['Total\\t' repmat('%3.0f\\t',1,size(totals,2))],totals);\n fprintf(1,'\\n\\t\\t')\n for i = 1:size(rmatx,2)\n if ~isfield(clusters,'shorttitle')\n fprintf(1,['Clust%3.0f\\t'],num2str(i))\n else\n fprintf(1,['%s\\t'],clusters(i).shorttitle)\n end\n end\n fprintf(1,'\\n\\t\\t') \n fprintf(1,[repmat('%3.0f\\t',1,size(clustertotals,2))],clustertotals);\nelse \n\n fprintf(1,'\\n')\n fprintf(1,['Total\\t' repmat('%3.0f\\t',1,size(totals,2))],totals);\n for i = 1:size(fnames,2), fprintf(1,'\\t'),end\n\n fprintf(1,[repmat('%3.0f\\t',1,size(clustertotals,2))],clustertotals);\nend\n\n% percentages for columns (brain regions)\n\nperc = 100* sum(newti > 0) ./ length(ustudyout);\nclusterperc = 100 * sum(rmatx > 0) ./ length(ustudyout);\n\nfprintf(1,'\\n')\nfprintf(1,['Percentage\\t' repmat('%3.0f\\t',1,size(perc,2))],perc);\nfor i = 1:size(fnames,2), fprintf(1,'\\t'),end\n\nif ~dotaskindic % line break if no task indicator\n fprintf(1,'\\n')\nend\n\nfprintf(1,[repmat('%3.2f\\t',1,size(clusterperc,2))],clusterperc);\n\nfprintf(1,'\\n')\nfprintf(1,'\\n')\n\n\n% replace NaN task values with 0\nwh = find(isnan(newti)); newti(wh) = 0;\n\n\n% Summary and percentages by condition\n\n\nfor j = 1:size(newti,2) % newti is task indicator\n \n for k = 1:size(rmatx,2)\n \n clcondtotal(j,k) = sum(real(rmatx(:,k) > 0) & newti(:,j));\n clcondperc(j,k) = 100 * clcondtotal(j,k) / totals(j); % % of studies in condition\n \n end\n \nend\n\n\n% Prob of task given activation in each region \n\n\n% p(t|a) = p(a|t)*p(t) / p(a)\n\n% with flat priors -- old way\n%pa = clustertotals ./ length(ustudyout); % overall p(a) for each region\n%pt = ones(1,size(newti,2)) ./ size(newti,2); % overall flat priors on task: 1 / number of tasks\n%pt = repmat(pt',1,size(clustertotals,2)); % replicate for each region; all rows of pt should be the same \n%pta = clcondperc ./ 100; % p(a|t) estimate\n%for j = 1:size(newti,2) % for each task condition\n% pt_given_a(j,:) = pta(j,:) .* pt(j,:) ./ pa; \n%end\n\nfor i = 1:size(rmatx,2) % for each region; weighting ON\n [pt_given_a{i},eff{i},z{i},p{i},stat] = p_task_given_activation(newti,rmatx(:,i),1); \nend\n\n\n\n\n % ------------------------------------\n % print tables\n % ------------------------------------\n \n \nfprintf(1,'Totals by condition and cluster\\n')\n\n% header\n\nfprintf(1,'\\t')\n for i = 1:size(rmatx,2)\n if ~isfield(clusters,'shorttitle')\n fprintf(1,['Clust%3.0f\\t'],num2str(i))\n else\n fprintf(1,['%s\\t'],clusters(i).shorttitle)\n end\n end\n fprintf(1,'\\n')\n \nfor j = 1:size(newti,2)\n \n fprintf(1,'%s\\t',newnames{j})\n \n str = [repmat('%3.0f\\t',1,size(clcondtotal,2))];\n fprintf(1,str,clcondtotal(j,:))\n fprintf(1,'\\n')\n \nend\n\n\nfprintf(1,'Percentages by condition and cluster\\n')\nfor j = 1:size(newti,2)\n \n fprintf(1,'%s\\t',newnames{j})\n \n str = [repmat('%3.0f\\t',1,size(clcondperc,2))];\n fprintf(1,str,clcondperc(j,:))\n fprintf(1,'\\n')\n \nend\n\n\nfprintf(1,'Probability of task given activation in each region\\n')\nfprintf(1,'Weighting: %s\\n',stat.weighted)\n \nfor i = 1:size(rmatx,2) % regions\n if ~isfield(clusters,'shorttitle')\n fprintf(1,['Clust%3.0f\\t'],num2str(i))\n else\n fprintf(1,['%s\\t'],clusters(i).shorttitle)\n end\n\n % header for task conditions\n fprintf(1,'\\t')\n for j = 1:size(newti,2) % task indicators of interest \n fprintf(1,'%s\\t',newnames{j})\n end\n fprintf(1,'\\n')\n\n fprintf(1,'Pt|A - Pt\\t');\n % effect pt_given_a - pt\n str = [repmat('\\t%3.2f\\t',1,length(eff{i}))];\n fprintf(1,str,eff{i})\n fprintf(1,'\\n')\n \n fprintf(1,'Z\\t');\n % z-score of effect pt_given_a - pt\n fprintf(1,str,z{i})\n fprintf(1,'\\n')\n \n fprintf(1,'p\\t');\n % z-score of effect pt_given_a - pt\n fprintf(1,str,p{i})\n fprintf(1,'\\n')\n \n fprintf(1,'\\n')\nend\n \n\n\n % ------------------------------------\n % save output in OUT structure\n % ------------------------------------\n \nOUT.cond_by_cl_counts = clcondtotal;\nOUT.clustercounts = clustertotals;\nOUT.conditioncounts = totals;\nOUT.ustudyout = ustudyout;\nOUT.fmatx = fmatx;\nOUT.rmatx = rmatx;\nOUT.factornames = fnames;\nOUT.levels = levels;\nOUT.pt_given_a = pt_given_a;\nOUT.effpt_given_a = eff;\nOUT.Zpt_given_a = z;\nOUT.Ppt_given_a = p;\n\nfor i = 1:length(clusters),\n if isfield(clusters,'shorttitle')\n OUT.clusternames{i} = clusters(i).shorttitle;,\n else\n OUT.clusternames{i} = ['CL' num2str(i)];\n end\nend\n\n%perc_barplot(OUT.cond_by_cl_counts,OUT.conditioncounts,OUT.levels{1},'test',OUT.clusternames)\n \nreturn\n \n \n \n\nfunction [b,a] = getYear(ustudy)\n% b is year, a is study\nclear a, clear b\nfor i = 1:length(ustudy)\n a{i} = ustudy{i}(1:end-2);\n b{i} = ustudy{i}(end-2:end);\n \n if strcmp(b{i}(end-1:end),'00') | strcmp(b{i}(end-1:end),'01') | strcmp(b{i}(end-1:end),'02') | ...\n strcmp(b{i}(end-2:end-1),'00') | strcmp(b{i}(end-2:end-1),'01') | strcmp(b{i}(end-2:end-1),'02')\n c = '20';\n else\n c = '19';\n end\n \n if ~(strcmp(b{i}(end),'a') | strcmp(b{i}(end),'b') | strcmp(b{i}(end),'c'))\n b{i} = b{i}(end-1:end);\n end\n b{i} = [c b{i}];\nend\n\n\n\nreturn\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "db_cluster_burt_table.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/cluster_multivariate/db_cluster_burt_table.m", "size": 7918, "source_encoding": "utf_8", "md5": "4f4cf06abd54854aa6b2ca0138eae0a3", "text": "function [OUT] = db_cluster_burt_table(clusters,fnames,DB)\n% function [OUT] = db_cluster_burt_table(clusters,field list (cell array of strings),DB)\n%\n% tor wager\n% Prints table of studies and lists whether they found activation in each cluster\\\n%\n% warning: does not count separate CONTRASTS, just STUDIES.\n% DB is a structure that contains all info from the database\n%\n% clusters is a struct in which XYZmm field has list of points\n% --should be output of database2clusters, which contains all fields\n%\n% fnames is a cell array that has names of all fields in clusters to use\n% each field should be a list of 1's and 0's in this case, for now.\n% enter names in clusters(i).shorttitle to use as region names.\n%\n% The significance testing done is on the double centered superindicator\n% matrix, for an SI matrix with 2 sets of columns: One coding for activation in each cluster, and the other \n% coding for each task type. Stats are performed on the cross-correlation\n% elements between the two sets - i.e., on the associations between\n% cluster and task type, controlling for overall number of points in\n% clusters and tasks (centering column means), and also controlling for the\n% differences between task types in showing more activation\n% across all clusters (centering row means for cluster indicators) and\n% weighting studies according to the inverse of how many task types they\n% involve simultaneously (centering row means for task indicators).\n\nverbose = 0;\n\ndisp('Output of db_cluster_burt_table')\n\n[ustudy,suni] = unique(DB.Study);\ndisp([num2str(length(ustudy)) ' studies in database'])\nfprintf(1,'\\n')\n \nfor stud = 1:length(ustudy)\n\n % get vectors of values in fnames (e.g., 1 or 0) for each study\n % -------------------------------------------------------------------\n for i = 1:length(fnames)\n eval(['tmp1 = DB.' fnames{i} '(suni);'])\n fmatx(stud,i) = tmp1(stud);\n end\n \n \n % get number of peaks in cluster and fill in rmatx (matx of regional peaks)\n % -------------------------------------------------------------------\n for i = 1:length(clusters)\n \n tmp1 = strcmp(ustudy{stud},clusters(i).Study);\n rmatx(stud,i) = sum(tmp1);\n \n end\n \nend\n \n \n % Contingency table - header row\n % -------------------------------------------------------------------\n \n print_header(fnames,clusters)\n \n \n % Contingency table - body\n % -------------------------------------------------------------------\n for i = 1:length(ustudy)\n fprintf(1,'%s\\t',ustudy{i})\n for j = 1:length(fnames), fprintf(1,'%3.0f\\t',fmatx(i,j)), end\n for j = 1:length(clusters), fprintf(1,'%3.0f\\t',rmatx(i,j)), end\n fprintf('\\n')\n end\n \n \n \n % Compute indicator matrix and Burt table\n % -------------------------------------------------------------------\n \n pmatx = sparse([fmatx rmatx]);\n rmatx = (rmatx > 0);\n bmatx = double([fmatx rmatx]); % superindicator matrix\n \n % Burt profile plot\n nms = fnames; \n if isfield(clusters,'shorttitle'), for i = 1:length(clusters), nms = [nms {clusters(i).shorttitle}];, end, end\n for i = 1:size(bmatx,2)-length(nms),nms = [nms {['Reg' num2str(i)]}];, end\n \n percentstudies = burt_profile([bmatx' * bmatx],nms,size(fmatx,2));\n title('Activations by task and brain region')\n \n % create double-centered bmatxc\n tmp1 = double(fmatx); tmp1 = scale(tmp1',1)';\n tmp2 = double(rmatx); tmp2 = scale(tmp2',1)';\n\n wh1 = find(all(tmp1,2) == 0); \n wh2 = find(all(tmp2,2) == 0);\n wh = unique([wh1; wh2]);\n \n bmatxc = [tmp1 tmp2];\n bmatxc(wh,:) = [];\n ustudy(wh) = [];\n bmatxc = scale(bmatxc,1);\n \n if ~isempty(wh1)\n disp('Warning: Some rows have the same value for all columns of task (1st set) entries. Removing.')\n end\n if ~isempty(wh2)\n disp('Warning: Some rows have the same value for all columns of region (2nd set) entries. Removing.')\n end\n \n burt = scale(bmatxc,1)'*scale(bmatxc,1); % Burt table of double-centered. this is what is used in analysis.\n \n \n % Indicator matrix - header row\n % -------------------------------------------------------------------\n fprintf('\\n')\n fprintf('Superindicator matrix, row-centered\\n')\n print_header(fnames,clusters)\n \n % Indicator matrix - body\n % -------------------------------------------------------------------\n str = repmat('%3.0f\\t',1,size(bmatxc,2));\n \n for i = 1:length(ustudy)\n fprintf(1,'%s\\t',ustudy{i})\n fprintf(1,str,bmatxc(i,:)), \n fprintf('\\n')\n end\n \n \n % Burt table - header row\n % -------------------------------------------------------------------\n fprintf('\\n')\n fprintf('Burt Table\\n')\n print_header(fnames,clusters)\n \n % Burt table - body\n % -------------------------------------------------------------------\n str = repmat('%3.0f\\t',1,size(bmatxc,2));\n \n for i = 1:length(fnames)\n fprintf(1,'%s\\t',fnames{i})\n fprintf(1,str,burt(i,:)), \n fprintf('\\n')\n end\n \n for i = 1:length(clusters)\n fprintf(1,'%s\\t',clusters(i).name)\n fprintf(1,str,burt(i,:)), \n fprintf('\\n')\n end\n \n % Centered Indicator matrix - header row\n % -------------------------------------------------------------------\n %fprintf('\\n')\n %fprintf('Double-Centered Superindicator matrix\\n')\n %print_header(fnames,clusters)\n \n % Centered Indicator matrix - body\n % -------------------------------------------------------------------\n %str = repmat('%3.6f\\t',1,size(bmatx,2));\n \n %for i = 1:length(ustudy)\n % fprintf(1,'%s\\t',ustudy{i})\n % fprintf(1,str,bmatx(i,:)), \n % fprintf('\\n')\n %end\n\n fprintf(1,'\\nBootstrapping\\n')\n % remove rows so that some studies activating more overall does not influence\n % the correspondence values; remove cols, see above\n\n OUT = permute_mtx(bmatxc,'ss',1,1000,length(fnames));\n n = length(fnames);\n \n OUT.pmatx = pmatx;\n OUT.descrip_pmatx = 'Sparse superindicator matrix with number of peaks for each study in entries';\n OUT.bmatx = bmatx;\n OUT.descrip_bmatx = 'Superindicator matrix, before centering';\n OUT.n = n;\n OUT.descrip_n = 'First n columns are tasks, rest are regions';\n OUT.ustudy = ustudy;\n OUT.descrip_ustudy = 'Unique studies included';\n OUT.burt = burt;\n OUT.descrip_burt = 'Burt table: Sum of double centered, squared bmatx';\n OUT.percentstudies = percentstudies;\n OUT.descrip_percentstudies = '% of studies activating each region in each task; rows are regions';\n OUT.nms = nms;\n \n % so we have a double-centered matrix; rows and cols are scaled above\n % task x region interaction, double centered\n OUT.MCA = tor_mca(bmatxc,'none',n,nms);\n \n % lines between tasks indicate unequal numbers of studies in diff tasks\n nmdsfig(OUT.MCA.pc,OUT.n,OUT.nms,OUT.p < .05);\n \n % tmp is probability of task, given activity in region (column),\n % without considering prior probabilities of task (e.g., all tasks are\n % equally likely). \n tmp = OUT.percentstudies' ./ repmat(sum(OUT.percentstudies'),size(OUT.percentstudies,2),1);\n \n \nreturn\n \n\n\n\nfunction print_header(fnames,clusters)\n\nfprintf(1,['\\nStudy\\t']) \n for j = 1:length(fnames) \n fprintf(1,'%s\\t',fnames{j}) \n end\n\n for j = 1:length(clusters)\n if isfield(clusters,'BAstring'), fprintf(1,'%s\\t',clusters(j).BAstring)\n else, fprintf(1,'%s\\t',clusters(j).name)\n end\n end\n fprintf('\\n\\t')\n for j = 1:length(fnames),fprintf(1,'\\t'),end\n for j = 1:length(clusters)\n fprintf(1,'%3.0f,%3.0f,%3.0f\\t',clusters(j).mm_center(1),clusters(j).mm_center(2),clusters(j).mm_center(3))\n end\n fprintf('\\n')\n \nreturn\n "} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "cluster_manova.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/cluster_multivariate/cluster_manova.m", "size": 6759, "source_encoding": "utf_8", "md5": "5cf41c3ea19a61206532ba5ebe4bac14", "text": "function cluster_manova(clusters,fnames,varargin)\n% function cluster_manova(clusters,fnames,verbose)\n% tor wager\n%\n% clusters is output of clusters2database, with all fields\n% from database\n% fnames is cell array of strings with names to test\n% e.g., {'Rule' 'Task'}\n%\n% uses stats toolbox\n% example: cluster_manova(clusters,fnames)\n%\n% verbose: optional, produces more output and tests\n\nif length(varargin) > 0, verb = 1; else, verb = 0;, end\n\nmycol = {'bo' 'ys' 'g^' 'cv' 'rd' 'ys'};\nwarning off % avoid openGL warnings on my machine\nfprintf(1,'\\nNote: df will not equal sums of individual class memberships if classes are fuzzy; \\nMANOVA run separately on each class')\nfprintf(1,'\\n-------------------------------------------------\\n* Cluster_Manova.m :: Table of Clusters \\n-------------------------------------------------\\n')\nclusters = cluster_table(clusters);\n\n\nfor i = 1:length(clusters)\n \n x = [clusters(i).x clusters(i).y clusters(i).z];\n fprintf(1,'\\n-------------------------------------------------\\n* Cluster %3.0f :: %s\\n-------------------------------------------------\\n',i,clusters(i).BAstring)\n \n if verb,\n % omnibus permutation test \n clear im\n fprintf(1,'\\nfuzzy_conf_cluster: Omnibus permutation test for differences\\n')\n for j = 1:length(fnames), eval(['im(:,j) = clusters(i).' fnames{j} ';']), end\n fuzzy_conf_cluster(im,x);\n end\n \n clear im, clear allcent\n for j = 1:length(fnames)\n % get centers and distances\n eval(['im(:,j) = clusters(i).' fnames{j} ';'])\n cent = mean(x(find(im(:,j)),:),1);\n allcent(j,:) = cent;\n if isempty(cent), cent = [NaN NaN NaN];,end\n end\n\n % distances between group centers\n fprintf(1,'\\nDistances between class centers\\n')\n for j = 1:length(fnames),fprintf(1,'%s\\t',fnames{j}),end,fprintf(1,'\\n')\n mydist = squareform(pdist(allcent,'euclid'));\n \n \n %fprintf(1,'%s\\t%3.0f\\t%3.0f\\t%3.2f\\t%3.4f\\t%3.0f%\\t',fnames{j},stats.dfB,stats.dfW,stats.lambda,p,round(100*missrate));\n fprintf(1,'Name\\tnum_peaks\\tdfB\\tdfW\\tWilk''s\\tp\\tmissclass. rate\\t\\n')\n \n \n for j = 1:length(fnames)\n \n d = 0;\n \n eval(['group = clusters(i).' fnames{j} ';'])\n if max(group) == 1 | any(group==0), group = group+1;,end\n \n % run manova if there are enough observations\n % print output line\n nvox = eval(['sum(clusters(i).' fnames{j} ');']);\n [d,stats] = manova(x,group,fnames{j},nvox);\n \n % print centers and distances\n \n fprintf(1,'%s\\t%3.2f\\t%3.2f\\t%3.2f\\t',fnames{j},allcent(j,1),allcent(j,2),allcent(j,3))\n fprintf(1,[repmat('%3.2f\\t',1,size(allcent,1)) '\\n'],mydist(j,:)');\n \n \n if d > 0 & verb\n % stuff to print if it's significant\n \n figure('Color','w'); hold on;\n %fprintf(1,'\\n%s Dimension Weights: %3.2f\\t%3.2f\\t%3.2f\\t', ...\n % fnames{j},stats.eigenvec(1,1),stats.eigenvec(2,1),stats.eigenvec(3,1))\n \n fprintf(1,'\\n%s Group Centers',fnames{j})\n fprintf(1,'\\nGroup\\tx\\ty\\tz\\t')\n for k = 1:max(group), \n tmp = mean(x(group==k,:));\n fprintf(1,'\\n%3.0f\\t%3.0f\\t%3.0f\\t%3.0f\\t',k,tmp(1),tmp(2),tmp(3))\n plot3(x(group==k,1),x(group==k,2),x(group==k,3),mycol{k})\n end\n addbrain\n camzoom(.7)\n title(['Cluster ' num2str(i) ' ' fnames{j} ': blue o = no, yellow square = yes'])\n set(gca,'FontSize',18)\n \n end \n \n if d > 0 % confidence volume stuff\n \n if sum(group==2) > 12,\n results = confidence_volume(x(group==2,:),mycol{j}(1));\n end\n \n hold on;\n plot3(x(group==2,1),x(group==2,2),x(group==2,3),mycol{j},'LineWidth',2);\n \n end\n \n end\n \n if verb \n % add ALL cluster centers and pairwise manovas\n all_pairwise(clusters(i),fnames)\n end\n \n fprintf(1,'\\n')\n \nend\n\nwarning on\n\nreturn\n\n\n\nfunction [missrate,c] = get_missclassrate(group,class)\n\n% misclassification rate with confusion matrix\nfor i = 1:max(group)\n for j = 1:max(class)\n c(i,j) = sum(group==i & class==j);\n end\nend\nmissrate = 1 - trace(c) ./ sum(c(:));\n\nreturn\n\n\n\n\nfunction all_pairwise(clusters,fnames)\n\nxyz = [clusters.x clusters.y clusters.z];\n\nfprintf(1,'\\n\\nCenters for each class\\n')\n\nfor i = 1:length(fnames),\n eval(['im(:,i) = clusters.' fnames{i} ';'])\n cent = mean(xyz(find(im(:,i)),:),1);\n \n if isempty(cent), fprintf(1,'No peaks of type %s in cluster\\n', fnames{i}),cent = [NaN NaN NaN];\n else, fprintf(1,'%s\\t%3.2f\\t%3.2f\\t%3.2f\\t\\n',fnames{i},cent(1),cent(2),cent(3))\n end\n allcent(i,:) = cent;\n \nend\n\n% distances between group centers\nfprintf(1,'\\nDistances between class centers\\n')\nfor i = 1:length(fnames),fprintf(1,'%s\\t',fnames{i}),end,fprintf(1,'\\n')\nmydist = squareform(pdist(allcent,'euclid'));\nfprintf(1,[repmat('%3.2f\\t',1,size(allcent,1)) '\\n'],mydist');\n\n% now do pairwise manovas\nfprintf(1,'\\nPairwise MANOVAs\\n')\nfprintf(1,'\\nName\\tdfB\\tdfW\\tWilk''s\\tp\\tmissclass. rate\\t\\n')\n\nfor i = 1:size(im,2)\n for j = (i+1):size(im,2)\n \n % build group identities, eliminate points in both groups\n group = im(:,i); group(find(im(:,j))) = 2; group(im(:,i) & im(:,j)) = 0;\n xyztmp = xyz; xyztmp(group == 0,:) = []; group(group == 0) = [];\n \n [d,stats] = manova(xyztmp,group,[fnames{i} ' vs. ' fnames{j}]);\n \n end\nend\n\n\nreturn\n\n\n\n\nfunction [d,stats,missrate] = manova(x,group,myname,nvox)\n\nd = 0;\n\n for k = 1:max(group), numg(k) = sum(group==k);,end\n \n if any(numg < 3), fprintf(1,'%s\\t%3.0f\\t Too few in cell to classify\\t\\t\\t\\t\\t\\t\\t\\t',myname,nvox);,\n elseif numg(1) == length(group), fprintf(1,'%s\\t%3.0f\\t No activations for one group in cluster\\t\\t\\t\\t\\t\\t\\t\\t',myname,nvox);,\n \n else\n class = classify(x,x,group);\n [d,p,stats] = manova1(x,group);\n \n %whos group, whos x, sum(group==1),sum(group==2), stats\n \n [missrate,c] = get_missclassrate(group,class);\n \n fprintf(1,'\\n%s\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.2f\\t%3.4f\\t%3.0f%%\\t',myname,nvox,stats.dfB,stats.dfW,stats.lambda,p,round(100*missrate));\n fprintf(1,'%3.2f\\t%3.2f\\t%3.2f\\t', ...\n stats.eigenvec(1,1),stats.eigenvec(2,1),stats.eigenvec(3,1))\n end\n \n return\n \n \n "} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "fuzzy_conf_cluster.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/cluster_multivariate/fuzzy_conf_cluster.m", "size": 3253, "source_encoding": "utf_8", "md5": "862891358f894daaf49e1dfa0ef618df", "text": "function OUT = fuzzy_conf_cluster(im,xyz)\n% OUT = fuzzy_conf_cluster(im,xyz)\n%\n% tor wager\n% \n% input:\n% this function takes a set of indicator vectors (im)\n% coded as 1's and 0's, and a list of varables (xyz)\n% \n% output: \n% a permutation test for whether there are separate regions \n% of the space defined by the columns of xyz\n% occupied by objects in the classes specified in the columns \n% of im\n% \n% this can be thought of as a clustering algorithm,\n% based on something similar to the silhouette index of \n% Kaufmann and Rousseeuw (1990)\n% with one important difference:\n% the algorithm confirms whether classes occupy different regions\n% of space, rather than trying to isolate the space they occupy\n% (as do data-driven clustering algorithms)\n%\n% think of it as a confirmatory version of the partitioning\n% around medoids algorithm\n%\n% objects can have membership in more than one class simultaneously.\n%\n% can replace and probably be better than linear discriminant analysis\n% because it makes fewer assumptions.\n\nniter = 5000;\n\n% ---------------------------------------------\n% correct permutation\n% ---------------------------------------------\n\n[OUT.avgq, OUT.q,center] = doquality(im,xyz);\n\n% ---------------------------------------------\n% bootstrap\n% ---------------------------------------------\n\nt1 = clock;\nfor i = 1:niter\n\n % permute columns of xyz\n for j = 1:size(xyz,2)\n xyz2(:,j) = getRandom(xyz(:,j));\n end\n\n [OUT.ho_avgq(i), OUT.ho_q(i,:)] = doquality(im,xyz2);\n \n if mod(i,500)==0, fprintf(1,'.'), end\nend\n\nfprintf(1,' done (in %4.0f s)!\\n',etime(clock,t1))\n\n% ---------------------------------------------\n% table of results\n% ---------------------------------------------\n\nfprintf(1,'\\nPermutation test on distribution of classes over xyz space\\n')\nfprintf(1,'Omnibus: \\tq = \\t%3.3f\\t, expected q = \\t%3.3f\\t, p = \\t%3.4f\\t\\n', ...\n OUT.avgq, mean(OUT.ho_avgq), sum(OUT.avgq <= OUT.ho_avgq) ./ length(OUT.ho_avgq))\n\nfprintf(1,'\\t95%% sig. level is at q = %3.3f\\n',prctile(OUT.ho_avgq,95))\n\nfprintf('\\nIndividual classes\\n')\nfprintf(1,'x\\ty\\tz\\tq\\texp. q\\tthreshold\\tp\\t\\n')\n\nfor i = 1:size(OUT.ho_q,2)\n tmp = OUT.ho_q(:,i);\n \n if ~any(isnan(tmp))\n fprintf(1,'%3.0f\\t%3.0f\\t%3.0f\\t%3.3f\\t%3.3f\\t%3.3f\\t%3.4f\\t\\n', ...\n center(i,1), center(i,2), center(i,3), ...\n OUT.q(i), ...\n mean(tmp), ...\n prctile(tmp,95), ...\n sum(OUT.q(i) <= tmp) ./ length(tmp))\n else\n fprintf(1,'Insufficient objects for this class\\n')\n end\n \nend\n\nreturn\n\n\n\n\n\n\n\n\nfunction [avgq,q,center] = doquality(im,xyz)\n\nfor i = 1:size(im,2) % for each class\n tmp = mean(xyz(find(im(:,i)),:),1); % get center\n center(i,:) = tmp;\n \n % dist of all points from each center\n d(:,i) = sum((repmat(tmp,size(xyz,1),1) - xyz).^2,2).^0.5;\n \nend\n\nfor i = 1:size(im,2) % for each class\n \n tmp = mean(d(find(im(:,i)),:),1); % get mean dist to all centers\n a = tmp(i); % distance to same class center\n tmp(i) = [];\n b = min(tmp); % distance to nearest neighboring class\n q(i) = (b - a) ./ max(a,b); % quality index for this class\n \nend\n \navgq = nanmean(q);\n\nreturn\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "dbcluster_contrast_table2.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/cluster_multivariate/dbcluster_contrast_table2.m", "size": 6183, "source_encoding": "utf_8", "md5": "824e29b24785b6c5d405afe254a8b126", "text": "function OUT = db_cluster_table(clusters,DB,varargin)\n% function OUT = db_cluster_table(clusters,DB,varargin)\n%\n% tor wager\n% counts studies and contrasts in each cluster\n%\n% clusters is a struct in which XYZmm field has list of points\n% --should be output of database2clusters, which contains all fields\n% DB is database output of database2clusters\n%\n% Prints one row per coordinate in any cluster, along with study names,\n% cluster ID, and values in fields you specify in fnames\n%\n% This prints outputs by cluster! ALSO takes multiple DBs\n% order is always CLUSTER, CLUSTERDB, CLUSTER2,CLUSTERDB2, etc.\n%\n% optional arguments:\n% fnames is a cell array that has names of all fields in clusters to use\n% first cell is which factor, following cells are levels to include\n% enter one argument per factor:\n%\n% example:\n% OUT = dbcluster_contrast_table(PAIN,PAINDB,{'Right_vs_Left' 'Right' 'Left'})\n% perc_barplot(OUT.cond_by_cl_counts,OUT.conditioncounts,OUT.levels{1},'test',OUT.clusternames)\n%\n% see also db_cluster_table.m \n\n% enter input arguments\n\nfor i = 1:length(varargin), \n if isstruct(varargin{i})\n % do nothing yet\n else\n fnames{i} = varargin{i}{1};\n if length(varargin{i}) > 1\n levels{i} = varargin{i}(2:end);\n else\n eval(['levels{i} = unique(DB. ' varargin{i}{1} ');'])\n end\n end\nend\n\n\n% get indicator for all levels\n\nfor i = 1:length(varargin), \n if isstruct(varargin{i}) & length(varargin{i}) > 1 % if clusters\n [fmatx{i},rmatx{i},ustudyout{i},taskindic{i},tasknms{i},allsuni{i}] = dbcluster2indic(varargin{i},varargin{i+1},fnames);\n \n end\nend\n\n\n\nfprintf(1,'%3.0f Unique contrasts\\n',length(ustudyout))\n\n% select only levels of interest\nnewti = []; newnames = {};\n\nfor i = 1:length(fnames)\n for j = 1:length(levels{i})\n wh = find(strcmp(tasknms,levels{i}{j}));\n \n newti = [newti taskindic(:,wh)];\n newnames = [newnames tasknms(wh)];\n end\nend\n \n\n% Display header\n\nfprintf(1,'Study\\t')\nfor i = 1:length(newnames)\n fprintf(1,'%s\\t',newnames{i})\nend\n for i = 1:size(fnames,2)\n fprintf(1,['%s\\t'],fnames{i})\n end\n \n for i = 1:size(rmatx,2)\n if ~isfield(clusters,'shorttitle')\n fprintf(1,['Clust%3.0f\\t'],num2str(i))\n else\n fprintf(1,['%s\\t'],clusters(i).shorttitle)\n end\n end\n \nfprintf(1,'\\n')\n\n\n% Display table body\n[yr,ustudyout] = getYear(ustudyout);\n\nfor i = 1:length(ustudyout)\n \n \n % print study name, task values, and number of peaks in each cluster\n fprintf(1,'%s\\t',[ustudyout{i} ' ' yr{i}]);\n \n for j = 1:size(newti,2)\n fprintf(1,['%3.0f\\t'],newti(i,j))\n end\n \n for j = 1:size(fmatx,2)\n fprintf(1,['%s\\t'],fmatx{i,j})\n end\n \n for j = 1:size(rmatx,2)\n fprintf(1,['%3.0f\\t'],rmatx(i,j))\n end\n \n fprintf(1,'\\n')\n \nend\n\n% Summary and percentages for columns\n\ntotals = sum(newti > 0);\nclustertotals = sum(rmatx > 0);\n\nfprintf(1,'\\n')\nfprintf(1,['Total\\t' repmat('%3.0f\\t',1,size(totals,2))],totals);\nfor i = 1:size(fnames,2), fprintf(1,'\\t'),end\nfprintf(1,[repmat('%3.0f\\t',1,size(clustertotals,2))],clustertotals);\n\nperc = 100* sum(newti > 0) ./ length(ustudyout);\nclusterperc = 100 * sum(rmatx > 0) ./ length(ustudyout);\n\nfprintf(1,'\\n')\nfprintf(1,['Percentage\\t' repmat('%3.0f\\t',1,size(perc,2))],perc);\nfor i = 1:size(fnames,2), fprintf(1,'\\t'),end\nfprintf(1,[repmat('%3.2f\\t',1,size(clusterperc,2))],clusterperc);\n\nfprintf(1,'\\n')\nfprintf(1,'\\n')\n\n% Summary and percentages by condition\n\n\nfor j = 1:size(newti,2)\n \n for k = 1:size(rmatx,2)\n \n clcondtotal(j,k) = sum(rmatx(:,k) > 0 & newti(:,j));\n clcondperc(j,k) = 100 * clcondtotal(j,k) / totals(j); % % of studies in condition\n \n end\n \nend\n\nfprintf(1,'Totals by condition and cluster\\n')\n\n% header\n\nfprintf(1,'\\t')\n for i = 1:size(rmatx,2)\n if ~isfield(clusters,'shorttitle')\n fprintf(1,['Clust%3.0f\\t'],num2str(i))\n else\n fprintf(1,['%s\\t'],clusters(i).shorttitle)\n end\n end\n fprintf(1,'\\n')\n \nfor j = 1:size(newti,2)\n \n fprintf(1,'%s\\t',newnames{j})\n \n str = [repmat('%3.0f\\t',1,size(clcondtotal,2))];\n fprintf(1,str,clcondtotal(j,:))\n fprintf(1,'\\n')\n \nend\n\n\nfprintf(1,'Percentages by condition and cluster\\n')\nfor j = 1:size(newti,2)\n \n fprintf(1,'%s\\t',newnames{j})\n \n str = [repmat('%3.0f\\t',1,size(clcondperc,2))];\n fprintf(1,str,clcondperc(j,:))\n fprintf(1,'\\n')\n \nend\n\nOUT.cond_by_cl_counts = clcondtotal;\nOUT.clustercounts = clustertotals;\nOUT.conditioncounts = totals;\nOUT.ustudyout = ustudyout;\nOUT.fmatx = fmatx;\nOUT.rmatx = rmatx;\nOUT.factornames = fnames;\nOUT.levels = levels;\n\nfor i = 1:length(clusters),\n if isfield(clusters,'shorttitle')\n OUT.clusternames{i} = clusters(i).shorttitle;,\n else\n OUT.clusternames{i} = ['CL' num2str(i)];\n end\nend\n\n%perc_barplot(OUT.cond_by_cl_counts,OUT.conditioncounts,OUT.levels{1},'test',OUT.clusternames)\n \nreturn\n \n \n \n\nfunction [b,a] = getYear(ustudy)\n% b is year, a is study\nclear a, clear b\nfor i = 1:length(ustudy)\n a{i} = ustudy{i}(1:end-2);\n b{i} = ustudy{i}(end-2:end);\n \n if strcmp(b{i}(end-1:end),'00') | strcmp(b{i}(end-1:end),'01') | strcmp(b{i}(end-1:end),'02') | ...\n strcmp(b{i}(end-2:end-1),'00') | strcmp(b{i}(end-2:end-1),'01') | strcmp(b{i}(end-2:end-1),'02')\n c = '20';\n else\n c = '19';\n end\n \n if ~(strcmp(b{i}(end),'a') | strcmp(b{i}(end),'b') | strcmp(b{i}(end),'c'))\n b{i} = b{i}(end-1:end);\n end\n b{i} = [c b{i}];\nend\n\n\n\nreturn\n\n\n \nfunction dummy \n cl = clusters(i);\n \n for k = 1:length(clusters(i).x)\n \n fprintf(1,['%s\\t%3.0f\\t%3.0f\\t%3.0f\\t%3.0f\\t'],cl.Study{k},i,cl.x(k),cl.y(k),cl.z(k))\n \n for j = 1:length(fnames)\n\n eval(['tmp1 = cl.' fnames{j} '(k);'])\n if iscell(tmp1)\n fprintf(1,'%s\\t',tmp1{1})\n else\n fprintf(1,'%3.0f\\t',tmp1)\n end\n \n end\n \n fprintf(1,'\\n')\n \n end\n \n\nreturn"} +{"plateform": "github", "repo_name": "canlab/Canlab_MKDA_MetaAnalysis-master", "name": "bootstrap_mtx.m", "ext": ".m", "path": "Canlab_MKDA_MetaAnalysis-master/cluster_multivariate/bootstrap_mtx.m", "size": 4032, "source_encoding": "utf_8", "md5": "c5cd31cf394de00d7487d2ebc2d02f31", "text": "function [OUT] = bootstrap_mtx(data,e,varargin)\n% [OUT] = bootstrap_mtx(data,e,[meth],[verbose],[niter])\n%\n% tor wager\n%\n% BOOTSTRAP TEST FOR SIG. DIFFERENCE IN COVARIANCE FROM e (Ho)\n%\n% This function takes as input two matrices,\n% an actual matrix of data\n% and an expected / null hypothesis\n% covariance or correlation matrix.\n%\n% the algorithm provides significance levels for\n% the cov / correlation of the columns of data,\n% based on the expected correlation e\n%\n% it computes a test statistic, which is the\n% average squared deviation from the expected\n% values, element by element, over the matrix.\n% This statistic provides an \"omnibus\" test\n% of whether there are deviations from the \n% expected values in the matrix.\n%\n% for each element, a statistic is also computed -\n% the squared deviation from the expected -\n% which provides a test of significance for each\n% element. \n%\n% a permutation test is used to create an Ho \n% distribution. Columns of the matrix are\n% randomly permuted (independently), and the test\n% statistics assessed over iterations.\n%\n% called in db_cluster_burt_table.m\n%\n% example:\n% data = bmatx1(:,1:5); ss = data'*data; e = diag(diag(ss));\n% OUT = permute_mtx(bmatx1(:,1:5),e,'ss',1,1000);\n\nif length(varargin) > 0, meth = varargin{1};, else, meth = 'corr';, end\nif length(varargin) > 1, verbose = varargin{2};, else, verbose = 1;, end\nif length(varargin) > 2, niter = varargin{3};, else, niter = 5000;, end\n\nswitch meth\ncase 'cov', m = cov(data);\ncase 'ss', m = data'*data;\ncase 'corr', m = corrcoef(data);\notherwise, error('Unknown method! OK methods are cov, ss, and corr')\nend\n\nif verbose,\n fprintf(1,'\\nBootstrap_mtx.m\\n--------------------------\\n')\n fprintf(1,'Test that columns of data have no systematic relationship\\n')\n fprintf(1,'\\nActual %s matrix for data',meth),m,\n fprintf(1,'\\nExpected Ho %s matrix for data',meth),e,\nend\n\n% get index of lower triangular matrix\n% to compute stats only on these values.\nmask = triu(Inf*eye(size(m,2))); maskind = find(mask==0);\n\n\n[s1,s2] = getstats(m,e,maskind);\n\nfor i = 1:niter\n \n if mod(i,1000) == 1, fprintf(1,'.');, end\n [mi] = getcov(data,meth);\n [s1n(i),s2n(i,:)] = getstats(mi,e,maskind);\n meanmi(:,:,i) = mi;\n \nend\nfprintf(1,'\\n')\nmeanmi = mean(meanmi,3);\n\n% p is prob that test statistic lies below 0\np = 1 - sum(s1n < 0) ./ niter;\nfor i = 1:length(s2), p2(i) = 1 - sum(s2n(:,i) < 0)./ niter;, end\np2c = p2 .* length(p2);\n\nif verbose,\n fprintf(1,'\\nMean Ho %s matrix\\n',meth),meanmi\n fprintf(1,'\\nOmnibus test for differences from expected on %s\\n',meth)\n fprintf(1,'D2 %3.3f, Ho mean D2 = %3.3f, ste = %3.3f, p = %3.4f\\n',s1,mean(s1n),std(s1n),p)\n fprintf(1,'\\nSignificant individual tests for differences from expected on %s\\n',meth)\n sig = find(p2 <= .05);\n for i = 1:length(sig)\n [row,col] = ind2sub(size(m),maskind(sig(i)));\n fprintf(1,'[%3.0f,%3.0f], D2 = %3.3f, Ho D2 = %3.3f, ste = %3.3f, p = %3.4f, bonf_p = %3.4f\\n',row,col,s2(sig(i)),nanmean(s2n(:,sig(i))),nanstd(s2n(:,sig(i))),p2(sig(i)),p2c(sig(i)))\n %figure; hist(s2n(:,sig(i))) \n end\n if isempty(sig), disp('No significant results.'), end\nend\n\nOUT.m = m; OUT.e = e; OUT.s1 = s1; OUT.s2 = s2;\nOUT.p = p; OUT.p2 = p2; OUT.p2c = p2c;OUT.meanmi = meanmi;\nOUT.sig = sig; OUT.niter = niter; OUT.meth = meth; OUT.s1n = s1n; OUT.s2n = s2n;\n\nreturn\n\n\n\n\nfunction [m] = getcov(data,meth)\n\n% this would be a bootstrap\n% resample data - tested to evenly sample rows\nlen = size(data,1);\nwh = ceil(rand(len,1) .* len);\nd2 = data(wh,:);\n\n% permute columns\n%for i = 1:size(data,2)\n% d2(:,i) = getRandom(data(:,i));\n%end\n \nswitch meth\ncase 'cov', m = cov(d2);\ncase 'ss', m = d2'*d2;\ncase 'corr', m = corrcoef(d2); \notherwise, error('Unknown method! OK methods are cov, ss, and corr')\nend\n\nreturn\n\n\n\nfunction [s1,s2] = getstats(m,e,maskind)\n% input is cov matrix of whatever form - corr, ss, cov\n\nm = m(maskind); m = m(:);\ne = e(maskind); e = e(:);\n\ns2 = ((m - e) .^ 2)';\ns1 = nanmean(s2);\n\nreturn\n\n\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "boundaryBenchGraphs.m", "ext": ".m", "path": "cs543_hw-master/HM1/hw1/prob_seg/util/boundaryBenchGraphs.m", "size": 2248, "source_encoding": "utf_8", "md5": "c3a3b145b9fd12ba99efcb9df6ffac38", "text": "function boundaryBenchGraphs(pbDir, iids)\r\n% function boundaryBenchGraphs(pbDir)\r\n%\r\n% Create graphs, after boundaryBench(pbDir) has been run.\r\n%\r\n% See also boundaryBench.\r\n%\r\n% David Martin \r\n% May 2003\r\n\r\nfname = fullfile(pbDir,'scores.txt');\r\nscores = dlmread(fname); % iid,thresh,r,p,f\r\nfname = fullfile(pbDir,'score.txt');\r\nscore = dlmread(fname); % thresh,r,p,f\r\n\r\n% create the overall PR graph\r\nfname = fullfile(pbDir,'pr.txt');\r\npr = dlmread(fname); % thresh,r,p,f\r\nh = figure(1); clf; hold on;\r\nprplot(h,pr(:,2),pr(:,3),sprintf('F=%4.2f',score(4)));\r\nph=plot(score(2),score(3),'ko','MarkerFaceColor','k','MarkerSize',10);\r\nlh=legend(ph,sprintf('F=%4.2f @(%4.2f,%4.2f) t=%4.2f',...\r\n score(4),score(2),score(3),score(1)));\r\np=get(lh,'Position');\r\np(1)=0.25;\r\np(2)=0.15;\r\nset(lh,'Position',p);\r\nprint(h,'-depsc2',fullfile(pbDir,'pr.eps'));\r\nprint(h,'-djpeg95','-r36',fullfile(pbDir,'pr_half.jpg'));\r\nprint(h,'-djpeg95','-r0',fullfile(pbDir,'pr_full.jpg'));\r\n%close(h);\r\n\r\nreturn; % do not do processing for each image\r\nfor i = 1:numel(iids),\r\n iid = iids(i);\r\n fprintf(2,'Processing image %d/%d (iid=%d)...\\n',i,numel(iids),iid);\r\n\r\n % create PR graphs for this image\r\n fname = fullfile(pbDir,sprintf('%d_pr.txt',iid));\r\n pri = dlmread(fname);\r\n h = figure(1); clf; hold on;\r\n prplot(h,pri(:,2),pri(:,3),sprintf('%d F=%4.2f',iid,scores(i,5)));\r\n ph=plot(scores(i,3),scores(i,4),'ko','MarkerFaceColor','k','MarkerSize',10);\r\n lh=legend(ph,sprintf('F=%4.2f @(%4.2f,%4.2f) t=%4.2f',...\r\n scores(i,5),scores(i,3),scores(i,4),scores(i,2)));\r\n p=get(lh,'Position');\r\n p(1)=0.25;\r\n p(2)=0.15;\r\n set(lh,'Position',p);\r\n print(h,'-depsc2',fullfile(pbDir,sprintf('%d_pr.eps',iid)));\r\n print(h,'-djpeg95','-r36',fullfile(pbDir,sprintf('%d_pr_half.jpg',iid)));\r\n print(h,'-djpeg95','-r0',fullfile(pbDir,sprintf('%d_pr_full.jpg',iid)));\r\n %close(h);\r\nend\r\n\r\nfunction prplot(h,r,p,ti)\r\nfigure(h); \r\nplot(r,p,'ko-');\r\nbox on;\r\ngrid on;\r\nset(gca,'Fontsize',12);\r\nset(gca,'XTick',[0 .25 .5 .75 1]);\r\nset(gca,'YTick',[0 .25 .5 .75 1]);\r\nset(gca,'XGrid','on');\r\nset(gca,'YGrid','on');\r\nxlabel('Recall');\r\nylabel('Precision');\r\ntitle(ti);\r\naxis square;\r\naxis([0 1 0 1]);\r\n\r\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "boundaryBench.m", "ext": ".m", "path": "cs543_hw-master/HM1/hw1/prob_seg/util/boundaryBench.m", "size": 3743, "source_encoding": "utf_8", "md5": "00ac15375b4669323749195739e19485", "text": "function boundaryBench(pbDir,iids,pres,nthresh,fast)\r\n% function boundaryBench(pbDir,pres,nthresh,fast)\r\n%\r\n% Run the boundary detector benchmark on the Pb files found in\r\n% pbDir for the BSDS test images.\r\n%\r\n% See also imgList, bsdsRoot.\r\n%\r\n% David Martin \r\n% March 2003\r\n\r\nif nargin<3, nthresh=30; end\r\nif nargin<4, fast=0; end\r\n\r\ncntR_total = zeros(nthresh,1);\r\nsumR_total = zeros(nthresh,1);\r\ncntP_total = zeros(nthresh,1);\r\nsumP_total = zeros(nthresh,1);\r\nscores = zeros(numel(iids),5);\r\n\r\nfor i = 1:numel(iids),\r\n iid = iids(i);\r\n %fprintf(2,'Processing image %d/%d (iid=%d)...\\n',i,numel(iids),iid);\r\n\r\n pbFile = fullfile(pbDir,sprintf('%d.bmp',iid));\r\n fprintf(2,' Reading pb file...\\n');\r\n pb = double(imread(pbFile))/255;\r\n if ndims(pb)~=2,\r\n error(sprintf('pb file ''%s'' is not grayscale',pbFile));\r\n end\r\n\r\n fprintf(2,' Reading segs...\\n');\r\n segs = readSegs(pres,iid);\r\n\r\n % Make sure the pb and the segmentations are the same size.\r\n if numel(pb)numel(segs{1}),\r\n error('Cannot evaluate pb bigger than segmentations.');\r\n end\r\n\r\n if fast,\r\n fwrite(2,' Calculating precision/recall (fast method) ');\r\n [thresh,cntR,sumR,cntP,sumP] = boundaryPRfast(pb,segs,nthresh);\r\n else\r\n fwrite(2,' Calculating precision/recall (exact method) ');\r\n [thresh,cntR,sumR,cntP,sumP] = boundaryPR(pb,segs,nthresh);\r\n end\r\n \r\n fprintf(2,' Writing results...\\n');\r\n\r\n R = cntR ./ (sumR + (sumR==0));\r\n P = cntP ./ (sumP + (sumP==0));\r\n F = fmeasure(R,P);\r\n [bestT,bestR,bestP,bestF] = maxF(thresh,R,P);\r\n figure(3), plot(R, P), axis([0 1 0 1]), title(sprintf('precision-recall, maxF=%0.2f', bestF))\r\n drawnow;\r\n \r\n fname = fullfile(pbDir,sprintf('%d_pr.txt',iid));\r\n fid = fopen(fname,'w');\r\n if fid==-1, \r\n error(sprintf('Could not open file %s for writing.',fname));\r\n end\r\n fprintf(fid,'%10g %10g %10g %10g\\n',[thresh R P F]');\r\n fclose(fid);\r\n \r\n scores(i,:) = [iid bestT bestR bestP bestF];\r\n fname = fullfile(pbDir,'scores.txt');\r\n fid = fopen(fname,'w');\r\n if fid==-1, \r\n error(sprintf('Could not open file %s for writing.',fname));\r\n end\r\n fprintf(fid,'%10d %10g %10g %10g %10g\\n',scores(1:i,:)');\r\n fclose(fid);\r\n\r\n cntR_total = cntR_total + cntR;\r\n sumR_total = sumR_total + sumR;\r\n cntP_total = cntP_total + cntP;\r\n sumP_total = sumP_total + sumP;\r\n\r\n R = cntR_total ./ (sumR_total + (sumR_total==0));\r\n P = cntP_total ./ (sumP_total + (sumP_total==0));\r\n F = fmeasure(R,P);\r\n [bestT,bestR,bestP,bestF] = maxF(thresh,R,P);\r\n \r\n fname = fullfile(pbDir,'pr.txt');\r\n fid = fopen(fname,'w');\r\n if fid==-1, \r\n error(sprintf('Could not open file %s for writing.',fname));\r\n end\r\n fprintf(fid,'%10g %10g %10g %10g\\n',[thresh R P F]');\r\n fclose(fid);\r\n \r\n fname = fullfile(pbDir,'score.txt');\r\n fid = fopen(fname,'w');\r\n if fid==-1, \r\n error(sprintf('Could not open file %s for writing.',fname));\r\n end\r\n fprintf(fid,'%10g %10g %10g %10g\\n',bestT,bestR,bestP,bestF);\r\n fclose(fid);\r\nend\r\n\r\n% compute f-measure fromm recall and precision\r\nfunction [f] = fmeasure(r,p)\r\nf = 2*p.*r./(p+r+((p+r)==0));\r\n\r\n% interpolate to find best F and coordinates thereof\r\nfunction [bestT,bestR,bestP,bestF] = maxF(thresh,R,P)\r\nbestT = thresh(1);\r\nbestR = R(1);\r\nbestP = P(1);\r\nbestF = fmeasure(R(1),P(1));\r\nfor i = 2:numel(thresh),\r\n for d = linspace(0,1),\r\n t = thresh(i)*d + thresh(i-1)*(1-d);\r\n r = R(i)*d + R(i-1)*(1-d);\r\n p = P(i)*d + P(i-1)*(1-d);\r\n f = fmeasure(r,p);\r\n if f > bestF,\r\n bestT = t;\r\n bestR = r;\r\n bestP = p;\r\n bestF = f;\r\n end\r\n end\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "boundaryBenchGraphsMulti.m", "ext": ".m", "path": "cs543_hw-master/HM1/hw1/prob_seg/util/boundaryBenchGraphsMulti.m", "size": 3482, "source_encoding": "utf_8", "md5": "0de26c4b8ac8f977b74078d8bf55f10e", "text": "function boundaryBenchGraphsMulti(baseDir, iidsTest)\r\n% function boundaryBenchGraphsMulti(baseDir)\r\n%\r\n% See also boundaryBenchGraphs.\r\n%\r\n% David Martin \r\n% July 2003\r\n\r\npresentations = {''};\r\npresNames = {''};\r\n%presentations = {'gray','color'};\r\n%presNames = {'Grayscale','Color'};\r\n%iidsTest = imgList('test');\r\n\r\n% Infer list of algorithms from directories present.\r\nfor k = 1:length(presentations),\r\n pres = presentations{k};\r\n dirlist = dir(fullfile(baseDir,pres));\r\n algs{k} = {};\r\n for i = 1:length(dirlist),\r\n alg = dirlist(i).name;\r\n if alg(1)=='.', continue; end\r\n if ~isdir(fullfile(baseDir,pres,alg)), continue; end\r\n %if length(dir(fullfile(baseDir,pres,alg,'name.txt')))~=1, continue; end\r\n if length(dir(fullfile(baseDir,pres,alg,'score.txt')))~=1, continue; end\r\n fname = fullfile(baseDir,pres,alg,'scores.txt');\r\n if length(dir(fname))~=1, continue; end\r\n tmp = dlmread(fname); % iid,thresh,r,p,f\r\n if size(tmp,1)~=numel(iidsTest), continue; end\r\n algs{k}{1+numel(algs{k})} = alg;\r\n end\r\nend\r\n\r\n% Read in all the scores.\r\nfor k = 1:length(presentations),\r\n pres = presentations{k};\r\n if numel(algs{k})==0, continue; end\r\n for i = 1:numel(algs{k}),\r\n alg = algs{k}{i};\r\n fprintf(2,'Perusing directory %s/%s...\\n',pres,alg);\r\n fname = fullfile(baseDir,pres,alg,'pr.txt');\r\n prvals{k}{i} = dlmread(fname); % thresh,r,p,f\r\n fname = fullfile(baseDir,pres,alg,'score.txt');\r\n ascores{k}{i} = dlmread(fname); % thresh,r,p,f\r\n %fname = fullfile(baseDir,pres,alg,'name.txt');\r\n %fp = fopen(fname,'r');\r\n %names{k}{i} = fgetl(fp);\r\n %fclose(fp);\r\n names{k}{i} = alg;\r\n end\r\n fname = fullfile(baseDir,pres,'human','score.txt');\r\n if numel(dir(fname))>0,\r\n hscore{k} = dlmread(fname); % r,p,f\r\n else\r\n hscore{k} = zeros(3,1);\r\n end\r\nend\r\n\r\n% Sort algorithms by overall F measure.\r\nfprintf(2,'Sorting algorithms...\\n');\r\nfor k = 1:length(presentations),\r\n if numel(algs{k})==0, continue; end\r\n pres = presentations{k};\r\n f = [];\r\n for i = 1:numel(algs{k}), f = [f ascores{k}{i}(4)]; end\r\n [unused,aperm{k}] = sort(f);\r\n aperm{k} = aperm{k}(end:-1:1);\r\nend\r\n\r\nfprintf(2,'Generating graphs...\\n');\r\nfor k = 1:length(presentations),\r\n pres = presentations{k};\r\n for i = 1:numel(algs{k}),\r\n for j = i+1:numel(algs{k}),\r\n ii = aperm{k}(i);\r\n jj = aperm{k}(j);\r\n h = figure(1); clf; hold on;\r\n prplot(h,prvals{k}{ii}(:,2),prvals{k}{ii}(:,3),'ko-');\r\n prplot(h,prvals{k}{jj}(:,2),prvals{k}{jj}(:,3),'kx-');\r\n lh = legend(sprintf('F=%4.2f %s',ascores{k}{ii}(4),names{k}{ii}),...\r\n sprintf('F=%4.2f %s',ascores{k}{jj}(4),names{k}{jj}),3);\r\n p = get(lh,'Position');\r\n p(1) = .225;\r\n set(lh,'Position',p);\r\n fname = sprintf('%s_%03d_%03d',pres,i,j);\r\n print(h,'-depsc2',...\r\n fullfile(baseDir,'html',sprintf('pr_%s.eps',fname)));\r\n print(h,'-djpeg95','-r36',...\r\n fullfile(baseDir,'html',sprintf('pr_%s_half.jpg',fname)));\r\n print(h,'-djpeg95','-r0',...\r\n fullfile(baseDir,'html',sprintf('pr_%s_full.jpg',fname)));\r\n %close(h);\r\n end\r\n end\r\nend\r\n\r\nfunction prplot(h,r,p,sym)\r\nfigure(h);\r\nplot(r,p,sym);\r\nbox on;\r\ngrid on;\r\nset(gca,'Fontsize',12);\r\nset(gca,'XTick',[0 .25 .5 .75 1]);\r\nset(gca,'YTick',[0 .25 .5 .75 1]);\r\nset(gca,'XGrid','on');\r\nset(gca,'YGrid','on');\r\nxlabel('Recall');\r\nylabel('Precision');\r\naxis square;\r\naxis([0 1 0 1]);\r\n\r\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "boundaryBenchHuman.m", "ext": ".m", "path": "cs543_hw-master/HM1/hw1/prob_seg/util/boundaryBenchHuman.m", "size": 2673, "source_encoding": "utf_8", "md5": "581d9142391e4de622846c1cf478fc28", "text": "function boundaryBenchHuman(pbRoot,pres, iids)\r\n% function boundaryBenchHuman(pbRoot,pres)\r\n%\r\n% Compute the human precision/recall data for the BSDS test images.\r\n%\r\n% See also imgList, bsdsRoot.\r\n%\r\n% David Martin \r\n% March 2003\r\n\r\n%iids = imgList('test');\r\n\r\n\r\ncR_total = 0;\r\nsR_total = 0;\r\ncP_total = 0;\r\nsP_total = 0;\r\nscores = zeros(0,4);\r\n\r\nfor i = 1:numel(iids),\r\n iid = iids(i);\r\n fprintf(2,'Processing %s image %d/%d (iid=%d)...\\n',...\r\n pres,i,numel(iids),iid);\r\n\r\n fprintf(2,' Reading segs...\\n');\r\n segs = readSegs(pres,iid);\r\n\r\n fwrite(2,' Computing PR ');\r\n cntR = zeros(numel(segs),1);\r\n sumR = zeros(numel(segs),1);\r\n cntP = zeros(numel(segs),1);\r\n sumP = zeros(numel(segs),1);\r\n n = numel(segs);\r\n progbar(0,n);\r\n for j = 1:n,\r\n % leave each out in turn\r\n pb = seg2bmap(segs{j});\r\n segs2 = cell(n-1,1);\r\n for k = 1:numel(segs),\r\n if k < j, segs2{k} = segs{k}; end\r\n if k > j, segs2{k-1} = segs{k}; end\r\n end\r\n [thresh,cntR(j),sumR(j),cntP(j),sumP(j)] = boundaryPR(pb,segs2);\r\n progbar(j,n);\r\n end\r\n\r\n fprintf(2,' Writing results...\\n');\r\n\r\n % pr values for each subject for each image\r\n \r\n R = cntR ./ (sumR + (sumR==0));\r\n P = cntP ./ (sumP + (sumP==0));\r\n F = fmeasure(R,P);\r\n\r\n fname = fullfile(pbRoot,pres,'human',sprintf('%d_pr.txt',iid));\r\n fid = fopen(fname,'w');\r\n if fid==-1, \r\n error(sprintf('Could not open file %s for writing.',fname));\r\n end\r\n fprintf(fid,'%10g %10g %10g\\n',[R P F]');\r\n fclose(fid);\r\n\r\n % overall pr for each image across all subjects\r\n\r\n cR = sum(cntR);\r\n sR = sum(sumR);\r\n cP = sum(cntP);\r\n sP = sum(sumP);\r\n bestR = cR ./ (sR + (sR==0));\r\n bestP = cP ./ (sP + (sP==0));\r\n bestF = fmeasure(bestR,bestP);\r\n scores(i,:) = [iid bestR bestP bestF];\r\n\r\n fname = fullfile(pbRoot,pres,'human','scores.txt');\r\n fid = fopen(fname,'w');\r\n if fid==-1, \r\n error(sprintf('Could not open file %s for writing.',fname));\r\n end\r\n fprintf(fid,'%10d %10g %10g %10g\\n',scores(1:i,:)');\r\n fclose(fid);\r\n\r\n % overall pr across all images\r\n \r\n cR_total = cR_total + cR;\r\n sR_total = sR_total + sR;\r\n cP_total = cP_total + cP;\r\n sP_total = sP_total + sP;\r\n R = cR_total ./ (sR_total + (sR_total==0));\r\n P = cP_total ./ (sP_total + (sP_total==0));\r\n F = fmeasure(R,P);\r\n \r\n fname = fullfile(pbRoot,pres,'human','score.txt');\r\n fid = fopen(fname,'w');\r\n if fid==-1, \r\n error(sprintf('Could not open file %s for writing.',fname));\r\n end\r\n fprintf(fid,'%10g %10g %10g\\n',R,P,F);\r\n fclose(fid);\r\nend\r\n\r\n% compute f-measure fromm recall and precision\r\nfunction [f] = fmeasure(r,p)\r\nf = 2*p.*r./(p+r+((p+r)==0));\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "runThis.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p3/runThis.m", "size": 2545, "source_encoding": "utf_8", "md5": "44f52356d239c12c2633085c86b26db6", "text": "function runThis()\n%% Code for CS 543 Homework 4,gch = GraphCut('open', Dc, 10*Sc, Problem 3 - Graph Cut Segmentation\n%\n%----------------------------------------------------------------\nclose all;\naddpath('./GCmex1.5/')\n\ndisp('Reading Image');\nim = im2double(imread('cat.jpg'));\nsz = size(im);\ndata = reshape(im, [sz(1) * sz(2), sz(3)]);\n\ndisp('Reading Polygon and Generating FG masks');\nload('cat_poly.mat');\nmask = poly2mask(poly(:,1), poly(:,2), sz(1), sz(2));\n\nK=2; %segment the image into K parts, 2: foreground and background\nk1 = 1;\nk2 = 1;\nnum_gmm = 5; % use 2 gaussian to estimate the foreground\n\nSEG_ITER = 2; % Number of iterations: estimate posibility -> graph cut\n\n% Prepare data: Smoothness\nSc=ones(K) - eye(K); \n% Calculate edge response\n[Hc, Vc] = edge_potential(im);\n\ndisp('Start Graph Cut...');\nfor iter = 1:SEG_ITER\n fprintf(1,'Performing Iteration %d...\\n', iter);\n % estimate GMM\n fg = data(mask(:), :);\n bg = data(~mask(:),:);\n % estimate gmm model\n fg_gmm = fitgmdist(fg, num_gmm);\n bg_gmm = fitgmdist(bg, num_gmm);\n % calculate the foreground probability\n p_fg = fg_gmm.pdf(data);\n p_fg = reshape(p_fg, sz(1), sz(2));\n p_bg = bg_gmm.pdf(data);\n p_bg = reshape(p_bg, sz(1), sz(2));\n \n figure(1);\n subplot(1,3,1); imagesc(p_fg, [0,1]); title('Foreground Intensity');\n subplot(1,3,2); imagesc(p_bg, [0,1]); title('Background Intensity');\n \n Dc = zeros(sz(1),sz(2), 2);\n Dc(:,:,1) = -log(p_fg ./ (p_bg + eps));\n Dc(:,:,2) = -log(p_bg ./ (p_fg + eps));\n \n % Construct GraphCut handle\n gch = GraphCut('open', Dc, k1 * Sc, k2 * exp(-Vc), k2 * exp(-Hc));\n % Perform GraphCut\n [gch, L] = GraphCut('swap',gch);\n gch = GraphCut('close', gch);\n % Use L to update fg_mask\n fg_mask = (L==0);\n figure(1);\n subplot(1,3,3);imagesc(fg_mask);title('Segmentation Mask');\nend\n\ndisp('Graph Cut Done!');\n% display\nsim = zeros(sz);\n% set background as blue\nsim(:,:,3) = 1.0;\n% set foreground as original pixels\nmask = zeros(sz);\nfor i = 1:sz(3)\n mask(:,:,i) = fg_mask;\nend\nsim = sim.*(1-mask) + im .* mask;\nfigure(2);\nimshow(sim); title('Segmentation Results using Graph Cut');\n\n% save to file\nimwrite(sim, './segmentation.png');\n\n%-----------------------------------------------%\nfunction [hC vC] = edge_potential(im)\ndg = fspecial('log', [13 13], sqrt(13));\nsz = size(im);\n\nvC = zeros(sz(1:2));\nhC = vC;\n\nfor b=1:size(im,3)\n vC = max(vC, abs(imfilter(im(:,:,b), dg, 'symmetric')));\n hC = max(hC, abs(imfilter(im(:,:,b), dg', 'symmetric')));\nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "GraphCut.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p3/GCmex1.5/GraphCut.m", "size": 14471, "source_encoding": "utf_8", "md5": "01f6bf97b8cc0b1cfe5e3250a8c3ba37", "text": "function [gch, varargout] = GraphCut(mode, varargin)\r\n%\r\n% Performing Graph Cut energy minimization operations on a 2D grid.\r\n% \r\n% Usage:\r\n% [gch ...] = GraphCut(mode, ...);\r\n% \r\n%\r\n% Inputs:\r\n% - mode: a string specifying mode of operation. See details below.\r\n%\r\n% Output:\r\n% - gch: A handle to the constructed graph. Handle this handle with care\r\n% and don't forget to close it in the end!\r\n%\r\n% Possible modes:\r\n% - 'open': Create a new graph object\r\n% [gch] = GraphCut('open', DataCost, SmoothnessCost);\r\n% [gch] = GraphCut('open', DataCost, SmoothnessCost, vC, hC);\r\n% [gch] = GraphCut('open', DataCost, SmoothnessCost, SparseSmoothness);\r\n%\r\n% Inputs:\r\n% - DataCost a height by width by num_labels matrix where\r\n% Dc(r,c,l) equals the cost for assigning label l to pixel at (r,c)\r\n% Note that the graph dimensions, and the number of labels are deduced \r\n% form the size of the DataCost matrix.\r\n% When using SparseSmoothness Dc is of (L)x(P) where L is the\r\n% number of labels and P is the number of nodes/pixels in the\r\n% graph.\r\n% - SmoothnessCost a #labels by #labels matrix where Sc(l1, l2)\r\n% is the cost of assigning neighboring pixels with label1 and\r\n% label2. This cost is spatialy invariant\r\n% - vC, hC:optional arrays defining spatialy varying smoothness cost. \r\n% Single precission arrays of size width*height.\r\n% The smoothness cost is computed using:\r\n% V_pq(l1, l2) = V(l1, l2) * w_pq\r\n% where V is the SmoothnessCost matrix\r\n% w_pq is spatialy varying parameter:\r\n% if p=(r,c) and q=(r+1,c) then w_pq = vCue(r,c)\r\n% if p=(r,c) and q=(r,c+1) then w_pq = hCue(r,c)\r\n% (therefore in practice the last column of vC and\r\n% the last row of vC are not used).\r\n% - SparseSmoothness: a sparse matrix defining both the graph\r\n% structure (might be other than grid) and the spatialy varying\r\n% smoothness term. Must be real positive sparse matrix of size\r\n% num_pixels by num_pixels, each non zero entry (i,j) defines a link\r\n% between pixels i and j with w_pq = SparseSmoothness(i,j).\r\n%\r\n% - 'set': Set labels\r\n% [gch] = GraphCut('set', gch, labels)\r\n%\r\n% Inputs:\r\n% - labels: a width by height array containing a label per pixel.\r\n% Array should be the same size of the grid with values\r\n% [0..num_labels].\r\n%\r\n%\r\n% - 'get': Get current labeling\r\n% [gch labels] = GraphCut('get', gch)\r\n%\r\n% Outputs:\r\n% - labels: a height by width array, containing a label per pixel. \r\n% note that labels values are in range [0..num_labels-1].\r\n%\r\n%\r\n% - 'energy': Get current values of energy terms\r\n% [gch se de] = GraphCut('energy', gch)\r\n% [gch e] = GraphGut('energy', gch)\r\n%\r\n% Outputs:\r\n% - se: Smoothness energy term.\r\n% - de: Data energy term.\r\n% - e = se + de\r\n%\r\n%\r\n% - 'expand': Perform labels expansion\r\n% [gch labels] = GraphCut('expand', gch)\r\n% [gch labels] = GraphCut('expand', gch, iter)\r\n% [gch labels] = GraphCut('expand', gch, [], label)\r\n% [gch labels] = GraphCut('expand', gch, [], label, indices)\r\n%\r\n% When no inputs are provided, GraphCut performs expansion steps\r\n% until it converges.\r\n%\r\n% Inputs:\r\n% - iter: a double scalar, the maximum number of expand\r\n% iterations to perform.\r\n% - label: scalar denoting the label for which to perfom\r\n% expand step (labels are [0..num_labels-1]).\r\n% - indices: array of linear indices of pixels for which\r\n% expand step is computed. \r\n%\r\n% Outputs:\r\n% - labels: a width*height array of type int32, containing a\r\n% label per pixel. note that labels values must be is range\r\n% [0..num_labels-1].\r\n%\r\n%\r\n% - 'swap': Perform alpha - beta swappings\r\n% [gch labels] = GraphCut('swap', gch)\r\n% [gch labels] = GraphCut('swap', gch, iter)\r\n% [gch labels] = GraphCut('swap', gch, label1, label2)\r\n%\r\n% When no inputs are provided, GraphCut performs alpha - beta swaps steps\r\n% until it converges.\r\n%\r\n% Inputs:\r\n% - iter: a double scalar, the maximum number of swap\r\n% iterations to perform.\r\n% - label1, label2: int32 scalars denoting two labels for swap\r\n% step.\r\n%\r\n% Outputs:\r\n% - labels: a width*height array of type int32, containing a\r\n% label per pixel. note that labels values must be is range\r\n% [0..num_labels-1].\r\n%\r\n%\r\n% - 'close': Close the graph and release allocated resources.\r\n% [gch] = GraphCut(gch,'close');\r\n%\r\n%\r\n%\r\n% This wrapper for Matlab was written by Shai Bagon (shai.bagon@weizmann.ac.il).\r\n% Department of Computer Science and Applied Mathmatics\r\n% Wiezmann Institute of Science\r\n% http://www.wisdom.weizmann.ac.il/\r\n%\r\n%\tThe core cpp application was written by Olga Veksler\r\n%\t(available from http://www.csd.uwo.ca/faculty/olga/code.html):\r\n%\r\n% [1] Efficient Approximate Energy Minimization via Graph Cuts\r\n% Yuri Boykov, Olga Veksler, Ramin Zabih,\r\n% IEEE transactions on PAMI, vol. 20, no. 12, p. 1222-1239, November\r\n% 2001.\r\n% \r\n% [2] What Energy Functions can be Minimized via Graph Cuts?\r\n% Vladimir Kolmogorov and Ramin Zabih.\r\n% IEEE Transactions on Pattern Analysis and Machine Intelligence\r\n% (PAMI), vol. 26, no. 2,\r\n% February 2004, pp. 147-159.\r\n% \r\n% [3] An Experimental Comparison of Min-Cut/Max-Flow Algorithms\r\n% for Energy Minimization in Vision.\r\n% Yuri Boykov and Vladimir Kolmogorov.\r\n% In IEEE Transactions on Pattern Analysis and Machine Intelligence\r\n% (PAMI),\r\n% vol. 26, no. 9, September 2004, pp. 1124-1137.\r\n% \r\n% [4] Matlab Wrapper for Graph Cut.\r\n% Shai Bagon.\r\n% in www.wisdom.weizmann.ac.il/~bagon, December 2006.\r\n% \r\n% This software can be used only for research purposes, you should cite ALL of\r\n% the aforementioned papers in any resulting publication.\r\n% If you wish to use this software (or the algorithms described in the\r\n% aforementioned paper)\r\n% for commercial purposes, you should be aware that there is a US patent:\r\n%\r\n% R. Zabih, Y. Boykov, O. Veksler,\r\n% \"System and method for fast approximate energy minimization via\r\n% graph cuts \",\r\n% United Stated Patent 6,744,923, June 1, 2004\r\n%\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n%\r\n%\r\n\r\nswitch lower(mode)\r\n case {'o', 'open'}\r\n % open a new graph cut\r\n if nargout ~= 1\r\n error('GraphCut:Open: wrong number of output arguments');\r\n end\r\n\r\n gch = OpenGraph(varargin{:});\r\n\r\n case {'c', 'close'}\r\n % close the GraphCut handle - free memory.\r\n if nargin ~= 2\r\n error('GraphCut:Close: Too many inputs');\r\n end\r\n gch = varargin{1};\r\n [gch] = GraphCutMex(gch, 'c');\r\n \r\n case {'g', 'get'}\r\n % get current labeling\r\n \r\n if nargout ~= 2\r\n error('GraphCut:GetLabels: wrong number of outputs');\r\n end\r\n [gch labels] = GetLabels(varargin{:});\r\n\r\n varargout{1} = labels;\r\n \r\n case {'s', 'set'}\r\n % set user defined labeling\r\n if nargout ~= 1\r\n error('GraphCut:SetLabels: Too many outputs');\r\n end\r\n \r\n [gch] = SetLabels(varargin{:});\r\n \r\n case {'en', 'n', 'energy'}\r\n % get current energy values\r\n if nargin ~= 2\r\n error('GraphCut:GetEnergy: too many input arguments');\r\n end\r\n gch = varargin{1};\r\n [gch se de] = GraphCutMex(gch, 'n');\r\n switch nargout\r\n case 2\r\n varargout{1} = se+de;\r\n case 3\r\n varargout{1} = se;\r\n varargout{2} = de;\r\n case 1\r\n otherwise\r\n error('GraphCut:GetEnergy: wrong number of output arguments')\r\n end\r\n \r\n \r\n case {'e', 'ex', 'expand'}\r\n % use expand steps to minimize energy\r\n if nargout > 2\r\n error('GraphCut:Expand: too many output arguments');\r\n end\r\n [gch labels] = Expand(varargin{:});\r\n if nargout == 2\r\n varargout{1} = labels;\r\n end\r\n \r\n case {'sw', 'a', 'ab', 'swap'}\r\n % use alpha beta swapping to minimize energy\r\n if nargout > 2\r\n error('GraphCut:Expand: too many output arguments');\r\n end\r\n [gch labels] = Swap(varargin{:});\r\n if nargout == 2\r\n varargout{1} = labels;\r\n end\r\n \r\n otherwise\r\n error('GraphCut: Unrecognized mode %s', mode);\r\nend\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% Aux functions\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nfunction gch = OpenGraph(varargin)\r\n% Usage [gch] = OpenGraph(Dc, Sc, [vC, hC]) - 2D grid\r\n% or [gch] = OpenGraph(Dc, Sc, [Contrast]) -3D grid\r\n% or [gch] = GraphCut(DataCost, SmoothnessCost, SparseSmoothness) - any graph\r\nnin = numel(varargin);\r\nif (nin~=2) && (nin ~= 3) && (nin~=4) \r\n error('GraphCut:Open: wrong number of inputs');\r\nend\r\n\r\n% Data cost\r\nDc = varargin{1};\r\nif ndims(Dc) == 4\r\n %% 3D graph\r\n [R C Z L] = size(Dc);\r\n if ~strcmp(class(Dc),'single')\r\n Dc = single(Dc);\r\n end\r\n Dc = permute(Dc,[4 1 2 3]);\r\n Dc = Dc(:)';\r\n \r\n % smoothness cost\r\n Sc = varargin{2};\r\n if any( size(Sc) ~= [L L] )\r\n error('GraphCut:Open: smoothness cost has incorrect size');\r\n end\r\n if ~strcmp(class(Sc),'single')\r\n Sc = single(Sc);\r\n end\r\n Sc = Sc(:)';\r\n if nin == 3\r\n Contrast = varargin{3};\r\n if any( size(Contrast) ~= [R C Z] )\r\n error('GraphCut:Open: Contrast term is of wrong size');\r\n end\r\n if ~strcmp(class(Contrast),'single')\r\n Contrast = single(Contrast);\r\n end\r\n Contrast = Contrast(:);\r\n \r\n gch = GraphCut3dConstr(R, C, Z, L, Dc, Sc, Contrast);\r\n elseif nin == 2\r\n gch = GraphCut3dConstr(R, C, Z, L, Dc, Sc);\r\n else\r\n error('GraphCut:Open: wrong number of inputs for 3D graph');\r\n end\r\nelseif ndims(Dc) == 3\r\n %% 2D graph\r\n [h w l] = size(Dc);\r\n if ~strcmp(class(Dc),'single')\r\n Dc = single(Dc);\r\n end\r\n Dc = permute(Dc,[3 2 1]);\r\n Dc = Dc(:)';\r\n\r\n % smoothness cost\r\n Sc = varargin{2};\r\n if any( size(Sc) ~= [l l] )\r\n error('GraphCut:Open: smoothness cost has incorrect size');\r\n end\r\n if ~strcmp(class(Sc),'single')\r\n Sc = single(Sc);\r\n end\r\n Sc = Sc(:)';\r\n\r\n if nin==4\r\n vC = varargin{3};\r\n if any( size(vC) ~= [h w] )\r\n error('GraphCut:Open: vertical cue size incorrect');\r\n end\r\n if ~strcmp(class(vC),'single')\r\n vC = single(vC);\r\n end\r\n vC = vC';\r\n\r\n hC = varargin{4};\r\n if any( size(hC) ~= [h w] )\r\n error('GraphCut:Open: horizontal cue size incorrect');\r\n end\r\n if ~strcmp(class(hC),'single')\r\n hC = single(hC);\r\n end\r\n hC = hC';\r\n gch = GraphCutConstr(w, h, l, Dc, Sc, vC(:), hC(:));\r\n elseif nin == 2\r\n gch = GraphCutConstr(w, h, l, Dc, Sc);\r\n else\r\n error('GraphCut:Open: wrong number of input for 2D grid');\r\n end\r\nelseif ndims(Dc) == 2\r\n %% arbitrary graph\r\n if nin ~= 3\r\n error('GraphCut:Open', 'incorect number of inputs');\r\n end\r\n \r\n [nl np] = size(Dc);\r\n Sc = varargin{2};\r\n if any(size(Sc) ~= [nl nl])\r\n error('GraphCut:Open', 'Wrong size of Dc or Sc');\r\n end\r\n \r\n SparseSc = varargin{3};\r\n if any(size(SparseSc) ~= [np np])\r\n error('GraphCut:Open', 'Wrong size of SparseSc');\r\n end\r\n \r\n gch = GraphCutConstrSparse(single(Dc(:)), single(Sc(:)), SparseSc);\r\n \r\nelse\r\n %% Unknown dimensionality...\r\n error('GraphCut:Open: data cost has incorect dimensionality');\r\nend\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nfunction [gch] = SetLabels(varargin)\r\n% usgae [gch] = SetLabels(gch, labels)\r\n\r\nif nargin ~= 2\r\n error('GraphCut:SetLabels: wrong number of inputs');\r\nend\r\ngch = varargin{1};\r\nlabels = varargin{2};\r\n\r\nif ~strcmp(class(labels), 'int32')\r\n labels = int32(labels);\r\nend\r\nlabels = labels';\r\n[gch] = GraphCutMex(gch, 's', labels(:));\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nfunction [gch labels] = GetLabels(varargin)\r\n\r\nif nargin ~= 1\r\n error('GraphCut:GetLabels: wrong number of inputs');\r\nend\r\ngch = varargin{1};\r\n[gch labels] = GraphCutMex(gch, 'g');\r\nlabels = labels';\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nfunction [gch labels] = Expand(varargin)\r\ngch = varargin{1};\r\nswitch nargin\r\n case 1\r\n [gch labels] = GraphCutMex(gch, 'e');\r\n case 2\r\n [gch labels] = GraphCutMex(gch, 'e', varargin{2});\r\n case 3\r\n [gch labels] = GraphCutMex(gch, 'e', varargin{2}, varargin{3});\r\n case 4\r\n ind = varargin{4};\r\n ind = int32(ind(:)-1)'; % convert to int32\r\n [gch labels] = GraphCutMex(gch, 'e', varargin{2}, varargin{3}, ind);\r\n otherwise\r\n error('GraphCut:Expand: wrong number of inputs');\r\nend\r\nlabels = labels';\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nfunction [gch labels] = Swap(varargin)\r\ngch = varargin{1};\r\nswitch nargin\r\n case 1\r\n [gch labels] = GraphCutMex(gch, 'a');\r\n case 2\r\n [gch labels] = GraphCutMex(gch, 'a', varargin{2});\r\n case 3\r\n [gch labels] = GraphCutMex(gch, 'a', varargin{2}, varargin{3});\r\n otherwise\r\n error('GraphCut:Swap: wrong number of inputarguments');\r\nend\r\nlabels = labels';\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "collect_eval_bdry.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/BSR/bench/benchmarks/collect_eval_bdry.m", "size": 4045, "source_encoding": "utf_8", "md5": "9fed7e6659da0261305de3f92b4a9446", "text": "function [ bestF, bestP, bestR, bestT, F_max, P_max, R_max, Area_PR] = collect_eval_bdry(pbDir)\r\n% function [ bestF, bestP, bestR, bestT, F_max, P_max, R_max, Area_PR ] = collect_eval_bdry(pbDir)\r\n%\r\n% calculate P, R and F-measure from individual evaluation files\r\n%\r\n% Pablo Arbelaez \r\n\r\n\r\nfname = fullfile(pbDir, 'eval_bdry.txt');\r\nif (length(dir(fname))==1),\r\n tmp = dlmread(fname); \r\n bestT = tmp(1);\r\n bestR = tmp(2);\r\n bestP = tmp(3);\r\n bestF = tmp(4);\r\n R_max = tmp(5);\r\n P_max = tmp(6);\r\n F_max = tmp(7);\r\n Area_PR = tmp(8);\r\nelse\r\n\r\n S = dir(fullfile(pbDir,'*_ev1.txt'));\r\n\r\n % deduce nthresh from .pr files\r\n filename = fullfile(pbDir,S(1).name);\r\n AA = dlmread(filename); % thresh cntR sumR cntP sumP\r\n\r\n thresh = AA(:,1);\r\n\r\n nthresh = numel(thresh);\r\n cntR_total = zeros(nthresh,1);\r\n sumR_total = zeros(nthresh,1);\r\n cntP_total = zeros(nthresh,1);\r\n sumP_total = zeros(nthresh,1);\r\n cntR_max = 0;\r\n sumR_max = 0;\r\n cntP_max = 0;\r\n sumP_max = 0;\r\n scores = zeros(length(S),5);\r\n\r\n for i = 1:length(S),\r\n\r\n iid = S(i).name(1:end-8);\r\n fprintf(2,'Processing image %s (%d/%d)...\\n',iid,i,length(S));\r\n\r\n filename = fullfile(pbDir,S(i).name);\r\n AA = dlmread(filename);\r\n cntR = AA(:, 2);\r\n sumR = AA(:, 3);\r\n cntP = AA(:, 4);\r\n sumP = AA(:, 5);\r\n\r\n R = cntR ./ (sumR + (sumR==0));\r\n P = cntP ./ (sumP + (sumP==0));\r\n F = fmeasure(R,P);\r\n\r\n [bestT,bestR,bestP,bestF] = maxF(thresh,R,P);\r\n scores(i,:) = [i bestT bestR bestP bestF];\r\n\r\n cntR_total = cntR_total + cntR;\r\n sumR_total = sumR_total + sumR;\r\n cntP_total = cntP_total + cntP;\r\n sumP_total = sumP_total + sumP;\r\n\r\n ff=find(F==max(F));\r\n cntR_max = cntR_max + cntR(ff(1));\r\n sumR_max = sumR_max + sumR(ff(1));\r\n cntP_max = cntP_max + cntP(ff(1));\r\n sumP_max = sumP_max + sumP(ff(1));\r\n\r\n end\r\n\r\n R = cntR_total ./ (sumR_total + (sumR_total==0));\r\n P = cntP_total ./ (sumP_total + (sumP_total==0));\r\n F = fmeasure(R,P);\r\n [bestT,bestR,bestP,bestF] = maxF(thresh,R,P);\r\n\r\n fname = fullfile(pbDir,'eval_bdry_img.txt');\r\n fid = fopen(fname,'w');\r\n if fid==-1,\r\n error('Could not open file %s for writing.',fname);\r\n end\r\n fprintf(fid,'%10d %10g %10g %10g %10g\\n',scores');\r\n fclose(fid);\r\n\r\n fname = fullfile(pbDir,'eval_bdry_thr.txt');\r\n fid = fopen(fname,'w');\r\n if fid==-1,\r\n error('Could not open file %s for writing.',fname);\r\n end\r\n fprintf(fid,'%10g %10g %10g %10g\\n',[thresh R P F]');\r\n fclose(fid);\r\n\r\n R_max = cntR_max ./ (sumR_max + (sumR_max==0));\r\n P_max = cntP_max ./ (sumP_max + (sumP_max==0));\r\n F_max = fmeasure(R_max,P_max);\r\n\r\n [Ru, indR] = unique(R);\r\n Pu = P(indR);\r\n Ri = 0 : 0.01 : 1;\r\n if numel(Ru)>1,\r\n P_int1 = interp1(Ru, Pu, Ri);\r\n P_int1(isnan(P_int1)) = 0;\r\n Area_PR = sum(P_int1)*0.01;\r\n\r\n else\r\n Area_PR = 0;\r\n end\r\n \r\n fname = fullfile(pbDir,'eval_bdry.txt');\r\n fid = fopen(fname,'w');\r\n if fid==-1,\r\n error('Could not open file %s for writing.',fname);\r\n end\r\n fprintf(fid,'%10g %10g %10g %10g %10g %10g %10g %10g\\n',bestT,bestR,bestP,bestF,R_max,P_max,F_max,Area_PR);\r\n fclose(fid);\r\n\r\n \r\n\r\nend\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% compute f-measure fromm recall and precision\r\nfunction [f] = fmeasure(r,p)\r\nf = 2*p.*r./(p+r+((p+r)==0));\r\n\r\n% interpolate to find best F and coordinates thereof\r\nfunction [bestT,bestR,bestP,bestF] = maxF(thresh,R,P)\r\nbestT = thresh(1);\r\nbestR = R(1);\r\nbestP = P(1);\r\nbestF = fmeasure(R(1),P(1));\r\nfor i = 2:numel(thresh),\r\n for d = linspace(0,1),\r\n t = thresh(i)*d + thresh(i-1)*(1-d);\r\n r = R(i)*d + R(i-1)*(1-d);\r\n p = P(i)*d + P(i-1)*(1-d);\r\n f = fmeasure(r,p);\r\n if f > bestF,\r\n bestT = t;\r\n bestR = r;\r\n bestP = p;\r\n bestF = f;\r\n end\r\n end\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "match_segmentations2.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/BSR/bench/benchmarks/match_segmentations2.m", "size": 1758, "source_encoding": "utf_8", "md5": "32c0a43565bb97cc551f6718eeeca2ee", "text": "function [sumRI sumVOI ] = match_segmentations2(seg, groundTruth)\r\n% match a test segmentation to a set of ground-truth segmentations with the PROBABILISTIC RAND INDEX and VARIATION OF INFORMATION metrics.\r\n\r\nsumRI = 0;\r\nsumVOI = 0;\r\n[tx, ty] = size(seg);\r\n\r\nfor s = 1 : numel(groundTruth)\r\n gt = groundTruth{s}.Segmentation;\r\n\r\n num1 = max(seg(:));\r\n num2 = max(gt(:));\r\n confcounts = zeros(num1, num2);\r\n for i = 1:tx\r\n for j = 1:ty\r\n u = seg(i,j);\r\n v = gt(i,j); \r\n confcounts(u,v) = confcounts(u,v)+1;\r\n end\r\n end\r\n \r\n curRI = rand_index(confcounts);\r\n curVOI = variation_of_information(confcounts);\r\n \r\n sumRI = sumRI + curRI;\r\n sumVOI = sumVOI + curVOI;\r\n\r\nend\r\n\r\nsumRI = sumRI / numel(groundTruth);\r\nsumVOI = sumVOI / numel(groundTruth);\r\n\r\n\r\n%% performance metrics following the implementation by Allen Yang:\r\n% http://perception.csl.uiuc.edu/coding/image_segmentation/\r\n\r\nfunction ri = rand_index(n)\r\nN = sum(sum(n));\r\nn_u=sum(n,2);\r\nn_v=sum(n,1);\r\nN_choose_2=N*(N-1)/2;\r\nri = 1 - ( sum(n_u .* n_u)/2 + sum(n_v .* n_v)/2 - sum(sum(n.*n)) )/N_choose_2;\r\n\r\nfunction vi = variation_of_information(n)\r\nN = sum(sum(n));\r\njoint = n / N; % the joint pmf of the two labels\r\nmarginal_2 = sum(joint,1); % row vector\r\nmarginal_1 = sum(joint,2); % column vector\r\nH1 = - sum( marginal_1 .* log2(marginal_1 + (marginal_1 == 0) ) ); % entropy of the first label\r\nH2 = - sum( marginal_2 .* log2(marginal_2 + (marginal_2 == 0) ) ); % entropy of the second label\r\nMI = sum(sum( joint .* log2_quotient( joint, marginal_1*marginal_2 ) )); % mutual information\r\nvi = H1 + H2 - 2 * MI; \r\n\r\nfunction lq = log2_quotient( A, B )\r\nlq = log2( (A + ((A==0).*B) + (B==0)) ./ (B + (B==0)) );\r\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "evaluateBenchmark.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/evaluateBenchmark.m", "size": 3028, "source_encoding": "utf_8", "md5": "2cd7527838b5de205f404cb1fa2b2e8e", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% evaluateBenchmark(filename, varargin)\n%\n% Creates and shows evaluation of the results of a prior run of\n% runBenchmark. Evaluation includes boundary recall, undersegmentation\n% erros and runtime.Most parameters (e.g. path of the stored benchmark \n% results) come from a bpf-file.\n%\n% 'PR_scheme' ... 'line', 'points', 'contours', 'areas'\n% 'names' ... names for the legend (cell array of string included in the plots (e.g. names of the\n% algorithms))\n%\nfunction evaluateBenchmark(filename, varargin)\n\n % parse input\n ip = inputParser;\n ip.addOptional('PR_scheme', 'line');\n ip.addOptional('names', 'result');\n ip.parse(varargin{:});\n \n % recall-#Segments\n nrFig = figure(); \n prepareBoundaryRecallPlot();\n \n % undersegmentation error-#Segments\n nuFig = figure(); \n prepareUndersegmentationErrorPlot();\n \n % time\n tFig = figure();\n prepareRuntimePlot(1);\n \n \n % show files\n if iscell(filename)\n % prepare plot handles\n nrHandles = zeros(length(filename), 1);\n nuHandles = zeros(length(filename), 1);\n tHandles = zeros(length(filename), 1); \n \n [colors ls] = getHighContrastColormap;\n for i=1:length(filename)\n [~, nrHandles(i)] = evalBPF_plot(filename{i},'figure', nrFig, 'metric', 'boundary_recall', 'color', colors(i,:), 'lineStyle', ls{i}, 'nameFlag', 0);\n [~, nuHandles(i)] = evalBPF_plot(filename{i},'figure', nuFig, 'metric', 'undersegmentation', 'color', colors(i,:), 'lineStyle', ls{i}, 'nameFlag', 0);\n [~, tHandles(i)] = evalBPF_plot(filename{i},'figure', tFig, 'metric', 'runtime', 'color', colors(i,:), 'lineStyle', ls{i}, 'nameFlag', 0);\n end\n \n % legend\n figure(nrFig); legend( nrHandles, ip.Results.names, 'Location','SouthEast');\n figure(nuFig); legend( nuHandles, ip.Results.names);\n figure(tFig); legend( tHandles, ip.Results.names);\n \n end\n % just plot\n evalBPF_plot(filename,'figure', nrFig, 'metric', 'boundary_recall','nameFlag', 0);\n evalBPF_plot(filename,'figure', nuFig, 'metric', 'undersegmentation', 'nameFlag', 0);\n evalBPF_plot(filename,'figure', tFig, 'metric', 'runtime', 'nameFlag', 0);\n \nend\n\n\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "getUndersegmentationError.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/getUndersegmentationError.m", "size": 3518, "source_encoding": "utf_8", "md5": "9444ac362cac13431efcd14eec863ed4", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% [undersegError undersegErrorTP undersegErrorSLIC] = getUndersegmentationError(S, GT)\n%\n% Compute undersegmentation errors described in Turbopixel and SLIC paper\n% and the new parameter free version \n%\n% S ... input segmentation (multi label image)\n% GT ... input ground truth segmentation (multi label image)\n%\n% undersegError ... (output) proposed undersegmentation error\n% undersegErrorTP ... (output) Turbopixel undersegmentation error \n% undersegError ... (output) SLIC undersegmentation error \n%\nfunction [undersegError undersegErrorTP undersegErrorSLIC] = getUndersegmentationError(S, GT)\n\n % check image sizes\n [hS wS cS] = size(S);\n [hGT wGT cGT] = size(GT);\n if hS~=hGT || wS~= wGT || cS~=1 || cGT~=1\n fprintf('Size error in getUndersegmentationError\\n');\n return;\n end\n\n % segment index should start with 1\n if min(S(:)) == 0\n S=S+1;\n end\n \n % number of segments in S and GT\n nS = double(max(S(:)));\n nGT = double(max(GT(:))); \n \n % prepare intersection matrix: M(i,j) = overlapping of GT==i and S==j\n % prepare areas of segments of S and GT\n areaS = zeros(nS,1); \n areaGT = zeros(nGT,1); \n M = zeros(nGT, nS);\n for y=1:hGT\n for x=1:wGT\n i = GT(y,x);\n j = S(y,x);\n M(i, j) = M(i,j) + 1;\n areaGT(i) = areaGT(i)+1;\n areaS(j) = areaS(j)+1;\n end\n end\n \n % proposed equation\n sum_undersegError = 0;\n for i=1:nGT\n idx = find(M(i,:)); % index of all non zero entries in this row\n for j=idx\n sum_undersegError = sum_undersegError + min(M(i,j), areaS(j)-M(i,j)); \n end \n end \n undersegError = sum_undersegError / numel(GT); \n\n\n % turbopixel equation\n sum_undersegError = 0;\n for i=1:nGT\n sum_covering_sp = 0;\n idx = find(M(i,:)); % index of all non zero entries in this row\n for j=idx\n sum_covering_sp = sum_covering_sp + areaS(j); \n end\n sum_undersegError = sum_undersegError + (sum_covering_sp-areaGT(i))/areaGT(i); \n end\n undersegErrorTP = sum_undersegError / nGT;\n\n \n % SLIC equation\n b=0.05; % minimum overlap is 5%\n sum_undersegError = 0;\n for i=1:nGT\n thresh = b*areaGT(i);\n sum_covering_sp = 0;\n idx = find(M(i,:)); % index of all non zero entries in this row\n for j=idx\n if areaS(j)>thresh\n sum_covering_sp = sum_covering_sp + areaS(j); \n end\n end\n sum_undersegError = sum_undersegError + sum_covering_sp; \n end\n undersegErrorSLIC = (sum_undersegError-wS*hS) / (wS*hS);\n \nend\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "evalBPF_plot.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/evalBPF_plot.m", "size": 4257, "source_encoding": "utf_8", "md5": "c2f73f68f7f3d095d58ea9baec1ac8f5", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% [fig_handle plot_handle] = evalBPF_plot(filename, varargin)\n% \n% Plot benchmark results (boundary recall, undersegmentation error or\n% runtime) of a BPF. Called after runAlgorithm and runBenchmark. See\n% evaluateBenchmark.m for example usage.\n%\n% filename ... input benchmark parameter filename (bpf-file)\n% 'lineStyle' ... line style of the curve\n% 'color' ... color of the plots\n% 'figure' ... handle of the figure to draw on (otherwise a new figure is\n% created)\n% 'metric' ... 'boundary_recall'\n% 'undersegmentation'\n% 'runtime'\n% 'nameFlag' ... if true, the names from the BPF file are shown \n%\nfunction [fig_handle plot_handle] = evalBPF_plot(filename, varargin)\n\n \n % parse input\n ip = inputParser;\n ip.addOptional('figure', []);\n ip.addOptional('color', 'k');\n ip.addOptional('lineStyle', '-');\n ip.addOptional('metric', 'boundary_recall');\n ip.addOptional('nameFlag', 0);\n ip.parse(varargin{:});\n \n % prepare figure or use existing figure given by parameter\n if isempty(ip.Results.figure)\n fig_handle = figure();\n hold on;\n grid on;\n else\n fig_handle = figure(ip.Results.figure);\n end\n \n % parse benchmark parameter file\n p = parseBenchmarkParameterFile(filename);\n \n % build parameterSetNames by using all parameter set names from\n % benchmark parameter file \n parameterSetNames = cell(length(p.parameterset),1);\n for parameterset_idx=1:length(p.parameterset)\n parameterSetNames{parameterset_idx} = p.parameterset{parameterset_idx}.name;\n end\n \n % for each entry in parameterSetNames: load results from disk and\n % collect data\n E = [];\n for i=1:length(parameterSetNames)\n % load from disk\n loadPath = fullfile(p.algResSavePath, parameterSetNames{i}, 'benchmarkResult.mat'); \n benchmarkResult = load(loadPath);\n \n % number of segments\n E(i).x = mean(benchmarkResult.imNSegments);\n \n if strcmp(ip.Results.metric, 'boundary_recall')\n % store average recall for later plotting of curve \n E(i).y = mean(benchmarkResult.imRecall); \n elseif strcmp(ip.Results.metric, 'undersegmentation')\n % store average undersegmentation error for later plotting of curve\n E(i).y = mean(benchmarkResult.imUnderseg); \n elseif strcmp(ip.Results.metric, 'runtime')\n % store average runtime and nSegments for later plotting of curve\n E(i).y = mean(benchmarkResult.imRuntime); \n end\n end\n \n % plot curve\n yVec = cell2mat({E(:).y});\n xVec = cell2mat({E(:).x});\n plot_handle = plot(xVec, yVec, 'color', ip.Results.color, 'marker', 'o'); \n plot_handle = plot(xVec, yVec, 'color', ip.Results.color, 'LineStyle', ip.Results.lineStyle);\n \n % show names\n if ip.Results.nameFlag\n if ~isempty(ip.Results.namesColor)\n for i=1:length(E)\n text(E(i).x,E(i).y,[' ' parameterSetNames{i}],...\n 'Clipping', 'on', ...\n 'Interpreter', 'non', ...\n 'color', ip.Results.namesColor);\n end\n else\n for i=1:length(E)\n text(E(i).x,E(i).y,[' ' parameterSetNames{i}],...\n 'Clipping', 'on', ...\n 'Interpreter', 'non', ...\n 'color', colors(i,:));\n end\n end\n end\n \nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "loadBSDS500.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/loadBSDS500.m", "size": 4204, "source_encoding": "utf_8", "md5": "52364326e75d055255c2d778ba9afef6", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% [images gt names] = loadBSDS500(BSDS500_root, mode, 'n', n, 'idx', idx)\n%\n% Load images and corresponding ground truth from BSDS500 dataset\n%\n% parameters:\n% BSDS500_root ... BSDS500 root directory path\n% mode ... 'train' or 'val' or 'test'\n% \n% varargin:\n% 'n' ... number of images to load (first n images)\n% 'idx' ... index of single image to load (index can vary on different\n% machines or operating systems)\n% 'name' ... name of single image to load (without file extension) e.g. '100007'\n% \n% return values:\n% if no 'idx' is given: \n% returns cell arrays with images and ground truth\n% otherwise\n% returns image, ground truth and name of image with index idx\n%\n% example usage:\n% [images gt names] = loadBSDS500('./', 'test', 'n', 100);\n% returns cell array with the first 100 images, ground truth data and\n% image names\n%\nfunction [images gt names] = loadBSDS500(BSDS500_root, mode, varargin)\n\n if isempty(BSDS500_root)\n BSDS500_root = '/home/nepe/etit_arbeit/data_sets/bsds500/BSR/BSDS500/data';\n end\n\n % parse input\n ip = inputParser;\n ip.addOptional('n', []);\n ip.addOptional('idx', []);\n ip.addOptional('name', []);\n ip.parse(varargin{:});\n\n % image files\n image_files = dir(fullfile(BSDS500_root,'images', mode, '*.jpg'));\n\n % number of images\n if isempty(ip.Results.n)\n n=length(image_files);\n else\n n=min(ip.Results.n, length(image_files));\n end\n \n % if no special index was given, load n images\n if isempty(ip.Results.idx) & isempty(ip.Results.name)\n \n % prepare storage\n images = cell(n,1);\n gt = cell(n,1);\n names = cell(n,1);\n\n % load images and ground truth \n fprintf('load %4d of %4d', 10, n);\n for i=1:n\n if mod(i,10) == 0 \n fprintf('\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b');\n fprintf('load %4d of %4d', i, n);\n end\n images{i} = imread( fullfile(BSDS500_root,'images', mode, image_files(i).name) );\n gt{i} = load( fullfile(BSDS500_root,'groundTruth', mode, [image_files(i).name(1:end-4) '.mat']));\n names{i} = image_files(i).name(1:end-4);\n end\n fprintf('\\n');\n \n elseif ~isempty(ip.Results.name)\n % load image with name name \n [images gt names] = loadBSDS500perName(BSDS500_root, mode, ip.Results.name);\n \n elseif ~isempty(ip.Results.idx)\n % just load the image with index idx\n [images gt names] = loadBSDS500perIdx(BSDS500_root, mode, ip.Results.idx);\n end\nend\n\n% load image with index index\nfunction [image gt name] = loadBSDS500perIdx(BSDS500_root, mode, idx)\n \n % image files\n image_files = dir(fullfile(BSDS500_root,'images', mode, '*.jpg'));\n \n % load\n image = imread( fullfile(BSDS500_root,'images', mode, image_files(idx).name) );\n gt = load( fullfile(BSDS500_root,'groundTruth', mode, [image_files(idx).name(1:end-4) '.mat']));\n name = image_files(idx).name(1:end-4);\nend\n\n% load image with index index\nfunction [image gt name] = loadBSDS500perName(BSDS500_root, mode, name)\n \n % image files\n image_files = dir(fullfile(BSDS500_root,'images', mode, '*.jpg'));\n \n % load\n image = imread( fullfile(BSDS500_root,'images', mode, [name '.jpg']) );\n gt = load( fullfile(BSDS500_root,'groundTruth', mode, [name '.mat']));\n \nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "parseBenchmarkParameterFile.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/parseBenchmarkParameterFile.m", "size": 2971, "source_encoding": "utf_8", "md5": "92c52df00bdcbef27314d96c0224b909", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% p = parseBenchmarkParameterFile(filename)\n% \n% parse file with parameters for benchmark\n% available benchmark parameters\n% \tBSDSroot\n% \tmode\n% \tparameterset\n% \tsaveImPath\n% \tsaveBenchResPath\n% algorithmCommand (->executed using \"eval\")\n%\nfunction p = parseBenchmarkParameterFile(filename)\n infile = fopen(filename,'rt');\n p.parameterset = {};\n \n while not(feof(infile))\n line = fgetl(infile);\n data = strread(line,'%s');\n if ~isempty(data)\n \n if strcmp(data(1), 'BSDS500_root')\n p.BSDS500_root = data{2};\n elseif strcmp(data(1), 'mode')\n p.mode = data{2};\n elseif strcmp(data(1), 'algResSavePath')\n p.algResSavePath = data{2};\n elseif strcmp(data(1), 'benchResSavePath')\n p.benchResSavePath = data{2};\n elseif strcmp(data(1), 'nImages')\n p.nImages = str2double(data{2});\n elseif strcmp(data(1), 'algorithmCommand') \n % the algorithm command is the rest of the line\n p.algorithmCommand = line(length('algorithmCommand')+2:end);\n elseif strcmp(data(1), 'parameterset')\n \n % add a (further) set of parameters, the parameters \n % are assumed to appear pairwise: \n % parameterset name1 value1 name2 value2 ...\n t=[];\n idx=1;\n for i=2:2:(length(data)-1) \n % update saveName\n if strcmp(data{i}, 'parametersetName')\n parametersetName = data{i+1};\n continue;\n end\n \n % otherwise store\n t(idx).name = data{i};\n t(idx).value = data{i+1};\n \n idx = idx+1;\n end \n newIdx = length(p.parameterset)+1;\n p.parameterset{newIdx}.params = t;\n p.parameterset{newIdx}.name = parametersetName;\n end \n \n end\n \n end\n fclose(infile);\nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "appplyTransform.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/appplyTransform.m", "size": 1740, "source_encoding": "utf_8", "md5": "136cb32ae30ebb5f94bc16ca0eeb241b", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% T = appplyTransform(I, A)\n%\n% Apply affine transformation on image. This function takes care of translations \n% by appending and removing rows and cols to obtain a coordinate system shift.\n%\n% I ... input image\n% A ... affine transform (input for maketform('affine')\n% T ... transformed image\n%\nfunction T = appplyTransform(I, A)\n\n %% make affine transform\n tform = maketform('affine',A);\n \n %% apply\n T = imtransform(I, tform, 'XYScale',1);\n\n %% to take effect of pure translations, append tx columns and ty rows\n tx = A(3,1);\n ty = A(3,2);\n \n % append first rows/cols if positive translation\n if tx>0\n T = [zeros(size(T,1), tx, size(T,3)), I];\n end\n if ty>0\n T = [zeros(ty, size(T,2), size(T,3)); T];\n end\n \n % remove first rows/cols if negative translation\n if tx<0\n T = T(:, (abs(tx)+1):size(T,2), :);\n end\n if ty<0\n T = T((abs(ty)+1):size(T,1),:, :);\n end\n \n \nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "multiLabelImage2boundaryImage.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/multiLabelImage2boundaryImage.m", "size": 1548, "source_encoding": "utf_8", "md5": "5ab8ac8b5747c8931fae12134c437401", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% boundary_image = multiLabelImage2boundaryImage(mli)\n%\n% Returns image with ones at all pixel where label in mli is different from\n% its right or bottom neighbor, otherwise the image value is zero\n%\n% mli ... input multi label image\n% boundary_image ... output boundary image\n%\nfunction boundary_image = multiLabelImage2boundaryImage(mli)\n\n % right and bottom shift images\n mli_right = mli(:, 1:size(mli,2)-1);\n mli_bottom = mli(1:size(mli,1)-1, :);\n \n % substract\n mli_h_diff = zeros(size(mli));\n mli_v_diff = zeros(size(mli));\n \n mli_h_diff(:,1:size(mli,2)-1) = (mli_right ~= mli(:, 2:size(mli,2)));\n mli_v_diff(1:size(mli,1)-1, :) = (mli_bottom ~= mli(2:size(mli,1), :));\n \n boundary_image = (mli_h_diff~=0) | (mli_v_diff~=0);\n\nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "getHighContrastColormap.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/getHighContrastColormap.m", "size": 1404, "source_encoding": "utf_8", "md5": "8471d9b6da27e728f75c6790990b6649", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% [C L] = getHighContrastColormap\n%\n% Get set of colors and line styles with high contrast\n%\n% C ... colormap\n% L ... cell array with strings of the linestyles\n%\nfunction [C L] = getHighContrastColormap\n\n values = [ \n 0.2 0.2 1;\n 1 0 0;\n 0.2 1 0.2;\n 0.5 0 0.5;\n 0.8 0.8 0;\n 0 1 1;\n 1 0 1;\n 0.6 0.6 0.6;\n 0 0 0;\n 0 0.5 0;\n 1 0.5 0];\n \n C = colormap(values);\n\n L = {'-', '-.', '--', '-', '-.', '--', '-', '-.', '--','-.', '-', '--', '-'};\nend\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "evaluateBenchmarkAffine.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/evaluateBenchmarkAffine.m", "size": 4899, "source_encoding": "utf_8", "md5": "8f7c342353d7249fb180d4ce031850a5", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% evaluateBenchmarkAffine(filenameBPF, filenameAPF, colors, lineStyles)\n%\n% Load benchmark parameter file and affine parameter file\n% and shows results of their benchmark setting.This function uses the\n% results of prior runs of runAlgorithmAffine and runBenchmarkAffine.\n% \n% filenameBPF ... input benchmark parameter filename (bpf-file)\n% filenameAPF ... input affine parameter filename (apf-file)\n% colors ... colors of the plots\n% lineStyles ... line styles of the plots\n% \nfunction evaluateBenchmarkAffine(filenameBPF, filenameAPF, colors, lineStyles)\n\n if ~iscell(filenameBPF)\n filenameBPF = {filenameBPF};\n n=1;\n else\n n = numel(filenameBPF);\n end\n\n \n if ~exist('colors', 'var')\n for i=1:n\n colors(i,:) = [1; 0; 0];\n end\n end\n \n if ~exist('lineStyles', 'var')\n for i=1:n\n lineStyles{i} = '-';\n end\n end\n \n % for each BPF\n for idx = 1:n\n if isempty(filenameBPF{idx})\n continue;\n end\n \n % load benchmark parameter files BPF, APF\n p = parseBenchmarkParameterFile(filenameBPF{idx});\n a = parseAffineParameterFile(filenameAPF);\n\n % for each parameterset \n for parameterset_idx=1:length(p.parameterset)\n\n % load results for affine set (get precision and recall vectors)\n loadPathBase = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, a.algResSavePathExtension);\n loadPath = fullfile(loadPathBase, 'benchmarkAffineResults.mat');\n if ~exist(loadPath, 'file')\n continue;\n end\n R = load(loadPath, 'R'); \n\n % compute average F for each affine set\n for i=1:numel(R.R)\n F_vec = 2*R.R{i}.precision.*R.R{i}.recall ./ (R.R{i}.precision + R.R{i}.recall);\n F(i) = mean(F_vec); \n end\n\n % rotation\n if strcmp(filenameAPF, 'apf/apf_rotation.txt')\n if exist('f_r', 'var'), f_r = figure(f_r); else f_r = figure(); end\n hold on;\n set(gca,'FontSize',14)\n grid on;\n plot([0 5 10 15 30 45 60 75 90 105 120 135 150 165 180] , [1 F], 'color', colors(idx, :), 'lineStyle', lineStyles{idx}, 'marker', '+');\n xlabel('Rotation angle in degree');\n ylabel('F');\n end\n\n % translation\n if strcmp(filenameAPF, 'apf/apf_translation.txt')\n if exist('f_t', 'var'), f_t = figure(f_t); else f_t = figure(); end\n hold on;\n set(gca,'FontSize',14)\n grid on;\n plot([1 5 10 20 25 30 40 50 60 70 80 90 100] , F, 'color', colors(idx, :), 'lineStyle', lineStyles{idx}, 'marker', '+');\n xlabel('Horizontal and Vertical Shift in Pixel');\n ylabel('F');\n end\n\n % sacle\n if strcmp(filenameAPF, 'apf/apf_scale.txt')\n if exist('f_s', 'var'), f_s = figure(f_s); else f_s = figure(); end\n F = [F(1:3), 1, F(4:6)];\n semilogx([0.25 0.5 0.6666 1 1.5 2 4] , F, 'color', colors(idx, :), 'lineStyle', lineStyles{idx}, 'marker', '+');\n hold on;\n set(gca,'FontSize',14)\n set(gca,'XTick',[0.25 0.5 0.6666 1 1.5 2 4])\n set(gca,'XTickLabel',{'0.25', '0.5', '0.66', '1', '1.5', '2', '4'})\n xlabel('Scale Factor');\n ylabel('F');\n grid on;\n end\n\n % shear\n if strcmp(filenameAPF, 'apf/apf_shear.txt')\n if exist('f_ss', 'var'), f_ss = figure(f_ss); else f_ss = figure(); end\n plot([0 0.01 0.025 0.05 0.1 0.25 0.5] , [1 F], 'color', colors(idx, :), 'lineStyle', lineStyles{idx}, 'marker', '+');\n hold on;\n set(gca,'FontSize',14)\n xlabel('Horizontal and Vertical Shear Factor');\n ylabel('F');\n grid on;\n end\n end\n end\n \n \n \nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "runAlgorithm.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/runAlgorithm.m", "size": 4212, "source_encoding": "utf_8", "md5": "4618189da95a5974bc37d4fd51526c3a", "text": "% runAlgorithm(filename)\n%\n% Load benchmark parameter file and run its algorithm and parameter\n% setting. Results are stored to disk at the location specified in the \n% bpf-file.\n%\n% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n\n%\nfunction runAlgorithm(filename)\n\n %% load benchmark parameter file\n p = parseBenchmarkParameterFile(filename);\n \n %% load benchmark images (images and their names)\n [images, ~, names] = loadBSDS500(p.BSDS500_root, p.mode, p.nImages);\n \n %% process each parameterset (run algorithm and process runtime computation)\n for parameterset_idx=1:length(p.parameterset)\n % ===== run algorithm ===\n % replace parameters in algorithmCommand string with values from p.parameterset{idx} \n % - simple string replace with check if the parameter name is unique in the command string)\n algorithmCommand = p.algorithmCommand;\n for k=1:length(p.parameterset{parameterset_idx}.params)\n \n paramName = p.parameterset{parameterset_idx}.params(k).name;\n paramValue = p.parameterset{parameterset_idx}.params(k).value;\n \n idx = strfind(algorithmCommand, paramName); \n if length(idx)~=1\n fprintf('Problem in runAlgorithm(): parameter %s was found %d times\\n', paramName, length(idx));\n fprintf('(algorithmCommand is: %s)\\n', algorithmCommand);\n return;\n end\n algorithmCommand = [algorithmCommand(1:idx-1) paramValue algorithmCommand(idx+length(paramName):end)]; \n end\n \n % create storage to save results\n savePathBase = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name); \n mkdir(savePathBase); \n \n fprintf('executing: %s\\n', algorithmCommand);\n % for each image\n for i=1:length(images)\n fprintf('working on: %d (name: %s)\\n', i, names{i});\n I = images{i};\n I_path = fullfile(p.BSDS500_root,'images', p.mode, [names{i} '.jpg']); \n \n % execute command: \n % - input is \"I\" (color, [0, 255])\n % - segmentation result is in \"S\" (integer)\n % - runtime is stored in \"time\"\n eval(algorithmCommand);\n \n % save resulting segment image\n savePath = fullfile(savePathBase, [(names{i}) '.png']); \n imwrite(S, savePath, 'bitdepth', 16);\n \n % save resulting visualization image\n saveVisPath = fullfile(savePathBase, [(names{i}) '_vis.png']); \n imwrite(imgVis, saveVisPath);\n\n % save times\n savePathTimes = fullfile(savePathBase, [(names{i}) '_time']); \n save(savePathTimes, 'time');\n end\n \n % ===== load all times, build runtimes matrix and store in runtimes.mat ====\n % storage for algorithm run times alg_times(i) is time for image i \n alg_times = zeros(length(images),1); \n for i=1:length(images)\n % load time of image i\n savePathTimes = fullfile(savePathBase, [(names{i}) '_time']); \n load_time = load(savePathTimes);\n \n % append to alg_times\n alg_times(i) = load_time.time;\n end\n \n % save times\n savePathTimes = fullfile(savePathBase, 'runtimes'); \n save(savePathTimes, 'alg_times');\n end\n\n \n \nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "prepareBoundaryRecallPlot.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/prepareBoundaryRecallPlot.m", "size": 1047, "source_encoding": "utf_8", "md5": "0dfedd840b028ac722c8288c97335509", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% prepareBoundaryRecallPlot\n% \n% Setup figure properties for plot\n%\nfunction prepareBoundaryRecallPlot\n hold on;\n set(gca,'FontSize',14); \n axis( [0 2500 0 1] );\n xlabel('Number of Segments');\n ylabel('Boundary Recall');\n ylim([0 1]);\n grid on;\nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "prepareRuntimePlot.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/prepareRuntimePlot.m", "size": 1295, "source_encoding": "utf_8", "md5": "dfcf2f99795f9f488dadece920099df6", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% prepareRuntimePlot(log_flag)\n% \n% Setup figure properties for plot\n%\n% log_flag ... logarithmic scale?\n%\nfunction prepareRuntimePlot(log_flag)\n\n % logarithmic scale?\n if exist('log_flag', 'var')>0 && log_flag==1\n semilogy(0,0);\n set(gca,'YTick',[0.1 1 10 100 1000])\n set(gca,'YTickLabel',{'0.1', '1', '10', '100', '1000'})\n end\n \n hold on;\n set(gca,'FontSize',14)\n xlabel('Number of Segments');\n ylabel('Runtime in Seconds');\n% grid on;\n axis( [0 2500 0 10000]);\nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "runAlgorithmAffine.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/runAlgorithmAffine.m", "size": 6128, "source_encoding": "utf_8", "md5": "0912b650a2eb13c9e5073c068762a415", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% runAlgorithmAffine(filenameBPF, filenameAPF)\n%\n% Load benchmark parameter file and affine parameter file\n% and segment images using their benchmark setting. Results are\n% stored to disk\n% \n% filenameBPF ... input benchmark parameter filename (bpf-file)\n% filenameAPF ... input affine parameter filename (apf-file)\n%\nfunction runAlgorithmAffine(filenameBPF, filenameAPF)\n\n %% load benchmark parameter files BPF, APF\n p = parseBenchmarkParameterFile(filenameBPF);\n a = parseAffineParameterFile(filenameAPF);\n \n \n %% load benchmark images (images and their names)\n [images, ~, names] = loadBSDS500(p.BSDS500_root, p.mode, p.nImages);\n \n %% draw border of zeros arround each image to compensate for effects\n %% caused by borders of zeros introduced by affine transformations\n bSize=10;\n for i=1:length(images) \n images{i} = [zeros(size(images{i},1),bSize,size(images{i},3)), images{i}, zeros(size(images{i},1),bSize,size(images{i},3))]; % cols\n images{i} = [zeros(bSize, size(images{i},2),size(images{i},3)); images{i}; zeros(bSize, size(images{i},2),size(images{i},3))]; % rows\n end\n \n %% process each parameterset (run algorithm and process runtime computation)\n for parameterset_idx=1:length(p.parameterset)\n % ===== run algorithm ===\n % replace parameters in algorithmCommand string with values from p.parameterset{idx} \n % - simple string replace with check if the parameter name is unique in the command string)\n algorithmCommand = p.algorithmCommand;\n for k=1:length(p.parameterset{parameterset_idx}.params)\n \n paramName = p.parameterset{parameterset_idx}.params(k).name;\n paramValue = p.parameterset{parameterset_idx}.params(k).value;\n \n idx = strfind(algorithmCommand, paramName); \n if length(idx)~=1\n fprintf('Problem in runAlgorithm(): parameter %s was found %d times\\n', paramName, length(idx));\n fprintf('(algorithmCommand is: %s)\\n', algorithmCommand);\n return;\n end\n algorithmCommand = [algorithmCommand(1:idx-1) paramValue algorithmCommand(idx+length(paramName):end)]; \n end\n fprintf('executing: %s\\n', algorithmCommand);\n \n \n % create base storage to save results\n savePathBase = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, a.algResSavePathExtension); \n mkdir(savePathBase);\n \n % create storage for original images\n savePathOriginal = fullfile(savePathBase, 'original');\n mkdir(savePathOriginal);\n \n % create storage for transformed images\n for affineSet_idx=1:length(a.affineSet) \n savePathAffine = fullfile(savePathBase, a.affineSet{affineSet_idx}.name);\n mkdir(savePathAffine);\n end\n \n % - run on image\n % - transform image\n % - run on transformed image\n % - retransform result\n % (- compare) \n % - save\n \n % for each image\n for i=1:length(images)\n fprintf('working on: %d (name: %s)\\n', i, names{i});\n I = images{i};\n \n % save temporarly for algorithms that do not use \"I\" but load from file\n I_path = fullfile(savePathOriginal, 'temp.png');\n imwrite(I, I_path);\n \n % execute command: \n % - input is \"I\" (color, [0, 255])\n % - segmentation result is in \"S\" (integer)\n % - runtime is stored in\"time\"\n eval(algorithmCommand);\n \n % save resulting segment image\n savePath = fullfile(savePathOriginal, [(names{i}) '.png']); \n imwrite(S, savePath, 'bitdepth', 16);\n \n % run on transformed images\n for j=1:length(a.affineSet)\n % get current transformation and apply on image\n A = a.affineSet{j}.a;\n I = appplyTransform(images{i}, A); \n \n % save temporarly for algorithms that do not use \"I\" but load from file\n I_path = fullfile(savePathOriginal, 'temp.png');\n imwrite(I, I_path);\n \n % execute command: \n % - input is \"I\" (color, [0, 255])\n % - segmentation result is in \"S\" (integer)\n eval(algorithmCommand);\n \n % retransform\n S_retransformed = appplyTransform(S, inv(A));\n \n % crop\n [h1 w1 c1] = size(images{i});\n [h2 w2 c2] = size(S_retransformed);\n x1 = round( 1-w1/2+w2/2 );\n y1 = round( 1-h1/2+h2/2 );\n x2 = round( w1-w1/2+w2/2 );\n y2 = round( h1-h1/2+h2/2 );\n \n S_cropped = S_retransformed( y1:y2, x1:x2 );\n \n % save\n savePath = fullfile(savePathBase, a.affineSet{j}.name, [(names{i}) '.png']); \n imwrite(S_cropped, savePath, 'bitdepth', 16);\n \n end\n \n end\n\n end\n \nend\n\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "compareBoundaryImagesSimple.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/compareBoundaryImagesSimple.m", "size": 2311, "source_encoding": "utf_8", "md5": "99a0fac1997a0290586decc67de7c40a", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% [TP FP TN FN] = compareBoundaryImagesSimple(bim1, bim2, k)\n%\n% computes true positives, false positives, true negatives and false\n% negatives from two boundary images. bim2 is regarded as ground truth\n%\n% bim1 ... boundary image\n% bim2 ... groundtruth boundary image\n% k ... maximum distance for neighbored pixel\n%\n% TP ... number of boundary pixel in bim1 in range k of boundary pixel\n% in bim2\n%\n% FP ... number of boundary pixel in bim1 that are not in range k of any\n% boundary pixel in bim2\n%\n% TN ... number of pixel not set in bim1 and not in bim2 OR not set in bim1 and set in\n% bim2 but neighbored to another set pixel in bim1 (this boundary pixel is\n% catched by another pixel in bim1, thus this pixel is okay to be negative)\n%\n% FN ... number of pixel that are not set in bim1 but in bim2 and no set \n% neighbor in range k in bim1\n%\nfunction [TP FP TN FN] = compareBoundaryImagesSimple(bim1, bim2, k)\n\n % expand boundaries to their k-neighborhod\n strel_disk = strel('disk',k);\n bim1_k = imdilate(bim1, strel_disk);\n bim2_k = imdilate(bim2, strel_disk);\n\n % positives masks\n TP_mask = bim2_k & bim1;\n FP_mask = (1-bim2_k) & bim1;\n \n % some temps\n bim2_and_bim1_k = bim2 & bim1_k;\n not_bim1 = 1-bim1;\n \n % negatives masks\n TN_mask = not_bim1 & ( (1-bim2) | bim2_and_bim1_k );\n FN_mask = not_bim1 & bim2 & (1-bim2_and_bim1_k);\n \n % count TP FP TN FN\n TP = sum(sum( TP_mask )); \n FP = sum(sum( FP_mask ));\n TN = sum(sum( TN_mask ));\n FN = sum(sum( FN_mask ));\nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "combineMultipleBoundaryImages.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/combineMultipleBoundaryImages.m", "size": 1273, "source_encoding": "utf_8", "md5": "37fbd357dd5c0be19676d8887256b024", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% combinedBim = combineMultipleBoundaryImages(bim)\n%\n% this function combined several boundary maps using OR function\n% bim ... input boundary maps in BSDS format: bim{i}.Boundaries: logical\n% combinedBim ... outpu image with 1 at pixels where there is at least\n% one 1 in the input bim\n%\nfunction combinedBim = combineMultipleBoundaryImages(bim)\n\n combinedBim = zeros(size(bim{1}.Boundaries));\n for i=2:length(bim)\n combinedBim = combinedBim | bim{i}.Boundaries;\n end\n\nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "parseAffineParameterFile.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/parseAffineParameterFile.m", "size": 2301, "source_encoding": "utf_8", "md5": "8267d58db149c3fc3266861d75fc5fd2", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% p = parseAffineParameterFile(filename)\n% \n% parse file with parameters for affine transformations\n%\n% The transformation conventions follow\n% http://www.mathworks.de/help/toolbox/images/f12-26140.html#f12-31782\n% \n% y=x*A\n%\n% e.g. translation: A=[ 1 0 0 ;\n% 0 1 0 ;\n% dx dy 1 ];\n%\n% available benchmark parameters\n% \talgResSavePathExtension ... extension to saveBenchResPath of used BPF\n% \taffine_trafo\n% affine_trafo name a11 a12 a13 a21 a22 a23 a31 a32 a33\nfunction p = parseAffineParameterFile(filename)\n infile = fopen(filename,'rt');\n p.affineSet = {};\n \n while not(feof(infile))\n line = fgetl(infile);\n data = strread(line,'%s');\n if ~isempty(data)\n \n if strcmp(data(1), 'algResSavePathExtension')\n p.algResSavePathExtension = data{2};\n elseif strcmp(data(1), 'affine_trafo') \n % add a (further) affine transformation, the trafo\n % is assumed to come in row first order:\n % affine_trafo name a11 a12 a13 a21 a22 a23 a31 a32 a33\n newIdx = length(p.affineSet)+1;\n p.affineSet{newIdx}.a = [str2num(data{3}) str2num(data{4}) str2num(data{5}); str2num(data{6}) str2num(data{7}) str2num(data{8}); str2num(data{9}) str2num(data{10}) str2num(data{11})];\n p.affineSet{newIdx}.name = data{2};\n end \n \n end\n \n end\n fclose(infile);\nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "prepareUndersegmentationErrorPlot.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/prepareUndersegmentationErrorPlot.m", "size": 1073, "source_encoding": "utf_8", "md5": "dc3fd415f896a50e8a641ec2ec23d8e9", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% prepareUndersegmentationErrorPlot\n% \n% Setup figure properties for plot\n%\nfunction prepareUndersegmentationErrorPlot()\n hold on;\n set(gca,'FontSize',14)\n xlabel('Number of Segments');\n ylabel('Undersegmentation Error');\n ylim([0 1]);\n axis( [0 3000 0.05 0.25]);\n grid on;\nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "runBenchmark.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/runBenchmark.m", "size": 4595, "source_encoding": "utf_8", "md5": "c0a212a9a28a3af874e8f85331eac9b5", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% runBenchmark(filename)\n%\n% Load benchmark parameter file and run its benchmark setting(s).\n% This function loads the results of a prior run of runAlgorithm and\n% computes the error metrics. Results are stored to disk at the location\n% specified in the bpf-file\n%\n% filename ... input benchmark parameter filename (bpf-file)\n%\nfunction runBenchmark(filename)\n\n %% load benchmark parameter file\n p = parseBenchmarkParameterFile(filename);\n \n %% load benchmark images\n [images gt names] = loadBSDS500(p.BSDS500_root, p.mode, p.nImages);\n \n % for each parameterset \n for parameterset_idx=1:length(p.parameterset)\n n = length(images);\n \n % prepare storage\n imName = zeros(n,1);\n imNSegments = zeros(n,1);\n imRecall = zeros(n,1);\n imPrecision = zeros(n,1);\n \n fprintf('working on parameter set: %s, image:%4d', p.parameterset{parameterset_idx}.name, 0);\n % for each image\n for i=1:n\n fprintf('\\b\\b\\b\\b%4d',i);\n % load algorithm result\n loadPath = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, [(names{i}) '.png']); \n S = imread(loadPath);\n \n % create boundary image from segment image\n B = multiLabelImage2boundaryImage(S);\n \n % Benchmark\n \n % TP FP TN FN\n combinedGTBim = combineMultipleBoundaryImages(gt{i}.groundTruth);\n [imTP imFP imTN imFN] = compareBoundaryImagesSimple(B, combinedGTBim, 2);\n recall = imTP/(imTP+imFN);\n precision = imTP/(imTP+imFP);\n \n % number of segments\n nSegments = max(S(:));\n \n % undersegmentation error\n sumUndersegError = 0;\n sumUndersegErrorTP = 0;\n sumUndersegErrorSLIC = 0;\n for j=1:length(gt{i}.groundTruth)\n [undersegError, undersegErrorTP, undersegErrorSLIC] = getUndersegmentationError(S, gt{i}.groundTruth{j}.Segmentation);\n sumUndersegError = sumUndersegError + undersegError;\n sumUndersegErrorTP = sumUndersegErrorTP + undersegErrorTP;\n sumUndersegErrorSLIC = sumUndersegErrorSLIC + undersegErrorSLIC; \n end\n undersegError = sumUndersegError/length(gt{i}.groundTruth);\n undersegErrorTP = sumUndersegErrorTP/length(gt{i}.groundTruth);\n undersegErrorSLIC = sumUndersegErrorSLIC/length(gt{i}.groundTruth);\n \n \n % store result for this image\n imName(i) = str2double(names{i});\n imNSegments(i) = nSegments;\n imRecall(i) = recall;\n imPrecision(i) = precision;\n imUnderseg(i) = undersegError;\n imUndersegTP(i) = undersegErrorTP;\n imUndersegSLIC(i) = undersegErrorSLIC;\n end\n fprintf('\\n');\n \n % load runtimes\n loadPath = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, 'runtimes.mat'); \n if exist(loadPath)\n runtimes = load(loadPath);\n imRuntime = runtimes.alg_times;\n\n % store to disk\n savePath = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, 'benchmarkResult.mat'); \n save(savePath, 'imName', 'imNSegments', 'imRecall', 'imPrecision', 'imUnderseg', 'imUndersegTP', 'imUndersegSLIC', 'imRuntime');\n else \n % store to disk\n savePath = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, 'benchmarkResult.mat'); \n save(savePath, 'imName', 'imNSegments', 'imRecall', 'imPrecision', 'imUnderseg', 'imUndersegTP', 'imUndersegSLIC');\n end\n \n end\n \nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "main_benchmark.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/main_benchmark.m", "size": 1035, "source_encoding": "utf_8", "md5": "55a73cbba20c008454601d4acf362374", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% main_benchmark(bpf_filename)\n%\n% process the 3 benchmarks steps: run algorithm, run benchmark and evaluate\n% benchmark\nfunction main_benchmark(bpf_filename)\n\n %runAlgorithm(bpf_filename)\n %runBenchmark(bpf_filename)\n evaluateBenchmark(bpf_filename)\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "runBenchmarkAffine.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/runBenchmarkAffine.m", "size": 6551, "source_encoding": "utf_8", "md5": "7a104dfee4b51baf5500842eeeee398e", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% runBenchmarkAffine(filenameBPF, filenameAPF)\n%\n% Load benchmark parameter file and affine parameter filename and run their\n% benchmark setting(s).\n% This function loads the results of a prior run of runAlgorithmAffine and\n% computes the error metrics. Results are stored to disk at the location\n% specified in the parameter files\n%\n% filenameBPF ... input benchmark parameter filename (bpf-file)\n% filenameAPF ... input affine parameter filename (apf-file)\n%\nfunction runBenchmarkAffine(filenameBPF, filenameAPF)\n\n %% load benchmark parameter files BPF, APF\n p = parseBenchmarkParameterFile(filenameBPF);\n a = parseAffineParameterFile(filenameAPF);\n \n \n %% load benchmark images\n [images gt names] = loadBSDS500(p.BSDS500_root, p.mode, p.nImages);\n \n % for each parameterset \n for parameterset_idx=1:length(p.parameterset)\n \n fprintf('working on parameter set: %s, image:%4d', p.parameterset{parameterset_idx}.name, 0);\n \n loadPathBase = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, a.algResSavePathExtension);\n \n % for each affine set \n for j=1:length(a.affineSet)\n recall = zeros(p.nImages, 1);\n precision = zeros(p.nImages, 1);\n % for each image\n for i=1:p.nImages\n % load original image result and create boundary map\n loadPath = fullfile(loadPathBase, 'original', [(names{i}) '.png']); \n S_ori = imread(loadPath);\n B_ori = multiLabelImage2boundaryImage(S_ori);\n B_ori = bwmorph(B_ori,'skel',Inf);\n \n % load transformed image result and create boundary map\n loadPath = fullfile(loadPathBase, a.affineSet{j}.name, [(names{i}) '.png']); \n S_t = imread(loadPath);\n B_t = multiLabelImage2boundaryImage(S_t);\n \n % extra thinning step\n B_t = bwmorph(B_t,'skel',Inf);\n \n % compare: Precision-Recall on boundary image\n [imTP imFP imTN imFN] = compareBoundaryImagesSimple(B_t, B_ori, 2);\n recall(i) = imTP/(imTP+imFN);\n precision(i) = imTP/(imTP+imFP);\n \n end\n % combine results for this affine transformation\n R{j}.name = a.affineSet{j}.name;\n R{j}.recall = recall;\n R{j}.precision = precision; \n end\n \n % store results for this affine set\n savePath = fullfile(loadPathBase, 'benchmarkAffineResults.mat');\n save(savePath, 'R');\n \n end\n \n fprintf('\\n');\n \n% %<<<<<<<<<<<<<\n% \n% % for each image\n% for i=1:n\n% fprintf('\\b\\b\\b\\b%4d',i);\n% % load algorithm result\n% loadPath = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, [(names{i}) '.png']); \n% S = imread(loadPath);\n% \n% % create boundary image from segment image\n% B = multiLabelImage2boundaryImage(S);\n% \n% % Benchmark\n% \n% % TP FP TN FN\n% combinedGTBim = combineMultipleBoundaryImages(gt{i}.groundTruth);\n% [imTP imFP imTN imFN] = compareBoundaryImagesSimple(B, combinedGTBim, 2);\n% recall = imTP/(imTP+imFN);\n% precision = imTP/(imTP+imFP);\n% \n% % number of segments\n% nSegments = max(S(:));\n% \n% % undersegmentation error\n% sumUndersegError = 0;\n% sumUndersegErrorTP = 0;\n% sumUndersegErrorSLIC = 0;\n% for j=1:length(gt{i}.groundTruth)\n% [undersegError, undersegErrorTP, undersegErrorSLIC] = getUndersegmentationError(S, gt{i}.groundTruth{j}.Segmentation);\n% sumUndersegError = sumUndersegError + undersegError;\n% sumUndersegErrorTP = sumUndersegErrorTP + undersegErrorTP;\n% sumUndersegErrorSLIC = sumUndersegErrorSLIC + undersegErrorSLIC; \n% end\n% undersegError = sumUndersegError/length(gt{i}.groundTruth);\n% undersegErrorTP = sumUndersegErrorTP/length(gt{i}.groundTruth);\n% undersegErrorSLIC = sumUndersegErrorSLIC/length(gt{i}.groundTruth);\n% \n% \n% % store result for this image\n% imName(i) = str2double(names{i});\n% imNSegments(i) = nSegments;\n% imRecall(i) = recall;\n% imPrecision(i) = precision;\n% imUnderseg(i) = undersegError;\n% imUndersegTP(i) = undersegErrorTP;\n% imUndersegSLIC(i) = undersegErrorSLIC;\n% end\n% fprintf('\\n');\n% \n% % load runtimes\n% loadPath = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, 'runtimes.mat'); \n% if exist(loadPath)\n% runtimes = load(loadPath);\n% imRuntime = runtimes.alg_times;\n% \n% % store to disk\n% savePath = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, 'benchmarkResult.mat'); \n% save(savePath, 'imName', 'imNSegments', 'imRecall', 'imPrecision', 'imUnderseg', 'imUndersegTP', 'imUndersegSLIC', 'imRuntime');\n% else \n% % store to disk\n% savePath = fullfile(p.algResSavePath, p.parameterset{parameterset_idx}.name, 'benchmarkResult.mat'); \n% save(savePath, 'imName', 'imNSegments', 'imRecall', 'imPrecision', 'imUnderseg', 'imUndersegTP', 'imUndersegSLIC');\n% end\n% \n% end\n \nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "main_runAffine.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/main_runAffine.m", "size": 1517, "source_encoding": "utf_8", "md5": "189214808bddc7ab035aaf0b6701acbf", "text": "% Superpixel Benchmark\n% Copyright (C) 2012 Peer Neubert, peer.neubert@etit.tu-chemnitz.de\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% -------------------------------------\n%\n% main_runAffine(bpf_filename)\n%\n% Run algorithm on transformed images for several affine transformations\n% and benchmark\n%\n% bpf_filename ... input benchmark parameter filename (bpf-file)\n%\nfunction main_runAffine(bpf_filename)\n\n runAlgorithmAffine(bpf_filename, 'apf/apf_translation.txt');\n runBenchmarkAffine(bpf_filename, 'apf/apf_translation.txt');\n \n runAlgorithmAffine(bpf_filename, 'apf/apf_rotation.txt');\n runBenchmarkAffine(bpf_filename, 'apf/apf_rotation.txt');\n \n runAlgorithmAffine(bpf_filename, 'apf/apf_shear.txt'); \n runBenchmarkAffine(bpf_filename, 'apf/apf_shear.txt');\n\n runAlgorithmAffine(bpf_filename, 'apf/apf_scale.txt');\n runBenchmarkAffine(bpf_filename, 'apf/apf_scale.txt');\n \nend"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "segment_box.m", "ext": ".m", "path": "cs543_hw-master/HM4/hw4_supp/hw4_supp/p1/superpixel_benchmark/segmentation_algorithms/segment_box.m", "size": 952, "source_encoding": "utf_8", "md5": "068d2a097e0422d88582129cec7a3ff1", "text": "% [S time] = segment_box(image, n)\n% \n% Perfom box segmentation\n%\n% Parameters\n% image ... Matlab image\n% n ... (approximate) number of superpixels \n%\n% Returns\n% S ... segment image\n% time ... execution time im ms of algorithm \n%\nfunction [S time] = segment_box(image,n)\n \n if ~exist('n','var') | isempty(n), n = 100; end\n \n % execute \n tic();\n \n [h w c] = size(image); \n B = zeros(h,w);\n \n ny = sqrt( n*h/w);\n nx = n/ny;\n \n dx = w/nx;\n dy = h/ny;\n \n for i=dx:dx:(w-dx)\n B(:, round(i)) = 255;\n end\n \n for i=dy:dy:(h-dy)\n B(round(i), :) = 255;\n end\n time = toc();\n \n % create multi-label-image\n S = uint16(boundaryImage2multiLabelImage(B));\n \nend\n\nfunction mli = boundaryImage2multiLabelImage(bim)\n inv_bim = max(bim(:))-bim;\n label_im = bwlabel(inv_bim,4);\n mli = imclose( label_im, strel([1 1 1; 1 1 1; 1 1 1]));\nend\n"} +{"plateform": "github", "repo_name": "liuxianming/cs543_hw-master", "name": "plotmatches.m", "ext": ".m", "path": "cs543_hw-master/HM3/hw3_codes/prob3/plotmatches.m", "size": 10221, "source_encoding": "utf_8", "md5": "a701b7d74819dd725219aa884d6f7f18", "text": "function h=plotmatches(I1,I2,P1,P2,matches,varargin)\n% PLOTMATCHES Plot keypoint matches\n% PLOTMATCHES(I1,I2,P1,P2,MATCHES) plots the two images I1 and I2\n% and lines connecting the frames (keypoints) P1 and P2 as specified\n% by MATCHES.\n%\n% P1 and P2 specify two sets of frames, one per column. The first\n% two elements of each column specify the X,Y coordinates of the\n% corresponding frame. Any other element is ignored.\n%\n% MATCHES specifies a set of matches, one per column. The two\n% elementes of each column are two indexes in the sets P1 and P2\n% respectively.\n%\n% The images I1 and I2 might be either both grayscale or both color\n% and must have DOUBLE storage class. If they are color the range\n% must be normalized in [0,1].\n%\n% The function accepts the following option-value pairs:\n%\n% 'Stacking' ['h']\n% Stacking of images: horizontal ['h'], vertical ['v'], diagonal\n% ['h'], overlap ['o']\n%\n% 'Interactive' [0]\n% If set to 1, starts the interactive session. In this mode the\n% program lets the user browse the matches by moving the mouse:\n% Click to select and highlight a match; press any key to end.\n% If set to a value greater than 1, the feature matches are not\n% drawn at all (useful for cluttered scenes).\n%\n% See also PLOTSIFTDESCRIPTOR(), PLOTSIFTFRAME(), PLOTSS().\n\n% AUTORIGHTS\n% Copyright (c) 2006 The Regents of the University of California.\n% All Rights Reserved.\n% \n% Created by Andrea Vedaldi\n% UCLA Vision Lab - Department of Computer Science\n% \n% Permission to use, copy, modify, and distribute this software and its\n% documentation for educational, research and non-profit purposes,\n% without fee, and without a written agreement is hereby granted,\n% provided that the above copyright notice, this paragraph and the\n% following three paragraphs appear in all copies.\n% \n% This software program and documentation are copyrighted by The Regents\n% of the University of California. The software program and\n% documentation are supplied \"as is\", without any accompanying services\n% from The Regents. The Regents does not warrant that the operation of\n% the program will be uninterrupted or error-free. The end-user\n% understands that the program was developed for research purposes and\n% is advised not to rely exclusively on the program for any reason.\n% \n% This software embodies a method for which the following patent has\n% been issued: \"Method and apparatus for identifying scale invariant\n% features in an image and use of same for locating an object in an\n% image,\" David G. Lowe, US Patent 6,711,293 (March 23,\n% 2004). Provisional application filed March 8, 1999. Asignee: The\n% University of British Columbia.\n% \n% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY\n% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,\n% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND\n% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN\n% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF\n% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT\n% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN \"AS IS\"\n% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE\n% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n% --------------------------------------------------------------------\n% Check the arguments\n% --------------------------------------------------------------------\n\nstack='h' ;\ninteractive=0 ;\nonly_interactive=0 ;\n\nfor k=1:2:length(varargin)\n switch lower(varargin{k})\n case 'stacking'\n stack=varargin{k+1} ;\n case 'interactive'\n interactive=varargin{k+1};\n otherwise\n error(['[Unknown option ''', varargin{k}, '''.']) ; \n end\nend\n \n% --------------------------------------------------------------------\n% Do the job\n% --------------------------------------------------------------------\n\n[M1,N1,K1]=size(I1) ;\n[M2,N2,K2]=size(I2) ;\n\nswitch stack\n case 'h'\n N3=N1+N2 ;\n M3=max(M1,M2) ;\n oj=N1 ;\n oi=0 ;\n case 'v'\n M3=M1+M2 ;\n N3=max(N1,N2) ;\n oj=0 ;\n oi=M1 ; \n case 'd'\n M3=M1+M2 ;\n N3=N1+N2 ;\n oj=N1 ;\n oi=M1 ;\n case 'o'\n M3=max(M1,M2) ;\n N3=max(N1,N2) ;\n oj=0;\n oi=0;\n otherwise\n error(['Unkown stacking type '''], stack, ['''.']) ;\nend\n\n% Combine the two images. In most cases just place one image next to\n% the other. If the stacking is 'o', however, combine the two images\n% linearly.\nI=zeros(M3,N3,K1) ;\nif stack ~= 'o'\n I(1:M1,1:N1,:) = I1 ;\n I(oi+(1:M2),oj+(1:N2),:) = I2 ;\nelse\n I(oi+(1:M2),oj+(1:N2),:) = I2 ;\n I(1:M1,1:N1,:) = I(1:M1,1:N1,:) + I1 ;\n I(1:min(M1,M2),1:min(N1,N2),:) = 0.5 * I(1:min(M1,M2),1:min(N1,N2),:) ;\nend\n\naxes('Position', [0 0 1 1]) ;\nimagesc(I) ; colormap gray ; hold on ; axis image ; axis off ;\n\nK = size(matches, 2) ;\nnans = NaN * ones(1,K) ;\n\nx = [ P1(1,matches(1,:)) ; P2(1,matches(2,:))+oj ; nans ] ;\ny = [ P1(2,matches(1,:)) ; P2(2,matches(2,:))+oi ; nans ] ;\n\n% if interactive > 1 we do not drive lines, but just points.\nif(interactive > 1)\n h = plot(x(:),y(:),'g.') ;\nelse\n h = line(x(:)', y(:)') ;\nend\nset(h,'Marker','.','Color','g') ;\n\n% --------------------------------------------------------------------\n% Interactive\n% --------------------------------------------------------------------\n\nif(~interactive), return ; end\n\nsel1 = unique(matches(1,:)) ;\nsel2 = unique(matches(2,:)) ;\n\nK1 = length(sel1) ; %size(P1,2) ;\nK2 = length(sel2) ; %size(P2,2) ;\nX = [ P1(1,sel1) P2(1,sel2)+oj ;\n P1(2,sel1) P2(2,sel2)+oi ; ] ;\n\nfig = gcf ;\nis_hold = ishold ;\nhold on ;\n\n% save the handlers for later to restore\ndhandler = get(fig,'WindowButtonDownFcn') ;\nuhandler = get(fig,'WindowButtonUpFcn') ;\nmhandler = get(fig,'WindowButtonMotionFcn') ;\nkhandler = get(fig,'KeyPressFcn') ;\npointer = get(fig,'Pointer') ;\n\nset(fig,'KeyPressFcn', @key_handler) ;\nset(fig,'WindowButtonDownFcn',@click_down_handler) ;\nset(fig,'WindowButtonUpFcn', @click_up_handler) ;\nset(fig,'Pointer','crosshair') ;\n\ndata.exit = 0 ; % signal exit to the interactive mode\ndata.selected = [] ; % currently selected feature\ndata.X = X ; % feature anchors\n\nhighlighted = [] ; % currently highlighted feature\nhh = [] ; % hook of the highlight plot\n\nguidata(fig,data) ;\nwhile ~ data.exit\n uiwait(fig) ;\n data = guidata(fig) ;\n if(any(size(highlighted) ~= size(data.selected)) || ...\n any(highlighted ~= data.selected) ) \n\n highlighted = data.selected ;\n\n % delete previous highlight\n if( ~isempty(hh) )\n delete(hh) ;\n end\n\n hh=[] ;\n \n % each selected feature uses its own color\n c=1 ;\n colors=[1.0 0.0 0.0 ;\n 0.0 1.0 0.0 ;\n 0.0 0.0 1.0 ;\n 1.0 1.0 0.0 ;\n 0.0 1.0 1.0 ;\n 1.0 0.0 1.0 ] ;\n \n % more than one feature might be seleted at one time...\n for this=highlighted\n\n % find matches\n if( this <= K1 ) \n sel=find(matches(1,:)== sel1(this)) ;\n else\n sel=find(matches(2,:)== sel2(this-K1)) ;\n end \n K=length(sel) ;\n \n % plot matches\n x = [ P1(1,matches(1,sel)) ; P2(1,matches(2,sel))+oj ; nan*ones(1,K) ] ;\n y = [ P1(2,matches(1,sel)) ; P2(2,matches(2,sel))+oi ; nan*ones(1,K) ] ;\n \n hh = [hh line(x(:)', y(:)',...\n 'Marker','*',...\n 'Color',colors(c,:),...\n 'LineWidth',3)];\n \n if( size(P1,1) == 4 )\n f1 = unique(P1(:,matches(1,sel))','rows')' ;\n hp=plotsiftframe(f1);\n set(hp,'Color',colors(c,:)) ;\n hh=[hh hp] ; \n end\n \n if( size(P2,1) == 4 )\n f2 = unique(P2(:,matches(2,sel))','rows')' ;\n f2(1,:)=f2(1,:)+oj ;\n f2(2,:)=f2(2,:)+oi ;\n hp=plotsiftframe(f2);\n set(hp,'Color',colors(c,:)) ;\n hh=[hh hp] ; \n end\n \n c=c+1 ;\n end\n \n drawnow ;\n end\nend\n\nif( ~isempty(hh) )\n delete(hh) ;\nend\n\nif ~is_hold\n hold off ; \nend\n\nset(fig,'WindowButtonDownFcn', dhandler) ;\nset(fig,'WindowButtonUpFcn', uhandler) ;\nset(fig,'WindowButtonMotionFcn',mhandler) ;\nset(fig,'KeyPressFcn', khandler) ;\nset(fig,'Pointer', pointer ) ;\n\n% ====================================================================\nfunction data=selection_helper(data)\n% --------------------------------------------------------------------\nP = get(gca, 'CurrentPoint') ;\nP = [P(1,1); P(1,2)] ;\n\nd = (data.X(1,:) - P(1)).^2 + (data.X(2,:) - P(2)).^2 ;\ndmin=min(d) ;\nidx=find(d==dmin) ;\n\ndata.selected = idx ;\n\n% ====================================================================\nfunction click_down_handler(obj,event)\n% --------------------------------------------------------------------\n% select a feature and change motion handler for dragging\n\n[obj,fig]=gcbo ;\ndata = guidata(fig) ;\ndata.mhandler = get(fig,'WindowButtonMotionFcn') ;\nset(fig,'WindowButtonMotionFcn',@motion_handler) ;\ndata = selection_helper(data) ;\nguidata(fig,data) ;\nuiresume(obj) ;\n\n% ====================================================================\nfunction click_up_handler(obj,event)\n% --------------------------------------------------------------------\n% stop dragging\n\n[obj,fig]=gcbo ;\ndata = guidata(fig) ;\nset(fig,'WindowButtonMotionFcn',data.mhandler) ;\nguidata(fig,data) ;\nuiresume(obj) ;\n\n% ====================================================================\nfunction motion_handler(obj,event)\n% --------------------------------------------------------------------\n% select features while dragging\n\ndata = guidata(obj) ;\ndata = selection_helper(data); \nguidata(obj,data) ;\nuiresume(obj) ;\n\n% ====================================================================\nfunction key_handler(obj,event)\n% --------------------------------------------------------------------\n% use keypress to exit\n\ndata = guidata(gcbo) ;\ndata.exit = 1 ;\nguidata(obj,data) ;\nuiresume(gcbo) ;\n\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "gen_7_5_kHz.m", "ext": ".m", "path": "openairinterface5g-master/openair1/PHY/MODULATION/gen_7_5_kHz.m", "size": 3298, "source_encoding": "utf_8", "md5": "a08e730b234a112cbf6aac5b44c3af8b", "text": "\nfunction [] = gen_7_5_kHz()\n[s6_n2, s6_e2] = gen_sig(6);\n[s15_n2, s15_e2] = gen_sig(15);\n[s25_n2, s25_e2] = gen_sig(25);\n[s50_n2, s50_e2] = gen_sig(50);\n[s75_n2, s75_e2] = gen_sig(75);\n[s100_n2, s100_e2] = gen_sig(100);\n\n\nfd=fopen(\"kHz_7_5.h\",\"w\");\nfprintf(fd,\"s16 s6n_kHz_7_5[%d]__attribute__((aligned(16))) = {\",length(s6_n2));\nfprintf(fd,\"%d,\",s6_n2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s6_n2(end));\n\nfprintf(fd,\"s16 s6e_kHz_7_5[%d]__attribute__((aligned(16))) = {\",length(s6_e2));\nfprintf(fd,\"%d,\",s6_e2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s6_e2(end));\n\nfprintf(fd,\"s16 s15n_kHz_7_5[%d]__attribute__((aligned(16))) = {\",length(s15_n2));\nfprintf(fd,\"%d,\",s15_n2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s15_n2(end));\n\nfprintf(fd,\"s16 s15e_kHz_7_5[%d]__attribute__((aligned(16))) = {\",length(s15_e2));\nfprintf(fd,\"%d,\",s15_e2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s15_e2(end));\n\nfprintf(fd,\"s16 s25n_kHz_7_5[%d]__attribute__((aligned(16))) = {\",length(s25_n2));\nfprintf(fd,\"%d,\",s25_n2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s25_n2(end));\n\nfprintf(fd,\"s16 s25e_kHz_7_5[%d]__attribute__((aligned(16))) = {\",length(s25_e2));\nfprintf(fd,\"%d,\",s25_e2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s25_e2(end));\n\nfprintf(fd,\"s16 s50n_kHz_7_5[%d]__attribute__((aligned(16))) = {\",length(s50_n2));\nfprintf(fd,\"%d,\",s50_n2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s50_n2(end));\n\nfprintf(fd,\"s16 s50e_kHz_7_5[%d]__attribute__((aligned(16))) = {\",length(s50_e2));\nfprintf(fd,\"%d,\",s50_e2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s50_e2(end));\n\nfprintf(fd,\"s16 s75n_kHz_7_5[%d]__attribute__((aligned(16))) = {\",length(s75_n2));\nfprintf(fd,\"%d,\",s75_n2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s75_n2(end));\n\nfprintf(fd,\"s16 s75e_kHz_7_5[%d]__attribute__((aligned(16))) = {\",length(s75_e2));\nfprintf(fd,\"%d,\",s75_e2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s75_e2(end));\n\nfprintf(fd,\"s16 s100n_kHz_7_5[%d]__attribute__((aligned(16)))= {\",length(s100_n2));\nfprintf(fd,\"%d,\",s100_n2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s100_n2(end));\n\nfprintf(fd,\"s16 s100e_kHz_7_5[%d]__attribute__((aligned(16)))= {\",length(s100_n2));\nfprintf(fd,\"%d,\",s100_e2(1:(end-1)));\nfprintf(fd,\"%d};\\n\\n\",s100_e2(end));\n\nfclose(fd);\nend\n\n\nfunction [s_n2, s_e2] = gen_sig(RB)\n % 20MHz BW\n cp0 = 160;\n cp = 144;\n cpe = 512;\n samplerate = 30.72e6;\n ofdm_size = 2048;\n len = 15360;\n switch(RB)\n case 6\n ratio = 1/16;\n case 15\n ratio = 1/8;\n case 25\n ratio = 1/4;\n case 50\n ratio = 1/2;\n case 75\n ratio = 3/4;\n case 100\n ratio = 1;\n otherwise\n disp(\"Wrong Number of RB\");\n end\n cp0 = cp0*ratio;\n cp = cp*ratio;\n cpe = cpe*ratio;\n samplerate = samplerate*ratio;\n ofdm_size = ofdm_size*ratio;\n len = len*ratio;\n \n s_n0 = floor(32767*exp(-sqrt(-1)*2*pi*(-cp0:ofdm_size-1)*7.5e3/samplerate));\n s_n1 = floor(32767*exp(-sqrt(-1)*2*pi*(-cp:ofdm_size-1)*7.5e3/samplerate));\n s_n = [s_n0 s_n1 s_n1 s_n1 s_n1 s_n1 s_n1];\n s_n2 = zeros(1, 2*len);\n s_n2(1:2:end) = real(s_n);\n s_n2(2:2:end) = imag(s_n);\n s_e = floor(32767*exp(-sqrt(-1)*2*pi*(-cpe:ofdm_size-1)*7.5e3/samplerate));\n s_e = [s_e s_e s_e s_e s_e s_e];\n s_e2 = zeros(1, 2*len);\n s_e2(1:2:end) = real(s_e);\n s_e2(2:2:end) = imag(s_e);\nend\n\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "f_tls_diag.m", "ext": ".m", "path": "openairinterface5g-master/targets/PROJECTS/TDDREC/f_tls_diag.m", "size": 1272, "source_encoding": "utf_8", "md5": "443132469284a3d4d0b38bd5fb7d0522", "text": "%\n% PURPOSE : TLS solution for AX = B based on SVD assuming X is diagonal\n%\n% ARGUMENTS :\n%\n% A : observation of A \n% B : observation of B\n%\n% OUTPUTS :\n%\n% X : TLS solution for X (Diagonal)\n%\n%**********************************************************************************************\n% EURECOM - All rights reserved\n%\n% AUTHOR : Xiwen JIANG, Florian Kaltenberger\n%\n% DEVELOPMENT HISTORY :\n% \n% Date Name(s) Version Description\n% ----------- ------------- ------- ------------------------------------------------------\n% Apr-30-2014 X. JIANG 0.1 creation of code\n%\n% REFERENCES/NOTES/COMMENTS :\n%\n% - I. Markovsky and S. V. Huffel, “Overview of total least-squares methods,” Signal Processing, vol. 87, pp.\n% 2283–2302, 2007 \n%\n%**********************************************************************************************\n\nfunction [X_est A_est B_est] = f_tls_diag(A,B)\n\nd_N = size(A,2);\nX_est = zeros(d_N);\nA_est = zeros(size(A));\nB_est = zeros(size(B));\nerr_est = zeros(d_N);\n\nfor d_n = 1:d_N\n [X_est(d_n,d_n) A_est(:,d_n) B_est(:,d_n)] = f_tls_svd(A(:,d_n),B(:,d_n));\nend\n\n%method 2: LS solution\n% for d_n = 1:d_N\n% X_est(d_n,d_n) = (A(:,d_n).'*A(:,d_n))\\A(:,d_n).'*B(:,d_n);\n% end\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "f_tls_ap.m", "ext": ".m", "path": "openairinterface5g-master/targets/PROJECTS/TDDREC/f_tls_ap.m", "size": 1368, "source_encoding": "utf_8", "md5": "223603e551ebede67ff13452e95097b1", "text": "%\r\n% PURPOSE : TLS solution for AX = B based on alternative projection\r\n%\r\n% ARGUMENTS :\r\n%\r\n% A : observation of A \r\n% B : observation of B\r\n%\r\n% OUTPUTS :\r\n%\r\n% X : TLS solution for X\r\n%\r\n%**********************************************************************************************\r\n% EURECOM - All rights reserved\r\n%\r\n% AUTHOR : Xiwen JIANG, Florian Kaltenberger\r\n%\r\n% DEVELOPMENT HISTORY :\r\n% \r\n% Date Name(s) Version Description\r\n% ----------- ------------- ------- ------------------------------------------------------\r\n% Mai-05-2014 X. JIANG 0.1 creation of code\r\n%\r\n% REFERENCES/NOTES/COMMENTS :\r\n%\r\n% - none.\r\n%\r\n%**********************************************************************************************\r\n\r\nfunction [X_est A_est B_est] = f_tls_ap(A,B)\r\n \r\n%** initlisation **\r\n e_new = 0;\r\n e_old = 1e14;\r\n e_thr = 1e-5; %error threshold: what if the error cannot fall down under the error threshold\r\n X_est = eye(size(A,2));\r\n A_est = A;\r\n \r\n%** alternative projection **\r\nwhile(abs(e_new-e_old)>e_thr)\r\n e_old = e_new;\r\n \r\n % optimise X_est\r\n X_est = (A_est'*A_est)\\A_est'*B;\r\n \r\n %optimise A_est\r\n A_est = B*X_est'/(X_est*X_est');\r\n \r\n e_new = norm(A_est*X_est-B)^2+norm(A_est-A)^2;\r\nend\r\n B_est = A_est*X_est;\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "f_ofdm_rx.m", "ext": ".m", "path": "openairinterface5g-master/targets/PROJECTS/TDDREC/f_ofdm_rx.m", "size": 1545, "source_encoding": "utf_8", "md5": "ade01596524abbe660fc84064cbb4724", "text": "%\r\n% PURPOSE : OFDM Receiver\r\n%\r\n% ARGUMENTS :\r\n%\r\n% m_sig_R\t\t: received signal with dimension ((d_N_FFT+d_N_CP)*d_N_ofdm) x d_N\r\n% d_N_FFT\t\t: total carrier number\r\n% d_N_CP\t\t: extented cyclic prefix\r\n% d_N_OFDM\t\t: OFDM symbol number per frame\r\n% v_active_rf\t: active RF antenna indicator\r\n%\r\n% OUTPUTS :\r\n%\r\n% m_sym_R \t\t: transmitted signal before IFFT with dimension d_N_f x d_N_ofdm x d_N_ant_act\r\n%\r\n%**********************************************************************************************\r\n% EURECOM - All rights reserved\r\n%\r\n% AUTHOR : Xiwen JIANG, Florian Kaltenberger\r\n%\r\n% DEVELOPMENT HISTORY :\r\n% \r\n% Date Name(s) Version Description\r\n% ----------- ------------- ------- ------------------------------------------------------\r\n% Apr-29-2014 X. JIANG 0.1 creation of code\r\n%\r\n% REFERENCES/NOTES/COMMENTS :\r\n%\r\n% - Based on the function \"genrandpskseq\" created by Mirsad Cirkic, Florian Kaltenberger.\r\n% \r\n%**********************************************************************************************\r\nfunction m_sym_R = f_ofdm_rx(m_sig_R, d_N_FFT, d_N_CP, d_N_OFDM, v_active_rf)\r\n\r\nd_N_ant_act = sum(v_active_rf);\r\nm_sig_R_eff = m_sig_R(:,find(v_active_rf));\r\nm_sig_R_f = reshape(m_sig_R_eff,(d_N_FFT+d_N_CP),d_N_OFDM,d_N_ant_act);\r\n\r\n%** delete the CP **\r\nm_sig_R_noCP = m_sig_R_f(d_N_CP+1:end,:,:);\r\n\r\n%** fft **\r\nm_sym_R_fft = 1/sqrt(d_N_FFT)*fft(m_sig_R_noCP,d_N_FFT,1);\r\n%m_sym_R_fft = fft(m_sig_R_noCP,d_N_FFT,1);\r\nm_sym_R = m_sym_R_fft([2:151 362:512],:,:);\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "f_ch_est.m", "ext": ".m", "path": "openairinterface5g-master/targets/PROJECTS/TDDREC/f_ch_est.m", "size": 1711, "source_encoding": "utf_8", "md5": "f583032bb1c37167a7ff2a029a629de9", "text": "%\r\n% PURPOSE : channel estimation using least square method\r\n%\r\n% ARGUMENTS :\r\n% \r\n% m_sym_T\t\t: transmitted symbol, d_N_f x d_N_ofdm x d_N_ant_act x d_N_meas\r\n% m_sym_R\t\t: received symbol, d_N_f x d_N_ofdm x d_N_ant_act x d_N_meas\r\n% d_N_meas : number of measurements\r\n% \r\n% OUTPUTS :\r\n%\r\n% m_H_est \t\t: estimation of sub-channels, d_N_antR x d_N_antT x d_N_f x d_N_meas\r\n%\r\n%**********************************************************************************************\r\n% EURECOM - All rights reserved\r\n%\r\n% AUTHOR : Xiwen JIANG, Florian Kaltenberger\r\n%\r\n% DEVELOPMENT HISTORY :\r\n% \r\n% Date Name(s) Version Description\r\n% ----------- ------------- ------- ------------------------------------------------------\r\n% Apr-29-2014 X. JIANG 0.1 creation of code\r\n%\r\n% REFERENCES/NOTES/COMMENTS :\r\n%\r\n% - Based on the function \"runmeas_full_duplex\" created by Mirsad Cirkic, Florian Kaltenberger.\r\n% \r\n%**********************************************************************************************\r\nfunction m_H_est = f_ch_est(m_sym_T, m_sym_R)\r\n\r\n%% ** initialisation **\r\n[d_N_f,d_N_OFDM,d_N_antT,d_N_meas] = size(m_sym_T);\r\nd_N_antR = size(m_sym_R,3);\r\nm_H_est = zeros(d_N_antR,d_N_antT,d_N_f,d_N_meas);\r\n\r\n%% ** estimate the subband channel for each measurement and antenna **\r\nfor d_n_meas = 1:d_N_meas\r\n for d_n_f = 1:d_N_f\r\n m_y = reshape(m_sym_R(d_n_f,:,:,d_n_meas),d_N_OFDM,d_N_antR).'; % squeeze: problem for antenna number = 1 case\r\n m_s = reshape(m_sym_T(d_n_f,:,:,d_n_meas),d_N_OFDM,d_N_antT).';\r\n m_H_est(:,:,d_n_f,d_n_meas) = m_y*m_s'/(m_s*m_s'); % LS channel estimation\r\n end\r\nend\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "f_ofdm_tx.m", "ext": ".m", "path": "openairinterface5g-master/targets/PROJECTS/TDDREC/f_ofdm_tx.m", "size": 1997, "source_encoding": "utf_8", "md5": "042917cd72b493f1384cbc5fa2fa2de5", "text": "%\r\n% PURPOSE : OFDM Transmitter\r\n%\r\n% ARGUMENTS :\r\n%\r\n% d_M \t\t\t: modulation order\r\n% d_N_f\t\t\t: carrier number carrying data\r\n% d_N_FFT\t\t: total carrier number\r\n% d_N_CP\t\t: extented cyclic prefix\r\n% d_N_OFDM\t\t: OFDM symbol number per frame\r\n% v_active_rf\t: active RF antenna indicator\r\n% d_amp : amplitude\r\n%\r\n% OUTPUTS :\r\n%\r\n% m_sym_T \t\t: transmitted signal before IFFT with dimension d_N_f x d_N_OFDM x d_N_ant_act\r\n% m_sig_T\t\t: OFDM signal with dimension ((d_N_FFT+d_N_CP)*d_N_OFDM) x d_N_ant\r\n%\r\n%**********************************************************************************************\r\n% EURECOM - All rights reserved\r\n%\r\n% AUTHOR : Xiwen JIANG, Florian Kaltenberger\r\n%\r\n% DEVELOPMENT HISTORY :\r\n% \r\n% Date Name(s) Version Description\r\n% ----------- ------------- ------- ------------------------------------------------------\r\n% Apr-29-2014 X. JIANG 0.1 creation of code\r\n%\r\n% REFERENCES/NOTES/COMMENTS :\r\n%\r\n% - Based on the function \"genrandpskseq\" created by Mirsad Cirkic, Florian Kaltenberger.\r\n% \r\n%**********************************************************************************************\r\nfunction [m_sym_T, m_sig_T] = f_ofdm_tx(d_M, d_N_f, d_N_FFT, d_N_CP, d_N_OFDM, v_active_rf, d_amp)\r\n\r\nd_N_ant_act = sum(v_active_rf);\r\n\r\n%** constellation table **\r\nv_MPSK = exp(sqrt(-1)*([1:d_M]*2*pi/d_M+pi/d_M));\t\t\t\t\t\t\t\t\r\n%** transmitted symbol **\r\n%v_state = [1;2;3;4];\r\n%rand(\"state\",v_state);\r\nm_sym_T = v_MPSK(ceil(rand(d_N_f, d_N_OFDM, d_N_ant_act)*d_M)); \r\n\r\n%** mapping useful data to favorable carriers **\r\nm_sym_T_ext = zeros(d_N_FFT,d_N_OFDM,d_N_ant_act);\r\nm_sym_T_ext(2:151,:,:) = m_sym_T(1:150,:,:);\r\nm_sym_T_ext(362:512,:,:) = m_sym_T(151:301,:,:);\r\n\r\n%** ifft **\r\nm_sig_T_ = sqrt(d_N_FFT)*ifft(m_sym_T_ext,d_N_FFT,1);\r\n\r\n%** add cyclic prefix **\r\nm_sig_T_ = [m_sig_T_(end-d_N_CP+1:end,:,:); m_sig_T_];\r\nd_L = (d_N_FFT+d_N_CP)*d_N_OFDM;\r\nm_sig_T = floor(reshape(m_sig_T_,d_L,d_N_ant_act)*d_amp);\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "f_ofdm_rx.m", "ext": ".m", "path": "openairinterface5g-master/targets/PROJECTS/TDDREC/v4_CH_EST/f_ofdm_rx.m", "size": 1545, "source_encoding": "utf_8", "md5": "798a54f027b266189ab1fdc57569dac1", "text": "%\r\n% PURPOSE : OFDM Receiver\r\n%\r\n% ARGUMENTS :\r\n%\r\n% m_sig_R\t\t: received signal with dimension ((d_N_FFT+d_N_CP)*d_N_ofdm) x d_N\r\n% d_N_FFT\t\t: total carrier number\r\n% d_N_CP\t\t: extented cyclic prefix\r\n% d_N_OFDM\t\t: OFDM symbol number per frame\r\n% v_active_rf\t: active RF antenna indicator\r\n%\r\n% OUTPUTS :\r\n%\r\n% m_sym_R \t\t: transmitted signal before IFFT with dimension d_N_f x d_N_ofdm x d_N_ant_act\r\n%\r\n%**********************************************************************************************\r\n% EURECOM - All rights reserved\r\n%\r\n% AUTHOR : Xiwen JIANG, Florian Kaltenberger\r\n%\r\n% DEVELOPMENT HISTORY :\r\n% \r\n% Date Name(s) Version Description\r\n% ----------- ------------- ------- ------------------------------------------------------\r\n% Apr-29-2014 X. JIANG 0.1 creation of code\r\n%\r\n% REFERENCES/NOTES/COMMENTS :\r\n%\r\n% - Based on the function \"genrandpskseq\" created by Mirsad Cirkic, Florian Kaltenberger.\r\n% \r\n%**********************************************************************************************\r\nfunction m_sym_R = f_ofdm_rx(m_sig_R, d_N_FFT, d_N_CP, d_N_OFDM, v_active_rf)\r\n\r\nd_N_ant_act = sum(v_active_rf);\r\nm_sig_R_eff = m_sig_R(:,find(v_active_rf));\r\nm_sig_R_f = reshape(m_sig_R_eff,(d_N_FFT+d_N_CP),d_N_OFDM,d_N_ant_act);\r\n\r\n%** delete the CP **\r\nm_sig_R_noCP = m_sig_R_f(d_N_CP+1:end,:,:);\r\n\r\n%** fft **\r\nm_sym_R_fft = 1/sqrt(d_N_FFT)*fft(m_sig_R_noCP,d_N_FFT,1);\r\n%m_sym_R_fft = fft(m_sig_R_noCP,d_N_FFT,1);\r\nm_sym_R = m_sym_R_fft([363:512 2:151],:,:);\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "f_ch_est.m", "ext": ".m", "path": "openairinterface5g-master/targets/PROJECTS/TDDREC/v4_CH_EST/f_ch_est.m", "size": 1708, "source_encoding": "utf_8", "md5": "ad1741afb57ea0bbc0da1f1f0d410ce6", "text": "\r\n% PURPOSE : channel estimation using least square method\r\n%% ARGUMENTS :\r\n% \r\n% m_sym_T\t\t: transmitted symbol, d_N_f x d_N_ofdm x d_N_ant_act x d_N_meas\r\n% m_sym_R\t\t: received symbol, d_N_f x d_N_ofdm x d_N_ant_act x d_N_meas\r\n% d_N_meas : number of measurements\r\n% \r\n% OUTPUTS :\r\n%\r\n% m_H_est \t\t: estimation of sub-channels, d_N_antR x d_N_antT x d_N_f x d_N_meas\r\n%\r\n%**********************************************************************************************\r\n% EURECOM - All rights reserved\r\n%\r\n% AUTHOR : Xiwen JIANG, Florian Kaltenberger\r\n%\r\n% DEVELOPMENT HISTORY :\r\n% \r\n% Date Name(s) Version Description\r\n% ----------- ------------- ------- ------------------------------------------------------\r\n% Apr-29-2014 X. JIANG 0.1 creation of code\r\n%\r\n% REFERENCES/NOTES/COMMENTS :\r\n%\r\n% - Based on the function \"runmeas_full_duplex\" created by Mirsad Cirkic, Florian Kaltenberger.\r\n% \r\n%**********************************************************************************************\r\nfunction m_H_est = f_ch_est(m_sym_T, m_sym_R)\r\n\r\n%% ** initialisation **\r\n[d_N_f,d_N_OFDM,d_N_antT,d_N_meas] = size(m_sym_T);\r\nd_N_antR = size(m_sym_R,3);\r\nm_H_est = zeros(d_N_antR,d_N_antT,d_N_f,d_N_meas);\r\n\r\n%% ** estimate the subband channel for each measurement and antenna **\r\nfor d_n_meas = 1:d_N_meas\r\n for d_n_f = 1:d_N_f\r\n m_y = reshape(m_sym_R(d_n_f,:,:,d_n_meas),d_N_OFDM,d_N_antR).'; % squeeze: problem for antenna number = 1 case\r\n m_s = reshape(m_sym_T(d_n_f,:,:,d_n_meas),d_N_OFDM,d_N_antT).';\r\n m_H_est(:,:,d_n_f,d_n_meas) = m_y*m_s'/(m_s*m_s'); % LS channel estimation\r\n end\r\nend\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "f_ofdm_tx.m", "ext": ".m", "path": "openairinterface5g-master/targets/PROJECTS/TDDREC/v4_CH_EST/f_ofdm_tx.m", "size": 1997, "source_encoding": "utf_8", "md5": "52b00cfe39a99e4f6d079fcc3cdad1f8", "text": "%\r\n% PURPOSE : OFDM Transmitter\r\n%\r\n% ARGUMENTS :\r\n%\r\n% d_M \t\t\t: modulation order\r\n% d_N_f\t\t\t: carrier number carrying data\r\n% d_N_FFT\t\t: total carrier number\r\n% d_N_CP\t\t: extented cyclic prefix\r\n% d_N_OFDM\t\t: OFDM symbol number per frame\r\n% v_active_rf\t: active RF antenna indicator\r\n% d_amp : amplitude\r\n%\r\n% OUTPUTS :\r\n%\r\n% m_sym_T \t\t: transmitted signal before IFFT with dimension d_N_f x d_N_OFDM x d_N_ant_act\r\n% m_sig_T\t\t: OFDM signal with dimension ((d_N_FFT+d_N_CP)*d_N_OFDM) x d_N_ant\r\n%\r\n%**********************************************************************************************\r\n% EURECOM - All rights reserved\r\n%\r\n% AUTHOR : Xiwen JIANG, Florian Kaltenberger\r\n%\r\n% DEVELOPMENT HISTORY :\r\n% \r\n% Date Name(s) Version Description\r\n% ----------- ------------- ------- ------------------------------------------------------\r\n% Apr-29-2014 X. JIANG 0.1 creation of code\r\n%\r\n% REFERENCES/NOTES/COMMENTS :\r\n%\r\n% - Based on the function \"genrandpskseq\" created by Mirsad Cirkic, Florian Kaltenberger.\r\n% \r\n%**********************************************************************************************\r\nfunction [m_sym_T, m_sig_T] = f_ofdm_tx(d_M, d_N_f, d_N_FFT, d_N_CP, d_N_OFDM, v_active_rf, d_amp)\r\n\r\nd_N_ant_act = sum(v_active_rf);\r\n\r\n%** constellation table **\r\nv_MPSK = exp(sqrt(-1)*([1:d_M]*2*pi/d_M+pi/d_M));\t\t\t\t\t\t\t\t\r\n%** transmitted symbol **\r\n%v_state = [1;2;3;4];\r\n%rand(\"state\",v_state);\r\nm_sym_T = v_MPSK(ceil(rand(d_N_f, d_N_OFDM, d_N_ant_act)*d_M)); \r\n\r\n%** mapping useful data to favorable carriers **\r\nm_sym_T_ext = zeros(d_N_FFT,d_N_OFDM,d_N_ant_act);\r\nm_sym_T_ext(2:151,:,:) = m_sym_T(151:300,:,:);\r\nm_sym_T_ext(363:512,:,:) = m_sym_T(1:150,:,:);\r\n\r\n%** ifft **\r\nm_sig_T_ = sqrt(d_N_FFT)*ifft(m_sym_T_ext,d_N_FFT,1);\r\n\r\n%** add cyclic prefix **\r\nm_sig_T_ = [m_sig_T_(end-d_N_CP+1:end,:,:); m_sig_T_];\r\nd_L = (d_N_FFT+d_N_CP)*d_N_OFDM;\r\nm_sig_T = floor(reshape(m_sig_T_,d_L,d_N_ant_act)*d_amp);\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "genorthqpskseq.m", "ext": ".m", "path": "openairinterface5g-master/targets/PROJECTS/TDDREC/v0/genorthqpskseq.m", "size": 1143, "source_encoding": "utf_8", "md5": "330b0dc2a723aa7a373d8a0cd01fcabb", "text": "# % Author: Mirsad Cirkic\n# % Organisation: Eurecom (and Linkoping University)\n# % E-mail: mirsad.cirkic@liu.se\n\nfunction [carrierdata, s]=genorthqpskseq(Ns,N,amp)\n \nif(N!=512*150)\n error('The sequence length must be 76800.');\nendif\n\ns = zeros(N,Ns);\nH=1; for k=1:log2(128) H=[H H; H -H]; end; H=H(:,1:120);\ni=1; while(i0) error(\"The code is not orhtogonal\\n\"); endif\n\ncarrierdata=zeros(120,Ns*301);\n\ninds=1:8;\nind=8;\nfor i=1:301\n for k=1:Ns \n carrierdata(:,i+(k-1)*301)=Hc(inds(ind),:)'; \n inds(ind)=[];\n ind=ind-1;\n if(ind==0) \n inds=1:8;\n ind=8;\n endif\n endfor\nendfor\n\nfor k=1:Ns \n frstgroup=(k-1)*301+[1:150]; # The first group of OFDM carriers\n sndgroup=(k-1)*301+[151:301]; # The second group of OFDM carriers\n for i=0:119\n fblock=[0 carrierdata(i+1,frstgroup) zeros(1,210) carrierdata(i+1,sndgroup)];\n ifblock=ifft(fblock,512)*sqrt(512);\t\t\t\t\n block = [ifblock(end-127:end) ifblock]; # Cycl. prefix \n s([1:640]+i*640,k)=floor(amp*block);\n endfor\nendfor\n\nendfunction"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "genrandpskseq.m", "ext": ".m", "path": "openairinterface5g-master/targets/PROJECTS/TDDREC/v0/genrandpskseq.m", "size": 776, "source_encoding": "utf_8", "md5": "5cb33d8e20311847ffaa652cf70a4865", "text": "% Author: Mirsad Cirkic\n% Organisation: Eurecom (and Linkoping University)\n% E-mail: mirsad.cirkic@liu.se\n\n\nfunction [carrierdata, s]=genrandpskseq(N,M,amp)\n \nif(mod(N,640)~=0)\n error('The sequence length must be divisible with 640.');\nend\ns = zeros(N,1);\nMPSK=exp(sqrt(-1)*([1:M]*2*pi/M+pi/M));\n\n% OFDM sequence with 512 FFT using randomly \n% generated 4-QAM and 128 cyclic prefix\ncarrierdata=zeros(120,301);\nfor i=0:(N/640-1) \n datablock=MPSK(ceil(rand(301,1)*M));\n for j=1:301\n carrierdata(i+1,j)=datablock(j);\n end\n fblock=[0 datablock(1:150) zeros(1,210) datablock(151:301)];\n ifblock=ifft(fblock,512)*sqrt(512);;\n % Adding cycl. prefix making the block of 640 elements\t\n block = [ifblock(end-127:end) ifblock]; \n s([1:640]+i*640)=floor(amp*block);\nend\n\nend\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "rfldec.m", "ext": ".m", "path": "openairinterface5g-master/targets/ARCH/EXMIMO/USERSPACE/OCTAVE/rfldec.m", "size": 363, "source_encoding": "utf_8", "md5": "24448e69682b1f6a6ea652c2426b08f7", "text": "## Decodes rf_local values: [ txi, txq, rxi, rxq ] = rfldec(rflocal)\n\n## Author: Matthias Ihmig \n## Created: 2012-12-05\n\nfunction [ txi, txq, rxi, rxq ] = rfldec(rflocal)\n txi = mod(floor( rflocal /1 ), 64)\n txq = mod(floor( rflocal /64), 64)\n rxi = mod(floor( rflocal /4096), 64)\n rxq = mod(floor( rflocal /262144), 64)\nendfunction\n"} +{"plateform": "github", "repo_name": "chunyeow/openairinterface5g-master", "name": "rfl.m", "ext": ".m", "path": "openairinterface5g-master/targets/ARCH/EXMIMO/USERSPACE/OCTAVE/rfl.m", "size": 225, "source_encoding": "utf_8", "md5": "9ad201a94d01db3e65ecedb02252ca19", "text": "## Composes rf_local values: rfl(txi, txq, rxi, rxq)\n\n## Author: Matthias Ihmig \n## Created: 2012-12-05\n\nfunction [ ret ] = rfl(txi, txq, rxi, rxq)\n ret = txi + txq*2^6 + rxi*2^12 + rxq*2^18;\nendfunction\n"} +{"plateform": "github", "repo_name": "kaiqzhan/ardupilot-raspilot-master", "name": "RotToQuat.m", "ext": ".m", "path": "ardupilot-raspilot-master/libraries/AP_NavEKF/Models/Common/RotToQuat.m", "size": 288, "source_encoding": "utf_8", "md5": "9239706354267c8f5f2a29f992c07de9", "text": "% convert froma rotation vector in radians to a quaternion\nfunction quaternion = RotToQuat(rotVec)\n\nvecLength = sqrt(rotVec(1)^2 + rotVec(2)^2 + rotVec(3)^2);\n\nif vecLength < 1e-6\n quaternion = [1;0;0;0];\nelse\n quaternion = [cos(0.5*vecLength); rotVec/vecLength*sin(0.5*vecLength)];\nend"} +{"plateform": "github", "repo_name": "kaiqzhan/ardupilot-raspilot-master", "name": "NormQuat.m", "ext": ".m", "path": "ardupilot-raspilot-master/libraries/AP_NavEKF/Models/Common/NormQuat.m", "size": 198, "source_encoding": "utf_8", "md5": "ed913e87efc9194a2c52b266fced8da7", "text": "% normalise the quaternion\nfunction quaternion = normQuat(quaternion)\n\nquatMag = sqrt(quaternion(1)^2 + quaternion(2)^2 + quaternion(3)^2 + quaternion(4)^2);\nquaternion(1:4) = quaternion / quatMag;\n"} +{"plateform": "github", "repo_name": "kaiqzhan/ardupilot-raspilot-master", "name": "QuatToEul.m", "ext": ".m", "path": "ardupilot-raspilot-master/libraries/AP_NavEKF/Models/Common/QuatToEul.m", "size": 436, "source_encoding": "utf_8", "md5": "c19c9235052d99b8b943a7157e83fc94", "text": "% Convert from a quaternion to a 321 Euler rotation sequence in radians\n\nfunction Euler = QuatToEul(quat)\n\nEuler = zeros(3,1);\n\nEuler(1) = atan2(2*(quat(3)*quat(4)+quat(1)*quat(2)), quat(1)*quat(1) - quat(2)*quat(2) - quat(3)*quat(3) + quat(4)*quat(4));\nEuler(2) = -asin(2*(quat(2)*quat(4)-quat(1)*quat(3)));\nEuler(3) = atan2(2*(quat(2)*quat(3)+quat(1)*quat(4)), quat(1)*quat(1) + quat(2)*quat(2) - quat(3)*quat(3) - quat(4)*quat(4));"} +{"plateform": "github", "repo_name": "fuweixiao/cuda_inpainting-master", "name": "fillPatch.m", "ext": ".m", "path": "cuda_inpainting-master/matlab/fillPatch.m", "size": 987, "source_encoding": "utf_8", "md5": "5c526d2ab81973301f7a08e4a90a4722", "text": "function [new_img] = fillPatch(old_img, nodeMidX, nodeMidY, listPatchX, listPatchY, label)\n% patch & node size\nradius = 16;\npatchW = radius; patchH = radius;\nnodeW = patchW / 2; nodeH = patchH / 2;\n[hh, ww, len] = size(label);\n\nnew_img = old_img;\nfor i = 1:hh\n for j = 1:ww\n if (label <= 0)\n display('uninitialized label!');\n else\n new_img = pastePatch(new_img, old_img, nodeMidX, nodeMidY, listPatchX(label), listPatchY(label));\n end\n end\nend\n\nend\n\nfunction [new_img] = pastePatch(new_img, old_img, nodeMidX, nodeMidY, patchX, patchY)\n % patch & node size\n radius = 16;\n patchW = radius; patchH = radius;\n nodeW = patchW / 2; nodeH = patchH / 2;\n % \n xx = nodeMidX - nodeW;\n yy = nodeMidY - nodeH;\n \n for i = 0:patchH - 1\n for j = 0:patchW - 1\n %for i = 0:nodeH - 1\n % for j = 0:nodeW - 1\n new_img(yy + i, xx + j, :) = old_img(patchY + i, patchX + j, :);\n end\n end\n \nend"} +{"plateform": "github", "repo_name": "fluongo/MATLAB_calcium-master", "name": "CellsortPlotPCspectrum_v2.m", "ext": ".m", "path": "MATLAB_calcium-master/workflow/CellsortPlotPCspectrum_v2.m", "size": 2659, "source_encoding": "utf_8", "md5": "9e85199b8fe87b08f41d31e3b489551d", "text": "function [pcanorm] = CellsortPlotPCspectrum_v2(fn, CovEvals, PCuse)\n% CellsortPlotPCspectrum(fn, CovEvals, PCuse)\n%\n% Plot the principal component (PC) spectrum and compare with the\n% corresponding random-matrix noise floor\n%\n% Inputs:\n% fn - movie file name. Must be in TIFF format.\n% CovEvals - eigenvalues of the covariance matrix\n% PCuse - [optional] - indices of PCs included in dimensionally reduced\n% data set\n%\n% Eran Mukamel, Axel Nimmerjahn and Mark Schnitzer, 2009\n% Email: eran@post.harvard.edu, mschnitz@stanford.edu\n%\n\nif nargin<3\n PCuse = [];\nend\n\n[pixw,pixh] = size(imread(fn,1));\nnpix = pixw*pixh;\n[directory_use vals nt] = tiff_frames(fn);\n\n% Random matrix prediction (Sengupta & Mitra)\np1 = npix; % Number of pixels\nq1 = nt; % Number of time frames\nq = max(p1,q1);\np = min(p1,q1);\nsigma = 1;\nlmax = sigma*sqrt(p+q + 2*sqrt(p*q));\nlmin = sigma*sqrt(p+q - 2*sqrt(p*q));\nlambda = [lmin: (lmax-lmin)/100.0123423421: lmax];\nrho = (1./(pi*lambda*(sigma^2))).*sqrt((lmax^2-lambda.^2).*(lambda.^2-lmin^2));\nrho(isnan(rho)) = 0;\nrhocdf = cumsum(rho)/sum(rho);\nnoiseigs = interp1(rhocdf, lambda, [p:-1:1]'/p, 'linear', 'extrap').^2 ;\n\n% Normalize the PC spectrum\nnormrank = min(nt-1,length(CovEvals));\npca_norm = CovEvals*noiseigs(normrank) / (CovEvals(normrank)*noiseigs(1));\n\nclf\nplot(pca_norm, 'o-', 'Color', [1,1,1]*0.3, 'MarkerFaceColor', [1,1,1]*0.3, 'LineWidth',2)\nhold on\nplot(noiseigs / noiseigs(1), 'b-', 'LineWidth',2)\nplot(2*noiseigs / noiseigs(1), 'b--', 'LineWidth',2)\nif ~isempty(PCuse)\n plot(PCuse, pca_norm(PCuse), 'rs', 'LineWidth',2)\nend\nhold off\nformataxes\nset(gca,'XScale','log','YScale','log', 'Color','none')\nxlabel('PC rank')\nylabel('Normalized variance')\naxis tight\nif isempty(PCuse)\n legend('Data variance','Noise floor','2 x Noise floor')\nelse\n legend('Data variance','Noise floor','2 x Noise floor','Retained PCs')\nend\n\nfntitle = fn;\nfntitle(fn=='_') = ' ';\ntitle(fntitle)\n\nfunction formataxes\n\nset(gca,'FontSize',12,'FontWeight','bold','FontName','Helvetica','LineWidth',2,'TickLength',[1,1]*.02,'tickdir','out')\nset(gcf,'Color','w','PaperPositionMode','auto')\n\nfunction [directory_use vals j] = tiff_frames(fn)\n \n m = dir;\n directory_use = [];\n vals = zeros(numel(m),1);\n\n for i = 1:numel(m)\n temp = strfind(m(i).name,'0');\n temp_2 = strfind(m(i).name,'.tif');\n if isempty(temp) || isempty(temp_2)\n vals(i) = 0;\n else\n vals(i) = str2double(m(i).name(temp(1) : temp_2-1));\n directory_use = [directory_use i];\n end\n end\n \n j = max(vals)\n \n"} +{"plateform": "github", "repo_name": "fluongo/MATLAB_calcium-master", "name": "CellsortPlotPCspectrum.m", "ext": ".m", "path": "MATLAB_calcium-master/workflow/CellsortPlotPCspectrum.m", "size": 2464, "source_encoding": "utf_8", "md5": "18cfdd6e9244ddb043ebd7a86be73608", "text": "function [pcanorm] = CellsortPlotPCspectrum(fn, CovEvals, PCuse)\n% CellsortPlotPCspectrum(fn, CovEvals, PCuse)\n%\n% Plot the principal component (PC) spectrum and compare with the\n% corresponding random-matrix noise floor\n%\n% Inputs:\n% fn - movie file name. Must be in TIFF format.\n% CovEvals - eigenvalues of the covariance matrix\n% PCuse - [optional] - indices of PCs included in dimensionally reduced\n% data set\n%\n% Eran Mukamel, Axel Nimmerjahn and Mark Schnitzer, 2009\n% Email: eran@post.harvard.edu, mschnitz@stanford.edu\n%\n\nif nargin<3\n PCuse = [];\nend\n\n[pixw,pixh] = size(imread(fn,1));\nnpix = pixw*pixh;\nnt = tiff_frames(fn);\n\n% Random matrix prediction (Sengupta & Mitra)\np1 = npix; % Number of pixels\nq1 = nt; % Number of time frames\nq = max(p1,q1);\np = min(p1,q1);\nsigma = 1;\nlmax = sigma*sqrt(p+q + 2*sqrt(p*q));\nlmin = sigma*sqrt(p+q - 2*sqrt(p*q));\nlambda = [lmin: (lmax-lmin)/100.0123423421: lmax];\nrho = (1./(pi*lambda*(sigma^2))).*sqrt((lmax^2-lambda.^2).*(lambda.^2-lmin^2));\nrho(isnan(rho)) = 0;\nrhocdf = cumsum(rho)/sum(rho);\nnoiseigs = interp1(rhocdf, lambda, [p:-1:1]'/p, 'linear', 'extrap').^2 ;\n\n% Normalize the PC spectrum\nnormrank = min(nt-1,length(CovEvals));\npca_norm = CovEvals*noiseigs(normrank) / (CovEvals(normrank)*noiseigs(1));\n\nclf\nplot(pca_norm, 'o-', 'Color', [1,1,1]*0.3, 'MarkerFaceColor', [1,1,1]*0.3, 'LineWidth',2)\nhold on\nplot(noiseigs / noiseigs(1), 'b-', 'LineWidth',2)\nplot(2*noiseigs / noiseigs(1), 'b--', 'LineWidth',2)\nif ~isempty(PCuse)\n plot(PCuse, pca_norm(PCuse), 'rs', 'LineWidth',2)\nend\nhold off\nformataxes\nset(gca,'XScale','log','YScale','log', 'Color','none')\nxlabel('PC rank')\nylabel('Normalized variance')\naxis tight\nif isempty(PCuse)\n legend('Data variance','Noise floor','2 x Noise floor')\nelse\n legend('Data variance','Noise floor','2 x Noise floor','Retained PCs')\nend\n\nfntitle = fn;\nfntitle(fn=='_') = ' ';\ntitle(fntitle)\n\nfunction formataxes\n\nset(gca,'FontSize',12,'FontWeight','bold','FontName','Helvetica','LineWidth',2,'TickLength',[1,1]*.02,'tickdir','out')\nset(gcf,'Color','w','PaperPositionMode','auto')\n\nfunction j = tiff_frames(fn)\n%\n% n = tiff_frames(filename)\n%\n% Returns the number of slices in a TIFF stack.\n%\n%\n\nstatus = 1; j=0;\njstep = 10^3;\nwhile status\n try\n j=j+jstep;\n imread(fn,j);\n catch\n if jstep>1\n j=j-jstep;\n jstep = jstep/10;\n else\n j=j-1;\n status = 0;\n end\n end\nend"} +{"plateform": "github", "repo_name": "fluongo/MATLAB_calcium-master", "name": "CellsortPCA_singleframes.m", "ext": ".m", "path": "MATLAB_calcium-master/workflow/CellsortPCA_singleframes.m", "size": 13500, "source_encoding": "utf_8", "md5": "0b7534cdf1ae2051fb3a5ea67e078dfd", "text": "function [mixedsig, mixedfilters, CovEvals, covtrace, movm, ...\n movtm] = CellsortPCA_singleframes(fn, flims, nPCs, dsamp, outputdir, badframes)\n\n% [mixedsig, mixedfilters, CovEvals, covtrace, movm, movtm] = CellsortPCA(fn, flims, nPCs, dsamp, outputdir, badframes)\n%\n% CELLSORT\n% Read TIFF movie data and perform singular-value decomposition (SVD)\n% dimensional reduction.\n% \n% NOTE: This is the nimmerjahn code except modified to work with single\n% tiff frames as opposed to tiff stacks, fn in this case corresponds to\n% the name of the first frame i.e. img_00000_00.tif\n%\n% Inputs:\n% fn - movie file name. Must be in TIFF format.\n% flims - 2-element vector specifying the endpoints of the range of\n% frames to be analyzed. If empty, default is to analyze all movie\n% frames.\n% nPCs - number of principal components to be returned\n% dsamp - optional downsampling factor. If scalar, specifies temporal\n% downsampling factor. If two-element vector, entries specify temporal\n% and spatial downsampling, respectively.\n% outputdir - directory in which to store output .mat files\n% badframes - optional list of indices of movie frames to be excluded\n% from analysis\n%\n% Outputs:\n% mixedsig - N x T matrix of N temporal signal mixtures sampled at T\n% points.\n% mixedfilters - N x X x Y array of N spatial signal mixtures sampled at\n% X x Y spatial points.\n% CovEvals - largest eigenvalues of the covariance matrix\n% covtrace - trace of covariance matrix, corresponding to the sum of all\n% eigenvalues (not just the largest few)\n% movm - average of all movie time frames at each pixel\n% movtm - average of all movie pixels at each time frame, after\n% normalizing each pixel deltaF/F\n%\n% Eran Mukamel, Axel Nimmerjahn and Mark Schnitzer, 2009\n% Email: eran@post.harvard.edu, mschnitz@stanford.edu\n%\n\ntic\nfprintf('-------------- CellsortPCA %s: %s -------------- \\n', date, fn)\n\nm = dir;\n\n%-----------------------\n\n% Note, I am calling this function regardless because then if I define a\n% flims outside of function, I can just refer to the vals/dir_use vectors\n% as indices\n[dir_use frame_nt nt_full] = tiff_frames(fn);\n\n if (nargin<2)||(isempty(flims))\n flims = [1,nt_full];\n end\nflims\ndsamp_time = dsamp(1);\ndsamp_space = dsamp(2);\n\n\n\nuseframes = setdiff((flims(1):flims(2)), badframes);\n% nt = length(1:dsamp_time:length(dir_use));\nnt = length(flims(1):dsamp_time:flims(2));\n\nif nargin<3 || isempty(nPCs)\n nPCs = min(150, nt);\nend\nif nargin<4 || isempty(dsamp)\n dsamp = [1,1];\nend\nif nargin<5 || isempty(outputdir)\n outputdir = [pwd,'/cellsort_preprocessed_data/'];\nend\nif nargin<6\n badframes = [];\nend\nif isempty(dir(outputdir))\n mkdir(pwd, '/cellsort_preprocessed_data/')\nend\nif outputdir(end)~='/';\n outputdir = [outputdir, '/'];\nend\n\n% %Downsampling\n% if length(dsamp)==1\n% dsamp_time = dsamp(1);\n% dsamp_space = 1;\n% else\n% dsamp_time = dsamp(1);\n% dsamp_space = dsamp(2); % Spatial downsample\n% end\n\n\n\n[fpath, fname] = fileparts(fn);\n if isempty(badframes)\n fnmat = [outputdir, fname, '_',num2str(flims(1)),',',num2str(flims(2)), '_', date,'.mat'];\n else\n fnmat = [outputdir, fname, '_',num2str(flims(1)),',',num2str(flims(2)),'_selframes_', date,'.mat'];\n end\n \n if ~isempty(dir(fnmat))\n fprintf('CELLSORT: Movie %s already processed;', ...\n fn)\n forceload = input(' Re-load data? [0-no/1-yes] ');\n if isempty(forceload) || forceload==0\n load(fnmat)\n return\n end\n end\n\nfncovmat = [outputdir, fname, '_cov_', num2str(flims(1)), ',', num2str(flims(2)), '_', date,'.mat'];\n\n[pixw,pixh] = size(imread(fn,1));\nnpix = pixw*pixh;\n\nfprintf(' %d pixels x %d time frames;', npix, nt*dsamp_time)\n if nt1\n firstframe = imresize(firstframe, size(mov(:,:,1)),'bilinear');\n end\n\n%------------\n% Save the output data\nsave(fnmat,'mixedfilters','CovEvals','mixedsig', ...\n 'movm','movtm','covtrace', 'fn', 'flims', 'nPCs', 'dsamp', 'outputdir', 'badframes')\nfprintf(' CellsortPCA: saving data and exiting; ')\ntoc\n\n function [covmat, mov, movm, movtm] = create_xcov(fn, pixw, pixh, useframes, nt, dsamp)\n %-----------------------\n % Load movie data to compute the spatial covariance matrix\n\n npix = pixw*pixh;\n\n % Downsampling\n if length(dsamp)==1\n dsamp_time = dsamp(1);\n dsamp_space = 1;\n else\n dsamp_time = dsamp(1);\n dsamp_space = dsamp(2); % Spatial downsample\n end\n\n if (dsamp_space==1)\n mov = zeros(pixw, pixh, nt);\n for jjind=1:length(useframes)\n jj = useframes(jjind);\n mov(:,:,jjind) = imread(fn,jj);\n if mod(jjind,500)==1\n fprintf(' Read frame %4.0f out of %4.0f; ', jjind, nt)\n toc\n end\n end\n else\n [pixw_dsamp,pixh_dsamp] = size(imresize( imread(fn,1), 1/dsamp_space, 'bilinear' ));\n mov = zeros(pixw_dsamp, pixh_dsamp, nt);\n for jjind=1:length(useframes)\n jj = useframes(jjind);\n mov(:,:,jjind) = imresize( imread(fn,jj), 1/dsamp_space, 'bilinear' );\n if mod(jjind,500)==1\n fprintf(' Read frame %4.0f out of %4.0f; ', jjind, nt)\n toc\n end\n end\n end\n\n fprintf(' Read frame %4.0f out of %4.0f; ', jjind, nt)\n toc\n mov = reshape(mov, npix, nt/dsamp_time);\n\n % DFoF normalization of each pixel\n movm = mean(mov,2); % Average over time\n movmzero = (movm==0);\n movm(movmzero) = 1;\n mov = mov ./ (movm * ones(1,nt)) - 1; % Compute Delta F/F\n mov(movmzero, :) = 0;\n\n if dsamp_time>1\n mov = filter(ones(dsamp_time,1)/dsamp_time, 1, mov, [], 2);\n mov = downsample(mov', dsamp_time)';\n end\n\n movtm = mean(mov,2); % Average over space\n clear movmzeros\n\n c1 = (mov*mov')/size(mov,2);\n toc\n covmat = c1 - movtm*movtm';\n clear c1\n end\n\nfunction [covmat, mov, movm, movtm] = create_tcov(fn, pixw, pixh, useframes, nt, dsamp)\n %-----------------------\n % Load movie data to compute the temporal covariance matrix\n % npix = pixw*pixh;\n\n % Downsampling\n\n dsamp_time = dsamp(1);\n dsamp_space = dsamp(2); % Spatial downsample\n\n % if (dsamp_space==1)\n \n [pixw_dsamp,pixh_dsamp] = size(imresize( imread(fn,1), 1/dsamp_space, 'bilinear' ));\n \n npix = pixw_dsamp * pixh_dsamp;\n \n mov = zeros(pixw_dsamp, pixh_dsamp, nt);\n \n \n % mov = zeros(pixw, pixh, nt);\n \n kk = 1;\n % Adding the downsamplign of time into this step...\n for jjind=flims(1):dsamp_time:flims(2)\n% jj = useframes(jjind);\n\n temp_fname = m(dir_use(jjind)).name;\n \n % mov(:,:,kk) = imread(temp_fname);\n mov(:,:,kk) = imresize( imread(temp_fname), 1/dsamp_space, 'bilinear' );\n \n kk = kk+1;\n if mod(jjind,500)==1\n fprintf(' Read frame %4.0f out of %4.0f; ', jjind, nt*dsamp_time)\n toc\n end\n\n end\n \n \n \n% else\n% [pixw_dsamp,pixh_dsamp] = size(imresize( imread(fn,1), 1/dsamp_space, 'bilinear' ));\n% mov = zeros(pixw_dsamp, pixh_dsamp, nt);\n% \n% for jjind=1:length(useframes)\n% jj = useframes(jjind);\n% mov(:,:,jjind) = imresize( imread(fn,jj), 1/dsamp_space, 'bilinear' );\n% if mod(jjind,500)==1\n% fprintf(' Read frame %4.0f out of %4.0f; ', jjind, nt*dsamp_time)\n% toc\n% end\n% \n% npix = pixw_dsamp *pixh_dsamp;\n% \n% end\n % end\n\n fprintf(' Read frame %4.0f out of %4.0f; ', jjind, nt*dsamp_time)\n toc\n mov = reshape(mov, npix, nt);\n\n \n movm = mean(mov,2); % Average over time\n \n \n% % DFoF normalization of each pixel\n% movm = mean(mov,2); % Average over time\n% movmzero = (movm==0); % Avoid dividing by zero\n% movm(movmzero) = 1;\n% mov = mov ./ (movm * ones(1,nt)) - 1;\n% mov(movmzero, :) = 0;\n\n% if dsamp_time>1\n% mov = filter(ones(dsamp,1)/dsamp, 1, mov, [], 2);\n% mov = downsample(mov', dsamp)';\n% end\n\n% if dsamp_time>1\n% mov = filter(ones(dsamp_time,1)/dsamp_time, 1, mov, [], 2);\n% mov = downsample(mov', dsamp_time)';\n% end\n\n\n c1 = (mov'*mov)/npix;\n movtm = mean(mov,1); % Average over space\n\n covmat = c1 - movtm'*movtm;\n clear c1\nend\n% end\n%%\n function [mixedsig, CovEvals, percentvar] = cellsort_svd(covmat, nPCs, nt, npix)\n %-----------------------\n % Perform SVD\n\n covtrace = trace(covmat) / npix;\n\n opts.disp = 0;\n opts.issym = 'true';\n if nPCs0);\n CovEvals = CovEvals(CovEvals>0);\n end\n\n \n mixedsig = mixedsig' * nt;\n \n % mixedsig = interp(mixedsig,dsamp_time^2);\n \n CovEvals = CovEvals / npix;\n\n percentvar = 100*sum(CovEvals)/covtrace;\n fprintf([' First ',num2str(nPCs),' PCs contain ',num2str(percentvar,3),'%% of the variance.\\n'])\n end\n\n function [mixedfilters] = reload_moviedata(npix, mov, mixedsig, CovEvals)\n %-----------------------\n % Re-load movie data\n nPCs = size(mixedsig,1);\n\n Sinv = inv(diag(CovEvals.^(1/2)));\n \n \n% movtm = interp(mean(mov,1),dsamp_time^2); % Upsample back to original\n% temp = downsample(movtm,dsamp_time^2);\n% movuse = mov - ones(npix,1) * temp;\n% \n movuse = mov - ones(npix,1) * movtm;\n \n mixedfilters = reshape(movuse * mixedsig' * Sinv, npix, nPCs);\n\n \n end\n\n% This below function can be used to output the number of frames in the\n% given movie.....\n\n function [directory_use vals j] = tiff_frames(fn)\n \n m = dir;\n directory_use = [];\n vals = zeros(numel(m),1);\n\n for i = 1:numel(m)\n temp = strfind(m(i).name,'_');\n temp_2 = strfind(m(i).name,'.tif');\n if isempty(temp) || isempty(temp_2)\n vals(i) = 0;\n else\n % vals(i) = str2double(m(i).name(temp(1)+1 : temp_2(1)-1));\n vals(i) = str2double(m(i).name(temp(1)+1 : temp(2)-1));\n directory_use = [directory_use i];\n end\n end\n \n j = max(vals)\n \n end\n end"} +{"plateform": "github", "repo_name": "yu-jiang/Paper_Automatica2012_CTLTI-master", "name": "Jiang2012Automatica.m", "ext": ".m", "path": "Paper_Automatica2012_CTLTI-master/Jiang2012Automatica.m", "size": 5918, "source_encoding": "utf_8", "md5": "fd35bee11aa913b28195817b63cb117d", "text": "% Code for the paper \"Computational adaptive optimal control with an\r\n% application to a car engine control problem\", Yu Jiang and Zhong-Ping\r\n% Jiang,vol. 48, no. 10, pp. 2699-2704, Oct. 2012.\r\n% Copyright 2011-2014 Yu Jiang, New York University.\r\n\r\nfunction []=Jiang2012Automatica()\r\nclc;\r\nx_save=[];\r\nt_save=[];\r\nflag=1; % 1: learning is on. 0: learning is off.\r\n\r\n% System matrices used for simulation purpose\r\nA=[-0.4125 -0.0248 0.0741 0.0089 0 0;\r\n 101.5873 -7.2651 2.7608 2.8068 0 0;\r\n 0.0704 0.0085 -0.0741 -0.0089 0 0.0200;\r\n 0.0878 0.2672 0 -0.3674 0.0044 0.3962;\r\n -1.8414 0.0990 0 0 -0.0343 -0.0330;\r\n 0 0 0 -359 187.5364 -87.0316];\r\n\r\nB=[-0.0042 0.0064\r\n -1.0360 1.5849\r\n 0.0042 0;\r\n 0.1261 0;\r\n 0 -0.0168;\r\n 0 0];\r\n\r\n[xn,un]=size(B);%size of B. un-column #, xn row #\r\n\r\n% Set the weighting matrices for the cost function\r\nQ=diag([1 1 0.1 0.1 0.1 0.1]);\r\nR=eye(2);\r\n\r\n% Initialize the feedback gain matrix\r\nK=zeros(un,xn); % Only if A is Hurwitz, K can be set as zero.\r\nN=200; %Length of the window, should be at least greater than xn^2\r\nNN=10; %Max iteration times\r\nT=.01; %Duration of time for each integration\r\n\r\n%x0=[10;2;100;2;-1;-2]; %Initial condition\r\nx0=[10;2;10;2;-1;-2];\r\ni1=(rand(1,100)-.5)*1000;\r\ni2=(rand(1,100)-.5)*1000;\r\n\r\nDxx=[];XX=[];XU=[]; % Data matrices\r\n\r\nX=[x0;kron(x0',x0')';kron(x0,zeros(un,1))]';\r\n\r\n% Run the simulation and obtain the data matrices \\delta_{xx}, I_{xx},\r\n% and I_{xu}\r\n\r\nfor i=1:N\r\n % Simulation the system and at the same time collect online info.\r\n [t,X]=ode45(@mysys, [(i-1)*T,i*T],X(end,:));\r\n\r\n %Append new data to the data matrices\r\n Dxx=[Dxx;kron(X(end,1:xn),X(end,1:xn))-kron(X(1,1:xn),X(1,1:xn))];\r\n XX=[XX;X(end,xn+1:xn+xn^2)-X(1,xn+1:xn+xn^2)];\r\n XU=[XU;X(end,xn+xn^2+1:end)-X(1,xn+xn^2+1:end)];\r\n\r\n % Keep track of the system trajectories\r\n x_save=[x_save;X];\r\n t_save=[t_save;t];\r\nend\r\n\r\nDxx=processing_Dxx(Dxx); % Only the distinct columns left\r\n\r\n% K=zeros(un,xn); % Initial stabilizing feedback gain matrix\r\nP_old=zeros(xn);P=eye(xn)*10; % Initialize the previous cost matrix\r\nit=0; % Counter for iterations\r\np_save=[]; % Track the cost matrices in all the iterations\r\nk_save=[]; % Track the feedback gain matrix in each iterations\r\n\r\n[K0,P0]=lqr(A,B,Q,R) % Calculate the ideal solution for comparion purpose\r\nk_save=[norm(K-K0)];\r\n\r\nwhile norm(P-P_old)>1e-10 & it<16 % Stopping criterion for learning\r\n it=it+1 % Update and display the # of iters\r\n P_old=P; % Update the previous cost matrix\r\n QK=Q+K'*R*K; % Update the Qk matrix\r\n X2=XX*kron(eye(xn),K'); %\r\n X1=[Dxx,-X2-XU]; % Left-hand side of the key equation\r\n Y=-XX*QK(:); % Right-hand side of the key equation\r\n pp=X1\\Y; % Solve the equations in the LS sense\r\n P=reshape_p(pp); % Reconstruct the symmetric matrix\r\n p_save=[p_save,norm(P-P0)]; % Keep track of the cost matrix\r\n BPv=pp(end-(xn*un-1):end);\r\n K=inv(R)*reshape(BPv,un,xn)/2 % Get the improved gain matrix\r\n k_save=[k_save,norm(K-K0)]; % Keep track of the control gains\r\nend\r\n\r\n% Plot the trajectories\r\nfigure(1)\r\nplot([0:length(p_save)-1],p_save,'o',[0:length(p_save)-1],p_save)\r\n%axis([-0.5,it-.5,-5,15])\r\nlegend('||P_k-P^*||')\r\nxlabel('Number of iterations')\r\n\r\nfigure(2)\r\nplot([0:length(k_save)-1],k_save,'^',[0:length(k_save)-1],k_save)\r\n%axis([-0.5,it+0.5,-.5,2])\r\nlegend('||K_k-K^*||')\r\nxlabel('Number of iterations')\r\n\r\n\r\n% Post-learning simulation\r\n[tt,xx]=ode23(@mysys,[t(end) 100],X(end,:)');\r\n\r\n% Keep track of the post-learning trajectories\r\nt_final=[t_save;tt];\r\nx_final=[x_save;xx];\r\n\r\n\r\nfigure(3)\r\nplot(t_final,x_final(:,1:6),'Linewidth',2)\r\n%axis([0,10,-100,200])\r\nlegend('x_1','x_2','x_3','x_4','x_5','x_6')\r\nxlabel('Time (sec)')\r\n\r\nfigure(4)\r\nplot(t_final,sqrt(sum(x_final(:,1:6).^2,2)),'Linewidth',2)\r\n%axis([0,200,-50,200])\r\nlegend('||x||')\r\nxlabel('Time (sec)')\r\n\r\nfigure(5)\r\nplot(t_final,3.6*x_final(:,1),'k-.', ...\r\n t_final, x_final(:,6),'-','Linewidth',2)\r\n%axis([0,10,-80,50])\r\nlegend('y_1 (MAF)','y_2 (MAP)')\r\nxlabel('Time (sec)')\r\n\r\n% The following nested function gives the dynamics of the sytem. Also,\r\n% integraters are included for the purpose of data collection.\r\n function dX=mysys(t,X)\r\n %global A B xn un i1 i2 K flag\r\n x=X(1:xn);\r\n\r\n if t>=2; % See if learning is stopped\r\n flag=0;\r\n end\r\n\r\n if flag==1\r\n u=zeros(un,1);\r\n for i=i1\r\n u(1)=u(1)+sin(i*t)/length(i1); % constructing the\r\n % exploration noise\r\n end\r\n for i=i2\r\n u(2)=u(2)+sin(i*t)/length(i2);\r\n end\r\n u=100*u;\r\n else\r\n u=-K*x;\r\n end\r\n\r\n dx=A*x+B*u;\r\n dxx=kron(x',x')';\r\n dux=kron(x',u')';\r\n dX=[dx;dxx;dux];\r\n end\r\n\r\n% This nested function reconstruct the P matrix from its distinct elements\r\n function P=reshape_p(p)\r\n P=zeros(xn);\r\n ij=0;\r\n for i=1:xn\r\n for j=1:i\r\n ij=ij+1;\r\n P(i,j)=p(ij);\r\n P(j,i)=P(i,j);\r\n end\r\n end\r\n end\r\n\r\n% The following nested function removes the repeated columns from Dxx\r\n function Dxx=processing_Dxx(Dxx)\r\n ij=[]; ii=[];\r\n\r\n for i=1:xn\r\n ii=[ii (i-1)*xn+i];\r\n end\r\n\r\n for i=1:xn-1\r\n for j=i+1:xn\r\n ij=[ij (i-1)*xn+j];\r\n end\r\n end\r\n\r\n Dxx(:,ii)=Dxx(:,ii)/2;\r\n Dxx(:,ij)=[];\r\n Dxx=Dxx*2;\r\n end\r\nend"} +{"plateform": "github", "repo_name": "yu-jiang/Paper_Automatica2012_CTLTI-master", "name": "Jiang2012Automatica_optimized_version.m", "ext": ".m", "path": "Paper_Automatica2012_CTLTI-master/Jiang2012Automatica_optimized_version.m", "size": 5110, "source_encoding": "utf_8", "md5": "dcbd4e40b52b0396bad43ba7c4e73062", "text": "% Code for the paper \"Computational adaptive optimal control with an\n% application to a car engine control problem\", Yu Jiang and Zhong-Ping\n% Jiang,vol. 48, no. 10, pp. 2699-2704, Oct. 2012.\n% Copyright 2011-2014 Yu Jiang, New York University.\n\nfunction []=Jiang2012Automatica()\nclc;\nx_save=[];\nt_save=[];\nflag=1; % 1: learning is on. 0: learning is off.\n\n% System matrices used for simulation purpose\nA=[-0.4125 -0.0248 0.0741 0.0089 0 0;\n 101.5873 -7.2651 2.7608 2.8068 0 0;\n 0.0704 0.0085 -0.0741 -0.0089 0 0.0200;\n 0.0878 0.2672 0 -0.3674 0.0044 0.3962;\n -1.8414 0.0990 0 0 -0.0343 -0.0330;\n 0 0 0 -359 187.5364 -87.0316];\n\nB=[-0.0042 0.0064\n -1.0360 1.5849\n 0.0042 0;\n 0.1261 0;\n 0 -0.0168;\n 0 0];\n\n[xn,un]=size(B);%size of B. un-column #, xn row #\n\n% Set the weighting matrices for the cost function\nQ=diag([1 1 0.1 0.1 0.1 0.1]);\nR=eye(2);\n\n% Initialize the feedback gain matrix\nK=zeros(un,xn); % Only if A is Hurwitz, K can be set as zero.\nN=200; %Length of the window, should be at least greater than xn^2\nNN=10; %Max iteration times\nT=.01; %Duration of time for each integration\n\n%x0=[10;2;100;2;-1;-2]; %Initial condition\nx0=[10;2;10;2;-1;-2];\ni1=(rand(1,100)-.5)*1000;\ni2=(rand(1,100)-.5)*1000;\n\nDxx=[];XX=[];XU=[]; % Data matrices\n\nX=[x0;kron(x0',x0')';kron(x0,zeros(un,1))]';\n\n% Run the simulation and obtain the data matrices \\delta_{xx}, I_{xx},\n% and I_{xu}\n\nfor i=1:N\n % Simulation the system and at the same time collect online info.\n [t,X]=ode45(@mysys, [(i-1)*T,i*T],X(end,:));\n\n %Append new data to the data matrices\n Dxx=[Dxx;kron(X(end,1:xn),X(end,1:xn))-kron(X(1,1:xn),X(1,1:xn))];\n XX=[XX;X(end,xn+1:xn+xn^2)-X(1,xn+1:xn+xn^2)];\n XU=[XU;X(end,xn+xn^2+1:end)-X(1,xn+xn^2+1:end)];\n\n % Keep track of the system trajectories\n x_save=[x_save;X];\n t_save=[t_save;t];\nend\n\n%Dxx=processing_Dxx(Dxx); % Only the distinct columns left\n\n% K=zeros(un,xn); % Initial stabilizing feedback gain matrix\nP_old=zeros(xn);P=eye(xn)*10; % Initialize the previous cost matrix\nit=0; % Counter for iterations\np_save=[]; % Track the cost matrices in all the iterations\nk_save=[]; % Track the feedback gain matrix in each iterations\n\n[K0,P0]=lqr(A,B,Q,R) % Calculate the ideal solution for comparion purpose\nk_save=[norm(K-K0)];\n\nwhile norm(P-P_old)>1e-10 & it<16 % Stopping criterion for learning\n it=it+1 % Update and display the # of iters\n P_old=P; % Update the previous cost matrix\n QK=Q+K'*R*K; % Update the Qk matrix\n X2=XX*kron(eye(xn),K'); %\n X1=[Dxx,-X2-XU]; % Left-hand side of the key equation\n Y=-XX*QK(:); % Right-hand side of the key equation\n %pp=X1\\Y; % Solve the equations in the LS sense\n pp = pinv(X1)*Y;\n\t%P=reshape_p(pp); % Reconstruct the symmetric matrix\n\tP = reshape(pp(1:xn*xn), [xn, xn]);\n\tP = (P +P')/2;\n p_save=[p_save,norm(P-P0)]; % Keep track of the cost matrix\n BPv=pp(end-(xn*un-1):end);\n K=inv(R)*reshape(BPv,un,xn)/2 % Get the improved gain matrix\n k_save=[k_save,norm(K-K0)]; % Keep track of the control gains\nend\n\n% Plot the trajectories\nfigure(1)\nplot([0:length(p_save)-1],p_save,'o',[0:length(p_save)-1],p_save)\n%axis([-0.5,it-.5,-5,15])\nlegend('||P_k-P^*||')\nxlabel('Number of iterations')\n\nfigure(2)\nplot([0:length(k_save)-1],k_save,'^',[0:length(k_save)-1],k_save)\n%axis([-0.5,it+0.5,-.5,2])\nlegend('||K_k-K^*||')\nxlabel('Number of iterations')\n\n\n% Post-learning simulation\n[tt,xx]=ode23(@mysys,[t(end) 100],X(end,:)');\n\n% Keep track of the post-learning trajectories\nt_final=[t_save;tt];\nx_final=[x_save;xx];\n\n\nfigure(3)\nplot(t_final,x_final(:,1:6),'Linewidth',2)\n%axis([0,10,-100,200])\nlegend('x_1','x_2','x_3','x_4','x_5','x_6')\nxlabel('Time (sec)')\n\nfigure(4)\nplot(t_final,sqrt(sum(x_final(:,1:6).^2,2)),'Linewidth',2)\n%axis([0,200,-50,200])\nlegend('||x||')\nxlabel('Time (sec)')\n\nfigure(5)\nplot(t_final,3.6*x_final(:,1),'k-.', ...\n t_final, x_final(:,6),'-','Linewidth',2)\n%axis([0,10,-80,50])\nlegend('y_1 (MAF)','y_2 (MAP)')\nxlabel('Time (sec)')\n\n% The following nested function gives the dynamics of the sytem. Also,\n% integraters are included for the purpose of data collection.\n function dX=mysys(t,X)\n %global A B xn un i1 i2 K flag\n x=X(1:xn);\n\n if t>=2; % See if learning is stopped\n flag=0;\n end\n\n if flag==1\n u=zeros(un,1);\n for i=i1\n u(1)=u(1)+sin(i*t)/length(i1); % constructing the\n % exploration noise\n end\n for i=i2\n u(2)=u(2)+sin(i*t)/length(i2);\n end\n u=100*u;\n else\n u=-K*x;\n end\n\n dx=A*x+B*u;\n dxx=kron(x',x')';\n dux=kron(x',u')';\n dX=[dx;dxx;dux];\n\tend\nend\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "imwritesc.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/imwritesc.m", "size": 1398, "source_encoding": "utf_8", "md5": "68650e74e308c991970251d3bed6b85f", "text": "% IMWRITESC - Writes an image to file, rescaling if necessary.\n%\n% Usage: imwritesc(im,name)\n% \n% Floating point image values are rescaled to the range 0-1 so that no\n% overflow occurs when writing 8-bit intensity values. The image format to\n% use is determined by MATLAB from the file ending.\n% If the image type is of uint8 no rescaling is performed.\n\n% Copyright (c) 1999-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 1999 - Original version\n% March 2004 - Modified to allow colour images of class 'double'\n% August 2005 - Octave compatibility\n% January 2013 - Separate Octave code path no longer needed\n\nfunction imwritesc(im,name)\n\n if strcmp(class(im), 'double')\n im = im - min(im(:)); % Offset so that min value is 0.\n im = im./max(im(:)); % Rescale so that max is 1.\n end\n imwrite(im,name);\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "circlesineramp.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/circlesineramp.m", "size": 5528, "source_encoding": "utf_8", "md5": "07bd0de1d4131398674bfe94cce19c1d", "text": "% CIRCLESINERAMP Generates test image for evaluating cyclic colour maps\n%\n% Usage: [im, alpha] = circlesineramp(sze, amp, wavelen, p, hole);\n% [im, alpha] = circlesineramp;\n%\n% Arguments: sze - Size of test image. Defaults to 512x512.\n% amp - Amplitude of sine wave. Defaults to pi/10\n% wavelen - Wavelength of sine wave at half radius of the\n% circular test image. Defaults to 8 pixels.\n% p - Power to which the linear attenuation of amplitude, \n% from outside edge to centre, is raised. For no\n% attenuation use p = 0. For linear attenuation use a\n% value of 1. The default value is 2, quadratic\n% attenuation. \n% hole - Flag 0/1 indicating whether the test image should have\n% a 'hole' in its centre. The default is 1, to have a\n% hole, this removes the distraction of the orientation\n% singularlity at the centre.\n% Returns:\n% im - The test image.\n% alpha - Alpha mask matching the regions outside of of the\n% circular test image that are set to NaN. Used if you\n% want to write an image with these regions transparent.\n%\n% The test image is a circular pattern consistsing of a sine wave superimposed\n% on a spiral ramp function. The spiral ramp starts at a value of 0 pointing\n% right, increasing anti-clockwise to a value of 2*pi as it completes the full\n% circle. This gives a 2*pi discontinuity on the right side of the image. The\n% amplitude of the superimposed sine wave is modulated from its full value at\n% the outside of the circular pattern to 0 at the centre. The default sine wave\n% amplitude of pi/10 means that the overall size of the sine wave from peak to\n% trough represents 2*(pi/10)/(2*pi) = 10% of the total spiral ramp of 2*pi. If\n% you are testing your colour map over a cycle of pi you should use amp = pi/20\n% to obtain an equivalent ratio of sine wave to circular ramp.\n%\n% The image is designed for evaluating the effectiveness of cyclic colour maps.\n% It is the cyclic companion to SINERAMP. Ideally the sine wave pattern should\n% be equally discernible over all angles around the test image. In practice\n% many colourmaps have uneven perceptual contrast over their range and often\n% include 'flat spots' of no perceptual contrast that can hide significant\n% features. Try MATLAB's hsv colour map.\n%\n% Ideally the test image should be rendered with a cyclic colour map using\n% SHOWANGULARIM though, in this case, rendering the image with SHOW or IMAGESC\n% will also be fine because all image values lie within, and use the full range\n% of, 0-2*pi. However, in general, default display methods typically do not\n% respect data values directly and can perform inappropriate offsetting and\n% normalisation of the angular data before display and rendering with a colour\n% map.\n%\n% For angular data to be rendered correctly it is important that the data values\n% are respected so that data values are correctly assigned to specific entries\n% in a cyclic colour map. The assignment of values to colours also depends on\n% whether the data is cyclic over pi, or 2*pi. SHOWANGULARIM supports this.\n%\n% See also: SHOWANGULARIM, SINERAMP, CHIRPLIN, CHIRPEXP, EQUALISECOLOURMAP, CMAP\n\n% Copyright (c) 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2014 Original version.\n% October 2014 Number of cycles calculated from wave length rather than\n% being specified directly.\n\nfunction [im, alpha] = circlesineramp(sze, amp, wavelen, p, hole)\n \n if ~exist('sze','var'), sze = 512; end\n if ~exist('amp','var'), amp = pi/10; end\n if ~exist('wavelen','var'), wavelen = 8; end\n if ~exist('p','var'), p = 2; end\n if ~exist('hole','var'), hole = 1; end\n\n % Set values for inner and outer radii of test pattern\n maxr = sze/2 * 0.9;\n if hole\n minr = 0.15*sze;\n else\n minr = 0;\n end\n \n % Determine number of cycles to achieve desired wavelength at half radius\n meanr = (maxr + minr)/2;\n circum = 2*pi*meanr;\n cycles = round(circum/wavelen);\n \n % Angles are +ve anticlockwise and mod 2*pi\n [x,y] = meshgrid([0:sze-1]-sze/2);\n theta = mod(atan2(-y,x), 2*pi); \n rad = sqrt(x.^2 + y.^2);\n \n % Normalise radius so that it varies 0-1 over minr to maxr\n rad = (rad-minr)/(maxr-minr);\n \n % Form the image\n im = amp*rad.^p .* sin(cycles*theta) + theta;\n\n % Ensure all values are within 0-2*pi so that a simple default display\n % with a cyclic colour map will render the image correctly.\n im = mod(im, 2*pi);\n\n % 'Nanify' values outside normalised radius values of 0-1\n alpha = ones(size(im));\n im(rad > 1) = NaN; \n alpha(rad > 1) = 0;\n\n if hole\n im(rad < 0) = NaN; \n alpha(rad < 0 ) = 0;\n end"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "showsurf.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/showsurf.m", "size": 3887, "source_encoding": "utf_8", "md5": "1f50f8abbac642a925b579a58b8e724d", "text": "% SHOWSURF - shows parametric surface in a convenient way\n%\n% This function wraps up the commands I usually use to display a surface.\n%\n% The surface is displayed using SURFL with interpolated shading, in my\n% favourite colormap of 'copper', with rotate3d on, and axis vis3d set.\n%\n% Usage can be any of the following\n% showsurf(Z)\n% showsurf(Z, figNo)\n% showsurf(Z, title)\n% showsurf(Z, figNo, title)\n% showsurf(X, Y, Z)\n% showsurf(X, Y, Z, figNo)\n% showsurf(X, Y, Z, title)\n% showsurf(X, Y, Z, figNo, title)\n%\n% If no figure number is specified a new figure is created. If you want the\n% current figure or subplot to be used specify 0 as the figure number.\n%\n% See also: SHOW\n\n% Copyright (c) 2009 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n \n% PK May 2009\n\nfunction showsurf(varargin)\n \n [X,Y,Z,figNo,titleString] = checkargs(varargin(:));\n\n if figNo == -1\n figure\n elseif figNo > 0\n figure(figNo), clf\n end\n \n surfl(X,Y,Z), shading interp, colormap(copper)\n rotate3d on, axis vis3d, title(titleString);\n \n \n%------------------------------------------------ \nfunction [X,Y,Z,figNo,title] = checkargs(args)\n \n nArgs = length(args);\n sze = cell(nArgs,1);\n for n = 1:nArgs\n sze{n} = size(args{n});\n end\n \n % default values\n figNo = -1; % Value to indicate create new window\n title = '';\n \n if nArgs == 1 % Assume we user has only supplied Z\n [X,Y] = meshgrid(1:sze{1}(2),1:sze{1}(1));\n Z = args{1};\n\n elseif nArgs == 2 % We have Z,figNo or Z,title\n if strcmp(class(args{2}),'char')\n title = args{2};\n else\n figNo = args{2};\n end\n [X,Y] = meshgrid(1:sze{1}(2),1:sze{1}(1));\n Z = args{1}; \n \n elseif nArgs == 3 % We have Z,figNo,title or X,Y,Z \n if strcmp(class(args{3}),'char')\n [X,Y] = meshgrid(1:sze{1}(2),1:sze{1}(1));\n Z = args{1}; \n figNo = args{2}; \n title = args{3}; \n else\n X = args{1};\n Y = args{2}; \n Z = args{3}; \n end\n \n elseif nArgs == 4 % We have X,Y,Z,figNo or X,Y,Z,title\n if strcmp(class(args{4}),'char')\n title = args{4};\n else\n figNo = args{4};\n end\n \n X = args{1};\n Y = args{2}; \n Z = args{3}; \n \n elseif nArgs == 5 % We have X,Y,Z,figNo,title \n X = args{1};\n Y = args{2}; \n Z = args{3}; \n figNo = args{4}; \n title = args{5};\n else\n error('Wrong number of arguments');\n end\n\n % Final sanity check because the code above made quite a few assumptions\n % about the validity of the supplied arguments\n if ~all(size(X)==size(Y)) || ~all(size(X)==size(Z))\n error('X,Y,Z must have the same dimensions');\n end\n \n if ~strcmp(class(title),'char')\n error('Expecting a string for the figure title');\n end\n \n if length(figNo) ~= 1 || ~isnumeric(figNo)\n error('Figure number should be a single numeric value');\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "randmap.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/randmap.m", "size": 731, "source_encoding": "utf_8", "md5": "620b6965c1e7db6de65c332753df18f4", "text": "% RANDMAP Generates a colourmap of random colours\n%\n% Useful for displaying a labeled segmented image\n%\n% map = randmap(N)\n%\n% Argument: N - Number of elements in the colourmap. Default = 1024. \n% This ensures images that have been segmented up to 1024\n% regions will (well, are more likely to) have a unique\n% colour for each region. \n%\n% See also: HSVMAP, LABMAP, GRAYMAP, BILATERALMAP, HSV, GRAY\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% February 2013\n\nfunction map = randmap(N)\n \n if ~exist('N', 'var'), N = 1024; end\n map = rand(N, 3);\n map(1,:) = [0 0 0]; % Make first entry black"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "viewlabspace2.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/viewlabspace2.m", "size": 5039, "source_encoding": "utf_8", "md5": "27e0e43cd469627a1e9eefb0e5ad2119", "text": "% VIEWLABSPACE2 Visualisation of L*a*b* space\n%\n% Usage: viewlabspace2(dtheta)\n%\n% Argument: dtheta - Optional specification of increment in angle of plane\n% through L*a*b* space. Defaults to pi/30\n%\n% Function allows interactive viewing of a sequence of images corresponding to\n% different vertical slices in L*a*b* space. \n% Initially a vertical slice in the a* direction is displayed.\n% Pressing arrow up/right will rotate the plane +dtheta\n% Pressing arrow down/left will rotate the plane by -dtheta\n% Press 'x' to exit.\n%\n% See also: VIEWLABSPACE, CMAP\n\n% To Do: Should be integrated with VIEWLABSPACE so that we get both views\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% March 2013\n\nfunction viewlabspace2(dtheta)\n \n if ~exist('dtheta', 'var'), dtheta = pi/30; end\n \n % Define some reference colours in rgb\n rgb = [1 0 0\n 0 1 0\n 0 0 1\n 1 1 0\n 0 1 1\n 1 0 1];\n \n colours = {'red '\n 'green '\n 'blue '\n 'yellow '\n 'cyan '\n 'magenta'};\n \n % ... and convert them to lab\n labv = applycform(rgb, makecform('srgb2lab'));\n\n % Obtain cylindrical coordinates in lab space\n labradius = sqrt(labv(:,2).^2+labv(:,3).^2);\n labtheta = atan2(labv(:,3), labv(:,2));\n \n % Define lightness - radius grid for image\n scale = 2;\n [rad, L] = meshgrid([-140:1/scale:140], [0:1/scale:100]);\n [rows,cols] = size(rad);\n \n % Scale and offset lab coords to fit image coords\n labc = zeros(size(labv));\n labc(:,1) = round(labv(:,1));\n labc(:,2) = round(scale*labv(:,2) + cols/2);\n labc(:,3) = round(scale*labv(:,3) + rows/2);\n \n % Print out lab values\n labv = round(labv);\n fprintf('\\nCoordinates of standard colours in L*a*b* space\\n\\n');\n for n = 1:length(labv)\n fprintf('%s L%3d a %4d b %4d angle %4.1f radius %4d\\n',...\n colours{n}, ...\n labv(n,1), labv(n,2), ...\n labv(n,3), labtheta(n), round(labradius(n)));\n end\n \n fprintf('\\n\\n')\n \n % Generate axis tick values\n tickval = [-100 -50 0 50 100];\n tickcoords = scale*tickval + cols/2;\n ticklabels = {'-100'; '-50'; '0'; '50'; '100'};\n\n \n ytickval = [0 20 40 60 80 100];\n ytickcoords = scale*ytickval;\n yticklabels = {'0'; '20'; '40'; '60'; '80'; '100'}; \n \n \n fprintf('Place cursor within figure\\n');\n fprintf('Use arrow keys to rotate the plane through L*a*b* space\\n');\n fprintf('''x'' to exit\\n');\n \n ch = 'l';\n theta = 0;\n while ch ~= 'x'\n\n % Build image in lab space\n lab = zeros(rows,cols,3);\n lab(:,:,1) = L;\n lab(:,:,2) = rad.*cos(theta);\n lab(:,:,3) = rad.*sin(theta);\n\n % Generate rgb values from lab\n rgb = applycform(lab, makecform('lab2srgb'));\n \n % Invert to reconstruct the lab values\n lab2 = applycform(rgb, makecform('srgb2lab'));\n\n % Where the reconstructed lab values differ from the specified values is\n % an indication that we have gone outside of the rgb gamut. Apply a\n % mask to the rgb values accordingly\n mask = max(abs(lab-lab2),[],3);\n \n for n = 1:3\n rgb(:,:,n) = rgb(:,:,n).*(mask<2); % tolerance of 1\n end\n\n figure(2), image(rgb), title(sprintf('Angle %d', round(theta/pi*180)));\n axis square, axis xy\n \n set(gca, 'xtick', tickcoords);\n set(gca, 'ytick', ytickcoords);\n set(gca, 'xticklabel', ticklabels);\n set(gca, 'yticklabel', yticklabels);\n xlabel('a*b* radius'); ylabel('L*'); \n impixelinfo\n\n hold on, \n plot(cols/2, rows/2, 'r+'); % Centre point for reference\n%{ \n % Plot reference colour positions\n for n = 1:length(labc)\n plot(labc(n,2), labc(n,3), 'w+')\n text(labc(n,2), labc(n,3), ...\n sprintf(' %s\\n %d %d %d ',colours{n},...\n labv(n,1), labv(n,2), labv(n,3)),...\n 'color', [1 1 1])\n end\n%} \n hold off\n\n % Handle keypresses within the figure\n pause \n ch = lower(get(gcf,'CurrentCharacter'));\n if ch == 29 || ch == 30\n theta = mod(theta + dtheta, 2*pi);\n elseif ch == 28 || ch == 31\n theta = mod(theta - dtheta, 2*pi);\n end\n \n end\n \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "chirplin.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/chirplin.m", "size": 1589, "source_encoding": "utf_8", "md5": "ec0a1da79fe966d9276fbd30096a364d", "text": "% CHIRPLIN Generates linear chirp test image\n%\n% The test image consists of a linear chirp signal in the horizontal direction\n% with the amplitude of the chirp being modulated from 1 at the top of the image\n% to 0 at the bottom.\n%\n% Usage: im = chirplin(sze, f0, k, p)\n%\n% Arguments: sze - [rows cols] specifying size of test image. If a\n% single value is supplied the image is square.\n% f0 - Initial frequency.\n% k - Rate at which frequency increases (try 0.001).\n% p - Power to which the linear attenuation of amplitude, \n% from top to bottom, is raised. For no attenuation use\n% p = 0. For contrast sensitivity experiments use larger\n% values of p. The default value is 4.\n%\n% Example: im = chirplin(500, 0, .001, 4)\n%\n% I have used this test image to evaluate the effectiveness of different\n% colourmaps, and sections of colourmaps, over varying spatial frequencies and\n% contrast.\n%\n% See also: CHIRPEXP\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% March 2012\n\nfunction im = chirplin(sze, f0, k, p)\n \n if length(sze) == 1\n rows = sze; cols = sze;\n elseif length(sze) == 2\n rows = sze(1); cols = sze(2);\n else\n error('size must be a 1 or 2 element vector');\n end\n \n if ~exist('p', 'var'), p = 4; end\n \n x = 0:cols-1;\n fx = sin((f0 + k/2*x).*x);\n \n A = ([(rows-1):-1:0]/(rows-1)).^p;\n im = A'*fx;"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "supertorus.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/supertorus.m", "size": 2444, "source_encoding": "utf_8", "md5": "91c1e7e27c0219d233582240dcb7c17e", "text": "% SUPERTORUS - generates a 'supertorus' surface\n%\n% Usage:\n% [x,y,z] = supertorus(xscale, yscale, zscale, rad, e1, e2, n)\n%\n% Arguments:\n% xscale, yscale, zscale - Scaling in the x, y and z directions.\n% e1, e2 - Exponents of the x and y coords.\n% rad - Mean radius of torus. \n% n - Number of subdivisions of logitude and latitude on\n% the surface.\n%\n% Returns: x,y,z - matrices defining paramteric surface of superquadratic\n%\n% If the result is not assigned to any output arguments the function\n% plots the surface for you, otherwise the x, y and z parametric\n% coordinates are returned for subsequent display using, say, SURFL.\n%\n% If rad is set to 0 the surface becomes a superquadratic\n%\n% Examples:\n% supertorus(1, 1, 1, 2, 1, 1, 100) - classical torus 100 subdivisions\n% supertorus(1, 1, 1, .8, 1, 1, 100) - an 'orange'\n% supertorus(1, 1, 1, 2, .1, 1, 100) - a round 'washer'\n% supertorus(1, 1, 1, 2, .1, 2, 100) - a square 'washer'\n%\n% See also: SUPERQUAD\n\n% Copyright (c) 2000 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2000\n\nfunction [x,y,z] = supertorus(xscale,yscale,zscale,rad,e1,e2, n)\n \n long = ones(n,1)*[-pi:2*pi/(n-1):pi];\n lat = [-pi:2*pi/(n-1): pi]'*ones(1,n);\n \n x = xscale * (rad + pow(cos(lat),e1)) .* pow(cos(long),e2);\n y = yscale * (rad + pow(cos(lat),e1)) .* pow(sin(long),e2);\n z = zscale * pow(sin(lat),e1);\n \n if nargout == 0\n surfl(x,y,z), shading interp, colormap(copper), axis equal\n clear x y z % suppress output\n end\n \n%--------------------------------------------------------------------\n% Internal function providing a modified definition of power whereby the\n% sign of the result always matches the sign of the input value.\n\nfunction r = pow(a,p)\n \n r = sign(a).* abs(a.^p);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "cmyk2rgb.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/cmyk2rgb.m", "size": 890, "source_encoding": "utf_8", "md5": "6d12e2501c39dec555e670c4190cf6e7", "text": "% CMYK2RGB Basic conversion of CMYK colour table to RGB\n%\n% Usage: map = cmyk2rgb(cmyk)\n%\n% Argument: cmyk - N x 4 table of cmyk values (assumed 0 - Returns)\n% 1: map - N x 3 table of RGB values\n%\n% Note that you can use MATLAB's functions MAKECFORM and APPLYCFORM to\n% perform the conversion. However I find that either the gamut mapping, or\n% my incorrect use of these functions does not result in a reversable\n% CMYK->RGB->CMYK conversion. Hence this simple function and its companion\n% RGB2CMYK \n%\n% See also: RGB2CMYK, MAP2GEOSOFTTBL, GEOSOFTTBL2MAP\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK July 2013\n\nfunction map = cmyk2rgb(cmyk)\n \n c = cmyk(:,1); m = cmyk(:,2); y = cmyk(:,3); k = cmyk(:,4);\n\n r = (1-c).*(1-k);\n g = (1-m).*(1-k);\n b = (1-y).*(1-k);\n \n map = [r g b];\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "graymap.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/graymap.m", "size": 865, "source_encoding": "utf_8", "md5": "b4f07ef527be1d1937f6ade25c5c67ac", "text": "% GRAYMAP Generates a gray colourmap over a specified range\n%\n% Usage: map = graymap(gmin, gmax, N)\n%\n% Arguments: gmin, gmax - Minimum and maximum gray values desired in\n% colourmap. Defaults are 0 and 1\n% N - Number of elements in the colourmap. Default = 256.\n%\n% See also: HSVMAP, LABMAP, RANDMAP, BILATERALMAP, HSV, GRAY\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% March 2012\n\n\nfunction map = graymap(gmin, gmax, N)\n \n if ~exist('gmin', 'var'), gmin = 0; end \n if ~exist('gmax', 'var'), gmax = 1; end \n if ~exist('N', 'var'), N = 256; end\n \n assert(gmin < gmax & gmin >= 0 & gmax <= 1, ...\n 'gmin and gmax must be between 0 and 1');\n \n g = (0:N-1)'/(N-1) * (gmax-gmin) + gmin;\n map = [g g g];"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "findimages.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/findimages.m", "size": 801, "source_encoding": "utf_8", "md5": "20b68f3c818e0bc36b576390784e740c", "text": "% FINDIMAGES - invokes image dialog box for multiple image loading\n%\n% Usage: [im, filename] = findimages\n%\n% Returns:\n% im - Cell array of images\n% filename - Cell arrauy of filenames of images\n%\n% See Also: FINDIMAGE\n\n% Peter Kovesi \n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% March 2013\n\nfunction [im, filename] = findimages\n \n [filename, pathname] = uigetfile({'*.*'}, ...\n 'Select images' ,'multiselect','on');\n if ~iscell(filename) % Assume canceled\n im = {};\n filename = {};\n return;\n end\n \n for n = 1:length(filename)\n filename{n} = [pathname filename{n}];\n im{n} = imread(filename{n}); \n end\n \n \n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "showlogfft.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/showlogfft.m", "size": 1718, "source_encoding": "utf_8", "md5": "8bf452f34bee6609519ee61053657aa2", "text": "% SHOWLOGFFT - Displays log amplitude spectrum of an fft.\n%\n% Usage: showlogfft(ft, figNo)\n%\n% Arguments: ft - Fourier transform to be displayed\n% figNo - Optional figure number to display image in.\n%\n% The fft is quadrant shifted to place zero frequency at the centre and the\n% log of the amplitude displayed (to compress grey values). An offset of 1\n% is added to avoid log(0)\n%\n% If figNo is omitted a new figure window is created. If figNo is supplied,\n% and the figure exists, the existing window is reused to display the image,\n% otherwise a new window is created.\n\n% Copyright (c) 1999 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 1999\n% September 2008 Octave compatible\nfunction showlogfft(im, figNo)\n\n Octave = exist('OCTAVE_VERSION', 'builtin') == 5; % Are we running under Octave\n Title = inputname(1); % Get variable name of image data \n \n if nargin == 2\n\tfigure(figNo); % Reuse or create a figure window with this number\n else\n\tfigNo = figure; % Create new figure window\n end\n\n imagesc(log(fftshift(abs(im))+1));\n colormap(gray); title(Title), axis('image')\n if ~Octave; truesize(figNo), end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "polyfit2d.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/polyfit2d.m", "size": 2438, "source_encoding": "utf_8", "md5": "a05847f0b684d1549e8bf19c81e011eb", "text": "% POLYFIT2D Fits 2D polynomial surface to data\n%\n% Usage: c = polyfit2d(x, y, z, degree)\n% \n% Arguments: x, y, z - coordinates of data points\n% degree - degree of polynomial surface\n% \n% Returns: c - The coefficients of polynomial surface. \n% There will be (degree+1)*(degree+2)/2\n% coefficients. \n%\n% For a degree 3 surface the coefficients progress in the form\n% 00 01 02 03 10 11 12 20 21 30\n% where the first digit is the y exponent and the 2nd the x exponent\n%\n% 0 0 0 1 0 2 0 3 1 0 1 1 1 2\n% c1 x y + c2 x y + c3 x y + c4 x y + c5 x y + c6 x y + c7 x y + ...\n% \n% To reduce numerical problems this function rescales the values of x and y to a\n% maximum magnitude of 1. The calculated coefficients are then rescaled to\n% account for this. Ideally the values of x and y would also be centred to have\n% zero mean. However, the correction that would then have to be applied to the\n% coefficients is not so simply done. If you do find that you have numerical\n% problems you could try centering x and y prior to calling this function.\n%\n% See also: POLYVAL2D\n \n% Peter Kovesi 2014\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK July 2014\n \nfunction c = polyfit2d(x, y, z, degree)\n \n % Ensure input are column vectors\n x = x(:);\n y = y(:);\n z = z(:);\n \n % To reduce numerical problems we perform normalisation of the data to keep\n % the maximum magnitude of x and y to 1.\n scale = max(abs([x; y]));\n x = x/scale;\n y = y/scale;\n \n nData = length(x);\n ncoeff = (degree+1)*(degree+2)/2;\n\n % Build Vandermonde matrix. p1 is the x exponent and p2 is the y exponent\n V = zeros(nData, ncoeff);\n\n col = 1;\n for p2 = 0:degree\n for p1 = 0:(degree-p2)\n V(:,col) = x.^p1 .* y.^p2;\n col = col+1;\n end\n end\n\n [Q,R] = qr(V,0); % Solution via QR decomposition\n c = R\\(Q'*z);\n \n if condest(R) > 1e10\n warning('Solution is ill conditioned. Coefficient values will be suspect')\n end\n \n % Scale coefficients to account for the earlier normalisation of x and y.\n col = 1;\n for p2 = 0:degree\n for p1 = 0:(degree-p2)\n c(col) = c(col)/scale^(p1+p2);\n col = col+1;\n end\n end \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "rgb2lab.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/rgb2lab.m", "size": 1063, "source_encoding": "utf_8", "md5": "29f5354eef11a490d28c05d752252407", "text": "% RGB2LAB - RGB to L*a*b* colour space\n%\n% Usage: Lab = rgb2lab(im, wp)\n%\n% Arguments: im - RGB image or Nx3 colourmap for conversion\n% wp - Optional string specifying the adapted white point.\n% This defaults to 'D65'.\n%\n% Returns: Lab - The converted image or colourmap.\n%\n% This function wraps up calls to MAKECFORM and APPLYCFORM in a convenient\n% form. Note that if the image is of type uint8 this function casts it to\n% double and divides by 255 so that RGB values are in the range 0-1 and the\n% transformed image can have the proper negative values for a and b. \n%\n% See also: LAB2RGB, RGB2NRGB, RGB2CMYK\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK May 2009\n\nfunction Lab = rgb2lab(im, wp)\n\n if ~exist('wp', 'var'), wp = 'D65'; end\n \n cform = makecform('srgb2lab',...\n 'adaptedwhitepoint', whitepoint(wp)); \n if strcmp(class(im),'uint8')\n im = double(im)/255;\n end\n Lab = applycform(im, cform);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "pathlist.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/pathlist.m", "size": 1202, "source_encoding": "utf_8", "md5": "2551671f5f3c9a17293d82ed6aee8167", "text": "% PATHLIST Produces a cell array of directories along a directory path\n%\n% Usage: plist = pathlist(fullpath)\n%\n% Example: If fullpath = '/Users/pk/Matlab/Spatial'\n% plist =\n% '/' '/Users/' '/Users/pk/' '/Users/pk/Matlab/' '/Users/pk/Matlab/Spatial'\n%\n% plist{end} is always fullpath\n% plist{end-1} is the parent directory\n% etc\n%\n% Not sure if this works appropriately under Windows\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% September 2010\n\nfunction plist = pathlist(fullpath)\n \n % Find locations of a forward or back slash in the full file name \n ind = find(fullpath == '/' | fullpath =='\\');\n \n % If there were no / or \\ in the full path just return fullpath\n if isempty(ind)\n plist{1} = fullpath;\n \n else % Step along the path and extract each incremental part\n\n for n = 1:length(ind)\n plist{n} = fullpath(1:ind(n));\n end\n \n % If there is no / or \\ at the end of the full path make fullpath the\n % final entry in the list\n if ind(end) ~= length(fullpath)\n plist{n+1} = fullpath;\n end\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "superquad.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/superquad.m", "size": 2798, "source_encoding": "utf_8", "md5": "2dfc95eb41c2bf03bb78f5f0bb8b7c07", "text": "% SUPERQUAD - generates a superquadratic surface\n%\n% Usage: [x,y,z] = superquad(xscale, yscale, zscale, e1, e2, n)\n%\n% Arguments:\n% xscale, yscale, zscale - Scaling in the x, y and z directions.\n% e1, e2 - Exponents of the x and y coords.\n% n - Number of subdivisions of logitude and latitude on\n% the surface.\n%\n% Returns: x,y,z - matrices defining paramteric surface of superquadratic\n%\n% If the result is not assigned to any output arguments the function\n% plots the surface for you, otherwise the x, y and z parametric\n% coordinates are returned for subsequent display using, say, SURFL.\n%\n% Examples:\n% superquad(1, 1, 1, 1, 1, 100) - sphere of radius 1 with 100 subdivisions\n% superquad(1, 1, 1, 2, 2, 100) - octahedron of radius 1 \n% superquad(1, 1, 1, 3, 3, 100) - 'pointy' octahedron \n% superquad(1, 1, 1, .1, .1, 100) - cube (with rounded edges)\n% superquad(1, 1, .2, 1, .1, 100) - 'square cushion'\n% superquad(1, 1, .2, .1, 1, 100) - cylinder\n%\n% See also: SUPERTORUS\n\n% Copyright (c) 2000 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2000\n\nfunction [x,y,z] = superquad(xscale, yscale, zscale, e1, e2, n)\n\n % Set up parameters of the parametric surface, in this case matrices\n % corresponding to longitude and latitude on our superquadratic sphere.\n long = ones(n,1)*[-pi:2*pi/(n-1):pi];\n lat = [-pi/2:pi/(n-1): pi/2]'*ones(1,n);\n \n x = xscale * pow(cos(lat),e1) .* pow(cos(long),e2);\n y = yscale * pow(cos(lat),e1) .* pow(sin(long),e2);\n z = zscale * pow(sin(lat),e1);\n \n % Ensure top and bottom ends are closed. If we do not do this you find\n % that due to numerical errors the ends may not be perfectly closed.\n x(1,:) = 0; y(1,:) = 0;\n x(end,:) = 0; y(end,:) = 0; \n \n if nargout == 0\n surfl(x,y,z), shading interp, colormap(copper), axis equal\n clear x y z % suppress output\n end\n\n%--------------------------------------------------------------------\n% Internal function providing a modified definition of power whereby the\n% sign of the result always matches the sign of the input value.\n\nfunction r = pow(a, p)\n \n r = sign(a).* abs(a).^p;\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "hsvmap.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/hsvmap.m", "size": 1842, "source_encoding": "utf_8", "md5": "ec6d79772fe1bba81deabf0312847a24", "text": "% HSVMAP Generates an HSV colourmap over a specified range of hues\n%\n% The function generates colours over a specified range of hues from the HSV\n% colourtmap\n%\n% map = hsvmap(hmin, hmax, N)\n%\n% Arguments: hmin - Minimum hue value 0 - 1. Default = 0\n% hmax - Maximum hue value 0 - 2. Default = 1 \n% N - Number of elements in the colourmap. Default = 256\n%\n% Note that hue values range from 0 to 1 in a cyclic manner. hmax can be set to\n% a value greater than one to allow one to specify a hue range that straddles\n% the 0 point. The resulting map is modulus 1. For example using\n% hmin = 0.9;\n% hmax = 1.1;\n% Will generate hues ranging from 0.9 up to 1.0, followed by hues 0.0 to 0.1\n%\n% hsvmap(0, 1, 256) will generate a colourmap that is identical to MATLAB's hsv\n% colourmap.\n%\n% See also: LABMAP, GRAYMAP, RANDMAP, BILATERALMAP, HSV, GRAY\n\n% Copyright (c) 2012 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% March 2012\n\nfunction map = hsvmap(hmin, hmax, N)\n \n if ~exist('N', 'var'), N = 256; end\n if ~exist('hmin', 'var'), hmin = 0; end\n if ~exist('hmax', 'var'), hmax = 1; end\n \n assert(hmax<2, 'hmax must be less than 2');\n \n h = [0:(N-1)]'/(N-0)*(hmax-hmin)+hmin;\n h(h>1) = h(h>1)-1; % Enforce hue wraparound 0-1\n \n map = hsv2rgb([h ones(N,2)]);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "rgb2nrgb.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/rgb2nrgb.m", "size": 1125, "source_encoding": "utf_8", "md5": "743c25dcc6996a893f06243bfc96fa8e", "text": "% RGB2NRGB - RGB to normalised RGB\n%\n% Usage: nrgb = rgb2nrgb(im, offset)\n%\n% Arguments: im - Colour image to be normalised\n% offset - Optional value added to (R+G+B) to discount low\n% intensity colour values. Defaults to 1\n%\n% r = R / (R + G + B) etc\n\n% Copyright (c) 2009 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n\n% May 2009\n\nfunction nrgb = rgb2nrgb(im, offset)\n \n if ndims(im) ~= 3;\n error('Image must be a colour image');\n end\n\n % Convert to double if needed and define an offset = 1/255 max value to\n % be used in the normalization to avoid division by zero\n if ~strcmp(class(im), 'double')\n im = double(im);\n if ~exist('offset', 'var'), offset = 1; end\n else % Assume we have doubles in range 0..1\n if ~exist('offset', 'var'), offset = 1/255; end\n end\n \n nrgb = zeros(size(im));\n gim = sum(im,3) + offset;\n\n nrgb(:,:,1) = im(:,:,1)./gim;\n nrgb(:,:,2) = im(:,:,2)./gim;\n nrgb(:,:,3) = im(:,:,3)./gim; "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "bbspline.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/bbspline.m", "size": 2725, "source_encoding": "utf_8", "md5": "a734eef68d0fdde4040b265425909148", "text": "% BBSPLINE - Basic B-spline\n%\n% Usage: S = bbspline(P, k, N)\n% \n% Arguments: P - [dim x Npts] array of control points\n% k - order of spline (>= 2). \n% k = 2: Linear\n% k = 3: Quadratic, etc\n% N - Optional number of points to evaluate along\n% spline. Defaults to 100.\n%\n% Returns: S - spline curve [dim x N] spline points\n%\n% See also: PBSPLINE\n\n% ** have t as an argument. If omitted it defaults to 0:0.01:1 ?\n\n% PK Jan 2014\n\n\nfunction S = bbspline(P, k, N)\n \n if ~exist('N', 'var'), N = 100; end\n \n [dim, np1] = size(P);\n n = np1-1;\n\n assert(k >= 2, 'Spline order must be 2 or greater'); \n assert(np1 >= k, 'No of control points must be >= k');\n assert(N >= 2, 'Spline must be evaluated at 2 or more points');\n\n % Knot vector for a periodic spline (does not seem to be quite right)\n% ti = 1:(k+n+1); % Periodic uniform knot vector\n\n % Set up open uniform knot vector from 0 - 1. \n % There are k repeated knots at each end.\n ti = 0:(k+n - 2*(k-1)); \n ti = ti/ti(end);\n ti = [repmat(ti(1), 1, k-1), ti, repmat(ti(end), 1, k-1)];\n \n nK = length(ti);\n \n % Generate values of t that the spline will be evaluated at\n dt = (ti(end)-ti(1))/(N-1);\n t = ti(1):dt:ti(end);\n \n % Build complete array of basis functions\n N = cell(nK, k);\n \n % 1st level of recursive construction\n for i = 1:nK-1\n N{i,1} = t >= ti(i) & t < ti(i+1) & ti(i) < ti(i+1); \n end\n\n % Subsequent levels of recursive basis construction. Note the logic to\n % handle repeated knot values where ti(i) == ti(i+1)\n for ki = 2:k \n for i = 1:nK-ki\n\n if (ti(i+ki-1) - ti(i)) < eps\n V1 = 0;\n else\n V1 = (t - ti(i))/(ti(i+ki-1) - ti(i)) .* N{i,ki-1};\n end\n \n if (ti(i+ki) - ti(i+1)) < eps\n V2 = 0;\n else\n V2 = (ti(i+ki) - t)/(ti(i+ki) - ti(i+1)) .* N{i+1,ki-1};\n end\n \n N{i,ki} = V1 + V2;\n\n% This is the ideal equation that the code above implements \n% N{i,ki} = (t - ti(i))/(ti(i+ki-1) - ti(i)) .* N{i,ki-1} + ...\n% (ti(i+ki) - t)/(ti(i+ki) - ti(i+1)) .* N{i+1,ki-1};\n end\n end\n \n % Apply basis functions to the control points\n S = zeros(dim, length(t));\n for d = 1:dim\n for i = 1:np1\n S(d,:) = S(d,:) + P(d,i)*N{i,k};\n end\n end\n \n % Set the last point of the spline. This is not evaluated by the code above\n % because the basis functions are defined from ti(i) <= t < ti(i+1)\n S(:,end) = P(:,end);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "weightedhistc.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/weightedhistc.m", "size": 1498, "source_encoding": "utf_8", "md5": "b474157c0a9fa58fc7eb358c7c7ccc37", "text": "% WEIGHTEDHISTC Weighted histogram count\n%\n% This function provides a basic equivalent to MATLAB's HISTC function for\n% weighted data. \n%\n% Usage: h = weightedhistc(vals, weights, edges)\n%\n% Arguments:\n% vals - vector of values.\n% weights - vector of weights associated with each element in vals. vals\n% and weights must be vectors of the same length.\n% edges - vector of bin boundaries to be used in the weighted histogram.\n%\n% Returns:\n% h - The weighted histogram\n% h(k) will count the weighted value vals(i) \n% if edges(k) <= vals(i) < edges(k+1). \n% The last bin will count any values of vals that match\n% edges(end). Values outside the values in edges are not counted. \n%\n% Use bar(edges,h) to display histogram\n%\n% See also: HISTC\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% November 2010\n\nfunction h = weightedhistc(vals, weights, edges)\n \n if ~isvector(vals) || ~isvector(weights) || length(vals)~=length(weights)\n error('vals and weights must be vectors of the same size');\n end\n \n Nedge = length(edges);\n h = zeros(size(edges));\n \n for n = 1:Nedge-1\n ind = find(vals >= edges(n) & vals < edges(n+1));\n if ~isempty(ind)\n h(n) = sum(weights(ind));\n end\n end\n\n ind = find(vals == edges(end));\n if ~isempty(ind)\n h(Nedge) = sum(weights(ind));\n end"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "bilateralmap.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/bilateralmap.m", "size": 2549, "source_encoding": "utf_8", "md5": "c9a16e3cdc46d415b9bb829195bb212e", "text": "% BILATERALMAP Generates a bilateral colourmap\n%\n% This function generate a colourmap where the first half has one hue and the\n% second half has another hue. Saturation varies linearly from 0 in the middle\n% to 1 at ech end. This gives a colourmap which varies from white at the middle\n% to an increasing saturation of the different hues as one moves to the ends.\n% This colourmap is useful where your data has a clear origin. The hue\n% indicates the polarity of your data, and saturation indicate amplitude.\n%\n% Usage: map = bilateralmap(H1, H2, V, N)\n%\n% Arguments:\n% H1 - Hue value for 1st half of map. This must be a value between\n% 0 and 1, defaults to 0.65 (blue).\n% H2 - Hue value for 2nd half of map, defaults to 1.0 (red).\n% V - Value as in 'V' in 'HSV', defaults to 1. Reduce this if you\n% want a darker map.\n% N - Number of elements in colourmap, defaults to 256.\n%\n% Returns:\n% map - N x 3 colourmap of RGB values.\n%\n% Some nominal hue values:\n% 0 - red\n% 0.07 - orange\n% 0.17 - yellow\n% 0.3 - green\n% 0.5 - cyan\n% 0.65 - blue\n% 0.85 - magenta\n% 1.0 - red\n%\n% See also: LABMAP, HSVMAP, GRAYMAP, RANDMAP\n\n% Copyright (c) 2012 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 2012\n\nfunction map = bilateralmap(H1, H2, V, N)\n \n % Default colourmap values\n if ~exist('H1','var'), H1 = 0.65; end % blue\n if ~exist('H2','var'), H2 = 1.00; end % red\n if ~exist('V' ,'var'), V = 1; end % 'value' of 1\n if ~exist('N', 'var'), N = 256; end \n \n % Construct map in HSV then convert to RGB at end\n Non2 = round(N/2);\n map = zeros(N,3);\n \n % First half of map has hue H1 and 2nd half H2\n map(1:Non2, 1) = H1;\n map(1+Non2 : end, 1) = H2;\n\n % Saturation varies linearly from 0 in the middle to 1 at each end\n map(1:Non2, 2) = (Non2-1:-1:0)'/Non2;\n map(1+Non2 : end, 2) = (1:N-Non2)'/(N-Non2);\n \n % Value is constant throughout\n map(:,3) = V;\n \n map = hsv2rgb(map);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "clouds.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/clouds.m", "size": 2219, "source_encoding": "utf_8", "md5": "55889e6ed17ca0979b08f7fb102f76e6", "text": "% CLOUDS\n%\n% Function to create a movie of noise images having 1/f amplitude spectum properties\n%\n% Usage: clouds(size, factor, meandev, stddev, lowvel, velfactor, nframes)\n%\n% size - size of image to produce\n% factor - controls spectrum = 1/(f^factor)\n% meandev - mean change in phaseangle per frame\n% stddev - stddev of change in phaseangle per frame\n% lowvel - phase velocity at 0 frequency \n% velfactor - phase velocity = freq^velfactor\n% nframes - no of frames in movie\n%\n% factor = 0 - raw Gaussian noise image\n% = 1 - gives the 1/f `standard' drop-off for `natural' images\n% = 1.5 - seems to give the most intersting `cloud patterns'\n% = 2 or greater - produces `blobby' images\n% PK 18-4-00\n%\n\nfunction clouds(size, factor, meandev, stddev, lowvel, velfactor, nframes)\n\nrows = size;\ncols = size;\nphase = 2*pi*rand(size,size); % Random uniform distribution 0 - 2pi\n\n% Create two matrices, x and y. All elements of x have a value equal to its \n% x coordinate relative to the centre, elements of y have values equal to \n% their y coordinate relative to the centre. From these two matrices produce\n% a radius matrix that gives distances from the middle\n\nx = ones(rows,1) * (-cols/2 : (cols/2 - 1)); \ny = (-rows/2 : (rows/2 - 1))' * ones(1,cols);\n\nx = x/(cols/2);\ny = y/(rows/2);\nradius = sqrt(x.^2 + y.^2); % Matrix values contain radius from centre.\nradius(rows/2+1,cols/2+1) = 1; % .. avoid division by zero.\n\nfilter = 1./(radius.^factor); % Construct the filter.\nfilter = fftshift(filter);\n\nphasemod = fftshift(radius.^velfactor + lowvel);\n\n% Construct fft of noise image with the specified amplitude spectrum\n\n\n\nfor n = 1:nframes\n if ~mod(n,10), fprintf('\\r %d', n); end\n dphase = meandev + stddev*randn(size,size);\n dphase = dphase.*phasemod;\n\n phase = phase + dphase;\n newfft = filter .* exp(i*phase);\n im = real(ifft2(newfft)); % Invert to obtain final noise image\n show(im,1), colormap(gray); axis('equal'), axis('off');\n\n if n==1\n CloudMovie = moviein(nframes);\n end\n\n CloudMovie(:,n) = getframe;\n\n\nend\n\nmovie(CloudMovie,-4,12);\n\nsave('CloudMovie','CloudMovie');\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "matprint.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/matprint.m", "size": 1453, "source_encoding": "utf_8", "md5": "bb847e0506584e9e043482b7a69bcbb4", "text": "% MATPRINT - prints a matrix with specified format string\n%\n% Usage: matprint(a, fmt, fid)\n%\n% a - Matrix to be printed.\n% fmt - C style format string to use for each value.\n% fid - Optional file id.\n%\n% Eg. matprint(a,'%3.1f') will print each entry to 1 decimal place\n\n% Copyright (c) 2002 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% March 2002\n\nfunction matprint(a, fmt, fid)\n \n if nargin < 3\n\tfid = 1;\n end\n \n [rows,cols] = size(a);\n \n % Construct a format string for each row of the matrix consisting of\n % 'cols' copies of the number formating specification\n fmtstr = [];\n for c = 1:cols\n fmtstr = [fmtstr, ' ', fmt];\n end\n fmtstr = [fmtstr '\\n']; % Add a line feed\n \n fprintf(fid, fmtstr, a'); % Print the transpose of the matrix because\n % fprintf runs down the columns of a matrix."} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "noiseonf.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/noiseonf.m", "size": 2320, "source_encoding": "utf_8", "md5": "fad84fc70d1aff602b459ef9097309a4", "text": "% NOISEONF - Creates 1/f spectrum noise images.\n%\n% Function to create noise images having 1/f amplitude spectum properties.\n% When displayed as a surface these images also generate great landscape\n% terrain. \n%\n% Usage: im = noiseonf(size, factor)\n%\n% size - A 1 or 2-vector specifying size of image to produce [rows cols]\n% factor - controls spectrum = 1/(f^factor)\n%\n% factor = 0 - raw Gaussian noise image\n% = 1 - gives the 1/f 'standard' drop-off for 'natural' images\n% = 1.5 - seems to give the most interesting 'cloud patterns'\n% = 2 or greater - produces 'blobby' images\n\n% Copyright (c) 1996-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n% The Software is provided \"as is\", without warranty of any kind.\n\n% December 1996\n% March 2009 Arbitrary image size \n% September 2011 Code tidy up\n% April 2014 Fixed to work with odd dimensioned images\n\nfunction im = noiseonf(sze, factor)\n \n if length(sze) == 2\n rows = sze(1); cols = sze(2);\n elseif length(sze) == 1\n rows = sze; cols = sze;\n else\n error('size must be a 1 or 2-vector');\n end\n \n % Generate an image of random Gaussian noise, mean 0, std dev 1. \n im = randn(rows,cols); \n \n imfft = fft2(im);\n mag = abs(imfft); % Get magnitude\n phase = imfft./mag; % and phase\n \n % Construct the amplitude spectrum filter\n % Add 1 to avoid divide by 0 problems later\n radius = filtergrid(rows,cols)*max(rows,cols) + 1; \n filter = 1./(radius.^factor); \n \n % Reconstruct fft of noise image, but now with the specified amplitude\n % spectrum\n newfft = filter .* phase; \n im = real(ifft2(newfft)); \n\n%caption = sprintf('noise with 1/(f^%2.1f) amplitude spectrum',factor);\n%imagesc(im), axis('equal'), axis('off'), title(caption);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "fillnan.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/fillnan.m", "size": 1673, "source_encoding": "utf_8", "md5": "dc2ec069c5ace1262d2f396fd2fa6f8e", "text": "% FILLNAN - fills NaN values in an image with closest non Nan value\n%\n% NaN values in an image are replaced with the value in the closest pixel\n% that is not a NaN.\n%\n% Usage: [newim, mask] = fillnan(im);\n%\n% Argument: im - Image to be 'filled'\n% Returns: newim - Filled image\n% mask - Binary image indicating regions in the original image\n% which were non NaN\n%\n% See Also: REMOVENAN\n\n\n% Copyright (c) 2007 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n\nfunction [newim, mask] = fillnan(im);\n \n % Generate distance transform from non NaN regions of the image. \n % L will contain indices of closest non NaN points in the image\n mask = ~isnan(im); \n \n if all(isnan(im(:)))\n newim = im;\n warning('All elements are NaN, no filling possible\\n');\n return\n end\n \n [dist,L] = bwdist(mask); \n \n [r,c] = find(isnan(im)); % Indices of points that are NaN\n \n newim = im;\n \n % Fill NaN locations with value of closest non NaN pixel\n for n = 1:length(r)\n\t newim(r(n),c(n)) = im(L(r(n),c(n)));\n end\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "testdbscan.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/testdbscan.m", "size": 2247, "source_encoding": "utf_8", "md5": "aa690910417795cfda803d2e25a271c2", "text": "% TESTDBSCAN Program to test/demonstrate the DBSCAN clustering algorithm\n%\n% Simple usage: testdbscan;\n%\n% Full usage: [C, ptsC] = testdbscan(E, minPts)\n% \n% \n% Arguments: \n% E - Distance threshold for clustering. Defaults to 0.3\n% minPts - Minimum number of points required to form a cluster. \n% Defaults to 3 \n%\n% Returns:\n% C - Cell array of length Nc listing indices of points associated with\n% each cluster.\n% ptsC - Array of length Npts listing the cluster number associated with\n% each point. If a point is denoted as noise (not enough nearby\n% elements to form a cluster) its cluster number is 0.\n%\n% See also: DBSCAN\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% Jan 2013\n\nfunction [C, ptsC, centres] = testdbscan(E, minPts)\n \n if ~exist('E', 'var'), E = 0.3; end;\n if ~exist('minPts', 'var'), minPts = 3; end;\n \n figure(1), clf, axis([-1 1 -1 1]);\n \n fprintf('Digitise a series of points that form some clusters. Right-click to finish\\n');\n [x,y] = digipts;\n hold on\n \n % Perform clustering\n P = [x'; y'];\n [C, ptsC, centres] = dbscan(P, E, minPts);\n \n \n for n = 1:length(x)\n text(x(n),y(n)+.04, sprintf('%d',ptsC(n)), 'color', [0 0 1]);\n end\n title('Points annotated by cluster number')\n hold off\n \n%--------------------------------------------------------------------------\n% DIGIPTS - digitise points in an image\n%\n% Function to digitise points in an image. Points are digitised by clicking\n% with the left mouse button. Clicking any other button terminates the\n% function. Each location digitised is marked with a red '+'.\n%\n% Usage: [u,v] = digipts\n%\n% where u and v are nx1 arrays of x and y coordinate values digitised in\n% the image.\n%\n% This function uses the cross-hair cursor provided by GINPUT. This is\n% much more useable than IMPIXEL\n\nfunction [u,v] = digipts\n \n hold on\n u = []; v = [];\n but = 1;\n while but == 1\n\t[x y but] = ginput(1);\n\tif but == 1\n\t u = [u;x];\n\t v = [v;y];\n\t \n\t plot(u,v,'r+');\n\tend\n end\n \n hold off\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "polartrans.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/polartrans.m", "size": 3367, "source_encoding": "utf_8", "md5": "9aed63869d7ac444d0e2198fcd91e306", "text": "% POLARTRANS - Transforms image to polar coordinates\n%\n% Usage: pim = polartrans(im, nrad, ntheta, cx, cy, linlog, shape)\n%\n% Arguments:\n% im - image to be transformed.\n% nrad - number of radius values.\n% ntheta - number of theta values.\n% cx, cy - optional specification of origin. If this is not\n% specified it defaults to the centre of the image.\n% linlog - optional string 'linear' or 'log' to obtain a\n% transformation with linear or logarithmic radius\n% values. linear is the default.\n% shape - optional string 'full' or 'valid'\n% 'full' results in the full polar transform being\n% returned (the circle that fully encloses the original\n% image). This is the default.\n% 'valid' returns the polar transform of the largest\n% circle that can fit within the image. \n%\n% Returns pim - image in polar coordinates with radius increasing\n% down the rows and theta along the columns. The size\n% of the image is nrad x ntheta. Note that theta is\n% +ve clockwise as x is considered +ve along the\n% columns and y +ve down the rows. \n%\n% When specifying the origin it is assumed that the top left pixel has\n% coordinates (1,1).\n\n% Copyright (c) 2002 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% December 2002\n% November 2006 Correction to calculation of maxlogr (thanks to Chang Lei)\n\nfunction pim = polartrans(im, nrad, ntheta, cx, cy, linlog, shape)\n\n[rows, cols] = size(im);\n\nif nargin==3 % Set origin to centre.\n cx = cols/2+.5; % Add 0.5 because indexing starts at 1\n cy = rows/2+.5;\nend\n\nif nargin < 7, shape = 'full'; end\nif nargin < 6, linlog = 'linear'; end\n\nif strcmp(shape,'full') % Find maximum radius value\n dx = max([cx-1, cols-cx]);\n dy = max([cy-1, rows-cy]);\n rmax = sqrt(dx^2+dy^2);\nelseif strcmp(shape,'valid') % Find minimum radius value\n rmax = min([cx-1, cols-cx, cy-1, rows-cy]);\nelse\n error('Invalid shape specification');\nend\n\n% Increments in radius and theta\n\ndeltatheta = 2*pi/ntheta;\n\nif strcmp(linlog,'linear')\n deltarad = rmax/(nrad-1);\n [theta, radius] = meshgrid([0:ntheta-1]*deltatheta, [0:nrad-1]*deltarad); \nelseif strcmp(linlog,'log')\n maxlogr = log(rmax);\n deltalogr = maxlogr/(nrad-1); \n [theta, radius] = meshgrid([0:ntheta-1]*deltatheta, exp([0:nrad-1]*deltalogr));\nelse\n error('Invalid radial transformtion (must be linear or log)');\nend\n\nxi = radius.*cos(theta) + cx; % Locations in image to interpolate data\nyi = radius.*sin(theta) + cy; % from. \n\n[x,y] = meshgrid([1:cols],[1:rows]);\npim = interp2(x, y, double(im), xi, yi);\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "labmap.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/labmap.m", "size": 8483, "source_encoding": "utf_8", "md5": "e7cda593bf59d9e52b88e7ef4e13bb57", "text": "% LABMAP - Generates a colourmap based on L*a*b* space\n%\n% This function can generate a wide range of colourmaps but it can be a bit\n% difficult to drive...\n%\n% The idea: Create a spiral path within in L*a*b* space to use as a\n% colourmap. L*a*b* space is designed to be perceptually uniform so, in\n% principle, it should be a good space in which to design colourmaps.\n%\n% L*a*b* space is treated (a bit inappropriately) as a cylindrical colourspace.\n% The spiral path is created by specifying linear ramps in: the angular value\n% around the origin of the a*b* plane; the Lightness variation; and the\n% saturation (the radius out from the centre of the a*b* plane).\n%\n% As an alternative an option is available to use a simple straight line\n% interpolation from the first colour, through the colourspace, to the final\n% colour. One is much less likely to go outside of the rgb gamut but the\n% variety of colourmaps will be limited\n%\n% Usage: map = labmap(theta, L, saturation, N, linear, debug)\n%\n% Arguments:\n% theta - 2-vector specifyinhg start and end angles in the a*b*\n% plane over which to define the colourmap (radians).\n% These angles specify a +ve or -ve ramp of values over\n% which opponent colour values vary. If you want\n% values to straddle the origin use theta values > 2pi\n% or < 0 as needed. \n% L - 2-vector specifying the lightness variation from\n% start to end over the colourmap. Values are in the\n% range 0-100. (You normally want a lightness\n% variation over the colourmap)\n% saturation - 2-vector specifying the saturation variation from\n% start to end over the colourmap. This specifies the\n% radius out from the centre of the a*b* plane where\n% the colours are defined. Values are in the range 0-127. \n% N - Number of elements in the colourmap. Default = 256.\n% linear - Flag 0/1. If this flag is set a simple straight line\n% interpolation, from the first to last colour, through\n% the colourspace is used. Default value is 0.\n% debug - Optional flag 0/1. If debug is set a plot of the\n% colourmap is displayed along with a diagnostic plot\n% of the specified L*a*b* values is generated along\n% with the values actually achieved. These are usually\n% quite different due to gamut limitations. However,\n% as long as the lightness varies in a near linear\n% fashion the colourmap is probably ok.\n%\n% theta, L and saturation can be specified as single values in which case\n% they are assumed to be specifying a 'ramp' of constant value.\n%\n% The colourmap is generated from a* and b* values that form a spiral about\n% the point (0, 0). a* = saturation*cos(theta) and b* = saturation*sin(theta)\n% while Lightness varies along the specified ramp.\n% a* +ve indicates magenta, a* -ve indicates cyan \n% b* +ve indicates yellow, b* -ve indicates blue\n%\n% Changing lightness values can change things considerably and you will need\n% some experimentation to get the colours you want. It is often useful to try\n% reversing the lightness ramp on your coloumap to see what it does. Note also\n% it is quite possible (quite common) to end up specifying L*a*b* values that\n% are outside the gamut of RGB space. Run the function with the debug flag\n% set to monitor this.\n%\n% A weakness of this simple cylindrical coordinate approach used here is that it\n% generates colours that are out of gamut far too readily. To do: A better approach\n% might be to show the allowable colours for a set of lightness values, allow\n% the user to specify 3 colours, and then fit some kind of spline through these\n% colours in lab space.\n%\n% L*a*b* space is more perceptually uniform than, say, HSV space. HSV and other\n% rainbow-like colourmaps can be quite problematic, especially around yellow\n% because lightness varies in a non-linear way along the colourmap. Personally I\n% find you can generate some rather nice colourmaps with LABMAP.\n% \n%\n% Coordinates of standard colours in L*a*b* space and in cylindrical coordinates\n% \n% red L 54 a 81 b 70 theta 0.7 radius 107\n% green L 88 a -79 b 81 theta 2.3 radius 113\n% blue L 30 a 68 b -112 theta -1.0 radius 131\n% yellow L 98 a -16 b 93 theta 1.7 radius 95\n% cyan L 91 a -51 b -15 theta -2.9 radius 53\n% magenta L 60 a 94 b -61 theta -0.6 radius 111\n%\n% Example colourmaps:\n%\n% labmap([pi pi/2], [20 100], [60 127]); % Dark green to yellow colourmap\n% labmap([3*pi/2 pi/3], [10 100], [60 127]); % Blue to yellow\n% labmap([3*pi/2 9*pi/4], [10 60], [60 127]); % Blue to red\n% lapmap( 0, [0 100], 0); % Lightness greyscale\n%\n% See also: VIEWLABSPACE, HSVMAP, GRAYMAP, HSV, GRAY, RANDMAP, BILATERALMAP\n\n% Copyright (c) 2012-2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% March 2012 \n% March 2013 Allow theta, lightness and saturation to vary as a ramps. Allow\n% cylindrical and linear interpolation across the colour space\n\nfunction map = labmap(theta, L, sat, N, linear, debug)\n \n if ~exist('theta', 'var'), theta = [0 2*pi]; end\n if ~exist('L', 'var'), L = 60; end \n if ~exist('sat', 'var'), sat = 127; end \n if ~exist('N', 'var'), N = 256; end\n if ~exist('linear', 'var'), linear = 0; end\n if ~exist('debug', 'var'), debug = 0; end\n\n if length(theta) == 1, theta = [theta theta]; end\n if length(L) == 1, L = [L L]; end\n if length(sat) == 1, sat = [sat sat]; end\n \n if ~linear % Use cylindrical interpolation\n % Generate linear ramps in theta, lightness and saturation\n thetar = [0:N-1]'/(N-1) * (theta(2)-theta(1)) + theta(1);\n Lr = [0:N-1]'/(N-1) * (L(2)-L(1)) + L(1);\n satr = [0:N-1]'/(N-1) * (sat(2)-sat(1)) + sat(1);\n \n lab = [Lr satr.*cos(thetar) satr.*sin(thetar)];\n map = applycform(lab, makecform('lab2srgb'));\n \n else % Interpolate a straight line between start and end colours\n c1 = [L(1) sat(1)*cos(theta(1)) sat(1)*sin(theta(1))];\n c2 = [L(2) sat(2)*cos(theta(2)) sat(2)*sin(theta(2))];\n dc = c2-c1;\n \n lab = [[0:N-1]'/(N-1).*dc(:,1)+c1(:,1) [0:N-1]'/(N-1).*dc(:,2)+c1(:,2)...\n [0:N-1]'/(N-1).*dc(:,3)+c1(:,3)];\n map = applycform(lab, makecform('lab2srgb'));\n end\n \n if debug\n % Display colourmap \n ramp = repmat(0:0.5:255, 100, 1);\n show(ramp,1), colormap(map);\n \n % Test 'integrity' of colourmap. Convert rgb back to lab. If this is\n % significantly different from the original lab map then we have gone\n % outside the rgb gamut\n labmap = applycform(map, makecform('srgb2lab')); \n \n diff = lab-labmap;\n R = 1:N;\n figure(2), plot(R,lab(:,1),'k-',R,lab(:,2),'r-',R,lab(:,3),'b-',...\n R,labmap(:,1),'k--',R,labmap(:,2),'r--',R,labmap(:,3),'b--')\n \n legend('Specified L', 'Specified a*', 'Specified b*',...\n 'Achieved L', 'Achieved a*', 'Achieved b*')\n title('Specified and achieved L*a*b* values in colourmap')\n \n % Crude threshold on adherance to specified lab values\n if max(diff(:)) > 10\n warning(sprintf(['Colormap is probably out of gamut. \\nMaximum difference' ...\n ' between desired and achieved lab values is %d'], ...\n round(max(diff(:)))));\n end\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "basename.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/basename.m", "size": 549, "source_encoding": "utf_8", "md5": "619048021d1d621f2344798ad8fec477", "text": "% BASENAME Trims off the .ending of a filename\n%\n% Usage: bname = basename(name)\n%\n% Argument: name - Name of a file with a .ending\n% Returns: bname - Name with the suffix trimmed\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% August 2010\n\nfunction bname = basename(name)\n \n % Find last instance of a '.' in the file name\n ind = find(name == '.', 1, 'last');\n \n if isempty(ind)\n bname = name;\n else\n bname = name(1:ind(end)-1);\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "showfft.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/showfft.m", "size": 1588, "source_encoding": "utf_8", "md5": "a10b28024b7bb20f06be15f948efa5b2", "text": "% SHOWFFT - Displays amplitude spectrum of an fft.\n%\n% Usage: showfft(ft, figNo)\n%\n% Arguments: ft - Fourier transform to be displayed\n% figNo - Optional figure number to display image in.\n%\n% The fft is quadrant shifted to place zero frequency at the centre.\n%\n% If figNo is omitted a new figure window is created. If figNo is supplied,\n% and the figure exists, the existing window is reused to display the image,\n% otherwise a new window is created.\n\n% Copyright (c) 1999 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 1999\n% September 2008 Octave compatible\n\nfunction showfft(im, figNo)\n\n Octave = exist('OCTAVE_VERSION', 'builtin') == 5; % Are we running under Octave\n Title = inputname(1); % Get variable name of image data \n \n if nargin == 2\n\tfigure(figNo); % Reuse or create a figure window with this number\n else\n\tfigNo = figure; % Create new figure window\n end\n\n imagesc(fftshift(abs(im)));\n colormap(gray); title(Title), axis('image')\n if ~Octave; truesize(figNo) end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "deres.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/deres.m", "size": 525, "source_encoding": "utf_8", "md5": "013e5ac5596abe1811cec7954e1abca0", "text": "% DERES - Deresolves an image.\n%\n% Usage: im2 = deres(im, s)\n%\n% Arguments: im - image to be deresolved\n% s = deresolution factor\n%\n% Returns the deresolved image\n\n% PK October 2000\n\nfunction im2 = deres(im, s)\n\n if ndims(im) == 3 % Assume colour image\n\tim2 = zeros(size(im));\n\tim2(:,:,1) = blkproc(im(:,:,1),[s s], 'mean2(x)');\n\tim2(:,:,2) = blkproc(im(:,:,2),[s s], 'mean2(x)');\n\tim2(:,:,3) = blkproc(im(:,:,3),[s s], 'mean2(x)');\n else\n\tim2 = blkproc(im,[s s], 'mean2(x)');\n end\n \n \n\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "showangularim.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/showangularim.m", "size": 5543, "source_encoding": "utf_8", "md5": "75afab7bd1c9c526602370d0b685a282", "text": "% SHOWANGULARIM - Displays image of angular data\n%\n% For angular data to be rendered correctly it is important that the data values\n% are respected so that data values are correctly assigned to specific entries\n% in a cyclic colour map. The assignment of values to colours also depends on\n% whether the data is cyclic over pi, or 2*pi. \n%\n% In contrast, default display methods typically do not respect data values\n% directly and can perform inappropriate offsetting and normalisation of the\n% angular data before display and rendering with a colour map.\n%\n% The rendering of the angular data with a specified colour map can be modulated\n% as a function of an associated image amplitude. This allows the colour map\n% encoding of the angular information to be modulated to represent the\n% amplitude/reliability/coherence of the angular data.\n%\n% Usage: rgbim = showangularim(ang, map);\n% rgbim = showangularim(ang, map, param_name, value, ...);\n%\n% Arguments:\n% ang - Image of angular data to be displayed.\n% map - Colour map to render the angular data with, ideally a\n% cyclic colour map. \n%\n% Possible param_name - value options \n%\n% 'amp' - Amplitude image used to modulate the mapped colours of the\n% angular data. If not supplied no modulation of colours is\n% performed. \n% 'bw' - Flag 0/1 indicating whether the amplitude image is used to\n% modulate the colour mapped image values towards black, 0\n% or white, 1. The default is 0, towards black.\n% 'cycle' - The cycle length of the angular data. Use a value of pi\n% if the data represents orientations, or 2*pi if the data\n% represents phase values. If the input data is in degrees\n% simply set cycle in degrees and the data will be\n% rendered appropriately. Default is 2*pi.\n% 'fig' - Optional figure number to use. If not specified a new\n% figure is created. If set to 0 the function runs\n% 'silently' returning rgbim without displaying the image. \n%\n% Returns: rgbim - The rendered image.\n%\n% Parameter name strings can be abbreviated to their first letter except for\n% 'amp' which can only be abbreviated to 'am'\n%\n% For a list of all cyclic colour maps that can be generated by LABMAPLIB use:\n% >> labmaplib('cyclic') \n%\n% See also: SCALOGRAM, RIDGEORIENT, LABMAPLIB, APPLYCOLOURMAP\n\n% Copyright (c) 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2014\n% October 2014 Changed optional argument handling to param_name - value pairs\n\n%function rgbim = showangularim(ang, amp, map, cycle, bw, fig)\nfunction rgbim = showangularim(varargin)\n \n [ang, amp, map, cycle, bw, fig] = parseinputs(varargin{:});\n \n % Apply colour map to angular data. Some care is needed with this. Unlike\n % normal 'linear' data one cannot apply shifts and/or rescale values to\n % normalise them. The raw angular data values have to be respected.\n \n ang = mod(ang, cycle); % Ensure data values are within range 0 - cycle\n rgbim = applycolourmap(ang, map, [0 cycle]); \n \n if ~isempty(amp) % Display image with rgb values modulated by amplitude \n \n amp = normalise(amp); % Enforce amplitude 0 - 1\n \n if ~bw % Modulate rgb values by amplitude fading to black\n for n = 1:3\n rgbim(:,:,n) = rgbim(:,:,n).*amp;\n end\n \n else % Modulate rgb values by amplitude fading to white\n for n = 1:3\n rgbim(:,:,n) = 1 - (1 - rgbim(:,:,n)).*amp;\n end \n end\n end\n \n if fig\n show(rgbim,fig)\n end\n \n % If function was not called with any output arguments clear rgbim so that\n % it is not printed on the screen.\n if ~nargout\n clear('rgbim')\n end\n \n\n%-----------------------------------------------------------------------\n% Function to parse the input arguments and set defaults\n\nfunction [ang, amp, map, cycle, bw, fig] = parseinputs(varargin)\n \n p = inputParser;\n\n numericORlogical = @(x) isnumeric(x) || islogical(x);\n \n % The first arguments are the image of angular data and the colour map.\n addRequired(p, 'ang', @isnumeric); \n addRequired(p, 'map', @isnumeric); \n \n % Optional parameter-value pairs and their defaults \n addParameter(p, 'amp', [], @isnumeric); \n addParameter(p, 'cycle', 2*pi, @isnumeric); \n addParameter(p, 'bw', 0, numericORlogical); \n addParameter(p, 'fig', -1, @isnumeric); \n \n parse(p, varargin{:});\n \n ang = p.Results.ang;\n map = p.Results.map; \n amp = p.Results.amp;\n cycle = p.Results.cycle; \n bw = p.Results.bw; \n fig = p.Results.fig; \n if fig < 0, fig = figure; end\n \n if ~isempty(amp) && ~all(size(amp)==size(ang))\n error('Amplitude data must be same size as angular data');\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "sineramp.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/sineramp.m", "size": 6455, "source_encoding": "utf_8", "md5": "05497c013c694f1734bc5d8f1a51fe4a", "text": "% SINERAMP - Generates sine on a ramp colour map test image\n%\n% The test image consists of a sine wave superimposed on a ramp function The\n% amplitude of the sine wave is modulated from its full value at the top of the\n% image to 0 at the bottom. \n%\n% The image is useful for evaluating the effectiveness of different colour maps.\n% Ideally the sine wave pattern should be equally discernible over the full\n% range of the colour map. In addition, across the bottom of the image, one\n% should not see any identifiable features as the underlying signal is a smooth\n% ramp. In practice many colour maps have uneven perceptual contrast over their\n% range and often include 'flat spots' of no perceptual contrast that can hide\n% significant features.\n%\n% Usage: im = sineramp(sze, amp, wavelen, p)\n% im = sineramp;\n%\n% Arguments: sze - [rows cols] specifying size of test image. If a\n% single value is supplied the image is square. \n% Defaults to [256 512]; Note the number of columns is\n% nominal and will be ajusted so that there are an\n% integer number of sine wave cycles across the image.\n% amp - Amplitude of sine wave. Defaults to 12.5\n% wavelen - Wavelength of sine wave in pixels. Defaults to 8.\n% p - Power to which the linear attenuation of amplitude, \n% from top to bottom, is raised. For no attenuation use\n% p = 0. For linear attenuation use a value of 1. For\n% contrast sensitivity experiments use larger values of\n% p. The default value is 2. \n% \n% The ramp function that the sine wave is superimposed on is adjusted slightly\n% for each row so that each row of the image spans the full data range of 0 to\n% 255. Thus using a large sine wave amplitude will result in the ramp at the\n% top of the test image being reduced relative to the slope of the ramp at\n% the bottom of the image.\n%\n% To start with try\n% >> im = sineramp; \n%\n% This is equivalent to \n% >> im = sineramp([256 512], 12.5, 8, 2);\n%\n% View it under 'gray' then try the 'jet', 'hsv', 'hot' etc colour maps. The\n% results may cause you some concern!\n%\n% If you are wishing to evaluate a cyclic colour map, say hsv, it is suggested\n% that you use the test image generated CIRCLESINERAMP. However you can use\n% this function to perform a basic evaluation of a cyclic colour map by\n% displaying two copies of the SINERAMP test image concatenated side-by-side.\n%\n% >> show([sineramp sineramp]), colour map(map_to_be_tested)\n%\n% However, note that despite there being an integer number of sine wave cycles\n% across the image and that each row has been adjusted to span the full data\n% range there will be a slight cyclic discontinuity at the top of the image,\n% though this is progressively removed as you move down the test image. \n%\n% See source code comments for more details on the default wavelength and amplitude.\n%\n% See also: CIRCLESINERAMP, CHIRPLIN, CHIRPEXP, EQUALISECOLOURMAP, CMAP\n\n\n% The Default Wavelength:\n% The default wavelength is 8 pixels. On a computer monitor with a nominal\n% pixel pitch of 0.25mm this corresponds to a wavelength of 2mm. With a monitor\n% viewing distance of 600mm this corresponds to 0.19 degrees of viewing angle or\n% approximately 5.2 cycles per degree. This falls within the range of spatial\n% frequencies (3-7 cycles per degree ) at which most people have maximal\n% contrast sensitivity to a sine wave grating (this varies with mean luminance).\n% A wavelength of 8 pixels is also sufficient to provide a reasonable discrete\n% representation of a sine wave. The aim is to present a stimulus that is well\n% matched to the performance of the human visual system so that what we are\n% primarily evaluating is the colour map's perceptual contrast and not the visual\n% performance of the viewer.\n%\n% The Default Amplitude:\n% This is set at 12.5 so that from peak to trough we have a local feature of\n% magnitude 25. This is approximately 10% of the 256 levels in a standard\n% colour map. It is not uncommon for colour maps to have perceptual flat spots\n% that can hide features of this magnitude.\n\n% Copyright (c) 2013-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% July 2013 Original version.\n% March 2014 Adjustments to make it better for evaluating cyclic colour maps.\n% June 2014 Default wavelength changed from 10 to 8.\n\nfunction im = sineramp2(sze, amp, wavelen, p)\n\n if ~exist('sze','var'), sze = [256 512]; end\n if ~exist('amp','var'), amp = 12.5; end\n if ~exist('wavelen','var'), wavelen = 8; end\n if ~exist('p','var'), p = 2; end\n \n if length(sze) == 1\n rows = sze; cols = sze;\n elseif length(sze) == 2\n rows = sze(1); cols = sze(2);\n else\n error('size must be a 1 or 2 element vector');\n end\n\n % Adjust width of image so that we have an integer number of cycles of\n % the sinewave. This is helps should one be using the test image to\n % evaluate a cyclic colour map. However you will still see a slight\n % cyclic discontinuity at the top of the image, though this will\n % disappear at the bottom of the test image\n \n cycles = round(cols/wavelen);\n cols = cycles*wavelen;\n \n % Sine wave\n x = 0:cols-1;\n fx = amp*sin( 1/wavelen * 2*pi*x);\n \n % Vertical modulating function\n A = ([(rows-1):-1:0]/(rows-1)).^p;\n im = A'*fx;\n \n % Add ramp\n ramp = meshgrid(0:(cols-1), 1:rows)/(cols-1);\n im = im + ramp*(255 - 2*amp);\n \n % Now normalise each row so that it spans the full data range from 0 to 255.\n % Again, this is important for evaluation of cyclic colour maps though a\n % small cyclic discontinuity will remain at the top of the test image.\n for r = 1:rows\n im(r,:) = normalise(im(r,:));\n end\n im = im * 255;\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "pbspline.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/pbspline.m", "size": 3360, "source_encoding": "utf_8", "md5": "0f159d999c118e226bfb35f4cd46b581", "text": "% PBSPLINE - Basic Periodic B-spline\n%\n% Usage: S = pbspline(P, k, N)\n% \n% Arguments: P - [dim x Npts] array of control points\n% k - order of spline (>= 2). \n% k = 2: Linear\n% k = 3: Quadratic, etc\n% N - Optional number of points to evaluate along\n% spline. Defaults to 100.\n%\n% Returns: S - spline curve [dim x N] spline points\n%\n% See also: BBSPLINE\n\n% PK March 2014\n\n% Needs a bit of tidying up and checking on domain of curve\n\nfunction S = pbspline(P, k, N)\n \n if ~exist('N', 'var'), N = 100; end\n \n % For a closed spline check if 1st and last control points match. If not\n % add another control point so that they do match\n if norm(P(:,1) - P(:,end)) > 0.01\n P = [P P(:,1)];\n end\n \n % Now add k - 1 control points that wrap over the first control points\n P = [P P(:,2:2+k-1)];\n \n [dim, np1] = size(P);\n n = np1-1;\n\n assert(k >= 2, 'Spline order must be 2 or greater'); \n assert(np1 >= k, 'No of control points must be >= k');\n assert(N >= 2, 'Spline must be evaluated at 2 or more points');\n \n % Form a uniform sequence. Number of knot points is m + 1 where m = n + k + 1\n ti = [0:(n+k+1)]/(n+k+1);\n nK = length(ti);\n\n % Domain of curve is [ti_k to ti_n] or [ti_(k+1) to ti_(n+1)] ???\n tstart = ti(k);\n tend = ti(n);\n\n dt = (tend-tstart)/(N-1);\n t = tstart:dt:tend;\n \n % Build complete array of basis functions\n N = cell(nK, k);\n \n % 1st level of recursive construction\n for i = 1:nK-1\n N{i,1} = t >= ti(i) & t < ti(i+1) & ti(i) < ti(i+1); \n end\n\n % Subsequent levels of recursive basis construction. Note the logic to\n % handle repeated knot values where ti(i) == ti(i+1)\n for ki = 2:k \n for i = 1:nK-ki\n\n if (ti(i+ki-1) - ti(i)) < eps\n V1 = 0;\n else\n V1 = (t - ti(i))/(ti(i+ki-1) - ti(i)) .* N{i,ki-1};\n end\n \n if (ti(i+ki) - ti(i+1)) < eps\n V2 = 0;\n else\n V2 = (ti(i+ki) - t)/(ti(i+ki) - ti(i+1)) .* N{i+1,ki-1};\n end\n \n N{i,ki} = V1 + V2;\n\n% This is the ideal equation that the code above implements \n% N{i,ki} = (t - ti(i))/(ti(i+ki-1) - ti(i)) .* N{i,ki-1} + ...\n% (ti(i+ki) - t)/(ti(i+ki) - ti(i+1)) .* N{i+1,ki-1};\n end\n end\n \n % Apply basis functions to the control points\n S = zeros(dim, length(t));\n for d = 1:dim\n for i = 1:np1\n S(d,:) = S(d,:) + P(d,i)*N{i,k};\n end\n end\n \n % Finally, because of the knot arrangements, the start of the spline may not\n % be close to the first control point if the spline order is 3 or greater.\n % Normally for a closed spline this is irrelevant. However for our purpose\n % of using closed bplines to form paths in a colourspace this is important to\n % us. The simple brute force solution used here is to search through the\n % spline points for the point that is closest to the 1st control point and\n % then rotate the spline points accordingly\n \n distsqrd = 0;\n for d = 1:dim\n distsqrd = distsqrd + (S(d,:) - P(d,1)).^2;\n end\n \n [~,ind] = min(distsqrd);\n \n S = circshift(S, [0, -ind+1]);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "cloud9.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/cloud9.m", "size": 3590, "source_encoding": "utf_8", "md5": "3ce5e64cce1547247f3b914e7a6fc5c8", "text": "% CLOUD9 - Cloud movie of 1/f noise.\n%\n% Function to create a movie of noise images having 1/f amplitude spectum\n% properties.\n%\n% Usage: CloudMovie = cloud9(size, factor, nturns, velfactor, nframes)\n%\n% size - [rows cols] size of image to produce\n% factor - controls spectrum = 1/(f^factor)\n% nturns - No of 2pi cycles phase can change over the whole sequence\n% lowvel - phase velocity at 0 frequency \n% velfactor - phase velocity = freq^velfactor\n% nframes - no of frames in movie\n%\n% factor = 0 - raw Gaussian noise image\n% = 1 - gives the 1/f `standard' drop-off for `natural' images\n% = 1.5 - seems to give the most intersting `cloud patterns'\n% = 2 or greater - produces `blobby' images\n%\n% Favourite parameters:\n% m = cloud9([480 640], 1.5, 4, 1, .1, 100);\n%\n\n% Copyright (c) 2000 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% April 2000\n\n\nfunction CloudMovie = cloud9(sze, factor, nturns, lowvel, velfactor, nframes)\n\nrows = sze(1);\ncols = sze(2);\nphase = i*random('Uniform',0,2*pi,rows,cols); % Random uniform distribution 0 - 2pi\n\n% Create two matrices, x and y. All elements of x have a value equal to its \n% x coordinate relative to the centre, elements of y have values equal to \n% their y coordinate relative to the centre. From these two matrices produce\n% a radius matrix that gives distances from the middle\n\nx = ones(rows,1) * (-cols/2 : (cols/2 - 1)); % x = x/(cols/2);\ny = (-rows/2 : (rows/2 - 1))' * ones(1,cols);% y = y/(rows/2);\n\nradius = sqrt(x.^2 + y.^2); % Matrix values contain radius from centre.\nradius(rows/2+1,cols/2+1) = 1; % .. avoid division by zero.\n\namp = 1./(radius.^factor); % Construct the amplitude spectrum\namp = fftshift(amp);\n\nphasemod = round(fftshift(radius.^velfactor + lowvel));\n\nphasechange = 2*pi*((random('unid',nturns+1,rows,cols) -1 - nturns/2) .* phasemod );\n\nmaxturns = max(max(phasechange/(2*pi)))\nmaxturns = min(min(phasechange/(2*pi)))\nminturns = min(min(abs(phasechange)/(2*pi)))\n\ndphase = i*phasechange/(nframes-1); % premultiply by i to save time in th eloop\n\n% Construct fft of noise image with the specified amplitude spectrum\n\nfig = figure(1), warning off, imagesc(zeros(rows,cols)), axis('off'), truesize(1)\n\n\nset(fig,'DoubleBuffer','on');\n%set(gca,'xlim',[-80 80],'ylim',[-80 80],...\n% \t 'NextPlot','replace','Visible','off')\nmov = avifile('cloud')\n\na = 0.7; % Set up colormap\nmap = a*bone + (1-a)*gray;\n\nfor n = 1:nframes\n fprintf('frame %d/%d \\r',n, nframes);\n\n phase = phase + dphase;\n newfft = amp .* exp(phase);\n im = real(ifft2(newfft)); % Invert to obtain final noise image\n imagesc(im), colormap(bone),axis('equal'), axis('off'), truesize(1)\n\n %if n==1\n % CloudMovie = moviein(nframes); % initialise movie storage\n %end\n F = getframe(gca);\n mov = addframe(mov,F);\n %CloudMovie(:,n) = getframe;\nend\nfprintf('\\n');\nwarning on\n mov = close(mov);\n%movie(CloudMovie,5,30);\n%save('CloudMovie','CloudMovie');\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "circle.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/circle.m", "size": 1226, "source_encoding": "utf_8", "md5": "3ce939f9b481cd974576f40a598a69b6", "text": "% CIRCLE - Draws a circle.\n%\n% Usage: circle(c, r, n, col)\n%\n% Arguments: c - A 2-vector [x y] specifying the centre.\n% r - The radius.\n% n - Optional number of sides in the polygonal approximation.\n% (defualt is 16 sides)\n% col - optional colour, defaults to blue.\n\n% Copyright (c) 1996-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction h = circle(c, r, nsides, col)\n \n if nargin == 2\n\tnsides = 16;\n end\n \n if nargin < 4\n\tcol = [0 0 1];\n end\n \n nsides = max(round(nsides),3); % Make sure it is an integer >= 3\n \n a = [0:2*pi/nsides:2*pi];\n h = line(r*cos(a)+c(1), r*sin(a)+c(2), 'color', col);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "showdivim.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/showdivim.m", "size": 2519, "source_encoding": "utf_8", "md5": "9205933da4b7d7051f7944c5724dc03b", "text": "% SHOWDIVIM - Displays image with diverging colour map\n%\n% For data to be displayed correctly with a diverging colour map it is\n% important that the data values are respected so that the reference value in\n% the data is correctly associated with the centre entry of a diverging\n% colour map.\n%\n% In contrast, default display methods typically do not respect data values\n% directly and can perform inappropriate offsetting and normalisation of the\n% angular data before display and rendering with a colour map.\n%\n% Usage: rgbim = showdivim(im, map, refval, fig)\n%\n% Arguments:\n% im - Image to be displayed.\n% map - Colour map to render the data with.\n% refval - Reference value to be associated with centre point of\n% diverging colour map. Defaults to 0.\n% fig - Optional figure number to use. If not specified a new\n% figure is created. If set to 0 the function runs\n% 'silently' returning rgbim without displaying the image. \n% Returns: \n% rgbim - The rendered image.\n%\n% For a list of all diverging colour maps that can be generated by LABMAPLIB\n% use: >> labmaplib('div')\n%\n% See also: SHOW, SHOWANGULARIM, APPLYCOLOURMAP\n\n% Copyright (c) 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% PK October 2014\n\nfunction rgbim = showdivim(im, map, refval, fig)\n \n if ~exist('refval', 'var'), refval = 0; end\n if ~exist('fig', 'var'), fig = figure; end\n\n minv = min(im(:));\n maxv = max(im(:));\n \n if refval < minv || refval > maxv\n fprintf('Warning: reference value is outside the range of image values\\n');\n end\n \n dr = max([maxv - refval, refval - minv]);\n range = [-dr dr] + refval;\n \n rgbim = applycolourmap(im, map, range);\n \n if fig\n show(rgbim,fig)\n end \n \n % If function was not called with any output arguments clear rgbim so that\n % it is not printed on the screen.\n if ~nargout\n clear('rgbim')\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "applycolourmap.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/applycolourmap.m", "size": 2248, "source_encoding": "utf_8", "md5": "cdab830abbc0e87f8934481ecf26f5c4", "text": "% APPLYCOLOURMAP Applies colourmap to a single channel image to obtain an RGB result\n%\n% Usage: rgbim = applycolourmap(im, map, range)\n%\n% Arguments: im - Single channel image to apply colourmap to.\n% map - RGB colourmap of size ncolours x 3. RGB values are\n% floating point values in the range 0-1.\n% range - Optional 2-vector specifying the min and max values in\n% the image to be mapped across the colour map. Values\n% outside this range are mapped to the end points of the\n% colour map. If range is omitted, or empty, the full range\n% of image values are used.\n%\n% Returns: rgbim - RGB image of floating point values in the range 0-1.\n% NaN values in the input image are rendered as black.\n%\n% This function is used by RELIEF as a base image upon which to apply relief\n% shading. Is is also used by SHOWANGULARIM.\n%\n% See also: IRELIEF, RELIEF, SHOWANGULARIM\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% November 2013\n% September 2014 - Optional range specification added and speeded up by removing loops!\n\nfunction rgbim = applycolourmap(im, map, range)\n \n [ncolours,chan] = size(map);\n assert(chan == 3, 'Colourmap must have 3 columns');\n assert(ndims(im) == 2, 'Image must be single channel');\n if ~isa(im,'double'), im = double(im); end\n \n if ~exist('range', 'var') || isempty(range)\n range = [min(im(:)) max(im(:))];\n end\n assert(range(1) < range(2), 'range(1) must be less than range(2)');\n \n [rows,cols] = size(im);\n \n % Convert image values to integers that can be used to index into colourmap\n im = round( (im-range(1))/(range(2)-range(1)) * (ncolours-1) ) + 1;\n\n mask = isnan(im);\n \n im(mask) = 1; % Set any Nan entries to 1 and\n im(im < 1) = 1; % clamp out of range entries.\n im(im > ncolours) = ncolours;\n \n rgbim = zeros(rows,cols,3);\n \n rgbim(:,:,1) = ~mask.*reshape(map(im,1), rows, cols);\n rgbim(:,:,2) = ~mask.*reshape(map(im,2), rows, cols);\n rgbim(:,:,3) = ~mask.*reshape(map(im,3), rows, cols); \n \n \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "derespolar.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/derespolar.m", "size": 2543, "source_encoding": "utf_8", "md5": "16675236c863fa3ce1c748e6f5264835", "text": "% DERESPOLAR - Desresolves image in polar coordinates.\n%\n% Performs a deresolution operation on an image using Polar Coordinates\n%\n% Usage: deres = derespolar(im, nr, na, xc, yc)\n% where: nr = resolution in the radial direction\n% na = resolution in the angular direction\n% xc = column of polar origin (optional)\n% yc = row of polar origin (optional)\n%\n% If xc and yc are omitted the polar origin defaults to the centre of the image\n\n% Copyright (c) 1999 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 1999\n\n% This code is horribly inefficient and needs a rewrite...\n\nfunction deres = derespolar(im,nr,na,xc,yc)\n\n [rows,cols] = size(im);\n if nargin == 3\n xc = round(cols/2);\n yc = round(rows/2);\n end\n \n if ndims(im) == 3 % Assume colour image\n deres = uint8(zeros(size(im)));\n deres(:,:,1) = iderespolar(im(:,:,1),nr,na,xc,yc);\n deres(:,:,2) = iderespolar(im(:,:,2),nr,na,xc,yc); \n deres(:,:,3) = iderespolar(im(:,:,3),nr,na,xc,yc); \n else\n deres = iderespolar(im,nr,na,xc,yc);\n end\n \n% Internal function that does the work\n \n function deres = iderespolar(im,nr,na,xc,yc) \n [rows,cols] = size(im);\n \n %x = ones(rows,1) * (-cols/2 : (cols/2 - 1)); \n %y = (-rows/2 : (rows/2 - 1))' * ones(1,cols);\n \n [x,y] = meshgrid(-xc:cols-xc-1, -yc:rows-yc-1);\n \n radius = sqrt(x.^2 + y.^2); % Matrix values contain radius from centre.\n theta = atan2(y,x); % Matrix values contain polar angle.\n \n dr = max(max(radius))/nr;\n da = max(max(theta+pi))/na;\n \n rp = round(radius/dr)*dr;\n ra = round(theta/da)*da;\n \n rowp = yc + rp.*sin(ra);\n colp = xc + rp.*cos(ra);\n \n rowp = round(rowp);\n colp = round(colp);\n rowp = max(rowp,1); rowp = min(rowp,rows);\n colp = max(colp,1); colp = min(colp,cols);\n \n for row = 1:rows\n for col = 1:cols\n\tderes(row,col) = im(rowp(row,col), colp(row,col));\n end\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "map2geosofttbl.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/map2geosofttbl.m", "size": 1642, "source_encoding": "utf_8", "md5": "8886e0a749224765428fd3f92e8ac2c4", "text": "% MAP2GEOSOFTTBL Converts MATLAB colourmap to Geosoft .tbl file\n%\n% Usage: map2geosofttbl(map, filename, cmyk)\n%\n% Arguments: map - N x 3 rgb colourmap\n% filename - Output filename\n% cmyk - Optional flag 0/1 indicating whether CMYK values should\n% be written. Defaults to 0 whereby RGB values are\n% written\n%\n% This function writes a RGB colourmap out to a .tbl file that can be loaded\n% into Geosoft Oasis Montaj or QGIS\n%\n% See also: RGB2CMYK\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK October 2012\n% June 2014 - RGB or CMYK option\n\nfunction map2geosofttbl(map, filename, cmyk)\n\n if ~exist('cmyk', 'var'), cmyk = 0; end\n\n [N, cols] = size(map);\n if cols ~= 3\n error('Colourmap must be N x 3 in size')\n end\n \n % Ensure filename ends with .tbl\n if ~strendswith(filename, '.tbl')\n filename = [filename '.tbl'];\n end\n \n fid = fopen(filename, 'wt'); \n\n if cmyk % Convert RGB values in map to CMYK and scale 0 - 255\n cmyk = round(rgb2cmyk(map)*255);\n kcmy = circshift(cmyk, [0 1]); % Shift K to 1st column\n \n fprintf(fid, '{ blk cyn mag yel }\\n');\n for n = 1:N\n fprintf(fid, ' %03d %03d %03d %03d \\n', kcmy(n,:)); \n end\n \n else % Write RGB values\n map = round(map*255);\n \n fprintf(fid, '{ red grn blu }\\n');\n for n = 1:N\n fprintf(fid, ' %3d %3d %3d\\n', map(n,:)); \n end \n \n end\n \n fclose(fid);\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "digipts.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/digipts.m", "size": 876, "source_encoding": "utf_8", "md5": "95a93e018771e295649e1cc41496df4e", "text": "% DIGIPTS - digitise points in an image\n%\n% Function to digitise points in an image. Points are digitised by clicking\n% with the left mouse button. Clicking any other button terminates the\n% function. Each location digitised is marked with a red '+'.\n%\n% Usage: [u,v] = digipts\n%\n% where u and v are nx1 arrays of x and y coordinate values digitised in\n% the image.\n%\n% This function uses the cross-hair cursor provided by GINPUT. This is\n% much more useable than IMPIXEL\n\n% Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk @ csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n% \n% May 2002\n\nfunction [u,v] = digipts\n \n hold on\n u = []; v = [];\n but = 1;\n while but == 1\n\t[x y but] = ginput(1);\n\tif but == 1\n\t u = [u;x];\n\t v = [v;y];\n\t \n\t plot(u,v,'r+');\n\tend\n end\n \n hold off\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "polyval2d.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/polyval2d.m", "size": 1403, "source_encoding": "utf_8", "md5": "699c1158bb9d569730ba4b087241556c", "text": "% POLYVAL2D Evaluates 2D polynomial surface generated by POLYFIT2D\n% \n% Usage: z = polyval2d(x, y, c)\n% \n% Arguments: x, y - Locations where polynomial is to be evaluated\n% c - Coefficients of polynomial as generated by polyfit2d\n% \n% Returns z - The surface values evalated at x, y\n% \n% For a degree 3 surface the coefficients are expected to progress in the\n% form \n% 00 01 02 03 10 11 12 20 21 30\n% where the first digit is the y exponent and the 2nd the x exponent\n%\n% 0 0 0 1 0 2 0 3 1 0 1 1 1 2\n% c1 x y + c2 x y + c3 x y + c4 x y + c5 x y + c6 x y + c7 x y + ...\n% \n% See also: POLYFIT2D \n\n% Peter Kovesi 2014\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK July 2014\n\nfunction z = polyval2d(x, y, c)\n \n % Solve quadratic to determin degree of polynomial\n % ncoeff = (degree+1)*(degree+2)/2\n ncoeff = length(c);\n degree = -1.5 + sqrt(2.25 - 2*(1-ncoeff));\n if round(degree) ~= degree\n error('Cannot determine polynomial degree from number of coefficients');\n end\n\n % p1 is the x exponent and p2 is the y exponent\n z = zeros(size(x));\n ind = 1;\n for p2 = 0:degree\n for p1 = 0:(degree-p2) \n z = z + c(ind) * x.^p1 .* y.^p2;\n ind = ind+1;\n end\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "implace.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/implace.m", "size": 3014, "source_encoding": "utf_8", "md5": "e28ca1e9784b3b7297c12b70c7278015", "text": "% IMPLACE - place image at specified location within larger image\n%\n% Usage: newim = implace(im1, im2, roff, coff)\n%\n% Arguments:\n%\n% im1 - Image that im2 is to be placed in.\n% im2 - Image to be placed.\n% roff - Row and column offset of placement of im2 relative \n% coff to im1, (0,0) aligns top left corners.\n%\n% Warning: The class of final image matches the class of im1. If im1 is of\n% type double and im2 is a uint8 colour image you will obtain a double image\n% having 3 colour channels with values ranging between 0-255. This will\n% need to be cast to uint8, or divided by 255, for display via imshow or\n% show.\n\n% Copyright (c) 2004-2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2004 Original version\n% July 2008 Bug fixes for colour images\n\nfunction newim = implace(im1, im2, roff, coff)\n \n [rows1, cols1, d] = size(im1);\n [rows2, cols2, d] = size(im2); \n \n % Find min row and column of im2 that will appear in im1\n rmin2 = max(1,1-roff);\n cmin2 = max(1,1-coff); \n \n % Find min row and column within im1 that im2 covers\n rmin1 = max(1,1+roff);\n cmin1 = max(1,1+coff); \n \n % Find max row and column of im2 that will appear in im1 \n rmax2 = min(rows1-roff, rows2);\n cmax2 = min(cols1-coff, cols2); \n \n % Find max row and column within im1 that im2 covers \n rmax1 = min(rows2+roff, rows1);\n cmax1 = min(cols2+coff, cols1); \n \n % Check for the case where there is no overlap of the images\n if rmax1 < 1 | cmax1 < 1 | rmax2 < 1 | cmax2 < 1 | ...\n rmin1 > rows1 | cmin1 > cols1 | rmin2 > rows2 | cmin2 > cols2\n\n\tnewim = im1; % Simply copy im1 to newim\n\t\n else % Place im2 into im1\n\t\n\t% Check if either image is colour and if one needs promoting to colour\n\tndim1 = ndims(im1);\n\tndim2 = ndims(im2); \n\t\n\tif ndim1 == 2 & ndim2 == 3\n\t fprintf('promoting im1 \\n');\n\t im1 = uint8(repmat(im1,[1,1,3])); % 'Promote' im1 to 3 channels\n\t ndim1 = 3;\n\telseif ndim2 == 2 & ndim1 == 3\n\t fprintf('promoting im2 \\n');\n\t im2 = uint8(repmat(im2,[1,1,3])); % 'Promote' im2 to 3 channels\n\t ndim2 = 3;\n\tend\n\t\n\tnewim = im1;\n\t\n if ndim1 ==2 % Greyscale\n\t newim(rmin1:rmax1, cmin1:cmax1) = ...\n im2(rmin2:rmax2, cmin2:cmax2);\n\telse % Assume colour\n\t newim(rmin1:rmax1, cmin1:cmax1,:) = ...\n im2(rmin2:rmax2, cmin2:cmax2,:);\t \n\tend\n\t\n end\n \n\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "namenpath.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/namenpath.m", "size": 921, "source_encoding": "utf_8", "md5": "2f308fc4b71683904c79d16a0a402c8e", "text": "% NAMENPATH Returns filename and its path from a full filename\n%\n% Usage: [name, pth] = namenpath(fullfilename)\n%\n% Argument: fullfilename - filename specifier which may include directory\n% path specification\n%\n% Returns: name - The filename without directory path specification\n% pth - The directory path\n% such that fullfilename = [pth name]\n\n% Copyright (c) 2010 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% July 2010\n\nfunction [name, pth] = namenpath(fullfilename)\n \n % Find the last instance of a forward or back slash in the full file name \n ind = find(fullfilename == '/' | fullfilename =='\\', 1, 'last');\n\n if isempty(ind)\n pth = './';\n name = fullfilename;\n else\n pth = fullfilename(1:ind); \n name = fullfilename(ind+1:end);\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "rgb2cmyk.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/rgb2cmyk.m", "size": 1000, "source_encoding": "utf_8", "md5": "21df7ae00f80e81c2fb8577985fd5f65", "text": "% RGB2CMYK - Basic conversion of RGB colour table to cmyk \n%\n% Usage: cmyk = rgb2cmyk(map)\n%\n% Argument: map - N x 3 table of RGB values (assumed 0 - 1)\n% Returns: cmyk - N x 4 table of cmyk values\n%\n% Note that you can use MATLAB's functions MAKECFORM and APPLYCFORM to\n% perform the conversion. However I find that either the gamut mapping, or\n% my incorrect use of these functions does not result in a reversable\n% CMYK->RGB->CMYK conversion. Hence this simple function and its companion\n% CMYK2RGB\n%\n% See also: CMYK2RGB, MAP2GEOSOFTTBL, GEOSOFTTBL2MAP\n\n% Peter Kovesi\n% Centre for Exploration Targeting \n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% July 2013\n% Feb 2014 % Fix for divide by 0 problem for [0 0 0] \n\nfunction cmyk = rgb2cmyk(map)\n \n k = min(1-map,[],2);\n denom = 1 - k + eps; % Add eps to avoid divide by 0\n c = (1-map(:,1) - k)./denom;\n m = (1-map(:,2) - k)./denom;\n y = (1-map(:,3) - k)./denom;\n \n cmyk = [c m y k];\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "removenan.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/removenan.m", "size": 1057, "source_encoding": "utf_8", "md5": "69d193c99b44b881024b4b92777413b4", "text": "% REMOVENAN - removes NaNs from an array \n%\n% Usage: m = removenan(a, defaultval)\n%\n% a - The matrix containing NaN values\n% defaultval - The default value to replace NaNs\n% if omitted this defaults to 0\n%\n% See Also: FILLNAN\n\n% Copyright (c) 2004 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2004\n\n\nfunction m = removenan(a, defaultval)\n \n if nargin == 1\n\tdefaultval = 0;\n end\n \n valid = find(~isnan(a));\n \n m = repmat(defaultval, size(a));\n m(valid) = a(valid);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "togglefigs.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/togglefigs.m", "size": 3177, "source_encoding": "utf_8", "md5": "fa815dc34f1c5f91ce9a79d45915bca9", "text": "% TOGGLEFIGS Convenient switching between figures to aid comparison\n%\n% Usage 1: togglefigs\n%\n% Use arrow keys to index through figures that are currently being displayed, or\n% enter single digit figure numbers to select figures directly.\n% Hit ''X'' to exit.\n%\n% Usage 2: togglefigs(figs)\n% Argument: figs - figure numbers entered as an array or individually\n% separated by commas, to toggle. Hitting \n% any key will cycle to next figure.\n%\n% Example if you have 3 figures you wish to compare manually drag them until\n% they are perfectly overlaid, then use\n% >> togglefigs(1, 2, 3) or\n% >> togglefigs(1:3)\n\n% PK March 2010\n% May 2011 Modified to automatically find all figures and allow you to\n% use arrow keys and single digit figure numbers.\n% Feb 2014 Automatically allign the positions of the specified figures\n\nfunction togglefigs(varargin)\n \n figs = getfigs(varargin(:));\n \n if isempty(figs)\n % No figure numbers were entered, find what figure windows are open\n figs = sort(get(0,'Children'));\n if isempty(figs)\n fprintf('No figure windows to display\\n');\n return\n else\n fprintf('Use arrow keys to index through figures, or enter single\\n');\n fprintf('digit figure numbers to select figures directly, hit ''X'' to exit\\n'); \n end\n\n \n % Set figures so that they all have the same position\n posn = get(figs(1),'Position'); \n for n = 2:length(figs)\n set(figs(n),'Position',posn);\n end \n \n figIndex = 1;\n figure(figs(figIndex));\n while 1\n pause;\n ch = get(gcf,'CurrentCharacter'); \n val = uint8(ch);\n numeral = val - uint8('0');\n \n if lower(ch)=='x'\n return\n elseif ismember(numeral,figs)\n [tf, figIndex] = ismember(numeral, figs);\n elseif val == 29 || val == 31\n figIndex = figIndex+1; if figIndex > length(figs), figIndex = 1; end\n elseif val == 28 || val == 30\n figIndex = figIndex-1; if figIndex < 1, figIndex = length(figs); end\n end\n figure(figs(figIndex));\n end\n\n else % Cycle through the list of figure numbers supplied in the argument list\n fprintf('Hit any key to toggle figures, ''X'' to exit\\n'); \n \n % Set figures so that they all have the same position\n posn = get(figs(1),'Position'); \n for n = 2:length(figs)\n set(figs(n),'Position',posn);\n end\n \n while 1\n for n = 1:length(figs)\n figure(figs(n));\n \n pause;\n ch = get(gcf,'CurrentCharacter'); \n if lower(ch)=='x'\n return\n end\n end\n end\n end\n \n%------------------------------------------\nfunction figs = getfigs(arg)\n \n% figs = zeros(size(arg));\n figs = [];\n for n = 1:length(arg)\n % figs(n) = arg{n};\n figs = [figs arg{n}];\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "geosofttbl2map.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/geosofttbl2map.m", "size": 1313, "source_encoding": "utf_8", "md5": "97f965db62a9a1ea1d2d5bccb32bd608", "text": "% GEOSOFTTBL2MAP Converts Geosoft .tbl file to MATLAB colourmap\n%\n% Usage: geosofttbl2map(filename, map)\n%\n% Arguments: filename - Input filename of tbl file\n% map - N x 3 rgb colourmap\n% \n%\n% This function reads a Geosoft .tbl file and converts the KCMY values to a RGB\n% colourmap.\n%\n% See also: MAP2GEOSOFTTBL, RGB2CMYK\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK July 2013\n\nfunction map = geosofttbl2map(filename)\n \n % Read the file\n [fid, msg] = fopen(filename, 'rt');\n error(msg);\n \n % Read, test and then discard first line\n txt = strtrim(fgetl(fid));\n % Very basic file check. Test that it starts with '{'\n if txt(1) ~= '{'\n error('This may not be a Geosoft tbl file')\n end\n \n % Read remaining lines containing the colour table\n [data, count] = fscanf(fid, '%d');\n \n if mod(count,4) % We expect 4 columns of data\n error('Number of values read not a multiple of 4');\n end\n\n % Reshape data so that columns form kcmy tuples\n kcmy = reshape(data, 4, count/4);\n % Transpose so that the rows form kcmy tuples and normalise 0-1\n kcmy = kcmy'/255; \n cmyk = [kcmy(:,2:4) kcmy(:,1)];\n map = cmyk2rgb(cmyk);\n \n fclose(fid);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "matscii.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/matscii.m", "size": 3441, "source_encoding": "utf_8", "md5": "58129d6167a995d9b76c9cce83edd57a", "text": "% MATSCII - Function to generate ASCII images\n%\n% Usage: picci = matscii(im, width, gamma, filename)\n%\n% im - 2D array of image brightness colours.\n% Image can be grey scale or colour.\n% width - desired width of resulting character image.\n% gamma - optional gamma value to enhance contrast,\n% gamma > 1 increases contrast, < 1 decreases contrast.\n% filename - optional filename in which to save the result.\n%\n% picci - the resulting 2D array of characters.\n%\n\n% Copyright (c) 2000-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2000\n% August 2005 tweaks for Octave\n% September 2005 RBG conversion error fixed (thanks to Firas Zeineddine)\n\nfunction picci = matscii(im, width, gamma, filename)\n\n% ASCII grey scale\n\n%g = '$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`''. ';\ng = '#8XOHLTI)i=+;:,. '; % This seems to be a better `grey scale'\ngmax = length(g);\n\ncharAspect = 0.55; % Width/height aspect ratio of characters\n\nif nargin <=2\n gamma = 1; % Default gamma value\nend\n\nim = double(im);\n\nif ndims(im) == 3 % We have a colour image\n im = (im(:,:,1) + im(:,:,2) + im(:,:,3))/3; % Grey value = (R+G+B)/3\nend\n\n[rows, cols] = size(im);\nscale = width/cols;\n\nrows = round(charAspect * scale * rows); % Rescaled rows and cols values\ncols = round(scale * cols);\n\nim = normalise(im).^gamma; % Rescale range 0-1 and apply gamma\n\nim = imresize(im, [rows, cols]); \n%im = myrescale(im, [rows, cols]); % Use this if you do not have the image\n %toolbox\n\nim = round(im*(gmax-1) + 1); % Rescale to range 1..gmax and round to ints.\n\npicci = char(zeros(rows,cols)); % Preallocate memory for output image.\n\nfor r = 1: rows\n for c = 1:cols\n picci(r,c) = g(im(r,c));\n end\nend\n\nif nargin == 4 % we have a filename\n [fid, msg] = fopen(filename,'wt');\n error(msg);\n for r = 1: rows\n fprintf(fid,'%s\\n',picci(r,:));\n end\n fclose(fid);\nend\n\n\n\n%-------------------------------------------------------------------\n% Internal function to rescale an image so that this code\n% does not require the image processing toolbox to run.\n%-------------------------------------------------------------------\n\nfunction newim = myrescale(im, newRowsCols)\n\n[rows,cols] = size(im);\nnewrows = newRowsCols(1);\nnewcols = newRowsCols(2);\n\nrowScale = (newrows-1)/(rows-1); % Arrays start at 1 rather than 0\ncolScale = (newcols-1)/(cols-1);\n\nnewim = zeros(newrows, newcols);\n\n% For each pixel in the final image find where that pixel `came from'\n% in the source image - use this as the scaled image value\n% Scaling eqns account for the fact that MATLAB arrays start at 1 rather than 0\n\nfor r = 1: newrows\n for c = 1: newcols\n\n sourceRow = round((r-1)/rowScale + 1);\n sourceCol = round((c-1)/colScale + 1);\n\n newim(r,c) = im(sourceRow, sourceCol);\n\n end\nend\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "chirpexp.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/chirpexp.m", "size": 1705, "source_encoding": "utf_8", "md5": "10fa570e744728ca340a78b6f94c7c64", "text": "% CHIRPEXP Generates exponential chirp test image\n%\n% The test image consists of a linear chirp signal in the horizontal direction\n% with the amplitude of the chirp being modulated from 1 at the top of the image\n% to 0 at the bottom.\n%\n% Usage: im = chirpexp(sze, f0, k, p)\n%\n% Arguments: sze - [rows cols] specifying size of test image. If a\n% single value is supplied the image is square.\n% f0 - Initial frequency\n% k - Rate at which frequency increases (try 1.008)\n% p - Power to which the linear attenuation of amplitude, \n% from top to bottom, is raised. For no attenuation use\n% p = 0. For contrast sensitivity experiments use larger\n% values of p. The default value is 4.\n%\n% Note that the resulting image is *very* sensitive to small changes in k\n%\n% Example: im = chirpexp(800, 3, 1.008, 4)\n%\n% I have used this test image to evaluate the effectiveness of different\n% colourmaps, and sections of colourmaps, over varying spatial frequencies and\n% contrast.\n%\n% See also: CHIRPLIN\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% March 2012\n\nfunction im = chirpexp(sze, f0, k, p)\n \n if length(sze) == 1\n rows = sze; cols = sze;\n elseif length(sze) == 2\n rows = sze(1); cols = sze(2);\n else\n error('size must be a 1 or 2 element vector');\n end\n\n assert(k>1,'k must be greater than 1');\n\n if ~exist('p', 'var'), p = 4; end\n \n x = 0:cols-1;\n fx = sin(f0*(k.^x-1)./log(x));\n \n A = ([(rows-1):-1:0]/(rows-1)).^p;\n im = A'*fx;"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "geoseries.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/geoseries.m", "size": 1666, "source_encoding": "utf_8", "md5": "8235bdedc3251f7e5b688f27de734492", "text": "% GEOSERIES Generate geometric series\n%\n% Usage 1: s = geoseries(s1, mult, n)\n%\n% Arguments: s1 - The starting value in the series.\n% mult - The scaling factor between succesive values.\n% n - The desired number of elements in the series.\n%\n% Usage 2: s = geoseries([s1 sn], n)\n%\n% Arguments: [s1 sn] - Two-element vector specifying the 1st and nth values\n% in the the series.\n% n - The desired number of elements in the series.\n%\n%\n% Example: s = geoseries(0.5, 2, 4)\n% s = 0.5000 1.0000 2.0000 4.0000\n%\n% Alternatively obtain the same series using\n% s = geoseries([0.5 4], 4)\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% March 2012\n\nfunction s = geoseries(varargin)\n \n [s1, mult, n] = checkargs(varargin(:));\n \n s = s1 * mult.^[0:(n-1)];\n \n%--------------------------------------------------------------- \n% Sort out arguments. If 1st and last values in series are specified compute\n% the multiplier from the desired number of elements.\n% max_val = s1*mult^(n-1)\n% mult = exp(log(max_val/s1)/(n-1));\n\nfunction [s1, mult, n] = checkargs(arg) \n \n if length(arg) == 2 & length(arg{1}) == 2\n s1 = arg{1}(1);\n sn = arg{1}(2);\n n = arg{2}; \n mult = exp(log(sn/s1)/(n-1));\n elseif length(arg) == 3 & length(arg{1}) == 1\n s1 = arg{1};\n mult = arg{2};\n n = arg{3};\n else\n error('Illegal input. Check usage');\n end\n\n assert(n == round(n) & n > 0, 'Number of elements must be a +ve integer')\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "strstartswith.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/strstartswith.m", "size": 704, "source_encoding": "utf_8", "md5": "7d481f98266b52e06c23ec8c2fc6265d", "text": "% STRSTARTSWITH - tests if a string starts with a specified substring\n%\n% Usage: b = strstartswith(str, substr)\n%\n% Arguments:\n% str - string to be tested\n% substr - starting string that we are hoping to find\n%\n% Returns: true/false. Note that case of strings is ignored\n% \n% See also: STRENDSWITH\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n% June 2010\n\nfunction b = strstartswith(str, substr)\n \n l = length(substr);\n \n % True if ssubstring not too long and all appropriate characters match\n % (ignoring case)\n b = l <= length(str) && strcmpi(str(1:l), substr);\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "cubicroots.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/cubicroots.m", "size": 2783, "source_encoding": "utf_8", "md5": "88bc63423a4c8bcc0d94d2848fa6be1f", "text": "% CUBICROOTS - finds real valued roots of cubic\n%\n% Usage: root = cubicroots(a,b,c,d)\n%\n% Arguments:\n% a, b, c, d - coeffecients of cubic defined as\n% ax^3 + bx^2 + cx + d = 0\n% Returns:\n% root - an array of 1 or 3 real valued roots\n% \n\n% Reference: mathworld.wolfram.com/CubicFormula.html\n% Code follows Cardano's formula\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% Nov 2008\n\nfunction root = cubicroots(a,b,c,d)\n \n if abs(a) < eps\n error('this is a quadratic')\n end\n \n % Divide through by a to simplify things\n b = b/a; c = c/a; d = d/a;\n bOn3 = b/3;\n \n q = (3*c - b^2)/9;\n r = (9*b*c - 27*d - 2*b^3)/54;\n discriminant = q^3 + r^2;\n \n if discriminant >= 0 % We have 1 real root and 2 imaginary\n s = realcuberoot(r + sqrt(discriminant)); \n t = realcuberoot(r - sqrt(discriminant));\n \n root = s + t - bOn3; % Just calculate the real root\n \n else % We have 3 real roots\n\n % In this case (r + sqrt(discriminate)) is complex so the following\n % code constructs the cube root of this complex quantity\n \n rho = sqrt(r^2 - discriminant); \n cubeRootrho = realcuberoot(rho); % Cube root of complex magnitude\n thetaOn3 = acos(r/rho)/3; % Complex angle/3\n \n crRhoCosThetaOn3 = cubeRootrho*cos(thetaOn3);\n crRhoSinThetaOn3 = cubeRootrho*sin(thetaOn3); \n\n root = zeros(1,3);\n root(1) = 2*crRhoCosThetaOn3 - bOn3;\n root(2) = -crRhoCosThetaOn3 - bOn3 - sqrt(3)*crRhoSinThetaOn3;\n root(3) = -crRhoCosThetaOn3 - bOn3 + sqrt(3)*crRhoSinThetaOn3;\n end \n\n \n%-----------------------------------------------------------------------------\n% REALCUBEROOT - computes real-valued cube root\n%\n% Usage: y = realcuberoot(x)\n%\n% In general there will be 3 solutions for the cube root of a number. Two\n% will be complex and one will be real valued. When you raise a negative\n% number to the power 1/3 in MATLAB you will not, by default, get the real\n% valued solution. This function ensures you get the real one\n\nfunction y = realcuberoot(x)\n \n y = sign(x).*abs(x).^(1/3);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "findimage.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/findimage.m", "size": 1030, "source_encoding": "utf_8", "md5": "d22c0bf85ea1bee389ca4ca6abdc58f4", "text": "% FINDIMAGE - invokes image dialog box for interactive image loading\n%\n% Usage: [im, filename] = findimage(disp, c)\n%\n% Arguments: \n% disp - optional flag 1/0 that results in image being displayed\n% c - optional flag 1/0 that results in imcrop being invoked \n% Returns:\n% im - image\n% filename - filename of image\n%\n% See Also: FINDIMAGES\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk\n%\n% March 2010\n\nfunction [im, filename] = findimage(disp, c)\n\n if ~exist('disp','var'), disp = 0; end\n if ~exist('c','var'), c = 0; end\n \n [filename, user_canceled] = imgetfile;\n if user_canceled\n im = [];\n filename = [];\n return;\n end\n \n im = imread(filename); \n \n if c\n fprintf('Crop a section of the image\\n')\n figure(99), clf, im = imcrop(im); delete(99)\n end\n \n if disp\n show(im, 99);\n end\n \n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "strendswith.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/strendswith.m", "size": 1172, "source_encoding": "utf_8", "md5": "a53036600dfe2e1dfcf91ecf2909348b", "text": "% STRENDSWITH - tests if a string ends with a specified substring\n%\n% Usage: b = strendswith(str, substr)\n%\n% Arguments:\n% str - string to be tested\n% substr - ending of string that we are hoping to find.\n% substr may be a cell array of string endings, in this case\n% the function returns true if any of the endings match.\n%\n% Returns: true/false. Note that case of strings is ignored\n% \n% See also: STRSTARTSWITH\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n% June 2010\n% April 2011 Modified to allow substr to be a cell array\n\nfunction b = strendswith(str, substr)\n\n if ~iscell(substr)\n tmp = substr;\n clear substr;\n substr{1} = tmp;\n end\n \n b = 0;\n for n = 1:length(substr)\n % Compute index of character in str that should match with the the first\n % character of str\n s = length(str) - length(substr{n}) + 1;\n \n % True if s > 0 and all appropriate characters match (ignoring case)\n b = b || (s > 0 && strcmpi(str(s:end), substr{n}));\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "viewlabspace.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/viewlabspace.m", "size": 7192, "source_encoding": "utf_8", "md5": "cbfb89e9024d64a0fe77892badc56b0c", "text": "% VIEWLABSPACE Visualisation of L*a*b* space\n%\n% Usage: viewlabspace(dL)\n%\n% Argument: dL - Optional increment in lightness with each slice of L*a*b*\n% space. Defaults to 5\n%\n% Function allows interactive viewing of a sequence of images corresponding to\n% different slices of lightness in L*a*b* space. Lightness varies from 0 to\n% 100. Initially a slice at a lightness of 50 is displayed.\n% Pressing 'l' or arrow up/right will increase the lightness by dL.\n% Pressing 'd' or arrow down/left will darken by dL.\n% Press 'x' to exit.\n%\n% The CIELAB colour coordinates of the cursor position within the slice images\n% is updated continuously. This is useful for determining suitable controls\n% points for the definition of colourmap paths through CIELAB space.\n%\n% See also: COLOURMAPPATH, ISOCOLOURMAPPATH, CMAP\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% March 2013\n% November 2013 Interactive CIELAB coordinate feedback from mouse position\n\nfunction viewlabspace(dL, figNo)\n \n if ~exist('dL', 'var'), dL = 5; end\n if ~exist('figNo', 'var'), figNo = 100; end\n \n % Define some reference colours in rgb\n rgb = [1 0 0\n 0 1 0\n 0 0 1\n 1 1 0\n 0 1 1\n 1 0 1\n 1 .5 0\n .5 0 1\n 0 .5 1\n 0 1 .5\n 1 0 .5];\n \n colours = {'red '\n 'green '\n 'blue '\n 'yellow '\n 'cyan '\n 'magenta'\n 'orange '\n 'violet '\n 'blue-cyan'\n 'green-cyan'\n 'red-magenta'};\n \n % ... and convert them to lab\n % Use D65 whitepoint to match typical monitors.\n wp = whitepoint('D65');\n labv = applycform(rgb, makecform('srgb2lab', 'AdaptedWhitePoint', wp));\n\n % Obtain cylindrical coordinates in lab space\n labradius = sqrt(labv(:,2).^2+labv(:,3).^2);\n labtheta = atan2(labv(:,3), labv(:,2));\n \n % Define a*b* grid for image\n scale = 2;\n [a, b] = meshgrid([-127:1/scale:127]);\n [rows,cols] = size(a);\n \n % Scale and offset lab coords to fit image coords\n labc = zeros(size(labv));\n labc(:,1) = round(labv(:,1));\n labc(:,2) = round(scale*labv(:,2) + cols/2);\n labc(:,3) = round(scale*labv(:,3) + rows/2);\n \n % Print out lab values\n labv = round(labv);\n fprintf('\\nCoordinates of standard colours in L*a*b* space\\n\\n');\n for n = 1:length(labv)\n fprintf('%s L%3d a %4d b %4d angle %4.1f radius %4d\\n',...\n colours{n}, ...\n labv(n,1), labv(n,2), ...\n labv(n,3), labtheta(n), round(labradius(n)));\n end\n \n fprintf('\\n\\n')\n \n % Generate axis tick values\n tickval = [-100 -50 0 50 100];\n tickcoords = scale*tickval + cols/2;\n ticklabels = {'-100'; '-50'; '0'; '50'; '100'};\n\n fig = figure(figNo);\n set(fig, 'WindowButtonMotionFcn', @labcoords)\n set(fig, 'KeyReleaseFcn', @keyreleasecb);\n texth = text(50, 50,'', 'color', [1 1 1]); % Text area to display\n % current a and b values\n \n fprintf('Place cursor within figure\\n');\n fprintf('Press ''l'' to lighten, ''d'' to darken, or use arrow keys\\n');\n fprintf('''x'' to exit\\n');\n\n L = 50;\n renderlabslice(L);\n \n \n%------------------------------------------------------\n% Window button move call back function\nfunction labcoords(src, evnt)\n cp = get(gca,'CurrentPoint');\n x = cp(1,1); y = cp(1,2);\n\n aval = round((x-(cols/2))/scale);\n bval = round((y-(rows/2))/scale);\n\n radius = sqrt(aval.^2 + bval.^2);\n hue = atan2(bval, aval);\n \n set(texth, 'String', sprintf('a %d b %d radius %d angle %d',...\n aval, bval, round(radius), round(hue/pi*180)));\nend\n\n%-----------------------------------------------------------------------\n% Key Release callback\n% If '+' or up is pressed we move up in lighness\n% '-' or down moves us down in lightness\n\nfunction keyreleasecb(src,evnt)\n \n if evnt.Character == 'l' | evnt.Character == 30\n L = min(L + dL, 100);\n\n elseif evnt.Character == 'd' | evnt.Character == 31\n L = max(L - dL, 0);\n \n elseif evnt.Character == 's' % Save slice as an image\n tmp = rgb;\n tmp(:,:,1) = flipud(tmp(:,:,1));\n tmp(:,:,2) = flipud(tmp(:,:,2));\n tmp(:,:,3) = flipud(tmp(:,:,3));\n % Draw a red cross at the achromatic point\n [r,c,~] = size(tmp);\n tmp = imageline(tmp, [c/2-5, r/2], [c/2+5, r/2], [255, 0 0]);\n tmp = imageline(tmp, [c/2, r/2-5], [c/2, r/2+5], [255, 0 0]);\n imwrite(tmp, sprintf('LAB_slice_L_%d.png',L));\n \n elseif evnt.Character == 'x'\n delete(figNo);\n return\n \n end\n\n renderlabslice(L); % Render a slice at this new lightness level\n labcoords(src, evnt); % Regenerate the cursor coordinates\nend \n\n%--------------------------------------------------------\n\nfunction renderlabslice(L)\n \n% Build image in lab space\n lab = zeros(rows,cols,3);\n lab(:,:,1) = L;\n lab(:,:,2) = a;\n lab(:,:,3) = b;\n \n \n wp = whitepoint('D65');\n \n % Generate rgb values from lab\n rgb = applycform(lab, makecform('lab2srgb', 'AdaptedWhitePoint', wp));\n \n % Invert to reconstruct the lab values\n lab2 = applycform(rgb, makecform('srgb2lab', 'AdaptedWhitePoint', wp));\n \n % Where the reconstructed lab values differ from the specified values is\n % an indication that we have gone outside of the rgb gamut. Apply a\n % mask to the rgb values accordingly\n mask = max(abs(lab-lab2),[],3);\n \n for n = 1:3\n rgb(:,:,n) = rgb(:,:,n).*(mask<2); % tolerance of 1\n end\n \n figure(figNo), image(rgb), title(sprintf('Lightness %d', L));\n axis square, axis xy\n % Recreate the text handle in the new image\n texth = text(50, 50,'', 'color', [1 1 1]);\n \n set(gca, 'xtick', tickcoords);\n set(gca, 'ytick', tickcoords);\n set(gca, 'xticklabel', ticklabels);\n set(gca, 'yticklabel', ticklabels);\n xlabel('a*'); ylabel('b*'); \n \n hold on, \n plot(cols/2, rows/2, 'r+'); % Centre point for reference\n \n % Plot reference colour positions\n for n = 1:length(labc)\n plot(labc(n,2), labc(n,3), 'w+')\n text(labc(n,2), labc(n,3), ...\n sprintf(' %s\\n %d %d %d ',colours{n},...\n labv(n,1), labv(n,2), labv(n,3)),...\n 'color', [1 1 1])\n end\n \n hold off\n \nend\n\n%--------------------------------------------------------\nend % of viewlabspace"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "circularstruct.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Misc/circularstruct.m", "size": 648, "source_encoding": "utf_8", "md5": "aec494462bd52689db93faf1d6a9ea60", "text": "% CIRCULARSTRUCT\n%\n% Function to construct a circular structuring element\n% for morphological operations.\n%\n% function strel = circularstruct(radius)\n%\n% Note radius can be a floating point value though the resulting\n% circle will be a discrete approximation\n%\n% Peter Kovesi March 2000\n\nfunction strel = circularstruct(radius)\n\nif radius < 1\n error('radius must be >= 1');\nend\n\ndia = ceil(2*radius); % Diameter of structuring element\n\nif mod(dia,2) == 0 % If diameter is a odd value\n dia = dia + 1; % add 1 to generate a `centre pixel'\nend\n\nr = fix(dia/2);\n[x,y] = meshgrid(-r:r);\nrad = sqrt(x.^2 + y.^2); \nstrel = rad <= radius;\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "supertorus.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapes/supertorus.m", "size": 2444, "source_encoding": "utf_8", "md5": "91c1e7e27c0219d233582240dcb7c17e", "text": "% SUPERTORUS - generates a 'supertorus' surface\n%\n% Usage:\n% [x,y,z] = supertorus(xscale, yscale, zscale, rad, e1, e2, n)\n%\n% Arguments:\n% xscale, yscale, zscale - Scaling in the x, y and z directions.\n% e1, e2 - Exponents of the x and y coords.\n% rad - Mean radius of torus. \n% n - Number of subdivisions of logitude and latitude on\n% the surface.\n%\n% Returns: x,y,z - matrices defining paramteric surface of superquadratic\n%\n% If the result is not assigned to any output arguments the function\n% plots the surface for you, otherwise the x, y and z parametric\n% coordinates are returned for subsequent display using, say, SURFL.\n%\n% If rad is set to 0 the surface becomes a superquadratic\n%\n% Examples:\n% supertorus(1, 1, 1, 2, 1, 1, 100) - classical torus 100 subdivisions\n% supertorus(1, 1, 1, .8, 1, 1, 100) - an 'orange'\n% supertorus(1, 1, 1, 2, .1, 1, 100) - a round 'washer'\n% supertorus(1, 1, 1, 2, .1, 2, 100) - a square 'washer'\n%\n% See also: SUPERQUAD\n\n% Copyright (c) 2000 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2000\n\nfunction [x,y,z] = supertorus(xscale,yscale,zscale,rad,e1,e2, n)\n \n long = ones(n,1)*[-pi:2*pi/(n-1):pi];\n lat = [-pi:2*pi/(n-1): pi]'*ones(1,n);\n \n x = xscale * (rad + pow(cos(lat),e1)) .* pow(cos(long),e2);\n y = yscale * (rad + pow(cos(lat),e1)) .* pow(sin(long),e2);\n z = zscale * pow(sin(lat),e1);\n \n if nargout == 0\n surfl(x,y,z), shading interp, colormap(copper), axis equal\n clear x y z % suppress output\n end\n \n%--------------------------------------------------------------------\n% Internal function providing a modified definition of power whereby the\n% sign of the result always matches the sign of the input value.\n\nfunction r = pow(a,p)\n \n r = sign(a).* abs(a.^p);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "superquad.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapes/superquad.m", "size": 2798, "source_encoding": "utf_8", "md5": "2dfc95eb41c2bf03bb78f5f0bb8b7c07", "text": "% SUPERQUAD - generates a superquadratic surface\n%\n% Usage: [x,y,z] = superquad(xscale, yscale, zscale, e1, e2, n)\n%\n% Arguments:\n% xscale, yscale, zscale - Scaling in the x, y and z directions.\n% e1, e2 - Exponents of the x and y coords.\n% n - Number of subdivisions of logitude and latitude on\n% the surface.\n%\n% Returns: x,y,z - matrices defining paramteric surface of superquadratic\n%\n% If the result is not assigned to any output arguments the function\n% plots the surface for you, otherwise the x, y and z parametric\n% coordinates are returned for subsequent display using, say, SURFL.\n%\n% Examples:\n% superquad(1, 1, 1, 1, 1, 100) - sphere of radius 1 with 100 subdivisions\n% superquad(1, 1, 1, 2, 2, 100) - octahedron of radius 1 \n% superquad(1, 1, 1, 3, 3, 100) - 'pointy' octahedron \n% superquad(1, 1, 1, .1, .1, 100) - cube (with rounded edges)\n% superquad(1, 1, .2, 1, .1, 100) - 'square cushion'\n% superquad(1, 1, .2, .1, 1, 100) - cylinder\n%\n% See also: SUPERTORUS\n\n% Copyright (c) 2000 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2000\n\nfunction [x,y,z] = superquad(xscale, yscale, zscale, e1, e2, n)\n\n % Set up parameters of the parametric surface, in this case matrices\n % corresponding to longitude and latitude on our superquadratic sphere.\n long = ones(n,1)*[-pi:2*pi/(n-1):pi];\n lat = [-pi/2:pi/(n-1): pi/2]'*ones(1,n);\n \n x = xscale * pow(cos(lat),e1) .* pow(cos(long),e2);\n y = yscale * pow(cos(lat),e1) .* pow(sin(long),e2);\n z = zscale * pow(sin(lat),e1);\n \n % Ensure top and bottom ends are closed. If we do not do this you find\n % that due to numerical errors the ends may not be perfectly closed.\n x(1,:) = 0; y(1,:) = 0;\n x(end,:) = 0; y(end,:) = 0; \n \n if nargout == 0\n surfl(x,y,z), shading interp, colormap(copper), axis equal\n clear x y z % suppress output\n end\n\n%--------------------------------------------------------------------\n% Internal function providing a modified definition of power whereby the\n% sign of the result always matches the sign of the input value.\n\nfunction r = pow(a, p)\n \n r = sign(a).* abs(a).^p;\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "gplot3d.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapes/gplot3d.m", "size": 3051, "source_encoding": "utf_8", "md5": "023a1e53d0acecbb7ff057579a8854eb", "text": "function [Xout,Yout,Zout]=gplot3d(A,xyz,lc)\n%GPLOT3D Plot graph, as in \"graph theory\".\n% This is a modification of MATLAB's GPLOT function for vertices in 3D.\n% GPLOT3D(A,xyz) plots the graph specified by A and xyz. A graph, G, is\n% a set of nodes numbered from 1 to n, and a set of connections, or\n% edges, between them. \n%\n% In order to plot G, two matrices are needed. The adjacency matrix,\n% A, has a(i,j) nonzero if and only if node i is connected to node\n% j. The coordinates array, xyz, is an n-by-3 matrix with the\n% position for node i in the i-th row, xyz(i,:) = [x(i) y(i) z(i)].\n% \n% GPLOT(A,xyz,LineSpec) uses line type and color specified in the\n% string LineSpec. See PLOT for possibilities.\n%\n% [X,Y] = GPLOT(A,xyz) returns the NaN-punctuated vectors\n% X and Y without actually generating a plot. These vectors\n% can be used to generate the plot at a later time if desired. As a\n% result, the two argument output case is only valid when xyz is of type\n% single or double.\n% \n% This code is MATLAB's GPLOT function modified so that it plots a graph\n% where the vertices are defined in 3D \n% \n% See also SPY, TREEPLOT, GPLOT\n%\n\n% John Gilbert\n% Copyright 1984-2009 The MathWorks, Inc. \n% $Revision: 5.12.4.4 $ $Date: 2009/04/21 03:26:12 $\n%\n% 3D modifications by Peter Kovesi \n% peter.kovesi at uwa edu au \n\n[i,j] = find(A);\n[~, p] = sort(max(i,j));\ni = i(p);\nj = j(p);\n\nX = [ xyz(i,1) xyz(j,1)]';\nY = [ xyz(i,2) xyz(j,2)]';\nZ = [ xyz(i,3) xyz(j,3)]';\n\nif isfloat(xyz) || nargout ~= 0\n X = [X; NaN(size(i))'];\n Y = [Y; NaN(size(i))'];\n Z = [Z; NaN(size(i))']; \nend\n\nif nargout == 0\n if ~isfloat(xyz)\n if nargin < 3\n lc = '';\n end\n [lsty, csty, msty] = gplotGetRightLineStyle(gca,lc); \n plot3(X,Y,Z,'LineStyle',lsty,'Color',csty,'Marker',msty);\n else\n if nargin < 3\n plot3(X(:),Y(:),Z(:));\n else\n plot3(X(:),Y(:),Z(:),lc);\n end\n end\nelse\n Xout = X(:);\n Yout = Y(:);\n Zout = Z(:); \nend\n\nfunction [lsty, csty, msty] = gplotGetRightLineStyle(ax, lc)\n% gplotGetRightLineStyle\n% Helper function which correctly sets the color, line style, and marker\n% style when plotting the data above. This style makes sure that the\n% plot is as conformant as possible to gplot from previous versions of\n% MATLAB, even when the coordinates array is not a floating point type.\nco = get(ax,'ColorOrder');\nlo = get(ax,'LineStyleOrder');\nholdstyle = getappdata(gca,'PlotHoldStyle');\nif isempty(holdstyle)\n holdstyle = 0;\nend\nlind = getappdata(gca,'PlotLineStyleIndex');\nif isempty(lind) || holdstyle ~= 1\n lind = 1;\nend\ncind = getappdata(gca,'PlotColorIndex');\nif isempty(cind) || holdstyle ~= 1\n cind = 1;\nend\nnlsty = lo(lind);\nncsty = co(cind,:);\nnmsty = 'none';\n% Get the linespec requested by the user.\n[lsty,csty,msty] = colstyle(lc);\nif isempty(lsty)\n lsty = nlsty;\nend\nif isempty(csty)\n csty = ncsty;\nend\nif isempty(msty)\n msty = nmsty;\nend\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "icosahedron.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapes/icosahedron.m", "size": 3196, "source_encoding": "utf_8", "md5": "deced73cec8d737a7b03e362c983c1e5", "text": "% ICOSAHEDRON Generates vertices and graph of icosahedron\n%\n% Usage: [xyz, A, F] = icosahedron(radius)\n%\n% Argument: radius - Optional radius of icosahedron. Defaults to 1.\n% Returns: xyz - 12x3 matrix of vertex coordinates.\n% A - Adjacency matrix defining connectivity of vertices.\n% F - 20x3 matrix specifying the 3 nodes that define each face.\n%\n% See also: GEODOME, GPLOT3D, DRAWFACES\n\n% Copyright (c) 2009 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2009\n\nfunction [xyz, A, F] = icosahedron(radius)\n \n if ~exist('radius','var')\n radius = 1;\n end\n \n % Compute the 12 vertices\n phi = (1+sqrt(5))/2; % Golden ratio\n xyz = [0 1 phi \n 0 -1 phi \n 0 1 -phi \n 0 -1 -phi \n 1 phi 0 \n -1 phi 0 \n 1 -phi 0 \n -1 -phi 0 \n phi 0 1 \n -phi 0 1 \n phi 0 -1 \n -phi 0 -1];\n\n % Scale to required radius\n xyz = xyz*radius/(sqrt(1+phi^2));\n \n % Define the adjacency matrix\n % 1 2 3 4 5 6 7 8 9 10 11 12\n A = [0 1 0 0 1 1 0 0 1 1 0 0 \n 1 0 0 0 0 0 1 1 1 1 0 0 \n 0 0 0 1 1 1 0 0 0 0 1 1 \n 0 0 1 0 0 0 1 1 0 0 1 1 \n 1 0 1 0 0 1 0 0 1 0 1 0 \n 1 0 1 0 1 0 0 0 0 1 0 1 \n 0 1 0 1 0 0 0 1 1 0 1 0 \n 0 1 0 1 0 0 1 0 0 1 0 1 \n 1 1 0 0 1 0 1 0 0 0 1 0 \n 1 1 0 0 0 1 0 1 0 0 0 1 \n 0 0 1 1 1 0 1 0 1 0 0 0 \n 0 0 1 1 0 1 0 1 0 1 0 0];\n \n % Define nodes that make up each face\n F = [1 2 9\n 1 9 5\n 1 5 6\n 1 6 10\n 1 10 2\n 2 7 9\n 9 7 11\n 9 11 5\n 5 11 3\n 5 3 6\n 6 3 12\n 6 12 10\n 10 12 8\n 10 8 2\n 2 8 7\n 4 7 8\n 4 8 12\n 4 12 3\n 4 3 11\n 4 11 7];\n \n % The icosahedron defined above is oriented so that an edge is at the\n % top. The following code transforms the vertex coordinates so that a\n % vertex is at the top to give a more conventional view.\n %\n % Define coordinate frame where z passes through one of the vertices and\n % transform the vertices so that one of the vertices is at the 'top'.\n Z = xyz(1,:)'; % Z passes through vertex 1\n X = xyz(2,:)'; % Choose adjacent vertex as an approximate X\n Y = cross(Z,X); % Y is perpendicular to Z and this approx X\n X = cross(Y,Z); % Final X is perpendicular to Y and Z\n X = X/norm(X); Y = Y/norm(Y); Z = Z/norm(Z); % Ensure unit vectors\n xyz = ([X Y Z]'*xyz')'; % Transform points;"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "geodome.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapes/geodome.m", "size": 7596, "source_encoding": "utf_8", "md5": "d70bca00571f6191c84ac6221a8de9b3", "text": "% GEODOME Generates geodesic sphere \n%\n% Usage: [xyz, A, F] = geodome(frequency, radius)\n%\n% The sphere is generated from subdivisions of the faces of an icosahedron.\n%\n% Arguments: \n% frequency - The number of subdivisions of each edge of an\n% icosahedron. A frequency of 1 will give you an\n% icosahedron. A high number will give you a more\n% spherical shape. Defaults to 2.\n% radius - Radius of the sphere. Defaults to 1.\n% Returns:\n% xyz - A nx3 matrix defining the vertex list, each row is the\n% x,y,z coordinates of a vertex.\n% A - Adjacency matrix defining the connectivity of the\n% vertices\n% F - A mx3 matrix defining the face list. Each row of F\n% specifies the 3 vertices that make up the face.\n%\n% Example:\n% [xyz, A, F] = geodome(3, 5); % Generate a 3-frequency sphere with\n% % radius 5\n% gplot3d(A, xyz); % Use adjacency matrix and vertex list to\n% % generate a wireframe plot.\n% drawfaces(xyz, F); % Use face and vertex lists to generate\n% % surface patch plot.\n% axis vis3d, axis off, rotate3d on\n%\n% See also: ICOSAHEDRON, GPLOT3D, DRAWFACES\n\n% Copyright (c) 2009 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2009 \n% April 2014 - Dome radius scaling fixed (thanks to Brad Keserich)\n\nfunction [xyz, A, F] = geodome(frequency, radius)\n\n if ~exist('frequency','var')\n frequency = 2;\n end\n\n if ~exist('radius','var')\n radius = 1;\n end\n \n if frequency < 1\n error('Frequency must be an integer >= 1');\n end\n \n % Generate vertices of base icosahedron\n [icosXYZ, icosA, icosF] = icosahedron(1);\n \n % Compute number of vertices in geodesic sphere. This is the 12 vertices\n % of the icosahedron + the extra vertices introduced on each of the 30\n % edges + the extra vertices in the interior of the of each of the 20\n % faces. This latter is a sum of an arithmetic series [1 .. (frequency-2)]\n fm1 = frequency - 1;\n fm2 = frequency - 2; \n nVert = 12 + 30*fm1 + 20*fm2*fm1/2;\n \n xyz = zeros(nVert,3);\n \n if frequency == 1 % Just return the icosahedron\n xyz = icosXYZ;\n A = icosA;\n F = icosF;\n else % For all frequencies > 1\n xyz(1:12,:) = icosXYZ; % Grab the vertices of the icosahedron\n offset = 13;\n\n % Find the nodes that connect edges. Note we use the upper triangular\n % part of the adjacency matrix so that we only get each edge once.\n [i,j] = find(triu(icosA));\n\n % Generate extra vertices on every edge of the icoshedron.\n for n = 1:length(i)\n xyz(offset:(offset+fm2) ,:) = ...\n divideEdge(icosXYZ(i(n),:), icosXYZ(j(n),:), frequency);\n offset = offset+fm1;\n end\n \n % Generate the extra vertices within each face of the icoshedron.\n for f = 1:length(icosF) \n \n % Re subdivide two of the edges of the face and get the vertices\n % (Yes, this is wasteful but it makes code logic easier)\n V1 = divideEdge(icosXYZ(icosF(f,1),:), icosXYZ(icosF(f,2),:), frequency);\n V2 = divideEdge(icosXYZ(icosF(f,1),:), icosXYZ(icosF(f,3),:), frequency); \n\n % Now divide the edges that join the new vertices along the\n % subdivided edges.\n for v = 2:fm1\n VF = divideEdge(V1(v,:), V2(v,:), v);\n xyz(offset:(offset+v-2),:) = VF;\n offset = offset+v-1;\n end\n end\n \n end\n\n xyz = xyz*radius; % Scale vertices to required radius\n A = adjacency(xyz);\n F = faces(A);\n\n%---------------------------------------------------------------------\n% Function to divide an edge defined between vertices V1 and V2 into nSeg\n% segments and return the coordinates of the vertices.\n% This function simplistically divides the distance between V1 and V2\n\nfunction vert = divideEdgeOld(V1, V2, nSeg)\n\n edge = V2 - V1; % Vector along edge\n\n % Now add appropriate fractions of the edge length to the first node\n vert = zeros(nSeg-1, 3);\n for f = 1:(nSeg-1)\n vert(f,:) = V1 + edge * f/nSeg;\n vert(f,:) = vert(f,:)/norm(vert(f,:)); % Normalize to unit length\n end\n\n\n%---------------------------------------------------------------------\n% Function to divide an edge defined between vertices V1 and V2 into nSeg\n% segments and return the coordinates of the vertices.\n% This function divides the *angle* between V1 and V2\n% rather than the distance.\nfunction vert = divideEdge(V1, V2, nSeg)\n\n axis = cross(V1,V2); \n angle = atan(norm(axis)/dot(V1,V2));\n axis = axis/norm(axis);\n \n % Now add appropriate fractions of the edge length to the first node\n vert = zeros(nSeg-1, 3);\n for f = 1:(nSeg-1)\n Q = newquaternion(f*angle/nSeg, axis);\n vert(f,:) = quaternionrotate(Q,V1);\n vert(f,:) = vert(f,:)/norm(vert(f,:)); % Normalize to unit length\n end\n\n \n \n%-------------------------------------------------------------------------\n% Function to build adjacency matrix for geodesic sphere by brute force\n \nfunction A = adjacency(xyz)\n \n nVert = length(xyz);\n A = zeros(nVert);\n\n % Find distances between all pairs of vertices \n for n1 = 1:nVert-1\n A(n1,n1) = Inf;\n for n2 = n1+1:nVert\n A(n1,n2) = norm(xyz(n2,:) - xyz(n1,:));\n end\n end\n A(nVert,nVert) = Inf;\n \n A = A+A'; % Make A symmetric\n \n % Find min distance in first row. \n minD = min(A(1,:)');\n\n % Assume that no edge can be more than 1.5 times this minimum distance, use\n % this to decide connectivity of nodes.\n A = A < minD*1.5;\n\n%-----------------------------------------------------------------------------\n% Function to find the triplets of vertices that define the faces of the\n% geodesic sphere\n\nfunction F = faces(A)\n \n % Strategy: We are only after cycles of length 3 in graph defined by A.\n % For every node N0 (except the last two, which we will not need to visit)\n % - Get list of neighbours, N1\n % - For each neighbour N1i in N1 find its list of neighbours, N2.\n % - Any neighbour in N2 that is in N1 must form a cycle of length 3 with N0\n \n nVert = length(A);\n F = [];\n \n for N0 = 1:nVert-2\n N1 = find(A(N0,:)); % Neighbours of N0\n for N1i = N1 \n N2 = find(A(N1i,:)); \n cycle = intersect(N2,N1); % Find the 2 nodes of N2 that are in N1\n F = [F; [N0 N1i cycle(1)]; [N0 N1i cycle(2)]];\n end\n end\n \n % Each face will be found multiple times, eliminate duplicates. \n F = sort(F,2); % Sort rows of face list\n F = unique(F,'rows'); % ...then extract the unique rows."} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "drawfaces.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapes/drawfaces.m", "size": 2247, "source_encoding": "utf_8", "md5": "5c8a03943a5894a51836931271cbc606", "text": "% DRAWFACES Draws triangular faces defined by vertices and face vertex lists\n%\n% Usage: drawfaces(xyz, F, col)\n%\n% Arguments:\n% xyz - A nx3 matrix defining the vertex list, each row is the\n% x,y,z coordinates of a vertex.\n% F - A mx3 matrix defining the face list. Each row of F\n% specifies the indices of the 3 vertices that make up the\n% face. \n% col - Optional colour specifier of the faces. This can be 'r',\n% 'g', 'b' 'w', k' etc or a RGB 3-vector. \n% Defaults to [1 1 1] (white). If col is specified as the \n% string 'rand' each face is given a random colour.\n% if col has n rows it is assumed that col specifies the\n% colour to be used for each vertex, see documentation for\n% PATCH.\n%\n% See also: GPLOT3D, ICOSAHEDRON, GEODOME\n\n% Copyright (c) 2009 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2009\n\nfunction drawfaces(xyz, F, col)\n \n if ~exist('col', 'var')\n col = [1 1 1];\n end\n \n nPatch = size(F,1);\n nVert = size(xyz,1);\n\n if size(col,1) == nVert\n for p = 1:nPatch\n coords = xyz(F(p,:),:);\n h = patch(coords(:,1), coords(:,2), coords(:,3), col(F(p,:),:));\n% set(h,'EdgeColor','none');\n end \n elseif strcmpi(col,'rand')\n for p = 1:nPatch\n coords = xyz(F(p,:),:);\n patch(coords(:,1), coords(:,2), coords(:,3),rand(1,3))\n end\n else\n for p = 1:nPatch\n coords = xyz(F(p,:),:);\n patch(coords(:,1), coords(:,2), coords(:,3), col)\n end\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "matchbymonogenicphase.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Match/matchbymonogenicphase.m", "size": 9328, "source_encoding": "utf_8", "md5": "e63225faedcf391fb6411d27d71a208e", "text": "% MATCHBYMONOGENICPHASE - match image feature points using monogenic phase data\n%\n% Function generates putative matches between previously detected\n% feature points in two images by looking for points that have minimal\n% differences in monogenic phase data within windows surrounding each point.\n% Only points that correlate most strongly with each other in *both*\n% directions are returned. This is a simple-minded N^2 comparison.\n%\n% This matcher performs rather well relative to normalised greyscale\n% correlation. Typically there are more putative matches found and fewer\n% outliers. There is a greater computational cost in the pre-filtering stage\n% but potentially the matching stage is much faster as each pixel is effectively\n% encoded with only 3 bits. (Though this potential speed is not realized in this\n% implementation)\n%\n% Usage: [m1,m2] = matchbymonogenicphase(im1, p1, im2, p2, w, dmax, ...\n% nscale, minWaveLength, mult, sigmaOnf)\n%\n% Arguments:\n% im1, im2 - Images containing points that we wish to match.\n% p1, p2 - Coordinates of feature pointed detected in im1 and\n% im2 respectively using a corner detector (say Harris\n% or phasecong2). p1 and p2 are [2xnpts] arrays though\n% p1 and p2 are not expected to have the same number\n% of points. The first row of p1 and p2 gives the row\n% coordinate of each feature point, the second row\n% gives the column of each point.\n% w - Window size (in pixels) over which the phase bit codes\n% around each feature point are matched. This should\n% be an odd number.\n% dmax - Maximum search radius for matching points. Used to \n% improve speed when there is little disparity between\n% images. Even setting it to a generous value of 1/4 of\n% the image size gives a useful speedup. \n% nscale - Number of filter scales.\n% minWaveLength - Wavelength of smallest scale filter.\n% mult - Scaling factor between successive filters.\n% sigmaOnf - Ratio of the standard deviation of the Gaussian\n% describing the log Gabor filter's transfer function in\n% the frequency domain to the filter center frequency. \n%\n%\n% Returns:\n% m1, m2 - Coordinates of points selected from p1 and p2\n% respectively such that (putatively) m1(:,i) matches\n% m2(:,i). m1 and m2 are [2xnpts] arrays defining the\n% points in each of the images in the form [row;col].\n%\n%\n% I have had good success with the folowing parameters:\n%\n% w = 11; Window size for correlation matching, 7 or greater\n% seems fine.\n% dmax = 50; \n% nscale = 1; Just one scale can give very good results. Adding\n% another scale doubles computation \n% minWaveLength = 10;\n% mult = 4; This is irrelevant if only one scale is used. If you do\n% use more than one scale try values in the range 2-4.\n% sigmaOnf = .2; This results in a *very* large bandwidth filter. A\n% large bandwidth seems to be very important in the\n% matching performance.\n%\n% See Also: MATCHBYCORRELATION, MONOFILT\n\n% Copyright (c) 2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2005 - Original version adapted from matchbycorrelation.m\n\n\nfunction [m1,m2,cormat] = matchbymonogenicphase(im1, p1, im2, p2, w, dmax, ...\n nscale, minWaveLength, mult, sigmaOnf)\n\n orientWrap = 0;\n [f1, h1f1, h2f1, A1] = ...\n monofilt(im1, nscale, minWaveLength, mult, sigmaOnf, orientWrap);\n\n [f2, h1f2, h2f2, A2] = ...\n monofilt(im2, nscale, minWaveLength, mult, sigmaOnf, orientWrap);\n\n % Normalise filter outputs to unit vectors (should also have masking for\n % unreliable filter outputs)\n for s = 1:nscale\n% f1{s} = f1{s}./A1{s}; f2{s} = f2{s}./A2{s};\n% h1f1{s} = h1f1{s}./A1{s}; h1f2{s} = h1f2{s}./A2{s}; \n% h2f1{s} = h2f1{s}./A1{s}; h2f2{s} = h2f2{s}./A2{s}; \n \n % Try quantizing oriented phase vector to 8 octants to see what\n % effect this has (Performance seems to be reduced only slightly)\n f1{s} = sign(f1{s}); f2{s} = sign(f2{s}); \n h1f1{s} = sign(h1f1{s}); h1f2{s} = sign(h1f2{s}); \n h2f1{s} = sign(h2f1{s}); h2f2{s} = sign(h2f2{s}); \n end\n \n % Generate correlation matrix\n cormat = correlationmatrix(f1, h1f1, h2f1, p1, ...\n f2, h1f2, h2f2, p2, w, dmax);\n\n [corrows,corcols] = size(cormat);\n \n % Find max along rows give strongest match in p2 for each p1\n [mp2forp1, colp2forp1] = max(cormat,[],2);\n \n % Find max down cols give strongest match in p1 for each p2 \n [mp1forp2, rowp1forp2] = max(cormat,[],1); \n \n % Now find matches that were consistent in both directions\n p1ind = zeros(1,length(p1)); % Arrays for storing matched indices\n p2ind = zeros(1,length(p2)); \n indcount = 0; \n for n = 1:corrows\n if rowp1forp2(colp2forp1(n)) == n % consistent both ways\n indcount = indcount + 1;\n p1ind(indcount) = n;\n p2ind(indcount) = colp2forp1(n);\n end\n end\n \n % Trim arrays of indices of matched points\n p1ind = p1ind(1:indcount); \n p2ind = p2ind(1:indcount); \n \n % Extract matched points from original arrays\n m1 = p1(:,p1ind); \n m2 = p2(:,p2ind); \n \n \n%------------------------------------------------------------------------- \n% Function that does the work. This function builds a 'correlation' matrix\n% that holds the correlation strength of every point relative to every other\n% point. While this seems a bit wasteful we need all this data if we want\n% to find pairs of points that correlate maximally in both directions.\n\nfunction cormat = correlationmatrix(f1, h1f1, h2f1, p1, ...\n f2, h1f2, h2f2, p2, w, dmax)\n \n if mod(w, 2) == 0 | w < 3\n error('Window size should be odd and >= 3');\n end\n\n r = (w-1)/2; % 'radius' of correlation window\n \n [rows1, npts1] = size(p1);\n [rows2, npts2] = size(p2); \n \n if rows1 ~= 2 | rows2 ~= 2\n error('Feature points must be specified in 2xN arrays');\n end \n \n % Reorganize monogenic phase data into a 4D matrices for convenience\n\n [im1rows,im1cols] = size(f1{1});\n [im2rows,im2cols] = size(f2{1});\n nscale = length(f1); \n phase1 = zeros(im1rows,im1cols,nscale,3);\n phase2 = zeros(im2rows,im2cols,nscale,3); \n \n for s = 1:nscale\n phase1(:,:,s,1) = f1{s}; phase1(:,:,s,2) = h1f1{s}; phase1(:,:,s,3) = h2f1{s};\n phase2(:,:,s,1) = f2{s}; phase2(:,:,s,2) = h1f2{s}; phase2(:,:,s,3) = h2f2{s}; \n end\n\n % Initialize correlation matrix values to -infinity\n cormat = repmat(-inf, npts1, npts2);\n \n % For every feature point in the first image extract a window of data\n % and correlate with a window corresponding to every feature point in\n % the other image. Any feature point less than distance 'r' from the\n % boundary of an image is not considered.\n \n % Find indices of points that are distance 'r' or greater from\n % boundary on image1 and image2;\n n1ind = find(p1(1,:)>r & p1(1,:)r & p1(2,:)r & p2(1,:)r & p2(2,:)r & p1(1,:)r & p1(2,:)r & p2(1,:)r & p2(2,:)> phaseSym = phasesym(im, 5, 6, 3, 2.5, 0.55, 2.0, 0);\n%\n% or as a partial list with unspecified parameters taking on default values\n% >> phaseSym = phasesym(im, 5, 6, 3);\n%\n% or as a partial list of parameters followed by some parameters specified via a\n% keyword-value pair, remaining parameters are set to defaults, for example:\n% >> phaseSym = phasesym(im, 5, 6, 3, 'polarity',-1, 'k', 2.5);\n% \n% The convolutions are done via the FFT. Many of the parameters relate to the\n% specification of the filters in the frequency plane. The values do not seem\n% to be very critical and the defaults are usually fine. You may want to\n% experiment with the values of 'nscales' and 'k', the noise compensation factor.\n%\n% Notes on filter settings to obtain even coverage of the spectrum\n% sigmaOnf .85 mult 1.3\n% sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave)\n% sigmaOnf .65 mult 2.1 \n% sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves)\n%\n% For maximum speed the input image should have dimensions that correspond to\n% powers of 2, but the code will operate on images of arbitrary size.\n%\n% See Also: PHASECONG, PHASECONG2, GABORCONVOLVE, PLOTGABORFILTERS\n\n% References:\n% Peter Kovesi, \"Symmetry and Asymmetry From Local Phase\" AI'97, Tenth\n% Australian Joint Conference on Artificial Intelligence. 2 - 4 December\n% 1997. http://www.cs.uwa.edu.au/pub/robvis/papers/pk/ai97.ps.gz.\n%\n% Peter Kovesi, \"Image Features From Phase Congruency\". Videre: A\n% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,\n% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html\n\n% April 1996 Original Version written \n% August 1998 Noise compensation corrected. \n% October 1998 Noise compensation corrected. - Again!!!\n% September 1999 Modified to operate on non-square images of arbitrary size. \n% February 2001 Specialised from phasecong.m to calculate phase symmetry \n% July 2005 Better argument handling + general cleanup and speed improvements\n% August 2005 Made Octave compatible.\n% January 2007 Small correction and cleanup of radius calculation for odd\n% image sizes.\n% May 2009 Noise compensation simplified reducing memory and\n% computation overhead. Spread function changed to a cosine\n% eliminating parameter dThetaOnSigma and ensuring even\n% angular coverage. \n\n% Copyright (c) 1996-2009 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n% \n% The software is provided \"as is\", without warranty of any kind.\n\nfunction[phaseSym, orientation, totalEnergy, T] = phasesym(varargin)\n\n % Get arguments and/or default values \n [im, nscale, norient, minWaveLength, mult, sigmaOnf, k, ...\n polarity, noiseMethod] = checkargs(varargin(:)); \n\n epsilon = 1e-4; % Used to prevent division by zero.\n [rows,cols] = size(im);\n imagefft = fft2(im); % Fourier transform of image\n zero = zeros(rows,cols);\n \n totalEnergy = zero; % Matrix for accumulating weighted phase \n % congruency values (energy).\n totalSumAn = zero; % Matrix for accumulating filter response\n % amplitude values.\n orientation = zero; % Matrix storing orientation with greatest\n % energy for each pixel.\n\n % Pre-compute some stuff to speed up filter construction\n\n % Set up X and Y matrices with ranges normalised to +/- 0.5\n % The following code adjusts things appropriately for odd and even values\n % of rows and columns.\n if mod(cols,2)\n\txrange = [-(cols-1)/2:(cols-1)/2]/(cols-1);\n else\n\txrange = [-cols/2:(cols/2-1)]/cols;\t\n end\n \n if mod(rows,2)\n\tyrange = [-(rows-1)/2:(rows-1)/2]/(rows-1);\n else\n\tyrange = [-rows/2:(rows/2-1)]/rows;\t\n end\n \n [x,y] = meshgrid(xrange, yrange);\n \n radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre.\n theta = atan2(-y,x); % Matrix values contain polar angle.\n % (note -ve y is used to give +ve\n % anti-clockwise angles)\n\n radius = ifftshift(radius); % Quadrant shift radius and theta so that filters\n theta = ifftshift(theta); % are constructed with 0 frequency at the corners.\n radius(1,1) = 1; % Get rid of the 0 radius value at the 0\n\t\t\t\t % frequency point (now at top-left corner)\n\t\t\t\t % so that taking the log of the radius will \n\t\t\t\t % not cause trouble.\t\t\t\t \n sintheta = sin(theta);\n costheta = cos(theta);\n clear x; clear y; clear theta; % save a little memory\n\n % Filters are constructed in terms of two components.\n % 1) The radial component, which controls the frequency band that the filter\n % responds to\n % 2) The angular component, which controls the orientation that the filter\n % responds to.\n % The two components are multiplied together to construct the overall filter.\n \n % Construct the radial filter components...\n % First construct a low-pass filter that is as large as possible, yet falls\n % away to zero at the boundaries. All log Gabor filters are multiplied by\n % this to ensure no extra frequencies at the 'corners' of the FFT are\n % incorporated as this seems to upset the normalisation process when\n % calculating phase congrunecy.\n lp = lowpassfilter([rows,cols],.4,10); % Radius .4, 'sharpness' 10\n\n logGabor = cell(1,nscale);\n \n for s = 1:nscale\n wavelength = minWaveLength*mult^(s-1);\n fo = 1.0/wavelength; % Centre frequency of filter.\n logGabor{s} = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); \n logGabor{s} = logGabor{s}.*lp; % Apply low-pass filter\n logGabor{s}(1,1) = 0; % Set the value at the 0 frequency point of the filter\n % back to zero (undo the radius fudge).\n end\n\n %% The main loop...\n\n for o = 1:norient % For each orientation....\n % Construct the angular filter spread function \n angl = (o-1)*pi/norient; % Filter angle.\n % For each point in the filter matrix calculate the angular distance from\n % the specified filter orientation. To overcome the angular wrap-around\n % problem sine difference and cosine difference values are first computed\n % and then the atan2 function is used to determine angular distance.\n ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.\n dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.\n dtheta = abs(atan2(ds,dc)); % Absolute angular distance.\n % Scale theta so that cosine spread function has the right wavelength\n % and clamp to pi.\n dtheta = min(dtheta*norient/2,pi); \n % The spread function is cos(dtheta) between -pi and pi. We add 1,\n % and then divide by 2 so that the value ranges 0-1\n spread = (cos(dtheta)+1)/2; \n \n sumAn_ThisOrient = zero; \n Energy_ThisOrient = zero; \n\n for s = 1:nscale % For each scale....\n filter = logGabor{s} .* spread; % Multiply radial and angular\n % components to get filter.\n\n % Convolve image with even and odd filters returning the result in EO\n EO = ifft2(imagefft .* filter);\n An = abs(EO); % Amplitude of even & odd filter response.\n sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses.\n\n % At the smallest scale estimate noise characteristics from the\n % distribution of the filter amplitude responses stored in sumAn. \n % tau is the Rayleigh parameter that is used to describe the\n % distribution.\n if s == 1 \n if noiseMethod == -1 % Use median to estimate noise statistics\n tau = median(sumAn_ThisOrient(:))/sqrt(log(4)); \n elseif noiseMethod == -2 % Use mode to estimate noise statistics\n tau = rayleighmode(sumAn_ThisOrient(:));\n end\n end\n\n % Now calculate the phase symmetry measure.\n if polarity == 0 % look for 'white' and 'black' spots\n Energy_ThisOrient = Energy_ThisOrient ...\n + abs(real(EO)) - abs(imag(EO));\n \n elseif polarity == 1 % Just look for 'white' spots\n Energy_ThisOrient = Energy_ThisOrient ...\n + real(EO) - abs(imag(EO));\n \n elseif polarity == -1 % Just look for 'black' spots\n Energy_ThisOrient = Energy_ThisOrient ...\n - real(EO) - abs(imag(EO));\n end\n\n end % ... and process the next scale \n\n %% Automatically determine noise threshold\n %\n % Assuming the noise is Gaussian the response of the filters to noise will\n % form Rayleigh distribution. We use the filter responses at the smallest\n % scale as a guide to the underlying noise level because the smallest scale\n % filters spend most of their time responding to noise, and only\n % occasionally responding to features. Either the median, or the mode, of\n % the distribution of filter responses can be used as a robust statistic to\n % estimate the distribution mean and standard deviation as these are related\n % to the median or mode by fixed constants. The response of the larger\n % scale filters to noise can then be estimated from the smallest scale\n % filter response according to their relative bandwidths.\n %\n % This code assumes that the expected reponse to noise on the phase congruency\n % calculation is simply the sum of the expected noise responses of each of\n % the filters. This is a simplistic overestimate, however these two\n % quantities should be related by some constant that will depend on the\n % filter bank being used. Appropriate tuning of the parameter 'k' will\n % allow you to produce the desired output. \n \n if noiseMethod >= 0 % We are using a fixed noise threshold\n T = noiseMethod; % use supplied noiseMethod value as the threshold\n else\n % Estimate the effect of noise on the sum of the filter responses as\n % the sum of estimated individual responses (this is a simplistic\n % overestimate). As the estimated noise response at succesive scales\n % is scaled inversely proportional to bandwidth we have a simple\n % geometric sum.\n totalTau = tau * (1 - (1/mult)^nscale)/(1-(1/mult));\n \n % Calculate mean and std dev from tau using fixed relationship\n % between these parameters and tau. See\n % http://mathworld.wolfram.com/RayleighDistribution.html\n EstNoiseEnergyMean = totalTau*sqrt(pi/2); % Expected mean and std\n EstNoiseEnergySigma = totalTau*sqrt((4-pi)/2); % values of noise energy\n \n % Noise threshold, make sure it is not less than epsilon.\n T = max(EstNoiseEnergyMean + k*EstNoiseEnergySigma, epsilon);\n end\n\n % Apply noise threshold, this is effectively wavelet denoising via\n % soft thresholding. Note 'Energy_ThisOrient' will have -ve values.\n % These will be floored out at the final normalization stage.\n Energy_ThisOrient = Energy_ThisOrient - T;\n \n % Update accumulator matrix for sumAn and totalEnergy\n totalSumAn = totalSumAn + sumAn_ThisOrient;\n totalEnergy = totalEnergy + Energy_ThisOrient;\n \n % Update orientation matrix by finding image points where the energy in\n % this orientation is greater than in any previous orientation (the\n % change matrix) and then replacing these elements in the orientation\n % matrix with the current orientation number.\n \n if(o == 1),\n maxEnergy = Energy_ThisOrient;\n else\n change = Energy_ThisOrient > maxEnergy;\n orientation = (o - 1).*change + orientation.*(~change);\n maxEnergy = max(maxEnergy, Energy_ThisOrient);\n end\n \n end % For each orientation\n \n % Normalize totalEnergy by the totalSumAn to obtain phase symmetry\n % totalEnergy is floored at 0 to eliminate -ve values\n phaseSym = max(totalEnergy, 0) ./ (totalSumAn + epsilon);\n \n % Convert orientation matrix values to degrees\n orientation = fix(orientation * (180 / norient));\n \n \n%------------------------------------------------------------------\n% CHECKARGS\n%\n% Function to process the arguments that have been supplied, assign\n% default values as needed and perform basic checks.\n \nfunction [im, nscale, norient, minWaveLength, mult, sigmaOnf, ...\n k, polarity, noiseMethod] = checkargs(arg)\n\n nargs = length(arg);\n \n if nargs < 1\n error('No image supplied as an argument');\n end \n \n % Set up default values for all arguments and then overwrite them\n % with with any new values that may be supplied\n im = [];\n nscale = 5; % Number of wavelet scales. \n norient = 6; % Number of filter orientations.\n minWaveLength = 3; % Wavelength of smallest scale filter. \n mult = 2.1; % Scaling factor between successive filters. \n sigmaOnf = 0.55; % Ratio of the standard deviation of the\n % Gaussian describing the log Gabor filter's\n % transfer function in the frequency domain\n % to the filter center frequency. \n k = 2.0; % No of standard deviations of the noise\n % energy beyond the mean at which we set the\n % noise threshold point. \n\n polarity = 0; % Look for both black and white spots of symmetrry\n noiseMethod = -1; % Use median response of smallest scale filter\n % to estimate noise characteristics.\n \n % Allowed argument reading states\n allnumeric = 1; % Numeric argument values in predefined order\n keywordvalue = 2; % Arguments in the form of string keyword\n % followed by numeric value\n readstate = allnumeric; % Start in the allnumeric state\n \n if readstate == allnumeric\n for n = 1:nargs\n if isa(arg{n},'char')\n readstate = keywordvalue;\n break;\n else\n if n == 1, im = arg{n}; \n elseif n == 2, nscale = arg{n}; \n elseif n == 3, norient = arg{n};\n elseif n == 4, minWaveLength = arg{n};\n elseif n == 5, mult = arg{n};\n elseif n == 6, sigmaOnf = arg{n};\n elseif n == 7, k = arg{n}; \n elseif n == 8, polarity = arg{n}; \n elseif n == 9,noiseMethod = arg{n}; \n end\n end\n end\n end\n\n % Code to handle parameter name - value pairs\n if readstate == keywordvalue\n while n < nargs\n \n if ~isa(arg{n},'char') || ~isa(arg{n+1}, 'double')\n error('There should be a parameter name - value pair');\n end\n \n if strncmpi(arg{n},'im' ,2), im = arg{n+1};\n elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1};\n elseif strncmpi(arg{n},'norient' ,4), norient = arg{n+1};\n elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1};\n elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1};\n elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1};\n elseif strncmpi(arg{n},'k' ,1), k = arg{n+1};\n elseif strncmpi(arg{n},'polarity',2), polarity = arg{n+1};\n elseif strncmpi(arg{n},'noiseMethod',4), noiseMethod = arg{n+1}; \n else error('Unrecognised parameter name');\n end\n\n n = n+2;\n if n == nargs\n error('Unmatched parameter name - value pair');\n end\n end\n end\n \n if isempty(im)\n error('No image argument supplied');\n end\n\n if ~isa(im, 'double')\n im = double(im);\n end\n \n if nscale < 1\n error('nscale must be an integer >= 1');\n end\n \n if norient < 1 \n error('norient must be an integer >= 1');\n end \n\n if minWaveLength < 2\n error('It makes little sense to have a wavelength < 2');\n end \n \n if polarity ~= -1 && polarity ~= 0 && polarity ~= 1\n error('Allowed polarity values are -1, 0 and 1')\n end\n \n\n%%-------------------------------------------------------------------------\n% RAYLEIGHMODE\n%\n% Computes mode of a vector/matrix of data that is assumed to come from a\n% Rayleigh distribution.\n%\n% Usage: rmode = rayleighmode(data, nbins)\n%\n% Arguments: data - data assumed to come from a Rayleigh distribution\n% nbins - Optional number of bins to use when forming histogram\n% of the data to determine the mode.\n%\n% Mode is computed by forming a histogram of the data over 50 bins and then\n% finding the maximum value in the histogram. Mean and standard deviation\n% can then be calculated from the mode as they are related by fixed\n% constants.\n%\n% mean = mode * sqrt(pi/2)\n% std dev = mode * sqrt((4-pi)/2)\n% \n% See\n% http://mathworld.wolfram.com/RayleighDistribution.html\n% http://en.wikipedia.org/wiki/Rayleigh_distribution\n%\n\nfunction rmode = rayleighmode(data, nbins)\n \n if nargin == 1\n nbins = 50; % Default number of histogram bins to use\n end\n\n mx = max(data(:));\n edges = 0:mx/nbins:mx;\n n = histc(data(:),edges); \n [dum,ind] = max(n); % Find maximum and index of maximum in histogram \n\n rmode = (edges(ind)+edges(ind+1))/2;\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "phasesymmono.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/phasesymmono.m", "size": 19431, "source_encoding": "utf_8", "md5": "30a844da3cb8a9df67b71b7235e99d8b", "text": "% PHASESYMMONO - phase symmetry of an image using monogenic filters\n%\n% This function calculates the phase symmetry of points in an image.\n% This is a contrast invariant measure of symmetry. This function can be\n% used as a line and blob detector. The greyscale 'polarity' of the lines\n% that you want to find can be specified.\n%\n% This code is considerably faster than PHASESYM but you may prefer the\n% output from PHASESYM's oriented filters.\n%\n% There are potentially many arguments, here is the full usage:\n%\n% [phaseSym, symmetryEnergy, T] = ...\n% phasesymmono(im, nscale, minWaveLength, mult, ...\n% sigmaOnf, k, polarity, noiseMethod)\n%\n% However, apart from the image, all parameters have defaults and the\n% usage can be as simple as:\n%\n% phaseSym = phasesymmono(im);\n% \n% Arguments:\n% Default values Description\n%\n% nscale 5 - Number of wavelet scales, try values 3-6\n% minWaveLength 3 - Wavelength of smallest scale filter.\n% mult 2.1 - Scaling factor between successive filters.\n% sigmaOnf 0.55 - Ratio of the standard deviation of the Gaussian \n% describing the log Gabor filter's transfer function \n% in the frequency domain to the filter center frequency.\n% k 2.0 - No of standard deviations of the noise energy beyond\n% the mean at which we set the noise threshold point.\n% You may want to vary this up to a value of 10 or\n% 20 for noisy images \n% polarity 0 - Controls 'polarity' of symmetry features to find.\n% 1 - just return 'bright' points\n% -1 - just return 'dark' points\n% 0 - return bright and dark points.\n% noiseMethod -1 - Parameter specifies method used to determine\n% noise statistics. \n% -1 use median of smallest scale filter responses\n% -2 use mode of smallest scale filter responses\n% 0+ use noiseMethod value as the fixed noise threshold \n% A value of 0 will turn off all noise compensation.\n%\n% Return values:\n% phaseSym - Phase symmetry image (values between 0 and 1).\n% symmetryEnergy - Un-normalised raw symmetry energy which may be\n% more to your liking.\n% T - Calculated noise threshold (can be useful for\n% diagnosing noise characteristics of images)\n%\n%\n% Notes on specifying parameters: \n%\n% The parameters can be specified as a full list eg.\n% >> phaseSym = phasesym(im, 5, 3, 2.5, 0.55, 2.0, 0);\n%\n% or as a partial list with unspecified parameters taking on default values\n% >> phaseSym = phasesym(im, 5, 3);\n%\n% or as a partial list of parameters followed by some parameters specified via a\n% keyword-value pair, remaining parameters are set to defaults, for example:\n% >> phaseSym = phasesym(im, 5, 3, 'polarity',-1, 'k', 2.5);\n% \n% The convolutions are done via the FFT. Many of the parameters relate to the\n% specification of the filters in the frequency plane. The values do not seem\n% to be very critical and the defaults are usually fine. You may want to\n% experiment with the values of 'nscales' and 'k', the noise compensation factor.\n%\n% Notes on filter settings to obtain even coverage of the spectrum\n% sigmaOnf .85 mult 1.3\n% sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave)\n% sigmaOnf .65 mult 2.1 \n% sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves)\n%\n% For maximum speed the input image should have dimensions that correspond to\n% powers of 2, but the code will operate on images of arbitrary size.\n%\n% See Also: PHASESYM, PHASECONGMONO\n\n% References:\n% Peter Kovesi, \"Symmetry and Asymmetry From Local Phase\" AI'97, Tenth\n% Australian Joint Conference on Artificial Intelligence. 2 - 4 December\n% 1997. http://www.cs.uwa.edu.au/pub/robvis/papers/pk/ai97.ps.gz.\n%\n% Peter Kovesi, \"Image Features From Phase Congruency\". Videre: A\n% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,\n% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html\n%\n% Michael Felsberg and Gerald Sommer, \"A New Extension of Linear Signal\n% Processing for Estimating Local Properties and Detecting Features\". DAGM\n% Symposium 2000, Kiel\n%\n% Michael Felsberg and Gerald Sommer. \"The Monogenic Signal\" IEEE\n% Transactions on Signal Processing, 49(12):3136-3144, December 2001\n\n\n\n% July 2008 Code developed from phasesym where local phase information\n% calculated using Monogenic Filters.\n% April 2009 Noise compensation simplified to speedup execution.\n% Options to calculate noise statistics via median or mode of\n% smallest filter response. Option to use a fixed threshold.\n% Return of T for 'instrumentation' of noise detection/compensation.\n% Removal of orientation calculation from phasesym (not clear\n% how best to calculate this from monogenic filter outputs)\n% June 2009 Clean up\n\n% Copyright (c) 1996-2009 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n% \n% The software is provided \"as is\", without warranty of any kind.\n\nfunction[phaseSym, symmetryEnergy, T] = phasesymmono(varargin)\n\n % Get arguments and/or default values \n [im, nscale, minWaveLength, mult, sigmaOnf, k, ...\n polarity, noiseMethod] = checkargs(varargin(:)); \n\n epsilon = .0001; % Used to prevent division by zero.\n\n [rows,cols] = size(im);\n IM = fft2(im); % Fourier transform of image\n zero = zeros(rows,cols);\n symmetryEnergy = zero; % Matrix for accumulating weighted phase \n % symmetry values (energy).\n sumAn = zero; % Matrix for accumulating filter response\n % amplitude values.\n \n % Pre-compute some stuff to speed up filter construction\n %\n % Set up u1 and u2 matrices with ranges normalised to +/- 0.5\n % The following code adjusts things appropriately for odd and even values\n % of rows and columns.\n if mod(cols,2)\n xrange = [-(cols-1)/2:(cols-1)/2]/(cols-1);\n else\n xrange = [-cols/2:(cols/2-1)]/cols; \n end\n \n if mod(rows,2)\n yrange = [-(rows-1)/2:(rows-1)/2]/(rows-1);\n else\n yrange = [-rows/2:(rows/2-1)]/rows; \n end\n \n [u1,u2] = meshgrid(xrange, yrange);\n \n u1 = ifftshift(u1); % Quadrant shift to put 0 frequency at the corners\n u2 = ifftshift(u2);\n \n radius = sqrt(u1.^2 + u2.^2); % Matrix values contain frequency\n % values as a radius from centre\n % (but quadrant shifted)\n \n % Get rid of the 0 radius value in the middle (at top left corner after\n % fftshifting) so that taking the log of the radius, or dividing by the\n % radius, will not cause trouble.\n radius(1,1) = 1;\n \n % Construct the monogenic filters in the frequency domain. The two\n % filters would normally be constructed as follows\n % H1 = i*u1./radius; \n % H2 = i*u2./radius;\n % However the two filters can be packed together as a complex valued\n % matrix, one in the real part and one in the imaginary part. Do this by\n % multiplying H2 by i and then adding it to H1 (note the subtraction\n % because i*i = -1). When the convolution is performed via the fft the\n % real part of the result will correspond to the convolution with H1 and\n % the imaginary part with H2. This allows the two convolutions to be\n % done as one in the frequency domain, saving time and memory.\n H = (i*u1 - u2)./radius;\n \n % The two monogenic filters H1 and H2 are not selective in terms of the\n % magnitudes of the frequencies. The code below generates bandpass\n % log-Gabor filters which are point-wise multiplied by IM to produce\n % different bandpass versions of the image before being convolved with H1\n % and H2\n \n % First construct a low-pass filter that is as large as possible, yet falls\n % away to zero at the boundaries. All filters are multiplied by\n % this to ensure no extra frequencies at the 'corners' of the FFT are\n % incorporated as this can upset the normalisation process when\n % calculating phase symmetry\n lp = lowpassfilter([rows,cols],.4,10); % Radius .4, 'sharpness' 10\n\n for s = 1:nscale\n wavelength = minWaveLength*mult^(s-1);\n fo = 1.0/wavelength; % Centre frequency of filter.\n logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); \n logGabor = logGabor.*lp; % Apply low-pass filter\n logGabor(1,1) = 0; % Set the value at the 0 frequency point of the filter\n % back to zero (undo the radius fudge).\n\n IMF = IM.*logGabor; % Bandpassed image in the frequency domain \n f = real(ifft2(IMF)); % Bandpassed image in spatial domain\n\n h = ifft2(IMF.*H); % Bandpassed monogenic filtering, real part of h contains\n % convolution result with h1, imaginary part\n % contains convolution result with h2.\n hAmp2 = real(h).^2 + imag(h).^2; % Squared amplitude of h1 h2 filter results\n \n sumAn = sumAn + sqrt(f.^2 + hAmp2); % Magnitude of Energy.\n \n % Now calculate the phase symmetry measure.\n if polarity == 0 % look for 'white' and 'black' spots\n symmetryEnergy = symmetryEnergy + abs(f) - sqrt(hAmp2);\n \n elseif polarity == 1 % Just look for 'white' spots\n symmetryEnergy = symmetryEnergy + f - sqrt(hAmp2); \n \n elseif polarity == -1 % Just look for 'black' spots\n symmetryEnergy = symmetryEnergy - f - sqrt(hAmp2); \n end\n \n % At the smallest scale estimate noise characteristics from the\n % distribution of the filter amplitude responses stored in sumAn. \n % tau is the Rayleigh parameter that is used to specify the\n % distribution.\n if s == 1 \n if noiseMethod == -1 % Use median to estimate noise statistics\n tau = median(sumAn(:))/sqrt(log(4)); \n elseif noiseMethod == -2 % Use mode to estimate noise statistics\n tau = rayleighmode(sumAn(:));\n end\n end\n \n end % For each scale\n\n % Compensate for noise\n %\n % Assuming the noise is Gaussian the response of the filters to noise will\n % form Rayleigh distribution. We use the filter responses at the smallest\n % scale as a guide to the underlying noise level because the smallest scale\n % filters spend most of their time responding to noise, and only\n % occasionally responding to features. Either the median, or the mode, of\n % the distribution of filter responses can be used as a robust statistic to\n % estimate the distribution mean and standard deviation as these are related\n % to the median or mode by fixed constants. The response of the larger\n % scale filters to noise can then be estimated from the smallest scale\n % filter response according to their relative bandwidths.\n %\n % This code assumes that the expected reponse to noise on the phase symmetry\n % calculation is simply the sum of the expected noise responses of each of\n % the filters. This is a simplistic overestimate, however these two\n % quantities should be related by some constant that will depend on the\n % filter bank being used. Appropriate tuning of the parameter 'k' will\n % allow you to produce the desired output. (though the value of k seems to\n % be not at all critical)\n \n if noiseMethod >= 0 % We are using a fixed noise threshold\n T = noiseMethod; % use supplied noiseMethod value as the threshold\n else\n % Estimate the effect of noise on the sum of the filter responses as\n % the sum of estimated individual responses (this is a simplistic\n % overestimate). As the estimated noise response at succesive scales\n % is scaled inversely proportional to bandwidth we have a simple\n % geometric sum.\n totalTau = tau * (1 - (1/mult)^nscale)/(1-(1/mult));\n \n % Calculate mean and std dev from tau using fixed relationship\n % between these parameters and tau. See\n % http://mathworld.wolfram.com/RayleighDistribution.html\n \n EstNoiseEnergyMean = totalTau*sqrt(pi/2); % Expected mean and std\n EstNoiseEnergySigma = totalTau*sqrt((4-pi)/2); % values of noise energy\n \n % Noise threshold, make sure it is not less than epsilon\n T = max(EstNoiseEnergyMean + k*EstNoiseEnergySigma, epsilon);\n end\n \n % Apply noise threshold - effectively wavelet denoising soft thresholding\n % and normalize symmetryEnergy by the sumAn to obtain phase symmetry.\n % Note the max operation is not necessary if you are after speed, it is\n % just 'tidy' not having -ve symmetry values\n phaseSym = max(symmetryEnergy-T, zero) ./ (sumAn + epsilon);\n \n \n%------------------------------------------------------------------\n% CHECKARGS\n%\n% Function to process the arguments that have been supplied, assign\n% default values as needed and perform basic checks.\n \nfunction [im, nscale, minWaveLength, mult, sigmaOnf, ...\n k, polarity, noiseMethod] = checkargs(arg)\n\n nargs = length(arg);\n \n if nargs < 1\n error('No image supplied as an argument');\n end \n \n % Set up default values for all arguments and then overwrite them\n % with with any new values that may be supplied\n im = [];\n nscale = 5; % Number of wavelet scales. \n minWaveLength = 3; % Wavelength of smallest scale filter. \n mult = 2.1; % Scaling factor between successive filters. \n sigmaOnf = 0.55; % Ratio of the standard deviation of the\n % Gaussian describing the log Gabor filter's\n % transfer function in the frequency domain\n % to the filter center frequency. \n k = 2.0; % No of standard deviations of the noise\n % energy beyond the mean at which we set the\n % noise threshold point. \n\n polarity = 0; % Look for both black and white spots of symmetry\n noiseMethod = -1; % Use the median response of smallest scale\n % filter to estimate noise statistics\n \n % Allowed argument reading states\n allnumeric = 1; % Numeric argument values in predefined order\n keywordvalue = 2; % Arguments in the form of string keyword\n % followed by numeric value\n readstate = allnumeric; % Start in the allnumeric state\n \n if readstate == allnumeric\n for n = 1:nargs\n if isa(arg{n},'char')\n readstate = keywordvalue;\n break;\n else\n if n == 1, im = arg{n}; \n elseif n == 2, nscale = arg{n}; \n elseif n == 3, minWaveLength = arg{n};\n elseif n == 4, mult = arg{n};\n elseif n == 5, sigmaOnf = arg{n};\n elseif n == 6, k = arg{n}; \n elseif n == 7, polarity = arg{n};\n elseif n == 8, noiseMethod = arg{n}; \n end\n end\n end\n end\n\n % Code to handle parameter name - value pairs\n if readstate == keywordvalue\n while n < nargs\n \n if ~isa(arg{n},'char') || ~isa(arg{n+1}, 'double')\n error('There should be a parameter name - value pair');\n end\n \n if strncmpi(arg{n},'im' ,2), im = arg{n+1};\n elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1};\n elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1};\n elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1};\n elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1};\n elseif strncmpi(arg{n},'k' ,1), k = arg{n+1};\n elseif strncmpi(arg{n},'polarity',2), polarity = arg{n+1};\n elseif strncmpi(arg{n},'noisemethod',3), noiseMethod = arg{n+1}; \n else error('Unrecognised parameter name');\n end\n\n n = n+2;\n if n == nargs\n error('Unmatched parameter name - value pair');\n end\n end\n end\n \n if isempty(im)\n error('No image argument supplied');\n end\n\n if ~isa(im, 'double')\n im = double(im);\n end\n \n if nscale < 1\n error('nscale must be an integer >= 1');\n end\n \n if minWaveLength < 2\n error('It makes little sense to have a wavelength < 2');\n end \n \n if polarity ~= -1 && polarity ~= 0 && polarity ~= 1\n error('Allowed polarity values are -1, 0 and 1')\n end\n \n \n%-------------------------------------------------------------------------\n% RAYLEIGHMODE\n%\n% Computes mode of a vector/matrix of data that is assumed to come from a\n% Rayleigh distribution.\n%\n% Usage: rmode = rayleighmode(data, nbins)\n%\n% Arguments: data - data assumed to come from a Rayleigh distribution\n% nbins - Optional number of bins to use when forming histogram\n% of the data to determine the mode.\n%\n% Mode is computed by forming a histogram of the data over 50 bins and then\n% finding the maximum value in the histogram. Mean and standard deviation\n% can then be calculated from the mode as they are related by fixed\n% constants.\n%\n% mean = mode * sqrt(pi/2)\n% std dev = mode * sqrt((4-pi)/2)\n% \n% See\n% http://mathworld.wolfram.com/RayleighDistribution.html\n% http://en.wikipedia.org/wiki/Rayleigh_distribution\n%\n\n\nfunction rmode = rayleighmode(data, nbins)\n \n if nargin == 1\n nbins = 50; % Default number of histogram bins to use\n end\n\n mx = max(data(:));\n edges = 0:mx/nbins:mx;\n n = histc(data(:),edges); \n [dum,ind] = max(n); % Find maximum and index of maximum in histogram \n\n rmode = (edges(ind)+edges(ind+1))/2;\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "phasecong2.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/phasecong2.m", "size": 22754, "source_encoding": "utf_8", "md5": "4c97e691728c820aefd65a29a31d6dc5", "text": "% PHASECONG2 - Computes edge and corner phase congruency in an image.\r\n%\r\n% This function calculates the PC_2 measure of phase congruency. \r\n% This function supersedes PHASECONG\r\n%\r\n% There are potentially many arguments, here is the full usage:\r\n%\r\n% [M m or ft pc EO] = phasecong2(im, nscale, norient, minWaveLength, ...\r\n% mult, sigmaOnf, dThetaOnSigma, k, cutOff, g)\r\n%\r\n% However, apart from the image, all parameters have defaults and the\r\n% usage can be as simple as:\r\n%\r\n% M = phasecong2(im);\r\n% \r\n% Arguments:\r\n% Default values Description\r\n%\r\n% nscale 4 - Number of wavelet scales, try values 3-6\r\n% norient 6 - Number of filter orientations.\r\n% minWaveLength 3 - Wavelength of smallest scale filter.\r\n% mult 2.1 - Scaling factor between successive filters.\r\n% sigmaOnf 0.55 - Ratio of the standard deviation of the Gaussian \r\n% describing the log Gabor filter's transfer function \r\n% in the frequency domain to the filter center frequency.\r\n% dThetaOnSigma 1.2 - Ratio of angular interval between filter orientations\r\n% and the standard deviation of the angular Gaussian\r\n% function used to construct filters in the\r\n% freq. plane.\r\n% k 2.0 - No of standard deviations of the noise energy beyond\r\n% the mean at which we set the noise threshold point.\r\n% You may want to vary this up to a value of 10 or\r\n% 20 for noisy images \r\n% cutOff 0.5 - The fractional measure of frequency spread\r\n% below which phase congruency values get penalized.\r\n% g 10 - Controls the sharpness of the transition in\r\n% the sigmoid function used to weight phase\r\n% congruency for frequency spread. \r\n%\r\n% Returned values:\r\n% M - Maximum moment of phase congruency covariance.\r\n% This is used as a indicator of edge strength.\r\n% m - Minimum moment of phase congruency covariance.\r\n% This is used as a indicator of corner strength.\r\n% or - Orientation image in integer degrees 0-180,\r\n% positive anticlockwise.\r\n% 0 corresponds to a vertical edge, 90 is horizontal.\r\n% ft - *Not correctly implemented at this stage*\r\n% A complex valued image giving the weighted mean \r\n% phase angle at every point in the image for each\r\n% orientation. \r\n% pc - Cell array of phase congruency images (values between 0 and 1) \r\n% for each orientation\r\n% EO - A 2D cell array of complex valued convolution results\r\n%\r\n% EO{s,o} = convolution result for scale s and orientation o. The real part\r\n% is the result of convolving with the even symmetric filter, the imaginary\r\n% part is the result from convolution with the odd symmetric filter.\r\n%\r\n% Hence:\r\n% abs(EO{s,o}) returns the magnitude of the convolution over the\r\n% image at scale s and orientation o.\r\n% angle(EO{s,o}) returns the phase angles.\r\n% \r\n% Notes on specifying parameters: \r\n%\r\n% The parameters can be specified as a full list eg.\r\n% >> [M m or ft pc EO] = phasecong2(im, 5, 6, 3, 2.5, 0.55, 1.2, 2.0, 0.4, 10);\r\n%\r\n% or as a partial list with unspecified parameters taking on default values\r\n% >> [M m or ft pc EO] = phasecong2(im, 5, 6, 3);\r\n%\r\n% or as a partial list of parameters followed by some parameters specified via a\r\n% keyword-value pair, remaining parameters are set to defaults, for example:\r\n% >> [M m or ft pc EO] = phasecong2(im, 5, 6, 3, 'cutOff', 0.3, 'k', 2.5);\r\n% \r\n% The convolutions are done via the FFT. Many of the parameters relate to the\r\n% specification of the filters in the frequency plane. The values do not seem\r\n% to be very critical and the defaults are usually fine. You may want to\r\n% experiment with the values of 'nscales' and 'k', the noise compensation factor.\r\n%\r\n% Notes on filter settings to obtain even coverage of the spectrum\r\n% dthetaOnSigma 1.2 norient 6\r\n% sigmaOnf .85 mult 1.3\r\n% sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave)\r\n% sigmaOnf .65 mult 2.1 \r\n% sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves)\r\n%\r\n% For maximum speed the input image should have dimensions that correspond to\r\n% powers of 2, but the code will operate on images of arbitrary size.\r\n%\r\n% See Also: PHASECONG, PHASESYM, GABORCONVOLVE, PLOTGABORFILTERS\r\n\r\n% References:\r\n%\r\n% Peter Kovesi, \"Image Features From Phase Congruency\". Videre: A\r\n% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,\r\n% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html\r\n%\r\n% Peter Kovesi, \"Phase Congruency Detects Corners and\r\n% Edges\". Proceedings DICTA 2003, Sydney Dec 10-12\r\n\r\n% April 1996 Original Version written \r\n% August 1998 Noise compensation corrected. \r\n% October 1998 Noise compensation corrected. - Again!!!\r\n% September 1999 Modified to operate on non-square images of arbitrary size. \r\n% May 2001 Modified to return feature type image. \r\n% July 2003 Altered to calculate 'corner' points. \r\n% October 2003 Speed improvements and refinements. \r\n% July 2005 Better argument handling, changed order of return values\r\n% August 2005 Made Octave compatible\r\n% May 2006 Bug in checkargs fixed\r\n% Jan 2007 Bug in setting radius to 0 for odd sized images fixed.\r\n% April 2009 Scaling of covariance values fixed. (Negligible change to results) \r\n\r\n% Copyright (c) 1996-2009 Peter Kovesi\r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% http://www.csse.uwa.edu.au/\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in all\r\n% copies or substantial portions of the Software.\r\n% \r\n% The software is provided \"as is\", without warranty of any kind.\r\n\r\nfunction [M, m, or, featType, PC, EO]=phasecong2(varargin)\r\n \r\n% Get arguments and/or default values\r\n[im, nscale, norient, minWaveLength, mult, sigmaOnf, ...\r\n dThetaOnSigma,k, cutOff, g] = checkargs(varargin(:));\r\n\r\nepsilon = .0001; % Used to prevent division by zero.\r\n\r\nthetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the\r\n % angular Gaussian function used to\r\n % construct filters in the freq. plane.\r\n\r\n[rows,cols] = size(im);\r\nimagefft = fft2(im); % Fourier transform of image\r\n\r\nzero = zeros(rows,cols);\r\ntotalEnergy = zero; % Total weighted phase congruency values (energy).\r\ntotalSumAn = zero; % Total filter response amplitude values.\r\norientation = zero; % Matrix storing orientation with greatest\r\n % energy for each pixel.\r\nEO = cell(nscale, norient); % Array of convolution results.\r\ncovx2 = zero; % Matrices for covariance data\r\ncovy2 = zero;\r\ncovxy = zero;\r\n\r\nestMeanE2n = [];\r\nifftFilterArray = cell(1,nscale); % Array of inverse FFTs of filters\r\n\r\n% Pre-compute some stuff to speed up filter construction\r\n\r\n% Set up X and Y matrices with ranges normalised to +/- 0.5\r\n% The following code adjusts things appropriately for odd and even values\r\n% of rows and columns.\r\nif mod(cols,2)\r\n xrange = [-(cols-1)/2:(cols-1)/2]/(cols-1);\r\nelse\r\n xrange = [-cols/2:(cols/2-1)]/cols;\r\nend\r\n\r\nif mod(rows,2)\r\n yrange = [-(rows-1)/2:(rows-1)/2]/(rows-1);\r\nelse\r\n yrange = [-rows/2:(rows/2-1)]/rows;\r\nend\r\n\r\n[x,y] = meshgrid(xrange, yrange);\r\n\r\nradius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre.\r\ntheta = atan2(-y,x); % Matrix values contain polar angle.\r\n % (note -ve y is used to give +ve\r\n % anti-clockwise angles)\r\n \r\nradius = ifftshift(radius); % Quadrant shift radius and theta so that filters\r\ntheta = ifftshift(theta); % are constructed with 0 frequency at the corners.\r\nradius(1,1) = 1; % Get rid of the 0 radius value at the 0\r\n % frequency point (now at top-left corner)\r\n % so that taking the log of the radius will\r\n % not cause trouble.\r\n\r\nsintheta = sin(theta);\r\ncostheta = cos(theta);\r\nclear x; clear y; clear theta; % save a little memory\r\n\r\n% Filters are constructed in terms of two components.\r\n% 1) The radial component, which controls the frequency band that the filter\r\n% responds to\r\n% 2) The angular component, which controls the orientation that the filter\r\n% responds to.\r\n% The two components are multiplied together to construct the overall filter.\r\n\r\n% Construct the radial filter components...\r\n\r\n% First construct a low-pass filter that is as large as possible, yet falls\r\n% away to zero at the boundaries. All log Gabor filters are multiplied by\r\n% this to ensure no extra frequencies at the 'corners' of the FFT are\r\n% incorporated as this seems to upset the normalisation process when\r\n% calculating phase congrunecy.\r\nlp = lowpassfilter([rows,cols],.45,15); % Radius .45, 'sharpness' 15\r\n\r\nlogGabor = cell(1,nscale);\r\n\r\nfor s = 1:nscale\r\n wavelength = minWaveLength*mult^(s-1);\r\n fo = 1.0/wavelength; % Centre frequency of filter.\r\n logGabor{s} = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));\r\n logGabor{s} = logGabor{s}.*lp; % Apply low-pass filter\r\n logGabor{s}(1,1) = 0; % Set the value at the 0 frequency point of the filter\r\n % back to zero (undo the radius fudge).\r\nend\r\n\r\n% Then construct the angular filter components...\r\n\r\nspread = cell(1,norient);\r\n\r\nfor o = 1:norient\r\n angl = (o-1)*pi/norient; % Filter angle.\r\n\r\n % For each point in the filter matrix calculate the angular distance from\r\n % the specified filter orientation. To overcome the angular wrap-around\r\n % problem sine difference and cosine difference values are first computed\r\n % and then the atan2 function is used to determine angular distance.\r\n\r\n ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.\r\n dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.\r\n dtheta = abs(atan2(ds,dc)); % Absolute angular distance.\r\n spread{o} = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the\r\n % angular filter component.\r\nend\r\n\r\n% The main loop...\r\n\r\nfor o = 1:norient % For each orientation.\r\n% fprintf('Processing orientation %d\\r',o);\r\n\r\n angl = (o-1)*pi/norient; % Filter angle.\r\n sumE_ThisOrient = zero; % Initialize accumulator matrices.\r\n sumO_ThisOrient = zero;\r\n sumAn_ThisOrient = zero;\r\n Energy = zero;\r\n\r\n for s = 1:nscale, % For each scale.\r\n filter = logGabor{s} .* spread{o}; % Multiply radial and angular\r\n % components to get the filter.\r\n\r\n% if o == 1 % accumulate filter info for noise compensation (nominally the same\r\n % for all orientations, hence it is only done once)\r\n ifftFilt = real(ifft2(filter))*sqrt(rows*cols); % Note rescaling to match power\r\n ifftFilterArray{s} = ifftFilt; % record ifft2 of filter\r\n% end\r\n\r\n % Convolve image with even and odd filters returning the result in EO\r\n EO{s,o} = ifft2(imagefft .* filter);\r\n\r\n An = abs(EO{s,o}); % Amplitude of even & odd filter response.\r\n sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses.\r\n sumE_ThisOrient = sumE_ThisOrient + real(EO{s,o}); % Sum of even filter convolution results.\r\n sumO_ThisOrient = sumO_ThisOrient + imag(EO{s,o}); % Sum of odd filter convolution results.\r\n\r\n if s==1 % Record mean squared filter value at smallest\r\n EM_n = sum(sum(filter.^2)); % scale. This is used for noise estimation.\r\n maxAn = An; % Record the maximum An over all scales.\r\n else\r\n maxAn = max(maxAn, An);\r\n end\r\n\r\n end % ... and process the next scale\r\n\r\n % Get weighted mean filter response vector, this gives the weighted mean\r\n % phase angle.\r\n\r\n XEnergy = sqrt(sumE_ThisOrient.^2 + sumO_ThisOrient.^2) + epsilon;\r\n MeanE = sumE_ThisOrient ./ XEnergy;\r\n MeanO = sumO_ThisOrient ./ XEnergy;\r\n\r\n % Now calculate An(cos(phase_deviation) - | sin(phase_deviation)) | by\r\n % using dot and cross products between the weighted mean filter response\r\n % vector and the individual filter response vectors at each scale. This\r\n % quantity is phase congruency multiplied by An, which we call energy.\r\n\r\n for s = 1:nscale,\r\n E = real(EO{s,o}); O = imag(EO{s,o}); % Extract even and odd\r\n % convolution results.\r\n Energy = Energy + E.*MeanE + O.*MeanO - abs(E.*MeanO - O.*MeanE);\r\n end\r\n\r\n % Compensate for noise\r\n % We estimate the noise power from the energy squared response at the\r\n % smallest scale. If the noise is Gaussian the energy squared will have a\r\n % Chi-squared 2DOF pdf. We calculate the median energy squared response\r\n % as this is a robust statistic. From this we estimate the mean.\r\n % The estimate of noise power is obtained by dividing the mean squared\r\n % energy value by the mean squared filter value\r\n\r\n medianE2n = median(reshape(abs(EO{1,o}).^2,1,rows*cols));\r\n meanE2n = -medianE2n/log(0.5);\r\n estMeanE2n(o) = meanE2n;\r\n\r\n noisePower = meanE2n/EM_n; % Estimate of noise power.\r\n\r\n% if o == 1\r\n % Now estimate the total energy^2 due to noise\r\n % Estimate for sum(An^2) + sum(Ai.*Aj.*(cphi.*cphj + sphi.*sphj))\r\n\r\n EstSumAn2 = zero;\r\n for s = 1:nscale\r\n EstSumAn2 = EstSumAn2 + ifftFilterArray{s}.^2;\r\n end\r\n\r\n EstSumAiAj = zero;\r\n for si = 1:(nscale-1)\r\n for sj = (si+1):nscale\r\n EstSumAiAj = EstSumAiAj + ifftFilterArray{si}.*ifftFilterArray{sj};\r\n end\r\n end\r\n sumEstSumAn2 = sum(sum(EstSumAn2));\r\n sumEstSumAiAj = sum(sum(EstSumAiAj));\r\n\r\n% end % if o == 1\r\n\r\n EstNoiseEnergy2 = 2*noisePower*sumEstSumAn2 + 4*noisePower*sumEstSumAiAj;\r\n\r\n tau = sqrt(EstNoiseEnergy2/2); % Rayleigh parameter\r\n EstNoiseEnergy = tau*sqrt(pi/2); % Expected value of noise energy\r\n EstNoiseEnergySigma = sqrt( (2-pi/2)*tau^2 );\r\n\r\n T = EstNoiseEnergy + k*EstNoiseEnergySigma; % Noise threshold\r\n\r\n % The estimated noise effect calculated above is only valid for the PC_1 measure.\r\n % The PC_2 measure does not lend itself readily to the same analysis. However\r\n % empirically it seems that the noise effect is overestimated roughly by a factor\r\n % of 1.7 for the filter parameters used here.\r\n\r\n T = T/1.7; % Empirical rescaling of the estimated noise effect to\r\n % suit the PC_2 phase congruency measure\r\n\r\n Energy = max(Energy - T, zero); % Apply noise threshold\r\n\r\n % Form weighting that penalizes frequency distributions that are\r\n % particularly narrow. Calculate fractional 'width' of the frequencies\r\n % present by taking the sum of the filter response amplitudes and dividing\r\n % by the maximum amplitude at each point on the image.\r\n\r\n width = sumAn_ThisOrient ./ (maxAn + epsilon) / nscale;\r\n\r\n % Now calculate the sigmoidal weighting function for this orientation.\r\n\r\n weight = 1.0 ./ (1 + exp( (cutOff - width)*g));\r\n\r\n % Apply weighting to energy and then calculate phase congruency\r\n\r\n PC{o} = weight.*Energy./sumAn_ThisOrient; % Phase congruency for this orientation\r\n featType{o} = E+i*O;\r\n\r\n % Build up covariance data for every point\r\n covx = PC{o}*cos(angl);\r\n covy = PC{o}*sin(angl);\r\n covx2 = covx2 + covx.^2;\r\n covy2 = covy2 + covy.^2;\r\n covxy = covxy + covx.*covy;\r\n\r\nend % For each orientation\r\n\r\nfprintf(' \\r');\r\n\r\n% Edge and Corner calculations\r\n\r\n% The following is optimised code to calculate principal vector\r\n% of the phase congruency covariance data and to calculate\r\n% the minimumum and maximum moments - these correspond to\r\n% the singular values.\r\n\r\n% First normalise covariance values by the number of orientations/2\r\n\r\ncovx2 = covx2/(norient/2);\r\ncovy2 = covy2/(norient/2);\r\ncovxy = 4*covxy/norient; % This gives us 2*covxy/(norient/2)\r\n\r\ndenom = sqrt(covxy.^2 + (covx2-covy2).^2)+epsilon;\r\nsin2theta = covxy./denom;\r\ncos2theta = (covx2-covy2)./denom;\r\nor = atan2(sin2theta,cos2theta)/2; % Orientation perpendicular to edge.\r\nor = round(or*180/pi); % Return result rounded to integer\r\n % degrees.\r\nneg = or < 0;\r\nor = ~neg.*or + neg.*(or+180); % Adjust range from -90 to 90\r\n % to 0 to 180.\r\n\r\nM = (covy2+covx2 + denom)/2; % Maximum moment\r\nm = (covy2+covx2 - denom)/2; % ... and minimum moment\r\n\r\n\r\n\r\n\r\n%------------------------------------------------------------------\r\n% CHECKARGS\r\n%\r\n% Function to process the arguments that have been supplied, assign\r\n% default values as needed and perform basic checks.\r\n\r\nfunction [im, nscale, norient, minWaveLength, mult, sigmaOnf, ...\r\n dThetaOnSigma,k, cutOff, g] = checkargs(arg);\r\n\r\n nargs = length(arg);\r\n \r\n if nargs < 1\r\n error('No image supplied as an argument');\r\n end\r\n \r\n % Set up default values for all arguments and then overwrite them\r\n % with with any new values that may be supplied\r\n im = [];\r\n nscale = 4; % Number of wavelet scales.\r\n norient = 6; % Number of filter orientations.\r\n minWaveLength = 3; % Wavelength of smallest scale filter.\r\n mult = 2.1; % Scaling factor between successive filters.\r\n sigmaOnf = 0.55; % Ratio of the standard deviation of the\r\n % Gaussian describing the log Gabor filter's\r\n % transfer function in the frequency domain\r\n % to the filter center frequency.\r\n dThetaOnSigma = 1.5; % Ratio of angular interval between filter orientations\r\n % and the standard deviation of the angular Gaussian\r\n % function used to construct filters in the\r\n % freq. plane.\r\n k = 2.0; % No of standard deviations of the noise\r\n % energy beyond the mean at which we set the\r\n % noise threshold point.\r\n cutOff = 0.5; % The fractional measure of frequency spread\r\n % below which phase congruency values get penalized.\r\n g = 10; % Controls the sharpness of the transition in\r\n % the sigmoid function used to weight phase\r\n % congruency for frequency spread.\r\n \r\n % Allowed argument reading states\r\n allnumeric = 1; % Numeric argument values in predefined order\r\n keywordvalue = 2; % Arguments in the form of string keyword\r\n % followed by numeric value\r\n readstate = allnumeric; % Start in the allnumeric state\r\n \r\n if readstate == allnumeric\r\n for n = 1:nargs\r\n if isa(arg{n},'char')\r\n readstate = keywordvalue;\r\n break;\r\n else\r\n if n == 1, im = arg{n};\r\n elseif n == 2, nscale = arg{n};\r\n elseif n == 3, norient = arg{n};\r\n elseif n == 4, minWaveLength = arg{n};\r\n elseif n == 5, mult = arg{n};\r\n elseif n == 6, sigmaOnf = arg{n};\r\n elseif n == 7, dThetaOnSigma = arg{n};\r\n elseif n == 8, k = arg{n};\r\n elseif n == 9, cutOff = arg{n};\r\n elseif n == 10,g = arg{n};\r\n end\r\n end\r\n end\r\n end\r\n\r\n % Code to handle parameter name - value pairs\r\n if readstate == keywordvalue\r\n while n < nargs\r\n \r\n if ~isa(arg{n},'char') || ~isa(arg{n+1}, 'double')\r\n error('There should be a parameter name - value pair');\r\n end\r\n \r\n if strncmpi(arg{n},'im' ,2), im = arg{n+1};\r\n elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1};\r\n elseif strncmpi(arg{n},'norient' ,2), norient = arg{n+1};\r\n elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1};\r\n elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1};\r\n elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1};\r\n elseif strncmpi(arg{n},'dThetaOnSigma',2), dThetaOnSigma = arg{n+1};\r\n elseif strncmpi(arg{n},'k' ,1), k = arg{n+1};\r\n elseif strncmpi(arg{n},'cutOff' ,2), cutOff = arg{n+1};\r\n elseif strncmpi(arg{n},'g' ,1), g = arg{n+1};\r\n else error('Unrecognised parameter name');\r\n end\r\n\r\n n = n+2;\r\n if n == nargs\r\n error('Unmatched parameter name - value pair');\r\n end\r\n \r\n end\r\n end\r\n \r\n if isempty(im)\r\n error('No image argument supplied');\r\n end\r\n\r\n if ~isa(im, 'double')\r\n im = double(im);\r\n end\r\n \r\n if nscale < 1\r\n error('nscale must be an integer >= 1');\r\n end\r\n \r\n if norient < 1\r\n error('norient must be an integer >= 1');\r\n end\r\n\r\n if minWaveLength < 2\r\n error('It makes little sense to have a wavelength < 2');\r\n end\r\n\r\n if cutOff < 0 || cutOff > 1\r\n error('Cut off value must be between 0 and 1');\r\n end\r\n\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "phasecong3.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/phasecong3.m", "size": 26465, "source_encoding": "utf_8", "md5": "0c014f3a3af8bd7658da095b5c402b61", "text": "% PHASECONG3 - Computes edge and corner phase congruency in an image.\r\n%\r\n% This function calculates the PC_2 measure of phase congruency. \r\n% This function supersedes PHASECONG2 and PHASECONG being faster and requires\r\n% less memory\r\n%\r\n% There are potentially many arguments, here is the full usage:\r\n%\r\n% [M m or ft pc EO, T] = phasecong3(im, nscale, norient, minWaveLength, ...\r\n% mult, sigmaOnf, k, cutOff, g, noiseMethod)\r\n%\r\n% However, apart from the image, all parameters have defaults and the\r\n% usage can be as simple as:\r\n%\r\n% M = phasecong3(im);\r\n% \r\n% Arguments:\r\n% Default values Description\r\n%\r\n% nscale 4 - Number of wavelet scales, try values 3-6\r\n% norient 6 - Number of filter orientations.\r\n% minWaveLength 3 - Wavelength of smallest scale filter.\r\n% mult 2.1 - Scaling factor between successive filters.\r\n% sigmaOnf 0.55 - Ratio of the standard deviation of the Gaussian \r\n% describing the log Gabor filter's transfer function \r\n% in the frequency domain to the filter center frequency.\r\n% k 2.0 - No of standard deviations of the noise energy beyond\r\n% the mean at which we set the noise threshold point.\r\n% You may want to vary this up to a value of 10 or\r\n% 20 for noisy images \r\n% cutOff 0.5 - The fractional measure of frequency spread\r\n% below which phase congruency values get penalized.\r\n% g 10 - Controls the sharpness of the transition in\r\n% the sigmoid function used to weight phase\r\n% congruency for frequency spread. \r\n% noiseMethod -1 - Parameter specifies method used to determine\r\n% noise statistics. \r\n% -1 use median of smallest scale filter responses\r\n% -2 use mode of smallest scale filter responses\r\n% 0+ use noiseMethod value as the fixed noise threshold \r\n%\r\n% Returned values:\r\n% M - Maximum moment of phase congruency covariance.\r\n% This is used as a indicator of edge strength.\r\n% m - Minimum moment of phase congruency covariance.\r\n% This is used as a indicator of corner strength.\r\n% or - Orientation image in integer degrees 0-180,\r\n% positive anticlockwise.\r\n% 0 corresponds to a vertical edge, 90 is horizontal.\r\n% ft - Local weighted mean phase angle at every point in the\r\n% image. A value of pi/2 corresponds to a bright line, 0\r\n% corresponds to a step and -pi/2 is a dark line.\r\n% pc - Cell array of phase congruency images (values between 0 and 1) \r\n% for each orientation\r\n% EO - A 2D cell array of complex valued convolution result\r\n% T - Calculated noise threshold (can be useful for\r\n% diagnosing noise characteristics of images). Once you know\r\n% this you can then specify fixed thresholds and save some\r\n% computation time.\r\n%\r\n% EO{s,o} = convolution result for scale s and orientation o. The real part\r\n% is the result of convolving with the even symmetric filter, the imaginary\r\n% part is the result from convolution with the odd symmetric filter.\r\n%\r\n% Hence:\r\n% abs(EO{s,o}) returns the magnitude of the convolution over the\r\n% image at scale s and orientation o.\r\n% angle(EO{s,o}) returns the phase angles.\r\n% \r\n% Notes on specifying parameters: \r\n%\r\n% The parameters can be specified as a full list eg.\r\n% >> [M m or ft pc EO] = phasecong3(im, 5, 6, 3, 2.5, 0.55, 2.0, 0.4, 10);\r\n%\r\n% or as a partial list with unspecified parameters taking on default values\r\n% >> [M m or ft pc EO] = phasecong3(im, 5, 6, 3);\r\n%\r\n% or as a partial list of parameters followed by some parameters specified via a\r\n% keyword-value pair, remaining parameters are set to defaults, for example:\r\n% >> [M m or ft pc EO] = phasecong3(im, 5, 6, 3, 'cutOff', 0.3, 'k', 2.5);\r\n% \r\n% The convolutions are done via the FFT. Many of the parameters relate to the\r\n% specification of the filters in the frequency plane. The values do not seem\r\n% to be very critical and the defaults are usually fine. You may want to\r\n% experiment with the values of 'nscales' and 'k', the noise compensation factor.\r\n%\r\n% Notes on filter settings to obtain even coverage of the spectrum\r\n% sigmaOnf .85 mult 1.3\r\n% sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave)\r\n% sigmaOnf .65 mult 2.1 \r\n% sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves)\r\n%\r\n% See Also: PHASECONG, PHASECONG2, PHASESYM, GABORCONVOLVE, PLOTGABORFILTERS\r\n\r\n% References:\r\n%\r\n% Peter Kovesi, \"Image Features From Phase Congruency\". Videre: A\r\n% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,\r\n% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html\r\n%\r\n% Peter Kovesi, \"Phase Congruency Detects Corners and\r\n% Edges\". Proceedings DICTA 2003, Sydney Dec 10-12\r\n\r\n% April 1996 Original Version written \r\n% August 1998 Noise compensation corrected. \r\n% October 1998 Noise compensation corrected. - Again!!!\r\n% September 1999 Modified to operate on non-square images of arbitrary size. \r\n% May 2001 Modified to return feature type image. \r\n% July 2003 Altered to calculate 'corner' points. \r\n% October 2003 Speed improvements and refinements. \r\n% July 2005 Better argument handling, changed order of return values\r\n% August 2005 Made Octave compatible\r\n% May 2006 Bug in checkargs fixed\r\n% Jan 2007 Bug in setting radius to 0 for odd sized images fixed.\r\n% April 2009 Scaling of covariance values fixed. (Negligible change to results) \r\n% May 2009 Noise compensation simplified reducing memory and\r\n% computation overhead. Spread function changed to a cosine,\r\n% eliminating parameter dThetaOnSigma and ensuring even\r\n% angular coverage. Frequency width measure slightly\r\n% improved.\r\n% November 2010 Cosine angular spread function corrected (it was 2x as wide\r\n% as it should have been)\r\n\r\n% Copyright (c) 1996-2010 Peter Kovesi\r\n% Centre for Exploration Targeting\r\n% The University of Western Australia\r\n% peter.kovesi at uwa edu au\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in \r\n% all copies or substantial portions of the Software.\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n\r\nfunction [M, m, or, featType, PC, EO, T, pcSum] = phasecong3(varargin)\r\n \r\n% Get arguments and/or default values \r\n [im, nscale, norient, minWaveLength, mult, sigmaOnf, ...\r\n k, cutOff, g, noiseMethod] = checkargs(varargin(:)); \r\n\r\n epsilon = .0001; % Used to prevent division by zero.\r\n [rows,cols] = size(im);\r\n imagefft = fft2(im); % Fourier transform of image\r\n\r\n zero = zeros(rows,cols);\r\n EO = cell(nscale, norient); % Array of convolution results. \r\n PC = cell(norient,1);\r\n covx2 = zero; % Matrices for covariance data\r\n covy2 = zero;\r\n covxy = zero;\r\n\r\n EnergyV = zeros(rows,cols,3); % Matrix for accumulating total energy\r\n % vector, used for feature orientation\r\n % and type calculation\r\n\r\n pcSum = zeros(rows,cols); \r\n % Pre-compute some stuff to speed up filter construction\r\n \r\n % Set up X and Y matrices with ranges normalised to +/- 0.5\r\n % The following code adjusts things appropriately for odd and even values\r\n % of rows and columns.\r\n if mod(cols,2)\r\n xrange = [-(cols-1)/2:(cols-1)/2]/(cols-1);\r\n else\r\n xrange = [-cols/2:(cols/2-1)]/cols; \r\n end\r\n \r\n if mod(rows,2)\r\n yrange = [-(rows-1)/2:(rows-1)/2]/(rows-1);\r\n else\r\n yrange = [-rows/2:(rows/2-1)]/rows; \r\n end\r\n \r\n [x,y] = meshgrid(xrange, yrange);\r\n \r\n radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre.\r\n theta = atan2(-y,x); % Matrix values contain polar angle.\r\n % (note -ve y is used to give +ve\r\n % anti-clockwise angles)\r\n \r\n radius = ifftshift(radius); % Quadrant shift radius and theta so that filters\r\n theta = ifftshift(theta); % are constructed with 0 frequency at the corners.\r\n radius(1,1) = 1; % Get rid of the 0 radius value at the 0\r\n % frequency point (now at top-left corner)\r\n % so that taking the log of the radius will \r\n % not cause trouble.\r\n sintheta = sin(theta);\r\n costheta = cos(theta);\r\n clear x; clear y; clear theta; % save a little memory\r\n \r\n % Filters are constructed in terms of two components.\r\n % 1) The radial component, which controls the frequency band that the filter\r\n % responds to\r\n % 2) The angular component, which controls the orientation that the filter\r\n % responds to.\r\n % The two components are multiplied together to construct the overall filter.\r\n \r\n % Construct the radial filter components...\r\n % First construct a low-pass filter that is as large as possible, yet falls\r\n % away to zero at the boundaries. All log Gabor filters are multiplied by\r\n % this to ensure no extra frequencies at the 'corners' of the FFT are\r\n % incorporated as this seems to upset the normalisation process when\r\n % calculating phase congrunecy.\r\n lp = lowpassfilter([rows,cols],.45,15); % Radius .45, 'sharpness' 15\r\n\r\n logGabor = cell(1,nscale);\r\n\r\n for s = 1:nscale\r\n wavelength = minWaveLength*mult^(s-1);\r\n fo = 1.0/wavelength; % Centre frequency of filter.\r\n logGabor{s} = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); \r\n logGabor{s} = logGabor{s}.*lp; % Apply low-pass filter\r\n logGabor{s}(1,1) = 0; % Set the value at the 0 frequency point of the filter\r\n % back to zero (undo the radius fudge).\r\n end\r\n \r\n %% The main loop...\r\n for o = 1:norient % For each orientation...\r\n % Construct the angular filter spread function\r\n angl = (o-1)*pi/norient; % Filter angle.\r\n % For each point in the filter matrix calculate the angular distance from\r\n % the specified filter orientation. To overcome the angular wrap-around\r\n % problem sine difference and cosine difference values are first computed\r\n % and then the atan2 function is used to determine angular distance.\r\n ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.\r\n dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.\r\n dtheta = abs(atan2(ds,dc)); % Absolute angular distance.\r\n % Scale theta so that cosine spread function has the right wavelength and clamp to pi \r\n dtheta = min(dtheta*norient/2,pi);\r\n % The spread function is cos(dtheta) between -pi and pi. We add 1,\r\n % and then divide by 2 so that the value ranges 0-1\r\n spread = (cos(dtheta)+1)/2; \r\n \r\n sumE_ThisOrient = zero; % Initialize accumulator matrices.\r\n sumO_ThisOrient = zero; \r\n sumAn_ThisOrient = zero; \r\n Energy = zero; \r\n\r\n for s = 1:nscale, % For each scale...\r\n filter = logGabor{s} .* spread; % Multiply radial and angular\r\n % components to get the filter. \r\n \r\n % Convolve image with even and odd filters returning the result in EO\r\n EO{s,o} = ifft2(imagefft .* filter); \r\n\r\n An = abs(EO{s,o}); % Amplitude of even & odd filter response.\r\n sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses.\r\n sumE_ThisOrient = sumE_ThisOrient + real(EO{s,o}); % Sum of even filter convolution results.\r\n sumO_ThisOrient = sumO_ThisOrient + imag(EO{s,o}); % Sum of odd filter convolution results.\r\n \r\n % At the smallest scale estimate noise characteristics from the\r\n % distribution of the filter amplitude responses stored in sumAn. \r\n % tau is the Rayleigh parameter that is used to describe the\r\n % distribution.\r\n if s == 1 \r\n if noiseMethod == -1 % Use median to estimate noise statistics\r\n tau = median(sumAn_ThisOrient(:))/sqrt(log(4)); \r\n elseif noiseMethod == -2 % Use mode to estimate noise statistics\r\n tau = rayleighmode(sumAn_ThisOrient(:));\r\n end\r\n maxAn = An;\r\n else\r\n % Record maximum amplitude of components across scales. This is needed\r\n % to determine the frequency spread weighting.\r\n maxAn = max(maxAn,An); \r\n end\r\n end % ... and process the next scale\r\n\r\n % Accumulate total 3D energy vector data, this will be used to\r\n % determine overall feature orientation and feature phase/type\r\n EnergyV(:,:,1) = EnergyV(:,:,1) + sumE_ThisOrient;\r\n EnergyV(:,:,2) = EnergyV(:,:,2) + cos(angl)*sumO_ThisOrient;\r\n EnergyV(:,:,3) = EnergyV(:,:,3) + sin(angl)*sumO_ThisOrient;\r\n \r\n % Get weighted mean filter response vector, this gives the weighted mean\r\n % phase angle.\r\n XEnergy = sqrt(sumE_ThisOrient.^2 + sumO_ThisOrient.^2) + epsilon; \r\n MeanE = sumE_ThisOrient ./ XEnergy; \r\n MeanO = sumO_ThisOrient ./ XEnergy; \r\n \r\n % Now calculate An(cos(phase_deviation) - | sin(phase_deviation)) | by\r\n % using dot and cross products between the weighted mean filter response\r\n % vector and the individual filter response vectors at each scale. This\r\n % quantity is phase congruency multiplied by An, which we call energy.\r\n\r\n for s = 1:nscale, \r\n E = real(EO{s,o}); O = imag(EO{s,o}); % Extract even and odd\r\n % convolution results.\r\n Energy = Energy + E.*MeanE + O.*MeanO - abs(E.*MeanO - O.*MeanE);\r\n end\r\n\r\n %% Automatically determine noise threshold\r\n %\r\n % Assuming the noise is Gaussian the response of the filters to noise will\r\n % form Rayleigh distribution. We use the filter responses at the smallest\r\n % scale as a guide to the underlying noise level because the smallest scale\r\n % filters spend most of their time responding to noise, and only\r\n % occasionally responding to features. Either the median, or the mode, of\r\n % the distribution of filter responses can be used as a robust statistic to\r\n % estimate the distribution mean and standard deviation as these are related\r\n % to the median or mode by fixed constants. The response of the larger\r\n % scale filters to noise can then be estimated from the smallest scale\r\n % filter response according to their relative bandwidths.\r\n %\r\n % This code assumes that the expected reponse to noise on the phase congruency\r\n % calculation is simply the sum of the expected noise responses of each of\r\n % the filters. This is a simplistic overestimate, however these two\r\n % quantities should be related by some constant that will depend on the\r\n % filter bank being used. Appropriate tuning of the parameter 'k' will\r\n % allow you to produce the desired output. \r\n \r\n if noiseMethod >= 0 % We are using a fixed noise threshold\r\n T = noiseMethod; % use supplied noiseMethod value as the threshold\r\n else\r\n % Estimate the effect of noise on the sum of the filter responses as\r\n % the sum of estimated individual responses (this is a simplistic\r\n % overestimate). As the estimated noise response at succesive scales\r\n % is scaled inversely proportional to bandwidth we have a simple\r\n % geometric sum.\r\n totalTau = tau * (1 - (1/mult)^nscale)/(1-(1/mult));\r\n \r\n % Calculate mean and std dev from tau using fixed relationship\r\n % between these parameters and tau. See\r\n % http://mathworld.wolfram.com/RayleighDistribution.html\r\n EstNoiseEnergyMean = totalTau*sqrt(pi/2); % Expected mean and std\r\n EstNoiseEnergySigma = totalTau*sqrt((4-pi)/2); % values of noise energy\r\n \r\n T = EstNoiseEnergyMean + k*EstNoiseEnergySigma; % Noise threshold\r\n end\r\n \r\n % Apply noise threshold, this is effectively wavelet denoising via\r\n % soft thresholding.\r\n Energy = max(Energy - T, 0); \r\n \r\n % Form weighting that penalizes frequency distributions that are\r\n % particularly narrow. Calculate fractional 'width' of the frequencies\r\n % present by taking the sum of the filter response amplitudes and dividing\r\n % by the maximum amplitude at each point on the image. If\r\n % there is only one non-zero component width takes on a value of 0, if\r\n % all components are equal width is 1.\r\n width = (sumAn_ThisOrient./(maxAn + epsilon) - 1) / (nscale-1); \r\n\r\n % Now calculate the sigmoidal weighting function for this orientation.\r\n weight = 1.0 ./ (1 + exp( (cutOff - width)*g)); \r\n\r\n % Apply weighting to energy and then calculate phase congruency\r\n PC{o} = weight.*Energy./sumAn_ThisOrient; % Phase congruency for this orientatio\r\n\r\n pcSum = pcSum+PC{o};\r\n \r\n % Build up covariance data for every point\r\n covx = PC{o}*cos(angl);\r\n covy = PC{o}*sin(angl);\r\n covx2 = covx2 + covx.^2;\r\n covy2 = covy2 + covy.^2;\r\n covxy = covxy + covx.*covy;\r\n \r\n end % For each orientation\r\n\r\n %% Edge and Corner calculations\r\n % The following is optimised code to calculate principal vector\r\n % of the phase congruency covariance data and to calculate\r\n % the minimumum and maximum moments - these correspond to\r\n % the singular values.\r\n \r\n % First normalise covariance values by the number of orientations/2\r\n covx2 = covx2/(norient/2);\r\n covy2 = covy2/(norient/2);\r\n covxy = 4*covxy/norient; % This gives us 2*covxy/(norient/2)\r\n denom = sqrt(covxy.^2 + (covx2-covy2).^2)+epsilon;\r\n M = (covy2+covx2 + denom)/2; % Maximum moment\r\n m = (covy2+covx2 - denom)/2; % ... and minimum moment\r\n \r\n % Orientation and feature phase/type computation\r\n or = atan2(EnergyV(:,:,3), EnergyV(:,:,2));\r\n or(or<0) = or(or<0)+pi; % Wrap angles -pi..0 to 0..pi\r\n or = round(or*180/pi); % Orientation in degrees between 0 and 180\r\n \r\n OddV = sqrt(EnergyV(:,:,2).^2 + EnergyV(:,:,3).^2);\r\n featType = atan2(EnergyV(:,:,1), OddV); % Feature phase pi/2 <-> white line,\r\n % 0 <-> step, -pi/2 <-> black line\r\n\r\n \r\n%%------------------------------------------------------------------\r\n% CHECKARGS\r\n%\r\n% Function to process the arguments that have been supplied, assign\r\n% default values as needed and perform basic checks.\r\n \r\nfunction [im, nscale, norient, minWaveLength, mult, sigmaOnf, ...\r\n k, cutOff, g, noiseMethod] = checkargs(arg)\r\n\r\n nargs = length(arg);\r\n \r\n if nargs < 1\r\n error('No image supplied as an argument');\r\n end \r\n \r\n % Set up default values for all arguments and then overwrite them\r\n % with with any new values that may be supplied\r\n im = [];\r\n nscale = 4; % Number of wavelet scales. \r\n norient = 6; % Number of filter orientations.\r\n minWaveLength = 3; % Wavelength of smallest scale filter. \r\n mult = 2.1; % Scaling factor between successive filters. \r\n sigmaOnf = 0.55; % Ratio of the standard deviation of the\r\n % Gaussian describing the log Gabor filter's\r\n % transfer function in the frequency domain\r\n % to the filter center frequency. \r\n k = 2.0; % No of standard deviations of the noise\r\n % energy beyond the mean at which we set the\r\n % noise threshold point. \r\n cutOff = 0.5; % The fractional measure of frequency spread\r\n % below which phase congruency values get penalized.\r\n g = 10; % Controls the sharpness of the transition in\r\n % the sigmoid function used to weight phase\r\n % congruency for frequency spread. \r\n noiseMethod = -1; % Choice of noise compensation method. \r\n \r\n % Allowed argument reading states\r\n allnumeric = 1; % Numeric argument values in predefined order\r\n keywordvalue = 2; % Arguments in the form of string keyword\r\n % followed by numeric value\r\n readstate = allnumeric; % Start in the allnumeric state\r\n \r\n if readstate == allnumeric\r\n for n = 1:nargs\r\n if isa(arg{n},'char')\r\n readstate = keywordvalue;\r\n break;\r\n else\r\n if n == 1, im = arg{n}; \r\n elseif n == 2, nscale = arg{n}; \r\n elseif n == 3, norient = arg{n};\r\n elseif n == 4, minWaveLength = arg{n};\r\n elseif n == 5, mult = arg{n};\r\n elseif n == 6, sigmaOnf = arg{n};\r\n elseif n == 7, k = arg{n};\r\n elseif n == 8, cutOff = arg{n};\r\n elseif n == 9, g = arg{n};\r\n elseif n == 10,noiseMethod = arg{n};\r\n end\r\n end\r\n end\r\n end\r\n\r\n % Code to handle parameter name - value pairs\r\n if readstate == keywordvalue\r\n while n < nargs\r\n \r\n if ~isa(arg{n},'char') || ~isa(arg{n+1}, 'double')\r\n error('There should be a parameter name - value pair');\r\n end\r\n \r\n if strncmpi(arg{n},'im' ,2), im = arg{n+1};\r\n elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1};\r\n elseif strncmpi(arg{n},'norient' ,4), norient = arg{n+1};\r\n elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1};\r\n elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1};\r\n elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1};\r\n elseif strncmpi(arg{n},'k' ,1), k = arg{n+1};\r\n elseif strncmpi(arg{n},'cutOff' ,2), cutOff = arg{n+1};\r\n elseif strncmpi(arg{n},'g' ,1), g = arg{n+1}; \r\n elseif strncmpi(arg{n},'noiseMethod' ,4), noiseMethod = arg{n+1}; \r\n else error('Unrecognised parameter name');\r\n end\r\n\r\n n = n+2;\r\n if n == nargs\r\n error('Unmatched parameter name - value pair');\r\n end\r\n \r\n end\r\n end\r\n \r\n if isempty(im)\r\n error('No image argument supplied');\r\n end\r\n\r\n if ndims(im) == 3\r\n warning('Colour image supplied: converting image to greyscale...')\r\n im = double(rgb2gray(im));\r\n end\r\n \r\n if ~isa(im, 'double')\r\n im = double(im);\r\n end\r\n\r\n if nscale < 1\r\n error('nscale must be an integer >= 1');\r\n end\r\n \r\n if norient < 1 \r\n error('norient must be an integer >= 1');\r\n end \r\n\r\n if minWaveLength < 2\r\n error('It makes little sense to have a wavelength < 2');\r\n end \r\n\r\n if cutOff < 0 || cutOff > 1\r\n error('Cut off value must be between 0 and 1');\r\n end\r\n \r\n%%-------------------------------------------------------------------------\r\n% RAYLEIGHMODE\r\n%\r\n% Computes mode of a vector/matrix of data that is assumed to come from a\r\n% Rayleigh distribution.\r\n%\r\n% Usage: rmode = rayleighmode(data, nbins)\r\n%\r\n% Arguments: data - data assumed to come from a Rayleigh distribution\r\n% nbins - Optional number of bins to use when forming histogram\r\n% of the data to determine the mode.\r\n%\r\n% Mode is computed by forming a histogram of the data over 50 bins and then\r\n% finding the maximum value in the histogram. Mean and standard deviation\r\n% can then be calculated from the mode as they are related by fixed\r\n% constants.\r\n%\r\n% mean = mode * sqrt(pi/2)\r\n% std dev = mode * sqrt((4-pi)/2)\r\n% \r\n% See\r\n% http://mathworld.wolfram.com/RayleighDistribution.html\r\n% http://en.wikipedia.org/wiki/Rayleigh_distribution\r\n%\r\n\r\nfunction rmode = rayleighmode(data, nbins)\r\n \r\n if nargin == 1\r\n nbins = 50; % Default number of histogram bins to use\r\n end\r\n\r\n mx = max(data(:));\r\n edges = 0:mx/nbins:mx;\r\n n = histc(data(:),edges); \r\n [dum,ind] = max(n); % Find maximum and index of maximum in histogram \r\n\r\n rmode = (edges(ind)+edges(ind+1))/2;\r\n\r\n\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "noisecomp.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/noisecomp.m", "size": 7750, "source_encoding": "utf_8", "md5": "9676f0608db5db81178e20d70f317783", "text": "% NOISECOMP - Function for denoising an image\n%\n% function cleanimage = noisecomp(image, k, nscale, mult, norient, softness)\n%\n% Parameters:\n% k - No of standard deviations of noise to reject 2-3\n% nscale - No of filter scales to use (5-7) - the more scales used\n% the more low frequencies are covered\n% mult - multiplying factor between scales (2.5-3)\n% norient - No of orientations to use (6)\n% softness - degree of soft thresholding (0-hard 1-soft)\n%\n% For maximum processing speed the input image should have a size that\n% is a power of 2. \n%\n% The convolutions are done via the FFT. Many of the parameters relate \n% to the specification of the filters in the frequency plane. \n% The parameters are set within the file rather than being specified as \n% arguments because they rarely need to be changed - nor are they very \n% critical.\n%\n% Reference:\n% Peter Kovesi, \"Phase Preserving Denoising of Images\". \n% The Australian Pattern Recognition Society Conference: DICTA'99. \n% December 1999. Perth WA. pp 212-217\n% http://www.cs.uwa.edu.au/pub/robvis/papers/pk/denoise.ps.gz. \n%\n\n% Copyright (c) 1998-2000 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 1998 - original version\n% May 1999 - \n% May 2000 - modified to allow arbitrary size images\n \n\nfunction cleanimage = noisecomp(image, k, nscale, mult, norient, softness)\n\n%nscale = 6; % Number of wavelet scales.\n%norient = 6; % Number of filter orientations.\nminWaveLength = 2; % Wavelength of smallest scale filter.\n%mult = 2; % Scaling factor between successive filters.\nsigmaOnf = 0.55; % Ratio of the standard deviation of the Gaussian \n % describing the log Gabor filter's transfer function \n % in the frequency domain to the filter center frequency.\ndThetaOnSigma = 1.; % Ratio of angular interval between filter orientations\n % and the standard deviation of the angular Gaussian\n % function used to construct filters in the freq. plane.\nepsilon = .00001;% Used to prevent division by zero.\n\n\nthetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the\n % angular Gaussian function used to\n % construct filters in the freq. plane.\n\nimagefft = fft2(image); % Fourier transform of image\n[rows,cols] = size(imagefft);\n\n% Create two matrices, x and y. All elements of x have a value equal to its \n% x coordinate relative to the centre, elements of y have values equal to \n% their y coordinate relative to the centre.\n\nx = ones(rows,1) * (-cols/2 : (cols/2 - 1))/(cols/2); \ny = (-rows/2 : (rows/2 - 1))' * ones(1,cols)/(rows/2);\n\nradius = sqrt(x.^2 + y.^2); % Matrix values contain normalised radius from centre.\nradius(round(rows/2+1),round(cols/2+1)) = 1; % Get rid of the 0 radius value in the middle so that\n % taking the log of the radius will not cause trouble.\ntheta = atan2(-y,x); % Matrix values contain polar angle.\n % (note -ve y is used to give +ve anti-clockwise angles)\nclear x; clear y; % save a little memory\nsig = [];\nestMeanEn = [];\naMean = [];\naSig = [];\n\ntotalEnergy = zeros(rows,cols); % response at each orientation.\n\nfor o = 1:norient, % For each orientation.\n disp(['Processing orientation ' num2str(o)]);\n angl = (o-1)*pi/norient; % Calculate filter angle.\n wavelength = minWaveLength; % Initialize filter wavelength.\n\n % Pre-compute filter data specific to this orientation\n % For each point in the filter matrix calculate the angular distance from the\n % specified filter orientation. To overcome the angular wrap-around problem\n % sine difference and cosine difference values are first computed and then\n % the atan2 function is used to determine angular distance.\n\n ds = sin(theta) * cos(angl) - cos(theta) * sin(angl); % Difference in sine.\n dc = cos(theta) * cos(angl) + sin(theta) * sin(angl); % Difference in cosine.\n dtheta = abs(atan2(ds,dc)); % Absolute angular distance.\n spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the angular filter component.\n\n for s = 1:nscale, % For each scale.\n\n % Construct the filter - first calculate the radial filter component.\n fo = 1.0/wavelength; % Centre frequency of filter.\n rfo = fo/0.5; % Normalised radius from centre of frequency plane \n % corresponding to fo.\n logGabor = exp((-(log(radius/rfo)).^2) / (2 * log(sigmaOnf)^2)); \n logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set the value at the center of the filter\n % back to zero (undo the radius fudge).\n\n filter = logGabor .* spread; % Multiply by the angular spread to get the filter.\n filter = fftshift(filter); % Swap quadrants to move zero frequency \n % to the corners.\n\n % Convolve image with even an odd filters returning the result in EO\n EOfft = imagefft .* filter; % Do the convolution.\n EO = ifft2(EOfft); % Back transform.\n aEO = abs(EO);\n\n if s == 1\n % Estimate the mean and variance in the amplitude response of the smallest scale \n % filter pair at this orientation. \n % If the noise is Gaussian the amplitude response will have a Rayleigh distribution.\n % We calculate the median amplitude response as this is a robust statistic. \n % From this we estimate the mean and variance of the Rayleigh distribution\n\n medianEn = median(reshape(aEO,1,rows*cols));\n meanEn = medianEn*.5*sqrt(-pi/log(0.5));\n\n RayVar = (4-pi)*(meanEn.^2)/pi;\n RayMean = meanEn;\n\n estMeanEn = [estMeanEn meanEn];\n sig = [sig sqrt(RayVar)];\n\n %% May want to look at actual distribution on special images\n % hist(reshape(aEO,1,rows*cols),100);\n % pause(1);\n end\n\n % Now apply soft thresholding\n\n T = (RayMean + k*sqrt(RayVar))/(mult^(s-1)); % Noise effect inversely proportional to\n % bandwidth/centre frequency.\n\n validEO = aEO > T; % Find where magnitude of energy exceeds noise.\n V = softness*T*EO./(aEO + epsilon); % Calculate array of noise vectors to subtract.\n V = ~validEO.*EO + validEO.*V; % Adjust noise vectors so that EO values will \n % not be negated\n EO = EO-V; % Subtract noise vector.\n\n totalEnergy = totalEnergy + EO;\n wavelength = wavelength * mult; % Wavelength of next filter\n end \nend % For each orientation\ndisp('Estimated mean noise in each orientation')\ndisp(estMeanEn);\n\ncleanimage = real(totalEnergy);\n%imagesc(cleanimage), title('denoised image'), axis image;\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "loggabor.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/loggabor.m", "size": 1707, "source_encoding": "utf_8", "md5": "c15d2b1f67996d38d0003a5309d2f76f", "text": "% LOGGABOR\n%\n% Plots 1D log-Gabor functions\n%\n\n% Author: Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk @ csse uwa edu au http://www.csse.uwa.edu.au/~pk \n\n\nfunction loggabor(nscale, wmin, mult, konwo)\n \n Npts = 2048;\n Nwaves = 1;\n \n wmax = 0.5;\n dw = wmax/(Npts-1);\n w = [0: dw: wmax]; \n \n wo = wmin/2;\n for s = 1:nscale\n\tw(1) = 1; % fudge\n\tGw{s} = exp( (-(log(w/wo)).^2) ./ (2*(log(konwo)).^2) );\n\tGw{s}(1) = 0; % undo fudge\n\t\n\t\n\n\tWave{s} = fftshift(ifft(Gw{s}));\n\twavelength = 1/wo;\n\tp = max(round(Npts/2 - Nwaves*wavelength),1);\n\tq = min(round(Npts/2 + Nwaves*wavelength),Npts);\n\tWave{s} = Wave{s}(p:q);\n\t\n\two = wo*mult;\n end\n \n w(1) = 0; % undo fudge \n \n lw = 2; % linewidth\n fs = 14; % font size\n figure(1), clf\n for s = 1:nscale\n\tsubplot(2,1,1), plot(w, Gw{s},'LineWidth',lw), \n\taxis([0 0.5 0 1.1]), hold on\n\tsubplot(2,1,2), semilogx(w, Gw{s},'LineWidth',lw), axis([0 0.5 0 1.1]), hold on\n end\n \n subplot(2,1,1), title('Log-Gabor Transfer Functions','FontSize',fs);\n xlabel('frequency','FontSize',fs)\n subplot(2,1,2), xlabel('log frequency','FontSize',fs)\n\n ymax = 1.05*max(abs(Wave{nscale}));\n\n figure(2), clf\n for s = 1:nscale \n\tsubplot(2,nscale,s), plot(real(Wave{s}),'LineWidth',lw), \n axis([0 length(Wave{s}) -ymax ymax]), axis off\n\tsubplot(2,nscale,s+nscale), plot(imag(Wave{s}),'LineWidth',lw),\n\taxis([0 length(Wave{s}) -ymax ymax]), axis off\n end\n \nsubplot(2,nscale,1), title('even symmetric wavelets','FontSize',fs);\nsubplot(2,nscale,nscale+1), title('odd symmetric wavelets','FontSize',fs);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "phasecongmono.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/phasecongmono.m", "size": 22519, "source_encoding": "utf_8", "md5": "5d0d160cd66ce1b8ed2bc3db2d332a8f", "text": "% PHASECONGMONO - phase congruency of an image using monogenic filters\n%\n% This code is considerably faster than PHASECONG3 but you may prefer the\n% output from PHASECONG3's oriented filters.\n%\n% There are potentially many arguments, here is the full usage:\n%\n% [PC or ft T] = ...\n% phasecongmono(im, nscale, minWaveLength, mult, ...\n% sigmaOnf, k, cutOff, g, deviationGain, noiseMethod)\n%\n% However, apart from the image, all parameters have defaults and the\n% usage can be as simple as:\n%\n% phaseCong = phasecongmono(im);\n% \n% Arguments:\n% Default values Description\n%\n% nscale 4 - Number of wavelet scales, try values 3-6\n% A lower value will reveal more fine scale\n% features. A larger value will highlight 'major'\n% features.\n% minWaveLength 3 - Wavelength of smallest scale filter.\n% mult 2.1 - Scaling factor between successive filters.\n% sigmaOnf 0.55 - Ratio of the standard deviation of the Gaussian \n% describing the log Gabor filter's transfer function \n% in the frequency domain to the filter center frequency.\n% k 3.0 - No of standard deviations of the noise energy beyond\n% the mean at which we set the noise threshold point.\n% You may want to vary this up to a value of 10 or\n% 20 for noisy images \n% cutOff 0.5 - The fractional measure of frequency spread\n% below which phase congruency values get penalized.\n% g 10 - Controls the sharpness of the transition in\n% the sigmoid function used to weight phase\n% congruency for frequency spread. \n% deviationGain 1.5 - Amplification to apply to the calculated phase\n% deviation result. Increasing this sharpens the\n% edge responses, but can also attenuate their\n% magnitude if the gain is too large. Sensible\n% values to use lie in the range 1-2.\n% noiseMethod -1 - Parameter specifies method used to determine\n% noise statistics. \n% -1 use median of smallest scale filter responses\n% -2 use mode of smallest scale filter responses\n% 0+ use noiseMethod value as the fixed noise threshold \n% A value of 0 will turn off all noise compensation.\n%\n% Returned values:\n% PC - Phase congruency indicating edge significance\n% or - Orientation image in integer degrees 0-180,\n% positive anticlockwise.\n% 0 corresponds to a vertical edge, 90 is horizontal.\n% ft - Local weighted mean phase angle at every point in the\n% image. A value of pi/2 corresponds to a bright line, 0\n% corresponds to a step and -pi/2 is a dark line.\n% T - Calculated noise threshold (can be useful for\n% diagnosing noise characteristics of images). Once you know\n% this you can then specify fixed thresholds and save some\n% computation time.\n%\n% Notes on specifying parameters: \n%\n% The parameters can be specified as a full list eg.\n% >> PC = phasecongmono(im, 5, 3, 2.5, 0.55, 2.0);\n%\n% or as a partial list with unspecified parameters taking on default values\n% >> PC = phasecongmono(im, 5, 3);\n%\n% or as a partial list of parameters followed by some parameters specified via a\n% keyword-value pair, remaining parameters are set to defaults, for example:\n% >> PC = phasecongmono(im, 5, 3, 'k', 2.5);\n% \n% The convolutions are done via the FFT. Many of the parameters relate to the\n% specification of the filters in the frequency plane. The values do not seem\n% to be very critical and the defaults are usually fine. You may want to\n% experiment with the values of 'nscales' and 'k', the noise compensation\n% factor.\n%\n% Typical sequence of operations to obtain an edge image:\n%\n% >> [PC, or] = phasecongmono(imread('lena.tif'));\n% >> nm = nonmaxsup(PC, or, 1.5); % nonmaxima suppression\n% >> bw = hysthresh(nm, 0.1, 0.3); % hysteresis thresholding 0.1 - 0.3\n% >> show(bw)\n%\n% Notes on filter settings to obtain even coverage of the spectrum\n% sigmaOnf .85 mult 1.3\n% sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave)\n% sigmaOnf .65 mult 2.1 \n% sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves)\n%\n% Note that better results are achieved using the large bandwidth filters. \n% I generally use a sigmaOnf value of 0.55 or even smaller.\n%\n% See Also: PHASECONG, PHASECONG3, PHASESYMMONO, GABORCONVOLVE,\n% PLOTGABORFILTERS, FILTERGRID\n\n% References:\n%\n% Peter Kovesi, \"Image Features From Phase Congruency\". Videre: A\n% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,\n% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html\n%\n% Michael Felsberg and Gerald Sommer, \"A New Extension of Linear Signal\n% Processing for Estimating Local Properties and Detecting Features\". DAGM\n% Symposium 2000, Kiel\n%\n% Michael Felsberg and Gerald Sommer. \"The Monogenic Signal\" IEEE\n% Transactions on Signal Processing, 49(12):3136-3144, December 2001\n%\n% Peter Kovesi, \"Phase Congruency Detects Corners and Edges\". Proceedings\n% DICTA 2003, Sydney Dec 10-12\n\n\n% August 2008 Initial version developed from phasesymmono and phasecong2\n% where local phase information is calculated via Monogenic\n% filters. Simplification of noise compensation to speedup\n% execution. Options to calculate noise statistics via median\n% or mode of smallest filter response. \n% April 2009 Return of T for 'instrumentation' of noise\n% detection/compensation. Option to use a fixed threshold.\n% Frequency width measure slightly improved.\n% June 2009 20% Speed improvement through calculating phase deviation via\n% acos() rather than computing cos(theta)-|sin(theta)| via dot\n% and cross products. Phase congruency is formed properly in\n% 2D rather than as multiple 1D computations as in\n% phasecong3. Also, much smaller memory footprint.\n% May 2013 Some tidying up, corrections to defualt parameters, changes\n% to reflect my latest thinking of the final phase congruency\n% calculation and addition of phase deviation gain parameter to\n% sharpen up the output. Use of periodic fft.\n\n% Copyright (c) 1996-2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction [PC, or, ft, T] = phasecongmono(varargin)\n\n % Get arguments and/or default values \n [im, nscale, minWaveLength, mult, sigmaOnf, k, ...\n noiseMethod, cutOff, g, deviationGain] = checkargs(varargin(:)); \n\n epsilon = .0001; % Used to prevent division by zero.\n\n [rows,cols] = size(im);\n IM = perfft2(im); % Periodic Fourier transform of image\n\n sumAn = zeros(rows,cols); % Matrix for accumulating filter response\n % amplitude values.\n sumf = zeros(rows,cols); \n sumh1 = zeros(rows,cols); \n sumh2 = zeros(rows,cols); \n\n % Generate grid data for constructing filters in the frequency domain \n [radius, u1, u2] = filtergrid(rows, cols); \n \n % Get rid of the 0 radius value in the middle (at top left corner after\n % fftshifting) so that taking the log of the radius, or dividing by the\n % radius, will not cause trouble.\n radius(1,1) = 1;\n \n % Construct the monogenic filters in the frequency domain. The two\n % filters would normally be constructed as follows\n % H1 = i*u1./radius; \n % H2 = i*u2./radius;\n % However the two filters can be packed together as a complex valued\n % matrix, one in the real part and one in the imaginary part. Do this by\n % multiplying H2 by i and then adding it to H1 (note the subtraction\n % because i*i = -1). When the convolution is performed via the fft the\n % real part of the result will correspond to the convolution with H1 and\n % the imaginary part with H2. This allows the two convolutions to be\n % done as one in the frequency domain, saving time and memory.\n H = (1i*u1 - u2)./radius;\n \n % The two monogenic filters H1 and H2 are not selective in terms of the\n % magnitudes of the frequencies. The code below generates bandpass\n % log-Gabor filters which are point-wise multiplied by IM to produce\n % different bandpass versions of the image before being convolved with H1\n % and H2\n \n % First construct a low-pass filter that is as large as possible, yet falls\n % away to zero at the boundaries. All filters are multiplied by\n % this to ensure no extra frequencies at the 'corners' of the FFT are\n % incorporated as this can upset the normalisation process when\n % calculating phase congruency\n lp = lowpassfilter([rows,cols],.45,15); % Radius .4, 'sharpness' 15\n\n for s = 1:nscale\n wavelength = minWaveLength*mult^(s-1);\n fo = 1.0/wavelength; % Centre frequency of filter.\n logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); \n logGabor = logGabor.*lp; % Apply low-pass filter\n logGabor(1,1) = 0; % Set the value at the 0 frequency point of the \n % filter back to zero (undo the radius fudge).\n\n IMF = IM.*logGabor; % Bandpassed image in the frequency domain.\n f = real(ifft2(IMF)); % Bandpassed image in spatial domain.\n\n h = ifft2(IMF.*H); % Bandpassed monogenic filtering, real part of h contains\n % convolution result with h1, imaginary part\n % contains convolution result with h2.\n h1 = real(h); \n h2 = imag(h); \n An = sqrt(f.^2 + h1.^2 + h2.^2); % Amplitude of this scale component.\n sumAn = sumAn + An; % Sum of component amplitudes over scale.\n sumf = sumf + f;\n sumh1 = sumh1 + h1;\n sumh2 = sumh2 + h2; \n \n % At the smallest scale estimate noise characteristics from the\n % distribution of the filter amplitude responses stored in sumAn. \n % tau is the Rayleigh parameter that is used to describe the\n % distribution.\n if s == 1 \n if noiseMethod == -1 % Use median to estimate noise statistics\n tau = median(sumAn(:))/sqrt(log(4));\n elseif noiseMethod == -2 % Use mode to estimate noise statistics\n tau = rayleighmode(sumAn(:));\n end\n maxAn = An;\n else\n % Record maximum amplitude of components across scales. This is needed\n % to determine the frequency spread weighting.\n maxAn = max(maxAn,An); \n end\n \n end % For each scale\n\n % Form weighting that penalizes frequency distributions that are\n % particularly narrow. Calculate fractional 'width' of the frequencies\n % present by taking the sum of the filter response amplitudes and dividing\n % by the maximum component amplitude at each point on the image. If\n % there is only one non-zero component width takes on a value of 0, if\n % all components are equal width is 1.\n width = (sumAn./(maxAn + epsilon) - 1) / (nscale-1); \n \n % Now calculate the sigmoidal weighting function.\n weight = 1.0 ./ (1 + exp( (cutOff - width)*g)); \n \n % Automatically determine noise threshold\n %\n % Assuming the noise is Gaussian the response of the filters to noise will\n % form Rayleigh distribution. We use the filter responses at the smallest\n % scale as a guide to the underlying noise level because the smallest scale\n % filters spend most of their time responding to noise, and only\n % occasionally responding to features. Either the median, or the mode, of\n % the distribution of filter responses can be used as a robust statistic to\n % estimate the distribution mean and standard deviation as these are related\n % to the median or mode by fixed constants. The response of the larger\n % scale filters to noise can then be estimated from the smallest scale\n % filter response according to their relative bandwidths.\n %\n % This code assumes that the expected reponse to noise on the phase\n % congruency calculation is simply the sum of the expected noise responses\n % of each of the filters. This is a simplistic overestimate, however these\n % two quantities should be related by some constant that will depend on the\n % filter bank being used. Appropriate tuning of the parameter 'k' will\n % allow you to produce the desired output. (though the value of k seems to\n % be not at all critical)\n \n if noiseMethod >= 0 % We are using a fixed noise threshold\n T = noiseMethod; % use supplied noiseMethod value as the threshold\n else\n % Estimate the effect of noise on the sum of the filter responses as\n % the sum of estimated individual responses (this is a simplistic\n % overestimate). As the estimated noise response at succesive scales\n % is scaled inversely proportional to bandwidth we have a simple\n % geometric sum.\n totalTau = tau * (1 - (1/mult)^nscale)/(1-(1/mult));\n \n % Calculate mean and std dev from tau using fixed relationship\n % between these parameters and tau. See\n % http://mathworld.wolfram.com/RayleighDistribution.html\n EstNoiseEnergyMean = totalTau*sqrt(pi/2); % Expected mean and std\n EstNoiseEnergySigma = totalTau*sqrt((4-pi)/2); % values of noise energy\n \n T = EstNoiseEnergyMean + k*EstNoiseEnergySigma; % Noise threshold\n end\n\n %------ Final computation of key quantities -------\n \n or = atan(-sumh2./sumh1); % Orientation - this varies +/- pi/2\n or(or<0) = or(or<0)+pi; % Add pi to -ve orientation value so that all\n % orientation values now range 0 - pi\n or = fix(or/pi*180); % Quantize to 0 - 180 degrees (for NONMAXSUP)\n \n ft = atan2(sumf,sqrt(sumh1.^2+sumh2.^2)); % Feature type - a phase angle\n % -pi/2 to pi/2.\n\n energy = sqrt(sumf.^2 + sumh1.^2 + sumh2.^2); % Overall energy\n\n % Compute phase congruency. The original measure, \n % PC = energy/sumAn \n % is proportional to the weighted cos(phasedeviation). This is not very\n % localised so this was modified to\n % PC = cos(phasedeviation) - |sin(phasedeviation)| \n % (Note this was actually calculated via dot and cross products.) This measure\n % approximates \n % PC = 1 - phasedeviation. \n\n % However, rather than use dot and cross products it is simpler and more\n % efficient to simply use acos(energy/sumAn) to obtain the weighted phase\n % deviation directly. Note, in the expression below the noise threshold is\n % not subtracted from energy immediately as this would interfere with the\n % phase deviation computation. Instead it is applied as a weighting as a\n % fraction by which energy exceeds the noise threshold. This weighting is\n % applied in addition to the weighting for frequency spread. Note also the\n % phase deviation gain factor which acts to sharpen up the edge response. A\n % value of 1.5 seems to work well. Sensible values are from 1 to about 2.\n\n PC = weight.*max(1 - deviationGain*acos(energy./(sumAn + epsilon)),0) ...\n .* max(energy-T,0)./(energy+epsilon);\n \n%------------------------------------------------------------------\n% CHECKARGS\n%\n% Function to process the arguments that have been supplied, assign\n% default values as needed and perform basic checks.\n \nfunction [im, nscale, minWaveLength, mult, sigmaOnf, ...\n k, noiseMethod, cutOff, g, deviationGain] = checkargs(arg)\n\n nargs = length(arg);\n \n if nargs < 1\n error('No image supplied as an argument');\n end \n \n % Set up default values for all arguments and then overwrite them\n % with with any new values that may be supplied\n im = [];\n nscale = 4; % Number of wavelet scales. \n minWaveLength = 3; % Wavelength of smallest scale filter. \n mult = 2.1; % Scaling factor between successive filters. \n sigmaOnf = 0.55; % Ratio of the standard deviation of the\n % Gaussian describing the log Gabor filter's\n % transfer function in the frequency domain\n % to the filter center frequency. \n k = 3.0; % No of standard deviations of the noise\n % energy beyond the mean at which we set the\n % noise threshold point. \n noiseMethod = -1; % Use the median response of smallest scale\n % filter to estimate noise statistics\n cutOff = 0.5;\n g = 10;\n deviationGain = 1.5;\n \n % Allowed argument reading states\n allnumeric = 1; % Numeric argument values in predefined order\n keywordvalue = 2; % Arguments in the form of string keyword\n % followed by numeric value\n readstate = allnumeric; % Start in the allnumeric state\n \n if readstate == allnumeric\n for n = 1:nargs\n if isa(arg{n},'char')\n readstate = keywordvalue;\n break;\n else\n if n == 1, im = arg{n}; \n elseif n == 2, nscale = arg{n}; \n elseif n == 3, minWaveLength = arg{n};\n elseif n == 4, mult = arg{n};\n elseif n == 5, sigmaOnf = arg{n};\n elseif n == 6, k = arg{n}; \n elseif n == 7, cutOff = arg{n}; \n elseif n == 8, g = arg{n};\n elseif n == 9, deviationGain = arg{n};\n elseif n == 10, noiseMethod = arg{n}; \n end\n end\n end\n end\n\n % Code to handle parameter name - value pairs\n if readstate == keywordvalue\n while n < nargs\n \n if ~isa(arg{n},'char') || ~isa(arg{n+1}, 'double')\n error('There should be a parameter name - value pair');\n end\n \n if strncmpi(arg{n},'im' ,2), im = arg{n+1};\n elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1};\n elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1};\n elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1};\n elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1};\n elseif strncmpi(arg{n},'k' ,1), k = arg{n+1};\n elseif strncmpi(arg{n},'cutOff' ,2), cutOff = arg{n+1}; \n elseif strncmpi(arg{n},'g' ,1), g = arg{n+1};\n elseif strncmpi(arg{n},'deviation',3), deviationGain = arg{n+1}; \n elseif strncmpi(arg{n},'noisemethod',3), noiseMethod = arg{n+1}; \n else error('Unrecognised parameter name');\n end\n\n n = n+2;\n if n == nargs\n error('Unmatched parameter name - value pair');\n end\n end\n end\n \n if isempty(im)\n error('No image argument supplied');\n end\n\n if ndims(im) == 3\n warning('Colour image supplied: converting image to greyscale...')\n im = double(rgb2gray(im));\n end\n \n if ~isa(im, 'double')\n im = double(im);\n end\n \n if nscale < 1\n error('nscale must be an integer >= 1');\n end\n \n if minWaveLength < 2\n error('It makes little sense to have a wavelength < 2');\n end \n \n \n%-------------------------------------------------------------------------\n% RAYLEIGHMODE\n%\n% Computes mode of a vector/matrix of data that is assumed to come from a\n% Rayleigh distribution.\n%\n% Usage: rmode = rayleighmode(data, nbins)\n%\n% Arguments: data - data assumed to come from a Rayleigh distribution\n% nbins - Optional number of bins to use when forming histogram\n% of the data to determine the mode.\n%\n% Mode is computed by forming a histogram of the data over 50 bins and then\n% finding the maximum value in the histogram. Mean and standard deviation\n% can then be calculated from the mode as they are related by fixed\n% constants.\n%\n% mean = mode * sqrt(pi/2)\n% std dev = mode * sqrt((4-pi)/2)\n% \n% See\n% http://mathworld.wolfram.com/RayleighDistribution.html\n% http://en.wikipedia.org/wiki/Rayleigh_distribution\n%\n\nfunction rmode = rayleighmode(data, nbins)\n \n if nargin == 1\n nbins = 50; % Default number of histogram bins to use\n end\n\n mx = max(data(:));\n edges = 0:mx/nbins:mx;\n n = histc(data(:),edges); \n [dum,ind] = max(n); % Find maximum and index of maximum in histogram \n\n rmode = (edges(ind)+edges(ind+1))/2;\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "highpassmonogenic.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/highpassmonogenic.m", "size": 4645, "source_encoding": "utf_8", "md5": "6f1ebd1682ed7dda4670c52c557cb788", "text": "% HIGHPASSMONOGENIC Compute phase and amplitude on highpass images via monogenic filters\n%\n% Usage: [phase, orient, E, f, h1f, h2f] = highpassmonogenic(im, maxwavelength, n)\n%\n% Arguments: im - Image to be processed.\n% maxwavelength - Wavelength(s) in pixels of the cut-in frequency(ies)\n% of the Butterworth highpass filter. \n% n - The order of the Butterworth filter. This is an\n% integer >= 1. The higher the value the sharper\n% the cutoff. I generaly do not use a value\n% higher than 2 to avoid ringing artifacts\n%\n% Returns: phase - The local phase. Values are between -pi/2 and pi/2\n% orient - The local orientation. Values between -pi and pi.\n% Note that where the local phase is close to\n% +-pi/2 the orientation will be poorly defined.\n% E - Local energy, or amplitude, of the signal.\n%\n% Note that maxwavelength can be an array in which case the outputs will all\n% be cell arrays with an element for each corresponding maxwavelength\n% value.\n%\n% Note also that this code uses the function PERFFT2 rather than FFT2. This\n% computes the 'periodic fft'. This comes at the cost of requiring an\n% additional fft however the minimisation of boundary effects in the result\n% makes it well worth it.\n%\n% See also: PERFFT2, MONOFILT\n\n% Copyright (c) 2012 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% March 2012\n\nfunction [phase, orient, E, f, h1f, h2f] = highpassmonogenic(im, maxwavelength, n)\n \n if ndims(im) == 3, im = rgb2gray(im); end\n assert(min(maxwavelength) >= 2, 'Minimum wavelength is 2 pixels')\n \n [rows,cols] = size(im); \n% IM = fft2(double(im));\n IM = perfft2(double(im)); % Note use of perfft2, replace with fft2 if\n % you wish.\n\n % Generate horizontal and vertical frequency grids that vary from -0.5 to\n % 0.5. Note there are various calls to clear further below to free up\n % memory to allow the processing of very large grids.\n [u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ...\n\t\t\t([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2)));\n\n u1 = ifftshift(u1); % Quadrant shift to put 0 frequency at the corners\n u2 = ifftshift(u2);\n \n radius = sqrt(u1.^2 + u2.^2); % Matrix values contain frequency\n % values as a radius from centre\n % (but quadrant shifted)\n \n % Get rid of the 0 radius value in the middle (at top left corner after\n % fftshifting) so that dividing by the radius, will not cause trouble.\n radius(1,1) = 1;\n \n H1 = i*u1./radius; % The two monogenic filters in the frequency domain\n H2 = i*u2./radius;\n H1(1,1) = 0;\n H2(1,1) = 0;\n radius(1,1) = 0; % undo fudge\n clear('u1', 'u2');\n \n if length(maxwavelength) == 1 % Only one scale requested\n \n % High pass Butterworth filter\n H = 1.0 - 1.0 ./ (1.0 + (radius * maxwavelength).^(2*n)); \n clear('radius');\n IM = IM.*H; clear('H');\n \n f = real(ifft2(IM));\n h1f = real(ifft2(H1.*IM)); clear('H1');\n h2f = real(ifft2(H2.*IM)); clear('H2', 'IM');\n \n phase = atan(f./sqrt(h1f.^2+h2f.^2 + eps));\n orient = atan2(h2f, h1f);\n E = sqrt(f.^2 + h1f.^2 + h2f.^2); \n \n else % Return output as cell arrays, with elements for each scale requested\n for s = 1:length(maxwavelength)\n % High pass Butterworth filter\n H = 1.0 - 1.0 ./ (1.0 + (radius * maxwavelength(s)).^(2*n)); \n \n f{s} = real(ifft2(H.*IM));\n h1f{s} = real(ifft2(H.*H1.*IM));\n h2f{s} = real(ifft2(H.*H2.*IM));\n \n phase{s} = atan(f{s}./sqrt(h1f{s}.^2+h2f{s}.^2 + eps));\n orient{s} = atan2(h2f{s}, h1f{s});\n E{s} = sqrt(f{s}.^2 + h1f{s}.^2 + h2f{s}.^2); \n end\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "step2line.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/step2line.m", "size": 2815, "source_encoding": "utf_8", "md5": "3de96275d1352c256efd4160cfc1ec2d", "text": "% STEP2LINE - Generate test image interpolating a step to a line.\n%\n% Function to generate a test image where the feature type changes\n% from a step edge to a line feature from top to bottom\n%\n% Usage:\n% im = step2line(nscales, ampexponent, sze)\n%\n% nscales - No of fourier components used to construct the signal\n% ampexponent - decay exponent of amplitude with frequency\n% a value of -1 will produce amplitude inversely\n% proportional to frequency (corresponds to step feature)\n% a value of -2 will result in the line feature\n% appearing as a triangular waveform.\n% sze - Optional size of image, defaults to 256x256\n%\n% Returns:\n% im - Image showing the grating pattern\n%\n% suggested parameters: \n% step2line(100, -1) \n%\n\n% Copyright (c) 1997 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% 1997 Original version\n% September 2011 Modified to allow number of cycles to be specified\n% January 2013 Fix Octave compatibility. Separate Octave code path no longer needed\n\nfunction im = step2line(nscales, ampexponent, Npts, nCycles, phaseCycles)\n\n if ~exist('Npts', 'var'), Npts = 256; end\n if ~exist('nCycles', 'var'), nCycles = 1.5; end\n if ~exist('phaseCycles', 'var'), phaseCycles = 0.5; end\n \n x = [0:(Npts-1)]/(Npts-1)*nCycles*2*pi;\n \n im = zeros(Npts,Npts);\n off = 0;\n \n for row = 1:Npts\n signal = zeros(1,Npts);\n for scale = 1:2:(nscales*2-1)\n signal = signal + scale^ampexponent*sin(scale*x + off);\n end\n im(row,:) = signal;\n off = off + phaseCycles*pi/Npts;\n end\n \n figure\n colormap(gray);\n imagesc(im), axis('off') , title('step to line feature interpolation');\n \n range = 3.2;\n s = 'Profiles having phase congruency at 0/180, 30/210, 60/240 and 90/270 degrees';\n\n figure\n subplot(4,1,1), plot(im(1,:)) , title(s), axis([0,Npts,-range,range]), axis('off');\n subplot(4,1,2), plot(im(fix(Npts/3),:)), axis([0,Npts,-range,range]), axis('off');\n subplot(4,1,3), plot(im(fix(2*Npts/3),:)), axis([0,Npts,-range,range]), axis('off');\n subplot(4,1,4), plot(im(Npts,:)), axis([0,Npts,-range,range]), axis('off');\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "odot.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/odot.m", "size": 3720, "source_encoding": "utf_8", "md5": "336255093ed76b067368d764f3d823d5", "text": "% ODOT - Demonstrates odot and oslash operators on 1D signal\n%\n% Usage: [smooth, energy] = odot(f, K)\n%\n% Arguments: f - a 1D signal\n% K - optional 'Weiner' type factor to condition the results\n% where division by 0 occurs in the 'oslash' operation.\n% K defaults to 'eps', If oscillations appear in the\n% plots try increasing the value of K\n%\n% Returns: energy - the Local Energy of the signal.\n% smooth - the smooth component of the signal obtained by\n% performing the 'oslash' operator between the\n% signal and its Local Energy.\n% Plots:\n% Signal Hilbert Transform of Signal\n% Local Energy Hilbert Transform of Energy\n% Smooth Component Reconstruction\n%\n% Smooth = signal 'oslash' energy\n% Reconstruction = energy 'odot' smooth\n%\n% Glitches in the results will be seen at points where the Local Energy\n% peaks - these points cause numerical grief. These problems can be\n% alleviated by smoothing the signal slightly and/or increasing the\n% parameter K.\n%\n% This code only works for 1D signals - I am not sure how you would\n% implement it for 2D images...\n\n% Reference: Robyn Owens. \"Feature-Free Images\", Pattern Recognition\n% Letters. Vol 15. pp 35-44, 1994.\n\n% Copyright (c) 2004 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% March 2004\n\nfunction [smooth, energy] = odot(f, K)\n \n if nargin == 1\n\tK = eps;\n end\n \n N = length(f);\n \n if rem(N,2) > 0 % odd No of elements - trim the last one off to make the\n\t\t % number of elements even for simplicity.\n\tN = N - 1;\n\tf = f(1:N);\n end\n \n F = fft(f);\n \n F(1) = 0; % Kill DC component\n f = real(ifft(F)); % Reconstruct signal minus DC component\n \n % Perform 90 degree phase shift on the signal by multiplying +ve\n % frequencies of the fft by i and the -ve frequencies by -i, and then\n % inverting. \n \n phaseshift = [ ones(1,N/2)*i ones(1,N/2)*(-i) ];\n \n % Hilbert Transform of signal\n h = real(ifft(F.*phaseshift)); \n \n energy = sqrt(f.^2 + h.^2); % Energy\n % Hilbert Transform of Energy\n energyh = real(ifft(fft(energy).*phaseshift)); \n\t\t\t\t\t \n % smooth = signal 'oslash' energy\n divisor = energy.^2 + energyh.^2; \n % Where divisor << K, weinercorrector -> 0/K\n % Where divisor >> K, weinercorrector -> 1 \n weinercorrector = divisor.^2 ./ ((divisor.^2)+K);\n smooth = (f.*energy + energyh.*h)./divisor .* weinercorrector;\n \n % Hilbert transform of smooth component\n smoothh=real(ifft(fft(smooth).*phaseshift));\n \n % Reconstruction = energy odot smooth\n recon = (smooth.*energy - smoothh.*energyh); \n \n subplot(3,2,1), plot(f),title('Signal'); \n subplot(3,2,2), plot(h),title('Hilbert Transform of Signal'); \n subplot(3,2,3), plot(energy),title('Local Energy'); \n subplot(3,2,4), plot(energyh),title('Hilbert Transform of Energy'); \n subplot(3,2,5), plot(smooth),title('Smooth Component'); \n subplot(3,2,6), plot(recon),title('Reconstruction'); "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "dispfeat.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/dispfeat.m", "size": 6082, "source_encoding": "utf_8", "md5": "1baad565a14949d330f8fe298e5a0322", "text": "% DISPFEAT - Displays feature types as detected by PHASECONG.\n%\n% This function provides a visualisation of the feature types as detected\n% by PHASECONG.\n%\n% Usage: im = dispfeat(ft, edgeim, 'l')\n%\n% Arguments: ft - An image providing the local weighted mean \n% phase angle at every point in the image for the \n% orientation having maximum energy. This image can be\n% complex valued in which case phase is assumed to be\n% the complex angle, or it can be real valued, in which\n% case it is assumed to be the phase directly.\n% edgeim - A binary edge image (typically obtained via\n% non-maxima suppression and thresholding).\n% This is used as a `mask' to specify which bits of\n% the phase data should be displayed.\n% Alternatively you can supply a phase congruency\n% image in which case it is used to control the\n% saturation of the colour coding\n% l - An optional parameter indicating that a line plot\n% encoded by line style should also be produced. If\n% this is the case then `edgeim' really should be an\n% edge image.\n% \n% Returns: im - An edge image with edges colour coded according to\n% feature type. \n%\n% Two or three plots are generated:\n% 1. An edge image with edges colour coded according to feature type.\n% 2. A histogram of the frequencies at which the different feature types\n% occur. \n% 3. Optionally a black/white edge image with edges coded by different line\n% styles. Not as pretty as the first plot, but it is something that can\n% be put in a paper and reproduced in black and white.\n\n% Copyright (c) 2001-2009 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% June 2001 Original version\n% May 2009 Allowance for phase data 'ft' to be real or complex valued.\n\nfunction im = dispfeat(ft, edgeim)\n\n% Construct the colour coded image\n\n maxhue = 0.7; % Hues vary from 0 (red) indicating line feature to \n\t\t % 0.7 (blue) indicating a step feature.\n nhues = 50; \n \n if ~isreal(ft) % Phase is encoded as complex values\n\tphaseang = angle(ft); \n else\n\tphaseang = ft; % Assume data is phase already\n end\n\t\t \n % Map -ve phase angles to 0-pi\n negphase = phaseang<0;\n phaseang = negphase.*(-phaseang) + ~negphase.*phaseang; \n \n % Then map angles > pi/2 to 0-pi/2\n x = phaseang>(pi/2); \n phaseang = x.*(pi-phaseang) + ~x.*phaseang;\n \n % Now set up a HSV image and convert to RGB\n hsvim(:,:,1) = (pi/2-phaseang)/(pi/2)*maxhue;\n hsvim(:,:,2) = edgeim; % saturation\n hsvim(:,:,3) = 1;\n \n hsvim(1,:,3) = 0;\n hsvim(end,:,3) = 0; \n hsvim(:,1,3) = 0;\n hsvim(:,end,3) = 0; \n \n im = hsv2rgb(hsvim);\n\n % Set up the colour key bar\n keybar(:,:,1) = [maxhue:-maxhue/nhues:0]';\n keybar(:,:,2) = 1;\n keybar(:,:,3) = 1;\n keybar = hsv2rgb(keybar);\n\n % Plot the results\n figure(1), clf\n subplot('position',[.05 .1 .75 .8]), imshow(im)\n subplot('position',[.8 .1 .1 .8]), imshow(keybar)\n\n text(3,2,'step feature');\n text(3,nhues/2,'step/line');\n text(3,nhues,'line feature');\n\n% Construct the histogram of feature types\n\n figure(2),clf\n data = phaseang(find(edgeim)); % find phase angles just at edge points\n\n Nbins = 32;\n bincentres = [0:pi/2/Nbins:pi/2];\n\n hdata = histc(data(:), bincentres);\n bar(bincentres+pi/4/Nbins, hdata) % plot histogram\n\n ymax = max(hdata);\n xlabel('phase angle'); ylabel('frequency');\n ypos = -.12*ymax;\n axis([0 pi/2 0 1.05*ymax])\n\nif nargin == 3\n \n% Construct the feature type image coded using different line styles\n\n % Generate a phase angle image with non-zero values only at edge\n % points. An offset of eps is added to differentiate points having 0\n % phase from non edge points.\n featedge = (phaseang+eps).*double(edgeim);\n\n % Now construct feature images over specified phase ranges\n f1 = featedge >= eps & featedge < pi/6;\n f2 = featedge >= pi/6 & featedge < pi/3;\n f3 = featedge >= pi/3 & featedge <= pi/2;\n \n fprintf('Linking edges for plots...\\n');\n [f1edgelst dum] = edgelink(f1,2);\n [f2edgelst dum] = edgelink(f2,2);\n [f3edgelst dum] = edgelink(f3,2);\n\n figno = 3;\n figure(figno), clf\n\n % Construct a legend by first drawing some dummy, zero length, lines\n % with the appropriate linestyles in the right order\n line([0 0],[0 0],'LineStyle','-');\n line([0 0],[0 0],'LineStyle','--');\n line([0 0],[0 0],'LineStyle',':');\n legend('step', 'step/line', 'line',3);\n\n % Now do the real plots\n plotedgelist(f1edgelst, figno, '-');\n plotedgelist(f2edgelst, figno, '--');\n plotedgelist(f3edgelst, figno, ':');\n\n % Draw a border around the whole image\n [r c] = size(edgeim);\n line([0 c c 0 0],[0 0 r r 0]);\n axis([0 c 0 r])\n axis equal\n axis ij\n axis off\n \nend\n\n\n%------------------------------------------------------------------------ \n% Internal function to plot an edgelist as generated by edgelink using a\n% specified linestyle\n\nfunction plotedgelist(elist, figno, linestyle)\n\n figure(figno);\n for e = 1:length(elist)\n line(elist{e}(:,2), elist{e}(:,1), 'LineStyle', linestyle, ...\n\t 'LineWidth',1);\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "gaborconvolve.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/gaborconvolve.m", "size": 10723, "source_encoding": "utf_8", "md5": "e6f93594f5594d23a349d49069729926", "text": "% GABORCONVOLVE - function for convolving image with log-Gabor filters\n%\n% Usage: [EO, BP] = gaborconvolve(im, nscale, norient, minWaveLength, mult, ...\n%\t\t\t sigmaOnf, dThetaOnSigma, Lnorm, feedback)\n%\n% Arguments:\n% The convolutions are done via the FFT. Many of the parameters relate \n% to the specification of the filters in the frequency plane. \n%\n% Variable Suggested Description\n% name value\n% ----------------------------------------------------------\n% im Image to be convolved.\n% nscale = 4; Number of wavelet scales.\n% norient = 6; Number of filter orientations.\n% minWaveLength = 3; Wavelength of smallest scale filter.\n% mult = 1.7; Scaling factor between successive filters.\n% sigmaOnf = 0.65; Ratio of the standard deviation of the\n% Gaussian describing the log Gabor filter's\n% transfer function in the frequency domain\n% to the filter center frequency.\n% dThetaOnSigma = 1.3; Ratio of angular interval between filter\n% orientations and the standard deviation of\n% the angular Gaussian function used to\n% construct filters in the freq. plane.\n% Lnorm 0 Optional integer indicating what norm the\n% filters should be normalized to. A value of 1\n% will produce filters with the same L1 norm, 2\n% will produce filters with matching L2\n% norm. the default value of 0 results in no\n% normalization (the filters have unit height\n% Gaussian transfer functions on a log frequency\n% scale) \n% feedback 0/1 Optional parameter. If set to 1 a message\n% indicating which orientation is being\n% processed is printed on the screen.\n%\n% Returns:\n%\n% EO - 2D cell array of complex valued convolution results\n%\n% EO{s,o} = convolution result for scale s and orientation o.\n% The real part is the result of convolving with the even\n% symmetric filter, the imaginary part is the result from\n% convolution with the odd symmetric filter.\n%\n% Hence:\n% abs(EO{s,o}) returns the magnitude of the convolution over the\n% image at scale s and orientation o.\n% angle(EO{s,o}) returns the phase angles.\n%\n% BP - Cell array of bandpass images corresponding to each scale s.\n% \n%\n% Notes on filter settings to obtain even coverage of the spectrum energy\n% dThetaOnSigma 1.2 - 1.3\n% sigmaOnf .90 mult 1.15\n% sigmaOnf .85 mult 1.2\n% sigmaOnf .75 mult 1.4 (bandwidth ~1 octave)\n% sigmaOnf .65 mult 1.7\n% sigmaOnf .55 mult 2.2 (bandwidth ~2 octaves)\n% \n% The determination of mult given sigmaOnf is entirely empirical. What I do is\n% plot out the sum of the squared filter amplitudes in the frequency domain and\n% see how even the coverage of the spectrum is. If there are concentric 'gaps'\n% in the spectrum one needs to reduce mult and/or reduce sigmaOnf (which\n% increases filter bandwidth)\n%\n% If there are 'gaps' radiating outwards then one needs to reduce dthetaOnSigma\n% (increasing angular bandwidth of the filters)\n%\n\n% For details of log-Gabor filters see: \n% D. J. Field, \"Relations Between the Statistics of Natural Images and the\n% Response Properties of Cortical Cells\", Journal of The Optical Society of\n% America A, Vol 4, No. 12, December 1987. pp 2379-2394\n\n% Copyright (c) 2001-2010 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2001 - Original version\n% April 2010 - Reworked to tidy things up. Return of bandpass images added.\n% March 2013 - Restored use of dThetaOnSigma to control angular spread of filters.\n\nfunction [EO, BP] = gaborconvolve(im, nscale, norient, minWaveLength, mult, ...\n\t\t\t sigmaOnf, dThetaOnSigma, Lnorm, feedback)\n \n if ndims(im) == 3\n warning('Colour image supplied: Converting to greyscale');\n im = rgb2gray(im);\n end\n \n if ~exist('Lnorm','var'), Lnorm = 0; end\n if ~exist('feedback','var'), feedback = 0; end \n if ~isa(im,'double'), im = double(im); end\n \n [rows cols] = size(im);\t\t\t\t\t\n imagefft = fft2(im); % Fourier transform of image\n EO = cell(nscale, norient); % Pre-allocate cell array\n BP = cell(nscale,1);\n \n % Pre-compute some stuff to speed up filter construction\n % Set up X and Y matrices with ranges normalised to +/- 0.5\n % The following code adjusts things appropriately for odd and even values\n % of rows and columns.\n if mod(cols,2)\n xrange = [-(cols-1)/2:(cols-1)/2]/(cols-1);\n else\n xrange = [-cols/2:(cols/2-1)]/cols; \n end\n \n if mod(rows,2)\n yrange = [-(rows-1)/2:(rows-1)/2]/(rows-1);\n else\n yrange = [-rows/2:(rows/2-1)]/rows; \n end\n \n [x,y] = meshgrid(xrange, yrange);\n \n radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre.\n theta = atan2(y,x); % Matrix values contain polar angle.\n \n radius = ifftshift(radius); % Quadrant shift radius and theta so that filters\n theta = ifftshift(theta); % are constructed with 0 frequency at the corners.\n radius(1,1) = 1; % Get rid of the 0 radius value at the 0\n % frequency point (now at top-left corner)\n % so that taking the log of the radius will \n % not cause trouble.\n sintheta = sin(theta);\n costheta = cos(theta);\n clear x; clear y; clear theta; % save a little memory\n \n % Filters are constructed in terms of two components.\n % 1) The radial component, which controls the frequency band that the filter\n % responds to\n % 2) The angular component, which controls the orientation that the filter\n % responds to.\n % The two components are multiplied together to construct the overall filter.\n \n % Construct the radial filter components...\n % First construct a low-pass filter that is as large as possible, yet falls\n % away to zero at the boundaries. All log Gabor filters are multiplied by\n % this to ensure no extra frequencies at the 'corners' of the FFT are\n % incorporated. This keeps the overall norm of each filter not too dissimilar.\n lp = lowpassfilter([rows,cols],.45,15); % Radius .45, 'sharpness' 15\n\n logGabor = cell(1,nscale);\n\n for s = 1:nscale\n wavelength = minWaveLength*mult^(s-1);\n fo = 1.0/wavelength; % Centre frequency of filter.\n logGabor{s} = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); \n logGabor{s} = logGabor{s}.*lp; % Apply low-pass filter\n logGabor{s}(1,1) = 0; % Set the value at the 0\n % frequency point of the filter \n % back to zero (undo the radius fudge).\n % Compute bandpass image for each scale \n if Lnorm == 2 % Normalize filters to have same L2 norm\n L = sqrt(sum(logGabor{s}(:).^2));\n elseif Lnorm == 1 % Normalize to have same L1\n L = sum(sum(abs(real(ifft2(logGabor{s})))));\n elseif Lnorm == 0 % No normalization\n L = 1;\n else\n error('Lnorm must be 0, 1 or 2');\n end\n \n logGabor{s} = logGabor{s}./L; \n BP{s} = ifft2(imagefft .* logGabor{s}); \n end\n \n % The main loop...\n for o = 1:norient, % For each orientation.\n if feedback\n fprintf('Processing orientation %d \\r', o);\n end\n \n angl = (o-1)*pi/norient; % Calculate filter angle.\n wavelength = minWaveLength; % Initialize filter wavelength.\n\n % Pre-compute filter data specific to this orientation\n % For each point in the filter matrix calculate the angular distance from the\n % specified filter orientation. To overcome the angular wrap-around problem\n % sine difference and cosine difference values are first computed and then\n % the atan2 function is used to determine angular distance.\n ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.\n dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.\n dtheta = abs(atan2(ds,dc)); % Absolute angular distance.\n\n % Calculate the standard deviation of the angular Gaussian\n % function used to construct filters in the freq. plane.\n thetaSigma = pi/norient/dThetaOnSigma; \n spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); \n \n for s = 1:nscale, % For each scale.\n filter = logGabor{s} .* spread; % Multiply by the angular spread to get the filter\n\n if Lnorm == 2 % Normalize filters to have the same L2 norm ** why sqrt 2 **????\n L = sqrt(sum(real(filter(:)).^2 + imag(filter(:)).^2 ))/sqrt(2);\n elseif Lnorm == 1 % Normalize to have same L1\n L = sum(sum(abs(real(ifft2(filter)))));\n elseif Lnorm == 0 % No normalization\n L = 1; \n end\n filter = filter./L; \n\n % Do the convolution, back transform, and save the result in EO\n EO{s,o} = ifft2(imagefft .* filter); \n \n wavelength = wavelength * mult; % Finally calculate Wavelength of next filter\n end % ... and process the next scale\n\n end % For each orientation\n \n if feedback, fprintf(' \\r'); end\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "monofilt.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/monofilt.m", "size": 6435, "source_encoding": "utf_8", "md5": "07ef46eb32d19a4d79e9ec304c6cb2d3", "text": "% MONOFILT - Apply monogenic filters to an image to obtain 2D analytic signal\n%\n% Implementation of Felsberg's monogenic filters\n%\n% Usage: [f, h1f, h2f, A, theta, psi] = ...\n% monofilt(im, nscale, minWaveLength, mult, sigmaOnf, orientWrap)\n% 3 4 2 0.65 1/0\n% Arguments:\n% The convolutions are done via the FFT. Many of the parameters relate \n% to the specification of the filters in the frequency plane. \n%\n% Variable Suggested Description\n% name value\n% ----------------------------------------------------------\n% im Image to be convolved.\n% nscale = 3; Number of filter scales.\n% minWaveLength = 4; Wavelength of smallest scale filter.\n% mult = 2; Scaling factor between successive filters.\n% sigmaOnf = 0.65; Ratio of the standard deviation of the\n% Gaussian describing the log Gabor filter's\n% transfer function in the frequency domain\n% to the filter center frequency. \n% orientWrap 1/0 Optional flag 1/0 to turn on/off\n% 'wrapping' of orientation data from a\n% range of -pi .. pi to the range 0 .. pi.\n% This affects the interpretation of the\n% phase angle - see note below. Defaults to 0.\n% Returns:\n% \n% f - cell array of bandpass filter responses with respect to scale.\n% h1f - cell array of bandpass h1 filter responses wrt scale.\n% h2f - cell array of bandpass h2 filter responses.\n% A - cell array of monogenic energy responses.\n% theta - cell array of phase orientation responses.\n% psi - cell array of phase angle responses.\n%\n% If orientWrap is 1 (on) theta will be returned in the range 0 .. pi and\n% psi (the phase angle) will be returned in the range -pi .. pi. If\n% orientWrap is 0 theta will be returned in the range -pi .. pi and psi will\n% be returned in the range -pi/2 .. pi/2. Try both options on an image of a\n% circle to see what this means!\n%\n% Experimentation with sigmaOnf can be useful depending on your application.\n% I have found values as low as 0.2 (a filter with a *very* large bandwidth)\n% to be useful on some occasions.\n%\n% See also: GABORCONVOLVE\n\n% References:\n% Michael Felsberg and Gerald Sommer. \"A New Extension of Linear Signal\n% Processing for Estimating Local Properties and Detecting Features\"\n% DAGM Symposium 2000, Kiel \n%\n% Michael Felsberg and Gerald Sommer. \"The Monogenic Signal\" IEEE\n% Transactions on Signal Processing, 49(12):3136-3144, December 2001\n\n% Copyright (c) 2004-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 2004 - Original version.\n% May 2005 - Orientation wrapping and code cleaned up.\n% August 2005 - Phase calculation improved.\n\nfunction [f, h1f, h2f, A, theta, psi] = ...\n\tmonofilt(im, nscale, minWaveLength, mult, sigmaOnf, orientWrap)\n\n if nargin == 5\n\torientWrap = 0; % Default is no orientation wrapping\n end\n \n if nargout > 4\n\tthetaPhase = 1; % Calculate orientation and phase\n else\n\tthetaPhase = 0; % Only return filter outputs\n end\n \n [rows,cols] = size(im); \n IM = fft2(double(im));\n \n % Generate horizontal and vertical frequency grids that vary from\n % -0.5 to 0.5 \n [u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ...\n\t\t\t([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2)));\n\n u1 = ifftshift(u1); % Quadrant shift to put 0 frequency at the corners\n u2 = ifftshift(u2);\n \n radius = sqrt(u1.^2 + u2.^2); % Matrix values contain frequency\n % values as a radius from centre\n % (but quadrant shifted)\n \n % Get rid of the 0 radius value in the middle (at top left corner after\n % fftshifting) so that taking the log of the radius, or dividing by the\n % radius, will not cause trouble.\n radius(1,1) = 1;\n \n H1 = i*u1./radius; % The two monogenic filters in the frequency domain\n H2 = i*u2./radius;\n \n % The two monogenic filters H1 and H2 are oriented in frequency space\n % but are not selective in terms of the magnitudes of the\n % frequencies. The code below generates bandpass log-Gabor filters\n % which are point-wise multiplied by H1 and H2 to produce different\n % bandpass versions of H1 and H2\n \n for s = 1:nscale\n\twavelength = minWaveLength*mult^(s-1);\n\tfo = 1.0/wavelength; % Centre frequency of filter.\n\tlogGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); \n\tlogGabor(1,1) = 0; % undo the radius fudge.\t\n\t\n\t% Generate bandpass versions of H1 and H2 at this scale\n\tH1s = H1.*logGabor; \n\tH2s = H2.*logGabor; \n\t\n\t% Apply filters to image in the frequency domain and get spatial\n % results \n\tf{s} = real(ifft2(IM.*logGabor)); \n\th1f{s} = real(ifft2(IM.*H1s));\n\th2f{s} = real(ifft2(IM.*H2s));\n\t\n\tA{s} = sqrt(f{s}.^2 + h1f{s}.^2 + h2f{s}.^2); % Magnitude of Energy.\n\n\t% If requested calculate the orientation and phase angles\n\tif thetaPhase \n\n\t theta{s} = atan2(h2f{s}, h1f{s}); % Orientation.\n\t \n\t % Here phase is measured relative to the h1f-h2f plane as an\n\t % 'elevation' angle that ranges over +- pi/2\n\t psi{s} = atan2(f{s}, sqrt(h1f{s}.^2 + h2f{s}.^2));\n\t \n\t if orientWrap\n\t\t% Wrap orientation values back into the range 0-pi\n\t\tnegind = find(theta{s}<0);\n\t\ttheta{s}(negind) = theta{s}(negind) + pi;\n\t\t\n\t\t% Where orientation values have been wrapped we should\n % adjust phase accordingly **check**\n\t\tpsi{s}(negind) = pi-psi{s}(negind);\n\t\tmorethanpi = find(psi{s}>pi);\n\t\tpsi{s}(morethanpi) = psi{s}(morethanpi)-2*pi;\n\t end\n\tend\n\t\n end\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ppdrc.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/ppdrc.m", "size": 6128, "source_encoding": "utf_8", "md5": "618b559c40273d70cd8fe32a1bdbc061", "text": "% PPDRC Phase Preserving Dynamic Range Compression\n%\n% Generates a series of dynamic range compressed images at different scales.\n% This function is designed to reveal subtle features within high dynamic range\n% images such as aeromagnetic and other potential field grids. Often this kind\n% of data is presented using histogram equalisation in conjunction with a\n% rainbow colourmap. A problem with histogram equalisation is that the contrast\n% amplification of a feature depends on how commonly its data value occurs,\n% rather than on the amplitude of the feature itself. In addition, the use of a\n% rainbow colourmap can introduce undesirable perceptual distortions.\n%\n% Phase Preserving Dynamic Range Compression allows subtle features to be\n% revealed without these distortions. Perceptually important phase information\n% is preserved and the contrast amplification of anomalies in the signal is\n% purely a function of their amplitude. It operates as follows: first a highpass\n% filter is applied to the data, this controls the desired scale of analysis.\n% The 2D analytic signal of the data is then computed to obtain local phase and\n% amplitude at each point in the image. The amplitude is attenuated by adding 1\n% and then taking its logarithm, the signal is then reconstructed using the\n% original phase values.\n%\n% Usage: dim = ppdrc(im, wavelength, clip, savename, n)\n%\n% Arguments: im - Image to be processed (can contain NaNs)\n% wavelength - Array of wavelengths, in pixels, of the cut-in\n% frequencies to be used when forming the highpass\n% versions of the image.\n% clip - Percentage of output image histogram to clip. Only a\n% very small value should be used, say 0.01 or 0.02, but \n% this can be beneficial. Defaults to 0.01%\n% savename - (optional) Basename of filname to be used when saving\n% the output images. Images are saved as\n% 'basename-n.png' where n is the highpass wavelength\n% for that image . You will be prompted to select a\n% folder to save the images in. \n% n - Order of the Butterworth high pass filter. Defaults\n% to 2\n%\n% Returns: dim - Cell array of the dynamic range reduced images. If\n% only one wavelength is specified the image is returned \n% directly, and not as a one element cell array.\n%\n% Note when specifying the array 'wavelength' it is suggested that you use\n% wavelengths that increase in a geometric series. You can use the function\n% GEOSERIES to conveniently do this\n% \n% Example using GEOSERIES to generate a set of wavelengths that increase\n% geometrically in 10 steps from 50 to 800. Output is saved in a series of\n% image files called 'result-n.png'\n% dim = compressdynamicrange(im, geoseries([50 800], 10), 'result');\n%\n% View the output images in the form of an Interactive Image using LINIMIX\n%\n% See also: HIGHPASSMONOGENIC, GEOSERIES, LINIMIX, HISTRUNCATE\n%\n% Reference:\n% Peter Kovesi, \"Phase Preserving Tone Mapping of Non-Photographic High Dynamic\n% Range Images\". Proceedings: Digital Image Computing: Techniques and\n% Applications 2012 (DICTA 2012). Available via IEEE Xplore\n\n% Copyright (c) 2012-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% April 2012 - Original version\n% Feb 2014 - Incorporated histogram truncation\n\nfunction [dim, mask] = ppdrc(im, wavelength, clip, savename, n)\n\n if ~exist('n', 'var') | isempty(n), n = 2; end\n if ~exist('clip', 'var') | isempty(clip), clip = 0.01; end\n if ~exist('savename', 'var') | isempty(savename), savename = 0; end\n\n nscale = length(wavelength);\n \n % Identify no-data regions in the image (assummed to be marked by NaN\n % values). These values are filled by a call to fillnan() when passing image\n % to highpassmonogenic. While fillnan() is a very poor 'inpainting' scheme\n % it does keep artifacts at the boundaries of no-data regions fairly small.\n mask = ~isnan(im);\n [ph, ~, E] = highpassmonogenic(fillnan(im), wavelength, n);\n \n % Construct each dynamic range reduced image \n\n if nscale == 1 % Single image: ph and E will not be cell arrays\n dim = histtruncate(sin(ph).*log1p(E), clip, clip).*mask;\n \n else % Array of images to be returned.\n range = zeros(nscale,1);\n for k = 1:nscale\n dim{k} = histtruncate(sin(ph{k}).*log1p(E{k}), clip, clip).*mask;\n range(k) = max(abs(dim{k}(:)));\n end\n \n maxrange = max(range);\n % Set the first two pixels of each image to +range and -range so that\n % when the sequence of images are displayed together, say using LINIMIX,\n % there are no unexpected overall brightness changes\n for k = 1:nscale\n dim{k}(1) = maxrange;\n dim{k}(2) = -maxrange;\n end\n end \n\n if savename\n fprintf('Select a folder to save output images in\\n');\n dirname = uigetdir([],'Select a folder to save images in');\n if ~dirname, return; end % Cancel\n \n if nscale == 1 \n imwritesc(dim,sprintf('%s/%s-%04d.png', ...\n dirname,savename,round(wavelength(1))))\n else\n for k = 1:nscale\n imwritesc(dim{k},sprintf('%s/%s-%04d.png', ...\n dirname,savename,round(wavelength(k))))\n end\n end\n end \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "plotgaborfilters.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/plotgaborfilters.m", "size": 10822, "source_encoding": "utf_8", "md5": "2734ffd48e7ead17030ee0fd2f31fce7", "text": "% PLOTGABORFILTERS - Plots log-Gabor filters\n%\n% The purpose of this code is to see what effect the various parameter\n% settings have on the formation of a log-Gabor filter bank.\n%\n% Usage: [Ffilter, Efilter, Ofilter] = plotgaborfilters(sze, nscale, norient,...\n% minWaveLength, mult, sigmaOnf, dThetaOnSigma)\n%\n% Arguments:\n% Many of the parameters relate to the specification of the filters in the frequency plane. \n%\n% Variable Suggested Description\n% name value\n% ----------------------------------------------------------\n% sze = 200 Size of image grid on which the filters\n% are calculated. Note that the actual size\n% of the filter is really specified by its\n% wavelength. \n% nscale = 4; Number of wavelet scales.\n% norient = 6; Number of filter orientations.\n% minWaveLength = 3; Wavelength of smallest scale filter.\n% mult = 1.7; Scaling factor between successive filters.\n% sigmaOnf = 0.65; Ratio of the standard deviation of the\n% Gaussian describing the log Gabor filter's\n% transfer function in the frequency domain\n% to the filter center frequency. \n% dThetaOnSigma = 1.3; Ratio of angular interval between filter\n% orientations and the standard deviation of\n% the angular Gaussian function used to\n% construct filters in the freq. plane.\n%\n% Note regarding the specification of norient: In the default case it is assumed\n% that the angles of the filters are evenly spaced at intervals of pi/norient\n% around the frequency plane. If you want to visualize filters at a specific\n% set of orientations that are not necessarily evenly spaced you can set the\n% orientations by passing a CELL array of orientations as the argument to\n% norient. In this case the value supplied for dThetaOnSigma will be used as\n% thetaSigma - the angular standard deviation of the filters. Yes, this is\n% an ugly abuse of the argument list, but there it is!\n% Example:\n% View filters over 3 scales with orientations of -0.3 and +0.3 radians,\n% minWaveLength of 6, mult of 2, sigmaOnf of 0.65 and thetaSigma of 0.4 \n% plotgaborfilters2(200, 3, {-.3 .3}, 6, 2, 0.65, 0.4);\n%\n% Returns:\n% Ffilter - a 2D cell array of filters defined in the frequency domain.\n% Efilter - a 2D cell array of even filters defined in the spatial domain.\n% Ofilter - a 2D cell array of odd filters defined in the spatial domain.\n%\n% Ffilter{s,o} = filter for scale s and orientation o.\n% The even and odd filters in the spatial domain for scale s,\n% orientation o, are obtained using. \n%\n% Efilter = ifftshift(real(ifft2(fftshift(filter{s,o}))));\n% Ofilter = ifftshift(imag(ifft2(fftshift(filter{s,o}))));\n%\n% Plots:\n% Figure 1 - Sum of the filters in the frequency domain\n% Figure 2 - Cross sections of Figure 1\n% Figures 3 and 4 - Surface and intensity plots of filters in the\n% spatial domain at the smallest and largest\n% scales respectively.\n%\n% See also: GABORCONVOLVE, PHASECONG\n\n% Copyright (c) 2001-2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2001 - Original version.\n% February 2005 - Cleaned up.\n% August 2005 - Ffilter,Efilter and Ofilter corrected to return with scale\n% varying as the first index in the cell arrays.\n% July 2008 - Allow specific filter orientations to be specified in\n% norient via a cell array.\n% March 2013 - Restored use of dThetaOnSigma to control angular spread of filters.\n\nfunction [Ffilter, Efilter, Ofilter, filtersum] = ...\n\tplotgaborfilters(sze, nscale, norient, minWaveLength, mult, ...\n\t\t\t\t sigmaOnf, dThetaOnSigma) \n\n if ~exist('dThetaOnSigma','var') || isempty(dThetaOnSigma), dThetaOnSigma = 1.3; end \n\n if length(sze) == 1\n rows = sze; cols = sze;\n else\n rows = sze(1); cols = sze(2);\n end\n \n if iscell(norient) % Filter orientations and spread have been specified\n % explicitly\n filterOrient = cell2mat(norient);\n thetaSigma = dThetaOnSigma; % Use dThetaOnSigma directly as thetaSigma \n norient = length(filterOrient);\n\t\n else % Usual setup with filters evenly oriented\n\tfilterOrient = [0 : pi/norient : pi-pi/norient];\n\t\n\t% Calculate the standard deviation of the angular Gaussian function\n\t% used to construct filters in the frequency plane. \n\tthetaSigma = pi/norient/dThetaOnSigma;\n end\n \n % Double up all the filter orientations by adding another set offset by\n % pi. This allows us to see the overall orientation coverage of the\n % filters a bit more easily.\n filterOrient = [filterOrient filterOrient+pi]; \n \n % Pre-compute some stuff to speed up filter construction\n \n % Set up X and Y matrices with ranges normalised to +/- 0.5\n % The following code adjusts things appropriately for odd and even values\n % of rows and columns.\n if mod(cols,2)\n\txrange = [-(cols-1)/2:(cols-1)/2]/(cols-1);\n else\n\txrange = [-cols/2:(cols/2-1)]/cols;\t\n end\n \n if mod(rows,2)\n\tyrange = [-(rows-1)/2:(rows-1)/2]/(rows-1);\n else\n\tyrange = [-rows/2:(rows/2-1)]/rows;\t\n end\n \n [x,y] = meshgrid(xrange, yrange);\n \n radius = sqrt(x.^2 + y.^2); % Normalised radius (frequency) values 0.0 - 0.5\n\n % Get rid of the 0 radius value in the middle so that taking the log of\n % the radius will not cause trouble.\n radius(fix(rows/2+1),fix(cols/2+1)) = 1; \n \n theta = atan2(-y,x); % Matrix values contain polar angle.\n\t\t\t\t % (note -ve y is used to give +ve\n\t\t\t\t % anti-clockwise angles)\n sintheta = sin(theta);\n costheta = cos(theta);\n clear x; clear y; clear theta; % save a little memory\n\n % Define a low-pass filter that is as large as possible, yet falls away to zero\n % at the boundaries. All log Gabor filters are multiplied by this to ensure\n % that filters are as similar as possible across orientations (Eliminate the\n % extra frequencies at the 'corners' of the FFT)\n lp = fftshift(lowpassfilter([rows,cols],.45,10)); % Radius .4, 'sharpness' 10\n\n % The main loop...\n\n filtersum = zeros(rows,cols);\n\n for o = 1:2*norient, % For each orientation.\n\tangl = filterOrient(o);\n\twavelength = minWaveLength; % Initialize filter wavelength.\n\n\t% Compute filter data specific to this orientation\n\t% For each point in the filter matrix calculate the angular distance from the\n\t% specified filter orientation. To overcome the angular wrap-around problem\n\t% sine difference and cosine difference values are first computed and then\n\t% the atan2 function is used to determine angular distance.\n\t\n\tds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.\n\tdc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.\n\tdtheta = abs(atan2(ds,dc)); % Absolute angular distance.\n\n if ~dThetaOnSigma % If set to 0 use cosine angular weight spread\n % function. (I do not think this is a good spread function)\n \n dtheta = min(dtheta*norient/2,pi);\n spread = (cos(dtheta)+1)/2;\n else % Use a Gaussian angular spread function\n spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); \n end\n \n\tfor s = 1:nscale, % For each scale.\n\t \n\t % Construct the filter - first calculate the radial filter component.\n\t fo = 1.0/wavelength; % Centre frequency of filter.\n\t \n\t logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); \n\t logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set value at center of the filter\n\t\t\t\t\t\t\t % back to zero (undo the radius fudge).\n\t\t\t\t\t\t\t \n logGabor = logGabor.*lp; % Apply low-pass filter \n\t Ffilter{s,o} = logGabor .* spread; % Multiply by the angular\n\t\t\t\t\t\t % spread to get the filter.\n\t\t\t\t\t \n filtersum = filtersum + Ffilter{s,o}.^2;\n\t\t\t\t\t\t \n\t Efilter{s,o} = ifftshift(real(ifft2(fftshift(Ffilter{s,o}))));\n\t Ofilter{s,o} = ifftshift(imag(ifft2(fftshift(Ffilter{s,o}))));\n \t\t\t\t\t \n\t wavelength = wavelength*mult;\n\tend\n end\n\n % Plot sum of filters and slices radially and tangentially\n figure(1), clf, show(filtersum,1), title('sum of filters');\n \n figure(2), clf\n subplot(2,1,1), plot(filtersum(round(rows/2+1),:))\n title('radial slice through sum of filters');\n \n ang = [0:pi/32:2*pi];\n r = rows/4;\n tslice = improfile(filtersum,r*cos(ang)+cols/2,r*sin(ang)+rows/2);\n subplot(2,1,2), plot(tslice), axis([0 length(tslice) 0 1.1*max(tslice)]);\n title('tangential slice through sum of filters at f = 0.25');\t \n\n % Plot Even and Odd filters at the largest and smallest scales\n h = figure(3); clf\n set(h,'name',sprintf('Filters: Wavelenth = %.2f',minWaveLength));\n subplot(3,2,1), surfl(Efilter{1,1}), shading interp, colormap(gray), \n title('Even Filter');\n subplot(3,2,2), surfl(Ofilter{1,1}), shading interp, colormap(gray)\n title('Odd Filter');\n subplot(3,2,3),imagesc(Efilter{1,1}), axis image, colormap(gray)\n subplot(3,2,4),imagesc(Ofilter{1,1}), axis image, colormap(gray)\n subplot(3,2,5),imagesc(Ffilter{1,1}), axis image, colormap(gray)\n title('Frequency Domain');\n \n h = figure(4); clf\n set(h,'name',sprintf('Filters: Wavelenth = %.2f',minWaveLength*mult^(nscale-1)));\n subplot(3,2,1), surfl(Efilter{nscale,1}), shading interp, colormap(gray)\n title('Even Filter');\n subplot(3,2,2), surfl(Ofilter{nscale,1}), shading interp, colormap(gray)\n title('Odd Filter');\n subplot(3,2,3),imagesc(Efilter{nscale,1}), axis image, colormap(gray)\n subplot(3,2,4),imagesc(Ofilter{nscale,1}), axis image, colormap(gray)\n subplot(3,2,5),imagesc(Ffilter{nscale,1}), axis image, colormap(gray)\n title('Frequency Domain');"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "spatialgabor.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/spatialgabor.m", "size": 2644, "source_encoding": "utf_8", "md5": "0d56aa13789e5563961e97238d519790", "text": "% SPATIALGABOR - applies single oriented gabor filter to an image\n%\n% Usage:\n% [Eim, Oim, Aim] = spatialgabor(im, wavelength, angle, kx, ky, showfilter)\n%\n% Arguments:\n% im - Image to be processed.\n% wavelength - Wavelength in pixels of Gabor filter to construct\n% angle - Angle of filter in degrees. An angle of 0 gives a\n% filter that responds to vertical features.\n% kx, ky - Scale factors specifying the filter sigma relative\n% to the wavelength of the filter. This is done so\n% that the shapes of the filters are invariant to the\n% scale. kx controls the sigma in the x direction\n% which is along the filter, and hence controls the\n% bandwidth of the filter. ky controls the sigma\n% across the filter and hence controls the\n% orientational selectivity of the filter. A value of\n% 0.5 for both kx and ky is a good starting point.\n% showfilter - An optional flag 0/1. When set an image of the\n% even filter is displayed for inspection.\n% \n% Returns:\n% Eim - Result from filtering with the even (cosine) Gabor filter\n% Oim - Result from filtering with the odd (sine) Gabor filter\n% Aim - Amplitude image = sqrt(Eim.^2 + Oim.^2)\n%\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% October 2006\n\nfunction [Eim, Oim, Aim] = spatialgabor(im, wavelength, angle, kx, ky, showfilter)\n\n if nargin == 5\n showfilter = 0;\n end\n \n im = double(im);\n [rows, cols] = size(im);\n newim = zeros(rows,cols);\n \n % Construct even and odd Gabor filters\n sigmax = wavelength*kx;\n sigmay = wavelength*ky;\n \n sze = round(3*max(sigmax,sigmay));\n [x,y] = meshgrid(-sze:sze);\n evenFilter = exp(-(x.^2/sigmax^2 + y.^2/sigmay^2)/2)...\n\t .*cos(2*pi*(1/wavelength)*x);\n \n oddFilter = exp(-(x.^2/sigmax^2 + y.^2/sigmay^2)/2)...\n\t .*sin(2*pi*(1/wavelength)*x); \n\n evenFilter = imrotate(evenFilter, angle, 'bilinear');\n oddFilter = imrotate(oddFilter, angle, 'bilinear'); \n\n % Do the filtering\n Eim = filter2(evenFilter,im); % Even filter result\n Oim = filter2(oddFilter,im); % Odd filter result\n Aim = sqrt(Eim.^2 + Oim.^2); % Amplitude \n \n if showfilter % Display filter for inspection\n figure(1), imshow(evenFilter,[]); title('filter'); \n end\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "phasecong.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/phasecong.m", "size": 16644, "source_encoding": "utf_8", "md5": "693c5ec683ef5ce8c816379185261bf7", "text": "% PHASECONG - Computes phase congruency on an image.\n%\n% Usage: [pc or ft] = phasecong(im)\n%\n% This function calculates the PC_2 measure of phase congruency. \n% For maximum speed the input image should be square and have a \n% size that is a power of 2, but the code will operate on images\n% of arbitrary size. \n%\n%\n% Returned values:\n% pc - Phase congruency image (values between 0 and 1) \n% or - Orientation image. Provides orientation in which \n% local energy is a maximum in in degrees (0-180), \n% angles positive anti-clockwise.\n% ft - A complex valued image giving the weighted mean \n% phase angle at every point in the image for the \n% orientation having maximum energy. Use the\n% function DISPFEAT to display this data.\n%\n% Parameters: \n% im - A greyscale image to be processed.\n% \n% You can also specify numerous optional parameters. See the code to find\n% out what they are. The convolutions are done via the FFT. Many of the\n% parameters relate to the specification of the filters in the frequency\n% plane. Default values for parameters are set within the file rather than\n% being required as arguments because they rarely need to be changed - nor\n% are they very critical. However, you may want to experiment with\n% specifying/editing the values of `nscales' and `noiseCompFactor'.\n%\n% Note this phase congruency code is very computationally expensive and uses\n% *lots* of memory.\n%\n%\n% Example MATLAB session:\n%\n% >> im = imread('picci.tif'); \n% >> image(im); % Display the image\n% >> [pc or ft] = phasecong(im);\n% >> imagesc(pc), colormap(gray); % Display the phase congruency image\n%\n%\n% To convert the phase congruency image to an edge map (with my usual parameters):\n%\n% >> nm = nonmaxsup(pc, or, 1.5); % Non-maxima suppression. \n% The parameter 1.5 can result in edges more than 1 pixel wide but helps\n% in picking up `broad' maxima.\n% >> edgim = hysthresh(nm, 0.4, 0.2); % Hysteresis thresholding.\n% >> edgeim = bwmorph(edgim,'skel',Inf); % Skeletonize the edgemap to fix\n% % the non-maximal suppression.\n% >> imagesc(edgeim), colormap(gray);\n%\n%\n% To display the different feature types present in your image use:\n%\n% >> dispfeat(ft,edgim);\n%\n% With a small amount of editing the code can be modified to calculate\n% a dimensionless measure of local symmetry in the image. The basis\n% of this is that one looks for points in the image where the local \n% phase is 90 or 270 degrees (the symmetric points in the cycle).\n% Editing instructions are within the code.\n%\n% Notes on filter settings to obtain even coverage of the spectrum\n% dthetaOnSigma 1.5\n% sigmaOnf .85 mult 1.3\n% sigmaOnf .75 mult 1.6 (bandwidth ~1 octave)\n% sigmaOnf .65 mult 2.1 \n% sigmaOnf .55 mult 3 (bandwidth ~2 octaves)\n%\n\n% References:\n%\n% Peter Kovesi, \"Image Features From Phase Congruency\". Videre: A\n% Journal of Computer Vision Research. MIT Press. Volume 1, Number 3,\n% Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html\n\n% Copyright (c) 1996-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% Original Version written April 1996 \n% Noise compensation corrected. August 1998\n% Noise compensation corrected. October 1998 - Again!!!\n% Modified to operate on non-square images of arbitrary size. September 1999\n% Modified to return feature type image. May 2001\n\n\n\nfunction[phaseCongruency,orientation, featType]=phasecong(im, nscale, norient, ...\n\t\t\t\t\t\tminWaveLength, mult, ...\n\t\t\t\t\t\tsigmaOnf, dThetaOnSigma, ...\n\t\t\t\t\t\tk, cutOff)\n\nsze = size(im);\n\nif nargin < 2\n nscale = 3; % Number of wavelet scales.\nend\nif nargin < 3\n norient = 6; % Number of filter orientations.\nend\nif nargin < 4\n minWaveLength = 3; % Wavelength of smallest scale filter.\nend\nif nargin < 5\n mult = 2; % Scaling factor between successive filters.\nend\nif nargin < 6\n sigmaOnf = 0.55; % Ratio of the standard deviation of the\n % Gaussian describing the log Gabor filter's transfer function \n\t\t\t % in the frequency domain to the filter center frequency.\nend\nif nargin < 7\n dThetaOnSigma = 1.7; % Ratio of angular interval between filter orientations\n\t\t\t % and the standard deviation of the angular Gaussian\n\t\t\t % function used to construct filters in the\n % freq. plane.\nend\nif nargin < 8\n k = 3.0; % No of standard deviations of the noise energy beyond the\n\t\t\t % mean at which we set the noise threshold point.\n\t\t\t % standard deviation to its maximum effect\n % on Energy.\nend\nif nargin < 9\n cutOff = 0.4; % The fractional measure of frequency spread\n % below which phase congruency values get penalized.\nend\n \ng = 10; % Controls the sharpness of the transition in the sigmoid\n % function used to weight phase congruency for frequency\n % spread.\nepsilon = .0001; % Used to prevent division by zero.\n\n\nthetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the\n % angular Gaussian function used to\n % construct filters in the freq. plane.\n\nimagefft = fft2(im); % Fourier transform of image\nsze = size(imagefft);\nrows = sze(1);\ncols = sze(2);\nzero = zeros(sze);\n\ntotalEnergy = zero; % Matrix for accumulating weighted phase \n % congruency values (energy).\ntotalSumAn = zero; % Matrix for accumulating filter response\n % amplitude values.\norientation = zero; % Matrix storing orientation with greatest\n % energy for each pixel.\nestMeanE2n = [];\n\n% Pre-compute some stuff to speed up filter construction\n\nx = ones(rows,1) * (-cols/2 : (cols/2 - 1))/(cols/2); \ny = (-rows/2 : (rows/2 - 1))' * ones(1,cols)/(rows/2);\nradius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre.\nradius(round(rows/2+1),round(cols/2+1)) = 1; % Get rid of the 0 radius value in the middle \n % so that taking the log of the radius will \n % not cause trouble.\ntheta = atan2(-y,x); % Matrix values contain polar angle.\n % (note -ve y is used to give +ve\n % anti-clockwise angles)\nsintheta = sin(theta);\ncostheta = cos(theta);\nclear x; clear y; clear theta; % save a little memory\n\n% The main loop...\n\nfor o = 1:norient, % For each orientation.\n disp(['Processing orientation ' num2str(o)]);\n angl = (o-1)*pi/norient; % Calculate filter angle.\n wavelength = minWaveLength; % Initialize filter wavelength.\n sumE_ThisOrient = zero; % Initialize accumulator matrices.\n sumO_ThisOrient = zero; \n sumAn_ThisOrient = zero; \n Energy_ThisOrient = zero; \n EOArray = []; % Array of complex convolution images - one for each scale.\n ifftFilterArray = []; % Array of inverse FFTs of filters\n\n % Pre-compute filter data specific to this orientation\n % For each point in the filter matrix calculate the angular distance from the\n % specified filter orientation. To overcome the angular wrap-around problem\n % sine difference and cosine difference values are first computed and then\n % the atan2 function is used to determine angular distance.\n\n ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.\n dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.\n dtheta = abs(atan2(ds,dc)); % Absolute angular distance.\n spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the angular filter component.\n\n for s = 1:nscale, % For each scale.\n\n % Construct the filter - first calculate the radial filter component.\n fo = 1.0/wavelength; % Centre frequency of filter.\n rfo = fo/0.5; % Normalised radius from centre of frequency plane \n % corresponding to fo.\n logGabor = exp((-(log(radius/rfo)).^2) / (2 * log(sigmaOnf)^2)); \n logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set the value at the center of the filter\n % back to zero (undo the radius fudge).\n\n filter = logGabor .* spread; % Multiply by the angular spread to get the filter.\n filter = fftshift(filter); % Swap quadrants to move zero frequency \n % to the corners.\n\n ifftFilt = real(ifft2(filter))*sqrt(rows*cols); % Note rescaling to match power\n ifftFilterArray = [ifftFilterArray ifftFilt]; % record ifft2 of filter\n\n % Convolve image with even and odd filters returning the result in EO\n EOfft = imagefft .* filter; % Do the convolution.\n EO = ifft2(EOfft); % Back transform.\n\n EOArray = [EOArray, EO]; % Record convolution result\n An = abs(EO); % Amplitude of even & odd filter response.\n\n sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses.\n sumE_ThisOrient = sumE_ThisOrient + real(EO); % Sum of even filter convolution results.\n sumO_ThisOrient = sumO_ThisOrient + imag(EO); % Sum of odd filter convolution results.\n\n if s == 1 % Record the maximum An over all scales\n maxAn = An;\n else\n maxAn = max(maxAn, An);\n end\n \n if s==1\n EM_n = sum(sum(filter.^2)); % Record mean squared filter value at smallest\n end % scale. This is used for noise estimation.\n\n wavelength = wavelength * mult; % Finally calculate Wavelength of next filter\n end % ... and process the next scale\n\n % Get weighted mean filter response vector, this gives the weighted mean phase angle.\n\n XEnergy = sqrt(sumE_ThisOrient.^2 + sumO_ThisOrient.^2) + epsilon; \n MeanE = sumE_ThisOrient ./ XEnergy; \n MeanO = sumO_ThisOrient ./ XEnergy; \n\n % Now calculate An(cos(phase_deviation) - | sin(phase_deviation)) | by using\n % dot and cross products between the weighted mean filter response vector and\n % the individual filter response vectors at each scale. This quantity is \n % phase congruency multiplied by An, which we call energy.\n\n for s = 1:nscale, \n EO = submat(EOArray,s,cols); % Extract even and odd filter \n E = real(EO); O = imag(EO);\n Energy_ThisOrient = Energy_ThisOrient ...\n + E.*MeanE + O.*MeanO - abs(E.*MeanO - O.*MeanE);\n end\n\n % Note: To calculate the phase symmetry measure replace the for loop above \n % with the following loop. (The calculation of MeanE, MeanO, sumE_ThisOrient \n % and sumO_ThisOrient can also be omitted). It is suggested that the value\n % of nscale is increased (to say, 5 for a 256x256 image) and that cutOff is\n % set to 0 to eliminate weighting for frequency spread.\n\n% for s = 1:nscale, \n% Energy_ThisOrient = Energy_ThisOrient ...\n% + abs(real(submat(EOArray,s,cols))) - abs(imag(submat(EOArray,s,cols)));\n% end\n\n % Compensate for noise\n % We estimate the noise power from the energy squared response at the smallest scale.\n % If the noise is Gaussian the energy squared will have a Chi-squared 2DOF pdf.\n % We calculate the median energy squared response as this is a robust statistic. \n % From this we estimate the mean. \n % The estimate of noise power is obtained by dividing the mean squared energy value\n % by the mean squared filter value\n\n medianE2n = median(reshape(abs(submat(EOArray,1,cols)).^2,1,rows*cols));\n meanE2n = -medianE2n/log(0.5);\n estMeanE2n = [estMeanE2n meanE2n];\n\n noisePower = meanE2n/EM_n; % Estimate of noise power.\n\n % Now estimate the total energy^2 due to noise\n % Estimate for sum(An^2) + sum(Ai.*Aj.*(cphi.*cphj + sphi.*sphj))\n\n EstSumAn2 = zero;\n for s = 1:nscale\n EstSumAn2 = EstSumAn2+submat(ifftFilterArray,s,cols).^2;\n end\n\n EstSumAiAj = zero;\n for si = 1:(nscale-1)\n for sj = (si+1):nscale\n EstSumAiAj = EstSumAiAj + submat(ifftFilterArray,si,cols).*submat(ifftFilterArray,sj,cols);\n end\n end\n\n EstNoiseEnergy2 = 2*noisePower*sum(sum(EstSumAn2)) + 4*noisePower*sum(sum(EstSumAiAj));\n\n tau = sqrt(EstNoiseEnergy2/2); % Rayleigh parameter\n EstNoiseEnergy = tau*sqrt(pi/2); % Expected value of noise energy\n EstNoiseEnergySigma = sqrt( (2-pi/2)*tau^2 );\n\n T = EstNoiseEnergy + k*EstNoiseEnergySigma; % Noise threshold\n\n % The estimated noise effect calculated above is only valid for the PC_1 measure. \n % The PC_2 measure does not lend itself readily to the same analysis. However\n % empirically it seems that the noise effect is overestimated roughly by a factor \n % of 1.7 for the filter parameters used here.\n\n T = T/1.7; % Empirical rescaling of the estimated noise effect to \n % suit the PC_2 phase congruency measure\n\n Energy_ThisOrient = max(Energy_ThisOrient - T, zero); % Apply noise threshold\n\n % Form weighting that penalizes frequency distributions that are particularly\n % narrow.\n % Calculate fractional 'width' of the frequencies present by taking\n % the sum of the filter response amplitudes and dividing by the maximum \n % amplitude at each point on the image.\n\n width = sumAn_ThisOrient ./ (maxAn + epsilon) / nscale; \n\n % Now calculate the sigmoidal weighting function for this orientation.\n\n weight = 1.0 ./ (1 + exp( (cutOff - width)*g)); \n\n % Apply weighting\n\n Energy_ThisOrient = weight.*Energy_ThisOrient;\n\n % Update accumulator matrix for sumAn and totalEnergy\n\n totalSumAn = totalSumAn + sumAn_ThisOrient;\n totalEnergy = totalEnergy + Energy_ThisOrient;\n\n % Update orientation matrix by finding image points where the energy in this\n % orientation is greater than in any previous orientation (the change matrix)\n % and then replacing these elements in the orientation matrix with the\n % current orientation number.\n\n if(o == 1),\n maxEnergy = Energy_ThisOrient;\n featType = E + i*O;\n else\n change = Energy_ThisOrient > maxEnergy;\n orientation = (o - 1).*change + orientation.*(~change);\n featType = (E+i*O).*change + featType.*(~change);\n maxEnergy = max(maxEnergy, Energy_ThisOrient);\n end\n\nend % For each orientation\n\n\ndisp('Mean Energy squared values recorded with smallest scale filter at each orientation');\ndisp(estMeanE2n);\n\n% Display results\n%imagesc(totalEnergy), axis image, title('total energy');\n%disp('Hit any key to continue '); pause\n%imagesc(totalSumAn), axis image, title('total sumAn'); \n%disp('Hit any key to continue '); pause\n\n% Normalize totalEnergy by the totalSumAn to obtain phase congruency\n\nphaseCongruency = totalEnergy ./ (totalSumAn + epsilon);\n\n%imagesc(phaseCongruency), axis image, title('phase congruency');\n\n% Convert orientation matrix values to degrees\n\norientation = orientation * (180 / norient);\n\nfeatType = featType*i; % Rotate feature phase angles by 90deg so that 0\n % phase corresponds to a step edge (this is a\n % fudge I must have something the wrong way\n % around somewhere)\n\n\n%\n% SUBMAT\n%\n% Function to extract the i'th sub-matrix 'cols' wide from a large\n% matrix composed of several matricies. The large matrix is used in\n% lieu of an array of matricies \n\nfunction a = submat(big,i,cols)\n\na = big(:,((i-1)*cols+1):(i*cols));\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "convexplpiccis.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/PhaseCongruency/Docs/convexplpiccis.m", "size": 2884, "source_encoding": "utf_8", "md5": "c73812719db08612eddaff3437e2413b", "text": "% Function to create images for the convolution explanation\r\n\r\nfunction [spread, logGabor, gfilter] = convexplpiccis\r\n\r\nrows = 200; cols = 200;\r\nwavelength = 16;\r\nsigmaOnf = 0.65;\r\nangl = 1;\r\nthetaSigma = 0.7;\r\n\r\n [x,y] = meshgrid([-cols/2:(cols/2-1)]/cols,...\r\n [-rows/2:(rows/2-1)]/rows);\r\n radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius \r\n % values ranging from 0 at the centre to \r\n % 0.5 at the boundary.\r\n radius(rows/2+1, cols/2+1) = 1; % Get rid of the 0 radius value in the middle \r\n % so that taking the log of the radius will \r\n % not cause trouble.\r\n\r\n\r\n\r\n fo = 1.0/wavelength; % Centre frequency of filter.\r\n\r\n % The following implements the log-gabor transfer function.\r\n logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); \r\n logGabor(rows/2+1, cols/2+1) = 0; % Set the value at the 0 frequency point \r\n % of the filter back to zero \r\n % (undo the radius fudge).\r\n\r\n\r\n show(logGabor,1), imwritesc(logGabor, 'loggabor.jpg');\r\n\r\n lp = lowpassfilter([rows,cols],.4,10); % Radius .4, 'sharpness' 10\r\n lp = fftshift(lp);\r\n logGabor = logGabor.*lp; % Apply low-pass filter\r\n\r\n show(lp,8);\r\n imwritesc(lp, 'lp.jpg');\r\n show(logGabor,2), imwritesc(logGabor, 'loggaborlp.jpg');\r\n\r\n\r\n\r\n theta = atan2(-y,x); % Matrix values contain polar angle.\r\n % (note -ve y is used to give +ve\r\n % anti-clockwise angles)\r\n sintheta = sin(theta);\r\n costheta = cos(theta);\r\n\r\n % For each point in the filter matrix calculate the angular distance from the\r\n % specified filter orientation. To overcome the angular wrap-around problem\r\n % sine difference and cosine difference values are first computed and then\r\n % the atan2 function is used to determine angular distance.\r\n\r\n ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.\r\n dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.\r\n dtheta = abs(atan2(ds,dc)); % Absolute angular distance.\r\n spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the angular \r\n % filter component.\r\n\r\n gfilter = spread.*logGabor;\r\n\r\n show(spread,3), imwritesc(spread, 'spread.jpg');\r\n show(gfilter,4), imwritesc(gfilter, 'filter.jpg');\r\n\r\n\r\nEO = ifft2(fftshift(gfilter));\r\nEO = fftshift(EO);\r\n\r\nimwritesc(real(EO),'realEO.jpg');\r\nimwritesc(imag(EO),'imagEO.jpg');\r\nfigure(9),surfl(real(EO)); shading interp, colormap(copper)\r\nfigure(10),surfl(imag(EO));shading interp, colormap(copper)\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "needleplotgrad.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapelet/needleplotgrad.m", "size": 758, "source_encoding": "utf_8", "md5": "c0bb3b31a34d8fc8cf86c384b5f2da52", "text": "% NEEDLEPLOTGRAD - needleplot of 3D surface from gradient data\r\n%\r\n% Usage: needleplotgrad(dzdx, dzdy, len, spacing)\r\n%\r\n% dzdx, dzdy - 2D arrays of gradient with respect to x and y.\r\n% len - length of needle to be plotted.\r\n% spacing - sub-sampling interval to be used in the\r\n% gradient data. (Plotting every point\r\n% is typically not feasible).\r\n\r\n% Peter Kovesi \r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% pk @ csse uwa edu au\r\n% http://www.csse.uwa.edu.au/~pk\r\n%\r\n% July 2003\r\n\r\nfunction needleplotgrad(dzdx, dzdy, len, spacing)\r\n\r\n [slant, tilt] = grad2slanttilt(dzdx, dzdy);\r\n needleplotst(slant, tilt, len, spacing);\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "needleplotst.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapelet/needleplotst.m", "size": 1443, "source_encoding": "utf_8", "md5": "86c5bdaa284362a76e6260f265211832", "text": "% NEEDLEPLOTST - needleplot of 3D surface from slant tilt data\r\n%\r\n% Usage: needleplotst(slant, tilt, len, spacing)\r\n%\r\n% slant, tilt - 2D arrays of slant and tilt values\r\n% len - length of needle to be plotted\r\n% spacing - sub-sampling interval to be used in the\r\n% slant and tilt data. (Plotting every point\r\n% is typically not feasible)\r\n\r\n% Peter Kovesi \r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% pk @ csse uwa edu au\r\n% http://www.csse.uwa.edu.au/~pk\r\n%\r\n% July 2003\r\n\r\nfunction needleplotst(slant, tilt, len, spacing)\r\n\r\n lw = 1; % linewidth\r\n if ~all(size(slant) == size(tilt))\r\n error('slant matrix must have same dimensions as tilt');\r\n end\r\n\r\n % Subsample the slant and tilt matrices according to the specified spacing\r\n s_slant = slant(1:spacing:end, 1:spacing:end);\r\n s_tilt = tilt(1:spacing:end, 1:spacing:end);\r\n\r\n [s_rows, s_cols] = size(s_slant);\r\n\r\n projlen = len*sin(s_slant); % projected length of each needle onto xy plane\r\n dx = projlen.*cos(s_tilt);\r\n dy = projlen.*sin(s_tilt);\r\n\r\n clf\r\n for r = 1:s_rows\r\n for c = 1:s_cols\r\n x = (c-1)*spacing+1;\r\n y = (r-1)*spacing+1;\r\n h = plot(x,y,'bo'); hold on\r\n set(h,'MarkerSize',2);\r\n line([x x+dx(r,c)],[y y+dy(r,c)],'color',[0 0 1],'linewidth',lw);\r\n end\r\n end\r\n axis('equal')\r\n hold('off')\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "grad2slanttilt.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapelet/grad2slanttilt.m", "size": 1097, "source_encoding": "utf_8", "md5": "051e7b40ca4bf4dbefca92a57a98e63f", "text": "% GRAD2SLANTTILT - gradient in x y to slant tilt\r\n%\r\n% Function to convert a matrix of surface gradients to \r\n% slant and tilt values.\r\n% \r\n% Usage: [slant, tilt] = grad2slanttilt(dzdx, dzdy)\r\n%\r\n\r\n% Copyright (c) 2003 Peter Kovesi\r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% http://www.csse.uwa.edu.au/\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in \r\n% all copies or substantial portions of the Software.\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n\r\n% July 2003\r\n\r\n\r\nfunction [slant, tilt] = grad2slanttilt(dzdx, dzdy)\r\n \r\n if ~all(size(dzdx) == size(dzdy))\r\n error('dzdx must have same dimensions as dzdy');\r\n end\r\n \r\n tilt = atan2(-dzdy, -dzdx);\r\n\r\n gradmag = sqrt(dzdx.^2 + dzdy.^2)+eps;\r\n slant = atan(gradmag);\r\n \r\n \r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "testp.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapelet/testp.m", "size": 2436, "source_encoding": "utf_8", "md5": "9568a363ea5a8f8a4a4d28e4b6bdb4ff", "text": "% Function to make ramps test surface for shape from shapelet testing\r\n%\r\n% Usage:\r\n% function [z,s,t] = testp(noise)\r\n%\r\n% Arguments:\r\n% noise - An optional parameter specifying the standard\r\n% deviation of Gaussian noise to add to the slant and tilt\r\n% values. \r\n% Returns;\r\n% z - A 2D array of surface height values which can be\r\n% viewed using surf(z)\r\n% s,t - Corresponding arrays of slant and tilt angles in\r\n% radians for each point on the surface.\r\n\r\n% Copyright (c) 2003-2005 Peter Kovesi\r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% http://www.csse.uwa.edu.au/\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in \r\n% all copies or substantial portions of the Software.\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n\r\n% July 2003 - Original version\r\n% August 2005 - Changes to accommodate Octave\r\n% September 2008 - Needle plot reinstated for Octave\r\n% January 2013 - Separate code path for Octave no longer needed (random()\r\n% is part of statistics package) \r\n\r\nfunction [z,s,t] = testp(noise)\r\n\r\n if nargin == 0\r\n noise = 0;\r\n end\r\n \r\n p1 = [zeros(1,15) [0:.2:10] zeros(1,15)];\r\n p2 = zeros(1,length(p1));\r\n n = ceil(length(p1)/2);\r\n p3 = [1:n n:-1:1]/n*6;\r\n p3 = p3(1:length(p1));\r\n \r\n z = [ones(15,1)*p2\r\n ones(15,1)*p1\r\n ones(15,1)*p3\r\n ones(15,1)*p2];\r\n \r\n \r\n figure(1); clf;% surfl(z), shading interp; colormap(copper);\r\n surf(z); % colormap(white);\r\n \r\n [dx, dy] = gradient(z);\r\n [s,t] = grad2slanttilt(dx,dy);\r\n \r\n [rows,cols] = size(s);\r\n\r\n if noise\r\n t = t + random('Normal',0,noise,rows,cols); % add noise to tilt\r\n s = s + random('Normal',0,noise,rows,cols); % ... and slant\r\n % constrain noisy slant values to 0-pi\r\n s = max(s, 0);\r\n s = min(s, pi/2-0.05); % -0.05 to avoid infinite gradient\r\n end\r\n \r\n figure(2),needleplotst(s,t,5,2), axis('off')\r\n\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "frankotchellappa.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapelet/frankotchellappa.m", "size": 2612, "source_encoding": "utf_8", "md5": "56bcc95bb901b40d8eee5f4e8a533b91", "text": "% FRANKOTCHELLAPPA - Generates integrable surface from gradients\n%\n% An implementation of Frankot and Chellappa'a algorithm for constructing\n% an integrable surface from gradient information.\n%\n% Usage: z = frankotchellappa(dzdx,dzdy)\n%\n% Arguments: dzdx, - 2D matrices specifying a grid of gradients of z\n% dzdy with respect to x and y.\n%\n% Returns: z - Inferred surface heights.\n\n% Reference:\n%\n% Robert T. Frankot and Rama Chellappa\n% A Method for Enforcing Integrability in Shape from Shading\n% IEEE PAMI Vol 10, No 4 July 1988. pp 439-451\n%\n% Note this code just implements the surface integration component of the\n% paper (Equation 21 in the paper). It does not implement their shape from\n% shading algorithm.\n\n% Copyright (c) 2004 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 2004\n\nfunction z = frankotchellappa(dzdx,dzdy)\n \n if ~all(size(dzdx) == size(dzdy))\n error('Gradient matrices must match');\n end\n\n [rows,cols] = size(dzdx);\n \n % The following sets up matrices specifying frequencies in the x and y\n % directions corresponding to the Fourier transforms of the gradient\n % data. They range from -0.5 cycles/pixel to + 0.5 cycles/pixel. The\n % fiddly bits in the line below give the appropriate result depending on\n % whether there are an even or odd number of rows and columns\n \n [wx, wy] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ...\n\t\t\t([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2)));\n \n % Quadrant shift to put zero frequency at the appropriate edge\n wx = ifftshift(wx); wy = ifftshift(wy);\n\n DZDX = fft2(dzdx); % Fourier transforms of gradients\n DZDY = fft2(dzdy);\n\n % Integrate in the frequency domain by phase shifting by pi/2 and\n % weighting the Fourier coefficients by their frequencies in x and y and\n % then dividing by the squared frequency. eps is added to the\n % denominator to avoid division by 0.\n \n Z = (-j*wx.*DZDX -j*wy.*DZDY)./(wx.^2 + wy.^2 + eps); % Equation 21\n \n z = real(ifft2(Z)); % Reconstruction\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "slanttilt2grad.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapelet/slanttilt2grad.m", "size": 1090, "source_encoding": "utf_8", "md5": "7fb013bc78a565346b80337d3535d16d", "text": "% SLANTTILT2GRAD - slant and tilt to gradient in x y \r\n%\r\n% Function to convert a matrix of slant and tilt values to\r\n% surface gradients.\r\n% \r\n% Usage: [dzdx, dzdy] = slanttilt2grad(slant, tilt)\r\n%\r\n\r\n% Copyright (c) 2003 Peter Kovesi\r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% http://www.csse.uwa.edu.au/\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in \r\n% all copies or substantial portions of the Software.\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n\r\n% July 2003\r\n\r\n\r\nfunction [dzdx, dzdy] = slanttilt2grad(slant, tilt)\r\n \r\n if ~all(size(slant) == size(tilt))\r\n error('slant matrix must have same dimensions as tilt');\r\n end\r\n \r\n gradmag = tan(slant); \r\n\r\n dzdx = -gradmag.*cos(tilt);\r\n dzdy = -gradmag.*sin(tilt);\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "shapeletsurf.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Shapelet/shapeletsurf.m", "size": 9292, "source_encoding": "utf_8", "md5": "ab9b782a8bb8c8d669105b6ffe6dba0c", "text": "% SHAPELETSURF - reconstructs surface from surface normals using shapelets\r\n%\r\n% Function reconstructs an estimate of a surface from its surface normals by\r\n% correlating the surface normals with that those of a bank of shapelet\r\n% basis functions. The correlation results are summed to produce the\r\n% reconstruction. The sumation of shapelet basis functions results in an\r\n% implicit integration of the surface while enforcing surface continuity.\r\n%\r\n% Note that the reconstruction is only valid up to a scale factor. However\r\n% the reconstruction process is very robust to noise and to missing data\r\n% values. Reconstructions (up to positive/negative shape ambiguity) are\r\n% possible where there is an ambiguity of pi in tilt values. Low quality\r\n% reconstructions are also possible with just slant, or just tilt data\r\n% alone.\r\n% \r\n%\r\n% Usage:\r\n% recsurf = shapletsurf(slant, tilt, nscales, minradius, mult, opt)\r\n% 6 1 2\r\n% Arguments:\r\n% slant - 2D array of surface slant values across image.\r\n% tilt - 2D array of surface tilt values.\r\n% nscales - number of shapelet scales to use.\r\n% minsigma - sigma of smallest scale Gaussian shapelet.\r\n% mult - scaling factor between successive shapelets.\r\n%\r\n% opt can be the string:\r\n% 'slanttilt' - reconstruct using both slant and tilt (default).\r\n% 'tiltamb' - reconstruct assuming tilt ambiguity of pi.\r\n% 'slant' - reconstruct with slant only.\r\n% 'tilt' - reconstruct with tilt only.\r\n% \r\n% Returns:\r\n% recsurf - reconstructed surface.\r\n%\r\n% Remember when viewing the surface you should use \r\n% >> axis ij \r\n% So that the surface corresponds to the image slant and tilt axes\r\n%\r\n% References:\r\n%\r\n% Peter Kovesi, \"Surface Normals to Surfaces via Shapelets\"\r\n% Proceedings Australia-Japan Advanced Workshop on Computer Vision\r\n% Adelaide, 9-11 September 2003\r\n%\r\n% Peter Kovesi, \"Shapelets Correlated with Surface Normals Produce\r\n% Surfaces\". Technical Report 03-003, October 2003.\r\n% http://www.csse.uwa.edu.au/~pk/research/pkpapers/shapelets-03-002.pdf\r\n\r\n% Copyright (c) 2003-2005 Peter Kovesi\r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% http://www.csse.uwa.edu.au/\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in \r\n% all copies or substantial portions of the Software.\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n\r\n% July 2003 - Original version.\r\n% September 2003 - Correction to reconstruction with tilt ambiguity.\r\n% October 2003 - Changed to use Gaussian shapelets.\r\n% February 2004 - Convolutions done via fft for speed.\r\n% March 2004 - Padding of slant and tilt data to accommodate large filters.\r\n\r\nfunction recsurf = shapeletsurf(varargin)\r\n \r\n [slant, tilt, nscales, minsigma, mult, opt] = checkargs(varargin(:));\r\n \r\n if strcmp(opt,'tiltamb') % If we have an ambiguity of pi in the tilt \r\n tilt = tilt*2; % work with doubled angles.\r\n end\r\n\r\n [rows,cols] = size(slant);\r\n\r\n % Check size of largest filter and, if necessary, pad slant and tilt\r\n % data with zeros so that the largest filter can be accommodated.\r\n % If this is not done wraparound in the convolutions via the FFT produce\r\n % artifacts in the reconstruction.\r\n % Treat max size as +- 3 sigma\r\n maxsize = ceil(6*minsigma*mult^(nscales-1)); \r\n paddingapplied = 0;\r\n\r\n if rows < maxsize | cols < maxsize % padding needed\r\n paddingapplied = 1;\r\n rowpad = max(0,round(maxsize-rows));\r\n colpad = max(0,round(maxsize-cols));\r\n fprintf('Warning: To accommodate the largest filter size the\\n');\r\n fprintf('slant and tilt data is being padded from %dx%d to %dx%d \\n', ...\r\n rows,cols, rows+rowpad, cols+colpad);\r\n\r\n slant = [slant zeros(rows, colpad)\r\n zeros(rowpad, cols+colpad)];\r\n tilt = [tilt zeros(rows, colpad)\r\n zeros(rowpad, cols+colpad)];\r\n origrows = rows; origcols = cols; % Remember original size.\r\n [rows,cols] = size(slant); % Update current size.\r\n end\r\n \r\n % Precompute some values for speed of execution. Note that because we\r\n % generally want to use shapelets at quite large scales relative to the\r\n % size of the image correlations are done in the frequency domain for\r\n % speed. (Note that in the code below the conjugate of the fft is used\r\n % because we want the correlation, not convolution.)\r\n surfgrad = tan(slant); SURFGRAD= fft2(surfgrad);\r\n sintilt = sin(tilt); SINTILT = fft2(sintilt);\r\n costilt = cos(tilt); COSTILT = fft2(costilt);\r\n SURFGRADSINTILT = fft2(surfgrad.*sintilt); \r\n SURFGRADCOSTILT = fft2(surfgrad.*costilt);\r\n \r\n for s = 1:nscales\r\n% fprintf('scale %d out of %d\\r',s,nscales);\r\n \r\n % Use a Gaussian filter shape as the shapelet basis function\r\n % as the phase distortion in the reconstruction should be zero.\r\n f = gaussianf(minsigma*mult^(s-1), rows, cols);\r\n\r\n [fdx,fdy] = gradient(f); % filter gradients\r\n [fslant,ftilt] = grad2slanttilt(fdx,fdy); % filter slants and tilts\r\n \r\n if strcmp(opt,'tiltamb')\r\n ftilt = ftilt*2;\r\n end \r\n \r\n % Now perform the correlations (via the fft) as required depending\r\n % on the options selected. \r\n sinftilt = sin(ftilt); \r\n cosftilt = cos(ftilt); \r\n filtgrad = tan(fslant); \r\n \r\n filtgradsintilt = filtgrad.*sinftilt;\r\n filtgradcostilt = filtgrad.*cosftilt;\r\n \r\n if strcmp(opt,'slanttilt') % both slant and tilt data available\r\n FILTGRADSINTILT = fft2(filtgrad.*sinftilt);\r\n FILTGRADCOSTILT = fft2(filtgrad.*cosftilt);\r\n fim{s} = real(ifft2(conj(FILTGRADCOSTILT) .* SURFGRADCOSTILT)) + ...\r\n real(ifft2(conj(FILTGRADSINTILT) .* SURFGRADSINTILT));\r\n \r\n elseif strcmp(opt,'tiltamb') % assume tilt ambiguity of pi\r\n FILTGRADSINTILT = fft2(filtgrad.*sinftilt);\r\n FILTGRADCOSTILT = fft2(filtgrad.*cosftilt);\r\n FILTGRAD = fft2(filtgrad);\r\n fim{s} = (real(ifft2(conj(FILTGRADCOSTILT) .* SURFGRADCOSTILT)) + ...\r\n real(ifft2(conj(FILTGRADSINTILT) .* SURFGRADSINTILT)) + ...\r\n real(ifft2(conj(FILTGRAD) .* SURFGRAD)))/2; \r\n \r\n elseif strcmp(opt,'tilt'); % tilt only reconstruction\r\n SINFTILT = fft2(sinftilt);\r\n COSFTILT = fft2(cosftilt);\r\n fim{s} = real(ifft2(conj(COSFTILT) .* COSTILT)) + ...\r\n real(ifft2(conj(SINFTILT) .* SINTILT)); \r\n \r\n elseif strcmp(opt,'slant'); % just use slant and ignore tilt\r\n FILTGRAD = fft2(filtgrad);\r\n fim{s} = real(ifft2(conj(FILTGRAD) .* SURFGRAD)); \r\n end\r\n \r\n end\r\n% fprintf('\\n');\r\n \r\n % Reconstruct by adding filtered outputs\r\n \r\n recsurf = zeros(size(slant));\r\n for s = 1:nscales\r\n recsurf = recsurf + fim{s};\r\n end\r\n\r\n\r\n if paddingapplied % result is padded - extract the bit we want.\r\n\trecsurf = recsurf(1:origrows, 1:origcols);\r\n end\r\n \r\n%-------------------------------------------------------------------------\r\n% Function to generate a Gaussian filter for use as a shapelet.\r\n% Usage:\r\n% f = gaussian(sigma, rows, cols)\r\n%\r\n% Arguments:\r\n% sigma - standard deviation of Gaussian\r\n% rows, cols - size of filter to create\r\n\r\nfunction f = gaussianf(sigma, rows, cols)\r\n\r\n [x,y] = meshgrid( [1:cols]-(fix(cols/2)+1), [1:rows]-(fix(rows/2)+1));\r\n r = sqrt(x.^2 + y.^2);\r\n f = fftshift(exp(-r.^2/(2*sigma^2)));\r\n\r\n%--------------------------------------------------------------------------\r\n% Function to check argument values and set defaults\r\n\r\nfunction [slant, tilt, nscales, minradius, mult, opt] = checkargs(arg);\r\n \r\n if length(arg)<5 \r\n error('too few arguments');\r\n elseif length(arg)>6\r\n error('too many arguments');\r\n end\r\n \r\n slant = arg{1};\r\n tilt = arg{2};\r\n nscales = arg{3};\r\n minradius = arg{4};\r\n mult = arg{5};\r\n \r\n if length(arg) == 5\r\n opt = 'slanttilt'; % Default is to assume both slant and tilt values\r\n % are valid.\r\n else\r\n opt = arg{6};\r\n end\r\n \r\n if ~all(size(slant)==size(tilt))\r\n error('slant and tilt matrices must match');\r\n end\r\n \r\n if nscales < 1\r\n error('number of scales must be 1 or greater');\r\n end\r\n \r\n if minradius < .1\r\n error('minimum radius of shapelet must be greater than .1');\r\n end\r\n \r\n if mult < 1\r\n error('scaling factor between successive filters should be greater than 1');\r\n end\r\n \r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ridgefreq.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FingerPrints/ridgefreq.m", "size": 2993, "source_encoding": "utf_8", "md5": "06dee0fde68607594d459ca300e6d102", "text": "% RIDGEFREQ - Calculates a ridge frequency image\n%\n% Function to estimate the fingerprint ridge frequency across a\n% fingerprint image. This is done by considering blocks of the image and\n% determining a ridgecount within each block by a call to FREQEST.\n%\n% Usage:\n% [freqim, medianfreq] = ridgefreq(im, mask, orientim, blksze, windsze, ...\n% minWaveLength, maxWaveLength)\n%\n% Arguments:\n% im - Image to be processed.\n% mask - Mask defining ridge regions (obtained from RIDGESEGMENT)\n% orientim - Ridge orientation image (obtained from RIDGORIENT)\n% blksze - Size of image block to use (say 32) \n% windsze - Window length used to identify peaks. This should be\n% an odd integer, say 3 or 5.\n% minWaveLength, maxWaveLength - Minimum and maximum ridge\n% wavelengths, in pixels, considered acceptable.\n% \n% Returns:\n% freqim - An image the same size as im with values set to\n% the estimated ridge spatial frequency within each\n% image block. If a ridge frequency cannot be\n% found within a block, or cannot be found within the\n% limits set by min and max Wavlength freqim is set\n% to zeros within that block.\n% medianfreq - Median frequency value evaluated over all the\n% valid regions of the image.\n%\n% Suggested parameters for a 500dpi fingerprint image\n% [freqim, medianfreq] = ridgefreq(im,orientim, 32, 5, 5, 15);\n%\n% I seem to find that the median frequency value is more useful as an\n% input to RIDGEFILTER than the more detailed freqim. This is possibly\n% due to deficiencies in FREQEST.\n%\n% See also: RIDGEORIENT, FREQEST, RIDGESEGMENT\n\n% Reference: \n% Hong, L., Wan, Y., and Jain, A. K. Fingerprint image enhancement:\n% Algorithm and performance evaluation. IEEE Transactions on Pattern\n% Analysis and Machine Intelligence 20, 8 (1998), 777 789.\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% January 2005\n\nfunction [freq, medianfreq] = ridgefreq(im, mask, orient, blksze, windsze, ...\n minWaveLength, maxWaveLength) \n \n [rows, cols] = size(im);\n freq = zeros(size(im));\n \n for r = 1:blksze:rows-blksze\n for c = 1:blksze:cols-blksze\n blkim = im(r:r+blksze-1, c:c+blksze-1); \n blkor = orient(r:r+blksze-1, c:c+blksze-1); \n \n freq(r:r+blksze-1,c:c+blksze-1) = ...\n freqest(blkim, blkor, windsze, minWaveLength, maxWaveLength);\n end\n end\n\n % Mask out frequencies calculated for non ridge regions\n freq = freq.*mask;\n \n % Find median freqency over all the valid regions of the image.\n medianfreq = median(freq(find(freq>0))); "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "freqest.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FingerPrints/freqest.m", "size": 3637, "source_encoding": "utf_8", "md5": "a4f96f1105673bbd0d6851306a9712c8", "text": "% FREQEST - Estimate fingerprint ridge frequency within image block\n%\n% Function to estimate the fingerprint ridge frequency within a small block\n% of a fingerprint image. This function is used by RIDGEFREQ\n%\n% Usage:\n% freqim = freqest(im, orientim, windsze, minWaveLength, maxWaveLength)\n%\n% Arguments:\n% im - Image block to be processed.\n% orientim - Ridge orientation image of image block.\n% windsze - Window length used to identify peaks. This should be\n% an odd integer, say 3 or 5.\n% minWaveLength, maxWaveLength - Minimum and maximum ridge\n% wavelengths, in pixels, considered acceptable.\n% \n% Returns:\n% freqim - An image block the same size as im with all values\n% set to the estimated ridge spatial frequency. If a\n% ridge frequency cannot be found, or cannot be found\n% within the limits set by min and max Wavlength\n% freqim is set to zeros.\n%\n% Suggested parameters for a 500dpi fingerprint image\n% freqim = freqest(im,orientim, 5, 5, 15);\n%\n% See also: RIDGEFREQ, RIDGEORIENT, RIDGESEGMENT\n%\n% Note I am not entirely satisfied with the output of this function.\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% January 2005\n\n \nfunction freqim = freqest(im, orientim, windsze, minWaveLength, maxWaveLength)\n \n debug = 0;\n \n [rows,cols] = size(im);\n \n % Find mean orientation within the block. This is done by averaging the\n % sines and cosines of the doubled angles before reconstructing the\n % angle again. This avoids wraparound problems at the origin.\n orientim = 2*orientim(:); \n cosorient = mean(cos(orientim));\n sinorient = mean(sin(orientim)); \n orient = atan2(sinorient,cosorient)/2;\n\n % Rotate the image block so that the ridges are vertical\n rotim = imrotate(im,orient/pi*180+90,'nearest', 'crop');\n \n % Now crop the image so that the rotated image does not contain any\n % invalid regions. This prevents the projection down the columns\n % from being mucked up.\n cropsze = fix(rows/sqrt(2)); offset = fix((rows-cropsze)/2);\n rotim = rotim(offset:offset+cropsze, offset:offset+cropsze);\n\n % Sum down the columns to get a projection of the grey values down\n % the ridges.\n proj = sum(rotim);\n \n % Find peaks in projected grey values by performing a greyscale\n % dilation and then finding where the dilation equals the original\n % values. \n dilation = ordfilt2(proj, windsze, ones(1,windsze));\n maxpts = (dilation == proj) & (proj > mean(proj));\n maxind = find(maxpts);\n\n % Determine the spatial frequency of the ridges by divinding the\n % distance between the 1st and last peaks by the (No of peaks-1). If no\n % peaks are detected, or the wavelength is outside the allowed bounds,\n % the frequency image is set to 0\n if length(maxind) < 2\n\tfreqim = zeros(size(im));\n else\n\tNoOfPeaks = length(maxind);\n\twaveLength = (maxind(end)-maxind(1))/(NoOfPeaks-1);\n\tif waveLength > minWaveLength & waveLength < maxWaveLength\n\t freqim = 1/waveLength * ones(size(im));\n\telse\n\t freqim = zeros(size(im));\n\tend\n end\n\n \n if debug\n\tshow(im,1)\n\tshow(rotim,2);\n\tfigure(3), plot(proj), hold on\n\tmeanproj = mean(proj)\n\tif length(maxind) < 2\n\t fprintf('No peaks found\\n');\n\telse\n\t plot(maxind,dilation(maxind),'r*'), hold off\n\t waveLength = (maxind(end)-maxind(1))/(NoOfPeaks-1);\n\tend\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ridgefilter.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FingerPrints/ridgefilter.m", "size": 4770, "source_encoding": "utf_8", "md5": "a6443447a69fa10919e580f23e30c264", "text": "% RIDGEFILTER - enhances fingerprint image via oriented filters\n%\n% Function to enhance fingerprint image via oriented filters\n%\n% Usage:\n% newim = ridgefilter(im, orientim, freqim, kx, ky, showfilter)\n%\n% Arguments:\n% im - Image to be processed.\n% orientim - Ridge orientation image, obtained from RIDGEORIENT.\n% freqim - Ridge frequency image, obtained from RIDGEFREQ.\n% kx, ky - Scale factors specifying the filter sigma relative\n% to the wavelength of the filter. This is done so\n% that the shapes of the filters are invariant to the\n% scale. kx controls the sigma in the x direction\n% which is along the filter, and hence controls the\n% bandwidth of the filter. ky controls the sigma\n% across the filter and hence controls the\n% orientational selectivity of the filter. A value of\n% 0.5 for both kx and ky is a good starting point.\n% showfilter - An optional flag 0/1. When set an image of the\n% largest scale filter is displayed for inspection.\n% \n% Returns:\n% newim - The enhanced image\n%\n% See also: RIDGEORIENT, RIDGEFREQ, RIDGESEGMENT\n\n% Reference: \n% Hong, L., Wan, Y., and Jain, A. K. Fingerprint image enhancement:\n% Algorithm and performance evaluation. IEEE Transactions on Pattern\n% Analysis and Machine Intelligence 20, 8 (1998), 777 789.\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% January 2005\n\nfunction newim = ridgefilter(im, orient, freq, kx, ky, showfilter)\n\n if nargin == 5\n showfilter = 0;\n end\n \n angleInc = 3; % Fixed angle increment between filter orientations in\n % degrees. This should divide evenly into 180\n \n im = double(im);\n [rows, cols] = size(im);\n newim = zeros(rows,cols);\n \n [validr,validc] = find(freq > 0); % find where there is valid frequency data.\n ind = sub2ind([rows,cols], validr, validc);\n\n % Round the array of frequencies to the nearest 0.01 to reduce the\n % number of distinct frequencies we have to deal with.\n freq(ind) = round(freq(ind)*100)/100;\n \n % Generate an array of the distinct frequencies present in the array\n % freq \n unfreq = unique(freq(ind)); \n \n % Generate a table, given the frequency value multiplied by 100 to obtain\n % an integer index, returns the index within the unfreq array that it\n % corresponds to\n freqindex = ones(100,1);\n for k = 1:length(unfreq)\n freqindex(round(unfreq(k)*100)) = k;\n end\n \n % Generate filters corresponding to these distinct frequencies and\n % orientations in 'angleInc' increments.\n filter = cell(length(unfreq),180/angleInc);\n sze = zeros(length(unfreq),1);\n \n for k = 1:length(unfreq)\n sigmax = 1/unfreq(k)*kx;\n sigmay = 1/unfreq(k)*ky;\n \n sze(k) = round(3*max(sigmax,sigmay));\n [x,y] = meshgrid(-sze(k):sze(k));\n reffilter = exp(-(x.^2/sigmax^2 + y.^2/sigmay^2)/2)...\n .*cos(2*pi*unfreq(k)*x);\n\n % Generate rotated versions of the filter. Note orientation\n % image provides orientation *along* the ridges, hence +90\n % degrees, and imrotate requires angles +ve anticlockwise, hence\n % the minus sign.\n for o = 1:180/angleInc\n filter{k,o} = imrotate(reffilter,-(o*angleInc+90),'bilinear','crop'); \n end\n end\n\n if showfilter % Display largest scale filter for inspection\n figure(7), imshow(filter{1,end},[]); title('filter'); \n end\n \n % Find indices of matrix points greater than maxsze from the image\n % boundary\n maxsze = sze(1); \n finalind = find(validr>maxsze & validrmaxsze & validc maxorientindex); \n orientindex(i) = orientindex(i)-maxorientindex; \n\n % Finally do the filtering\n for k = 1:length(finalind)\n r = validr(finalind(k));\n c = validc(finalind(k));\n\n % find filter corresponding to freq(r,c)\n filterindex = freqindex(round(freq(r,c)*100));\n \n s = sze(filterindex); \n newim(r,c) = sum(sum(im(r-s:r+s, c-s:c+s).*filter{filterindex,orientindex(r,c)}));\n end\n\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ridgesegment.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FingerPrints/ridgesegment.m", "size": 2320, "source_encoding": "utf_8", "md5": "2bb49bf39ab2cc6bdd3a9e158ef0a054", "text": "% RIDGESEGMENT - Normalises fingerprint image and segments ridge region\n%\n% Function identifies ridge regions of a fingerprint image and returns a\n% mask identifying this region. It also normalises the intesity values of\n% the image so that the ridge regions have zero mean, unit standard\n% deviation.\n%\n% This function breaks the image up into blocks of size blksze x blksze and\n% evaluates the standard deviation in each region. If the standard\n% deviation is above the threshold it is deemed part of the fingerprint.\n% Note that the image is normalised to have zero mean, unit standard\n% deviation prior to performing this process so that the threshold you\n% specify is relative to a unit standard deviation.\n%\n% Usage: [normim, mask, maskind] = ridgesegment(im, blksze, thresh)\n%\n% Arguments: im - Fingerprint image to be segmented.\n% blksze - Block size over which the the standard\n% deviation is determined (try a value of 16).\n% thresh - Threshold of standard deviation to decide if a\n% block is a ridge region (Try a value 0.1 - 0.2)\n%\n% Returns: normim - Image where the ridge regions are renormalised to\n% have zero mean, unit standard deviation.\n% mask - Mask indicating ridge-like regions of the image, \n% 0 for non ridge regions, 1 for ridge regions.\n% maskind - Vector of indices of locations within the mask. \n%\n% Suggested values for a 500dpi fingerprint image:\n%\n% [normim, mask, maskind] = ridgesegment(im, 16, 0.1)\n%\n% See also: RIDGEORIENT, RIDGEFREQ, RIDGEFILTER\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% January 2005\n\n\nfunction [normim, mask, maskind] = ridgesegment(im, blksze, thresh)\n \n im = normalise(im,0,1); % normalise to have zero mean, unit std dev\n \n fun = inline('std(x(:))*ones(size(x))');\n \n stddevim = blkproc(im, [blksze blksze], fun);\n \n mask = stddevim > thresh;\n maskind = find(mask);\n \n % Renormalise image so that the *ridge regions* have zero mean, unit\n % standard deviation.\n im = im - mean(im(maskind));\n normim = im/std(im(maskind)); \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "plotridgeorient.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FingerPrints/plotridgeorient.m", "size": 1898, "source_encoding": "utf_8", "md5": "830409dd2081c8e49dec602b704f949d", "text": "% PLOTRIDGEORIENT - plot of ridge orientation data\r\n%\r\n% Usage: plotridgeorient(orient, spacing, im, figno)\r\n%\r\n% orientim - Ridge orientation image (obtained from RIDGEORIENT)\r\n% spacing - Sub-sampling interval to be used in ploting the\r\n% orientation data the (Plotting every point is\r\n% typically not feasible) \r\n% im - Optional fingerprint image in which to overlay the\r\n% orientation plot.\r\n% figno - Optional figure number for plot\r\n%\r\n% A spacing of about 20 is recommended for a 500dpi fingerprint image\r\n%\r\n% See also: RIDGEORIENT, RIDGEFREQ, FREQEST, RIDGESEGMENT\r\n\r\n% Peter Kovesi \r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% pk at csse uwa edu au\r\n% http://www.csse.uwa.edu.au/~pk\r\n%\r\n% January 2005\r\n\r\nfunction plotridgeorient(orient, spacing, im, figno)\r\n\r\n if fix(spacing) ~= spacing\r\n\terror('spacing must be an integer');\r\n end\r\n \r\n [rows, cols] = size(orient);\r\n \r\n lw = 2; % linewidth\r\n len = 0.8*spacing; % length of orientation lines\r\n\r\n % Subsample the orientation data according to the specified spacing\r\n\r\n s_orient = orient(spacing:spacing:rows-spacing, ...\r\n\t\t spacing:spacing:cols-spacing);\r\n\r\n xoff = len/2*cos(s_orient);\r\n yoff = len/2*sin(s_orient); \r\n \r\n if nargin >= 3 % Display fingerprint image\r\n\tif nargin == 4\r\n\t show(im, figno); hold on\r\n\telse\r\n\t show(im); hold on\r\n\tend\r\n end\r\n \r\n % Determine placement of orientation vectors\r\n [x,y] = meshgrid(spacing:spacing:cols-spacing, ...\r\n\t\t spacing:spacing:rows-spacing);\r\n \r\n x = x-xoff;\r\n y = y-yoff;\r\n \r\n % Orientation vectors\r\n u = xoff*2;\r\n v = yoff*2;\r\n \r\n quiver(x,y,u,v,0,'.','linewidth',1, 'color','r');\r\n \r\n axis equal, axis ij, hold off\r\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ridgeorient.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FingerPrints/ridgeorient.m", "size": 4785, "source_encoding": "utf_8", "md5": "d0a1e0389d1ba0031b88a48553cbba9f", "text": "% RIDGEORIENT - Estimates the local orientation of ridges in a fingerprint\n%\n% Usage: [orientim, reliability, coherence] = ridgeorientation(im, gradientsigma,...\n% blocksigma, ...\n% orientsmoothsigma)\n%\n% Arguments: im - A normalised input image.\n% gradientsigma - Sigma of the derivative of Gaussian\n% used to compute image gradients.\n% blocksigma - Sigma of the Gaussian weighting used to\n% sum the gradient moments.\n% orientsmoothsigma - Sigma of the Gaussian used to smooth\n% the final orientation vector field. \n% Optional: if ommitted it defaults to 0\n% \n% Returns: orientim - The orientation image in radians.\n% Orientation values are +ve clockwise\n% and give the direction *along* the\n% ridges.\n% reliability - Measure of the reliability of the\n% orientation measure. This is a value\n% between 0 and 1. I think a value above\n% about 0.5 can be considered 'reliable'.\n% reliability = 1 - Imin./(Imax+.001);\n% coherence - A measure of the degree to which the local\n% area is oriented.\n% coherence = ((Imax-Imin)./(Imax+Imin)).^2;\n%\n% With a fingerprint image at a 'standard' resolution of 500dpi suggested\n% parameter values might be:\n%\n% [orientim, reliability] = ridgeorient(im, 1, 3, 3);\n%\n% See also: RIDGESEGMENT, RIDGEFREQ, RIDGEFILTER\n\n% May 2003 Original version by Raymond Thai, \n% January 2005 Reworked by Peter Kovesi \n% October 2011 Added coherence computation and orientsmoothsigma made optional\n%\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n\n\nfunction [orientim, reliability, coherence] = ...\n ridgeorient(im, gradientsigma, blocksigma, orientsmoothsigma)\n \n if ~exist('orientsmoothsigma', 'var'), orientsmoothsigma = 0; end\n [rows,cols] = size(im);\n \n % Calculate image gradients.\n sze = fix(6*gradientsigma); if ~mod(sze,2); sze = sze+1; end\n f = fspecial('gaussian', sze, gradientsigma); % Generate Gaussian filter.\n [fx,fy] = gradient(f); % Gradient of Gausian.\n \n Gx = filter2(fx, im); % Gradient of the image in x\n Gy = filter2(fy, im); % ... and y\n \n % Estimate the local ridge orientation at each point by finding the\n % principal axis of variation in the image gradients.\n \n Gxx = Gx.^2; % Covariance data for the image gradients\n Gxy = Gx.*Gy;\n Gyy = Gy.^2;\n \n % Now smooth the covariance data to perform a weighted summation of the\n % data.\n sze = fix(6*blocksigma); if ~mod(sze,2); sze = sze+1; end \n f = fspecial('gaussian', sze, blocksigma);\n Gxx = filter2(f, Gxx); \n Gxy = 2*filter2(f, Gxy);\n Gyy = filter2(f, Gyy);\n \n % Analytic solution of principal direction\n denom = sqrt(Gxy.^2 + (Gxx - Gyy).^2) + eps;\n sin2theta = Gxy./denom; % Sine and cosine of doubled angles\n cos2theta = (Gxx-Gyy)./denom;\n\n if orientsmoothsigma\n sze = fix(6*orientsmoothsigma); if ~mod(sze,2); sze = sze+1; end \n f = fspecial('gaussian', sze, orientsmoothsigma); \n cos2theta = filter2(f, cos2theta); % Smoothed sine and cosine of\n sin2theta = filter2(f, sin2theta); % doubled angles\n end\n \n orientim = pi/2 + atan2(sin2theta,cos2theta)/2;\n \n % Calculate 'reliability' of orientation data. Here we calculate the area\n % moment about the orientation axis found (this will be the minimum moment)\n % and an axis perpendicular (which will be the maximum moment). The\n % reliability measure is given by 1.0-min_moment/max_moment. The reasoning\n % being that if the ratio of the minimum to maximum moments is close to one\n % we have little orientation information.\n \n Imin = (Gyy+Gxx)/2 - (Gxx-Gyy).*cos2theta/2 - Gxy.*sin2theta/2;\n Imax = Gyy+Gxx - Imin;\n \n reliability = 1 - Imin./(Imax+.001);\n coherence = ((Imax-Imin)./(Imax+Imin)).^2;\n \n % Finally mask reliability to exclude regions where the denominator\n % in the orientation calculation above was small. Here I have set\n % the value to 0.001, adjust this if you feel the need\n reliability = reliability.*(denom>.001);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "testfin.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FingerPrints/Docs/testfin.m", "size": 1759, "source_encoding": "utf_8", "md5": "8bd1035571269c92bbeebfee58b37d75", "text": "% TESTFIN \n%\n% Function to demonstrate use of fingerprint code\n%\n% Usage: [newim, binim, mask, reliability] = testfin(im);\n%\n% Argument: im - Fingerprint image to be enhanced.\n%\n% Returns: newim - Ridge enhanced image.\n% binim - Binary version of enhanced image.\n% mask - Ridge-like regions of the image\n% reliability - 'Reliability' of orientation data\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% January 2005\n\n\nfunction [newim, binim, mask, reliability] = testfin(im)\n \n if nargin == 0\n\tim = imread('finger.png');\n end\n \n % Identify ridge-like regions and normalise image\n blksze = 16; thresh = 0.1;\n [normim, mask] = ridgesegment(im, blksze, thresh);\n show(normim,1);\n \n % Determine ridge orientations\n [orientim, reliability] = ridgeorient(normim, 1, 5, 5);\n plotridgeorient(orientim, 20, im, 2)\n show(reliability,6)\n \n % Determine ridge frequency values across the image\n blksze = 36; \n [freq, medfreq] = ridgefreq(normim, mask, orientim, blksze, 5, 5, 15);\n show(freq,3) \n \n % Actually I find the median frequency value used across the whole\n % fingerprint gives a more satisfactory result...\n freq = medfreq.*mask;\n \n % Now apply filters to enhance the ridge pattern\n newim = ridgefilter(normim, orientim, freq, 0.5, 0.5, 1);\n show(newim,4);\n \n % Binarise, ridge/valley threshold is 0\n binim = newim > 0;\n show(binim,5);\n\n % Display binary image for where the mask values are one and where\n % the orientation reliability is greater than 0.5\n show(binim.*mask.*(reliability>0.5), 7)\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "adjcontrast.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/GreyTrans/adjcontrast.m", "size": 1772, "source_encoding": "utf_8", "md5": "df466fd21398669febf7971b25906279", "text": "% ADJCONTRAST - Adjusts image contrast using sigmoid function.\n%\n% function g = adjcontrast(im, gain, cutoff)\n%\n% Arguments:\n% im - image to be processed.\n% gain - controls the actual contrast; \n% A value of about 5 is neutral (little change).\n% A value of 1 reduces contrast to about 20% of original\n% A value of 10 increases contrast about 2.5x.\n% a reasonable range of values to experiment with.\n% cutoff - represents the (normalised) grey value about which\n% contrast is increased or decreased. An initial\n% value you might use is 0.5 (the midpoint of the\n% greyscale) but different images may require\n% different points of the greyscale to be enhanced. \n\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% July 2001\n\nfunction newim = adjcontrast(im, gain, cutoff)\n\n if isa(im,'uint8');\n\tnewim = double(im);\n else \n\tnewim = im;\n end\n \t\n % rescale range 0-1\n newim = newim-min(min(newim));\n newim = newim./max(max(newim));\n\n newim = 1./(1 + exp(gain*(cutoff-newim))); % Apply Sigmoid function\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "histtruncate.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/GreyTrans/histtruncate.m", "size": 4297, "source_encoding": "utf_8", "md5": "8662c6c4ad1997ffd87d3053e4425473", "text": "% HISTTRUNCATE - Truncates ends of an image histogram.\n%\n% Function truncates a specified percentage of the lower and\n% upper ends of an image histogram.\n%\n% This operation allows grey levels to be distributed across\n% the primary part of the histogram. This solves the problem\n% when one has, say, a few very bright values in the image which\n% have the overall effect of darkening the rest of the image after\n% rescaling.\n%\n% Usage: \n% [newim, sortv] = histtruncate(im, lHistCut, uHistCut)\n% [newim, sortv] = histtruncate(im, lHistCut, uHistCut, sortv)\n%\n% Arguments:\n% im - Image to be processed\n% lHistCut - Percentage of the lower end of the histogram\n% to saturate.\n% uHistCut - Percentage of the upper end of the histogram\n% to saturate. If omitted or empty defaults to the value\n% for lHistCut.\n% sortv - Optional array of sorted image pixel values obtained\n% from a previous call to histtruncate. Supplying this\n% data speeds the operation of histtruncate when one is\n% repeatedly varying lHistCut and uHistCut.\n%\n% Returns:\n% newim - Image with values clipped at the specified histogram\n% fraction values. If the input image was colour the\n% lightness values are clipped and stretched to the range\n% 0-1. If the input image is greyscale no stretching is\n% applied. You may want to use NORMAALISE to achieve this\n% sortv - Sorted image values for reuse in subsequent calls to\n% histruncate.\n%\n% See also: NORMALISE\n\n% Copyright (c) 2001-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.cet.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% July 2001 - Original version\n% February 2012 - Added handling of NaN values in image\n% February 2014 - Code cleanup\n% September 2014 - Default for uHistCut + cleanup\n\nfunction [newim, sortv] = histtruncate(im, lHistCut, uHistCut, sortv)\n \n if ~exist('uHistCut', 'var') || isempty(uHistCut), uHistCut = lHistCut; end\n\n if lHistCut < 0 | lHistCut > 100 | uHistCut < 0 | uHistCut > 100\n\terror('Histogram truncation values must be between 0 and 100');\n end\n \n if ~exist('sortv', 'var'), sortv = []; end\n\n if ndims(im) == 3 % Assume colour image in RGB\n\thsv = rgb2hsv(im); % Convert to HSV \n % Apply histogram truncation just to intensity component\n [hsv(:,:,3), sortv] = Ihisttruncate(hsv(:,:,3), lHistCut, uHistCut, sortv);\n\n % Stretch intensity component to 0-1\n hsv(:,:,3) = normalise(hsv(:,:,3));\n\tnewim = hsv2rgb(hsv); % Convert back to RGB\n \n else\n [newim, sortv] = Ihisttruncate(im, lHistCut, uHistCut, sortv);\n end\n \n \n%-----------------------------------------------------------------------\n% Internal function that does the work\n%-----------------------------------------------------------------------\n \nfunction [im, sortv] = Ihisttruncate(im, lHistCut, uHistCut, sortv)\n \n if ndims(im) > 2\n\terror('HISTTRUNCATE only defined for grey value images');\n end\n \n % Generate a sorted array of pixel values or use supplied values\n if isempty(sortv)\n sortv = sort(im(:));\n end\n \n % Any NaN values end up at the end of the sorted list. We need to\n % eliminate these\n sortv = sortv(~isnan(sortv));\n N = length(sortv(:));\n \n % Compute indicies corresponding to specified upper and lower fractions\n % of the histogram.\n lind = floor(1 + N*lHistCut/100);\n hind = ceil(N - N*uHistCut/100);\n\n low_in = sortv(lind);\n high_in = sortv(hind);\n\n % Adjust image\n im(im < low_in) = low_in;\n im(im > high_in) = high_in;\n \n % Normalise? normalise with NaNs?\n \n\n \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "adjgamma.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/GreyTrans/adjgamma.m", "size": 1278, "source_encoding": "utf_8", "md5": "7923fe5b3ada0cd08b5edf5528839448", "text": "% ADJGAMMA - Adjusts image gamma.\n%\n% function g = adjgamma(im, g)\n%\n% Arguments:\n% im - image to be processed.\n% g - image gamma value.\n% Values in the range 0-1 enhance contrast of bright\n% regions, values > 1 enhance contrast in dark\n% regions. \n\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% July 2001\n\nfunction newim = adjgamma(im, g)\n\n if g <= 0\n\terror('Gamma value must be > 0');\n end\n\n if isa(im,'uint8');\n\tnewim = double(im);\n else \n\tnewim = im;\n end\n \t\n % rescale range 0-1\n newim = newim-min(min(newim));\n newim = newim./max(max(newim));\n \n newim = newim.^(1/g); % Apply gamma function\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "histeqfloat.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/GreyTrans/histeqfloat.m", "size": 2523, "source_encoding": "utf_8", "md5": "c9d2c9d7f401952ba393c03926112405", "text": "% HISTEQFLOAT Floating point image histogram equalisation\n%\n% Histogram equalisation for images containing floating point values. The number\n% of distinct values in the output image will be the same as the number of\n% distinct values in the input image.\n%\n% Usage: nim = histeqfloat(im, nbins)\n%\n% Arguments: im - Image to be equalised.\n% nbins - Number of bins to use in forming the histogram. Defaults\n% to 256.\n%\n% Returns: nim - Histogram equalised image.\n%\n% This function differs from classical histogram equalisation functions in that\n% the cumulative histogram of the image grey values is treated as forming a set\n% of points on the cumulative distribution function. The key point being that\n% it is used as a *function* rather than as a lookup table for mapping input\n% grey values to their output values. Under this approach, for images\n% containing floating point values, the number of distinct values in the output\n% image will be the same as the number of distinct values in the input image.\n% This can result in a significant improvement in output compared to HISTEQ\n%\n% For integer valued images the number of distinct values in the output image\n% must be less than, or equal to, the number of distinct values in the input\n% image (typically much less than).\n%\n% See also: HISTEQ\n\n% Copyright (c) 2012 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2012\n\nfunction nim = histeqfloat(im, nbins)\n \n if ~exist('nbins', 'var'), nbins = 256; end\n \n im = normalise(im); % Adjust image range 0-1\n \n % Compute histogram bin centres and form histogram\n centres = [1/nbins/2 : 1/nbins : 1-1/nbins/2];\n n = hist(im(:), centres);\n\n n = cumsum(n/sum(n)); % Cumulative sum of normalised histogram\n \n % Use 1D spline interpolation on the cumulative histogram to map image\n % values to their new ones, then reshape the image back to its original\n % size.\n nim = reshape(interp1(centres, n, im(:), 'spline'), size(im));\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "extractfields.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/GreyTrans/extractfields.m", "size": 3195, "source_encoding": "utf_8", "md5": "fc2a0b4ffe621599238d4558ebbab88e", "text": "% EXTRACTFIELDS - Separates fields from a video frame.\n%\n% Function to separate fields from a video frame\n% and (optionally) interpolate intermediate lines\n% for each field.\n%\n% Usage: [f1, f2] = extractfields(im,interp)\n%\n% f1 and f2 are the odd and even fields\n% im is the frame to be split\n% interp is an optional string `interp' indicating\n% whether f1 and f2 should be padded out with interpolated\n% lines.\n\n% Copyright (c) 2000 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2000\n% June 2014 Fixed class of returned image for colour images\n\nfunction [f1, f2] = extractfields(im, interpstring)\n \n if nargin < 2\n\tinterpstring = 'nointerp';\n end\n \n if (ndims(im)==3), % A colour image - Transform red, green, blue components separately\n\t[f1r, f2r] = extractFieldsI(im(:,:,1), interpstring);\n\t[f1g, f2g] = extractFieldsI(im(:,:,2), interpstring);\n\t[f1b, f2b] = extractFieldsI(im(:,:,3), interpstring);\n\n if strcmp(class(im),'double')\n f1 = zeros([size(f1r),3]);\n f1(:,:,1) = f1r;\n f1(:,:,2) = f1g;\n f1(:,:,3) = f1b;\n \n f2 = zeros([size(f2r),3]);\n f2(:,:,1) = f2r;\n f2(:,:,2) = f2g;\n f2(:,:,3) = f2b; \n else\n \n % Reform colour image for field 1\n f1 = repmat(uint8(0),[size(f1r),3]);\n f1(:,:,1) = uint8(round(f1r));\n f1(:,:,2) = uint8(round(f1g));\n f1(:,:,3) = uint8(round(f1b));\n \n % Reform colour image for field 2\n f2 = repmat(uint8(0),[size(f2r),3]);\n f2(:,:,1) = uint8(round(f2r));\n f2(:,:,2) = uint8(round(f2g));\n f2(:,:,3) = uint8(round(f2b));\n \n end\n \n else % Assume grey scale image\n\t[f1, f2] = extractFieldsI(im,interpstring);\n end\n \n%-------------------------------------------------------------- \nfunction [f1, f2] = extractFieldsI(im, interpstring)\n \n [rows,cols] = size(im);\n im = double(im);\n if nargin==2\n\tif strcmp(interpstring, 'interp')\n\t interp = 1;\n\telseif strcmp(interpstring, 'nointerp')\n\t interp = 0;\n\telse\n\t warning(['unknown interpolation option - no interpolation is' ...\n\t\t ' being used']);\n\t interp = 0;\n\tend\n else\n\tinterp = 0;\n end\n \n \n if mod(rows,2) == 1\n\trows = rows-1; % This ensures even and odd fields end up with \n end % the same No of rows\n \n f1 = im(1:2:rows,:); % odd lines\n f2 = im(2:2:rows,:); % even lines\n \n if interp\n\tf1 = interpfields(f1,'odd');\n\tf2 = interpfields(f2,'even');\n end\n \n \n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "interpfields.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/GreyTrans/interpfields.m", "size": 2616, "source_encoding": "utf_8", "md5": "995c2497c2bd2f01a7fc72cc0c552c7e", "text": "% INTERPFIELDS - Interpolates lines on a field extracted from a video frame.\n%\n% Function to interpolate intermediate lines on odd or even\n% fields extracted from a video frame\n%\n% Usage: intp = interpfields(field, oddeven);\n%\n%\n% Arguments: field - the field to be interpolated\n% oddeven - optional flag 1/0 indicating whether the field\n% is formed from the odd rows (default is 1)\n%\n% Returns: interp - an image with extra rows inserted. These rows are\n% obtained by averaging the rows above and below.\n% A future enhancement might be to use bicubic\n% interpolation.\n\n% Copyright (c) 2000-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2000 - original version\n% March 2004 - modified to use bicubic interpolation and to work for\n% colour images\n% August 2004 - Corrected No of rows to interpolate to avoid NaNs in the result\n% August 2005 - Made compatible under Octave\n\nfunction intp = interpfields(field, oddeven);\n\n v = version; Octave = v(1)<'5'; % Crude Octave test\n \n if nargin==2\n\tif strcmp(oddeven, 'odd')\n\t odd = 1;\n\telse\n\t odd = 0;\n\tend\n else % assume odd field\n\todd = 1;\n end\n \n field = double(field);\n if ndims(field) == 3\n\t[rows, cols, depth] = size(field);\n elseif ndims(field) == 2\n\t[rows, cols] = size(field);\n\tdepth = 1;\n else\n\terror('can only interpolate greyscale or colour images');\n end\n \n intp = zeros(2*rows-1,cols,depth); \n \n [x,y] = meshgrid(1:cols,1:2:2*rows-1); % coords at which data is defined.\n [xi,yi] = meshgrid(1:cols,1:2*rows-1); % coords where we want data defined.\n \n for d = 1:depth\n\tif Octave\n\t intp(:,:,d) = interp2(x,y,field(:,:,d),xi,yi,'linear'); \n\telse\n\t intp(:,:,d) = interp2(x,y,field(:,:,d),xi,yi,'bicubic'); \n\tend\n end\n \n if odd % pad an extra row at the bottom\n\tintp = [intp; field(rows,:,:)];\n else\n\tintp = [field(1,:,:); intp ]; % pad an extra row at the top\n end\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "agc.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/GreyTrans/agc.m", "size": 3871, "source_encoding": "utf_8", "md5": "e4153ae09348114147d2cd732b327195", "text": "% AGC Automatic Gain Control for geophysical images\n%\n% Usage: agcim = agc(im, sigma, p, r)\n%\n% Arguments: im - The input image. NaNs in the image are handled\n% automatically. \n% sigma - The standard deviation of the Gaussian filter used to\n% determine local image mean values and to perform the\n% summation used to determine the local gain values.\n% Sigma is specified in pixels, try experimenting with a\n% wide range of values. \n% p - The power used to compute the p-norm of the local image\n% region. The gain is obtained from the p-norm. If\n% unspecified its value defaults to 2 and r defaults to 0.5\n% r - Normally r = 1/p (and it defaults to this) but it can\n% specified separately to achieve specific results. See\n% Rajagopalan's papers.\n%\n% Returns: agcim - The Automatic Gain Controlled image.\n%\n% The algorithm is based on Shanti Rajagopalan's papers, referenced below, with\n% a couple of differences.\n%\n% 1) The gain is computed from the difference between the image and its local\n% mean. The aim of this is to avoid any local base-level issues and to allow\n% the code to be applied to a wide range of image types, not just magnetic\n% gradient data. The gain is applied to the difference between the image and\n% its local mean to obtain the final AGC image.\n%\n% 2) The computation of the local mean and the summation operations used to\n% compute the local gain is performed using Gaussian smoothing. The aim of this\n% is to avoid abrupt changes in gain as the summation window is moved across the\n% image. The effective window size is controlled by the value of sigma used to\n% specify the Gaussian filter.\n%\n% References:\n% * Shanti Rajagopalan \"The use of 'Automatic Gain Control' to Display Vertical\n% Magnetic Gradient Data\". 5th ASEG Conference 1987. pp 166-169\n%\n% * Shanti Rajagopalan and Peter Milligan. \"Image Enhancement of Aeromagnetic Data\n% using Automatic Gain Control\". Exploration Geophysics (1995) 25. pp 173-178\n\n% Copyright (c) 2012 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% April 2012 - Original version\n\nfunction agcim = agc(im, sigma, p, r)\n \n % Default values for p and r\n if ~exist('p', 'var'), p = 2; end\n if exist('p','var') & ~exist('r', 'var')\n r = 1/p;\n elseif ~exist('r', 'var')\n r = 0.5; \n end\n\n % Make provision for the image containing NaNs\n mask = ~isnan(im);\n if any(mask)\n im = fillnan(im);\n end\n \n % Get local mean by smoothing the image with a Gaussian filter\n h = fspecial('gaussian', 6*sigma, sigma);\n localMean = filter2(h, im);\n \n % Subtract image from local mean, raise to power 'p' then apply Gaussian\n % smoothing filter to obtain a local weighted sum. Finally raise the result\n % to power 'r' to obtain the 'gain'. Typically p = 2 and r = 0.5 which will\n % make gain equal to the local RMS. The abs() function is used to allow\n % for arbitrary 'p' and 'r'.\n gain = (filter2(h, abs(im-localMean).^p)).^r;\n \n % Apply inverse gain to the difference between the image and the local\n % mean to obtain the final AGC image. \n agcim = (im-localMean)./(gain + eps) .* mask; \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "normalise.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/GreyTrans/normalise.m", "size": 2312, "source_encoding": "utf_8", "md5": "5ea78a2901be537abb01b07cd78b3ddf", "text": "% NORMALISE - Normalises image values to 0-1, or to desired mean and variance\n%\n% Usage:\n% n = normalise(im)\n%\n% Offsets and rescales image so that the minimum value is 0\n% and the maximum value is 1. Result is returned in n. If the image is\n% colour the image is converted to HSV and the value/intensity component\n% is normalised to 0-1 before being converted back to RGB.\n%\n%\n% n = normalise(im, reqmean, reqvar)\n%\n% Arguments: im - A grey-level input image.\n% reqmean - The required mean value of the image.\n% reqvar - The required variance of the image.\n%\n% Offsets and rescales image so that it has mean reqmean and variance\n% reqvar. Colour images cannot be normalised in this manner.\n\n% Copyright (c) 1996-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% January 2005 - modified to allow desired mean and variance\n\n\nfunction n = normalise(im, reqmean, reqvar)\n\n if ~(nargin == 1 | nargin == 3)\n error('No of arguments must be 1 or 3');\n end\n \n if nargin == 1 % Normalise 0 - 1\n\tif ndims(im) == 3 % Assume colour image \n\t hsv = rgb2hsv(im);\n\t v = hsv(:,:,3);\n\t v = v - min(v(:)); % Just normalise value component\n\t v = v/max(v(:));\n\t hsv(:,:,3) = v;\n\t n = hsv2rgb(hsv);\n\telse % Assume greyscale \n\t if ~isa(im,'double'), im = double(im); end\n\t n = im - min(im(:));\n\t n = n/max(n(:));\n\tend\n\t\n else % Normalise to desired mean and variance\n\t\n\tif ndims(im) == 3 % colour image?\n\t error('cannot normalise colour image to desired mean and variance');\n\tend\n\n\tif ~isa(im,'double'), im = double(im); end\t\n\tim = im - mean(im(:)); \n\tim = im/std(im(:)); % Zero mean, unit std dev\n\n\tn = reqmean + im*sqrt(reqvar);\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "remapim.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/GreyTrans/remapim.m", "size": 2589, "source_encoding": "utf_8", "md5": "197534d04489cb4cfd3b0d641d848c0a", "text": "% REMAPIM - Remaps image intensity values\n%\n% Usage: newim = remapim(im, x, y, rescale)\n% \\\n% optional\n% Arguments\n% im - Image to be transformed.\n% x,y - Coordinates of spline control points that define the\n% mapping function. These coordinates are in the range\n% 0-1 and are typically obtained experimentally via the\n% function GREYTRANS\n% rescale - An optional flag (0 or 1) indicating whether image\n% values should be normalised to the range 0-1. \n% This is only provided for speed when called\n% by GREYTRANS. By default the input image will\n% be normalised to the range 0-1.\n%\n% Image intensity values are remapped to new values via a mapping\n% function defined by a series of spline points. The mapping function is\n% defined over the range 0-1, accordingly the input image is normalised\n% to the range 0-1. The output image will also lie in this range. \n\n% Copyright (c) 2002-2003 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% April 2002 - original version.\n% March 2003 - modified to work with colour images.\n\nfunction nim = remapim(im, x, y, rescale)\n\n if nargin < 4\n\trescale = 1;\n end\n \n if ndims(im)==3 % Assume we have a colour image\n hsv = rgb2hsv(im);\n % Apply remapping just to the value component\n hsv(:,:,3) = remap(hsv(:,:,3), x, y, rescale);\n nim = hsv2rgb(hsv);\n else % Assume we have a 2D greyscale image\n\tnim = remap(im, x, y, rescale);\n end\n\n\n% Internal function that does the work\n\nfunction nim = remap(im, x, y, rescale) \n\n if rescale\n\tim = normalise(im);\n end\n \n nim = spline(x,y,im); % Remap image values \n\n % clamp image values within bounds 0 - 1\n gt0 = nim > 0;\n nim = nim.*gt0; % values < 0 become 0\n \n lt1 = nim < 1;\n nim = nim.*lt1 + ~lt1; % values > 1 become 1\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "greytrans.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/GreyTrans/greytrans.m", "size": 4462, "source_encoding": "utf_8", "md5": "f2f1254324be1d786b5fee45794f6bca", "text": "% GREYTRANS - Interactive greyscale manipulation of an image (RGB or greyscale)\n%\n% Usage: [newim, x, y] = greytrans(im, npts)\n%\n% Arguments\n% im - Image to be transformed\n% npts - Optional number of control points of the spline\n% defining the mapping function. This defaults to 4 if\n% not specified.\n%\n% Returns:\n% newim - The transformed image.\n% x,y - Coordinates of spline control points that define the\n% mapping function. These coordinates can be passed\n% to the function REMAPIM if you want to apply the\n% transformation to other images.\n%\n% Image intensity values are remapped to new values via a mapping\n% function defined by a series of spline points. The mapping function is\n% defined over the range 0-1, accordingly the input image is normalised\n% to the range 0-1. The output image will also lie in this range. \n% Colour images are processed by first converting to HSV and then\n% remapping the Value component and then reconstructing new RGB values.\n\n% Copyright (c) 2002-2003 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% April 2002\n% March 2003 - modified to work with colour images.\n\nfunction [nim,x,y] = greytrans(im, npts)\n \n if nargin == 1\n\tnpts = 4; % default No of control points\n end\n\n if npts < 2\n\terror('Number of control points must be > 2');\n end\n \n x = [0:npts-1]/(npts-1); y = x;\n h = figure(1); clf\n% set(h,'Position',[150 100 800 550]), clf\n im = normalise(im); % rescale range 0 - 1\n him1 = subplot('Position',[.025 .28 .45 .7]);\n him2 = subplot('Position',[.525 .28 .45 .7]); \n hcp = subplot('Position',[.35 .03 .25 .25]);\n \n subplot(him1), imshow(im), title('Original Image'); \n subplot(him2), imshow(im), title('Remapped Image'); \n subplot(hcp), plotcurve(x,y);\n \n if ndims(im)==3 % Assume we have a colour image\n\tcolour = 1;\n hsv = rgb2hsv(im);\n\tv = hsv(:,:,3); % Extract the value - this is what we want to\n % remap\n else\n\tcolour = 0;\n end\n \n fprintf('Manipulate the mapping curve by clicking with the left mouse button.\\n');\n fprintf('The closest control point is moved to the digitised location.\\n');\n fprintf('Click any other button to exit\\n');\n \n but = 1;\n while but==1\n\tsubplot(hcp), [xp yp but] = ginput(1);\n\tif but ~= 1\n\t break;\n\tend\n\tind = indexOfClosestPt(xp,yp,x,y);\n\n\t% Make sure control points cannot 'cross' each other and keep\n % x-coords of end points at 0 and 1\n\tif ind > 1 & ind < npts\n\t if xp < x(ind-1)\n\t\tx(ind) = x(ind-1)+0.01;\n\t elseif xp > x(ind+1)\n\t\tx(ind) = x(ind+1)-0.01;\n\t else\n\t\tx(ind) = xp;\n\t end\n\telseif ind == 1\n\t x(ind) = 0;\n\telseif ind == npts\n\t x(ind) = 1;\n\tend\n\n\t% Make sure you cannot put control points too high or low...\n\tif yp > 1 \n\t yp = 1;\n\telseif yp < 0\n\t yp = 0;\n\tend\n\n\ty(ind) = yp;\n\t\n\tsubplot(hcp), plotcurve(x,y);\n\tif colour\n\t nv = remapim(v, x , y, 0); % Remap value component\n\t hsv(:,:,3) = nv; % Reconstruct colour image\n\t nim = hsv2rgb(hsv);\n\telse\n\t nim = remapim(im, x , y, 0);\n\tend\n\tsubplot(him2), imshow(nim), title('Remapped Image');\n\tdrawnow\n end\n \n%----------------------------------------------------------------\n% Function to find control point closest to digitised location\n\nfunction ind = indexOfClosestPt(xp,yp,x,y)\n dist = sqrt( (x-xp).^2 + (y-yp).^2 );\n [d,ind] = min(dist);\n\n%----------------------------------------------------------------\n% Function to plot mapping curve\n\nfunction plotcurve(x,y)\n xx = [0:.01:1]; \n yy = spline(x,y,xx); \n plot(x, y,'ro'); \n hold on\n plot(xx,yy);\n xlabel('input grey value');\n ylabel('output grey value'); \n title('Mapping Function');\n axis([0 1 0 1]), axis square\n drawnow\n hold off\n\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ransacfitfundmatrix7.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/ransacfitfundmatrix7.m", "size": 6338, "source_encoding": "utf_8", "md5": "e8bb75917201904ec6c3bdd4f36479f1", "text": "% RANSACFITFUNDMATRIX7 - fits fundamental matrix using RANSAC\n%\n% Usage: [F, inliers] = ransacfitfundmatrix7(x1, x2, t)\n%\n% This function requires Andrew Zisserman's 7 point fundamental matrix code. \n% See: http://www.robots.ox.ac.uk/~vgg/hzbook/code/\n%\n% Arguments:\n% x1 - 2xN or 3xN set of homogeneous points. If the data is\n% 2xN it is assumed the homogeneous scale factor is 1.\n% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.\n% t - The distance threshold between data point and the model\n% used to decide whether a point is an inlier or not. \n% Note that point coordinates are normalised to that their\n% mean distance from the origin is sqrt(2). The value of\n% t should be set relative to this, say in the range \n% 0.001 - 0.01 \n%\n% Note that it is assumed that the matching of x1 and x2 are putative and it\n% is expected that a percentage of matches will be wrong.\n%\n% Returns:\n% F - The 3x3 fundamental matrix such that x2'Fx1 = 0.\n% inliers - An array of indices of the elements of x1, x2 that were\n% the inliers for the best model.\n%\n% See Also: RANSAC, FUNDMATRIX, RANSACFITFUNDMATRIX\n\n% Copyright (c) 2004-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2004 Original version\n% August 2005 Distance error function changed to match changes in RANSAC\n% June 2009 Bug in the wrapper function fixed (thanks to Peter Corke)\n\nfunction [F, inliers] = ransacfitfundmatrix7(x1, x2, t, feedback)\n\n if ~all(size(x1)==size(x2))\n error('Data sets x1 and x2 must have the same dimension');\n end\n\n if nargin == 3\n\tfeedback = 0;\n end\n \n [rows,npts] = size(x1);\n if rows~=2 & rows~=3\n error('x1 and x2 must have 2 or 3 rows');\n end\n \n if rows == 2 % Pad data with homogeneous scale factor of 1\n x1 = [x1; ones(1,npts)];\n x2 = [x2; ones(1,npts)]; \n end\n \n % Normalise each set of points so that the origin is at centroid and\n % mean distance from origin is sqrt(2). normalise2dpts also ensures the\n % scale parameter is 1. Note that 'fundmatrix' will also call\n % 'normalise2dpts' but the code in 'ransac' that calls the distance\n % function will not - so it is best that we normalise beforehand.\n [x1, T1] = normalise2dpts(x1);\n [x2, T2] = normalise2dpts(x2);\n\n s = 7; % Number of points needed to fit a fundamental matrix using\n % a 7 point solution\n \n fittingfn = @vgg_F_from_7pts_wrapper; % Wrapper for AZ's code\n distfn = @funddist;\n degenfn = @isdegenerate;\n % x1 and x2 are 'stacked' to create a 6xN array for ransac\n [F, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback);\n\n % Now do a final least squares fit on the data points considered to\n % be inliers.\n F = fundmatrix(x1(:,inliers), x2(:,inliers));\n \n % Denormalise\n F = T2'*F*T1;\n\n \n%--------------------------------------------------------------------------\n% Function providing a wrapper for Andrew Zisserman's 7 point fundamental\n% matrix code. See: http://www.robots.ox.ac.uk/~vgg/hzbook/code/\n% This code takes inputs and returns output according to the requirements of\n% RANSAC\n \nfunction F = vgg_F_from_7pts_wrapper(x)\n \n Fvgg = vgg_F_from_7pts_2img(x(1:3,:), x(4:6,:));\n\n if isempty(Fvgg)\n\tF = [];\n\treturn;\n end\n \n % Store the (potentially) 3 solutions in a cell array\n [rows,cols,Nsolutions] = size(Fvgg);\n for n = 1:Nsolutions\n\tF{n} = Fvgg(:,:,n);\n end\n\n%--------------------------------------------------------------------------\n% Function to evaluate the first order approximation of the geometric error\n% (Sampson distance) of the fit of a fundamental matrix with respect to a\n% set of matched points as needed by RANSAC. See: Hartley and Zisserman,\n% 'Multiple View Geometry in Computer Vision', page 270.\n%\n% Note that this code allows for F being a cell array of fundamental matrices of\n% which we have to pick the best one. (A 7 point solution can return up to 3\n% solutions)\n\nfunction [bestInliers, bestF] = funddist(F, x, t);\n \n x1 = x(1:3,:); % Extract x1 and x2 from x\n x2 = x(4:6,:);\n \n \n if iscell(F) % We have several solutions each of which must be tested\n\t\t \n\tnF = length(F); % Number of solutions to test\n\tbestF = F{1}; % Initial allocation of best solution\n\tninliers = 0; % Number of inliers\n\t\n\tfor k = 1:nF\n\t x2tFx1 = zeros(1,length(x1));\n\t for n = 1:length(x1)\n\t\tx2tFx1(n) = x2(:,n)'*F{k}*x1(:,n);\n\t end\n\t \n\t Fx1 = F{k}*x1;\n\t Ftx2 = F{k}'*x2; \n\n\t % Evaluate distances\n\t d = x2tFx1.^2 ./ ...\n\t\t (Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);\n\t \n\t inliers = find(abs(d) < t); % Indices of inlying points\n\t \n\t if length(inliers) > ninliers % Record best solution\n\t\tninliers = length(inliers);\n\t\tbestF = F{k};\n\t\tbestInliers = inliers;\n\t end\n\tend\n \n else % We just have one solution\n\tx2tFx1 = zeros(1,length(x1));\n\tfor n = 1:length(x1)\n\t x2tFx1(n) = x2(:,n)'*F*x1(:,n);\n\tend\n\t\n\tFx1 = F*x1;\n\tFtx2 = F'*x2; \n\t\n\t% Evaluate distances\n\td = x2tFx1.^2 ./ ...\n\t (Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);\n\t\n\tbestInliers = find(abs(d) < t); % Indices of inlying points\n\tbestF = F; % Copy F directly to bestF\n\t\n end\n\t\n\n\n%----------------------------------------------------------------------\n% (Degenerate!) function to determine if a set of matched points will result\n% in a degeneracy in the calculation of a fundamental matrix as needed by\n% RANSAC. This function assumes this cannot happen...\n \nfunction r = isdegenerate(x)\n r = 0; \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "fitline3d.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/fitline3d.m", "size": 1247, "source_encoding": "utf_8", "md5": "1f7cee8975c9f96bfb8aa43046474e5f", "text": "% FITLINE3D - Fits a line to a set of 3D points\r\n%\r\n% Usage: [L] = fitline3d(XYZ)\r\n%\r\n% Where: XYZ - 3xNpts array of XYZ coordinates\r\n% [x1 x2 x3 ... xN;\r\n% y1 y2 y3 ... yN;\r\n% z1 z2 z3 ... zN]\r\n%\r\n% Returns: L - 3x2 matrix consisting of the two endpoints of the line\r\n% that fits the points. The line is centered about the\r\n% mean of the points, and extends in the directions of the\r\n% principal eigenvectors, with scale determined by the\r\n% eigenvalues.\r\n%\r\n% Author: Felix Duvallet (CMU)\r\n% August 2006\r\n\r\n\r\n\r\nfunction L = fitline3d(XYZ)\r\n\r\n% Since the covariance matrix should be 3x3 (not NxN), need\r\n% to take the transpose of the points.\r\nXYZ = XYZ';\r\n\r\n% find mean of the points\r\nmu = mean(XYZ, 1);\r\n\r\n% covariance matrix\r\nC = cov(XYZ);\r\n\r\n% get the eigenvalues and eigenvectors\r\n[V, D] = eig(C);\r\n\r\n% largest eigenvector is in the last column\r\ncol = size(V, 2); %get the number of columns\r\n\r\n% get the last eigenvector column and the last eigenvalue\r\neVec = V(:, col);\r\neVal = D(col, col);\r\n\r\n% start point - center about mean and scale eVector by eValue\r\nL(:, 1) = mu' - sqrt(eVal)*eVec;\r\n% end point\r\nL(:, 2) = mu' + sqrt(eVal)*eVec;\r\n\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ransacfitfundmatrix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/ransacfitfundmatrix.m", "size": 5544, "source_encoding": "utf_8", "md5": "b87d72c56902f27c573b6c545f6754ab", "text": "% RANSACFITFUNDMATRIX - fits fundamental matrix using RANSAC\n%\n% Usage: [F, inliers] = ransacfitfundmatrix(x1, x2, t)\n%\n% Arguments:\n% x1 - 2xN or 3xN set of homogeneous points. If the data is\n% 2xN it is assumed the homogeneous scale factor is 1.\n% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.\n% t - The distance threshold between data point and the model\n% used to decide whether a point is an inlier or not. \n% Note that point coordinates are normalised to that their\n% mean distance from the origin is sqrt(2). The value of\n% t should be set relative to this, say in the range \n% 0.001 - 0.01 \n%\n% Note that it is assumed that the matching of x1 and x2 are putative and it\n% is expected that a percentage of matches will be wrong.\n%\n% Returns:\n% F - The 3x3 fundamental matrix such that x2'Fx1 = 0.\n% inliers - An array of indices of the elements of x1, x2 that were\n% the inliers for the best model.\n%\n% See Also: RANSAC, FUNDMATRIX\n\n% Copyright (c) 2004-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2004 Original version\n% August 2005 Distance error function changed to match changes in RANSAC\n\nfunction [F, inliers] = ransacfitfundmatrix(x1, x2, t, feedback)\n\n if ~all(size(x1)==size(x2))\n error('Data sets x1 and x2 must have the same dimension');\n end\n \n if nargin == 3\n\tfeedback = 0;\n end\n \n [rows,npts] = size(x1);\n if rows~=2 & rows~=3\n error('x1 and x2 must have 2 or 3 rows');\n end\n \n if rows == 2 % Pad data with homogeneous scale factor of 1\n x1 = [x1; ones(1,npts)];\n x2 = [x2; ones(1,npts)]; \n end\n \n % Normalise each set of points so that the origin is at centroid and\n % mean distance from origin is sqrt(2). normalise2dpts also ensures the\n % scale parameter is 1. Note that 'fundmatrix' will also call\n % 'normalise2dpts' but the code in 'ransac' that calls the distance\n % function will not - so it is best that we normalise beforehand.\n [x1, T1] = normalise2dpts(x1);\n [x2, T2] = normalise2dpts(x2);\n\n s = 8; % Number of points needed to fit a fundamental matrix. Note that\n % only 7 are needed but the function 'fundmatrix' only\n % implements the 8-point solution.\n \n fittingfn = @fundmatrix;\n distfn = @funddist;\n degenfn = @isdegenerate;\n % x1 and x2 are 'stacked' to create a 6xN array for ransac\n [F, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback);\n\n % Now do a final least squares fit on the data points considered to\n % be inliers.\n F = fundmatrix(x1(:,inliers), x2(:,inliers));\n \n % Denormalise\n F = T2'*F*T1;\n \n%--------------------------------------------------------------------------\n% Function to evaluate the first order approximation of the geometric error\n% (Sampson distance) of the fit of a fundamental matrix with respect to a\n% set of matched points as needed by RANSAC. See: Hartley and Zisserman,\n% 'Multiple View Geometry in Computer Vision', page 270.\n%\n% Note that this code allows for F being a cell array of fundamental matrices of\n% which we have to pick the best one. (A 7 point solution can return up to 3\n% solutions)\n\nfunction [bestInliers, bestF] = funddist(F, x, t);\n \n x1 = x(1:3,:); % Extract x1 and x2 from x\n x2 = x(4:6,:);\n \n \n if iscell(F) % We have several solutions each of which must be tested\n\t\t \n\tnF = length(F); % Number of solutions to test\n\tbestF = F{1}; % Initial allocation of best solution\n\tninliers = 0; % Number of inliers\n\t\n\tfor k = 1:nF\n\t x2tFx1 = zeros(1,length(x1));\n\t for n = 1:length(x1)\n\t\tx2tFx1(n) = x2(:,n)'*F{k}*x1(:,n);\n\t end\n\t \n\t Fx1 = F{k}*x1;\n\t Ftx2 = F{k}'*x2; \n\n\t % Evaluate distances\n\t d = x2tFx1.^2 ./ ...\n\t\t (Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);\n\t \n\t inliers = find(abs(d) < t); % Indices of inlying points\n\t \n\t if length(inliers) > ninliers % Record best solution\n\t\tninliers = length(inliers);\n\t\tbestF = F{k};\n\t\tbestInliers = inliers;\n\t end\n\tend\n \n else % We just have one solution\n\tx2tFx1 = zeros(1,length(x1));\n\tfor n = 1:length(x1)\n\t x2tFx1(n) = x2(:,n)'*F*x1(:,n);\n\tend\n\t\n\tFx1 = F*x1;\n\tFtx2 = F'*x2; \n\t\n\t% Evaluate distances\n\td = x2tFx1.^2 ./ ...\n\t (Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);\n\t\n\tbestInliers = find(abs(d) < t); % Indices of inlying points\n\tbestF = F; % Copy F directly to bestF\n\t\n end\n\t\n\n\n%----------------------------------------------------------------------\n% (Degenerate!) function to determine if a set of matched points will result\n% in a degeneracy in the calculation of a fundamental matrix as needed by\n% RANSAC. This function assumes this cannot happen...\n \nfunction r = isdegenerate(x)\n r = 0; \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ransacfitaffinefund.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/ransacfitaffinefund.m", "size": 4443, "source_encoding": "utf_8", "md5": "1f0e4e13663302b2d953db1e18f9ffe2", "text": "% RANSACFITAFFINEFUND - fits affine fundamental matrix using RANSAC\n%\n% Usage: [F, inliers] = ransacfitaffinefund(x1, x2, t)\n%\n% Arguments:\n% x1 - 2xN or 3xN set of homogeneous points. If the data is\n% 2xN it is assumed the homogeneous scale factor is 1.\n% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.\n% t - The distance threshold between data point and the model\n% used to decide whether a point is an inlier or not. \n% Note that point coordinates are normalised to that their\n% mean distance from the origin is sqrt(2). The value of\n% t should be set relative to this, say in the range \n% 0.001 - 0.01 \n%\n% Note that it is assumed that the matching of x1 and x2 are putative and it\n% is expected that a percentage of matches will be wrong.\n%\n% Returns:\n% F - The 3x3 fundamental matrix such that x2'Fx1 = 0.\n% inliers - An array of indices of the elements of x1, x2 that were\n% the inliers for the best model.\n%\n% See Also: RANSAC, FUNDMATRIX AFFINEFUNDMATRIX\n\n% Copyright (c) 2004-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2004 Original version\n% August 2005 Distance error function changed to match changes in RANSAC\n\nfunction [F, inliers] = ransacfitaffinefund(x1, x2, t, feedback)\n\n if ~all(size(x1)==size(x2))\n error('Data sets x1 and x2 must have the same dimension');\n end\n \n if nargin == 3\n\tfeedback = 0;\n end\n \n [rows,npts] = size(x1);\n if rows~=2 & rows~=3\n error('x1 and x2 must have 2 or 3 rows');\n end\n \n if rows == 2 % Pad data with homogeneous scale factor of 1\n x1 = [x1; ones(1,npts)];\n x2 = [x2; ones(1,npts)]; \n end\n \n % Normalise each set of points so that the origin is at centroid and\n % mean distance from origin is sqrt(2). normalise2dpts also ensures the\n % scale parameter is 1. Note that 'fundmatrix' will also call\n % 'normalise2dpts' but the code in 'ransac' that calls the distance\n % function will not - so it is best that we normalise beforehand.\n [x1, T1] = normalise2dpts(x1);\n [x2, T2] = normalise2dpts(x2);\n\n s = 4; % Number of points needed to fit an affine fundamental matrix. \n \n fittingfn = @affinefundmatrix;\n distfn = @funddist;\n degenfn = @isdegenerate;\n % x1 and x2 are 'stacked' to create a 6xN array for ransac\n [F, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback);\n\n % Now do a final least squares fit on the data points considered to\n % be inliers.\n F = affinefundmatrix(x1(:,inliers), x2(:,inliers));\n \n % Denormalise\n F = T2'*F*T1;\n \n%--------------------------------------------------------------------------\n% Function to evaluate the first order approximation of the geometric error\n% (Sampson distance) of the fit of a fundamental matrix with respect to a\n% set of matched points as needed by RANSAC. See: Hartley and Zisserman,\n% 'Multiple View Geometry in Computer Vision', page 270.\n\nfunction [inliers, F] = funddist(F, x, t);\n \n x1 = x(1:3,:); % Extract x1 and x2 from x\n x2 = x(4:6,:);\n \n x2tFx1 = zeros(1,length(x1));\n for n = 1:length(x1)\n\tx2tFx1(n) = x2(:,n)'*F*x1(:,n);\n end\n \n Fx1 = F*x1;\n Ftx2 = F'*x2; \n \n % Evaluate distances\n d = x2tFx1.^2 ./ ...\n\t (Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);\n \n inliers = find(abs(d) < t); % Indices of inlying points\n \n\n%----------------------------------------------------------------------\n% (Degenerate!) function to determine if a set of matched points will result\n% in a degeneracy in the calculation of a fundamental matrix as needed by\n% RANSAC. This function assumes this cannot happen...\n \nfunction r = isdegenerate(x)\n r = 0; \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "fitplane.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/fitplane.m", "size": 1694, "source_encoding": "utf_8", "md5": "a058a2453754cff9ea42776f1034436a", "text": "% FITPLANE - solves coefficients of plane fitted to 3 or more points\n%\n% Usage: B = fitplane(XYZ)\n%\n% Where: XYZ - 3xNpts array of xyz coordinates to fit plane to. \n% If Npts is greater than 3 a least squares solution \n% is generated.\n%\n% Returns: B - 4x1 array of plane coefficients in the form\n% b(1)*X + b(2)*Y +b(3)*Z + b(4) = 0\n% The magnitude of B is 1.\n%\n% See also: RANSACFITPLANE\n\n% Copyright (c) 2003-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% June 2003\n\nfunction B = fitplane(XYZ)\n \n [rows,npts] = size(XYZ); \n \n if rows ~=3\n error('data is not 3D');\n end\n \n if npts < 3\n error('too few points to fit plane');\n end\n \n % Set up constraint equations of the form AB = 0,\n % where B is a column vector of the plane coefficients\n % in the form b(1)*X + b(2)*Y +b(3)*Z + b(4) = 0.\n \n A = [XYZ' ones(npts,1)]; % Build constraint matrix\n \n if npts == 3 % Pad A with zeros\n A = [A; zeros(1,4)]; \n end\n\n [u d v] = svd(A); % Singular value decomposition.\n B = v(:,4); % Solution is last column of v.\n\n\n\n \n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "randomsample.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/randomsample.m", "size": 2218, "source_encoding": "utf_8", "md5": "d672616e8ac80b56f5cb91ac584537d8", "text": "% RANDOMSAMPLE - selects n random items from an array\n%\n% Usage: items = randomsample(a, n)\n%\n% Arguments: a - Either an array of values from which the items are to\n% be selected, or an integer in which case the items\n% are values selected from the array [1:a]\n% n - The number of items to be selected.\n%\n%\n% This function can be used as a basic replacement for RANDSAMPLE for those\n% who do not have the statistics toolbox.\n% Also,\n% r = randomsample(n,n) will give a random permutation of the integers 1:n \n%\n% See also: RANSAC\n\n% Strategy is to generate a random integer index into the array and select that\n% item from the array. The selected element in the array is then overwritten by\n% the last element in the array and the process is then repeated except that\n% when we select the next element we generate a random integer index that lies\n% in the range 1 to arraylength - 1, and so on. This ensures items are not\n% repeated.\n\n% Copyright (c) 2006 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au \n% http://www.csse.uwa.edu.au/~pk\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2006 \n\n\n\nfunction item = randomsample(a, n)\n \n npts = length(a);\n\n if npts == 1 % We have a scalar argument for a\n\tnpts = a;\n\ta = [1:a]; % Construct an array 1:a\n end\n \n if npts < n\n\terror(...\n\tsprintf('Trying to select %d items from a list of length %d',n, npts));\n end\n \n item = zeros(1,n);\n \n for i = 1:n\n\t% Generate random value in the appropriate range \n\tr = ceil((npts-i+1).*rand);\n\titem(i) = a(r); % Select the rth element from the list\n\ta(r) = a(end-i+1); % Overwrite selected element\n end % ... and repeat"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "iscolinear.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/iscolinear.m", "size": 2318, "source_encoding": "utf_8", "md5": "65025b7413f8f6b4cb16dd1689a5900f", "text": "% ISCOLINEAR - are 3 points colinear\n%\n% Usage: r = iscolinear(p1, p2, p3, flag)\n%\n% Arguments:\n% p1, p2, p3 - Points in 2D or 3D.\n% flag - An optional parameter set to 'h' or 'homog'\n% indicating that p1, p2, p3 are homogneeous\n% coordinates with arbitrary scale. If this is\n% omitted it is assumed that the points are\n% inhomogeneous, or that they are homogeneous with\n% equal scale.\n%\n% Returns:\n% r = 1 if points are co-linear, 0 otherwise\n\n% Copyright (c) 2004-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2004\n% January 2005 - modified to allow for homogeneous points of arbitrary\n% scale (thanks to Michael Kirchhof)\n\n\nfunction r = iscolinear(p1, p2, p3, flag)\n\n if nargin == 3 % Assume inhomogeneous coords\n\tflag = 'inhomog';\n end\n \n if ~all(size(p1)==size(p2)) | ~all(size(p1)==size(p3)) | ...\n ~(length(p1)==2 | length(p1)==3) \n error('points must have the same dimension of 2 or 3');\n end\n \n % If data is 2D, assume they are 2D inhomogeneous coords. Make them\n % homogeneous with scale 1.\n if length(p1) == 2 \n p1(3) = 1; p2(3) = 1; p3(3) = 1;\n end\n\n if flag(1) == 'h'\n\t% Apply test that allows for homogeneous coords with arbitrary\n % scale. p1 X p2 generates a normal vector to plane defined by\n % origin, p1 and p2. If the dot product of this normal with p3\n % is zero then p3 also lies in the plane, hence co-linear.\n\tr = abs(dot(cross(p1, p2),p3)) < eps;\n else\n\t% Assume inhomogeneous coords, or homogeneous coords with equal\n % scale.\n\tr = norm(cross(p2-p1, p3-p1)) < eps;\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ransacfithomography.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/ransacfithomography.m", "size": 4920, "source_encoding": "utf_8", "md5": "d479d49f7c8e8689283005bcbe340b61", "text": "% RANSACFITHOMOGRAPHY - fits 2D homography using RANSAC\n%\n% Usage: [H, inliers] = ransacfithomography(x1, x2, t)\n%\n% Arguments:\n% x1 - 2xN or 3xN set of homogeneous points. If the data is\n% 2xN it is assumed the homogeneous scale factor is 1.\n% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.\n% t - The distance threshold between data point and the model\n% used to decide whether a point is an inlier or not. \n% Note that point coordinates are normalised to that their\n% mean distance from the origin is sqrt(2). The value of\n% t should be set relative to this, say in the range \n% 0.001 - 0.01 \n%\n% Note that it is assumed that the matching of x1 and x2 are putative and it\n% is expected that a percentage of matches will be wrong.\n%\n% Returns:\n% H - The 3x3 homography such that x2 = H*x1.\n% inliers - An array of indices of the elements of x1, x2 that were\n% the inliers for the best model.\n%\n% See Also: ransac, homography2d, homography1d\n\n% Copyright (c) 2004-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2004 - original version\n% July 2004 - error in denormalising corrected (thanks to Andrew Stein)\n% August 2005 - homogdist2d modified to fit new ransac specification.\n\nfunction [H, inliers] = ransacfithomography(x1, x2, t)\n\n if ~all(size(x1)==size(x2))\n error('Data sets x1 and x2 must have the same dimension');\n end\n \n [rows,npts] = size(x1);\n if rows~=2 & rows~=3\n error('x1 and x2 must have 2 or 3 rows');\n end\n \n if npts < 4\n error('Must have at least 4 points to fit homography');\n end\n \n if rows == 2 % Pad data with homogeneous scale factor of 1\n x1 = [x1; ones(1,npts)];\n x2 = [x2; ones(1,npts)]; \n end\n \n % Normalise each set of points so that the origin is at centroid and\n % mean distance from origin is sqrt(2). normalise2dpts also ensures the\n % scale parameter is 1. Note that 'homography2d' will also call\n % 'normalise2dpts' but the code in 'ransac' that calls the distance\n % function will not - so it is best that we normalise beforehand.\n [x1, T1] = normalise2dpts(x1);\n [x2, T2] = normalise2dpts(x2);\n \n s = 4; % Minimum No of points needed to fit a homography.\n \n fittingfn = @homography2d;\n distfn = @homogdist2d;\n degenfn = @isdegenerate;\n % x1 and x2 are 'stacked' to create a 6xN array for ransac\n [H, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t);\n \n % Now do a final least squares fit on the data points considered to\n % be inliers.\n H = homography2d(x1(:,inliers), x2(:,inliers));\n \n % Denormalise\n H = T2\\H*T1; \n\n%----------------------------------------------------------------------\n% Function to evaluate the symmetric transfer error of a homography with\n% respect to a set of matched points as needed by RANSAC.\n\nfunction [inliers, H] = homogdist2d(H, x, t);\n \n x1 = x(1:3,:); % Extract x1 and x2 from x\n x2 = x(4:6,:); \n \n % Calculate, in both directions, the transfered points \n Hx1 = H*x1;\n invHx2 = H\\x2;\n \n % Normalise so that the homogeneous scale parameter for all coordinates\n % is 1.\n \n x1 = hnormalise(x1);\n x2 = hnormalise(x2); \n Hx1 = hnormalise(Hx1);\n invHx2 = hnormalise(invHx2); \n \n d2 = sum((x1-invHx2).^2) + sum((x2-Hx1).^2);\n inliers = find(abs(d2) < t); \n \n \n%----------------------------------------------------------------------\n% Function to determine if a set of 4 pairs of matched points give rise\n% to a degeneracy in the calculation of a homography as needed by RANSAC.\n% This involves testing whether any 3 of the 4 points in each set is\n% colinear. \n \nfunction r = isdegenerate(x)\n\n x1 = x(1:3,:); % Extract x1 and x2 from x\n x2 = x(4:6,:); \n \n r = ...\n iscolinear(x1(:,1),x1(:,2),x1(:,3)) | ...\n iscolinear(x1(:,1),x1(:,2),x1(:,4)) | ...\n iscolinear(x1(:,1),x1(:,3),x1(:,4)) | ...\n iscolinear(x1(:,2),x1(:,3),x1(:,4)) | ...\n iscolinear(x2(:,1),x2(:,2),x2(:,3)) | ...\n iscolinear(x2(:,1),x2(:,2),x2(:,4)) | ...\n iscolinear(x2(:,1),x2(:,3),x2(:,4)) | ...\n iscolinear(x2(:,2),x2(:,3),x2(:,4));\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ransac.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/ransac.m", "size": 10145, "source_encoding": "utf_8", "md5": "3089c4a4e2a58e086c8b1c5579aa9c53", "text": "% RANSAC - Robustly fits a model to data with the RANSAC algorithm\n%\n% Usage:\n%\n% [M, inliers] = ransac(x, fittingfn, distfn, degenfn s, t, feedback, ...\n% maxDataTrials, maxTrials)\n%\n% Arguments:\n% x - Data sets to which we are seeking to fit a model M\n% It is assumed that x is of size [d x Npts]\n% where d is the dimensionality of the data and Npts is\n% the number of data points.\n%\n% fittingfn - Handle to a function that fits a model to s\n% data from x. It is assumed that the function is of the\n% form: \n% M = fittingfn(x)\n% Note it is possible that the fitting function can return\n% multiple models (for example up to 3 fundamental matrices\n% can be fitted to 7 matched points). In this case it is\n% assumed that the fitting function returns a cell array of\n% models.\n% If this function cannot fit a model it should return M as\n% an empty matrix.\n%\n% distfn - Handle to a function that evaluates the\n% distances from the model to data x.\n% It is assumed that the function is of the form:\n% [inliers, M] = distfn(M, x, t)\n% This function must evaluate the distances between points\n% and the model returning the indices of elements in x that\n% are inliers, that is, the points that are within distance\n% 't' of the model. Additionally, if M is a cell array of\n% possible models 'distfn' will return the model that has the\n% most inliers. If there is only one model this function\n% must still copy the model to the output. After this call M\n% will be a non-cell object representing only one model. \n%\n% degenfn - Handle to a function that determines whether a\n% set of datapoints will produce a degenerate model.\n% This is used to discard random samples that do not\n% result in useful models.\n% It is assumed that degenfn is a boolean function of\n% the form: \n% r = degenfn(x)\n% It may be that you cannot devise a test for degeneracy in\n% which case you should write a dummy function that always\n% returns a value of 1 (true) and rely on 'fittingfn' to return\n% an empty model should the data set be degenerate.\n%\n% s - The minimum number of samples from x required by\n% fittingfn to fit a model.\n%\n% t - The distance threshold between a data point and the model\n% used to decide whether the point is an inlier or not.\n%\n% feedback - An optional flag 0/1. If set to one the trial count and the\n% estimated total number of trials required is printed out at\n% each step. Defaults to 0.\n%\n% maxDataTrials - Maximum number of attempts to select a non-degenerate\n% data set. This parameter is optional and defaults to 100.\n%\n% maxTrials - Maximum number of iterations. This parameter is optional and\n% defaults to 1000.\n%\n% Returns:\n% M - The model having the greatest number of inliers.\n% inliers - An array of indices of the elements of x that were\n% the inliers for the best model.\n%\n%\n% Note that the desired probability of choosing at least one sample free from\n% outliers is set at 0.99. You will need to edit the code should you wish to\n% change this (it should probably be a parameter)\n%\n% For an example of the use of this function see RANSACFITHOMOGRAPHY or\n% RANSACFITPLANE \n\n% References:\n% M.A. Fishler and R.C. Boles. \"Random sample concensus: A paradigm\n% for model fitting with applications to image analysis and automated\n% cartography\". Comm. Assoc. Comp, Mach., Vol 24, No 6, pp 381-395, 1981\n%\n% Richard Hartley and Andrew Zisserman. \"Multiple View Geometry in\n% Computer Vision\". pp 101-113. Cambridge University Press, 2001\n\n% Copyright (c) 2003-2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au \n% http://www.csse.uwa.edu.au/~pk\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% May 2003 - Original version\n% February 2004 - Tidied up.\n% August 2005 - Specification of distfn changed to allow model fitter to\n% return multiple models from which the best must be selected\n% Sept 2006 - Random selection of data points changed to ensure duplicate\n% points are not selected.\n% February 2007 - Jordi Ferrer: Arranged warning printout.\n% Allow maximum trials as optional parameters.\n% Patch the problem when non-generated data\n% set is not given in the first iteration.\n% August 2008 - 'feedback' parameter restored to argument list and other\n% breaks in code introduced in last update fixed.\n% December 2008 - Octave compatibility mods\n% June 2009 - Argument 'MaxTrials' corrected to 'maxTrials'!\n% January 2013 - Separate code path for Octave no longer needed\n\nfunction [M, inliers] = ransac(x, fittingfn, distfn, degenfn, s, t, feedback, ...\n maxDataTrials, maxTrials)\n\n % Test number of parameters\n error ( nargchk ( 6, 9, nargin ) );\n \n if nargin < 9; maxTrials = 1000; end;\n if nargin < 8; maxDataTrials = 100; end;\n if nargin < 7; feedback = 0; end;\n \n [rows, npts] = size(x);\n \n p = 0.99; % Desired probability of choosing at least one sample\n % free from outliers (probably should be a parameter)\n\n bestM = NaN; % Sentinel value allowing detection of solution failure.\n trialcount = 0;\n bestscore = 0;\n N = 1; % Dummy initialisation for number of trials.\n \n while N > trialcount\n \n % Select at random s datapoints to form a trial model, M.\n % In selecting these points we have to check that they are not in\n % a degenerate configuration.\n degenerate = 1;\n count = 1;\n while degenerate\n % Generate s random indicies in the range 1..npts\n % (If you do not have the statistics toolbox with randsample(),\n % use the function RANDOMSAMPLE from my webpage)\n if ~exist('randsample', 'file')\n ind = randomsample(npts, s);\n else\n ind = randsample(npts, s);\n end\n\n % Test that these points are not a degenerate configuration.\n degenerate = feval(degenfn, x(:,ind));\n \n if ~degenerate\n % Fit model to this random selection of data points.\n % Note that M may represent a set of models that fit the data in\n % this case M will be a cell array of models\n M = feval(fittingfn, x(:,ind));\n \n % Depending on your problem it might be that the only way you\n % can determine whether a data set is degenerate or not is to\n % try to fit a model and see if it succeeds. If it fails we\n % reset degenerate to true.\n if isempty(M)\n degenerate = 1;\n end\n end\n \n % Safeguard against being stuck in this loop forever\n count = count + 1;\n if count > maxDataTrials\n warning('Unable to select a nondegenerate data set');\n break\n end\n end\n \n % Once we are out here we should have some kind of model...\n % Evaluate distances between points and model returning the indices\n % of elements in x that are inliers. Additionally, if M is a cell\n % array of possible models 'distfn' will return the model that has\n % the most inliers. After this call M will be a non-cell object\n % representing only one model.\n [inliers, M] = feval(distfn, M, x, t);\n \n % Find the number of inliers to this model.\n ninliers = length(inliers);\n \n if ninliers > bestscore % Largest set of inliers so far...\n bestscore = ninliers; % Record data for this model\n bestinliers = inliers;\n bestM = M;\n \n % Update estimate of N, the number of trials to ensure we pick,\n % with probability p, a data set with no outliers.\n fracinliers = ninliers/npts;\n pNoOutliers = 1 - fracinliers^s;\n pNoOutliers = max(eps, pNoOutliers); % Avoid division by -Inf\n pNoOutliers = min(1-eps, pNoOutliers);% Avoid division by 0.\n N = log(1-p)/log(pNoOutliers);\n end\n \n trialcount = trialcount+1;\n if feedback\n fprintf('trial %d out of %d \\r',trialcount, ceil(N));\n end\n\n % Safeguard against being stuck in this loop forever\n if trialcount > maxTrials\n warning( ...\n sprintf('ransac reached the maximum number of %d trials',...\n maxTrials));\n break\n end\n end\n \n if feedback, fprintf('\\n'); end\n \n if ~isnan(bestM) % We got a solution\n M = bestM;\n inliers = bestinliers;\n else\n M = [];\n inliers = [];\n error('ransac was unable to find a useful solution');\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "fitline.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/fitline.m", "size": 3537, "source_encoding": "utf_8", "md5": "4b7acec43fdeacc38c926e7d3e6d8a59", "text": "% FITLINE - Least squares fit of a line to a set of points\n%\n% Usage: [C, dist] = fitline(XY)\n%\n% Where: XY - 2xNpts array of xy coordinates to fit line to data of\n% the form \n% [x1 x2 x3 ... xN\n% y1 y2 y3 ... yN]\n% \n% XY can also be a 3xNpts array of homogeneous coordinates.\n%\n% Returns: C - 3x1 array of line coefficients in the form\n% c(1)*X + c(2)*Y + c(3) = 0\n% dist - Array of distances from the fitted line to the supplied\n% data points. Note that dist is only calculated if the\n% function is called with two output arguments.\n%\n% The magnitude of C is scaled so that line equation corresponds to\n% sin(theta)*X + (-cos(theta))*Y + rho = 0\n% where theta is the angle between the line and the x axis and rho is the\n% perpendicular distance from the origin to the line. Rescaling the\n% coefficients in this manner allows the perpendicular distance from any\n% point (x,y) to the line to be simply calculated as\n% r = abs(c(1)*X + c(2)*Y + c(3))\n%\n%\n% If you want to convert this line representation to the classical form \n% Y = a*X + b\n% use\n% a = -c(1)/c(2)\n% b = -c(3)/c(2)\n%\n% Note, however, that this assumes c(2) is not zero\n\n% Copyright (c) 2003-2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% June 2003 - Original version\n% September 2004 - Rescaling to allow simple distance calculation.\n% November 2008 - Normalising of coordinates added to condition the solution.\n\nfunction [C, dist] = fitline(XY)\n \n [rows,npts] = size(XY); \n\n if npts < 2\n error('Too few points to fit line');\n end \n \n if rows ==2 % Add homogeneous scale coordinate of 1 \n XY = [XY; ones(1,npts)];\n end\n\n if npts == 2 % Pad XY with a third column of zeros\n XY = [XY zeros(3,1)]; \n end\n \n % Normalise points so that centroid is at origin and mean distance from\n % origin is sqrt(2). This conditions the equations\n [XYn, T] = normalise2dpts(XY);\n \n % Set up constraint equations of the form XYn'*C = 0,\n % where C is a column vector of the line coefficients\n % in the form c(1)*X + c(2)*Y + c(3) = 0.\n\n [u d v] = svd(XYn',0); % Singular value decomposition.\n C = v(:,3); % Solution is last column of v.\n\n % Denormalise the solution\n C = T'*C;\n \n % Rescale coefficients so that line equation corresponds to\n % sin(theta)*X + (-cos(theta))*Y + rho = 0\n % so that the perpendicular distance from any point (x,y) to the line\n % to be simply calculated as \n % r = abs(c(1)*X + c(2)*Y + c(3))\n\n theta = atan2(C(1), -C(2));\n\n % Find the scaling (but avoid dividing by zero)\n if abs(sin(theta)) > abs(cos(theta))\n k = C(1)/sin(theta);\n else\n k = -C(2)/cos(theta);\n end\n \n C = C/k;\n \n % If requested, calculate the distances from the fitted line to\n % the supplied data points \n if nargout==2 \n dist = abs(C(1)*XY(1,:) + C(2)*XY(2,:) + C(3));\n end\n\n\n\n\n \n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ransacfitline.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/ransacfitline.m", "size": 4628, "source_encoding": "utf_8", "md5": "164727c9f870963847fe09846fef96a5", "text": "% RANSACFITLINE - fits line to 3D array of points using RANSAC\n%\n% Usage [L, inliers] = ransacfitline(XYZ, t, feedback)\n%\n% This function uses the RANSAC algorithm to robustly fit a line\n% to a set of 3D data points.\n%\n% Arguments:\n% XYZ - 3xNpts array of xyz coordinates to fit line to.\n% t - The distance threshold between data point and the line\n% used to decide whether a point is an inlier or not.\n% feedback - Optional flag 0 or 1 to turn on RANSAC feedback\n% information.\n%\n% Returns:.\n% V - Line obtained by a simple fitting on the points that\n% are considered inliers. The line goes through the\n% calculated mean of the inlier points, and is parallel to\n% the principal eigenvector. The line is scaled by the\n% square root of the largest eigenvalue.\n% This line is a n*2 matrix. The first column is the\n% beginning point, the second column is the end point of the\n% line.\n% L - The two points in the data set that were found to\n% define a line having the most number of inliers.\n% The two columns of L defining the two points.\n% inliers - The indices of the points that were considered\n% inliers to the fitted line.\n%\n% See also: RANSAC, FITPLANE, RANSACFITPLANE\n\n% Copyright (c) 2003-2006 Peter Kovesi and Felix Duvallet (CMU)\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% Aug 2006 - created ransacfitline from ransacfitplane\n% author: Felix Duvallet\n\nfunction [V, L, inliers] = ransacfitline(XYZ, t, feedback)\n \n if nargin == 2\n\tfeedback = 0;\n end\n \n [rows, npts] = size(XYZ);\n \n if rows ~=3\n error('data is not 3D');\n end\n \n if npts < 2\n error('too few points to fit line');\n end\n \n s = 2; % Minimum No of points needed to fit a line.\n \n fittingfn = @defineline;\n distfn = @lineptdist;\n degenfn = @isdegenerate;\n\n [L, inliers] = ransac(XYZ, fittingfn, distfn, degenfn, s, t, feedback);\n \n % Find the line going through the mean, parallel to the major\n % eigenvector\n V = fitline3d(XYZ(:, inliers));\n \n%------------------------------------------------------------------------\n% Function to define a line given 2 data points as required by\n% RANSAC.\n\nfunction L = defineline(X);\n L = X;\n \n%------------------------------------------------------------------------\n% Function to calculate distances between a line and an array of points.\n% The line is defined by a 3x2 matrix, L. The two columns of L defining\n% two points that are the endpoints of the line.\n%\n% A line can be defined with two points as:\n% lambda*p1 + (1-lambda)*p2\n% Then, the distance between the line and another point (p3) is:\n% norm( lambda*p1 + (1-lambda)*p2 - p3 )\n% where\n% (p2-p1).(p2-p3)\n% lambda = ---------------\n% (p1-p2).(p1-p2)\n%\n% lambda can be found by taking the derivative of:\n% (lambda*p1 + (1-lambda)*p2 - p3)*(lambda*p1 + (1-lambda)*p2 - p3)\n% with respect to lambda and setting it equal to zero\n\nfunction [inliers, L] = lineptdist(L, X, t)\n\n p1 = L(:,1);\n p2 = L(:,2);\n \n npts = length(X);\n d = zeros(npts, 1);\n \n for i = 1:npts\n p3 = X(:,i);\n \n lambda = dot((p2 - p1), (p2-p3)) / dot( (p1-p2), (p1-p2) );\n \n d(i) = norm(lambda*p1 + (1-lambda)*p2 - p3);\n end\n \n inliers = find(abs(d) < t);\n \n%------------------------------------------------------------------------\n% Function to determine whether a set of 2 points are in a degenerate\n% configuration for fitting a line as required by RANSAC.\n% In this case two points are degenerate if they are the same point\n% or if they are exceedingly close together.\n\nfunction r = isdegenerate(X)\n %find the norm of the difference of the two points\n % this will be 0 iff the two points are the same (the norm of their\n % difference is zero)\n r = norm(X(:,1) - X(:,2)) < eps;\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ransacfitplane.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/ransacfitplane.m", "size": 4394, "source_encoding": "utf_8", "md5": "baa5ff279844792a35a0615536c87855", "text": "% RANSACFITPLANE - fits plane to 3D array of points using RANSAC\r\n%\r\n% Usage [B, P, inliers] = ransacfitplane(XYZ, t, feedback)\r\n%\r\n% This function uses the RANSAC algorithm to robustly fit a plane\r\n% to a set of 3D data points.\r\n%\r\n% Arguments:\r\n% XYZ - 3xNpts array of xyz coordinates to fit plane to.\r\n% t - The distance threshold between data point and the plane\r\n% used to decide whether a point is an inlier or not.\r\n% feedback - Optional flag 0 or 1 to turn on RANSAC feedback\r\n% information.\r\n%\r\n% Returns:\r\n% B - 4x1 array of plane coefficients in the form\r\n% b(1)*X + b(2)*Y +b(3)*Z + b(4) = 0\r\n% The magnitude of B is 1.\r\n% This plane is obtained by a least squares fit to all the\r\n% points that were considered to be inliers, hence this\r\n% plane will be slightly different to that defined by P below.\r\n% P - The three points in the data set that were found to\r\n% define a plane having the most number of inliers.\r\n% The three columns of P defining the three points.\r\n% inliers - The indices of the points that were considered\r\n% inliers to the fitted plane.\r\n%\r\n% See also: RANSAC, FITPLANE\r\n\r\n% Copyright (c) 2003-2008 Peter Kovesi\r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% http://www.csse.uwa.edu.au/\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in \r\n% all copies or substantial portions of the Software.\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n\r\n% June 2003 - Original version.\r\n% Feb 2004 - Modified to use separate ransac function\r\n% Aug 2005 - planeptdist modified to fit new ransac specification\r\n% Dec 2008 - Much faster distance calculation in planeptdist (thanks to\r\n% Alastair Harrison) \r\n\r\n\r\nfunction [B, P, inliers] = ransacfitplane(XYZ, t, feedback)\r\n \r\n if nargin == 2\r\n\tfeedback = 0;\r\n end\r\n \r\n [rows, npts] = size(XYZ);\r\n \r\n if rows ~=3\r\n error('data is not 3D');\r\n end\r\n \r\n if npts < 3\r\n error('too few points to fit plane');\r\n end\r\n \r\n s = 3; % Minimum No of points needed to fit a plane.\r\n \r\n fittingfn = @defineplane;\r\n distfn = @planeptdist;\r\n degenfn = @isdegenerate;\r\n\r\n [P, inliers] = ransac(XYZ, fittingfn, distfn, degenfn, s, t, feedback);\r\n \r\n % Perform least squares fit to the inlying points\r\n B = fitplane(XYZ(:,inliers));\r\n \r\n%------------------------------------------------------------------------\r\n% Function to define a plane given 3 data points as required by\r\n% RANSAC. In our case we use the 3 points directly to define the plane.\r\n\r\nfunction P = defineplane(X);\r\n P = X;\r\n \r\n%------------------------------------------------------------------------\r\n% Function to calculate distances between a plane and a an array of points.\r\n% The plane is defined by a 3x3 matrix, P. The three columns of P defining\r\n% three points that are within the plane.\r\n\r\nfunction [inliers, P] = planeptdist(P, X, t)\r\n \r\n n = cross(P(:,2)-P(:,1), P(:,3)-P(:,1)); % Plane normal.\r\n n = n/norm(n); % Make it a unit vector.\r\n \r\n npts = length(X);\r\n d = zeros(npts,1); % d will be an array of distance values.\r\n\r\n % The following loop builds up the dot product between a vector from P(:,1)\r\n % to every X(:,i) with the unit plane normal. This will be the\r\n % perpendicular distance from the plane for each point\r\n for i=1:3\r\n\td = d + (X(i,:)'-P(i,1))*n(i); \r\n end\r\n \r\n inliers = find(abs(d) < t);\r\n \r\n \r\n%------------------------------------------------------------------------\r\n% Function to determine whether a set of 3 points are in a degenerate\r\n% configuration for fitting a plane as required by RANSAC. In this case\r\n% they are degenerate if they are colinear.\r\n\r\nfunction r = isdegenerate(X)\r\n \r\n % The three columns of X are the coords of the 3 points.\r\n r = iscolinear(X(:,1),X(:,2),X(:,3));"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "testfund.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/example/testfund.m", "size": 4750, "source_encoding": "utf_8", "md5": "0deb774af59a52b8be800cea1cfb2adc", "text": "% Demonstration of feature matching via simple correlation, and then using\n% RANSAC to estimate the fundamental matrix and at the same time identify\n% (mostly) inlying matches\n%\n% Usage: testfund - Demonstrates fundamental matrix calculation\n% on two default images.\n% testfund(im1,im2) - Computes fundamental matrix on two supplied\n% images.\n%\n% Edit code as necessary to tweak parameters\n\n% Copyright (c) 2004-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2004\n% August 2005 Octave compatibility\n% July 2013 Adust threshold to suit use of Farid and Simoncelli's\n% derivative filters now used in harris.m\n\nfunction testfund(im1,im2)\n \n if nargin == 0\n\tim1 = imread('im02.jpg');\n\tim2 = imread('im03.jpg');\n end\n\n v = version; Octave=v(1)<'5'; % Crude Octave test \n thresh = 20; % Harris corner threshold\n nonmaxrad = 3; % Non-maximal suppression radius\n dmax = 50; % Maximum search distance for matching\n w = 11; % Window size for correlation matching\n \n % Find Harris corners in image1 and image2\n [cim1, r1, c1] = harris(im1, 1, thresh, 3);\n show(im1,1), hold on, plot(c1,r1,'r+');\n\n [cim2, r2, c2] = harris(im2, 1, thresh, 3);\n show(im2,2), hold on, plot(c2,r2,'r+');\n drawnow\n\n correlation = 1; % Change this between 1 or 0 to switch between the two\n % matching functions below\n \n if correlation % Use normalised correlation matching\n\t[m1,m2] = matchbycorrelation(im1, [r1';c1'], im2, [r2';c2'], w, dmax);\n\t\n else % Use monogenic phase matching\n\tnscale = 1;\n\tminWaveLength = 10;\n\tmult = 4;\n\tsigmaOnf = .2;\n\t[m1,m2] = matchbymonogenicphase(im1, [r1';c1'], im2, [r2';c2'], w, dmax,...\n\t\t\t\t\tnscale, minWaveLength, mult, sigmaOnf);\n end \n \n % Display putative matches\n show(im1,3), set(3,'name','Putative matches')\n if Octave, figure(1); title('Putative matches'), axis('equal'), end \n for n = 1:length(m1);\n\tline([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)])\n end\n\n % Assemble homogeneous feature coordinates for fitting of the\n % fundamental matrix, note that [x,y] corresponds to [col, row]\n x1 = [m1(2,:); m1(1,:); ones(1,length(m1))];\n x2 = [m2(2,:); m2(1,:); ones(1,length(m1))]; \n \n t = .002; % Distance threshold for deciding outliers\n \n % Change the commenting on the lines below to switch between the use\n % of 7 or 8 point fundamental matrix solutions, or affine fundamental\n % matrix solution.\n% [F, inliers] = ransacfitfundmatrix7(x1, x2, t, 1); \n [F, inliers] = ransacfitfundmatrix(x1, x2, t, 1);\n% [F, inliers] = ransacfitaffinefund(x1, x2, t, 1); \n\n fprintf('Number of inliers was %d (%d%%) \\n', ...\n\t length(inliers),round(100*length(inliers)/length(m1)))\n fprintf('Number of putative matches was %d \\n', length(m1)) \n \n % Display both images overlayed with inlying matched feature points\n \n if Octave\n\tfigure(4); title('Inlying matches'), axis('equal'), \n else\n show(im1,4), set(4,'name','Inlying matches'), hold on\n end \n plot(m1(2,inliers),m1(1,inliers),'r+');\n plot(m2(2,inliers),m2(1,inliers),'g+'); \n\n for n = inliers\n\tline([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)],'color',[0 0 1])\n end\n\n if Octave, return, end\n \n response = input('Step through each epipolar line [y/n]?\\n','s');\n if response == 'n'\n\treturn\n end \n \n % Step through each matched pair of points and display the\n % corresponding epipolar lines on the two images.\n \n l2 = F*x1; % Epipolar lines in image2\n l1 = F'*x2; % Epipolar lines in image1\n \n % Solve for epipoles\n [U,D,V] = svd(F);\n e1 = hnormalise(V(:,3));\n e2 = hnormalise(U(:,3));\n \n for n = inliers\n\tfigure(1), clf, imshow(im1), hold on, plot(x1(1,n),x1(2,n),'r+');\n\thline(l1(:,n)); plot(e1(1), e1(2), 'g*');\n\n\tfigure(2), clf, imshow(im2), hold on, plot(x2(1,n),x2(2,n),'r+');\n\thline(l2(:,n)); plot(e2(1), e2(2), 'g*');\n\tfprintf('hit any key to see next point\\r'); pause\n end\n\n fprintf(' \\n');\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "testfitline.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/example/testfitline.m", "size": 3953, "source_encoding": "utf_8", "md5": "f97a656b9a7452fe4bce589b0ea934c4", "text": "% TESTFITLINE - demonstrates RANSAC line fitting\n%\n% Usage: testfitline(outliers, sigma, t, feedback)\n%\n% Arguments:\n% outliers - Fraction specifying how many points are to be\n% outliers.\n% sigma - Standard deviation of inlying points from the\n% true line.\n% t - Distance threshold to be used by the RANSAC\n% algorithm for deciding whether a point is an\n% inlier. \n% feedback - Optional flag 0 or 1 to turn on RANSAC feedback\n% information.\n%\n% Try using: testfitline(0.3, 0.05, 0.05)\n%\n% See also: RANSACFITPLANE, FITPLANE\n\n% Copyright (c) 2003-2006 Peter Kovesi and Felix Duvallet (CMU)\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% August 2006 testfitline created from testfitplane\n% author: Felix Duvallet\n\nfunction testfitline(outliers, sigma, t, feedback)\n\n close all;\n\n if nargin == 3\n feedback = 0;\n end\n \n % Hard wire some constants - vary these as you wish\n \n npts = 100; % Number of 3D data points\t\n \n % Define a line:\n % Y = m*X\n % Z = n*X + Y + b\n % This definition needs fixing, but it works for now\n \n m = 6;\n n = -3;\n b = -4;\n \n outsigma = 30*sigma; % outlying points have a distribution that is\n % 30 times as spread as the inlying points\n \n vpts = round((1-outliers)*npts); % No of valid points\n opts = npts - vpts; % No of outlying points\n \n % Generate npts points in the line\n X = rand(1,npts);\n \n Y = m*X;\n Z = n*X + Y + b;\n Z = zeros(size(Y));\n \n \n XYZ = [X\n \t Y\n \t Z];\n\n % Add uniform noise of +/-sigma\n XYZ = XYZ + (2*rand(size(XYZ))-1)*sigma;\n \n % Generate opts random outliers\n \n n = length(XYZ);\n ind = randperm(n); % get a random set of point indices\n ind = ind(1:opts); % ... of length opts\n \n % Add uniform noise of outsigma to the points chosen to be outliers. \n XYZ(:,ind) = XYZ(:,ind) + sign(rand(3,opts)-.5).*(rand(3,opts)+1)*outsigma; \n\n \n % Perform RANSAC fitting of the line\n [V, P, inliers] = ransacfitline(XYZ, t, feedback);\n \n if(feedback)\n disp(['Number of Inliers: ' num2str(length(inliers)) ]);\n end\n\n % We want to plot the inlier points blue, with the outlier points in\n % red. In order to do that, we must find the outliers.\n % Use setxor on all the points, and the inliers to find outliers\n % (plotting all the points in red and then plotting over them in blue\n % does not work well)\n oulier_points = setxor(transpose(XYZ), transpose(XYZ(:, inliers)), 'rows');\n oulier_points = oulier_points';\n \n % Display the cloud of outlier points\n figure(1); clf\n hold on;\n plot3(oulier_points(1,:),oulier_points(2,:),oulier_points(3,:), 'r*');\n\n % Plot the inliers as blue points\n plot3(XYZ(1,inliers), XYZ(2, inliers), XYZ(3, inliers), 'b*');\n\n % Display the line formed by the 2 points that gave the\n % line of maximum consensus as a green line\n line(P(1,:), P(2,:), P(3,:), 'Color', 'green', 'LineWidth', 4);\n \n %Display the line formed by the covariance fitting in magenta\n line(V(1,:), V(2, :), V(3,:), 'Color', 'magenta', 'LineWidth', 5);\n \n box('on'), grid('on'), rotate3d('on')\n \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "testhomog.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/example/testhomog.m", "size": 2978, "source_encoding": "utf_8", "md5": "8c24c0c26133700b6ca737053fc660e7", "text": "% Demonstration of feature matching via simple correlation, and then using\n% RANSAC to estimate the homography between two images and at the same time\n% identify (mostly) inlying matches\n%\n% Usage: testhomog - Demonstrates homography calculation on two \n% default images\n% testhomog(im1,im2) - Computes homography on two supplied images\n%\n% Edit code as necessary to tweak parameters\n\n% Copyright (c) 2004-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2004\n% August 2005 Octave compatibility\n\nfunction testhomog(im1,im2)\n\n if nargin == 0\n\tim1 = imread('boats.tif');\n\tim2 = imread('boatsrot.tif'); \n end\n \n close all \n v = version; Octave=v(1)<'5'; % Crude Octave test\n thresh = 500; % Harris corner threshold\n nonmaxrad = 3; % Non-maximal suppression radius\n dmax = 50;\n w = 11; % Window size for correlation matching\n \n % Find Harris corners in image1 and image2\n [cim1, r1, c1] = harris(im1, 1, thresh, 3);\n show(im1,1), hold on, plot(c1,r1,'r+');\n\n [cim2, r2, c2] = harris(im2, 1, thresh, 3);\n show(im2,2), hold on, plot(c2,r2,'r+');\n\n drawnow\n\n [m1,m2] = matchbycorrelation(im1, [r1';c1'], im2, [r2';c2'], w, dmax);\n\n % Display putative matches\n show(im1,3), set(3,'name','Putative matches'), \n if Octave, figure(1); title('Putative matches'), axis('equal'), end \n for n = 1:length(m1);\n\tline([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)])\n end\n\n % Assemble homogeneous feature coordinates for fitting of the\n % homography, note that [x,y] corresponds to [col, row]\n x1 = [m1(2,:); m1(1,:); ones(1,length(m1))];\n x2 = [m2(2,:); m2(1,:); ones(1,length(m1))]; \n \n t = .001; % Distance threshold for deciding outliers\n [H, inliers] = ransacfithomography(x1, x2, t);\n\n fprintf('Number of inliers was %d (%d%%) \\n', ...\n\t length(inliers),round(100*length(inliers)/length(m1)))\n fprintf('Number of putative matches was %d \\n', length(m1)) \n \n % Display both images overlayed with inlying matched feature points\n\n if Octave\n\tfigure(4); title('Inlying matches'), axis('equal'), \n else\n show(im1,4), set(4,'name','Inlying matches'), hold on\n end \n plot(m1(2,inliers),m1(1,inliers),'r+');\n plot(m2(2,inliers),m2(1,inliers),'g+'); \n\n for n = inliers\n\tline([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)],'color',[0 0 1])\n end\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "testfundOctave.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/example/testfundOctave.m", "size": 2769, "source_encoding": "utf_8", "md5": "44430d35fa0a1d0a29001b5d76e0f81a", "text": "% Demonstration of feature matching via simple correlation, and then using\n% RANSAC to estimate the fundamental matrix and at the same time identify\n% (mostly) inlying matches\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% February 2004\n% August 2005 Octave version\n\nfunction testfundOctave\n\n close all \n \n thresh = 500; % Harris corner threshold\n nonmaxrad = 3; % Non-maximal suppression radius\n dmax = 50;\n w = 11; % Window size for correlation matching\n \n im1 = imread('im02.jpg');\n im2 = imread('im03.jpg');\n\n % Find Harris corners in image1 and image2\n [cim1, r1, c1] = harris(im1, 1, thresh, 3);\n% show(im1,1), hold on, plot(c1,r1,'r+');\n\n [cim2, r2, c2] = harris(im2, 1, thresh, 3);\n% show(im2,2), hold on, plot(c2,r2,'r+');\n\n drawnow\n\n\n [m1,m2] = matchbycorrelation(im1, [r1';c1'], im2, [r2';c2'], w, dmax);\n\n % Display putative matches\n% show(im1,3), set(3,'name','Putative matches'), hold on \n for n = 1:length(m1);\n\tline([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)])\n end\n\n % Assemble homogeneous feature coordinates for fitting of the\n % fundamental matrix, note that [x,y] corresponds to [col, row]\n x1 = [m1(2,:); m1(1,:); ones(1,length(m1))];\n x2 = [m2(2,:); m2(1,:); ones(1,length(m1))]; \n \n t = .001; % Distance threshold for deciding outliers\n [F, inliers] = ransacfitfundmatrix(x1, x2, t);\n\n fprintf('Number of inliers was %d (%d%%) \\n', ...\n\t length(inliers),round(100*length(inliers)/length(m1)))\n fprintf('Number of putative matches was %d \\n', length(m1)) \n \n % Display both images overlayed with inlying matched feature points\n% show(double(im1)+double(im2),4), set(4,'name','Inlying matches'), hold on \n plot(m1(2,inliers),m1(1,inliers),'r+');\n plot(m2(2,inliers),m2(1,inliers),'g+'); \n\n for n = inliers\n\tline([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)],'color',[0 0 1])\n end\n \n\n \n % Step through each matched pair of points and display the\n % corresponding epipolar lines on the two images.\n \n l2 = F*x1; % Epipolar lines in image2\n l1 = F'*x2; % Epipolar lines in image1\n\n \n % Solve for epipoles\n [U,D,V] = svd(F,0);\n e1 = hnormalise(V(:,3));\n e2 = hnormalise(U(:,3));\n \n return\n \n for n = inliers\n\tfigure(1), clf, imshow(im1), hold on, plot(x1(1,n),x1(2,n),'r+');\n\thline(l1(:,n)); plot(e1(1), e1(2), 'g*');\n\n\tfigure(2), clf, imshow(im2), hold on, plot(x2(1,n),x2(2,n),'r+');\n\thline(l2(:,n)); plot(e2(1), e2(2), 'g*');\n\tfprintf('hit any key to see next point\\r'); pause\n end\n\n fprintf(' \\n');\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "testfitplane.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/example/testfitplane.m", "size": 3474, "source_encoding": "utf_8", "md5": "8e3a7a2e2bd65da6d3a122e6e903d3f8", "text": "% TESTFITPLANE - demonstrates RANSAC plane fitting\r\n%\r\n% Usage: testfitplane(outliers, sigma, t, feedback)\r\n%\r\n% Arguments:\r\n% outliers - Fraction specifying how many points are to be\r\n% outliers.\r\n% sigma - Standard deviation of inlying points from the\r\n% true plane.\r\n% t - Distance threshold to be used by the RANSAC\r\n% algorithm for deciding whether a point is an\r\n% inlier. \r\n% feedback - Optional flag 0 or 1 to turn on RANSAC feedback\r\n% information.\r\n%\r\n% Try using: testfitplane(0.3, 0.05, 0.05)\r\n%\r\n% See also: RANSACFITPLANE, FITPLANE\r\n\r\n% Copyright (c) 2003-2005 Peter Kovesi\r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% http://www.csse.uwa.edu.au/\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in \r\n% all copies or substantial portions of the Software.\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n\r\n% June 2003\r\n\r\nfunction testfitplane(outliers, sigma, t, feedback)\r\n\r\n if nargin == 3\r\n\tfeedback = 0;\r\n end\r\n \r\n % Hard wire some constants - vary these as you wish\r\n \r\n npts = 100; % Number of 3D data points\t\r\n \r\n % Define a plane ax + by + cz + d = 0\r\n a = 10; b = -3; c = 5; d = 1;\r\n \r\n B = [a b c d]';\r\n B = B/norm(B);\r\n \r\n outsigma = 30*sigma; % outlying points have a distribution that is\r\n % 30 times as spread as the inlying points\r\n \r\n vpts = round((1-outliers)*npts); % No of valid points\r\n opts = npts - vpts; % No of outlying points\r\n \r\n % Generate npts points in the plane\r\n X = rand(1,npts);\r\n Y = rand(1,npts);\r\n Z = (-a*X -b*Y -d)/c;\r\n \r\n XYZ = [X\r\n\t Y\r\n\t Z];\r\n \r\n % Add uniform noise of +/-sigma\r\n XYZ = XYZ + (2*rand(size(XYZ))-1)*sigma;\r\n \r\n % Generate opts random outliers\r\n \r\n n = length(XYZ);\r\n ind = randperm(n); % get a random set of point indices\r\n ind = ind(1:opts); % ... of length opts\r\n \r\n % Add uniform noise of outsigma to the points chosen to be outliers.\r\n% XYZ(:,ind) = XYZ(:,ind) + (2*rand(3,opts)-1)*outsigma;\r\n \r\n XYZ(:,ind) = XYZ(:,ind) + sign(rand(3,opts)-.5).*(rand(3,opts)+1)*outsigma; \r\n \r\n \r\n\r\n % Display the cloud of points\r\n figure(1), clf, plot3(XYZ(1,:),XYZ(2,:),XYZ(3,:), 'r*');\r\n \r\n % Perform RANSAC fitting of the plane\r\n [Bfitted, P, inliers] = ransacfitplane(XYZ, t, feedback);\r\n\r\n fprintf('Original plane coefficients: ');\r\n fprintf('%8.3f ',B);\r\n fprintf('\\nFitted plane coefficients: ');\r\n fprintf('%8.3f ',Bfitted); \r\n fprintf('\\n');\r\n \r\n % Display the triangular patch formed by the 3 points that gave the\r\n % plane of maximum consensus\r\n patch(P(1,:), P(2,:), P(3,:), 'g')\r\n \r\n box('on'), grid('on'), rotate3d('on')\r\n \r\n fprintf('\\nRotate image so that planar patch is seen edge on\\n');\r\n fprintf('If the fit has been successful the inlying points should\\n');\r\n fprintf('form a line\\n\\n'); \r\n \r\n\r\n \r\n \r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "testvgghomog.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Robust/example/testvgghomog.m", "size": 2985, "source_encoding": "utf_8", "md5": "fb71f9f4828200b6a682941b00c1b3a6", "text": "% Demonstration of feature matching via simple correlation, and then using\n% RANSAC to estimate the homography between two images and at the same time\n% identify (mostly) inlying matches\n%\n% Usage: testhomog - Demonstrates homography calculation on two \n% default images\n% testhomog(im1,im2) - Computes homography on two supplied images\n%\n% Edit code as necessary to tweak parameters\n\n% Copyright (c) 2004-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2004\n% August 2005 Octave compatibility\n\nfunction testvgghomog(im1,im2)\n\n if nargin == 0\n\tim1 = imread('boats.tif');\n\tim2 = imread('boatsrot.tif'); \n end\n \n close all \n v = version; Octave=v(1)<'5'; % Crude Octave test\n thresh = 500; % Harris corner threshold\n nonmaxrad = 3; % Non-maximal suppression radius\n dmax = 50;\n w = 11; % Window size for correlation matching\n \n % Find Harris corners in image1 and image2\n [cim1, r1, c1] = harris(im1, 1, thresh, 3);\n show(im1,1), hold on, plot(c1,r1,'r+');\n\n [cim2, r2, c2] = harris(im2, 1, thresh, 3);\n show(im2,2), hold on, plot(c2,r2,'r+');\n\n drawnow\n\n [m1,m2] = matchbycorrelation(im1, [r1';c1'], im2, [r2';c2'], w, dmax);\n\n % Display putative matches\n show(im1,3), set(3,'name','Putative matches'), \n if Octave, figure(1); title('Putative matches'), axis('equal'), end \n for n = 1:length(m1);\n\tline([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)])\n end\n\n % Assemble homogeneous feature coordinates for fitting of the\n % homography, note that [x,y] corresponds to [col, row]\n x1 = [m1(2,:); m1(1,:); ones(1,length(m1))];\n x2 = [m2(2,:); m2(1,:); ones(1,length(m1))]; \n \n t = .001; % Distance threshold for deciding outliers\n [H, inliers] = ransacfithomography_vgg(x1, x2, t);\n\n fprintf('Number of inliers was %d (%d%%) \\n', ...\n\t length(inliers),round(100*length(inliers)/length(m1)))\n fprintf('Number of putative matches was %d \\n', length(m1)) \n \n % Display both images overlayed with inlying matched feature points\n\n if Octave\n\tfigure(4); title('Inlying matches'), axis('equal'), \n else\n show(im1,4), set(4,'name','Inlying matches'), hold on\n end \n plot(m1(2,inliers),m1(1,inliers),'r+');\n plot(m2(2,inliers),m2(1,inliers),'g+'); \n\n for n = inliers\n\tline([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)],'color',[0 0 1])\n end\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "map2lutfile.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/map2lutfile.m", "size": 754, "source_encoding": "utf_8", "md5": "2300f6e519f599653ffb3bf7f3286eeb", "text": "% MAP2LUTFILE Writes a colourmap to a .lut file for use with ImageJ\n%\n% Usage: map2lutfile(map, fname)\n%\n% The format of a lookup table for ImageJ is 256 bytes of red values, followed\n% by 256 green values and finally 256 blue values. A total of 768 bytes.\n%\n\n% PK June 2014\n\nfunction map2lutfile(map, fname)\n\n [N, chan] = size(map);\n if N ~= 256 | chan ~= 3\n error('Colourmap must be 256x3');\n end\n \n % Ensure file has a .lut ending\n if ~strendswith(fname, '.lut') \n fname = [fname '.lut'];\n end\n\n % Convert map to integers 0-255 and form into a single vector of\n % sequential RGB values\n map = round(map(:)*255);\n\n fid = fopen(fname, 'w'); \n fwrite(fid, map, 'uint8');\n fclose(fid);\n\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "labmaplib.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/labmaplib.m", "size": 57246, "source_encoding": "utf_8", "md5": "dcd370a01f0282850d06f15390cb801c", "text": "% LABMAPLIB Library of colour maps designed in CIELAB or RGB space\n%\n% Usage: 1: [map, name, desc] = labmaplib(I, param_name, value ...)\n% 2: labmaplib\n% 3: labmaplib(str)\n%\n% Arguments for Usage 1:\n%\n% I - An integer specifying the index of the colour map to be\n% generated or a string specifying a colour map name to search\n% for. Type labmaplib with no arguments to get a full list of\n% possible colour maps and their corresponding numbers.\n%\n% Possible param_name - value options:\n%\n% 'chromaK' - The scaling to apply to the chroma values of the colour map,\n% 0 - 1. The default is 1 giving a fully saturated colour map\n% as designed. However, depending on your application you may\n% want a colour map with reduced chroma/saturation values.\n% You can use values greater than 1 however gamut clipping is\n% likely to occur giving rise to artifacts in the colour map. \n% 'N' - Number of values in the colour map. Defaults to 256.\n% 'shift' - Fraction of the colour map length N that the colour map is\n% to be cyclically rotated, may be negative. (Should only be\n% applied to cyclic colour maps!). Defaults to 0.\n% 'reverse' - If set to 1 reverses the colour map. Defaults to 0.\n% 'diagnostics' - If set to 1 displays various diagnostic plots. Note the\n% diagnostic plots will be for the map _before_ any cyclic\n% shifting or reversing is applied. Defaults to 0.\n%\n% The parameter name strings can be abbreviated to their first letter.\n%\n% Returns:\n% map - Nx3 rgb colour map\n% name - A string giving a nominal name for the colour map\n% desc - A string giving a brief description of the colour map\n%\n% Colour Map naming convention:\n%\n% linear_kryw_5-100_c67_n256\n% / / | \\ \\\n% Colour Map attribute(s) / | \\ Number of colour map entries\n% / | \\\n% String indicating nominal | Mean chroma of colour map\n% hue sequence. |\n% Range of lightness values\n%\n% In addition, the name of the colour map may have cyclic shift information\n% appended to it, it may also have a flag indicating it is reversed. \n% \n% cyclic_wrwbw_90-40_c42_n256_s25_r\n% / \\\n% / Indicates that the map is reversed.\n% / \n% Percentage of colour map length\n% that the map has been rotated by.\n%\n% * Attributes may be: linear, diverging, cyclic, rainbow, or isoluminant. A\n% colour map may have more than one attribute. For example, diverging-linear or\n% cyclic-isoluminant.\n%\n% * Lightness values can range from 0 to 100. For linear colour maps the two\n% lightness values indicate the first and last lightness values in the\n% map. For diverging colour maps the second value indicates the lightness value\n% of the centre point of the colour map (unless it is a diverging-linear\n% colour map). For cyclic and rainbow colour maps the two values indicate the\n% minimum and maximum lightness values. Isoluminant colour maps have only\n% one lightness value. \n%\n% * The string of characters indicating the nominal hue sequence uses the following code\n% r - red g - green b - blue\n% c - cyan m - magenta y - yellow\n% o - orange v - violet \n% k - black w - white j - grey\n%\n% ('j' rhymes with grey). Thus a 'heat' style colour map would be indicated by\n% the string 'kryw'. If the colour map is predominantly one colour then the\n% full name of that colour may be used. Note these codes are mainly used to\n% indicate the hues of the colour map independent of the lightness/darkness and\n% saturation of the colours.\n% \n% * Mean chroma/saturation is an indication of vividness of the colour map. A\n% value of 0 corresponds to a greyscale. A value of 50 or more will indicate a\n% vivid colour map.\n%\n%\n% Usage 2 and 3: labmaplib(str)\n%\n% Given the large number of colour maps that this function can create this usage\n% option provides some help by listing the numbers of all the colour maps with\n% names containing the string 'str'. Typically this is used to search for\n% colour maps having a specified attribute: 'linear', 'diverging', 'rainbow',\n% 'cyclic', or 'isoluminant' etc. If 'str' is omitted all colour maps are\n% listed. \n%\n% >> labmaplib % lists all colour maps\n% >> labmaplib('diverging') % lists all diverging colour maps\n%\n% Note the listing of colour maps can be a bit slow because each colour map has to\n% be created in order to determine its full name.\n%\n% See also: EQUALISECOLOURMAP, VIEWLABSPACE, SINERAMP, CIRCLESINERAMP, COLOURMAPPATH\n\n% Adding your own colour maps is straightforward.\n%\n% 1) Colour maps are almost invariably defined via a spline path through CIELAB\n% colourspace. Use VIEWLABSPACE to work out the positions of the spline\n% control points in CIELAB space to achieve the colour map path you desire.\n% These are stored in an array 'colpts' with columns corresponding to L a\n% and b. If desired the path can be specified in terms of RGB space by\n% setting 'colourspace' to 'RGB'. See the ternary colour maps as an example.\n%\n% 2) Set 'splineorder' to 2 for a linear spline segments. Use 3 for a quadratic\n% b-spline.\n%\n% 3) If the colour map path has lightness gradient reversals set 'sigma' to a\n% value of around 5 to 7 to smooth the gradient reversal.\n%\n% 4) If the colour map is of very low lightness contrast, or isoluminant, set\n% the lightness, a and b colour difference weight vector W to [1 1 1].\n% See EQUALISECOLOURMAP for more details\n%\n% 5) Set the attribute and hue sequence strings ('attributeStr' and 'hueStr')\n% appropriately so that a colour map name can be generated. Note that if you\n% are constructing a cyclic colour map it is important that 'attributeStr'\n% contains the word 'cyclic'. This ensures that a periodic b-spline is used\n% and also ensures that smoothing is applied in a cyclic manner. Setting the\n% description string is optional.\n%\n% 6) Run LABMAPLIB specifying the number of your new colour map with the\n% diagnostics flag set to one. Various plots are generated allowing you to\n% check the perceptual uniformity, colour map path, and any gamut clipping of\n% your colour map.\n\n% Copyright (c) 2013-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% December 2013 Original version\n% March 2014 Various enhancements\n% August 2014 Catalogue listing\n% September 2014 Provision for specifying paths in RGB, cyclic shifting and\n% reversing \n\nfunction [map, name, desc] = labmaplib(varargin)\n\n [I, N, chromaK, shift, reverse, diagnostics] = parseinputs(varargin{:}); \n \n % Check if the user wants to list a catalogue of colour maps\n if ischar(I)\n catalogue(I);\n return\n end\n\n % Default parameters for colour map construction. \n % Individual colour map specifications may override some of these.\n colourspace = 'LAB'; % Control points specified in CIELAB space\n sigma = 0; % Default smoothing for colour map lightness equalisation.\n splineorder = 3; % Default order of b-spline colour map curve.\n formula = 'CIE76'; % Default colour difference formula.\n W = [1 0 0]; % Colour difference weighting for Lightness,\n % chroma and hue (default is to only use Lightness)\n desc = '';\n name = '';\n attributeStr = '';\n hueStr = '';\n \n switch I\n \n %% 1-19 series: Linear scales going from low to high\n \n case 1 % Grey 0 - 100 \n desc = 'Grey scale'; \n attributeStr = 'linear';\n hueStr = 'grey';\n colpts = [ 0 0 0 \n 100 0 0];\n splineorder = 2;\n \n case 2 % Grey 10 - 95\n desc = ['Grey scale with slightly reduced contrast to '...\n 'avoid display saturation problems'];\n attributeStr = 'linear';\n hueStr = 'grey'; \n colpts = [10 0 0\n 95 0 0];\n splineorder = 2;\n \n case 3 \n desc = 'Black-Red-Yellow-White heat colour map';\n attributeStr = 'linear';\n hueStr = 'kryw';\n\n colpts = [5 0 0\n 15 37 21\n 25 49 37\n 35 60 50\n 45 72 60\n 55 80 70\n 65 56 73\n 75 31 78\n 85 9 84\n 100 0 0 ];\n \n case 4 \n desc = 'Black-Red-Yellow heat colour map';\n attributeStr = 'linear';\n hueStr = 'kry';\n colpts = [5 0 0\n 15 37 21\n 25 49 37\n 35 60 50\n 45 72 60\n 55 80 70\n 65 56 73\n 75 31 78\n 85 9 84\n 98 -16 93];\n \n case 5 \n desc = 'Colour Map along the green edge of CIELAB space';\n attributeStr = 'linear';\n hueStr = 'green';\n colpts = [ 5 -9 5\n 15 -23 20\n 25 -31 31\n 35 -39 39\n 45 -47 47\n 55 -55 55\n 65 -63 63\n 75 -71 71\n 85 -79 79\n 95 -38 90]; \n \n case 6 \n desc = 'Blue shades running vertically up the blue edge of CIELAB space';\n attributeStr = 'linear';\n hueStr = 'blue';\n colpts = [ 5 30 -52\n 15 49 -80\n 25 64 -105\n 35 52 -103\n 45 26 -87\n 55 6 -72\n 65 -12 -56\n 75 -29 -40\n 85 -44 -24\n 95 -31 -9]; \n \n case 7 \n desc = 'Blue-Pink-Light Pink colour map';\n attributeStr = 'linear';\n hueStr = 'bmw';\n colpts = [ 5 30 -52\n 15 49 -80\n 25 64 -105\n 35 73 -105\n 45 81 -88\n 55 90 -71\n 65 85 -55\n 75 58 -38\n 85 34 -23\n 95 10 -7]; \n\n case 10 \n desc = 'Blue-Magenta-Orange-Yellow highly saturated colour map';\n attributeStr = 'linear';\n hueStr = 'bmy';\n colpts = [10 polar2ab( 78,-60) \n 20 polar2ab(100,-60)\n 30 polar2ab( 78,-40)\n 40 polar2ab( 74,-20) \n 50 polar2ab( 80, 0) \n 60 polar2ab( 80, 20)\n 70 polar2ab( 72, 50)\n 80 polar2ab( 84, 77)\n 95 polar2ab( 90, 95)];\n\n case 11 \n desc = 'Blue-Green-Yellow colour map';\n attributeStr = 'linear';\n hueStr = 'bgy';\n colpts = [10 polar2ab( 78,-60) \n 20 polar2ab(100,-60) \n 30 polar2ab( 80,-70)\n 40 polar2ab( 40,-100) \n 50 polar2ab( 37, 180) \n 60 polar2ab( 80, 135)\n 70 polar2ab( 93, 135)\n 80 polar2ab( 105, 135) % green\n 95 polar2ab( 90, 95)]; % yellow\n \n case 12 \n desc = 'Blue-Magenta-Green-Yellow highly saturated colour map';\n attributeStr = 'linear';\n hueStr = 'bmgy';\n colpts = [10 polar2ab( 78,-60) \n 20 polar2ab(100,-60) \n 30 polar2ab( 78,-40)\n 40 polar2ab( 74,-20) \n 50 polar2ab( 80, 0) \n 60 polar2ab( 95, 45)\n 70 polar2ab( 70, 110)\n 80 polar2ab( 105, 135)\n 95 polar2ab( 90, 95)]; \n \n case 13 \n desc = 'Dark Red-Brown-Green-Yellow colour map';\n attributeStr = 'linear';\n hueStr = 'rgy';\n colpts = [10 polar2ab( 35, 24) \n 20 polar2ab( 50, 35) \n 30 polar2ab( 49, 55)\n 40 polar2ab( 50, 75) \n 50 polar2ab( 55, 95) \n 60 polar2ab( 67, 115)\n 70 polar2ab( 75, 115)\n 80 polar2ab( 80, 100)\n 95 polar2ab( 90, 95)]; \n \n case 14\n desc = ['Attempt at a ''geographical'' colour map. '...\n 'Best used with relief shading'];\n attributeStr = 'linear';\n hueStr = 'gow';\n colpts = [60 polar2ab(20, 180) % pale blue green\n 65 polar2ab(30, 135)\n 70 polar2ab(35, 75)\n 75 polar2ab(45, 85)\n 80 polar2ab(22, 90) \n 85 0 0 ];\n \n case 15 % Adaptation of 14. Lighter and slightly more saturated. I\n % think this is better \n desc = ['Attempt at a ''geographical'' colour map. '...\n 'Best used with relief shading'];\n attributeStr = 'linear';\n hueStr = 'gow';\n colpts = [65 polar2ab(50, 135) % pale blue green\n 75 polar2ab(45, 75)\n 80 polar2ab(45, 85)\n 85 polar2ab(22, 90) \n 90 0 0 ];\n\n case 16\n desc = 'Attempt at a ''water depth'' colour map';\n attributeStr = 'linear';\n hueStr = 'blue';\n colpts = [95 0 0\n 80 polar2ab(20, -95)\n 70 polar2ab(25, -95)\n 60 polar2ab(25, -95)\n 50 polar2ab(35, -95)];\n\n \n % The following three colour maps are for ternary images, eg Landsat images\n % and radiometric images. These colours form the nominal red, green and\n % blue 'basis colours' that are used to form the composite image. They are\n % designed so that they, and their secondary colours, have nearly the same\n % lightness levels and comparable chroma. This provides consistent feature\n % salience no matter what channel-colour assignment is made. The\n % colour maps are specified as straight lines in RGB space. For their\n % derivation see\n % http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary\n \n case 17\n desc = 'red colour map for ternary images';\n attributeStr = 'linear';\n hueStr = 'ternary-red';\n colourspace = 'RGB';\n colpts = [0.00 0.00 0.00\n 0.90 0.17 0.00];\n\n splineorder = 2; \n \n case 18\n desc = 'green colour map for ternary images';\n attributeStr = 'linear';\n hueStr = 'ternary-green';\n colourspace = 'RGB';\n colpts = [0.00 0.00 0.00\n 0.00 0.50 0.00];\n \n splineorder = 2; \n \n case 19\n desc = 'blue colour map for ternary images';\n attributeStr = 'linear';\n hueStr = 'ternary-blue';\n colourspace = 'RGB';\n colpts = [0.00 0.00 0.00\n 0.10 0.33 1.00];\n\n splineorder = 2; \n \n %% 20 Series: Diverging colour maps\n \n % Note that on these colour maps we do not go to full white but use a\n % lightness value of 95. This helps avoid saturation problems on monitors.\n % A lightness smoothing sigma of 7 is used to avoid generating a false\n % feature at the white point in the middle. Note however, this does create\n % a small perceptual contrast blind spot at the middle.\n \n case 20 \n desc = 'Diverging blue-white-red colour map';\n attributeStr = 'diverging';\n hueStr = 'bwr';\n colpts = [40 polar2ab(83,-64)\n 95 0 0\n 40 polar2ab(83, 39)]; \n sigma = 7;\n splineorder = 2; \n \n case 21 \n desc = 'Diverging green-white-violet colour map';\n attributeStr = 'diverging';\n hueStr = 'gwv';\n colpts = [55 -50 55\n 95 0 0\n 55 60 -55]; \n sigma = 7;\n splineorder = 2; \n \n case 22 \n desc = 'Diverging green-white-red colour map';\n attributeStr = 'diverging';\n hueStr = 'gwr';\n colpts = [55 -50 55\n 95 0 0\n 55 63 39]; \n sigma = 7;\n splineorder = 2; \n \n case 23 \n desc = 'Diverging orange/brown to crimson/purple';\n attributeStr = 'diverging';\n hueStr ='owm';\n colpts = [45 polar2ab(63, 61)\n 95 0 0 \n 45 polar2ab(63, -15)]; \n sigma = 7;\n splineorder = 2; \n \n case 24\n desc = 'Diverging blue - black - red colour map';\n attributeStr = 'diverging';\n hueStr = 'bkr';\n colpts = [55 polar2ab(70, -85)\n 10 0 0\n 55 polar2ab(70, 35)]; \n sigma = 7;\n splineorder = 2; \n \n case 25\n desc = 'Diverging green - black - red colour map';\n attributeStr = 'diverging';\n hueStr = 'gkr';\n colpts = [60 polar2ab(80, 134)\n 10 0 0\n 60 polar2ab(80, 40)]; \n sigma = 7;\n splineorder = 2; \n \n case 26\n desc = 'Diverging blue - black - yellow colour map';\n attributeStr = 'diverging';\n hueStr = 'bky';\n colpts = [60 polar2ab(60, -95)\n 10 0 0\n 60 polar2ab(60, 85)]; \n sigma = 7;\n splineorder = 2; \n \n case 27\n desc = 'Diverging green - black - magenta colour map';\n attributeStr = 'diverging';\n hueStr = 'gkm';\n colpts = [60 polar2ab(80, 134)\n 10 0 0\n 60 polar2ab(80, -37)]; \n sigma = 7;\n splineorder = 2; \n \n case 28 % Constant lightness diverging map for when you want to use\n % relief shading ? Perhaps lighten the grey so it is not quite\n % isoluminant ?\n desc = 'Diverging isoluminat lightblue - lightgrey - orange colour map';\n attributeStr = 'diverging-isoluminant';\n hueStr = 'cjo';\n colpts = [70 polar2ab(50, -115)\n 70 0 0\n 70 polar2ab(50, 45)]; \n sigma = 7;\n splineorder = 2; \n W = [1 1 1];\n\n \n case 29 % Constant lightness diverging map for when you want to use\n % relief shading ? Perhaps lighten the grey so it is not quite\n % isoluminant ?\n desc = 'Diverging isoluminat lightblue - lightgrey - pink colour map';\n attributeStr = 'diverging-isoluminant';\n hueStr = 'cjm';\n colpts = [75 polar2ab(48, -127)\n 75 0 0\n 75 polar2ab(48, -30)]; \n sigma = 7;\n splineorder = 2; \n W = [1 1 1];\n \n \n % 30 Series: Cyclic colour maps\n \n case 31 % Cyclic isoluminant path around perimeter of 60 slice Looks\n % reasonable, may want a bit of cyclic shifting, but looks good.\n % It really hurts to look at a sinewave with this map!\n attributeStr = 'cyclic-isoluminant';\n hueStr = 'grmbg';\n colpts = [60 -55 60\n 60 0 60\n 60 60 65\n 60 70 0\n 60 95 -60\n 60 40 -60\n 60 5 -60\n 60 -40 0\n 60 -55 60];\n W = [1 1 1];\n \n case 32 % Cyclic non-isoluminant path between 45 and 55 lightness\n % Interesting but not as successful as No 31\n % Problem in the blue section\n attributeStr = 'cyclic';\n hueStr = 'bormb';\n colpts = [55 -55 -55\n 55 15 60\n 55 80 70\n 50 80 -5\n 45 80 -90\n 45 55 -90 \n 45 25 -90\n 50 -25 -25\n 55 -55 -55]; \n W = [1 1 1];\n \n case 33 % Attempt at an isoluminant green-magenta cyclic map\n % Perhaps apply a circshift of -25, or + 35 to it\n % It really hurts to look at a sinewave with this map!\n attributeStr = 'cyclic-isoluminant';\n hueStr = 'mvgom'; \n colpts = [65 70 -15\n 65 85 -55\n 65 40 -55\n 65 -55 25\n 65 -60 60\n 65 -20 65\n 65 70 -15];\n W = [1 1 1];\n \n case 34 % Circle at 55\n attributeStr = 'cyclic-isoluminant';\n hueStr = 'mgbm';\n colpts = [55 polar2ab(36,0)\n 55 polar2ab(36,60)\n 55 polar2ab(36,120)\n 55 polar2ab(36,180)\n 55 polar2ab(36,240)\n 55 polar2ab(36,300)\n 55 polar2ab(36,360)];\n W = [1 1 1];\n\n case 35 % Circle at 67 - sort of ok but a bit flouro\n attributeStr = 'cyclic-isoluminant';\n hueStr = 'mgbm';\n rad = 42;\n ang = 124;\n colpts = [67 polar2ab(rad, ang-90)\n 67 polar2ab(rad, ang)\n 67 polar2ab(rad, ang+90)\n 67 polar2ab(rad, ang+180)\n 67 polar2ab(rad, ang-90)];\n W = [1 1 1];\n \n case 36 % Same as 35 with shift for cycle of length pi\n attributeStr = 'cyclic-isoluminant_s';\n hueStr = 'mgbm';\n rad = 42;\n ang = 124;\n colpts = [67 polar2ab(rad, ang-90)\n 67 polar2ab(rad, ang)\n 67 polar2ab(rad, ang+90)\n 67 polar2ab(rad, ang+180)\n 67 polar2ab(rad, ang-90)];\n W = [1 1 1];\n shift = N/4;\n\n \n case 37 % Distorted larger circle at 55 but with reduced radius across\n % the cyan section of the circle to fit within the gamut.\n % Quite a good compromise.\n attributeStr = 'cyclic-isoluminant';\n hueStr = 'mogbm'; \n colpts = [55 polar2ab(60,0)\n 55 polar2ab(60,60)\n 55 polar2ab(60,120)\n 55 polar2ab(60,145) \n 55 polar2ab(37,180)\n 55 polar2ab(35,240)\n 55 polar2ab(50,270)\n 55 polar2ab(60,300)\n 55 polar2ab(60,360)];\n W = [1 1 1];\n \n case 39 % Constant lightness 'v' path to test importance of having a smooth\n % path in hue. Slight 'feature' at the green corner (Seems more\n % important on poor monitors) but is a good example of the\n % relative unimportance of hue slope continuity \n attributeStr = 'isoluminant-example';\n hueStr = 'vgr';\n colpts = [50 80 -75\n 50 -50 50\n 50 80 65];\n splineorder = 2; % linear path \n W = [0 0 0];\n \n \n %% 40 Series: Rainbow style colour maps\n \n case 41 % Reasonable rainbow colour map after it has been fixed by\n % equalisecolour map with a smoothing sigma value of about 7.\n desc = ['The least worst rainbow colour map I can devise. Note there are' ...\n ' small perceptual blind spots at yellow and red'];\n attributeStr = 'rainbow';\n hueStr = 'bgyrm'; \n colpts = [35 60 -100\n 45 -15 -30\n 60 -55 60\n 85 0 80\n 55 70 65\n 75 55 -35]; \n sigma = 7;\n splineorder = 2; % linear path \n\n case 42 % A sort of rainbow map. Deliberately illustrates issues in the\n % design of these maps. The direction/lightness discontinuities in\n % LAB space at green, yellow and red produce features in the\n % colour map. It is also interesting in that it shows the\n % importance of constant change in L. The slope is low from blue\n % to green relative green to yellow. This is noticeable when the\n % sineramp test image is viewed with this colour map\n attributeStr = 'rainbow'; \n hueStr = 'bgyrm'; \n colpts = [45 30 -80\n 55 -30 -10\n 60 -55 60\n 85 0 80\n 55 70 65\n 60 80 -55];\n splineorder = 2; % linear path \n W = [0 0 0];\n \n case 43 % Constant lightness of 50 version of the colour map above. \n attributeStr = 'isoluminant';\n hueStr = 'bgrm';\n colpts = [50 30 -80\n 50 -30 -10\n 50 -55 60\n 50 0 80\n 50 70 65\n 50 80 -55]; \n splineorder = 2; % linear path \n W = [1 1 1];\n\n case 44 % Similar to 41 but with the colour map finishing at red rather\n % than continuing onto pink.\n desc = ['Reasonable rainbow colour map from blue to red. Note there is' ...\n ' a small perceptual blind spot at yellow'];\n attributeStr = 'rainbow';\n hueStr = 'bgyr';\n colpts = [35 60 -100\n 45 -15 -30\n 60 -55 60\n 85 0 80\n 55 75 70];\n sigma = 5;\n splineorder = 2; % linear path \n\n \n %% Miscellaneous \n case 50 % Line from max blue saturation to max green saturation\n attributeStr = 'linear';\n hueStr = 'bg';\n colpts = [30 polar2ab(135, -59)\n 90 polar2ab(112, 135)];\n splineorder = 2; % linear path \n \n case 51 % Line from max red saturation to max green saturation\n attributeStr = 'linear';\n hueStr = 'rog';\n colpts = [50 polar2ab(100, 40)\n 90 polar2ab(112, 135)];\n splineorder = 2; % linear path \n \n case 52 % Line from max blue saturation to max red saturation\n desc = 'Line from max blue saturation to max red saturation';\n attributeStr = 'linear';\n hueStr = 'bmr';\n colpts = [20 polar2ab(110, -59)\n 60 polar2ab(100, 46)];\n splineorder = 2; % linear path \n \n case 53 % Line from black- max blue saturation to max green saturation\n % - white\n attributeStr = 'linear'; \n hueStr = 'bgw'; \n colpts = [5 0 0\n 30 polar2ab(100, -59)\n 40 polar2ab(115, -59)\n 80 polar2ab(112, 135)\n 90 polar2ab(100, 135)\n 95 0 0]; \n \n case 54 \n desc = 'Isoluminant arc blue-magenta-yellow at lightness = 65';\n attributeStr = 'isoluminant';\n hueStr = 'cmo';\n colpts = [65 -13 -55\n 65 48 -54\n 65 67 -7\n 65 61 40\n 65 22 68];\n W = [1 1 1];\n \n case 55 \n desc = 'Low contrast arc blue-magenta-yellow ';\n attributeStr = 'linear';\n hueStr = 'bmo';\n colpts = [50 polar2ab(80, -80)\n 55 polar2ab(90, -50)\n 60 polar2ab(82, -10)\n 65 polar2ab(80, 51)\n 75 polar2ab(77, 83)];\n W = [1 1 1];\n\n case 56 \n desc = 'Isoluminant green to orange at lightness 75';\n attributeStr = 'isoluminant';\n hueStr = 'go';\n colpts = [75 polar2ab(53, 135)\n 75 polar2ab(53, 80)];\n \n W = [1 1 1];\n splineorder = 2;\n \n case 57 % Grey 10 - 90\n desc = ['Grey scale with slightly reduced contrast to '...\n 'avoid display saturation problems'];\n attributeStr = 'linear';\n hueStr = 'grey';\n colpts = [10 0 0\n 90 0 0];\n splineorder = 2; \n \n case 58\n desc = ['Diverging blue - red colour map. No smoothing to illustrate' ...\n ' feature problem'];\n attributeStr = 'diverging-nosmoothing';\n hueStr = 'bwr';\n colpts = [40 31 -80\n 95 0 0\n 40 65 56]; \n sigma = 0;\n splineorder = 2; \n \n case 59 \n desc = ['Isoluminant blue to green to orange at lightness 70. '...\n 'Poor on its own but works well with relief shading'];\n attributeStr = 'isoluminant';\n hueStr = 'cgo';\n colpts = [70 polar2ab(40, -115)\n 70 polar2ab(50, 160)\n 70 polar2ab(50, 90)\n 70 polar2ab(50, 45)];\n W = [1 1 1];\n \n case 60 \n desc = ['Diverging blue - red colour map. Large degree of smoothing for' ...\n ' poster'];\n attributeStr = 'diverging-oversmoothed';\n hueStr = 'bwr';\n colpts = [40 31 -80\n 95 0 0\n 40 65 56]; \n sigma = 12;\n splineorder = 2; \n \n case 61 \n desc = 'Non-Isoluminant version of No 62, lightness 25 to 75.';\n attributeStr = 'linear';\n hueStr = 'bm';\n colpts = [25 polar2ab(40, -125)\n 42 polar2ab(40, -80)\n 59 polar2ab(40, -40)\n 75 polar2ab(50, 0)];\n \n case 62\n desc = ['Isoluminant version of No 61, lightness 70. '...\n 'Poor on its own but works well with relief shading'];\n attributeStr = 'isoluminant';\n hueStr = 'cm';\n colpts = [70 polar2ab(40, -125)\n 70 polar2ab(40, -80)\n 70 polar2ab(40, -40)\n 70 polar2ab(50, 0)];\n W = [1 1 1]; \n \n case 63 \n desc = 'Non-Isoluminant version of No 62, lightness 35 to 75.';\n attributeStr = 'linear';\n hueStr = 'bm';\n \n colpts = [35 polar2ab(40, -125)\n 48 polar2ab(40, -80)\n 62 polar2ab(40, -40)\n 75 polar2ab(50, 0)];\n \n case 64 % Adaptation of 59 shifted to 80 from 70\n desc = ['Isoluminant blue to green to orange at lightness 80. '...\n 'Poor on its own but works well with relief shading'];\n attributeStr = 'isoluminant';\n hueStr = 'cgo';\n colpts = [80 polar2ab(40, -115)\n 80 polar2ab(50, 160)\n 80 polar2ab(50, 90)\n 80 polar2ab(50, 45)];\n W = [1 1 1];\n \n %% More cyclic attempts \n \n case 70 % 29-9-2014 Everything one tries converges to a similar solution!\n % How do you get 4 perceptually equivalent land mark colours from\n % a tristimulaus system?!\n \n % Hit the corners of the gamut red - green - blue/cyan - blue with\n % small tweeks to keep linear path within the gamut. However,\n % keep the control points symmetric in terms of lightness and only\n % weight for lightness when equalising. This achieves symmetry of\n % the colour arrangement despite the non symmetric path because\n % the control points are symmetric in terms of lightness.\n % BUT the trouble is we 'see' only three colours! The colourmap\n % looks green for top half, blue for bottom left and red for\n % bottom right. Interesting example\n attributeStr = 'cyclic';\n hueStr = 'rgcbr';\n colpts = [55 75 65\n 80 -80 76\n 55 19 -71\n 30 65 -95\n 55 80 67];\n W = [1 0 0];\n sigma = 3; \n splineorder = 2;\n \n \n \n case 71 % Attempt at cyclic map based on No 41 a rainbow map\n % Looks really nice!!\n % Problem is that key colours are not spaced as well as one\n % would like.\n attributeStr = 'cyclic';\n hueStr = 'bgyrmb'; \n colpts = [35 60 -100\n 45 -15 -30\n 60 -55 60\n 85 0 80\n 55 70 65\n 75 55 -35\n 35 60 -100]; \n sigma = 5;\n splineorder = 2; % linear path \n\n \n case 72 % Variation of 78. Perceptually this is good. Excellent balance\n % of colours in the quadrants but the colour mix is not to my\n % taste. Don't like the green. The reg-green transition clashes\n attributeStr = 'cyclic';\n hueStr = 'bgrmb'; \n blu = [35 70 -100];\n colpts = [blu\n 70 -70 64\n 35 65 50\n 70 75 -46\n blu ]; \n sigma = 7;\n splineorder = 2; % linear path \n \n case 73 % 2nd Attempt to modify 71 so that key colours are placed at\n % quadrants. Competing with 74 but I think this is a bit\n % better but 74 has better symmetry\n\n attributeStr = 'cyclic';\n hueStr = 'bgyrm'; \n colpts = [35 60 -100\n 45 -15 -30\n 80 0 80\n 53 70 65\n 80 47 -31\n 35 60 -100]; \n sigma = 7;\n splineorder = 2; % linear path \n\n \n case 74 % 3rd Attempt to modify 71 so that key colours are placed at\n % quadrants. Competing with 73. Has better symmetry\n\n attributeStr = 'cyclic';\n hueStr = 'byrmb'; \n colpts = [40 70 -95\n 60 -25 -20\n 80 0 80\n 40 70 -95\n 80 47 -31\n 60 80 -65\n 40 70 -95]; \n sigma = 7;\n splineorder = 2; % linear path \n\n \n \n case 75 % Like 70 but use yellow instead of green - Nicer to look at\n \n attributeStr = 'cyclic';\n hueStr = 'rycbr';\n colpts = [55 75 65\n 90 -10 85\n 55 19 -71\n 20 50 -77\n 55 80 67];\n W = [1 0 0];\n sigma = 3; \n splineorder = 2;\n \n \n \n case 76 % Try a variation based on 78 with green instead of magenta. OK\n % but I dislike the colour mix\n attributeStr = 'cyclic';\n hueStr = 'byrmb'; \n blu = [35 70 -100];\n colpts = [blu\n 85 -85 81\n 35 60 48\n% 35 -40 40\n 85 3 87\n blu ]; \n sigma = 7;\n splineorder = 2; % linear path \n\n case 476 % okish\n\n attributeStr = 'cyclic';\n hueStr = 'byrmb'; \n blu = [35 70 -100];\n colpts = [blu\n 85 -40 -25\n 35 -40 40\n 85 10 87\n 60 35 -60\n blu ]; \n sigma = 7;\n splineorder = 2; % linear path \n\n\n case 479 % Try same as 477 but with yellow/orange instead of green and\n % cyan instead of magenta. Nup!\n attributeStr = 'cyclic';\n hueStr = 'byrmb'; \n blu = [35 70 -100];\n colpts = [blu\n 70 37 77\n 35 65 50\n 70 -12 -50\n blu ]; \n sigma = 7;\n splineorder = 2; % linear path \n \n \n case 77 % OK\n attributeStr = 'cyclic';\n hueStr = 'mygbm';\n ang = 112;\n colpts = [70 polar2ab(46, ang-90)\n 90 polar2ab(82, ang)\n 70 polar2ab(46, ang+90)\n 50 polar2ab(82, ang+180)\n 70 polar2ab(46, ang-90)];\n W = [1 1 1];\n \n\n case 78 % Development of 74 to improve placement of key colours.\n % Control points are placed so that lightness steps up and\n % down are equalised. Additional intermediate points are\n % placed to try to even up the 'spread' of the key colours.\n % I think this is my best zigzag style cyclic map - Good!\n \n attributeStr = 'cyclic';\n hueStr = 'mrybm'; \n mag = [75 60 -40];\n yel = [75 0 77];\n blu = [35 70 -100];\n red = [35 60 48];\n colpts = [mag\n 55 70 0 \n red\n 55 35 62\n yel\n 50 -20 -30\n blu\n 55 45 -67\n mag];\n \n sigma = 7;\n splineorder = 2; % linear path \n \n \n case 79 % We start at dark pink with 0 phase 90 (the peak corresponds to\n % the brightest point in the colour map at yellow, then down to\n % green/blue at 180, blue at 270 (darkest point) then back up to\n % dark pink.\n attributeStr = 'cyclic'; \n hueStr = 'mybm';\n colpts = [67.5 42.5 15\n 95 -30 85\n 67.5 -42.5 -15\n 40 30 -85\n 67.5 42.5 15]; \n W = [1 1 1];\n sigma = 9; \n \n case 80 % Try to push 79 a bit further. Greater range of lightness\n % values and slightly more saturated colours. Seems to work\n % however I do not find the colour sequence that\n % attractive. This is a constraint of the gamut.\n attributeStr = 'cyclic';\n hueStr = 'mybm'; \n ang = 124;\n colpts = [60 polar2ab(40, ang-90)\n 100 polar2ab(98, ang)\n 60 polar2ab(40, ang+90)\n 20 polar2ab(98, ang+180)\n 60 polar2ab(40, ang-90)];\n W = [1 1 1];\n sigma = 7; \n \n case 82\n desc = 'Cyclic: greyscale'; % Works well\n attributeStr = 'cyclic';\n hueStr = 'grey';\n colpts = [50 0 0\n 85 0 0\n 15 0 0\n 50 0 0];\n sigma = 7;\n splineorder = 2;\n \n case 84 % red-white-blue-black-red allows quadrants to be identified\n desc = 'Cyclic: red - white - blue - black - red'; \n attributeStr = 'cyclic';\n hueStr = 'rwbkr';\n colpts = [50 polar2ab(85, 39)\n 85 0 0\n 50 polar2ab(85, -70)\n 15 0 0\n 50 polar2ab(85, 39)];\n sigma = 7;\n splineorder = 2;\n\n case 85 % A big diamond across the gamut. Really good!\n % Incorporates two extra conrol points around blue to extend the\n % width of that segment slightly.\n attributeStr = 'cyclic';\n hueStr = 'mygbm';\n colpts = [62.5 83 -54\n 80 20 25\n 95 -20 90\n 62.5 -65 62 \n 42 10 -50\n 30 75 -103 \n 48 70 -80 \n 62.5 83 -54];\n sigma = 7;\n splineorder = 2;\n \n \n case 87 % works fine but I think I would rather use 88 below instead\n desc = 'Cyclic: grey-yellow-grey-blue'; \n attributeStr = 'cyclic';\n hueStr = 'jyjbj';\n colpts = [60 0 0\n 90 -10 90\n 60 0 0\n 30 79 -108\n 60 0 0];\n sigma = 7;\n splineorder = 2; \n\n case 88 % % white-red-white-blue-white Works nicely\n desc = 'Cyclic: white - red - white - blue'; \n attributeStr = 'cyclic';\n hueStr = 'wrwbw';\n colpts = [90 0 0\n 40 65 56\n 90 0 0\n 40 31 -80\n 90 0 0];\n sigma = 7;\n splineorder = 2; \n \n\n %-------------------------------------------\n case 101\n desc = ['Two linear segments with different slope to illustrate importance' ...\n ' of lightness gradient. Equalised lightness.'];\n attributeStr = 'linear-lightnessnormalised';\n hueStr = 'by';\n colpts = [40 polar2ab(60, -75)\n 72 0 0\n 80 polar2ab(70, 105)]; \n splineorder = 2;\n \n case 102\n desc = ['Two linear segments with different slope to illustrate importance' ...\n ' of lightness gradient. Equalised CIE76'];\n attributeStr = 'linear-CIE76normalised';\n hueStr = 'by';\n colpts = [40 polar2ab(60, -75)\n 72 0 0\n 80 polar2ab(70, 105)];\n W = [1 1 1];\n splineorder = 2;\n \n \n case 103 % Constant lightness 'v' path to test unimportance of having a smooth\n % path in hue. Slight 'feature' at the red corner (Seems more\n % important on poor monitors)\n attributeStr = 'isoluminant-HueSlopeDiscontinuity';\n hueStr = 'brg';\n colpts = [50 17 -78\n 50 77 57\n 50 -48 50];\n splineorder = 2; % linear path \n W = [1 1 1]; \n \n case 104 % Linear diverging blue - grey - orange. This works but the\n % blue and orange are not nice to look at\n attributeStr = 'diverging-linear';\n hueStr = 'bjo';\n colpts = [30 polar2ab(90, -60)\n 47.5 0 0 \n 65 polar2ab(90,55)];\n splineorder = 2;\n \n case 105 % Linear diverging blue - grey - yellow. Works well\n attributeStr = 'diverging-linear';\n hueStr = 'bjy';\n colpts = [30 polar2ab(89, -59)\n 60 0 0 \n 90 polar2ab(89,96)];\n splineorder = 2;\n \n case 106 % Linear diverging blue - grey - green\n attributeStr = 'diverging-linear';\n hueStr = 'bjg';\n colpts = [20 polar2ab(110, -58)\n 55 0 0 \n 90 polar2ab(110,135)];\n splineorder = 2;\n \n case 107 % Linear diverging blue - grey - red\n attributeStr = 'diverging-linear';\n hueStr = 'bjr'; \n colpts = [30 polar2ab(105, -60)\n 42.5 0 0 \n 55 polar2ab(105,40)];\n splineorder = 2;\n \n \n case 108 % Linear diverging blue - grey - magenta\n attributeStr = 'diverging-linear';\n hueStr = 'bjm'; \n colpts = [30 polar2ab(105, -60)\n 45 0 0 \n 60 polar2ab(105,-32)];\n splineorder = 2;\n \n case 109 % low contrast diverging map for when you want to use\n % relief shading Adapted from 29. Works well\n desc = 'Diverging lowcontrast cyan - white - magenta colour map';\n attributeStr = 'diverging';\n hueStr = 'cwm';\n colpts = [80 polar2ab(44, -135)\n 100 0 0\n 80 polar2ab(44, -30)]; \n sigma = 0; % Try zero smoothing- not needed for low contrast\n splineorder = 2; \n W = [1 1 1];\n\n case 110 % low contrast diverging map for when you want to use\n % relief shading. Try green-white-yellow becuase you have have\n % much more strongly saturated colours. Works well but colours\n % are a bit unusual. Unsure which should be +ve or -ve\n desc = 'Diverging lowcontrast green - white - yellow colour map';\n attributeStr = 'diverging';\n hueStr = 'gwy';\n colpts = [80 polar2ab(83, 135)\n 95 0 0\n 80 polar2ab(83, 80)]; \n sigma = 0;\n splineorder = 2; \n W = [1 1 1];\n \n case 111 % Slightly increased contrast version of 109 works well with\n % relief shading.\n attributeStr = 'diverging';\n hueStr = 'bwr';\n colpts = [60 polar2ab(60, -85)\n 95 0 0\n 60 polar2ab(60, 40)]; \n sigma = 0;\n splineorder = 2; \n W = [1 1 1];\n \n case 112 % low contrast linear diverging attempt\n % magenta grey yellow. OK but colour interpretation not so\n % intuitive \n attributeStr = 'diverging';\n hueStr = 'mjy';\n colpts = [70 polar2ab(87, -32)\n 82.5 0 0\n 95 polar2ab(87, 100)]; \n sigma = 0;\n splineorder = 2; \n W = [1 1 1]; \n \n case 113 % Lightened version of 20 for relief shading - Good.\n desc = 'Diverging blue - red colour map';\n attributeStr = 'diverging';\n hueStr = 'bwr';\n colpts = [55 polar2ab(73,-74)\n 98 0 0\n 55 polar2ab(73, 39)]; \n sigma = 3; % Less smoothing needed for low contrast\n splineorder = 2; \n \n \n %% Special colour maps designed to illustrate various design principles.\n \n % A set of isoluminant colour maps only varying in saturation to test\n % the importance of saturation (not much) Colour Maps are linear with\n % a reversal to test importance of continuity. \n % uses de2000 with no smoothing\n \n case 200 % Isoluminant 50 only varying in saturation\n attributeStr = 'isoluminant';\n hueStr = 'r';\n colpts = [50 0 0\n 50 77 64\n 50 0 0];\n splineorder = 2;\n W = [1 1 1];\n \n case 201 % Isoluminant 50 only varying in saturation\n attributeStr = 'isoluminant';\n hueStr = 'b';\n colpts = [50 0 0\n 50 0 -56\n 50 0 0];\n splineorder = 2;\n W = [1 1 1]; \n \n case 202 % Isoluminant 90 only varying in saturation\n attributeStr = 'isoluminant';\n hueStr = 'isoluminant_90_g';\n colpts = [90 0 0\n 90 -76 80\n 90 0 0];\n splineorder = 2;\n W = [1 1 1]; \n\n \n case 203 % Isoluminant 55 only varying in saturation. CIEDE76\n attributeStr= 'isoluminant-CIE76';\n hueStr = 'jr';\n colpts = [55 0 0\n 55 80 67];\n splineorder = 2;\n W = [1 1 1]; \n formula = 'CIE76';\n \n case 204 % Same as 203 but using CIEDE2000\n attributeStr= 'isoluminant-CIEDE2000';\n hueStr = 'jr';\n colpts = [55 0 0\n 55 80 67];\n splineorder = 2;\n W = [1 1 1]; \n formula = 'CIEDE2000'; \n \n case 205 % Grey 0 - 100. Same as No 1 but with CIEDE2000\n desc = 'Grey scale'; \n attributeStr= 'linear-CIEDE2000';\n hueStr = 'grey';\n colpts = [ 0 0 0 \n 100 0 0];\n splineorder = 2;\n formula = 'CIEDE2000'; \n\n case 206 % Isoluminant 30 only varying in saturation\n attributeStr= 'isoluminant';\n hueStr = 'b';\n colpts = [30 0 0\n 30 77 -106];\n splineorder = 2;\n W = [1 1 1]; \n \n case 210 % Blue to yellow section of rainbow map 41 for illustrating\n % colour ordering issues\n attributeStr= 'rainbow-section1';\n hueStr = 'bgy'; \n colpts = [35 60 -100\n 45 -15 -30\n 60 -55 60\n 85 0 80];\n splineorder = 2; % linear path \n\n case 211 % Red to yellow section of rainbow map 41 for illustrating\n % colour ordering issues\n attributeStr= 'rainbow-section2';\n hueStr = 'ry'; \n colpts = [55 70 65\n 85 0 80];\n splineorder = 2; % linear path \n\n case 212 % Red to pink section of rainbow map 41 for illustrating\n % colour ordering issues\n attributeStr= 'rainbow-section3'; \n hueStr = 'rm'; \n colpts = [55 70 65\n 75 55 -35]; \n splineorder = 2; % linear path \n \n\n \n %% Another attempt at getting a better set of ternary colour maps. Try\n % slightly unequal lightness values\n case 217\n desc = '5-55 lightness red colour map for radiometric data';\n attributeStr = 'linear';\n hueStr = 'ternary-red';\n ang = 36; % 37\n colpts = [5 0 0\n 30 polar2ab(38,ang) % 40\n 55 polar2ab(94, ang)]; % 100 39\n splineorder = 2;\n \n case 218\n desc = '5-55 lightness green colour map for radiometric data';\n attributeStr = 'linear';\n hueStr = 'ternary-green';\n colpts = [5 0 0\n 65 polar2ab(88, 137)]; % 90 136\n splineorder = 2; \n \n case 219\n desc = '5-55 lightness blue colour map for radiometric data';\n attributeStr = 'linear';\n hueStr = 'ternary-blue';\n colpts = [5 0 0\n 43 polar2ab(87, -65)]; % 93 54\n splineorder = 2; \n \n\n \n %% ------ Rejects / Maps that need more work -------------\n % These are not listed in a catalogue search\n \n case 336 % Circle at 75 - is too bright ? might be ok with relief\n % shading if that makes any sense with cyclic data\n attributeStr = 'cyclic-isoluminant';\n hueStr = 'mgbm';\n colpts = [75 polar2ab(43,0)\n 75 polar2ab(43,60)\n 75 polar2ab(43,120)\n 75 polar2ab(43,180)\n 75 polar2ab(43,240)\n 75 polar2ab(43,300)\n 75 polar2ab(43,360)];\n W = [1 1 1]; \n \n \n case 374 % More circular less lightness contrast. Dk Green violet red,\n % orange greem cycle. Not centred on grey. Might be ok with\n % some work. Want some compromise between equalisation on 1\n % or 2.\n attributeStr = 'cyclic';\n hueStr = 'gmog';\n colpts = [50 polar2ab(50, 90)\n 40 polar2ab(40, -235)\n 50 polar2ab(50, -25)\n 60 polar2ab(90, 45)\n 50 polar2ab(50, 90)];\n W = [1 1 1];\n sigma = 9; \n \n \n case 378 % Similar philosophy to 77 but hue shift\n % pink yellow/green blue purple pink - also looks good but a\n % bit more lairy than 77\n attributeStr = 'cyclic';\n hueStr = 'mgbvm';\n colpts = [70 30 32\n 90 -75 80 \n 70 -30 -32\n 50 80 -75\n 70 30 32];\n W = [1 1 1];\n sigma = 9; \n \n \n case 381 % green cyan pink/red green - A bit dark and needs some\n % equalisation work\n attributeStr = 'cyclic';\n hueStr = 'gcmg'; \n colpts = [50 -40 25\n 70 -25 -40 \n 50 40 -25\n 30 25 40 \n 50 -40 25];\n W = [1 1 1];\n sigma = 9; \n \n case 384 % Nuh\n desc = 'Cyclic: red - white - green - black - red'; \n attributeStr = 'cyclic';\n hueStr = 'rwgkr';\n colpts = [50 polar2ab(40, 30)\n 85 0 0\n 50 polar2ab(40, 140)\n 15 0 0\n 50 polar2ab(40, 30)];\n sigma = 7;\n splineorder = 2;\n\n \n case 385 % Cyclic: red - green. Problem is that red is perceived as\n % +ve but is a darker colour than green giving confilicting\n % perceptual cues\n desc = 'Cyclic: red - green'; \n attributeStr = 'cyclic';\n hueStr = 'gr';\n colpts = [65 0 60\n 45 70 50\n 85 -70 70 \n 65 0 60];\n sigma = 7;\n splineorder = 2; \n \n case 386 \n desc = 'Cyclic: red - blue'; % A bit harsh on the eye but the colour\n % and lighness cues are in sync\n attributeStr = 'cyclic';\n hueStr = 'vrvbv';\n colpts = [45 60 -17.5\n 55 70 65\n 35 50 -100\n 45 60 -17.5];\n sigma = 7;\n splineorder = 2; \n \n \n \n %%------------------------------------------------------------- \n \n otherwise\n warning('Sorry, no colour map option with that number');\n map = [];\n return\n \n end\n\n \n % Adjust chroma/saturation but only if colourspace is LAB\n if strcmpi(colourspace, 'LAB')\n colpts(:,2:3) = chromaK * colpts(:,2:3);\n end\n \n % Colour map path is formed via a b-spline in the specified colour space\n Npts = size(colpts,1);\n \n if Npts < 2\n error('Number of input points must be 2 or more')\n elseif Npts < splineorder\n splineorder = Npts;\n fprintf('Warning: Spline order is greater than number of data points\\n')\n fprintf('Reducing order of spline to %d\\n', Npts)\n end\n \n % Rely on the attribute string to identify if colour map is cyclic. We may\n % want to construct a colour map that has identical endpoints but do not\n % necessarily want continuity in the slope of the colour map path.\n if strfind(attributeStr, 'cyclic')\n cyclic = 1;\n labspline = pbspline(colpts', splineorder, N);\n else\n cyclic = 0;\n labspline = bbspline(colpts', splineorder, N);\n end \n \n % Apply contrast equalisation with required parameters. Note that sigma is\n % normalised with respect to a colour map of length 256 so that if a short\n % colour map is specified the smoothing that is applied is adjusted to suit.\n sigma = sigma*N/256;\n map = equalisecolourmap(colourspace, labspline', formula,...\n W, sigma, cyclic, diagnostics); \n\n % If specified apply a cyclic shift to the colour map\n if shift\n if isempty(strfind(attributeStr, 'cyclic'))\n fprintf('Warning: Colour map shifting being applied to a non-cyclic map\\n');\n end\n map = circshift(map, round(N*shift)); \n end\n \n if reverse\n map = flipud(map);\n end \n \n % Compute mean chroma of colour map\n lab = rgb2lab(map);\n meanchroma = sum(sqrt(sum(lab(:,2:3).^2, 2)))/N;\n \n % Construct lightness range description\n if strcmpi(colourspace, 'LAB') % Use the control points\n L = colpts(:,1);\n else % For RGB use the converted CIELAB values\n L = round(lab(:,1));\n end\n minL = min(L);\n maxL = max(L);\n \n if minL == maxL % Isoluminant\n LStr = sprintf('%d', minL);\n \n elseif L(1) == maxL && ...\n (~isempty(strfind(attributeStr, 'diverging')) ||...\n ~isempty(strfind(attributeStr, 'linear')))\n LStr = sprintf('%d-%d', maxL, minL);\n \n else \n LStr = sprintf('%d-%d', minL, maxL);\n end\n \n % Build overall colour map name\n name = sprintf('%s_%s_%s_c%d_n%d',...\n attributeStr, hueStr, LStr, round(meanchroma), N);\n \n if shift\n name = sprintf('%s_s%d', name, round(shift*100)); \n end\n \n if reverse\n name = sprintf('%s_r', name);\n end \n \n \n if diagnostics % Print description and plot path in colourspace\n fprintf('%s\\n',desc);\n colourmappath(map, 6, 'lab', 10)\n end\n \n \n%------------------------------------------------------------------\n\nfunction ab = polar2ab(radius, angle_degrees)\n \n theta = angle_degrees/180*pi;\n ab = radius*[cos(theta) sin(theta)];\n \n\n%------------------------------------------------------------------\n%\n% Function to list colour maps with names containing a specific string.\n% Typically this is used to search for colour maps having a specified attribute:\n% 'linear', 'diverging', 'rainbow', 'cyclic', 'isoluminant' or 'all'.\n\nfunction catalogue(str)\n \n if ~exist('str', 'var')\n str = 'all';\n end\n \n fprintf('\\n No Colour Map name\\n')\n fprintf('---------------------------------\\n')\n \n warning('off');\n for n = 1:300\n [m, name] = labmaplib(n);\n if ~isempty(m)\n if any(strfind(name, str)) || strcmpi(str, 'all')\n fprintf('%4d %s\\n', n, name);\n end\n end\n end\n \n warning('on');\n\n%-----------------------------------------------------------------------\n% Function to parse the input arguments and set defaults\n\nfunction [I, N, chromaK, shift, reverse, diagnostics] = parseinputs(varargin)\n \n p = inputParser;\n\n numericORchar = @(x) isnumeric(x) || ischar(x);\n numericORlogical = @(x) isnumeric(x) || islogical(x);\n \n % The first argument is either a colour map number or a string to search for\n % in a colourmap name. If no argument is supplied it is assumed the user\n % wants to list all possible colourmaps. \n addOptional(p, 'I', 'all', numericORchar); \n \n % Optional parameter-value pairs and their defaults \n addParameter(p, 'N', 256, @isnumeric); \n addParameter(p, 'shift', 0, @isnumeric); \n addParameter(p, 'chromaK', 1, @isnumeric); \n addParameter(p, 'reverse', 0, numericORlogical); \n addParameter(p, 'diagnostics', 0, numericORlogical); \n \n parse(p, varargin{:});\n \n I = p.Results.I;\n N = p.Results.N;\n chromaK = p.Results.chromaK;\n shift = p.Results.shift;\n reverse = p.Results.reverse;\n diagnostics = p.Results.diagnostics; \n \n if abs(shift) > 1\n error('Cyclic shift fraction magnitude cannot be larger than 1');\n end\n \n if chromaK < 0\n error('chromaK must be greater than 0')\n end \n \n if chromaK > 1\n fprintf('Warning: chromaK is greater than 1. Gamut clipping may occur')\n end \n \n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "map2ermapperlutfile.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/map2ermapperlutfile.m", "size": 1797, "source_encoding": "utf_8", "md5": "aace8b9f7a1a077cdab2c5bc541bea51", "text": "% MAP2ERMAPPERLUTFILE Writes ER Mapper LUT colour map file\n%\n% Usage: map2ermapperlutfile(map, filename, name, description)\n%\n% Arguments: map - N x 3 rgb colour map of values 0-1.\n% filename - Filename of LUT file to create. A .lut ending is added\n% if the filename has no suffix.\n% name - Optional string to name the colour map. This is used\n% by ER Mapper to construct the lookup table menu list.\n% description - Optional string to describe the colour map.\n%\n% The ER Mapper LUT file format is also used ny MapInfo\n%\n% See also: READERMAPPERLUTFILE, READIMAGEJLUTFILE\n\n% 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK September 2014\n\nfunction map2ermapperlutfile(map, filename, name, description)\n \n if ~exist('name','var'), name = basename(namenpath(filename)); end\n if ~exist('description','var'), description = ''; end\n \n [N, chan] = size(map);\n if chan ~= 3\n error('Colourmap must be Nx3');\n end\n \n % Ensure file has a .lut ending\n if ~strendswith(filename, '.lut') \n filename = [filename '.lut'];\n end\n \n [fid, msg] = fopen(filename, 'wt');\n error(msg);\n\n % Scale colour map values to 16 bit ints\n map = round(map*(2^16 - 1));\n \n fprintf(fid, 'LookUpTable Begin\\n');\n fprintf(fid, ' Name = \"%s\"\\n', name);\n fprintf(fid, ' Description = \"%s\"\\n', description);\n fprintf(fid, ' NrEntries = %d\\n', N);\n fprintf(fid, ' LUT = {\\n', N);\n \n for n = 1:N\n fprintf(fid, '%8d %8d %8d %8d\\n',n-1, map(n,1), map(n,2), map(n,3));\n end\n \n fprintf(fid, ' }\\n');\n fprintf(fid, 'LookUpTable End\\n');\n \n fclose(fid);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "equalisecolourmap.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/equalisecolourmap.m", "size": 17848, "source_encoding": "utf_8", "md5": "c7a0f9aaa4f59e3e4036e8066e7ee6d4", "text": "% EQUALISECOLOURMAP - Equalise colour contrast over a colourmap\n%\n% Usage: newrgbmap = equalisecolourmap(rgblab, map, formula, W, sigma, diagnostics)\n%\n% Arguments: rgblab - String 'RGB' or 'LAB' indicating the type of data\n% in map.\n% map - A Nx3 RGB or CIELAB colour map\n% formula - String 'CIE76' or 'CIEDE2000'\n% W - A 3-vector of weights to be applied to the\n% lightness, chroma and hue components of the\n% difference equation. Use [1 0 0] to only take into\n% account lightness, [1 1 1] for the full formula.\n% See note below.\n% sigma - Optional Gaussian smoothing parameter, see\n% explanation below.\n% cyclic - Flag 1/0 indicating whether the colour map is\n% cyclic. This affects how smoothing is applied at\n% the end points.\n% diagnostics - Optional flag 0/1 indicating whether diagnostic\n% plots should be displayed. Defaults to 0.\n%\n% Returns: newrgbmap - RGB colour map adjusted so that the perceptual\n% contrast of colours along the colour map is constant.\n%\n% Suggested parameters:\n%\n% The CIE76 and CIEDE2000 colour difference formulas were developed for much\n% lower spatial frequencies than we are typically interested in. Neither is\n% ideal for our application. While the CIEDE2000 lightness correction is\n% probably useful the difference is barely noticeable. The CIEDE2000 chroma\n% correction is definitely *not* suitable for our needs. \n%\n% For colour maps with a significant range of lightness use:\n% formula = 'CIE76' or 'CIEDE2000'\n% W = [1 0 0] (Only correct for lightness)\n% sigma = 5 - 7\n%\n% For isoluminant or low lightness gradient colour maps use: \n% formula = 'CIE76'\n% W = [1 1 1] (Correct for colour and lightness)\n% sigma = 5 - 7\n%\n% Ideally, for a colour map to be effective the perceptual contrast along the\n% colour map should be constant. Many colour maps are very poor in this regard.\n% Try testing your favourite colour map on the SINERAMP test image. The\n% perceptual contrast is very much dominated by the contrast in colour lightness\n% values along the map. This function attempts to equalise the chosen\n% perceptual contrast measure along a colour map by stretching and/or\n% compressing sections of the colour map.\n%\n% This function's primary use is for the correction of colour maps generated by\n% CMAP however it can be applied to any colour map. There are limitations to\n% what this function can correct. When applied to some of MATLAB's colour maps\n% such as 'jet', 'hsv' and 'cool' you get colour discontinuity artifacts because\n% these colour maps have segments that are nearly constant in lightness.\n% However, it does a nice job of fixing up MATLAB's 'hot', 'winter', 'spring'\n% and 'autumn' colour maps. If you do see colour discontinuities in the\n% resulting colour map try changing W from [1 0 0] to [1 1 1], or some\n% intermediate weighting of [1 0.5 0.5], say.\n%\n% Difference formula: Neither CIE76 or CIEDE2000 difference measures are ideal\n% for the high spatial frequencies that we are interested in. Empirically I\n% find that CIEDE2000 seems to give slightly better results on colour maps where\n% there is a significant lightness gradient (this applies to most colour maps).\n% In this case you would be using a weighting vector W = [1 0 0]. For\n% isoluminant, or low lightness gradient colour maps where one is using a\n% weighting vector W = [1 1 1] CIE76 should be used as the CIEDE2000 chroma\n% correction is inapropriate for the spatial frequencies we are interested in.\n%\n% Weighting vetor W: The CIEDE2000 colour difference formula incorporates the\n% scaling parameters kL, kC, kH in the demonimator of the lightness, chroma, and\n% hue difference components respectively. The 3 components of W correspond to\n% the reciprocal of these 3 parameters. (I do not know why they chose to put\n% kL, kC, kH in the denominator. If you wanted to ignore, say, the chroma\n% component you would have to set kC to Inf, rather than setting W(2) to 0 which\n% seems more sensible to me). If you are using CIE76 then W(2) amd W(3) are\n% applied to the differences in a and b. In this case you should ensure W(2) =\n% W(3). In general, for the spatial frequencies of interest to us, lightness\n% differences are overwhelmingly more important than chroma or hue and W shoud\n% be set to [1 0 0]\n%\n% Smoothing parameter sigma: \n% The output colour map will have lightness values of constant slope magnitude.\n% However, it is possible that the sign of the slope may change, for example at\n% the mid point of a bilateral colour map. This slope discontinuity of lightness\n% can induce a false apparent feature in the colour map. A smaller effect is\n% also occurs for slope discontinuities in a and b. For such colour maps it can\n% be useful to introduce a small amount of smoothing of the Lab values to soften\n% the transition of sign in the slope to remove this apparent feature. However\n% in doing this one creates a small region of suppressed luminance contrast in\n% the colour map which induces a 'blind spot' that compromises the visibility of\n% features should they fall in that data range. Accordingly the smoothing\n% should be kept to a minimum. A value of sigma in the range 5 to 7 in a 256\n% element colour map seems about right. As a guideline sigma should not be more\n% than about 1/25 of the number of entries in the colour map, preferably less.\n%\n% If you use the CIEDE2000 formula option this function requires Gaurav Sharma's\n% MATLAB implementation of the CIEDE2000 color difference formula deltaE2000.m\n% available at: http://www.ece.rochester.edu/~gsharma/ciede2000/\n%\n% See also: CMAP, SINERAMP, COLOURMAPPATH, ISOCOLOURMAPPATH\n\n% Copyright (C) 2013-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% December 2013 - Original version\n% June 2014 - Generalised and cleaned up\n\nfunction newrgbmap = equalisecolourmap(rgblab, map, formula, W, sigma, cyclic, diagnostics)\n \n if ~exist('formula', 'var'), formula = 'CIE76'; end\n if ~exist('W', 'var'), W = [1 0 0]; end\n if ~exist('sigma', 'var'), sigma = 0; end\n if ~exist('cyclic', 'var'), cyclic = 0; end\n if ~exist('diagnostics', 'var'), diagnostics = 0; end\n \n N = size(map,1); % No of colour map entries\n\n if N/sigma < 25\n warning(['It is not recommended that sigma be larger than 1/25 of' ...\n ' colour map length'])\n end\n\n if strcmpi(rgblab, 'RGB') & (max(map(:)) > 1.01 | min(map(:) < 0.01))\n error('If map is RGB values should be in the range 0-1')\n elseif strcmpi(rgblab, 'LAB') & max(abs(map(:))) < 10\n error('If map is LAB magnitude of values are expected to be > 10')\n end\n \n % Use D65 whitepoint to match typical monitors.\n wp = whitepoint('D65');\n \n % If input is RGB convert colour map to Lab. \n if strcmpi(rgblab, 'RGB')\n rgbmap = map;\n labmap = applycform(map, makecform('srgb2lab', 'AdaptedWhitePoint', wp));\n L = labmap(:,1);\n a = labmap(:,2);\n b = labmap(:,3);\n elseif strcmpi(rgblab, 'LAB')\n labmap = map;\n rgbmap = applycform(map, makecform('lab2srgb', 'AdaptedWhitePoint', wp));\n L = map(:,1);\n a = map(:,2);\n b = map(:,3);\n else\n error('Input must be RGB or LAB')\n end\n\n % The following section of code computes the locations to interpolate into\n % the colour map in order to achieve equal steps of perceptual contrast.\n % The process is repeated recursively on its own output. This helps overcome\n % the approximations induced by using linear interpolation to estimate the\n % locations of equal perceptual contrast. This is mainly an issue for\n % colour maps with only a few entries.\n\n for iter = 1:3\n % Compute perceptual colour difference values along the colour map using\n % the chosen formula and weighting vector.\n if strcmpi(formula, 'CIE76')\n deltaE = cie76(L, a, b, W);\n elseif strcmpi(formula, 'CIEDE2000')\n if ~exist('deltaE2000','file')\n fprintf('You need Gaurav Sharma''s function deltaE2000.m\\n');\n fprintf('available at:\\n');\n fprintf('http://www.ece.rochester.edu/~gsharma/ciede2000/\\n');\n newrgbmap = [];\n return\n end\n \n deltaE = ciede2000(L, a, b, W);\n else\n error('Unknown colour difference formula')\n end\n \n % Form cumulative sum of of delta E values. However, first ensure all\n % values are larger than 0.001 to ensure the cumulative sum always\n % increases.\n deltaE(deltaE < 0.001) = 0.001;\n cumdE = cumsum(deltaE);\n \n % Form an array of equal steps in cumulative contrast change.\n equicumdE = (0:(N-1))'/(N-1) * (cumdE(end)-cumdE(1)) + cumdE(1);\n \n % Solve for the locations that would give equal Delta E values.\n method = 'linear';\n newN = interp1(cumdE, (1:N)', equicumdE, method, 'extrap');\n \n % newN now represents the locations where we want to interpolate into the\n % colour map to obtain constant perceptual contrast\n L = interp1((1:N)', L, newN, method, 'extrap'); \n a = interp1((1:N)', a, newN, method, 'extrap');\n b = interp1((1:N)', b, newN, method, 'extrap');\n \n % Record initial colour differences for evaluation at the end\n if iter == 1 \n initialdeltaE = deltaE;\n initialcumdE = cumdE;\n initialequicumdE = equicumdE;\n initialnewN = newN;\n end\n end\n \n % Apply smoothing of the path in CIELAB space if requested. The aim is to\n % smooth out sharp lightness/colour changes that might induce the perception\n % of false features. In doing this there will be some cost to the\n % perceptual contrast at these points.\n if sigma\n L = smooth(L, sigma, cyclic);\n a = smooth(a, sigma, cyclic);\n b = smooth(b, sigma, cyclic);\n end\n\n % Convert map back to RGB\n newlabmap = [L a b];\n newrgbmap = applycform(newlabmap, makecform('lab2srgb', 'AdaptedWhitePoint', wp));\n \n if diagnostics\n % Compute actual perceptual contrast values achieved\n if strcmpi(formula, 'CIE76')\n newdeltaE = cie76(L, a, b, W);\n elseif strcmpi(formula, 'CIEDE2000')\n newdeltaE = ciede2000(L, a, b, W);\n else\n error('Unknown colour difference formula')\n end\n \n show(sineramp,1,'Unequalised input colour map'), colormap(rgbmap);\n show(sineramp,2,'Equalised colour map'), colormap(newrgbmap);\n\n figure(3), clf\n subplot(2,1,1)\n plot(initialcumdE)\n title(sprintf('Cumulative change in %s of input colour map', formula));\n axis([1 N 0 1.05*max(cumdE(:))]);\n xlabel('Colour map index');\n\n subplot(2,1,2)\n plot(1:N, initialdeltaE, 1:N, newdeltaE)\n axis([1 N 0 1.05*max(initialdeltaE(:))]);\n legend('Original colour map', ...\n 'Adjusted colour map', 'location', 'NorthWest');\n title(sprintf('Magnitude of %s differences along colour map', formula));\n xlabel('Colour map index');\n ylabel('dE')\n \n % Convert newmap back to Lab to check for gamut clipping\n labmap = applycform(newrgbmap,...\n makecform('srgb2lab', 'AdaptedWhitePoint', wp));\n figure(4), clf\n subplot(3,1,3)\n plot(1:N, L-labmap(:,1),...\n 1:N, a-labmap(:,2),...\n 1:N, b-labmap(:,3))\n legend('Lightness', 'a', 'b', 'Location', 'NorthWest')\n maxe = max(abs([L-labmap(:,1); a-labmap(:,2); b-labmap(:,3)]));\n axis([1 N -maxe maxe]);\n title('Difference between desired and achieved L a b values (gamut clipping)')\n \n % Plot RGB values\n subplot(3,1,1)\n plot(1:N, newrgbmap(:,1),'r-',...\n 1:N, newrgbmap(:,2),'g-',...\n 1:N, newrgbmap(:,3),'b-')\n \n legend('Red', 'Green', 'Blue', 'Location', 'NorthWest')\n axis([1 N 0 1.1]); \n title('RGB values along colour map')\n \n % Plot Lab values\n subplot(3,1,2)\n plot(1:N, L, 1:N, a, 1:N, b)\n legend('Lightness', 'a', 'b', 'Location', 'NorthWest')\n axis([1 N -100 100]); \n title('L a b values along colour map')\n \n \n %% Extra plots to generate figures.\n % The following plots were developed for illustrating the\n % equalization of MATLAB's hot(64) colour map. Run using:\n % >> hoteq = equalisecolourmap('RGB', hot, 'CIE76', [1 0 0], 0, 0, 1);\n\n fs = 12; % fontsize\n % Colour difference values\n figure(10), clf\n plot(1:N, initialdeltaE, 'linewidth', 2);\n axis([1 N 0 1.05*max(initialdeltaE(:))]);\n title(sprintf('Magnitude of %s lightness differences along colour map', ...\n formula), 'fontweight', 'bold', 'fontsize', fs);\n \n xlabel('Colour map index', 'fontweight', 'bold', 'fontsize', fs);\n ylabel('dE', 'fontweight', 'bold', 'fontsize', fs);\n\n % Cumulative difference plot showing mapping of equicontrast colours\n figure(11), clf\n plot(initialcumdE, 'linewidth', 2), hold on\n s = 7;\n for n = 1:s:N\n line([0 initialnewN(n) initialnewN(n)],...\n [initialequicumdE(n) initialequicumdE(n) 0], ...\n 'linestyle', '--', 'color', [0 0 0])\n \n ah = s/2; % Arrow height and width\n aw = ah/5;\n plot([initialnewN(n)-aw initialnewN(n) initialnewN(n)+aw],...\n [ah 0 ah],'k-') \n end\n \n title(sprintf('Cumulative change in %s lightness of colour map', formula), ...\n 'fontweight', 'bold', 'fontsize', fs);\n axis([1 N+6 0 1.05*max(cumdE(:))]);\n xlabel('Colour map index', 'fontweight', 'bold', 'fontsize', fs);\n ylabel('Equispaced cumulative contrast', 'fontweight', 'bold', 'fontsize', fs);\n hold off\n \n \n end\n\n%----------------------------------------------------------------------------\n%\n% Function to smooth an array of values but also ensure end values are not\n% altered or, if the map is cyclic, ensures smoothing is applied across the end\n% points in a cyclic manner. Assumed that the input data is a column vector\n\nfunction Ls = smooth(L, sigma, cyclic)\n \n sze = ceil(6*sigma); if ~mod(sze,2), sze = sze+1; end\n G = fspecial('gaussian', [sze 1], sigma);\n \n if cyclic \n Le = [L(:); L(:); L(:)]; % Form a concatenation of 3 repetitions of the array. \n Ls = filter2(G, Le); % Apply smoothing filter\n % and then return the center section \n Ls = Ls(length(L)+1: length(L)+length(L));\n \n else % Non-cyclic colour map: Pad out input array L at both ends by 3*sigma\n % with additional values at the same slope. The aim is to eliminate\n % edge effects in the filtering\n extension = (1:ceil(3*sigma))';\n \n dL1 = L(2)-L(1);\n dL2 = L(end)-L(end-1);\n Le = [-flipud(dL1*extension)+L(1); L; dL2*extension+L(end)];\n \n Ls = filter2(G, Le); % Apply smoothing filter\n \n % Trim off extensions\n Ls = Ls(length(extension)+1 : length(extension)+length(L));\n end\n \n%----------------------------------------------------------------------------\n% Delta E using the CIE76 formula + weighting\n\nfunction deltaE = cie76(L, a, b, W)\n \n N = length(L);\n \n % Compute central differences \n dL = zeros(size(L));\n da = zeros(size(a));\n db = zeros(size(b));\n\n dL(2:end-1) = (L(3:end) - L(1:end-2))/2;\n da(2:end-1) = (a(3:end) - a(1:end-2))/2;\n db(2:end-1) = (b(3:end) - b(1:end-2))/2;\n \n % Differences at end points\n dL(1) = L(2) - L(1); dL(end) = L(end) - L(end-1);\n da(1) = a(2) - a(1); da(end) = a(end) - a(end-1);\n db(1) = b(2) - b(1); db(end) = b(end) - b(end-1);\n \n deltaE = sqrt(W(1)*dL.^2 + W(2)*da.^2 + W(3)*db.^2);\n \n%----------------------------------------------------------------------------\n% Delta E using the CIEDE2000 formula + weighting\n%\n% This function requires Gaurav Sharma's MATLAB implementation of the CIEDE2000\n% color difference formula deltaE2000.m available at:\n% http://www.ece.rochester.edu/~gsharma/ciede2000/\n\nfunction deltaE = ciede2000(L, a, b, W)\n\n N = length(L);\n Lab = [L(:) a(:) b(:)];\n KLCH = 1./W;\n \n % Compute deltaE using central differences\n deltaE = zeros(N, 1);\n deltaE(2:end-1) = deltaE2000(Lab(1:end-2,:), Lab(3:end,:), KLCH)/2; \n \n % Differences at end points \n deltaE(1) = deltaE2000(Lab(1,:), Lab(2,:), KLCH);\n deltaE(end) = deltaE2000(Lab(end-1,:), Lab(end,:), KLCH);\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "cmap.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/cmap.m", "size": 39595, "source_encoding": "utf_8", "md5": "935b84d3970635a6758ed182998117e1", "text": "% CMAP Library of perceptually uniform colour maps\n%\n% Usage: 1: [map, name, desc] = cmap(I, param_name, value ...)\n% 2: cmap\n% 3: cmap(str)\n%\n% Arguments for Usage 1:\n%\n% I - A string label indicating the colour map to be generated or a\n% string specifying a colour map name or attribute to search\n% for. Type 'cmap' with no arguments to get a full list of\n% possible colour maps and their corresponding labels.\n%\n% labels: 'L1' - 'L15' for linear maps\n% 'D1' - 'D12' for diverging maps\n% 'C1' - 'C9' for cyclic maps\n% 'R1' - 'R2' for rainbow maps\n% 'I1' - 'I3' for isoluminant maps\n%\n% Some colour maps have alternate labels for convenience and readability.\n% >> map = cmap('L1') or map = cmap('grey') will produce a linear grey map.\n% >> cmap % With no arguments lists all colour maps and labels.\n%\n% Possible param_name - value options:\n%\n% 'chromaK' - The scaling to apply to the chroma values of the colour map,\n% 0 - 1. The default is 1 giving a fully saturated colour map\n% as designed. However, depending on your application you may\n% want a colour map with reduced chroma/saturation values.\n% You can use values greater than 1 however gamut clipping is\n% likely to occur giving rise to artifacts in the colour map. \n% 'N' - Number of values in the colour map. Defaults to 256.\n% 'shift' - Fraction of the colour map length N that the colour map is\n% to be cyclically rotated, may be negative. (Should only be\n% applied to cyclic colour maps!). Defaults to 0.\n% 'reverse' - If set to 1 reverses the colour map. Defaults to 0.\n% 'diagnostics' - If set to 1 displays various diagnostic plots. Note the\n% diagnostic plots will be for the map _before_ any cyclic\n% shifting or reversing is applied. Defaults to 0.\n%\n% The parameter name strings can be abbreviated to their first letter.\n%\n% Returns:\n% map - Nx3 rgb colour map\n% name - A string giving a nominal name for the colour map\n% desc - A string giving a brief description of the colour map\n%\n%\n% Usage 2 and 3: cmap(str)\n%\n% Given the large number of colour maps that this function can create this usage\n% option provides some help by listing the numbers of all the colour maps with\n% names containing the string 'str'. Typically this is used to search for\n% colour maps having a specified attribute: 'linear', 'diverging', 'rainbow',\n% 'cyclic', or 'isoluminant' etc. If 'str' is omitted all colour maps are\n% listed. \n%\n% >> cmap % lists all colour maps\n% >> cmap('diverging') % lists all diverging colour maps\n%\n% Note the listing of colour maps can be a bit slow because each colour map has to\n% be created in order to determine its full name.\n%\n%\n% Colour Map naming convention:\n%\n% linear_kryw_5-100_c67_n256\n% / / | \\ \\\n% Colour Map attribute(s) / | \\ Number of colour map entries\n% / | \\\n% String indicating nominal | Mean chroma of colour map\n% hue sequence. |\n% Range of lightness values\n%\n% In addition, the name of the colour map may have cyclic shift information\n% appended to it, it may also have a flag indicating it is reversed. \n% \n% cyclic_wrwbw_90-40_c42_n256_s25_r\n% / \\\n% / Indicates that the map is reversed.\n% / \n% Percentage of colour map length\n% that the map has been rotated by.\n%\n% * Attributes may be: linear, diverging, cyclic, rainbow, or isoluminant. A\n% colour map may have more than one attribute. For example, diverging-linear or\n% cyclic-isoluminant.\n%\n% * Lightness values can range from 0 to 100. For linear colour maps the two\n% lightness values indicate the first and last lightness values in the\n% map. For diverging colour maps the second value indicates the lightness value\n% of the centre point of the colour map (unless it is a diverging-linear\n% colour map). For cyclic and rainbow colour maps the two values indicate the\n% minimum and maximum lightness values. Isoluminant colour maps have only\n% one lightness value. \n%\n% * The string of characters indicating the nominal hue sequence uses the following code\n% r - red g - green b - blue\n% c - cyan m - magenta y - yellow\n% o - orange v - violet \n% k - black w - white j - grey\n%\n% ('j' rhymes with grey). Thus a 'heat' style colour map would be indicated by\n% the string 'kryw'. If the colour map is predominantly one colour then the\n% full name of that colour may be used. Note these codes are mainly used to\n% indicate the hues of the colour map independent of the lightness/darkness and\n% saturation of the colours.\n% \n% * Mean chroma/saturation is an indication of vividness of the colour map. A\n% value of 0 corresponds to a greyscale. A value of 50 or more will indicate a\n% vivid colour map.\n%\n%\n% See also: EQUALISECOLOURMAP, VIEWLABSPACE, SINERAMP, CIRCLESINERAMP, COLOURMAPPATH\n\n% Adding your own colour maps is straightforward.\n%\n% 1) Colour maps are almost invariably defined via a spline path through CIELAB\n% colourspace. Use VIEWLABSPACE to work out the positions of the spline\n% control points in CIELAB space to achieve the colour map path you desire.\n% These are stored in an array 'colpts' with columns corresponding to L a and\n% b. If desired the path can be specified in terms of RGB space by setting\n% 'colourspace' to 'RGB'. See the ternary colour maps as an example. Note\n% the case expression for the colour map label must be upper case.\n%\n% 2) Set 'splineorder' to 2 for a linear spline segments. Use 3 for a quadratic\n% b-spline.\n%\n% 3) If the colour map path has lightness gradient reversals set 'sigma' to a\n% value of around 5 to 7 to smooth the gradient reversal.\n%\n% 4) If the colour map is of very low lightness contrast, or isoluminant, set\n% the lightness, a and b colour difference weight vector W to [1 1 1].\n% See EQUALISECOLOURMAP for more details\n%\n% 5) Set the attribute and hue sequence strings ('attributeStr' and 'hueStr')\n% appropriately so that a colour map name can be generated. Note that if you\n% are constructing a cyclic colour map it is important that 'attributeStr'\n% contains the word 'cyclic'. This ensures that a periodic b-spline is used\n% and also ensures that smoothing is applied in a cyclic manner. Setting the\n% description string is optional.\n%\n% 6) Run CMAP specifying the number of your new colour map with the diagnostics\n% flag set to one. Various plots are generated allowing you to check the\n% perceptual uniformity, colour map path, and any gamut clipping of your\n% colour map.\n\n% Copyright (c) 2013-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% December 2013 Original version\n% March 2014 Various enhancements\n% August 2014 Catalogue listing\n% September 2014 Provision for specifying paths in RGB, cyclic shifting and\n% reversing \n% October 2014 Renamed to CMAP (from LABMAPLIB) and all the failed\n% experimental maps cleaned out and retained maps renumbered\n% in a more coherent way\n\nfunction [map, name, desc] = cmap(varargin)\n\n [I, N, chromaK, shift, reverse, diagnostics] = parseinputs(varargin{:}); \n \n % Default parameters for colour map construction. \n % Individual colour map specifications may override some of these.\n colourspace = 'LAB'; % Control points specified in CIELAB space\n sigma = 0; % Default smoothing for colour map lightness equalisation.\n splineorder = 3; % Default order of b-spline colour map curve.\n formula = 'CIE76'; % Default colour difference formula.\n W = [1 0 0]; % Colour difference weighting for Lightness,\n % chroma and hue (default is to only use Lightness)\n desc = '';\n name = '';\n attributeStr = '';\n hueStr = '';\n \n switch I % Note all case expressions must be upper case.\n \n %----------------------------------------------------------------------------- \n %% Linear series\n \n case {'L1', 'GREY'} % Grey 0 - 100 \n desc = 'Grey scale'; \n attributeStr = 'linear';\n hueStr = 'grey';\n colpts = [ 0 0 0 \n 100 0 0];\n splineorder = 2;\n \n case {'L2', 'REDUCEDGREY'} % Grey 10 - 95\n desc = ['Grey scale with slightly reduced contrast to '...\n 'avoid display saturation problems'];\n attributeStr = 'linear';\n hueStr = 'grey'; \n colpts = [10 0 0\n 95 0 0];\n splineorder = 2;\n \n case {'L3', 'HEAT', 'HEATWHITE'}\n desc = 'Black-Red-Yellow-White heat colour map';\n attributeStr = 'linear';\n hueStr = 'kryw';\n\n colpts = [5 0 0\n 15 37 21\n 25 49 37\n 35 60 50\n 45 72 60\n 55 80 70\n 65 56 73\n 75 31 78\n 85 9 84\n 100 0 0 ];\n \n case {'L4', 'HEATYELLOW'}\n desc = 'Black-Red-Yellow heat colour map';\n attributeStr = 'linear';\n hueStr = 'kry';\n colpts = [5 0 0\n 15 37 21\n 25 49 37\n 35 60 50\n 45 72 60\n 55 80 70\n 65 56 73\n 75 31 78\n 85 9 84\n 98 -16 93];\n \n case 'L5'\n desc = 'Colour Map along the green edge of CIELAB space';\n attributeStr = 'linear';\n hueStr = 'green';\n colpts = [ 5 -9 5\n 15 -23 20\n 25 -31 31\n 35 -39 39\n 45 -47 47\n 55 -55 55\n 65 -63 63\n 75 -71 71\n 85 -79 79\n 95 -38 90]; \n \n case 'L6'\n desc = 'Blue shades running vertically up the blue edge of CIELAB space';\n attributeStr = 'linear';\n hueStr = 'blue';\n colpts = [ 5 30 -52\n 15 49 -80\n 25 64 -105\n 35 52 -103\n 45 26 -87\n 55 6 -72\n 65 -12 -56\n 75 -29 -40\n 85 -44 -24\n 95 -31 -9]; \n \n case 'L7'\n desc = 'Blue-Pink-Light Pink colour map';\n attributeStr = 'linear';\n hueStr = 'bmw';\n colpts = [ 5 30 -52\n 15 49 -80\n 25 64 -105\n 35 73 -105\n 45 81 -88\n 55 90 -71\n 65 85 -55\n 75 58 -38\n 85 34 -23\n 95 10 -7]; \n\n case 'L8'\n desc = 'Blue-Magenta-Orange-Yellow highly saturated colour map';\n attributeStr = 'linear';\n hueStr = 'bmy';\n colpts = [10 ch2ab( 78,-60) \n 20 ch2ab(100,-60)\n 30 ch2ab( 78,-40)\n 40 ch2ab( 74,-20) \n 50 ch2ab( 80, 0) \n 60 ch2ab( 80, 20)\n 70 ch2ab( 72, 50)\n 80 ch2ab( 84, 77)\n 95 ch2ab( 90, 95)];\n\n case 'L9' % Blue to yellow section of R1 with short extensions at\n % each end \n attributeStr = 'linear';\n hueStr = 'bgyw'; \n colpts = [15 50 -65\n 35 67 -100\n 45 -14 -30\n 60 -55 60\n 85 -10 80\n 95 -17 50\n 100 0 0];\n \n case {'L10', 'GEOGRAPHIC1'}\n desc = ['A ''geographical'' colour map. '...\n 'Best used with relief shading'];\n attributeStr = 'linear';\n hueStr = 'gow';\n colpts = [60 ch2ab(20, 180) % pale blue green\n 65 ch2ab(30, 135)\n 70 ch2ab(35, 75)\n 75 ch2ab(45, 85)\n 80 ch2ab(22, 90) \n 85 0 0 ];\n \n case {'L11', 'GEOGRAPHIC2'} % Lighter version of L10 with a bit more chroma \n desc = ['A ''geographical'' colour map. '...\n 'Best used with relief shading'];\n attributeStr = 'linear';\n hueStr = 'gow';\n colpts = [65 ch2ab(50, 135) % pale blue green\n 75 ch2ab(45, 75)\n 80 ch2ab(45, 85)\n 85 ch2ab(22, 90) \n 90 0 0 ];\n\n case {'L12', 'DEPTH'}\n desc = 'A ''water depth'' colour map';\n attributeStr = 'linear';\n hueStr = 'blue';\n colpts = [95 0 0\n 80 ch2ab(20, -95)\n 70 ch2ab(25, -95)\n 60 ch2ab(25, -95)\n 50 ch2ab(35, -95)];\n\n \n % The following three colour maps are for ternary images, eg Landsat images\n % and radiometric images. These colours form the nominal red, green and\n % blue 'basis colours' that are used to form the composite image. They are\n % designed so that they, and their secondary colours, have nearly the same\n % lightness levels and comparable chroma. This provides consistent feature\n % salience no matter what channel-colour assignment is made. The colour\n % maps are specified as straight lines in RGB space. For their derivation\n % see\n % http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary\n \n case {'L13', 'REDTERNARY'}\n desc = 'red colour map for ternary images';\n attributeStr = 'linear';\n hueStr = 'ternary-red';\n colourspace = 'RGB';\n colpts = [0.00 0.00 0.00\n 0.90 0.17 0.00];\n\n splineorder = 2; \n \n case {'L14', 'GREENTERNARY'}\n desc = 'green colour map for ternary images';\n attributeStr = 'linear';\n hueStr = 'ternary-green';\n colourspace = 'RGB';\n colpts = [0.00 0.00 0.00\n 0.00 0.50 0.00];\n \n splineorder = 2; \n \n case {'L15', 'BLUETERNARY'}\n desc = 'blue colour map for ternary images';\n attributeStr = 'linear';\n hueStr = 'ternary-blue';\n colourspace = 'RGB';\n colpts = [0.00 0.00 0.00\n 0.10 0.33 1.00];\n\n splineorder = 2; \n\n \n \n \n \n \n\n %--------------------------------------------------------------------------------\n %% Diverging colour maps\n \n % Note that on these colour maps often we do not go to full white but use a\n % lightness value of 95. This helps avoid saturation problems on monitors.\n % A lightness smoothing sigma of 5 to 7 is used to avoid generating a false\n % feature at the white point in the middle. Note however, this does create\n % a small perceptual contrast blind spot at the middle.\n \n case 'D1'\n desc = 'Diverging blue-white-red colour map';\n attributeStr = 'diverging';\n hueStr = 'bwr';\n colpts = [40 ch2ab(83,-64)\n 95 0 0\n 40 ch2ab(83, 39)]; \n sigma = 7;\n splineorder = 2; \n \n case 'D2'\n desc = 'Diverging green-white-violet colour map';\n attributeStr = 'diverging';\n hueStr = 'gwv';\n colpts = [55 -50 55\n 95 0 0\n 55 60 -55]; \n sigma = 7;\n splineorder = 2; \n \n case 'D3'\n desc = 'Diverging green-white-red colour map';\n attributeStr = 'diverging';\n hueStr = 'gwr';\n colpts = [55 -50 55\n 95 0 0\n 55 63 39]; \n sigma = 7;\n splineorder = 2; \n \n case 'D4'\n desc = 'Diverging blue - black - red colour map';\n attributeStr = 'diverging';\n hueStr = 'bkr';\n colpts = [55 ch2ab(70, -85)\n 10 0 0\n 55 ch2ab(70, 35)]; \n sigma = 7;\n splineorder = 2; \n \n case 'D5'\n desc = 'Diverging green - black - red colour map';\n attributeStr = 'diverging';\n hueStr = 'gkr';\n colpts = [60 ch2ab(80, 134)\n 10 0 0\n 60 ch2ab(80, 40)]; \n sigma = 7;\n splineorder = 2; \n \n case 'D6'\n desc = 'Diverging blue - black - yellow colour map';\n attributeStr = 'diverging';\n hueStr = 'bky';\n colpts = [60 ch2ab(60, -95)\n 10 0 0\n 60 ch2ab(60, 85)]; \n sigma = 7;\n splineorder = 2; \n\n case 'D7' % Linear diverging blue - grey - yellow. Works well\n attributeStr = 'diverging-linear';\n hueStr = 'bjy';\n colpts = [30 ch2ab(89, -59)\n 60 0 0 \n 90 ch2ab(89,96)];\n splineorder = 2;\n\n case 'D8' % Linear diverging blue - grey - red\n attributeStr = 'diverging-linear';\n hueStr = 'bjr'; \n colpts = [30 ch2ab(105, -60)\n 42.5 0 0 \n 55 ch2ab(105,40)];\n splineorder = 2;\n \n case 'D9' % Lightened version of D1 for relief shading - Good.\n desc = 'Diverging low contrast blue - red colour map';\n attributeStr = 'diverging';\n hueStr = 'bwr';\n colpts = [55 ch2ab(73,-74)\n 98 0 0\n 55 ch2ab(73, 39)]; \n sigma = 2; % Less smoothing needed for low contrast\n splineorder = 2; \n \n case 'D10' % low contrast diverging map for when you want to use\n % relief shading \n desc = 'Diverging low contrast cyan - white - magenta colour map';\n attributeStr = 'diverging';\n hueStr = 'cwm';\n colpts = [80 ch2ab(44, -135)\n 100 0 0\n 80 ch2ab(44, -30)]; \n sigma = 0; % No smoothing needed for lightness range of 20\n splineorder = 2; \n W = [1 1 1];\n \n case 'D11' % Constant lightness diverging map for when you want to use\n % relief shading ? Perhaps lighten the grey so it is not quite\n % isoluminant ?\n desc = 'Diverging isoluminat lightblue - lightgrey - orange colour map';\n attributeStr = 'diverging-isoluminant';\n hueStr = 'cjo';\n colpts = [70 ch2ab(50, -115)\n 70 0 0\n 70 ch2ab(50, 45)]; \n sigma = 7;\n splineorder = 2; \n W = [1 1 1];\n \n case 'D12' % Constant lightness diverging map for when you want to use\n % relief shading ? Perhaps lighten the grey so it is not quite\n % isoluminant ?\n desc = 'Diverging isoluminat lightblue - lightgrey - pink colour map';\n attributeStr = 'diverging-isoluminant';\n hueStr = 'cjm';\n colpts = [75 ch2ab(48, -127)\n 75 0 0\n 75 ch2ab(48, -30)]; \n sigma = 7;\n splineorder = 2; \n W = [1 1 1];\n \n \n %------------------------------------------------------------------------- \n %% Cyclic colour maps\n \n case 'C1' % I think this is my best zigzag style cyclic map - Good!\n % Control points are placed so that lightness steps up and\n % down are equalised. Additional intermediate points are\n % placed to try to even up the 'spread' of the key colours.\n attributeStr = 'cyclic';\n hueStr = 'mrybm'; \n mag = [75 60 -40];\n yel = [75 0 77];\n blu = [35 70 -100];\n red = [35 60 48];\n colpts = [mag\n 55 70 0 \n red\n 55 35 62\n yel\n 50 -20 -30\n blu\n 55 45 -67\n mag];\n \n sigma = 7;\n splineorder = 2; % linear path \n\n case 'C2' % A big diamond across the gamut. Really good! Incorporates two\n % extra cotnrol points around blue to extend the width of that\n % segment slightly.\n attributeStr = 'cyclic';\n hueStr = 'mygbm';\n colpts = [62.5 83 -54\n 80 20 25\n 95 -20 90\n 62.5 -65 62 \n 42 10 -50\n 30 75 -103 \n 48 70 -80 \n 62.5 83 -54];\n sigma = 7;\n splineorder = 2;\n \n case 'C3' % red-white-blue-black-red allows quadrants to be identified\n desc = 'Cyclic: red - white - blue - black - red'; \n attributeStr = 'cyclic';\n hueStr = 'rwbkr';\n colpts = [50 ch2ab(85, 39)\n 85 0 0\n 50 ch2ab(85, -70)\n 15 0 0\n 50 ch2ab(85, 39)];\n sigma = 7;\n splineorder = 2;\n \n case 'C4' % white-red-white-blue-white Works nicely\n desc = 'Cyclic: white - red - white - blue'; \n attributeStr = 'cyclic';\n hueStr = 'wrwbw';\n colpts = [90 0 0\n 40 65 56\n 90 0 0\n 40 31 -80\n 90 0 0];\n sigma = 7;\n splineorder = 2; \n\n case {'C5', 'CYCLICGREY'} % Cyclic greyscale Works well\n desc = 'Cyclic: greyscale'; \n attributeStr = 'cyclic';\n hueStr = 'grey';\n colpts = [50 0 0\n 85 0 0\n 15 0 0\n 50 0 0];\n sigma = 7;\n splineorder = 2;\n \n case 'C6' % Circle at 67 - sort of ok but a bit flouro\n attributeStr = 'cyclic-isoluminant';\n hueStr = 'mgbm';\n chr = 42;\n ang = 124;\n colpts = [67 ch2ab(chr, ang-90)\n 67 ch2ab(chr, ang)\n 67 ch2ab(chr, ang+90)\n 67 ch2ab(chr, ang+180)\n 67 ch2ab(chr, ang-90)];\n W = [1 1 1];\n \n case 'C7' % Elliptical path - ok\n attributeStr = 'cyclic';\n hueStr = 'mygbm';\n ang = 112;\n colpts = [70 ch2ab(46, ang-90)\n 90 ch2ab(82, ang)\n 70 ch2ab(46, ang+90)\n 50 ch2ab(82, ang+180)\n 70 ch2ab(46, ang-90)];\n W = [1 1 1];\n \n case 'C8' % Elliptical path. Greater range of lightness values and\n % slightly more saturated colours. Seems to work however I do\n % not find the colour sequence that attractive. This is a\n % constraint of the gamut.\n attributeStr = 'cyclic';\n hueStr = 'mybm'; \n ang = 124;\n colpts = [60 ch2ab(40, ang-90)\n 100 ch2ab(98, ang)\n 60 ch2ab(40, ang+90)\n 20 ch2ab(98, ang+180)\n 60 ch2ab(40, ang-90)];\n W = [1 1 1];\n sigma = 7; \n\n case 'C9' % Variation of C1. Perceptually this is good. Excellent balance\n % of colours in the quadrants but the colour mix is not to my\n % taste. Don't like the green. The reg-green transition clashes\n attributeStr = 'cyclic';\n hueStr = 'bgrmb'; \n blu = [35 70 -100];\n colpts = [blu\n 70 -70 64\n 35 65 50\n 70 75 -46\n blu ]; \n sigma = 7;\n splineorder = 2; % linear path \n \n \n %----------------------------------------------------------------------------- \n %% Rainbow style colour maps\n \n case {'R1', 'RAINBOW'} % Reasonable rainbow colour map after it has been\n % fixed by equalisecolourmap.\n desc = ['The least worst rainbow colour map I can devise. Note there are' ...\n ' small perceptual blind spots at yellow and red'];\n attributeStr = 'rainbow';\n hueStr = 'bgyrm'; \n colpts = [35 60 -100\n 45 -15 -30\n 60 -55 60\n 85 0 80\n 55 70 65\n 75 55 -35]; \n sigma = 7;\n splineorder = 2; % linear path \n\n case {'R2', 'RAINBOW2'} % Similar to R1 but with the colour map finishing\n % at red rather than continuing onto pink.\n desc = ['Reasonable rainbow colour map from blue to red. Note there is' ...\n ' a small perceptual blind spot at yellow'];\n attributeStr = 'rainbow';\n hueStr = 'bgyr';\n colpts = [35 60 -100\n 45 -15 -30\n 60 -55 60\n 85 0 80\n 55 75 70];\n sigma = 5;\n splineorder = 2; % linear path \n \n \n case 'R3' % Diverging rainbow. The blue and red points are matched in\n % lightness and chroma as are the green and magenta points \n attributeStr = 'diverging-rainbow';\n hueStr = 'bgymr';\n colpts = [45 39 -83\n 52 -23 -23\n 60 -55 55\n 85 -2 85\n 60 74 -17\n 45 70 59];\n \n sigma = 5;\n splineorder = 2; % linear path \n \n \n\n %----------------------------------------------------------------------------- \n %% Isoluminant colour maps \n \n case 'I1'\n desc = ['Isoluminant blue to green to orange at lightness 70. '...\n 'Poor on its own but works well with relief shading'];\n attributeStr = 'isoluminant';\n hueStr = 'cgo';\n colpts = [70 ch2ab(40, -115)\n 70 ch2ab(50, 160)\n 70 ch2ab(50, 90)\n 70 ch2ab(50, 45)];\n W = [1 1 1];\n\n case 'I2' % Adaptation of I1 shifted to 80 from 70\n desc = ['Isoluminant blue to green to orange at lightness 80. '...\n 'Poor on its own but works well with relief shading'];\n attributeStr = 'isoluminant';\n hueStr = 'cgo';\n colpts = [80 ch2ab(40, -115)\n 80 ch2ab(50, 160)\n 80 ch2ab(50, 90)\n 80 ch2ab(50, 45)];\n W = [1 1 1];\n \n case 'I3'\n attributeStr = 'isoluminant';\n hueStr = 'cm';\n colpts = [70 ch2ab(40, -125)\n 70 ch2ab(40, -80)\n 70 ch2ab(40, -40)\n 70 ch2ab(50, 0)];\n W = [1 1 1]; \n \n\n \n %----------------------------------------------------------------------------- \n %% Experimental colour maps and colour maps that illustrate some design principles\n\n\n case 'X1'\n desc = ['Two linear segments with different slope to illustrate importance' ...\n ' of lightness gradient.'];\n attributeStr = 'linear-lightnessnormalised';\n hueStr = 'by';\n colpts = [30 ch2ab(102, -54)\n 40 0 0\n 90 ch2ab(90, 95)];\n W = [1 0 0];\n splineorder = 2;\n \n case 'X2'\n desc = ['Two linear segments with different slope to illustrate importance' ...\n ' of lightness gradient.'];\n attributeStr = 'linear-CIE76normalised';\n hueStr = 'by';\n colpts = [30 ch2ab(102, -54)\n 40 0 0\n 90 ch2ab(90, 95)];\n W = [1 1 1];\n splineorder = 2; \n\n \n case 'X3' % Constant lightness 'v' path to test unimportance of having a smooth\n % path in hue/chroma. Slight 'feature' at the red corner (Seems more\n % important on poor monitors)\n attributeStr = 'isoluminant-HueChromaSlopeDiscontinuity';\n hueStr = 'brg';\n colpts = [50 17 -78\n 50 77 57\n 50 -48 50];\n splineorder = 2; % linear path \n W = [1 1 1]; \n \n \n \n % A set of isoluminant colour maps only varying in saturation to test\n % the importance of saturation (not much) Colour Maps are linear with\n % a reversal to test importance of continuity. \n \n case 'X10' % Isoluminant 50 only varying in saturation\n attributeStr = 'isoluminant';\n hueStr = 'r';\n colpts = [50 0 0\n 50 77 64\n 50 0 0];\n splineorder = 2;\n sigma = 0;\n W = [1 1 1];\n \n case 'X11' % Isoluminant 50 only varying in saturation\n attributeStr = 'isoluminant';\n hueStr = 'b';\n colpts = [50 0 0\n 50 0 -56\n 50 0 0];\n splineorder = 2;\n sigma = 0;\n W = [1 1 1]; \n \n case 'X12' % Isoluminant 90 only varying in saturation\n attributeStr = 'isoluminant';\n hueStr = 'isoluminant_90_g';\n colpts = [90 0 0\n 90 -76 80\n 90 0 0];\n splineorder = 2;\n sigma = 0;\n W = [1 1 1]; \n\n \n % Difference in CIE76 and CIEDE2000 in chroma \n \n case 'X13' % Isoluminant 55 only varying in chroma. CIEDE76\n attributeStr= 'isoluminant-CIE76';\n hueStr = 'jr';\n colpts = [55 0 0\n 55 80 67];\n splineorder = 2;\n W = [1 1 1]; \n formula = 'CIE76';\n \n case 'X14' % Same as X13 but using CIEDE2000\n attributeStr= 'isoluminant-CIEDE2000';\n hueStr = 'jr';\n colpts = [55 0 0\n 55 80 67];\n splineorder = 2;\n W = [1 1 1]; \n formula = 'CIEDE2000'; \n \n case 'X15' % Grey 0 - 100. Same as No 1 but with CIEDE2000\n desc = 'Grey scale'; \n attributeStr= 'linear-CIEDE2000';\n hueStr = 'grey';\n colpts = [ 0 0 0 \n 100 0 0];\n splineorder = 2;\n formula = 'CIEDE2000'; \n\n case 'X16' % Isoluminant 30 only varying in chroma\n attributeStr= 'isoluminant';\n hueStr = 'b';\n colpts = [30 0 0\n 30 77 -106];\n splineorder = 2;\n W = [1 1 1]; \n \n \n case 'X21' % Blue to yellow section of rainbow map R1 for illustrating\n % colour ordering issues\n attributeStr= 'rainbow-section1';\n hueStr = 'bgy'; \n colpts = [35 60 -100\n 45 -15 -30\n 60 -55 60\n 85 0 80];\n splineorder = 2; % linear path \n\n case 'X22' % Red to yellow section of rainbow map R1 for illustrating\n % colour ordering issues\n attributeStr= 'rainbow-section2';\n hueStr = 'ry'; \n colpts = [55 70 65\n 85 0 80];\n splineorder = 2; % linear path \n\n case 'X23' % Red to pink section of rainbow map R1 for illustrating\n % colour ordering issues\n attributeStr= 'rainbow-section3'; \n hueStr = 'rm'; \n colpts = [55 70 65\n 75 55 -35]; \n splineorder = 2; % linear path \n\n \n case 'XD1' % Same as D1 but with no smoothing\n desc = 'Diverging blue-white-red colour map';\n attributeStr = 'diverging';\n hueStr = 'bwr';\n colpts = [40 ch2ab(83,-64)\n 95 0 0\n 40 ch2ab(83, 39)]; \n sigma = 0;\n splineorder = 2; \n \n\n case 'X30'\n desc = 'red - green - blue interpolated in rgb';\n attributeStr = 'linear';\n hueStr = 'rgb';\n colourspace = 'RGB';\n colpts = [1.00 0.00 0.00\n 0.00 1.00 0.00\n 0.00 0.00 1.00];\n sigma = 0;\n W = [0 0 0];\n splineorder = 2; \n \n case 'X31'\n desc = 'red - green - blue interpolated in CIELAB';\n attributeStr = 'linear';\n hueStr = 'rgb';\n colourspace = 'LAB';\n colpts = [53 80 67\n 88 -86 83\n 32 79 -108];\n sigma = 0;\n W = [0 0 0];\n splineorder = 2; \n \n \n \n \n\n %%------------------------------------------------------------- \n \n otherwise\n % Invoke the catalogue search to help the user\n catalogue(I);\n \n clear map;\n clear name;\n clear desc;\n return\n \n end\n\n \n % Adjust chroma/saturation but only if colourspace is LAB\n if strcmpi(colourspace, 'LAB')\n colpts(:,2:3) = chromaK * colpts(:,2:3);\n end\n \n % Colour map path is formed via a b-spline in the specified colour space\n Npts = size(colpts,1);\n \n if Npts < 2\n error('Number of input points must be 2 or more')\n elseif Npts < splineorder\n splineorder = Npts;\n fprintf('Warning: Spline order is greater than number of data points\\n')\n fprintf('Reducing order of spline to %d\\n', Npts)\n end\n \n % Rely on the attribute string to identify if colour map is cyclic. We may\n % want to construct a colour map that has identical endpoints but do not\n % necessarily want continuity in the slope of the colour map path.\n if strfind(attributeStr, 'cyclic')\n cyclic = 1;\n labspline = pbspline(colpts', splineorder, N);\n else\n cyclic = 0;\n labspline = bbspline(colpts', splineorder, N);\n end \n \n % Apply contrast equalisation with required parameters. Note that sigma is\n % normalised with respect to a colour map of length 256 so that if a short\n % colour map is specified the smoothing that is applied is adjusted to suit.\n sigma = sigma*N/256;\n map = equalisecolourmap(colourspace, labspline', formula,...\n W, sigma, cyclic, diagnostics); \n\n % If specified apply a cyclic shift to the colour map\n if shift\n if isempty(strfind(attributeStr, 'cyclic'))\n fprintf('Warning: Colour map shifting being applied to a non-cyclic map\\n');\n end\n map = circshift(map, round(N*shift)); \n end\n \n if reverse\n map = flipud(map);\n end \n \n % Compute mean chroma of colour map\n lab = rgb2lab(map);\n meanchroma = sum(sqrt(sum(lab(:,2:3).^2, 2)))/N;\n \n % Construct lightness range description\n if strcmpi(colourspace, 'LAB') % Use the control points\n L = colpts(:,1);\n else % For RGB use the converted CIELAB values\n L = round(lab(:,1));\n end\n minL = min(L);\n maxL = max(L);\n \n if minL == maxL % Isoluminant\n LStr = sprintf('%d', minL);\n \n elseif L(1) == maxL && ...\n (~isempty(strfind(attributeStr, 'diverging')) ||...\n ~isempty(strfind(attributeStr, 'linear')))\n LStr = sprintf('%d-%d', maxL, minL);\n \n else \n LStr = sprintf('%d-%d', minL, maxL);\n end\n \n % Build overall colour map name\n name = sprintf('%s_%s_%s_c%d_n%d',...\n attributeStr, hueStr, LStr, round(meanchroma), N);\n \n if shift\n name = sprintf('%s_s%d', name, round(shift*100)); \n end\n \n if reverse\n name = sprintf('%s_r', name);\n end \n \n \n if diagnostics % Print description and plot path in colourspace\n fprintf('%s\\n',desc);\n colourmappath(map, 'fig', 10)\n end\n \n \n%------------------------------------------------------------------\n% Conversion from (chroma, hue angle) description to (a*, b*) coords\n\nfunction ab = ch2ab(chroma, angle_degrees)\n \n theta = angle_degrees/180*pi;\n ab = chroma*[cos(theta) sin(theta)];\n \n\n%------------------------------------------------------------------\n%\n% Function to list colour maps with names containing a specific string.\n% Typically this is used to search for colour maps having a specified attribute:\n% 'linear', 'diverging', 'rainbow', 'cyclic', 'isoluminant' or 'all'.\n% This code is awful!\n\nfunction catalogue(str)\n \n if ~exist('str', 'var')\n str = 'all';\n end\n \n % Get all case expressions in this function\n caseexpr = findcaseexpr;\n \n % Construct all colour map names\n for n = 1:length(caseexpr)\n % Get 1st comma separated element in caseexpr\n label = strtok(caseexpr{n},','); \n [~, name{n}] = cmap(label);\n end\n\n % Check each colour name for the specified search string. Exclude the\n % experimental maps with label starting with X.\n fprintf('\\n CMAP label(s) Colour Map name\\n')\n fprintf('------------------------------------------------\\n')\n \n found = 0;\n \n for n = 1:length(caseexpr) \n if caseexpr{n}(1) ~= 'X' \n if any(strfind(upper(name{n}), str)) || strcmpi(str, 'all')\n fprintf('%-20s %s\\n', caseexpr{n}, name{n});\n found = 1;\n end\n end\n end \n\n if ~found\n fprintf('Sorry, no colour map with label or attribute %s found\\n', str);\n end\n\n\n%-----------------------------------------------------------------------\n% Function to find all the case expressions in this function. Yuk there must\n% be a better way! Assumes the case statement do not span more than one line\n\nfunction caseexpr = findcaseexpr\n [fid, msg] = fopen([mfilename('fullpath') '.m'], 'r');\n error(msg);\n\n caseexpr = {};\n n = 0;\n line = fgetl(fid);\n\n while ischar(line) \n [tok, remain] = strtok(line);\n \n if strcmpi(tok, 'case')\n % If we are here remain should be the case expression.\n % Remove any trailing comment from case expression\n [tok, remain] = strtok(remain,'%'); \n\n % Remove any curly brackets from the case expression\n tok(tok=='{') = [];\n tok(tok=='}') = [];\n tok(tok=='''') = [];\n\n n = n+1;\n caseexpr{n} = tok; \n end\n line = fgetl(fid);\n end\n \n caseexpr = strtrim(caseexpr);\n \n fclose(fid);\n\n%-----------------------------------------------------------------------\n% Function to parse the input arguments and set defaults\n\nfunction [I, N, chromaK, shift, reverse, diagnostics] = parseinputs(varargin)\n \n p = inputParser;\n\n numericORchar = @(x) isnumeric(x) || ischar(x);\n numericORlogical = @(x) isnumeric(x) || islogical(x);\n \n % The first argument is either a colour map label string or a string to\n % search for in a colourmap name. If no argument is supplied it is assumed\n % the user wants to list all possible colourmaps.\n addOptional(p, 'I', 'all', @ischar); \n \n % Optional parameter-value pairs and their defaults \n addParameter(p, 'N', 256, @isnumeric); \n addParameter(p, 'shift', 0, @isnumeric); \n addParameter(p, 'chromaK', 1, @isnumeric); \n addParameter(p, 'reverse', 0, numericORlogical); \n addParameter(p, 'diagnostics', 0, numericORlogical); \n \n parse(p, varargin{:});\n \n I = strtrim(upper(p.Results.I));\n N = p.Results.N;\n chromaK = p.Results.chromaK;\n shift = p.Results.shift;\n reverse = p.Results.reverse;\n diagnostics = p.Results.diagnostics; \n \n if abs(shift) > 1\n error('Cyclic shift fraction magnitude cannot be larger than 1');\n end\n \n if chromaK < 0\n error('chromaK must be greater than 0')\n end \n \n if chromaK > 1\n fprintf('Warning: chromaK is greater than 1. Gamut clipping may occur')\n end \n \n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ternarycolours.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/ternarycolours.m", "size": 4004, "source_encoding": "utf_8", "md5": "ea4668fc20c8bc3e6e26893981927aab", "text": "% TERNARYCOLOURS Determine 3 basis colours for a ternary image\n%\n% This function determines 3 basis colours for constructing ternary/radiometric\n% images. Ideally these are isoluminant and have the same chroma. While this\n% function does not achieve this perfectly the three colours it generates are\n% fairly good.\n%\n% Usage: [C1, C2, C3, rgb1, rgb2, rgb3] = ternarycolours\n%\n% Returns: C1 C2 C3 - Basis colours defined in CIELAB space\n% rgb1-3 - Basis colours in RGB space.\n%\n% The strategy is to first define 2 colours in CIELAB, a nominal 'red' and\n% 'green'. From this we compute third colour, 'blue' so that the 3 colours when\n% summed in RGB space produce a neutral grey.\n%\n% After some experimentation the two colours in CIELAB that I defined were\n% C1 = [53 80 67]; % Red (as in RGB red)\n% C2 = [52 -57 55]; % Green having maximum chroma at a lightness of 52\n%\n% This results in the third colour being\n% C3 = [50 30 -78];\n%\n% These are not quite isoluminant but seems to be a good compromise. Choosing a\n% green with a lightness of 52 results in a 'blue' with a lightness of about\n% 50. While this is slightly darker than the other colours it allows the blue to\n% have a larger chroma/saturation than what would be otherwise possible at a\n% lightness of 53. The three colours have chroma of 104, 79 and 86\n% respectively. While these are not equal they are comparable. Visually the\n% result appears to be a reasonable compromise.\n% \n% The RGB values that these three colours correspond to are:\n% rgb1 = [1.00 0.00 0.00]\n% rgb2 = [0.00 0.57 0.00]\n% rgb3 = [0.00 0.43 1.00]\n%\n% Inspecting these values we can see that by using a reduced green (RGB green\n% has a lightness of about 88) some of this 'greenness' is transferred to the\n% 'blue' basis colour increasing its lightness and making it more of a cyan\n% colour.\n%\n% See also: VIEWLABSPACE, LINEARRGBMAP, LABMAPLIB\n\n% Copyright (c) 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% August 2014\n\nfunction [C1, C2, C3, rgb1, rgb2, rgb3] = ternarycolours\n\n % Define the two initial basis colours. These are what I came up with by\n % experimentation, edit as you wish...\n C1 = [53 80 67]; % Red (as in RGB red)\n C2 = [52 -57 55]; % Green having maximum chroma at a lightness of 52\n \n % Convert to rgb and subtract from [1 1 1] to solve for the rgb values of\n % the 3rd basis colour.\n rgb1 = lab2rgb(C1);\n rgb2 = lab2rgb(C2);\n rgb3 = [1 1 1] - rgb1 - rgb2;\n \n % Convert back to CIELAB space to check for any gamut clipping etc\n C1 = rgb2lab(rgb1);\n C2 = rgb2lab(rgb2);\n C3 = rgb2lab(rgb3);\n \n % Reconstruct rgb3 to check for gamut clipping\n rgb3 = lab2rgb(C3);\n \n % Construct linear rgb colourmaps to these 3 colours so that we can\n % inspect what we have created.\n map1 = linearrgbmap(rgb1);\n map2 = linearrgbmap(rgb2);\n map3 = linearrgbmap(rgb3);\n \n show(sineramp, 11), colormap(map1);\n show(sineramp, 12), colormap(map2);\n show(sineramp, 13), colormap(map3);\n \n % Form the sum of the colourmaps so that we can check there is no colour\n % cast in the sum of the maps.\n summaps = map1+map2+map3;\n max(summaps(:));\n summaps = summaps/max(summaps(:));\n show(sineramp, 14), colormap(summaps);\n \n figure(15)\n plot(0:255,summaps(:,1), 'r-', ...\n 0:255,summaps(:,2), 'g-', ...\n 0:255,summaps(:,3), 'b-')\n title('R G B values of summed colourmaps')\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "map2qgisstyle.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/map2qgisstyle.m", "size": 3266, "source_encoding": "utf_8", "md5": "e8e5248686bb0f8761231f97fcc521db", "text": "% MAP2QGISSTYLE Writes colour maps to QGIS style file\n%\n% Usage: map2qgisstyle(map, mapname, filename)\n%\n% Arguments: map - N x 3 colour map, or a cell array of N x 3 colour maps \n% mapname - String giving the colour map name, or a cell array of\n% strings\n% filename - File name to write QGIS xml style file to.\n%\n% See also: WRITEQGISMAPS\n\n% Copyright (c) 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 2014\n\n\nfunction map2qgisstyle(map, mapname, filename)\n \n% Ideally I should construct a DOMnode object and write that out using xmlwrite\n% but I do not know enough about the QGIS spec. Hence this hand rolled file.\n \n % If a single colourmap has been supplied rather than a cell array\n % convert it and its mapname to a single element cell arrays\n if ~iscell(map)\n tmp1 = map; delete map;\n tmp2 = mapname; delete mapname;\n map{1} = tmp1;\n mapname{1} = tmp2;\n end\n \n nmaps = length(map);\n \n % Ensure file has a .xml ending\n if ~strendswith(filename, '.xml') \n filename = [filename '.xml'];\n end\n \n [fid, msg] = fopen(filename, 'wt');\n error(msg);\n \n fprintf(fid,'\\n');\n fprintf(fid,'\\n');\n\n fprintf(fid,'\\n');\n \n fprintf(fid,'\\n');\n\n for m = 1:nmaps\n % Convert colour map values from doubles in range 0-1 to ints ranging\n % from 0-255\n map{m} = round(map{m}*255);\n [mapelements,~] = size(map{m});\n \n \n fprintf(fid,'\\n', mapname{m});\n \n fprintf(fid,'\\n', ...\n map{m}(1,1), map{m}(1,2), map{m}(1,3));\n \n fprintf(fid,'\\n', ...\n map{m}(end,1), map{m}(end,2), map{m}(end,3));\n fprintf(fid,'\\n');\n\n fprintf(fid,'\\n'); \n fprintf(fid,'\\n');\n \n end % for each map\n \n fprintf(fid,'\\n');\n fprintf(fid,'\\n'); \n \n fclose(fid);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ternaryimage.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/ternaryimage.m", "size": 3966, "source_encoding": "utf_8", "md5": "34a7ce4ff9d4772808994acf7a46b194", "text": "% TERNARYIMAGE Perceptualy uniform ternary image from 3 bands of data\n%\n% Usage: rgbim = ternaryimage(im, bands, histcut, Rmap, Gmap, Bmap)\n%\n% Arguments\n% im - Multiband image with at least 3 bands, or a cell array of\n% at least 3 images.\n% bands - Array of 3 values indicating the bands, to be assigned to\n% the red, green and blue basis colour maps. If omitted, or\n% empty, bands defaults to [1 2 3].\n% histcut - Percentage of image band histograms to clip. It can be\n% useful to clip 1-2%. If you see lots of white in your\n% ternary image you have clipped too much. Defaults to 0.\n% R/G/Bmap - Three basis colourmaps to be applied to the specified\n% bands of the input image which are then summed to form\n% the ternary image. If omitted the colour maps default to\n% those generated by TERNARYMAPS. \n% If Rmap is the string 'RGB' then the RGB primaries are\n% used. This creates a 'classical' ternary image. (Though not\n% very efficiently).\n%\n% Returns: \n% rgbim - RGB ternary image\n%\n% The default colour maps obtained from TERNARYMAPS result in colours that are\n% not as vivid as the RGB primaries but they produce perceptually uniform\n% ternary images with consistent feature salience no matter what permutation of\n% channel-colour assignement is used.\n%\n% For the derivation of the three primary colours used by TERNARYMAPS see:\n% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary\n%\n% See also: TERNARYMAPS, APPLYCOLOURMAP, LINEARRGBMAP\n\n% Copyright (c) 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction rgbim = ternaryimage(im, bands, histcut, Rmap, Gmap, Bmap)\n \n if ~exist('bands', 'var') || isempty(bands), bands = [1 2 3]; end\n if ~exist('histcut', 'var'), histcut = 0; end \n if ~exist('Rmap', 'var'), [Rmap, Gmap, Bmap] = ternarymaps; end\n if strcmpi(Rmap, 'RGB')\n Rmap = linearrgbmap([1 0 0]);\n Gmap = linearrgbmap([0 1 0]);\n Bmap = linearrgbmap([0 0 1]);\n end\n\n if iscell(im)\n \n if max(bands) > length(im)\n error('Band specification outside image range');\n end\n \n if histcut\n rgbim = applycolourmap(histtruncate(im{bands(1)}, histcut), Rmap) + ...\n applycolourmap(histtruncate(im{bands(2)}, histcut), Gmap) + ...\n applycolourmap(histtruncate(im{bands(3)}, histcut), Bmap);\n else\n rgbim = applycolourmap(im{bands(1)}, Rmap) + ...\n applycolourmap(im{bands(2)}, Gmap) + ...\n applycolourmap(im{bands(3)}, Bmap); \n end\n else\n \n if max(bands) > size(im,3)\n error('Band specification outside image range');\n end\n \n if histcut\n rgbim = applycolourmap(histtruncate(im(:,:,bands(1)), histcut), Rmap) + ...\n applycolourmap(histtruncate(im(:,:,bands(2)), histcut), Gmap) + ...\n applycolourmap(histtruncate(im(:,:,bands(3)), histcut), Bmap);\n else\n rgbim = applycolourmap(im(:,:,bands(1)), Rmap) + ...\n applycolourmap(im(:,:,bands(2)), Gmap) + ...\n applycolourmap(im(:,:,bands(3)), Bmap);\n end\n end"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "linearrgbmap.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/linearrgbmap.m", "size": 882, "source_encoding": "utf_8", "md5": "ffe885dc19eb15928ea8117e1902d32e", "text": "% LINEARRGBMAP Linear rgb colourmap from black to a specified colour\n%\n% Usage: map = linearrgbmap(C, N)\n%\n% Arguments: C - 3-vector specifying RGB colour\n% N - Number of colourmap elements, defaults to 256\n%\n% Returns: map - Nx3 RGB colourmap ranging from [0 0 0] to colour C \n%\n% It is suggested that you pass the resulting colour map to EQUALISECOLOURMAP\n% to obtain a map with uniform steps in perceptual lightness\n% >> map = equalisecolourmap('rgb', linearrgbmap(C, N));\n%\n% See also: EQUALISECOLOURMAP, TERNARYMAPS, COLOURMAPPATH\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK August 2014\n\nfunction map = linearrgbmap(C, N)\n \n if ~exist('N', 'var'), N = 256; end\n \n map = zeros(N,3);\n ramp = (0:(N-1))'/(N-1);\n \n for n = 1:3\n map(:,n) = C(n) * ramp;\n end"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "readermapperlutfile.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/readermapperlutfile.m", "size": 3143, "source_encoding": "utf_8", "md5": "137e2c6fab526b434b8ab24d23106693", "text": "% READERMAPPERLUTFILE Read ER Mapper LUT colour map file\n%\n% Usage: [map, name, description] = readermapperlutfile(filename)\n%\n% Argument: filename - Filename to read\n% \n% Returns:\n% map - N x 3 rgb colour map of values 0-1.\n% name - Name of colour map (if specified in file).\n% description - Description of colour map (if specified in file).\n%\n% The ER Mapper LUT file format is also used by MapInfo\n%\n% This function has minimal error checking and assumes the file is reasonably\n% 'well formed'.\n%\n% See also: MAP2ERMAPPERLUTFILE, MAP2IMAGEJLUTFILE\n\n% 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK Sept 2014\n\nfunction [map, name, description] = readermapperlutfile(filename)\n \n map = []; name = ''; description = '';\n \n if ~exist('filename', 'var')\n [filename, pathname] = uigetfile('*.lut');\n if ~filename\n return;\n end\n filename = [pathname filename];\n end\n \n [fid,msg] = fopen(filename, 'r');\n if fid == -1\n error(sprintf('Unable to open %s', filename));\n end\n\n % Read each line, discard empty lines and look for keywords\n line = fgetl(fid);\n [tok, remain] = strtok(line);\n \n while ~strcmpi(tok, 'LUT')\n\n if strcmpi(tok, 'Name')\n name = processline(remain);\n elseif strcmpi(tok, 'Description') \n description = processline(remain);\n elseif strcmpi(tok, 'NrEntries') \n NrEntries = eval(processline(remain));\n end\n \n line = fgetl(fid);\n if line == -1\n error('Unexpected end of file encountered');\n end\n\n [tok, remain] = strtok(line); \n end\n\n if ~exist('NrEntries', 'var')\n error('Unable to determine number of colour map entries')\n end\n \n % If we get to here we expect to have NrEntries lines of the form\n % EntryNo R G B\n % There may also be a comment at the end of each line so we have to read\n % them one by one.\n % Note that we read the data from the file in row order but MATLAB stores\n % it in column order hence the [4 NrEntries] dimensioning and the\n % subsequent transpose\n map = zeros(4, NrEntries);\n \n for n = 1:NrEntries\n line = fgetl(fid);\n if line == -1\n error('Unexpected end of file encountered');\n end\n \n % Read 4 ints from each line and ignore anything beyond\n [map(:,n), count] = sscanf(line, '%d %d %d %d');\n if count ~= 4\n error('Incorrect number of entries in colour map');\n end \n \n end\n \n map = map';\n \n % Read the final } and LookUpTable End ?\n \n fclose(fid);\n \n % Remove the first column of map and rescale values 0-1\n map = double(map(:,2:4))/(2^16-1);\n \n \n%---------------------------------------------------------\n% Grab the remaining token in a line ignoring white space, tabs, '=' and '\"'\nfunction tok = processline(line)\n \n [tok,remain] = strtok(line, [' = \"' char(9)]);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "writecolourmapfn.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/writecolourmapfn.m", "size": 1354, "source_encoding": "utf_8", "md5": "2b064a86456dae2b3ea2634a7edad8c0", "text": "% WRITECOLOURMAPFN Creates a MATLAB function file from a Nx3 colourmap \n%\n% Usage: writecolourmapfn(map, fname)\n%\n\n% PK June 2014\n\nfunction writecolourmapfn(map, fname)\n\n [N, chan] = size(map);\n if chan ~= 3\n error('Colourmap must be Nx3');\n end\n \n if strendswith(fname, '.m') % If fname has been given a .m ending\n fname = strtok(fname, '.'); % remove it (but we will restore it later)\n end\n \n % Convert any '-' characters in the name to '_' as '-' is an operator and\n % cannot be used in a function name\n fname(fname=='-') = '_';\n \n fid = fopen([fname '.m'], 'wt');\n\n % Strip off any directory path from the filename\n str = strsplit(fname, '/');\n fname = str{end};\n\n fprintf(fid, '%% Uniform Perceptual Contrast Colourmap\\n');\n fprintf(fid, '%% \\n');\n fprintf(fid, '%% Usage: map = %s\\n', fname);\n fprintf(fid, '%% \\n');\n fprintf(fid, '%% \\n');\n fprintf(fid, '%% Centre for Exploration Targeting\\n');\n fprintf(fid, '%% The University of Western Australia\\n');\n fprintf(fid, '%% %s \\n', date);\n fprintf(fid, '%% \\n'); \n \n fprintf(fid, 'function map = %s\\n', fname);\n fprintf(fid, 'map = [ ...\\n');\n\n for n = 1:N\n fprintf(fid, '%f %f %f\\n', map(n,1), map(n,2), map(n,3));\n end\n fprintf(fid, '];\\n');\n\n fclose(fid);\n\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "map2geosofttbl.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/map2geosofttbl.m", "size": 1634, "source_encoding": "utf_8", "md5": "f354e08adec5586e24061af7e42c98de", "text": "% MAP2GEOSOFTTBL Converts MATLAB colourmap to Geosoft .tbl file\n%\n% Usage: map2geosofttbl(map, filename, cmyk)\n%\n% Arguments: map - N x 3 rgb colourmap\n% filename - Output filename\n% cmyk - Optional flag 0/1 indicating whether CMYK values should\n% be written. Defaults to 0 whereby RGB values are\n% written\n%\n% This function writes a RGB colourmap out to a .tbl file that can be loaded\n% into Geosoft Oasis Montaj\n%\n% See also: RGB2CMYK\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK October 2012\n% June 2014 - RGB or CMYK option\n\nfunction map2geosofttbl(map, filename, cmyk)\n\n if ~exist('cmyk', 'var'), cmyk = 0; end\n\n [N, cols] = size(map);\n if cols ~= 3\n error('Colourmap must be N x 3 in size')\n end\n \n % Ensure filename ends with .tbl\n if ~strendswith(filename, '.tbl')\n filename = [filename '.tbl'];\n end\n \n fid = fopen(filename, 'wt'); \n\n if cmyk % Convert RGB values in map to CMYK and scale 0 - 255\n cmyk = round(rgb2cmyk(map)*255);\n kcmy = circshift(cmyk, [0 1]); % Shift K to 1st column\n \n fprintf(fid, '{ blk cyn mag yel }\\n');\n for n = 1:N\n fprintf(fid, ' %03d %03d %03d %03d \\n', kcmy(n,:)); \n end\n \n else % Write RGB values\n map = round(map*255);\n \n fprintf(fid, '{ red grn blu }\\n');\n for n = 1:N\n fprintf(fid, ' %3d %3d %3d\\n', map(n,:)); \n end \n \n end\n \n fclose(fid);\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "readimagejlutfile.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/readimagejlutfile.m", "size": 1122, "source_encoding": "utf_8", "md5": "f1de0f94122413d9e59d237a6b0c2674", "text": "% READIMAGEJLUTFILE Reads lut colourmap file as used by ImageJ\n%\n% Usage: map = readimagejlutfile(fname)\n%\n% Argument: fname - Filename of a .lut file\n% Returns: map - 256 x 3 colourmap table \n%\n% The format of a lookup table for ImageJ is 256 bytes of red values, followed\n% by 256 green values and finally 256 blue values. A total of 768 bytes.\n%\n% See also: MAP2IMAGEJLUTFILE, MAP2ERMAPPERLUTFILE\n\n% 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK June 2014\n\nfunction map = readimagejlutfile(fname)\n\n map = [];\n \n if ~exist('filename', 'var')\n [filename, pathname] = uigetfile('*.lut');\n if ~filename\n return;\n end\n filename = [pathname filename];\n end\n \n [fid, msg] = fopen(fname, 'r');\n if fid == -1\n error(sprintf('Unable to open %s', fname));\n end\n \n map = fread(fid, inf, 'uint8');\n if length(map) ~= 768\n error('LUT file does not have 768 entries');\n end\n \n map = reshape(map, 256, 3);\n map = double(map)/255;\n \n fclose(fid);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "map2actfile.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/map2actfile.m", "size": 741, "source_encoding": "utf_8", "md5": "4c119e2da488dd0845d360b13ebc6d46", "text": "% MAP2ACTFILE Writes colourmap to .act file Adobe Colourmap Table\n%\n% Usage: map2actfile(map, fname)\n%\n% An Adobe Colourmap Table is a file of 256 sets of R G and B values written as\n% bytes, a total of 768 bytes.\n%\n\n% PK June 2014\n\nfunction map2actfile(map, fname)\n\n [N, chan] = size(map);\n if N ~= 256 | chan ~= 3\n error('Colourmap must be 256x3');\n end\n \n % Ensure file has a .act ending\n if ~strendswith(fname, '.act') \n fname = [fname '.act'];\n end\n\n % Convert map to integers 0-255 and form into a single vector of\n % sequential RGB values\n map = round(map*255);\n map = map';\n map = map(:);\n\n fid = fopen(fname, 'w'); \n fwrite(fid, map, 'uint8');\n fclose(fid);\n\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ternarymaps.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/ternarymaps.m", "size": 1992, "source_encoding": "utf_8", "md5": "f1edae4213fc031028b69d29f72addcc", "text": "% TERNARYMAPS Returns three basis colour maps for generating ternary images\n% \n% Usage: [Rmap, Gmap, Bmap] = ternarymaps(N);\n%\n% Argument: N - Number of elements within the colour maps. This is optional\n% and defaults to 256\n% Returns: \n% Rmap, Gmap, Bmap - Three colour maps that are nominally red, green\n% and blue but the colours have been chosen so that\n% they, and their secondary colours, are closely matched\n% in lightness.\n%\n% The colours are not as vivid as the RGB primaries but they produce ternary\n% images with consistent feature salience no matter what permutation of\n% channel-colour assignement is used.\n%\n% For the derivation of the three primary colours see:\n% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary\n%\n% See also: TERNARYIMAGE, EQUALISECOLOURMAP, LINEARRGBMAP, APPLYCOLOURMAP\n\n% Copyright (c) 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction [Rmap, Gmap, Bmap] = ternarymaps(N)\n \n if ~exist('N', 'var'), N = 256; end\n \n % The three primary colours. For their derivation see:\n % http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary\n R = [0.90 0.17 0.00];\n G = [0.00 0.50 0.00];\n B = [0.10 0.33 1.00];\n \n Rmap = equalisecolourmap('rgb', linearrgbmap(R, N));\n Gmap = equalisecolourmap('rgb', linearrgbmap(G, N));\n Bmap = equalisecolourmap('rgb', linearrgbmap(B, N));\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "geosofttbl2map.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/geosofttbl2map.m", "size": 1313, "source_encoding": "utf_8", "md5": "97f965db62a9a1ea1d2d5bccb32bd608", "text": "% GEOSOFTTBL2MAP Converts Geosoft .tbl file to MATLAB colourmap\n%\n% Usage: geosofttbl2map(filename, map)\n%\n% Arguments: filename - Input filename of tbl file\n% map - N x 3 rgb colourmap\n% \n%\n% This function reads a Geosoft .tbl file and converts the KCMY values to a RGB\n% colourmap.\n%\n% See also: MAP2GEOSOFTTBL, RGB2CMYK\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK July 2013\n\nfunction map = geosofttbl2map(filename)\n \n % Read the file\n [fid, msg] = fopen(filename, 'rt');\n error(msg);\n \n % Read, test and then discard first line\n txt = strtrim(fgetl(fid));\n % Very basic file check. Test that it starts with '{'\n if txt(1) ~= '{'\n error('This may not be a Geosoft tbl file')\n end\n \n % Read remaining lines containing the colour table\n [data, count] = fscanf(fid, '%d');\n \n if mod(count,4) % We expect 4 columns of data\n error('Number of values read not a multiple of 4');\n end\n\n % Reshape data so that columns form kcmy tuples\n kcmy = reshape(data, 4, count/4);\n % Transpose so that the rows form kcmy tuples and normalise 0-1\n kcmy = kcmy'/255; \n cmyk = [kcmy(:,2:4) kcmy(:,1)];\n map = cmyk2rgb(cmyk);\n \n fclose(fid);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "colourmappath.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/colourmappath.m", "size": 11106, "source_encoding": "utf_8", "md5": "657a67e384f4f2074c75cffc36b9c945", "text": "% COLOURMAPPATH Plots the path of a colour map through colour space\n%\n% Usage: colourmappath(map, param_name, value, ....)\n%\n% Required argument:\n% map - The colourmap to be plotted\n%\n% Optional parameter-value pairs, default values in brackets:\n% 'N' - The nmber of slices through the colourspace to plot (6).\n% 'colspace' - String 'rgb' or 'lab' indicating the colourspace to plot\n% ('lab'). \n% 'fig' - Optional figure number to use (new figure created).\n% 'linewidth' - Width of map path line (2.5).\n% 'dotspace' - Spacing between colour map entries where dots are plotted\n% along the path (5).\n% 'dotsize' - (15). Use 0 if you want no dots plotted.\n% 'dotcolour' - ([0.8 0.8 0.8])\n% 'fontsize' - (14).\n% 'fontweight' - ('bold').\n%\n% The colour space is represented as a series of semi-transparent 2D slices\n% which hopefully lets you visualise the colour space and the colour map path\n% simultaneously.\n%\n% Note that for some reason repeated calls of this function to render a colour\n% map path in RGB space seem to ultimately cause MATLAB to crash (under MATLAB\n% 2013b on OSX). Rendering paths in CIELAB space cause no problem.\n%\n% See also: CMAP, EQUALISECOLOURMAP, VIEWLABSPACE, SINERAMP, CIRCSINERAMP\n\n% Copyright (c) 2013-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 2013 - Original version\n% October 2014 - Parameter options added\n\n%function colourmappath(map, N, colspace, fig) % Original argument list\nfunction colourmappath(varargin)\n\n [map, N, colspace, fig, linewidth, ds, dotcolour, dotsize, fontsize, fontweight] ...\n = parseinputs(varargin{:}); \n \n mapref = map;\n\n %% RGB plot ---------------------------------------------------------\n if strcmpi(colspace, 'rgb')\n \n R = 255;\n delta = 2; % Downsampling factor for red and green\n [x,y] = meshgrid(0:delta:R, 0:delta:R);\n [sze, ~] = size(x);\n im = zeros(sze, sze, 3, 'uint8');\n \n figure(fig), clf, axis([-1 sze+1 -1 sze+1 -1 sze+1])\n \n % Draw N red-green planes of increasing blue value through RGB space \n for b = 0:R/(N-1):R\n for r = 0:delta:R\n for g = 0:delta:R\n im(g/delta+1, r/delta+1, :) = [r; g; round(b)];\n end\n end\n \n h = warp(b*ones(sze,sze), im); hold on\n set(h, 'FaceAlpha', 0.9);\n end\n \n % Plot the colour map path through the RGB colour space. Rescale map\n % to account for scaling to 255 and for downsampling (yuk)\n map(:,1:2) = map(:,1:2)*255/delta;\n map(:,3) = map(:,3)*255;\n line(map(:,1), map(:,2), map(:,3), 'linewidth', linewidth, 'color', [0 0 0]);\n hold on\n \n % Plot a dot for every 'dotspace' point along the colour map to indicate the\n % spacing of colours in the colour map\n if dotsize\n plot3(map(1:ds:end,1), map(1:ds:end,2), map(1:ds:end,3), '.', ...\n 'Color', dotcolour, 'MarkerSize', dotsize);\n end\n hold off\n\n % Generate axis tick values\n tickcoords = [0:50:250]/delta;\n ticklabels = {'0'; '50'; '100'; '150'; '200'; '250'};\n \n set(gca, 'xtick', tickcoords);\n set(gca, 'ytick', tickcoords);\n set(gca, 'xticklabel', ticklabels);\n set(gca, 'yticklabel', ticklabels); \n \n xlabel('Red');\n ylabel('Green');\n zlabel('Blue');\n \n set(gca,'Fontsize', fontsize);\n set(gca,'Fontweight', fontweight);\n \n axis vis3d\n \n \n %% CIELAB plot ----------------------------------------------------\n elseif strcmpi(colspace, 'lab')\n \n if iscell(mapref) % We have a cell array of colour maps\n figure(fig), clf, axis([-110 110 -110 110 0 100])\n for n = 1:length(mapref)\n lab = rgb2lab(mapref{n});\n line(lab(:,2), lab(:,3), lab(:,1), 'linewidth', linewidth, 'color', [0 0 0])\n hold on\n if dotsize\n plot3(lab(1:ds:end,2), lab(1:ds:end,3), lab(1:ds:end,1), '.', ...\n 'Color', dotcolour, 'MarkerSize', dotsize);\n end\n end\n \n elseif ~isempty(map) % Single colour map supplied\n lab = rgb2lab(mapref);\n \n figure(fig), clf, axis([-110 110 -110 110 0 100])\n line(lab(:,2), lab(:,3), lab(:,1), 'linewidth', linewidth, 'color', [0 0 0])\n hold on\n if dotsize\n plot3(lab(1:ds:end,2), lab(1:ds:end,3), lab(1:ds:end,1), '.', ...\n 'Color', dotcolour, 'MarkerSize', dotsize);\n end\n % line([0 0], [0 0], [0 100]) % Line up a = 0, b = 0 axis\n end\n \n %% Generate Lab image slices\n \n % Define a*b* grid for image\n scale = 1;\n [a, b] = meshgrid([-127:1/scale:127]);\n [rows,cols] = size(a);\n \n % Generate N equi-spaced lightness levels between 5 and 95.\n for L = 5:90/(N-1):95 % For each lightness level...\n \n % Build image in lab space\n lab = zeros(rows,cols,3); \n lab(:,:,1) = L;\n lab(:,:,2) = a;\n lab(:,:,3) = b;\n \n % Generate rgb values from lab\n rgb = applycform(lab, makecform('lab2srgb'));\n \n % Invert to reconstruct the lab values\n lab2 = applycform(rgb, makecform('srgb2lab'));\n \n % Where the reconstructed lab values differ from the specified values is\n % an indication that we have gone outside of the rgb gamut. Apply a\n % mask to the rgb values accordingly\n mask = max(abs(lab-lab2),[],3);\n \n for n = 1:3\n rgb(:,:,n) = rgb(:,:,n).*(mask<2); % tolerance of 2\n end\n \n [x,y,z,cdata] = labsurface(lab, rgb, L, 100);\n h = surface(x,y,z,cdata); shading interp; hold on\n set(h, 'FaceAlpha', 0.9);\n \n end % for each lightness level\n \n % Generate axis tick values\n tickval = [-100 -50 0 50 100];\n tickcoords = tickval; %scale*tickval + cols/2;\n ticklabels = {'-100'; '-50'; '0'; '50'; '100'};\n \n set(gca, 'xtick', tickcoords);\n set(gca, 'ytick', tickcoords);\n set(gca, 'xticklabel', ticklabels);\n set(gca, 'yticklabel', ticklabels); \n \n ztickval = [0 20 40 60 80 100];\n zticklabels = {'0' '20' ' 40' '60' '80' '100'};\n set(gca, 'ztick', ztickval);\n set(gca, 'zticklabel', zticklabels); \n\n set(gca,'Fontsize', fontsize);\n set(gca,'Fontweight', fontweight);\n \n % Label axes. Note option for manual placement for a and b\n manual = 0;\n if ~manual\n xlabel('a', 'Fontsize', fontsize, 'FontWeight', fontweight);\n ylabel('b', 'Fontsize', fontsize, 'FontWeight', fontweight);\n else\n text(0, -170, 0, 'a', 'Fontsize', fontsize, 'FontWeight', ...\n fontweight); \n text(155, 0, 0, 'b', 'Fontsize', fontsize, 'FontWeight', ...\n fontweight);\n end\n zlabel('L', 'Fontsize', fontsize, 'FontWeight', fontweight);\n \n axis vis3d\n \n grid on, box on\n view(64, 28)\n hold off\n \n else\n error('colspace must be rgb or lab')\n end\n \n%-------------------------------------------------------------------\n% LABSURFACE\n%\n% Idea to generate lab surfaces. Generate lab surface image, Sample a\n% parametric grid of x, y, z and colour values. Texturemap the colour values\n% onto the surface.\n%\n% Find first and last rows of image containing valid values. Interpolate y\n% over this range. For each value of y find first and last valid x values.\n% Interpolate x over this range sampling colour values as one goes.\n\nfunction [x, y, z, cdata] = labsurface(lab, rgb, zval, N)\n \n x = zeros(N,N);\n y = zeros(N,N);\n z = zeros(N,N);\n cdata = zeros(N,N,3);\n \n % Determine top and bottom edges of non-zero section of image\n gim = sum(rgb, 3); % Sum over all colour channels\n rowsum = sum(gim, 2); % Sum over rows\n \n ind = find(rowsum);\n top = ind(1);\n bottom = ind(end);\n rowvals = round(top + (0:N-1)/(N-1)*(bottom-top));\n\n rowind = 1;\n for row = rowvals\n % Find first and last non-zero elements in this row\n ind = find(gim(row,:));\n left = ind(1);\n right = ind(end);\n colvals = round(left + (0:N-1)/(N-1)*(right-left));\n\n % Fill matrices\n colind = 1;\n for col = colvals\n x(rowind,colind) = lab(row,col,2);\n y(rowind,colind) = lab(row,col,3); \n \n z(rowind,colind) = zval;\n cdata(rowind, colind, :) = rgb(row, col, :);\n \n colind = colind+1;\n end\n \n rowind = rowind+1;\n end\n \n%-----------------------------------------------------------------------\n% Function to parse the input arguments and set defaults\n\nfunction [map, N, colspace, fig, linewidth, dotspace, dotcolour, dotsize, ...\n fontsize, fontweight] = parseinputs(varargin)\n \n p = inputParser;\n% numericorcell = @(x) isnumeric(x) || iscell(x);\n \n% addRequired(p, 'map', @numericorcell); \n addRequired(p, 'map'); \n \n % Optional parameter-value pairs and their defaults \n addParameter(p, 'N', 6, @isnumeric); \n addParameter(p, 'colspace', 'LAB', @ischar); \n addParameter(p, 'fig', -1, @isnumeric); \n addParameter(p, 'linewidth', 2.5, @isnumeric); \n addParameter(p, 'dotspace', 5, @isnumeric);\n addParameter(p, 'dotsize', 15, @isnumeric);\n addParameter(p, 'dotcolour', [0.8 0.8 0.8], @isnumeric);\n addParameter(p, 'fontsize', 14, @isnumeric);\n addParameter(p, 'fontweight', 'bold', @ischar);\n \n parse(p, varargin{:});\n \n map = p.Results.map;\n N = p.Results.N;\n colspace = p.Results.colspace;\n dotspace = p.Results.dotspace;\n dotcolour = p.Results.dotcolour;\n dotsize = p.Results.dotsize;\n linewidth = p.Results.linewidth;\n fontsize = p.Results.fontsize;\n fontweight = p.Results.fontweight;\n fig = p.Results.fig; \n if fig < 0, fig = figure; end \n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "map2imagejlutfile.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/map2imagejlutfile.m", "size": 946, "source_encoding": "utf_8", "md5": "20cb86304c4f39be3822f85d6648f55f", "text": "% MAP2IMAGEJLUTFILE Writes a colourmap to a .lut file for use with ImageJ\n%\n% Usage: map2imagejlutfile(map, fname)\n%\n% The format of a lookup table for ImageJ is 256 bytes of red values, followed\n% by 256 green values and finally 256 blue values. A total of 768 bytes.\n%\n% See also: READIMAGEJLUTFILE, READERMAPPERLUTFILE\n\n% 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n\n% PK June 2014\n\nfunction map2imagejlutfile(map, fname)\n\n [N, chan] = size(map);\n if N ~= 256 | chan ~= 3\n error('Colourmap must be 256x3');\n end\n \n % Ensure file has a .lut ending\n if ~strendswith(fname, '.lut') \n fname = [fname '.lut'];\n end\n\n % Convert map to integers 0-255 and form into a single vector of\n % sequential RGB values\n map = round(map(:)*255);\n\n fid = fopen(fname, 'w'); \n fwrite(fid, map, 'uint8');\n fclose(fid);\n\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "generatelabslice.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Colourmaps/generatelabslice.m", "size": 2213, "source_encoding": "utf_8", "md5": "99f7d5a31fd659193715f4e2451be585", "text": "% GENERATELABSLICE Generates RGB image of slice through CIELAB space\n%\n% Usage: rgbim = generatelabslice(L, flip);\n%\n% Arguments: L - Desired lightness level of slice through CIELAB space\n% flip - If set to 1 the image is fliped up-down. Default is 0\n% Returns: rgbim - RGB image of slice\n%\n% The size of the returned image is 255 x 255. \n% The achromatic point being at (128, 128)\n% To convert from image (row, col) values to CIELAB (a, b) use:\n% The a coordinate corresponds to (col - 128)\n% If flip == 0 b = (row - 128) \n% else b = -(row - 128)\n%\n% See also: VIEWLABSPACE\n\n% Copyright (c) 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% PK September 2014\n\nfunction rgb = generatelabslice(L, flip)\n\n if ~exist('flip', 'var'), flip = 0; end\n \n % Define a*b* grid for image\n [a, b] = meshgrid([-127:127]);\n \n if flip\n a = flipud(a); % Flip to make image display match convention\n b = flipud(b); % of LAB space display\n end\n \n [rows,cols] = size(a);\n \n % Build image in lab space\n labim = zeros(rows,cols,3); \n labim(:,:,1) = L;\n labim(:,:,2) = a;\n labim(:,:,3) = b;\n \n % Generate rgb values from lab\n rgb = applycform(labim, makecform('lab2srgb'));\n \n % Invert to reconstruct the lab values\n labim2 = applycform(rgb, makecform('srgb2lab'));\n \n % Where the reconstructed lab values differ from the specified values is\n % an indication that we have gone outside of the rgb gamut. Apply a\n % mask to the rgb values accordingly\n mask = max(abs(labim-labim2),[],3);\n \n for n = 1:3\n rgb(:,:,n) = rgb(:,:,n).*(mask<1); % tolerance of 1\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "makehomogeneous.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/makehomogeneous.m", "size": 649, "source_encoding": "utf_8", "md5": "19d1cac5b6483d4dd545ef8b6bca5dcb", "text": "% MAKEHOMOGENEOUS - Appends a scale of 1 to array inhomogeneous coordinates \n%\n% Usage: hx = makehomogeneous(x)\n%\n% Argument:\n% x - an N x npts array of inhomogeneous coordinates.\n%\n% Returns:\n% hx - an (N+1) x npts array of homogeneous coordinates with the\n% homogeneous scale set to 1\n%\n% See also: MAKEINHOMOGENEOUS\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% April 2010\n\nfunction hx = makehomogeneous(x)\n \n [rows, npts] = size(x);\n hx = ones(rows+1, npts);\n hx(1:rows,:) = x;\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "plotPoint.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/plotPoint.m", "size": 1068, "source_encoding": "utf_8", "md5": "d515fe2aec3bd3915d334310b903a4ba", "text": "% PLOTPOINT - Plots point with specified mark and optional text label.\n%\n% Function to plot 2D points with an optionally specified\n% marker and optional text label.\n%\n% Usage:\n% plotPoint(p) where p is a 2D point\n% plotPoint(p, 'mark') where mark is say 'r+' or 'g*' etc\n% plotPoint(p, 'mark', 'text') \n%\n\n% Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk @ csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% April 2000\n% November 2006 Typo in setting 'mk' fixed, text offset relative to point improved.\n\n\nfunction plotPoint(p, mark, txt)\nhold on\n\nmk = 'r+'; % Default mark is a red +\n\nif nargin >= 2\n mk = mark;\nend\n\nplot(p(1), p(2), mk);\n\nif nargin == 3\n % Print text next to point - calculate an appropriate amount to offset\n % the text from the point.\n\n xlim = get(gca,'Xlim');\n ylim = get(gca,'Ylim'); \n offset = min((xlim(2)-xlim(1)),(ylim(2)-ylim(1)))/50;\n \n text(p(1)+offset,p(2)-offset,txt,'Color',mk(1)); \nend\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "lengthRatioConstraint.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/lengthRatioConstraint.m", "size": 1137, "source_encoding": "utf_8", "md5": "587f4507cf32933e2f0468f438c17505", "text": "% lengthRatioConstraint - Affine transform constraints given a length ratio.\n%\n% Function calculates centre and radius of the constraint\n% circle in alpha-beta space generated by having a known\n% lenth ratio between two non-parallel line segemnts in\n% an affine image\n%\n% Usage: [c, r] = lengthRatioConstraint(p11, p12, p21, p22, s) \n%\n% Where: p11, p12 and p21, p22 are four points defining two line\n% segments having a known length ratio.\n% s is the known length ratio\n% c is the 2D coordinate of the centre of the constraint circle.\n% r is the radius of the centre of the constraint circle.\n\n% Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk @ csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% April 2000\n%\n% Equations from Liebowitz and Zisserman \n\nfunction [c, r] = lengthRatioConstraint(p11, p12, p21, p22, s) \n\ndp1 = p12-p11; dx1 = dp1(1); dy1 = dp1(2);\ndp2 = p22-p21; dx2 = dp2(1); dy2 = dp2(2);\n\nc = [(dx1*dy1 - s^2*dx2*dy2)/(dy1^2 - s^2*dy2^2), 0];\n\nr = abs( s*(dx2*dy1 - dx1*dy2)/(dy1^2 - s^2*dy2^2) );\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "fundfromcameras.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/fundfromcameras.m", "size": 1308, "source_encoding": "utf_8", "md5": "89d7618588ec84ececead8d97ea76b3e", "text": "% FUNDFROMCAMERAS - Fundamental matrix from camera matrices\n%\n% Usage: F = fundfromcameras(P1, P2)\n%\n% Arguments: P1, P2 - Two 3x4 camera matrices\n% Returns: F - Fundamental matrix relating the two camera views\n%\n% See also: FUNDMATRIX, AFFINEFUNDMATRIX\n\n% Reference: Hartley and Zisserman p244\n\n% Copyright (c) 2009 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction F = fundfromcameras(P1, P2)\n\n if ~all(size(P1) == [3 4]) | ~all(size(P2) == [3 4]) \n error('Camera matrices must be 3x4');\n end\n\n C1 = null(P1); % Camera centre 1 is the null space of P1\n e2 = P2*C1; % epipole in camera 2\n\n e2x = [ 0 -e2(3) e2(2) % Skew symmetric matrix from e2\n e2(3) 0 -e2(1)\n -e2(2) e2(1) 0 ];\n\n F = e2x*P2*pinv(P1);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "circleintersect.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/circleintersect.m", "size": 2710, "source_encoding": "utf_8", "md5": "489ffc783300c34976f2c82fbed8c020", "text": "% CIRCLEINTERSECT - Finds intersection of two circles.\n%\n% Function to return the intersection points between two circles\n% given their centres and radi.\n%\n% Usage: [i1, i2] = circleintersect(c1, r1, c2, r2, lr)\n%\n% Where:\n% c1 and c2 are 2-vectors specifying the centres of the two circles.\n% r1 and r2 are the radii of the two circles.\n% i1 and i2 are the two 2D intersection points (if they exist)\n% lr is an optional string specifying what solution is wanted:\n% 'l' for the solution to the left of the line from c1 to c2\n% 'r' for the solution to the right of the line from c1 to c2\n% 'lr' if both solutions are wanted (default).\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% Peter Kovesi\n% pk @ csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% April 2000 - original version\n% October 2003 - mods to allow selection of left/right solutions\n% and catching of degenerate triangles\n\nfunction [i1, i2] = circleintersect(c1, r1, c2, r2, lr)\n\nif nargin == 4\n lr = 'lr';\nend\n\nmaxmag = max([max(r1, r2), max(c1), max(c2)]); % maximum value in data input\ntol = 100*(maxmag+1)*eps; % Tolerance used for deciding whether values are equal\n % scaling by 100 is a bit arbitrary...\n\nbv = (c2-c1); % Baseline vector from c1 to c2\nb = norm(bv); % The distance between the centres\n\n% Trap case of baseline of zero length. If r1 == r2\n% we have a valid geometric situation, but there are an infinite number of\n% solutions. Here we simply choose to add r1 in the x direction to c1.\nif b < eps & abs(r1-r2) < tol \n i1 = c1 + [r1 0];\n i2 = i1;\n return\nend\n\nbv = bv/b; % Normalise baseline vector.\nbvp = [-bv(2) bv(1)]; % Vector perpendicular to baseline\n\n% Trap the degenerate cases where one of the radii are zero, or nearly zero\n\nif r1 < tol & abs(b-r2) < tol\n i1 = c1;\n i2 = c1;\n return;\nelseif r2 < tol & abs(b-r1) < tol\n i1 = c2;\n i2 = c2;\n return;\nend\n\n% Check triangle inequality\nif b > (r1+r2) | r1 > (b+r2) | r2 > (b+r1)\n c1, c2, r1, r2, b\n error('No solution to circle intersection');\nend\n\n% Normal solution\ncosR2 = (b^2 + r1^2 - r2^2)/(2*b*r1);\nsinR2 = sqrt(1-cosR2^2);\n\nif strcmpi(lr,'lr') \n i1 = c1 + r1*cosR2*bv + r1*sinR2*bvp; % 'left' solution\n i2 = c1 + r1*cosR2*bv - r1*sinR2*bvp; % and 'right solution\nelseif strcmpi(lr,'l')\n i1 = c1 + r1*cosR2*bv + r1*sinR2*bvp; % 'left' solution\n i2 = [];\nelseif strcmpi(lr,'r')\n i1 = c1 + r1*cosR2*bv - r1*sinR2*bvp; % 'right solution\n i2 = [];\nelse\n error('illegal left/right solution request');\nend\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "homoTrans.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/homoTrans.m", "size": 879, "source_encoding": "utf_8", "md5": "bde17d25ed5c319d12d7c6c52fa76ac9", "text": "% HOMOTRANS - homogeneous transformation of points\n%\n% Function to perform a transformation on homogeneous points/lines\n% The resulting points are normalised to have a homogeneous scale of 1\n%\n% Usage:\n% t = homoTrans(P,v);\n%\n% Arguments:\n% P - 3 x 3 or 4 x 4 transformation matrix\n% v - 3 x n or 4 x n matrix of points/lines\n\n% Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk @ csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% April 2000\n% September 2007\n\nfunction t = homotrans(P,v);\n \n [dim,npts] = size(v);\n \n if ~all(size(P)==dim)\n\terror('Transformation matrix and point dimensions do not match');\n end\n\n t = P*v; % Transform\n\n for r = 1:dim-1 % Now normalise \n\tt(r,:) = t(r,:)./t(end,:);\n end\n \n t(end,:) = ones(1,npts);\n \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "imTrans.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/imTrans.m", "size": 6645, "source_encoding": "utf_8", "md5": "fea80d088fd8c2973f2ee271ab3dc146", "text": "% IMTRANS - Homogeneous transformation of an image.\n%\n% Applies a geometric transform to an image\n%\n% [newim, newT] = imTrans(im, T, region, sze);\n%\n% Arguments: \n% im - The image to be transformed.\n% T - The 3x3 homogeneous transformation matrix.\n% region - An optional 4 element vector specifying \n% [minrow maxrow mincol maxcol] to transform.\n% This defaults to the whole image if you omit it\n% or specify it as an empty array [].\n% sze - An optional desired size of the transformed image\n% (this is the maximum No of rows or columns).\n% This defaults to the maximum of the rows and columns\n% of the original image.\n%\n% Returns:\n% newim - The transformed image.\n% newT - The transformation matrix that relates transformed image\n% coordinates to the reference coordinates for use in a\n% function such as DIGIPLANE.\n%\n% The region argument is used when one is inverting a perspective\n% transformation of a plane and the vanishing line of the plane lies within\n% the image. Attempts to transform any part of the vanishing line will\n% position you at infinity. Accordingly one should specify a region that\n% excludes any part of the vanishing line.\n%\n% The sze parameter is optionally used to control the size of the\n% output image. When inverting a perpective or affine transformation\n% the scale parameter is unknown/arbitrary, and without specifying\n% it explicitly the transformed image can end up being very small \n% or very large.\n%\n% Problems: If your transformed image ends up as being two small bits of\n% image separated by a large black area then the chances are that you have\n% included the vanishing line of the plane within the specified region to\n% transform. If your image degenerates to a very thin triangular shape\n% part of your region is probably very close to the vanishing line of the\n% plane.\n\n% Copyright (c) 2000-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% April 2000 - original version.\n% July 2001 - transformation of region boundaries corrected.\n\nfunction [newim, newT] = imTrans(im, T, region, sze);\n\nif isa(im,'uint8')\n im = double(im); % Make sure image is double \nend\n\n% Set up default region and transformed image size values\nif ndims(im) == 3\n [rows cols depth] = size(im);\nelse\n [rows cols] = size(im);\n depth = 1;\nend\n\nif nargin == 2\n region = [1 rows 1 cols];\n sze = max([rows cols]);\nelseif nargin == 3 \n sze = max([rows cols]);\nend\n\nif isempty(region)\n region = [1 rows 1 cols];\nend\n\n\t\nthreeD = (ndims(im)==3); % A colour image\nif threeD % Transform red, green, blue components separately\n im = im/255; \n [r, newT] = transformImage(im(:,:,1), T, region, sze);\n [g, newT] = transformImage(im(:,:,2), T, region, sze);\n [b, newT] = transformImage(im(:,:,3), T, region, sze);\n \n newim = repmat(uint8(0),[size(r),3]);\n newim(:,:,1) = uint8(round(r*255));\n newim(:,:,2) = uint8(round(g*255));\n newim(:,:,3) = uint8(round(b*255));\n \nelse % Assume the image is greyscale\n [newim, newT] = transformImage(im, T, region, sze);\nend\n\n%------------------------------------------------------------\n\n% The internal function that does all the work\n\nfunction [newim, newT] = transformImage(im, T, region, sze);\n\n[rows, cols] = size(im);\n\nif 0\n% Determine default parameters if needed\nif nargin == 2\n region = [1 rows 1 cols];\n sze = max(rows,cols);\nelseif nargin == 3\n sze = max(rows,cols);\nelseif nargin ~= 4\n error('Incorrect arguments to imtrans');\nend\nend\n% Cut the image down to the specified region\n%if nargin == 3 | nargin == 4\n im = im(region(1):region(2), region(3):region(4));\n [rows, cols] = size(im);\n%end\n\n% Find where corners go - this sets the bounds on the final image\nB = bounds(T,region);\nnrows = B(2) - B(1);\nncols = B(4) - B(3);\n\n% Determine any rescaling needed\ns = sze/max(nrows,ncols);\n\nS = [s 0 0 % Scaling matrix\n 0 s 0\n 0 0 1];\n\nT = S*T;\nTinv = inv(T);\n\n% Recalculate the bounds of the new (scaled) image to be generated\nB = bounds(T,region);\nnrows = B(2) - B(1);\nncols = B(4) - B(3);\n\n% Construct a transformation matrix that relates transformed image\n% coordinates to the reference coordinates for use in a function such as\n% DIGIPLANE. This transformation is just an inverse of a scaling and\n% origin shift. \nnewT=inv(S - [0 0 B(3); 0 0 B(1); 0 0 0]);\n\n% Set things up for the image transformation.\nnewim = zeros(nrows,ncols);\n[xi,yi] = meshgrid(1:ncols,1:nrows); % All possible xy coords in the image.\n\n% Transform these xy coords to determine where to interpolate values\n% from. Note we have to work relative to x=B(3) and y=B(1).\nsxy = homoTrans(Tinv, [xi(:)'+B(3) ; yi(:)'+B(1) ; ones(1,ncols*nrows)]);\nxi = reshape(sxy(1,:),nrows,ncols);\nyi = reshape(sxy(2,:),nrows,ncols);\n\n[x,y] = meshgrid(1:cols,1:rows);\nx = x+region(3)-1; % Offset x and y relative to region origin.\ny = y+region(1)-1; \nnewim = interp2(x,y,double(im),xi,yi); % Interpolate values from source image.\n\n\n%% Plot bounding region\n%P = [region(3) region(4) region(4) region(3)\n% region(1) region(1) region(2) region(2)\n% 1 1 1 1 ];\n%B = round(homoTrans(T,P));\n%Bx = B(1,:);\n%By = B(2,:);\n%Bx = Bx-min(Bx); Bx(5)=Bx(1);\n%By = By-min(By); By(5)=By(1);\n%show(newim,2), axis xy\n%line(Bx,By,'Color',[1 0 0],'LineWidth',2);\n%% end plot bounding region\n\n\n%---------------------------------------------------------------------\n%\n% Internal function to find where the corners of a region, R\n% defined by [minrow maxrow mincol maxcol] are transformed to \n% by transform T and returns the bounds, B in the form \n% [minrow maxrow mincol maxcol]\n\nfunction B = bounds(T, R)\n\nP = [R(3) R(4) R(4) R(3) % homogeneous coords of region corners\n R(1) R(1) R(2) R(2)\n 1 1 1 1 ];\n \nPT = round(homoTrans(T,P)); \n\nB = [min(PT(2,:)) max(PT(2,:)) min(PT(1,:)) max(PT(1,:))];\n% minrow maxrow mincol maxcol \n\n\n\n\n\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "affinefundmatrix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/affinefundmatrix.m", "size": 3219, "source_encoding": "utf_8", "md5": "7cbd1c7c427cf3466f0df1c9c57cd131", "text": "% AFFINEFUNDMATRIX - computes affine fundamental matrix from 4 or more points\n%\n% Function computes the affine fundamental matrix from 4 or more matching\n% points in a stereo pair of images. The Gold Standard algorithm given\n% by Hartley and Zisserman p351 (2nd Ed.) is used. \n%\n% Usage: [F, e1, e2] = affinefundmatrix(x1, x2)\n% [F, e1, e2] = affinefundmatrix(x)\n%\n% Arguments:\n% x1, x2 - Two sets of corresponding point. If each set is 3xN\n% it is assumed that they are homogeneous coordinates.\n% If they are 2xN it is assumed they are inhomogeneous.\n% \n% x - If a single argument is supplied it is assumed that it\n% is in the form x = [x1; x2]\n% Returns:\n% F - The 3x3 fundamental matrix such that x2'*F*x1 = 0.\n% e1 - The epipole in image 1 such that F*e1 = 0\n% e2 - The epipole in image 2 such that F'*e2 = 0\n%\n\n% Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% Feb 2005 \n\n\nfunction [F,e1,e2] = affinefundmatrix(varargin)\n \n [x1, x2, npts] = checkargs(varargin(:));\n\n X = [x2; x1]; % Form vectors of correspondences\n Xmean = mean(X,2); % Mean \n\n deltaX = zeros(size(X));\n for k = 1:4\n\tdeltaX(k,:) = X(k,:) - Xmean(k);\n end\n \n [U,D,V] = svd(deltaX',0);\n \n % Form fundamental matrix from the column of V corresponding to\n % smallest singular value.\n v = V(:,4);\n F = [ 0 0 v(1)\n\t 0 0 v(2)\n\t v(3) v(4) -v'*Xmean];\n \n % Solve for epipoles\n [U,D,V] = svd(F,0);\n e1 = V(:,3);\n e2 = U(:,3);\n \n%--------------------------------------------------------------------------\n% Function to check argument values and set defaults\n\nfunction [x1, x2, npts] = checkargs(arg);\n \n if length(arg) == 2\n x1 = arg{1};\n x2 = arg{2};\n if ~all(size(x1)==size(x2))\n error('x1 and x2 must have the same size');\n elseif size(x1,1) == 3\n\t % Convert to inhomogeneous coords\n x1(1,:) = x1(1,:)./x1(3,:);\n x1(2,:) = x1(2,:)./x1(3,:);\t \n x2(1,:) = x2(1,:)./x2(3,:);\n x2(2,:) = x2(2,:)./x2(3,:);\t \t \n\t x1 = x1(1:2,:); x2 = x2(1:2,:);\n elseif size(x1,1) ~= 2\n\t error('x1 and x2 must be 2xN or 3xN arrays');\n end\n \n elseif length(arg) == 1\n if size(arg{1},1) == 6\n x1 = arg{1}(1:3,:);\n x2 = arg{1}(4:6,:);\n\t % Convert to inhomogeneous coords\n x1(1,:) = x1(1,:)./x1(3,:);\n x1(2,:) = x1(2,:)./x1(3,:);\t \n x2(1,:) = x2(1,:)./x2(3,:);\n x2(2,:) = x2(2,:)./x2(3,:);\t \t \t \n\t x1 = x1(1:2,:); x2 = x2(1:2,:);\t \n elseif size(arg{1},1) == 4\n x1 = arg{1}(1:2,:);\n x2 = arg{1}(3:4,:);\t \n\telse\n\t error('Single argument x must be 6xN');\n end\n else\n error('Wrong number of arguments supplied');\n end\n \n npts = size(x1,2);\n if npts < 4\n error('At least 4 points are needed to compute the affine fundamental matrix');\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "imTransD.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/imTransD.m", "size": 3965, "source_encoding": "utf_8", "md5": "253939b60899cb7418ae8eebee0f8b87", "text": "% IMTRANSD - Homogeneous transformation of an image.\n%\n% This is a stripped down version of imTrans which does not apply any origin\n% shifting to the transformed image\n%\n% Applies a geometric transform to an image\n%\n% newim = imTransD(im, T, sze, lhrh);\n%\n% Arguments: \n% im - The image to be transformed.\n% T - The 3x3 homogeneous transformation matrix.\n% sze - 2 element vector specifying the size of the image that the\n% transformed image is placed into. If you are not sure\n% where your image is going to 'go' make sze large! (though\n% this does not help you if the image is placed at a negative\n% location) \n% lhrh - String 'lh' or 'rh' indicating whether the transform was\n% computed assuming columns represent x and rows represent y\n% (a left handed coordinate system) or if it was computed\n% using rows as x and columns as y (a right handed system,\n% albeit rotated 90 degrees). The default is assumed 'lh'\n% though 'rh' is probably more sensible.\n%\n%\n% Returns:\n% newim - The transformed image.\n%\n% See also: IMTRANS\n%\n\n% Copyright (c) 2000-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% April 2000 - Original version.\n% April 2010 - Allowance for left hand and right hand coordinate systems.\n% Offset of 1 pixel that was (incorrectly) applied in\n% transformImage removed.\n\nfunction newim = imTransD(im, T, sze, lhrh);\n\n if ~exist('lhrh','var'), lhrh = 'l'; end\n \n if isa(im,'uint8')\n im = double(im); % Make sure image is double \n end\n \n if lhrh(1) == 'r' % Transpose the image allowing for colour images\n im = permute(im,[2 1 3]);\n end\n \n threeD = (ndims(im)==3); % A colour image\n if threeD % Transform red, green, blue components separately\n im = im/255; \n r = transformImage(im(:,:,1), T, sze);\n g = transformImage(im(:,:,2), T, sze);\n b = transformImage(im(:,:,3), T, sze);\n \n newim = repmat(uint8(0),[size(r),3]);\n newim(:,:,1) = uint8(round(r*255));\n newim(:,:,2) = uint8(round(g*255));\n newim(:,:,3) = uint8(round(b*255));\n \n else % Assume the image is greyscale\n newim = transformImage(im, T, sze);\n end\n \n if lhrh(1) == 'r' % Transpose back again\n newim = permute(newim,[2 1 3]); \n end\n \n%------------------------------------------------------------\n\n% The internal function that does all the work\n\nfunction newim = transformImage(im, T, sze);\n \n [rows, cols] = size(im);\n \n % Set things up for the image transformation.\n newim = zeros(rows,cols);\n [xi,yi] = meshgrid(1:cols,1:rows); % All possible xy coords in the image.\n \n % Transform these xy coords to determine where to interpolate values\n % from. \n Tinv = inv(T);\n sxy = homoTrans(Tinv, [xi(:)' ; yi(:)' ; ones(1,cols*rows)]);\n \n xi = reshape(sxy(1,:),rows,cols);\n yi = reshape(sxy(2,:),rows,cols);\n \n [x,y] = meshgrid(1:cols,1:rows);\n \n% x = x-1; % Offset x and y relative to region origin.\n% y = y-1; \n newim = interp2(x,y,im,xi,yi); % Interpolate values from source image.\n \n % Place new image into an image of the desired size\n newim = implace(zeros(sze),newim,0,0);\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "hnormalise.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/hnormalise.m", "size": 1010, "source_encoding": "utf_8", "md5": "40eeebb3462ab60fb05b133bf0055baf", "text": "% HNORMALISE - Normalises array of homogeneous coordinates to a scale of 1\n%\n% Usage: nx = hnormalise(x)\n%\n% Argument:\n% x - an Nxnpts array of homogeneous coordinates.\n%\n% Returns:\n% nx - an Nxnpts array of homogeneous coordinates rescaled so\n% that the scale values nx(N,:) are all 1.\n%\n% Note that any homogeneous coordinates at infinity (having a scale value of\n% 0) are left unchanged.\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk\n%\n% February 2004\n\nfunction nx = hnormalise(x)\n \n [rows,npts] = size(x);\n nx = x;\n\n % Find the indices of the points that are not at infinity\n finiteind = find(abs(x(rows,:)) > eps);\n\n% if length(finiteind) ~= npts\n% warning('Some points are at infinity');\n% end\n\n % Normalise points not at infinity\n for r = 1:rows-1\n\tnx(r,finiteind) = x(r,finiteind)./x(rows,finiteind);\n end\n nx(rows,finiteind) = 1;\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "homography2d.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/homography2d.m", "size": 2493, "source_encoding": "utf_8", "md5": "60985e0ab95fe690d769c83adff61080", "text": "% HOMOGRAPHY2D - computes 2D homography\r\n%\r\n% Usage: H = homography2d(x1, x2)\r\n% H = homography2d(x)\r\n%\r\n% Arguments:\r\n% x1 - 3xN set of homogeneous points\r\n% x2 - 3xN set of homogeneous points such that x1<->x2\r\n% \r\n% x - If a single argument is supplied it is assumed that it\r\n% is in the form x = [x1; x2]\r\n% Returns:\r\n% H - the 3x3 homography such that x2 = H*x1\r\n%\r\n% This code follows the normalised direct linear transformation \r\n% algorithm given by Hartley and Zisserman \"Multiple View Geometry in\r\n% Computer Vision\" p92.\r\n%\r\n\r\n% Peter Kovesi\r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% pk at csse uwa edu au\r\n% http://www.csse.uwa.edu.au/~pk\r\n%\r\n% May 2003 - Original version.\r\n% Feb 2004 - Single argument allowed for to enable use with RANSAC.\r\n% Feb 2005 - SVD changed to 'Economy' decomposition (thanks to Paul O'Leary)\r\n\r\nfunction H = homography2d(varargin)\r\n \r\n [x1, x2] = checkargs(varargin(:));\r\n\r\n % Attempt to normalise each set of points so that the origin \r\n % is at centroid and mean distance from origin is sqrt(2).\r\n [x1, T1] = normalise2dpts(x1);\r\n [x2, T2] = normalise2dpts(x2);\r\n \r\n % Note that it may have not been possible to normalise\r\n % the points if one was at infinity so the following does not\r\n % assume that scale parameter w = 1.\r\n \r\n Npts = length(x1);\r\n A = zeros(3*Npts,9);\r\n \r\n O = [0 0 0];\r\n for n = 1:Npts\r\n\tX = x1(:,n)';\r\n\tx = x2(1,n); y = x2(2,n); w = x2(3,n);\r\n\tA(3*n-2,:) = [ O -w*X y*X];\r\n\tA(3*n-1,:) = [ w*X O -x*X];\r\n\tA(3*n ,:) = [-y*X x*X O ];\r\n end\r\n \r\n [U,D,V] = svd(A,0); % 'Economy' decomposition for speed\r\n \r\n % Extract homography\r\n H = reshape(V(:,9),3,3)';\r\n \r\n % Denormalise\r\n H = T2\\H*T1;\r\n \r\n\r\n%--------------------------------------------------------------------------\r\n% Function to check argument values and set defaults\r\n\r\nfunction [x1, x2] = checkargs(arg);\r\n \r\n if length(arg) == 2\r\n\tx1 = arg{1};\r\n\tx2 = arg{2};\r\n\tif ~all(size(x1)==size(x2))\r\n\t error('x1 and x2 must have the same size');\r\n\telseif size(x1,1) ~= 3\r\n\t error('x1 and x2 must be 3xN');\r\n\tend\r\n\t\r\n elseif length(arg) == 1\r\n\tif size(arg{1},1) ~= 6\r\n\t error('Single argument x must be 6xN');\r\n\telse\r\n\t x1 = arg{1}(1:3,:);\r\n\t x2 = arg{1}(4:6,:);\r\n\tend\r\n else\r\n\terror('Wrong number of arguments supplied');\r\n end\r\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "digiplane.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/digiplane.m", "size": 2368, "source_encoding": "utf_8", "md5": "9634b931390f4536b8d7280b8745f6a1", "text": "% DIGIPLANE - Digitise and transform points within a planar region in an image.\n%\n% This function allows you to digitise points within a planar region of an\n% image for which an inverse perspective transformation has been previously\n% determined using, say, INVPERSP. The digitised points are then\n% transformed into coordinates defined in terms of the reference frame.\n%\n% Usage: pts = digiplane(im, T, xyij)\n%\n% Arguments: im - Image. \n% T - Inverse perspective transform.\n% xyij - An optional string 'xy' or 'ij' indicating what\n% coordinate system should be used when displaying\n% the image. \n% xy - cartesian system with origin at bottom-left.\n% ij - 'matrix' system with origin at top-left.\n% An image which has been rectified, say using\n% imTrans, may want 'xy' set.\n%\n% Returns: pts - Nx2 array of transformed (x,y) coordinates.\n%\n% See also: invpersp, imTrans\n%\n%\n% Examples of use:\n% Assuming you have an image `im' for which you have a set of image\n% points 'impts' and a corresponding set of reference points 'refpts'.\n%\n% T = invpersp(refpts, impts); % Compute perspective transformation.\n% p = digiplane(im,T); % Digitise points in original image.\n%\n% ... or work with the rectified image\n% [newim, newT] = imTrans(im,T); % Rectify image using T from above\n% p = digiplane(newim,newT); % Digitise points in rectified image. \n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk @ csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% August 2001\n\nfunction pts = digiplane(im, T, xyij)\n \n if nargin < 3\n\txyij = 'ij';\n end\n \n pts = [];\n figure(1), clf, imshow(im), axis(xyij), hold on\n \n fprintf('Digitise points in the image with the left mouse button\\n');\n fprintf('Click any other button to exit\\n');\n\n [x,y,but] = ginput(1);\n while but == 1\n\tp = T*[x;y;1]; % Transform point.\n\txp = p(1)/p(3);\n\typ = p(2)/p(3);\n\tpts = [pts; xp yp];\n\t\n\tplot(x,y,'r+'); % Mark coordinates on image.\n\ttext(x+3,y-3,sprintf('[%.1f, %.1f]',xp,yp),'Color',[0 0 1], ...\n\t 'FontSize',6); \n\n\t[x,y,but] = ginput(1); \t% Get next point.\n end\n \n\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "circle.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/circle.m", "size": 1226, "source_encoding": "utf_8", "md5": "3ce939f9b481cd974576f40a598a69b6", "text": "% CIRCLE - Draws a circle.\n%\n% Usage: circle(c, r, n, col)\n%\n% Arguments: c - A 2-vector [x y] specifying the centre.\n% r - The radius.\n% n - Optional number of sides in the polygonal approximation.\n% (defualt is 16 sides)\n% col - optional colour, defaults to blue.\n\n% Copyright (c) 1996-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction h = circle(c, r, nsides, col)\n \n if nargin == 2\n\tnsides = 16;\n end\n \n if nargin < 4\n\tcol = [0 0 1];\n end\n \n nsides = max(round(nsides),3); % Make sure it is an integer >= 3\n \n a = [0:2*pi/nsides:2*pi];\n h = line(r*cos(a)+c(1), r*sin(a)+c(2), 'color', col);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "makeinhomogeneous.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/makeinhomogeneous.m", "size": 791, "source_encoding": "utf_8", "md5": "ce76d362845ed0c7eef257d1d0406795", "text": "% MAKEINHOMOGENEOUS - Converts homogeneous coords to inhomogeneous coordinates \n%\n% Usage: x = makehomogeneous(hx)\n%\n% Argument:\n% hx - an N x npts array of homogeneous coordinates.\n%\n% Returns:\n% x - an (N-1) x npts array of inhomogeneous coordinates\n%\n% Warning: If there are any points at infinity (scale = 0) the coordinates\n% of these points are simply returned minus their scale coordinate.\n%\n% See also: MAKEHOMOGENEOUS, HNORMALISE\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% April 2010\n\nfunction x = makeinhomogeneous(hx)\n \n hx = hnormalise(hx); % Normalise to scale of one\n x = hx(1:end-1,:); % Extract all but the last row\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "equalAngleConstraint.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/equalAngleConstraint.m", "size": 1377, "source_encoding": "utf_8", "md5": "ad2156349de0fe1efde5bee65bc38203", "text": "% equalAngleConstraint - Affine transform constraints given two equal angles.\n%\n% Function calculates centre and radius of the constraint\n% circle in alpha-beta space generated by having two equal\n% (but unknown) angles between two pairs of lines in \n% an affine image\n%\n% Usage: [c, r] = equalAngleConstraint(la1, lb1, la2, lb2)\n%\n% Where: la1 and lb1 are two lines defined using homogeneous coords that\n% are separated by an angle that is known to\n% be the same as the angle between \n% la2 and lb2 - the other two lines.\n% c is the 2D coordinate of the centre of the constraint circle.\n% r is the radius of the centre of the constraint circle.\n\n% Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk @ csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% April 2000\n%\n% Equations from Liebowitz and Zisserman \n\nfunction [c, r] = equalAngleConstraint(la1, lb1, la2, lb2)\n\na1 = -1a1(2)/la1(1); % direction of line la1\nb1 = -1b1(2)/lb1(1); % direction of line lb1\n\na2 = -1a2(2)/la2(1); % direction of line la2\nb2 = -1b2(2)/lb2(1); % direction of line lb2\n\nc = [(a1*b2 - b1*a2)/(a1 - b1 - a2 + b2), 0];\n\nr = ((a1*b2 - b1*a2)/(a1 - b1 - a2 + b2))^2 ...\n + ((a1 - b1)*(a1*b1 - a2*b2))/(a1 - b1 - a2 + b2) ...\n - a1*b1;\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "homogreprojerr.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/homogreprojerr.m", "size": 1423, "source_encoding": "utf_8", "md5": "15a06a2d240a29dd5d8a3a1e64268057", "text": "% HOMOGREPROJERR\n%\n% Computes the symmetric reprojection error for points related by a\n% homography.\n%\n% Usage:\n% d2 = homogreprojerr(H, x1, x2)\n%\n% Arguments:\n% H - The homography.\n% x1, x2 - [ndim x npts] arrays of corresponding homogeneous\n% data points.\n%\n% Returns:\n% d2 - 1 x npts vector of squared reprojection distances for\n% each corresponding pair of points.\n\n% Copyright (c) 2003-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2003\n% November 2005 - bug fix (thanks to Scott Blunsden)\n\nfunction d2 = homogreprojerr(H, x1, x2)\n \n x2t = H*x1; % Calculate projections of points\n x1t = H\\x2;\n \n x1 = hnormalise(x1); % Ensure scale is 1\n x2 = hnormalise(x2); \n x1t = hnormalise(x1t);\n x2t = hnormalise(x2t); \n \n d2 = sum( (x1-x1t).^2 + (x2-x2t).^2) );"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "rq3.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/rq3.m", "size": 2075, "source_encoding": "utf_8", "md5": "e3b4214d505526702abed6b2183c76ea", "text": "% RQ3 RQ decomposition of 3x3 matrix\n%\n% Usage: [R,Q] = rq3(A)\n%\n% Argument: A - 3 x 3 matrix\n% Returns: R - Upper triangular 3 x 3 matrix\n% Q - 3 x 3 orthonormal rotation matrix\n% Such that R*Q = A\n%\n% The signs of the rows and columns of R and Q are chosen so that the diagonal\n% elements of R are +ve.\n%\n% See also: DECOMPOSECAMERA\n\n% Follows algorithm given by Hartley and Zisserman 2nd Ed. A4.1 p 579\n\n% Copyright (c) 2010 Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% October 2010\n% February 2014 Incorporated modifications suggested by Mathias Rothermel to\n% avoid potential division by zero problems\n\nfunction [R,Q] = rq3(A)\n \n if ~all(size(A)==[3 3])\n error('A must be 3x3');\n end\n \n eps = 1e-10;\n \n % Find rotation Qx to set A(3,2) to 0\n A(3,3) = A(3,3) + eps;\n c = -A(3,3)/sqrt(A(3,3)^2+A(3,2)^2);\n s = A(3,2)/sqrt(A(3,3)^2+A(3,2)^2);\n Qx = [1 0 0; 0 c -s; 0 s c];\n R = A*Qx;\n \n % Find rotation Qy to set A(3,1) to 0\n R(3,3) = R(3,3) + eps;\n c = R(3,3)/sqrt(R(3,3)^2+R(3,1)^2);\n s = R(3,1)/sqrt(R(3,3)^2+R(3,1)^2);\n Qy = [c 0 s; 0 1 0;-s 0 c];\n R = R*Qy;\n \n % Find rotation Qz to set A(2,1) to 0 \n R(2,2) = R(2,2) + eps;\n c = -R(2,2)/sqrt(R(2,2)^2+R(2,1)^2);\n s = R(2,1)/sqrt(R(2,2)^2+R(2,1)^2); \n Qz = [c -s 0; s c 0; 0 0 1];\n R = R*Qz;\n \n Q = Qz'*Qy'*Qx';\n \n % Adjust R and Q so that the diagonal elements of R are +ve\n for n = 1:3\n if R(n,n) < 0\n R(:,n) = -R(:,n);\n Q(n,:) = -Q(n,:);\n end\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "knownAngleConstraint.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/knownAngleConstraint.m", "size": 929, "source_encoding": "utf_8", "md5": "b51714229fca51b80fc72c837575dd25", "text": "% knownAngleConstraint - Affine transform constraints given a known angle.\n%\n% Function calculates centre and radius of the constraint\n% circle in alpha-beta space generated by having a known\n% angle between two lines in an affine image\n%\n% Usage: [c, r] = knownAngleConstraint(la, lb, theta)\n%\n% Where: la and lb are the two lines defined using homogeneous coords.\n% theta is the known angle between the lines.\n% c is the 2D coordinate of the centre of the constraint circle.\n% r is the radius of the centre of the constraint circle.\n\n% Peter Kovesi April 2000\n% Department of Computer Science\n% The University of Western Australia\n\n% Equations from Liebowitz and Zisserman \n\nfunction [c, r] = knownAngleConstraint(la, lb, theta)\n\na = -la(2)/la(1); % direction of line la\nb = -lb(2)/lb(1); % direction of line lb\n\nc = [(a+b)/2, (a-b)/2*cot(theta)];\n\nr = abs( (a-b)/(2*sin(theta)) );\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "fundmatrix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/fundmatrix.m", "size": 3966, "source_encoding": "utf_8", "md5": "035de87dbdc38f5d36c84caeb895ca93", "text": "% FUNDMATRIX - computes fundamental matrix from 8 or more points\n%\n% Function computes the fundamental matrix from 8 or more matching points in\n% a stereo pair of images. The normalised 8 point algorithm given by\n% Hartley and Zisserman p265 is used. To achieve accurate results it is\n% recommended that 12 or more points are used\n%\n% Usage: [F, e1, e2] = fundmatrix(x1, x2)\n% [F, e1, e2] = fundmatrix(x)\n%\n% Arguments:\n% x1, x2 - Two sets of corresponding 3xN set of homogeneous\n% points.\n% \n% x - If a single argument is supplied it is assumed that it\n% is in the form x = [x1; x2]\n% Returns:\n% F - The 3x3 fundamental matrix such that x2'*F*x1 = 0.\n% e1 - The epipole in image 1 such that F*e1 = 0\n% e2 - The epipole in image 2 such that F'*e2 = 0\n%\n\n% Copyright (c) 2002-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% Feb 2002 - Original version.\n% May 2003 - Tidied up and numerically improved.\n% Feb 2004 - Single argument allowed to enable use with RANSAC.\n% Mar 2005 - Epipole calculation added, 'economy' SVD used.\n% Aug 2005 - Octave compatibility\n\nfunction [F,e1,e2] = fundmatrix(varargin)\n \n [x1, x2, npts] = checkargs(varargin(:));\n Octave = exist('OCTAVE_VERSION', 'builtin') == 5; % Are we running under Octave\n \n % Normalise each set of points so that the origin \n % is at centroid and mean distance from origin is sqrt(2). \n % normalise2dpts also ensures the scale parameter is 1.\n [x1, T1] = normalise2dpts(x1);\n [x2, T2] = normalise2dpts(x2);\n \n % Build the constraint matrix\n A = [x2(1,:)'.*x1(1,:)' x2(1,:)'.*x1(2,:)' x2(1,:)' ...\n x2(2,:)'.*x1(1,:)' x2(2,:)'.*x1(2,:)' x2(2,:)' ...\n x1(1,:)' x1(2,:)' ones(npts,1) ]; \n\n if Octave\n\t[U,D,V] = svd(A); % Don't seem to be able to use the economy\n % decomposition under Octave here\n else\n\t[U,D,V] = svd(A,0); % Under MATLAB use the economy decomposition\n end\n\n % Extract fundamental matrix from the column of V corresponding to\n % smallest singular value.\n F = reshape(V(:,9),3,3)';\n \n % Enforce constraint that fundamental matrix has rank 2 by performing\n % a svd and then reconstructing with the two largest singular values.\n [U,D,V] = svd(F,0);\n F = U*diag([D(1,1) D(2,2) 0])*V';\n \n % Denormalise\n F = T2'*F*T1;\n \n if nargout == 3 \t% Solve for epipoles\n\t[U,D,V] = svd(F,0);\n\te1 = hnormalise(V(:,3));\n\te2 = hnormalise(U(:,3));\n end\n \n%--------------------------------------------------------------------------\n% Function to check argument values and set defaults\n\nfunction [x1, x2, npts] = checkargs(arg);\n \n if length(arg) == 2\n x1 = arg{1};\n x2 = arg{2};\n if ~all(size(x1)==size(x2))\n error('x1 and x2 must have the same size');\n elseif size(x1,1) ~= 3\n error('x1 and x2 must be 3xN');\n end\n \n elseif length(arg) == 1\n if size(arg{1},1) ~= 6\n error('Single argument x must be 6xN');\n else\n x1 = arg{1}(1:3,:);\n x2 = arg{1}(4:6,:);\n end\n else\n error('Wrong number of arguments supplied');\n end\n \n npts = size(x1,2);\n if npts < 8\n error('At least 8 points are needed to compute the fundamental matrix');\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "hline.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/hline.m", "size": 1836, "source_encoding": "utf_8", "md5": "6b627df996e670c2c7287683e1851639", "text": "% HLINE - Plot 2D lines defined in homogeneous coordinates.\n%\n% Function for ploting 2D homogeneous lines defined by 2 points\n% or a line defined by a single homogeneous vector\n%\n% Usage: hline(p1,p2) where p1 and p2 are 2D homogeneous points.\n% hline(p1,p2,'colour_name') 'black' 'red' 'white' etc\n% hline(l) where l is a line in homogeneous coordinates\n% hline(l,'colour_name')\n%\n% Note that in the case where a homogeneous line is supplied as the argument\n% the extent of the line drawn depends on the current axis limits. This will\n% require you to set the desired limits with a call to AXIS prior to calling\n% this function.\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% April 2000\n% October 2013 Corrections to computation of line limits\n\nfunction hline(a, b, c)\n\ncol = 'blue'; % default colour\n\nif nargin >= 2 & isa(a,'double') & isa(b,'double') % Two points specified\n\n p1 = a./a(3); % make sure homogeneous points lie in z=1 plane\n p2 = b./b(3);\n\n if nargin == 3 & isa(c,'char') % 2 points and a colour specified\n col = c;\n end\n\nelseif nargin >= 1 & isa(a,'double') % A single line specified\n\n a = a./a(3); % ensure line in z = 1 plane (not needed??)\n\n if abs(a(1)) > abs(a(2)) % line is more vertical\n ylim = get(gca,'Ylim');\n p1 = hcross(a, [0 -1 ylim(1)]');\n p2 = hcross(a, [0 -1 ylim(2)]'); \n \n else % line more horizontal\n xlim = get(gca,'Xlim');\n p1 = hcross(a, [-1 0 xlim(1)]');\n p2 = hcross(a, [-1 0 xlim(2)]'); \n end\n\n if nargin == 2 & isa(b,'char') % 1 line vector and a colour specified\n col = b;\n end\n\nelse\n error('Bad arguments passed to hline');\nend\n\nline([p1(1) p2(1)], [p1(2) p2(2)], 'color', col);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "homography1d.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/homography1d.m", "size": 2662, "source_encoding": "utf_8", "md5": "bf1d84269964988e4400e66cabf14617", "text": "% HOMOGRAPHY1D - computes 1D homography\r\n%\r\n% Usage: H = homography1d(x1, x2)\r\n%\r\n% Arguments:\r\n% x1 - 2xN set of homogeneous points\r\n% x2 - 2xN set of homogeneous points such that x1<->x2\r\n% Returns:\r\n% H - the 2x2 homography such that x2 = H*x1\r\n%\r\n% This code is modelled after the normalised direct linear transformation\r\n% algorithm for the 2D homography given by Hartley and Zisserman p92.\r\n%\r\n\r\n% Peter Kovesi\r\n% School of Computer Science & Software Engineering\r\n% The University of Western Australia\r\n% pk @ csse uwa edu au\r\n% http://www.csse.uwa.edu.au/~pk\r\n%\r\n% May 2003\r\n\r\nfunction H = homography1d(x1, x2)\r\n\r\n % check matrix sizes\r\n if ~all(size(x1) == size(x2))\r\n error('x1 and x2 must have same dimensions');\r\n end\r\n \r\n % Attempt to normalise each set of points so that the origin \r\n % is at centroid and mean distance from origin is 1.\r\n [x1, T1] = normalise1dpts(x1);\r\n [x2, T2] = normalise1dpts(x2);\r\n\r\n % Note that it may have not been possible to normalise\r\n % the points if one was at infinity so the following does not\r\n % assume that scale parameter w = 1.\r\n\r\n Npts = length(x1);\r\n A = zeros(2*Npts,4);\r\n\r\n for n = 1:Npts\r\n X = x1(:,n)';\r\n x = x2(1,n); w = x2(2,n);\r\n A(n,:) = [-w*X x*X];\r\n end\r\n\r\n [U,D,V] = svd(A);\r\n\r\n % Extract homography\r\n H = reshape(V(:,4),2,2)';\r\n\r\n % Denormalise\r\n H = T2\\H*T1;\r\n\r\n % Report error in fitting homography...\r\n\r\n% NORMALISE1DPTS - normalises 1D homogeneous points\r\n%\r\n% Function translates and normalises a set of 1D homogeneous points \r\n% so that their centroid is at the origin and their mean distance from \r\n% the origin is 1. \r\n%\r\n% Usage: [newpts, T] = normalise1dpts(pts)\r\n%\r\n% Argument:\r\n% pts - 2xN array of 2D homogeneous coordinates\r\n%\r\n% Returns:\r\n% newpts - 2xN array of transformed 1D homogeneous coordinates\r\n% T - The 2x2 transformation matrix, newpts = T*pts\r\n% \r\n% Note that if one of the points is at infinity no normalisation\r\n% is possible. In this case a warning is printed and pts is\r\n% returned as newpts and T is the identity matrix.\r\n\r\nfunction [newpts, T] = normalise1dpts(pts)\r\n\r\n if ~all(pts(2,:))\r\n warning('Attempt to normalise a point at infinity')\r\n newpts = pts;\r\n T = eye(2);\r\n return;\r\n end\r\n\r\n % Ensure homogeneous coords have scale of 1\r\n pts(1,:) = pts(1,:)./pts(2,:);\r\n\r\n c = mean(pts(1,:)')'; % Centroid.\r\n newp = pts(1,:)-c; % Shift origin to centroid.\r\n\r\n meandist = mean(abs(newp));\r\n scale = 1/meandist;\r\n\r\n T = [scale -scale*c\r\n 0 1 ];\r\n\r\n newpts = T*pts;\r\n\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "decomposecamera.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/decomposecamera.m", "size": 3283, "source_encoding": "utf_8", "md5": "74f6d563e0498193a8e7d05ec90963c1", "text": "% DECOMPOSECAMERA Decomposition of a camera projection matrix\n%\n% Usage: [K, R, C, pp, pv] = decomposecamera(P);\n%\n% P is decomposed into the form P = K*[R -R*C]\n%\n% Argument: P - 3 x 4 camera projection matrix\n% Returns: \n% K - Calibration matrix of the form\n% | ax s x0 |\n% | 0 ay y0 |\n% | 0 0 1 |\n%\n% Where: \n% ax = f/pixel_width and ay = f/pixel_height,\n% x0 and y0 define the principal point in pixels,\n% s is the camera skew.\n% R - 3 x 3 rotation matrix defining the world coordinate frame\n% in terms of the camera frame. Columns of R transposed define\n% the directions of the camera X, Y and Z axes in world\n% coordinates. \n% C - Camera centre position in world coordinates.\n% pp - Image principal point.\n% pv - Principal vector from the camera centre C through pp\n% pointing out from the camera. This may not be the same as \n% R'(:,3) if the principal point is not at the centre of the\n% image, but it should be similar. \n%\n% See also: RQ3\n\n% Reference: Hartley and Zisserman 2nd Ed. pp 155-164\n\n% Copyright (c) 2010 Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% October 2010 Original version\n% November 2013 Description of rotation matrix R corrected (transposed)\n\nfunction [K, R, C, pp, pv] = decomposecamera(P)\n \n % Projection matrix from Hartley and Zisserman p 163 used for testing\n if ~exist('P','var')\n P = [ 3.53553e+2 3.39645e+2 2.77744e+2 -1.44946e+6\n -1.03528e+2 2.33212e+1 4.59607e+2 -6.32525e+5\n 7.07107e-1 -3.53553e-1 6.12372e-1 -9.18559e+2];\n end\n \n % Convenience variables for the columns of P\n p1 = P(:,1);\n p2 = P(:,2);\n p3 = P(:,3);\n p4 = P(:,4); \n\n M = [p1 p2 p3];\n m3 = M(3,:)';\n \n % Camera centre, analytic solution\n X = det([p2 p3 p4]);\n Y = -det([p1 p3 p4]);\n Z = det([p1 p2 p4]);\n T = -det([p1 p2 p3]); \n \n C = [X;Y;Z;T]; \n C = C/C(4); \n C = C(1:3); % Make inhomogeneous\n \n % C = null(P,'r'); % numerical way of computing C\n \n % Principal point\n pp = M*m3;\n pp = pp/pp(3); \n pp = pp(1:2); % Make inhomogeneous\n \n % Principal ray pointing out of camera\n pv = det(M)*m3;\n pv = pv/norm(pv);\n \n % Perform RQ decomposition of M matrix. Note that rq3 returns K with +ve\n % diagonal elements, as required for the calibration marix.\n [K R] = rq3(M);\n \n % Check that R is right handed, if not give warning\n if dot(cross(R(:,1), R(:,2)), R(:,3)) < 0\n warning('Note that rotation matrix is left handed');\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "normalise2dpts.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/normalise2dpts.m", "size": 2361, "source_encoding": "utf_8", "md5": "2b9d94a3681186006a3fd47a45faf939", "text": "% NORMALISE2DPTS - normalises 2D homogeneous points\n%\n% Function translates and normalises a set of 2D homogeneous points \n% so that their centroid is at the origin and their mean distance from \n% the origin is sqrt(2). This process typically improves the\n% conditioning of any equations used to solve homographies, fundamental\n% matrices etc.\n%\n% Usage: [newpts, T] = normalise2dpts(pts)\n%\n% Argument:\n% pts - 3xN array of 2D homogeneous coordinates\n%\n% Returns:\n% newpts - 3xN array of transformed 2D homogeneous coordinates. The\n% scaling parameter is normalised to 1 unless the point is at\n% infinity. \n% T - The 3x3 transformation matrix, newpts = T*pts\n% \n% If there are some points at infinity the normalisation transform\n% is calculated using just the finite points. Being a scaling and\n% translating transform this will not affect the points at infinity.\n\n% Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% May 2003 - Original version\n% February 2004 - Modified to deal with points at infinity.\n% December 2008 - meandist calculation modified to work with Octave 3.0.1\n% (thanks to Ron Parr)\n\n\nfunction [newpts, T] = normalise2dpts(pts)\n\n if size(pts,1) ~= 3\n error('pts must be 3xN');\n end\n \n % Find the indices of the points that are not at infinity\n finiteind = find(abs(pts(3,:)) > eps);\n \n if length(finiteind) ~= size(pts,2)\n warning('Some points are at infinity');\n end\n \n % For the finite points ensure homogeneous coords have scale of 1\n pts(1,finiteind) = pts(1,finiteind)./pts(3,finiteind);\n pts(2,finiteind) = pts(2,finiteind)./pts(3,finiteind);\n pts(3,finiteind) = 1;\n \n c = mean(pts(1:2,finiteind)')'; % Centroid of finite points\n newp(1,finiteind) = pts(1,finiteind)-c(1); % Shift origin to centroid.\n newp(2,finiteind) = pts(2,finiteind)-c(2);\n \n dist = sqrt(newp(1,finiteind).^2 + newp(2,finiteind).^2);\n meandist = mean(dist(:)); % Ensure dist is a column vector for Octave 3.0.1\n \n scale = sqrt(2)/meandist;\n \n T = [scale 0 -scale*c(1)\n 0 scale -scale*c(2)\n 0 0 1 ];\n \n newpts = T*pts;\n \n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "hcross.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Projective/hcross.m", "size": 919, "source_encoding": "utf_8", "md5": "dbb3f3d4ef79e25ca3000ea976409e0c", "text": "% HCROSS - Homogeneous cross product, result normalised to s = 1.\n%\n% Function to form cross product between two points, or lines,\n% in homogeneous coodinates. The result is normalised to lie\n% in the scale = 1 plane.\n% \n% Usage: c = hcross(a,b)\n%\n\n% Copyright (c) 2000-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% April 2000\n\nfunction c = hcross(a,b)\nc = cross(a,b);\nc = c/c(3);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "upwardcontinue.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Geosci/upwardcontinue.m", "size": 3839, "source_encoding": "utf_8", "md5": "a7a1d8416166d9c658b7a7d4bac8770b", "text": "% UPWARDCONTINUE Upward continuation for magnetic or gravity potential field data\n%\n% Usage: [up, psf] = upwardcontinue(im, h, dx, dy)\n%\n% Arguments: im - Input potential field image\n% h - Height to upward continue to (+ve)\n% dx, dy - Grid spacing in x and y. The upward continuation height\n% is computed relative to the grid spacing. If omitted dx =\n% dy = 1, that is, the value of h is in grid spacing units.\n% If dy is omitted it is assumed dy = dx. \n%\n% Returns: up - The upward continued field image\n% psf - The point spread function corresponding to the upward\n% continuation height.\n%\n% Upward continuation filtering is done in the frequency domain whereby the\n% Fourier transform of the upward continued image F(Up) is obtained from the\n% Fourier transform of the input image F(U) using\n% F(Up) = e^(-2*pi*h * sqrt(u^2 + v^2)) * F(U)\n% where u and v are the spatial frequencies over the input grid.\n%\n% To minimise edge effect problems Moisan's Periodic FFT is used. This avoids\n% the need for data tapering. \n%\n% References: \n% Richard Blakely, \"Potential Theory in Gravity and Magnetic Applications\"\n% Cambridge University Press, 1996, pp 315-319\n%\n% L. Moisan, \"Periodic plus Smooth Image Decomposition\", Journal of\n% Mathematical Imaging and Vision, vol 39:2, pp. 161-179, 2011.\n%\n% See also: PERFFT2\n\n% Copyright (c) Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% June 2012 - Original version.\n% June 2014 - Tidied up and documented.\n% August 2014 - Smooth, non periodic component of orginal image added back to\n% filtered result so that calculation of residual against the\n% original image is facilitated.\n\nfunction [up, psf] = upwardcontinue(im, h, dx, dy)\n\n if ~exist('dx', 'var'), dx = 1; end\n if ~exist('dy', 'var'), dy = dx; end\n \n [rows,cols,chan] = size(im);\n assert(chan == 1, 'Image must be single channel');\n\n mask = ~isnan(im); \n \n % Use Periodic FFT rather than data tapering to minimise edge effects.\n % Save the smooth, non periodic component of the image to add back into\n % the final filtered result.\n [IM, ~, ~, sm] = perfft2(fillnan(im)); \n \n % Generate horizontal and vertical frequency grids that vary from\n % -0.5 to 0.5 \n [u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ...\n\t\t\t([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2)));\n\n % Quadrant shift to put 0 frequency at the corners. Also, divide by grid\n % size to get correct spatial frequencies\n u1 = ifftshift(u1)/dx; \n u2 = ifftshift(u2)/dy;\n\n freq = sqrt(u1.^2 + u2.^2); % Matrix values contain spatial frequency\n % values as a radius from centre (but\n % quadrant shifted) \n \n % Continuation filter in the frequency domain\n W = exp(-2*pi*h*freq);\n \n % Apply filter to obtain upward continuation, add smooth component of\n % image back in and apply mask to remove NaN values\n up = (real(ifft2(IM.*W)) + sm) .* double(mask);\n \n % Reconstruct the spatial representation of the point spread function\n % corresponding to the upward continuation height\n psf = real(fftshift(ifft2(W)));\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "orientationfilter.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Geosci/orientationfilter.m", "size": 6042, "source_encoding": "utf_8", "md5": "9e5fa0a05cdc4d0f3b48c2710e4e91f4", "text": "% ORIENTATIONFILTER Generate orientation selective filterings of an image\n%\n% Usage: oim = orientationfilter(im, norient, angoverlap, boost, cutoff, histcut)\n%\n% Arguments: im - Image to be filtered.\n% norient - Number of orientations, try 8.\n% angoverlap - Angular bandwidth overlap factor. A value of 1 gives a \n% minimum overlap between adjacent filter orientations\n% while still providing full coverage of the spectrum.\n% However, it is often useful to provide greater overlap\n% between adjacent filter orientations, especially if the\n% output is to be viewed using the CYCLEMIX image\n% blender. This gives smoother transitions between\n% images. Try values 1.5 to 2.0 \n% boost - The ratio that high frequency values are boosted\n% (or supressed) relative to the low frequency values.\n% Try values in the range 2 - 4 to start with. Use a\n% value of 1 for no boost. \n% cutoff - Cutoff frequency of the highboost filter 0 - 0.5, try 0.2\n% histcut - Percentage of the histogram extremes to truncate. This\n% is useful in preventing outlying values in the data\n% from dominating in the image rescaling for display. Try\n% a small amount, say, 0.01%\n%\n% Returns: oim - Cell array of length 'norient' containing the\n% orientation filtered images.\n%\n%\n% This function is designed to help identify oriented structures within an image\n% by applying orientation selective filters. If one is looking for lineaments\n% it is typically useful to boost the high frequency components in the image as\n% well, hence the combination of the two filters\n%\n% Example: Generate 8 orientation filterings of an image with an angular\n% bandwidth overlap factor of 1.5 and amplifying spatial frequencies greater\n% than 0.1 (wavelenths < 10 pixels) by a factor of 2. Also truncate the image\n% histograms so that 0.01% of image pixels are saturated. This helps ensure\n% that outlying data values do not dominate when the image is scaled for\n% display.\n%\n% >> oim = orienationfilter(im, 8, 1.5, 2, 0.1, 0.01);\n%\n% An effective way to view all the output images is to use the cyclic image\n% blending tool CYCLEMIX.m\n%\n% >> cyclemix(oim);\n%\n% Note that the cyclemix control wheel varies from 0 - 2pi and these angles are\n% mapped to the orientation filtered images which vary from 0 - pi in angle.\n% This makes the interface a bit counterintuitive to use. To get around this\n% one can replicate the the cell array of orientation filtered images giving an\n% array that corresponds to the angles 0 - pi, 0 - pi. When this is passed to\n% cyclemix you get a much more intuitive interface\n%\n% >> cyclemix({oim{:} oim{:}})\n% \n% See also: CYCLEMIX, HIGHBOOSTFILTER, HISTTRUNCATE \n\n% Copyright (c) 2012-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% August 2012 Original version\n% July 2014 Revised to incorporate highboost filtering and histogram truncation\n\nfunction oim = orientationfilter(im, norient, angoverlap, boost, cutoff, histcut)\n \n IM = fft2(im);\n [rows,cols] = size(im);\n\n if ~exist('angoverlap','var')\n angScale = norient/2;\n else\n angScale = norient/2 / angoverlap;\n end\n \n % If a highboost filter has been specified apply it to the fourier\n % transform of the image.\n if exist('cutoff', 'var')\n IM = IM .* highboostfilter([rows,cols], cutoff, 1, boost);\n end\n \n if ~exist('histcut','var'), histcut = 0; end\n \n % Construct frequency domain filter matrices\n [ ~ , u1, u2] = filtergrid(rows,cols);\n \n theta = atan2(-u2,u1); % Matrix values contain polar angle.\n % (note -ve y is used to give +ve\n % anti-clockwise angles)\n sintheta = sin(theta);\n costheta = cos(theta);\n\n for o = 1:norient % For each orientation...\n angl = (o-1)*pi/norient; % Filter angle.\n \n % For each point in the filter matrix calculate the angular distance from\n % the specified filter orientation. To overcome the angular wrap-around\n % problem sine difference and cosine difference values are first computed\n % and then the atan2 function is used to determine angular distance.\n ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine.\n dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine.\n dtheta = abs(atan2(ds,dc)); % Absolute angular distance.\n \n % Scale theta so that cosine spread function has the right wavelength and clamp to pi \n dtheta = min(dtheta*angScale,pi);\n\n % The orientation filter haa a cosine cross section in the frequency domain\n % The spread function is cos(dtheta) between -pi and pi. We add 1,\n % and then divide by 2 so that the value ranges 0-1\n spread = (cos(dtheta)+1)/2; \n spread = spread + fliplr(flipud(spread));\n % show(fftshift(spread),o);\n \n % Apply orientation filter\n oim{o} = real(ifft2(IM.*spread));\n \n % Truncate extremes of image histogram\n if histcut\n oim{o} = histtruncate(oim{o}, histcut, histcut);\n end\n end"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "relief.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Geosci/relief.m", "size": 5218, "source_encoding": "utf_8", "md5": "8f99e38c832592297aa91384d12779a2", "text": "% RELIEF Generates relief shaded image\n%\n% Usage: shadeim = relief(im, azimuth, elevation, dx, rgbim)\n%\n% Arguments: im - Image/heightmap to be relief shaded.\n% azimuth - Of light direction in degrees. Zero azimuth points \n% upwards and increases clockwise. Defaults to 45.\n% elevation - Of light direction in degrees. Defaults to 45.\n% gradscale - Scaling to apply to the surface gradients. If the shading\n% is excessive decrease the scaling. Try successive doubling\n% or halving to find a good value. \n% rgbim - Optional RGB image to which the shading pattern derived\n% from 'im' is applied. Alternatively, rgbim can be a Nx3\n% RGB colourmap which is applied to the input\n% image/heightmap in order to obtain a RGB image to which\n% the shading pattern is applied.\n%\n% This function generates a relief shaded image. For interactive relief\n% shading use IRELIEF. IRELIEF reports the azimuth, elevation and gradient\n% scaling values that can then be reused on this function.\n%\n% Lambertian shading is used to form the relief image. This obtained from the\n% cosine of the angle between the surface normal and light direction. Note that\n% shadows are ignored. Thus a small feature that might otherwise be in the\n% shadow of a nearby large structure is rendered as if the large feature was not\n% there.\n%\n% See also: IRELIEF, APPLYCOLOURMAP\n\n% Copyright (c) 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% April 2014 \n\nfunction shadeim = relief(im, az, el, gradscale, rgbim)\n\n [rows, cols, chan] = size(im);\n assert(chan==1)\n \n if ~exist('az', 'var'), az = 45; end\n if ~exist('el', 'var'), el = 45; end\n if ~exist('gradscale', 'var'), gradscale = 1; end\n \n if exist('rgbim', 'var') \n [rr, cc, ch] = size(rgbim);\n if cc == 3 && ch == 1 % Assume this is a colourmap that is to be\n % applied to the image/heightmap \n rgbim = applycolourmap(im, rgbim);\n \n elseif ~isempty(rgbim) % Check its size\n if rows ~= rr || cols ~= cc || ch ~= 3\n error('Sizes of im and rgbim are not compatible'); \n end\n end\n else % No image supplied\n rgbim = []; \n end\n \n\n % Obtain surface normals of im\n loggrad = 'lin';\n [n1, n2, n3] = surfacenormals(im, gradscale, loggrad);\n \n % Convert azimuth and elevation to a lighting direction vector. Note that\n % the vector is constructed so that an azimuth of 0 points upwards and\n % increases clockwise.\n az = az/180*pi;\n el = el/180*pi;\n I = [cos(el)*sin(az), cos(el)*cos(az), sin(el)];\n I = I./norm(I); % Ensure I is a unit vector \n \n % Generate Lambertian shading via the dot product between surface normals\n % and the light direction. Note that the product with n2 is negated to\n % account for the image +ve y increasing downwards.\n shading = I(1)*n1 - I(2)*n2 + I(3)*n3; \n\n % Remove -ve shading values which are generated by surface normals pointing\n % away from the light source.\n shading(shading < 0) = 0;\n \n % If no RGB image has been supplied just return the raw shading image\n if isempty(rgbim)\n shadeim = shading;\n \n else % Apply shading to the RGB image supplied\n shadeim = zeros(size(rgbim));\n \n for n = 1:3\n shadeim(:,:,n) = rgbim(:,:,n).*shading;\n end\n end\n \n % ** Resolve issue with RGB image being double or uint8\n \n \n%---------------------------------------------------------------------------\n% Compute image/heightmap surface normals\n\nfunction [n1, n2, n3] = surfacenormals(im, gradscale, loggrad)\n \n % Compute partial derivatives of z.\n % p = dz/dx, q = dz/dy\n\n [p,q] = gradient(im); \n p = p*gradscale;\n q = q*gradscale;\n \n % If specified take logs of gradient.\n % Note that taking the log of the surface gradients will produce a surface\n % that is not integrable (probably only of theoretical interest)\n if strcmpi(loggrad, 'log')\n p = sign(p).*log1p(abs(p));\n q = sign(q).*log1p(abs(q));\n elseif strcmpi(loggrad, 'loglog')\n p = sign(p).*log1p(log1p(abs(p)));\n q = sign(q).*log1p(log1p(abs(q)));\n elseif strcmpi(loggrad, 'logloglog')\n p = sign(p).*log1p(log1p(log1p(abs(p))));\n q = sign(q).*log1p(log1p(log1p(abs(q))));\n end\n \n % Generate surface unit normal vectors. Components stored in n1, n2\n % and n3 \n mag = sqrt(1 + p.^2 + q.^2);\n n1 = -p./mag;\n n2 = -q./mag;\n n3 = 1./mag;\n\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "irelief.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Geosci/irelief.m", "size": 13014, "source_encoding": "utf_8", "md5": "f5dec6de9b362a6a4b8ee3a046bf3209", "text": "% IRELIEF Interactive Relief Shading\n%\n% Usage: irelief(im, rgbim, figNo)\n%\n% Arguments: im - Image/heightmap to be relief shaded\n% rgbim - Optional RGB image to which the shading pattern derived\n% from 'im' is applied. Alternatively, rgbim can be a Nx3\n% RGB colourmap which is applied to the input\n% image/heightmap in order to obtain a RGB image to which\n% the shading pattern is applied.\n% figNo - Optional figure window number to use.\n%\n% This function provides an interactive relief shading image\n%\n% Click in the image to toggle in/out of interactive relief shading mode. The\n% location of the click defines a reference point which is indicated by a\n% surrounding circle. Positioning the cursor at the centre of the circle\n% corresponds to the sun being placed directly overhead. Moving it radially\n% outwards reduces the sun's elevation and moving it around the circle\n% corresponds to changing the sun's azimuth. The intended use is that you would\n% click on a feature of interest within an image and then move the sun around\n% with respect to that feature to illuminate it from various directions.\n%\n% Lambertian shading is used to form the relief image. This is the cosine of\n% the angle between the surface normal and light direction. Note that shadows\n% are ignored. Thus a small feature that might otherwise be in the shadow of a\n% nearby large structure is rendered as if the large feature was not there.\n%\n% Note that the scale of the surface gradient of the input image is arbitrary,\n% indeed it is likely to be of mixed units. However, the gradient scale has a\n% big effect on the resulting image display. Initially the gradient is scaled\n% to achieve a median value of 0.25. Using the up and down arrow keys the\n% user can successively double or halve the gradient values to obtain a\n% pleasing result.\n%\n% A note on colourmaps: It is strongly suggested that you use a constant\n% lightness colourmap, or low contrast colourmap, to construct the image to\n% which the shading is applied. The reason for this is that the perception of\n% features within the data is provided by the relief shading. If the colourmap\n% itself has a wide range of lightness values within its colours then these will\n% induce an independent shading pattern that will interfere with the relief\n% shading. Thus, the use of a map having colours of uniform lightness ensures\n% that they do not interfere with the perception of features induced by the\n% relief shading.\n%\n% See also: RELIEF, APPLYCOLOURMAP\n\n% Copyright (c) 2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% April 2014 \n\nfunction irelief(im, rgbim, figNo)\n\n [rows, cols, chan] = size(im);\n assert(chan==1)\n \n if exist('rgbim', 'var') \n [rr, cc, ch] = size(rgbim);\n if cc == 3 && ch == 1 % Assume this is a colourmap that is to be\n % applied to the image/heightmap \n rgbim = applycolourmap(im, rgbim);\n \n elseif ~isempty(rgbim) % Check its size\n if rows ~= rr || cols ~= cc || ch ~= 3\n error('Sizes of im and rgbim are not compatible'); \n end\n end\n\n shrgbim = zeros(rows,cols,3); % Allocate space for shaded image\n \n else % No image supplied\n rgbim = []; \n end\n \n % Compute a gradient scaling to give initial median gradient of 0.25 \n gradscale = initialgradscale;\n loggrad = 'linear';\n\n % Max radius value for normalising radius values when determining\n % elevation and azimuth\n maxRadius = min(rows/6,cols/6);\n \n fprintf('\\nClick in the image to toggle in/out of relief rendering mode. \\n\\n');\n fprintf(['The clicked location is the reference point for specifying the' ...\n ' sun direction. \\n']);\n fprintf('Move the cursor with respect to this point to change the illumination.\\n\\n');\n fprintf('Use up and down arrow keys to increase/decrease surface gradients.\\n\\n');\n \n if exist('figNo','var')\n fig = figure(figNo); clf\n else\n fig = figure;\n end\n \n % precompute surface normals \n [n1, n2, n3] = surfacenormals(im, gradscale, loggrad);\n \n % Generate an initial dummy image to display and obtain its handle\n S = warning('off');\n imHandle = imshow(ones(rows,cols), 'border', 'tight');\n ah = get(fig,'CurrentAxes');\n \n if isempty(rgbim) % Use a slightly reduced contrast grey colourmap\n colormap(labmaplib(2)); \n end\n \n % Set initial reference point to the centre of the image and draw a\n % circle around this point.\n xo = cols/2;\n yo = rows/2;\n [xd, yd] = circlexy([xo, yo], maxRadius); \n ho = line(xd, yd, 'Color', [.8 .8 .8]);\n set(ho,'Visible', 'off');\n\n % Set up button down callback and window title \n set(fig, 'WindowButtonDownFcn', @wbdcb);\n set(fig, 'KeyReleaseFcn', @keyreleasecb);\n set(fig, 'NumberTitle', 'off')\n set(fig, 'name', 'CET Interactive Relief Shading Tool') \n set(fig, 'Menubar','none');\n \n % Text area to display current azimuth, elevation, gradscale values\n texth = text(50, 50,'', 'color', [1 1 1], 'FontSize', 20);\n \n % Generate initial image display.\n relief(xo+maxRadius, yo-maxRadius);\n \n drawnow\n warning(S) \n \n blending = 0;\n \n % Set up custom pointer\n myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];\n myPointer(~myPointer) = NaN;\n\n hold on\n \n%----------------------------------------------------------------------- \n% Window button down callback\nfunction wbdcb(src,evnt)\n \n if strcmp(get(src,'SelectionType'),'normal')\n if ~blending % Turn blending on\n blending = 1;\n set(ho,'Visible', 'on');\n set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...\n 'PointerShapeHotSpot',[9 9])\n set(src,'WindowButtonMotionFcn',@wbmcb)\n\n % Reset reference point to the click location\n cp = get(ah,'CurrentPoint');\n xo = cp(1,1);\n yo = cp(1,2);\n \n [xd, yd] = circlexy([xo, yo], maxRadius); \n set(ho,'XData', xd);\n set(ho,'YData', yd);\n \n else % Turn blending off\n blending = 0;\n set(ho,'Visible', 'off');\n set(src,'Pointer','arrow')\n set(src,'WindowButtonMotionFcn','')\n \n % For paper illustration (need marker size of 95 if using export_fig)\n cp = get(ah,'CurrentPoint');\n x = cp(1,1);\n y = cp(1,2);\n end\n \n % Right-clicks while blending also reset the origin for determining elevation and azimuth\n elseif blending && strcmp(get(src,'SelectionType'),'alt') \n\n cp = get(ah,'CurrentPoint');\n xo = cp(1,1);\n yo = cp(1,2);\n \n [xd, yd] = circlexy([xo, yo], maxRadius); \n set(ho,'XData', xd);\n set(ho,'YData', yd);\n \n wbmcb(src,evnt); % update the display\n end\n \nend \n\n%----------------------------------------------------------------------- \n% Window button move call back\nfunction wbmcb(src,evnt)\n cp = get(ah,'CurrentPoint');\n x = cp(1,1); y = cp(1,2);\n relief(x, y);\nend\n\n%-----------------------------------------------------------------------\n% Key Release callback\n% If '+' or up is pressed the gradients in the image are doubled\n% '-' or down halves the gradients\n\nfunction keyreleasecb(src,evnt)\n \n if evnt.Character == '+' | evnt.Character == 30\n gradscale = gradscale*2;\n [n1, n2, n3] = surfacenormals(im, gradscale, loggrad);\n \n elseif evnt.Character == '-' | evnt.Character == 31\n gradscale = gradscale/2; \n [n1, n2, n3] = surfacenormals(im, gradscale, loggrad);\n \n elseif evnt.Character == 'l'\n if strcmp(loggrad, 'linear')\n loggrad = 'log';\n fprintf('Using log of gradients\\n');\n \n elseif strcmp(loggrad, 'log') \n loggrad = 'loglog'; \n fprintf('Using log of log of gradients\\n'); \n \n elseif strcmp(loggrad, 'loglog') \n loggrad = 'logloglog'; \n fprintf('Using log log log gradients\\n'); \n \n elseif strcmp(loggrad, 'logloglog') \n loggrad = 'linear'; \n fprintf('Using raw data gradients\\n'); \n \n end\n [n1, n2, n3] = surfacenormals(im, gradscale, loggrad);\n \n end\n \n wbmcb(src,evnt); % update the display\nend \n\n%-----------------------------------------------------------------------\nfunction relief(x, y)\n \n % Clamp x and y to image limits\n x = max(0,x); x = min(cols,x); \n y = max(0,y); y = min(rows,y); \n \n % Convert to polar coordinates with respect to reference point\n xp = x - xo;\n yp = y - yo;\n \n radius = sqrt(xp.^2 + yp.^2);\n \n % Compute azimuth. We want 0 azimuth pointing up increasing\n % clockwise. Hence yp must be negaated becasuse +ve y points down in the\n % image, pi/2 must be subtracted to shift 0 from east to north, and the\n % overall result must be negated to make angles +ve clockwise (yuk).\n azimuth = -(atan2(-yp, xp) - pi/2); \n \n % Convert radius to normalised coords with respect to image size a\n radius = radius/maxRadius;\n radius = min(radius,1);\n \n % Convert azimuth and elevation to a light direction. Note that\n % the vector is constructed so that an azimuth of 0 points upwards and\n % increases clockwise.\n elevation = pi/2 - radius*2*pi/8;\n I = [cos(elevation)*sin(azimuth), cos(elevation)*cos(azimuth), sin(elevation)]; \n I = I./norm(I); % Ensure I is a unit vector \n \n % Display light direction and current gradscale value\n set(texth, 'String', sprintf('Az: %d El: %d Gs: %.2f', ...\n round(azimuth/pi*180), round(elevation/pi*180), gradscale));\n \n % Generate Lambertian shading - dot product between surface normal and light\n % direction. Note that the product with n2 is negated to account for the\n % image +ve y increasing downwards.\n shading = I(1)*n1 - I(2)*n2 + I(3)*n3; \n\n % Remove -ve shading values (surfaces pointing away from light source)\n shading(shading < 0) = 0;\n \n % If an image has been supplied apply shading to it\n if ~isempty(rgbim)\n for n = 1:3\n shrgbim(:,:,n) = rgbim(:,:,n).*shading;\n end\n set(imHandle,'CData', shrgbim);\n \n else % Just display shading image\n set(imHandle,'CData', shading);\n end\n \nend \n\n%---------------------------------------------------------------------------\n% Compute image/heightmap surface normals\n\nfunction [n1, n2, n3] = surfacenormals(im, gradscale, loggrad)\n \n % Compute partial derivatives of z.\n % p = dz/dx, q = dz/dy\n\n [p,q] = gradient(im); \n p = p*gradscale;\n q = q*gradscale;\n \n % If specified take logs of gradient \n if strcmpi(loggrad, 'log')\n p = sign(p).*log1p(abs(p));\n q = sign(q).*log1p(abs(q));\n elseif strcmpi(loggrad, 'loglog')\n p = sign(p).*log1p(log1p(abs(p)));\n q = sign(q).*log1p(log1p(abs(q)));\n elseif strcmpi(loggrad, 'logloglog')\n p = sign(p).*log1p(log1p(log1p(abs(p))));\n q = sign(q).*log1p(log1p(log1p(abs(q))));\n end\n \n % Generate surface unit normal vectors. Components stored in n1, n2\n % and n3 \n mag = sqrt(1 + p.^2 + q.^2);\n n1 = -p./mag;\n n2 = -q./mag;\n n3 = 1./mag;\nend\n\n%---------------------------------------------------------------------------\n% Generate coordinates of points around a circle with centre c, radius r\n\nfunction [xd, yd] = circlexy(c, r)\n nsides = 32;\n a = [0:2*pi/nsides:2*pi];\n xd = r*cos(a) + c(1);\n yd = r*sin(a) + c(2);\nend\n\n%---------------------------------------------------------------------------\n% Estimate initial gradient scale for a reasonable initial shading result\n% Aim for a median gradient of around 0.25\n\nfunction gradscale = initialgradscale\n mediantarget = 0.25;\n [p,q] = gradient(im); \n pt = abs([p(:); q(:)]);\n pt(isnan(pt) | pt = 1, 'Padding size must be > 1')\n\n b = round(b); % ensure integer\n [rows, cols, channels] = size(im);\n if rows <= 2*b || cols <= 2*b\n error('Amount to be trimmed is greater than image size');\n end\n tim = im(1+b:end-b, 1+b:end-b, 1:channels);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "regionadjacency.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/regionadjacency.m", "size": 4510, "source_encoding": "utf_8", "md5": "c2fb48dec79835eac0afc0d068601942", "text": "% REGIONADJACENCY Computes adjacency matrix for image of labeled segmented regions\n%\n% Usage: [Am, Al] = regionadjacency(L, connectivity)\n%\n% Arguments: L - A region segmented image, such as might be produced by a\n% graph cut or superpixel algorithm. All pixels in each\n% region are labeled by an integer.\n% connectivity - 8 or 4. If not specified connectivity defaults to 8.\n%\n% Returns: Am - An adjacency matrix indicating which labeled regions are\n% adjacent to each other, that is, they share boundaries. Am\n% is sparse to save memory.\n% Al - A cell array representing the adjacency list corresponding\n% to Am. Al{n} is an array of the region indices adjacent to\n% region n.\n%\n% Regions with a label of 0 are not processed. They are considered to be\n% 'background regions' that are not to be considered. If you want to include\n% these regions you should assign a new positive label to these areas using, say\n% >> L(L==0) = max(L(:)) + 1;\n%\n% See also: CLEANUPREGIONS, RENUMBERREGIONS, SLIC\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% February 2013 Original version\n% July 2013 Speed improvement in sparse matrix formation (4x)\n\nfunction [Am, varargout] = regionadjacency(L, connectivity)\n\n if ~exist('connectivity', 'var'), connectivity = 8; end\n [rows,cols] = size(L);\n \n % Identify the unique labels in the image, excluding 0 as a label.\n labels = setdiff(unique(L(:))',0);\n\n if isempty(labels)\n warning('There are no objects in the image')\n Am = [];\n Al = {};\n return\n end\n\n N = max(labels); % Required size of adjacency matrix\n \n % Strategy: Step through the labeled image. For 8-connectedness inspect \n % pixels as follows and set the appropriate entries in the adjacency\n % matrix. \n % x - o\n % / | \\\n % o o o\n %\n % For 4-connectedness we only inspect the following pixels\n % x - o\n % | \n % o \n %\n % Becuase the adjacency search looks 'forwards' a final OR operation is\n % performed on the adjacency matrix and its transpose to ensure\n % connectivity both ways.\n\n % Allocate vectors for forming row, col, value triplets used to construct\n % sparse matrix. Forming these vectors first is faster than filling\n % entries directly into the sparse matrix\n i = zeros(rows*cols,1); % row value\n j = zeros(rows*cols,1); % col value\n s = zeros(rows*cols,1); % value\n \n if connectivity == 8\n n = 1;\n for r = 1:rows-1\n\n % Handle pixels in 1st column\n i(n) = L(r,1); j(n) = L(r ,2); s(n) = 1; n=n+1;\n i(n) = L(r,1); j(n) = L(r+1,1); s(n) = 1; n=n+1;\n i(n) = L(r,1); j(n) = L(r+1,2); s(n) = 1; n=n+1;\n \n % ... now the rest of the column\n for c = 2:cols-1\n i(n) = L(r,c); j(n) = L(r ,c+1); s(n) = 1; n=n+1;\n i(n) = L(r,c); j(n) = L(r+1,c-1); s(n) = 1; n=n+1;\n i(n) = L(r,c); j(n) = L(r+1,c ); s(n) = 1; n=n+1;\n i(n) = L(r,c); j(n) = L(r+1,c+1); s(n) = 1; n=n+1;\n end\n end\n \n elseif connectivity == 4\n n = 1;\n for r = 1:rows-1\n for c = 1:cols-1\n i(n) = L(r,c); j(n) = L(r ,c+1); s(n) = 1; n=n+1;\n i(n) = L(r,c); j(n) = L(r+1,c ); s(n) = 1; n=n+1;\n end\n end\n \n else\n error('Connectivity must be 4 or 8');\n end\n \n % Form the logical sparse adjacency matrix\n Am = logical(sparse(i, j, s, N, N)); \n \n % Zero out the diagonal \n for r = 1:N\n Am(r,r) = 0;\n end\n \n % Ensure connectivity both ways for all regions.\n Am = Am | Am';\n \n % If an adjacency list is requested...\n if nargout == 2\n Al = cell(N,1);\n for r = 1:N\n Al{r} = find(Am(r,:));\n end\n varargout{1} = Al;\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "integgausfilt.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/integgausfilt.m", "size": 2500, "source_encoding": "utf_8", "md5": "a2a14a4604cd4a021514fffb77dd587e", "text": "% INTEGGAUSFILT - Approximate Gaussian filtering using integral filters\n%\n% This function approximates Gaussian filtering by repeatedly applying\n% averaging filters. The averaging is performed via integral images which\n% results in a fixed and very low computational cost that is independent of\n% the Gaussian size.\n%\n% Usage: fim = integgausfilt(im, sigma, nFilt)\n%\n% Arguments:\n% im - Image to be Gaussian smoothed\n% sigma - Desired standard deviation of Gaussian filter\n% nFilt - The number of average filterings to be used to\n% approximate the Gaussian. This should be a minimum of\n% 3, using 4 is better. If the smoothed image is to be\n% differentiated an additional averaging should be applied\n% for each derivative. Eg if a second derivative is to be\n% taken at least 5 averagings should be applied. If omitted\n% this parameter defaults to 5.\n%\n% Note that the desired standard deviation will not be achieved exactly. A\n% combination of different sized averaging filters are applied to approximate it\n% as closely as possible. If nFilt is 5 the deviation from the desired standard\n% deviation will be at most about 0.15 pixels\n%\n% See also: INTEGAVERAGE, SOLVEINTEG, INTEGRALIMAGE\n\n% Copyright (c) 2009 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2009\n\nfunction im = integgausfilt(im, sigma, nFilt)\n \n if ~exist('nFilt', 'var')\n nFilt = 5;\n end\n \n % Solve for the combination of averaging filter sizes that will result in\n % the closest approximation of sigma given nFilt.\n [wl, wu, m] = solveinteg(sigma, nFilt);\n radl = (wl-1)/2;\n radu = (wu-1)/2;\n \n % Apply the averaging filters via integral images.\n for i = 1:m\n im = integaverage(im,radl);\n end\n \n for n = 1:(nFilt-m)\n im = integaverage(im,radu);\n end\n \n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "anisodiff.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/anisodiff.m", "size": 2600, "source_encoding": "utf_8", "md5": "3d6827b7cb6831ab151cc363a892fd5a", "text": "% ANISODIFF - Anisotropic diffusion.\n%\n% Usage:\n% diff = anisodiff(im, niter, kappa, lambda, option)\n%\n% Arguments:\n% im - input image\n% niter - number of iterations.\n% kappa - conduction coefficient 20-100 ?\n% lambda - max value of .25 for stability\n% option - 1 Perona Malik diffusion equation No 1\n% 2 Perona Malik diffusion equation No 2\n%\n% Returns:\n% diff - diffused image.\n%\n% kappa controls conduction as a function of gradient. If kappa is low\n% small intensity gradients are able to block conduction and hence diffusion\n% across step edges. A large value reduces the influence of intensity\n% gradients on conduction.\n%\n% lambda controls speed of diffusion (you usually want it at a maximum of\n% 0.25)\n%\n% Diffusion equation 1 favours high contrast edges over low contrast ones.\n% Diffusion equation 2 favours wide regions over smaller ones.\n\n% Reference: \n% P. Perona and J. Malik. \n% Scale-space and edge detection using ansotropic diffusion.\n% IEEE Transactions on Pattern Analysis and Machine Intelligence, \n% 12(7):629-639, July 1990.\n%\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk @ csse uwa edu au\n% http://www.csse.uwa.edu.au\n%\n% June 2000 original version. \n% March 2002 corrected diffusion eqn No 2.\n\nfunction diff = anisodiff(im, niter, kappa, lambda, option)\n\nif ndims(im)==3\n error('Anisodiff only operates on 2D grey-scale images');\nend\n\nim = double(im);\n[rows,cols] = size(im);\ndiff = im;\n \nfor i = 1:niter\n% fprintf('\\rIteration %d',i);\n\n % Construct diffl which is the same as diff but\n % has an extra padding of zeros around it.\n diffl = zeros(rows+2, cols+2);\n diffl(2:rows+1, 2:cols+1) = diff;\n\n % North, South, East and West differences\n deltaN = diffl(1:rows,2:cols+1) - diff;\n deltaS = diffl(3:rows+2,2:cols+1) - diff;\n deltaE = diffl(2:rows+1,3:cols+2) - diff;\n deltaW = diffl(2:rows+1,1:cols) - diff;\n\n % Conduction\n\n if option == 1\n cN = exp(-(deltaN/kappa).^2);\n cS = exp(-(deltaS/kappa).^2);\n cE = exp(-(deltaE/kappa).^2);\n cW = exp(-(deltaW/kappa).^2);\n elseif option == 2\n cN = 1./(1 + (deltaN/kappa).^2);\n cS = 1./(1 + (deltaS/kappa).^2);\n cE = 1./(1 + (deltaE/kappa).^2);\n cW = 1./(1 + (deltaW/kappa).^2);\n end\n\n diff = diff + lambda*(cN.*deltaN + cS.*deltaS + cE.*deltaE + cW.*deltaW);\n\n% Uncomment the following to see a progression of images\n% subplot(ceil(sqrt(niter)),ceil(sqrt(niter)), i)\n% imagesc(diff), colormap(gray), axis image\n\nend\n%fprintf('\\n');\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "drawregionboundaries.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/drawregionboundaries.m", "size": 2312, "source_encoding": "utf_8", "md5": "52e55969a30f9db62b4847f5a14997d4", "text": "% DRAWREGIONBOUNDARIES Draw boundaries of labeled regions in an image\n%\n% Usage: maskim = drawregionboundaries(l, im, col)\n%\n% Arguments:\n% l - Labeled image of regions.\n% im - Optional image to overlay the region boundaries on.\n% col - Optional colour specification. Defaults to black. Note that\n% the colour components are specified as values 0-255.\n% For example red is [255 0 0] and white is [255 255 255].\n%\n% Returns: \n% maskim - If no image has been supplied maskim is a binary mask\n% image indicating where the region boundaries are.\n% If an image has been supplied maskim is the image with the\n% region boundaries overlaid \n%\n% See also: MASKIMAGE\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% Feb 2013\n\nfunction maskim = drawregionboundaries(l, im, col)\n \n % Form the mask by applying a sobel edge detector to the labeled image,\n % thresholding and then thinning the result.\n% h = [1 0 -1\n% 2 0 -2\n% 1 0 -1];\n h = [-1 1]; % A simple small filter is better in this application.\n % Small regions 1 pixel wide get missed using a Sobel\n % operator \n gx = filter2(h ,l);\n gy = filter2(h',l);\n maskim = (gx.^2 + gy.^2) > 0;\n maskim = bwmorph(maskim, 'thin', Inf);\n \n % Zero out any mask values that may have been set around the edge of the\n % image.\n maskim(1,:) = 0; maskim(end,:) = 0;\n maskim(:,1) = 0; maskim(:,end) = 0;\n \n % If an image has been supplied apply the mask to the image and return it \n if exist('im', 'var') \n if ~exist('col', 'var'), col = 0; end\n maskim = maskimage(im, maskim, col);\n end"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "canny.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/canny.m", "size": 2293, "source_encoding": "utf_8", "md5": "6bdaaea9bcfecd3c0443e573bdac5381", "text": "% CANNY - Canny edge detection\n%\n% Function to perform Canny edge detection. \n%\n% Usage: [gradient or] = canny(im, sigma)\n%\n% Arguments: im - image to be procesed\n% sigma - standard deviation of Gaussian smoothing filter.\n% Optional, defaults to 1.\n%\n% Returns: gradient - edge strength image (gradient amplitude)\n% or - orientation image (in degrees 0-180, positive\n% anti-clockwise)\n%\n%\n% To obtain a binary edge image one would typically do the following\n% >> [gr or] = canny(im, sigma); % Choose sigma to taste\n% >> nm = nonmaxsup(gr, or, rad); % I use a rad value ~ 1.2 to 1.5\n% >> bw = hysthresh(nm, T1, T2); % Choose T1 and T2 until the result looks ok \n%\n% See also: NONMAXSUP, HYSTHRESH, DERIVATIVE5\n\n% Copyright (c) 1999-2010 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% April 1999 Original version\n% January 2003 Error in calculation of d2 corrected\n% August 2010 Changed to use derivatives computed using Farid and\n% Simoncelli's filters. Cleaned up\n% May 2013 Sigma optional with default of 1\n\nfunction [gradient, or] = canny(im, sigma)\n\n assert(ndims(im) == 2, 'Image must be greyscale');\n if ~exist('sigma', 'var'), sigma = 1; end\n \n % If needed convert im to double\n if ~strcmp(class(im),'double')\n im = double(im); \n end\n\n im = gaussfilt(im, sigma); % Smooth the image.\n [Ix, Iy] = derivative5(im,'x','y'); % Get derivatives.\n gradient = sqrt(Ix.*Ix + Iy.*Iy); % Gradient magnitude.\n or = atan2(-Iy, Ix); % Angles -pi to + pi.\n or(or<0) = or(or<0)+pi; % Map angles to 0-pi.\n or = or*180/pi; % Convert to degrees.\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "integralimage.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/integralimage.m", "size": 1583, "source_encoding": "utf_8", "md5": "625ff486923979d644b6b48a01c2af43", "text": "% INTEGRALIMAGE - computes integral image of an image\n%\n% Usage: intim = integralimage(im)\n%\n% This function computes an integral image such that the value of intim(r,c)\n% equals sum(sum(im(1:r, 1:c))\n%\n% An integral image can be used with the function INTEGRALFILTER to perform\n% filtering operations (using rectangular filters) on an image in time that \n% only depends on the image size, irrespective of the filter size.\n%\n% See also: INTEGRALFILTER, INTEGAVERAGE, INTFILTTRANSPOSE\n\n% Reference: Crow, Franklin (1984). \"Summed-area tables for texture\n% mapping\". SIGGRAPH '84. pp. 207-212. \n% Paul Viola and Michael Jones, \"Robust Real-Time Face Detection\",\n% IJCV 57(2). pp 137-154. 2004.\n\n% Copyright (c) 2006 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 2006\n\nfunction intim = integralimage(im)\n \n if ndims(im) == 3\n error('Image must be greyscale');\n end\n \n if strcmp(class(im),'uint8') % A cast to double is needed\n im = double(im);\n end\n \n intim = cumsum(cumsum(im,1),2);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "slic.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/slic.m", "size": 14802, "source_encoding": "utf_8", "md5": "6b0c38eeaddd4c3c4c9de2c660dffb6d", "text": "% SLIC Simple Linear Iterative Clustering SuperPixels\n%\n% Implementation of Achanta, Shaji, Smith, Lucchi, Fua and Susstrunk's\n% SLIC Superpixels\n%\n% Usage: [l, Am, Sp, d] = slic(im, k, m, seRadius, colopt, mw)\n%\n% Arguments: im - Image to be segmented.\n% k - Number of desired superpixels. Note that this is nominal\n% the actual number of superpixels generated will generally\n% be a bit larger, espiecially if parameter m is small.\n% m - Weighting factor between colour and spatial\n% differences. Values from about 5 to 40 are useful. Use a\n% large value to enforce superpixels with more regular and\n% smoother shapes. Try a value of 10 to start with.\n% seRadius - Regions morphologically smaller than this are merged with\n% adjacent regions. Try a value of 1 or 1.5. Use 0 to\n% disable.\n% colopt - String 'mean' or 'median' indicating how the cluster\n% colour centre should be computed. Defaults to 'mean'\n% mw - Optional median filtering window size. Image compression\n% can result in noticeable artifacts in the a*b* components\n% of the image. Median filtering can reduce this. mw can be\n% a single value in which case the same median filtering is\n% applied to each L* a* and b* components. Alternatively it\n% can be a 2-vector where mw(1) specifies the median\n% filtering window to be applied to L* and mw(2) is the\n% median filtering window to be applied to a* and b*.\n%\n% Returns: l - Labeled image of superpixels. Labels range from 1 to k.\n% Am - Adjacency matrix of segments. Am(i, j) indicates whether\n% segments labeled i and j are connected/adjacent\n% Sp - Superpixel attribute structure array with fields:\n% L - Mean L* value\n% a - Mean a* value\n% b - Mean b* value\n% r - Mean row value\n% c - Mean column value\n% stdL - Standard deviation of L* \n% stda - Standard deviation of a* \n% stdb - Standard deviation of b* \n% N - Number of pixels\n% edges - List of edge numbers that bound each\n% superpixel. This field is allocated, but not set,\n% by SLIC. Use SPEDGES for this.\n% d - Distance image giving the distance each pixel is from its\n% associated superpixel centre.\n%\n% It is suggested that use of this function is followed by SPDBSCAN to perform a\n% DBSCAN clustering of superpixels. This results in a simple and fast\n% segmentation of an image.\n%\n% Minor variations from the original algorithm as defined in Achanta et al's\n% paper:\n%\n% - SuperPixel centres are initialised on a hexagonal grid rather than a square\n% one. This results in a segmentation that will be nominally 6-connected\n% which hopefully facilitates any subsequent post-processing that seeks to\n% merge superpixels.\n% - Initial cluster positions are not shifted to point of lowest gradient\n% within a 3x3 neighbourhood because this will be rendered irrelevant the\n% first time cluster centres are updated.\n%\n% Reference: R. Achanta, A. Shaji, K. Smith, A. Lucchi, P. Fua and\n% S. Susstrunk. \"SLIC Superpixels Compared to State-of-the-Art Superpixel\n% Methods\" PAMI. Vol 34 No 11. November 2012. pp 2274-2281.\n%\n% See also: SPDBSCAN, MCLEANUPREGIONS, REGIONADJACENCY, DRAWREGIONBOUNDARIES, RGB2LAB\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% Feb 2013\n% July 2013 Super pixel attributes returned as a structure array\n\n% Note that most of the computation time is not in the clustering, but rather\n% in the region cleanup process.\n\n\nfunction [l, Am, Sp, d] = slic(im, k, m, seRadius, colopt, mw, nItr, eim, We)\n \n if ~exist('colopt','var') || isempty(colopt), colopt = 'mean'; end\n if ~exist('mw','var') || isempty(mw), mw = 0; end\n if ~exist('nItr','var') || isempty(nItr), nItr = 10; end\n \n if exist('eim', 'var'), USEDIST = 0; else, USEDIST = 1; end\n \n MEANCENTRE = 1;\n MEDIANCENTRE = 2;\n \n if strcmp(colopt, 'mean')\n centre = MEANCENTRE;\n elseif strcmp(colopt, 'median')\n centre = MEDIANCENTRE; \n else\n error('Invalid colour centre computation option');\n end\n \n [rows, cols, chan] = size(im);\n if chan ~= 3\n error('Image must be colour');\n end\n \n % Convert image to L*a*b* colourspace. This gives us a colourspace that is\n % nominally perceptually uniform. This allows us to use the euclidean\n % distance between colour coordinates to measure differences between\n % colours. Note the image becomes double after conversion. We may want to\n % go to signed shorts to save memory.\n im = rgb2lab(im); \n\n % Apply median filtering to colour components if mw has been supplied\n % and/or non-zero\n if mw\n if length(mw) == 1\n mw(2) = mw(1); % Use same filtering for L and chrominance\n end\n for n = 1:3\n im(:,:,n) = medfilt2(im(:,:,n), [mw(1) mw(1)]);\n end\n end\n \n % Nominal spacing between grid elements assuming hexagonal grid\n S = sqrt(rows*cols / (k * sqrt(3)/2));\n \n % Get nodes per row allowing a half column margin at one end that alternates\n % from row to row\n nodeCols = round(cols/S - 0.5);\n % Given an integer number of nodes per row recompute S\n S = cols/(nodeCols + 0.5); \n\n % Get number of rows of nodes allowing 0.5 row margin top and bottom\n nodeRows = round(rows/(sqrt(3)/2*S));\n vSpacing = rows/nodeRows;\n\n % Recompute k\n k = nodeRows * nodeCols;\n \n % Allocate memory and initialise clusters, labels and distances.\n C = zeros(6,k); % Cluster centre data 1:3 is mean Lab value,\n % 4:5 is row, col of centre, 6 is No of pixels\n l = -ones(rows, cols); % Pixel labels.\n d = inf(rows, cols); % Pixel distances from cluster centres.\n \n % Initialise clusters on a hexagonal grid\n kk = 1;\n r = vSpacing/2;\n \n for ri = 1:nodeRows\n % Following code alternates the starting column for each row of grid\n % points to obtain a hexagonal pattern. Note S and vSpacing are kept\n % as doubles to prevent errors accumulating across the grid.\n if mod(ri,2), c = S/2; else, c = S; end\n \n for ci = 1:nodeCols\n cc = round(c); rr = round(r);\n C(1:5, kk) = [squeeze(im(rr,cc,:)); cc; rr];\n c = c+S;\n kk = kk+1;\n end\n \n r = r+vSpacing;\n end\n \n % Now perform the clustering. 10 iterations is suggested but I suspect n\n % could be as small as 2 or even 1\n S = round(S); % We need S to be an integer from now on\n \n for n = 1:nItr\n for kk = 1:k % for each cluster\n\n % Get subimage around cluster\n rmin = max(C(5,kk)-S, 1); rmax = min(C(5,kk)+S, rows); \n cmin = max(C(4,kk)-S, 1); cmax = min(C(4,kk)+S, cols); \n subim = im(rmin:rmax, cmin:cmax, :); \n assert(numel(subim) > 0)\n \n % Compute distances D between C(:,kk) and subimage\n if USEDIST\n D = dist(C(:, kk), subim, rmin, cmin, S, m);\n else\n D = dist2(C(:, kk), subim, rmin, cmin, S, m, eim, We);\n end\n\n % If any pixel distance from the cluster centre is less than its\n % previous value update its distance and label\n subd = d(rmin:rmax, cmin:cmax);\n subl = l(rmin:rmax, cmin:cmax);\n updateMask = D < subd;\n subd(updateMask) = D(updateMask);\n subl(updateMask) = kk;\n \n d(rmin:rmax, cmin:cmax) = subd;\n l(rmin:rmax, cmin:cmax) = subl; \n end\n \n % Update cluster centres with mean values\n C(:) = 0;\n for r = 1:rows\n for c = 1:cols\n tmp = [im(r,c,1); im(r,c,2); im(r,c,3); c; r; 1];\n C(:, l(r,c)) = C(:, l(r,c)) + tmp;\n end\n end\n \n % Divide by number of pixels in each superpixel to get mean values\n for kk = 1:k \n C(1:5,kk) = round(C(1:5,kk)/C(6,kk)); \n end\n \n % Note the residual error, E, is not calculated because we are using a\n % fixed number of iterations \n end\n \n % Cleanup small orphaned regions and 'spurs' on each region using\n % morphological opening on each labeled region. The cleaned up regions are\n % assigned to the nearest cluster. The regions are renumbered and the\n % adjacency matrix regenerated. This is needed because the cleanup is\n % likely to change the number of labeled regions.\n [l, Am] = mcleanupregions(l, seRadius);\n\n % Recompute the final superpixel attributes and write information into\n % the Sp struct array.\n N = length(Am);\n Sp = struct('L', cell(1,N), 'a', cell(1,N), 'b', cell(1,N), ...\n 'stdL', cell(1,N), 'stda', cell(1,N), 'stdb', cell(1,N), ...\n 'r', cell(1,N), 'c', cell(1,N), 'N', cell(1,N));\n [X,Y] = meshgrid(1:cols, 1:rows);\n L = im(:,:,1); \n A = im(:,:,2); \n B = im(:,:,3); \n for n = 1:N\n mask = l==n;\n nm = sum(mask(:));\n if centre == MEANCENTRE \n Sp(n).L = sum(L(mask))/nm;\n Sp(n).a = sum(A(mask))/nm;\n Sp(n).b = sum(B(mask))/nm;\n \n elseif centre == MEDIANCENTRE\n Sp(n).L = median(L(mask));\n Sp(n).a = median(A(mask));\n Sp(n).b = median(B(mask));\n end\n \n Sp(n).r = sum(Y(mask))/nm;\n Sp(n).c = sum(X(mask))/nm;\n \n % Compute standard deviations of the colour components of each super\n % pixel. This can be used by code seeking to merge superpixels into\n % image segments. Note these are calculated relative to the mean colour\n % component irrespective of the centre being calculated from the mean or\n % median colour component values.\n Sp(n).stdL = std(L(mask));\n Sp(n).stda = std(A(mask));\n Sp(n).stdb = std(B(mask));\n\n Sp(n).N = nm; % Record number of pixels in superpixel too.\n end\n \n%-- dist -------------------------------------------\n%\n% Usage: D = dist(C, im, r1, c1, S, m)\n% \n% Arguments: C - Cluster being considered\n% im - sub-image surrounding cluster centre\n% r1, c1 - row and column of top left corner of sub image within the\n% overall image.\n% S - grid spacing\n% m - weighting factor between colour and spatial differences.\n%\n% Returns: D - Distance image giving distance of every pixel in the\n% subimage from the cluster centre\n%\n% Distance = sqrt( dc^2 + (ds/S)^2*m^2 )\n% where:\n% dc = sqrt(dl^2 + da^2 + db^2) % Colour distance\n% ds = sqrt(dx^2 + dy^2) % Spatial distance\n%\n% m is a weighting factor representing the nominal maximum colour distance\n% expected so that one can rank colour similarity relative to distance\n% similarity. try m in the range [1-40] for L*a*b* space\n%\n% ?? Might be worth trying the Geometric Mean instead ??\n% Distance = sqrt(dc * ds)\n% but having a factor 'm' to play with is probably handy\n\n% This code could be more efficient\n\nfunction D = dist(C, im, r1, c1, S, m)\n\n % Squared spatial distance\n % ds is a fixed 'image' we should be able to exploit this\n % and use a fixed meshgrid for much of the time somehow...\n [rows, cols, chan] = size(im);\n [x,y] = meshgrid(c1:(c1+cols-1), r1:(r1+rows-1));\n x = x-C(4); % x and y dist from cluster centre\n y = y-C(5);\n ds2 = x.^2 + y.^2;\n \n % Squared colour difference\n for n = 1:3\n im(:,:,n) = (im(:,:,n)-C(n)).^2;\n end\n dc2 = sum(im,3);\n \n D = sqrt(dc2 + ds2/S^2*m^2);\n \n \n \n%--- dist2 ------------------------------------------\n%\n% Usage: D = dist2(C, im, r1, c1, S, m, eim)\n% \n% Arguments: C - Cluster being considered\n% im - sub-image surrounding cluster centre\n% r1, c1 - row and column of top left corner of sub image within the\n% overall image.\n% S - grid spacing\n% m - weighting factor between colour and spatial differences.\n% eim - Edge strength sub-image corresponding to im\n%\n% Returns: D - Distance image giving distance of every pixel in the\n% subimage from the cluster centre\n%\n% Distance = sqrt( dc^2 + (ds/S)^2*m^2 )\n% where:\n% dc = sqrt(dl^2 + da^2 + db^2) % Colour distance\n% ds = sqrt(dx^2 + dy^2) % Spatial distance\n%\n% m is a weighting factor representing the nominal maximum colour distance\n% expected so that one can rank colour similarity relative to distance\n% similarity. try m in the range [1-40] for L*a*b* space\n%\n\nfunction D = dist2(C, im, r1, c1, S, m, eim, We)\n\n % Squared spatial distance\n % ds is a fixed 'image' we should be able to exploit this\n % and use a fixed meshgrid for much of the time somehow...\n [rows, cols, chan] = size(im);\n [x,y] = meshgrid(c1:(c1+cols-1), r1:(r1+rows-1));\n x = x-C(4);\n y = y-C(5);\n ds2 = x.^2 + y.^2;\n \n % Squared colour difference\n for n = 1:3\n im(:,:,n) = (im(:,:,n)-C(n)).^2;\n end\n dc2 = sum(im,3);\n \n % Combine colour and spatial distance measure\n D = sqrt(dc2 + ds2/S^2*m^2);\n \n % for every pixel in the subimage call improfile to the cluster centre\n % and use the largest value as the 'edge distance'\n rCentre = C(5)-r1; % Cluster centre coords relative to this sub-image\n cCentre = C(4)-c1;\n de = zeros(rows,cols);\n for r = 1:rows\n for c = 1:cols\n v = improfile(eim,[c cCentre], [r rCentre]);\n de(r,c) = max(v);\n end\n end\n\n % Combine edge distance with weight, We with total Distance.\n D = D + We * de;\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "nonmaxsuppts.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/nonmaxsuppts.m", "size": 5260, "source_encoding": "utf_8", "md5": "6399ae2ee34081b954004dc47eec6578", "text": "% NONMAXSUPPTS - Non-maximal suppression for features/corners\n%\n% Non maxima suppression and thresholding for points generated by a feature\n% or corner detector.\n%\n% Usage: [r,c] = nonmaxsuppts(cim, radius, thresh, im)\n% /\n% optional\n%\n% [r,c, rsubp, csubp] = nonmaxsuppts(cim, radius, thresh, im)\n% \n% Arguments:\n% cim - corner strength image.\n% radius - radius of region considered in non-maximal\n% suppression. Typical values to use might\n% be 1-3 pixels.\n% thresh - threshold.\n% im - optional image data. If this is supplied the\n% thresholded corners are overlayed on this\n% image. This can be useful for parameter tuning.\n% Returns:\n% r - row coordinates of corner points (integer valued).\n% c - column coordinates of corner points.\n% rsubp - If four return values are requested sub-pixel\n% csubp - localization of feature points is attempted and\n% returned as an additional set of floating point\n% coords. Note that you may still want to use the integer\n% valued coords to specify centres of correlation windows\n% for feature matching.\n%\n% Note: An issue with integer valued images is that if there are multiple pixels\n% all with the same value within distance 2*radius of each other then they will\n% all be marked as local maxima. \n\n% Copyright (c) 2003-2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2003 Original version\n% August 2005 Subpixel localization and Octave compatibility\n% January 2010 Fix for completely horizontal and vertical lines (by Thomas Stehle,\n% RWTH Aachen University) \n% January 2011 Warning given if no maxima found\n\nfunction [r,c, rsubp, csubp] = nonmaxsuppts(cim, radius, thresh, im)\n\n subPixel = nargout == 4; % We want sub-pixel locations \n [rows,cols] = size(cim);\n \n % Extract local maxima by performing a grey scale morphological\n % dilation and then finding points in the corner strength image that\n % match the dilated image and are also greater than the threshold.\n sze = 2*radius+1; % Size of dilation mask.\n mx = ordfilt2(cim, sze^2,ones(sze)); % Grey-scale dilate.\n\n % Make mask to exclude points within radius of the image boundary. \n bordermask = zeros(size(cim));\n bordermask(radius+1:end-radius, radius+1:end-radius) = 1;\n \n % Find maxima, threshold, and apply bordermask\n cimmx = (cim==mx) & (cim>thresh) & bordermask;\n \n [r,c] = find(cimmx); % Find row,col coords.\n\n \n if subPixel % Compute local maxima to sub pixel accuracy \n if ~isempty(r) % ...if we have some ponts to work with\n \n ind = sub2ind(size(cim),r,c); % 1D indices of feature points\n w = 1; % Width that we look out on each side of the feature\n % point to fit a local parabola\n \n % Indices of points above, below, left and right of feature point\n indrminus1 = max(ind-w,1);\n indrplus1 = min(ind+w,rows*cols);\n indcminus1 = max(ind-w*rows,1);\n indcplus1 = min(ind+w*rows,rows*cols);\n \n % Solve for quadratic down rows\n rowshift = zeros(size(ind));\n cy = cim(ind);\n ay = (cim(indrminus1) + cim(indrplus1))/2 - cy;\n by = ay + cy - cim(indrminus1);\n rowshift(ay ~= 0) = -w*by(ay ~= 0)./(2*ay(ay ~= 0)); % Maxima of quadradic\n rowshift(ay == 0) = 0;\n \n % Solve for quadratic across columns \n colshift = zeros(size(ind));\n cx = cim(ind);\n ax = (cim(indcminus1) + cim(indcplus1))/2 - cx;\n bx = ax + cx - cim(indcminus1); \n colshift(ax ~= 0) = -w*bx(ax ~= 0)./(2*ax(ax ~= 0)); % Maxima of quadradic\n colshift(ax == 0) = 0;\n \n rsubp = r+rowshift; % Add subpixel corrections to original row\n csubp = c+colshift; % and column coords.\n else\n rsubp = []; csubp = [];\n end\n end\n \n if nargin==4 && ~isempty(r) % Overlay corners on supplied image.\n figure(1), imshow(im,[]), hold on\n if subPixel\n plot(csubp,rsubp,'r+'), title('corners detected');\n else \n plot(c,r,'r+'), title('corners detected');\n end\n hold off\n end\n \n if isempty(r) \n warning('No maxima above threshold found\\n');\n end\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "hysthresh.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/hysthresh.m", "size": 2218, "source_encoding": "utf_8", "md5": "1083374237be0a6bad69e6afd431e1c0", "text": "% HYSTHRESH - Hysteresis thresholding\n%\n% Usage: bw = hysthresh(im, T1, T2)\n%\n% Arguments:\n% im - image to be thresholded (assumed to be non-negative)\n% T1 - upper threshold value\n% T2 - lower threshold value\n% (T1 and T2 can be entered in any order, the larger of the\n% two values is used as the upper threshold)\n% Returns:\n% bw - the thresholded image (containing values 0 or 1)\n%\n% Function performs hysteresis thresholding of an image.\n% All pixels with values above threshold T1 are marked as edges\n% All pixels that are connected to points that have been marked as edges\n% and with values above threshold T2 are also marked as edges. Eight\n% connectivity is used.\n\n% Copyright (c) 1996-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% December 1996 - Original version\n% March 2001 - Speed improvements made (~4x)\n% April 2005 - Modified to cope with MATLAB 7's uint8 behaviour\n% July 2005 - Enormous simplification and great speedup by realizing\n% that you can use bwselect to do all the work\n\nfunction bw = hysthresh(im, T1, T2)\n\n if T1 < T2 % T1 and T2 reversed - swap values \n\ttmp = T1;\n\tT1 = T2; \n\tT2 = tmp;\n end\n \n aboveT2 = im > T2; % Edge points above lower\n % threshold. \n [aboveT1r, aboveT1c] = find(im > T1); % Row and colum coords of points\n % above upper threshold.\n\t\t\t\t\t \n % Obtain all connected regions in aboveT2 that include a point that has a\n % value above T1 \n bw = bwselect(aboveT2, aboveT1c, aboveT1r, 8);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "renumberregions.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/renumberregions.m", "size": 2350, "source_encoding": "utf_8", "md5": "0bf07a365af7d4978066949f3e98d8a5", "text": "% RENUMBERREGIONS\n%\n% Usage: [nL, minLabel, maxLabel] = renumberregions(L)\n%\n% Argument: L - A labeled image segmenting an image into regions, such as\n% might be produced by a graph cut or superpixel algorithm.\n% All pixels in each region are labeled by an integer.\n%\n% Returns: nL - A relabeled version of L so that label numbers form a\n% sequence 1:maxRegions or 0:maxRegions-1 depending on\n% whether L has a region labeled with 0s or not.\n% minLabel - Minimum label in the renumbered image. This will be 0 or 1.\n% maxLabel - Maximum label in the renumbered image.\n%\n% Application: Segmentation algorithms can produce a labeled image with a non\n% contiguous numbering of regions 1 4 6 etc. This function renumbers them into a\n% contiguous sequence. If the input image has a region labeled with 0s this\n% region is treated as a privileged 'background region' and retains its 0\n% labeling. The resulting image will have labels ranging over 0:maxRegions-1.\n% Otherwise the image will be relabeled over the sequence 1:maxRegions\n%\n% See also: CLEANUPREGIONS, REGIONADJACENCY\n\n% Copyright (c) 2010 Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% October 2010\n% February 2013 Return label numbering range\n\nfunction [nL, minLabel, maxLabel] = renumberregions(L)\n\n nL = L;\n labels = unique(L(:))'; % Sorted list of unique labels\n N = length(labels);\n \n % If there is a label of 0 we ensure that we do not renumber that region\n % by removing it from the list of labels to be renumbered.\n if labels(1) == 0\n labels = labels(2:end);\n minLabel = 0;\n maxLabel = N-1;\n else\n minLabel = 1;\n maxLabel = N;\n end\n \n % Now do the relabelling\n count = 1;\n for n = labels\n nL(L==n) = count;\n count = count+1;\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "harris.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/harris.m", "size": 4704, "source_encoding": "utf_8", "md5": "db810db41e16c4fc210438eeb81ad3be", "text": "% HARRIS - Harris corner detector\n%\n% Usage: cim = harris(im, sigma)\n% [cim, r, c] = harris(im, sigma, thresh, radius, disp)\n% [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp)\n%\n% Arguments: \n% im - image to be processed.\n% sigma - standard deviation of smoothing Gaussian. Typical\n% values to use might be 1-3.\n% thresh - threshold (optional). Try a value ~50\n% radius - radius of region considered in non-maximal\n% suppression (optional). Typical values to use might\n% be 1-3.\n% disp - optional flag (0 or 1) indicating whether you want\n% to display corners overlayed on the original\n% image. This can be useful for parameter tuning. This\n% defaults to 0\n%\n% Returns:\n% cim - binary image marking corners.\n% r - row coordinates of corner points.\n% c - column coordinates of corner points.\n% rsubp - If five return values are requested sub-pixel\n% csubp - localization of feature points is attempted and\n% returned as an additional set of floating point\n% coords. Note that you may still want to use the integer\n% valued coords to specify centres of correlation windows\n% for feature matching.\n%\n% If thresh and radius are omitted from the argument list only 'cim' is returned\n% as a raw corner strength image. You may then want to look at the values\n% within 'cim' to determine the appropriate threshold value to use. Note that\n% the Harris corner strength varies with the intensity gradient raised to the\n% 4th power. Small changes in input image contrast result in huge changes in\n% the appropriate threshold.\n%\n% Note that this code computes Noble's version of the detector which does not\n% require the parameter 'k'. See comments in code if you wish to use Harris'\n% original measure.\n%\n% See also: NONMAXSUPPTS, DERIVATIVE5\n\n% References: \n% C.G. Harris and M.J. Stephens. \"A combined corner and edge detector\", \n% Proceedings Fourth Alvey Vision Conference, Manchester.\n% pp 147-151, 1988.\n%\n% Alison Noble, \"Descriptions of Image Surfaces\", PhD thesis, Department\n% of Engineering Science, Oxford University 1989, p45.\n\n% Copyright (c) 2002-2010 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% March 2002 - Original version\n% December 2002 - Updated comments\n% August 2005 - Changed so that code calls nonmaxsuppts\n% August 2010 - Changed to use Farid and Simoncelli's derivative filters\n\nfunction [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp)\n \n error(nargchk(2,5,nargin));\n if nargin == 4\n\tdisp = 0;\n end\n \n if ~isa(im,'double')\n\tim = double(im);\n end\n\n subpixel = nargout == 5;\n\n % Compute derivatives and elements of the structure tensor.\n [Ix, Iy] = derivative5(im, 'x', 'y');\n Ix2 = gaussfilt(Ix.^2, sigma);\n Iy2 = gaussfilt(Iy.^2, sigma); \n Ixy = gaussfilt(Ix.*Iy, sigma); \n\n % Compute the Harris corner measure. Note that there are two measures\n % that can be calculated. I prefer the first one below as given by\n % Nobel in her thesis (reference above). The second one (commented out)\n % requires setting a parameter, it is commonly suggested that k=0.04 - I\n % find this a bit arbitrary and unsatisfactory. \n\n cim = (Ix2.*Iy2 - Ixy.^2)./(Ix2 + Iy2 + eps); % My preferred measure.\n% k = 0.04;\n% cim = (Ix2.*Iy2 - Ixy.^2) - k*(Ix2 + Iy2).^2; % Original Harris measure.\n\n if nargin > 2 % We should perform nonmaximal suppression and threshold\n\n\tif disp % Call nonmaxsuppts to so that image is displayed\n\t if subpixel\n\t\t[r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh, im);\n\t else\n\t\t[r,c] = nonmaxsuppts(cim, radius, thresh, im);\t\t\n\t end\n\telse % Just do the nonmaximal suppression\n\t if subpixel\n\t\t[r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh);\n\t else\n\t\t[r,c] = nonmaxsuppts(cim, radius, thresh);\t\t\n\t end\n\tend\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "imsetborder.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/imsetborder.m", "size": 807, "source_encoding": "utf_8", "md5": "8dd6e75f6b5240fffbdb56e60521ef9b", "text": "% IMSETBORDER - sets pixels on image border to a value \n%\n% Usage: im = imsetborder(im, b, v)\n%\n% Arguments:\n% im - image\n% b - border size \n% v - value to set image borders to (defaults to 0)\n%\n% See also: IMPAD, IMTRIM\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n\n% June 2010\n\nfunction im = imsetborder(im, b, v)\n \n if ~exist('v','var'), v = 0; end \n\n assert(b >= 1, 'Padding size must be >= 1')\n b = round(b); % ensure integer\n \n [rows,cols,channels] = size(im);\n for chan = 1:channels\n im(1:b,:,chan) = v;\n im(end-b+1:end,:,chan) = v; \n im(:,1:b,chan) = v;\n im(:,end-b+1:end,chan) = v; \n end"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "integralfilter.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/integralfilter.m", "size": 3939, "source_encoding": "utf_8", "md5": "ec95f49a7ef5558aefe8fd9a4309c358", "text": "% INTEGRALFILTER - performs filtering using an integral image\n%\n% This function exploits an integral image to perform filtering operations\n% (using rectangular filters) on an image in time that only depends on the \n% image size irrespective of the filter size.\n%\n% Usage: fim = integralfilter(intim, f)\n%\n% Arguments: intim - An integral image computed using INTEGRALIMAGE.\n% f - An n x 5 array defining the filter (see below).\n%\n% Returns: fim - The filtered image.\n%\n%\n% Defining Filters: f is a n x 5 array in the following form\n% [ r1 c1 r2 c2 v\n% r1 c1 r2 c2 v\n% r1 c1 r2 c2 v\n% ....... ]\n%\n% Where (r1 c1) and (r2 c2) are the row and column coordinates defining the\n% top-left and bottom-right corners of a rectangular region of the filter\n% (inclusive) and v is the value to be associated with that region of the\n% filter. The row and column coordinates of the rectangular region are defined\n% with respect to the reference point of the filter, typically its centre.\n%\n% Examples:\n% f = [-3 -3 3 3 1/49] % Defines a 7x7 averaging filter\n%\n% f = [-3 -3 3 -1 -1\n% -3 1 3 3 1]; % Defines a differnce of boxes filter over a 7x7\n% region where the left 7x3 region has a value\n% of -1, the right 7x3 region has a value of +1,\n% and the vertical line of pixels through the\n% centre have a (default) value of 0.\n%\n% If you want to check your filter design simply apply it to the integral image\n% of an image that is zero everywhere except for one pixel with a value of 1.\n% This will give you the impulse response/point spread function of your filter.\n%\n% Note under MATLAB the execution speed of this filtering code may not be any\n% faster than using imfilter (sadly). So in some sense this code is a bit\n% academic. However it is interesting that this interpreted code can perform\n% filtering at a speed that is comparable to the native code that is exectuted\n% via imfilter. Under Octave there may be useful speed gains.\n%\n% See also: INTEGRALIMAGE, INTEGAVERAGE, INTFILTTRANSPOSE\n\n% Reference: Paul Viola and Michael Jones, \"Robust Real-Time Face Detection\",\n% IJCV 57(2). pp 137-154. 2004.\n\n% Copyright (c) 2007 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 2007\n\n\nfunction fim = integralfilter(intim, f)\n\n [rows, cols] = size(intim);\n fim = zeros(rows, cols);\n \n\n [nfilters, fcols] = size(f);\n if fcols ~= 5\n error('Filters must be specified via an nx5 matrix');\n end\n\n f(:,1:2) = f(:,1:2)-1; % Adjust the values of r1 and c1 to save addition\n % operations inside the loops below\n \n rmin = 1-min(f(:,1)); % Set loop bounds so that we do not try to\n rmax = rows - max(f(:,3)); % access values outside the image. \n cmin = 1-min(f(:,2));\n cmax = cols - max(f(:,4));\n \n for r = rmin:rmax\n for c = cmin:cmax\n for n = 1:nfilters\n \n fim(r,c) = fim(r,c) + f(n,5)*...\n (intim(r+f(n,3),c+f(n,4)) - intim(r+f(n,1),c+f(n,4)) ...\n - intim(r+f(n,3),c+f(n,2)) + intim(r+f(n,1),c+f(n,2)));\n \n end\n end\n end\n \n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "adaptivethresh.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/adaptivethresh.m", "size": 5822, "source_encoding": "utf_8", "md5": "bc7dac46afe55c2c4fb9c0add2d40792", "text": "% ADAPTIVETHRESH - Wellner's adaptive thresholding\n%\n% Thresholds an image using a threshold that is varied across the image relative\n% to the local mean, or median, at that point in the image. Works quite well on\n% text with shadows\n%\n% Usage: bw = adaptivethresh(im, fsize, t, filterType, thresholdMode)\n%\n% bw = adaptivethresh(im) (uses default parameter values)\n%\n% Arguments: im - Image to be thresholded.\n%\n% fsize - Filter size used to determine the local weighted mean\n% or local median. \n% - If the filterType is 'gaussian' fsize specifies the\n% standard deviation of Gaussian smoothing to be\n% applied. \n% - If the filterType is 'median' fsize specifies the\n% size of the window over which the local median is\n% calculated. \n%\n% The value for fsize should be large, around one tenth to\n% one twentieth of the image size. It defaults to one\n% twentieth of the maximum image dimension.\n%\n% t - Depending on the value of 'mode' this is the value\n% expressed as a percentage or fixed amount, relative to\n% the local average, or median grey value, below which\n% the local threshold is set. \n% Try values in the range -20 to +20. \n% Use +ve values to threshold dark objects against a\n% white background. Use -ve values if you are\n% thresholding white objects on a predominatly \n% dark background so that the local threshold is set\n% above the local mean/median. This parameter defaults to 15.\n%\n% filterType - Optional string specifying smoothing to be used\n% - 'gaussian' use Gaussian smoothing to obtain local\n% weighted mean as the local reference value for setting\n% the local threshold. This is the default\n% - 'median' use median filtering to obtain local reference\n% value for setting the local threshold\n%\n% thresholdMode - Optional string specifying the way the threshold is\n% defined. \n% - 'relative' the value of t represents the percentage,\n% relative to the local average grey value, below which\n% the local threshold is set. This is the default.\n% - 'fixed' the value of t represents the fixed grey level\n% relative to the local average grey value, below which\n% the local threshold is set. \n%\n% Note that in the 'relative' threshold mode the amount the\n% threshold differs from the local mean/median will vary in\n% proportion with the local mean/median. A small difference\n% from the local mean in the dark regions of the image will\n% be more significant than the same difference in a bright\n% portion of the image. This will match with human\n% perception. However this does mean that the results will\n% depend on the grey value origin and whether the image\n% is,say, negated.\n%\n% The implementation differs from Pierre Wellner's original adaptive\n% thresholding algorithm in that he calculated the local weighted mean just\n% along the row, or pairs of rows, in the image using a recursive filter. Here\n% we use symmetrical 2D Gaussian smoothing to calculate the local mean. This is\n% slower but more general. This code also offers the option of using median\n% filtering as a robust alternative to the mean (outliers will not influence the\n% result) and offers the option of using a fixed threshold relative to the\n% mean/median. Despite the potential advantage of median filtering being\n% more robust I find the output from using Gaussian filtering more pleasing.\n%\n% Reference: Pierre Wellner, \"Adaptive Thresholding for the DigitalDesk\" Rank\n% Xerox Technical Report EPC-1993-110 1993\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% August 2008 \n\nfunction bw = adaptivethresh(im, fsize, t, filterType, thresholdMode)\n\n % Set up default parameter values as needed\n if nargin < 2\n\tfsize = fix(length(im)/20);\n end\n \n if nargin < 3\n\tt = 15;\n end\n \n if nargin < 4\n\tfilterType = 'gaussian';\n end \n \n if nargin < 5\n\tthresholdMode = 'relative';\n end\n \n % Apply Gaussian or median smoothing\n if strncmpi(filterType, 'gaussian', 3)\n\tg = fspecial('gaussian', 6*fsize, fsize);\n\tfim = filter2(g, im);\n elseif strncmpi(filterType, 'median', 3)\n\tfim = medfilt2(im, [fsize fsize], 'symmetric');\t\n else\n\terror('Filtertype must be ''gaussian'' or ''median'' ');\n end\n \n % Finally apply the threshold\n if strncmpi(thresholdMode,'relative',3)\n\tbw = im > fim*(1-t/100);\n elseif strncmpi(thresholdMode,'fixed',3)\n\tbw = im > fim-t;\n else\n\terror('mode must be ''relative'' or ''fixed'' ');\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "featureorient.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/featureorient.m", "size": 4226, "source_encoding": "utf_8", "md5": "a6493ad9d0ee982914e92bc8b1e31ce3", "text": "% FEATUREORIENT - Estimates the local orientation of features in an edgeimage\n%\n% Usage: orientim = featureorient(im, gradientsigma,...\n% blocksigma, ...\n% orientsmoothsigma, ...\n% radians)\n%\n% Arguments: im - A normalised input image.\n% gradientsigma - Sigma of the derivative of Gaussian\n% used to compute image gradients. This can\n% be 0 as the derivatives are calculaed with\n% a 5-tap filter.\n% blocksigma - Sigma of the Gaussian weighting used to\n% form the local weighted sum of gradient\n% covariance data. A small value around 1,\n% or even less, is usually fine on most\n% feature images.\n% orientsmoothsigma - Sigma of the Gaussian used to smooth\n% the final orientation vector field. \n% Optional: if ommitted it defaults to 0\n% radians - Optional flag 0/1 indicating whether the\n% output should be given in radians. Defaults\n% to 0 (degrees)\n% \n% Returns: orientim - The orientation image in degrees/radians\n% range is (0 - 180) or (0 - pi).\n% Orientation values are +ve anti-clockwise\n% and give the orientation across the feature\n% ridges \n%\n% The intended application of this function is to compute orientations on a\n% feature image prior to nonmaximal suppression in the case where no orientation\n% information is available from the feature detection process. Accordingly \n% the default output is in degrees to suit NONMAXSUP.\n%\n% See also: NONMAXSUP, RIDGEORIENT\n\n% Copyright (c) 1996-2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2013 Adapted from RIDGEORIENT\n\nfunction or = featureorient(im, gradientsigma, blocksigma, orientsmoothsigma, ...\n radians)\n \n if ~exist('orientsmoothsigma', 'var'), orientsmoothsigma = 0; end\n if ~exist('radians', 'var'), radians = 0; end\n [rows,cols] = size(im);\n \n im = gaussfilt(im, gradientsigma); % Smooth the image.\n [Gx, Gy] = derivative5(im,'x','y'); % Get derivatives. \n Gy = -Gy; % Negate Gy to give +ve anticlockwise angles.\n \n % Estimate the local ridge orientation at each point by finding the\n % principal axis of variation in the image gradients.\n Gxx = Gx.^2; % Covariance data for the image gradients\n Gxy = Gx.*Gy;\n Gyy = Gy.^2;\n \n % Now smooth the covariance data to perform a weighted summation of the\n % data.\n Gxx = gaussfilt(Gxx, blocksigma);\n Gxy = 2*gaussfilt(Gxy, blocksigma);\n Gyy = gaussfilt(Gyy, blocksigma);\n \n % Analytic solution of principal direction\n denom = sqrt(Gxy.^2 + (Gxx - Gyy).^2) + eps;\n sin2theta = Gxy./denom; % Sine and cosine of doubled angles\n cos2theta = (Gxx-Gyy)./denom;\n\n if orientsmoothsigma\n cos2theta = gaussfilt(cos2theta, orientsmoothsigma); % Smoothed sine and cosine of\n sin2theta = gaussfilt(sin2theta, orientsmoothsigma); % doubled angles\n end\n \n or = atan2(sin2theta,cos2theta)/2;\n or(or<0) = or(or<0)+pi; % Map angles to 0-pi.\n\n if ~radians % Convert to degrees.\n or = or*180/pi; \n end"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "cleanupregions.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/cleanupregions.m", "size": 5516, "source_encoding": "utf_8", "md5": "c5b7d4595fd7df10edbce6cbb7cc912e", "text": "% CLEANUPREGIONS Cleans up small segments in an image of segmented regions\n%\n% Usage: [seg, Am] = cleanupregions(seg, areaThresh, connectivity)\n%\n% Arguments: seg - A region segmented image, such as might be produced by a\n% graph cut algorithm. All pixels in each region are labeled\n% by an integer.\n% areaThresh - Regions below this area in pixels will be merged with an\n% adjacent segment. I find a value of about 1/20th of the\n% expected mean segment area, or 1/1000th of the image area\n% usually looks 'about right'.\n% connectivity - Specify 8 or 4 connectivity. If not specified 8\n% connectivity is assumed.\n%\n% Note that regions with a label of 0 are ignored. These are treated as\n% privileged 'background regions' and are untouched. If you want these\n% regions to be considered you should assign a new positive label to these\n% areas using, say\n% >> L(L==0) = max(L(:)) + 1;\n%\n% Returns: seg - The updated segment image.\n% Am - Adjacency matrix of segments. Am(i, j) indicates whether\n% segments labeled i and j are connected/adjacent\n%\n% Typical application:\n% If a graph cut or superpixel algorithm fails to converge stray segments\n% can be left in the result. This function tries to clean things up by:\n% 1) Checking there is only one region for each segment label. If there is more\n% than one region they are given unique labels.\n% 2) Eliminating regions below a specified size and assigning them a label of an\n% adjacent region.\n%\n% See also: MCLEANUPREGIONS, REGIONADJACENCY, RENUMBERREGIONS\n\n% Copyright (c) 2010 Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% October 2010 - Original version\n% February 2013 - Connectivity choice, function returns adjacency matrix.\n\nfunction [seg, Am] = cleanupregions(seg, areaThresh, connectivity, prioritySeg)\n\n if ~exist('connectivity','var'), connectivity = 8; end\n if ~exist('prioritySeg','var'), prioritySeg = -1; end\n \n % 1) Ensure every segment is distinct but do not touch segments with a\n % label of 0\n labels = unique(seg(:))';\n maxlabel = max(labels);\n labels = setdiff(labels,0); % Remove 0 from the label list\n \n for l = labels\n [bl,num] = bwlabel(seg==l, connectivity); \n \n if num > 1 % We have more than one region with the same label\n for n = 2:num\n maxlabel = maxlabel+1; % Generate a new label\n seg(bl==n) = maxlabel; % and assign to this segment\n end\n end\n end\n\n if areaThresh\n % 2) Merge segments with small areas\n stat = regionprops(seg,'area'); % Get segment areas\n area = cat(1, stat.Area);\n Am = regionadjacency(seg); % Get adjacency matrix\n labels = unique(seg(:))';\n labels = setdiff(labels,0); % Remove 0 from the label list\n for n = labels\n if ~isnan(area(n)) && area(n) < areaThresh \n % Find regions adjacent to n and keep merging with the first element \n % in the adjacency list until we obtain an area >= areaThresh, \n % or we run out of regions to merge.\n ind = find(Am(n,:));\n\n while ~isempty(ind) && area(n) < areaThresh\n\n if ismember(prioritySeg, ind)\n [seg, Am, area] = mergeregions(n, prioritySeg, seg, Am, area);\n prioritySeg = n;\n else\n [seg, Am, area] = mergeregions(n, ind(1), seg, Am, area);\n end\n \n ind = find(Am(n,:)); % (The adjacency matrix will have changed) \n end\n end\n end\n \n end\n \n % 3) As some regions will have been absorbed into others and no longer exist\n % we now renumber the regions so that they sequentially increase from 1.\n % We also need to reconstruct the adjacency matrix to reflect the reduced\n % number of regions and their relabeling\n [seg, minLabel, maxLabel] = renumberregions(seg);\n Am = regionadjacency(seg); \n \n%-------------------------------------------------------------------\n% Function to merge segment s2 into s1\n% The segment image, Adjacency matrix and area arrays are updated.\n% We could make this a nested function for efficiency but then it would not\n% run under Octave.\nfunction [seg, Am, area] = mergeregions(s1, s2, seg, Am, area)\n \n if s1==s2\n fprintf('s1 == s2!\\n')\n return\n end\n \n % The area of s1 is now that of s1 and s2\n area(s1) = area(s1)+area(s2);\n area(s2) = NaN;\n \n % s1 inherits the adjacancy matrix entries of s2\n Am(s1,:) = Am(s1,:) | Am(s2,:);\n Am(:,s1) = Am(:,s1) | Am(:,s2); \n \n Am(s1,s1) = 0; % Ensure s1 is not connected to itself\n\n % Disconnect s2 from the adjacency matrix\n Am(s2,:) = 0;\n Am(:,s2) = 0;\n \n % Relabel s2 with s1 in the segment image\n seg(seg==s2) = s1;\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "subpix2d.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/subpix2d.m", "size": 3983, "source_encoding": "utf_8", "md5": "18d15956198e29a24e64871a95378041", "text": "% SUBPIX2D Sub-pixel locations in 2D image\n%\n% Usage: [rs, cs] = subpix2d(r, c, L);\n%\n% Arguments:\n% r, c - row, col vectors of extrema to pixel precision.\n% L - 2D corner image\n%\n% Returns:\n% rs, cs - row, col vectors of valid extrema to sub-pixel\n% precision.\n%\n% Note that the number of sub-pixel extrema returned can be less than the number\n% of integer precision extrema supplied. Any computed sub-pixel location that\n% is more than 0.5 pixels from the initial integer location is rejected. The\n% reasoning is that this implies that the extrema should be centred on a\n% neighbouring pixel, but this is inconsistent with the assumption that the\n% input data represents extrema locations to pixel precision.\n%\n% The sub-pixel locations are solved by forming a Taylor series representation\n% of the corner image values in the vicinity of each integer location extrema\n%\n% L(x) = L + dL/dx' x + 1/2 x' d2L/dx2 x\n%\n% x represents a position relative to the integer location of the extrema. This\n% gives us a quadratic and we solve for the location where the gradient is zero\n% - these are the extrema locations to sub-pixel precision\n%\n% Reference: Brown and Lowe \"Invariant Features from Interest Point Groups\"\n% BMVC 2002 pp 253-262 \n%\n% See also: SUBPIX3D\n\n% Copyright (c) 2010 Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% July 2010\n\nfunction [rs, cs] = subpix2d(R, C, L)\n \n if ndims(L) == 3\n error('Corner image must be grey scale');\n end\n \n [rows, cols] = size(L);\n x = zeros(2, length(R)); % Buffer for storing sub-pixel locations\n m = 0; % Counter for valid extrema\n \n for n = 1:length(R)\n r = R(n); % Convenience variables\n c = C(n);\n \n % If coords are too close to boundary skip\n if r < 2 || c < 2 || ...\n r > rows-1 || c > cols-1\n continue\n end\n \n % Compute partial derivatives via finite differences\n \n % 1st derivatives\n dLdr = (L(r+1,c) - L(r-1,c))/2;\n dLdc = (L(r,c+1) - L(r,c-1))/2;\n \n D = [dLdr; dLdc]; % Column vector of derivatives\n \n % 2nd Derivatives\n d2Ldr2 = L(r+1,c) - 2*L(r,c) + L(r-1,c);\n d2Ldc2 = L(r,c+1) - 2*L(r,c) + L(r,c-1);\n\n d2Ldrdc = (L(r+1,c+1) - L(r+1,c-1) - L(r-1,c+1) + L(r-1,c-1))/4;\n \n % Form Hessian from 2nd derivatives\n H = [d2Ldr2 d2Ldrdc \n d2Ldrdc d2Ldc2 ];\n \n % Solve for location where gradients are zero - these are the extrema\n % locations to sub-pixel precision\n if rcond(H) < eps \n continue; % Skip to next point\n% warning('Hessian is singular');\n else\n dx = -H\\D; % dx is location relative to centre pixel\n\n % Check solution is within 0.5 pixels of centre. A solution \n % outside of this implies that the extrema should be centred on a\n % neighbouring pixel, but this is inconsistent with the\n % assumption that the input data represents extrema locations to\n % pixel precision. Hence these points are rejected\n if all(abs(dx) <= 0.5) \n m = m + 1;\n x(:,m) = [r;c] + dx;\n end\n end\n \n end\n \n % Extract the subpixel row and column values from x noting we just\n % have m valid extrema.\n rs = x(1, 1:m);\n cs = x(2, 1:m);\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "filterregionproperties.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/filterregionproperties.m", "size": 3361, "source_encoding": "utf_8", "md5": "78fd996bb33dcfb2a24751069b09f3ee", "text": "% FILTERREGIONPROPERTIES Filters regions on their property's values\n% \n% Usage: bw = filterregionproperties(bw, {property, fn, value}, { ... } )\n%\n% Arguments: \n% bw - Binary image\n% {property, fn, value} - 3-element cell array consisting of:\n% property - String matching one of the properties\n% computed by REGIONPROPS.\n% fn - Handle to a function that will compare\n% the region property to a\n% value. Typically @lt or @gt.\n% value - The value that the region property is\n% compared against\n%\n% You can specify multiple {property, fn, value} cell arrays in the argument\n% list. Blobs/regions in the binary image that satisfy all the specified\n% constaints are retained in the image.\n%\n% Examples:\n%\n% Retain blobs that have an area greater than 50 pixels\n% >> bw = filterregionproperties(bw, {'Area', @gt, 50});\n%\n% Retain blobs with an area less than 20 and having a major axis orientation\n% that is greater than 0\n% >> bw = filterregionproperties(bw, {'Area', @lt, 20}, {'Orientation', @gt, 0});\n%\n% See also: REGIONPROPS\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% PK May 2013\n\nfunction bw = filterregionproperties(bw, varargin) \n\n varargin = varargin(:);\n \n % Form separate cell arrays of the properties, functions and values, \n % and perform basic check of datatypes\n nOps = length(varargin);\n property = cell(nOps,1);\n fn = cell(nOps,1);\n value = cell(nOps,1);\n \n for m = 1:nOps\n if length(varargin{m}) ~= 3\n error('Property, function and value must be a 3 element cell array');\n end\n\n property{m} = varargin{m}{1};\n fn{m} = varargin{m}{2};\n value{m} = varargin{m}{3}; \n\n if ~ischar(property{m})\n error('Property must be a string');\n end\n if ~strcmp(class(fn{m}), 'function_handle')\n error('Invalid function handle');\n end\n end\n \n [L, N] = bwlabel(bw); % Label image\n s = regionprops(L, property); % Get region properties\n\n % Form a table indicating which labeled region should be zeroed out on\n % the basis that its properties do not satisfy the\n % property-function-value requirements\n table = ones(N,1);\n for n = 1:N\n for m = 1:nOps\n if ~feval(fn{m}, s(n).(property{m}), value{m});\n table(n) = 0;\n end\n end\n end\n\n % Step through the binary image applying the table to zero out the\n % appropriate blobs\n for n = 1:numel(bw)\n if bw(n)\n bw(n) = table(L(n));\n end\n end\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "intfilttranspose.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/intfilttranspose.m", "size": 1102, "source_encoding": "utf_8", "md5": "0007e26379314049c0716d1ff851e36c", "text": "% INTFILTTRANSPOSE - transposes an integral filter\n%\n% Usage: ft = intfilttranspose(f)\n%\n% Argument: f - an integral image filter as described in the function INTEGRALFILTER\n%\n% Returns: ft - a transposed version of the filter\n%\n% See also: INTEGRALFILTER, INTEGRALIMAGE, INTEGAVERAGE\n\n% Copyright (c) 2007 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 2007\n\nfunction ft = intfilttranspose(f)\n \n [nfilt, dum] = size(f);\n ft = f;\n \n for n = 1:nfilt\n ft(n,1:4) = [f(n,2) -f(n,3) f(n,4) -f(n,1)];\n end\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "makeregionsdistinct.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/makeregionsdistinct.m", "size": 2142, "source_encoding": "utf_8", "md5": "87ec3511235a3eefd60cffbc8135de46", "text": "% MAKEREGIONSDISTINCT Ensures labeled segments are distinct\n%\n% Usage: [seg, maxlabel] = makeregionsdistinct(seg, connectivity)\n%\n% Arguments: seg - A region segmented image, such as might be produced by a\n% superpixel or graph cut algorithm. All pixels in each\n% region are labeled by an integer.\n% connectivity - Optional parameter indicating whether 4 or 8 connectedness\n% should be used. Defaults to 4.\n%\n% Returns: seg - A labeled image where all segments are distinct.\n% maxlabel - Maximum segment label number.\n%\n% Typical application: A graphcut or superpixel algorithm may terminate in a few\n% cases with multiple regions that have the same label. This function\n% identifies these regions and assigns a unique label to them.\n%\n% See also: SLIC, CLEANUPREGIONS, RENUMBERREGIONS\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% June 2013\n\n\nfunction [seg, maxlabel] = makeregionsdistinct(seg, connectivity)\n \n if ~exist('connectivity', 'var'), connectivity = 4; end\n \n % Ensure every segment is distinct but do not touch segments \n % with a label of 0\n labels = unique(seg(:))';\n maxlabel = max(labels);\n labels = setdiff(labels,0); % Remove 0 from the label list\n \n for l = labels\n [bl,num] = bwlabel(seg==l, connectivity); \n \n if num > 1 % We have more than one region with the same label\n for n = 2:num\n maxlabel = maxlabel+1; % Generate a new label\n seg(bl==n) = maxlabel; % and assign to this segment\n end\n end\n end\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "mcleanupregions.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/mcleanupregions.m", "size": 4352, "source_encoding": "utf_8", "md5": "956767ca7a2a6d8f168c2b2ab86d64f9", "text": "% MCLEANUPREGIONS Morphological clean up of small segments in an image of segmented regions\n%\n% Usage: [seg, Am] = mcleanupregions(seg, seRadius)\n%\n% Arguments: seg - A region segmented image, such as might be produced by a\n% graph cut algorithm. All pixels in each region are labeled\n% by an integer.\n% seRadius - Structuring element radius. This can be set to 0 in which\n% case the function will simply ensure all labeled regions\n% are distinct and relabel them if necessary. \n%\n% Returns: seg - The updated segment image.\n% Am - Adjacency matrix of segments. Am(i, j) indicates whether\n% segments labeled i and j are connected/adjacent\n%\n% Typical application:\n% If a graph cut or superpixel algorithm fails to converge stray segments\n% can be left in the result. This function tries to clean things up by:\n% 1) Checking there is only one region for each segment label. If there is\n% more than one region they are given unique labels.\n% 2) Eliminating regions below the structuring element size\n%\n% Note that regions labeled 0 are treated as a 'privileged' background region\n% and is not processed/affected by the function.\n%\n% See also: REGIONADJACENCY, RENUMBERREGIONS, CLEANUPREGIONS, MAKEREGIONSDISTINCT\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% March 2013 \n% June 2013 Improved morphological cleanup process using distance map\n\nfunction [seg, Am, mask] = mcleanupregions(seg, seRadius)\noption = 2;\n % 1) Ensure every segment is distinct \n [seg, maxlabel] = makeregionsdistinct(seg);\n \n % 2) Perform a morphological opening on each segment, subtract the opening\n % from the orignal segment to obtain regions to be reassigned to\n % neighbouring segments.\n if seRadius\n se = circularstruct(seRadius); % Accurate and not noticeably slower\n % if radius is small\n% se = strel('disk', seRadius, 4); % Use approximated disk for speed\n mask = zeros(size(seg));\n\n if option == 1 \n for l = 1:maxlabel\n b = seg == l;\n mask = mask | (b - imopen(b,se));\n end\n \n else % Rather than perform a morphological opening on every\n % individual region in sequence the following finds separate\n % lists of unconnected regions and performs openings on these.\n % Typically an image can be covered with only 5 or 6 lists of\n % unconnected regions. Seems to be about 2X speed of option\n % 1. (I was hoping for more...)\n list = finddisconnected(seg);\n \n for n = 1:length(list)\n b = zeros(size(seg));\n for m = 1:length(list{n})\n b = b | seg == list{n}(m);\n end\n\n mask = mask | (b - imopen(b,se));\n end\n end\n \n % Compute distance map on inverse of mask\n [~, idx] = bwdist(~mask);\n \n % Assign a label to every pixel in the masked area using the label of\n % the closest pixel not in the mask as computed by bwdist\n seg(mask) = seg(idx(mask));\n end\n \n % 3) As some regions will have been relabled, possibly broken into several\n % parts, or absorbed into others and no longer exist we ensure all regions\n % are distinct again, and renumber the regions so that they sequentially\n % increase from 1. We also need to reconstruct the adjacency matrix to\n % reflect the changed number of regions and their relabeling.\n\n seg = makeregionsdistinct(seg);\n [seg, minLabel, maxLabel] = renumberregions(seg);\n Am = regionadjacency(seg); \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "integaverage.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/integaverage.m", "size": 2088, "source_encoding": "utf_8", "md5": "6ff6d948c4e18c25ee2d9269d186448c", "text": "% INTEGAVERAGE - performs averaging filtering using an integral image\n%\n% Usage: avim = integaverage(im,rad)\n%\n% Arguments: im - Image to be filtered\n% rad - 'Radius' of square region over which averaging is\n% performed (rad = 1 implies a 3x3 average) \n% Returns: avim - Averaged image\n%\n% See also: INTEGRALIMAGE, INTEGRALFILTER, INTFILTTRANSPOSE\n\n% Reference: Paul Viola and Michael Jones, \"Robust Real-Time Face Detection\",\n% IJCV 57(2). pp 137-154. 2004.\n\n% Copyright (c) 2007 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 2007 - Original version\n% September 2009 - Changed so that input is the image rather than its\n% integral image\n\nfunction avim = integaverage(im, rad)\n \n if rad == 0 % Trap case where averaging filter is 1x1 hence radius = 0\n avim = im;\n return;\n end\n \n [rows, cols] = size(im);\n intim = integralimage(im);\n avim = zeros(rows, cols);\n\n % Fiddle with indices to ensure we calculate the average over a square\n % region that has an odd No of pixels on each side (ie has a centre pixel\n % located over each pixel of interest)\n \n down = rad; % offset to 'lower' indices\n up = down+1; % offset to 'upper' indices\n \n for r = 1+up:rows-down\n for c = 1+up:cols-down\n avim(r,c) = intim(r+down,c+down) - intim(r-up,c+down) ...\n - intim(r+down,c-up) + intim(r-up,c-up);\n end\n end\n \n avim = avim/(down+up)^2;\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "subpix3d.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/subpix3d.m", "size": 4434, "source_encoding": "utf_8", "md5": "22fda4d036d1bac30b6b36da20187f7a", "text": "% SUBPIX3D Sub-pixel locations in 3D volume\n%\n% Usage: [rs, cs, ss] = subpix3d(r, c, s, L);\n%\n% Arguments:\n% r, c, s - row, col and scale vectors of extrema to pixel precision.\n% L - 3D volumetric corner data, or 2D + scale space data.\n%\n% Returns:\n% rs, cs, ss - row, col and scale vectors of valid extrema to sub-pixel\n% precision.\n%\n% Note that the number of sub-pixel extrema returned can be less than the number\n% of integer precision extrema supplied. Any computed sub-pixel location that\n% is more than 0.5 pixels from the initial integer location is rejected. The\n% reasoning is that this implies that the extrema should be centred on a\n% neighbouring pixel, but this is inconsistent with the assumption that the\n% input data represents extrema locations to pixel precision.\n%\n% The sub-pixel locations are solved by forming a Taylor series representation\n% of the scale-space values in the vicinity of each integer location extrema\n%\n% L(x) = L + dL/dx' x + 1/2 x' d2L/dx2 x\n%\n% x represents a position relative to the integer location of the extrema. This\n% gives us a quadratic and we solve for the location where the gradient is zero\n% - these are the extrema locations to sub-pixel precision\n%\n% Reference: Brown and Lowe \"Invariant Features from Interest Point Groups\"\n% BMVC 2002 pp 253-262 \n%\n% See also: SUBPIX2D\n\n% Copyright (c) 2010 Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% July 2010\n\nfunction [rs, cs, ss] = subpix3d(R, C, S, L)\n \n [rows, cols, scales] = size(L);\n x = zeros(3, length(R)); % Buffer for storing sub-pixel locations\n m = 0; % Counter for valid extrema\n \n for n = 1:length(R)\n r = R(n); % Convenience variables\n c = C(n);\n s = S(n);\n \n % If coords are too close to boundary skip\n if r < 2 || c < 2 || s < 2 || ...\n r > rows-1 || c > cols-1 || s > scales-1\n continue\n end\n \n % Compute partial derivatives via finite differences\n \n % 1st derivatives\n dLdr = (L(r+1,c,s) - L(r-1,c,s))/2;\n dLdc = (L(r,c+1,s) - L(r,c-1,s))/2;\n dLds = (L(r,c,s+1) - L(r,c,s-1))/2; \n \n D = [dLdr; dLdc; dLds]; % Column vector of derivatives\n \n % 2nd Derivatives\n d2Ldr2 = L(r+1,c,s) - 2*L(r,c,s) + L(r-1,c,s);\n d2Ldc2 = L(r,c+1,s) - 2*L(r,c,s) + L(r,c-1,s);\n d2Lds2 = L(r,c,s+1) - 2*L(r,c,s) + L(r,c,s-1); \n \n d2Ldrdc = (L(r+1,c+1,s) - L(r+1,c-1,s) - L(r-1,c+1,s) + L(r-1,c-1,s))/4;\n d2Ldrds = (L(r+1,c,s+1) - L(r+1,c,s-1) - L(r-1,c,s+1) + L(r-1,c,s-1))/4;\n d2Ldcds = (L(r,c+1,s+1) - L(r,c+1,s-1) - L(r,c-1,s+1) + L(r,c-1,s-1))/4;\n \n % Form Hessian from 2nd derivatives\n H = [d2Ldr2 d2Ldrdc d2Ldrds\n d2Ldrdc d2Ldc2 d2Ldcds\n d2Ldrds d2Ldcds d2Lds2 ];\n \n % Solve for location where gradients are zero - these are the extrema\n % locations to sub-pixel precision\n if rcond(H) < eps\n continue; % Skip to next point \n% warning('Hessian is singular');\n else\n dx = -H\\D; % dx is location relative to centre pixel\n\n % Check solution is within 0.5 pixels of centre. A solution \n % outside of this implies that the extrema should be centred on a\n % neighbouring pixel, but this is inconsistent with the\n % assumption that the input data represents extrema locations to\n % pixel precision. Hence these points are rejected\n if all(abs(dx) <= 0.5) \n m = m + 1;\n x(:,m) = [r;c;s] + dx;\n end\n end\n \n end\n \n % Extract the subpixel row, column and scale values from x noting we just\n % have m valid extrema.\n rs = x(1, 1:m);\n cs = x(2, 1:m);\n ss = x(3, 1:m); \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "fastradial.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/fastradial.m", "size": 5399, "source_encoding": "utf_8", "md5": "b540902aad74684be591d3126ad87319", "text": "% FASTRADIAL - Loy and Zelinski's fast radial feature detector\r\n%\r\n% An implementation of Loy and Zelinski's fast radial feature detector\r\n%\r\n% Usage: S = fastradial(im, radii, alpha, beta)\r\n%\r\n% Arguments:\r\n% im - Image to be analysed\r\n% radii - Array of integer radius values to be processed\r\n% suggested radii might be [1 3 5]\r\n% alpha - Radial strictness parameter.\r\n% 1 - slack, accepts features with bilateral symmetry.\r\n% 2 - a reasonable compromise.\r\n% 3 - strict, only accepts radial symmetry.\r\n% ... and you can go higher\r\n% beta - Gradient threshold. Gradients below this threshold do\r\n% not contribute to symmetry measure, defaults to 0.\r\n%\r\n% Returns S - Symmetry map. Bright points with high symmetry are\r\n% marked with large positive values. Dark points of\r\n% high symmetry marked with large -ve values.\r\n%\r\n% To localize points use NONMAXSUPPTS on S, -S or abs(S) depending on\r\n% what you are seeking to find.\r\n\r\n% Reference:\r\n% Loy, G. Zelinsky, A. Fast radial symmetry for detecting points of\r\n% interest. IEEE PAMI, Vol. 25, No. 8, August 2003. pp 959-973.\r\n\r\n% Copyright (c) 2004-2010 Peter Kovesi\r\n% Centre for Exploration Targeting\r\n% The University of Western Australia\r\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in \r\n% all copies or substantial portions of the Software.\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n\r\n% November 2004 - original version\r\n% July 2005 - Bug corrected: magitude and orientation matrices were\r\n% not zeroed for each radius value used (Thanks to Ben\r\n% Jackson) \r\n% December 2009 - Gradient threshold added + minor code cleanup\r\n% July 2010 - Gradients computed via Farid and Simoncelli's 5 tap\r\n% derivative filters\r\n\r\nfunction [S, So] = fastradial(im, radii, alpha, beta, feedback)\r\n \r\n if ~exist('beta','var'), beta = 0; end\r\n if ~exist('feedback','var'), feedback = 0; end \r\n \r\n if any(radii ~= round(radii)) || any(radii < 1)\r\n error('radii must be integers and > 1')\r\n end\r\n \r\n [rows,cols]=size(im);\r\n \r\n % Compute derivatives in x and y via Farid and Simoncelli's 5 tap\r\n % derivative filters\r\n [imgx, imgy] = derivative5(im, 'x', 'y');\r\n mag = sqrt(imgx.^2 + imgy.^2)+eps; % (+eps to avoid division by 0)\r\n \r\n % Normalise gradient values so that [imgx imgy] form unit \r\n % direction vectors.\r\n imgx = imgx./mag; \r\n imgy = imgy./mag;\r\n \r\n S = zeros(rows,cols); % Symmetry matrix\r\n So = zeros(rows,cols); % Orientation only symmetry matrix \r\n \r\n [x,y] = meshgrid(1:cols, 1:rows);\r\n \r\n for n = radii\r\n M = zeros(rows,cols); % Magnitude projection image\r\n O = zeros(rows,cols); % Orientation projection image\r\n\r\n % Coordinates of 'positively' and 'negatively' affected pixels\r\n posx = x + round(n*imgx);\r\n posy = y + round(n*imgy);\r\n \r\n negx = x - round(n*imgx);\r\n negy = y - round(n*imgy);\r\n \r\n % Clamp coordinate values to range [1 rows 1 cols]\r\n posx( posx<1 ) = 1;\r\n posx( posx>cols ) = cols;\r\n posy( posy<1 ) = 1;\r\n posy( posy>rows ) = rows;\r\n \r\n negx( negx<1 ) = 1;\r\n negx( negx>cols ) = cols;\r\n negy( negy<1 ) = 1;\r\n negy( negy>rows ) = rows;\r\n \r\n % Form the orientation and magnitude projection matrices\r\n for r = 1:rows\r\n for c = 1:cols\r\n if mag(r,c) > beta\r\n O(posy(r,c),posx(r,c)) = O(posy(r,c),posx(r,c)) + 1;\r\n O(negy(r,c),negx(r,c)) = O(negy(r,c),negx(r,c)) - 1;\r\n \r\n M(posy(r,c),posx(r,c)) = M(posy(r,c),posx(r,c)) + mag(r,c);\r\n M(negy(r,c),negx(r,c)) = M(negy(r,c),negx(r,c)) - mag(r,c);\r\n end\r\n end\r\n end\r\n \r\n % Clamp Orientation projection matrix values to a maximum of \r\n % +/-kappa, but first set the normalization parameter kappa to the\r\n % values suggested by Loy and Zelinski\r\n if n == 1, kappa = 8; else kappa = 9.9; end\r\n \r\n O(O > kappa) = kappa; \r\n O(O < -kappa) = -kappa; \r\n \r\n % Unsmoothed symmetry measure at this radius value\r\n F = M./kappa .* (abs(O)/kappa).^alpha;\r\n Fo = sign(O) .* (abs(O)/kappa).^alpha; % Orientation only based measure\r\n \r\n % Smooth and spread the symmetry measure with a Gaussian proportional to\r\n % n. Also scale the smoothed result by n so that large scales do not\r\n % lose their relative weighting.\r\n S = S + gaussfilt(F, 0.25*n) * n;\r\n So = So + gaussfilt(Fo, 0.25*n) * n; \r\n \r\n end % for each radius\r\n \r\n S = S /length(radii); % Average\r\n So = So/length(radii); "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "maskimage.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/maskimage.m", "size": 1122, "source_encoding": "utf_8", "md5": "189c1feb312b970fdf4e22824ef53747", "text": "% MASKIMAGE Apply mask to image\n%\n% Usage: maskedim = maskimage(im, mask, col)\n%\n% Arguments: im - Image to be masked\n% mask - Binary masking image\n% col - Value/colour to be applied to regions where mask == 1\n% If im is a colour image col can be a 3-vector\n% specifying the colour values to be applied.\n%\n% Returns: maskedim - The masked image\n%\n% See also; DRAWREGIONBOUNDARIES\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% School of Earth and Environment\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n%\n% Feb 2013\n\nfunction maskedim = maskimage(im, mask, col)\n \n [rows,cols, chan] = size(im);\n \n % Set default colour to 0 (black)\n if ~exist('col', 'var'), col = 0; end\n \n % Ensure col has same length as image depth.\n if length(col) == 1\n col = repmat(col, [chan 1]);\n else\n assert(length(col) == chan);\n end\n \n % Perform masking\n maskedim = im;\n for n = 1:chan\n tmp = maskedim(:,:,n);\n tmp(mask) = col(n);\n maskedim(:,:,n) = tmp;\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "impad.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/impad.m", "size": 1007, "source_encoding": "utf_8", "md5": "dbffc182864409600c65556c2136b244", "text": "% IMPAD - adds zeros to the boundary of an image\n%\n% Usage: paddedim = impad(im, b, v)\n%\n% Arguments: im - Image to be padded (greyscale or colour)\n% b - Width of padding boundary to be added\n% v - Optional padding value if you do not want it to be 0.\n%\n% Returns: paddedim - Padded image of size rows+2*b x cols+2*b\n%\n% See also: IMTRIM, IMSETBORDER\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n% June 2010\n% January 2011 Added optional padding value\n\nfunction pim = impad(im, b, v)\n\n assert(b >= 1, 'Padding size must be >= 1')\n if ~exist('v', 'var'), v = 0; end\n \n b = round(b); % Ensure integer\n [rows, cols, channels] = size(im);\n if nargin == 3\n pim = v*ones(rows+2*b, cols+2*b, channels, class(im));\n else\n pim = zeros(rows+2*b, cols+2*b, channels, class(im));\n end\n \n pim(1+b:rows+b, 1+b:cols+b, 1:channels) = im;"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "finddisconnected.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/finddisconnected.m", "size": 2563, "source_encoding": "utf_8", "md5": "3e7d83e1dd00f59f9bd54fe42b93428b", "text": "% FINDDISCONNECTED find groupings of disconnected labeled regions\n%\n% Usage: list = finddisconnected(l)\n%\n% Argument: l - A labeled image segmenting an image into regions, such as\n% might be produced by a graph cut or superpixel algorithm.\n% All pixels in each region are labeled by an integer.\n%\n% Returns: list - A cell array of lists of regions that are not\n% connected. Typically there are 5 to 6 lists.\n%\n% Used by MCLEANUPREGIONS to reduce the number of morphological closing\n% operations \n%\n% See also: MCLEANUPREGIONS, REGIONADJACENCY\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% PK July 2013\n\n\nfunction list = finddisconnected(l)\n \n debug = 0;\n [Am, Al] = regionadjacency(l);\n \n N = max(l(:)); % number of labels\n \n % Array for keeping track of visited labels\n visited = zeros(N,1);\n\n list = {};\n listNo = 0;\n for n = 1:N\n\n if ~visited(n)\n listNo = listNo + 1;\n list{listNo} = n;\n visited(n) = 1;\n \n % Find all regions not directly connected to n and not visited\n notConnected = setdiff(find(~Am(n,:)), find(visited));\n \n % For each unconnected region check that it is not already\n % connected to a region in the list. If not, add to list\n for m = notConnected\n if isempty(intersect(Al{m}, list{listNo}))\n list{listNo} = [list{listNo} m];\n visited(m) = 1;\n end\n end\n end % if not visited(n)\n \n end\n \n % Display each list of unconncted regions as an image\n if debug \n for n = 1:length(list)\n \n mask = zeros(size(l));\n for m = 1:length(list{n})\n mask = mask | l == list{n}(m);\n end\n \n fprintf('list %d of %d length %d \\n', n, length(list), length(list{n}))\n show(mask);\n keypause\n end\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "gaussfilt.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/gaussfilt.m", "size": 1114, "source_encoding": "utf_8", "md5": "4e021d34f436d86073a1a4fcb135b2b7", "text": "% GAUSSFILT - Small wrapper function for convenient Gaussian filtering\n%\n% Usage: smim = gaussfilt(im, sigma)\n%\n% Arguments: im - Image to be smoothed.\n% sigma - Standard deviation of Gaussian filter.\n%\n% Returns: smim - Smoothed image.\n%\n% If called with sigma = 0 the function immediately returns with im assigned\n% to smim\n%\n% See also: INTEGGAUSSFILT\n\n% Peter Kovesi\n% Centre for Explortion Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n\n% March 2010\n% June 2013 - Provision for multi-channel images\n\nfunction smim = gaussfilt(im, sigma)\n \n if sigma < eps\n smim = im;\n return;\n end\n \n % If needed convert im to double\n if ~strcmp(class(im),'double')\n im = double(im); \n end\n \n sze = max(ceil(6*sigma), 1);\n if ~mod(sze,2) % Ensure filter size is odd\n sze = sze+1;\n end\n \n h = fspecial('gaussian', [sze sze], sigma);\n\n % Apply filter to all image channels\n smim = zeros(size(im));\n for n = 1:size(im,3)\n smim(:,:,n) = filter2(h, im(:,:,n));\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "derivative5.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/derivative5.m", "size": 4808, "source_encoding": "utf_8", "md5": "989b39a3f681a8cad7375573fa1a7a0f", "text": "% DERIVATIVE5 - 5-Tap 1st and 2nd discrete derivatives\n%\n% This function computes 1st and 2nd derivatives of an image using the 5-tap\n% coefficients given by Farid and Simoncelli. The results are significantly\n% more accurate than MATLAB's GRADIENT function on edges that are at angles\n% other than vertical or horizontal. This in turn improves gradient orientation\n% estimation enormously. If you are after extreme accuracy try using DERIVATIVE7.\n%\n% Usage: [gx, gy, gxx, gyy, gxy] = derivative5(im, derivative specifiers)\n%\n% Arguments:\n% im - Image to compute derivatives from.\n% derivative specifiers - A comma separated list of character strings\n% that can be any of 'x', 'y', 'xx', 'yy' or 'xy'\n% These can be in any order, the order of the\n% computed output arguments will match the order\n% of the derivative specifier strings.\n% Returns:\n% Function returns requested derivatives which can be:\n% gx, gy - 1st derivative in x and y\n% gxx, gyy - 2nd derivative in x and y\n% gxy - 1st derivative in y of 1st derivative in x\n%\n% Examples:\n% Just compute 1st derivatives in x and y\n% [gx, gy] = derivative5(im, 'x', 'y'); \n% \n% Compute 2nd derivative in x, 1st derivative in y and 2nd derivative in y\n% [gxx, gy, gyy] = derivative5(im, 'xx', 'y', 'yy')\n%\n% See also: DERIVATIVE7\n\n% Reference: Hany Farid and Eero Simoncelli \"Differentiation of Discrete\n% Multi-Dimensional Signals\" IEEE Trans. Image Processing. 13(4): 496-508 (2004)\n\n% Copyright (c) 2010 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% April 2010\n\nfunction varargout = derivative5(im, varargin)\n\n varargin = varargin(:);\n varargout = cell(size(varargin));\n \n % Check if we are just computing 1st derivatives. If so use the\n % interpolant and derivative filters optimized for 1st derivatives, else\n % use 2nd derivative filters and interpolant coefficients.\n % Detection is done by seeing if any of the derivative specifier\n % arguments is longer than 1 char, this implies 2nd derivative needed.\n secondDeriv = false; \n for n = 1:length(varargin)\n if length(varargin{n}) > 1\n secondDeriv = true;\n break\n end\n end\n \n if ~secondDeriv\n % 5 tap 1st derivative cofficients. These are optimal if you are just\n % seeking the 1st deriavtives\n p = [0.037659 0.249153 0.426375 0.249153 0.037659];\n d1 =[0.109604 0.276691 0.000000 -0.276691 -0.109604];\n else \n % 5-tap 2nd derivative coefficients. The associated 1st derivative\n % coefficients are not quite as optimal as the ones above but are\n % consistent with the 2nd derivative interpolator p and thus are\n % appropriate to use if you are after both 1st and 2nd derivatives.\n p = [0.030320 0.249724 0.439911 0.249724 0.030320];\n d1 = [0.104550 0.292315 0.000000 -0.292315 -0.104550];\n d2 = [0.232905 0.002668 -0.471147 0.002668 0.232905];\n end\n\n % Compute derivatives. Note that in the 1st call below MATLAB's conv2\n % function performs a 1D convolution down the columns using p then a 1D\n % convolution along the rows using d1. etc etc.\n gx = false;\n \n for n = 1:length(varargin)\n if strcmpi('x', varargin{n})\n varargout{n} = conv2(p, d1, im, 'same'); \n gx = true; % Record that gx is available for gxy if needed\n gxn = n;\n elseif strcmpi('y', varargin{n})\n varargout{n} = conv2(d1, p, im, 'same');\n elseif strcmpi('xx', varargin{n})\n varargout{n} = conv2(p, d2, im, 'same'); \n elseif strcmpi('yy', varargin{n})\n varargout{n} = conv2(d2, p, im, 'same');\n elseif strcmpi('xy', varargin{n}) | strcmpi('yx', varargin{n})\n if gx\n varargout{n} = conv2(d1, p, varargout{gxn}, 'same');\n else\n gx = conv2(p, d1, im, 'same'); \n varargout{n} = conv2(d1, p, gx, 'same');\n end\n else\n error(sprintf('''%s'' is an unrecognized derivative option',varargin{n}));\n end\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "solveinteg.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/solveinteg.m", "size": 3146, "source_encoding": "utf_8", "md5": "0b0df74b4066fbe41ed1f8a44f09200f", "text": "% SOLVEINTEG\n%\n% This function is used by INTEGGAUSFILT to solve for the multiple averaging\n% filter widths needed to approximate a Gaussian of desired standard deviation.\n%\n% Usage: [wl, wu, m, sigmaActual] = solveinteg(sigma, n)\n%\n% Arguments: sigma - Desired standard deviation of Gaussian. This should not\n% be less than one.\n% n - Number of averaging passes that will be used. I\n% suggest using a value that is at least 4, use at least\n% 5, perhaps 6 if you will be taking derivatives.\n%\n% Returns: wl - Width of smaller averaging filter to use\n% wu - Width of larger averaging filter to use\n% (Note wu = wl + 2 and wl is always odd)\n% m - The number of filterings to be done with the smaller\n% averaging filter. The number of filterings to be done\n% with the larger filter is n-m\n% sigmaActual - The actual standard deviation of the approximated\n% Gaussian that is achieved.\n%\n% Note that the desired standard deviation will not be achieved exactly. A\n% combination of different sized averaging filters are applied to approximate it\n% as closely as possible. If n is 5 the deviation from the desired standard\n% deviation will be at most about 0.15 pixels\n%\n% To acheive a filtering that approximates a Gaussian with the desired\n% standard deviation perform:\n% m filterings with an averaging filter of width wl, followed by\n% n-m filterings with an averaging filter of width wu\n%\n% See also: INTEGGAUSSFILT, INTEGAVERAGE, INTEGRALIMAGE\n\n% Copyright (c) 2009 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2009\n\nfunction [wl, wu, m, sigmaActual] = solveinteg(sigma, n)\n \n if sigma < 0.8\n warning('Sigma values below about 0.8 cannot be represented');\n end\n \n wIdeal = sqrt(12*sigma^2/n + 1); % Ideal averaging filter width \n \n % wl is first odd valued integer less than wIdeal\n wl = floor(wIdeal);\n if ~mod(wl,2)\n wl = wl-1;\n end\n \n % wu is the next odd value > wl\n wu = wl+2;\n \n % Compute m. Refer to the tech note for derivation of this formula\n mIdeal = (12*sigma^2 - n*wl^2 - 4*n*wl - 3*n)/(-4*wl - 4);\n m = round(mIdeal);\n \n if m > n || m < 0\n error('calculation of m has failed');\n end\n \n % Compute actual sigma that will be achieved\n sigmaActual = sqrt((m*wl^2 + (n-m)*wu^2 - n)/12);\n% fprintf('wl %d wu %d m %d actual sigma %.3f\\n', wl, wu, m, sigmaActual);\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "derivative7.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/derivative7.m", "size": 3752, "source_encoding": "utf_8", "md5": "59ac2311726917925b934ce48b7ae87f", "text": "% DERIVATIVE5 - 7-Tap 1st and 2nd discrete derivatives\n%\n% This function computes 1st and 2nd derivatives of an image using the 7-tap\n% coefficients given by Farid and Simoncelli. The results are significantly\n% more accurate than MATLAB's GRADIENT function on edges that are at angles\n% other than vertical or horizontal. This in turn improves gradient orientation\n% estimation enormously.\n%\n% Usage: [gx, gy, gxx, gyy, gxy] = derivative7(im, derivative specifiers)\n%\n% Arguments:\n% im - Image to compute derivatives from.\n% derivative specifiers - A comma separated list of character strings\n% that can be any of 'x', 'y', 'xx', 'yy' or 'xy'\n% These can be in any order, the order of the\n% computed output arguments will match the order\n% of the derivative specifier strings.\n% Returns:\n% Function returns requested derivatives which can be:\n% gx, gy - 1st derivative in x and y\n% gxx, gyy - 2nd derivative in x and y\n% gxy - 1st derivative in y of 1st derivative in x\n%\n% Examples:\n% Just compute 1st derivatives in x and y\n% [gx, gy] = derivative7(im, 'x', 'y'); \n% \n% Compute 2nd derivative in x, 1st derivative in y and 2nd derivative in y\n% [gxx, gy, gyy] = derivative7(im, 'xx', 'y', 'yy')\n%\n% See also: DERIVATIVE5\n\n% Reference: Hany Farid and Eero Simoncelli \"Differentiation of Discrete\n% Multi-Dimensional Signals\" IEEE Trans. Image Processing. 13(4): 496-508 (2004)\n\n% Copyright (c) 2010 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% April 2010\n\nfunction varargout = derivative7(im, varargin)\n\n varargin = varargin(:);\n varargout = cell(size(varargin));\n\n % 7-tap interpolant and 1st and 2nd derivative coefficients\n p = [ 0.004711 0.069321 0.245410 0.361117 0.245410 0.069321 0.004711];\n d1 = [ 0.018708 0.125376 0.193091 0.000000 -0.193091 -0.125376 -0.018708];\n d2 = [ 0.055336 0.137778 -0.056554 -0.273118 -0.056554 0.137778 0.055336];\n \n % Compute derivatives. Note that in the 1st call below MATLAB's conv2\n % function performs a 1D convolution down the columns using p then a 1D\n % convolution along the rows using d1. etc etc.\n gx = false; \n for n = 1:length(varargin)\n if strcmpi('x', varargin{n})\n varargout{n} = conv2(p, d1, im, 'same'); \n gx = true; % Record that gx is available for gxy if needed\n gxn = n;\n elseif strcmpi('y', varargin{n})\n varargout{n} = conv2(d1, p, im, 'same');\n elseif strcmpi('xx', varargin{n})\n varargout{n} = conv2(p, d2, im, 'same'); \n elseif strcmpi('yy', varargin{n})\n varargout{n} = conv2(d2, p, im, 'same');\n elseif strcmpi('xy', varargin{n}) | strcmpi('yx', varargin{n})\n if gx\n varargout{n} = conv2(d1, p, varargout{gxn}, 'same');\n else\n gx = conv2(p, d1, im, 'same'); \n varargout{n} = conv2(d1, p, gx, 'same');\n end\n else\n error(sprintf('''%s'' is an unrecognized derivative option',varargin{n}));\n end\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "nonmaxsup.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/nonmaxsup.m", "size": 6606, "source_encoding": "utf_8", "md5": "175ee530f04d95568bfbdb8b17524c7f", "text": "% NONMAXSUP - Non-maxima suppression\n%\n% Usage:\n% [im,location] = nonmaxsup(inimage, orient, radius);\n%\n% Function for performing non-maxima suppression on an image using an\n% orientation image. It is assumed that the orientation image gives \n% feature normal orientation angles in degrees (0-180).\n%\n% Input:\n% inimage - Image to be non-maxima suppressed.\n% \n% orient - Image containing feature normal orientation angles in degrees\n% (0-180), angles positive anti-clockwise.\n% \n% radius - Distance in pixel units to be looked at on each side of each\n% pixel when determining whether it is a local maxima or not.\n% This value cannot be less than 1.\n% (Suggested value about 1.2 - 1.5)\n%\n% Returns:\n% im - Non maximally suppressed image.\n% location - Complex valued image holding subpixel locations of edge\n% points. For any pixel the real part holds the subpixel row\n% coordinate of that edge point and the imaginary part holds\n% the column coordinate. (If a pixel value is 0+0i then it\n% is not an edgepoint.)\n% (Note that if this function is called without 'location'\n% being specified as an output argument is not computed)\n%\n% Notes:\n%\n% The suggested radius value is 1.2 - 1.5 for the following reason. If the\n% radius parameter is set to 1 there is a chance that a maxima will not be\n% identified on a broad peak where adjacent pixels have the same value. To\n% overcome this one typically uses a radius value of 1.2 to 1.5. However\n% under these conditions there will be cases where two adjacent pixels will\n% both be marked as maxima. Accordingly there is a final morphological\n% thinning step to correct this.\n%\n% This function is slow. It uses bilinear interpolation to estimate\n% intensity values at ideal, real-valued pixel locations on each side of\n% pixels to determine if they are local maxima.\n\n% Copyright (c) 1996-2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% December 1996 - Original version\n% September 2004 - Subpixel localization added\n% August 2005 - Made Octave compatible\n% October 2013 - Final thinning applied to binary image for Octave\n% compatbility (Thanks to Chris Pudney)\n\n\nfunction [im, location] = nonmaxsup(inimage, orient, radius)\n\nif any(size(inimage) ~= size(orient))\n error('image and orientation image are of different sizes');\nend\n\nif radius < 1\n error('radius must be >= 1');\nend\n\nOctave = exist('OCTAVE_VERSION', 'builtin') == 5; % Are we running under Octave\n\n[rows,cols] = size(inimage);\nim = zeros(rows,cols); % Preallocate memory for output image\n\nif nargout == 2\n location = zeros(rows,cols);\nend\n\niradius = ceil(radius);\n\n% Precalculate x and y offsets relative to centre pixel for each orientation angle \n\nangle = [0:180].*pi/180; % Array of angles in 1 degree increments (but in radians).\nxoff = radius*cos(angle); % x and y offset of points at specified radius and angle\nyoff = radius*sin(angle); % from each reference position.\n\nhfrac = xoff - floor(xoff); % Fractional offset of xoff relative to integer location\nvfrac = yoff - floor(yoff); % Fractional offset of yoff relative to integer location\n\norient = fix(orient)+1; % Orientations start at 0 degrees but arrays start\n % with index 1.\n\n% Now run through the image interpolating grey values on each side\n% of the centre pixel to be used for the non-maximal suppression.\n\nfor row = (iradius+1):(rows - iradius)\n for col = (iradius+1):(cols - iradius) \n\n or = orient(row,col); % Index into precomputed arrays\n x = col + xoff(or); % x, y location on one side of the point in question\n y = row - yoff(or);\n\n fx = floor(x); % Get integer pixel locations that surround location x,y\n cx = ceil(x);\n fy = floor(y);\n cy = ceil(y);\n tl = inimage(fy,fx); % Value at top left integer pixel location.\n tr = inimage(fy,cx); % top right\n bl = inimage(cy,fx); % bottom left\n br = inimage(cy,cx); % bottom right\n\n upperavg = tl + hfrac(or) * (tr - tl); % Now use bilinear interpolation to\n loweravg = bl + hfrac(or) * (br - bl); % estimate value at x,y\n v1 = upperavg + vfrac(or) * (loweravg - upperavg);\n\n if inimage(row, col) > v1 % We need to check the value on the other side...\n\n x = col - xoff(or); % x, y location on the `other side' of the point in question\n y = row + yoff(or);\n\n fx = floor(x);\n cx = ceil(x);\n fy = floor(y);\n cy = ceil(y);\n tl = inimage(fy,fx); % Value at top left integer pixel location.\n tr = inimage(fy,cx); % top right\n bl = inimage(cy,fx); % bottom left\n br = inimage(cy,cx); % bottom right\n upperavg = tl + hfrac(or) * (tr - tl);\n loweravg = bl + hfrac(or) * (br - bl);\n v2 = upperavg + vfrac(or) * (loweravg - upperavg);\n\n if inimage(row,col) > v2 % This is a local maximum.\n im(row, col) = inimage(row, col); % Record value in the output\n % image.\n\n % Code for sub-pixel localization if it was requested\n if nargout == 2\n % Solve for coefficients of parabola that passes through \n % [-1, v1] [0, inimage] and [1, v2]. \n % v = a*r^2 + b*r + c\n c = inimage(row,col);\n a = (v1 + v2)/2 - c;\n b = a + c - v1;\n \n % location where maxima of fitted parabola occurs\n r = -b/(2*a);\n location(row,col) = complex(row + r*yoff(or), col - r*xoff(or));\n end\n \n end\n\n end\n end\nend\n\n\n% Finally thin the 'nonmaximally suppressed' image by pointwise\n% multiplying itself with a morphological skeletonization of itself.\n%\n% I know it is oxymoronic to thin a nonmaximally supressed image but \n% fixes the multiple adjacent peaks that can arise from using a radius\n% value > 1.\n\nif Octave\n skel = bwmorph(im>0,'thin',Inf); % Octave's 'thin' seems to produce better results.\nelse\n skel = bwmorph(im>0,'skel',Inf);\nend\nim = im.*skel;\nif nargout == 2\n location = location.*skel;\nend\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "integgaussfilt.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Spatial/integgaussfilt.m", "size": 4116, "source_encoding": "utf_8", "md5": "957cc904a9b7d1545d8c3094dfc9e044", "text": "% INTEGGAUSSFILT - Approximate Gaussian filtering using integral filters\n%\n% This function approximates Gaussian filtering by repeatedly applying\n% averaging filters. The averaging is performed via integral images which\n% results in a fixed and very low computational cost that is independent of\n% the Gaussian size.\n%\n% Usage: [fim, sigmaActual] = integgaussfilt(im, sigma, nFilt)\n%\n% Arguments:\n% im - Image to be Gaussian smoothed\n% sigma - Desired standard deviation of Gaussian filter\n% nFilt - The number of average filterings to be used to\n% approximate the Gaussian. This should be a minimum of\n% 3, using 4 is better. If the smoothed image is to be\n% differentiated an additional averaging should be applied\n% for each derivative. Eg if a second derivative is to be\n% taken at least 5 averagings should be applied. If omitted\n% this parameter defaults to 5.\n%\n% Returns:\n% fim - Smoothed image \n% sigmaActual - Actual standard deviation of approximate Gaussian filter\n% that was used \n%\n% Notes:\n% 1. The desired standard deviation will not be achieved exactly. A combination\n% of different sized averaging filters are applied to approximate it as closely\n% as possible. If nFilt is 5 the deviation from the desired standard deviation\n% will be at most about 0.15 pixels.\n%\n% 2. Values of sigma less than about 1.8 cannot be well approximated by\n% repeated averagings. For sigma < 1.8 the smoothing is performed using\n% conventional Gaussian convolution.\n%\n% See also: INTEGAVERAGE, SOLVEINTEG, INTEGRALIMAGE, GAUSSFILT\n\n% Copyright (c) 2009-2010 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2009 - Original version\n% April 2010 - Added return of actual standard deviation of effective\n% filter used. Use standard convolution for small sigma\n\nfunction [im, sigmaActual] = integgaussfilt(im, sigma, nFilt)\n \n if ~exist('nFilt', 'var')\n nFilt = 5;\n end\n \n % First check if sigma is too small to be well represented by repeated\n % averagings. 5 averagings with a width 3 filter produces an equivalent\n % sigma of ~1.8 This represents the minimum threshold. For sigma less\n % than this we use conventional convolution\n if sigma < 1.8\n im = gaussfilt(im, sigma);\n sigmaActual = sigma;\n \n else % Use repeated averagings via integral images\n \n % Solve for the combination of averaging filter sizes that will result\n % in the closest approximation of sigma given nFilt.\n [wl, wu, m, sigmaActual] = solveinteg(sigma, nFilt);\n radl = (wl-1)/2;\n radu = (wu-1)/2;\n \n % Apply the averaging filters via integral images.\n for i = 1:m\n im = integaverage(im,radl);\n% im = runningaverage(im,radl);\n end\n \n for n = 1:(nFilt-m)\n im = integaverage(im,radu);\n% im = runningaverage(im,radu);\n end\n \n end\n\n \n%------------------------------------------------------------------- \n% GAUSSFILT - Small wrapper function for convenient Gaussian filtering\n%\n% Usage: smim = gaussfilt(im, sigma)\n%\n\nfunction smim = gaussfilt(im, sigma)\n \n sze = ceil(6*sigma); \n if ~mod(sze,2) % Ensure filter size is odd\n sze = sze+1;\n end\n sze = max(sze,1); % and make sure it is at least 1\n \n h = fspecial('gaussian', [sze sze], sigma);\n smim = filter2(h, im);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "rotx.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/rotx.m", "size": 589, "source_encoding": "utf_8", "md5": "bc55598911b9d73eb90ab44cab59a9db", "text": "% ROTX - Homogeneous transformation for a rotation about the x axis\n%\n% Usage: T = rotx(theta)\n%\n% Argument: theta - rotation about x axis\n% Returns: T - 4x4 homogeneous transformation matrix\n%\n% See also: TRANS, ROTY, ROTZ, INVHT\n\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction T = rotx(theta)\n\nT = [ 1 0 0 0\n 0 cos(theta) -sin(theta) 0\n 0 sin(theta) cos(theta) 0\n 0 0 0 1];\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "angleaxisrotate.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/angleaxisrotate.m", "size": 1383, "source_encoding": "utf_8", "md5": "9ac58e5db9309d73f49b53b0f9c99b6d", "text": "% ANGLEAXISROTATE - uses angle axis descriptor to rotate vectors\n%\n% Usage: v2 = angleaxisrotate(t, v)\n%\n% Arguments: t - 3-vector giving rotation axis with magnitude equal to the\n% rotation angle in radians.\n% v - 4xn matrix of homogeneous 4-vectors to be rotated or\n% 3xn matrix of inhomogeneous 3-vectors to be rotated\n% Returns: v2 - The rotated vectors. \n%\n% See also: MATRIX2ANGLEAXIS, NEWANGLEAXIS, ANGLEAXIS2MATRIX, ANGLEAXIS2MATRIX2,\n% NORMALISEANGLEAXIS\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction v2 = angleaxisrotate(t, v)\n \n [ndim,npts] = size(v);\n\n T = angleaxis2matrix(t);\n\n if ndim == 3\n v2 = T(1:3,1:3)*v;\n\n elseif ndim == 4\n v2 = T*v;\n\n else\n error('v must be 4xN or 3xN');\n end\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "homotrans.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/homotrans.m", "size": 1371, "source_encoding": "utf_8", "md5": "8fc0c2c8b73dcccc47ba10e8a451beee", "text": "% HOMOTRANS - Homogeneous transformation of points/lines\n%\n% Function to perform a transformation on 2D or 3D homogeneous coordinates\n% The resulting coordinates are normalised to have a homogeneous scale of 1\n%\n% Usage:\n% t = homotrans(P, v);\n%\n% Arguments:\n% P - 3 x 3 or 4 x 4 homogeneous transformation matrix\n% v - 3 x n or 4 x n matrix of homogeneous coordinates\n\n% Copyright (c) 2000-2007 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction t = homotrans(P, v);\n \n [dim,npts] = size(v);\n \n if ~all(size(P)==dim)\n error('Transformation matrix and point dimensions do not match');\n end\n\n t = P*v; % Transform\n\n for r = 1:dim-1 % Now normalise \n t(r,:) = t(r,:)./t(end,:);\n end\n \n t(end,:) = ones(1,npts);\n \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "trans.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/trans.m", "size": 708, "source_encoding": "utf_8", "md5": "c2bc04ae87a1f56d814ee75d140cea19", "text": "% TRANS - Homogeneous transformation for a translation by x, y, z\n%\n% Usage: T = trans(x, y, z)\n% T = trans(v)\n%\n% Arguments: x,y,z - translations in x,y and z, or alternatively\n% v - 3-vector defining x, y and z.\n% Returns: T - 4x4 homogeneous transformation matrix\n%\n% See also: ROTX, ROTY, ROTZ, INVHT\n\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction T = trans(x, y, z)\n\n if nargin == 1 % x is a 3-vector\n y = x(2); z = x(3); x = x(1);\n end\n \n T = [ 1 0 0 x\n 0 1 0 y\n 0 0 1 z\n 0 0 0 1];\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "plotframe.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/plotframe.m", "size": 1677, "source_encoding": "utf_8", "md5": "40c9bb130ec46ca33912f804e87f2eac", "text": "% PLOTFRAME - plots a coordinate frame specified by a homogeneous transform \n%\n% Usage: function plotframe(T, len, label)\n%\n% Arguments:\n% T - 4x4 homogeneous transform\n% len - length of axis arms to plot (defaults to 1)\n% label - text string to append to x,y,z labels on axes\n%\n% len and label are optional and default to 1 and '' respectively\n%\n% See also: ROTX, ROTY, ROTZ, TRANS, INVHT\n\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction plotframe(T, len, label, colr)\n\n if ~all(size(T) == [4,4])\n error('plotframe: matrix is not 4x4')\n end\n \n if ~exist('len','var')\n len = 1;\n end\n \n if ~exist('label','var') \n label = '';\n end\n \n if ~exist('colr','var') \n colr = [0 0 1];\n end \n \n % Assume scale specified by T(4,4) == 1\n \n origin = T(1:3, 4); % 1st three elements of 4th column\n X = origin + len*T(1:3, 1); % point 'len' units out along x axis\n Y = origin + len*T(1:3, 2); % point 'len' units out along y axis\n Z = origin + len*T(1:3, 3); % point 'len' units out along z axis\n \n line([origin(1),X(1)], [origin(2), X(2)], [origin(3), X(3)], 'color', colr);\n line([origin(1),Y(1)], [origin(2), Y(2)], [origin(3), Y(3)], 'color', colr);\n line([origin(1),Z(1)], [origin(2), Z(2)], [origin(3), Z(3)], 'color', colr);\n \n text(X(1), X(2), X(3), ['x' label], 'color', colr);\n text(Y(1), Y(2), Y(3), ['y' label], 'color', colr);\n text(Z(1), Z(2), Z(3), ['z' label], 'color', colr);\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "newangleaxis.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/newangleaxis.m", "size": 1101, "source_encoding": "utf_8", "md5": "4ad89dd95a736dff8b3603430648964c", "text": "% NEWANGLEAXIS - Constructs angle-axis descriptor\n%\n% Usage: t = newangleaxis(theta, axis)\n%\n% Arguments: theta - angle of rotation\n% axis - 3-vector defining axis of rotation\n% Returns: t - 3-vector giving rotation axis with magnitude equal to the\n% rotation angle in radians.\n%\n% See also: MATRIX2ANGLEAXIS, ANGLEAXISROTATE, ANGLEAXIS2MATRIX\n% NORMALISEANGLEAXIS\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction t = newangleaxis(theta, axis)\n \n if length(axis) ~= 3\n error('axis must be a 3 vector');\n end\n \n axis = axis/norm(axis); % Make unit length\n \n % Normalise theta to lie in the range -pi to pi to ensure one-to-one mapping\n % between angle-axis descriptor and resulting rotation. Note that -ve\n % rotations are achieved by reversing the direction of the axis.\n \n if abs(theta) > pi\n theta = theta*(1 - (2*pi)/abs(theta));\n end\n \n t = theta*axis;"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "rotz.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/rotz.m", "size": 593, "source_encoding": "utf_8", "md5": "485891081a31d4907a07ce934642fea2", "text": "% ROTZ - Homogeneous transformation for a rotation about the z axis\n%\n% Usage: T = rotz(theta)\n%\n% Argument: theta - rotation about z axis\n% Returns: T - 4x4 homogeneous transformation matrix\n%\n% See also: TRANS, ROTX, ROTY, INVHT\n\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction T = rotz(theta)\n\nT = [ cos(theta) -sin(theta) 0 0\n sin(theta) cos(theta) 0 0\n 0 0 1 0\n 0 0 0 1];\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "angleaxis2matrix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/angleaxis2matrix.m", "size": 1793, "source_encoding": "utf_8", "md5": "0252f63ff9c4999658e4db8055454f0c", "text": "% ANGLEAXIS2MATRIX - converts angle-axis descriptor to 4x4 homogeneous\n% transformation matrix\n%\n% Usage: T = amgleaxis2matrix(t)\n%\n% Argument: t - 3-vector giving rotation axis with magnitude equal to the\n% rotation angle in radians.\n% Returns: T - 4x4 Homogeneous transformation matrix\n%\n% See also: MATRIX2ANGLEAXIS, ANGLEAXISROTATE, NEWANGLEAXIS, NORMALISEANGLEAXIS\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction T = angleaxis2matrix(t)\n\n theta = sqrt(t(:)'*t(:)); % = norm(t), but faster\n if theta < eps % If the rotation is very small...\n T = [ 1 -t(3) t(2) 0\n t(3) 1 -t(1) 0\n -t(2) t(1) 1 0\n 0 0 0 1];\n \n return\n end\n \n % Otherwise set up standard matrix, first setting up some convenience\n % variables\n t = t/theta; x = t(1); y = t(2); z = t(3);\n \n c = cos(theta); s = sin(theta); C = 1-c;\n xs = x*s; ys = y*s; zs = z*s;\n xC = x*C; yC = y*C; zC = z*C;\n xyC = x*yC; yzC = y*zC; zxC = z*xC;\n\n T = [ x*xC+c xyC-zs zxC+ys 0\n xyC+zs y*yC+c yzC-xs 0\n zxC-ys yzC+xs z*zC+c 0\n 0 0 0 1];\n \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "matrix2quaternion.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/matrix2quaternion.m", "size": 2010, "source_encoding": "utf_8", "md5": "ad7a1983aceaa9953be167eddabb22ae", "text": "% MATRIX2QUATERNION - Homogeneous matrix to quaternion\n%\n% Converts 4x4 homogeneous rotation matrix to quaternion\n%\n% Usage: Q = matrix2quaternion(T)\n%\n% Argument: T - 4x4 Homogeneous transformation matrix\n% Returns: Q - a quaternion in the form [w, xi, yj, zk]\n%\n% See Also QUATERNION2MATRIX\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction Q = matrix2quaternion(T)\n\n % This code follows the implementation suggested by Hartley and Zisserman \n R = T(1:3, 1:3); % Extract rotation part of T\n \n % Find rotation axis as the eigenvector having unit eigenvalue\n % Solve (R-I)v = 0;\n [v,d] = eig(R-eye(3));\n \n % The following code assumes the eigenvalues returned are not necessarily\n % sorted by size. This may be overcautious on my part.\n d = diag(abs(d)); % Extract eigenvalues\n [s, ind] = sort(d); % Find index of smallest one\n if d(ind(1)) > 0.001 % Hopefully it is close to 0\n warning('Rotation matrix is dubious');\n end\n \n axis = v(:,ind(1)); % Extract appropriate eigenvector\n \n if abs(norm(axis) - 1) > .0001 % Debug\n warning('non unit rotation axis');\n end\n \n % Now determine the rotation angle\n twocostheta = trace(R)-1;\n twosinthetav = [R(3,2)-R(2,3), R(1,3)-R(3,1), R(2,1)-R(1,2)]';\n twosintheta = axis'*twosinthetav;\n \n theta = atan2(twosintheta, twocostheta);\n \n Q = [cos(theta/2); axis*sin(theta/2)];\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "vector2quaternion.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/vector2quaternion.m", "size": 563, "source_encoding": "utf_8", "md5": "a87aa8408a94f8010721a2ea603c64f9", "text": "% VECTOR2QUATERNION - embeds 3-vector in a quaternion representation\n%\n% Usage: Q = vector2quaternion(v)\n%\n% Argument: v - 3-vector\n% Returns: Q - Quaternion given by [0; v(:)]\n%\n% See also: NEWQUATERNION, QUATERNIONROTATE, QUATERNIONPRODUCT, QUATERNIONCONJUGATE\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n \nfunction Q = vector2quaternion(v)\n\n if length(v) ~= 3\n error('v must be a 3-vector');\n end\n\n Q = [0; v(:)];"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "invht.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/invht.m", "size": 505, "source_encoding": "utf_8", "md5": "62f8fca3096c7b08ba22952fef7e6416", "text": "% INVHT - inverse of a homogeneous transformation matrix\n%\n% Usage: Tinv = invht(T)\n%\n% Argument: T - 4x4 homogeneous transformation matrix\n% Returns: Tinv - inverse\n%\n% See also: TRANS, ROTX, ROTY, ROTZ\n\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction Tinv = invht(T)\n \n A = T(1:3,1:3);\n \n Tinv = [ A' -A'*T(1:3,4)\n 0 0 0 1 ];"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "roty.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/roty.m", "size": 589, "source_encoding": "utf_8", "md5": "1523f4098a8a375de8eed1c69ae75c92", "text": "% ROTY - Homogeneous transformation for a rotation about the y axis\n%\n% Usage: T = roty(theta)\n%\n% Argument: theta - rotation about y axis\n% Returns: T - 4x4 homogeneous transformation matrix\n%\n% See also: TRANS, ROTX, ROTZ, INVHT\n\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction T = roty(theta)\n\nT = [ cos(theta) 0 sin(theta) 0\n 0 1 0 0\n -sin(theta) 0 cos(theta) 0\n 0 0 0 1];\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "invrpy.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/invrpy.m", "size": 1251, "source_encoding": "utf_8", "md5": "327fc230e354d616448b0620e8b51b4f", "text": "% INVRPY - inverse of Roll Pitch Yaw transform\n%\n% Usage: [rpy1, rpy2] = invrpy(RPY)\n% \n% Argument: RPY - 4x4 Homogeneous transformation matrix or 3x3 rotation matrix\n% Returns: rpy1 = [phi1, theta1, psi1] - the 1st solution and\n% rpy2 = [phi2, theta2, psi2] - the 2nd solution\n%\n% rotx(phi1)*roty(theta1)*rotz(psi1) = RPY\n%\n% See also: INVEULER, INVHT, ROTX, ROTY, ROTZ\n\n% Reference: Richard P. Paul Robot Manipulators: Mathematics, Programming and Control.\n% MIT Press 1981. Page 70\n%\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction [rpy1, rpy2] = invrpy(RPY)\n\n phi1 = atan2(RPY(2,1), RPY(1,1));\n phi2 = phi1 + pi;\n \n theta1 = atan2(-RPY(3,1), cos(phi1)*RPY(1,1) + sin(phi1)*RPY(2,1));\n theta2 = atan2(-RPY(3,1), cos(phi2)*RPY(1,1) + sin(phi2)*RPY(2,1));\n \n psi1 = atan2(sin(phi1)*RPY(1,3) - cos(phi1)*RPY(2,3), ...\n -sin(phi1)*RPY(1,2) + cos(phi1)*RPY(2,2));\n psi2 = atan2(sin(phi2)*RPY(1,3) - cos(phi2)*RPY(2,3), ...\n -sin(phi2)*RPY(1,2) + cos(phi2)*RPY(2,2));\n \n rpy1 = [phi1, theta1, psi1];\n rpy2 = [phi2, theta2, psi2];\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "normaliseangleaxis.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/normaliseangleaxis.m", "size": 995, "source_encoding": "utf_8", "md5": "a160233e601e4a5bf231afef48739445", "text": "% NORMALISEANGLEAXIS - normalises angle-axis descriptor\n%\n% Function normalises theta so that it has maximum magnitude of pi to ensure one-to-one\n% mapping between angle-axis descriptor and resulting rotation\n%\n% Usage: t2 = normaliseangleaxis(t)\n%\n% Argument: t - 3-vector giving rotation axis with magnitude equal to the\n% rotation angle in radians.\n% Returns: t2 - Normalised angle-axis descriptor\n%\n% Note this function only works for |t| up to a magnitude of 2pi\n%\n% See also: MATRIX2ANGLEAXIS, NEWANGLEAXIS, ANGLEAXIS2MATRIX, ANGLEAXIS2MATRIX2,\n% ANGLEAXISROTATE\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction t2 = normaliseangleaxis(t)\n \n if length(t) ~= 3\n error('axis must be a 3 vector');\n end\n \n if norm(t) > pi\n t2 = t*(1 - (2*pi)/norm(t));\n else\n t2 = t;\n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "quaternionconjugate.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/quaternionconjugate.m", "size": 525, "source_encoding": "utf_8", "md5": "d7df86d9770e7881f0cda73f664a8be5", "text": "% QUATERNIONCONJUGATE - Conjugate of a quaternion\n%\n% Usage: Qconj = quaternionconjugate(Q)\n%\n% Argument: Q - Quaternions in the form Q = [Qw Qi Qj Qk]\n% Returns: Qconj - Conjugate\n%\n% See also: NEWQUATERNION, QUATERNIONROTATE, QUATERNIONPRODUCT\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction Qconj = quaternionconjugate(Q)\n \n Qconj = Q(:);\n Qconj(2:4) = -Qconj(2:4);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "dhtrans.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/dhtrans.m", "size": 1161, "source_encoding": "utf_8", "md5": "817bf7d3f603627a2da4773fefc67097", "text": "% DHTRANS - computes Denavit Hartenberg matrix\n%\n% This function calculates the 4x4 homogeneous transformation matrix, representing\n% the Denavit Hartenberg matrix, given link parameters of joint angle, length, joint\n% offset and twist.\n%\n% Usage: T = DHtrans(theta, offset, length, twist)\n% \n% Arguments: theta - joint angle (rotation about local z)\n% offset - offset (translation along z)\n% length - translation along link x axis\n% twist - rotation about link x axis\n%\n% Returns: T - 4x4 Homogeneous transformation matrix\n%\n% See also: TRANS, ROTX, ROTY, ROTZ, INVHT\n\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction T = dhtrans(theta, offset, length, twist)\n\nT = [ cos(theta) -sin(theta)*cos(twist) sin(theta)*sin(twist) length*cos(theta)\n sin(theta) cos(theta)*cos(twist) -cos(theta)*sin(twist) length*sin(theta)\n 0 sin(twist) cos(twist) offset\n 0 0 0 1 ];"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "matrix2angleaxis.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/matrix2angleaxis.m", "size": 2351, "source_encoding": "utf_8", "md5": "1c675a6fc3be8ab220ce1ca0f2adde3b", "text": "% MATRIX2ANGLEAXIS - Homogeneous matrix to angle-axis description\n%\n% Usage: t = matrix2angleaxis(T)\n%\n% Argument: T - 4x4 Homogeneous transformation matrix\n% Returns: t - 3-vector giving rotation axis with magnitude equal to the\n% rotation angle in radians.\n%\n% See also: ANGLEAXIS2MATRIX, ANGLEAXIS2MATRIX2, ANGLEAXISROTATE, NEWANGLEAXIS, \n% NORMALISEANGLEAXIS\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% 2008 - Original version\n% May 2013 - Code to trap small rotations added\n\nfunction t = matrix2angleaxis(T)\n\n % This code follows the implementation suggested by Hartley and Zisserman\n R = T(1:3, 1:3); % Extract rotation part of T\n \n % Trap case where rotation is very small. (See angleaxis2matrix.m)\n Reye = R-eye(3);\n if norm(Reye) < 1e-8\n t = [T(3,2); T(1,3); T(2,1)];\n return\n end\n\n % Otherwise find rotation axis as the eigenvector having unit eigenvalue\n % Solve (R-I)v = 0;\n [v,d] = eig(Reye);\n \n % The following code assumes the eigenvalues returned are not necessarily\n % sorted by size. This may be overcautious on my part.\n d = diag(abs(d)); % Extract eigenvalues\n [s, ind] = sort(d); % Find index of smallest one\n if d(ind(1)) > 0.001 % Hopefully it is close to 0\n warning('Rotation matrix is dubious');\n end\n \n axis = v(:,ind(1)); % Extract appropriate eigenvector\n \n if abs(norm(axis) - 1) > .0001 % Debug\n warning('non unit rotation axis');\n end\n \n % Now determine the rotation angle\n twocostheta = trace(R)-1;\n twosinthetav = [R(3,2)-R(2,3), R(1,3)-R(3,1), R(2,1)-R(1,2)]';\n twosintheta = axis'*twosinthetav;\n \n theta = atan2(twosintheta, twocostheta);\n \n t = theta*axis;\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "quaternionproduct.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/quaternionproduct.m", "size": 818, "source_encoding": "utf_8", "md5": "bcfe792d9518a1c110b9957970f4f7c8", "text": "% QUATERNIONPRODUCT - Computes product of two quaternions\n%\n% Usage: Q = quaternionproduct(A, B)\n%\n% Arguments: A, B - Quaternions assumed to be 4-vectors in the\n% form A = [Aw Ai Aj Ak]\n% Returns: Q - Quaternion product\n%\n% See also: NEWQUATERNION, QUATERNIONROTATE, QUATERNIONCONJUGATE\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction Q = quaternionproduct(A, B)\n\n Q = zeros(4,1); \n Q(1) = A(1)*B(1) - A(2)*B(2) - A(3)*B(3) - A(4)*B(4);\n Q(2) = A(1)*B(2) + A(2)*B(1) + A(3)*B(4) - A(4)*B(3);\n Q(3) = A(1)*B(3) - A(2)*B(4) + A(3)*B(1) + A(4)*B(2);\n Q(4) = A(1)*B(4) + A(2)*B(3) - A(3)*B(2) + A(4)*B(1);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "quaternion2matrix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/quaternion2matrix.m", "size": 1413, "source_encoding": "utf_8", "md5": "7296cadf62f6ca9273e726ffd7e19d95", "text": "% QUATERNION2MATRIX - Quaternion to a 4x4 homogeneous transformation matrix\n%\n% Usage: T = quaternion2matrix(Q)\n%\n% Argument: Q - a quaternion in the form [w xi yj zk]\n% Returns: T - 4x4 Homogeneous rotation matrix\n% \n% See also MATRIX2QUATERNION, NEWQUATERNION, QUATERNIONROTATE\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\nfunction T = quaternion2matrix(Q)\n \n Q = Q/norm(Q); % Ensure Q has unit norm\n \n % Set up convenience variables\n w = Q(1); x = Q(2); y = Q(3); z = Q(4);\n w2 = w^2; x2 = x^2; y2 = y^2; z2 = z^2;\n xy = x*y; xz = x*z; yz = y*z;\n wx = w*x; wy = w*y; wz = w*z;\n \n T = [w2+x2-y2-z2 , 2*(xy - wz) , 2*(wy + xz) , 0\n 2*(wz + xy) , w2-x2+y2-z2 , 2*(yz - wx) , 0\n 2*(xz - wy) , 2*(wx + yz) , w2-x2-y2+z2 , 0\n 0 , 0 , 0 , 1];\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "newquaternion.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/newquaternion.m", "size": 647, "source_encoding": "utf_8", "md5": "a36af1ff9a23186bd42b779523671cea", "text": "% NEWQUATERNION - Construct quaternion \n%\n% Q = newquaternion(theta, axis)\n%\n% Arguments: theta - angle of rotation\n% axis - 3-vector defining axis of rotation\n% Returns: Q - a quaternion in the form [w xi yj zk]\n%\n% See Also: QUATERNION2MATRIX, MATRIX2QUATERNION, QUATERNIONROTATE\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction Q = newquaternion(theta, axis)\n \n axis = axis./norm(axis);\n Q = zeros(4,1); \n Q(1) = cos(theta/2);\n Q(2:4) = sin(theta/2)*axis;\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "quaternionrotate.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/quaternionrotate.m", "size": 2026, "source_encoding": "utf_8", "md5": "e0b6a4a18c8be41ee01226e17cbd83e8", "text": "% QUATERNIONROTATE - Rotates a 3D vector by a quaternion \n%\n% Usage: vnew = quaternionrotate(Q, v)\n%\n% Arguments: Q - a quaternion in the form [w xi yj zk]\n% v - a vector to rotate, either an inhomogeneous 3-vector or a\n% homogeneous 4-vector\n% Returns: vnew - rotated vector\n%\n% See also MATRIX2QUATERNION, QUATERNION2MATRIX, NEWQUATERNION\n\n% Copyright (c) 2008 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% Code forms the equivalent 3x3 rotation matrix from the quaternion and\n% applies it to a vector \n%\n% Note that Qw^2 + Qi^2 + Qj^2 + Qk^2 = 1\n% So the top-left entry of the rotation matrix of\n% Qw^2 + Qi^2 - Qj^2 - Qk^2\n% can be rewritten as\n% Qw^2 + Qi^2 + Qj^2 + Qk^2 - 2Qj^2 - 2Qk^2\n% = 1 - 2Qj^2 - 2Qk^2\n%\n% Similar optimization applies to the other diagonal elements\n\nfunction vnew = quaternionrotate(Q, v)\n\n % Copy v to vnew to allocate space. If v is a 4 element homogeneous\n % vector this also sets the homogeneous scale factor of vnew\n vnew = v; \n \n Qw = Q(1); Qi = Q(2); Qj = Q(3); Qk = Q(4);\n \n t2 = Qw*Qi;\n t3 = Qw*Qj;\n t4 = Qw*Qk;\n t5 = -Qi*Qi;\n t6 = Qi*Qj;\n t7 = Qi*Qk;\n t8 = -Qj*Qj;\n t9 = Qj*Qk;\n t10 = -Qk*Qk;\n vnew(1) = 2*( (t8 + t10)*v(1) + (t6 - t4)*v(2) + (t3 + t7)*v(3) ) + v(1);\n vnew(2) = 2*( (t4 + t6)*v(1) + (t5 + t10)*v(2) + (t9 - t2)*v(3) ) + v(2);\n vnew(3) = 2*( (t7 - t3)*v(1) + (t2 + t9)*v(2) + (t5 + t8)*v(3) ) + v(3);\n \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "inveuler.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Rotations/inveuler.m", "size": 1220, "source_encoding": "utf_8", "md5": "5ebf0b9f54aead905ee1300724228adc", "text": "% INVEULER - inverse of Euler transform\n%\n% Usage: [euler1, euler2] = inveuler(T)\n%\n% Argument: T - 4x4 Homogeneous transformation matrix or 3x3 rotation matrix\n% Returns: euler1 = [phi1, theta1, psi1] - the 1st solution and,\n% euler2 = [phi2, theta2, psi2] - the 2nd solution\n%\n% rotz(phi1)*roty(theta1)*rotz(psi1) = T\n%\n% See also: INVRPY, INVHT, ROTX, ROTY, ROTZ\n\n% Reference: Richard P. Paul Robot Manipulators: Mathematics, Programming and Control.\n% MIT Press 1981. Page 68\n%\n% Copyright (c) 2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n\nfunction [euler1, euler2] = inveuler(T)\n\n phi1 = atan2(T(2,3), T(1,3));\n phi2 = phi1 + pi;\n \n theta1 = atan2(cos(phi1)*T(1,3) + sin(phi1)*T(2,3), T(3,3));\n theta2 = atan2(cos(phi2)*T(1,3) + sin(phi2)*T(2,3), T(3,3));\n \n psi1 = atan2(-sin(phi1)*T(1,1) + cos(phi1)*T(2,1), ...\n -sin(phi1)*T(1,2) + cos(phi1)*T(2,2));\n psi2 = atan2(-sin(phi2)*T(1,1) + cos(phi2)*T(2,1), ...\n -sin(phi2)*T(1,2) + cos(phi2)*T(2,2));\n \n euler1 = [phi1, theta1, psi1];\n euler2 = [phi2, theta2, psi2];\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ternarymix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Blender/ternarymix.m", "size": 13368, "source_encoding": "utf_8", "md5": "53527c33bc58e77326e03f0354a5bbb6", "text": "% TERNARYMIX Image blending and swiping over three images\n%\n% Function uses Barycentric coordinates over a triangle to interpolate/blend\n% three images. You can also switch to a swiping mode of display between the\n% three images.\n%\n% Usage: ternarymix(im, nodeLabel, normBlend, figNo)\n%\n% Arguments: im - 3-element cell array of images to blend. If omitted or\n% empty a file selection dialog box is presented.\n% nodeLabel - Optional cell array of strings for labeling the 3 nodes\n% of the interface. \n% normBlend - Sets the image normalisation that is used.\n% 0 - No normalisation applied other than image clamping.\n% 1 - Image is normalised so that max value in any\n% channel is 1. This is the default\n% 2 - Normalise to have fixed mean grey value.\n% (This is hard-wired at 0.2 . Edit function wbmcb\n% below to change) \n% 3 - Normalise so that max grey value is a fixed value\n% (This is hard-wired at 0.6 . Edit function wbmcb\n% below to change) \n% figNo - Optional figure number to use. \n%\n% This function sets up an interface consisting of a triangle with nodes\n% corresponding to the three input images. Positioning the cursor within the\n% triangle produces an interactive blend of the images formed from a weighted\n% sum of the images. The weights correspond to the barycentric coordinates of\n% the cursor within the triangle. The program starts out assigning a lightness\n% matched basis colour to each image. These colours are nominally red, green\n% and blue but have been constructed so that they are matched in lightness\n% values and also have secondary colours that are closely matched.\n% Unfortunately the normalisation of the blended image undoes some of this\n% lightness matching but I am not sure there is a good way around this.\n%\n% Hitting 'c' cycles the basis colours between the set of lightness matched\n% Isoluminant colours, the RGB primaries, and grey scale images.\n%\n% Hitting 's' toggles between blending and swiping mode.\n%\n% See also: LINIMIX, BILINIMIX, CLIQUEMIX, CYCLEMIX, BINARYMIX\n\n% Reference:\n% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.\n% \"Interactive Multi-Image Blending for Visualization and Interpretation\",\n% Computers & Geosciences 72 (2014) 147-155.\n% http://doi.org/10.1016/j.cageo.2014.07.010\n%\n% For information about the construction of the lighness matched basis\n% colours see:\n% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary\n\n% Copyright (c) 2012-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% May 2012 - Original version\n% March 2014 - General cleanup and added option to specify colours associated\n% with each image when using the RGB option.\n% Dec 2014 - Updated isoluminant basis colours. Added interactive colour\n% mode section and swiping.\n\nfunction ternarymix(im, nodeLabel, normBlend, figNo)\n \n if ~exist('im', 'var'), im = []; end\n if ~exist('normBlend', 'var') || isempty(normBlend), normBlend = 1; end\n if ~exist('figNo', 'var') || isempty(figNo)\n fig = figure;\n else\n fig = figure(figNo); \n end\n \n [im, nImages, fname] = collectncheckimages(im);\n assert(nImages == 3, 'Three images must be supplied');\n\n [rows,cols] = size(im{1});\n \n if ~exist('nodeLabel', 'var') || isempty(nodeLabel)\n for n = 1:3\n nodeLabel{n} = namenpath(fname{n});\n end\n end\n \n % Set up three 'basis' images from the three input images and their\n % corresponding basis colours.\n colourdisplay = 'ISO';\n imcol = {[0.90 0.17 0.00], [0.00 0.50 0.00], [0.10 0.33 1.00]};\n \n for n = 1:3\n % It is useful to truncate extreme image values that are at the ends\n % of the histogram. Here we remove the 0.25% extremes of the histogram.\n im{n} = histtruncate(im{n}, 0.25, 0.25);\n im{n} = normalise(im{n}); % Renormalise 0-1\n basis{n} = applycolour(im{n}, imcol{n});\n end \n\n % Display 1st image and get handle to Cdata in the figure\n % Suppress display warnings for images that are large\n S = warning('off');\n figure(fig); clf, \n imposition = [0.35 0.0 0.65 1.0];\n subplot('position', imposition);\n imshow(basis{1}); drawnow\n imHandle = get(gca,'Children');\n warning(S)\n \n % Set up interface figure \n ah = subplot('position',[0.0 0.4 0.35 0.35]); \n\n % Draw triangle interface and label vertices\n theta = [0 2/3*pi 4/3*pi]+pi/2;\n v = [cos(theta)\n sin(theta)];\n \n hold on;\n plot([v(1,:) 0], [v(2,:) 0], 'k.', 'markersize',40)\n plot([v(1,:) 0], [v(2,:) 0], '.', 'markersize',20, 'Color', [.8 .8 .8])\n line([v(1,:) v(1,1)], [v(2,:) v(2,1)], 'LineWidth', 2)\n \n for n = 1:nImages\n text(v(1,n)*1.2, v(2, n)*1.2, nodeLabel{n}, ...\n 'HorizontalAlignment','center', 'FontWeight', 'bold', 'FontSize', 16);\n end\n \n coltxt = text(-1,-1,'ISO','FontWeight', 'bold', 'FontSize', 16);\n \n r = 1.1;\n axis ([-r r -r r]), axis off, axis equal\n \n % Set callback function and window title\n setwindowsize(fig, [rows cols], imposition);\n set(fig, 'WindowButtonDownFcn',@wbdcb);\n set(fig, 'KeyReleaseFcn', @keyreleasecb); \n set(fig, 'NumberTitle', 'off') \n set(fig, 'name', ' Ternary Mix')\n set(fig, 'Menubar','none');\n\n % Set up custom pointer\n myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];\n myPointer(~myPointer) = NaN;\n\n fprintf('\\nClick and move the mouse within the triangle interface.\\n'); \n fprintf('Left-click to toggle blending on and off.\\n'); \n fprintf('Hit ''c'' to cycle between isoluminant colours, RGB and grey.\\n'); \n fprintf('Hit ''s'' to toggle between swiping and blending modes.\\n\\n');\n blending = 0;\n hspot = 0;\n blendswipe = 'blend'; % Start in blending mode \n \n%--------------------------------------------------------------------\n% Window button down callback\nfunction wbdcb(src,evnt)\n if strcmp(get(src,'SelectionType'),'normal')\n if ~blending % Turn blending on\n blending = 1;\n set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...\n 'PointerShapeHotSpot',[9 9])\n set(src,'WindowButtonMotionFcn',@wbmcb)\n \n if hspot % For paper illustration\n delete(hspot);\n end \n \n else % Turn blending off\n blending = 0;\n set(src,'Pointer','arrow')\n set(src,'WindowButtonMotionFcn','')\n \n % For paper illustration\n cp = get(ah,'CurrentPoint');\n x = cp(1,1);\n y = cp(1,2);\n if gca == ah\n hspot = plot(x, y, '.', 'color', [0 0 0], 'Markersize', 40'); \n end\n end\n end\nend\n \n%--------------------------------------------------------------------\n% Window button move call back\nfunction wbmcb(src,evnt)\n cp = get(ah,'CurrentPoint');\n xy = [cp(1,1); cp(1,2)];\n\n if strcmp(blendswipe, 'swipe')\n swipe(xy); \n\n else % Blend\n [w1,w2,w3] = barycentriccoords(xy, v(:,1), v(:,2), v(:,3));\n blend = w1*basis{1} + w2*basis{2} + w3*basis{3};\n \n % Various normalisation options \n \n if normBlend == 0 % No normalisation\n blend(blend>1) = 1; % but clamp values to 1\n \n elseif normBlend == 1 || strcmpi(colourdisplay, 'GREY') % Normalise by max value in blend\n blend = blend/max(blend(:));\n \n elseif normBlend == 2 % Normalise to have fixed mean grey value\n g = 0.299*blend(:,:,1) + 0.587*blend(:,:,2) + 0.114*blend(:,:,3);\n g(isnan(g(:))) = [];\n meang = mean(g(:));\n blend = blend/meang*0.2; % Mean grey value of 0.2\n blend(blend>1) = 1; % Clamp values to 1\n \n elseif normBlend == 3 % Normalise so that max grey value is a fixed value\n g = 0.299*blend(:,:,1) + 0.587*blend(:,:,2) + 0.114*blend(:,:,3);\n blend = blend/max(g(:))*0.6; % Max grey of 0.6\n blend(blend>1) = 1; % Clamp values to 1\n end\n \n set(imHandle,'CData', blend); \n end\nend\n\n%-----------------------------------------------------------------------\n% Key Release callback\n% If 'c' is pressed the display cycles between using Lightness matched\n% colours, RGB and Grey. If 's' is pressed we toggle between swiping and\n% blending.\n\nfunction keyreleasecb(src,evnt)\n \n if evnt.Character == 'c' \n if strcmp(colourdisplay, 'ISO')\n colourdisplay = 'RGB';\n set(coltxt, 'String', 'RGB');\n imcol = {[1 0 0], [0 1 0], [0 0 1]}; \n for n = 1:3\n basis{n} = applycolour(im{n}, imcol{n});\n end\n \n elseif strcmp(colourdisplay, 'RGB') \n colourdisplay = 'GREY'; \n set(coltxt, 'String', 'Grey');\n for n = 1:3\n basis{n} = applycolour(im{n}, [1 1 1]);\n end \n \n elseif strcmp(colourdisplay, 'GREY') \n colourdisplay = 'ISO'; \n set(coltxt, 'String', 'ISO');\n imcol = {[0.90 0.17 0.00], [0.00 0.50 0.00], [0.10 0.33 1.00]}; \n for n = 1:3\n basis{n} = applycolour(im{n}, imcol{n});\n end \n end\n \n elseif evnt.Character == 's' % Swipe/Blend toggle\n if strcmp(blendswipe, 'swipe')\n blendswipe = 'blend';\n else\n blendswipe = 'swipe';\n end\n \n end\n \n wbmcb(src,evnt); % update the display\nend \n\n%-----------------------------------------------------------------------\n% Generate swipe image given xy which has its origin at the centre of the\n% triangle with vertices at a radius of 1\nfunction swipe(xy)\n\n % Convert cursor position to row and col coords\n x = round(( xy(1) + 1) * cols/2);\n y = round((-xy(2) + 1) * rows/2);\n \n % Clamp x and y to image limits\n x = max(1,x); x = min(cols,x); \n y = max(1,y); y = min(rows,y); \n \n % Three images. 1st image occupies top half, swiped vertically. 2nd and\n % 3rd images share bottom half and are swiped horizontally.\n\n swipeim = [ basis{1}(1:y, :, :)\n basis{2}(y+1:end, 1:x, :) basis{3}(y+1:end, x+1:end, :)];\n \n set(imHandle,'CData', swipeim);\n \nend \n\n%------------------------------------------------------------------------\nend % of main function and its nested functions \n\n%------------------------------------------------------------------------\n% Given 3 vertices and a point convert the xy coordinates of the point to\n% Barycentric coordinates with respect to vertices v1, v2 and v3. \n% Assumes all arguements are 2-element column vectors. \n% Returns 3 barycentric coordinates / weights.\n\nfunction [l1,l2,l3] = barycentriccoords(p, v1, v2, v3)\n \n l = [v1-v3, v2-v3]\\(p-v3);\n\n l1 = l(1);\n l2 = l(2);\n l3 = 1 - l1 - l2;\n \n % Simple clamping of resulting coords to range [0 1]\n l1 = min(max(l1,0),1);\n l2 = min(max(l2,0),1);\n l3 = min(max(l3,0),1);\n\n % Perhaps ideally if p is outside triangle p should be projected to the\n % closest point on the triangle before computing barycentric coords \nend \n\n%------------------------------------------------------------------------\n% Function to set up window size nicely\nfunction setwindowsize(fig, imsze, imposition)\n \n screen = get(0,'ScreenSize');\n scsze = [screen(4) screen(3)];\n window = get(fig, 'Position');\n \n % Set window height to match image height\n window(4) = imsze(1);\n \n % Set window width to match image width allowing for fractional width of\n % image specified in imposition\n window(3) = imsze(2)/imposition(3);\n \n % Check size of window relative to screen. If larger rescale the window\n % size to fit 80% of screen dimension.\n winsze = [window(4) window(3)];\n ratio = max(winsze./scsze);\n if ratio > 1\n winsze = winsze/ratio * 0.8;\n end\n \n window(3:4) = [winsze(2) winsze(1)];\n set(fig, 'Position', window);\n \nend\n\n \n%----------------------------------------------------------------------------------\n% Apply a colour to a scalar image\n\nfunction rgbim = applycolour(im, col)\n \n [rows,cols] = size(im);\n rgbim = zeros(rows,cols,3);\n \n for r = 1:rows\n for c = 1:cols\n rgbim(r,c,:) = im(r,c)*col(:); \n end\n end\nend"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "binarymix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Blender/binarymix.m", "size": 11564, "source_encoding": "utf_8", "md5": "53c5c89d010c8dc56ca1daef824526f9", "text": "% BINARYMIX Image blending and swiping between two images\n%\n% Function blends two images. Each image is coloured with two lightness\n% matched colours that sum to white. Like a ternary image but binary!\n% You can also switch between blending and swiping.\n%\n% Usage: binarymix(im, nodeLabel, normBlend, figNo)\n%\n% Arguments: im - 2-element cell array of images to blend. If omitted or\n% empty a file selection dialog box is presented.\n% nodeLabel - Optional cell array of strings for labeling the 2 nodes\n% of the interface. \n% normBlend - Sets the image normalisation that is used.\n% 0 - No normalisation applied other than image clamping.\n% 1 - Image is normalised so that max value in any\n% channel is 1. This is the default\n% 2 - Normalise to have fixed mean grey value.\n% (This is hard-wired at 0.2 . Edit function wbmcb\n% below to change) \n% 3 - Normalise so that max grey value is a fixed value\n% (This is hard-wired at 0.6 . Edit function wbmcb\n% below to change) \n% figNo - Optional figure number to use. \n%\n% This function sets up an interface consisting of a line with nodes at each end\n% corresponding to the two input images. Positioning the cursor along the line\n% produces an interactive blend of the images formed from a weighted sum of the\n% images.\n%\n% Hitting 'c' cycles the display between two choices for the image basis colours\n% and grey scale images. Each set of two basis colours sum to white. Where your\n% two images/data sets are in agreement, and you are at the blend mid-point, you\n% will see achromatic regions in the blended result.\n%\n% Hitting 's' toggles between blending and swiping mode.\n%\n% See also: TERNARYMIX, LINIMIX, BILINIMIX, CLIQUEMIX, CYCLEMIX\n\n% Reference:\n% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.\n% \"Interactive Multi-Image Blending for Visualization and Interpretation\",\n% Computers & Geosciences 72 (2014) 147-155.\n% http://doi.org/10.1016/j.cageo.2014.07.010\n%\n% For information about the construction of the lighness matched basis\n% colours see:\n% http://peterkovesi.com/projects/colourmaps/ColourmapTheory/index.html#ternary\n\n% Copyright (c) 2012-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% Dec 2014 - Adapted from TERNARYMIX\n\n% [0.00 0.71 0.00], [1.00 0.29 1.00]; % Green - Magenta\n% [1 0.4 0]; b = [0 0.6 1]; % Red/Orange - Blue/Cyan\n\nfunction binarymix(im, nodeLabel, normBlend, figNo)\n \n if ~exist('im', 'var'), im = []; end\n if ~exist('normBlend', 'var') || isempty(normBlend), normBlend = 1; end\n if ~exist('figNo', 'var') || isempty(figNo)\n fig = figure;\n else\n fig = figure(figNo); \n end\n\n [im, nImages, fname] = collectncheckimages(im);\n assert(nImages == 2, 'Three images must be supplied');\n\n [rows,cols] = size(im{1});\n \n if ~exist('nodeLabel', 'var') || isempty(nodeLabel)\n for n = 1:2\n nodeLabel{n} = namenpath(fname{n});\n end\n end\n \n % Set up two 'basis' images from the two input images and their\n % corresponding basis colours.\n % Set up initial lightness matched colours\n colourdisplay = 'COL1';\n imcol = {[0.00 0.71 0.00], [1.00 0.29 1.00]};\n for n = 1:2\n % It is useful to truncate extreme image values that are at the ends\n % of the histogram. Here we remove the 0.25% extremes of the histogram.\n im{n} = histtruncate(im{n}, 0.25, 0.25);\n im{n} = normalise(im{n}); % Renormalise 0-1\n basis{n} = applycolour(im{n}, imcol{n});\n end \n\n % Display 1st image and get handle to Cdata in the figure\n % Suppress display warnings for images that are large\n S = warning('off');\n figure(fig); clf, \n imposition = [0.35 0.0 0.65 1.0];\n subplot('position', imposition);\n imshow(basis{1}); drawnow\n imHandle = get(gca,'Children');\n warning(S)\n \n % Set up interface figure \n ah = subplot('position',[0.0 0.4 0.35 0.35]); \n\n % Draw slider interface and label vertices\n theta = [0 pi];\n v = [cos(theta)\n sin(theta)];\n \n hold on;\n plot(v(1,:), v(2,:), 'k.', 'markersize',40)\n plot(v(1,:), v(2,:), '.', 'markersize',20, 'Color', [.8 .8 .8])\n line(v(1,:), v(2,:), 'LineWidth', 2)\n \n for n = 1:nImages\n text(v(1,n)*1.2, v(2, n)*1.2, nodeLabel{n}, ...\n 'HorizontalAlignment','center', 'FontWeight', 'bold', 'FontSize', 16);\n end\n \n r = 1.1;\n axis ([-r r -r r]), axis off, axis equal\n \n % Set callback function and window title\n setwindowsize(fig, [rows cols], imposition);\n set(fig, 'WindowButtonDownFcn',@wbdcb);\n set(fig, 'KeyReleaseFcn', @keyreleasecb); \n set(fig, 'NumberTitle', 'off') \n set(fig, 'name', ' Binary Mix')\n set(fig, 'Menubar','none');\n\n % Set up custom pointer\n myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];\n myPointer(~myPointer) = NaN;\n\n fprintf('\\nClick and move the mouse on the slider.\\n');\n fprintf('Left-click to toggle blending on and off.\\n');\n fprintf('Hit ''c'' to cycle between two colour choices and grey .\\n');\n fprintf('Hit ''s'' to toggle between swiping and blending modes.\\n\\n');\n blending = 0;\n hspot = 0;\n blendswipe = 'blend'; % Start in blending mode \n \n%--------------------------------------------------------------------\n% Window button down callback\nfunction wbdcb(src,evnt)\n if strcmp(get(src,'SelectionType'),'normal')\n if ~blending % Turn blending on\n blending = 1;\n set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...\n 'PointerShapeHotSpot',[9 9])\n set(src,'WindowButtonMotionFcn',@wbmcb)\n \n if hspot % For paper illustration\n delete(hspot);\n end \n \n else % Turn blending off\n blending = 0;\n set(src,'Pointer','arrow')\n set(src,'WindowButtonMotionFcn','')\n \n % For paper illustration\n cp = get(ah,'CurrentPoint');\n x = cp(1,1);\n y = cp(1,2);\n if gca == ah\n hspot = plot(x, y, '.', 'color', [0 0 0], 'Markersize', 40'); \n end\n end\n end\nend\n \n%--------------------------------------------------------------------\n% Window button move call back\nfunction wbmcb(src,evnt)\n cp = get(ah,'CurrentPoint');\n xy = [cp(1,1); cp(1,2)];\n \n % Project xy onto segment v1 v2\n L = norm(v(:,2) - v(:,1));\n v1v2 = (v(:,2) - v(:,1))/L;\n w = dot( xy - v(:,1), v1v2) / L;\n \n if w < 0, w = 0; end\n if w > 1, w = 1; end\n \n if strcmp(blendswipe, 'swipe')\n swipe(1-w); \n \n else % Blend\n blend = (1-w)*basis{1} + w*basis{2};\n \n % Various normalisation options \n \n if normBlend == 0 % No normalisation\n blend(blend>1) = 1; % but clamp values to 1\n \n elseif normBlend == 1 || strcmpi(col, 'grey') % Normalise by max value in blend\n blend = blend/max(blend(:));\n \n elseif normBlend == 2 % Normalise to have fixed mean grey value\n g = 0.299*blend(:,:,1) + 0.587*blend(:,:,2) + 0.114*blend(:,:,3);\n g(isnan(g(:))) = [];\n meang = mean(g(:));\n blend = blend/meang*0.2; % Mean grey value of 0.2\n blend(blend>1) = 1; % Clamp values to 1\n \n elseif normBlend == 3 % Normalise so that max grey value is a fixed value\n g = 0.299*blend(:,:,1) + 0.587*blend(:,:,2) + 0.114*blend(:,:,3);\n blend = blend/max(g(:))*0.6; % Max grey of 0.6\n blend(blend>1) = 1; % Clamp values to 1\n end\n\n set(imHandle,'CData', blend); \n end\n \nend\n\n%-----------------------------------------------------------------------\n% Key Release callback\n% If 'c' is pressed the display cycles between two choices of Lightness matched\n% colours and Grey.\n% Pressing 's' toggles between swiping and blending modes\n\nfunction keyreleasecb(src,evnt)\n \n if evnt.Character == 'c' % Toggle colours\n if strcmp(colourdisplay, 'COL1')\n colourdisplay = 'COL2';\n imcol = {[1.0 0.4 0.0], [0.0 0.6 1.0]};\n for n = 1:2\n basis{n} = applycolour(im{n}, imcol{n});\n end\n \n elseif strcmp(colourdisplay, 'COL2') \n colourdisplay = 'GREY'; \n for n = 1:2\n basis{n} = applycolour(im{n}, [1 1 1]);\n end \n \n elseif strcmp(colourdisplay, 'GREY') \n colourdisplay = 'COL1'; \n imcol = {[0.00 0.71 0.00], [1.00 0.29 1.00]};\n for n = 1:2\n basis{n} = applycolour(im{n}, imcol{n});\n end \n end\n \n elseif evnt.Character == 's' % Swipe/Blend toggle\n if strcmp(blendswipe, 'swipe')\n blendswipe = 'blend';\n else\n blendswipe = 'swipe';\n end\n \n end\n \n wbmcb(src,evnt); % update the display\nend \n\n%-----------------------------------------------------------------------\n% Generate swipe image given value of w between 0 and 1\nfunction swipe(w)\n\n x = round(w*(cols-1));\n \n % Construct swipe image from the input images\n swipeim = [basis{1}(:, 1:x, :) basis{2}(:, x+1:end, :)];\n \n set(imHandle,'CData', swipeim);\n \nend \n\n\n%------------------------------------------------------------------------\nend % of main function and its nested functions \n\n%------------------------------------------------------------------------\n% Function to set up window size nicely\nfunction setwindowsize(fig, imsze, imposition)\n \n screen = get(0,'ScreenSize');\n scsze = [screen(4) screen(3)];\n window = get(fig, 'Position');\n \n % Set window height to match image height\n window(4) = imsze(1);\n \n % Set window width to match image width allowing for fractional width of\n % image specified in imposition\n window(3) = imsze(2)/imposition(3);\n \n % Check size of window relative to screen. If larger rescale the window\n % size to fit 80% of screen dimension.\n winsze = [window(4) window(3)];\n ratio = max(winsze./scsze);\n if ratio > 1\n winsze = winsze/ratio * 0.8;\n end\n \n window(3:4) = [winsze(2) winsze(1)];\n set(fig, 'Position', window);\n \nend\n\n%----------------------------------------------------------------------------------\n% Apply a colour to a scalar image\n\nfunction rgbim = applycolour(im, col)\n \n [rows,cols] = size(im);\n rgbim = zeros(rows,cols,3);\n \n for r = 1:rows\n for c = 1:cols\n rgbim(r,c,:) = im(r,c)*col(:); \n end\n end\nend "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "logisticweighting.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Blender/logisticweighting.m", "size": 3064, "source_encoding": "utf_8", "md5": "2896739e6134ef8ef15bfd4bc3726f12", "text": "% LOGISTICWEIGHTING Weighting function based on the logistics function\n% \n% Adaptation of the generalised logistics function for defining the variation of\n% a weighting function for blending images\n%\n% Usage: w = logisticweighting(x, b, R)\n% \n% Arguments: x - Value, or array of values at which to evaluate the weighting\n% function.\n% b - Parameter specifying the growth rate of the logistics function.\n% This controls the slope of the weighting function at its\n% midpoint. Probably most convenient to specify this as a\n% power of 2.\n% b = 0 Perfect linear transition from wmin to wmax. \n% b = 2^0 Near linear transition from wmin to wmax.\n% b = 2^4 Sigmoidal transition.\n% b = 2^10 Near step-like transition at midpoint.\n% R - 4-vector specifying [xmin, xmax, wmin, wmax] the minimum and\n% maximum weights over the minimum and maximum x values that\n% will be used. The midpoint of the sigmoidal weighting\n% function will occur at (xmin+xmax)/2 at a value of\n% (wmin+wmax)/2. Note that if an x value outside of this range\n% is supplied the resulting weight will also be outside of the\n% desired range. Defaults to R = [-1 1 -1 1]\n%\n% Returns: w - Weight values for each supplied x-coordinate.\n%\n\n% Copyright (c) 2012 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% May 2012\n\nfunction w = logisticweighting(x, b, R)\n \n if ~exist('R', 'var'), R = [-1 1 -1 1]; end\n \n b = max(b, 1e-10); % Constrain b to a small value that does not cause\n % numerical problems\n \n [xmin xmax wmin wmax] = deal(R(1), R(2), R(3), R(4));\n xHalfRange = (xmax-xmin)/2;\n wHalfRange = (wmax-wmin)/2;\n M = (xmin+xmax)/2; % Midpoint of curve\n\n % We use a form of the generalised logistics function with asymptotes -A and\n % +A, and growth rate b.\n %\n % W(x) = A - 2*A/(1 + e^(-b*x))\n %\n % First, given the desired value of b, we solve for the value of A that will\n % generate a generalised logistics curve centred on (0,0) and passing\n % through (-xrange/2, -wrange/2) and (+xrange/2, +wrange/2)\n A = wHalfRange/(1 - 2/(1+exp(-b*xHalfRange)));\n \n % Apply an offset of M to x to shift the curve to the desired position\n % and add a vertical offset to obtain the desired weighting range\n w = A - 2*A./(1 + exp(-b*(x-M))) + (wmin+wHalfRange);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "cyclemix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Blender/cyclemix.m", "size": 9035, "source_encoding": "utf_8", "md5": "3290a5ce842ce329f1eb6607a37fd6af", "text": "% CYCLEMIX Multi-image blending over a cyclic sequence of images\n%\n% Usage: cyclemix(im, figNo, nodeLabel)\n%\n% Arguments:\n% im - A cell array of images to be blended. If omitted, or\n% empty, the user is prompted to select images via a file\n% dialog. \n% figNo - Optional figure number. \n% nodeLabel - Optional cell array of strings specifying the labels to\n% be associated with the nodes on the blending interface.\n%\n% This function sets up an interface consisting of a circle with equispaced\n% nodes around it corresponding to the input images to be blended. An\n% additional virtual node corresponding to the average of all the images is\n% placed at the centre of the circle. Positioning the mouse at some location\n% within the circle generates an interactive blend formed from the weighted sum\n% of the two image nodes that the mouse is between (in an angular sense) and\n% between the central average image according to the radial position of the\n% mouse.\n%\n% An application where this blending tool can be useful is to blend between a\n% sequence of images that have been filtered according to a parameter that is\n% cyclic, say an orientation filter.\n%\n% See also: LINIMIX, BILINIMIX, CLIQUEMIX, TERNARYMIX\n\n% Reference:\n% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.\n% \"Interactive Multi-Image Blending for Visualization and Interpretation\",\n% Computers & Geosciences 72 (2014) 147-155.\n% http://doi.org/10.1016/j.cageo.2014.07.010\n\n% Copyright (c) 2011-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% August 2011 Original version\n% March 2014 Cleanup and documentation\n\nfunction cyclemix(im, figNo)\n \n if ~exist('im', 'var'), im = []; end\n if ~exist('figNo', 'var') || isempty(figNo)\n fig = figure;\n else\n fig = figure(figNo); \n end\n\n [im, nImages, fname] = collectncheckimages(im);\n \n % Compute average image\n avim = zeros(size(im{1}));\n for n = 1:nImages\n avim = avim + im{n};\n end\n avim = avim/nImages;\n \n % Generate vertices of blending polygon interface\n deltaTheta = 2*pi/nImages;\n theta = [0:(nImages-1)] * deltaTheta;\n v = [cos(theta)\n sin(theta)];\n\n % Display 1st image and get handle to Cdata in the figure\n % Suppress display warnings for images that are large\n S = warning('off'); \n figure(fig), clf,\n imposition = [0.35 0.0 0.65 1.0];\n subplot('position', imposition);\n imshow(normalise(im{1}), 'border', 'tight');\n set(fig, 'NumberTitle', 'off') \n set(fig, 'name', ' CycleMix')\n set(fig, 'Menubar','none');\n imHandle = get(gca,'Children');\n warning(S);\n \n % Set up interface figure \n ah = subplot('position',[0.0 0.4 0.35 0.35]); \n\n h = circle([0 0], 1, 36, [0 0 1]);\n set(h,'linewidth',2)\n hold on\n plot(v(1,:), v(2,:), '.', 'color', [0 0 0], 'markersize', 40')\n plot(v(1,:), v(2,:), '.', 'color',[.9 .9 .9], 'markersize',20)\n \n radsc = 1.2;\n for n = 1:nImages\n if v(1,n) < -0.1\n text(v(1,n)*radsc, v(2, n)*radsc, namenpath(fname{n}), ...\n 'FontSize', 16, 'FontWeight', 'bold',...\n 'HorizontalAlignment','right');\n elseif v(1,n) > 0.1\n text(v(1,n)*radsc, v(2, n)*radsc, namenpath(fname{n}), ...\n 'FontSize', 16, 'FontWeight', 'bold',...\n 'HorizontalAlignment','left');\n else\n text(v(1,n)*radsc, v(2, n)*radsc, namenpath(fname{n}), ...\n 'FontSize', 16, 'FontWeight', 'bold',...\n 'HorizontalAlignment','center'); \n end\n end\n \n r = 1.25;\n axis ([-r r -r r]), axis off, axis equal\n\n % Set callback function\n set(fig,'WindowButtonDownFcn',@wbdcb);\n [rows, cols, ~] = size(im{1});\n setwindowsize(fig, [rows cols], imposition);\n \n % Set up custom pointer\n myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];\n myPointer(~myPointer) = NaN; \n\n fprintf('\\nLeft-click to toggle blending on and off.\\n'); \n blending = 0;\n hspot = 0;\n\n%---------------------------------------------------------------- \n% Window button down callback\nfunction wbdcb(src,evnt)\n if strcmp(get(src,'SelectionType'),'normal')\n if ~blending % Turn blending on\n blending = 1;\n set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...\n 'PointerShapeHotSpot',[9 9])\n set(src,'WindowButtonMotionFcn',@wbmcb)\n \n if hspot % For paper illustration\n delete(hspot);\n end \n \n else % Turn blending off\n blending = 0;\n set(src,'Pointer','arrow')\n set(src,'WindowButtonMotionFcn','')\n \n % For paper illustration\n cp = get(ah,'CurrentPoint');\n x = cp(1,1);\n y = cp(1,2);\n if gca == ah\n hspot = plot(x, y, '.', 'color', [0 0 0], 'Markersize', 40'); \n end\n end\n \n end \nend\n\n%----------------------------------------------------------------\n% Window button move call back\nfunction wbmcb(src,evnt)\n cp = get(ah,'CurrentPoint');\n x = cp(1,1);\n y = cp(1,2);\n blend(x,y)\nend\n \n%-------------------------------------------------------------------\nfunction blend(x,y)\n \n % Get radius and angle of cursor relative to centre of circle\n radius = min(norm([x y]), .999); % Clamp radius to a max of 1\n ang = atan2(y,x);\n \n % Define a sigmoidal weighting function for radius values ranging from 0 to\n % 1 yielding weights that range from 1 to 0. This is the weighting that is\n % applied to the average image associated with the centre of the circular\n % interface. Using a sigmoidal function provides a slight 'flat spot' at\n % the centre (and edges) of the interface where the weights do not change\n % much. This makes the interface a bit easier to use near the centre\n % which otherwise forms a singularity with respect to cursor movements.\n radialWeight = logisticweighting(radius, 2^4, [0 1 1 0]);\n \n % Compute angular distance to all vertices\n ds = sin(theta) * cos(ang) - cos(theta) * sin(ang); % Difference in sine.\n dc = cos(theta) * cos(ang) + sin(theta) * sin(ang); % Difference in cosine.\n distTheta = abs(atan2(ds,dc)); % Absolute angular distance.\n \n % First form a 2-image blend from the two images that are on each side of\n % the cursor in an angular sense\n \n % Zero out angular distances > deltaTheta, these will correspond to nodes\n % that are not on each side of the cursor in an angular sense. There should\n % be only two non-zero elements after this.\n distTheta(distTheta > deltaTheta) = 0;\n \n % Form normalised angular blending weights.\n angularWeight = (deltaTheta-distTheta)/deltaTheta;\n \n % Identify the indices of the non-zero weights\n ind = find(distTheta); \n \n if length(ind) == 2\n blend = angularWeight(ind(1))*im{ind(1)} + angularWeight(ind(2))*im{ind(2)};\n elseif length(ind) == 1 % Unlikely, but possible.\n blend = angularWeight(ind(1))*im{ind(1)};\n end\n \n % Now form a 2-image blend between this image and the centre, average image.\n blend = (1-radialWeight)*blend + radialWeight*avim;\n \n blend = normalise(blend);\n set(imHandle,'CData', blend);\n \nend % end of blend\n\n%---------------------------------------------------------------------\nend % of main function and nested functions\n \n%------------------------------------------------------------------------\n% Function to set up window size nicely\nfunction setwindowsize(fig, imsze, imposition)\n \n screen = get(0,'ScreenSize');\n scsze = [screen(4) screen(3)];\n window = get(fig, 'Position');\n \n % Set window height to match image height\n window(4) = imsze(1);\n \n % Set window width to match image width allowing for fractional width of\n % image specified in imposition\n window(3) = imsze(2)/imposition(3);\n \n % Check size of window relative to screen. If larger rescale the window\n % size to fit 80% of screen dimension.\n winsze = [window(4) window(3)];\n ratio = max(winsze./scsze);\n if ratio > 1\n winsze = winsze/ratio * 0.8;\n end\n \n window(3:4) = [winsze(2) winsze(1)];\n set(fig, 'Position', window);\n \nend\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "swipe.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Blender/swipe.m", "size": 4265, "source_encoding": "utf_8", "md5": "127b092d90f1b8edeb9f165489e6bcb0", "text": "% SWIPE Interactive image swiping between 2, 3 or 4 images.\n%\n% Usage swipe(im, figNo)\n%\n% Arguments: im - 2D Cell array of images to be blended. Two, three or four\n% images can be blended.\n% figNo - Optional figure window number to use.\n%\n% Click in the image to toggle in/out of swiping mode. Move the cursor \n% within the image to swipe between the input images.\n%\n% See also: TERNARYMIX, CYCLEMIX, CLIQUEMIX, LINIMIX, BILINIMIX\n%\n\n% Copyright (c) 2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% June 2013\n \nfunction swipe(im, figNo) \n \n if ~exist('im', 'var'), im = []; end\n [im, nImages, fname] = collectncheckimages(im);\n \n if isempty(im) % Cancel\n return;\n end\n \n if length(im) < 2 || length(im) > 4\n error('Can only swipe between 2, 3 or 4 images');\n end\n \n [rows,cols,~] = size(im{1});\n \n fprintf('\\nClick in the image to toggle in/out of swiping mode \\n');\n fprintf('Move the cursor within the image to \\n');\n fprintf('swipe between the input images\\n\\n');\n \n % Set up figure and handles to image data\n if exist('figNo','var')\n fig = figure(figNo); clf;\n else\n fig = figure;\n end\n \n S = warning('off');\n imshow(im{1});\n% imshow(im{1}, 'border', 'tight');\n drawnow\n warning(S)\n \n set(fig, 'name', 'CET Image Swiper')\n set(fig,'Menubar','none');\n ah = get(fig,'CurrentAxes');\n imHandle = get(ah,'Children'); \n \n % Set up button down callback\n set(fig,'WindowButtonDownFcn',@wbdcb);\n swiping = 0;\n \n % Set up custom pointer\n myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];\n myPointer(~myPointer) = NaN;\n \n \n%----------------------------------------------------------------------- \n% Window button down callback. This toggles swiping on and off changing the\n% cursor appropriately.\n\nfunction wbdcb(src,evnt)\n if strcmp(get(src,'SelectionType'),'normal')\n if ~swiping % Turn swiping on\n swiping = 1;\n set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...\n 'PointerShapeHotSpot',[8 8])\n set(src,'WindowButtonMotionFcn',@wbmcb)\n \n else % Turn swiping off\n swiping = 0;\n set(src,'Pointer','arrow')\n set(src,'WindowButtonMotionFcn','')\n end\n end\nend \n\n%----------------------------------------------------------------------- \n% Window button move call back\n\nfunction wbmcb(src,evnt)\n cp = round(get(ah,'CurrentPoint'));\n x = cp(1,1); y = cp(1,2);\n swipe(x, y)\nend\n\n%-----------------------------------------------------------------------\nfunction swipe(x, y)\n \n % Clamp x and y to image limits\n x = max(1,x); x = min(cols,x); \n y = max(1,y); y = min(rows,y); \n \n % Construct swipe image from the input images\n if length(im) == 2; % Vertical swipe between 2 images\n swipeim = [im{1}(1:y, :, :)\n im{2}(y+1:end, :, :)];\n \n % Three images. 1st image occupies top half, swiped vertically. 2nd and\n % 3rd images share bottom half and are swiped horizontally.\n elseif length(im) == 3;\n swipeim = [ im{1}(1:y, :, :)\n im{2}(y+1:end, 1:x, :) im{3}(y+1:end, x+1:end, :)];\n \n % Four input images placed in quadrants\n elseif length(im) == 4;\n swipeim = [im{1}(1:y, 1:x, :) im{2}(1:y, x+1:end, :)\n im{3}(y+1:end, 1:x, :) im{4}(y+1:end, x+1:end, :)];\n end\n \n set(imHandle,'CData', swipeim);\n \n set(fig, 'name', 'CET Image Swiper') \nend \n\n%---------------------------------------------------------------------------\nend % of swipe\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "cliquemix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Blender/cliquemix.m", "size": 15564, "source_encoding": "utf_8", "md5": "8d782463d2676131bc2e13681c3bd26e", "text": "% CLIQUEMIX Multi-image blending and swiping over a clique\n%\n% Function allows blending and swiping between any pair within a collection of images\n%\n% Usage: cliquemix(im, B, figNo, nodeLabel)\n%\n% Arguments:\n% im - A cell array of images to be blended. If omitted, or\n% empty, the user is prompted to select images via a file\n% dialog. \n% B - Parameter controlling the weighting function when\n% blending between two images.\n% B = 0 Linear transition between images (default)\n% B = 2^4 Sigmoidal transition at midpoint.\n% B = 2^10 Near step-like transition at midpoint.\n% figNo - Optional figure number. \n% nodeLabel - Optional cell array of strings specifying the labels to\n% be associated with the nodes on the blending interface.\n%\n% This function sets up an interface consisting of a regular polygon with nodes\n% corresponding to the input images to be blended. Each node is conected to\n% every other node forming a clique. Positioning the cursor along any of the\n% edges joining two nodes will generate an interactive blend formed from the\n% 2-image blend of the images connected by the edge. As the mouse is moved\n% around the interface the blend snaps to the edge closest to the mouse position\n% (with some hysteresis to reduce unwanted transitions). A right-click on any\n% edge will lock the blending to that edge irrespective of the mouse position.\n% A second right-click will unlock the edge. \n%\n% Hitting 's' toggles between blending and swiping mode.\n%\n% This tool allows you to compare any image with any other image in a collection\n% with ease. However once you go beyond about 8 images the difference in edge\n% lengths on the interface starts to make the tool less natural to use.\n%\n% See also: LINIMIX, BILINIMIX, TERNARYMIX, BINARYMIX, CYCLEMIX, LOGISTICWEIGHTING\n\n% Reference:\n% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.\n% \"Interactive Multi-Image Blending for Visualization and Interpretation\",\n% Computers & Geosciences 72 (2014) 147-155.\n% http://doi.org/10.1016/j.cageo.2014.07.010\n\n% Copyright (c) 2011-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% August 2011 - Original version\n% May 2012 - General rework and cleanup\n% March 2014 - More tidying up\n% December 2014 - Incorporation of swiping option\n\nfunction cliquemix(im, B, figNo, nodeLabel)\n \n if ~exist('B', 'var') || isempty(B), B = 0; end % linear blending\n if ~exist('im', 'var'), im = []; end\n if ~exist('figNo', 'var') || isempty(figNo)\n fig = figure;\n else\n fig = figure(figNo); \n end\n \n [im, nImages, fname] = collectncheckimages(im);\n \n % If interface node names have not been supplied use default image names\n if ~exist('nodeLabel', 'var') \n nodeLabel = fname;\n end\n\n % Display 1st image and get handle to Cdata in figure(2)\n % Suppress display warnings for images that are large\n S = warning('off');\n figure(fig), clf;\n imposition = [0.35 0.0 0.65 1.0];\n subplot('position', imposition);\n imshow(im{1},'border', 'tight'); drawnow\n imHandle = get(gca,'Children');\n warning(S)\n \n % Draw the interface clique and label vertices \n ah = subplot('position',[0.0 0.4 0.35 0.35]); \n\n % Generate vertices of blending polygon interface\n deltaTheta = 2*pi/nImages;\n theta = [0:(nImages-1)] * deltaTheta + pi/2;\n v = [cos(theta)\n sin(theta)];\n\n % Construct list of edges that link the vertices\n eNo = 0;\n for n = 1:(nImages-1)\n for m = (n+1):nImages\n eNo = eNo+1;\n edge{eNo}.n1 = n;\n edge{eNo}.n2 = m;\n edge{eNo}.v1 = v(:,n);\n edge{eNo}.v2 = v(:,m);\n \n edge{eNo}.h = ...\n line([edge{eNo}.v1(1) edge{eNo}.v2(1)], ...\n [edge{eNo}.v1(2) edge{eNo}.v2(2)], ...\n 'LineWidth', 2);\n end\n end\n \n hold on\n plot(v(1,:), v(2,:), '.', 'color', [0 0 0], 'Markersize', 30')\n hold off\n\n radsc = 1.2;\n for n = 1:nImages\n if v(1,n) < -0.1\n text(v(1,n)*radsc, v(2, n)*radsc, namenpath(nodeLabel{n}), ...\n 'FontSize', 16, 'FontWeight', 'bold',...\n 'HorizontalAlignment','right');\n elseif v(1,n) > 0.1\n text(v(1,n)*radsc, v(2, n)*radsc, namenpath(nodeLabel{n}), ...\n 'FontSize', 16, 'FontWeight', 'bold',...\n 'HorizontalAlignment','left');\n else\n text(v(1,n)*radsc, v(2, n)*radsc, namenpath(nodeLabel{n}), ...\n 'FontSize', 16, 'FontWeight', 'bold',...\n 'HorizontalAlignment','center'); \n end\n end\n\n r = 1.2; axis ([-r r -r r]), axis off, axis equal\n \n % Set callback function and window title\n [rows,cols,chan] = size(im{1});\n setwindowsize(fig, [rows cols], imposition);\n \n set(fig, 'WindowButtonDownFcn',@wbdcb);\n set(fig, 'KeyReleaseFcn', @keyreleasecb);\n set(fig, 'NumberTitle', 'off') \n set(fig, 'name', ' CliqueMix')\n set(fig, 'Menubar','none');\n \n % Set up custom pointer\n myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];\n myPointer(~myPointer) = NaN; \n \n blending = 0;\n locked = 0; \n currentEdge = 1;\n blendswipe = 'blend'; % Start in blending mode \n \n fprintf('\\nLeft-click to toggle blending on and off.\\n');\n fprintf('Right-click to toggle edge locking on and off.\\n');\n fprintf('A right-click will also turn blending on if it was off\\n');\n fprintf('Hit ''s'' to toggle between swiping and blending modes.\\n\\n');\n \n%--------------------------------------------------------------------\n% Window button down callback\nfunction wbdcb(src,evnt)\n \n click = get(src,'SelectionType');\n \n % Left click toggles blending\n if strcmp(click,'normal')\n if ~blending % Turn blending on\n blending = 1;\n set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...\n 'PointerShapeHotSpot',[9 9]) \n set(src,'WindowButtonMotionFcn',@wbmcb)\n \n else % Turn blending off and unlock\n blending = 0;\n locked = 0; \n set(src,'Pointer','arrow')\n set(src,'WindowButtonMotionFcn','')\n set(edge{currentEdge}.h, 'color', [0 0 1]);\n end\n \n % Right click toggles edge locking\n elseif strcmp(click,'alt')\n if blending && ~locked\n % Lock to closest edge\n e = closestedge;\n if e ~= currentEdge\n set(edge{currentEdge}.h, 'color', [0 0 1]);\n currentEdge = e;\n end\n set(edge{currentEdge}.h, 'color', [1 0 0]);\n locked = 1;\n \n elseif ~blending && ~locked\n % Turn blending on and lock to closest edge\n blending = 1;\n locked = 1;\n set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...\n 'PointerShapeHotSpot',[9 9]) \n set(src,'WindowButtonMotionFcn',@wbmcb) \n\n currentEdge = closestedge;\n set(edge{currentEdge}.h, 'color', [1 0 0]);\n \n elseif locked % Unlock\n locked = 0;\n set(edge{currentEdge}.h, 'color', [0 0.5 0]);\n end\n end\nend\n \n%--------------------------------------------------------------------\n% Window button move call back\nfunction wbmcb(src,evnt)\n cp = get(ah,'CurrentPoint');\n x = cp(1,1); y = cp(1,2);\n \n [e, n1, n2, frac] = activeedge(x,y);\n \n if strcmp(blendswipe, 'blend')\n w = logisticweighting(frac, B,[0 1 0 1]);\n \n blend = w*im{n1} + (1-w)*im{n2};\n else\n blend = swipe(n1, n2, frac);\n end\n set(imHandle,'CData', blend); \nend\n\n%---------------------------------------------------------------------\n% ACTIVEEDGE\n% Establish the edge in the graph that is currently 'active'. Return the node\n% numbers, n1 and n2, that define the edge and the fractional distance of the\n% projected cursor point along the edge from n1 to n2\n%\n% This version maintains a ring buffer that records the edge that the cursor\n% is closest to for the last N instantiations of this function. The 'active'\n% edge is set to the edge number that appears most frequently in the ring\n% buffer (the mode). Seems to work quite well however the bahaviour is\n% dependent on the speed of the computer. It would be good to have something\n% that was tied to actual time.\n\nfunction [e, n1, n2, frac] = activeedge(x,y)\n\n N = 30; % Buffer size\n persistent ebuf; % Buffer for recording which edge we have been on\n persistent ptr; % Pointer into buffer.\n \n if isempty(ebuf), ebuf = currentEdge*ones(1,N); end \n if isempty(ptr), ptr = 0; end \n \n if locked\n v1 = edge{currentEdge}.v1; v2 = edge{currentEdge}.v2; \n [eDist, pfrac] = dist2segment(v1, v2, x, y);\n\n e = currentEdge;\n n1 = edge{currentEdge}.n1;\n n2 = edge{currentEdge}.n2;\n frac = 1-pfrac;\n \n else % Not locked. Find edge closest to x,y\n\n eDist = zeros(1,length(edge));\n pfrac = zeros(1,length(edge)); \n \n for n = 1:length(edge)\n v1 = edge{n}.v1; v2 = edge{n}.v2; \n [eDist(n), pfrac(n)] = dist2segment(v1, v2, x, y);\n end\n \n [minDist, ind] = min(eDist);\n ptr = mod(ptr+1,N-1);\n ebuf(ptr+1) = ind;\n \n % Set edge to be the one which is most common within ebuf\n e = mode(ebuf);\n \n if e ~= currentEdge\n set(edge{currentEdge}.h, 'color', [0 0 1]);\n currentEdge = e;\n end\n \n set(edge{currentEdge}.h, 'color', [0 0.5 0]);\n \n % Identify the indices of the images associated with this edge and\n % also calculate the fractional position we are along this edge for\n % the blending\n n1 = edge{e}.n1;\n n2 = edge{e}.n2;\n frac = 1-pfrac(e);\n end\nend % of activeedge\n\n\n%------------------------------------------------------------------------\n% Find edge closest to cursor\nfunction e = closestedge\n\n cp = get(ah,'CurrentPoint');\n x = cp(1,1); y = cp(1,2);\n eDist = zeros(1,length(edge));\n \n for n = 1:length(edge)\n v1 = edge{n}.v1; v2 = edge{n}.v2; \n eDist(n) = dist2segment(v1, v2, x, y);\n end\n \n [~, e] = min(eDist);\nend\n\n%------------------------------------------------------------------------\n% Given an x,y coordinate and a line segment with end points v1 and v2. Find the\n% closest point on the line segment. Return the distance to the line segment\n% and the fractional distance of the closest point on the segment from v1 to v2.\n\nfunction [d, frac] = dist2segment(v1, v2, x, y)\n\n xy = [x;y];\n v1v2 = v2-v1; % Vector from v1 to v2\n D = norm(v1v2); % Distance v1 to v2\n v1xy = xy-v1; % Vector from v1 to xy\n \n % projection of v1xy on unit vector v1v2\n proj = dot(v1v2/D, v1xy);\n \n if proj < 0 % Closest point is v1\n d = norm(v1xy);\n frac = 0;\n elseif proj > D % Closest point is v2\n d = norm(xy-v2);\n frac = 1;\n else % Somewhere in the middle\n pt = v1 + proj*v1v2/D;\n d = norm(xy-pt);\n frac = proj/D;\n end \n\nend % of dist2segment\n \n%------------------------------------------------------------------------\n% Function to set up window size nicely\nfunction setwindowsize(fig, imsze, imposition)\n \n screen = get(0,'ScreenSize');\n scsze = [screen(4) screen(3)];\n window = get(fig, 'Position');\n \n % Set window height to match image height\n window(4) = imsze(1);\n \n % Set window width to match image width allowing for fractional width of\n % image specified in imposition\n window(3) = imsze(2)/imposition(3);\n \n % Check size of window relative to screen. If larger rescale the window\n % size to fit 80% of screen dimension.\n winsze = [window(4) window(3)];\n ratio = max(winsze./scsze);\n if ratio > 1\n winsze = winsze/ratio * 0.8;\n end\n \n window(3:4) = [winsze(2) winsze(1)];\n set(fig, 'Position', window);\n \nend\n\n%-----------------------------------------------------------------------\n% Generate swipe image given the two end nodes of the active edge and the\n% fractional distance along the edge.\n\nfunction swipeim = swipe(n1, n2, frac)\n \n % Form vectors from the centre of the image to the corners and construct\n % the dot product between v(:,n2)-v(:,n1) to determine the extreme\n % corners of the image that are relevant\n corner = [1 cols cols 1\n 1 1 rows rows];\n\n % Vectors from centre of image to top-left, top-right, bottom-right,\n % bottom-left corners.\n c = corner - repmat([cols/2; rows/2], 1, 4);\n \n % Vector from node 1 to node 2\n d = v(:,n2) - v(:,n1);\n d(2) = -d(2); % Negate y to match image coordinate frame\n d1 = d/norm(d);\n \n % Find c2, the index of corner direction maximally alligned with d\n dotcd = c'*d; % Dot product between c and d\n [~,c1] = max(dotcd);\n c2 = mod((c1-1)-2, 4) + 1; % Opposite corner to c2\n c1c2 = corner(:,c2)-corner(:,c1);\n\n % Compute distance from c1 to c2 in the direction of d\n dist = dot(c1c2, d1); \n \n % Construct location that is 'frac' units along line parallel to\n % v(:,n2)-v(:,n1) between the two extreme image corners\n % This has to be frac*dist from c1 to c2\n p = corner(:,c1) + frac*dist*d1; \n\n % Cut the image in two at the point along a line perpendicular to\n % v(:,n2)-v(:,n1) and construct a mask for defining the image parts to be\n % combined. \n % Form equation (p - [c;r]).d\n % mask is where this value is > 0 giving all image points closest to n2\n [x,y] = meshgrid(1:cols, 1:rows);\n x = p(1) - x;\n y = p(2) - y;\n mask = (x*d(1) + y*d(2)) < 0;\n \n swipeim = im{n2};\n if chan == 1\n swipeim(mask) = im{n1}(mask);\n else % Colour\n swipeim = zeros(rows,cols,chan);\n for ch = 1:chan\n swipeim(:,:,ch) = im{n1}(:,:,ch) .* mask + im{n2}(:,:,ch) .* ~mask;\n end\n end\n \nend \n\n%-----------------------------------------------------------------------\n% Key Release callback\n% If 's' is pressed system toggles between swiping and blending modes\n\nfunction keyreleasecb(src,evnt)\n \n if evnt.Character == 's' % Swipe/Blend toggle\n if strcmp(blendswipe, 'swipe')\n blendswipe = 'blend';\n else\n blendswipe = 'swipe';\n end\n end\n \n wbmcb(src,evnt); % update the display\nend \n\n%------------------------------------------------------------------------\nend % of everything\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "collectncheckimages.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Blender/collectncheckimages.m", "size": 5392, "source_encoding": "utf_8", "md5": "7f3d2bd790c314d39156748f34dce0ed", "text": "% COLLECTNCHECKIMAGES Collects and checks images prior to blending\n%\n% Usage: [im, nImages, fname, pathname] = collectncheckimages(im)\n%\n% Used by image blending functions\n%\n% Argument: im - Cell arry of images. If omitted a dialog box is\n% presented so that images can be selected interactively.\n%\n% Returns: im - Cell array of images of consistent size and colour class.\n% If input images are of different sizes the images are\n% trimmed to the size of the smallest image. If some\n% images are colour any greyscale images are converted to\n% colour by copying the image to the R G and B channels.\n% nImages - Number of images in the cell array.\n% fname - A cell array of the filenames of the images if they were\n% interactively selected via a dialog box.\n% pathname - The file path if the images were selected via a dialog\n% box.\n%\n% If the image selection via a dialog box is cancelled all values are returned\n% as empty cell arrays or 0\n%\n% See also: LINIMIX, BILINIMIX, TERNARYMIX, CLIQUEMIX, CYCLEMIX\n\n% Copyright (c) 2012-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% May 2012 - Original version\n% March 2014 - Provison for 'im' being a 2D cell array\n% August 2014 - Fix to avoid normalisation of colour images\n\nfunction [im, nImages, fname, pathname] = collectncheckimages(im)\n \n if ~exist('im', 'var') | isempty(im) % We need to select several images\n \n fprintf('Select several images...\\n');\n [fname, pathname] = uigetfile({'*.png';'*.tiff';'*.jpg'},...\n 'MultiSelect','on');\n\n if isnumeric(fname) && fname == 0 % Selection was cancelled\n im = {};\n nImages = 0;\n fname = {};\n pathname = {};\n return\n end\n \n % If single file has been selected place its name in a single element\n % cell array so that it is consistent with the rest of the code.\n if isa(fname, 'char')\n tmp = fname;\n fname = {};\n fname{1} = tmp;\n end\n \n nImages = length(fname);\n im = cell(1,nImages);\n \n for n = 1:nImages\n im{n} = double(imread([pathname fname{n}]));\n end\n \n elseif iscell(im) % A cell array of images to blend has been supplied. \n\n % Give each image a nominal name\n nImages = prod(size(im)); % (im might be a 2D cell array of images)\n fname = cell(1,nImages);\n for n = 1:nImages\n fname{n} = sprintf('%d', n);\n end\n pathname = '';\n end \n \n if nImages == 1 % See if we have a multi-channel image\n [rows, cols, chan] = size(im{1});\n \n assert(chan > 1, ...\n 'Input must be a cell arrayof images, or a multi-channel image');\n \n % Copy the channels out into a cell array of separate images and\n % generate nominal names.\n nImages = chan;\n tmp = im{1}; \n im = cell(1,nImages);\n fname = cell(1,nImages);\n for n = 1:nImages\n im{n} = tmp(:,:,n);\n fname{n} = sprintf('Band %d', n);\n end\n pathname = '';\n end \n\n % Check sizes of images\n rows = zeros(nImages,1); cols = zeros(nImages,1); chan = zeros(nImages,1);\n for n = 1:nImages\n [rows(n) cols(n), chan(n)] = size(im{n});\n end\n\n % If necessary trim all images down to the size of the smallest image and\n % give a warning. Given that the imput images need to be registered this\n % should perhaps be classed as an error.\n if ~all(rows == rows(1)) || ~all(cols == cols(1)) \n fprintf('Not all images are the same size\\n');\n fprintf('Trimming images to the match the smallest\\n');\n \n minrows = min(rows); mincols = min(cols);\n for n = 1:nImages\n im{n} = im{n}(1:minrows, 1:mincols, :); \n end\n end\n\n % If one image is RGB ensure every image is stored as rgb, even if it\n % is greyscale. \n if ~(all(chan == 3) || all(chan == 1))\n for n = 1:nImages\n if chan(n) == 1\n % Replicate image in R, G and B channels\n im{n} = repmat(im{n},[1 1 3]); \n end\n end\n end\n \n % Finally normalise images as needed and ensure class is double. Note that\n % if an input image had three channels we assume it is already normalised\n % 0-255 (if uint8) or 0-1 (if double) hence we only normalise a double image\n % if it originally only had one channel.\n for n = 1:nImages\n if strcmp(class(im{n}),'uint8')\n im{n} = double(im{n})/255;\n elseif chan(n) == 1\n im{n} = normalise(double(im{n})); \n end\n end"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "linimix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Blender/linimix.m", "size": 6472, "source_encoding": "utf_8", "md5": "c68afc24d26a59ce58a2fff608c974ee", "text": "% LINIMIX An Interactive Image for viewing multiple images\n%\n% Usage: linimix(im, B, figNo, XY)\n%\n% Arguments: im - 1D Cell array of images to be blended. If this is not\n% supplied, or is empty, the user is prompted with a file\n% dialog to select a series of images.\n% B - Parameter controlling the weighting function when\n% blending between two images.\n% B = 0 Linear transition between images (default)\n% B = 2^4 Sigmoidal transition at midpoint.\n% B = 2^10 Near step-like transition at midpoint.\n% figNo - Optional figure window number to use.\n% XY - Character 'X' or 'Y' indicating whether x or y movements\n% of the cursor controls the blending. Defaults to 'Y'.\n%\n% This function provides an 'Interactive Image'. It is intended to allow\n% efficient visual exploration of a sequence of images that have been processed\n% with a series of different parameter values, for example, scale. The vertical\n% position of the cursor within the image controls the linear blend between\n% images. With the cursor at the top the first image is displayed, at the\n% bottom the last image is displayed. At positions in between blends of\n% intermediate images are dislayed. \n%\n% Click in the image to toggle in/out of blending mode. Move the cursor up and\n% down within the image to blend between the input images.\n%\n% Use BILINIMIX if you want the horizontal position of the cursor to be used\n% too. This will allow visual exploration of a sequence of images controlled by\n% two different processing parameters. Alternatively one could blend between\n% images of two different modalities over some varing parameter, say scale.\n%\n% See also: BILINIMIX, TERNARYMIX, CLIQUEMIX, CYCLEMIX, LOGISTICWEIGHTING\n\n% Reference:\n% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.\n% \"Interactive Multi-Image Blending for Visualization and Interpretation\",\n% Computers & Geosciences 72 (2014) 147-155.\n% http://doi.org/10.1016/j.cageo.2014.07.010\n\n% Copyright (c) 2012-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% March 2012\n% March 2014 - Allow horizontal or vertical mouse movements to control blending\n\nfunction linimix(im, B, figNo, XY)\n\n if ~exist('im', 'var'), im = []; end\n [im, nImages, fname] = collectncheckimages(im);\n\n if ~exist('B', 'var') || isempty(B), B = 0; end\n if exist('figNo','var')\n fig = figure(figNo); clf;\n else\n fig = figure;\n end\n if ~exist('XY', 'var'), XY = 'Y'; end\n XY = upper(XY);\n \n % Generate nodes for the multi-image linear blending\n [rows,cols,~] = size(im{1});\n if XY == 'Y'\n v = round([0:1/(nImages-1):1] * rows); \n elseif XY == 'X'\n v = round([0:1/(nImages-1):1] * cols); \n else\n error('XY must be ''x'' or ''y'' ')\n end\n\n fprintf('\\nClick in the image to toggle in/out of blending mode \\n');\n fprintf('Move the cursor within the image to blend between the input images.\\n\\n');\n \n S = warning('off');\n imshow(im{ max(1,fix(nImages/2)) }, 'border', 'tight');\n drawnow\n warning(S)\n \n ah = get(fig,'CurrentAxes');\n imHandle = get(ah,'Children'); % Handle to image data\n \n % Set up button down callback and window title\n set(fig,'WindowButtonDownFcn',@wbdcb);\n set(fig, 'NumberTitle', 'off')\n set(fig, 'name', 'CET Linear Image Blender')\n set(fig,'Menubar','none'); \n blending = 0;\n \n % Set up custom pointer\n myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];\n myPointer(~myPointer) = NaN;\n \n hspot = 0;\n hold on\n\n%----------------------------------------------------------------------- \n% Window button down callback. This toggles blending on and off changing the\n% cursor appropriately.\n\nfunction wbdcb(src,evnt)\n if strcmp(get(src,'SelectionType'),'normal')\n if ~blending % Turn blending on\n blending = 1;\n set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...\n 'PointerShapeHotSpot',[9 9])\n set(src,'WindowButtonMotionFcn',@wbmcb)\n \n if hspot % For paper illustration\n delete(hspot);\n end \n \n else % Turn blending off\n blending = 0;\n set(src,'Pointer','arrow')\n set(src,'WindowButtonMotionFcn','')\n \n % For paper illustration (need marker size of 95 if using export_fig)\n cp = get(ah,'CurrentPoint');\n x = cp(1,1);\n y = cp(1,2);\n hspot = plot(x, y, '.', 'color', [0 0 0], 'Markersize', 50'); \n \n end\n end\nend \n\n%----------------------------------------------------------------------- \n% Window button move call back\n\nfunction wbmcb(src,evnt)\n cp = get(ah,'CurrentPoint');\n if XY == 'Y'\n p = cp(1,2);\n p = max(0,p); p = min(rows,p); % clamp to range 0-rows\n else\n p = cp(1,1);\n p = max(0,p); p = min(cols,p); % clamp to range 0-cols\n end\n \n blend(p)\nend\n\n%-----------------------------------------------------------------------\nfunction blend(p)\n \n % Find distance from each of the vertices v\n dist = abs(v - p);\n \n % Find the two closest vertices\n [dist, ind] = sort(dist); \n \n % w1 is the fractional distance from the cursor to the 2nd image\n % relative to the distance between the 1st and 2nd images\n w1 = dist(2)/(dist(1)+dist(2));\n \n % Apply the logistics wighting function to w1 to obtain the desired\n % transition weighting\n w = logisticweighting(w1, B, [0 1 0 1]);\n \n blendim = w*im{ind(1)} + (1-w)*im{ind(2)};\n \n set(imHandle,'CData', blendim);\n set(fig, 'name', 'CET Image Blender');\nend \n\n%---------------------------------------------------------------------------\nend % of linimix\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "bilinimix.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/Blender/bilinimix.m", "size": 5635, "source_encoding": "utf_8", "md5": "f1768150812e05ba0dbf1f8ac2b8e2ec", "text": "% BILINIMIX An Interactive Image for viewing multiple images\n%\n% Usage: bilinimix(im, figNo)\n%\n% Arguments: im - 2D Cell array of greyscale images to be blended. \n% figNo - Optional figure window number to use.\n%\n% This function provides an 'Interactive Image'. It is intended to allow\n% efficient visual exploration of a sequence of images that have been processed\n% with a series of two different parameter values, for example, scale and image\n% mix. The horizontal and vertical position of the cursor within the image\n% controls the bilinear blend of the two parameters over the images. \n%\n% To achieve this you need to prepare a set of images that cover a coarsely\n% quantized range of properties you want to view. Think of these images as\n% being arranged in a 2D grid corresponding to the 2D cell array of images\n% supplied to the function. Positioning the cursor at some location within the\n% grid will result in a blended image being constructed from the bilinear\n% interpolation of the 4 images surrounding the cursor position.\n%\n% Click in the image to toggle in/out of blending mode. Move the cursor \n% within the image to blend between the input images.\n%\n% See also: LINIMIX, TERNARYMIX, CLIQUEMIX, CYCLEMIX, LOGISTICWEIGHTING\n%\n% Note this code is a bit rough in places but is still reasonably useful at this\n% stage. I suggest you stick with greyscale images at this stage.\n\n% Reference:\n% Peter Kovesi, Eun-Jung Holden and Jason Wong, 2014.\n% \"Interactive Multi-Image Blending for Visualization and Interpretation\",\n% Computers & Geosciences 72 (2014) 147-155.\n% http://doi.org/10.1016/j.cageo.2014.07.010\n\n% Copyright (c) 2012-2014 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% April 2012 - Original version\n% March 2014 - General cleanup\n\nfunction bilinimix(im, figNo)\n \n assert(iscell(im), 'Input images must be in a cell array');\n [gridRows gridCols] = size(im);\n\n [im, nImages, fname] = collectncheckimages(im); \n [minrows,mincols,~] = size(im{1,1});\n\n fprintf('\\nClick in the image to toggle in/out of blending mode \\n');\n fprintf('Move the cursor up-down and left-right within the image to \\n');\n fprintf('blend between the input images\\n\\n');\n\n if exist('figNo','var')\n fig = figure(figNo); clf\n else\n fig = figure;\n end\n \n S = warning('off');\n imshow(im{ max(1,fix(nImages/2)) }, 'border', 'tight');\n drawnow\n warning(S)\n\n\n ah = get(fig,'CurrentAxes');\n imHandle = get(ah,'Children'); % Gives access to Cdata in the figure\n\n % Set up button down callback and window title \n set(fig, 'WindowButtonDownFcn',@wbdcb);\n set(fig, 'NumberTitle', 'off')\n set(fig, 'name', 'CET Bilinear Image Blender') \n set(fig, 'Menubar','none');\n blending = 0;\n \n % Set up custom pointer\n myPointer = [circularstruct(7) zeros(15,1); zeros(1, 16)];\n myPointer(~myPointer) = NaN;\n\n hspot = 0;\n hold on\n \n%----------------------------------------------------------------------- \n% Window button down callback\nfunction wbdcb(src,evnt)\n if strcmp(get(src,'SelectionType'),'normal')\n if ~blending % Turn blending on\n blending = 1;\n set(src,'Pointer','custom', 'PointerShapeCData', myPointer,...\n 'PointerShapeHotSpot',[9 9])\n set(src,'WindowButtonMotionFcn',@wbmcb)\n \n if hspot % For paper illustration\n delete(hspot);\n end\n \n else % Turn blending off\n blending = 0;\n set(src,'Pointer','arrow')\n set(src,'WindowButtonMotionFcn','')\n \n % For paper illustration (need marker size of 95 if using export_fig)\n cp = get(ah,'CurrentPoint');\n x = cp(1,1);\n y = cp(1,2);\n hspot = plot(x, y, '.', 'color', [0 0 0], 'Markersize', 50'); \n end\n end\nend \n\n%----------------------------------------------------------------------- \n% Window button move call back\nfunction wbmcb(src,evnt)\n cp = get(ah,'CurrentPoint');\n x = cp(1,1); y = cp(1,2);\n blend(x, y)\nend\n\n%-----------------------------------------------------------------------\nfunction blend(x, y)\n \n % Clamp x and y to image limits\n x = max(0,x); x = min(mincols,x); \n y = max(0,y); y = min(minrows,y); \n \n % Compute grid coodinates of (x,y)\n % im{1,1} im{1,2} ... im{1, gridCols}\n % .. .. ..\n % im{gridRows,1} .. ... im{gridRows, gridCols}\n gx = x/mincols * (gridCols-1) + 1;\n gy = y/minrows * (gridRows-1) + 1;\n \n % Compute bilinear interpolation between the images\n gxf = floor(gx); gxc = ceil(gx);\n gyf = floor(gy); gyc = ceil(gy);\n\n frac = gxc-gx;\n blendyf = (frac)*im{gyf,gxf} + (1-frac)*im{gyf,gxc};\n blendyc = (frac)*im{gyc,gxf} + (1-frac)*im{gyc,gxc};\n\n frac = gyc-gy;\n blendim = (frac)*blendyf + (1-frac)*blendyc;\n \n set(imHandle,'CData', blendim);\n \nend \n\n%---------------------------------------------------------------------------\nend % of bilinimix\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "findendsjunctions.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/LineSegments/findendsjunctions.m", "size": 3885, "source_encoding": "utf_8", "md5": "1c766254222e0b8fd5326786249247bf", "text": "% FINDENDSJUNCTIONS - find junctions and endings in a line/edge image\n%\n% Usage: [rj, cj, re, ce] = findendsjunctions(edgeim, disp)\n% \n% Arguments: edgeim - A binary image marking lines/edges in an image. It is\n% assumed that this is a thinned or skeleton image \n% disp - An optional flag 0/1 to indicate whether the edge\n% image should be plotted with the junctions and endings\n% marked. This defaults to 0.\n%\n% Returns: rj, cj - Row and column coordinates of junction points in the\n% image. \n% re, ce - Row and column coordinates of end points in the\n% image.\n%\n% See also: EDGELINK\n%\n% Note I am not sure if using bwmorph's 'thin' or 'skel' is best for finding\n% junctions. Skel can result in an image where multiple adjacent junctions are\n% produced (maybe this is more a problem with this junction detection code).\n% Thin, on the other hand, can produce different output when you rotate an image\n% by 90 degrees. On balance I think using 'thin' is better. Skeletonisation and\n% thinning is surprisingly awkward.\n\n% Copyright (c) 2006-2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% November 2006 - Original version\n% May 2013 - Call to bwmorph to ensure image is thinned was removed as\n% this might cause problems if the image used to find\n% junctions is different from the image used for, say,\n% edgelinking \n\nfunction [rj, cj, re, ce] = findendsjunctions(b, disp)\n\n if nargin == 1\n\tdisp = 0;\n end\n \n % Set up look up table to find junctions. To do this we use the function\n % defined at the end of this file to test that the centre pixel within a 3x3\n % neighbourhood is a junction.\n lut = makelut(@junction, 3);\n junctions = applylut(b, lut);\n [rj,cj] = find(junctions);\n \n % Set up a look up table to find endings. \n lut = makelut(@ending, 3);\n ends = applylut(b, lut);\n [re,ce] = find(ends); \n\n if disp \n\tshow(edgeim,1), hold on\n\tplot(cj,rj,'r+')\n\tplot(ce,re,'g+') \n end\n\n%----------------------------------------------------------------------\n% Function to test whether the centre pixel within a 3x3 neighbourhood is a\n% junction. The centre pixel must be set and the number of transitions/crossings\n% between 0 and 1 as one traverses the perimeter of the 3x3 region must be 6 or\n% 8.\n%\n% Pixels in the 3x3 region are numbered as follows\n%\n% 1 4 7\n% 2 5 8\n% 3 6 9\n\nfunction b = junction(x)\n \n a = [x(1) x(2) x(3) x(6) x(9) x(8) x(7) x(4)]';\n b = [x(2) x(3) x(6) x(9) x(8) x(7) x(4) x(1)]'; \n crossings = sum(abs(a-b));\n \n b = x(5) && crossings >= 6;\n \n%----------------------------------------------------------------------\n% Function to test whether the centre pixel within a 3x3 neighbourhood is an\n% ending. The centre pixel must be set and the number of transitions/crossings\n% between 0 and 1 as one traverses the perimeter of the 3x3 region must be 2.\n%\n% Pixels in the 3x3 region are numbered as follows\n%\n% 1 4 7\n% 2 5 8\n% 3 6 9\n\nfunction b = ending(x)\n a = [x(1) x(2) x(3) x(6) x(9) x(8) x(7) x(4)]';\n b = [x(2) x(3) x(6) x(9) x(8) x(7) x(4) x(1)]'; \n crossings = sum(abs(a-b));\n \n b = x(5) && crossings == 2;\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "selectseg.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/LineSegments/selectseg.m", "size": 3097, "source_encoding": "utf_8", "md5": "bdbe2a909309c465b0131e308d8ddc32", "text": "% SELECTSEG - Interactive selection of linesegments with mouse.\n%\n% Usage: segs = selectseg(seglist);\n% \n% seglist - an Nx4 array storing line segments in the form\n% [x1 y1 x2 y2\n% x1 y1 x2 y2\n% . . ] etc \n%\n%\n% See also: EDGELINK, LINESEG, MAXLINEDEV, MERGESEG\n%\n\n% Copyright (c) 2000-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% December 2000\n\nfunction segs = selectseg(seglist);\n\nsegs = [];\nselectedSegs = [NaN];\n\nfigure(1), clf, drawseg(seglist,1);\n\n\nNseg = size(seglist,1);\n\n fprintf('Select segments by clicking with the left mouse button\\n');\n fprintf('Last segment is indicated by clicking with any other mouse button\\n');\n\n count = 0;\n but = 1;\n while but==1 & count < Nseg\n [xp,yp,but] = ginput(1); % Get digitised point\n\tcount = count + 1;\t\n\trmin = Inf;\n\tfor s = 1:Nseg\n\t r = segdist(xp,yp,seglist(s,:));\n\t % if distance is closest so far and segment is not already\n % selected...\n\t if r < rmin & ~any(selectedSegs==s)\n\t\trmin = r;\n\t\tclosestseg = seglist(s,:);\n smin = s;\n\t end\n\tend\n\t\n\tsegs = [segs; closestseg]; % Build up list of segments\n\tselectedSegs = [selectedSegs smin]; % Remeber selected seg Nos\n\t\n\tline([closestseg(1) closestseg(3)], [closestseg(2) closestseg(4)], ...\n\t 'Color',[1 0 0]);\n\ttext((closestseg(1)+closestseg(3))/2, ...\n\t (closestseg(2)+closestseg(4))/2, sprintf('%d',count));\n\n end \n \nfunction r = segdist(xp,yp,seg)\n \n% Function returns distance from point (xp,yp) to line defined by end\n% points (x1,y1) (x2,y2)\n%\t\n% \n% Eqn of line joining end pts (x1 y1) and (x2 y2) can be parameterised by\n%\n% x*(y1-y2) + y*(x2-x1) + y2*x1 - y1*x2 = 0\n%\n% (See Jain, Rangachar and Schunck, \"Machine Vision\", McGraw-Hill\n% 1996. pp 194-196)\n \n x1=seg(1);y1=seg(2);\n x2=seg(3);y2=seg(4); \n \n y1my2 = y1-y2; % Pre-compute parameters\n x2mx1 = x2-x1;\n C = y2*x1 - y1*x2;\n D = norm([x1 y1] - [x2 y2]); % Distance between end points\n\n r = abs(xp*y1my2 + yp*x2mx1 + C)/D; % Perp. distance from line to (xp,yp)\n\n % Correct the distance if (xp,yp) is `outside' the ends of the segment\n d1 = [xp yp]-[x1 y1];\n d2 = [xp yp]-[x2 y2]; \n if dot(d1,d2) > 0 % (xp,yp) is not `between' the end points of the\n % segment\n\t\t\t \n\tr = min(norm(d1),norm(d2)); % return distance to closest end\n % point\n end\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "maxlinedev.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/LineSegments/maxlinedev.m", "size": 2478, "source_encoding": "utf_8", "md5": "64cc6d88009aa2a148c843e2d4041218", "text": "% MAXLINEDEV - Find max deviation from a line in an edge contour.\n%\n% Function finds the point of maximum deviation from a line joining the\n% endpoints of an edge contour.\n%\n% Usage: [maxdev, index, D, totaldev] = maxlinedev(x,y)\n%\n% Arguments:\n% x, y - arrays of x,y (col,row) indicies of connected pixels \n% on the contour.\n% Returns:\n% maxdev - Maximum deviation of contour point from the line\n% joining the end points of the contour (pixels).\n% index - Index of the point having maxdev.\n% D - Distance between end points of the contour so that\n% one can calculate maxdev/D - the normalised error.\n% totaldev - Sum of the distances of all the pixels from the\n% line joining the endpoints.\n%\n% See also: EDGELINK, LINESEG\n%\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% December 2000 - Original version\n% February 2003 - Added calculation of total deviation\n% August 2006 - Avoid degeneracy when endpoints are coincident\n% February 2007 - Corrected distance calculation when endpoints are\n% coincident.\n\nfunction [maxdev, index, D, totaldev] = maxlinedev(x,y)\n\n Npts = length(x);\n \n if Npts == 1\n\twarning('Contour of length 1');\n\tmaxdev = 0; index = 1;\n\tD = 1; totaldev = 0;\n\treturn;\n elseif Npts == 0\n\terror('Contour of length 0');\n end\n\n % D = norm([x(1) y(1)] - [x(Npts) y(Npts)]); % Distance between end points\n D = sqrt((x(1)-x(Npts))^2 + (y(1)-y(Npts))^2); % This runs much faster\n\n if D > eps \n\t\n\t% Eqn of line joining end pts (x1 y1) and (x2 y2) can be parameterised by\n\t% \n\t% x*(y1-y2) + y*(x2-x1) + y2*x1 - y1*x2 = 0\n\t%\n\t% (See Jain, Rangachar and Schunck, \"Machine Vision\", McGraw-Hill\n\t% 1996. pp 194-196)\n\t\n\ty1my2 = y(1)-y(Npts); % Pre-compute parameters\n\tx2mx1 = x(Npts)-x(1);\n\tC = y(Npts)*x(1) - y(1)*x(Npts);\n\t\n\t% Calculate distance from line segment for each contour point\n\td = abs(x*y1my2 + y*x2mx1 + C)/D; \n\t\n else % End points are coincident, calculate distances from 1st point\n \n d = sqrt((x - x(1)).^2 + (y - y(1)).^2);\n\tD = 1; % Now set D to 1 so that normalised error can be used\n\t\n end\t\t\t\t\t\t\n\n [maxdev, index] = max(d);\n\n if nargout == 4\n\ttotaldev = sum(d.^2);\n end\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "drawedgelist.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/LineSegments/drawedgelist.m", "size": 5139, "source_encoding": "utf_8", "md5": "37224c54b8034d4fadf13c9b60861db5", "text": "% DRAWEDGELIST - plots pixels in edgelists\n%\n% Usage: h = drawedgelist(edgelist, rowscols, lw, col, figno, mid)\n%\n% Arguments:\n% edgelist - Cell array of edgelists in the form\n% { [r1 c1 [r1 c1 etc }\n% ...\n% rN cN] ....]\n% rowscols - Optional 2 element vector [rows cols] specifying the size\n% of the image from which edges were detected (used to set\n% size of plotted image). If omitted or specified as [] this\n% defaults to the bounds of the linesegment points\n% lw - Optional line width specification. If omitted or specified\n% as [] it defaults to a value of 1;\n% col - Optional colour specification. Eg [0 0 1] for blue. This\n% can also be specified as the string 'rand' to generate a\n% random color coding for each edgelist so that it is easier\n% to see how the edges have been broken up into separate\n% lists. If omitted or specified as [] it defaults to blue.\n% col can also be a N x 3 array of colours where N is the\n% length of edgelist, thus specifying a particulr colour for\n% each edge.\n% figno - Optional figure number in which to display image.\n% mid - Optional flag 0/1. If set each edge is drawn by joining\n% the mid points betwen points along the edge lists. This is\n% intended only to be used for edgelists at pixel resolution.\n% It reduces staircasing on diagonal lines giving nicer output.\n%\n% Returns:\n% h - Array of handles to each plotted edgelist\n%\n% See also: EDGELINK, LINESEG\n\n% Copyright (c) 2003-2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2003 - Original version\n% September 2004 - Revised and updated\n% December 2006 - Colour and linewidth specification updated\n% January 2011 - Axis setting corrected (thanks to Stzpz)\n% July 2013 - Colours can be specified for each edge\n% Feb 2014 - Code cleanup + mid segment drawing option\n\nfunction h = drawedgelist(edgelist, rowscols, lw, col, figno, mid)\n \n if ~exist('rowscols', 'var') | isempty(rowscols), rowscols = [1 1]; end\n if ~exist('lw', 'var') | isempty(lw), lw = 1; end\n if ~exist('col', 'var') | isempty(col), col = [0 0 1]; end\n if exist('figno', 'var'), figure(figno); end\n if ~exist('mid', 'var'), mid = 0; end\n \n debug = 0;\n Nedge = length(edgelist);\n h = zeros(length(edgelist),1);\n \n % Set up edge colours\n if strcmp(col,'rand')\n col = hsv(Nedge); % HSV colour map with Nedge entries\n\tcol = col(randperm(Nedge),:); % Form random permutation of colours\n \n elseif all(size(col) == [1 3]) % Single colour for all edges\n col = repmat(col,[Nedge 1]);\n \n elseif all(size(col) == [Nedge 3]) % Colour for each edge specified\n ; % we do not need to do anything\n \n else\n error('Colour not specified properly'); \n end\n \n if mid\n for I = 1:Nedge\n melist = midedge(edgelist{I});\n h(I) = line(melist(:,2), melist(:,1),...\n 'LineWidth', lw, 'Color', col(I,:));\n end\t\n \n else\n for I = 1:Nedge\n h(I) = line(edgelist{I}(:,2), edgelist{I}(:,1),...\n 'LineWidth', lw, 'Color', col(I,:));\n end\t\n end\n \n if debug\n\tfor I = 1:Nedge\n\t mid = fix(length(edgelist{I})/2);\n\t text(edgelist{I}(mid,2), edgelist{I}(mid,1),sprintf('%d',I))\n\tend\n end\n \n % Check whether we need to expand bounds\n minx = 1; miny = 1;\n maxx = rowscols(2); maxy = rowscols(1);\n\n for I = 1:Nedge\n\tminx = min(min(edgelist{I}(:,2)),minx);\n\tminy = min(min(edgelist{I}(:,1)),miny);\n\tmaxx = max(max(edgelist{I}(:,2)),maxx);\n\tmaxy = max(max(edgelist{I}(:,1)),maxy);\t\n end\t \n\n axis('equal'); axis('ij');\n axis([minx maxx miny maxy]);\n \n if nargout == 0\n clear h\n end\n \n%------------------------------------------------------------------------\n\n% Function to construct a new edge list formed by stepping through the mid\n% points of each segment of the edgelist. The idea is to form a smoother path\n% along the edgelist. This is intended for edgelists formed at pixel\n% resolution.\n\nfunction melist = midedge(elist)\n \n melist = [elist(1,:); (elist(1:end-1, :) + elist(2:end, :))/2; elist(end,:)];\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "lineseg.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/LineSegments/lineseg.m", "size": 3017, "source_encoding": "utf_8", "md5": "ff2e4a5d3f9faabdf548561ed00b22b6", "text": "% LINESEG - Form straight line segements from an edge list.\n%\n% Usage: seglist = lineseg(edgelist, tol)\n%\n% Arguments: edgelist - Cell array of edgelists where each edgelist is an\n% Nx2 array of (row col) coords.\n% tol - Maximum deviation from straight line before a\n% segment is broken in two (measured in pixels).\n% Returns:\n% seglist - A cell array of in the same format of the input\n% edgelist but each seglist is a subsampling of its\n% corresponding edgelist such that straight line\n% segments between these subsampled points do not\n% deviate from the original points by more than tol.\n%\n% This function takes each array of edgepoints in edgelist, finds the\n% size and position of the maximum deviation from the line that joins the\n% endpoints, if the maximum deviation exceeds the allowable tolerance the\n% edge is shortened to the point of maximum deviation and the test is\n% repeated. In this manner each edge is broken down to line segments,\n% each of which adhere to the original data with the specified tolerance.\n%\n% See also: EDGELINK, MAXLINEDEV, DRAWEDGELIST\n%\n\n% Copyright (c) 2000-2006 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% December 2000 - Original version\n% February 2003 - Added the returning of nedgelist data.\n% December 2006 - Changed so that separate cell arrays of line segments are\n% formed, in the same format used for edgelists\n\n\nfunction seglist = lineseg(edgelist, tol)\n \n Nedge = length(edgelist);\n seglist = cell(1,Nedge);\n \n for e = 1:Nedge\n y = edgelist{e}(:,1); % Note that (col, row) corresponds to (x,y)\n\tx = edgelist{e}(:,2);\n\n\tfst = 1; % Indices of first and last points in edge\n\tlst = length(x); % segment being considered.\n\n\tNpts = 1;\t\n\tseglist{e}(Npts,:) = [y(fst) x(fst)];\n\t\n\twhile fst tol % While deviation is > tol \n\t\tlst = i+fst-1; % Shorten line to point of max deviation by adjusting lst\n\t\t[m,i] = maxlinedev(x(fst:lst),y(fst:lst));\n\t end\n\t\n\t Npts = Npts+1;\n\t seglist{e}(Npts,:) = [y(lst) x(lst)];\n\t \n\t fst = lst; % reset fst and lst for next iteration\n\t lst = length(x);\n\tend\n end\n\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "cleanedgelist.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/LineSegments/cleanedgelist.m", "size": 13314, "source_encoding": "utf_8", "md5": "a79468f2b92f2ce262730a04d766d643", "text": "% CLEANEDGELIST - remove short edges from a set of edgelists\n%\n% Function to clean up a set of edge lists generated by EDGELINK so that\n% isolated edges and spurs that are shorter that a minimum length are removed.\n% This code can also be use with a set of line segments generated by LINESEG.\n%\n% Usage: nedgelist = cleanedgelist(edgelist, minlength)\n%\n% Arguments:\n% edgelist - a cell array of edge lists in row,column coords in\n% the form\n% { [r1 c1 [r1 c1 etc }\n% r2 c2 ...\n% ...\n% rN cN] ....] \n% minlength - minimum edge length of interest\n%\n% Returns:\n% nedgelist - the new, cleaned up set of edgelists\n%\n% See also: EDGELINK, DRAWEDGELIST, LINESEG\n\n% Copyright (c) 2006-2007 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% December 2006 Original version\n% February 2007 A major rework to fix several problems, hope they really are\n% fixed!\n\n\nfunction nedgelist = cleanedgelist(edgelist, minlength)\n \n Nedges = length(edgelist);\n Nnodes = 2*Nedges;\n\n % Each edgelist has two end nodes - the starting point and the ending point.\n % We build up an adjacency/connection matrix for each node so that we can\n % determine which, if any, edgelists are connected to a node. We also\n % maintain an adjacency matrix for the edges themselves.\n % \n % It is tricky maintaining all this information but it does allow the\n % code to run much faster.\n\n % First extract the end nodes from each edgelist. The nodes are numbered\n % so that the start node has number 2*edgenumber-1 and the end node has\n % number 2*edgenumber\n node = zeros(Nnodes, 2);\n for n = 1:Nedges\n node(2*n-1,:) = edgelist{n}(1,:);\n node(2*n ,:) = edgelist{n}(end,:); \n end\n \n % Now build the adjacency/connection matrices. \n A = zeros(Nnodes); % Adjacency matrix for nodes\n B = zeros(Nedges); % Adjacency matrix for edges\n \n for n = 1:Nnodes-1\n for m = n+1:Nnodes\n % If nodes m & n are connected\n A(n,m) = node(n,1)==node(m,1) && node(n,2)==node(m,2);\n A(m,n) = A(n,m);\n \n if A(n,m)\n edgen = fix((n+1)/2);\n edgem = fix((m+1)/2); \n B(edgen, edgem) = 1;\n B(edgem, edgen) = 1; \n end\n end\n end\n\n % If we sum the columns of the adjacency matrix we get the number of\n % other edgelists that are connected to an edgelist\n Nconnections = sum(A); % Connection count array for nodes\n Econnections = sum(B); % Connection count array for edges\n \n\n % Check every edge to see if any of its ends are connected to just one edge.\n % This should not happen, but occasionally does due to a problem in\n % EDGELINK. Here we simply merge it with the edge it is connected to.\n % Ultimately I want to be able to remove this block of code.\n % I think there are also some cases that are (still) not properly handled\n % by CLEANEDGELIST and there may be a case for repeating this block of\n % code at the end for another final cleanup pass\n for n = 1:Nedges\n if ~B(n,n) && ~isempty(edgelist{n}) % if edge is not connected to itself\n [spurdegree, spurnode, startnode, sconns, endnode, econns] = connectioninfo(n);\n if sconns == 1\n node2merge = find(A(startnode,:));\n mergenodes(node2merge,startnode);\n end\n \n if ~isempty(edgelist{n}) % If we have not removed this edge in\n % the code above check the other end.\n if econns == 1\n node2merge = find(A(endnode,:));\n mergenodes(node2merge,endnode);\n end \n end\n end\n end\n \n \n % Now check every edgelist, if the edgelength is below the minimum length\n % check if we should remove it.\n\n if minlength > 0\n \n for n = 1:Nedges\n \n [spurdegree, spurnode] = connectioninfo(n);\n \n if ~isempty(edgelist{n}) && edgelistlength(edgelist{n}) < minlength \n\n % Remove unconnected lists, or lists that are only connected to\n % themselves. \n if ~Econnections(n) || (Econnections(n)==1 && B(n,n) == 1)\n removeedge(n);\n \n % Process edges that are spurs coming from a 3-way junction.\n elseif spurdegree == 2\n %fprintf('%d is a spur\\n',n) %%debug\n\n linkingedges = find(B(n,:));\n \n if length(linkingedges) == 1 % We have a loop with a spur\n % coming from the join in the\n % loop\n % Just remove the spur, leaving the loop intact.\n removeedge(n); \n \n else % Check the other edges coming from this point. If any\n % are also spurs make sure we remove the shortest one\n spurs = n;\n len = edgelistlength(edgelist{n});\n for i = 1:length(linkingedges)\n spurdegree = connectioninfo(linkingedges(i));\n if spurdegree\n spurs = [spurs linkingedges(i)]; \n len = [len edgelistlength(edgelist{linkingedges(i)})]; \n end\n end\n\n linkingedges = [linkingedges n];\n \n [mn,i] = min(len);\n edge2delete = spurs(i);\n [spurdegree, spurnode] = connectioninfo(edge2delete);\n\n nodes2merge = find(A(spurnode,:));\n \n if length(nodes2merge) ~= 2\n error('attempt to merge other than 2 nodes');\n end\n \n removeedge(edge2delete); \n mergenodes(nodes2merge(1),nodes2merge(2)) \n \n end \n\n % Look for spurs coming from 4-way junctions that are below the minimum length\n elseif spurdegree == 3\n removeedge(n); % Just remove it, no subsequent merging needed.\n end\n end\n end\n \n % Final cleanup of any new isolated edges that might have been created by\n % removing spurs. An edge is isolated if it has no connections to other\n % edges, or is only connected to itself (in a loop).\n \n for n = 1:Nedges\n if ~isempty(edgelist{n}) && edgelistlength(edgelist{n}) < minlength \n if ~Econnections(n) || (Econnections(n)==1 && B(n,n) == 1)\n removeedge(n); \n end\n end\n end\n \n end % if minlength > 0\n \n % Run through the edgelist and extract out the non-empty lists\n m = 0;\n for n = 1:Nedges\n if ~isempty(edgelist{n})\n m = m+1;\n nedgelist{m} = edgelist{n};\n end\n end\n \n \n%---------------------------------------------------------------------- \n% Internal function to merge 2 edgelists together at the specified nodes and\n% perform the necessary updates to the edge adjacency and node adjacency\n% matrices and the connection count arrays\n\nfunction mergenodes(n1,n2)\n \n edge1 = fix((n1+1)/2); % Indices of the edges associated with the nodes\n edge2 = fix((n2+1)/2); \n\n % Get indices of nodes at each end of the two edges\n s1 = 2*edge1-1; e1 = 2*edge1;\n s2 = 2*edge2-1; e2 = 2*edge2; \n \n if edge1==edge2\n % We should not get here, but somehow we occasionally do\n % fprintf('Nodes %d %d\\n',n1,n2) %% debug\n % warning('Attempt to merge an edge with itself')\n return\n end\n \n if ~A(n1,n2)\n error('Attempt to merge nodes that are not connected');\n end\n \n if mod(n1,2) % node n1 is the start of edge1\n flipedge1 = 1; % edge1 will need to be reversed in order to join edge2\n else \n flipedge1 = 0; \n end\n \n if mod(n2,2) % node n2 is the start of edge2 \n flipedge2 = 0;\n else\n flipedge2 = 1;\n end\n \n % Join edgelists together - with appropriate reordering depending on which\n % end is connected to which. The result is stored in edge1\n \n if ~flipedge1 && ~flipedge2 \n edgelist{edge1} = [edgelist{edge1}; edgelist{edge2}];\n\n A(e1,:) = A(e2,:); A(:,e1) = A(:,e2);\n Nconnections(e1) = Nconnections(e2);\n \n elseif ~flipedge1 && flipedge2\n edgelist{edge1} = [edgelist{edge1}; flipud(edgelist{edge2})]; \n \n A(e1,:) = A(s2,:); A(:,e1) = A(:,s2);\n Nconnections(e1) = Nconnections(s2);\n\n elseif flipedge1 && ~flipedge2\n edgelist{edge1} = [flipud(edgelist{edge1}); edgelist{edge2}]; \n \n A(s1,:) = A(e1,:); A(:,s1) = A(:,e1);\n A(e1,:) = A(e2,:); A(:,e1) = A(:,e2); \n Nconnections(s1) = Nconnections(e1);\n Nconnections(e1) = Nconnections(e2); \n\n elseif flipedge1 && flipedge2\n edgelist{edge1} = [flipud(edgelist{edge1}); flipud(edgelist{edge2})];\n\n A(s1,:) = A(e1,:); A(:,s1) = A(:,e1); \n A(e1,:) = A(s2,:); A(:,e1) = A(:,s2);\n Nconnections(s1) = Nconnections(e1);\n Nconnections(e1) = Nconnections(s2);\n \n else\n fprintf('merging edges %d and %d\\n',edge1, edge2); %%debug \n error('We should not have got here - edgelists cannot be merged');\n end\n \n % Now correct the edge adjacency matrix to reflect the new arrangement\n % The edges that the new edge1 is connected to is all the edges that\n % edge1 and edge2 were connected to\n B(edge1,:) = B(edge1,:) | B(edge2,:);\n B(:,edge1) = B(:,edge1) | B(:,edge2); \n B(edge1, edge1) = 0;\n\n % Recompute connection counts because we have shuffled the adjacency matrices\n Econnections = sum(B);\n Nconnections = sum(A);\n \n removeedge(edge2); % Finally discard edge2\n \nend % end of mergenodes\n\n%-------------------------------------------------------------------- \n\n% Function to provide information about the connections at each end of an\n% edgelist \n%\n% [spurdegree, spurnode, startnode, sconns, endnode, econns] = connectioninfo(n)\n%\n% spurdegree - If this is non-zero it indicates this edgelist is a spur, the\n% value is the number of edges this spur is connected to.\n% spurnode - If this is a spur spurnode is the index of the node that is\n% connected to other edges, 0 otherwise.\n% startnode - index of starting node of edgelist.\n% endnode - index of end node of edgelist.\n% sconns - number of connections to start node.\n% econns - number of connections to end node.\n \nfunction [spurdegree, spurnode, startnode, sconns, endnode, econns] = connectioninfo(n)\n\n if isempty(edgelist{n})\n spurdegree = 0; spurnode = 0;\n startnode = 0; sconns = 0; endnode = 0; econns = 0;\n return\n end\n \n startnode = 2*n-1;\n endnode = 2*n;\n sconns = Nconnections(startnode); % No of connections to start node\n econns = Nconnections(endnode); % No of connections to end node \n \n if sconns == 0 && econns >= 1\n spurdegree = econns;\n spurnode = endnode;\n elseif sconns >= 1 && econns == 0\n spurdegree = sconns;\n spurnode = startnode; \n else\n spurdegree = 0;\n spurnode = 0;\n end\n \nend\n\n%--------------------------------------------------------------------\n% Function to remove an edgelist and perform the necessary updates to the edge\n% adjacency and node adjacency matrices and the connection count arrays\n\nfunction removeedge(n)\n \n edgelist{n} = [];\n Econnections = Econnections - B(n,:); \n Econnections(n) = 0; \n B(n,:) = 0;\n B(:,n) = 0;\n \n nodes2delete = [2*n-1, 2*n];\n \n Nconnections = Nconnections - A(nodes2delete(1),:); \n Nconnections = Nconnections - A(nodes2delete(2),:); \n \n A(nodes2delete, :) = 0;\n A(:, nodes2delete) = 0; \n \nend\n\n%--------------------------------------------------------------------\n% Function to compute the path length of an edgelist\n\nfunction l = edgelistlength(edgelist)\n l = sum(sqrt(sum((edgelist(1:end-1,:)-edgelist(2:end,:)).^2, 2)));\nend\n\n%--------------------------------------------------------------------\nend % End of cleanedgelists\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "edgelink.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/LineSegments/edgelink.m", "size": 21107, "source_encoding": "utf_8", "md5": "25bee720223bdbc51946de674aa2d085", "text": "% EDGELINK - Link edge points in an image into lists\n%\n% Usage: [edgelist edgeim, etypr] = edgelink(im, minlength, location)\n%\n% **Warning** 'minlength' is ignored at the moment because 'cleanedgelist'\n% has some bugs and can be memory hungry\n%\n% Arguments: im - Binary edge image, it is assumed that edges\n% have been thinned (or are nearly thin).\n% minlength - Optional minimum edge length of interest, defaults\n% to 1 if omitted or specified as []. Ignored at the\n% moment. \n% location - Optional complex valued image holding subpixel\n% locations of edge points. For any pixel the\n% real part holds the subpixel row coordinate of\n% that edge point and the imaginary part holds\n% the column coordinate. See NONMAXSUP. If\n% this argument is supplied the edgelists will\n% be formed from the subpixel coordinates,\n% otherwise the the integer pixel coordinates of\n% points in 'im' are used.\n%\n% Returns: edgelist - a cell array of edge lists in row,column coords in\n% the form\n% { [r1 c1 [r1 c1 etc }\n% r2 c2 ...\n% ...\n% rN cN] ....] \n%\n% edgeim - Image with pixels labeled with edge number. \n% Note that junctions in the labeled edge image will be\n% labeled with the edge number of the last edge that was\n% tracked through it. Note that this image also includes\n% edges that do not meet the minimum length specification.\n% If you want to see just the edges that meet the\n% specification you should pass the edgelist to\n% DRAWEDGELIST.\n%\n% etype - Array of values, one for each edge segment indicating\n% its type\n% 0 - Start free, end free\n% 1 - Start free, end junction\n% 2 - Start junction, end free (should not happen)\n% 3 - Start junction, end junction\n% 4 - Loop\n%\n% This function links edge points together into lists of coordinate pairs.\n% Where an edge junction is encountered the list is terminated and a separate\n% list is generated for each of the branches.\n%\n% Note I am not sure if using bwmorph's 'thin' or 'skel' is best for\n% preprocessing the edge image prior to edgelinking. The main issue is the\n% treatment of junctions. Skel can result in an image where multiple adjacent\n% junctions are produced (maybe this is more a problem with my junction\n% detection code). Thin, on the other hand, can produce different output when\n% you rotate an image by 90 degrees. On balance I think using 'thin' is better.\n% Note, however, the input image should be 'nearly thin' otherwise the thinning\n% operation could shorten the ends of structures. Skeletonisation and thinning\n% is surprisingly awkward.\n%\n% See also: DRAWEDGELIST, LINESEG, MAXLINEDEV, CLEANEDGELIST,\n% FINDENDSJUNCTIONS, FILLEDGEGAPS\n\n% Copyright (c) 1996-2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% February 2001 - Original version\n% September 2004 - Revised to allow subpixel edge data to be used\n% November 2006 - Changed so that edgelists start and stop at every junction \n% January 2007 - Trackedge modified to discard isolated pixels and the\n% problems they cause (thanks to Jeff Copeland)\n% January 2007 - Fixed so that closed loops are closed!\n% May 2013 - Completely redesigned with a new linking strategy that\n% hopefully handles adjacent junctions correctly. It runs\n% about twice as fast too.\n\nfunction [edgelist, edgeim, etype] = edgelink(im, minlength, location)\n \n % Set up some global variables to avoid passing (and copying) of arguments,\n % this improves speed.\n global EDGEIM;\n global ROWS;\n global COLS;\n global JUNCT;\n \n if ~exist('minlength','var') || isempty(minlength), minlength = 0; end\n \n EDGEIM = im ~= 0; % Make sure image is binary.\n EDGEIM = bwmorph(EDGEIM,'clean'); % Remove isolated pixels\n\n % Make sure edges are thinned. Use 'thin' rather than 'skel', see\n % comments in header.\n EDGEIM = bwmorph(EDGEIM,'thin',Inf); \n [ROWS, COLS] = size(EDGEIM);\n \n % Find endings and junctions in edge data\n [RJ, CJ, re, ce] = findendsjunctions(EDGEIM);\n Njunct = length(RJ);\n Nends = length(re);\n \n % Create a sparse matrix to mark junction locations. This makes junction\n % testing much faster. A value of 1 indicates a junction, a value of 2\n % indicates we have visited the junction.\n JUNCT = spalloc(ROWS,COLS, Njunct);\n for n = 1:Njunct\n JUNCT(RJ(n),CJ(n)) = 1; \n end\n\n % ? Think about using labels >= 2 so that EDGEIM can be uint16, say. %\n EDGEIM = double(EDGEIM); % Cast to double to allow the use of -ve labelings\n edgeNo = 0;\n \n % Summary of strategy:\n % 1) From every end point track until we encounter an end point or\n % junction. As we track points along an edge image pixels are labeled with\n % the -ve of their edge No.\n % 2) From every junction track out on any edges that have not been\n % labeled yet.\n % 3) Scan through the image looking for any unlabeled pixels. These\n % correspond to isolated loops that have no junctions.\n\n\n %% 1) Form tracks from each unlabeled endpoint until we encounter another\n % endpoint or junction.\n for n = 1:Nends\n if EDGEIM(re(n),ce(n)) == 1 % Endpoint is unlabeled\n edgeNo = edgeNo + 1;\n [edgelist{edgeNo} endType] = trackedge(re(n), ce(n), edgeNo);\n etype(edgeNo) = endType;\n end\n end\n \n %% 2) Handle junctions.\n % Junctions are awkward when they are adjacent to other junctions. We\n % start by looking at all the neighbours of a junction. \n % If there is an adjacent junction we first create a 2-element edgetrack\n % that links the two junctions together. We then look to see if there are\n % any non-junction edge pixels that are adjacent to both junctions. We then\n % test to see which of the two junctions is closest to this common pixel and\n % initiate an edge track from the closest of the two junctions through this\n % pixel. When we do this we set the 'avoidJunction' flag in the call to\n % trackedge so that the edge track does not immediately loop back and\n % terminate on the other adjacent junction.\n % Having checked all the common neighbours of both junctions we then\n % track out on any remaining untracked neighbours of the junction \n \n for j = 1:Njunct\n if JUNCT(RJ(j),CJ(j)) ~= 2; % We have not visited this junction\n JUNCT(RJ(j),CJ(j)) = 2;\n\n % Call availablepixels with edgeNo = 0 so that we get a list of\n % available neighbouring pixels that can be linked to and a list of\n % all neighbouring pixels that are also junctions.\n [ra, ca, rj, cj] = availablepixels(RJ(j), CJ(j), 0);\n \n for k = 1:length(rj) % For all adjacent junctions...\n % Create a 2-element edgetrack to each adjacent junction\n edgeNo = edgeNo + 1;\n edgelist{edgeNo} = [RJ(j) CJ(j); rj(k) cj(k)];\n etype(edgeNo) = 3; % Edge segment is junction-junction\n EDGEIM(RJ(j), CJ(j)) = -edgeNo;\n EDGEIM(rj(k), cj(k)) = -edgeNo;\n \n % Check if the adjacent junction has some untracked pixels that\n % are also adjacent to the initial junction. Thus we need to\n % get available pixels adjacent to junction (rj(k) cj(k))\n [rak, cak] = availablepixels(rj(k), cj(k));\n \n % If both junctions have untracked neighbours that need checking...\n if ~isempty(ra) && ~isempty(rak)\n \n % Find untracked neighbours common to both junctions. \n commonrc = intersect([ra ca], [rak cak], 'rows');\n \n for n = 1:size(commonrc, 1);\n % If one of the junctions j or k is closer to this common\n % neighbour use that as the start of the edge track and the\n % common neighbour as the 2nd element. When we call\n % trackedge we set the avoidJunction flag to prevent the\n % track immediately connecting back to the other junction.\n distj = norm(commonrc(n,:) - [RJ(j) CJ(j)]);\n distk = norm(commonrc(n,:) - [rj(k) cj(k)]);\n edgeNo = edgeNo + 1;\n if distj < distk\n edgelist{edgeNo} = trackedge(RJ(j), CJ(j), edgeNo, ...\n commonrc(n,1), commonrc(n,2), 1);\n else \n edgelist{edgeNo} = trackedge(rj(k), cj(k), edgeNo, ...\n commonrc(n,1), commonrc(n,2), 1);\n end\n etype(edgeNo) = 3; % Edge segment is junction-junction\n end\n end\n \n % Track any remaining unlabeled pixels adjacent to this junction k\n for m = 1:length(rak)\n if EDGEIM(rak(m), cak(m)) == 1\n edgeNo = edgeNo + 1;\n edgelist{edgeNo} = trackedge(rj(k), cj(k), edgeNo, rak(m), cak(m));\n etype(edgeNo) = 3; % Edge segment is junction-junction\n end \n end\n \n % Mark that we have visited junction (rj(k) cj(k))\n JUNCT(rj(k), cj(k)) = 2;\n \n end % for all adjacent junctions\n\n % Finally track any remaining unlabeled pixels adjacent to original junction j\n for m = 1:length(ra)\n if EDGEIM(ra(m), ca(m)) == 1\n edgeNo = edgeNo + 1;\n edgelist{edgeNo} = trackedge(RJ(j), CJ(j), edgeNo, ra(m), ca(m));\n etype(edgeNo) = 3; % Edge segment is junction-junction \n end \n end\n \n end % If we have not visited this junction\n end % For each junction\n \n %% 3) Scan through the image looking for any unlabeled pixels. These\n % should correspond to isolated loops that have no junctions or endpoints.\n for ru = 1:ROWS\n for cu = 1:COLS\n if EDGEIM(ru,cu) == 1 % We have an unlabeled edge\n edgeNo = edgeNo + 1; \n [edgelist{edgeNo} endType] = trackedge(ru, cu, edgeNo);\n etype(edgeNo) = endType; \n end\n end\n end\n \n edgeim = -EDGEIM; % Finally negate image to make edge encodings +ve.\n\n % Eliminate isolated edges and spurs that are below the minimum length\n % ** DISABLED for the time being **\n% if nargin >= 2 && ~isempty(minlength)\n%\tedgelist = cleanedgelist2(edgelist, minlength);\n% end\n \n % If subpixel edge locations are supplied upgrade the integer precision\n % edgelists that were constructed with data from 'location'.\n if nargin == 3\n\tfor I = 1:length(edgelist)\n\t ind = sub2ind(size(im),edgelist{I}(:,1),edgelist{I}(:,2));\n\t edgelist{I}(:,1) = real(location(ind))';\n\t edgelist{I}(:,2) = imag(location(ind))'; \n\tend\n end\n\n clear global EDGEIM;\n clear global ROWS;\n clear global COLS;\n clear global JUNCT;\n \n%---------------------------------------------------------------------- \n% TRACKEDGE\n%\n% Function to track all the edge points starting from an end point or junction.\n% As it tracks it stores the coords of the edge points in an array and labels the\n% pixels in the edge image with the -ve of their edge number. This continues\n% until no more connected points are found, or a junction point is encountered.\n%\n% Usage: edgepoints = trackedge(rstart, cstart, edgeNo, r2, c2, avoidJunction)\n% \n% Arguments: rstart, cstart - Row and column No of starting point.\n% edgeNo - The current edge number.\n% r2, c2 - Optional row and column coords of 2nd point.\n% avoidJunction - Optional flag indicating that (r2,c2)\n% should not be immediately connected to a\n% junction (if possible).\n%\n% Returns: edgepoints - Nx2 array of row and col values for\n% each edge point.\n% endType - 0 for a free end\n% 1 for a junction\n% 5 for a loop\n\nfunction [edgepoints endType] = trackedge(rstart, cstart, edgeNo, r2, c2, avoidJunction)\n \n global EDGEIM;\n global JUNCT;\n \n if ~exist('avoidJunction', 'var'), avoidJunction = 0; end\n \n edgepoints = [rstart cstart]; % Start a new list for this edge.\n EDGEIM(rstart,cstart) = -edgeNo; % Edge points in the image are \n\t\t\t % encoded by -ve of their edgeNo.\n\n preferredDirection = 0; % Flag indicating we have/not a\n % preferred direction.\n \n % If the second point has been supplied add it to the track and set the\n % path direction\n if exist('r2', 'var') && exist('c2', 'var')\n edgepoints = [edgepoints\n r2 c2 ];\n EDGEIM(r2, c2) = -edgeNo;\n % Initialise direction vector of path and set the current point on\n % the path\n dirn = unitvector([r2-rstart c2-cstart]);\n r = r2;\n c = c2;\n preferredDirection = 1;\n else\n dirn = [0 0]; \n r = rstart;\n c = cstart;\n end\n \n % Find all the pixels we could link to\n [ra, ca, rj, cj] = availablepixels(r, c, edgeNo);\n \n while ~isempty(ra) || ~isempty(rj)\n \n % First see if we can link to a junction. Choose the junction that\n % results in a move that is as close as possible to dirn. If we have no\n % preferred direction, and there is a choice, link to the closest\n % junction\n % We enter this block:\n % IF there are junction points and we are not trying to avoid a junction\n % OR there are junction points and no non-junction points, ie we have\n % to enter it even if we are trying to avoid a junction\n if (~isempty(rj) && ~avoidJunction) || (~isempty(rj) && isempty(ra))\n\n % If we have a prefered direction choose the junction that results\n % in a move that is as close as possible to dirn.\n if preferredDirection \n dotp = -inf;\n for n = 1:length(rj)\n dirna = unitvector([rj(n)-r cj(n)-c]); \n dp = dirn*dirna';\n if dp > dotp\n dotp = dp;\n rbest = rj(n); cbest = cj(n);\n dirnbest = dirna;\n end\n end \n \n % Otherwise if we have no established direction, we should pick a\n % 4-connected junction if possible as it will be closest. This only\n % affects tracks of length 1 (Why do I worry about this...?!).\n else\n distbest = inf;\n for n = 1:length(rj)\n dist = sum([rj(n)-r; cj(n)-c]); \n if dist < distbest\n rbest = rj(n); cbest = cj(n);\n distbest = dist;\n dirnbest = unitvector([rj(n)-r cj(n)-c]); \n end\n end\n preferredDirection = 1;\n end\n \n % If there were no junctions to link to choose the available\n % non-junction pixel that results in a move that is as close as possible\n % to dirn\n else \n dotp = -inf;\n for n = 1:length(ra)\n dirna = unitvector([ra(n)-r ca(n)-c]); \n dp = dirn*dirna';\n if dp > dotp\n dotp = dp;\n rbest = ra(n); cbest = ca(n);\n dirnbest = dirna;\n end\n end\n\n avoidJunction = 0; % Clear the avoidJunction flag if it had been set\n end\n \n % Append the best pixel to the edgelist and update the direction and EDGEIM\n r = rbest; c = cbest;\n edgepoints = [edgepoints\n r c ];\n dirn = dirnbest;\n EDGEIM(r, c) = -edgeNo;\n\n % If this point is a junction exit here\n if JUNCT(r, c);\n endType = 1; % Mark end as being a junction\n return;\n else\n % Get the next set of available pixels to link.\n [ra, ca, rj, cj] = availablepixels(r, c, edgeNo); \n end\n end\n \n % If we get here we are at an endpoint or our sequence of pixels form a\n % loop. If it is a loop the edgelist should have start and end points\n % matched to form a loop. If the number of points in the list is four or\n % more (the minimum number that could form a loop), and the endpoints are\n % within a pixel of each other, append a copy of the first point to the end\n % to complete the loop\n \n endType = 0; % Mark end as being free, unless it is reset below\n \n if length(edgepoints) >= 4\n\tif abs(edgepoints(1,1) - edgepoints(end,1)) <= 1 && ...\n abs(edgepoints(1,2) - edgepoints(end,2)) <= 1 \n\t edgepoints = [edgepoints\n\t\t\t edgepoints(1,:)];\n endType = 5; % Mark end as being a loop\n end\n end\n\n%---------------------------------------------------------------------- \n% AVAILABLEPIXELS\n%\n% Find all the pixels that could be linked to point r, c\n%\n% Arguments: rp, cp - Row, col coordinates of pixel of interest.\n% edgeNo - The edge number of the edge we are seeking to\n% track. If not supplied its value defaults to 0\n% resulting in all adjacent junctions being returned,\n% (see note below)\n%\n% Returns: ra, ca - Row and column coordinates of available non-junction\n% pixels.\n% rj, cj - Row and column coordinates of available junction\n% pixels.\n%\n% A pixel is avalable for linking if it is:\n% 1) Adjacent, that is it is 8-connected.\n% 2) Its value is 1 indicating it has not already been assigned to an edge\n% 3) or it is a junction that has not been labeled -edgeNo indicating we have\n% not already assigned it to the current edge being tracked. If edgeNo is\n% 0 all adjacent junctions will be returned\n \nfunction [ra, ca, rj, cj] = availablepixels(rp, cp, edgeNo)\n\n global EDGEIM;\n global JUNCT;\n global ROWS;\n global COLS;\n \n % If edgeNo not supplied set to 0 to allow all adjacent junctions to be returned\n if ~exist('edgeNo', 'var'), edgeNo = 0; end\n \n ra = []; ca = [];\n rj = []; cj = [];\n \n % row and column offsets for the eight neighbours of a point\n roff = [-1 0 1 1 1 0 -1 -1];\n coff = [-1 -1 -1 0 1 1 1 0];\n \n r = rp+roff;\n c = cp+coff;\n \n % Find indices of arrays of r and c that are within the image bounds\n ind = find((r>=1 & r<=ROWS) & (c>=1 & c<=COLS));\n\n % A pixel is avalable for linking if its value is 1 or it is a junction\n % that has not been labeled -edgeNo\n for i = ind\n if EDGEIM(r(i),c(i)) == 1 && ~JUNCT(r(i), c(i));\n ra = [ra; r(i)];\n ca = [ca; c(i)];\n elseif (EDGEIM(r(i),c(i)) ~= -edgeNo) && JUNCT(r(i), c(i));\n rj = [rj; r(i)];\n cj = [cj; c(i)];\n end\n end\n \n \n%--------------------------------------------------------------------- \n% UNITVECTOR Normalises a vector to unit magnitude\n%\n\nfunction nv = unitvector(v)\n \n nv = v./sqrt(v(:)'*v(:)); "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "edgelist2image.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/LineSegments/edgelist2image.m", "size": 2027, "source_encoding": "utf_8", "md5": "5c5436b3f23a712f883ddb43a21e1d1c", "text": "% EDGELIST2IMAGE - transfers edgelist data back into a 2D image array\n%\n% Usage: im = edgelist2image(edgelist, rowscols)\n%\n% edgelist - Cell array of edgelists in the form\n% { [r1 c1 [r1 c1 etc }\n% ...\n% rN cN] ....]\n% rowscols - Optional 2 element vector [rows cols] specifying the size\n% of the image from which edges were detected (used to set\n% size of plotted image). If omitted or specified as [] this\n% defaults to the bounds of the linesegment points\n%\n% Note this function will only work effectively on 'dense' edgelist data\n% obtained, say, directly from edgelink. If you have subsequently fitted\n% line segments to the edgelist data this function will only mark the endpoints\n% of the segments, use DRAWEDGELIST instead.\n%\n% See also: EDGELINK, DRAWEDGELIST\n\n% Copyright (c) 2007 Peter Kovesi\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% September 2007\n\n\nfunction im = edgelist2image(edgelist, rowscols)\n\n if nargin < 2, rowscols = [1 1]; end\n\n Nedge = length(edgelist);\n \n % Establish bounds of image\n minx = 1; miny = 1;\n maxx = rowscols(2); maxy = rowscols(1);\n\n for I = 1:Nedge\n\tminx = min(min(edgelist{I}(:,2)),minx);\n\tminy = min(min(edgelist{I}(:,1)),miny);\n\tmaxx = max(max(edgelist{I}(:,2)),maxx);\n\tmaxy = max(max(edgelist{I}(:,1)),maxy);\t\n end\t \n \n % Draw the edgelist data into an image array\n im = zeros(maxy,maxx);\n \n for I = 1:Nedge\n\tind = sub2ind([maxy maxx], edgelist{I}(:,1), edgelist{I}(:,2));\n\tim(ind) = 1;\n end\t\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "bandpassfilter.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/bandpassfilter.m", "size": 1514, "source_encoding": "utf_8", "md5": "d98c0b715b1b05c4e8c5e415a260dd2c", "text": "% BANDPASSFILTER - Constructs a band-pass butterworth filter\n%\n% usage: f = bandpassfilter(sze, cutin, cutoff, n)\n% \n% where: sze is a two element vector specifying the size of filter \n% to construct [rows cols].\n% cutin and cutoff are the frequencies defining the band pass 0 - 0.5\n% n is the order of the filter, the higher n is the sharper\n% the transition is. (n must be an integer >= 1).\n%\n% The frequency origin of the returned filter is at the corners.\n%\n% See also: LOWPASSFILTER, HIGHPASSFILTER, HIGHBOOSTFILTER\n%\n\n% Copyright (c) 1999 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 1999\n\n\nfunction f = bandpassfilter(sze, cutin, cutoff, n)\n \n if cutin < 0 | cutin > 0.5 | cutoff < 0 | cutoff > 0.5\n\terror('frequencies must be between 0 and 0.5');\n end\n \n if rem(n,1) ~= 0 | n < 1\n\terror('n must be an integer >= 1');\n end\n \n f = lowpassfilter(sze, cutoff, n) - lowpassfilter(sze, cutin, n);\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "upwardcontinue.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/upwardcontinue.m", "size": 4042, "source_encoding": "utf_8", "md5": "c50e198c0e568fd171e5713d3d05342b", "text": "% UPWARDCONTINUE Upward continuation for magnetic or gravity potential field data\n%\n% Usage: [up, pim, psf] = upwardcontinue(im, h, dx, dy)\n%\n% Arguments: im - Input potential field image\n% h - Height to upward continue to (+ve)\n% dx, dy - Grid spacing in x and y. The upward continuation height\n% is computed relative to the grid spacing. If omitted dx =\n% dy = 1, that is, the value of h is in grid spacing units.\n% If dy is omitted it is assumed dy = dx. \n%\n% Returns: up - The upward continued field image\n% pim - The periodic component of the input potential field\n% image. See note below.\n% psf - The point spread function corresponding to the upward\n% continuation height.\n%\n% Upward continuation filtering is done in the frequency domain whereby the\n% Fourier transform of the upward continued image F(Up) is obtained from the\n% Fourier transform of the input image F(U) using\n% F(Up) = e^(-2*pi*h * sqrt(u^2 + v^2)) * F(U)\n% where u and v are the spatial frequencies over the input grid.\n%\n% To minimise edge effect problems Moisan's Periodic FFT is used. This avoids\n% the need for data tapering. Moisan's \"Periodic plus Smooth Image\n% Decomposition\" decomposes an image into two components\n% im = p + s\n% where s is the 'smooth' component with mean 0 and p is the 'periodic'\n% component which has no sharp discontinuities when one moves cyclically across\n% the image boundaries. \n%\n% Accordingly if you are doing residual analysis you should subtract the upward\n% continued image from the periodic component of the input image 'pim' rather\n% than from the raw input image 'im'.\n%\n% References: \n% Richard Blakely, \"Potential Theory in Gravity and Magnetic Applications\"\n% Cambridge University Press, 1996, pp 315-319\n%\n% L. Moisan, \"Periodic plus Smooth Image Decomposition\", Journal of\n% Mathematical Imaging and Vision, vol 39:2, pp. 161-179, 2011.\n%\n% See also: PERFFT2\n\n% Copyright (c) Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% June 2012 - Original version\n% June 2014 - Tidied up and documented\n\nfunction [up, pim, psf] = upwardcontinue(im, h, dx, dy)\n\n if ~exist('dx', 'var'), dx = 1; end\n if ~exist('dy', 'var'), dy = dx; end\n \n [rows,cols,chan] = size(im);\n assert(chan == 1, 'Image must be single channel');\n\n mask = ~isnan(im);\n \n % Use Periodic FFT rather than data tapering to minimise edge effects.\n [IM,~,pim] = perfft2(fillnan(im)); \n \n % Generate horizontal and vertical frequency grids that vary from\n % -0.5 to 0.5 \n [u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ...\n\t\t\t([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2)));\n\n % Quadrant shift to put 0 frequency at the corners. Also, divide by grid\n % size to get correct spatial frequencies\n u1 = ifftshift(u1)/dx; \n u2 = ifftshift(u2)/dy;\n\n freq = sqrt(u1.^2 + u2.^2); % Matrix values contain spatial frequency\n % values as a radius from centre (but\n % quadrant shifted) \n \n % Continuation filter in the frequency domain\n W = exp(-2*pi*h*freq);\n \n % Apply filter to obtain upward continuation\n up = real(ifft2(IM.*W)) .* double(mask);\n \n % Reconstruct the spatial representation of the point spread function\n % corresponding to the upward continuation height\n psf = real(fftshift(ifft2(W)));\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "highboostfilter.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/highboostfilter.m", "size": 1962, "source_encoding": "utf_8", "md5": "ada657e25d617c134fb03bf410b0be5b", "text": "% HIGHBOOSTFILTER - Constructs a high-boost Butterworth filter.\n%\n% usage: f = highboostfilter(sze, cutoff, n, boost)\n% \n% where: sze is a two element vector specifying the size of filter \n% to construct [rows cols].\n% cutoff is the cutoff frequency of the filter 0 - 0.5.\n% n is the order of the filter, the higher n is the sharper\n% the transition is. (n must be an integer >= 1).\n% boost is the ratio that high frequency values are boosted\n% relative to the low frequency values. If boost is less\n% than one then a 'lowboost' filter is generated\n%\n%\n% The frequency origin of the returned filter is at the corners.\n%\n% See also: LOWPASSFILTER, HIGHPASSFILTER, BANDPASSFILTER\n%\n\n% Copyright (c) 1999-2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 1999\n% November 2001 modified so that filter is specified in terms of high to\n% low boost rather than a zero frequency offset.\n\n\nfunction f = highboostfilter(sze, cutoff, n, boost)\n \n if cutoff < 0 | cutoff > 0.5\n\terror('cutoff frequency must be between 0 and 0.5');\n end\n \n if rem(n,1) ~= 0 | n < 1\n\terror('n must be an integer >= 1');\n end\n\n if boost >= 1 % high-boost filter\n\tf = (1-1/boost)*highpassfilter(sze, cutoff, n) + 1/boost;\n else % low-boost filter\n\tf = (1-boost)*lowpassfilter(sze, cutoff, n) + boost;\n end\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "invfft2.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/invfft2.m", "size": 250, "source_encoding": "utf_8", "md5": "41b97c8ab7dc15522b2c5a414bf55b38", "text": "% INVFFT2 - takes inverse fft and returns real part\n%\n% Function to `wrap up' taking the inverse Fourier transform\n% and extracting the real part into the one operation\n\n% Peter Kovesi October 1999\n\nfunction ift = invfft2(ft)\nift = real(ifft2(ft));\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "lowpassfilter.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/lowpassfilter.m", "size": 2448, "source_encoding": "utf_8", "md5": "1bdb6b9b70b06af9d2bc12b6b877da54", "text": "% LOWPASSFILTER - Constructs a low-pass butterworth filter.\n%\n% usage: f = lowpassfilter(sze, cutoff, n)\n% \n% where: sze is a two element vector specifying the size of filter \n% to construct [rows cols].\n% cutoff is the cutoff frequency of the filter 0 - 0.5\n% n is the order of the filter, the higher n is the sharper\n% the transition is. (n must be an integer >= 1).\n% Note that n is doubled so that it is always an even integer.\n%\n% 1\n% f = --------------------\n% 2n\n% 1.0 + (w/cutoff)\n%\n% The frequency origin of the returned filter is at the corners.\n%\n% See also: HIGHPASSFILTER, HIGHBOOSTFILTER, BANDPASSFILTER\n%\n\n% Copyright (c) 1999 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 1999\n% August 2005 - Fixed up frequency ranges for odd and even sized filters\n% (previous code was a bit approximate)\n\nfunction f = lowpassfilter(sze, cutoff, n)\n \n if cutoff < 0 | cutoff > 0.5\n\terror('cutoff frequency must be between 0 and 0.5');\n end\n \n if rem(n,1) ~= 0 | n < 1\n\terror('n must be an integer >= 1');\n end\n\n if length(sze) == 1\n\trows = sze; cols = sze;\n else\n\trows = sze(1); cols = sze(2);\n end\n\n % Set up X and Y matrices with ranges normalised to +/- 0.5\n % The following code adjusts things appropriately for odd and even values\n % of rows and columns.\n if mod(cols,2)\n\txrange = [-(cols-1)/2:(cols-1)/2]/(cols-1);\n else\n\txrange = [-cols/2:(cols/2-1)]/cols;\t\n end\n\n if mod(rows,2)\n\tyrange = [-(rows-1)/2:(rows-1)/2]/(rows-1);\n else\n\tyrange = [-rows/2:(rows/2-1)]/rows;\t\n end\n \n [x,y] = meshgrid(xrange, yrange);\n radius = sqrt(x.^2 + y.^2); % A matrix with every pixel = radius relative to centre.\n f = ifftshift( 1.0 ./ (1.0 + (radius ./ cutoff).^(2*n)) ); % The filter\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "imspect.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/imspect.m", "size": 4926, "source_encoding": "utf_8", "md5": "1567515542e483c4deb2ccc804ff7ac9", "text": "% IMSPECT - Plots image amplitude spectrum averaged over all orientations.\n%\n% Usage: [amp, f, slope] = imspect(im, nbins, lowcut)\n% \\ /\n% optional\n% Arguments:\n% im - Image to be analysed.\n% nbins - No of frequency bins to use (defaults to 100).\n% lowcut - Percentage of lower frequencies to ignore when\n% finding line of best fit. This avoids problems\n% with amplitude spikes at low frequencies. \n% (defaults to 2%) .\n%\n% Returns:\n% amp - 1D array of amplitudes.\n% f - Corresponding array of frequencies.\n% slope - Slope of line of best fit to the log-log data\n%\n% Be wary of using too many frequency bins. With more bins there will be \n% fewer elements per bin, or even none, producing a very noisy result.\n%\n% See also: PERFFT2\n\n% Copyright (c) 2001-2003 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% July 2001 - original version.\n% May 2003 - correction of frequency origin for even and odd size images.\n% - corrections to allow for non-square images.\n% - extra commenting\n% August 2014 - Changed to use perfft2 rather than fft2 to minimise edge effects\n\nfunction [amp, f, slope] = imspect(im, nbins, lowcut)\n \n if nargin < 2\n\tnbins = 100; % Default No of frequency 'bins'\n end\n if nargin < 3\n\tlowcut = 2; % Ignore lower 2% of curve when finding\n end % line of best fit.\n\n amp = zeros(1, nbins); % preallocate some memory\n fcount = ones(1, nbins);\n \n mag = fftshift(abs(perfft2(double(im)))); % Amplitude spectrum\n\n % Generate a matrix 'radius' every element of which has a value\n % given by its distance from the centre. This is used to index\n % the frequency values in the spectrum.\n [rows, cols] = size(im); \n [x,y] = meshgrid([1:cols],[1:rows]);\n\n % The following fiddles the origin to the correct position\n % depending on whether we have and even or odd size. \n % In addition the values of x and y are normalised to +- 0.5\n if mod(cols,2) == 0\n x = (x-cols/2-1)/cols;\n else\n x = (x-(cols+1)/2)/(cols-1);\n end\n if mod(rows,2) == 0\n y = (y-rows/2-1)/rows;\n else\n y = (y-(rows+1)/2)/(rows-1);\n end\n\n radius = sqrt(x.^2 + y.^2);\n\n % Quantise radius to the desired number of frequency bins\n radius = round(radius/max(max(radius))*(nbins-1)) + 1;\n \n % Now go through the spectrum and build the histogram of amplitudes\n % vs frequences.\n for r = 1:rows\n\tfor c = 1:cols\n\t ind = radius(r,c); \n\t amp(ind) = amp(ind)+mag(r,c);\n\t fcount(ind) = fcount(ind)+1;\n\tend\n end\n \n % Average the amplitude at each frequency bin. We also add 'eps'\n % to avoid potential problems later on in taking logs.\n amp = amp./fcount + eps; \n\n % Generate corrected frequency scale for each quantised frequency bin.\n % Note that the maximum frequency is sqrt(0.5) corresponding to the\n % points in the corners of the spectrum\n f = [1:nbins]/nbins*sqrt(.5); \n\n % Plots\n\n % Find first index value beyond the specified histogram cutoff\n fst = round(nbins*lowcut/100 + 1); \n \n figure(1), clf\n lw = 2; % Line width\n fs = 16; % Font size\n plot(f(fst:end),amp(fst:end), 'Linewidth', lw)\n xlabel('frequency'), ylabel('amplitude');\n title('Histogram of amplitude vs frequency');\n\n figure(2), % clf\n loglog(f(fst:end),amp(fst:end), 'Linewidth', lw)\n xlabel('log frequency', 'Fontsize', fs, 'Fontweight', 'bold');\n ylabel('log amplitude', 'Fontsize', fs, 'Fontweight', 'bold');\n \n % Find line of best fit (ignoring specified fraction of low frequency values) \n p = polyfit(log(f(fst:end)), log(amp(fst:end)),1);\n slope = p(1);\n y = exp(p(1)*log(f(fst:end)) + p(2)); % log(y) = p(1)*log(f) + p(2)\n hold on\n loglog(f(fst:end), y,'Color',[1 0 0], 'Linewidth', lw)\n\n n = round(nbins/5);\n text(f(n), amp(n)*2, sprintf('Slope = %.2f',p(1)), ...\n 'Fontsize', fs, 'Fontweight', 'bold');\n % title('Histogram of log amplitude vs log frequency');\n\n set(gca, 'FontSize', 14);\n set(gca, 'FontWeight', 'bold'); \n set(gca, 'LineWidth', 1.5); \n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "psf.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/psf.m", "size": 2323, "source_encoding": "utf_8", "md5": "de5c27f8dd4eb69a3ae36c1be3f20990", "text": "% PSF - Generates point spread functions for use with deconvolution fns.\n%\n% This function can generate a variety function shapes based around the\n% Butterworth filter. In plan view the filter can be elliptical and at\n% any orientation. The `squareness/roundness' of the shape can also be\n% manipulated.\n%\n% Usage: h = psf(sze, order, ang, eccen, rc, sqrness)\n%\n% sze - two element array specifying size of filter [rows cols]\n% order - an even integer specifying the order of the Butterworth filter.\n% This controls the sharpness of the cutoff.\n% ang - angle of rotation of the filter in radians\n% eccen - ratio of eccentricity of the filter shape (major/minor axis ratio)\n% rc - mean radius of the filter in pixels\n% sqrness - even integer specifying `squareness' of the filter shape\n% a value of 2 gives a circular filter (if eccen = 1), higher\n% values make the shape squarer. \n\n% Copyright (c) 1999 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% June 1999\n\nfunction h = psf(sze, order, ang, eccen, rc, sqrness)\n\n if mod(sqrness,2) ~=0\n\terror('squareness parameter must be an even integer');\n end\n \n rows = sze(1);\n cols = sze(2);\n \n x = ones(rows,1) * [1:cols] - (fix(cols/2)+1);\n y = [1:rows]' * ones(1,cols) - (fix(rows/2)+1);\n \n xp = x*cos(ang) - y*sin(ang); % Rotate axes by specified angle.\n yp = x*sin(ang) + y*cos(ang);\n \n x = sqrt(eccen)*xp; % Distort x and y according to eccentricity.\n y = yp/sqrt(eccen);\n \n radius = (x.^sqrness + y.^sqrness).^(1/sqrness); % Distort distance metric\n\t\t\t\t\t\t % by squareness measure.\n h = 1./(1+(radius./rc).^order); % Butterworth filter \n h = h./(sum(sum(h))); % and normalise.\n\t\t\t\t\t\t \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "filtergrid.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/filtergrid.m", "size": 2441, "source_encoding": "utf_8", "md5": "a196e165846902098ffcbc16ddf71f6c", "text": "% FILTERGRID Generates grid for constructing frequency domain filters\n%\n% Usage: [radius, u1, u2] = filtergrid(rows, cols)\n% [radius, u1, u2] = filtergrid([rows, cols])\n%\n% Arguments: rows, cols - Size of image/filter\n%\n% Returns: radius - Grid of size [rows cols] containing normalised\n% radius values from 0 to 0.5. Grid is quadrant\n% shifted so that 0 frequency is at radius(1,1)\n% u1, u2 - Grids containing normalised frequency values\n% ranging from -0.5 to 0.5 in x and y directions\n% respectively. u1 and u2 are quadrant shifted.\n%\n% Used by PHASECONGMONO, PHASECONG3 etc etc\n%\n\n% Copyright (c) 1996-2013 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n%\n% May 2013\n\nfunction [radius, u1, u2] = filtergrid(rows, cols)\n\n % Handle case where rows, cols has been supplied as a 2-vector\n if nargin == 1 & length(rows) == 2 \n tmp = rows;\n rows = tmp(1);\n cols = tmp(2);\n end\n \n % Set up X and Y spatial frequency matrices, u1 and u2, with ranges\n % normalised to +/- 0.5 The following code adjusts things appropriately for\n % odd and even values of rows and columns so that the 0 frequency point is\n % placed appropriately.\n if mod(cols,2)\n u1range = [-(cols-1)/2:(cols-1)/2]/(cols-1);\n else\n u1range = [-cols/2:(cols/2-1)]/cols; \n end\n \n if mod(rows,2)\n u2range = [-(rows-1)/2:(rows-1)/2]/(rows-1);\n else\n u2range = [-rows/2:(rows/2-1)]/rows; \n end\n \n [u1,u2] = meshgrid(u1range, u2range);\n \n % Quadrant shift so that filters are constructed with 0 frequency at\n % the corners\n u1 = ifftshift(u1);\n u2 = ifftshift(u2);\n \n % Construct spatial frequency values in terms of normalised radius from\n % centre. \n radius = sqrt(u1.^2 + u2.^2); \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "highpassfilter.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/highpassfilter.m", "size": 1443, "source_encoding": "utf_8", "md5": "78f60a0dd6f0ef66653d547868fad1f9", "text": "% HIGHPASSFILTER - Constructs a high-pass butterworth filter.\n%\n% usage: f = highpassfilter(sze, cutoff, n)\n% \n% where: sze is a two element vector specifying the size of filter \n% to construct [rows cols].\n% cutoff is the cutoff frequency of the filter 0 - 0.5\n% n is the order of the filter, the higher n is the sharper\n% the transition is. (n must be an integer >= 1).\n%\n% The frequency origin of the returned filter is at the corners.\n%\n% See also: LOWPASSFILTER, HIGHBOOSTFILTER, BANDPASSFILTER\n%\n% Copyright (c) 1999 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 1999\n\nfunction f = highpassfilter(sze, cutoff, n)\n \n if cutoff < 0 | cutoff > 0.5\n\terror('cutoff frequency must be between 0 and 0.5');\n end\n\n if rem(n,1) ~= 0 | n < 1\n\terror('n must be an integer >= 1');\n end\n \n f = 1.0 - lowpassfilter(sze, cutoff, n);\n \n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "circsine.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/circsine.m", "size": 4364, "source_encoding": "utf_8", "md5": "4b2d3f6974bd3cd11dde7d3b2a600790", "text": "% CIRCSINE Generates circular sine wave grating\r\n% Can also be use to construct phase congruent patterns\r\n%\r\n% Usage: im = circsine(sze, wavelength, nScales, ampExponent, offset, p, trim)\r\n%\r\n% Arguments:\r\n% sze - The size of the square image to be produced.\r\n% wavelength - The wavelength in pixels of the sine wave.\r\n% nScales - No of fourier components used to construct the\r\n% signal. This is typically 1, if you want a simple sine\r\n% wave, or >50 if you want to build a phase congruent\r\n% waveform. Defaults to 1.\r\n% ampExponent - Decay exponent of amplitude with frequency.\r\n% A value of -1 will produce amplitude inversely\r\n% proportional to frequency (this will produce a step\r\n% feature if offset is 0)\r\n% A value of -2 with an offset of pi/2 will result in a\r\n% triangular waveform.\r\n% Defaults to -1;\r\n% offset - Phase offset to apply to circular pattern.\r\n% This controls the feature type, see examples below.\r\n% Defaults to pi/2 if nScales is 1, else, 0\r\n% p - Optional parameter specifying the norm to use in\r\n% calculating the radius from the centre. This defaults to\r\n% 2, resulting in a circular pattern. Large values gives\r\n% a square pattern\r\n% trim - Optional flag indicating whether you want the\r\n% circular pattern trimmed from the corners leaving\r\n% only complete cicles. Defaults to 0.\r\n%\r\n% Examples:\r\n% nScales = 1 - You get a simple circular sine wave pattern \r\n% nScales 50, ampExponent -1, offset 0 - Square waveform\r\n% nScales 50, ampExponent -2, offset pi/2 - Triangular waveform\r\n% nScales 50, ampExponent -1.5, offset pi/4 - Something in between square and\r\n% triangular \r\n% nScales 50, ampExponent -1.5, offset 0 - Looks like a square but is not.\r\n%\r\n% See also: STARSINE, STEP2LINE\r\n\r\n\r\n% Copyright (c) 2003-2010 Peter Kovesi\r\n% Centre for Exploration Targeting\r\n% School of Earth and Environment\r\n% The University of Western Australia\r\n% peter.kovesi at uwa edu au\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in \r\n% all copies or substantial portions of the Software.\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n\r\n% May 2003 - Original version\r\n% Nov 2006 - Trim flag added\r\n% Dec 2010 - Ability to construct phase congruent patterns, order of argument\r\n% list changed\r\n\r\nfunction im = circsine(sze, wavelength, nScales, ampExponent, offset, p, trim)\r\n\r\n if ~exist('trim', 'var'), trim = 0; end\r\n if ~exist('p', 'var'), p = 2; end\r\n if ~exist('ampExponent', 'var'), ampExponent = -1; end\r\n if ~exist('nScales', 'var'), nScales = 1; end \r\n\r\n % If we have one scale, hence just making a sine wave, and offset is not\r\n % specified set it to pi/2 to give cintinuity at the centre\r\n if nScales == 1 && ~exist('offset', 'var')\r\n offset = pi/2; \r\n elseif ~exist('offset', 'var')\r\n offset = 0;\r\n end\r\n \r\n if mod(p,2)\r\n\terror('p should be an even number');\r\n end\r\n \r\n % Place origin at centre for odd sized image, and below and the the\r\n % right of centre for an even sized image\r\n if mod(sze,2) == 0 % even sized image\r\n\tl = -sze/2;\r\n\tu = sze/2-1;\r\n else\r\n\tl = -(sze-1)/2;\r\n\tu = (sze-1)/2;\r\n end\r\n \r\n [x,y] = meshgrid(l:u);\r\n r = (x.^p + y.^p).^(1/p);\r\n\r\n im = zeros(size(r));\r\n \r\n for scale = 1:2:(2*nScales-1)\r\n im = im + scale^ampExponent* sin(scale* r * 2*pi/wavelength + offset); \r\n end\r\n \r\n if trim % Remove circular pattern from the 'corners'\r\n\tcycles = fix(sze/2/wavelength); % No of complete cycles within sze/2\r\n\tim = im.* (r < cycles*wavelength) + (r>= cycles*wavelength);\r\n end\r\n \r\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "starsine.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/starsine.m", "size": 2906, "source_encoding": "utf_8", "md5": "929263192b6c499585f5af175f649a83", "text": "% STARSINE Generates phase congruent star shaped sine wave grating\r\n%\r\n% Usage: im = starsine(sze, nCycles, nScales, ampExponent, offset)\r\n%\r\n% Arguments:\r\n% sze - The size of the square image to be produced.\r\n% nCycles - The number of sine wave cycles around centre point.\r\n% Typically an integer, but any value can be used.\r\n% nScales - No of fourier components used to construct the\r\n% signal. This is typically 1, if you want a simple sine\r\n% wave, or >50 if you want to build a phase congruent\r\n% waveform.\r\n% ampExponent - Decay exponent of amplitude with frequency.\r\n% A value of -1 will produce amplitude inversely\r\n% proportional to frequency (this will produce a step\r\n% feature if offset is 0)\r\n% A value of -2 with an offset of pi/2 will result in a\r\n% triangular waveform.\r\n% offset - Phase offset to apply to star pattern.\r\n%\r\n% Examples:\r\n% nScales = 1 - You get a simple sine wave pattern radiating out\r\n% from the centre. Use 'offset' if you wish to\r\n% rotate it a bit.\r\n% nScales 50, ampExponent -1, offset 0 - Square waveform\r\n% nScales 50, ampExponent -2, offset pi/2 - Triangular waveform\r\n% nScales 50, ampExponent -1.5, offset pi/4 - Something in between square and\r\n% triangular \r\n% nScales 50, ampExponent -1.5, offset 0 - Looks like a square but is not.\r\n%\r\n% See also: CIRCSINE, STEP2LINE\r\n\r\n% Copyright (c) 2010 Peter Kovesi\r\n% Centre for Exploration Targeting\r\n% School of Earth and Enironment\r\n% The University of Western Australia\r\n% peter.kovesi at uwa edu au\r\n% \r\n% Permission is hereby granted, free of charge, to any person obtaining a copy\r\n% of this software and associated documentation files (the \"Software\"), to deal\r\n% in the Software without restriction, subject to the following conditions:\r\n% \r\n% The above copyright notice and this permission notice shall be included in \r\n% all copies or substantial portions of the Software.\r\n%\r\n% The Software is provided \"as is\", without warranty of any kind.\r\n\r\n% December 2010\r\n\r\nfunction im = starsine(sze, nCycles, nScales, ampExponent, offset)\r\n\r\n if ~exist('offset', 'var')\r\n\toffset = 0;\r\n end\r\n \r\n % Place origin at centre for odd sized image, and below and the the\r\n % right of centre for an even sized image\r\n if mod(sze,2) == 0 % even sized image\r\n\tl = -sze/2;\r\n\tu = sze/2-1;\r\n else\r\n\tl = -(sze-1)/2;\r\n\tu = (sze-1)/2;\r\n end\r\n \r\n [x,y] = meshgrid(l:u);\r\n theta = atan2(y,x);\r\n\r\n im = zeros(size(theta));\r\n \r\n for scale = 1:2:(nScales*2 - 1)\r\n im = im + scale^ampExponent*sin(scale*nCycles*theta + offset);\r\n end\r\n \r\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "freqcomp.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/freqcomp.m", "size": 5474, "source_encoding": "utf_8", "md5": "58a18bdbdc50fca6a82844487445c5ad", "text": "% FREQCOMP - Demonstrates image reconstruction from Fourier components\n%\n% Usage: recon = freqcomp(im, Npts, delay)\n%\n% Arguments: im - Image to be reconstructed.\n% Npts - Number of frequency components to consider\n% (defaults to 50).\n% delay - Optional time delay between animations of the\n% reconstruction. If this is omitted the function\n% waits for a key to be pressed before moving to\n% the next component.\n%\n% Returns: recon - The image reconstructed from the specified\n% number of components\n%\n% This program displays:\n%\n% * The image.\n% * The Fourier transform (spectrum) of the image with a conjugate\n% pair of Fourier components marked with red dots.\n% * The sine wave basis function that corresponds to the Fourier\n% transform pair marked in the image above. \n% * The reconstruction of the image generated from the sum of the sine\n% wave basis functions considered so far.\n\n% Copyright (c) 2002-2003 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% March 2002 - Original version\n% April 2003 - General cleanup of code\n\nfunction recon = freqcomp(im, Npts, delay)\n \n if ndims(im) == 3\n\tim = rgb2gray(im);\n\twarning('converting colour image to greyscale');\n end\n \n if nargin < 2\n\tNpts = 50;\n end\n \n [rows,cols] = size(im);\n \n % If necessary crop one row and/or column so that there are an even\n % number of rows and columns, this makes things easier later.\n if mod(rows,2) % odd\n\trows = rows-1;\n end\n if mod(cols,2) % odd\n\tcols = cols-1;\n end\n\n im = im(1:rows,1:cols);\n rc = fix(rows/2)+1; % Centre point\n cc = fix(cols/2)+1;\n\n % The following code constructs two arrays of coordinates within the FFT\n % of the image that correspond to complex conjugate pairs of points that\n % spiral out from the centre visiting every frequency component on\n % the way.\n p1 = zeros(Npts,2); % Path 1\n p2 = zeros(Npts,2); % Path 2\n \n m = zeros(rows,cols); % Matrix for marking visited points\n m(rc,cc) = 1;\n m(rc,cc-1) = 1;\n m(rc,cc+1) = 1; \n \n p1(1,:) = [rc cc-1];\n p2(1,:) = [rc cc+1]; \n d1 = [0 -1]; % initial directions of the paths\n d2 = [0 1];\n \n % Mark out two symmetric spiral paths out from the centre (I wish I\n % could think of a neater way of doing this)\n \n for n = 2:Npts\n\tl1 = [-d1(2) d1(1)]; % left direction\n\tl2 = [-d2(2) d2(1)];\t\n\t\n\tlp1 = p1(n-1,:) + l1; % coords of point in left direction\n\tlp2 = p2(n-1,:) + l2;\t\n\t\n\tif ~m(lp1(1), lp1(2)) % go left\n\t p1(n,:) = lp1;\n\t d1 = l1;\n\t m(p1(n,1), p1(n,2)) = 1; % mark point as visited\n\telse % go sraight ahead\n\t p1(n,:) = p1(n-1,:) + d1;\n\t m(p1(n,1), p1(n,2)) = 1; % mark point as visited\n\tend\n\n\tif ~m(lp2(1), lp2(2)) % go left\n\t p2(n,:) = lp2;\n\t d2 = l2;\n\t m(p2(n,1), p2(n,2)) = 1; % mark point as visited\n\telse % go sraight ahead\n\t p2(n,:) = p2(n-1,:) + d2;\n\t m(p2(n,1), p2(n,2)) = 1; % mark point as visited\n\tend\n\t\n end\n \n % Having constructed the path of frequency components to be visited\n % we take the FFT of the image and then enter a loop that\n % incrementally reconstructs the image from its components.\n \n IM = fftshift(fft2(im));\n recon = zeros(rows,cols); % Initialise reconstruction matrix\n \n if max(rows,cols) < 150\n\tfontsze = 7;\n else\n\tfontsze = 10;\n end\n \n figure(1), clf\n subplot(2,2,1),imagesc(im),colormap gray, axis image, axis off\n title('Original Image','FontSize',fontsze);\n subplot(2,2,2),imagesc(log(abs(IM))),colormap gray, axis image\n axis off, title('Fourier Transform + frequency component pair','FontSize',fontsze);\n \n warning off % Turn off warnings that might arise if the images cannot be\n % displayed full size\n truesize(1) \n\n for n = 1:Npts\n\t \n\t % Extract the pair of Fourier components\n\t F = zeros(rows,cols);\n\t F(p1(n,1), p1(n,2)) = IM(p1(n,1), p1(n,2));\n\t F(p2(n,1), p2(n,2)) = IM(p2(n,1), p2(n,2));\t \n\t \n\t % Invert and add to reconstruction\n\t f = real(ifft2(fftshift(F)));\n\t recon = recon+f;\n\t \n\t % Display results\n\t subplot(2,2,2),imagesc(log(abs(IM))),colormap gray, axis image\n axis off, title('Fourier Transform + frequency component pair','FontSize',fontsze);\n\t hold on, plot([p1(n,2), p2(n,2)], [p1(n,1), p2(n,1)],'r.'); hold off\n\t subplot(2,2,3),imagesc(recon),colormap gray, axis image, axis off, title('Reconstruction','FontSize',fontsze);\n\t subplot(2,2,4),imagesc(f),colormap gray, axis image, axis off\n\t title('Basis function corresponding to frequency component pair','FontSize',fontsze);\t \n\n\t if nargin == 3\n\t pause(delay);\n\t else\n\t fprintf('Hit any key to continue \\n'); pause\n\t end\n\t \n end\n \n warning on % Restore warnings\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "psf2.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/psf2.m", "size": 3000, "source_encoding": "utf_8", "md5": "20d5aff861110c5341b9d6fec90f8007", "text": "% PSF2 - Generates point spread functions for use with deconvolution fns.\n%\n% This function can generate a variety function shapes based around the\n% Butterworth filter. In plan view the filter can be elliptical and at\n% any orientation. The 'squareness/roundness' of the shape can also be\n% manipulated.\n%\n% Usage: h = psf2(sze, order, ang, lngth, width, sqrness)\n%\n% sze - two element array specifying size of filter [rows cols]\n% order - an even integer specifying the order of the Butterworth filter.\n% This controls the sharpness of the cutoff.\n% ang - angle of rotation of the filter in radians.\n% lngth - length of the filter in pixels along its major axis.\n% width - width of the filter in pixels along its minor axis.\n% sqrness - even integer specifying 'squareness' of the filter shape\n% a value of 2 gives a circular filter (if lngth == width), higher\n% values make the shape squarer. \n%\n% This function is almost identical to psf, it just has a different way of\n% specifying the function shape whereby length and width are defined\n% explicitly (rather than an average radius), this may be more convenient for\n% some applications.\n\n% Copyright (c) 1999-2003 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% June 1999\n% May 2003 - Changed arguments so that psf is specified in terms of a length\n% and width rather than an average radius.\n\nfunction h = psf2(sze, order, ang, lngth, width, sqrness)\n\n if mod(sqrness,2) ~=0\n\terror('squareness parameter must be an even integer');\n end\n \n rows = sze(1);\n cols = sze(2);\n \n [x,y] = meshgrid([1:cols],[1:rows]);\n\n % The following fiddles the origin to the correct position\n % depending on whether we have and even or odd size\n if mod(cols,2) == 0\n x = x-cols/2-1;\n else\n x = x-(cols+1)/2;\n end\n if mod(rows,2) == 0\n y = y-rows/2-1;\n else\n y = y-(rows+1)/2;\n end\n \n xp = x*cos(ang) - y*sin(ang); % Rotate axes by specified angle.\n yp = x*sin(ang) + y*cos(ang);\n \n rc = lngth/2; % Set cutoff radius to half the length \n yp = yp*lngth/width; % Adjust y measure to give appropriate relative width.\n \n radius = (xp.^sqrness + yp.^sqrness).^(1/sqrness); % Distort distance metric\n\t\t\t\t\t\t % by squareness measure.\n h = 1./(1+(radius./rc).^order); % Butterworth filter \n h = h./(sum(sum(h))); % and normalise.\n\t\t\t\t\t\t \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "perfft2.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/perfft2.m", "size": 3150, "source_encoding": "utf_8", "md5": "8216912bde513f4fbc7b59635da9d870", "text": "% PERFFT2 2D Fourier transform of Moisan's periodic image component\n%\n% Usage: [P, S, p, s] = perfft2(im)\n%\n% Argument: im - Image to be transformed\n% Returns: P - 2D fft of periodic image component\n% S - 2D fft of smooth component\n% p - Periodic component (spatial domain)\n% s - Smooth component (spatial domain)\n%\n% Moisan's \"Periodic plus Smooth Image Decomposition\" decomposes an image \n% into two components\n% im = p + s\n% where s is the 'smooth' component with mean 0 and p is the 'periodic'\n% component which has no sharp discontinuities when one moves cyclically across\n% the image boundaries. \n%\n% This wonderful decomposition is very useful when one wants to obtain an FFT of\n% an image with minimal artifacts introduced from the boundary discontinuities.\n% The image p gathers most of the image information but avoids periodization\n% artifacts.\n%\n% The typical use of this function is to obtain a 'periodic only' fft of an\n% image \n% >> P = perfft2(im);\n%\n% Displaying the amplitude spectrum of P will yield a clean spectrum without the\n% typical vertical-horizontal 'cross' arising from the image boundaries that you\n% would normally see.\n%\n% Note if you are using the function to perform filtering in the frequency\n% domain you may want to retain s (the smooth component in the spatial domain)\n% and add it back to the filtered result at the end. \n%\n% The computational cost of obtaining the 'periodic only' FFT involves taking an\n% additional FFT.\n%\n%\n% Reference: \n% This code is adapted from Lionel Moisan's Scilab function 'perdecomp.sci' \n% \"Periodic plus Smooth Image Decomposition\" 07/2012 available at\n%\n% http://www.mi.parisdescartes.fr/~moisan/p+s\n%\n% Paper:\n% L. Moisan, \"Periodic plus Smooth Image Decomposition\", Journal of\n% Mathematical Imaging and Vision, vol 39:2, pp. 161-179, 2011.\n\n% Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% peter.kovesi at uwa edu au\n% September 2012\n\nfunction [P, S, p, s] = perfft2(im)\n \n if ~isa(im, 'double'), im = double(im); end\n [rows,cols] = size(im);\n \n % Compute the boundary image which is equal to the image discontinuity\n % values across the boundaries at the edges and is 0 elsewhere\n s = zeros(size(im));\n s(1,:) = im(1,:) - im(end,:);\n s(end,:) = -s(1,:);\n s(:,1) = s(:,1) + im(:,1) - im(:,end);\n s(:,end) = s(:,end) - im(:,1) + im(:,end);\n \n % Generate grid upon which to compute the filter for the boundary image in\n % the frequency domain. Note that cos() is cyclic hence the grid values can\n % range from 0 .. 2*pi rather than 0 .. pi and then pi .. 0\n [cx, cy] = meshgrid(2*pi*[0:cols-1]/cols, 2*pi*[0:rows-1]/rows); \n \n % Generate FFT of smooth component\n S = fft2(s)./(2*(2 - cos(cx) - cos(cy)));\n \n % The (1,1) element of the filter will be 0 so S(1,1) may be Inf or NaN\n S(1,1) = 0; % Enforce 0 mean \n\n P = fft2(im) - S; % FFT of periodic component\n\n if nargout > 2 % Generate spatial domain results \n s = real(ifft2(S)); \n p = im - s; \n end\n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "invfft2shft.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/invfft2shft.m", "size": 308, "source_encoding": "utf_8", "md5": "1ee9d3b8e1e84f25b0fb5503595f7bfa", "text": "% INVFFT2SHFT - takes inverse fft, quadrant shifts and returns real part.\n%\n% Function to `wrap up' taking the inverse Fourier transform\n% quadrant shifting and extraction of the real part into the one operation\n\n% Peter Kovesi October 1999\n\nfunction ift = invfft2shft(ft)\nift = fftshift(real(ifft2(ft)));\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "quantizephase.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/quantizephase.m", "size": 1944, "source_encoding": "utf_8", "md5": "c4d5690a2daf54b63e4c2fd0ccecb488", "text": "% QUANTIZEPHASE Quantize phase values in an image\n%\n% Usage: qim = quantizephase(im, N)\n%\n% Arguments: im - Image to be processed\n% N - Desired number of quantized phase values \n%\n% Returns: qim - Phase quantized image\n%\n% Phase values in an image are important. However, despite this, they can be\n% quantized very heavily with little perceptual loss. The value of N can be\n% as low as 4, or even 3! Using N = 2 is also worth a look.\n%\n% \n\n% Copyright (c) 2011 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n% \n% The software is provided \"as is\", without warranty of any kind.\n\n% May 2011\n\nfunction qim = quantizephase(im, N)\n \n IM = fft2(im);\n amp = abs(IM);\n phase = angle(IM);\n \n % Quantize the phase values as follows:\n % Add pi - .001 so that values range [0 - 2pi)\n % Divide by 2pi so that values range [0 - 1)\n % Scale by N so that values range [0 - N)\n % Round twoards 0 using fix giving integers [0 - N-1]\n % Scale by 2*pi/N to give N discrete phase values [0 - 2*pi)\n % Subtract pi so that discrete values range [-pi - pi)\n % Add pi/N to counteract the phase shift induced by rounding towards 0\n % using fix.\n phase = fix( (phase+pi-.001)/(2*pi) * N) * (2*pi)/N - pi + pi/N ;\n % figure, hist(phase(:),100)\n\n % Reconstruct Fourier transform with quantized phase values and take inverse\n % to obtain the new image.\n QIM = amp.*(cos(phase) + i*sin(phase));\n qim = real(ifft2(QIM)); \n \n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "homomorphic.m", "ext": ".m", "path": "SeAMS-master/Utilities/MatlabFns/FrequencyFilt/homomorphic.m", "size": 5424, "source_encoding": "utf_8", "md5": "51155a84aab5eba10f502eb788a81b16", "text": "% HOMOMORPHIC - Performs homomorphic filtering on an image.\n%\n% Function performs homomorphic filtering on an image. This form of\n% filtering sharpens features and flattens lighting variantions in an image.\n% It usually is very effective on images which have large variations in\n% lighting, for example when a subject appears against strong backlighting.\n%\n%\n% Usage: newim =\n% homomorphic(inimage,boost,CutOff,order,lhistogram_cut,uhistogram_cut, hndl)\n% homomorphic(inimage,boost,CutOff,order,lhistogram_cut,uhistogram_cut)\n% homomorphic(inimage,boost,CutOff,order,hndl)\n% homomorphic(inimage,boost,CutOff,order)\n%\n% Parameters: (suggested values are in brackets)\n% boost - The ratio that high frequency values are boosted\n% relative to the low frequency values (2).\n% CutOff - Cutoff frequency of the filter (0 - 0.5)\n% order - Order of the modified Butterworth style filter that\n% is used, this must be an integer > 1 (2)\n% lhistogram_cut - Percentage of the lower end of the filtered image's\n% histogram to be truncated, this eliminates extreme\n% values in the image from distorting the final result. (0)\n% uhistogram_cut - Percentage of upper end of histogram to truncate. (5)\n% hndl - Optional handle to text box for updating\n% messages to be sent to a GUI interface.\n%\n% If lhistogram_cut and uhistogram_cut are not specified no histogram truncation will be\n% applied.\n%\n%\n% Suggested values: newim = homomorphic(im, 2, .25, 2, 0, 5);\n%\n\n% homomorphic called with no arguments invokes GUI interface.\n%\n% or simply homomorphic to invoke the GUI - GUI version does not work!\n\n% Copyright (c) 1999-2001 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% June 1999\n% December 2001 cleaned up and modified to work with colour images\n\nfunction him = homomorphic(im, boost, CutOff, order, varargin)\n \n\n% if nargin == 0 % invoke GUI if it exists\n%\tif exist('homomorphicGUI.m');\n%\t homomorphicGUI;\n%\t return;\n%\telse\n%\t error('homomorphicGUI does not exist');\n%\tend\n% \n% else\n \n\tif ndims(im) == 2 % Greyscale image\n\t him = Ihomomorphic(im, boost, CutOff, order, varargin);\n\t \n\telse % Assume colour image in RGB format\n\t hsv = rgb2hsv(im); % Convert to HSV and apply homomorphic\n\t\t\t\t % filtering to just the intensity component.\n hsv(:,:,3) = Ihomomorphic(hsv(:,:,3), boost, CutOff, order, varargin);\n\t him = hsv2rgb(hsv); % Convert back to RGB\n\tend\n\t\n% end\n \n%------------------------------------------------------------------------\n% Internal function that does the real work\n%------------------------------------------------------------------------ \n\t\nfunction him = Ihomomorphic(im, boost, CutOff, order, varargin)\n\n % The possible elements in varargin are:\n % {lhistogram_cut, uhistogram_cut, hndl}\n\n varargin = varargin{:};\n \n if nargin == 5\n\tnopparams = length(varargin);\n end\n \n if (nopparams == 3)\n\tdispStatus = 1;\n\ttruncate = 1;\n\tlhistogram_cut = varargin{1};\n\tuhistogram_cut = varargin{2};\t\n\thndl = varargin{3};\t\t\n elseif (nopparams == 2)\n\tdispStatus = 0;\n\ttruncate = 1;\n\tlhistogram_cut = varargin{1};\n\tuhistogram_cut = varargin{2};\t\n elseif (nopparams == 1)\n\tdispStatus = 1;\n\ttruncate = 0;\n\thndl = varargin{1};\t\t\t\n elseif (nopparams == 0)\n\tdispStatus = 0;\n\ttruncate = 0;\n else\n\tdisp('Usage: newim = homomorphic(inimage,LowGain,HighGain,CutOff,order,lhistogram_cut,uhistogram_cut)');\n\terror('or newim = homomorphic(inimage,LowGain,HighGain,CutOff,order)');\n end\n \n [rows,cols] = size(im);\n \n im = normalise(im); % Rescale values 0-1 (and cast\n\t\t\t\t\t % to `double' if needed).\n FFTlogIm = fft2(log(im+.01)); % Take FFT of log (with offset\n % to avoid log of 0).\n h = highboostfilter([rows cols], CutOff, order, boost);\n him = exp(real(ifft2(FFTlogIm.*h))); % Apply the filter, invert\n\t\t\t\t\t % fft, and invert the log.\n\n if truncate\n\t\t\t\t\t\t \n\t% Problem:\n\t% The extreme bright values in the image are exaggerated by the filtering. \n\t% These (now very) bright values have the overall effect of darkening the\n\t% whole image when we rescale values to 0-255.\n\t%\n\t% Solution:\n\t% Construct a histogram of the image. Find the level below which a high\n\t% percentage of the image lies (say 95%). Saturate the grey levels in\n\t% the image to this level.\n\t\n\tif dispStatus\n\t set(hndl,'String','Calculating histogram and truncating...');\n\t drawnow;\n\telse\n\t disp('Calculating histogram and truncating...');\n\tend\n\t\n\thim = histtruncate(him, lhistogram_cut, uhistogram_cut);\n\n else\n\thim = normalise(him); % No truncation, but fix range 0-1\n end\n \n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "uigetvariables.m", "ext": ".m", "path": "SeAMS-master/Utilities/Miscellaneous/uigetvariables.m", "size": 16902, "source_encoding": "utf_8", "md5": "f4620a99811d119011fab23a47c295ed", "text": "function varout = uigetvariables(prompts,intro,types,ndimensions)\r\n%%\r\n% uigetvariables Open variable selection dialog box\r\n%\r\n% VARS = uigetvariables(PROMPTS) creates a dialog box that returns\r\n% variables selected from the base workspace. PROMPTS is a cell array of\r\n% strings, with one entry for each variable you would like the user to\r\n% select. VARS is a cell array containing the selected variables. Each\r\n% element of VARS corresponds with the selection for the same element of\r\n% PROMPTS.\r\n%\r\n% If the user hits CANCEL or dismisses the dialog, VARS is an empty cell\r\n% array. If the user does not select a variable for a given prompt, the\r\n% value in VARS for that prompt is an empty array.\r\n%\r\n% VARS = uigetvariables(PROMPTS,INTRO) includes introductory text to guide the user\r\n% of the dialog. INTRO is a string. If INTRO is not specified, no\r\n% introduction is included. The text in INTRO is wrapped automatically to\r\n% fit in the dialog.\r\n%\r\n% VARS = uigetvariables(PROMPTS,INTRO,TYPES) restricts the types of the variables\r\n% which can be selected for each prompt. TYPES is a cell array of strings\r\n% of the same length as PROMPTS, each entry specifies the allowable type of\r\n% variables for each prompt. The elements of TYPES may be any of the\r\n% following:\r\n% any Any type. Use this if you don't care.\r\n% numeric Any numeric type, as determined by isnumeric\r\n% logical Logical\r\n% string String or cell array of strings\r\n%\r\n% vars = uigetvariables(PROMPTS,INTRO,TYPES,NDIMENSIONS) also specifies required\r\n% dimensionality of variables. NDIMENSIONS is a numeric array of length PROMPTS,\r\n% with each element specifying the required dimensionality of the variables\r\n% for the corresponding element of PROMPTS. NDIMENSIONS works a little\r\n% different from ndims, in that it allows you to distinguish among scalars,\r\n% vectors, and matrices.\r\n% Allowable values are:\r\n%\r\n% Value Meaning\r\n% ------------ ----------\r\n% Inf Any size. Use this if you don't care, or want more than one allowable size\r\n% 0 Scalar (1x1)\r\n% 1 Vector (1xN or Nx1)\r\n% 2 Matrix (NxM)\r\n% 3 or higher Specified number of dimensions\r\n%\r\n% vars = uigetvariables(PROMPTS,INTRO,VALFCN) applies an arbitrary\r\n% validation function to determine which variables are valid for each\r\n% prompt. VALFCN is either a single function handle, or a cell array of\r\n% function handles of same length as PROMPTS. If VALFCN is a single\r\n% function handle, it is applied to every prompt. Use a cell array of\r\n% function handles to specify a unique validation function for each prompt.\r\n% VALFCN must return true if a variable passes the validation or false if\r\n% the variable does not. Syntax of VALFCN must be \r\n% TF = VALFCN(variable)\r\n%\r\n% Examples\r\n%\r\n% % Put some sample data in your base workspace:\r\n% scalar1 = 1;\r\n% str1 = 'a string';\r\n% cellstr1 = {'a string';'in a cell'};cellstr2 = {'another','string','in','a','cell'}; \r\n% cellstr3 = {'1','2';,'3','4'}\r\n% vector1 = rand(1,10); vector2 = rand(5,1);\r\n% array1 = rand(5,5); array2 = rand(5,5); array3 = rand(10,10);\r\n% threed1 = rand(3,4,5);\r\n% fourd1 = rand(1,2,3,4);\r\n%\r\n% % Select any two variables from entire workspace\r\n% tvar = uigetvariables({'Please select any variable','And another'});\r\n% \r\n% % Include introductory text\r\n% tvar = uigetvariables({'Please select any variable','And another'},'Here are some very detailed directions about how you should use this dialog. Pick one variable, then pick another variable.');\r\n% \r\n% % Control type of variables\r\n% tvar = uigetvariables({'Pick a number:','Pick a string:','Pick another number:'},[],{'numeric','string','numeric'});\r\n% \r\n% % Control size of variables.\r\n% tvar = uigetvariables({'Pick a scalar:','Pick a vector:','Pick a matrix:'},[],[],[0 1 2]);\r\n% \r\n% % Control type and size of variables\r\n% tvar = uigetvariables({'Pick a scalar:','Pick a string','Pick a 4D array'},[],{'numeric','string','numeric'},[0 Inf 4]);\r\n% tvar = uigetvariables({'Pick a scalar:','Pick a string vector','Pick a 3D array'},[],{'numeric','string','numeric'},[0 1 3]);\r\n% \r\n% % Advanced - use custom validation functions\r\n% \r\n% % Custom validation functions\r\n% tvar = uigetvariables({'Pick a number:','Any number:','One more, please:'},'Use a custom validation function to require every input to be numeric',@isnumeric);\r\n% tvar = uigetvariables({'Pick a number:','Pick a cell string:','Pick a 3D array:'},[],{@isnumeric,@iscellstr,@(x) ndims(x)==3});\r\n% \r\n% % No variable found\r\n% tvar = uigetvariables('Pick a 6D numeric array:','What if there is no valid data?',@(x) isnumeric(x)&&ndims(x)==6);\r\n\r\n% Scott Hirsch\r\n% Scott.Hirsch@mathworks.com\r\n\r\n% Copyright 2010-2013 The Mathworks Inc\r\n\r\n\r\n% Allow for single prompt as string\r\nif ~iscell(prompts)\r\n prompts = {prompts};\r\nend\r\n\r\nif nargin<2 || isempty(intro)\r\n intro = '';\r\nend\r\n\r\nnPrompts = length(prompts);\r\n\r\n% Assume the user didn't specify validation function\r\nspecifiedValidationFcn = false;\r\n\r\n%% \r\nif nargin==3 && ~isempty(types) % See if I've got function handle\r\n % Grab the first value from cell to test type\r\n if iscell(types)\r\n test = types{1};\r\n else\r\n test = types;\r\n end\r\n \r\n switch class(test)\r\n case 'function_handle'\r\n % Put \"types\" input variable into valfcn\r\n % Replicate a single function handle into a cell array if necessary\r\n if ~iscell(types)\r\n valfcn = cell(nPrompts,1);\r\n valfcn = cellfun(@(f) types,valfcn,'UniformOutput',false);\r\n else\r\n valfcn = types;\r\n end\r\n specifiedValidationFcn = true;\r\n end\r\nend\r\n\r\n%% \r\n% If the user didn't specify the validation function, we will build it for\r\n% them. \r\nif ~specifiedValidationFcn\r\n if nargin<3 || isempty(types)\r\n types = cellstr(repmat('any',nPrompts,1));\r\n elseif length(types)==1 % allow for single prompt with single type\r\n types = {types};\r\n end\r\n \r\n if nargin<4 || isempty(ndimensions)\r\n ndimensions = inf(1,nPrompts);\r\n end\r\n \r\n % Base validation functions to choose from:\r\n isscalarfcn = @(var) numel(var)==1;\r\n isvectorfcn = @(var) length(size(var))==2&&any(size(var)==1)&&~isscalarfcn(var);\r\n isndfcn = @(var,dim) ndims(var)==dim && ~isscalar(var) && ~isvectorfcn(var);\r\n \r\n isanyfcn = @(var) true; % What an optimistic function! :)\r\n isnumericfcn = @(var) isnumeric(var);\r\n islogicalfcn = @(var) islogical(var);\r\n isstringfcn = @(var) ischar(var) | iscellstr(var);\r\n\r\n valfcn = cell(1,nPrompts);\r\n \r\n for ii=1:nPrompts\r\n \r\n switch types{ii}\r\n case 'any'\r\n valfcn{ii} = isanyfcn;\r\n case 'numeric'\r\n valfcn{ii} = isnumericfcn;\r\n case 'logical'\r\n valfcn{ii} = islogicalfcn;\r\n case 'string'\r\n valfcn{ii} = isstringfcn;\r\n otherwise\r\n valfcn{ii} = isanyfcn;\r\n end\r\n \r\n switch ndimensions(ii)\r\n case 0 % 0 - scalar\r\n valfcn{ii} = @(var) isscalarfcn(var) & valfcn{ii}(var);\r\n case 1 % 1 - vector\r\n valfcn{ii} = @(var) isvectorfcn(var) & valfcn{ii}(var);\r\n case Inf % Inf - Any shape\r\n valfcn{ii} = @(var) isanyfcn(var) & valfcn{ii}(var);\r\n otherwise % ND\r\n valfcn{ii} = @(var) isndfcn(var,ndimensions(ii)) & valfcn{ii}(var);\r\n end\r\n end\r\nend\r\n\r\n\r\n%% Get list of variables in base workspace\r\nallvars = evalin('base','whos');\r\nnVars = length(allvars);\r\nvarnames = {allvars.name};\r\nvartypes = {allvars.class};\r\nvarsizes = {allvars.size};\r\n\r\n\r\n% Convert variable sizes from numbers:\r\n% [N M], [N M P], ... etc\r\n% to text:\r\n% NxM, NxMxP\r\nvarsizes = cellfun(@mat2str,varsizes,'UniformOutput',false);\r\n%too lazy for regexp. Strip off brackets\r\nvarsizes = cellfun(@(s) s(2:end-1),varsizes,'UniformOutput',false);\r\n% replace blank with x\r\nvarsizes = strrep(varsizes,' ','x');\r\n\r\nvardisplay = strcat(varnames,' (',varsizes,{' '},vartypes,')');\r\n\r\n%% Build list of variables for each prompt\r\n% Also include one that's prettied up a bit for display, which has an extra\r\n% first entry saying '(select one)'. This allows for no selection, for\r\n% optional input arguments.\r\nvalidVariables = cell(nPrompts,1);\r\nvalidVariablesDisplay = cell(nPrompts,1); \r\n\r\nfor ii=1:nPrompts\r\n % turn this into cellfun once I understand what I'm doing.\r\n assignin('base','validationfunction_',valfcn{ii})\r\n validVariables{ii} = cell(nVars,1);\r\n validVariablesDisplay{ii} = cell(nVars+1,1);\r\n t = false(nVars,1);\r\n for jj = 1:nVars\r\n t(jj) = evalin('base',['validationfunction_(' varnames{jj} ');']);\r\n end\r\n if any(t) % Found at least one variable\r\n validVariables{ii} = varnames(t);\r\n validVariablesDisplay{ii} = vardisplay(t);\r\n validVariablesDisplay{ii}(2:end+1) = validVariablesDisplay{ii};\r\n validVariablesDisplay{ii}{1} = '(select one)';\r\n else\r\n validVariables{ii} = '(no valid variables)';\r\n validVariablesDisplay{ii} = '(no valid variables)';\r\n end\r\n \r\n evalin('base','clear validationfunction_')\r\nend\r\n\r\n\r\n%% Compute layout\r\noffset = 1;\r\nmaxStringLength = max(cellfun(@(s) length(s),prompts));\r\ncomponentWidth = max([maxStringLength, 50]);\r\ncomponentHeight = 1;\r\n\r\n% Buttons\r\nbuttonHeight = 1.77;\r\nbuttonWidth = 10.6;\r\n\r\n\r\n% Wrap intro string. Need to do this now to include height in dialog.\r\n% Could use textwrap, which comes with MATLAB, instead of linewrap. This would just take a\r\n% bit more shuffling around with the order I create and size things.\r\nif ~isempty(intro)\r\n intro = linewrap(intro,componentWidth);\r\n introHeight = length(intro); % Intro is now an Nx1 cell string\r\nelse\r\n introHeight = 0;\r\nend\r\n\r\n\r\ndialogWidth = componentWidth + 2*offset;\r\ndialogHeight = 2*nPrompts*(componentHeight+offset) + buttonHeight + offset + introHeight;\r\n\r\n% Component positions, starting from bottom of figure\r\npopuppos = [offset 2*offset+buttonHeight componentWidth componentHeight];\r\ntextpos = popuppos; textpos(2) = popuppos(2)+componentHeight;\r\n\r\n%% Build figure\r\n% hFig = dialog('Units','Characters','WindowStyle','modal','Name','Select variable(s)','CloseRequestFcn',@nestedCloseReq);\r\nhFig = dialog('Units','Characters','WindowStyle','normal','Name','Select variable(s)','CloseRequestFcn',@nestedCloseReq);\r\n% set(hFig,'DefaultUicontrolFontSize',10)\r\n% set(hFig,'DefaultUicontrolFontName','Arial')\r\n \r\npos = get(hFig,'Position');\r\nset(hFig,'Position',[pos(1:2) dialogWidth dialogHeight])\r\nuicontrol('Parent',hFig,'style','Pushbutton','Callback',@nestedCloseReq,'String','OK', 'Units','characters','Position',[dialogWidth-2*offset-2*buttonWidth .5*offset buttonWidth buttonHeight]);\r\nuicontrol('Parent',hFig,'style','Pushbutton','Callback',@nestedCloseReq,'String','Cancel','Units','characters','Position',[dialogWidth-offset-buttonWidth .5*offset buttonWidth buttonHeight]);\r\n\r\n\r\nfor ii=nPrompts:-1:1\r\n uicontrol('Parent',hFig,'Style','text', 'Units','char','Position',textpos, 'String',prompts{ii},'HorizontalAlignment','left');\r\n hPopup(ii) = uicontrol('Parent',hFig,'Style','popupmenu','Units','char','Position',popuppos,'String',validVariablesDisplay{ii},'UserData',validVariables{ii});\r\n \r\n % Set up positions for next go round\r\n popuppos(2) = popuppos(2) + 1.5*offset + 2*componentHeight;\r\n textpos(2) = textpos(2) + 1.5*offset + 2*componentHeight;\r\nend\r\n\r\nif ~isempty(intro)\r\n intropos = [offset dialogHeight-introHeight-1 componentWidth introHeight+.5];\r\n uicontrol('Parent',hFig,'Style','text','Units','Characters','Position',intropos, 'String',intro,'HorizontalAlignment','left');\r\nend\r\n\r\nuiwait(hFig)\r\n\r\n\r\n function nestedCloseReq(obj,~)\r\n % How did I get here?\r\n % If pressed OK, get variables. Otherwise, don't.\r\n \r\n if strcmp(get(obj,'type'),'uicontrol') && strcmp(get(obj,'String'),'OK')\r\n for ind=1:nPrompts\r\n str = get(hPopup(ind),'UserData'); % Store real variable name here\r\n val = get(hPopup(ind),'Value')-1; % Remove offset to account for '(select one)' as initial entry\r\n \r\n if val==0 % User didn't select anything\r\n varout{ind} = [];\r\n elseif strcmp(str,'(no valid variables)')\r\n varout{ind} = [];\r\n else\r\n varout{ind} = evalin('base',str{val});\r\n end\r\n end\r\n else % Cancel - return empty\r\n varout = {};\r\n end\r\n \r\n delete(hFig)\r\n \r\n end\r\nend\r\n\r\n\r\n\r\n\r\nfunction c = linewrap(s, maxchars)\r\n%LINEWRAP Separate a single string into multiple strings\r\n% C = LINEWRAP(S, MAXCHARS) separates a single string into multiple\r\n% strings by separating the input string, S, on word breaks. S must be a\r\n% single-row char array. MAXCHARS is a nonnegative integer scalar\r\n% specifying the maximum length of the broken string. C is a cell array\r\n% of strings.\r\n%\r\n% C = LINEWRAP(S) is the same as C = LINEWRAP(S, 80).\r\n%\r\n% Note: Words longer than MAXCHARS are not broken into separate lines.\r\n% This means that C may contain strings longer than MAXCHARS.\r\n%\r\n% This implementation was inspired a blog posting about a Java line\r\n% wrapping function:\r\n% http://joust.kano.net/weblog/archives/000060.html\r\n% In particular, the regular expression used here is the one mentioned in\r\n% Jeremy Stein's comment.\r\n%\r\n% Example\r\n% s = 'Image courtesy of Joe and Frank Hardy, MIT, 1993.'\r\n% c = linewrap(s, 40)\r\n%\r\n% See also TEXTWRAP.\r\n\r\n% Steven L. Eddins\r\n% $Revision: 1.7 $ $Date: 2006/02/08 16:54:51 $\r\n\r\n% http://www.mathworks.com/matlabcentral/fileexchange/9909-line-wrap-a-string\r\n% Copyright (c) 2009, The MathWorks, Inc.\r\n% All rights reserved.\r\n% \r\n% Redistribution and use in source and binary forms, with or without \r\n% modification, are permitted provided that the following conditions are \r\n% met:\r\n% \r\n% * Redistributions of source code must retain the above copyright \r\n% notice, this list of conditions and the following disclaimer.\r\n% * Redistributions in binary form must reproduce the above copyright \r\n% notice, this list of conditions and the following disclaimer in \r\n% the documentation and/or other materials provided with the distribution\r\n% * Neither the name of the The MathWorks, Inc. nor the names \r\n% of its contributors may be used to endorse or promote products derived \r\n% from this software without specific prior written permission.\r\n% \r\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \r\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \r\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \r\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \r\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \r\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \r\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \r\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \r\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \r\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \r\n% POSSIBILITY OF SUCH DAMAGE.\r\n\r\nnarginchk(1, 2);\r\n\r\nbad_s = ~ischar(s) || (ndims(s) > 2) || (size(s, 1) ~= 1); %#ok\r\nif bad_s\r\n error('S must be a single-row char array.');\r\nend\r\n\r\nif nargin < 2\r\n % Default value for second input argument.\r\n maxchars = 80;\r\nend\r\n\r\n% Trim leading and trailing whitespace.\r\ns = strtrim(s);\r\n\r\n% Form the desired regular expression from maxchars.\r\nexp = sprintf('(\\\\S\\\\S{%d,}|.{1,%d})(?:\\\\s+|$)', maxchars, maxchars);\r\n\r\n% Interpretation of regular expression (for maxchars = 80):\r\n% '(\\\\S\\\\S{80,}|.{1,80})(?:\\\\s+|$)'\r\n%\r\n% Match either a non-whitespace character followed by 80 or more\r\n% non-whitespace characters, OR any sequence of between 1 and 80\r\n% characters; all followed by either one or more whitespace characters OR\r\n% end-of-line.\r\n\r\ntokens = regexp(s, exp, 'tokens').';\r\n\r\n% Each element if the cell array tokens is single-element cell array \r\n% containing a string. Convert this to a cell array of strings.\r\nget_contents = @(f) f{1};\r\nc = cellfun(get_contents, tokens, 'UniformOutput', false);\r\n\r\n% Remove trailing whitespace characters from strings in c. This can happen\r\n% if multiple whitespace characters separated the last word on a line from\r\n% the first word on the following line.\r\nc = deblank(c);\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "manual_thresh.m", "ext": ".m", "path": "SeAMS-master/Utilities/manual_thresh/manual_thresh.m", "size": 19169, "source_encoding": "utf_8", "md5": "2792d784903dcb7c3d71724a8f33502a", "text": "function [level,level2,bw] = manual_thresh(im,cmap,defaultLevel) %mainfunction\r\n% manual_thresh Interactively select intensity levels band for image thresholding.\r\n% manual_thresh launches a GUI (graphical user interface) for thresholding\r\n% an intensity input image, IM. IM is displayed in the top of the figure . A \r\n% colorbar and IM's histogram are displayed on the bottom. lines on the\r\n% histogram indicates the current threshold levels. The segmented image\r\n% (with the intensity levels between the low and high threshold levels is\r\n% displayed as a upper layer with tranperent background on the top of the image. To change the\r\n% level, click and drag the lines or use the editable text or sliders. The output image updates automatically.\r\n% \r\n% There are two ways to use this tool.\r\n% \r\n% Mode 1 - nonblocking behavior:\r\n% manual_thresh (IM) launches GUI tool. You can continue using the MATLAB\r\n% Desktop. Since no results are needed, the function does not block\r\n% execution of other commands.\r\n% \r\n% manual_thresh (IM,CMAP) allows the user to specify the colormap, CMAP. If\r\n% not specified, the default colormap is used.\r\n% \r\n% manual_thresh (IM,CMAP,DEFAULTLEVEL) allows the user to specify the\r\n% default low threshold level. If not specified, DEFAULTLEVEL is determined\r\n% by GRAYTHRESH. Valid values for DEFAULTLEVEL must be consistent with\r\n% the data type of IM for integer intensity images: uint8 [0,255], uint16\r\n% [0,65535], int16 [-32768,32767].\r\n% \r\n% Example\r\n% x = imread('coins.png');\r\n% manual_thresh(x) %no return value, so MATLAB keeps running\r\n% \r\n% Mode 2 - blocking behavior:\r\n% [LOW LEVEL, HIGH LEVEL] = manual_thresh (...) returns the user selected levels, LOW LEVEL $ HIGH LEVEL, and\r\n% MATLAB waits for the result before proceeding. This blocking behavior\r\n% mode allows the tool to be inserted into an image processing algorithm\r\n% to support an automated workflow.\r\n% \r\n% [LOW LEVEL, HIGH LEVEL,BW] = manual_thresh(...) also returns the thresholded binary \r\n% output image, BW.\r\n% \r\n% Example\r\n% x = imread('coins.png');\r\n% [LOW LEVEL, HIGH LEVEL] = manual_thresh(x') %MATLAB waits for GUI tool to finish\r\n\r\n% By Yishay Tauber JSC,Physics department,Bar Ilan University,Israel.\r\n% Based on thresh_tool by Robert Bemis found in MATLAB CENTRAL\r\n \r\n\r\n\r\n%defensive programming\r\nerror(nargchk(1,3,nargin))\r\nerror(nargoutchk(0,3,nargout))\r\n\r\n%validate defaultLevel within range\r\nif nargin>2 %user specified DEFAULTLEVEL\r\n dataType = class(im);\r\n switch dataType\r\n case {'uint8','uint16','int16'}\r\n if defaultLevelintmax(dataType)\r\n error(['Specified DEFAULTLEVEL outside class range for ' dataType])\r\n elseif defaultLevelmax(im(:))\r\n error('Specified DEFAULTLEVEL outside data range for IM')\r\n end\r\n case{ 'double','single'}\r\n %okay, do nothing\r\n otherwise\r\n error(['Unsupport image type ' dataType])\r\n end %switch\r\nend\r\n\r\nmax_colors=1000; %practical limit\r\n\r\n%calculate bins centers\r\ncolor_range = double(limits(im));\r\nif isinteger(im)\r\n %try direct indices first\r\n num_colors = diff(color_range)+1;\r\n if num_colorsmax_colors %too many levels\r\n num_colors = max_colors; %practical limit\r\n di = diff(color_range)/(num_colors-1);\r\n end\r\nend\r\nbin_ctrs = [color_range(1):di:color_range(2)];\r\n%new figure - interactive GUI tool for level segmenting\r\nscrsz = get(0,'ScreenSize');\r\n\r\nh_fig = figure('Position',[ scrsz(3)/10 scrsz(4)/10 8*scrsz(3)/10 8*scrsz(4)/10]);\r\nset(h_fig,'ToolBar','Figure')\r\nif nargin>1 && isstr(cmap) && strcmp(lower(cmap),'jet')\r\n full_map = jet(num_colors);\r\nelseif nargin>1 && isnumeric(cmap) && length(size(cmap))==2 && size(cmap,2)==3\r\n full_map = cmap;\r\nelse\r\nfull_map = gray (num_colors);\r\nend\r\n h_ax1 = axes('unit','norm','pos',[0.1 0.25 0.8 0.7]);\r\nsetappdata(h_fig,'im',im)\r\n%top - input image\r\n colormap(full_map);\r\nimagesc(im);\r\naxis image\r\naxis off\r\n hold on\r\nsizeim=size(im);\r\nlayer=ones (sizeim(1),sizeim(2));\r\nback=ind2rgb(layer,[1 0 0]);\r\nthreshimage=image(back);\r\naxis image\r\naxis off\r\nsetappdata (h_fig,'threshimage',threshimage);\r\n% bottom - color bar\r\ncbar=colorbar('location','southoutside');\r\nset(cbar,'unit','norm','Position',[0.05 0.05 0.9 0.05]);\r\nset(cbar,'xlim',[0 color_range(2)],'xtick',[0 color_range(2)])\r\n\r\n\r\n%next to bottom - intensity distribution\r\nh_hist = axes('unit','norm','pos',[0.05 0.1 0.9 0.1]);\r\nn = hist(double(im(:)),bin_ctrs);\r\nbar(bin_ctrs,n)\r\n\r\naxis([[0 color_range(2)+1] limits(n(2:end-1))]) %ignore saturated end scaling\r\nset(h_hist,'xtick',[],'ytick',[])\r\ntitle('Intensity Distribution')\r\n%threshold level - initial guess (graythresh)\r\nlo = double(color_range(1));\r\n hi = double(color_range(2));\r\nif nargin>2 %user specified default level\r\n low_level = defaultLevel;\r\nelse %graythresh default\r\n \r\n norm_im = (double(im)-lo)/(hi-lo);\r\n norm_level = graythresh(norm_im); %GRAYTHRESH assumes DOUBLE range [0,1]\r\n low_level = norm_level*(hi-lo)+lo;\r\nend\r\nhigh_level=hi;\r\n%uicontrols (text edit & slider)\r\nlow_level_edit = uicontrol('Style','edit','unit','norm','Position',[0.055,0.8,0.05,0.03]);\r\nset(low_level_edit,'BackgroundColor','white','String',num2str(floor(low_level)),'callback',@low_level_edit_Callback);\r\nsetappdata(h_fig,'low_level_edit',low_level_edit);\r\nhigh_level_edit = uicontrol('Style','edit','unit','norm','Position',[0.055,0.72,0.05,0.03]);\r\nset(high_level_edit,'BackgroundColor','white','String',num2str(ceil(high_level)),'callback',@high_level_edit_Callback);\r\nsetappdata(h_fig,'high_level_edit',high_level_edit);\r\nlow_level_slider=uicontrol('Style','slider','unit','norm','Position',[0.005,0.77,0.1,0.03]);\r\nhigh_level_slider=uicontrol('Style','slider','unit','norm','Position',[0.005,0.69,0.1,0.03]);\r\nset (low_level_slider,'Value',low_level,'Min',lo,'Max',hi,'SliderStep',[(1/(hi-lo)) 0.1],'callback',@low_level_slider_Callback);\r\nset (high_level_slider,'Value',low_level,'Min',lo,'Max',hi,'SliderStep',[(1/(hi-lo)) 0.1],'callback',@high_level_slider_Callback);\r\nsetappdata(h_fig,'low_level_slider',low_level_slider);\r\nsetappdata(h_fig,'high_level_slider',high_level_slider);\r\nuicontrol('Style','text','String','low:','unit','norm','Position',[0.005,0.8,0.05,0.03]);\r\nuicontrol('Style','text','String','high:','unit','norm','Position',[0.005,0.72,0.05,0.03]);\r\n%display level as vertical line\r\naxes(h_hist)\r\nh_lev = vline(low_level,'-');\r\nh_lev2 = vline(high_level,'-');\r\nset(h_lev,'LineWidth',2,'color',0.5*[1 0 0],'UserData',low_level)\r\nset(h_lev2,'LineWidth',2,'color',0.5*[0 0 1],'UserData',high_level)\r\nsetappdata(h_fig,'h_lev',h_lev)\r\nsetappdata(h_fig,'h_lev2',h_lev2)\r\n%attach draggable behavior for user to change level\r\nmove_vlines(h_lev,h_lev2,@update_plot);\r\n\r\nupdate_plot\r\n\r\n%add reset button \r\nh_reset = uicontrol('unit','norm','pos',[0.0 0.95 .1 .05]);\r\nset(h_reset,'string','Reset','callback',@ResetOriginalLevel)\r\n\r\nif nargout>0 %return result(s)\r\n h_done = uicontrol('unit','norm','pos',[0.9 0.95 0.1 0.05]);\r\n set(h_done,'string','Done','callback','delete(gcbo)') %better\r\n %inspect(h_fig)\r\n set(h_fig,'WindowStyle','modal')\r\n waitfor(h_done)\r\n if ishandle(h_fig)\r\n h_lev = getappdata(gcf,'h_lev');\r\n level = mean(get(h_lev,'xdata'));\r\n h_lev2 = getappdata(gcf,'h_lev2');\r\n level2 = mean(get(h_lev2,'xdata'));\r\n if nargout>2\r\n thresh = getappdata(gcf,'threshimage');\r\n bw = logical(get(thresh,'AlphaData'));\r\n end\r\n delete(h_fig)\r\n else\r\n warning('THRESHTOOL:UserAborted','User Aborted - no return value')\r\n level = [];\r\n end\r\nend\r\n\r\nend %manual_thresh (mainfunction)\r\n\r\n\r\nfunction ResetOriginalLevel(hObject,varargin) %subfunction\r\nh_lev = getappdata(gcf,'h_lev');\r\ninit_level = get(h_lev,'UserData');\r\nset(h_lev,'XData',init_level*[1 1])\r\nh_lev2 = getappdata(gcf,'h_lev2');\r\nhigh_level = get(h_lev2,'UserData');\r\nset(h_lev2,'XData',high_level*[1 1])\r\nupdate_plot\r\nend %ResetOriginalLevel (subfunction)\r\n\r\n\r\nfunction update_plot %subfunction\r\nim = getappdata(gcf,'im');\r\nh_lev = getappdata(gcf,'h_lev');\r\nh_lev2 = getappdata(gcf,'h_lev2');\r\nlow_level = mean(get(h_lev,'xdata'));\r\nhigh_level = mean(get(h_lev2,'xdata'));\r\ntext1=getappdata(gcf,'low_level_edit');\r\ntext2=getappdata(gcf,'high_level_edit');\r\nslider1=getappdata(gcf,'low_level_slider');\r\nslider2=getappdata(gcf,'high_level_slider');\r\n set (text1,'String',num2str(floor(low_level))); set (slider1,'Value',floor(low_level));\r\n set (text2,'String',num2str(ceil(high_level))); set (slider2,'Value',ceil(high_level));\r\nh_ax1 = getappdata(gcf,'threshimage');\r\n%segmented image using upper layer with tranperent background\r\nbw = (((im>=low_level).*(im<=high_level)));\r\n set(h_ax1, 'AlphaData', bw);\r\n\r\nend %update_plot (subfunction)\r\n\r\n\r\n%function rgbsubimage(im,map), error('DISABLED')\r\n\r\n\r\n%----------------------------------------------------------------------\r\nfunction move_vlines(handle1,handle2,DoneFcn) %subfunction\r\n%move_vlines implements horizontal movement of two lines.\r\n%\r\n% \r\n%Note: This tools strictly requires MOVEX_TEXT, and isn't much good\r\n% without VLINE by Brandon Kuczenski, available at MATLAB Central.\r\n%\r\n\r\n% This seems to lock the axes position\r\nset(gcf,'Nextplot','Replace')\r\nset(gcf,'DoubleBuffer','on')\r\n\r\nh_ax=get(handle1,'parent');\r\nh_fig=get(h_ax,'parent');\r\nsetappdata(h_fig,'h_vline',handle1)\r\nsetappdata(h_fig,'h_vline2',handle2)\r\nif nargin<3, DoneFcn=[]; end\r\nsetappdata(h_fig,'DoneFcn',DoneFcn)\r\nset(handle1,'ButtonDownFcn',@DownFcn)\r\nset(handle2,'ButtonDownFcn',@DownFcn2)\r\n function DownFcn(hObject,eventdata,varargin) %Nested--%\r\n set(gcf,'WindowButtonMotionFcn',@MoveFcn) %\r\n set(gcf,'WindowButtonUpFcn',@UpFcn) %\r\n end %DownFcn------------------------------------------%\r\nfunction DownFcn2(hObject,eventdata,varargin) %Nested--%\r\n set(gcf,'WindowButtonMotionFcn',@MoveFcn2) %\r\n set(gcf,'WindowButtonUpFcn',@UpFcn) %\r\n end %DownFcn------------------------------------------%\r\n\r\n function UpFcn(hObject,eventdata,varargin) %Nested----%\r\n set(gcf,'WindowButtonMotionFcn',[]) %\r\n DoneFcn=getappdata(hObject,'DoneFcn'); %\r\n if isstr(DoneFcn) %\r\n eval(DoneFcn) %\r\n elseif isa(DoneFcn,'function_handle') %\r\n feval(DoneFcn) %\r\n end %\r\n end %UpFcn--------------------------------------------%\r\n\r\n function MoveFcn(hObject,eventdata,varargin) %Nested------%\r\n h_vline=getappdata(hObject,'h_vline'); %\r\n h_ax=get(h_vline,'parent'); %\r\n cp = get(h_ax,'CurrentPoint'); %\r\n h_fig=get(h_ax,'parent');\r\n high_level=get (getappdata(h_fig,'h_vline2'),'XData');\r\n xpos = cp(1); \r\n x_range=get(h_ax,'xlim');%\r\n x_range=[x_range(1) high_level(1)]; %\r\n if xposx_range(2), xpos=x_range(2); end %\r\n XData = get(h_vline,'XData'); %\r\n XData(:)=xpos; %\r\n set(h_vline,'xdata',XData) %\r\n \r\n \r\n end %MoveFcn----------------------------------------------%\r\nfunction MoveFcn2(hObject,eventdata,varargin) %Nested------%\r\n h_vline=getappdata(hObject,'h_vline2'); %\r\n h_ax=get(h_vline,'parent'); %\r\n cp = get(h_ax,'CurrentPoint'); %\r\n h_fig=get(h_ax,'parent');\r\n low_level=get (getappdata(h_fig,'h_vline'),'XData');\r\n xpos = cp(1); \r\n x_range=get(h_ax,'xlim');%\r\n x_range=[low_level(1) x_range(2)]; %\r\n if xposx_range(2), xpos=x_range(2); end \r\n XData = get(h_vline,'XData'); %\r\n XData(:)=xpos; %\r\n set(h_vline,'xdata',XData) %\r\n \r\n end %MoveFcn----------------------------------------------%\r\n\r\nend %move_vlines(subfunction)\r\n\r\n\r\n\r\n%----------------------------------------------------------------------\r\nfunction [x,y] = limits(a) %subfunction\r\n% LIMITS returns min & max values of matrix; else scalar value.\r\n%\r\n% [lo,hi]=LIMITS(a) returns LOw and HIgh values respectively.\r\n%\r\n% lim=LIMITS(a) returns 1x2 result, where lim = [lo hi] values\r\n\r\nif nargin~=1 | nargout>2 %bogus syntax\r\n error('usage: [lo,hi]=limits(a)')\r\nend\r\n\r\nsiz=size(a);\r\n\r\nif prod(siz)==1 %scalar\r\n result=a; % value\r\nelse %matrix\r\n result=[min(a(:)) max(a(:))]; % limits\r\nend\r\n\r\nif nargout==1 %composite result\r\n x=result; % 1x2 vector\r\nelseif nargout==2 %separate results\r\n x=result(1); % two scalars\r\n y=result(2);\r\nelse %no result\r\n ans=result % display answer\r\nend\r\n\r\nend %limits (subfunction)\r\n\r\n\r\n\r\n\r\n\r\n%--------------------------------------------------------------------------------------------------------------\r\nfunction hhh=vline(x,in1,in2) %subfunction\r\n% function h=vline(x, linetype, label)\r\n% \r\n% Draws a vertical line on the current axes at the location specified by 'x'. Optional arguments are\r\n% 'linetype' (default is 'r:') and 'label', which applies a text label to the graph near the line. The\r\n% label appears in the same color as the line.\r\n%\r\n% The line is held on the current axes, and after plotting the line, the function returns the axes to\r\n% its prior hold state.\r\n%\r\n% The HandleVisibility property of the line object is set to \"off\", so not only does it not appear on\r\n% legends, but it is not findable by using findobj. Specifying an output argument causes the function to\r\n% return a handle to the line, so it can be manipulated or deleted. Also, the HandleVisibility can be \r\n% overridden by setting the root's ShowHiddenHandles property to on.\r\n%\r\n% h = vline(42,'g','The Answer')\r\n%\r\n% returns a handle to a green vertical line on the current axes at x=42, and creates a text object on\r\n% the current axes, close to the line, which reads \"The Answer\".\r\n%\r\n% vline also supports vector inputs to draw multiple lines at once. For example,\r\n%\r\n% vline([4 8 12],{'g','r','b'},{'l1','lab2','LABELC'})\r\n%\r\n% draws three lines with the appropriate labels and colors.\r\n% \r\n% By Brandon Kuczenski for Kensington Labs.\r\n% brandon_kuczenski@kensingtonlabs.com\r\n% 8 November 2001\r\n\r\n% Downloaded 8/7/03 from MATLAB Central\r\n% http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=1039&objectType=file\r\n\r\nif length(x)>1 % vector input\r\n for I=1:length(x)\r\n switch nargin\r\n case 1\r\n linetype='r:';\r\n label='';\r\n case 2\r\n if ~iscell(in1)\r\n in1={in1};\r\n end\r\n if I>length(in1)\r\n linetype=in1{end};\r\n else\r\n linetype=in1{I};\r\n end\r\n label='';\r\n case 3\r\n if ~iscell(in1)\r\n in1={in1};\r\n end\r\n if ~iscell(in2)\r\n in2={in2};\r\n end\r\n if I>length(in1)\r\n linetype=in1{end};\r\n else\r\n linetype=in1{I};\r\n end\r\n if I>length(in2)\r\n label=in2{end};\r\n else\r\n label=in2{I};\r\n end\r\n end\r\n h(I)=vline(x(I),linetype,label);\r\n end\r\nelse\r\n switch nargin\r\n case 1\r\n linetype='r:';\r\n label='';\r\n case 2\r\n linetype=in1;\r\n label='';\r\n case 3\r\n linetype=in1;\r\n label=in2;\r\n end\r\n\r\n \r\n \r\n \r\n g=ishold(gca);\r\n hold on\r\n\r\n y=get(gca,'ylim');\r\n h=plot([x x],y,linetype);\r\n if length(label)\r\n xx=get(gca,'xlim');\r\n xrange=xx(2)-xx(1);\r\n xunit=(x-xx(1))/xrange;\r\n if xunit<0.8\r\n text(x+0.01*xrange,y(1)+0.1*(y(2)-y(1)),label,'color',get(h,'color'))\r\n else\r\n text(x-.05*xrange,y(1)+0.1*(y(2)-y(1)),label,'color',get(h,'color'))\r\n end\r\n end \r\n\r\n if g==0\r\n hold off\r\n end\r\n set(h,'tag','vline','handlevisibility','off')\r\nend % else\r\n\r\nif nargout\r\n hhh=h;\r\nend\r\n\r\nend %vline (subfunction)\r\n%callbacks for the uicontrols\r\nfunction low_level_edit_Callback (hObject, eventdata)\r\n level=str2double(get(hObject,'String')) ;\r\n h_lev = getappdata(gcf,'h_lev');\r\n h_lev2 = getappdata(gcf,'h_lev2');\r\n high=get(h_lev2,'XData');\r\n slidermin=floor(get(getappdata(gcf,'low_level_slider'),'Min'));\r\n if (level<=slidermin)\r\n set(hObject,'String',num2str(slidermin));\r\n set(h_lev,'XData',slidermin*[1 1])\r\n elseif (level=slidermax)\r\n set(hObject,'String',num2str(slidermax));\r\n set(h_lev2,'XData',slidermax*[1 1])\r\n elseif (level>low(1))\r\n set(h_lev2,'XData',level*[1 1])\r\n else\r\n set(h_lev2,'XData',low)\r\n end \r\n feval(@update_plot)\r\nend\r\nfunction low_level_slider_Callback (hObject, eventdata)\r\nlevel=get(hObject,'Value') ;\r\n h_lev = getappdata(gcf,'h_lev');\r\n h_lev2 = getappdata(gcf,'h_lev2');\r\n high=get(h_lev2,'XData');\r\n if (levellow(1))\r\n set(h_lev2,'XData',level*[1 1])\r\n else\r\n set(h_lev2,'XData',low)\r\n end \r\n feval(@update_plot)\r\nend"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ImportAsciiRaster.m", "ext": ".m", "path": "SeAMS-master/Utilities/ImportAsciiRaster/ImportAsciiRaster.m", "size": 10699, "source_encoding": "utf_8", "md5": "1de28239be4ab728680d905e26553ca9", "text": "function [Z R] = ImportAsciiRaster(varargin)\r\n% [Z R] = ImportAsciiRaster(...)\r\n% \r\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % \r\n% % %\r\n% % Produced by Giuliano Langella %\r\n% % e-mail:gyuliano@libero.it %\r\n% % March 2008 %\r\n% % %\r\n% % Last Updated: 20 April, 2010 %\r\n% % %\r\n% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % \r\n%\r\n%\r\n%\r\n% ----- TODO -----\r\n% 1.\\ The function should take care of xll-center and yll-center when\r\n% they are found instead of -corner conditions.\r\n% \r\n% ----- SYNTAX -----\r\n% Z = ImportAsciiRaster; ==> nodata:NaN; ref:'h'; type:'s'; FilePath:uigetfile\r\n% [Z h] = ImportAsciiRaster; ==> nodata:NaN; ref:'h'; type:'s'; FilePath:uigetfile\r\n% [Z R] = ImportAsciiRaster(varargin); ==> see OPTIONS\r\n%\r\n%\r\n% ----- OPTIONS -----\r\n% +'nodata'(optional) [numeric] = output No-Data Value.\r\n% Default output NoData is NaN. When specified it substitutes the input\r\n% no-data value, which is stored in 'NODATA_value' from header.\r\n%\r\n% +'ref'(optional) [string]: Geospatial Reference Matrix.\r\n% --> 'h' (default) for header matrix (as the .hdr file in Arc-Info Binary Raster).\r\n% --> 'r' for spatial-referencing matrix R (Mapping Toolbox);\r\n%\r\n% +'type'(optional) [string]: class type of Z output in multiselection case only.\r\n% --> 's' (default) gets a structure array with field name equal to\r\n% imported filename without extension;\r\n% --> 'd' gets a double array with size (nrows, ncols, N. files); it is\r\n% useful in case of several layers with same reference matrix.\r\n% NOTE: be careful to multi-select grids with same spatial extent.\r\n%\r\n% +'FilePath'(optional) [char]: Complete path + filename + file extension.\r\n% If it is not given the uigetfile will ask for file(s).\r\n%\r\n% ----- DESCRIPTION -----\r\n% This function imports Arc-Info ASCII Raster (*.asc, *.txt) files. You are\r\n% allowed to import single or multiple files by multi-selection (CRTL +\r\n% Mouse_Left_Click). In the latter case by default a structure array is\r\n% created in order to store the several rasters; items of the structure\r\n% array are called as the imported raster. A facultative option is now\r\n% added to create a stack of double 3-D array instead of a structure array\r\n% in case more grid files are selected. This might be useful to handle for\r\n% instance multi-temporal remote sensing datasets (such as NDVI), or\r\n% multiple realizations of Geostatistical Simulation. You can create a\r\n% stack with dimension compatibly with you computer memory.\r\n% \r\n% ----- EXAMPLE_1 -----\r\n% [Z R] = ImportAsciiRaster('r'); % import DEM and Aspect\r\n% Exaggeration_Factor = 1.6; % use an exaggeration factor\r\n% figure(gcf); mapshow(Z.DEM*Exaggeration_Factor,R.DEM,'DisplayType','surface');\r\n% colormap(demcmap(Z.DEM))\r\n% view(3); grid off; axis off\r\n% axis on; xlabel('Easting'); ylabel('Northing'); zlabel('Elevation')\r\n%\r\n% ----- EXAMPLE_2 -----\r\n% [Z R] = ImportAsciiRaster(NaN, 'r', 'd'); %import 15 Geostatistical Simulations\r\n% M = mean(Z,3); %compute mean along 3rd dimension\r\n% figure(gcf); h=pcolor(M); axis off; %pcolor plot\r\n% set(h,'LineStyle','none')\r\n% colormap(jet), colorbar('Location', 'SouthOutside')\r\n% saveas(gcf, 'clay_simulation.eps', 'psc2') %save to color EPS for LaTex\r\n%\r\n\r\n%% MAIN\r\n\r\n% Read varargins [given by user]\r\nFilePath = cell(0);\r\nFileName = cell(0);\r\nfor i = 1:size(varargin,2)\r\n if iscell(varargin{i})\r\n FilePath = varargin{i};\r\n for i = 1:length(FilePath)\r\n FileName{end+1} = path2file(FilePath{i});\r\n end\r\n else\r\n switch varargin{i}\r\n case{'h','r'} % header\r\n ref = varargin{i};\r\n case{'s','d'} % var type\r\n type = varargin{i};\r\n otherwise \r\n if isnan(varargin{i}) | isnumeric(varargin{i}) % nodata\r\n nodata = varargin{i};\r\n elseif ischar(varargin{i}) % filepath\r\n FilePath{end+1} = varargin{i};\r\n FileName{end+1} = path2file(FilePath{end});\r\n if ~exist(FilePath{end},'file')\r\n error(['File ',varargin{i},' does not exist!'])\r\n end\r\n end\r\n end\r\n end\r\nend\r\n\r\n% get file(s) [use UI if any file is given as varargin]\r\nif ~sum(size(FilePath))\r\n % UIGETFILE - .asc/.txt - Multiselect on\r\n [FileName, PathName] = uigetfile({'*.asc','Arc-Info ASCII Raster (*.asc)'; ...\r\n '*.txt','Text ASCII Raster (*.txt)'; ...\r\n '*.*', 'All Files (*.*)'}, ...\r\n 'Pick Raster(s)', ...\r\n pwd, ...\r\n 'MultiSelect', 'on');\r\n % FILEPATH\r\n if iscell(FileName)\r\n for NumFile = 1:length(FileName)\r\n FilePath{NumFile} = strcat(PathName, FileName(NumFile));\r\n end\r\n else\r\n FilePath{1} = strcat(PathName, FileName);\r\n FileName = {FileName};\r\n end\r\nend\r\n\r\n% set undefined varargins\r\nif ~exist('nodata', 'var'), nodata = NaN; end % default\r\nif ~exist('ref', 'var'), ref = 'h'; end % default\r\nif ~exist('type', 'var'), type = 's'; end % default\r\nif length(FileName)==1, type = ''; end % double\r\n\r\n%'''''''''''''''''\r\n% clc\r\nfprintf('\\nReading...\\n')\r\n%'''''''''''''''''\r\n\r\n% START LOOP FOR EACH FILE TO BE IMPORTED\r\nfor NumFile = 1:size(FilePath,2)\r\n\r\n fprintf('\\t-->[%s]\\n', strvcat(FilePath{NumFile}))\r\n fprintf('\\tOutput NODATA-Value:\\t %f\\n', nodata)\r\n fprintf('\\tSpatial Reference Mat:\\t %s\\n', ref)\r\n if ~isempty(type),fprintf('\\tGrid class type:\\t %s\\n', type),end\r\n \r\n start = 0;\r\n eval(['fid = fopen(''', strvcat(FilePath{NumFile}), ''',''r'');']);\r\n if fid==-1, error('Invalid file name!!'), end\r\n\r\n % ******************** Import HEADER ****************************\r\n while start == 0; % to be sure to read HEADER of file\r\n\r\n Read_header = fscanf(fid,'%s',1);\r\n % x- and y- llcenter are for instance used in ISATIS\r\n switch Read_header\r\n case {'ncols', 'NCOLS'}\r\n ncols = fscanf(fid,'%f',1);\r\n case {'nrows', 'NROWS'}\r\n nrows = fscanf(fid,'%f',1);\r\n case {'xllcorner', 'XLLCORNER', 'xllcenter'}\r\n xllcorner = fscanf(fid,'%f',1);\r\n case {'yllcorner', 'YLLCORNER', 'yllcenter'}\r\n yllcorner = fscanf(fid,'%f',1);\r\n case {'cellsize', 'CELLSIZE'}\r\n cellsize = fscanf(fid,'%f',1);\r\n case {'xdim'}\r\n xdim = fscanf(fid,'%f',1);\r\n case {'ydim'}\r\n ydim = fscanf(fid,'%f',1); \r\n case {'NODATA_value', 'nodata_value', 'NODATA_VALUE'}\r\n NODATA_value = fscanf(fid,'%f',1);\r\n start = 1;\r\n otherwise\r\n error('Unrecognized %s in header',Read_header)\r\n end %switch\r\n\r\n end %while\r\n % *****************************************************************\r\n\r\n % ----------- pixel geometry -----------\r\n if exist('cellsize','var') % ==> the pixel is squared\r\n xdim = cellsize;\r\n ydim = cellsize;\r\n end\r\n % -------------------------------------- \r\n \r\n % ----------- Import RASTER -----------\r\n import = fscanf(fid,'%f',[ncols nrows]);\r\n fclose(fid);\r\n % -----------------------------------------\r\n\r\n \r\n % +++++++++++++ Write No-Data Value +++++++++++++++++++\r\n import(find(import == NODATA_value)) = nodata;\r\n % +++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n %mulsel = @(O,I,inv) [O '.' strrep(strvcat(FileName{NumFile}{:}(1:length(FileName{NumFile}{:})-4)),'-','_') ' = ' I inv ';'];\r\n mulsel = @(O,I,inv) [O '.' strrep(strvcat(FileName{NumFile}(1:length(FileName{NumFile})-4)),'-','_') ' = ' I inv ';'];\r\n % @@@@@@@@@@@@ Write RASTER @@@@@@@@@@@@@@@\r\n if type == 's' % structure array of 2-D layers\r\n %eval(['Z.' strrep(strvcat(FileName{NumFile}{:}(1:length(FileName{NumFile}{:})-4)),'-','_') ' = import'';']);\r\n eval(mulsel('Z','import',''''))\r\n elseif type == 'd' % double 3-D array stack\r\n Z(:,:,NumFile) = import';\r\n else % single 2-D layer\r\n Z = import';\r\n end\r\n % @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n\r\n \r\n % ----------------- Write HEADER -------------------------\r\n if nargout == 2\r\n % Reference Matrix\r\n if ref == 'r'\r\n % ulc: Upper Left Centre point, that is the point in the centre of\r\n % the first upper-left pixel. This point is requested by\r\n % 'makerefmat.m' function.\r\n ulc_X = xllcorner + xdim /2;\r\n ulc_Y = yllcorner - ydim /2 + nrows*ydim;\r\n % This is the R spatial-referencing matrix used in Mapping Toolbox\r\n temp_R = makerefmat(ulc_X,ulc_Y,xdim,-ydim);\r\n % Header Matrix\r\n elseif ref == 'h'\r\n if ~exist('cellsize','var')\r\n warning('Unable to make canonical header')\r\n temp_R = [ncols; nrows; xllcorner; yllcorner; xdim; ydim; NODATA_value];\r\n else\r\n % This is the common header used in Arc/Info ASCII-Raster\r\n temp_R = [ncols; nrows; xllcorner; yllcorner; cellsize; NODATA_value];\r\n end\r\n end %if\r\n % MultiSelection\r\n if type == 's'\r\n %eval(['R.' strrep(strvcat(FileName{NumFile}{:}(1:length(FileName{NumFile}{:})-4)),'-','_') ' = temp_R;']);\r\n eval(mulsel('R','temp_R',''))\r\n else\r\n R = temp_R;\r\n end\r\n end %nargout\r\n % -----------------------------------------------------\r\n \r\n \r\nend %NumFile\r\n\r\n\r\nfprintf('...Completed!\\n')\r\n\r\nreturn\r\n\r\nfunction [filename] = path2file(filepath)\r\n\r\nfnd_b_slash = strfind(char(filepath), filesep);\r\n\r\nif fnd_b_slash \r\n STR = char(filepath);\r\n filename = cellstr(STR(fnd_b_slash(end)+1:end));\r\nelse\r\n filename = filepath;\r\nend\r\nreturn\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "membership2.m", "ext": ".m", "path": "SeAMS-master/Utilities/Membership/membership2.m", "size": 489, "source_encoding": "utf_8", "md5": "6c25e6d8e6b2b2546bccb5fbf7de2f27", "text": "\r\n\r\nfunction [Seg2] = membership2(Seg,Mem_Class_BW)\r\n% Author: Ciaran Robb\r\n\r\n% Membership function\r\n\r\n% Acknowledgement: Peter Kovesi for his renumberregions function\r\n\r\n% Outputs: a int32 labeled image from an arbitrarily labeled one\r\n% Seg = segmented image labeled with integers\r\n% Inputs\r\n% Mem_Class_BW = either a boolean statement related to and image (e.g\r\n% mean_image>10) or a binary image.\r\n\r\nSeg2 = Seg;\r\nSeg2(Mem_Class_BW == 0) = 0;\r\nSeg2 = renumberregions(Seg2);\r\n\r\n\r\n\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "membership.m", "ext": ".m", "path": "SeAMS-master/Utilities/Membership/membership.m", "size": 587, "source_encoding": "utf_8", "md5": "f620500170f18624167d1ed67d895143", "text": "%Membership function\r\n%Outputs a binary image & int32 label image\r\n\r\n%Seg = segmented image labeled with integers\r\n%label_Vector = vector with segment properties(eg cluster val, slope val)\r\n%statement = boolean rule e.g KMEAN ==3 or >3 or whatevs\r\n\r\nfunction [Seg2] = membership(Seg,statement)\r\n\r\nSeg2 = Seg;\r\n\r\nAllow = statement;\r\nKp = find(Allow);%keep\r\nMem_Class_BW = ismember(Seg, Kp);\r\nSeg2(BW == 0) = 0;\r\nSeg2 = renumberregions(Seg2);\r\n%LMP2 = bwlabel(Mem_lumps2);\r\nRGB = label2rgb(Seg2, 'hsv',[1 1 1],'shuffle');\r\nfigure, imshow(RGB), hold on % figure with transparency\r\n\r\n\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "colorscale2.m", "ext": ".m", "path": "SeAMS-master/Utilities/colorscale/colorscale2.m", "size": 1041, "source_encoding": "utf_8", "md5": "392570709b7350e76d705821abb7e599", "text": "%Allows visualisation of labeled object properties (such as a kmean\r\n%value or slope value)via a colormap\r\n%\r\n%output results are superimposed on a background image such as a dem\r\n\r\nfunction colorscale2(Scale,Seg,hillshd)\r\n%Scale = array with each object value eg mean slope or kmean value\r\n%Props = the image objects - ie regions labeled with an integer\r\n%Max = the maximum value of image object\r\n%hillshd = a hillshade grid to superimpose results on\r\n\r\n%Neils idea - what is colorvalue??\r\n%PCAseg \r\n%for k=1:(size(Seg,1))\r\n %\r\n % L(Seg(1).PixelList(:,1),Seg(1).PixelList(:,2))=idx(k);\r\n %\r\n%end\r\n\r\nmal = transpose(Scale);\r\nL = zeros(size(Seg)); %preallocate\r\nfor k=1:(size(Seg,1))\r\n %\r\n L(Seg(1).PixelList(:,1),Seg(1).PixelList(:,2))=mal(k);\r\n %\r\nend\r\ncmap = hsv(max(mal); %a colormap(hsv works better than jet)\r\nLrgb = label2rgb(L,cmap); %build rgb image\r\nfigure, imshow(hillshd), hold on\r\nhimage = imshow(Lrgb); \r\nset(himage, 'AlphaData', 0.2);\r\ntitle('Stats Property ranked by colormap')\r\nfigure, imshow(Lrgb);"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "SeAMS.m", "ext": ".m", "path": "SeAMS-master/MainMenu/SeAMS.m", "size": 5600, "source_encoding": "utf_8", "md5": "5fa29b89852c96072094fe511839969d", "text": "function varargout = SeAMS(varargin)\n% SEAMS MATLAB code for SeAMS.fig\n% SEAMS, by itself, creates a new SEAMS or raises the existing\n% singleton*.\n%\n% H = SEAMS returns the handle to a new SEAMS or the handle to\n% the existing singleton*.\n%\n% SEAMS('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SEAMS.M with the given input arguments.\n%\n% SEAMS('Property','Value',...) creates a new SEAMS or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before SeAMS_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to SeAMS_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help SeAMS\n\n% Last Modified by GUIDE v2.5 12-Jun-2015 14:41:45\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @SeAMS_OpeningFcn, ...\n 'gui_OutputFcn', @SeAMS_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before SeAMS is made visible.\nfunction SeAMS_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to SeAMS (see VARARGIN)\n\n% Choose default command line output for SeAMS\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes SeAMS wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = SeAMS_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --------------------------------------------------------------------\nfunction Segmentation_Callback(hObject, eventdata, handles)\n% hObject handle to Segmentation (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nSegmentationGUI\n\n% --------------------------------------------------------------------\nfunction Untitled_5_Callback(hObject, eventdata, handles)\n% hObject handle to Untitled_5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Untitled_6_Callback(hObject, eventdata, handles)\n% hObject handle to Untitled_6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nSVC\n\n\n\n\n\n% --------------------------------------------------------------------\nfunction Workspace_Callback(hObject, eventdata, handles)\n% hObject handle to Workspace (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction External1_Callback(hObject, eventdata, handles)\n% hObject handle to External1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im \n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('Error'),'Error','Error');\n return\nend\nim = double(imread(path));\n%axes(handles.axes1);\nI1 = uint8(im);\nfigure, imshow(I1,'DisplayRange',[]), colormap(jet);\nassignin('base','I', im);\n\n% --------------------------------------------------------------------\nfunction Workspace1_Callback(hObject, eventdata, handles)\n% hObject handle to Workspace1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Thresholding_Clustering_Callback(hObject, eventdata, handles)\n% hObject handle to Thresholding_Clustering (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction MultiThresh_Callback(hObject, eventdata, handles)\n% hObject handle to MultiThresh (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im\nim(im<0)=0;\n[level,level2,bw] = manual_thresh(im,jet);\nassignin('base','BW',bw);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "OBIAmainGUI.m", "ext": ".m", "path": "SeAMS-master/MainMenu/OBIAmainGUI.m", "size": 5739, "source_encoding": "utf_8", "md5": "2c1ea18d821c12f3cf7451713c0063c6", "text": "function varargout = OBIAmainGUI(varargin)\n% OBIAMAINGUI MATLAB code for OBIAmainGUI.fig\n% OBIAMAINGUI, by itself, creates a new OBIAMAINGUI or raises the existing\n% singleton*.\n%\n% H = OBIAMAINGUI returns the handle to a new OBIAMAINGUI or the handle to\n% the existing singleton*.\n%\n% OBIAMAINGUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in OBIAMAINGUI.M with the given input arguments.\n%\n% OBIAMAINGUI('Property','Value',...) creates a new OBIAMAINGUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before OBIAmainGUI_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to OBIAmainGUI_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help OBIAmainGUI\n\n% Last Modified by GUIDE v2.5 11-Dec-2014 19:26:18\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @OBIAmainGUI_OpeningFcn, ...\n 'gui_OutputFcn', @OBIAmainGUI_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before OBIAmainGUI is made visible.\nfunction OBIAmainGUI_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to OBIAmainGUI (see VARARGIN)\n\n% Choose default command line output for OBIAmainGUI\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes OBIAmainGUI wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = OBIAmainGUI_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --------------------------------------------------------------------\nfunction Segmentation_Callback(hObject, eventdata, handles)\n% hObject handle to Segmentation (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nSegmentationGUI\n\n% --------------------------------------------------------------------\nfunction Untitled_5_Callback(hObject, eventdata, handles)\n% hObject handle to Untitled_5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Untitled_6_Callback(hObject, eventdata, handles)\n% hObject handle to Untitled_6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nImageStats\n\n\n\n\n\n% --------------------------------------------------------------------\nfunction Workspace_Callback(hObject, eventdata, handles)\n% hObject handle to Workspace (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction External1_Callback(hObject, eventdata, handles)\n% hObject handle to External1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im \n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('Error'),'Error','Error');\n return\nend\nim = double(imread(path));\n%axes(handles.axes1);\nI1 = uint8(im);\nfigure, imshow(I1,'DisplayRange',[]), colormap(jet);\nassignin('base','I', im);\n\n% --------------------------------------------------------------------\nfunction Workspace1_Callback(hObject, eventdata, handles)\n% hObject handle to Workspace1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Thresholding_Clustering_Callback(hObject, eventdata, handles)\n% hObject handle to Thresholding_Clustering (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction MultiThresh_Callback(hObject, eventdata, handles)\n% hObject handle to MultiThresh (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im\nim(im<0)=0;\n[level,level2,bw] = manual_thresh(im,jet);\nassignin('base','BW',bw);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "GetSkewAndKurtosis.m", "ext": ".m", "path": "SeAMS-master/Stats/GetSkewAndKurtosis.m", "size": 1249, "source_encoding": "utf_8", "md5": "265531d940e9066de44d2df78ff072ba", "text": "%------------------------------------------------------------------------------------------------------\r\n% Get the skew and kurtosis from the histogram bin values.\r\n% Uses formulas from http://itl.nist.gov/div898/handbook/eda/section3/eda35b.htm\r\n% Courtesy of Image Analyst, Matlab Central file exchange\r\nfunction [skew kurtosis meanGL varianceGL sd] = GetSkewAndKurtosis(I)\r\n\ttry\r\n [pixelCounts GLs] = imhist(I); \r\n\t\t% Get the number of pixels in the histogram.\r\n\t\tnumberOfPixels = sum(pixelCounts);\r\n\t\t% Get the mean gray lavel.\r\n\t\tmeanGL = sum(GLs .* pixelCounts) / numberOfPixels;\r\n\t\t% Get the variance, which is the second central moment.\r\n\t\tvarianceGL = sum((GLs - meanGL) .^ 2 .* pixelCounts) / (numberOfPixels-1);\r\n\t\t% Get the standard deviation.\r\n\t\tsd = sqrt(varianceGL);\r\n\t\t% Get the skew.\r\n\t\tskew = sum((GLs - meanGL) .^ 3 .* pixelCounts) / ((numberOfPixels - 1) * sd^3);\r\n\t\t% Get the kurtosis.\r\n\t\tkurtosis = sum((GLs - meanGL) .^ 4 .* pixelCounts) / ((numberOfPixels - 1) * sd^4);\r\n\tcatch ME\r\n\t\terrorMessage = sprintf('Error in GetSkewAndKurtosis().\\nThe error reported by MATLAB is:\\n\\n%s', ME.message);\r\n\t\tuiwait(warndlg(errorMessage));\r\n\t\tset(handles.txtInfo, 'String', errorMessage);\r\n\tend\r\n\treturn; % from GetSkewAndKurtosis"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "Ctextprops.m", "ext": ".m", "path": "SeAMS-master/Stats/Ctextprops.m", "size": 1569, "source_encoding": "utf_8", "md5": "7836ad08a9f063364a2e3e2c4e7a3c65", "text": "%Author: Ciaran Robb\r\n% Segment Pixel statistics\r\n% Acknowledgements to Image Analyst for the GetSkewAndKurtosis function\r\n\r\n% Loops through each region/segment extracting pixel statistics and outputs\r\n% the following:\r\n% TextStats = 7 by n of statistical props of region pixel vals\r\n% Each 'stat vector' can be called via \r\n% TextStats(1,:) = Mean \r\n% TextStats(2,:) = Entropy \r\n% TextStats(3,:) = stddev \r\n% TextStats(4,:)= skewness\r\n% TextStats(5,:)= variance\r\n% TextStats(6,:) = Kurtosis \r\n% the 7th value is the label value retained for export to csv for use in\r\n% GIS\r\n\r\n%Seg = a segmented image\r\n%I = the image from which pixel stats are extracted\r\n\r\nfunction TextStats = Ctextprops(Seg,I)\r\n\r\nif(size(I,3)==3)\r\n I = rgb2gray(I);\r\nend\r\n \r\nstructure= regionprops(Seg,I,'Image','BoundingBox', 'MeanIntensity',...\r\n 'PixelValues');\r\nn=length(structure);\r\nTextStats = zeros(7,n);\r\nTextStats(1,:) = [structure.MeanIntensity];\r\nfor k =1:n\r\n Mask = structure(k).Image;\r\n BBox = structure(k).BoundingBox;\r\n I2= I(round(structure(k).BoundingBox(2):structure(k).BoundingBox(2)+structure(k).BoundingBox(4)-1),...\r\n round(structure(k).BoundingBox(1):structure(k).BoundingBox(1)+structure(k).BoundingBox(3)-1));\r\n I2 = double(I2);\r\n I3 = I2.*double(Mask);\r\n outprops = entropy(double(I3)*100);\r\n [skew kurtosis meanGL varianceGL sd] = GetSkewAndKurtosis(I3);\r\n TextStats(2,k) = outprops';\r\n TextStats(3,k) = sd';\r\n TextStats(4,k) = skew';\r\n TextStats(5,k) = varianceGL';\r\n TextStats(6,k) = kurtosis;\r\n TextStats(7,k) = k;\r\nend"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "cotextureprops.m", "ext": ".m", "path": "SeAMS-master/Stats/cotextureprops.m", "size": 1209, "source_encoding": "utf_8", "md5": "e910c9d832aa6f0bd12d3d0fd0c00a56", "text": "%Graycoprops loop\r\n%Author: Ciaran Robb\r\n%This function allows texture propeties based on relationship 'in space'\r\n%rather than simply the DN vals\r\n\r\n%Takes the binary mask from regionprops('Image') and calls masked pixel\r\n%values from an image\r\n%struct = regionprops.Image (Boundingbox of object with mask pixels==1\r\n%see regionprops)\r\n%Seg -labeled blobs/segmented image\r\n%I = Image to be masked\r\n\r\nfunction Stats = cotextureprops(Seg,I,offset1, offset2)\r\n\r\nstructure= regionprops(Seg,I,'Image','BoundingBox');\r\nn=length(structure);\r\nStats = zeros(5,n);\r\n\r\nfor k =1:n\r\n Mask = structure(k).Image;\r\n BBox = structure(k).BoundingBox;\r\n I2= I(round(structure(k).BoundingBox(2):structure(k).BoundingBox(2)+structure(k).BoundingBox(4)-1),...\r\n round(structure(k).BoundingBox(1):structure(k).BoundingBox(1)+structure(k).BoundingBox(3)-1));\r\n I2 = double(I2);\r\n I3 = I2.*double(Mask);\r\n glcm = graycomatrix(I3, 'offset', [offset1 offset2],'Symmetric', true);\r\n outprops = graycoprops(glcm, 'all'); \r\n Stats(1,k) = outprops.Contrast;\r\n Stats(2,k) = outprops.Correlation;\r\n Stats(3,k) = outprops.Energy;\r\n Stats(4,k) = outprops.Homogeneity;\r\n Stats(5,k) = k;\r\nend\r\n\r\n\r\n "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "SVC.m", "ext": ".m", "path": "SeAMS-master/Stats/SVC.m", "size": 28567, "source_encoding": "utf_8", "md5": "b770fcfa307625b05a5e1d8852cb9403", "text": "% Statistics, visualisation and classification\n% Author Ciaran Robb\n% Written with GUIDE, this GUI provides functions for the calculation and\n% display and classification of segment statistics.\n\n% Acknowledgements for material adapted form the Matlab file exchange:\n% Anton Semechko for the adaptation of his fuzzy cmeans clustering\n% function\n% Laurent. S, for the adaptation of their kmeans++ function \n% Brett Shoelson for his uigetvariables function\n% Yist Tauber for the manual_thresh function/gui\n% Giuliano Langella for the Import and SaveAsciiRaster functions\n% % Acknowledgement: Peter Kovesi for his draw region boundary function\n\n\n% The code is organised into callbacks that are related to each other and\n% are ordered as follows:\n% PIXEL, REGION PROPERTYS AND THEIR DISPLAY IN THE GUI\n% MENU HEADING CALLBACKS\n% CLASSIFICATION CALLBACKS\n% INPUT AND OUTPUT OF FILES\n% EXPORT OF DATA\n% MISCELLANEOUS\n\nfunction varargout = SVC(varargin)\n% SVC MATLAB code for SVC.fig\n% SVC, by itself, creates a new SVC or raises the existing\n% singleton*.\n%\n% H = SVC returns the handle to a new SVC or the handle to\n% the existing singleton*.\n%\n% SVC('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SVC.M with the given input arguments.\n%\n% SVC('Property','Value',...) creates a new SVC or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before SVC_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to SVC_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help SVC\n\n% Last Modified by GUIDE v2.5 12-Jun-2015 14:44:10\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @SVC_OpeningFcn, ...\n 'gui_OutputFcn', @SVC_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before SVC is made visible.\nfunction SVC_OpeningFcn(hObject, ~, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to SVC (see VARARGIN)\n\n% Choose default command line output for SVC\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes SVC wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = SVC_OutputFcn(~, ~, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n%PIXEL AND REGION PROPERTY CALCULATION CALLBACKS\n% --------------------------------------------------------------------\nfunction Process_Callback(~,~, handles)\n% Processing menu callback\n\n% --------------------------------------------------------------------\nfunction Process_Harlick_Texture_Callback(~,~, handles)\n% This function is the callback for calculating Harlick texture features\n\nglobal im seg CoStats waitbarHandle offset1 offset2;\nx = inputdlg('Enter offsets:',...\n 'GCLM offsets', [1 50]);\nh = waitbar(0,'Calculating texture...');\nkinput = str2num(x{:});\noffset1 = kinput(:,1);\noffset2 =kinput(:,2);\n\nI = im;\nif(size(im,3)==3)\n im = rgb2gray(im);\nend\nwaitbar(0.5,h,'Calculating texture...');\nCoStats = cotextureprops(seg,im, offset1, offset2);\nwaitbar(0.8,h,'Calculating texture...');\nassignin('base','CoTextprops',CoStats);\nwaitbar(1,h,'Done!');\nclose(h);\n\n% --------------------------------------------------------------------\nfunction Process_ImStats_Callback(~, ~, ~)\n% This function is the callback for calculating image statistics and region\n% properties\n\nglobal im seg Stats StatsR StatsG StatsB props ;\nh = waitbar(0,'Calculating stats...');\nI = im;\nif(size(I,3)==3)\n R = im(:,:,1);\n G = im(:,:,2);\n B = im(:,:,3);\n [StatsR] = Ctextprops(seg,R);\n [StatsG] = Ctextprops(seg,G);\n [StatsB] = Ctextprops(seg,B);\n ClrStats= [StatsR(1,:); StatsG(1,:); StatsB(1,:)];\n assignin('base','ClrStats',ClrStats);\n clearvars ClrStats\nend\nwaitbar(0.2,h,'Calculating stats...')\nStats = Ctextprops(seg,I);\nwaitbar(0.5,h,'Image stats done, calculating region props...')\nprops = regionprops(seg, 'Area', 'Eccentricity',...\n'Extent', 'MajorAxisLength', 'MinorAxisLength', 'Orientation','Solidity');\nwaitbar(0.8,h,'Calculating stats...')\nassignin('base','ImStats',Stats)\nassignin('base','Props',props)\nwaitbar(1,h,'Done!');\nclose(h);\n\n%REGION PROPERTY CALLBACKS---------------------------------------------\n\n% --------------------------------------------------------------------\nfunction Area_Callback(~,~, handles)\n%The call back for displaying the area property\nglobal seg props BW2 edge\n[BW2] = colorscale(seg,[props.Area]);\nBW2b = BW2;\nBW2b(edge)=0; \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\n% --------------------------------------------------------------------\nfunction Major_Axis_Callback(~,~, handles)\n% The call back for displaying the major axis length property\nglobal im seg props BW2 edge\n[BW2] = colorscale(seg,[props.MajorAxisLength]);\nBW2b = BW2;\nBW2b(edge==1)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Minor_Axis_Callback(~,~, handles)\n%The call back for displaying the minor axis length property\nglobal im seg props BW2 edge\n[BW2] = colorscale(seg,[props.MinorAxisLength]);\nBW2b = BW2;\nBW2b(edge)=0;\nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\n% --------------------------------------------------------------------\nfunction Eccentricity_Callback(~,~, handles)\n%The call back for displaying the eccentrcity property\nglobal im seg props BW2 edge\n[BW2] = colorscale(seg,[props.Eccentricity]*100);\nBW2b = BW2;\nBW2b(edge)=0;\nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n%---------------------------------------------------------------------\n% --------------------------------------------------------------------\nfunction Orientation_Callback(~,~, handles)\n% The call back to display orientation\n\nglobal im seg props BW2 edge\nOrient = [props.Orientation];\n[BW2] = colorscale(seg,Orient);\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\nOrient = [props.Orientation]+180;\n[BW2] =colorscale(seg,Orient); \n\n\n% --------------------------------------------------------------------\nfunction Extent_Callback(~,~, handles)\n%The call back for displaying the extent property\nglobal im seg props BW2 edge\n[BW2] = colorscale(seg,[props.Extent]*100);\nBW2b = BW2;\nBW2b(edge)=0;\nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\n% --------------------------------------------------------------------\nfunction Solidity_Callback(~,~, handles)\n%The call back for displaying the solidity property\nglobal im seg props BW2 edge\n[BW2] = colorscale(seg,[props.Solidity]*100);\nBW2b = BW2;\nBW2b(edge)=0;\nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\n% --------------------------------------------------------------------\nfunction Image_Stats_Callback(~,~, handles)\n% hObject handle to Image_Stats (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n%PIXEL PROPERTY CALLBACKS---------------------------------------------\n% --------------------------------------------------------------------\nfunction Mean_Callback(~,~, handles)\n%The call back for displaying the mean pixel value property\n\nglobal im seg Stats BW2 I1 StatsR StatsG StatsB edge \nif(size(im,3)==3)\n [BWR] = colorscale(seg,StatsR(1,:));\n [BWG] = colorscale(seg,StatsG(1,:));\n [BWB] = colorscale(seg,StatsB(1,:));\n BW2 = uint8(cat(3, BWR, BWG, BWB));\n BW2(BW2<0)=0;\n %axes(handles.axes1); \n imshow(imoverlay(BW2, edge, [0 0 0]));\nelse \n[BW2] = colorscale(seg,Stats(1,:));\nBW2(BW2<0)=0;\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n\n colorbar('location','eastoutside');\nend\n\n\n% --------------------------------------------------------------------\nfunction Stdev_Callback(~,~, handles)\n%The call back for displaying the stdev pixel value property\n\nglobal im seg Stats StatsR BW2 edge\n[BW2] = colorscale(seg,Stats(3,:)*100);\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\n% --------------------------------------------------------------------\nfunction Skew_Callback(~,~, handles)\n%The call back for displaying the pixel skewness property\n\nglobal im seg Stats StatsR BW2 edge\n[BW2] = colorscale(seg,Stats(4,:));\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Variance_Callback(~,~, handles)\n%The call back for displaying the pixel variance\n\nglobal im seg Stats StatsR BW2 edge\n[BW2] = colorscale(seg,Stats(5,:)*100);\nBW2b = BW2;\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Kurtosis_Callback(~,~, handles)\n%The call back for displaying the pixel kurtosis\nglobal im seg Stats StatsR BW2 edge\n[BW2] = colorscale(seg,Stats(6,:));\nBW2b = BW2;\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\nfunction Entropy_Callback(~,~, handles)\nglobal seg Stats BW2 edge\n[BW2] = colorscale(seg,Stats(2,:)*100);\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n% HARLICK TEXTURE DISPLAY CALLBACKS---------------------------------------\nfunction Display_Texture_Harlick_Callback(~,~, handles)\n% hObject handle to Display_Texture_Harlick (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Contrast_Callback(~,~, handles)\n% hObject handle to Contrast (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg CoStats BW2 edge\n[BW2] = colorscale(seg,CoStats(1,:)*10);\nBW2b = BW2;\nBW2b(edge)=0; \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),... \n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Correlation_Callback(~,~, handles)\n% hObject handle to Correlation (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg CoStats BW2 edge\n[BW2] = colorscale(seg,CoStats(2,:)*10);\nBW2b = BW2;\nBW2b(edge)=0; \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),... \n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Energy_Callback(~,~, handles)\n% hObject handle to Energy (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg CoStats BW2 edge\n[BW2] = colorscale(seg,CoStats(3,:)*100);\nBW2b = BW2;\nBW2b(edge)=0; \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),... \n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Homogeneity_Callback(~,~, handles)\n% hObject handle to Homogeneity (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg CoStats BW2 edge\n[BW2] = colorscale(seg,CoStats(4,:)*100);\nBW2b = BW2; \nBW2b(edge)=0; \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),... \n colorbar('location','eastoutside');\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit5_CreateFcn(~,~, handles)\n% hObject handle to edit5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\n% --- Executes on button press in pushbutton26.\nfunction pushbutton26_Callback(~,~, handles)\n% hObject handle to pushbutton26 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal BW2\n[lowThreshold highThreshold lastThresholdedBand] = ...\n threshold(jetthresh(BW2), ...\n max(BW2(:)), BW2);\nBW3 = BW2 >=lowThreshold & BW2 <=highThreshold;\nassignin('base','BW',bw);\n\n\n%MENU HEADING CALLBACKS-----------------------------------------------\n\n% --------------------------------------------------------------------\nfunction Classify_Callback(~,~, handles)\n% hObject handle to Classify (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% --------------------------------------------------------------------\nfunction Untitled_18_Callback(~,~, handles)\n% hObject handle to Untitled_18 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Reset_Callback(~,~, handles)\n% hObject handle to Reset (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Export_Callback(~,~, handles)\n% hObject handle to Export (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Save_Seg_Callback(~,~, handles)\n% hObject handle to Save_Seg (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n%CLASSIFICATION CALLBACKS--------------------------------------------\n\n% --------------------------------------------------------------------\nfunction Fuzzy_Cmeans_Callback(~,~, handles)\n% hObject handle to Fuzzy_Cmeans (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nglobal BW2 edge \nx = inputdlg('Enter number of clusters, fuzzy weighting:',...\n 'Fuzzy Cmeans', [1 50]);\nkinput = str2num(x{:});\nk = kinput(:,1);\nfz =kinput(:,2);\n[L,C,U,LUT,H]=FastFCMeans(uint16(BW2),k,fz);\nBW2=L;\nBW2b=BW2;\nBW2b(edge)=0;\nimshow(BW2b,'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\nassignin('base','FzCmeans',L);\nclearvars BW2b\n\n\n% --------------------------------------------------------------------\nfunction Cluster_Position_Callback(~,~, handles)\n% hObject handle to Cluster_Position (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal BW2 seg edge\n\nx = inputdlg('Enter no of clusters:',...\n 'Cluster Position', [1 50]);\nclusters = str2num(x{:});\n\n[Clustered]= ClusterCentroid(seg, clusters);\n[BW2] = colorscale(seg,Clustered);\nassignin('base', 'Posimage', BW2);\nBW2b = BW2;\nBW2b = BW2;\nBW2b(edge)=0;\nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Kmeans_xx_Callback(~,~, handles)\n% hObject handle to Kmeans_xx (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Multi_Thresholding_Callback(~,~, handles)\n% hObject handle to Multi_Thresholding (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal BW2 seg\n[level,level2,bw] = manual_thresh(BW2,jet);\nnewseg=membership2(seg,bw);\nx = inputdlg('Enter class name:',...\n 'Re-label & export', [1 50]);\nkinput=x{:};\nassignin('base',kinput,newseg);\n\n\n%INPUT AND OUTPUT CALLBACKS-------------------------------------------\n\n% --------------------------------------------------------------------\nfunction Image_Callback(~,~, handles)\n% hObject handle to Image (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Seg_Callback(~,~, handles)\n% hObject handle to Seg (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Seg_From_File_Callback(~,~, handles)\n% Open a non geo-referenced segmentation image\nglobal im seg \n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('You will need a file!'));\n return\nend\nseg=imread(path);\n%axes(handles.axes1);\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n\n% --------------------------------------------------------------------\nfunction Seg_From_Workspace_Callback(~,~, handles)\n% Open a segmentation raster from the workspace\nglobal seg im edge\nx = inputdlg('Enter variable name:',...\n 'Image from workspace', [1 50]);\nkinput=x{:}; \nseg = evalin('base',kinput);\n%axes(handles.axes1);\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \n\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n%axes(handles.axes1);\n%imshow(imoverlay(I1,edge, [1 1 1]));\nend\n\n% --------------------------------------------------------------------\nfunction IM_From_File_Callback(~,~, handles)\n%Open a non-geo-reffed tif image\n\nglobal im im2\n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('You will need a file!'));\n return\nend\nim=imread(path);\nI = uint8(im);\n%im=im2double(im); %converts to double\nim=double(im); %for backup process :)\nif(size(im,3)==3)\n imshow(I);\nelse\n%axes(handles.axes1);\nimshow(im,'DisplayRange',[]), colormap(jet);\nend\n\n\n% --------------------------------------------------------------------\nfunction Im_From_Workspace_Callback(~,~, handles)\n% Open image from workspace\nglobal im \n% = uigetvariables({'Please select any variable','And another'});\nim = double(im);\n%axes(handles.axes1);\nimshow(im,'DisplayRange',[]), colormap(jet);\n\n\n% --------------------------------------------------------------------\nfunction Seg_To_File_Callback(~,~, handles)\n% hObject handle to Seg_To_File (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% --------------------------------------------------------------------\nfunction View_Callback(hObject, eventdata, handles)\n% MENU ITEM\n\n\n% --------------------------------------------------------------------\nfunction Prop_Bck_Callback(hObject, eventdata, handles)\n% Display a property overlayed on a background image\nglobal BW2 seg im BckIm edge\nrgb = label2rgb(uint16(BW2), 'jet', [1 1 1]);\n % figure with transparency\nfigure,imshow(BckIm), hold on\nhimage = imshow(rgb);\nset(himage, 'AlphaData', 0.3);\nclearvars rgb \n% --------------------------------------------------------------------\nfunction Back_Im_file_Callback(hObject, eventdata, handles)\n% Background menu item\n\n\n% --------------------------------------------------------------------\nfunction Bck_File_Callback(hObject, eventdata, handles)\n%Open a non-geo reffed background image - eg hillshade\nglobal BckIm im\n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('Error'),'Error','Error');\n return\nend\nBckIm=imread(path);\nBckIm=uint8(BckIm);\n% if(size(im,3)==3)\n% BckIm=rgb2gray(BckIm);\n% end\n\n\n% --------------------------------------------------------------------\nfunction Bck_Wrk_Callback(hObject, eventdata, handles)\n% Open a non-geo reffed background image - eg hillshade from the workspace\nglobal BckIm \nBckIm = uigetvariables({'Image'});\nBckIm=BckIM{1,1};\nBckIm = uint8(BckIm);\n% if(size(im,3)==3)\n% BckIm=rgb2gray(BckIm);\n% end\n\n\n% --------------------------------------------------------------------\nfunction Open_asc_Callback(hObject, eventdata, handles)\n% % Open a geo reffed image from file\nglobal im h seg\n[im, h] = ImportAsciiRaster;\nimshow(im, 'DisplayRange', []), colormap('jet');\n\n\n% --------------------------------------------------------------------\nfunction seg_asc_open_Callback(hObject, eventdata, handles)\n% % Open a geo reffed segmentation from file\nglobal seg h I1 \n[seg, h] = ImportAsciiRaster;\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \n\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n%imshow(imoverlay(I1,edge, [0 0 0]));\nend\n\n% --------------------------------------------------------------------\nfunction Save_asc_seg_Callback(hObject, eventdata, handles)\n% save a segmentation to arcgrid format\nglobal h seg\nx = inputdlg('Enter variable name:',...\n 'Save new class', [1 50]);\nkinput=x{:}; \nnewseg = evalin('base',kinput);\nSaveAsciiRaster(newseg, h);\n\n\n% --------------------------------------------------------------------\nfunction Workspace_import_Callback(hObject, eventdata, handles)\n% Open both image and segmentation from the workspace\nglobal seg im edge I1\nvars = uigetvariables({'Image','Segmentation'});\nim = vars{1,1};\nseg = vars{1,2};\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \n\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n%imshow(imoverlay(I1,edge, [1 1 1]));\nend\nclearvars -except seg im edge I1 \n\n\n% --------------------------------------------------------------------\nfunction Workspace_menu_import_Callback(hObject, eventdata, handles)\n% workspace import menu item\n\n\n% --------------------------------------------------------------------\nfunction Image_wrkspace_import_Callback(hObject, eventdata, handles)\n% Import an image from the workspace\nglobal seg im edge I1\nvars = uigetvariables({'Image'});\nim = vars{1,1};\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n rgb = I1;\n imshow(rgb);\nelse \n\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n%mshow(im, 'DisplayRange',[]), colormap(jet);\nend\nclearvars -except seg im edge I1 \n\n% --------------------------------------------------------------------\nfunction Seg_wrkspace_import_Callback(hObject, eventdata, handles)\n% import a segmentation from the workspace\nglobal seg im edge I1\nvars = uigetvariables({'Segmentation raster'});\nseg= vars{1,1};\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \n\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n%imshow(imoverlay(I1,edge, [1 1 1]));\nend\nclearvars -except seg im edge I1 \n\n\n% --------------------------------------------------------------------\nfunction BckAsc_Callback(hObject, eventdata, handles)\n% Open a background image in arcgrid format from fiel\nglobal BckIm\n[BckIm, h] = ImportAsciiRaster;\nBckIm = uint8(BckIm);\n\n% EXPORT PROPS/DATA CALLBACKS----------------------------------------------\nfunction Save_Texture_Harlick_Callback(~,~, handles)\n%Save to csv for use with GIS - eg join to a segmentation shapefile\nglobal CoStats\nStats2=CoStats;\n%Rounding and multiplication for visualisation in GIS\nStats2 = round(Stats2/0.01)*0.01;\nContrast = round(Stats2(1,:).*10);\nCorrelation = Stats2(2,:).*100;\nEnergy = Stats2(3,:).*100;\nHomogeneity = Stats2(4,:).*100;\nLabel = Stats2(5,:).*100;\nTable = table(Contrast, Correlation, Energy, Homogeneity, Label); \n[filename, pathname] = uiputfile('*.csv', 'Choose a file name');\noutname = fullfile(pathname, filename);\nwritetable(Table, filename);\nclearvars Table Contrast Correlation Energy Homogeneity Label\n\nfunction Save_Stats_2_XLS_Callback(~,~, handles)\n% Save pixel stats and region props to csv for use with GIS\nglobal Stats props\nStats2=Stats';\nStats2 = round(Stats2/0.01)*0.01;\nMean = Stats2(:,1);\nStdev = Stats2(:,2);\nSkewness = Stats2(:,3);\nVariance = Stats2(:,4);\nKurtosis = Stats2(:,5);\nEntropy = Stats2(:,6);\nLabel = Stats2(:,7);\nArea = [props.Area]';\nMajorAxisLength = [props.MajorAxisLength]';\nMinorAxisLength = [props.MinorAxisLength]';\nEccentricity = [props.Eccentricity]';\nOrientation = [props.Orientation]';\nSolidity = [props.Solidity]';\nExtent =[props.Extent]';\nTable = table(Mean, Stdev, Skewness, Variance, Kurtosis, Entropy, Label,...\n MajorAxisLength, MinorAxisLength, Eccentricity, Solidity, Extent);\n[filename, pathname] = uiputfile('*.csv', 'Choose a file name');\noutname = fullfile(pathname, filename);\nwritetable(Table, filename);\nclearvars Table Mean Stdev Skewness Variance Kurtosis Entropy Label...\n MajorAxisLength MinorAxisLength Eccentricity Solidity Extent\n\n\n% Miscellaneous----------------------------------------------------------\nfunction Display_Callback(~,~, handles)\n% Display menu item\n\n\n% --------------------------------------------------------------------\nfunction Export_Cluster_Callback(~,~, handles)\n% Export clustering results and re-label to the workspace for further analysis\nglobal BW2 seg\nx = inputdlg('Enter cluster number:',...\n 'Choose cluster & re-label', [1 50]);\nkinput = str2num(x{:});\nh = waitbar(0,'Re-labeling...');\nnewseg=membership2(seg,BW2==kinput);\nwaitbar(1,h,'Re-labeling done');\nclose(h);\n%seg = newseg;\nx = inputdlg('Enter class name:',...\n 'Choose cluster & re-label', [1 50]);\nkinput=x{:};\nassignin('base',kinput,newseg);\n\n\n% --------------------------------------------------------------------\nfunction Colour_Thresholder_Callback(~,~, handles)\n% Opens the matlab color thresholder with the currently displayed image\nglobal BW2\ncolorThresholder(BW2);\n\n% --------------------------------------------------------------------\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "ImageStats.m", "ext": ".m", "path": "SeAMS-master/Stats/ImageStats.m", "size": 28724, "source_encoding": "utf_8", "md5": "b438db423579b557837bd65143727707", "text": "% Statistics, visualisation and classification\n% Author Ciaran Robb\n% Written with GUIDE, this GUI provides functions for the calculation and\n% display and classification of segment statistics.\n\n% Acknowledgements for material adapted form the Matlab file exchange:\n% Anton Semechko for the adaptation of his fuzzy cmeans clustering\n% function\n% Laurent. S, for the adaptation of their kmeans++ function \n% Brett Shoelson for his uigetvariables function\n% Yist Tauber for the manual_thresh function/gui\n% Giuliano Langella for the Import and SaveAsciiRaster functions\n% % Acknowledgement: Peter Kovesi for his draw region boundary function\n\n\n% The code is organised into callbacks that are related to each other and\n% are ordered as follows:\n% PIXEL, REGION PROPERTYS AND THEIR DISPLAY IN THE GUI\n% MENU HEADING CALLBACKS\n% CLASSIFICATION CALLBACKS\n% INPUT AND OUTPUT OF FILES\n% EXPORT OF DATA\n% MISCELLANEOUS\n\nfunction varargout = ImageStats(varargin)\n% IMAGESTATS MATLAB code for ImageStats.fig\n% IMAGESTATS, by itself, creates a new IMAGESTATS or raises the existing\n% singleton*.\n%\n% H = IMAGESTATS returns the handle to a new IMAGESTATS or the handle to\n% the existing singleton*.\n%\n% IMAGESTATS('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in IMAGESTATS.M with the given input arguments.\n%\n% IMAGESTATS('Property','Value',...) creates a new IMAGESTATS or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before ImageStats_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to ImageStats_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help ImageStats\n\n% Last Modified by GUIDE v2.5 08-Jun-2015 16:31:36\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @ImageStats_OpeningFcn, ...\n 'gui_OutputFcn', @ImageStats_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before ImageStats is made visible.\nfunction ImageStats_OpeningFcn(hObject, ~, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to ImageStats (see VARARGIN)\n\n% Choose default command line output for ImageStats\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes ImageStats wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = ImageStats_OutputFcn(~, ~, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n%PIXEL AND REGION PROPERTY CALCULATION CALLBACKS\n% --------------------------------------------------------------------\nfunction Process_Callback(~,~, handles)\n% Processing menu callback\n\n% --------------------------------------------------------------------\nfunction Process_Harlick_Texture_Callback(~,~, handles)\n% This function is the callback for calculating Harlick texture features\n\nglobal im seg CoStats waitbarHandle offset1 offset2;\nx = inputdlg('Enter offsets:',...\n 'GCLM offsets', [1 50]);\nh = waitbar(0,'Calculating texture...');\nkinput = str2num(x{:});\noffset1 = kinput(:,1);\noffset2 =kinput(:,2);\n\nI = im;\nif(size(im,3)==3)\n im = rgb2gray(im);\nend\nwaitbar(0.5,h,'Calculating texture...');\nCoStats = cotextureprops(seg,im, offset1, offset2);\nwaitbar(0.8,h,'Calculating texture...');\nassignin('base','CoTextprops',CoStats);\nwaitbar(1,h,'Done!');\nclose(h);\n\n% --------------------------------------------------------------------\nfunction Process_ImStats_Callback(~, ~, ~)\n% This function is the callback for calculating image statistics and region\n% properties\n\nglobal im seg Stats StatsR StatsG StatsB props ;\nh = waitbar(0,'Calculating stats...');\nI = im;\nif(size(I,3)==3)\n R = im(:,:,1);\n G = im(:,:,2);\n B = im(:,:,3);\n [StatsR] = Ctextprops(seg,R);\n [StatsG] = Ctextprops(seg,G);\n [StatsB] = Ctextprops(seg,B);\n ClrStats= [StatsR(1,:); StatsG(1,:); StatsB(1,:)];\n assignin('base','ClrStats',ClrStats);\n clearvars ClrStats\nend\nwaitbar(0.2,h,'Calculating stats...')\nStats = Ctextprops(seg,I);\nwaitbar(0.5,h,'Image stats done, calculating region props...')\nprops = regionprops(seg, 'Area', 'Eccentricity',...\n'Extent', 'MajorAxisLength', 'MinorAxisLength', 'Orientation','Solidity');\nwaitbar(0.8,h,'Calculating stats...')\nassignin('base','ImStats',Stats)\nassignin('base','Props',props)\nwaitbar(1,h,'Done!');\nclose(h);\n\n%REGION PROPERTY CALLBACKS---------------------------------------------\n\n% --------------------------------------------------------------------\nfunction Area_Callback(~,~, handles)\n%The call back for displaying the area property\nglobal seg props BW2 edge\n[BW2] = colorscale(seg,[props.Area]);\nBW2b = BW2;\nBW2b(edge)=0; \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\n% --------------------------------------------------------------------\nfunction Major_Axis_Callback(~,~, handles)\n% The call back for displaying the major axis length property\nglobal im seg props BW2 edge\n[BW2] = colorscale(seg,[props.MajorAxisLength]);\nBW2b = BW2;\nBW2b(edge==1)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Minor_Axis_Callback(~,~, handles)\n%The call back for displaying the minor axis length property\nglobal im seg props BW2 edge\n[BW2] = colorscale(seg,[props.MinorAxisLength]);\nBW2b = BW2;\nBW2b(edge)=0;\nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\n% --------------------------------------------------------------------\nfunction Eccentricity_Callback(~,~, handles)\n%The call back for displaying the eccentrcity property\nglobal im seg props BW2 edge\n[BW2] = colorscale(seg,[props.Eccentricity]*100);\nBW2b = BW2;\nBW2b(edge)=0;\nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n%---------------------------------------------------------------------\n% --------------------------------------------------------------------\nfunction Orientation_Callback(~,~, handles)\n% The call back to display orientation\n\nglobal im seg props BW2 edge\nOrient = [props.Orientation];\n[BW2] = colorscale(seg,Orient);\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\nOrient = [props.Orientation]+180;\n[BW2] =colorscale(seg,Orient); \n\n\n% --------------------------------------------------------------------\nfunction Extent_Callback(~,~, handles)\n%The call back for displaying the extent property\nglobal im seg props BW2 edge\n[BW2] = colorscale(seg,[props.Extent]*100);\nBW2b = BW2;\nBW2b(edge)=0;\nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\n% --------------------------------------------------------------------\nfunction Solidity_Callback(~,~, handles)\n%The call back for displaying the solidity property\nglobal im seg props BW2 edge\n[BW2] = colorscale(seg,[props.Solidity]*100);\nBW2b = BW2;\nBW2b(edge)=0;\nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\n% --------------------------------------------------------------------\nfunction Image_Stats_Callback(~,~, handles)\n% hObject handle to Image_Stats (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n%PIXEL PROPERTY CALLBACKS---------------------------------------------\n% --------------------------------------------------------------------\nfunction Mean_Callback(~,~, handles)\n%The call back for displaying the mean pixel value property\n\nglobal im seg Stats BW2 I1 StatsR StatsG StatsB edge \nif(size(im,3)==3)\n [BWR] = colorscale(seg,StatsR(1,:));\n [BWG] = colorscale(seg,StatsG(1,:));\n [BWB] = colorscale(seg,StatsB(1,:));\n BW2 = uint8(cat(3, BWR, BWG, BWB));\n BW2(BW2<0)=0;\n %axes(handles.axes1); \n imshow(imoverlay(BW2, edge, [0 0 0]));\nelse \n[BW2] = colorscale(seg,Stats(1,:));\nBW2(BW2<0)=0;\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n\n colorbar('location','eastoutside');\nend\n\n\n% --------------------------------------------------------------------\nfunction Stdev_Callback(~,~, handles)\n%The call back for displaying the stdev pixel value property\n\nglobal im seg Stats StatsR BW2 edge\n[BW2] = colorscale(seg,Stats(3,:)*100);\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\n% --------------------------------------------------------------------\nfunction Skew_Callback(~,~, handles)\n%The call back for displaying the pixel skewness property\n\nglobal im seg Stats StatsR BW2 edge\n[BW2] = colorscale(seg,Stats(4,:));\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Variance_Callback(~,~, handles)\n%The call back for displaying the pixel variance\n\nglobal im seg Stats StatsR BW2 edge\n[BW2] = colorscale(seg,Stats(5,:)*100);\nBW2b = BW2;\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Kurtosis_Callback(~,~, handles)\n%The call back for displaying the pixel kurtosis\nglobal im seg Stats StatsR BW2 edge\n[BW2] = colorscale(seg,Stats(6,:));\nBW2b = BW2;\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n\nfunction Entropy_Callback(~,~, handles)\nglobal seg Stats BW2 edge\n[BW2] = colorscale(seg,Stats(2,:)*100);\nBW2b = BW2;\nBW2b(edge)=0;\n%axes(handles.axes1); \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n% HARLICK TEXTURE DISPLAY CALLBACKS---------------------------------------\nfunction Display_Texture_Harlick_Callback(~,~, handles)\n% hObject handle to Display_Texture_Harlick (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Contrast_Callback(~,~, handles)\n% hObject handle to Contrast (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg CoStats BW2 edge\n[BW2] = colorscale(seg,CoStats(1,:)*10);\nBW2b = BW2;\nBW2b(edge)=0; \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),... \n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Correlation_Callback(~,~, handles)\n% hObject handle to Correlation (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg CoStats BW2 edge\n[BW2] = colorscale(seg,CoStats(2,:)*10);\nBW2b = BW2;\nBW2b(edge)=0; \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),... \n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Energy_Callback(~,~, handles)\n% hObject handle to Energy (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg CoStats BW2 edge\n[BW2] = colorscale(seg,CoStats(3,:)*100);\nBW2b = BW2;\nBW2b(edge)=0; \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),... \n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Homogeneity_Callback(~,~, handles)\n% hObject handle to Homogeneity (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg CoStats BW2 edge\n[BW2] = colorscale(seg,CoStats(4,:)*100);\nBW2b = BW2; \nBW2b(edge)=0; \nimshow(BW2b, 'DisplayRange',[]), colormap(jet),... \n colorbar('location','eastoutside');\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit5_CreateFcn(~,~, handles)\n% hObject handle to edit5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\n% --- Executes on button press in pushbutton26.\nfunction pushbutton26_Callback(~,~, handles)\n% hObject handle to pushbutton26 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal BW2\n[lowThreshold highThreshold lastThresholdedBand] = ...\n threshold(jetthresh(BW2), ...\n max(BW2(:)), BW2);\nBW3 = BW2 >=lowThreshold & BW2 <=highThreshold;\nassignin('base','BW',bw);\n\n\n%MENU HEADING CALLBACKS-----------------------------------------------\n\n% --------------------------------------------------------------------\nfunction Classify_Callback(~,~, handles)\n% hObject handle to Classify (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% --------------------------------------------------------------------\nfunction Untitled_18_Callback(~,~, handles)\n% hObject handle to Untitled_18 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Reset_Callback(~,~, handles)\n% hObject handle to Reset (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Export_Callback(~,~, handles)\n% hObject handle to Export (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Save_Seg_Callback(~,~, handles)\n% hObject handle to Save_Seg (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n%CLASSIFICATION CALLBACKS--------------------------------------------\n\n% --------------------------------------------------------------------\nfunction Fuzzy_Cmeans_Callback(~,~, handles)\n% hObject handle to Fuzzy_Cmeans (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nglobal BW2 edge \nx = inputdlg('Enter number of clusters, fuzzy weighting:',...\n 'Fuzzy Cmeans', [1 50]);\nkinput = str2num(x{:});\nk = kinput(:,1);\nfz =kinput(:,2);\n[L,C,U,LUT,H]=FastFCMeans(uint16(BW2),k,fz);\nBW2=L;\nBW2b=BW2;\nBW2b(edge)=0;\nimshow(BW2b,'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\nassignin('base','FzCmeans',L);\nclearvars BW2b\n\n\n% --------------------------------------------------------------------\nfunction Cluster_Position_Callback(~,~, handles)\n% hObject handle to Cluster_Position (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal BW2 seg edge\n\nx = inputdlg('Enter no of clusters:',...\n 'Cluster Position', [1 50]);\nclusters = str2num(x{:});\n\n[Clustered]= ClusterCentroid(seg, clusters);\n[BW2] = colorscale(seg,Clustered);\nassignin('base', 'Posimage', BW2);\nBW2b = BW2;\nBW2b = BW2;\nBW2b(edge)=0;\nimshow(BW2b, 'DisplayRange',[]), colormap(jet),...\n colorbar('location','eastoutside');\n\n% --------------------------------------------------------------------\nfunction Kmeans_xx_Callback(~,~, handles)\n% hObject handle to Kmeans_xx (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Multi_Thresholding_Callback(~,~, handles)\n% hObject handle to Multi_Thresholding (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal BW2 seg\n[level,level2,bw] = manual_thresh(BW2,jet);\nnewseg=membership2(seg,bw);\nx = inputdlg('Enter class name:',...\n 'Re-label & export', [1 50]);\nkinput=x{:};\nassignin('base',kinput,newseg);\n\n\n%INPUT AND OUTPUT CALLBACKS-------------------------------------------\n\n% --------------------------------------------------------------------\nfunction Image_Callback(~,~, handles)\n% hObject handle to Image (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Seg_Callback(~,~, handles)\n% hObject handle to Seg (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Seg_From_File_Callback(~,~, handles)\n% Open a non geo-referenced segmentation image\nglobal im seg \n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('You will need a file!'));\n return\nend\nseg=imread(path);\n%axes(handles.axes1);\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n\n% --------------------------------------------------------------------\nfunction Seg_From_Workspace_Callback(~,~, handles)\n% Open a segmentation raster from the workspace\nglobal seg im edge\nx = inputdlg('Enter variable name:',...\n 'Image from workspace', [1 50]);\nkinput=x{:}; \nseg = evalin('base',kinput);\n%axes(handles.axes1);\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \n\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n%axes(handles.axes1);\n%imshow(imoverlay(I1,edge, [1 1 1]));\nend\n\n% --------------------------------------------------------------------\nfunction IM_From_File_Callback(~,~, handles)\n%Open a non-geo-reffed tif image\n\nglobal im im2\n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('You will need a file!'));\n return\nend\nim=imread(path);\nI = uint8(im);\n%im=im2double(im); %converts to double\nim=double(im); %for backup process :)\nif(size(im,3)==3)\n imshow(I);\nelse\n%axes(handles.axes1);\nimshow(im,'DisplayRange',[]), colormap(jet);\nend\n\n\n% --------------------------------------------------------------------\nfunction Im_From_Workspace_Callback(~,~, handles)\n% Open image from workspace\nglobal im \n% = uigetvariables({'Please select any variable','And another'});\nim = double(im);\n%axes(handles.axes1);\nimshow(im,'DisplayRange',[]), colormap(jet);\n\n\n% --------------------------------------------------------------------\nfunction Seg_To_File_Callback(~,~, handles)\n% hObject handle to Seg_To_File (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% --------------------------------------------------------------------\nfunction View_Callback(hObject, eventdata, handles)\n% MENU ITEM\n\n\n% --------------------------------------------------------------------\nfunction Prop_Bck_Callback(hObject, eventdata, handles)\n% Display a property overlayed on a background image\nglobal BW2 seg im BckIm edge\nrgb = label2rgb(uint16(BW2), 'jet', [1 1 1]);\n % figure with transparency\nfigure,imshow(BckIm), hold on\nhimage = imshow(rgb);\nset(himage, 'AlphaData', 0.3);\nclearvars rgb \n% --------------------------------------------------------------------\nfunction Back_Im_file_Callback(hObject, eventdata, handles)\n% Background menu item\n\n\n% --------------------------------------------------------------------\nfunction Bck_File_Callback(hObject, eventdata, handles)\n%Open a non-geo reffed background image - eg hillshade\nglobal BckIm im\n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('Error'),'Error','Error');\n return\nend\nBckIm=imread(path);\nBckIm=uint8(BckIm);\n% if(size(im,3)==3)\n% BckIm=rgb2gray(BckIm);\n% end\n\n\n% --------------------------------------------------------------------\nfunction Bck_Wrk_Callback(hObject, eventdata, handles)\n% Open a non-geo reffed background image - eg hillshade from the workspace\nglobal BckIm \nBckIm = uigetvariables({'Image'});\nBckIm=BckIM{1,1};\nBckIm = uint8(BckIm);\n% if(size(im,3)==3)\n% BckIm=rgb2gray(BckIm);\n% end\n\n\n% --------------------------------------------------------------------\nfunction Open_asc_Callback(hObject, eventdata, handles)\n% % Open a geo reffed image from file\nglobal im h seg\n[im, h] = ImportAsciiRaster;\nimshow(im, 'DisplayRange', []), colormap('jet');\n\n\n% --------------------------------------------------------------------\nfunction seg_asc_open_Callback(hObject, eventdata, handles)\n% % Open a geo reffed segmentation from file\nglobal seg h I1 \n[seg, h] = ImportAsciiRaster;\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \n\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n%imshow(imoverlay(I1,edge, [0 0 0]));\nend\n\n% --------------------------------------------------------------------\nfunction Save_asc_seg_Callback(hObject, eventdata, handles)\n% save a segmentation to arcgrid format\nglobal h seg\nx = inputdlg('Enter variable name:',...\n 'Save new class', [1 50]);\nkinput=x{:}; \nnewseg = evalin('base',kinput);\nSaveAsciiRaster(newseg, h);\n\n\n% --------------------------------------------------------------------\nfunction Workspace_import_Callback(hObject, eventdata, handles)\n% Open both image and segmentation from the workspace\nglobal seg im edge I1\nvars = uigetvariables({'Image','Segmentation'});\nim = vars{1,1};\nseg = vars{1,2};\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \n\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n%imshow(imoverlay(I1,edge, [1 1 1]));\nend\nclearvars -except seg im edge I1 \n\n\n% --------------------------------------------------------------------\nfunction Workspace_menu_import_Callback(hObject, eventdata, handles)\n% workspace import menu item\n\n\n% --------------------------------------------------------------------\nfunction Image_wrkspace_import_Callback(hObject, eventdata, handles)\n% Import an image from the workspace\nglobal seg im edge I1\nvars = uigetvariables({'Image'});\nim = vars{1,1};\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n rgb = I1;\n imshow(rgb);\nelse \n\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n%mshow(im, 'DisplayRange',[]), colormap(jet);\nend\nclearvars -except seg im edge I1 \n\n% --------------------------------------------------------------------\nfunction Seg_wrkspace_import_Callback(hObject, eventdata, handles)\n% import a segmentation from the workspace\nglobal seg im edge I1\nvars = uigetvariables({'Segmentation raster'});\nseg= vars{1,1};\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \n\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\n%imshow(imoverlay(I1,edge, [1 1 1]));\nend\nclearvars -except seg im edge I1 \n\n\n% --------------------------------------------------------------------\nfunction BckAsc_Callback(hObject, eventdata, handles)\n% Open a background image in arcgrid format from fiel\nglobal BckIm\n[BckIm, h] = ImportAsciiRaster;\nBckIm = uint8(BckIm);\n\n% EXPORT PROPS/DATA CALLBACKS----------------------------------------------\nfunction Save_Texture_Harlick_Callback(~,~, handles)\n%Save to csv for use with GIS - eg join to a segmentation shapefile\nglobal CoStats\nStats2=CoStats;\n%Rounding and multiplication for visualisation in GIS\nStats2 = round(Stats2/0.01)*0.01;\nContrast = round(Stats2(1,:).*10);\nCorrelation = Stats2(2,:).*100;\nEnergy = Stats2(3,:).*100;\nHomogeneity = Stats2(4,:).*100;\nLabel = Stats2(5,:).*100;\nTable = table(Contrast, Correlation, Energy, Homogeneity, Label); \n[filename, pathname] = uiputfile('*.csv', 'Choose a file name');\noutname = fullfile(pathname, filename);\nwritetable(Table, filename);\nclearvars Table Contrast Correlation Energy Homogeneity Label\n\nfunction Save_Stats_2_XLS_Callback(~,~, handles)\n% Save pixel stats and region props to csv for use with GIS\nglobal Stats props\nStats2=Stats';\nStats2 = round(Stats2/0.01)*0.01;\nMean = Stats2(:,1);\nStdev = Stats2(:,2);\nSkewness = Stats2(:,3);\nVariance = Stats2(:,4);\nKurtosis = Stats2(:,5);\nEntropy = Stats2(:,6);\nLabel = Stats2(:,7);\nArea = [props.Area]';\nMajorAxisLength = [props.MajorAxisLength]';\nMinorAxisLength = [props.MinorAxisLength]';\nEccentricity = [props.Eccentricity]';\nOrientation = [props.Orientation]';\nSolidity = [props.Solidity]';\nExtent =[props.Extent]';\nTable = table(Mean, Stdev, Skewness, Variance, Kurtosis, Entropy, Label,...\n MajorAxisLength, MinorAxisLength, Eccentricity, Solidity, Extent);\n[filename, pathname] = uiputfile('*.csv', 'Choose a file name');\noutname = fullfile(pathname, filename);\nwritetable(Table, filename);\nclearvars Table Mean Stdev Skewness Variance Kurtosis Entropy Label...\n MajorAxisLength MinorAxisLength Eccentricity Solidity Extent\n\n\n% Miscellaneous----------------------------------------------------------\nfunction Display_Callback(~,~, handles)\n% Display menu item\n\n\n% --------------------------------------------------------------------\nfunction Export_Cluster_Callback(~,~, handles)\n% Export clustering results and re-label to the workspace for further analysis\nglobal BW2 seg\nx = inputdlg('Enter cluster number:',...\n 'Choose cluster & re-label', [1 50]);\nkinput = str2num(x{:});\nh = waitbar(0,'Re-labeling...');\nnewseg=membership2(seg,BW2==kinput);\nwaitbar(1,h,'Re-labeling done');\nclose(h);\n%seg = newseg;\nx = inputdlg('Enter class name:',...\n 'Choose cluster & re-label', [1 50]);\nkinput=x{:};\nassignin('base',kinput,newseg);\n\n\n% --------------------------------------------------------------------\nfunction Colour_Thresholder_Callback(~,~, handles)\n% Opens the matlab color thresholder with the currently displayed image\nglobal BW2\ncolorThresholder(BW2);\n\n% --------------------------------------------------------------------\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "kmeansxx.m", "ext": ".m", "path": "SeAMS-master/Classify/kmeans++/kmeansxx.m", "size": 2910, "source_encoding": "utf_8", "md5": "a3faae98bf59aaeeba031cc316e05061", "text": "function [L,C] = kmeansxx(X,k)\n%KMEANS Cluster multivariate data using the k-means++ algorithm.\n% [L,C] = kmeans(X,k) produces a 1-by-size(X,2) vector L with one class\n% label per column in X and a size(X,1)-by-k matrix C containing the\n% centers corresponding to each class.\n\n% Version: 2013-02-08\n% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n%\n% References:\n% [1] J. B. MacQueen, \"Some Methods for Classification and Analysis of \n% MultiVariate Observations\", in Proc. of the fifth Berkeley\n% Symposium on Mathematical Statistics and Probability, L. M. L. Cam\n% and J. Neyman, eds., vol. 1, UC Press, 1967, pp. 281-297.\n% [2] D. Arthur and S. Vassilvitskii, \"k-means++: The Advantages of\n% Careful Seeding\", Technical Report 2006-13, Stanford InfoLab, 2006.\n\nL = [];\nL1 = 0;\n\nwhile length(unique(L)) ~= k\n \n % The k-means++ initialization.\n C = X(:,1+round(rand*(size(X,2)-1)));\n L = ones(1,size(X,2));\n for i = 2:k\n D = X-C(:,L);\n D = cumsum(sqrt(dot(D,D,1)));\n if D(end) == 0, C(:,i:k) = X(:,ones(1,k-i+1)); return; end\n C(:,i) = X(:,find(rand < D/D(end),1));\n [~,L] = max(bsxfun(@minus,2*real(C'*X),dot(C,C,1).'));\n end\n \n % The k-means algorithm.\n while any(L ~= L1)\n L1 = L;\n for i = 1:k, l = L==i; C(:,i) = sum(X(:,l),2)/sum(l); end\n [~,L] = max(bsxfun(@minus,2*real(C'*X),dot(C,C,1).'),[],1);\n end\n \nend\nfunction [L,C] = kmeansxx(X,k)\n%KMEANS Cluster multivariate data using the k-means++ algorithm.\n% [L,C] = kmeans(X,k) produces a 1-by-size(X,2) vector L with one class\n% label per column in X and a size(X,1)-by-k matrix C containing the\n% centers corresponding to each class.\n\n% Version: 2013-02-08\n% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n%\n% References:\n% [1] J. B. MacQueen, \"Some Methods for Classification and Analysis of \n% MultiVariate Observations\", in Proc. of the fifth Berkeley\n% Symposium on Mathematical Statistics and Probability, L. M. L. Cam\n% and J. Neyman, eds., vol. 1, UC Press, 1967, pp. 281-297.\n% [2] D. Arthur and S. Vassilvitskii, \"k-means++: The Advantages of\n% Careful Seeding\", Technical Report 2006-13, Stanford InfoLab, 2006.\n\nL = [];\nL1 = 0;\n\nwhile length(unique(L)) ~= k\n \n % The k-means++ initialization.\n C = X(:,1+round(rand*(size(X,2)-1)));\n L = ones(1,size(X,2));\n for i = 2:k\n D = X-C(:,L);\n D = cumsum(sqrt(dot(D,D,1)));\n if D(end) == 0, C(:,i:k) = X(:,ones(1,k-i+1)); return; end\n C(:,i) = X(:,find(rand < D/D(end),1));\n [~,L] = max(bsxfun(@minus,2*real(C'*X),dot(C,C,1).'));\n end\n \n % The k-means algorithm.\n while any(L ~= L1)\n L1 = L;\n for i = 1:k, l = L==i; C(:,i) = sum(X(:,l),2)/sum(l); end\n [~,L] = max(bsxfun(@minus,2*real(C'*X),dot(C,C,1).'),[],1);\n end\n \nend\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "kxxGUI.m", "ext": ".m", "path": "SeAMS-master/Classify/kmeans++/kxxGUI.m", "size": 8900, "source_encoding": "utf_8", "md5": "8620835bd7444ddbb0366f2a34c2e802", "text": "function varargout = kxxGUI(varargin)\n% KXXGUI MATLAB code for kxxGUI.fig\n% KXXGUI, by itself, creates a new KXXGUI or raises the existing\n% singleton*.\n%\n% H = KXXGUI returns the handle to a new KXXGUI or the handle to\n% the existing singleton*.\n%\n% KXXGUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in KXXGUI.M with the given input arguments.\n%\n% KXXGUI('Property','Value',...) creates a new KXXGUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before kxxGUI_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to kxxGUI_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help kxxGUI\n\n% Last Modified by GUIDE v2.5 22-Jan-2014 15:04:28\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @kxxGUI_OpeningFcn, ...\n 'gui_OutputFcn', @kxxGUI_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before kxxGUI is made visible.\nfunction kxxGUI_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to kxxGUI (see VARARGIN)\n\n% Choose default command line output for kxxGUI\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes kxxGUI wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = kxxGUI_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in pushbutton4.\nfunction pushbutton4_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal seg cluster kmeans waitbarHandle\nwaitbarHandle = waitbar(0,'Extracting Class...');\n\tset(waitbarHandle,...\n\t\t'Name','Calculating Texture Props');\nseg3 = membership(seg, kmeans==cluster);\nclose(waitbarHandle);\t\n[FileName, PathName] = uiputfile('*.Tiff', 'Save As'); %# <-- dot\nName = fullfile(PathName,FileName); %# <--- reverse the order of arguments\nimwrite(seg3, Name, 'Tiff');\n\n% --- Executes on button press in pushbutton1.\nfunction pushbutton1_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im im2\n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('Error'),'Error','Error');\n return\nend\nim=imread(path);\n%im=im2double(im); %converts to double\nim2=im; %for backup process :)\naxes(handles.axes1);\nI = uint8(im);\nimshow(I), colormap('jet');\n\n% --- Executes on button press in pushbutton2.\nfunction pushbutton2_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg\n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('Error'),'Error','Error');\n return\nend\nseg=imread(path);\naxes(handles.axes1);\nI1 = uint8(im);\nimshow(segboundaries(seg, I1, [1 0 0]));\n\n\nfunction edit1_Callback(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit1 as text\n% str2double(get(hObject,'String')) returns contents of edit1 as a double\nglobal k\n\nk = str2double(get(hObject,'String'));\n\n% --- Executes during object creation, after setting all properties.\nfunction edit1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in pushbutton3.\nfunction pushbutton3_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg k kmeans\naxes(handles.axes1);\nI3= uint8(im);\nprops = regionprops(seg, I3, 'MeanIntensity'); \nkmeans = kmeansxx([props.MeanIntensity], k);\nassignin('base','kmeans',kmeans)\n[kim] =colorscale(seg, kmeans);\n\nimagesc(kim), colorbar('location','southoutside'), colormap('jet');\n\n\n\n% --- Executes on button press in pushbutton5.\nfunction pushbutton5_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im2 im seg\naxes(handles.axes1);\nI2 = uint8(im2);\nimshow(segboundaries(seg, I2, [0 0 0]));\n\n\n\nfunction edit2_Callback(hObject, eventdata, handles)\n% hObject handle to edit2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit2 as text\n% str2double(get(hObject,'String')) returns contents of edit2 as a double\nglobal cluster2 cluster kmean\n\ncluster = str2double(get(hObject,'String'));\ncluster2 = kmean==cluster;\n\n% --- Executes during object creation, after setting all properties.\nfunction edit2_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in pushbutton7.\nfunction pushbutton7_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton7 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal kmeans seg\nkmeans2 = kmeans';\nStats3=num2cell(kmeans2);\n[filename, pathname] = uiputfile('*.xls', 'Choose a file name');\noutname = fullfile(pathname, filename);\nxlswrite(outname, Stats3);\n\n\n\nfunction edit3_Callback(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit3 as text\n% str2double(get(hObject,'String')) returns contents of edit3 as a double\nglobal cluster\ncluster = str2double(get(hObject,'String'));\n\n% --- Executes during object creation, after setting all properties.\nfunction edit3_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "SegmentationGUI.m", "ext": ".m", "path": "SeAMS-master/SegmentationOBIA/SegmentationGUI.m", "size": 11708, "source_encoding": "utf_8", "md5": "1dc49d3367b35a65a4b2b36ccc19b9c4", "text": "% Segmentation GUI\n% Authour: Ciaran Robb\n% Written with guide, this GUI provides three means of segmentating an\n% image and visualising the results\n% Acknowledgements for adaptation of file exchange/publically availbale: \n% Sean Lankton & Shai Bagon for the wrapping of EDISON C++ code\n% Sylvan Boltz for the SRM function\n% Brett Shoelson for the uigetvariables function\n% Giuliano Langella for the Import and SaveAsciiRaster functions\n\n\n% Refs\n% Comaniciu, D., Meer, P., 2002. Mean shift: A robust approach toward feature\n% space analysis. Pattern Analysis and Machine Intelligence, IEEE Transac-\n% -tions on 24 (5), 603–619.\n% Meer, P., Georgescu, B., 2001. Edge detection with embedded confidence.\n% IEEE Transactions on Pattern Analysis and Machine Intelligence 23 (12),\n% 1351–1365.\n% Nock, R., Nielsen, F., 2004. Statistical region merging. Pattern Analysis and\n% Machine Intelligence, IEEE Transactions on 26 (11), 1452–1458.\n% Meyer, F., Jul. 1994. Topographic distance and watershed lines. Signal\n% Processing 38 (1), 113–125.\n\n% Code is ordered as follows:\n\n% INPUT/OUTPUT CALLBACKS\n% SEGMENTATION CALLBACKS\n% MENU HEADING CALLBACKS\n% SEGMENTATION RESULTS VIEW CALLBACKS\n\n\nfunction varargout = SegmentationGUI(varargin)\n% SEGMENTATIONGUI MATLAB code for SegmentationGUI.fig\n% SEGMENTATIONGUI, by itself, creates a new SEGMENTATIONGUI or raises the existing\n% singleton*.\n%\n% H = SEGMENTATIONGUI returns the handle to a new SEGMENTATIONGUI or the handle to\n% the existing singleton*.\n%\n% SEGMENTATIONGUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SEGMENTATIONGUI.M with the given input arguments.\n%\n% SEGMENTATIONGUI('Property','Value',...) creates a new SEGMENTATIONGUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before SegmentationGUI_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to SegmentationGUI_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help SegmentationGUI\n\n% Last Modified by GUIDE v2.5 25-Jan-2015 17:56:53\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @SegmentationGUI_OpeningFcn, ...\n 'gui_OutputFcn', @SegmentationGUI_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before SegmentationGUI is made visible.\nfunction SegmentationGUI_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to SegmentationGUI (see VARARGIN)\n\n% Choose default command line output for SegmentationGUI\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes SegmentationGUI wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = SegmentationGUI_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n% INPUT/OUTPUT CALLBACKS--------------------------------------------------\n% --------------------------------------------------------------------\n% --------------------------------------------------------------------\n% --------------------------------------------------------------------\nfunction Open_asc_im_Callback(hObject, eventdata, handles)\n% Open an arcgrid image\nglobal im h I1\n[im, h] = ImportAsciiRaster(0);\nI1=uint8(im);\nif(size(im,3)==3)\n imshow(I1);\nelse \naxes(handles.axes1);\nimshow(im, 'DisplayRange',[]), colormap(jet);\nend\n\nfunction save_asc_ms_Callback(hObject, eventdata, handles)\n% Save mena shift image to arcgrid format\nglobal h ms\nSaveAsciiRaster(ms, h);\n\n% --------------------------------------------------------------------\nfunction Save_asc_seg_Callback(hObject, eventdata, handles)\n% Save segmentation to arcgrid format\nglobal h seg\nSaveAsciiRaster(seg, h);\n\n\n\nfunction MS_save_to_file_Callback(hObject, eventdata, handles)\n% Save mean-shift image to non geo reffed tif\nglobal ms\n[FileName, PathName] = uiputfile('*.tif', 'Save As'); %# <-- dot\nName = fullfile(PathName,FileName); %# <--- reverse the order of arguments\nimwrite(ms, Name, 'tif');\n\n% --------------------------------------------------------------------\nfunction Workspace_Save_Callback(hObject, eventdata, handles)\n% save mean shift and segmentation to workspace\nglobal ms seg \nassignin('base','seg',seg)\nassignin('base','ms',ms)\n% --------------------------------------------------------------------\nfunction Save_to_file_Callback(hObject, eventdata, handles)\n% Save segmentation image to non geo reffed tif\nglobal seg\nseg1 = uint16(seg);\n[FileName, PathName] = uiputfile('*.tif', 'Save As'); %# <-- dot\nName = fullfile(PathName,FileName); %# <--- reverse the order of arguments\nimwrite(seg1, Name, 'tif');\n\n% --------------------------------------------------------------------\nfunction FromFile_Callback(hObject, eventdata, handles)\n% Open image from tif format (no geo ref)\nglobal im I1 \n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('Error'),'Error','Error');\n return\nend\nim=double(imread(path));\nI1=uint8(im);\n%im2=im; %for backup process \naxes(handles.axes1);\nimshow(I1);\n\n% --------------------------------------------------------------------\nfunction WorkSpace_menu_Callback(hObject, eventdata, handles)\n% Open image from workspace\nglobal seg im I1\nim = uigetvariables({'Image'});\nim=im{1,1};\nim = double(im);\naxes(handles.axes1);\nif(size(im,3)==3)\n imshow(im) \nelse \nimshow(im,'DisplayRange',[]), colormap(jet);\nend\nclearvars -except seg im edge I1 h\n% --------------------------------------------------------------------\n\n% SEGMENTATION CALLBACKS----------------------------------------------\n% --------------------------------------------------------------------\nfunction Watershed_Menu_Callback(hObject, eventdata, handles)\n% watershed segmentation\nglobal im seg edge I1\nx = inputdlg('Enter pixel gradient threshold:',...\n 'Watershed Segmentation',[1 50]);\nh = waitbar(0.2,'Segmenting...');\nkinput = str2num(x{:});\n[edge, segcontour, seg] = Cshed(im, kinput);\nassignin('base','seg',seg)\nwaitbar(0.5, h, 'Segmenting...');\naxes(handles.axes1);\nedge=drawregionboundaries(seg);\nassignin('base','edge',edge)\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \nwaitbar(0.8, h, 'Segmenting...');\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nwaitbar(1, h, 'Done!');\nimshow(imoverlay(rgb,edge, [1 1 1]));\nclose(h)\nclearvars -except seg im edge I1 h\nend\n\n% --------------------------------------------------------------------\nfunction MeanShift_Menu_Callback(hObject, eventdata, handles)\n% Mean shift segmentation\nglobal im seg ms I1 edge\nx = inputdlg('Enter range,radius,minimum segment size:',...\n 'Mean Shift Segmentation',[1 50]);\nh = waitbar(0.2,'Segmenting...');\nkinput = str2num(x{:});\nradius = kinput(:,1);\nrange =kinput(:,2);\nMinSize =kinput(:,3);\nwaitbar(0.5,'Segmenting...');\n[ms seg grad conf] = msseg(im, radius, range, MinSize);\nclearvars im2\nms=ms*100;\nwaitbar(0.7,'Segmenting...');\nassignin('base','seg',seg)\nassignin('base','ms',ms)\naxes(handles.axes1);\nedge =drawregionboundaries(seg);\nif(size(I1,3)==3)\n imshow(imoverlay(I1,edge, [0 0 0]));\nelse \nedge = drawregionboundaries(seg); \nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\nclearvars -except ms seg edge im I1 h\nwaitbar(1,'Done!');\nend\nclose(h);\n\n% --------------------------------------------------------------------\nfunction SRM_Callback(hObject, eventdata, handles)\n% Statistical region merging callbacks\nglobal seg im edge I1 mn\nx = inputdlg('Enter merging threshold (Approx number of segments):',...\n 'Statistical Region Merging',[1 50]);\nh = waitbar(0.2,'Segmenting...');\nkinput = str2num(x{:});\n[seg edge] = srm2(im, kinput);\nwaitbar(0.5,h,'Segmenting...');\nassignin('base','seg',seg)\naxes(handles.axes1);\nedge=drawregionboundaries(seg);\nwaitbar(0.8,h,'Segmenting...');\nassignin('base','edge',edge)\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \nedge = drawregionboundaries(seg); \nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [1 1 1]));\nclearvars -except seg im edge I1 h\nwaitbar(1,h,'Done!');\nend\nclose(h);\n% -MENU HEADING CALLBACKS----------------------------------------------\n% ----------------------------------------------------------------------\nfunction Open_menu_Callback(hObject, eventdata, handles)\n\n% --------------------------------------------------------------------\nfunction Save_menu_Callback(hObject, eventdata, handles)\n% --------------------------------------------------------------------\nfunction Save_MS_Callback(hObject, eventdata, handles)\n% --------------------------------------------------------------------\nfunction MS_save_Workspace_Callback(hObject, eventdata, handles)\n% --------------------------------------------------------------------\nfunction File_menu_Callback(hObject, eventdata, handles)\n% --------------------------------------------------------------------\nfunction View_Callback(hObject, eventdata, handles)\n% --------------------------------------------------------------------\nfunction SegmentationMenu_Callback(hObject, eventdata, handles)\n\n% SEGMENTATION RESULTS VIEW CALLBACKS--------------------------------\n%-------------------------------------------------------------------------\nfunction Seg_Outlines_Callback(hObject, eventdata, handles)\n% \nglobal I1 edge\nif(size(I1,3)==3)\n rgb = I1;\n imshow(imoverlay(rgb,edge, [0 0 0]));\nelse \nassignin('base','edge',edge)\nMax = max(I1(:));\nMax = double(Max);\n[X, map] = gray2ind(I1,Max);\nrgb = ind2rgb(X, jet(Max));\nimshow(imoverlay(rgb,edge, [0 0 0]));\nclearvars -except seg im edge I1 h\nend\n% --------------------------------------------------------------------\nfunction Mean_Image_view_Callback(hObject, eventdata, handles)\n% \nglobal ms\nif(size(ms,3)==3)\n ms =uint8(ms);\n imshow(ms);\nelse \nimshow(ms, 'DisplayRange',[])\nend\n\n% --------------------------------------------------------------------\nfunction Outlines_Mean_Image_Callback(hObject, eventdata, handles)\n% Displays outlines and mean image - only works with mean shift\nglobal ms seg\nif(size(ms,3)==3)\n \n imshow(imoverlay(rgb,ms, [0 0 0]));\nelse \nMax = max(ms(:));\n\nimshow(drawregionboundaries(seg,uint8(ms)));\nclearvars -except seg im edge I1 h\nend\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "msseg.m", "ext": ".m", "path": "SeAMS-master/SegmentationOBIA/MeanShift/msseg.m", "size": 1378, "source_encoding": "utf_8", "md5": "657017fe6adeb096ffb573671357c921", "text": "% Performing mean_shift image segmentation using EDISON code implementation\r\n% of Comaniciu's paper with a MEX wrapper from Shai Bagon. links at bottom\r\n% of help\r\n%\r\n% Usage:\r\n% [S L grad conf] = msseg(I,hs,hr,M)\r\n% \r\n% Inputs:\r\n% I - original image in RGB or grayscale\r\n% hs - spatial bandwith for mean shift analysis\r\n% hr - range bandwidth for mean shift analysis\r\n% M - minimum size of final output regions\r\n%\r\n% Outputs:\r\n% S - segmented image\r\n% L - resulting label map\r\n%\r\n% Links:\r\n% Comaniciu's Paper\r\n% http://www.caip.rutgers.edu/riul/research/papers/abstract/mnshft.html\r\n% EDISON code\r\n% http://www.caip.rutgers.edu/riul/research/code/EDISON/index.html\r\n% Shai's mex wrapper code\r\n% http://www.wisdom.weizmann.ac.il/~bagon/matlab.html\r\n%\r\n% Author:\r\n% This file and re-wrapping by Shawn Lankton (www.shawnlankton.com)\r\n% Nov. 2007\r\n%------------------------------------------------------------------------\r\n\r\nfunction [S L grad conf] = msseg(I,hs,hr,M)\r\n gray = 0;\r\n if(size(I,3)==1)\r\n gray = 1;\r\n I = repmat(I,[1 1 3]);\r\n end\r\n \r\n if(nargin < 4)\r\n hs = 10; hr = 7; M = 30;\r\n end\r\n \r\n [fimg L modes regsize grad conf] = edison_wrapper(I,@RGB2Luv,...\r\n 'SpatialBandWidth',hs,'RangeBandWidth',hr,...\r\n 'MinimumRegionArea',M,'speedup',1);\r\n \r\n S = Luv2RGB(fimg);\r\n\r\n if(gray == 1)\r\n S = rgb2gray(S);\r\n end"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "edison_wrapper.m", "ext": ".m", "path": "SeAMS-master/SegmentationOBIA/MeanShift/edison_matlab_interface/edison_wrapper.m", "size": 6071, "source_encoding": "utf_8", "md5": "e38b90d4d1c4979c05527087208324c4", "text": "function [varargout] = edison_wrapper(rgbim, featurefun, varargin)\n%\n% Performing mean_shift operation on image\n%\n% Usage:\n% [fimage labels modes regSize grad conf] = edison_wrapper(rgbim, featurefunc, ...)\n% \n% Inputs:\n% rgbim - original image in RGB space\n% featurefunc - converting RGB to some feature space in which to perform\n% the segmentation, like @RGB2Lab etc.\n%\n% Allowed parameters:\n% 'steps' - What steps the algorithm should perform:\n% 1 - only mean shift filtering\n% 2 - filtering and region fusion [default]\n% 'synergistic' - perform synergistic segmentation [true]|false\n% 'SpatialBandWidth' - segmentation spatial radius (integer) [7]\n% 'RangeBandWidth' - segmentation feature space radius (float) [6.5]\n% 'MinimumRegionArea'- minimum segment area (integer) [20]\n% 'SpeedUp' - algorithm speed up {1,2,3} [2]\n% 'GradientWindowRadius' - synergistic parameters (integer) [2]\n% 'MixtureParameter' - synergistic parameter (float 0,1) [.3]\n% 'EdgeStrengthThreshold'- synergistic parameter (float 0,1) [.3]\n%\n% Outputs:\n% fimage - the result in feature space\n% labels - labels of regions [if steps==2]\n% modes - list of all modes [if steps==2]\n% regSize - size, in pixels, of each region [if steps==2]\n% grad - gradient map [if steps==2 and synergistic]\n% conf - confidence map [if steps==2 and synergistic]\n%\n\n\n% rgbim must be of type uint8\nif ~isa(rgbim,'uint8'),\n if max(rgbim(:)) <= 1,\n rgbim = im2uint8(rgbim);\n else\n rgbim = uint8(rgbim);\n end\nend\nimsiz = size(rgbim);\n\nfim = im2single(rgbim);\nfim = single(featurefun(fim));\n\nrgbim = permute(rgbim,[3 2 1]);\nfim = permute(fim, [3 2 1]);\n\np = parse_inputs(varargin);\n\nlabels = [];\nmodes =[];\nregSize = [];\ngrad = [];\nconf = [];\n\nif p.steps == 1\n [fimage] = edison_wrapper_mex(fim, rgbim, p);\nelse\n if p.synergistic\n [fimage labels modes regSize grad conf] = edison_wrapper_mex(fim, rgbim, p);\n else\n [fimage labels modes regSize] = edison_wrapper_mex(fim, rgbim, p);\n end\n grad = reshape(grad,imsiz([2 1]))';\n conf = reshape(conf',imsiz([2 1]))';\nend\nfimage = permute(fimage, [3 2 1]);\n\nif nargout >= 1, varargout{1} = fimage; end;\nif nargout >= 2, varargout{2} = labels'; end;\nif nargout >= 3, varargout{3} = modes; end;\nif nargout >= 4, varargout{4} = regSize; end;\nif nargout >= 5, varargout{5} = grad; end;\nif nargout >= 6, varargout{6} = conf; end;\n\n\n%--------------------------------------------------------%\nfunction [p] = parse_inputs(args)\n% Allowed parameters\n% 'steps' - What steps the algorithm should perform:\n% 1 - only mean shift filtering\n% 2 - filtering and region fusion [defualt]\n% 'synergistic' - perform synergistic segmentation [true]|false\n% 'SpatialBandWidth' - segmentation spatial radius (integer) [7]\n% 'RangeBandWidth' - segmentation feature space radius (float) [6.5]\n% 'MinimumRegionArea'- minimum segment area (integer) [20]\n% 'SpeedUp' - algorithm speed up {0,1,2} [1]\n% 'GradientWindowRadius' - synergistic parameters (integer) [2]\n% 'MixtureParameter' - synergistic parameter (float 0,1) [.3]\n% 'EdgeStrengthThreshold'- synergistic parameter (float 0,1) [.3]\n\n\n% convert ars to parameters - then init all the rest according to defualts\ntry \n p = struct(args{:});\ncatch\n error('edison_wrapper:parse_inputs','Cannot parse arguments');\nend\n\n% % modes of operation\n% -. edge detection -- currently unsupported\n% 1. Filtering\n% 2. Fusing regions\n% 3. Segmentation\nif ~isfield(p,'steps')\n p.steps = 2;\nend\nif p.steps ~= 1 && p.steps ~=2 \n error('edison_wrapper:parse_inputs','steps must be either 1 or 2');\nend\n\n% % parameters\n% Flags\n% 1. synergistic\nif ~isfield(p,'synergistic')\n p.synergistic = true;\nend\np.synergistic = logical(p.synergistic);\n\n% Mean Shift Segmentation parameters\n% SpatialBandWidth [integer]\nif ~isfield(p,'SpatialBandWidth')\n p.SpatialBandWidth = 7;\nend\nif p.SpatialBandWidth < 0 || p.SpatialBandWidth ~= round(p.SpatialBandWidth)\n error('edison_wrapper:parse_inputs','SpatialBandWidth must be a positive integer');\nend\n% RangeBandWidth [float]\nif ~isfield(p,'RangeBandWidth')\n p.RangeBandWidth = 6.5;\nend\nif p.RangeBandWidth < 0\n error('edison_wrapper:parse_inputs','RangeBandWidth must be positive');\nend\n% MinimumRegionArea [integer]\nif ~isfield(p,'MinimumRegionArea')\n p.MinimumRegionArea = 20;\nend\nif p.MinimumRegionArea < 0 || p.MinimumRegionArea ~= round(p.MinimumRegionArea)\n error('edison_wrapper:parse_inputs','MinimumRegionArea must be a positive integer');\nend\n% SpeedUp\nif ~isfield(p,'SpeedUp')\n p.SpeedUp = 2;\nend\nif p.SpeedUp ~=1 && p.SpeedUp ~= 2 && p.SpeedUp ~= 3\n error('edison_wrapper:parse_inputs','SpeedUp must be either 1, 2 or 3');\nend\n% Synergistic Segmentation parameters\n% GradientWindowRadius [integer]\nif ~isfield(p,'GradientWindowRadius')\n p.GradientWindowRadius = 2;\nend\nif p.GradientWindowRadius < 0 || p.GradientWindowRadius ~= round(p.GradientWindowRadius)\n error('edison_wrapper:parse_inputs','GradientWindowRadius must be a positive integer');\nend\n% MixtureParameter [float (0,1)]\nif ~isfield(p,'MixtureParameter')\n p.MixtureParameter = .3;\nend\nif p.MixtureParameter < 0 || p.MixtureParameter > 1\n error('edison_wrapper:parse_inputs','MixtureParameter must be between zero and one');\nend\n% EdgeStrengthThreshold [float (0,1)]\nif ~isfield(p,'EdgeStrengthThreshold')\n p.EdgeStrengthThreshold = .3;\nend\nif p.EdgeStrengthThreshold < 0 || p.EdgeStrengthThreshold > 1\n error('edison_wrapper:parse_inputs','MixtureParameter must be between zero and one');\nend\n\n% % Currently unsupported\n% Edge Detection Parameters\n% GradientWindowRadius [integer]\n% MinimumLength [integer]\n% NmxRank [float (0,1)]\n% NmxConf [float (0,1)]\n% NmxType\n% HysterisisHighRank [float (0,1)]\n% HysterisisHighConf [float (0,1)]\n% HysterisisHighType \n% HysterisisLowRank [float (0,1)]\n% HysterisisLowConf [float (0,1)]\n% HysterisisLowType \n\n% % "} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "srm_getborders.m", "ext": ".m", "path": "SeAMS-master/SegmentationOBIA/srm/srm_getborders.m", "size": 226, "source_encoding": "utf_8", "md5": "9f24b148c7e587960b326e5d9bfd11e3", "text": "\nfunction borders = srm_getborders(map)\n\ndx = conv2(map, [-1 1], 'same');\ndy = conv2(map, [-1 1]', 'same');\ndy(end,:) = 0; % ignore the last row of dy\ndx(:,end) = 0; % and the last col of dx\nborders = find(dx ~= 0 | dy ~= 0);\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "srm.m", "ext": ".m", "path": "SeAMS-master/SegmentationOBIA/srm/srm.m", "size": 4375, "source_encoding": "utf_8", "md5": "472ad0601f793c588e0136ebb29bf385", "text": "% Statistical Region Merging\n%\n% Nock, Richard and Nielsen, Frank 2004. Statistical Region Merging. IEEE Trans. Pattern Anal. Mach. Intell. 26, 11 (Nov. 2004), 1452-1458.\n% DOI= http://dx.doi.org/10.1109/TPAMI.2004.110\n\n%Segmentation parameter Q; Q small few segments, Q large may segments\n\nfunction [maps,images, im_final]=srm(image,Qlevels)\n\nimage = double(image);\nif(size(image,3)==1)\n image = repmat(image,[1 1 3]);\nend\n\n% Smoothing the image, comment this line if you work on clean or synthetic images\nh=fspecial('gaussian',[3 3],1);\nimage=imfilter(image,h,'symmetric');\n\nsmallest_region_allowed=10;\n\nsize_image=size(image);\nn_pixels=size_image(1)*size_image(2);\n\n% Compute image gradient\n[Ix,Iy]=srm_imgGrad(image(:,:,:));\nIx=max(abs(Ix),[],3);\nIy=max(abs(Iy),[],3);\nnormgradient=sqrt(Ix.^2+Iy.^2);\n\nIx(:,end)=[];\nIy(end,:)=[];\n\n[~,index]=sort(abs([Iy(:);Ix(:)]));\n\nn_levels=numel(Qlevels);\nmaps=cell(n_levels,1);\nimages=cell(n_levels,1);\nim_final=zeros(size_image);\n\nmap=reshape(1:n_pixels,size_image(1:2));\n% gaps=zeros(size(map)); % For future release\ntreerank=zeros(size_image(1:2));\n\nsize_segments=ones(size_image(1:2));\nimage_seg=image;\n\n%Building pairs\nn_pairs=numel(index);\nidx2=reshape(map(:,1:end-1),[],1);\nidx1=reshape(map(1:end-1,:),[],1);\n\npairs1=[ idx1;idx2 ];\npairs2=[ idx1+1;idx2+size_image(1) ];\n\nfor Q=Qlevels\n iter=find(Q==Qlevels);\n \n for i=1:n_pairs\n C1=pairs1(index(i));\n C2=pairs2(index(i));\n \n %Union-Find structure, here are the finds, average complexity O(1)\n while (map(C1)~=C1 ); C1=map(C1); end\n while (map(C2)~=C2 ); C2=map(C2); end\n \n % Compute the predicate, region merging test\n g=256;\n logdelta=2*log(6*n_pixels);\n \n dR=(image_seg(C1)-image_seg(C2))^2;\n dG=(image_seg(C1+n_pixels)-image_seg(C2+n_pixels))^2;\n dB=(image_seg(C1+2*n_pixels)-image_seg(C2+2*n_pixels))^2;\n \n logreg1 = min(g,size_segments(C1))*log(1.0+size_segments(C1));\n logreg2 = min(g,size_segments(C2))*log(1.0+size_segments(C2));\n \n dev1=((g*g)/(2.0*Q*size_segments(C1)))*(logreg1 + logdelta);\n dev2=((g*g)/(2.0*Q*size_segments(C2)))*(logreg2 + logdelta);\n \n dev=dev1+dev2;\n \n \n predicat=( (dR treerank(C2)\n map(C2) = C1; reg=C1;\n elseif treerank(C1) < treerank(C2)\n map(C1) = C2; reg=C2;\n elseif C1 ~= C2\n map(C2) = C1; reg=C1;\n treerank(C1) = treerank(C1) + 1;\n end\n \n if C1~=C2\n % Merge regions\n nreg=size_segments(C1)+size_segments(C2);\n image_seg(reg)=(size_segments(C1)*image_seg(C1)+size_segments(C2)*image_seg(C2))/nreg;\n image_seg(reg+n_pixels)=(size_segments(C1)*image_seg(C1+n_pixels)+size_segments(C2)*image_seg(C2+n_pixels))/nreg;\n image_seg(reg+2*n_pixels)=(size_segments(C1)*image_seg(C1+2*n_pixels)+size_segments(C2)*image_seg(C2+2*n_pixels))/nreg;\n size_segments(reg)=nreg;\n end\n end\n end\n \n \n % Done, building two result figures, figure 1 is the segmentation map,\n % figure 2 is the segmentation map with the average color in each segment\n \n \n while 1\n map_ = map(map) ;\n if isequal(map_,map) ; break ; end\n map = map_ ;\n end\n \n \n \n for i=1:3\n im_final(:,:,i)=image_seg(map+(i-1)*n_pixels);\n end\n images{iter}=im_final;\n \n [clusterlist,~,labels] = unique(map) ;\n labels=reshape(labels,size(map));\n nlabels=numel(clusterlist);\n maps{iter}=map;\n %This last lot here don't appear to do anything - as pointed out on\n %file exchange\n% bgradient = sparse(srm_boundarygradient(labels, nlabels, normgradient));\n% bgradient = bgradient - tril(bgradient);\n% idx=find(bgradient>0);\n% [~,index]=sort(bgradient(idx));\n% n_pairs=numel(idx);\n% [xlabels,ylabels]=ind2sub([nlabels,nlabels],idx);\n% pairs1=clusterlist(xlabels);\n% pairs2=clusterlist(ylabels);\nend\n\n\n\n\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "Ciaran1981/SeAMS-master", "name": "srmGUI.m", "ext": ".m", "path": "SeAMS-master/SegmentationOBIA/srm/srmGUI.m", "size": 9479, "source_encoding": "utf_8", "md5": "1e16b5c97f7de9d1b52d0dedb28c309c", "text": "function varargout = srmGUI(varargin)\n% SRMGUI MATLAB code for srmGUI.fig\n% SRMGUI, by itself, creates a new SRMGUI or raises the existing\n% singleton*.\n%\n% H = SRMGUI returns the handle to a new SRMGUI or the handle to\n% the existing singleton*.\n%\n% SRMGUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SRMGUI.M with the given input arguments.\n%\n% SRMGUI('Property','Value',...) creates a new SRMGUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before srmGUI_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to srmGUI_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help srmGUI\n\n% Last Modified by GUIDE v2.5 28-Feb-2014 11:36:54\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @srmGUI_OpeningFcn, ...\n 'gui_OutputFcn', @srmGUI_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before srmGUI is made visible.\nfunction srmGUI_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to srmGUI (see VARARGIN)\n\n% Choose default command line output for srmGUI\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes srmGUI wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = srmGUI_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --------------------------------------------------------------------\nfunction Untitled_1_Callback(hObject, eventdata, handles)\n% hObject handle to Untitled_1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Untitled_2_Callback(hObject, eventdata, handles)\n% hObject handle to Untitled_2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im im2 I1 \n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('Error'),'Error','Error');\n return\nend\nim=imread(path);\nI1=im; %for backup process :)\naxes(handles.axes1);\nif(size(I,3)==3)\n imshow(uint8(I));\nelse\nimshow(I1, 'DisplayRange',[]), colormap(jet);\nend\n\n% --------------------------------------------------------------------\nfunction Untitled_4_Callback(hObject, eventdata, handles)\n% hObject handle to Untitled_4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal seg im \nim = evalin('base','MnImage');\nI1 = uint8(im);\nim = double(im);\naxes(handles.axes1);\nimshow(I1);\n\n% --- Executes on button press in pushbutton1.\nfunction pushbutton1_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n global seg2 im seg MergeLevel waitbarHandle;\n waitbarHandle = waitbar(0,'Merging...');\n\tset(waitbarHandle,...\n\t\t'Name','Merging');\nI1 = uint8(im);\n[maps,images]=srm(I1,MergeLevel);\nIedge=zeros([size(images{1},1),size(images{1},2)]);\nmap=reshape(maps{1},size(Iedge));\nquick_I2{1} = images{1} ;\nprecision=numel(maps);\nquick_I1 = cell(precision,1);\nnewseg = cell2mat(quick_I2);\nnewseg = newseg(:,:,1);\nseg = newseg;\nedge =drawregionboundaries(seg);\nclose(waitbarHandle);\nimshow(imoverlay( I1, edge, [1 0 0]));\n\n% --- Executes on slider movement.\nfunction slider2_Callback(hObject, eventdata, handles)\n% hObject handle to slider2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\nglobal g_Floating;\n global g_MaxThreshold;\n global g_MinThreshold;\n global g_LastThresholdedColorBand;\n g_LastThresholdedColorBand = get(handles.listbox_DisplayColorBand,'Value') - 1;\n\n % Get the value of the sliders\n minSliderValue = get(hObject,'Value');\n\t% Round it to an integer if the image is a uint (not a floating).\n\tif g_Floating == 0 \n\t minSliderValue = round(minSliderValue);\n\tend\n\t\n %disp(['Moved min slider. New value = ' num2str(minSliderValue)]);\n\n % Set the global variable.\n if (minSliderValue <= g_MaxThreshold)\n g_MinThreshold = minSliderValue;\n % Update the label.\n set(handles.edit_Min, 'string', num2str(g_MinThreshold));\n end\n % Call guidata anytime you use the set() command or directly access\n % a variable you added to the handles structure. Generally it's a good\n % practice to just automatically add this at the end of every function.\n guidata(hObject, handles);\n\n % Apply the threshold to the display so we can see its effect.\n ShowThresholdedBinaryImage(hObject, eventdata, handles);\n\n% --- Executes during object creation, after setting all properties.\nfunction slider2_CreateFcn(hObject, eventdata, handles)\n% hObject handle to slider2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n\nfunction edit1_Callback(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit1 as text\n% str2double(get(hObject,'String')) returns contents of edit1 as a double\nglobal MergeLevel\n MergeLevel= str2double(get(hObject,'String'));\n % Call guidata anytime you use the set() command or directly access\n % a variable you added to the handles structure. Generally it's a good\n % practice to just automatically add this at the end of every function.\n \n% --- Executes during object creation, after setting all properties.\nfunction edit1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes during object creation, after setting all properties.\n\n\n% --------------------------------------------------------------------\nfunction Untitled_5_Callback(hObject, eventdata, handles)\n% hObject handle to Untitled_5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction Untitled_6_Callback(hObject, eventdata, handles)\n% hObject handle to Untitled_6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal im seg\n[path,user_cance]=imgetfile();\nif user_cance\n msgbox(sprintf('Error'),'Error','Error');\n return\nend\nseg=imread(path);\naxes(handles.axes1);\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nimshow(imoverlay( I1,edge, [1 0 0]));\n\n% --------------------------------------------------------------------\nfunction Untitled_7_Callback(hObject, eventdata, handles)\n% hObject handle to Untitled_7 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal seg im\nseg = evalin('base','seg');\naxes(handles.axes1);\nI1 = uint8(im);\nedge =drawregionboundaries(seg);\nimshow(imoverlay( I1,edge, [1 0 0]));\n"} +{"plateform": "github", "repo_name": "mws262/MATLABImpedanceControlExample-master", "name": "Plotter.m", "ext": ".m", "path": "MATLABImpedanceControlExample-master/Plotter.m", "size": 6269, "source_encoding": "utf_8", "md5": "0a6c3e6b52f07e49e907914089d1e67e", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Animate the acrobot after the MAIN script has been run.\n%\n% Matthew Sheen, 2014\n%\n% Note: data is passed from this to the callback functions in the figure\n% object's UserData field.\n% For compatibility with 2014a and earlier, I use set/get instead of the\n% object.field notation.\n% Can also be done with global vars as in the backup version. I hate\n% global variables so, this version is the result.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Plotter(p)\nclose all\n\n%Playback speed:\n% playback = p.animationSpeed;\n\n%Name the whole window and define the mouse callback function\nf = figure;\nset(f,'WindowButtonMotionFcn','','WindowButtonDownFcn',@ClickDown,'WindowButtonUpFcn',@ClickUp,'KeyPressFc',@KeyPress);\n\nfigData.xtarget = [];\nfigData.ytarget = [];\nfigData.Fx = [];\nfigData.Fy = [];\nfigData.xend = [];\nfigData.yend = [];\nfigData.fig = f;\nfigData.tarControl = true;\n\n%%%%%%%% 1st Subplot -- the pendulum animation %%%%%%%\nfigData.simArea = subplot(1,1,1); %Eliminated other subplots, but left this for syntax consistency.\naxis equal\nhold on\n\n%Create pendulum link1 object:\nwidth1 = p.l1*0.05;\nxdat1 = 0.5*width1*[-1 1 1 -1];\nydat1 = p.l1*[0 0 1 1];\nlink1 = patch(xdat1,ydat1, [0 0 0 0],'r');\n\n%Create pendulum link2 object:\nwidth2 = p.l2*0.05;\nxdat2 = 0.5*width2*[-1 1 1 -1];\nydat2 = p.l2*[0 0 1 1];\nlink2 = patch(xdat2,ydat2, [0 0 0 0],'b');\naxis([-3.5 3.5 -3.6 3.6]);\n\n%Dots for the hinges:\nh1 = plot(0,0,'.k','MarkerSize',40); %First link anchor\nh2 = plot(0,0,'.k','MarkerSize',40); %link1 -> link2 hinge\n\n%Timer label:\ntimer = text(-3.2,-3.2,'0.00','FontSize',28);\n\n%Torque meters on screen\ntmeter1 = text(0.6,-3.2,'0.00','FontSize',22,'Color', 'r');\ntmeter2 = text(2.2,-3.2,'0.00','FontSize',22,'Color', 'b');\n\n%Target Pt.\ntargetPt = plot(p.xtarget,p.ytarget,'xr','MarkerSize',30);\n\nhold off\n\n%Make the whole window big for handy viewing:\nset(f, 'units', 'inches', 'position', [5 5 10 9])\nset(f,'Color',[1,1,1]);\n\n% Turn the axis off\nax = get(f,'Children');\nset(ax,'Visible','off');\n\n%Animation plot loop -- Includes symplectic integration now.\nz1 = p.init;\ntold = 0;\n\nset(f,'UserData',figData);\n\ntic %Start the clock\nwhile (ishandle(f))\n figData = get(f,'UserData');\n %%%% INTEGRATION %%%%\n tnew = toc;\n dt = tnew - told;\n \n %Old velocity and position\n xold = [z1(1),z1(3)];\n vold = [z1(2),z1(4)];\n \n %Call RHS given old state\n [zdot1, T1, T2] = FullDyn(tnew,z1,p);\n vinter1 = [zdot1(1),zdot1(3)];\n ainter = [zdot1(2),zdot1(4)];\n \n vinter2 = vold + ainter*dt; %Update velocity based on old RHS call\n \n %Update position.\n xnew = xold + vinter2*dt;\n vnew = (xnew-xold)/dt;\n \n z2 = [xnew(1) vnew(1) xnew(2) vnew(2)];\n\n z1 = z2;\n told = tnew;\n %%%%%%%%%%%%%%%%%%%%\n \n %If there are new mouse click locations, then set those as the new\n %target.\n if ~isempty(figData.xtarget)\n p.xtarget = figData.xtarget;\n end\n \n if ~isempty(figData.ytarget)\n p.ytarget = figData.ytarget;\n end\n set(targetPt,'xData',p.xtarget); %Change the target point graphically.\n set(targetPt,'yData',p.ytarget);\n \n %When you hit a key, it changes to force mode, where the mouse will\n %pull things.\n ra_e = ForwardKin(p.l1,p.l2,z1(1),z1(3));\n figData.xend = ra_e(1);\n figData.yend = ra_e(2);\n set(f,'UserData',figData);\n \n if ~isempty(figData.Fx)\n p.Fx = figData.Fx;\n end\n if ~isempty(figData.Fy)\n p.Fy = figData.Fy;\n end\n \n tstar = told; %Get the time (used during this entire iteration)\n \n %On screen timer.\n set(timer,'string',strcat(num2str(tstar,3),'s'))\n zstar = z1;%interp1(time,zarray,tstar); %Interpolate data at this instant in time.\n \n %Rotation matrices to manipulate the vertices of the patch objects\n %using theta1 and theta2 from the output state vector.\n rot1 = [cos(zstar(1)), -sin(zstar(1)); sin(zstar(1)),cos(zstar(1))]*[xdat1;ydat1];\n set(link1,'xData',rot1(1,:))\n set(link1,'yData',rot1(2,:))\n \n rot2 = [cos(zstar(3)+zstar(1)), -sin(zstar(3)+zstar(1)); sin(zstar(3)+zstar(1)),cos(zstar(3)+zstar(1))]*[xdat2;ydat2];\n \n set(link2,'xData',rot2(1,:)+(rot1(1,3)+rot1(1,4))/2) %We want to add the midpoint of the far edge of the first link to all points in link 2.\n set(link2,'yData',rot2(2,:)+(rot1(2,3)+rot1(2,4))/2)\n \n %Change the hinge dot location\n set(h2,'xData',(rot1(1,3)+rot1(1,4))/2)\n set(h2,'yData',(rot1(2,3)+rot1(2,4))/2)\n \n %Show torques on screen (text only atm) update for time series later.\n set(tmeter1,'string',strcat(num2str(T1,2),' Nm'));\n set(tmeter2,'string',strcat(num2str(T2,2),' Nm'));\n \n drawnow;\nend\nend\n\n%%%% BEGIN CALLBACKS FOR MOUSE AND KEYBOARD STUFF %%%%%\n\n% When click-up occurs, disable the mouse motion detecting callback\nfunction ClickUp(varargin)\n figData = get(varargin{1},'UserData');\n set(figData.fig,'WindowButtonMotionFcn','');\n figData.Fx = 0;\n figData.Fy = 0;\n set(varargin{1},'UserData',figData);\nend\n\n% When click-down occurs, enable the mouse motion detecting callback\nfunction ClickDown(varargin)\n figData = get(varargin{1},'UserData');\n figData.Fx = 0;\n figData.Fy = 0;\n\n set(figData.fig,'WindowButtonMotionFcn',@MousePos);\n set(varargin{1},'UserData',figData);\nend\n\n% any keypress switches from dragging the setpoint to applying a\n% disturbance.\nfunction KeyPress(hObject, eventdata, handles)\n\nfigData = get(hObject,'UserData');\n\nfigData.tarControl = ~figData.tarControl;\n\n if figData.tarControl\n disp('Mouse will change the target point of the end effector.')\n else\n disp('Mouse will apply a force on end effector.') \n end\nset(hObject,'UserData',figData);\nend\n\n% Checks mouse position and sends it back up.\nfunction MousePos(varargin)\n figData = get(varargin{1},'UserData');\n\n mousePos = get(figData.simArea,'CurrentPoint');\n if figData.tarControl\n figData.xtarget = mousePos(1,1);\n figData.ytarget = mousePos(1,2);\n else\n figData.Fx = 10*(mousePos(1,1)-figData.xend);\n figData.Fy = 10*(mousePos(1,2)-figData.yend);\n end\n set(varargin{1},'UserData',figData);\nend"} +{"plateform": "github", "repo_name": "tahmidmehdi/machine_learning_classification-master", "name": "TrainTestSVM.m", "ext": ".m", "path": "machine_learning_classification-master/TrainTestSVM.m", "size": 1805, "source_encoding": "utf_8", "md5": "8041dedecf34ea1f501c246751569c0f", "text": "% Author: Tahmid Mehdi\n% Trains data using SVM and performs k-fold cross-validation \n\n% Performs SVM algorithm to classify data in X and calculates error rate and time elapsed.\n% PRE: X is the matrix of inputs\n% Y is the vector of class attributes\n% folds is the number of tests to perform (int >=1)\nfunction [error, time] = TrainTestSVM(X, Y, folds)\n m = size(X, 1);\n error = zeros(folds);\n % binary classification\n if size(unique(Y),1) == 2\n for test = 1:folds\n CVSVMModel = fitcsvm(X,Y, 'Holdout', 0.3);\n error(test) = kfoldLoss(CVSVMModel);\n end\n % finds time elapsed\n f = @() fitcsvm(X,Y);\n time = timeit(f);\n % multiclass classification\n else\n for test = 1:folds\n % picks 30% of data for testing\n holdout = round(m*0.3);\n testIndices = randperm(m, holdout);\n dataTrain = [];\n dataTest = [];\n classTrain = [];\n classTest = [];\n for i = 1:m\n if any(i==testIndices)\n dataTest = vertcat(dataTest, X(i, :));\n classTest = vertcat(classTest, Y(i));\n else\n dataTrain = vertcat(dataTrain, X(i, :));\n classTrain = vertcat(classTrain, Y(i));\n end\n end\n\n result = multisvm(dataTrain, classTrain, dataTest);\n % calculates error rate\n misclassifications = 0;\n for j = 1:length(result)\n misclassifications = misclassifications + (result(j) ~= classTest(j));\n end\n error(test) = misclassifications/length(result);\n end\n f = @() multisvm(dataTrain, classTrain, dataTest);\n time = timeit(f);\n end\nend"} +{"plateform": "github", "repo_name": "tahmidmehdi/machine_learning_classification-master", "name": "TestKMeans.m", "ext": ".m", "path": "machine_learning_classification-master/TestKMeans.m", "size": 1128, "source_encoding": "utf_8", "md5": "af5566d160717bf64d32a733098afa70", "text": "% Author: Tahmid Mehdi\n% Performs and tests k-means clustering \n\n% Performs k-means algorithm to classify data in X and calculates accuracy rate and time elapsed.\n% PRE: X is the matrix of inputs\n% Y is the vector of class attributes\n% k is the number of clusters (int >0)\n% folds is the number of tests to perform (int >=1)\nfunction [accuracy, time] = TestKMeans(X, Y, k, folds)\n rng(1); % ensures replication\n m = size(X, 1);\n accuracy = zeros(folds);\n \n for test = 1:folds\n result = kmeans(X, k);\n % finds accuracy by pairwise agreement among data points\n if k==2\n correctPairs = 0;\n for i = 1:m-1\n for j = (i+1):m\n correctPairs = correctPairs + ((Y(i)==Y(j))==(result(i)==result(j)));\n end\n end\n accuracy = correctPairs/(0.5*m*(m-1));\n % finds rand index which is an accuracy measure\n else\n accMetrics = PartAgreeCoef(result, Y);\n accuracy = accMetrics.ri;\n end\n end\n % finds time\n f = @() kmeans(X,k);\n time = timeit(f);\nend"} +{"plateform": "github", "repo_name": "tahmidmehdi/machine_learning_classification-master", "name": "TestFCM.m", "ext": ".m", "path": "machine_learning_classification-master/TestFCM.m", "size": 1283, "source_encoding": "utf_8", "md5": "fb5bf28683276c30e65d6ee0d4c4e603", "text": "% Author: Tahmid Mehdi\n% Performs and tests fuzzy c-means clustering \n\n% Performs fcm algorithm to classify data in X and calculates accuracy rate and time elapsed.\n% PRE: X is the matrix of inputs\n% Y is the vector of class attributes\n% c is the number of clusters (int >0)\n% folds is the number of tests to perform (int >=1)\nfunction [accuracy, time] = TestFCM(X, Y, c, folds)\n opts = [nan;nan;nan;0];\n accuracy = zeros(folds);\n m = size(X, 1);\n \n for test = 1:folds\n [~, U, ~] = fcm(X, c, opts);\n % result is a vector with the ith entry equalling the class which\n % it has the highest degree of membership in \n [~, result] = max(U);\n % finds accuracy by pairwise agreement among data points\n if c==2\n correctPairs = 0;\n for i = 1:m-1\n for j = (i+1):m\n correctPairs = correctPairs + ((Y(i)==Y(j))==(result(i)==result(j)));\n end\n end\n accuracy = correctPairs/(0.5*m*(m-1));\n % finds rand index which is an accuracy measure\n else\n accMetrics = PartAgreeCoef(result', Y);\n accuracy = accMetrics.ri;\n end\n end\n % finds time\n f = @() fcm(X,c);\n time = timeit(f);\nend"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "NonLinear_ODE.m", "ext": ".m", "path": "Ark-master/Nonlinear_ODE_Spectral/NonLinear_ODE.m", "size": 20901, "source_encoding": "utf_8", "md5": "70f47302bfe235e99dcc0ec99d3e959a", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% This is a non-linear pseudo-spectral ODE solver over all R\r\n%\r\n% Author: Nicholas A. Battista \r\n% Institution (current): The College of New Jersey (TCNJ)\r\n% Institution (created): Rochester Institute of Technology\r\n% Date Created: August 2009\r\n% Last update: December 2020\r\n%\r\n% Running the code solves the following non-linear ODE:\r\n% \r\n% Laplacian(u) + 1/(1+u)^7 = f(r)\r\n%\r\n% with\r\n%\r\n% f(r) = 8*r^2/(1+r^2)^3 - 6/(1+r^2)^2 + 1/(1+ (1/(1+r^2)) )^7, [FAST CONV.] \r\n% or \r\n% f(r) = (r^2-6*r+6)*exp(-r) + 1/(1+(r^2*exp(-r)))^7, [SLOW CONV.] \r\n%\r\n% with Dirichelet BCs,\r\n%\r\n% du/dr(0)=0 & u(r->inf) = 0 \r\n%\r\n% and exact solution,\r\n%\r\n% u(r) = 1/(1+r^2) [FAST CONV.]\r\n% or\r\n% u(r) = r^2 e^(-r). [SLOW CONV.]\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction NonLinear_ODE\r\n\r\nStart_Num = 5; %Number of collocation pts to start simulation\r\nEnd_Num = 50; %Number of collocation pts to end simulation\r\n\r\nprint_info();\r\n\r\n\r\n%\r\n% Sweeps over different #'s of collocation pts to compare accuracies\r\nfor N=Start_Num:End_Num \r\n \r\n %For first iteration, initializes the vectors containing the errors for fast and slow convergence examples\r\n if N==Start_Num\r\n NerrorL2_F = zeros(1,N);\r\n NerrorInf_F = NerrorL2_F;\r\n time_F = NerrorL2_F;\r\n \r\n NerrorL2_S = NerrorL2_F;\r\n NerrorInf_S = NerrorL2_F;\r\n time_S = NerrorL2_F;\r\n end\r\n \r\n %Finds solution for particular number of basis functions, N, for FAST convergence example\r\n fast = 1; %Flag to run the FAST example\r\n [A, un_F, NerrorL2_F, NerrorInf_F, time_F] = find_Solution(N,NerrorL2_F,NerrorInf_F,time_F,fast);\r\n \r\n %Finds solution for particular number of basis functions, N, for SLOW convergence example\r\n fast = 0; %Flag to run the SLOW example\r\n [A, un_S, NerrorL2_S, NerrorInf_S, time_S] = find_Solution(N,NerrorL2_S,NerrorInf_S,time_S,fast);\r\n\r\n\r\nend %ends for loop at beginning looping over number of grid pts\r\n\r\nfprintf('\\n -------------------------------------------------------------- \\n\\n');\r\n\r\nplot_collocation_grid(N,A);\r\n\r\nplot_solution(N,un_F,un_S)\r\n\r\nplot_error_convergence(Start_Num,End_Num,NerrorL2_F,NerrorInf_F,NerrorL2_S,NerrorInf_S);\r\n\r\nplot_time_increase(Start_Num,End_Num,time_F,time_S);\r\n\r\nplot_coefficients(un_F,un_S)\r\n\r\nfprintf('\\n\\nThat is it! Thanks!\\n\\n');\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: finds the approximate solution to the PDF for a particular\r\n% number of collocation pts, N_A\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [A, un, NerrorL2, NerrorInf, time] = find_Solution(N_A,NerrorL2,NerrorInf,time,fast)\r\n\r\n\r\n%collocation points in r and theta directions\r\nA = cheby_collocation_points(N_A); %%Cheby collocation pts b/w [-1,1]\r\n\r\nun = initial_guess(N_A); %Initial guess for spectral coefficients\r\ntol = 1e-8; %Error Tolerance for Newton's Method\r\nerr= 1; %Error to initialize Newton's Method\r\nn=1; %Counter\r\n\r\nfprintf('\\n -------------------------------------------------------------- \\n\\n');\r\nfprintf('%d (# of basis functions in x and y)\\n\\n',N_A);\r\n\r\n%Stores Function,Deriv, and 2nd Deriv. Cheby. Poly Values\r\n[TAA, TA_P, TA_PP] = all_Cheby(A);\r\n\r\nif fast == 1\r\n fprintf('NEWTON METHOD FOR FAST CONVERGENCE EXAMPLE\\n');\r\nelse\r\n fprintf('NEWTON METHOD FOR SLOW CONVERGENCE EXAMPLE\\n');\r\nend\r\nfprintf('Step | Error\\n');\r\n\r\ntic\r\nwhile err > tol\r\n J = jacobian(N_A,A,TAA,TA_P,TA_PP,un);\r\n fn = build_rhs(N_A,A,un,fast);\r\n un1 = un - J\\fn;\r\n err = sqrt((un1-un)'*(un1-un));\r\n un = un1;\r\n\r\n fprintf(' %d | %d\\n',n,err);\r\n n=n+1;\r\nend\r\ntime(N_A) = toc;\r\n\r\nfprintf('Newton Method Converged within tol of %d\\n\\n',tol);\r\n\r\n[NerrorL2, NerrorInf] = expconv(N_A,un,NerrorL2,NerrorInf,fast);\r\n\r\n%Nerror = SupNormExpConv(N_A,Nerror,Sinitial,un);\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: s collocation grid points!\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction val = cheby_collocation_points(N)\r\n\r\nx = zeros(1,N+1);\r\nfor i=1:N+1\r\n x(N+2-i) = cos(pi*(i-1)/N);\r\nend\r\nval = x'; %% Need transpose\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: plots the collocation grid\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction plot_collocation_grid(N_A,A)\r\n\r\nfprintf('\\nplotting collocation grids...\\n');\r\n\r\nfigure(1)\r\n%\r\nfs = 15; % FontSize\r\n%\r\nfor k = 1:N_A+1\r\n plot(A(k),0,'mo','MarkerFaceColor','m'); hold on;\r\nend\r\nxlabel('A')\r\ntitle('Collocation Points');\r\nset(gca,'FontSize',fs);\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: Builds Jacobian Matrix\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction jac = jacobian(N_A,A,TAA,TA_P,TA_PP,un)\r\n\r\n\r\njac = zeros(N_A+1,N_A+1);\r\nfor a = 1:N_A+1 %%Runs over Chebyshev Collocation points: A e [-1,1]\r\n \r\n for j = 1:N_A+1 %%Runs over jth Chebyshev Polynomial\r\n \r\n TA_pp = TA_PP(j,a);\r\n TA_p = TA_P(j,a);\r\n TA = TAA(j,a);\r\n \r\n if a == 1\r\n jac(a,j) = TA_p;\r\n elseif a == N_A+1\r\n jac(a,j) = TA;\r\n else\r\n %jac(a,j) = 1/4*(1-A(a))^4*TA_pp + 1/2*((1-A(a))^4 /(A(a)+1))*TA_p + 2*interpolateAB(N_A,A(a),un)*TA ;\r\n jac(a,j) = 1/4*(1-A(a))^4*TA_pp + 1/2*((1-A(a))^4 /(A(a)+1))*TA_p - 7*(1+interpolateAB(N_A,A(a),un))^(-8)*TA ;\r\n\r\n end\r\n \r\n\r\n end\r\n\r\nend\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: Builds Right Hand Side (Boundary Conditions) [ie- Right hand Side of PDE, e.g., Lu = f]\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction val = build_rhs(N_A,A,un,fast) \r\n\r\nrhs = zeros(1,N_A+1);\r\nfor a = 1:N_A+1 %%Runs over Chebyshev Collocation points: A e [0,1]\r\n \r\n %UA = exp( - ((1+A(a))/(1-A(a)))^2 );\r\n %UA_A = 4*(1+A(a))/(A(a)-1)^3*UA; \r\n %UA_AA = -8*A(a)*(A(a)^2- 2*A(a) - 7 )/(A(a)-1)^6*UA;\r\n \r\n \r\n if a == 1\r\n rhs(a) = interpolateAB_p(N_A,A(a),un);\r\n elseif a == N_A+1\r\n rhs(a)= interpolateAB(N_A,A(a),un);\r\n else\r\n r = (1+A(a))/(1-A(a));\r\n %rhs(a) = Laplacian(A(a)) + interpolateAB(A(a))^2 - (1/4*(1-A(a))^4*UA_AA + 1/2*((1-A(a))^4/(1+A(a)))*UA_A + UA^2 );\r\n %rhs(a) = Laplacian(N_A,A(a),un) + interpolateAB(N_A,A(a),un)^2 - ( (r^2-6*r+6)*exp(-r) + (r^2*exp(-r))^2 );\r\n if fast == 1\r\n rhs(a) = Laplacian(N_A,A(a),un) + 1/(1+ interpolateAB(N_A,A(a),un))^7 - ( 8*r^2/(1+r^2)^3 - 6/(1+r^2)^2 + 1/(1+ (1/(1+r^2)) )^7 ); \r\n else\r\n rhs(a) = Laplacian(N_A,A(a),un) + 1/(1+ interpolateAB(N_A,A(a),un))^7 - ( (r^2-6*r+6)*exp(-r) + 1/(1+(r^2*exp(-r)))^7 );\r\n end\r\n end\r\n \r\n\r\nend\r\n\r\nval = rhs';\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: gives the value of the approximation series, u(r)\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction val = interpolateAB(N_A,A,un) \r\n\r\nval = 0;\r\n\r\nfor m =1:N_A+1\r\n \r\n TA = T(m-1,A);\r\n\r\n val = val + un(m)*TA;\r\n\r\nend\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: gives the value of the derivative of the approximation series, u'(r)\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction val = interpolateAB_p(N_A,A,un) \r\n\r\nval = 0;\r\n\r\nfor m =1:N_A+1\r\n \r\n TA_p = Tp(m-1,A);\r\n\r\n val = val + un(m)*TA_p;\r\n\r\nend\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: computes Laplacian in new coordinates, del^2(u)(r)\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction val = Laplacian(N_A,A,un) \r\n\r\nval = 0;\r\n\r\nfor j = 1:N_A+1\r\n \r\n TA_pp = Tpp(j-1,A);\r\n TA_p = Tp(j-1,A);\r\n\r\n val = val + un(j)*( 1/4*(1-A)^4*TA_pp + 1/2*((1-A)^4 /(A+1))*TA_p );\r\n\r\nend\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: T''(x) (2nd Derivative of Chebyshev Function of 1st Kind)\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction val = Tpp(j,x) \r\n\r\nif x == 1\r\n val = (j^4-j^2)/3;\r\nelseif x == -1\r\n val = (-1)^j*(j^4-j^2)/3;\r\nelse\r\n val = (j*(j+1)*T(j,x)-j*U(j,x))/(x^2-1);\r\nend\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: T'(x) (1st Derivative of Chebyshev Function of 1st Kind)\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction val = Tp(j,x) \r\n\r\nval = j*U(j-1,x);\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: T(x) (Chebyshev Function of 1st Kind); jth Cheby. polynomial\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction val = T(j,x) \r\n\r\nif x == 1\r\n val = 1;\r\nelseif x == -1\r\n val = (-1)^j;\r\nelse\r\n val = cos(j*acos(x));\r\nend\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: U(x) (Chebyshev Function of 2nd Kind); jth 2nd Cheby. polynomial\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction val = U(j,x) \r\n\r\nif x == 1\r\n val = j+1;\r\nelseif x == -1\r\n val = (-1)^j*(j+1);\r\nelseif j == -1\r\n val = 0;\r\nelse\r\n val = sin((j+1)*acos(x))/sin(acos(x));\r\nend\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: Stores chebyshev polynomials (and 1st & 2nd derivatives) in a\r\n% matrix that is indexed by: \r\n% MAT(k,a): k - which polynomial index, T_k\r\n% a - which collocation pt. index, \"X_a\"\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [TA, TA_p, TA_pp] = all_Cheby(A)\r\n\r\nlen = length(A);\r\nTA = zeros(len,len);\r\nTA_p = TA;\r\nTA_pp = TA;\r\nfor a=1:length(A)\r\n for k=1:length(A)\r\n TA(k,a) = T(k-1,A(a));\r\n TA_p(k,a) = Tp(k-1,A(a));\r\n TA_pp(k,a) = Tpp(k-1,A(a));\r\n end\r\nend\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: plots the approximate solutions vs. the exact solutions\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction plot_solution(N,un_F,un_S)\r\n\r\nfprintf('\\nplotting numerical solns vs. exact soln...\\n');\r\n\r\nxx = -1:.01:1;\r\n\r\numatrix_F = zeros(1,length(xx));\r\numatrix_S = umatrix_F;\r\nfor i = 1:length(xx)\r\n umatrix_F(i) = interpolateAB(N,xx(i),un_F);\r\n umatrix_S(i) = interpolateAB(N,xx(i),un_S);\r\nend\r\n\r\n\r\n%------------------\r\n% Exact Solutions\r\n%------------------\r\nA=xx;\r\nSOL1 = 1./( 1+ ( (1+A)./(1-A) ).^2 );\r\nSOL2 = ( (1+A)./(1-A) ).^2 .* exp(- ( (1+A)./(1-A) ) );\r\n\r\nfigure(2)\r\n%\r\nlw=8; % LineWidth\r\nfs=15; % FontSize\r\n%\r\nsubplot(1,2,1)\r\nplot(xx,SOL1,'k-','LineWidth',lw-3); hold on;\r\nplot(xx,umatrix_F,'r-','LineWidth',lw-3); hold on;\r\nplot(xx,SOL1,'k-','LineWidth',lw); hold on;\r\nplot(xx,umatrix_F,'r-','LineWidth',lw-5); hold on;\r\nxlabel('A')\r\nylabel('U(A)')\r\ntitle('Soln: u(r) = 1/(1+r^2) [FAST CONV.]');\r\nleg=legend('Exact','Numerical');\r\naxis([-1 1 -0.1 1.1]);\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n\r\nsubplot(1,2,2)\r\nplot(xx,SOL2,'k-','LineWidth',lw-3); hold on;\r\nplot(xx,umatrix_S,'r-','LineWidth',lw-3); hold on;\r\nplot(xx,SOL2,'k-','LineWidth',lw); hold on;\r\nplot(xx,umatrix_S,'r-','LineWidth',lw-5); hold on;\r\nxlabel('A')\r\nylabel('U(A)')\r\ntitle('Soln: u(r) = r^2 exp(-r) [SLOW CONV.]')\r\nleg=legend('Exact','Numerical');\r\naxis([-1 1 -0.1 0.6]);\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n\r\n\r\n% subplot(2,2,2)\r\n% ezplot('1/(1+((1+A)/(1-A))^2)',[-1 1])\r\n% title('Exact Soln: u(r)=1/(1+r^2) [FAST CONV.]')\r\n% axis([-1 1 -0.1 1.1]);\r\n% \r\n% subplot(2,2,3)\r\n% plot(xx,umatrix_S,'r-','LineWidth',lw)\r\n% xlabel('A')\r\n% ylabel('U(A)')\r\n% title('Numerical Soln: u(r) = r^2 exp(-r) [SLOW CONV.]')\r\n% axis([-1 1 -0.1 0.6]);\r\n% \r\n% subplot(2,2,4)\r\n% ezplot('((1+A)/(1-A))^2*exp(-((1+A)/(1-A)))',[-1 1])\r\n% title('Exact Soln: u(r) = r^2 exp(-r) [SLOW CONV.]')\r\n% axis([-1 1 -0.1 0.6]);\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: computes the error between approximate solution and exact\r\n% solution.\r\n%\r\n% RETURNS: -2 vectors containing L2-error and Inf-error \r\n% -each vector index corresponds to different # of\r\n% collocation pts.\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [NerrorL2, NerrorInf] = expconv(N,un,NerrorL2,NerrorInf,fast)\r\n\r\n%Grids to compare solution over\r\nAAA = -1:0.1:1;\r\n\r\noneVector = ones(length(AAA),1);\r\nuAexact = oneVector;\r\n\r\n%Computes each separation on variable solution respectively\r\nfor i = 1:length(AAA) \r\n r = (1+AAA(i))/(1-AAA(i));\r\n if fast == 1\r\n uAexact(i) = 1/(1+r^2); %FAST CONVERGENCE EXAMPLE\r\n else\r\n uAexact(i) = r^2*exp(-r); %SLOW CONVERGENCE EXAMPLE\r\n end\r\n if i==length(AAA)\r\n uAexact(i) = 0; \r\n end\r\nend\r\n\r\n%%%Creates matrix of exact solution @ points [-1,1]x[-1,1] in steps of 0.01\r\n%%%Creates spectral solution @ points [-1,1]x[-1,1] in steps of 0.01\r\n%%%Finds difference between exact and spectral solution\r\nlen = length(uAexact);\r\nsol = zeros(1,len);\r\nerror = zeros(1,len);\r\nfor i = 1:length(AAA)\r\n sol(i) = interpolateAB(N,AAA(i),un);\r\n error(i) = abs( sol(i) - uAexact(i) );\r\nend\r\n\r\n%Computes L2-Norm Error\r\nabsError = sqrt(sum(sum(error)));\r\nfprintf('The L2-Norm Error is: %d\\n',absError);\r\n\r\n%Computes Inf-Norm Error\r\nmaxError = max(max(abs(error)));\r\nfprintf('The Inf-Norm Error is: %d\\n',maxError);\r\n\r\n%L2-Norm Error Vector\r\nNerrorL2(N) = absError;\r\n\r\n%Inf-Norm Error Vector\r\nNerrorInf(N) = maxError;\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: plots the Convergence Rates for both cases - \"fast\" and \"slow\"\r\n% convergence\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction plot_error_convergence(S,E,NerrorL2_F,NerrorInf_F,NerrorL2_S,NerrorInf_S)\r\n\r\nfprintf('\\nplotting error convergence...\\n');\r\n\r\ncount = 1:1:E;\r\n%\r\nms=7; % MarkerSize\r\nfs=15; % FontSize\r\n%\r\nfigure(3)\r\n%\r\nsubplot(2,2,1)\r\nplot(count(S:E),NerrorL2_F(S:E),'ro','MarkerSize',ms,'MarkerFaceColor','r'); hold on;\r\nplot(count(S:E),NerrorL2_S(S:E),'b^','MarkerSize',ms,'MarkerFaceColor','b');\r\nxlabel('N')\r\nylabel('L2-Error')\r\ntitle('Error Convergence: L2-Error vs. N')\r\nleg=legend('fast','slow');\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n%\r\nsubplot(2,2,2)\r\nsemilogy(count(S:E),NerrorL2_F(S:E),'ro','MarkerSize',ms,'MarkerFaceColor','r'); hold on;\r\nsemilogy(count(S:E),NerrorL2_S(S:E),'b^','MarkerSize',ms,'MarkerFaceColor','b');\r\nxlabel('N')\r\nylabel('L2-Error')\r\ntitle('Error Convergence: Log(L2-Error) vs. N')\r\nleg=legend('fast','slow');\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n%\r\nsubplot(2,2,3)\r\nplot(count(S:E),NerrorInf_F(S:E),'ro','MarkerSize',ms,'MarkerFaceColor','r'); hold on;\r\nplot(count(S:E),NerrorInf_S(S:E),'b^','MarkerSize',ms,'MarkerFaceColor','b');\r\nxlabel('N')\r\nylabel('Inf-Norm Error')\r\ntitle('Error Convergence: Inf-Norm Error vs. N')\r\nleg=legend('fast','slow');\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n%\r\nsubplot(2,2,4)\r\nsemilogy(count(S:E),NerrorInf_F(S:E),'ro','MarkerSize',ms,'MarkerFaceColor','r'); hold on;\r\nsemilogy(count(S:E),NerrorInf_S(S:E),'b^','MarkerSize',ms,'MarkerFaceColor','b');\r\nxlabel('N')\r\nylabel('Inf-Norm Error')\r\ntitle('Error Convergence: Log(Inf-Norm Error) vs. N')\r\nleg=legend('fast','slow');\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: s the initial guess for a solution\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction val = initial_guess(N_A)\r\n\r\nuntmp = zeros(1,N_A+1);\r\nfor i = 1:N_A+1\r\n untmp(i) = 0;\r\nend\r\n\r\nval = untmp';\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: plots computational time needed to solve\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction plot_time_increase(S,E,time_F,time_S)\r\n\r\nfprintf('\\nplotting time complexity...\\n');\r\n\r\ncount = 1:1:E;\r\n\r\nms = 7; % MarkerSize\r\nfs = 15; % FontSize\r\n\r\nfigure(4)\r\nsubplot(1,2,1);\r\nplot(count(S:E),time_F(S:E),'ro','MarkerSize',ms,'MarkerFaceColor','r'); hold on;\r\nplot(count(S:E),time_S(S:E),'b^','MarkerSize',ms,'MarkerFaceColor','b'); hold on;\r\nxlabel('N')\r\nylabel('Time for Each Simulation')\r\ntitle('Time Complexity vs. N')\r\nleg=legend('fast','slow');\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n%\r\nsubplot(1,2,2);\r\nsemilogy(count(S:E),time_F(S:E),'ro','MarkerSize',ms,'MarkerFaceColor','r'); hold on;\r\nsemilogy(count(S:E),time_S(S:E),'b^','MarkerSize',ms,'MarkerFaceColor','b');\r\nxlabel('N')\r\nylabel('Time for Each Simulation')\r\ntitle('Time Complexity vs. N')\r\nleg=legend('fast','slow');\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: plots the spectral coefficients to show exponential decay\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction plot_coefficients(un_F,un_S)\r\n\r\nfprintf('\\nplotting spectral coefficients...\\n');\r\n\r\ncount = 0:1:length(un_F)-1;\r\n\r\nms = 7; % MarkerSize\r\nfs = 15; % FontSize\r\n\r\nfigure(5)\r\nsubplot(2,2,1);\r\nplot(count,un_F,'ro','MarkerSize',ms,'MarkerFaceColor','r'); hold on;\r\nplot(count,un_S,'b^','MarkerSize',ms,'MarkerFaceColor','b'); hold on;\r\nxlabel('n')\r\nylabel('c_n (coefficients)')\r\ntitle('Spectral Coefficients: abs(c_n) vs. n')\r\nleg=legend('fast','slow');\r\naxis([0 length(un_F)-1 -0.6 0.6]);\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n\r\nsubplot(2,2,2);\r\nplot(count,abs(un_F),'ro','MarkerSize',ms,'MarkerFaceColor','r'); hold on;\r\nplot(count,abs(un_S),'b^','MarkerSize',ms,'MarkerFaceColor','b'); hold on;\r\nxlabel('n')\r\nylabel('|c_n| (mag. of coefficient)')\r\ntitle('Spectral Coefficients: abs(c_n) vs. n')\r\nleg=legend('fast','slow');\r\naxis([0 length(un_F)-1 0 0.6]);\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n\r\nsubplot(2,2,3:4);\r\nsemilogy(count,abs(un_F),'ro','MarkerSize',ms,'MarkerFaceColor','r'); hold on;\r\nsemilogy(count,abs(un_S),'b^','MarkerSize',ms,'MarkerFaceColor','b'); hold on;\r\nxlabel('n')\r\nylabel('|c_n| (mag. of coefficients)')\r\ntitle('Spectral Coefficients: log(c_n) vs. n')\r\nleg=legend('fast','slow');\r\nset(leg,'FontSize',fs);\r\nset(gca,'FontSize',fs);\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n\r\nfunction print_info()\r\n\r\nfprintf('\\n\\nThis is a non-linear pseudo-spectral ODE solver over all R\\n');\r\nfprintf('Author: Nicholas A. Battista \\n');\r\nfprintf('Last update: September 2018\\n\\n');\r\nfprintf('Running the code solves the following non-linear ODE:\\n\\n');\r\n\r\nfprintf(' Laplacian(u) + 1/(1+u)^7 = f(r)\\n\\n');\r\nfprintf('with\\n');\r\nfprintf(' f(r) = 8*r^2/(1+r^2)^3 - 6/(1+r^2)^2 + 1/(1+ (1/(1+r^2)) )^7, [FAST CONV.] \\n\\n');\r\nfprintf(' or \\n\\n');\r\nfprintf(' f(r) = (r^2-6*r+6)*exp(-r) + 1/(1+(r^2*exp(-r)))^7, [SLOW CONV.] \\n\\n');\r\nfprintf('with Dirichelet BCs,\\n');\r\nfprintf(' du/dr(0)=0, u(r->inf) = 0 \\n\\n');\r\nfprintf('and exact solution,\\n');\r\nfprintf(' u(r) = 1/(1+r^2) [FAST CONV.]\\n');\r\nfprintf(' or \\n');\r\nfprintf(' u(r) = r^2 e^(-r) [SLOW CONV.].\\n');\r\nfprintf('\\n Note: This simulation will take roughly 5 minutes to complete the convergence study\\n');\r\nfprintf('\\n -------------------------------------------------------------- \\n');\r\nfprintf('\\n -->> BEGIN THE SIMULATION <<--\\n');\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Taylor_Series_Terms.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Taylor_Series/Taylor_Series_Terms.m", "size": 1496, "source_encoding": "utf_8", "md5": "23bbfc1ba8c172b19f75aa4a24074bc9", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 1/10/18\n%\n% FUNCTION: for a provided error tolerance, computes # of terms necessary\n% in Taylor Series for a particular x value\n%\n% Inputs: x: point to evaluate Taylor Series at\n% err_tol: error tolerance specified \n%\n% Returns: num: # of terms necessary\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction num = Taylor_Series_Terms(x,err_tol)\n\n% Consider actual function as: sin(x)\n\n% Initialization For While Loop\nerror = 1; % could be any value > err_tol\nn = -1; % beginning number of terms in Taylor Series. Note: upon\n % starting the while loop, will go to n=0\n\n \n% will keep looping and adding an additional term to the Taylor Series until our error is less than that of the error tolerance\nwhile error > err_tol\n \n % Add one more Taylor Series term \n n = n + 1;\n\n % Compute Taylor Series\n TS = 0; %initialize Taylor Series\n for i=0:n\n TS = TS + (-1)^i*(x)^(2*i+1) / factorial(2*i+1);\n end\n \n % Compute the error\n error = abs( sin(x) - TS );\n \nend\n\n% If loop ends, last n value must be # of terms until error tolerance was satisfied\nnum = n;\n\n% Prints to the command window inside of MATLAB\nfprintf('It took %d terms to achieve an error tolerance of %d\\n',num,err_tol);"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Taylor_Series_Playtime.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Taylor_Series/Taylor_Series_Playtime.m", "size": 1774, "source_encoding": "utf_8", "md5": "b88081c05b72e55056365cd05e0cdfb1", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 1/10/18\n%\n% FUNCTION: Finds scaling relation for # of terms in Taylor Series as moves\n% away from Maclaurin Centered Point at a=0.\n%\n% Inputs: x: point to evaluate Taylor Series at\n% err_tol: error tolerance specified \n%\n% Returns: num: # of terms necessary\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Taylor_Series_Playtime()\n\n% Set an error tolerance \nerr_tol = 1e-9; \n\n% Decide what x values you want to evaluate \nvals = [1e-2:1e-2:9e-2 1e-1:1e-1:9e-1 1:1:20]; \n\n% Loop over all possible x values and compute # of terms for specified error\nfor i=1:length(vals)\n \n % define the x as index i from the vector of possible values\n x = vals(i); \n \n % use function from earlier to find number of necessary terms in Taylor Series and save it to a new vector\n num_vector(i) = Taylor_Series(x,err_tol);\n \nend\n\n%\n% plots the x-Value vs # of TS terms\n%\nfigure(1)\nplot(vals,num_vector,'*'); hold on;\nxlabel('x value put in');\nylabel('number of terms in Taylor Series');\n\n%\n% plots the x-Value vs. $ of TS terms but with a semi-log scaling on x-axis\n%\nfigure(2)\nsemilogx(vals,num_vector,'r*'); hold on;\nxlabel('x value put in');\nylabel('number of terms in Taylor Series');\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% QUESTIONS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% 1. What is causing the large jumps in number of terms? (Where it seems discontinuous?\n% 2. How do computers actually compute values of sin(100) then?"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Second_Order_BVP_Mixed_3_5Pt_Stencil.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Stencils/Differentiation/Second_Order_BVP_Mixed_3_5Pt_Stencil.m", "size": 3894, "source_encoding": "utf_8", "md5": "54b56c3da6ff31f36ccfd228dbfc6e2d", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 3/4/18\n%\n% FUNCTION: compute the solution of the following BOUNDARY VALUE PROBLEM:\n% u'' = f\n% u(0) = 1; u(1) = 2;\n%\n% NOTE: 1. f is constructed to already know the true solution. \n% 2. u(x) = (1-x)*cos(x)+2xsin(0.5pi*x)\n% 3. f = 2sin(x) + (x-1)cos(x) + 2pi*cos( 0.5pi*x ) - 0.5pi^2*xsin(0.5pi*x)\n%\n% Inputs: N: number of data points to interpolate\n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction maxErr = Second_Order_BVP_Mixed_3_5Pt_Stencil(N)\n\n% Declare boundaries\na=0;\nb=1;\n\n% Boundary Values\nu0 = 1;\nuN = 2;\n\n% Make grid resolution\nh = (b-a)/N;\n\n% Construct grid\nx = 0:h:1;\n\n% Construct second derivative matrix\nD2 = give_Me_Second_Derivative_Matrix(N,h);\n\n% Set up RHS + Boundary Values\nRHS = give_Me_RHS(N,x,u0,uN,h);\n\n% Find approximate solution values\nuSol = inv(D2)*RHS;\n\n% Tack on EXACT boundary values to ends of approximate solution\nuSol = [u0; uSol; uN];\n\n% Plots APPROXIMATE vs. TRUE solution\n%plot_Approx_Vs_True_Soln(x,uSol,a,b)\n\n% give MAX ERROR\ntrueSOL = (1-x).*cos(x)+2*x.*sin(0.5*pi*x);\nmaxErr = max( abs(trueSOL' - uSol) );\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: plots Approximate vs. True Solution to BVP\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Approx_Vs_True_Soln(x,uSol,a,b)\n\n% Plot TRUE solution (on finer grid)\nms = 8; lw = 5;\nxFine = a:0.001:b;\nplot(xFine,(1-xFine).*cos(xFine)+2*xFine.*sin(0.5*pi*xFine),'r.','MarkerSize',ms,'LineWidth',lw); hold on;\n\n% Plot APPROXIMATE solution\nplot(x,uSol,'.','MarkerSize',ms+20,'LineWidth',lw); hold on;\nxlabel('x');\nylabel('u(x)');\nleg = legend('True Soln','Approx. Soln');\nset(gca,'FontSize',18);\nset(leg,'FontSize',16);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: right hand side of BVP: f(x)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction vecF = f(x,N)\n\n% Computes RHS of BVP for ALL x\nfVec = 2*sin(x) + (x-1).*cos(x) + 2*pi*cos( 0.5*pi*x ) - 0.5*pi^2.*x.*sin(0.5*pi*x);\n\n% Only return the interior of the domain\nvecF = fVec(2:N);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Constructs Second Order Derivative Matrix of Size N-1 x N-1\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction rhs = give_Me_RHS(N,x,u0,uN,h)\n\n% Evaluate RHS of the BVP, f(x).\nrhs = f(x,N);\n\n% Tack on the boundary values for left-most and right-most points!\n% NOTE: subtraction since coming from LHS of equation\nrhs(1) = rhs(1) - u0/h^2;\nrhs(2) = rhs(2) - (-1/12)*u0/h^2;\nrhs(end-1) = rhs(end-1) - (-1/12)*uN/h^2;\nrhs(end) = rhs(end) - uN/h^2;\n\n% Make column vector\nrhs = rhs';\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Constructs Second Order Derivative Matrix of Size N-1 x N-1\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction A = give_Me_Second_Derivative_Matrix(N,h)\n\n% Initialize A\nA = zeros(N-1,N-1);\n\n% Set up tridiagonal matrix\nfor i=1:N-1\n \n if i==1\n A(i,i) = -2;\n A(i,i+1) = 1;\n elseif i==N-1\n A(i,i) = -2;\n A(i,i-1) = 1;\n elseif i==2\n A(i,i-1) = 4/3; \n A(i,i) = -5/2;\n A(i,i+1) = 4/3;\n A(i,i+2) = -1/12;\n elseif i==N-2\n A(i,i+1) = 4/3; \n A(i,i) = -5/2;\n A(i,i-1) = 4/3;\n A(i,i-2) = -1/12;\n else\n A(i,i-2) = -1/12;\n A(i,i-1) = 4/3; \n A(i,i) = -5/2;\n A(i,i+1) = 4/3;\n A(i,i+2) = -1/12;\n end\n \n \nend\n\n% Put factor of 1/h^2 in front\nA = 1/h^2*A;\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Second_Order_BVP.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Stencils/Differentiation/Second_Order_BVP.m", "size": 3500, "source_encoding": "utf_8", "md5": "09b14df8c6b1942cd687613c578130a4", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 3/4/18\n%\n% FUNCTION: compute the solution of the following BOUNDARY VALUE PROBLEM:\n% u'' = f\n% u(0) = 1; u(1) = 2;\n%\n% NOTE: 1. f is constructed to already know the true solution. \n% 2. u(x) = (1-x)*cos(x)+2xsin(0.5pi*x)\n% 3. f = 2sin(x) + (x-1)cos(x) + 2pi*cos( 0.5pi*x ) - 0.5pi^2*xsin(0.5pi*x)\n%\n% Inputs: N: number of data points to interpolate\n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction maxErr = Second_Order_BVP(N)\n\n% Declare boundaries\na=0;\nb=1;\n\n% Boundary Values\nu0 = 1;\nuN = 2;\n\n% Make grid resolution\nh = (b-a)/N;\n\n% Construct grid\nx = 0:h:1;\n\n% Construct second derivative matrix\nD2 = give_Me_Second_Derivative_Matrix(N,h);\n\n% Set up RHS + Boundary Values\nRHS = give_Me_RHS(N,x,u0,uN,h);\n\n% Find approximate solution values\nuSol = inv(D2)*RHS;\n\n% Tack on EXACT boundary values to ends of approximate solution\nuSol = [u0; uSol; uN];\n\n% Plots APPROXIMATE vs. TRUE solution\n%plot_Approx_Vs_True_Soln(x,uSol,a,b)\n\n% give MAX ERROR\ntrueSOL = (1-x).*cos(x)+2*x.*sin(0.5*pi*x);\nmaxErr = max( abs(trueSOL' - uSol) );\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: plots Approximate vs. True Solution to BVP\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Approx_Vs_True_Soln(x,uSol,a,b)\n\n% Plot TRUE solution (on finer grid)\nms = 8; lw = 5;\nxFine = a:0.001:b;\nplot(xFine,(1-xFine).*cos(xFine)+2*xFine.*sin(0.5*pi*xFine),'r.','MarkerSize',ms,'LineWidth',lw); hold on;\n\n% Plot APPROXIMATE solution\nplot(x,uSol,'.','MarkerSize',ms+20,'LineWidth',lw); hold on;\nxlabel('x');\nylabel('u(x)');\nleg = legend('True Soln','Approx. Soln');\nset(gca,'FontSize',18);\nset(leg,'FontSize',16);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: right hand side of BVP: f(x)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction vecF = f(x,N)\n\n% Computes RHS of BVP for ALL x\nfVec = 2*sin(x) + (x-1).*cos(x) + 2*pi*cos( 0.5*pi*x ) - 0.5*pi^2.*x.*sin(0.5*pi*x);\n\n% Only return the interior of the domain\nvecF = fVec(2:N);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Constructs Second Order Derivative Matrix of Size N-1 x N-1\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction rhs = give_Me_RHS(N,x,u0,uN,h)\n\n% Evaluate RHS of the BVP, f(x).\nrhs = f(x,N);\n\n% Tack on the boundary values for left-most and right-most points!\n% NOTE: subtraction since coming from LHS of equation\nrhs(1) = rhs(1) - u0/h^2;\nrhs(end) = rhs(end) - uN/h^2;\n\n% Make column vector\nrhs = rhs';\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Constructs Second Order Derivative Matrix of Size N-1 x N-1\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction A = give_Me_Second_Derivative_Matrix(N,h)\n\n% Initialize A\nA = zeros(N-1,N-1);\n\n% Set up tridiagonal matrix\nfor i=1:N-1\n \n if i==1\n A(i,i) = -2;\n A(i,i+1) = 1;\n elseif i==N-1\n A(i,i) = -2;\n A(i,i-1) = 1;\n else\n A(i,i-1) = 1;\n A(i,i) = -2;\n A(i,i+1) = 1;\n end\n \nend\n\n% Put factor of 1/h^2 in front\nA = 1/h^2*A;\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Stencils_5Pt.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Stencils/Differentiation/Stencils_5Pt.m", "size": 1290, "source_encoding": "utf_8", "md5": "656f69aeb44c750c2ba7b1b609a2d578", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 3/1/18\n%\n% FUNCTION: computes stencil weights (coefficients) for a 4-point stencil\n% that approximates a function value at xR (the reference point)\n%\n% Inputs: \n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Stencils_5Pt()\n\n% \n% SET UP 5-PT STENCIL: f(xR) = c0*f(x0) + c1*f(x1) + c2*f(x2) + c3*f(x3) + c4*f(x4)\n% \n% NOTE: using xR = 0.2 (middle point for symmetric stencil)\n%\n\n% Stencil Nodes\nx0=0;\nx1=0.1;\nx2=0.2;\nx3=0.3;\nx4=0.4;\n\n% \"Reference\" Point\nxR=0.10;\n\n% Constuct Vandermonde Transpose Matrix\nA1 = [1 1 1 1 1]; % Row 1\nA2 = [x0-xR x1-xR x2-xR x3-xR x4-xR]; % Row 2\nA3 = A2.^2; % Row 3\nA4 = A2.^3; % Row 4\nA5 = A2.^4; % Row 5\nA = [A1; A2; A3; A4; A5]; % Pieces the matrix together row by row\n\n% Constructs Right Hand Side, eg, [(x-xR)^0 (x-xR)^1 (x-xR)^2 (x-XR)^3]_{x=0}\nb = [1 0 0 0 0]';\n\n% Find coefficients\nc = inv(A)*b\n\n\n% Store coefficints (if you decide to use them for somethng later!)\nc0 = c(1);\nc1 = c(2);\nc2 = c(3);\nc4 = c(4);\nc5 = c(5);"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "compute_Second_Order_BVP_Error.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Stencils/Differentiation/compute_Second_Order_BVP_Error.m", "size": 2043, "source_encoding": "utf_8", "md5": "5f67163ca63cbd4a16035855c3c49a3d", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 3/4/18\n%\n% FUNCTION: compute the error when approximating the solution to the \n% following BOUNDARY VALUE PROBLEM:\n% u'' = f\n% u(0) = 1; u(1) = 2;\n%\n% NOTE: 1. f is constructed to already know the true solution. \n% 2. u(x) = (1-x)*cos(x)+2xsin(0.5pi*x)\n% 3. f = 2sin(x) + (x-1)cos(x) + 2pi*cos( 0.5pi*x ) - 0.5pi^2*xsin(0.5pi*x)\n%\n% Inputs: \n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction compute_Second_Order_BVP_Error()\n\n% How many boundary points to try\nNVec = [5 10:10:90 100:100:900 1000:1000:5000];\n\n% Initialize error vector / time storage vector\nerrVec = zeros(1,length(NVec));\ntime = errVec;\n\n% Find error for each approximate solution\nfor i=1:length(NVec)\n \n % Compute error for approximation using Nvec(i) # of grid points\n tic\n errVec(i) = Second_Order_BVP( NVec(i) );\n \n time(i) = toc;\nend\n\n% Calculate Approximate Order of Convergence!\ncalculate_Order_Of_Convergence(errVec,NVec);\n\n% PLOTS ERROR VS. GRID RESOLUTION (N)\nfigure(1) \nms = 30; lw = 5;\nloglog(NVec,errVec,'.','MarkerSize',ms,'LineWidth',lw);\nxlabel('N (grid resolution)');\nylabel('Max. Abs. Error');\nset(gca,'FontSize',18)\n\n% PLOTS HOW LONG IT TAKES TO RUN FOR EACH N\nfigure(2) \nloglog(NVec,time,'.','MarkerSize',ms,'LineWidth',lw);\nxlabel('N (grid resolution)');\nylabel('Time');\nset(gca,'FontSize',18)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: calculates approximate order of convergence\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction calculate_Order_Of_Convergence(errVec,NVec)\n\n% CALCULATE APPROXIMATE SLOPE:\nslope = ( log(errVec(10)) - log(errVec(20)) ) / ( log(NVec(10)) - log(NVec(20)) );\nfprintf('\\n\\nOrder of Convergence is approximately: %d\\n\\n',slope);\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Second_Order_BVP_5Pt_Stencil.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Stencils/Differentiation/Second_Order_BVP_5Pt_Stencil.m", "size": 4010, "source_encoding": "utf_8", "md5": "48a82fd2427fae0cfe43071856175377", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 3/4/18\n%\n% FUNCTION: compute the solution of the following BOUNDARY VALUE PROBLEM:\n% u'' = f\n% u(0) = 1; u(1) = 2;\n%\n% NOTE: 1. f is constructed to already know the true solution. \n% 2. u(x) = (1-x)*cos(x)+2xsin(0.5pi*x)\n% 3. f = 2sin(x) + (x-1)cos(x) + 2pi*cos( 0.5pi*x ) - 0.5pi^2*xsin(0.5pi*x)\n%\n% Inputs: N: number of data points to interpolate\n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction maxErr = Second_Order_BVP_5Pt_Stencil(N)\n\n% Declare boundaries\na=0;\nb=1;\n\n% Boundary Values\nu0 = 1;\nuN = 2;\n\n% Make grid resolution\nh = (b-a)/N;\n\n% Construct grid\nx = 0:h:1;\n\n% Construct second derivative matrix\nD2 = give_Me_Second_Derivative_Matrix(N,h);\n\n% Set up RHS + Boundary Values\nRHS = give_Me_RHS(N,x,u0,uN,h);\n\n% Find approximate solution values\nuSol = inv(D2)*RHS;\n\n% Tack on EXACT boundary values to ends of approximate solution\nuSol = [u0; uSol; uN];\n\n% Plots APPROXIMATE vs. TRUE solution\n%plot_Approx_Vs_True_Soln(x,uSol,a,b)\n\n% give MAX ERROR\ntrueSOL = (1-x).*cos(x)+2*x.*sin(0.5*pi*x);\nmaxErr = max( abs(trueSOL' - uSol) );\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: plots Approximate vs. True Solution to BVP\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Approx_Vs_True_Soln(x,uSol,a,b)\n\n% Plot TRUE solution (on finer grid)\nms = 8; lw = 5;\nxFine = a:0.001:b;\nplot(xFine,(1-xFine).*cos(xFine)+2*xFine.*sin(0.5*pi*xFine),'r.','MarkerSize',ms,'LineWidth',lw); hold on;\n\n% Plot APPROXIMATE solution\nplot(x,uSol,'.','MarkerSize',ms+20,'LineWidth',lw); hold on;\nxlabel('x');\nylabel('u(x)');\nleg = legend('True Soln','Approx. Soln');\nset(gca,'FontSize',18);\nset(leg,'FontSize',16);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: right hand side of BVP: f(x)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction vecF = f(x,N)\n\n% Computes RHS of BVP for ALL x\nfVec = 2*sin(x) + (x-1).*cos(x) + 2*pi*cos( 0.5*pi*x ) - 0.5*pi^2.*x.*sin(0.5*pi*x);\n\n% Only return the interior of the domain\nvecF = fVec(2:N);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Constructs Second Order Derivative Matrix of Size N-1 x N-1\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction rhs = give_Me_RHS(N,x,u0,uN,h)\n\n% Evaluate RHS of the BVP, f(x).\nrhs = f(x,N);\n\n% Tack on the boundary values for left-most and right-most points!\n% NOTE: subtraction since coming from LHS of equation\nrhs(1) = rhs(1) - (11/12)*u0/h^2;\nrhs(2) = rhs(2) - (-1/12)*u0/h^2;\nrhs(end-1) = rhs(end-1) - (-1/12)*uN/h^2;\nrhs(end) = rhs(end) - (11/12)*uN/h^2;\n\n% Make column vector\nrhs = rhs';\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Constructs Second Order Derivative Matrix of Size N-1 x N-1\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction A = give_Me_Second_Derivative_Matrix(N,h)\n\n% Initialize A\nA = zeros(N-1,N-1);\n\n% Set up tridiagonal matrix\nfor i=1:N-1\n \n if i==1\n A(i,i) = -5/3;\n A(i,i+1) = 1/2;\n A(i,i+2) = 1/3;\n A(i,i+3) = -1/12;\n elseif i==N-1\n A(i,i) = -5/3;\n A(i,i-1) = 1/2;\n A(i,i-2) = 1/3;\n A(i,i-3) = -1/12;\n elseif i==2\n A(i,i-1) = 4/3; \n A(i,i) = -5/2;\n A(i,i+1) = 4/3;\n A(i,i+2) = -1/12;\n elseif i==N-2\n A(i,i+1) = 4/3; \n A(i,i) = -5/2;\n A(i,i-1) = 4/3;\n A(i,i-2) = -1/12;\n else\n A(i,i-2) = -1/12;\n A(i,i-1) = 4/3; \n A(i,i) = -5/2;\n A(i,i+1) = 4/3;\n A(i,i+2) = -1/12;\n end\n \n \nend\n\n% Put factor of 1/h^2 in front\nA = 1/h^2*A;\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "compute_Second_Order_BVP_Error_Compare.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Stencils/Differentiation/compute_Second_Order_BVP_Error_Compare.m", "size": 3127, "source_encoding": "utf_8", "md5": "21af1be0831976b4cd1451230a67c305", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 3/22/18\n%\n% FUNCTION: compute the error when approximating the solution to the \n% following BOUNDARY VALUE PROBLEM:\n% u'' = f\n% u(0) = 1; u(1) = 2;\n%\n% NOTE: 1. f is constructed to already know the true solution. \n% 2. u(x) = (1-x)*cos(x)+2xsin(0.5pi*x)\n% 3. f = 2sin(x) + (x-1)cos(x) + 2pi*cos( 0.5pi*x ) - 0.5pi^2*xsin(0.5pi*x)\n%\n% Inputs: \n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction compute_Second_Order_BVP_Error_Compare()\n\n% How many boundary points to try\nNVec = [7 10:10:90 100:100:900 1000:1000:2000];\n\n% Initialize error vector / time storage vector\nerrVec = zeros(1,length(NVec));\ntime = errVec;\n\n% Find error for each approximate solution\nfor i=1:length(NVec)\n \n % Compute error for approximation using Nvec(i) # of grid points\n tic\n errVec3pt(i) = Second_Order_BVP( NVec(i) );\n time3pt(i) = toc;\n \n tic\n errVec5pt(i) = Second_Order_BVP_5Pt_Stencil( NVec(i) );\n time5pt(i) = toc;\n\n tic\n errVecMix(i) = Second_Order_BVP_Mixed_3_5Pt_Stencil( NVec(i) );\n timeMix(i) = toc;\n \nend\n\n\n% Calculate Approximate Order of Convergence!\ncalculate_Order_Of_Convergence(errVec3pt,NVec,'3 pt');\ncalculate_Order_Of_Convergence(errVec5pt,NVec,'5 pt');\n\n\n% PLOTS ERROR VS. GRID RESOLUTION (N)\nfigure(1) \nms = 48; lw = 4;\nloglog(NVec,errVec3pt,'b.-','MarkerSize',ms,'LineWidth',lw); hold on;\nloglog(NVec,errVec5pt,'r.-','MarkerSize',ms,'LineWidth',lw); hold on;\nxlabel('N (grid resolution)');\nylabel('Max. Abs. Error');\nlegend('3pt Stencil','5pt Stencil');\nset(gca,'FontSize',18)\nset(legend,'FontSize',18);\npause();\n\n% add Mixed pt. stencil info!\ncalculate_Order_Of_Convergence(errVecMix,NVec,'Mixed 3 & 5 pt');\nloglog(NVec,errVecMix,'k.-','MarkerSize',ms,'LineWidth',lw); hold on;\nlegend('3pt Stencil','5pt Stencil','Mixed 3&5 Pt Stencil');\n\n\n% PLOTS HOW LONG IT TAKES TO RUN FOR EACH N\n%figure(2) \n%loglog(NVec,time3pt,'b.-','MarkerSize',ms,'LineWidth',lw); hold on;\n%loglog(NVec,time5pt,'r.-','MarkerSize',ms,'LineWidth',lw); hold on;\n%loglog(NVec,timeMix,'k.-','MarkerSize',ms,'LineWidth',lw); hold on;\n%xlabel('N (grid resolution)');\n%ylabel('Time');\n%legend('3pt Stencil','5pt Stencil','Mixed 3&5pt Stencil);\n%set(legend,'FontSize',18);\n%set(gca,'FontSize',18)\n\nfprintf('\\n\\n');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: calculates approximate order of convergence\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction calculate_Order_Of_Convergence(errVec,NVec,str)\n\n% CALCULATE APPROXIMATE SLOPE:\nif strcmp(str,'3pt')\n slope = ( log(errVec(10)) - log(errVec(20)) ) / ( log(NVec(10)) - log(NVec(20)) );\nelse\n slope = ( log(errVec(5)) - log(errVec(8)) ) / ( log(NVec(5)) - log(NVec(8)) );\nend\n\nstrPrint = ['\\n\\nOrder of Convergence is approximately: %d for ' str ' stencil\\n'];\nfprintf(strPrint,slope);\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Stencils.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Stencils/Differentiation/Stencils.m", "size": 1116, "source_encoding": "utf_8", "md5": "930b0fc84379ae1eb2cfee47074d22c5", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 3/1/18\n%\n% FUNCTION: computes stencil weights (coefficients) for a 4-point stencil\n% that approximates a function value at xR (the reference point)\n%\n% Inputs: \n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Stencils()\n\n% \n% SET UP 4-PT STENCIL: f(xR) = c0*f(x0) + c1*f(x1) + c2*f(x2) + c3*f(x3)\n%\n\n% Stencil Nodes\nx0=0;\nx1=0.1;\nx2=0.2;\nx3=0.3;\n\n% \"Reference\" Point\nxR=0.15;\n\n% Constuct Vandermonde Transpose Matrix\nA1 = [1 1 1 1]; % Row 1\nA2 = [x0-xR x1-xR x2-xR x3-xR]; % Row 2\nA3 = A2.^2; % Row 3\nA4 = A2.^3; % Row 4\nA = [A1; A2; A3; A4]; % Pieces the matrix together row by row\n\n% Constructs Right Hand Side, eg, [(x-xR)^0 (x-xR)^1 (x-xR)^2 (x-XR)^3]_{x=0}\nb = [1 0 0 0]';\n\n% Find coefficients\nc = inv(A)*b\n\n% Store coefficints (if you decide to use them for somethng later!)\nc0 = c(1);\nc1 = c(2);\nc2 = c(3);\nc4 = c(4);"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Newton_Cotes_Romberg.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Stencils/Integration/Newton_Cotes_Romberg.m", "size": 5497, "source_encoding": "utf_8", "md5": "424ac11bd5d63d087d7fc44b5c33e384", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nicholas Battista\n% Institution: The College of NJ (TCNJ)\n% Email: battistn[at]tcnj[.]edu\n% Created: March 25, 2018\n%\n% This function numerically integrates a function, f(x) between integration\n% bounds a and b. This function it integrates is found on line 134.\n%\n% It computes the Newton-Cotes stencil for a particular\n% number of quadrature points, i.e., finds the uniformly spaced quadrature\n% pts over [a,b] as well as the quadrature coefficients.\n%\n% We then compute a composite scheme with just [a,b]->[a,(a+b)/2]U[(a+b)/2,b] \n% and combine the two approximations for Romberg Integration\n%\n% It will then compare the numerically integrated solution to an exact\n% solution if you feed it an exact solution to the integral for testing. It\n% then loops over many different Newton-Cotes stencils (i.e., for different\n% numbers of quadrature pts and then performs a convergence study to see how\n% error decays with higher order stencils.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Newton_Cotes_Romberg()\n\n\n%Integration Bounds\na = 0;\nb = 1;\n\n%Number of Quadrature Pts for Looping\nN_S = 1; \nN_E = 18;\n\n%Number of Quadrature Points\nerr = zeros(1,N_E); err_C = err; err_R = err;\nNvec = N_S:1:N_E;\nfor j=N_S:N_E-1\n \n %Begin counting time for integration\n tic\n \n %Number of Quad Pts for particular stencil\n N = Nvec(j);\n \n %distance between quad-pts\n dx = (b-a)/(N-1);\n\n %quad pts\n x = a:dx:b;\n \n %gives vandermond-transpose matrix\n mat = Coeff_Matrix(N,x);\n\n %gives us RHS to find coeffs\n vec = Monomial_Vector(N,b);\n\n %gives coefficients\n c = mat\\vec;\n\n %actually does the \"integration\" on [0,1]\n int = Integrate(N,x,c);\n\n %computes composite integral [0,1] -> [0,0.5]U[0.5,1]\n x = a:(b-a)/N:b;\n int_composite = Integrate_Composite(N,x,c,2);\n \n %forms Romberg integration approximation\n int_Rom = int + (int_composite - int)/( 1 - (1/2)^N );\n \n %computers error between exact and numerical approximation\n err(N) = abs( (-cos(1)+1) - int );\n err_C(N) = abs( (-cos(1)+1) - int_composite );\n err_R(N) = abs( (-cos(1)+1) - int_Rom );\n \n %stores time for computation\n time(j) = toc;\n \nend\n\n% figure attributes\nms = 15; lw = 4; fs = 20;\n\nfigure(1)\n%subplot(1,4,1:2);\nsemilogy(Nvec,err(1:end),'o-','MarkerSize',ms,'LineWidth',lw); hold on;\nxlabel('Number of Quadrature Pts.');\nylabel('Log(Error)');\ntitle('Convergence Study');\nleg = legend('N-pt Stencil');\nset(leg,'FontSize',fs-1);\nset(gca,'FontSize',fs);\n%\npause();\n%\nsemilogy(Nvec(2),err_R(2),'<-','MarkerSize',ms,'LineWidth',lw); hold on;\nxlabel('Number of Quadrature Pts.');\nylabel('Log(Error)');\nleg = legend('N-pt Stencil','N-pt Stencil w/ Romberg');\ntitle('Convergence Study');\nset(gca,'FontSize',fs);\nset(leg,'FontSize',fs-1);\n%\npause();\n%\nsemilogy(Nvec,err_R(1:end),'<-','MarkerSize',ms,'LineWidth',lw); hold on;\nxlabel('Number of Quadrature Pts.');\nylabel('Log(Error)');\nleg = legend('N-pt Stencil','N-pt Stencil w/ Romberg');\ntitle('Convergence Study');\nset(gca,'FontSize',fs);\nset(leg,'FontSize',fs-1);\n\n%figure(2)\n%subplot(1,4,3:4);\n%semilogy(Nvec,time,'ro-','MarkerSize',ms,'LineWidth',lw); hold on;\n%xlabel('Number of Quadrature Pts.');\n%ylabel('Log(Time for Each Integration)');\n%title('Computational Time Study');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Actually does the Numerical Approximation to the Integral\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction int = Integrate(N,x,c)\n\nint = 0;\nfor i=1:N\n int = int + c(i)*f(x(i));\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Actually does the Numerical Approximation to the Integral using Composite\n% Integration with nPartitions\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction int_C = Integrate_Composite(N,x,c,nPartitions)\n\nh = ( x(end) - x(1) )/nPartitions; % Finds length of each sub-interval\n\nint_j = zeros(1,nPartitions); % Initialize storage fr each sub-integral value\n\nxPartitionPts = x(1):h:x(end); % Finds partition points in integration domain\n\nfor j=1:(nPartitions)\n \n % Make Quadrature Points on Subinterval\n if N==1\n xSub = xPartitionPts(j);\n else\n xSub = xPartitionPts(j):h/(N-1):xPartitionPts(j+1);\n end\n \n % Compute sub-interval integral\n for i=1:N\n int_j(j) = int_j(j) + h*c(i)*f( xSub(i) );\n end\n \nend\n\nint_C = sum( int_j ); % Add all sub-interval integral values together to get total composite value\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Gives us RHS to find coefficients for integration stencil\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction vec = Monomial_Vector(N,b)\n\n%This assumes an integration bounds are [0,b]\nvec = zeros(N,1);\n\nfor i=1:N\n vec(i,1) = b^(i)/i; \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Gives us the transpose of vandermonde matrix for finding integration\n% stencil coefficients\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction mat = Coeff_Matrix(N,x)\n\nif N==1\n mat = 1;\nelse\n\n mat = zeros(N,N);\n\n for i=1:N\n mat(i,:) = x.^(i-1); \n end\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function to be integrated, f(x)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = f(x) \n\nval = sin(x);"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Newton_Cotes.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Stencils/Integration/Newton_Cotes.m", "size": 3335, "source_encoding": "utf_8", "md5": "46c00af417f2974f80e6471191cd6520", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%Author: Nicholas Battista\n%Institution: The College of NJ (TCNJ)\n%Email: battistn[at]tcnj[.]edu\n%Created: March 25, 2018\n%\n%This function numerically integrates a function, f(x) between integration\n%bounds a and b. This function it integrates is found on line 134.\n%\n%It computes the Newton-Cotes stencil for a particular\n%number of quadrature points, i.e., finds the uniformly spaced quadrature\n%pts over [a,b] as well as the quadrature coefficients.\n%\n%It will then compare the numerically integrated solution to an exact\n%solution if you feed it an exact solution to the integral for testing. It\n%then loops over many different Newton-Cotes stencils (i.e., for different\n%numbers of quadrature pts and then performs a convergence study to see how\n%error decays with higher order stencils.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Newton_Cotes()\n\n\n%Integration Bounds\na = 0;\nb = 1;\n\n%Number of Quadrature Pts for Looping\nN_S = 1; \nN_E = 18;\n\n%Number of Quad-pts\nerr = zeros(1,N_E);\nNvec = N_S:1:N_E;\nfor j=N_S:N_E\n \n %Begin counting time for integration\n tic\n \n %Number of quadrature pts for particular stencil\n N = Nvec(j);\n \n %distance between quad-pts\n dx = (b-a)/(N-1);\n\n %quad pts\n x = a:dx:b;\n\n %gives vandermond-transpose matrix\n mat = Coeff_Matrix(N,x);\n\n %gives us RHS to find coeffs\n vec = Monomial_Vector(N,b);\n\n %gives coefficients\n c = mat\\vec;\n\n %actually does the \"integration\"\n int = Integrate(N,x,c);\n \n %computers error between exact and numerical approximation\n err(N) = abs( (-cos(1)+1) - int );\n\n %stores time for computation\n time(j) = toc;\n \nend\n\n% figure attributes\nms = 15; lw = 4; fs = 20;\n\nfigure(1)\n%subplot(1,4,1:2);\nsemilogy(Nvec,err,'o-','MarkerSize',ms,'LineWidth',lw); hold on;\nxlabel('Number of Quadrature Pts.');\nylabel('Log(Error)');\ntitle('Convergence Study');\nset(gca,'FontSize',fs);\n\n\n%figure(2)\n%subplot(1,4,3:4);\n%semilogy(Nvec,time,'ro-','MarkerSize',ms,'LineWidth',lw); hold on;\n%xlabel('Number of Quadrature Pts.');\n%ylabel('Log(Time for Each Integration)');\n%title('Computational Time Study');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Actually does the Numerical Approximation to the Integral\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction int = Integrate(N,x,c)\n\nint = 0;\nfor i=1:N\n int = int + c(i)*f(x(i));\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Gives us RHS to find coefficients for integration stencil\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction vec = Monomial_Vector(N,b)\n\n%This assumes an integration bounds are [0,b]\nvec = zeros(N,1);\n\nfor i=1:N\n vec(i,1) = b^(i)/i; \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Gives us the transpose of vandermonde matrix for finding integration\n% stencil coefficients\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction mat = Coeff_Matrix(N,x)\n\nmat = zeros(N,N);\n\nfor i=1:N\n mat(i,:) = x.^(i-1); \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function to be integrated, f(x)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = f(x) \n\nval = sin(x);"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Standard_Interp.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Interpolation/Standard_Interp.m", "size": 1815, "source_encoding": "utf_8", "md5": "0a5cae430d93cc3953f6f8a45aa1aa36", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 2/5/18\n%\n% FUNCTION: computes interpolation polynomial using the standard monomial\n% basis\n%\n% Inputs: N: number of data points to interpolate\n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Standard_Interp(N)\n\n% initialization\ndataX = (0:1/(N-1):1)'; % uniform grid points\ndataX = sort(dataX); % orders vector of x-Values in ascending order\ndataY = f(dataX); % gives corresponding y-data from given function f(x)\n\n% form matrix for finding coefficients (transpose of Vandermonde Matrix)\nfor i=1:N\n for j=1:N\n A(j,i) = dataX(j)^(i-1);\n end\nend\n\n% finds coefficients by inverting the matrix\ncoeffs = inv(A)*dataY;\n\n% plots TRUE function\nlw = 5;\nx=0:0.0125:1;\nplot( x, f(x), 'b-','LineWidth',lw); hold on; \n\npause();\n\n% plots original data points\nms = 10;\nplot(dataX,dataY,'k.','MarkerSize',ms+40); hold on;\n\npause();\n\n% plot INTERPOLATED POLYNOMIAL\nx=0:0.0025:1;\nfor i=1:length(x)\n plot(x(i), p(coeffs,x(i),N),'r.','MarkerSize',ms); hold on;\nend\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: function gives function values for input vector, x\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = p(c,x,N)\n\nxPowers = zeros(1,N);\nfor i=1:N\n xPowers(1,i) = x^(i-1);\nend\n\nval = c'*xPowers';\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: function gives function values for input vector, x\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = f(x)\n\nval = (x.^2+2).*exp(2*x).*cos(5*x).^2;"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "test_QR_Algorithm.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Numerical_Linear_Algebra/test_QR_Algorithm.m", "size": 3246, "source_encoding": "utf_8", "md5": "ea4c757edaa0e519c6356590332f4b73", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 5/1/18\n%\n% FUNCTION: computes numerical eigenvalues using QR Algorithm\n%\n% Inputs: \n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction test_QR_Algorithm()\n\nclf; % Clear any existing plots\n\nN = 15;\n\n% CREATE RANDOM MATRIX\nA = rand(N,N);\n[Q,~] = qr(A); % <-- just to get an orthogonal matrix\nv = 10*rand(N,1);\nD = diag(v);\nA = Q*D*Q';\n\n% SYMMETRIC MATRIX EXAMPLE\n%A = randi(2,N,N) - 1;\n%A = A - tril(A,-1) + triu(A,1)';\n\n% USE MATLAB TO COMPUTE EIGENVALUES\neigTrue = eig(A);\neigTrue = sort(eigTrue)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% <<- perform QR Algorithm ->> %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% initialize\nnIter = 1000;\neigApprox = zeros(N,nIter);\n\n% Loop to Perform QR Algorithm\nfor j=1:nIter\n [Q,R] = qr(A);\n A = R*Q;\n eigApprox(:,j) = diag(A);\nend\n\n% Last Approximation:\neigApprox_Last = eigApprox(:,nIter);\n[~,idx] = sort( eigApprox_Last );\neigApprox_Last = eigApprox_Last(idx)\n\n% Error Convergence\n[err_L2,err_Inf] = give_Me_Error_For_Every_Iteration(nIter,eigApprox,eigTrue);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% <<- PLOTTING THE ERROR ->> %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Convergence Plot: L2 Error %%%%\nlw = 4; ms = 32; fs = 22;\n%\nsubplot(1,2,1)\nplot(1:1:nIter, err_L2,'.-','MarkerSize',ms,'LineWidth',lw); hold on;\nxlabel('Iteration Number');\nylabel('L2 Error');\nset(gca,'FontSize',fs);\n%\nsubplot(1,2,2)\nloglog(1:1:nIter, err_L2,'.-','MarkerSize',ms,'LineWidth',lw); hold on;\nxlabel('Iteration Number');\nylabel('L2 Error');\nset(gca,'FontSize',fs);\n\n%\n% Convergence Plot: L-INFINITY Error %%%%\nlw = 4; ms = 32; fs = 22;\n%\nsubplot(1,2,1)\nplot(1:1:nIter, err_Inf,'.-','MarkerSize',ms,'LineWidth',lw); hold on;\nxlabel('Iteration Number');\nylabel('L2 Error');\nset(gca,'FontSize',fs);\nleg = legend('L2-Error','L-Inf Error'); \nset(leg,'FontSize',fs);\n%\nsubplot(1,2,2)\nloglog(1:1:nIter, err_Inf,'.-','MarkerSize',ms,'LineWidth',lw); hold on;\nxlabel('Iteration Number');\nylabel('L2 Error');\nset(gca,'FontSize',fs);\nleg = legend('L2-Error','L-Inf Error'); \nset(leg,'FontSize',fs);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: compute the L2 Norm of Error for every iteration\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [err_L2,err_Inf] = give_Me_Error_For_Every_Iteration(nIter,eigApprox,eigTrue)\n\n% Initialize L2_Error storage vector\nerr_L2 = zeros( nIter , 1 );\nerr_Inf = err_L2;\n\n% ReOrder eigApprox\n\nfor j=1:nIter\n \n % Get Approximation Eigenvalues at jth step\n eigApprox_j = eigApprox(:,j);\n \n % Sort Eigenvalues into ascending order (so to compare with MATLAB)\n [~,idx] = sort( eigApprox_j );\n eigApprox_j = eigApprox_j(idx);\n %eigApprox_j = eigApprox_j(end:-1:1);\n \n % Get error between EXACT and APPROX at each step, j\n errVec = eigTrue - eigApprox_j; \n \n % Compute L2-Error between EXACT AND APPROX at each step, j\n err_L2(j) = sqrt( errVec'*errVec );\n \n % Compute L-Inf Error between EXACT ANA APPROX at each step, j\n err_Inf(j) = max( abs( errVec ) );\n \nend\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Fixed_Point_Iteration.m", "ext": ".m", "path": "Ark-master/MAT331_Numerical_Analysis/Root-Finding/Fixed_Point_Iteration.m", "size": 1574, "source_encoding": "utf_8", "md5": "602b4376febeab2881c2b51d42fb740e", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Author: Nick Battista\n% Instutition: TCNJ\n% Course: MAT 331 (Numerical Analysis)\n% Date: 1/20/18\n%\n% FUNCTION: computes the root of a function using Fixed-Pt Iteration to\n% within a specified error tolerance\n%\n% Inputs: p0: initial guess\n% err_tol: error tolerance specified \n% NMAX: max. number of iterations allowed\n%\n% Returns: \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Fixed_Point_Iteration(p0,errTol,NMAX)\n\n% initialization\nn = 0; % counter\nerr = 1; % initial error to get started\n\n\nwhile ( (n< NMAX) && (err > errTol) )\n \n p = g(p0); % find next guess at root\n err = abs( p - p0 ); % computes error\n p0 = p; % redefine current guess as previous for next loop iteration\n n = n+1; % add one to counter\n\nend\n\nif n Playing with %d bingo cards\\n',Nboards);\n else\n fprintf('-> Playing with %d bingo cards\\n',Nboards);\n end\n \n for j=1:Ngames\n\n B = please_Make_Boards(Nboards); %Makes boards for game!\n balls = randperm(75); %Draw balls randomly for entire game!\n \n \n %Play Regular Bingo -> Return boards and counter for inner/outer square/cover-all\n [B ct_reg num_winners_reg] = play_Regular_Bingo(B,balls);\n \n [B ct_inner num_winners_in] = play_Inner_Square_Bingo(B,balls,ct_reg);\n \n [B ct_outer num_winners_out] = play_Outer_Square_Bingo(B,balls,ct_inner);\n \n [B ct_cover num_winners_cover] = play_Cover_All_Bingo(B,balls,ct_outer);\n \n \n %Row: different games for specific # of boards\n %Column: Different # of boards\n %k: Different amount of games played in a series of simulations for convergence\n count_reg(j,i,k) = ct_reg;\n numWinnersReg(j,i,k) = num_winners_reg;\n\n count_inner(j,i,k) = ct_inner;\n numWinnersInner(j,i,k) = num_winners_in;\n \n count_outer(j,i,k) = ct_outer;\n numWinnersOut(j,i,k) = num_winners_out;\n \n count_cover(j,i,k) = ct_cover;\n numWinnersCover(j,i,k) = num_winners_cover;\n\n end\n end\nend\n\n\n% AvgMat: row - different # of Monte carlo sims. per game / column: different # of bingo cards\nAvgMatReg = please_Compute_Averages(count_reg,NgamesVec);\nAvgMatIn = please_Compute_Averages(count_inner,NgamesVec);\nAvgMatOut = please_Compute_Averages(count_outer,NgamesVec);\nAvgMatCover = please_Compute_Averages(count_cover,NgamesVec);\n\n% Plots data of interest\nplot_Games_Required_To_Win(NgamesVec,BoardsVec,AvgMatReg,AvgMatIn,AvgMatOut,AvgMatCover);\nplot_Convergence_Study(BoardsVec,AvgMatReg,AvgMatIn,AvgMatOut,AvgMatCover);\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: constructs Nboards of bingo randomly and stores them in a 3D\n% Matrix.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction B = please_Make_Boards(Nboards)\n\n%Nboards: Number of boards\n\nB = zeros(5,5,Nboards);\n\n%B: 1-15\n%I: 16-30\n%N: 31-45\n%G: 46-60\n%O: 61-75\n\nfor i=1:Nboards\n\n %Creates random vector of numbers in appropriate interval\n B1 = randperm(15);\n I1 = randperm(15)+15;\n N1 = randperm(15)+30;\n G1 = randperm(15)+45;\n O1 = randperm(15)+60;\n\n %Take first 5 random values in appropriate intervals for board columns\n Bvec = B1(1:5)';\n Ivec = I1(1:5)';\n Nvec = N1(1:5)'; \n Gvec = G1(1:5)';\n Ovec = O1(1:5)';\n\n %Set FREE SPACE (to zero)\n Nvec(3) = 0;\n\n %Sets the Bingo Board!\n B(:,1,i) = Bvec;\n B(:,2,i) = Ivec;\n B(:,3,i) = Nvec;\n B(:,4,i) = Gvec;\n B(:,5,i) = Ovec;\n\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Plays \"regular\" bingo\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [B ct num_winners] = play_Regular_Bingo(B,balls)\n\nwin_flag = 0; %initialize winning flag to end game\nct = 0; %counter for number of balls drawn\n\nwhile ( win_flag == 0 )\n\n ct = ct+1; %updates counter when picking another ball\n ball = balls(ct); %draws a ball from already randomly drawn balls\n B = please_Dab_Bingo_Boards(B,ball); %dabs bingo board (sets elements to ZERO)\n \n %Checks for Regular Bingo\n [win_flag,num_winners] = please_Check_Regular_Bingo_For_Win(B); \n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCION: \"dabs\" out bingo board when certain ball is called. \n% Note: Board starts with all 1's, Change 1 -> 0 when number is called.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction B = please_Dab_Bingo_Boards(B,ball)\n\nindices = find(B==ball);\nB(indices) = 0;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Checks to see if any boards have won regular bingo.\n% Regular Bingo: Straight Lines (horizontal, vertical, diagonal), inner\n% and/or outer four corners.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [win_flag,num_winners] = please_Check_Regular_Bingo_For_Win(B)\n\nNboards = length(B(1,1,:)); \nwin_flag = 0;\nnum_winners = 0;\nwin_flag2 = 0;\n\nfor i=1:Nboards\n \n %Check ROWS\n if max(B(1,:,i))==0\n win_flag2 = 1;\n elseif max(B(2,:,i))==0\n win_flag2 = 1;\n elseif max(B(3,:,i))==0\n win_flag2 = 1;\n elseif max(B(4,:,i))==0\n win_flag2 = 1;\n elseif max(B(5,:,i))==0\n win_flag2 = 1;\n end\n \n %Check COLUMNS if board hasn't won yet \n if win_flag2 == 0\n if max(B(:,1,i))==0\n win_flag2 = 1;\n elseif max(B(:,2,i))==0\n win_flag2 = 1;\n elseif max(B(:,3,i))==0\n win_flag2 = 1;\n elseif max(B(:,4,i))==0\n win_flag2 = 1;\n elseif max(B(:,5,i))==0\n win_flag2 = 1; \n end\n end\n \n %Check DIAGONALS and 4-CORNERS (both outer and inner)!\n if win_flag2 ==0\n \n %check backslash \n m11 = B(1,1,i);\n m22 = B(2,2,i);\n m44 = B(4,4,i);\n m55 = B(5,5,i);\n t1 = [m11 m22 m44 m55];\n if max(t1) == 0\n win_flag2 = 1; \n end\n \n %check forward slash\n m51 = B(5,1,i);\n m42 = B(4,2,i);\n m24 = B(2,4,i);\n m15 = B(1,5,i);\n t1 = [m15 m24 m42 m51];\n if max(t1) == 0\n win_flag2 = 1; \n end\n \n %check OUTER 4-corners\n t1 = [m11 m15 m51 m55];\n if max(t1) == 0\n win_flag2 = 1;\n end\n \n %check INNER 4-corners\n t1 = [m22 m42 m24 m44];\n if max(t1) == 0\n win_flag2 = 1;\n end\n \n end\n \n if win_flag2 == 1\n num_winners = num_winners+1;\n end\n \n win_flag2 = 0;\n \nend %ENDS LOOP OVER BOARDS\n \nif num_winners > 0 \n win_flag = 1;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Plays inner square bingo\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [B ct num_winners] = play_Inner_Square_Bingo(B,balls,ct)\n\nwin_flag = 0; %initialize winning flag to end game\n% ct: counter for number of balls drawn in regular bingo so far\n\nwhile ( win_flag == 0 )\n\n ct = ct+1; %updates counter when picking another ball\n ball = balls(ct); %draws a ball from already randomly drawn balls\n B = please_Dab_Bingo_Boards(B,ball); %dabs bingo board (sets elements to ZERO)\n \n %Checks for Regular Bingo\n [win_flag,num_winners] = please_Check_Inner_Square_For_Win(B); \n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Checks to see if any board has inner square completed.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [win_flag,num_winners] = please_Check_Inner_Square_For_Win(B)\n\nNboards = length(B(1,1,:)); \nwin_flag = 0;\nnum_winners = 0;\nwin_flag2 = 0;\n\nfor i=1:Nboards\n\n %check INNER SQUARE \n m22 = B(2,2,i);\n m23 = B(2,3,i);\n m24 = B(2,4,i);\n m32 = B(3,2,i);\n m34 = B(3,4,i);\n m42 = B(4,2,i);\n m43 = B(4,3,i);\n m44 = B(4,4,i);\n t1 = [m22 m23 m24 m32 m34 m42 m43 m44];\n if max(t1) == 0\n win_flag2 = 1; \n end\n \n if win_flag2 == 1\n num_winners = num_winners+1;\n end\n \n win_flag2 = 0;\n \nend %ENDS LOOP OVER BOARDS\n\nif num_winners > 0 \n win_flag = 1;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Plays outer square bingo\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [B ct num_winners] = play_Outer_Square_Bingo(B,balls,ct)\n\nfirst = 1;\nwin_flag = 0; %initialize winning flag to end game\n% ct: counter for number of balls drawn in regular bingo + inner square so far\n\nwhile ( win_flag == 0 )\n \n if (first==1)\n \n %Checks for Outer Square Bingo BEFORE drawing another ball\n [win_flag,num_winners] = please_Check_Outer_Square_For_Win(B); \n first = 0;\n \n else\n \n ct = ct+1; %updates counter when picking another ball\n ball = balls(ct); %draws a ball from already randomly drawn balls\n B = please_Dab_Bingo_Boards(B,ball); %dabs bingo board (sets elements to ZERO)\n\n %Checks for Outer Square Bingo \n [win_flag,num_winners] = please_Check_Outer_Square_For_Win(B); \n end\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Checks if any boards have completed outer square bingo\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [win_flag,num_winners] = please_Check_Outer_Square_For_Win(B)\n\nNboards = length(B(1,1,:)); \nwin_flag = 0;\nnum_winners = 0;\nwin_flag2 = 0;\n\nfor i=1:Nboards\n\n %CHECK OUTER SQUARE \n m11 = B(1,1,i);\n m12 = B(1,2,i);\n m13 = B(1,3,i);\n m14 = B(1,4,i);\n m15 = B(1,5,i);\n m51 = B(5,1,i);\n m52 = B(5,2,i);\n m53 = B(5,3,i);\n m54 = B(5,4,i);\n m55 = B(5,5,i);\n m21 = B(2,1,i);\n m31 = B(3,1,i);\n m41 = B(4,1,i);\n m25 = B(2,5,i);\n m35 = B(3,5,i);\n m45 = B(4,5,i);\n t1 = [m11 m12 m13 m14 m15 m51 m52 m53 m54 m55 m21 m31 m41 m25 m35 m45];\n if max(t1) == 0\n win_flag2 = 1; \n end\n \n if win_flag2 == 1\n num_winners = num_winners+1;\n end\n \n win_flag2 = 0;\n \nend %ENDS LOOP OVER BOARDS\n\nif num_winners > 0 \n win_flag = 1;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Plays cover-all bingo!\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [B ct num_winners] = play_Cover_All_Bingo(B,balls,ct)\n\nfirst=1;\nwin_flag = 0; %initialize winning flag to end game\n% ct: counter for number of balls drawn in regular bingo + inner square so far\n\nwhile ( win_flag == 0 )\n \n if (first == 1)\n \n %Checks for Cover All Bingo BEFORE drawing another ball\n [win_flag,num_winners] = please_Check_Cover_All_For_Win(B); \n first = 0; \n \n else\n \n ct = ct+1; %updates counter when picking another ball\n ball = balls(ct); %draws a ball from already randomly drawn balls\n B = please_Dab_Bingo_Boards(B,ball); %dabs bingo board (sets elements to ZERO)\n \n %Checks for Cover All Bingo \n [win_flag,num_winners] = please_Check_Cover_All_For_Win(B); \n \n end\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Checks to see if any board has completed cover all.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [win_flag,num_winners] = please_Check_Cover_All_For_Win(B)\n\nNboards = length(B(1,1,:)); \nwin_flag = 0;\nnum_winners = 0;\nwin_flag2 = 0;\n\nfor i=1:Nboards\n\n %CHECK COVER ALL \n if max(max(B(:,:,i))) == 0\n win_flag2 = 1; \n end\n \n if win_flag2 == 1\n num_winners = num_winners+1;\n end\n \n win_flag2 = 0;\n \nend %ENDS LOOP OVER BOARDS\n\nif num_winners > 0 \n win_flag = 1;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Computes averages for each set of monte carlo simulations\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction AvgMat = please_Compute_Averages(count,NgamesVec)\n\n% count(j,i,k): \n% row,j: game played for specific number of boards\n% column,i: different number of board\n% index, k: different number of simulations for convergence\n\nAvgMat = zeros(length(NgamesVec),length(count(1,:,1)));\n\nfor k=1:length(NgamesVec)\n \n vec = sum(count(:,:,k)) / NgamesVec(k);\n AvgMat(k,:) = vec;\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Plots the number of games required to win all 4 bingo games\n% (regular bingo, inenr square, outer square, cover all) in the most\n% resolved Monte Carlo case (i.e., highest number of games played for each\n% number of bingo cards)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Games_Required_To_Win(NgamesVec,BoardsVec,AvgMatReg,AvgMatIn,AvgMatOut,AvgMatCover)\n\n%\n% Plots all 4 different bingo games together \n%\nfigure(1);\nsims = length(AvgMatCover(:,1));\nplot(BoardsVec,AvgMatReg(sims,:),'r-'); hold on;\nplot(BoardsVec,AvgMatIn(sims,:),'b-'); hold on;\nplot(BoardsVec,AvgMatOut(sims,:),'k-'); hold on;\nplot(BoardsVec,AvgMatCover(sims,:),'g-'); hold on;\nplot(BoardsVec,AvgMatReg(sims,:),'r*'); hold on;\nplot(BoardsVec,AvgMatIn(sims,:),'b*'); hold on;\nplot(BoardsVec,AvgMatOut(sims,:),'k*'); hold on;\nplot(BoardsVec,AvgMatCover(sims,:),'g*'); hold on;\nstrTitle = sprintf('Number of Draws Until You Win! (Averaging %d games per # of cards)', NgamesVec(end));\ntitle(strTitle);\nxlabel('Number of Bingo Cards');\nylabel('Average # of Draws to Win!');\nlegend('Regular Bingo','Inner Square','Outer Square','Cover All');\n\n%\n% Plots all 4 different bingo games separately\n%\nfigure(2)\n%\nstrLegend = sprintf('%d games averaged',NgamesVec(end));\n%\nsubplot(2,2,1);\nplot(BoardsVec,AvgMatReg(sims,:),'b-'); hold on;\nplot(BoardsVec,AvgMatReg(sims,:),'r*'); hold on;\ntitle('Regular Bingo');\nxlabel('Number of Bingo Cards');\nylabel('Draws to Win');\nlegend(strLegend);\n%\nsubplot(2,2,2);\nplot(BoardsVec,AvgMatIn(sims,:),'b-'); hold on;\nplot(BoardsVec,AvgMatIn(sims,:),'r*'); hold on;\ntitle('Inner Square Bingo');\nxlabel('Number of Bingo Cards');\nylabel('Draws to Win');\nlegend(strLegend);\n%\nsubplot(2,2,3);\nplot(BoardsVec,AvgMatOut(sims,:),'b-'); hold on;\nplot(BoardsVec,AvgMatOut(sims,:),'r*'); hold on;\ntitle('Outer Square Bingo');\nxlabel('Number of Bingo Cards');\nylabel('Draws to Win');\nlegend(strLegend);\n%\nsubplot(2,2,4);\nplot(BoardsVec,AvgMatCover(sims,:),'b-'); hold on;\nplot(BoardsVec,AvgMatCover(sims,:),'r*'); hold on;\ntitle('Cover All Bingo');\nxlabel('Number of Bingo Cards');\nylabel('Draws to Win');\nlegend(strLegend);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Plots the CONVERGENCE STUDY for how many games are required to\n% get more accurate data for number of draws necessary to win at each type\n% of bingo game.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Convergence_Study(BoardsVec,AvgMatReg,AvgMatIn,AvgMatOut,AvgMatCover)\n\n%\n% Plots CONVERGENCE STUDY for all 4 different bingo games separately \n%\nfigure(3);\nsubplot(2,2,1);\nplot(BoardsVec,AvgMatReg(1,:),'m-'); hold on;\nplot(BoardsVec,AvgMatReg(2,:),'b-'); hold on;\nplot(BoardsVec,AvgMatReg(3,:),'k-'); hold on;\nplot(BoardsVec,AvgMatReg(4,:),'g-'); hold on;\nplot(BoardsVec,AvgMatReg(5,:),'r-','LineWidth',2); hold on;\nplot(BoardsVec,AvgMatReg(1,:),'m-'); hold on;\nplot(BoardsVec,AvgMatReg(2,:),'b-'); hold on;\nplot(BoardsVec,AvgMatReg(3,:),'k-'); hold on;\nplot(BoardsVec,AvgMatReg(4,:),'g-'); hold on;\nplot(BoardsVec,AvgMatReg(1,:),'m*'); hold on;\nplot(BoardsVec,AvgMatReg(2,:),'b*'); hold on;\nplot(BoardsVec,AvgMatReg(3,:),'k*'); hold on;\nplot(BoardsVec,AvgMatReg(4,:),'g*'); hold on;\nplot(BoardsVec,AvgMatReg(5,:),'r*'); hold on;\ntitle('Convergence Study: Reg. Bingo');\nxlabel('Number of Bingo Cards');\nylabel('Average # of Draws to Win!');\nlegend('5','10','25','50','100');\n%\nsubplot(2,2,2);\nplot(BoardsVec,AvgMatIn(1,:),'m-'); hold on;\nplot(BoardsVec,AvgMatIn(2,:),'b-'); hold on;\nplot(BoardsVec,AvgMatIn(3,:),'k-'); hold on;\nplot(BoardsVec,AvgMatIn(4,:),'g-'); hold on;\nplot(BoardsVec,AvgMatIn(5,:),'r-','LineWidth',2); hold on;\nplot(BoardsVec,AvgMatIn(1,:),'m-'); hold on;\nplot(BoardsVec,AvgMatIn(2,:),'b-'); hold on;\nplot(BoardsVec,AvgMatIn(3,:),'k-'); hold on;\nplot(BoardsVec,AvgMatIn(4,:),'g-'); hold on;\nplot(BoardsVec,AvgMatIn(1,:),'m*'); hold on;\nplot(BoardsVec,AvgMatIn(2,:),'b*'); hold on;\nplot(BoardsVec,AvgMatIn(3,:),'k*'); hold on;\nplot(BoardsVec,AvgMatIn(4,:),'g*'); hold on;\nplot(BoardsVec,AvgMatIn(5,:),'r*'); hold on;\ntitle('Convergence Study: Inner Square');\nxlabel('Number of Bingo Cards');\nylabel('Average # of Draws to Win!');\nlegend('5','10','25','50','100');\n%\nsubplot(2,2,3);\nplot(BoardsVec,AvgMatOut(1,:),'m-'); hold on;\nplot(BoardsVec,AvgMatOut(2,:),'b-'); hold on;\nplot(BoardsVec,AvgMatOut(3,:),'k-'); hold on;\nplot(BoardsVec,AvgMatOut(4,:),'g-'); hold on;\nplot(BoardsVec,AvgMatOut(5,:),'r-','LineWidth',2); hold on;\nplot(BoardsVec,AvgMatOut(1,:),'m-'); hold on;\nplot(BoardsVec,AvgMatOut(2,:),'b-'); hold on;\nplot(BoardsVec,AvgMatOut(3,:),'k-'); hold on;\nplot(BoardsVec,AvgMatOut(4,:),'g-'); hold on;\nplot(BoardsVec,AvgMatOut(1,:),'m*'); hold on;\nplot(BoardsVec,AvgMatOut(2,:),'b*'); hold on;\nplot(BoardsVec,AvgMatOut(3,:),'k*'); hold on;\nplot(BoardsVec,AvgMatOut(4,:),'g*'); hold on;\nplot(BoardsVec,AvgMatOut(5,:),'r*'); hold on;\ntitle('Convergence Study: Outer Square');\nxlabel('Number of Bingo Cards');\nylabel('Average # of Draws to Win!');\nlegend('5','10','25','50','100');\n%\nsubplot(2,2,4);\nplot(BoardsVec,AvgMatCover(1,:),'m-'); hold on;\nplot(BoardsVec,AvgMatCover(2,:),'b-'); hold on;\nplot(BoardsVec,AvgMatCover(3,:),'k-'); hold on;\nplot(BoardsVec,AvgMatCover(4,:),'g-'); hold on;\nplot(BoardsVec,AvgMatCover(5,:),'r-','LineWidth',2); hold on;\nplot(BoardsVec,AvgMatCover(1,:),'m-'); hold on;\nplot(BoardsVec,AvgMatCover(2,:),'b-'); hold on;\nplot(BoardsVec,AvgMatCover(3,:),'k-'); hold on;\nplot(BoardsVec,AvgMatCover(4,:),'g-'); hold on;\nplot(BoardsVec,AvgMatCover(1,:),'m*'); hold on;\nplot(BoardsVec,AvgMatCover(2,:),'b*'); hold on;\nplot(BoardsVec,AvgMatCover(3,:),'k*'); hold on;\nplot(BoardsVec,AvgMatCover(4,:),'g*'); hold on;\nplot(BoardsVec,AvgMatCover(5,:),'r*'); hold on;\ntitle('Convergence Study: Cover All');\nxlabel('Number of Bingo Cards');\nylabel('Average # of Draws to Win!');\nlegend('5','10','25','50','100');\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: prints simulation information\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_info()\n\n\nfprintf('\\n\\n**********************************************************************************\\n');\nfprintf('\\nAuthor: Nicholas A. Battista \\n');\nfprintf('University: UNC-CH \\n');\nfprintf('First Created: January 19, 2015 \\n');\nfprintf('Last Revision: May 5, 2015 \\n\\n');\nfprintf('**********************************************************************************\\n\\n');\n\nfprintf('This code plays the game of Bingo in a Monte Carlo setting, averaging\\n');\nfprintf(' N simulated games of Bingo for a specified number of bingo boards \\n\\n');\n\nfprintf('It tries to answer the following questions: \\n');\nfprintf(' 1. What is the expected number of draws to win regular bingo\\n');\nfprintf(' if there are N bingo boards in play? \\n');\nfprintf(' 2. What is the convergence rate of expected number of draws \\n');\nfprintf(' vs. # of bingo boards for a certain number of simulated bingo games? \\n');\nfprintf(' 3. What about inner square, outer square, and cover all? \\n\\n');\n\nfprintf('Initially it will play {5,10,25,50,100} games of bingo with each number\\n');\nfprintf(' of bingo boards. It varies the number of boards between {1,5,10,15,...,75}.\\n\\n');\n\nfprintf('NOTE: Monte Carlo simulation will take roughly 5 minutes. Please sit back and enjoy!\\n'); \n\nfprintf('\\n**********************************************************************************\\n');\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Interp.m", "ext": ".m", "path": "Ark-master/Interpolation/Interp.m", "size": 5337, "source_encoding": "utf_8", "md5": "fe9742b32ce148e917ab015a010fa097", "text": "function Interp()\n\n%Author: Nicholas Battista\n%Date of Last Revision: August 14, 2014\n\n%This function interpolates a function, f(x) [on line 228], using the\n%Newton Interpolation Scheme. \n\n%It interpolates over a uniform grid on interval [a,b] for a bunch of\n%different studies using an increasing number of interpolation pts. It then\n%conducts a convergence study, plotting the error vs. # of interpolation\n%pts.\n\n%It will also plot various interpolating polynomials for specific numbers\n%of interpolation pts with the data given to interpolate. \n\n\na=-pi/2; %Starting pt\nb= pi/2; %Ending pt\n\nNS = 1; %Starting # of Interpolation Pts. - 1 for Conv. Study \nNE = 31; %Ending # of Interpolation Pts. - 1 for Conv. Study\n\n%Initialization of Storage Matrices / Vectors to use for plotting\nC_Mat = zeros(NE,NE);\nX_Mat = C_Mat;\nerr = zeros(NE,1);\n\nfor N=NS:NE % (# of interpolation pts - 1)\n\n %Uniformly spaced interpolation pts\n h = (b-a)/N;\n x=zeros(1,N);\n x=a:h:b;\n\n %Associated y-values\n y = f(x);\n\n %Creates Newton-Interpolation Matrix\n mat = give_me_Matrix(x);\n\n %Newton Polynomial Coefficients\n c = mat\\y';\n \n %Storing Coefficients / Interpolation Pts\n C_Mat(1:N+1,N) = c;\n X_Mat(1:N+1,N) = x';\n \n %Find Error\n err(N) = compute_Error(a,b,c,x);\n\nend\n\n%Plots Convergence Study\nplot_Convergence_Study(NS,NE,err);\n\n%Plots Each Trial Against Actual Poly\nplot_Interpolation_Polys(a,b,NS,NE,C_Mat,X_Mat)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function to plot the convergence study\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Interpolation_Polys(a,b,NS,NE,C_Mat,X_Mat)\n\nNVec = NS:4:NE; \n\nlen = length(NVec); %# of trials being plotted\n\n%Computes # of subplot columns (tries to make it aesthetically pleasing)\nif ceil(len/2) > 4\n Ncols = 3;\nelse\n Ncols = 2;\nend\n\n%Computes # of subplot rows (tries to make it aesthetically pleasing)\nNrows = ceil(len/Ncols);\n\nfor j=1:length(NVec); \n\n N = NVec(j); %# interpolation pts. - 1 \n c = C_Mat(1:N+1,N);\n x = X_Mat(1:N+1,N);\n h=(b-a)/N;\n \n %Plots Interpolation Pts\n xTest = a:h:b; \n for i=1:length(xTest)\n yTest(i) = interp_poly(c,x,xTest(i));\n fTest(i) = f(xTest(i));\n end\n\n xLen = 0;%(b-a);\n \n %Plots Points along entire interval\n xTest2 = a-xLen/5:h/20:b+xLen/5;\n for i=1:length(xTest2)\n yTest2(i) = interp_poly(c,x,xTest2(i));\n end\n figure(2)\n subplot(Nrows,Ncols,j);\n plot(xTest,yTest,'.'); hold on;\n plot(xTest,fTest,'r.','MarkerSize',10); hold on;\n plot(xTest2,yTest2,'.','MarkerSize',6); hold on;\n plot(xTest,fTest,'r.','MarkerSize',10); hold on;\n xlabel('x');\n ylabel('Function, f(x) and Poly. fit, p(x)');\n title(sprintf('Poly Fits: N = %d', N))\n legend('p(x)','f(x)');\n \nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function to plot the convergence study\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Convergence_Study(NS,NE,err)\n\nsubplot(1,2,1);\nplot(NS:1:NE,err,'o-');\nxlabel('# of pts.');\nylabel('Error');\ntitle('Convergence Study');\n\nsubplot(1,2,2);\nsemilogy(NS:1:NE,err,'o-');\nxlabel('# of pts.');\nylabel('log(Error)');\ntitle('Convergence Study');\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function to evaluate coeff poly\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction err = compute_Error(a,b,c,x)\n\n xTest = a:0.01:b;\n yTest = zeros(1,length(xTest));\n yExact = yTest;\n \n for i=1:length(xTest)\n yTest(i) = interp_poly(c,x,xTest(i));\n yExact(i) = f(xTest(i));\n end\n \n errVec = abs(yTest - yExact);\n err = max(errVec);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function to evaluate coeff poly\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = coeff_poly(i,xV,xPt)\n\n%xPt: pt. we're evaluating the interpolating polynomial at\n%xV: vector of interpolation pts\n\nval = 1; %initialize\nfor j=1:i\n val = val * (xPt - xV(j)); \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function to evaluate interpolation polynomial\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction valy = interp_poly(c,xV,xPt)\n\n%xPt: pt. we're evaluating the interpolation polynomial at\n%xV: interpolation pts\n\nlen = length(c);\nvaly = c(1); %initialize\nfor i=2:len\n valy = valy + c(i)*coeff_poly(i-1,xV,xPt); \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function to create Matrix\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction mat = give_me_Matrix(x)\n\nlen = length(x);\n\nmat = ones(len,len);\n\nfor i=1:len\n mat(i,2) = x(i) - x(1);\nend\n\nfor i=3:len %loops over columns\n for j=1:len %loops over rows \n \n if (j err_Tol\n \n n = n+1; % counter increases by 1\n \n v = J*v; % multiply eigenvector guess by Jacobian matrix\n \n RQ(n) = v'*J*v / (v'*v); % compute approximate eigenvalue\n \n err = RQ(n) - RQ(n-1);\n \n err_Vec(n-1) = err;\n \nend\n\n%\n% Print some info\nfprintf('It tooks %d iterations to achieve an error tolerance of %d\\n\\n',n-1,err_Tol);\n\n\n%\n% plot Dominant Eigenvalue\n%\nfigure(1)\nnVec = 1:1:n; % Create vector of iteration numbers\nms = 42; % MarkerSize for Plotting\nlw = 4; % LineWidth for Plotting\nfs = 20; % FontSize for Plotting\nplot(nVec, RQ,'.-','LineWidth',lw,'MarkerSize',ms);\nxlabel('Iteration Number');\nylabel('Eigenvalue Estimate');\nset(gca,'FontSize',fs);\n\n%\n% plot Errors between successive iterations\n%\nfigure(2)\nsemilogy(nVec(1:end-1), abs(err_Vec),'r.-','LineWidth',lw,'MarkerSize',ms);\nxlabel('Iteration Number');\nylabel('Error');\nset(gca,'FontSize',fs);\n\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "royalRoads.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Genetic_Algorithms/speedy_GA/royalRoads.m", "size": 297, "source_encoding": "utf_8", "md5": "c5c668ec83e1ad6483374cf69eb4a87a", "text": "% The royal roads function. The chromosome length (i.e. len) \r\n% should be a multiple of 8\r\nfunction fitness=R1(pop)\r\n[popSize len]=size(pop);\r\nfitness=zeros(popSize,1);\r\nfor i=1:8:len\r\n temp=sum(pop(:,i:i+7),2);\r\n temp=double(temp==8);\r\n fitness=fitness+temp*8;\r\nend\r\nfitness=fitness';\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "oneMax.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Genetic_Algorithms/speedy_GA/oneMax.m", "size": 66, "source_encoding": "utf_8", "md5": "31a9c0ac4446868351f87baa83fc5051", "text": "% onemax\r\nfunction fitness=oneMax(pop)\r\nfitness=sum(pop,2)'; \r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "FitzHugh_Nagumo_PDE.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Neurons/PDE/FitzHugh_Nagumo_PDE.m", "size": 4837, "source_encoding": "utf_8", "md5": "11b8baf57f96b55fa8f793aebbf8a477", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% This script solves the FitzHugh-Nagumo Equations in 1d, which are \n% a simplified version of the more complicated Hodgkin-Huxley Equations. \n%\n% Author: Nick Battista\n% Created: 09/11/2015\n%\n% Equations:\n% dv/dt = D*Laplacian(v) - v*(v-a)*(v-1) - w + I(t)\n% dw/dt = eps*(v-gamma*w)\n%\n% Variables & Parameters:\n% v(x,t): membrane potential\n% w(x,t): blocking mechanism\n% D: diffusion rate of potential\n% a: threshold potential\n% gamma: resetting rate\n% eps: strength of blocking\n% I(t): initial condition for applied activation\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction FitzHugh_Nagumo_PDE()\n\n% Parameters in model %\nD = 1.0; % Diffusion coefficient\na = 0.3; % Threshold potential (Note: a=0.3 is traveling wave value, a=0.335 is interesting)\ngamma = 1.0; % Resetting rate (Note: large values give 'funky thick' traveling wave, gamma = 1.0 is desired)\neps = 0.001; % Blocking strength (Note: eps = 0.001 is desired)\nI_mag = 0.05; % Activation strength\n\n% Discretization/Simulation Parameters %\nN = 800; % # of discretized points %800\nL = 2000; % Length of domain, [0,L] %500\ndx = L/N; % Spatial Step\nx = 0:dx:L; % Computational Domain\n\n% Temporal Parameters %\nT_final = 10000; % Sets the final time\nNp = 10; % Set the number of pulses\npulse = T_final/Np; % determines the length of time between pulses.\nNT = 800000; % Number of total time-steps to be taken\ndt = T_final/NT; % Time-step taken\ni1 = 0.475; % fraction of total length where current starts\ni2 = 0.525; % fraction of total length where current ends\ndp = pulse/50; % Set the duration of the current pulse\npulse_time = 0; % pulse time is used to store the time that the next pulse of current will happen\nIIapp=zeros(1,N+1); % this vector holds the values of the applied current along the length of the neuron\ndptime = T_final/100; % This sets the length of time frames that are saved to make a movie.\n\n% Initialization %\nv = zeros(1,N+1);\nw = v;\nt=0;\nptime = 0; \ntVec = 0:dt:T_final;\nNsteps = length(tVec);\nvNext = zeros(Nsteps,N+1); vNext(1,:) = v;\nwNext = zeros(Nsteps,N+1); wNext(1,:) = w;\n\n%\n% **** % **** BEGIN SIMULATION! **** % **** %\n%\nfor i=2:Nsteps\n \n % Update the time\n t = t+dt; \n \n % Give Laplacian\n DD_v_p = give_Me_Laplacian(v,dx); \n \n % Gives applied current activation wave\n [IIapp,pulse_time] = Iapp(pulse_time,i1,i2,I_mag,N,pulse,dp,t,IIapp);\n \n % Update potential and blocking mechanism, using Forward Euler\n vN = v + dt * ( D*DD_v_p - v.*(v-a).*(v-1) - w + IIapp );\n wN = w + dt * ( eps*( v - gamma*w ) );\n \n % Update time-steps\n v = vN;\n w = wN;\n \n % Store time-step values\n vNext(i,:) = v;\n wNext(i,:) = w;\n \n %This is used to determine if the current time step will be a frame in the movie\n if t > ptime\n figure(1)\n plot(x, v,'r-','LineWidth',5);\n axis([0 L -0.2 1.0]);\n set(gca,'Linewidth',7);\n xlabel('Distance (x)');\n ylabel('Electropotenital (v)');\n ptime = ptime+dptime;\n fprintf('Time(s): %d\\n',t);\n pause(0.05);\n end\n \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: the injection function, Iapp = activation wave for system, and\n% returns both the activation as well as updated pulse_time\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [app,pulse_time] = Iapp(pulse_time,i1,i2,I_mag,N,pulse,dp,t,app)\n\n\n %Check to see if there should be a pulse\n if t > (pulse_time)\n \n % Sets pulsing region to current amplitude of I_mag x\\in[i1*N,i2*N]\n for j=(floor(i1*N):floor(i2*N))\n app(j) = I_mag; \n end\n \n % Checks if the pulse is over & then resets pulse_time to the next pulse time.\n if t > (pulse_time+dp)\n pulse_time = pulse_time+pulse;\n end\n \n else\n \n % Resets to no activation\n app = zeros(1,N+1);\n \n end\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: gives Laplacian of the membrane potential, note: assumes\n% periodicity and uses the 2nd order central differencing operator.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction DD_v = give_Me_Laplacian(v,dx)\n\nNpts = length(v);\nDD_v = zeros(1,Npts);\n\nfor i=1:Npts\n if i==1\n DD_v(i) = ( v(i+1) - 2*v(i) + v(end) ) / dx^2;\n elseif i == Npts\n DD_v(i) = ( v(1) - 2*v(i) + v(i-1) ) / dx^2;\n else\n DD_v(i) = ( v(i+1) - 2*v(i) + v(i-1) ) /dx^2;\n end\n\nend\n\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "FitzHugh_Nagumo_ODE.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Neurons/ODE/FitzHugh_Nagumo_ODE.m", "size": 3604, "source_encoding": "utf_8", "md5": "a3bd5dcc0ee16452a9f9503e871068aa", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% This script solves the FitzHugh-Nagumo Equations in 1d, which are \n% a simplified version of the more complicated Hodgkin-Huxley Equations. \n%\n% Author: Nick Battista\n% Created: 04/21/2019\n%\n% Equations:\n% dv/dt = - v*(v-a)*(v-1) - w + I(t)\n% dw/dt = eps*(v-gamma*w)\n%\n% Variables & Parameters:\n% v(t): membrane potential\n% w(t): blocking mechanism\n% D: diffusion rate of potential\n% a: threshold potential\n% gamma: resetting rate\n% eps: strength of blocking\n% I(t): initial condition for applied activation\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction FitzHugh_Nagumo_ODE()\n\n% Parameters in model %\na = 0.15; % Threshold potential (Note: a=0.3 is traveling wave value, a=0.335 is interesting)\ngamma = 1.0; % Resetting rate (Note: large values give 'funky thick' traveling wave, gamma = 1.0 is desired)\neps = 0.001; % Blocking strength (Note: eps = 0.001 is desired)\nI_mag = 0.05; % Activation strength\n\n% Temporal Parameters %\nT_final = 5000; % Sets the final time\nNp = 5; % Set the number of pulses\npulse = T_final/Np; % determines the length of time between pulses.\nNT = 400000; % Number of total time-steps to be taken\ndt = T_final/NT; % Time-step taken\ndp = pulse/50; % Set the duration of the current pulse\npulse_time = 0; % pulse time is used to store the time that the next pulse of current will happen\n\n% Initialization %\nv = 0;\nw = v;\nt=0;\ntVec = 0:dt:T_final;\nNsteps = length(tVec);\nvVec = zeros(Nsteps,1); vVec(1) = v;\nwVec = zeros(Nsteps,1); wVec(1) = w;\n\n%\n% **** % **** BEGIN SIMULATION! **** % **** %\n%\nfor i=2:Nsteps\n \n % Update the time\n t = t+dt; \n \n % Gives applied current activation wave\n [IIapp,pulse_time] = Iapp(pulse_time,I_mag,pulse,dp,t);\n \n % Update potential and blocking mechanism, using Forward Euler\n vN = v + dt * ( - v.*(v-a).*(v-1) - w + IIapp );\n wN = w + dt * ( eps*( v - gamma*w ) );\n \n % Update time-steps\n v = vN;\n w = wN;\n \n % Store time-step values\n vVec(i) = v;\n wVec(i) = w;\n \nend\n\n%\n% Plots Action Potential (cell voltage) / Blocking Strength vs. Time\n%\nfigure(1)\nlw = 5; % LineWidth\nfs = 18; % FontSize\nplot(tVec,vVec,'r-','LineWidth',lw); hold on;\nplot(tVec,wVec,'b-','LineWidth',lw-2); hold on;\nxlabel('Time');\nylabel('Quantity');\nleg = legend('Potential','Blocking Strength');\nset(gca,'FontSize',fs);\nset(leg,'FontSize',fs);\n\n%\n% Plots Phase Plane: Action Potential vs. Blocking Strength\n%\nfigure(2)\nlw = 5; % LineWidth\nfs = 18; % FontSize\nplot(wVec,vVec,'k-','LineWidth',lw); hold on;\nxlabel('Blocking Strength');\nylabel('Potential');\nset(gca,'FontSize',fs);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: the injection function, Iapp = activation wave for system, and\n% returns both the activation as well as updated pulse_time\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [app,pulse_time] = Iapp(pulse_time,I_mag,pulse,dp,t)\n\n\n %Check to see if there should be a pulse\n if t > (pulse_time)\n \n % Sets pulsing region to current amplitude of I_mag x\\in[i1*N,i2*N]\n app = I_mag; \n \n % Checks if the pulse is over & then resets pulse_time to the next pulse time.\n if t > (pulse_time+dp)\n pulse_time = pulse_time+pulse;\n end\n \n else\n \n % Resets to no activation\n app = 0;\n \n end\n\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "please_Compare_Logistic.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Compare_Discrete_to_Continuous/please_Compare_Logistic.m", "size": 2847, "source_encoding": "utf_8", "md5": "1b392d5975b96baed60b1d4ca04aad34", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Compares Discrete to Continuous Logistic Equation\n%\n% Author: Nick Battista\n% Institution: TCNJ\n% Created: March 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction please_Compare_Logistic(k)\n\n\n%\n% Clears any previous plots that are open in MATLAB\nclf;\n\n%\n% Time Information / Initialization\n%\nTFinal = 100; % Simulation runs until TFinal\n\n\n%\n% Initial Values\n%\nx0 = 25;\n\n\n%\n% Parameter Values\n%\n%k = 2.0; % growth rate\nC = 250; % carrying capacity\n\n%\n% Call function to solve Discrete Dynamical System\n%\n[X_dis,tVec_Discrete] = please_Solve_Discrete_System(TFinal,k,C,x0);\n\n%\n% Call function to solve Continuous Dynamical System\n%\n[X_con,tVec_Continuous] = please_Solve_Continuous_System(TFinal,k,C,x0);\n\n%\n% Plot Attributes\n%\nlw = 3; % LineWidth (how thick the lines should be)\nms = 30; % MarkerSize (how big the plot points should be)\nfs = 18; % FontSize (how big the font should be for labels)\n\n%\n% PLOT 1: Populations vs. Time\n%\nfigure(1)\nplot(tVec_Discrete,X_dis,'b.-','LineWidth',lw,'MarkerSize',ms); hold on;\nplot(tVec_Continuous,X_con,'r-','LineWidth',lw,'MarkerSize',ms); hold on;\nxlabel('Time');\nylabel('Population');\nleg = legend('Discrete','Continuous');\nset(gca,'FontSize',fs);\nset(leg,'FontSize',fs);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: solves Logistic Differential Equation\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nfunction [X,tVec] = please_Solve_Continuous_System(TFinal,k,C,x0)\n\n%\n% Initialize Time Information \n%\ndt = 0.02; % Time-step\nt= 0; % Initial Time\n\n%\n% Initialize Initial Population / Time Storage Vector / Counter for While Loop Indexing\n%\nX(1) = x0;\ntVec(1) = 0;\nn = 1;\n\n%\n% Solve ODE using Euler's Method\n%\nwhile tG : people who are prescribed prescription opioids\neps = 0.74; % G->S : people who use their prescriptions and then go back to susceptible\nbeta = 0.006; % S->H : people who get opioids from their relatives/friends/etc to abuse them\nmu = 0.00824; % : natural death rate\nmuSTAR = 0.00834 ; % : enhanced death rate for opioid abusers\ngamma =(1-eps); % G->H : percent of prescribed opioid class who get addicted to opioids\nzeta = 0.75; % H->R : rate at which Opioid abusers start treatment\ndelta = 0.09; % R->S : people who finish their treatment and then go back to susceptible class\nnu = coeff*(1-delta); % R->H : rate at which users in treatment fall back into drug use\nsigma = (1-coeff)*(1-delta); % R->H : rate at which people in treatment fall back into use themselves.\n\n\n% NOTE: sigma+delta+mu = 1.0;\n% NOTE: eps+gamma = 1.0;\n\n%\n% Components of vectors\n%\nS = sol(1); % Susceptible Class\nP = sol(2); % Prescribed Opioid Class\nR = sol(3); % People in Treatment\nA = 1 - S - P - R; % Abusing Opioid Class\n\nLambda = mu*(S+R+P) + muSTAR*A;\n\n%\n% Stochastic Piece (\"white noise\")\n%\nif stochastic_flag == 1\n white_noise = awgn(x1,1,'measured');\nelse\n white_noise = 0;\nend\n\n\n%\n% ODES (RHS)\n%\nLambda = mu*(S+P+R) + muSTAR*A; \ndS = Lambda - (alpha+mu)*S - beta*(1-xi)*S*A - beta*xi*S*P + eps*P + delta*R;\ndP = alpha*S - (gamma+eps+mu)*P;\ndR = zeta*A - nu*R*A - (delta+mu+sigma)*R;\n\n% OLD\n%dS = Lambda + delta*R - alpha*S - beta*S*H + eps*G - mu*S;\n%dP = alpha*S - gamma*G - eps*G - mu*G;\n%dR = zeta*H - nu*R*H - delta*R - mu*R - sigma*R;\n\n\n%\n% Vector to be evaluated\n%\ndvdt = [dS dP dR]';\n\n\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: plots phase planes!\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Phase_Planes(x1,x2,x3,x4)\n\nfigure(1)\nplot(x1,x2,'r-','LineWidth',3); hold on;\nplot(x1,x3,'b-','LineWidth',3); hold on;\nplot(x1,x4,'k-','LineWidth',3); hold on;\nxlabel('x1');\nylabel('x2,x3,x4');\nlegend('G vs. S','H vs. S','R vs. S');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: plots phase planes!\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Time_Evolutions(t,x1,x2,x3,x4)\n\nlw = 5;\nms = 10;\n\nfigure(2)\nplot(t,x1,'-','LineWidth',lw,'MarkerSize',ms,'Color',[0.25 0.5 1]); hold on;\nplot(t,x2,'-','LineWidth',lw,'MarkerSize',ms,'Color',[0.9 0.35 0.1]); hold on;\nplot(t,x3,'r-','LineWidth',lw,'MarkerSize',ms); hold on; %\nplot(t,x4,'-','LineWidth',lw,'MarkerSize',ms,'Color',[0 .4 0]); hold on; %,, ,'Color',[0.3 0 0.9]\nxlabel('time');\nylabel('populations');\nleg=legend('Susceptible', 'Prescribed', 'Opioid Abuse', 'Treatment');\nset(gca,'FontSize',20)\nset(leg,'FontSize',18)"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "compute_Jacobian_for_SIR_w_Deaths.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Epidemiology/ode45/compute_Jacobian_for_SIR_w_Deaths.m", "size": 1611, "source_encoding": "utf_8", "md5": "c8af14f9401c16e45c0fadc12959fe42", "text": "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: sets up a Jacobian Matrix and finds eigenvalues\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction compute_Jacobian_for_SIR_w_Deaths()\n\n\n%\n% SIR Model Parameters\n%\nbeta = 0.5; % rate of disease transmission\ngamma = 0.5; % rate of recovery\nmu = 0.01; % natural death rate\nmuStar = 2*mu; % enhanced death rate (natural death rate + death rate from disease)\nLambda = 0.005; % birth rate \n\n\n%\n% Equilibrium Population Values\n%\nS = ( gamma + muStar ) / beta;\nI = Lambda/(gamma+muStar) - mu/beta;\nR = (gamma/mu)*I;\n\n\n%\n% Compute elements of Jacobian\n%\nJ11 = -beta*I - mu; % d(Sdot)/dS\nJ12 = -beta*S; % d(Sdot)/dI\nJ13 = 0; % d(Sdot)/dR\n%\nJ21 = beta*I; % d(Idot)/dS\nJ22 = beta*S - gamma - muStar; % d(Idot)/dI\nJ23 = 0; % d(Idot)/dR\n%\nJ31 = 0; % d(Rdot)/dS\nJ32 = gamma; % d(Rdot)/dI\nJ33 = -mu; % d(Rdot)/dR\n\n\n%\n% Construct Jacobian Matrix\n%\nJ = [J11 J12 J13; J21 J22 J23; J31 J32 J33];\n\n\n%\n% Compute eigenvalues of Jacobian (returns them in a vector array)\n%\neigVals = eigs(J);\n\n%\n% Print Eigenvalues to Screen\n%\nfprintf('\\n\\nTheEIGENVALUES of the JACOBIAN are:');\nfprintf('\\n\\neig1 = %4.4f\\n',eigVals(1));\nfprintf('\\n\\neig2 = %4.4f\\n',eigVals(2));\nfprintf('\\n\\neig3 = %4.4f\\n\\n\\n',eigVals(3));\n%\nfprintf('LARGEST eigenvalue is: %4.4f\\n\\n',max(eigVals));"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "go_Go_Logistic_ode45.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Epidemiology/ode45/go_Go_Logistic_ode45.m", "size": 3030, "source_encoding": "utf_8", "md5": "9e86adb726a8dbdcad2d74ba767dae09", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Solves the Logistic Equation using MATLAB's\n% ODE 45 built in differential equation solver, which uses RK-4\n% (4th Order Runge-Kutta Method)\n%\n% dP/dt = k*P*(1 - P/C)\n% \n% Parameters: k <- growth rate\n% C <- carrying capacity\n%\n% Author: Nick Battista\n% Institution: TCNJ\n% Created: March 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction go_Go_Logistic_ode45()\n\n%\n% Clears any previous plots that are open in MATLAB\nclf;\n\n%\n% Time Information / Initialization\n%\nTstart = 0; % Simulation starts a tstart (initial value)\nTstop = 150; % Simulation runs until time = TFinal\n\n\n\n%\n% Initial Values\n%\np0 = 5; % Initial Population, P\nInitial_Values = [p0]; % Stores initial values in vector\n\n\n\n%\n% ode45 is matlab's ode solver\n%\noptions=odeset('RelTol',1e-4);\n[t,sol] = ode45(@f,[Tstart Tstop],Initial_Values,options);\n\n\n%\n% storing solutions for each variable after solving ODE/ODE System.\n% \nP = sol(:,1); %gives us P(t)\n\n\n\n%\n% Plotting solutions\n%\nplot_Time_Evolutions(t,P)\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: RHS vector of the problem: this function evaluates the \n% RHS of the ODEs and passes it back to the ode45 solver\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction dvdt = f(t,sol)\n\n\n%\n% Components of vectors\n%\nP = sol(1); % Susceptible\n\n\n%\n% ODE Parameter Values\n%\nk = 0.25; % logistic growth rate\nC = 150; % carrying capacity\n\n\n\n%\n% ODES (RHS)\n%\ndPdt = k*P*( 1 - P/C );\n\n\n\n\n%\n% Vector to be evaluated\n%\ndvdt = [dPdt]';\n\n\n\nreturn\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: plots the time evolutions (solutions to ODEs)!\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Time_Evolutions(t,P)\n\n%\n% Plot Attributes\n%\nlw = 4; % LineWidth (how thick the lines should be)\nms = 25; % MarkerSize (how big the plot points should be)\nfs = 18; % FontSize (how big the font should be for labels)\n\n%\n% PLOT 1: Populations vs. Time\n%\nfigure(1)\nplot(t,P,'b.-','LineWidth',lw,'MarkerSize',ms); hold on;\nxlabel('Time');\nylabel('Population');\nleg = legend('Logistic');\nset(gca,'FontSize',fs);\nset(leg,'FontSize',fs);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: plots the phase planes!\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Phase_Planes(S,I,R)\n\n%\n% Plot Attributes\n%\nlw = 4; % LineWidth (how thick the lines should be)\nms = 25; % MarkerSize (how big the plot points should be)\nfs = 18; % FontSize (how big the font should be for labels)\n\nfigure(2)\nplot(S,I,'b.-','LineWidth',lw,'MarkerSize',ms); hold on;\nxlabel('Susceptible');\nylabel('Infected');\nset(gca,'FontSize',fs);\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "go_Go_SIR.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Epidemiology/Euler_Method/go_Go_SIR.m", "size": 2370, "source_encoding": "utf_8", "md5": "87c84e39cd53309415720450851e0d9b", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Solves Standard Base Case SIR Model (no deaths)\n%\n% Author: Nick Battista\n% Institution: TCNJ\n% Created: March 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction go_Go_SIR()\n\n%\n% Clears any previous plots that are open in MATLAB\nclf;\n\n%\n% Time Information / Initialization\n%\nTFinal = 150; % Simulation runs until time = TFinal\ndt = 0.0025; % Time-step\nt = 0; % Initialize Time to 0.\nn = 0; % Initialize storage counter to 0.\n\n\n%\n% Initial Values\n%\ns0 = 0.95; % Initial Population for Susceptible, S\ni0 = 0.05; % Initial Population for Infected, I\nr0 = 0; % Initial Population for Recovered, R\n\n\n%\n% Parameter Values\n%\nbeta = 0.65; % rate of disease transmission\ngamma = 0.45; % rate of recovery\n\n\n%\n% Saves Initial Values into Storage Vectors\n%\nS(1) = s0;\nI(1) = i0;\nR(1) = r0;\nTimeVec(1) = t;\n\n%\n% While-loop that iteratively solves the discrete dynamical system\n%\nwhile t 0, unstable.\r\n% \r\n% Input: X,N,Nv\r\n% Output: R_0\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction R_0 = R0_calc(X)\r\n \r\n %\r\n % SIR w/ Deaths Parameter Vector\r\n % X = [beta gamma mu muStar Lambda]\r\n beta = X(1);\r\n gamma = X(2);\r\n mu = X(3);\r\n muStar = X(4);\r\n Lambda = X(5);\r\n \r\n %\r\n % Disease Free Equilibria (DFE) Pop. Values\r\n %\r\n S = Lambda/mu;\r\n I = 0;\r\n R = 0;\r\n \r\n %\r\n % Construct Jacobian Matrix\r\n %\r\n % 1st Row of Jacobian\r\n J11 = -beta*I-mu;\r\n J12 = -beta*S;\r\n J13 = 0;\r\n % 2nd Row of Jacobian\r\n J21 = beta*I;\r\n J22 = beta*S-gamma-muStar;\r\n J23 = 0;\r\n % 3rd Row of Jacobian\r\n J31 = 0;\r\n J32 = gamma;\r\n J33 = -mu;\r\n \r\n % Fill in Jacobian Entries\r\n J = [J11 J12 J13; J21 J22 J23; J31 J32 J33];\r\n \r\n % Compute Eigenvalues of Jacobian\r\n J_eigs = eigs(J);\r\n\r\n % Only Take Largest Eigenvalue (not exactly R_0, but proxy for stability, e.g., epidemic or no)\r\n R_0 = max(J_eigs);\r\n \r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: Performs the Sobol Calculations to calculate R_0 sensitivities\r\n% \r\n% Input: Sobol Matrices -> A and B, # of params -> d, # of simulations to be used -> N\r\n% Output: out=[S_y ; S_total]\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\nfunction out=sobol_R0(sobol_mat,d,N)\r\n\r\n\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix A\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\n A = sobol_mat(1:N,1:d);\r\n \r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix A\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\n B = sobol_mat(1:N,d+1:2*d);\r\n\r\n mat_size = size(A);\r\n\r\n for i = 1:mat_size(1)\r\n\r\n %Vector of parameters\r\n X = A(i,:);\r\n\r\n %\r\n % Compute R_0: note-> X = (beta, gamma, mu, muStar, Lambda)\r\n % \r\n R0_A(i) = R0_calc(X);\r\n\r\n end\r\n \r\n \r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix B\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\n %B = sobol_mat(1:N,d+1:2*d);\r\n \r\n for i = 1:mat_size(1)\r\n\r\n %Vector of parameters\r\n X = B(i,:);\r\n\r\n %\r\n % Compute R_0: note-> X = (beta, gamma, mu, muStar, Lambda)\r\n %\r\n R0_B(i) = R0_calc(X);\r\n \r\n end\r\n\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Cross matrices\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n for j=1:d %%%each j is a new matrix\r\n\r\n A2 = A;\r\n A2(:,j) = B(:,j); %exchange jth column of A with B\r\n\r\n for i = 1:mat_size(1)\r\n\r\n %Vector of parameters\r\n X = A2(i,:);\r\n\r\n %\r\n % Compute R_0: note-> X = (beta, gamma, mu, muStar, Lambda)\r\n %\r\n R0_mix(i,j) = R0_calc(X);\r\n \r\n end\r\n\r\n end\r\n \r\n %\r\n %y_mix(i,j) : i from 1:N (simulation number) and j from 1:d.\r\n %\r\n %var_y = var(y_A);\r\n var_R0 = var(R0_A);\r\n \r\n \r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix of all outputs\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n final_mat = [R0_A' R0_B' R0_mix];\r\n\r\n % First Order Sobol Indices\r\n S_R0 = first_order_ver2(final_mat);\r\n \r\n % Total Sobol Indices\r\n S_total_R0 = total_order_ver2(final_mat);\r\n \r\n %%Confidence interval\r\n % ci = bootci(10000,@(X) first_order_ver2(X),final_mat);\r\n % ci = bootci(1000,@(X) mean_R0(X),final_mat);\r\n % ci2 = bootci(1000,@(X) total_order_calc(X,var_R0),final_mat);\r\n \r\n figure()\r\n histogram(reshape(final_mat,1,N*(d+2)),'Normalization','pdf')\r\n title('Probability distribution of $\\lambda_{max}$ values','interpreter','latex')\r\n set(gca,'FontSize',18)\r\n \r\n %\r\n % Sobol 1st Order and Total Indices\r\n %\r\n out(1,:)=S_R0;\r\n out(2,:)=S_total_R0;\r\n \r\n %\r\n % Confidence Intervals\r\n %\r\n % out(2,:) = ci(1,:); %lower bounds\r\n % out(3,:) = ci(2,:); %upper bounds\r\n % out(5,:)=ci2(1,:);\r\n % out(6,:)=ci2(2,:);\r\n\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: computes First-Order Sobol Indices\r\n% \r\n% Input: matrix of all values from trials\r\n% Output: out (first order indices for each parameter)\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction out = first_order_ver2(final_mat)\r\n \r\n size_mat = size(final_mat);\r\n Ns = size_mat(1);\r\n\r\n for j=1:size_mat(2)-2\r\n out(j)=(Ns*final_mat(:,2)'*final_mat(:,j+2)-(final_mat(:,2)'*ones(Ns,1))^2)/...\r\n (Ns*final_mat(:,2)'*final_mat(:,2)-(final_mat(:,2)'*ones(Ns,1))^2);\r\n end\r\n \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: computes Total-Order Sobol Indices\r\n% \r\n% Input: matrix of all values from trials\r\n% Output: out (first order indices for each parameter)\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\nfunction out = total_order_ver2(final_mat)\r\n \r\n size_mat = size(final_mat);\r\n Ns = size_mat(1);\r\n\r\n for j=1:size_mat(2)-2\r\n out(j)=1-...\r\n (Ns*final_mat(:,1)'*final_mat(:,j+2)-(final_mat(:,2)'*ones(Ns,1))^2)/...\r\n (Ns*final_mat(:,2)'*final_mat(:,2)-(final_mat(:,2)'*ones(Ns,1))^2);\r\n end\r\n \r\n\r\n "} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Sobol_ODE_System.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/Mizuhara/Sobol_ODE_System.m", "size": 11988, "source_encoding": "utf_8", "md5": "f37cee9dc49f21c939a117adc336394a", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: Performs Sobol Sensitivity Analysis For Calculating Stability\r\n% of a Disease Free Equilibrium for the SIR Model w/ Deaths\r\n% \r\n% Orig. Author: Dr. Matthew Mizuhara (TCNJ)\r\n%\r\n% Modifications: Dr. Nick Battista (TCNJ) \r\n% Date: April 3, 2019\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction Sobol_ODE_System()\r\n\r\n%\r\n% Computational parameters\r\n%\r\nN = 100000; % # of simulations used in estimate\r\nd = 5; % # of parameters used for sensitivity calculations\r\nTend = 365; % Time Final (Needed for ODE only)\r\ntspan = [0 Tend]; % Range of Time for ODE to be Solved\r\n\r\n%\r\n% Setting Up Sobol Matrix\r\n%\r\n\r\n% Constructs a new Sobol sequence point set in d-dimensions.\r\ns = sobolset(2*d);\r\n\r\n% Creates N by 2d matrix of parameters\r\nsobol_mat = s(1:N,:); %N by 2d matrix of parameters\r\n\r\n% Parameter Order to be Used Below (just for us to reference order here):\r\n% X = [beta gamma mu muStar Lambda]\r\n\r\n%\r\n% PARAMETER RANGES\r\n%\r\n% beta\r\nbetaLow = 0.05;\r\nbetaHigh= 0.5;\r\n% gamma\r\ngammaLow = 0.05;\r\ngammaHigh=0.5;\r\n% mu\r\nmuLow = 0.005;\r\nmuHigh = 2*muLow;\r\n% muStar \r\nmuStarLow = 2*muLow;\r\nmuStarHigh = 10*muLow;\r\n% Lambda\r\nLambdaLow = muLow;\r\nLambdaHigh= 3*muHigh;\r\n\r\n%\r\n%Rescale Sobol Matrix Automatically Based on Ranges Above\r\n%\r\nsobol_mat(:,1)=sobol_mat(:,1)*(betaHigh-betaLow)+betaLow; %beta\r\nsobol_mat(:,2)=sobol_mat(:,2)*(gammaHigh-gammaLow)+gammaLow; %gamma\r\nsobol_mat(:,3)=sobol_mat(:,3)*(muHigh-muLow)+muLow; %mu\r\nsobol_mat(:,4)=sobol_mat(:,4)*(muStarHigh-muStarLow)+muStarLow; %muStar\r\nsobol_mat(:,5)=sobol_mat(:,5)*(LambdaHigh-LambdaLow)+LambdaLow; %Lambda\r\n%\r\nsobol_mat(:,6)=sobol_mat(:,6)*(betaHigh-betaLow)+betaLow; %beta\r\nsobol_mat(:,7)=sobol_mat(:,7)*(gammaHigh-gammaLow)+gammaLow; %gamma\r\nsobol_mat(:,8)=sobol_mat(:,8)*(muHigh-muLow)+muLow; %mu\r\nsobol_mat(:,9)=sobol_mat(:,9)*(muStarHigh-muStarLow)+muStarLow; %muStar\r\nsobol_mat(:,10)=sobol_mat(:,10)*(LambdaHigh-LambdaLow)+LambdaLow; %Lambda\r\n\r\n \r\n%\r\n% Actually Perform Sobol Sensitivity (and record how long it takes using tic-toc)\r\n%\r\nfprintf('\\n\\nTime to run Sobol Sensitivity:\\n');\r\ntic \r\nout = sobol_R0(sobol_mat,d,N);\r\ntoc\r\nfprintf('\\n\\n');\r\n\r\n\r\n% Store First Order Sobol Indices\r\nS_R0 = out(1,:);\r\n\r\n% Store Second Order Sobol Indices\r\nS_total_R0=out(2,:);\r\n\r\n% Create Vector of #'s As Dummy for Each Parameter for Plotting\r\nx=1:d;\r\n\r\n%\r\n% Creates Bar Graph for 1st Order Sobol Indices\r\n%\r\nfigure()\r\nbar(x,S_R0)\r\ntitle('R_0: First order Sobol indices')\r\nxticklabels({'\\beta','\\gamma','\\mu','\\mu^*','\\Lambda'})\r\nmaxS = 1.05*max(S_R0);\r\nminS = min( 1.05*min(S_R0), 0 );\r\naxis([0 6 minS maxS])\r\n\r\n%\r\n% Creates Bar Graph for Total Order Sobol Indices\r\n%\r\nfigure()\r\nbar(x,S_total_R0)\r\ntitle('R_0: Total Sobol indices')\r\nxticklabels({'\\beta','\\gamma','\\mu','\\mu^*','\\Lambda'})\r\nmaxS = 1.05*max(S_total_R0);\r\nminS = min( 1.05*min(S_total_R0), 0 );\r\naxis([0 6 minS maxS])\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: Performs the Sobol Calculations for ODE System\r\n% \r\n% Input: A,B, d,N\r\n% Output: out=[S_y ; S_total]\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction out= sobol_y(sobol_mat,d,N)\r\n\r\n\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix A\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\n A = sobol_mat(1:N,1:d);\r\n \r\n \r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix B\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\n B = sobol_mat(1:N,d+1:2*d);\r\n\r\n mat_size = size(A);\r\n\r\n for i = 1:mat_size(1)\r\n\r\n %Vector of parameters\r\n X = A(i,:);\r\n\r\n % Solves the ODE System\r\n y = brauer_zika_ode(X,N,Nv,Tend,I_init);\r\n % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a)\r\n\r\n %Measure number of infected humans\r\n y_A(i) = y(end,3); %Number of infected humans\r\n % R0_A(i) = X(2)/X(4)+X(1)*X(6)*X(7)/(X(5)*X(4)*(X(5)+X(7)));\r\n\r\n end\r\n \r\n \r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix B\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\n %B = sobol_mat(1:N,d+1:2*d);\r\n \r\n for i = 1:mat_size(1)\r\n\r\n %Vector of parameters\r\n X = B(i,:);\r\n\r\n % Solves the ODE System\r\n y = brauer_zika_ode(X,N,Nv,Tend,I_init);\r\n % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a)\r\n\r\n % Measure number of infected humans\r\n y_B(i) = y(end,3); %Number of infected humans\r\n % R0_B(i) = X(2)/X(4)+X(1)*X(6)*X(7)/(X(5)*X(4)*(X(5)+X(7)));\r\n\r\n end\r\n\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Cross matrices\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n for j=1:d %%%each j is a new matrix\r\n\r\n A2 = A;\r\n A2(:,j) = B(:,j); %exchange jth column of A with B\r\n\r\n for i = 1:mat_size(1)\r\n\r\n %Vector of parameters\r\n X = A2(i,:);\r\n\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Solve ODE\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n y = brauer_zika_ode(X,N,Nv,Tend,I_init);\r\n % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a)\r\n\r\n % Measure number of infected humans\r\n y_mix(i,j) = y(end,3); %Number of infected humans\r\n % R0_mix(i,j) = X(2)/X(4)+X(1)*X(6)*X(7)/(X(5)*X(4)*(X(5)+X(7)));\r\n\r\n end\r\n\r\n end\r\n \r\n %%y_mix(i,j) : i from 1:N (simulation number) and j from 1:d.\r\n \r\n var_y = var(y_A);\r\n %var_R0 = var(R0_A);\r\n \r\n %First order indices\r\n \r\n for i=1:d\r\n \r\n sumy=0;\r\n %sumR0 =0;\r\n for j=1:N\r\n\r\n sumy = sumy+ y_B(j)*(y_mix(j,i)-y_A(j));\r\n % sumR0 = sumR0+ R0_B(j)*(R0_mix(j,i)-R0_A(j));\r\n end\r\n S_y(i) = sumy/N/var_y;\r\n % S_R0(i) = sumR0/N/var_R0;\r\n end\r\n \r\n \r\n %Total order indices\r\n \r\n for i=1:d\r\n \r\n sumy=0;\r\n %sumR0 =0;\r\n for j=1:N\r\n \r\n sumy = sumy+ (y_A(j)-y_mix(j,i)).^2;\r\n % sumR0 = sumR0+ (R0_A(j)-R0_mix(j,i)).^2;\r\n end\r\n \r\n S_total_y(i) = sumy/(2*N)/var_y;\r\n % S_total_R0(i) = sumR0/(2*N)/var_R0;\r\n end\r\n\r\n out(1,:)=S_y;\r\n out(2,:)=S_total_y;\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: Performs the Sobol Calculations to calculate R_0 sensitivities\r\n% \r\n% Input: A,B, d,N\r\n% Output: out=[S_y ; S_total]\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\nfunction out=sobol_R0(sobol_mat,d,N)\r\n\r\n\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix A\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\n A = sobol_mat(1:N,1:d);\r\n \r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix A\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\n B = sobol_mat(1:N,d+1:2*d);\r\n\r\n mat_size = size(A);\r\n\r\n for i = 1:mat_size(1)\r\n\r\n %Vector of parameters\r\n X = A(i,:);\r\n\r\n %\r\n % Compute R_0: note-> X = (beta, alpha,kappa,gamma, mu, beta_v,eta)\r\n % \r\n R0_A(i) = R0_calc(X);\r\n\r\n end\r\n \r\n \r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix B\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\n %B = sobol_mat(1:N,d+1:2*d);\r\n \r\n for i = 1:mat_size(1)\r\n\r\n %Vector of parameters\r\n X = B(i,:);\r\n\r\n %\r\n % Compute R_0: note-> X = (beta, alpha,kappa,gamma, mu, beta_v,eta)\r\n %\r\n R0_B(i) = R0_calc(X);\r\n \r\n end\r\n\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Cross matrices\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n for j=1:d %%%each j is a new matrix\r\n\r\n A2 = A;\r\n A2(:,j) = B(:,j); %exchange jth column of A with B\r\n\r\n for i = 1:mat_size(1)\r\n\r\n %Vector of parameters\r\n X = A2(i,:);\r\n\r\n %\r\n % Compute R_0: note-> X = (beta, alpha,kappa,gamma, mu, beta_v,eta)\r\n %\r\n R0_mix(i,j) = R0_calc(X);\r\n \r\n end\r\n\r\n end\r\n \r\n %\r\n %y_mix(i,j) : i from 1:N (simulation number) and j from 1:d.\r\n %\r\n %var_y = var(y_A);\r\n var_R0 = var(R0_A);\r\n \r\n \r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n % Matrix of all outputs\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n final_mat = [R0_A' R0_B' R0_mix];\r\n\r\n % First Order Sobol Indices\r\n S_R0 = first_order_ver2(final_mat);\r\n \r\n % Total Sobol Indices\r\n S_total_R0 = total_order_ver2(final_mat);\r\n \r\n %%Confidence interval\r\n % ci = bootci(10000,@(X) first_order_ver2(X),final_mat);\r\n % ci = bootci(1000,@(X) mean_R0(X),final_mat);\r\n % ci2 = bootci(1000,@(X) total_order_calc(X,var_R0),final_mat);\r\n \r\n figure()\r\n histogram(reshape(final_mat,1,N*(d+2)),'Normalization','pdf')\r\n title('Probability distribution of $R_0$ values','interpreter','latex')\r\n\r\n %\r\n % Sobol 1st Order and Total Indices\r\n %\r\n out(1,:)=S_R0;\r\n out(2,:)=S_total_R0;\r\n \r\n %\r\n % Confidence Intervals\r\n %\r\n % out(2,:) = ci(1,:); %lower bounds\r\n % out(3,:) = ci(2,:); %upper bounds\r\n %out(5,:)=ci2(1,:);\r\n %out(6,:)=ci2(2,:);\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: returns the \"R0 value\" for a particular parameter set\r\n%\r\n% Note: not exactly R_0 but a proxy for stability by returning\r\n% largest eigenvalue. If eigVal > 0, unstable.\r\n% \r\n% Input: X,N,Nv\r\n% Output: R_0\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction R_0 = R0_calc(X)\r\n \r\n %\r\n % SIR w/ Deaths Parameter Vector\r\n % X = [beta gamma mu muStar Lambda]\r\n beta = X(1);\r\n gamma = X(2);\r\n mu = X(3);\r\n muStar = X(4);\r\n Lambda = X(5);\r\n \r\n %\r\n % Disease Free Equilibria (DFE) Pop. Values\r\n %\r\n S = Lambda/mu;\r\n I = 0;\r\n R = 0;\r\n \r\n %\r\n % Construct Jacobian Matrix\r\n %\r\n % 1st Row of Jacobian\r\n J11 = -beta*I-mu;\r\n J12 = -beta*S;\r\n J13 = 0;\r\n % 2nd Row of Jacobian\r\n J21 = beta*I;\r\n J22 = beta*S-gamma-muStar;\r\n J23 = 0;\r\n % 3rd Row of Jacobian\r\n J31 = 0;\r\n J32 = gamma;\r\n J33 = -mu;\r\n \r\n % Fill in Jacobian Entries\r\n J = [J11 J12 J13; J21 J22 J23; J31 J32 J33];\r\n \r\n % Compute Eigenvalues of Jacobian\r\n J_eigs = eigs(J);\r\n\r\n % Only Take Largest Eigenvalue (not exactly R_0, but proxy for stability, e.g., epidemic or no)\r\n R_0 = max(J_eigs);\r\n \r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: computes First-Order Sobol Indices\r\n% \r\n% Input: matrix of all values from trials\r\n% Output: out (first order indices for each parameter)\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction out = first_order_ver2(final_mat)\r\n \r\n size_mat = size(final_mat);\r\n Ns = size_mat(1);\r\n\r\n for j=1:size_mat(2)-2\r\n out(j)=(Ns*final_mat(:,2)'*final_mat(:,j+2)-(final_mat(:,2)'*ones(Ns,1))^2)/...\r\n (Ns*final_mat(:,2)'*final_mat(:,2)-(final_mat(:,2)'*ones(Ns,1))^2);\r\n end\r\n \r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% FUNCTION: computes Total-Order Sobol Indices\r\n% \r\n% Input: matrix of all values from trials\r\n% Output: out (first order indices for each parameter)\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\nfunction out = total_order_ver2(final_mat)\r\n \r\n size_mat = size(final_mat);\r\n Ns = size_mat(1);\r\n\r\n for j=1:size_mat(2)-2\r\n out(j)=1-...\r\n (Ns*final_mat(:,1)'*final_mat(:,j+2)-(final_mat(:,2)'*ones(Ns,1))^2)/...\r\n (Ns*final_mat(:,2)'*final_mat(:,2)-(final_mat(:,2)'*ones(Ns,1))^2);\r\n end\r\n \r\n\r\n "} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "fnc_GetInputs.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_GetInputs.m", "size": 815, "source_encoding": "utf_8", "md5": "c0043b47041ba0bc78f08e4bfbc311b0", "text": "%% fnc_GetInputs: give the vector of the inputs corresponding to the index\r\n% (useful to scan all the possible combinations of the\r\n% inputs)\r\n% \r\n% Usage:\r\n% ii = fnc_GetInputs(i)\r\n%\r\n% Inputs:\r\n% i scalar index of the inputs (given by fnc_GetIndex)\r\n%\r\n% Output:\r\n% ii array of the corresponding inputs\r\n%\r\n% ------------------------------------------------------------------------\r\n% See also \r\n% fnc_GetIndex \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 29-01-2011\r\n%\r\n% History:\r\n% 1.0 29-01-2011 First release.\r\n% 23-09-2014 Changed: de2bi to bitget\r\n%%\r\n\r\nfunction ii = fnc_GetInputs(i)\r\n\r\nii = find(bitget(i, 1:(floor(log(i)/log(2)) + 1)));"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "GSA_GetSy_MultiOut_MultiSI.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_GetSy_MultiOut_MultiSI.m", "size": 6532, "source_encoding": "utf_8", "md5": "713a7c7a6ce495892c15cf3ec1efc17a", "text": "%% GSA_GetSy_MultiOut_MultiSI: calculate the Sobol' sensitivity indices\r\n%\r\n% Usage:\r\n% [S, eS, pro] = GSA_GetSy_MultiOut_MultiSI(pro, iset, verbose)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n% iset cell array or array of inputs of the considered set, they can be selected\r\n% by index (1,2,3 ...) or by name ('in1','x',..) or\r\n% mixed\r\n% verbose if not empty, it shows the time (in hours) for\r\n% finishing\r\n%\r\n% Output:\r\n% S sensitivity coefficient\r\n% eS error of sensitivity coefficient\r\n% pro updated project structure\r\n%\r\n% ------------------------------------------------------------------------\r\n% Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008.\r\n% See also\r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 15-02-2011\r\n%\r\n% History:\r\n% 1.0 15-04-2011 Added verbose parameter\r\n% 1.0 15-01-2011 First release.\r\n% 06-01-2014 Added comments.\r\n%%\r\n\r\nfunction [S, eS, pro] = GSA_GetSy_MultiOut_MultiSI(pro, iset, verbose)\r\n\r\nif ~exist('verbose','var')\r\n verbose = 0;\r\nelse\r\n verbose = ~isempty(verbose) && verbose;\r\nend\r\n\r\noutput = size(pro.GSA.fE,2);\r\n\r\n% get the indexes corresponding to the variables in iset\r\nindex = fnc_SelectInput(pro, iset);\r\n\r\nif isempty(index)\r\n S = zeros(output,1);\r\n eS = zeros(output,1);\r\nelse\r\n S = zeros(output,1);\r\n eS = zeros(output,1);\r\n % number of variables in iset\r\n n_index = length(index);\r\n % number of possibile combinations for the n variables in iset \r\n L = 2^n_index;\r\n \r\n if verbose\r\n tic\r\n end\r\n % for all the possible combinations of variables in iset\r\n for i=1:(L-1)\r\n % calculate the indexes of the variables in the i-th combination \r\n ii = fnc_GetInputs(i);\r\n % calculate the real indexes of the variables in the i-th\r\n % combination\r\n si = fnc_GetIndex(index(ii));\r\n % if the part of sensitivity due to the si variables is not\r\n % calculated yet (useful to avoid to calculate again, saving time)\r\n if sum(isnan(pro.GSA.GSI(:,si))) > 0\r\n \r\n %-------\r\n % if the part of variance in ANOVA corresponding to the si \r\n % variables is not calculated yet (useful to avoid to calculate\r\n % again, saving time)\r\n if sum(isnan(pro.GSA.Di(:,si))) > 0\r\n \r\n % get the indexes of the variables in the current\r\n % combination of the variables in the iset\r\n ixi = fnc_GetInputs(si);\r\n s = length(ixi);\r\n l = 2^s - 1;\r\n \r\n %======\r\n if sum(isnan(pro.GSA.Dmi(:,si))) > 0\r\n n = length(pro.Inputs.pdfs);\r\n N = size(pro.SampleSets.E,1);\r\n H = pro.SampleSets.E(:,:);\r\n cii = fnc_GetComplementaryInputs(si,n);\r\n % create the new mixed (E and T) samples to perform the \r\n % quasi-Monte Carlo algorithm (see section 2.4) \r\n H(:,cii) = pro.SampleSets.T(:,cii);\r\n \r\n % Store the sample set in the project structure array\r\n pro.SampleSets.H{si} = H;\r\n \r\n % Parfor loop requirements\r\n model_function_handle = pro.Model.handle;\r\n fH_cell = cell(N,1);\r\n \r\n % Evaluate the model at the sample points in set H\r\n parfor j=1:N\r\n fH_cell{j} = feval(model_function_handle,H(j,:)); % the function output must be a single variable that takes the form of a row vector\r\n end\r\n \r\n % Convert the cell array to a numeric array, and store \r\n % the simulation results in the project structure array\r\n pro.GSA.fH{si} = cell2mat(fH_cell); % this will only work if all output generated by the function is numeric\r\n \r\n % calculate the elements of the summation reported in\r\n % section 2.4 as I\r\n ff = (pro.GSA.fE - repmat(pro.GSA.mfE,size(pro.GSA.fE,1),1)).*(pro.GSA.fH{si}-repmat(pro.GSA.mfE,size(pro.GSA.fH{si},1),1));\r\n \r\n % calculate the I value in section 2.4\r\n pro.GSA.Dmi(:,si) = nanmean(ff)';\r\n pro.GSA.eDmi(:,si) = 1.96*sqrt((nanmean(ff.^2)' - pro.GSA.Dmi(:,si).^2)./sum(~isnan(ff))');\r\n end\r\n %=======\r\n \r\n Di = pro.GSA.Dmi(:,si);\r\n eDi = pro.GSA.eDmi(:,si).^2;\r\n \r\n % compute the summation of the I values for all the\r\n % combinations of the current subset\r\n for j=1:(l-1)\r\n sii = fnc_GetInputs(j);\r\n k = fnc_GetIndex(ixi(sii));\r\n s_r = s - length(sii);\r\n % add the part of variance due to the j-th subset of\r\n % variables or subtract it following eq. (20)\r\n Di = Di + pro.GSA.Dmi(:,k)*((-1)^s_r);\r\n eDi = eDi + pro.GSA.eDmi(:,k).^2;\r\n end\r\n \r\n % add/subtract the square of the mean value (here it's 0)\r\n pro.GSA.Di(:,si) = Di + ((pro.GSA.f0').^2)*((-1)^s);\r\n pro.GSA.eDi(:,si) = sqrt(eDi + 2*((pro.GSA.ef0').^2));\r\n \r\n \r\n end\r\n %------\r\n % calculate the partial sensitivity coefficient by definition \r\n pro.GSA.GSI(:,si) = pro.GSA.Di(:,si)./(pro.GSA.D');\r\n pro.GSA.eGSI(:,si) = pro.GSA.GSI(:,si).*pro.GSA.eDi(:,si)./(pro.GSA.D');\r\n end\r\n % sum the partial sensitivity coefficients for all the combinations\r\n % of the variables in iset\r\n S = S + pro.GSA.GSI(:,si);\r\n eS = eS + pro.GSA.eGSI(:,si);\r\n \r\n if verbose\r\n timelapse = toc;\r\n disp(timelapse*(L-1-i)/i/60/60);\r\n end\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "fnc_getSobolSequence.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_getSobolSequence.m", "size": 5664, "source_encoding": "utf_8", "md5": "476e90688fb596a2d7b46d05c269f9ea", "text": "%% fnc_getSobolSequence: give a set of sobol quasi-random \r\n%\r\n% Usage:\r\n% X = fnc_getSobolSequence(dim, N, dbpath)\r\n%\r\n% Inputs:\r\n% dim number of variables, the MAX number of variables is 40\r\n% N number of samples\r\n%\r\n% Output:\r\n% X matrix [N x dim] with the quasti-random samples\r\n% \r\n% ------------------------------------------------------------------------\r\n%\r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 01-02-2011\r\n%\r\n% History:\r\n% 1.0 01-02-2011 First release.\r\n%\r\n%\r\n% Credits: \r\n% This code is based on the one developed by John Burkardt\r\n% (http://people.sc.fsu.edu/~jburkardt/m_src/sobol_dataset/sobol_dataset.html)\r\n% and previously by Bennett Fox\r\n%\r\n%%\r\n\r\nfunction X = fnc_getSobolSequence(dim, N)\r\n\r\np = fileparts(mfilename('fullpath'));\r\ndbpath = [p,'/SobolSets'];\r\n\r\nif exist(dbpath,'dir') \r\n nf = dir([dbpath,'/*.mat']);\r\n for i=1:length(nf)\r\n [DIM, remain] = strtok(nf(i).name(2:end), 'N');\r\n if (str2double(DIM) == dim)\r\n NN = strtok(remain(2:end), '.');\r\n if (str2double(NN) == N)\r\n load([dbpath,'/',nf(i).name]);\r\n return\r\n end\r\n end\r\n end\r\nend\r\n\r\nnextseed = 2^floor(log2(N)+1);\r\n\r\nX = nan(N,dim);\r\nMeM = InitSobol(dim);\r\n\r\nfor j = 1:N\r\n [X(j,:), nextseed, MeM] = getNewSobolVector(dim, nextseed, MeM);\r\nend\r\n\r\nif exist(dbpath,'dir') \r\n save([dbpath,'/S',num2str(dim),'N',num2str(N),'.mat'],'X');\r\nend\r\n\r\n%% ------------------------------------------------------------------------\r\n\r\n function [ qrv, nextseed, MeM ] = getNewSobolVector (dim, seed, MeM)\r\n\r\n seed = max(floor(seed),0);\r\n\r\n if ( seed == 0 )\r\n l = 1;\r\n MeM.lastq = zeros(1,dim);\r\n elseif ( seed == (MeM.seed_save + 1) )\r\n l = smallest0bit(seed);\r\n elseif ( seed <= MeM.seed_save )\r\n MeM.seed_save = 0;\r\n l = 1;\r\n MeM.lastq(1:dim) = 0;\r\n\r\n for seed_temp = MeM.seed_save : seed - 1\r\n l = smallest0bit(seed_temp);\r\n for i = 1:dim\r\n MeM.lastq(i) = bitxor(MeM.lastq(i), MeM.v(i,l));\r\n end\r\n end\r\n\r\n l = smallest0bit(seed);\r\n\r\n elseif ((MeM.seed_save + 1) < seed)\r\n\r\n for seed_temp = (MeM.seed_save + 1):(seed - 1)\r\n l = smallest0bit(seed_temp);\r\n for i = 1 : dim\r\n MeM.lastq(i) = bitxor(MeM.lastq(i),MeM.v(i,l) );\r\n end\r\n end\r\n\r\n l = smallest0bit(seed);\r\n\r\n end\r\n\r\n qrv = nan(1,dim);\r\n\r\n for i = 1 : dim\r\n qrv(i) = MeM.lastq(i) * MeM.recipd;\r\n MeM.lastq(i) = bitxor ( MeM.lastq(i), MeM.v(i,l) );\r\n end\r\n\r\n MeM.seed_save = seed;\r\n nextseed = seed + 1;\r\n\r\n%% -------------------------------------------------------------------------\r\n\r\nfunction i = smallest0bit(b)\r\n\r\n i = 0;\r\n b = floor(b);\r\n\r\n while (true)\r\n i = i + 1;\r\n halfb = floor(b/2);\r\n if (b == 2*halfb)\r\n break;\r\n end\r\n\r\n b = halfb;\r\n end\r\n\r\n \r\n%% ----------------------------------------------------------------------\r\n function MeM = InitSobol(dim)\r\n\r\n MeM.seed_save = -1;\r\n MeM.v = zeros(40,30);\r\n\r\n MeM.v(1:40,1) = 1;\r\n MeM.v(3:40,2) = [ ...\r\n 1, 3, 1, 3, 1, 3, 3, 1, ...\r\n 3, 1, 3, 1, 3, 1, 1, 3, 1, 3, ...\r\n 1, 3, 1, 3, 3, 1, 3, 1, 3, 1, ...\r\n 3, 1, 1, 3, 1, 3, 1, 3, 1, 3 ]';\r\n\r\n MeM.v(4:40,3) = [ ...\r\n 7, 5, 1, 3, 3, 7, 5, ...\r\n 5, 7, 7, 1, 3, 3, 7, 5, 1, 1, ...\r\n 5, 3, 3, 1, 7, 5, 1, 3, 3, 7, ...\r\n 5, 1, 1, 5, 7, 7, 5, 1, 3, 3 ]';\r\n\r\n MeM.v(6:40,4) = [ ...\r\n 1, 7, 9,13,11, ...\r\n 1, 3, 7, 9, 5,13,13,11, 3,15, ...\r\n 5, 3,15, 7, 9,13, 9, 1,11, 7, ...\r\n 5,15, 1,15,11, 5, 3, 1, 7, 9 ]';\r\n \r\n MeM.v(8:40,5) = [ ...\r\n 9, 3,27, ...\r\n 15,29,21,23,19,11,25, 7,13,17, ...\r\n 1,25,29, 3,31,11, 5,23,27,19, ...\r\n 21, 5, 1,17,13, 7,15, 9,31, 9 ]';\r\n\r\n MeM.v(14:40,6) = [ ...\r\n 37,33, 7, 5,11,39,63, ...\r\n 27,17,15,23,29, 3,21,13,31,25, ...\r\n 9,49,33,19,29,11,19,27,15,25 ]';\r\n\r\n MeM.v(20:40,7) = [ ...\r\n 13, ...\r\n 33,115, 41, 79, 17, 29,119, 75, 73,105, ...\r\n 7, 59, 65, 21, 3,113, 61, 89, 45,107 ]';\r\n\r\n MeM.v(38:40,8) = [ ...\r\n 7, 23, 39 ]';\r\n MeM.poly(1:40)= [ ...\r\n 1, 3, 7, 11, 13, 19, 25, 37, 59, 47, ...\r\n 61, 55, 41, 67, 97, 91, 109, 103, 115, 131, ...\r\n 193, 137, 145, 143, 241, 157, 185, 167, 229, 171, ...\r\n 213, 191, 253, 203, 211, 239, 247, 285, 369, 299 ];\r\n\r\n MeM.v(1,:) = 1;\r\n for i = 2 : dim\r\n j = MeM.poly(i);\r\n m = 0;\r\n\r\n while ( 1 )\r\n\r\n j = floor ( j / 2 );\r\n\r\n if ( j <= 0 )\r\n break;\r\n end\r\n\r\n m = m + 1;\r\n end\r\n\r\n j = MeM.poly(i);\r\n for k = m : -1 : 1\r\n j2 = floor ( j / 2 );\r\n includ(k) = ( j ~= 2 * j2 );\r\n j = j2;\r\n end\r\n\r\n for j = m + 1 : 30\r\n newv = MeM.v(i,j-m);\r\n l = 1;\r\n for k = 1 : m\r\n l = 2 * l;\r\n if ( includ(k) )\r\n newv = bitxor ( newv, l * MeM.v(i,j-k) );\r\n end\r\n end\r\n MeM.v(i,j) = newv;\r\n end\r\n end\r\n\r\n l = 1;\r\n for j = 29 : -1 : 1\r\n l = 2 * l;\r\n MeM.v(:,j) = MeM.v(:,j) * l;\r\n end\r\n\r\n MeM.recipd = 1.0 / ( 2 * l );\r\n MeM.lastq(1:dim) = 0;\r\n\r\n "} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "pro_SetModel.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pro_SetModel.m", "size": 737, "source_encoding": "utf_8", "md5": "b5631a61b6e339d981141888764dbc4c", "text": "%% pro_SetModel: Set the model to the project\r\n%\r\n% Usage:\r\n% pro = pro_SetModel(pro, model, name)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n% model handle to the @(x)model(x,...) where x is a vector \r\n% name optional, name of the model\r\n%\r\n% Output:\r\n% pro project structure\r\n% \r\n% ------------------------------------------------------------------------\r\n% See also \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 28-01-2011\r\n%\r\n% History:\r\n% 1.0 28-01-2011 First release.\r\n%%\r\n\r\nfunction pro = pro_SetModel(pro, model, name)\r\n\r\npro.Model.handle = model;\r\nif nargin>2\r\n pro.Model.Name = name;\r\nend\r\n "} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "GSA_FAST_GetSi.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_FAST_GetSi.m", "size": 2821, "source_encoding": "utf_8", "md5": "615e97c23d674dc13c9495ed0581ec33", "text": "%% GSA_FAST_GetSi: calculate the FAST sensitivity indices\r\n% Ref: Cukier, R.I., C.M. Fortuin, K.E. Shuler, A.G. Petschek and J.H.\r\n% Schaibly (1973). Study of the sensitivity of coupled reaction systems to uncertainties in rate coefficients. I Theory. Journal of Chemical Physics \r\n%\r\n% Max number of input variables: 50\r\n%\r\n% Usage:\r\n% Si = GSA_FAST_GetSi(pro)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n%\r\n% Output:\r\n% Si vector of first order sensitivity coefficients\r\n%\r\n% ------------------------------------------------------------------------\r\n% Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008.\r\n% See also\r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 01-05-2011\r\n%\r\n% History:\r\n% 1.0 01-05-2011 First release.\r\n% 06-01-2014 Added comments.\r\n%%\r\n \r\n\r\nfunction Si = GSA_FAST_GetSi(pro)\r\n\r\n% retrieve the number of input variables\r\nk = length(pro.Inputs.pdfs);\r\n\r\n% set the number of discrete intervals for numerical integration of (13)\r\n% increasing this parameter makes more precise the numerical integration\r\nM = 10;\r\n\r\n% read the table of incommensurate frequencies for k variables\r\nW = fnc_FAST_getFreqs(k);\r\n\r\n% set the maximum integer frequency\r\nWmax = W(k);\r\n\r\n% calculate the Nyquist frequency and multiply it for the number of\r\n% intervals\r\nN = 2*M*Wmax+1;\r\n\r\nq = (N-1)/2;\r\n\r\n% set the variable of integration\r\nS = pi/2*(2*(1:N)-N-1)/N;\r\nalpha = W'*S;\r\n\r\n% calculate the new input variables, see (10)\r\nNormedX = 0.5 + asin(sin(alpha'))/pi;\r\n\r\n% retrieve the corresponding inputs for the new input variables. \r\nX = fnc_FAST_getInputs(pro, NormedX);\r\n\r\nY = nan(N,1);\r\n\r\n% calculate the output of the model at input sample points\r\nfor j=1:N\r\n Y(j) = pro.Model.handle(X(j,:));\r\nend\r\n\r\nA = zeros(N,1);\r\nB = zeros(N,1);\r\nN0 = q+1;\r\n\r\n\r\n% ----\r\nf1 = sum( reshape(Y(2:end),2,(N-1)/2) ); \r\nfdiff = -diff( reshape(Y(2:end),2,(N-1)/2) ); \r\n\r\nfor j=1:N\r\n if mod(j,2)==0 % compute the real part of the Fourier coefficients\r\n sj = Y(1) ;\r\n for g=1:(N-1)/2\r\n sj = sj + f1(g)*cos(j*g*pi/N) ;\r\n end\r\n A(j) = sj/N ;\r\n else % compute the imaginary part of the Fourier coefficients\r\n sj = 0 ;\r\n for g=1:(N-1)/2\r\n sj = sj + fdiff(g)*sin(j*g*pi/N) ;\r\n end\r\n B(j) = sj/N ;\r\n end\r\nend\r\n\r\n% compute the total variance by summing the squares of the Fourier\r\n% coefficients\r\nV = 2*(A'*A + B'*B);\r\n\r\n% calculate the sensitivity coefficients for each input variable\r\nfor i=1:k\r\n I = (1:M)*W(i) ;\r\n Si(i) = 2*(A(I)'*A(I) + B(I)'*B(I)) / V;\r\nend\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "GSA_Init_MultiOut_MultiSI.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_Init_MultiOut_MultiSI.m", "size": 2732, "source_encoding": "utf_8", "md5": "2865c383d6cf2056d97f442ab4257a9b", "text": "%% GSA_Init_MultiOut_MultiSI: initialize the variables used in the GSA computation\r\n%\r\n% Usage:\r\n% pro = GSA_Init_MultiOut_MultiSI(pro)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n%\r\n% Output:\r\n% pro updated project structure\r\n%\r\n% ------------------------------------------------------------------------\r\n% Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008.\r\n% See also\r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 15-02-2011\r\n%\r\n% History:\r\n% 1.0 15-01-2011 First release.\r\n% 06-01-2014 Added comments.\r\n%%\r\n\r\nfunction pro = GSA_Init_MultiOut_MultiSI(pro)\r\n\r\n% get two sets of samples of the input variables\r\n[E, T] = fnc_SampleInputs(pro);\r\n\r\n% Store the sample sets in the project structure array\r\npro.SampleSets.E = E;\r\npro.SampleSets.T = T;\r\n\r\n% get the number of input variables\r\nn = length(pro.Inputs.pdfs);\r\n\r\n% set the number of possible combinations of the input variables\r\nL = 2^n;\r\nN = pro.N;\r\n\r\n% Parfor loop requirements\r\nmodel_function_handle = pro.Model.handle;\r\nfE_cell = cell(N,1);\r\n\r\n% Evaluate the model at the sample points in set E\r\nparfor j=1:N\r\n fE_cell{j} = feval(model_function_handle,E(j,:)); % the function output must be a single variable that takes the form of a row vector\r\nend\r\n\r\n% Convert the cell array to a numeric array, and store the simulation \r\n% results in the project structure array\r\npro.GSA.fE = cell2mat(fE_cell); % this will only work if all output generated by the function is numeric\r\n\r\n% Number of output variables\r\noutput = size(pro.GSA.fE,2);\r\n\r\n% calculate the mean value for all the outcome variables\r\npro.GSA.mfE = nanmean(pro.GSA.fE);\r\n\r\npro.GSA.mfE(isnan(pro.GSA.mfE)) = 0;\r\n\r\n% calculate the mean value of the differences from the mean (it will be 0)\r\npro.GSA.f0 = nanmean(pro.GSA.fE - repmat(pro.GSA.mfE,size(pro.GSA.fE,1),1));\r\n\r\n% calculate the total variance of the model outcomes\r\npro.GSA.D = nanmean((pro.GSA.fE - repmat(pro.GSA.mfE,size(pro.GSA.fE,1),1)).^2) - pro.GSA.f0.^2;\r\n\r\n% approximate the error of the mean value\r\npro.GSA.ef0 = 1.96*sqrt(pro.GSA.D./sum(~isnan(pro.GSA.fE - repmat(pro.GSA.mfE,size(pro.GSA.fE,1),1))));\r\n\r\n% prepare the structures for the temporary calculations of sensitivity\r\n% coefficients\r\npro.SampleSets.H = cell(1,L-1);\r\n\r\npro.GSA.fH = cell(1,L-1);\r\n\r\npro.GSA.Dmi = nan(output,L-1);\r\npro.GSA.eDmi = nan(output,L-1);\r\n\r\npro.GSA.Di = nan(output,L-1);\r\npro.GSA.eDi = nan(output,L-1);\r\n\r\npro.GSA.GSI = nan(output,L-1);\r\npro.GSA.eGSI = nan(output,L-1);\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "GSA_GetTotalSy.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_GetTotalSy.m", "size": 2158, "source_encoding": "utf_8", "md5": "eec4d448625695d12ae9bee76f277830", "text": "%% GSA_GetTotalSy: calculate the total sensitivity S of a subset of inputs\r\n%\r\n% Usage:\r\n% [Stot eStot pro] = GSA_GetTotalSy(pro, iset, verbose)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n% iset cell array or array of inputs of the considered set, they can be selected\r\n% by index (1,2,3 ...) or by name ('in1','x',..) or\r\n% mixed\r\n% verbose if not empty, it shows the time (in hours) for\r\n% finishing\r\n%\r\n% Output:\r\n% Stot Total sensitiviy for the considered set\r\n% eStot associated error estimation (at 50%)\r\n% pro updated project structure\r\n%\r\n% ------------------------------------------------------------------------\r\n% Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008.\r\n% See also\r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 15-02-2011\r\n%\r\n% History:\r\n% 1.0 15-04-2011 Added verbose parameter\r\n% 1.0 15-02-2011 First release.\r\n% 06-01-2014 Added comments.\r\n%%\r\n\r\nfunction [Stot eStot pro] = GSA_GetTotalSy(pro, iset, verbose)\r\n% calculate the total global sensitivity coefficient of the variable set \r\n% with index iset\r\n\r\nif ~exist('verbose','var')\r\n verbose = 0;\r\nelse\r\n verbose = ~isempty(verbose) && verbose;\r\nend\r\n\r\n\r\n% get the number of input variables\r\nn = length(pro.Inputs.pdfs);\r\n\r\n% get the indexes corresponding to the variables in iset\r\nindex = fnc_SelectInput(pro, iset);\r\n\r\n% calculate the complementary set of the input indexes\r\ncompli = setdiff(1:n, index);\r\n\r\nif isempty(compli)\r\n Stot = 1;\r\n eStot = 0;\r\nelse\r\n % calculate the global sensitivity coefficient for the complementary\r\n % set of input variables\r\n [S eS pro] = GSA_GetSy(pro, compli, verbose);\r\n % follow by equations in 2.3, calculate the total global sensitivity\r\n % coefficient\r\n Stot = 1 - S;\r\n eStot = eS;\r\nend"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "pdf_Sobol.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pdf_Sobol.m", "size": 587, "source_encoding": "utf_8", "md5": "c70f1059c9562b2e2191a0fc5ebdec89", "text": "%% pdf_Sobol: Foo function for simulate a Sobol Set\r\n%\r\n% Usage:\r\n% pdf_Sobol()\r\n%\r\n% Inputs:\r\n% range vector [min max] range of the random variable\r\n%\r\n% Output:\r\n% range vector [min max] range of the random variable\r\n% ------------------------------------------------------------------------\r\n% See also \r\n% \r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 01-02-2011\r\n%\r\n% History:\r\n% 1.0 01-02-2011 First release.\r\n%%\r\n\r\nfunction range = pdf_Sobol(range)\r\n\r\nrange = range(:)';\r\n% empty function"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "fnc_GetComplementaryInputs.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_GetComplementaryInputs.m", "size": 860, "source_encoding": "utf_8", "md5": "b49201eeff86fb5e3cf106d439e5da76", "text": "%% fnc_GetComplementaryInputs: give the vector of the complementary inputs\r\n%% corresponding to the index i \r\n%\r\n% Usage:\r\n% cii = fnc_GetComplementaryInputs(i, n)\r\n%\r\n% Inputs:\r\n% i scalar index of the inputs (given by fnc_GetIndex)\r\n% n number of total inputs\r\n%\r\n% Output:\r\n% cii array of the corresponding complementary inputs\r\n%\r\n% ------------------------------------------------------------------------\r\n% See also \r\n% fnc_GetIndex \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 30-01-2011\r\n%\r\n% History:\r\n% 1.0 30-01-2011 First release.\r\n% 23-09-2014 Changed: de2bi to bitget\r\n%%\r\n \r\nfunction cii = fnc_GetComplementaryInputs(i, n)\r\n\r\ncii = find(bitget(2^n - i - 1, 1:(n+1)));\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "GSA_GetTotalSy_MultiOut_MultiSI.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_GetTotalSy_MultiOut_MultiSI.m", "size": 2289, "source_encoding": "utf_8", "md5": "cd64bdc0cc001ee5445fa1eeb621e1c2", "text": "%% GSA_GetTotalSy_MultiOut_MultiSI: calculate the total sensitivity S of a subset of inputs\r\n%\r\n% Usage:\r\n% [Stot, eStot, pro] = GSA_GetTotalSy_MultiOut_MultiSI(pro, iset, verbose)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n% iset cell array or array of inputs of the considered set, they can be selected\r\n% by index (1,2,3 ...) or by name ('in1','x',..) or\r\n% mixed\r\n% verbose if not empty, it shows the time (in hours) for\r\n% finishing\r\n%\r\n% Output:\r\n% Stot Total sensitiviy for the considered set\r\n% eStot associated error estimation (at 50%)\r\n% pro updated project structure\r\n%\r\n% ------------------------------------------------------------------------\r\n% Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008.\r\n% See also\r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 15-02-2011\r\n%\r\n% History:\r\n% 1.0 15-04-2011 Added verbose parameter\r\n% 1.0 15-02-2011 First release.\r\n% 06-01-2014 Added comments.\r\n%%\r\n\r\nfunction [Stot, eStot, pro] = GSA_GetTotalSy_MultiOut_MultiSI(pro, iset, verbose)\r\n% calculate the total global sensitivity coefficient of the variable set \r\n% with index iset\r\n\r\nif ~exist('verbose','var')\r\n verbose = 0;\r\nelse\r\n verbose = ~isempty(verbose) && verbose;\r\nend\r\n\r\noutput = size(pro.GSA.fE,2);\r\n\r\n% get the number of input variables\r\nn = length(pro.Inputs.pdfs);\r\n\r\n% get the indexes corresponding to the variables in iset\r\nindex = fnc_SelectInput(pro, iset);\r\n\r\n% calculate the complementary set of the input indexes\r\ncompli = setdiff(1:n, index);\r\n\r\nif isempty(compli)\r\n Stot = ones(output,1);\r\n eStot = zeros(output,1);\r\nelse\r\n % calculate the global sensitivity coefficient for the complementary\r\n % set of input variables\r\n [S, eS, pro] = GSA_GetSy_MultiOut_MultiSI(pro, compli, verbose);\r\n % follow by equations in 2.3, calculate the total global sensitivity\r\n % coefficient\r\n Stot = 1 - S;\r\n eStot = eS;\r\nend"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "pdf_LogNormal.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pdf_LogNormal.m", "size": 984, "source_encoding": "utf_8", "md5": "8896cef0cd5300b0b762f35f13e2305c", "text": "%% pdf_LogNormal: LogNormal Probability Density Function\r\n%\r\n% Usage:\r\n% x = pdf_LogNormal(N, m, s)\r\n%\r\n% Inputs:\r\n% N scalar, number of samples\r\n% m mean of the lognormal distribution \r\n% s standard deviation of the lognormal distribution\r\n%\r\n% Output:\r\n% x vector with the sampled data\r\n% if N==0 -> x = [m - 3*s, m + 3*s]\r\n% \r\n%\r\n% ------------------------------------------------------------------------\r\n% See also \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 28-12-2013\r\n%\r\n% History:\r\n% 1.0 28-12-2013 First release.\r\n%%\r\n\r\nfunction x = pdf_LogNormal(N, m, s)\r\n\r\n\r\nif N==0\r\n x = [m - 3*s, m + 3*s];\r\nelse\r\n mu = log((m^2)/sqrt(s^2+m^2));\r\n sigma = sqrt(log((s^2)/(m^2)+1));\r\n % sample a lognormal distribution function \r\n x = lognrnd(mu,sigma, [N 1]); \r\nend\r\n \r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "GSA_FAST_GetSi_MultiOut.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_FAST_GetSi_MultiOut.m", "size": 3673, "source_encoding": "utf_8", "md5": "65d7e073de6289ba1a61082a24f2539b", "text": "%% GSA_FAST_GetSi: calculate the FAST sensitivity indices for multi-output systems\r\n% Ref: Cukier, R.I., C.M. Fortuin, K.E. Shuler, A.G. Petschek and J.H.\r\n% Schaibly (1973). Study of the sensitivity of coupled reaction systems to uncertainties in rate coefficients. I Theory. Journal of Chemical Physics \r\n%\r\n% Max number of input variables: 50\r\n%\r\n% Usage:\r\n% Si = GSA_FAST_GetSi(pro)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n%\r\n% Output:\r\n% Si vector of first order sensitivity coefficients for\r\n% sets comprising only a single input variable at a\r\n% time\r\n%\r\n% ------------------------------------------------------------------------\r\n% Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008.\r\n% See also\r\n%\r\n% Author : Simon Johnstone-Robertson\r\n%\r\n% Release: 1.0\r\n% Date : 01-06-2015\r\n%\r\n% History:\r\n% 1.0 01-06-2015 First release.\r\n%%\r\n \r\n\r\nfunction [Si,pro] = GSA_FAST_GetSi_MultiOut(pro)\r\n\r\n% retrieve the number of input variables\r\nn = length(pro.Inputs.pdfs);\r\n\r\n% set the number of discrete intervals for numerical integration of (13)\r\n% increasing this parameter makes the numerical integration more precise\r\nM = 10;\r\n\r\n% read the table of incommensurate frequencies for k variables\r\nW = fnc_FAST_getFreqs(n);\r\n\r\n% set the maximum integer frequency\r\nWmax = W(n);\r\n\r\n% calculate the Nyquist frequency and multiply it for the number of\r\n% intervals\r\nN = 2*M*Wmax+1;\r\n\r\nq = (N-1)/2;\r\n\r\n% set the variable of integration\r\nS = pi/2*(2*(1:N)-N-1)/N;\r\nalpha = W'*S;\r\n\r\n% calculate the new input variables, see (10)\r\nNormedX = 0.5 + asin(sin(alpha'))/pi;\r\n\r\n% retrieve the corresponding inputs for the new input variables. \r\nX = fnc_FAST_getInputs(pro, NormedX);\r\n\r\n% Store the sample set in the project structure array\r\npro.SampleSets.X = X;\r\n\r\n% Parfor loop requirements\r\nmodel_function_handle = pro.Model.handle;\r\nfX_cell = cell(N,1);\r\n\r\n% Evaluate the model at the sample points in set X\r\nparfor j=1:N\r\n fX_cell{j} = feval(model_function_handle,X(j,:)); % the function output must be a single variable that takes the form of a row vector\r\nend\r\n\r\n% Convert the cell array to a numeric array\r\nfX = cell2mat(fX_cell); % this will only work if all output generated by the function is numeric\r\n\r\n% Store simulation results in the project structure array\r\npro.GSA.fX = fX;\r\n\r\nA = zeros(N,size(fX,2));\r\nB = zeros(N,size(fX,2));\r\nN0 = q+1;\r\nSi = NaN(size(fX,2),n);\r\n\r\n% Calculate the sensitivity indices of each input variable for all outcome variables\r\nfor output = 1:size(fX,2)\r\n % compute the real part of the Fourier coefficients\r\n for j=2:2:N\r\n A(j,output) = 1/N*(fX(N0,output)+(fX(N0+(1:q),output)+fX(N0-(1:q),output))'* ...\r\n cos(pi*j*(1:q)/N)');\r\n end\r\n\r\n % compute the imaginary part of the Fourier coefficients\r\n for j=1:2:N\r\n B(j,output) = 1/N*(fX(N0+(1:q),output)-fX(N0-(1:q),output))'* ...\r\n sin(pi*j*(1:q)/N)';\r\n end\r\n\r\n % compute the total variance by summing the squares of the Fourier\r\n % coefficients\r\n V = 2*(A(:,output)'*A(:,output)+B(:,output)'*B(:,output));\r\n\r\n % calculate the sensitivity coefficients for each input variable\r\n for i=1:n\r\n Vi=0;\r\n for j=1:M\r\n % numerical integration (13) \r\n Vi = Vi+A(j*W(i),output)^2+B(j*W(i),output)^2;\r\n end\r\n Vi = 2*Vi;\r\n % set the global first order sensitivity coefficient\r\n Si(output,i) = Vi/V;\r\n end\r\nend"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "pdf_Uniform.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pdf_Uniform.m", "size": 978, "source_encoding": "utf_8", "md5": "f659aa1ae3c3b37bac6d0f07679b4dd6", "text": "%% pdf_Uniform: Uniform Probability Density Function\r\n%\r\n% Usage:\r\n% x = pdf_Uniform(N, range, seed)\r\n%\r\n% Inputs:\r\n% N scalar, number of samples\r\n% range vector [min max] range of the random variable\r\n% seed optional, seed for the random number generator\r\n%\r\n% Output:\r\n% x vector with the sampled data\r\n% if N==0 -> x = range \r\n%\r\n% ------------------------------------------------------------------------\r\n% See also \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 28-01-2011\r\n%\r\n% History:\r\n% 1.0 28-01-2011 First release.\r\n%%\r\n\r\nfunction x = pdf_Uniform(N, range, seed)\r\n\r\nif nargin>2\r\n rand('twister',seed);\r\nelse\r\n rand('twister', round(cputime*1000 + 100000*rand));\r\nend\r\n\r\nif N==0\r\n x = range(:)';\r\nelse\r\n % sample an uniform distribution function \r\n x = rand(N,1)*diff(range) + range(1);\r\nend\r\n \r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "GSA_GetSy.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_GetSy.m", "size": 5381, "source_encoding": "utf_8", "md5": "893c7908ac99647e1f267405a09491d7", "text": "%% GSA_GetSy: calculate the Sobol' sensitivity indices\r\n%\r\n% Usage:\r\n% [S eS pro] = GSA_GetSy(pro, iset, verbose)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n% iset cell array or array of inputs of the considered set, they can be selected\r\n% by index (1,2,3 ...) or by name ('in1','x',..) or\r\n% mixed\r\n% verbose if not empty, it shows the time (in hours) for\r\n% finishing\r\n%\r\n% Output:\r\n% S sensitivity coefficient\r\n% eS error of sensitivity coefficient\r\n% pro project structure\r\n%\r\n% ------------------------------------------------------------------------\r\n% Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008.\r\n% See also\r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 15-02-2011\r\n%\r\n% History:\r\n% 1.0 15-04-2011 Added verbose parameter\r\n% 1.0 15-01-2011 First release.\r\n% 06-01-2014 Added comments.\r\n%%\r\n\r\nfunction [S eS pro] = GSA_GetSy(pro, iset, verbose)\r\n\r\n\r\nif ~exist('verbose','var')\r\n verbose = 0;\r\nelse\r\n verbose = ~isempty(verbose) && verbose;\r\nend\r\n\r\n% get the indexes corresponding to the variables in iset\r\nindex = fnc_SelectInput(pro, iset);\r\n\r\nif isempty(index)\r\n S = 0;\r\n eS = 0;\r\nelse\r\n S = 0;\r\n eS = 0;\r\n % number of variables in iset\r\n n = length(index);\r\n % number of possibile combinations for the n variables in iset \r\n L = 2^n;\r\n \r\n if verbose\r\n tic\r\n end\r\n % for all the possible combinations of variables in iset\r\n for i=1:(L-1)\r\n % calculate the indexes of the variables in the i-th combination \r\n ii = fnc_GetInputs(i);\r\n % calculate the real indexes of the variables in the i-th\r\n % combination\r\n si = fnc_GetIndex(index(ii));\r\n % if the part of sensitivity due to the si variables is not\r\n % calculated yet (useful to avoid to calculate again, saving time)\r\n if isnan(pro.GSA.GSI(si))\r\n \r\n %-------\r\n % if the part of variance in ANOVA corresponding to the si \r\n % variables is not calculated yet (useful to avoid to calculate\r\n % again, saving time)\r\n if isnan(pro.GSA.Di(si))\r\n \r\n % get the indexes of the variables in the current\r\n % combination of the variables in the iset\r\n ixi = fnc_GetInputs(si);\r\n s = length(ixi);\r\n l = 2^s - 1;\r\n \r\n %======\r\n if isnan(pro.GSA.Dmi(si))\r\n n = length(pro.Inputs.pdfs);\r\n N = size(pro.SampleSets.E,1);\r\n H = pro.SampleSets.E(:,:);\r\n cii = fnc_GetComplementaryInputs(si, n);\r\n % create the new mixed (E and T) samples to perform the \r\n % quasi-Monte Carlo algorithm (see section 2.4) \r\n H(:,cii) = pro.SampleSets.T(:,cii);\r\n ff = nan(N,1);\r\n \r\n % calculate the elements of the summation reported in\r\n % section 2.4 as I\r\n for j=1:N\r\n ff(j) = pro.GSA.fE(j)*(pro.Model.handle(H(j,:))-pro.GSA.mfE);\r\n end\r\n \r\n % calculate the I value in section 2.4\r\n pro.GSA.Dmi(si) = nanmean(ff);\r\n pro.GSA.eDmi(si) = 0.9945*sqrt((nanmean(ff.^2) - pro.GSA.Dmi(si)^2)/sum(~isnan(ff)));\r\n end\r\n %=======\r\n \r\n Di = pro.GSA.Dmi(si);\r\n eDi = pro.GSA.eDmi(si)^2;\r\n \r\n % compute the summation of the I values for all the\r\n % combinations of the current subset\r\n for j=1:(l-1)\r\n sii = fnc_GetInputs(j);\r\n k = fnc_GetIndex(ixi(sii));\r\n s_r = s - length(sii);\r\n % add the part of variance due to the j-th subset of\r\n % variables or subtract it following eq. (20)\r\n Di = Di + pro.GSA.Dmi(k)*((-1)^s_r);\r\n eDi = eDi + pro.GSA.eDmi(k)^2;\r\n end\r\n \r\n % add/subtract the square of the mean value (here it's 0)\r\n pro.GSA.Di(si) = Di + (pro.GSA.f0^2)*((-1)^s);\r\n pro.GSA.eDi(si) = sqrt(eDi + 2*(pro.GSA.ef0^2));\r\n \r\n \r\n end\r\n %------\r\n % calculate the partial sensitivity coefficient by definition \r\n pro.GSA.GSI(si) = pro.GSA.Di(si)/pro.GSA.D;\r\n pro.GSA.eGSI(si) = pro.GSA.GSI(si)*pro.GSA.eDi(si)/pro.GSA.D;\r\n end\r\n % sum the partial sensitivity coefficients for all the combinations\r\n % of the variables in iset\r\n S = S + pro.GSA.GSI(si);\r\n eS = eS + pro.GSA.eGSI(si);\r\n \r\n if verbose\r\n timelapse = toc;\r\n disp(timelapse*(L-1-i)/i/60/60);\r\n end\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "fnc_SampleInputs.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_SampleInputs.m", "size": 1960, "source_encoding": "utf_8", "md5": "0a48c67ce4e145af19646989a90059ae", "text": "%% fnc_SampleInputs: function that samples the input variables of a project\r\n%\r\n% Usage:\r\n% [Set1 Set2] = fnc_SampleInputs(pro)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n%\r\n% Output:\r\n% Set1, Set2 matrix with the input pdfs sampled\r\n%\r\n% ------------------------------------------------------------------------\r\n% See also \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 28-01-2011\r\n%\r\n% History:\r\n% 1.0 28-01-2011 First release.\r\n%%\r\n\r\nfunction [Set1 Set2] = fnc_SampleInputs(pro)\r\n\r\n% get the number of input variables\r\nninputs = length(pro.Inputs.pdfs);\r\n% prepare two sets of samples\r\nSet1 = nan(pro.N, ninputs);\r\nSet2 = nan(pro.N, ninputs);\r\n\r\nisobol = [];\r\nsobolRange = [];\r\n\r\n% scan all the input variables and select those that have to be sampled\r\n% with a Sobol' set (quasi-random). For the other other variables \r\n% create the stocastic sampling sets by using their pdfs\r\nfor i=1:ninputs\r\n if ~isempty(strfind(func2str(pro.Inputs.pdfs{i}),'pdf_Sobol'))\r\n isobol(end+1) = i;\r\n sobolRange = [sobolRange; pro.Inputs.pdfs{i}()];\r\n else\r\n Set1(:,i) = pro.Inputs.pdfs{i}(pro.N);\r\n Set2(:,i) = pro.Inputs.pdfs{i}(pro.N);\r\n end\r\nend\r\n\r\nif ~isempty(isobol)\r\n % create the Sobol quasi-random sets\r\n ninsobol = length(isobol);\r\n \r\n if exist('sobolset')\r\n % if the Matlab/Toolbox version includes the function get the set\r\n % by using it\r\n S = fnc_getSobolSetMatlab(ninsobol*2, pro.N);\r\n else\r\n % otherwise use the implemented function for Sobol sequences\r\n S = fnc_getSobolSequence(ninsobol*2, pro.N);\r\n end\r\n Min = repmat(sobolRange(:,1)', pro.N, 1);\r\n Max = repmat(sobolRange(:,2)', pro.N, 1); \r\n \r\n % denormalization of the sample points\r\n Set1(:,isobol) = Min + S(:,1:ninsobol).*(Max-Min);\r\n Set2(:,isobol) = Min + S(:,(ninsobol+1):end).*(Max-Min); \r\nend"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "pro_Create.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pro_Create.m", "size": 1220, "source_encoding": "utf_8", "md5": "90e9e94083a92c8114c2a3e7218fbf6d", "text": "%% pro_Create: Create an empty new project structure\r\n%\r\n% Usage:\r\n% pro = pro_Create()\r\n%\r\n% Inputs:\r\n%\r\n% Output:\r\n% pro project structure\r\n% .Inputs.pdfs: cell-array of the model inputs with the pdf handles\r\n% .Inputs.Names: cell-array with the input names \r\n% .N: scalar, number of samples of crude Monte Carlo\r\n% .Model.handle: handle to the model function\r\n% .Model.Name: string name of the model\r\n% \r\n% ------------------------------------------------------------------------\r\n% Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008.\r\n% See also \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 28-01-2011\r\n%\r\n% History:\r\n% 1.0 28-01-2011 First release.\r\n%%\r\n\r\nfunction pro = pro_Create()\r\n\r\npro.Inputs.pdfs = {};\r\npro.Inputs.Names = {};\r\npro.N = 10000;\r\npro.Model.handle = [];\r\npro.Model.Name = [];\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "GSA_Init.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_Init.m", "size": 2123, "source_encoding": "utf_8", "md5": "7d0dad1cfa42510cc7dde92b3e61b394", "text": "%% GSA_Init: initialize the variables used in the GSA computation\r\n%\r\n% Usage:\r\n% pro = GSA_Init(pro)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n%\r\n% Output:\r\n% pro project structure\r\n%\r\n% ------------------------------------------------------------------------\r\n% Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008.\r\n% See also\r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 15-02-2011\r\n%\r\n% History:\r\n% 1.0 15-01-2011 First release.\r\n% 06-01-2014 Added comments.\r\n%%\r\n\r\nfunction pro = GSA_Init(pro)\r\n\r\n% get two sets of samples of the input variables\r\n[E T] = fnc_SampleInputs(pro);\r\n\r\npro.SampleSets.E = E;\r\npro.SampleSets.T = T;\r\n\r\n% get the number of input variables\r\nn = length(pro.Inputs.pdfs);\r\n\r\n% set the number of possible combinations of the input variables\r\nL = 2^n;\r\nN = pro.N;\r\n\r\n% prepare the structure for the evaluation of the model at the sample\r\n% points in the set E\r\npro.GSA.fE = nan(N,1);\r\n\r\n% evaluate the model at the sample points in the set E\r\nfor j=1:N\r\n pro.GSA.fE(j) = pro.Model.handle(pro.SampleSets.E(j,:));\r\nend\r\n\r\n% calculate the mean value of the model outcomes\r\npro.GSA.mfE = nanmean(pro.GSA.fE);\r\n\r\nif isnan(pro.GSA.mfE)\r\n pro.GSA.mfE = 0;\r\nend\r\n\r\n% subtract the mean values from the model outcomes \r\npro.GSA.fE = pro.GSA.fE - pro.GSA.mfE;\r\n\r\n% calculate the mean values (it will be 0)\r\npro.GSA.f0 = nanmean(pro.GSA.fE);\r\n\r\n% calculate the total variance of the model outcomes\r\npro.GSA.D = nanmean(pro.GSA.fE.^2) - pro.GSA.f0^2;\r\n\r\n% approximate the error of the mean value\r\npro.GSA.ef0 = 0.9945*sqrt(pro.GSA.D/sum(~isnan(pro.GSA.fE)));\r\n\r\n% prepare the structures for the temporary calculations of sensitivity\r\n% coefficients\r\npro.GSA.Dmi = nan(1,L-1);\r\npro.GSA.eDmi = nan(1,L-1);\r\n\r\npro.GSA.Di = nan(1,L-1);\r\npro.GSA.eDi = nan(1,L-1);\r\n\r\npro.GSA.GSI = nan(1,L-1);\r\npro.GSA.eGSI = nan(1,L-1);\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "fnc_SelectInput.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_SelectInput.m", "size": 1288, "source_encoding": "utf_8", "md5": "606f98697f0d34b9abcbe755c81cc9c2", "text": "%% fnc_SelectInput: select the input indexes from a generic list\r\n%\r\n% Usage:\r\n% index = fnc_SelectInput(pro, iset)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n% iset cell array or array of inputs of the considered set, they can be selected\r\n% by index (1,2,3 ...) or by name ('in1','x',..) or\r\n% mixed\r\n%\r\n% Output:\r\n% index vector of indexes corresponding to the iset inputs\r\n%\r\n% ------------------------------------------------------------------------\r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 02-02-2011\r\n%\r\n% History:\r\n% 1.0 02-02-2011 First release.\r\n%%\r\n\r\nfunction index = fnc_SelectInput(pro, iset)\r\n \r\nindex = nan(size(iset));\r\n\r\nif iscell(iset)\r\n for i=1:length(iset)\r\n in = iset{i};\r\n if isnumeric(in)\r\n index(i) = floor(in);\r\n else\r\n for j=1:length(pro.Inputs.pdfs)\r\n if strcmp(in,pro.Inputs.Names{j})\r\n index(i) = j;\r\n end\r\n end\r\n end\r\n end\r\nelse\r\n index = iset;\r\nend\r\n\r\nif sum(isnan(index))>0 \r\n disp('Warning: some input is not well defined');\r\nend\r\n\r\nindex = sort(unique(index)); \r\n "} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "pdf_Normal.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pdf_Normal.m", "size": 825, "source_encoding": "utf_8", "md5": "d49ba6d66f3efe7d058216c404a1f51c", "text": "%% pdf_Normal: Normal Probability Density Function\r\n%\r\n% Usage:\r\n% x = pdf_Normal(N, mu, sigma)\r\n%\r\n% Inputs:\r\n% N scalar, number of samples\r\n% mu mean\r\n% sigma standard deviation\r\n%\r\n% Output:\r\n% x vector with the sampled data\r\n% if N==0 -> x = [mu - 3*sigma, mu + 3*sigma] \r\n%\r\n% ------------------------------------------------------------------------\r\n% See also \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 28-12-2013\r\n%\r\n% History:\r\n% 1.0 28-12-2013 First release.\r\n%%\r\n\r\nfunction x = pdf_Normal(N, mu, sigma)\r\n\r\nif N==0\r\n x = [mu - 3*sigma, mu + 3*sigma];\r\nelse\r\n % sample a normal distribution function \r\n x = normrnd(mu,sigma, [N 1]); \r\nend\r\n \r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "SATestModel.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/SATestModel.m", "size": 332, "source_encoding": "utf_8", "md5": "91dbcf8abd962cf881b22a89207e0f4d", "text": "% calculate the real analytical values of the global sensitivity \r\n% coefficients for the model \"Sobol' function\" in TestModel.m \r\nfunction [D Si] = SATestModel(p)\r\n\r\nBi = 1./(3*((1+p).^2));\r\n\r\nD = prod((1+Bi))-1;\r\n\r\nL = 2^length(p);\r\n\r\nSi = nan(1,L-1);\r\n\r\nfor i=1:(L-1)\r\n ii = fnc_GetInputs(i);\r\n Si(i) = prod(Bi(ii))/D;\r\nend"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "fnc_GetIndex.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_GetIndex.m", "size": 622, "source_encoding": "utf_8", "md5": "b74b5906e01446ab95d012835f362269", "text": "%% fnc_GetIndex: give the index of the element in the vector that\r\n%% corresponds to the set of inputs\r\n%\r\n% Usage:\r\n% i = fnc_GetIndex(C)\r\n%\r\n% Inputs:\r\n% C array of input indexes\r\n%\r\n% Output:\r\n% i index in the vector that contains all the variances\r\n%\r\n% ------------------------------------------------------------------------\r\n% See also \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 29-01-2011\r\n%\r\n% History:\r\n% 1.0 29-01-2011 First release.\r\n%%\r\n \r\nfunction i = fnc_GetIndex(C)\r\n\r\ni = sum(2.^(C-1));"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "pro_AddInput.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pro_AddInput.m", "size": 722, "source_encoding": "utf_8", "md5": "b2ea9c1585cfaa09d5707d2f9a28ee4e", "text": "%% pro_AddInput: Add a model input to the project \r\n%\r\n% Usage:\r\n% pro = pro_AddInput(pro, inputpdf, name, analyse)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n% inputpdf reference to a @(N)pdf(N,...)\r\n% name name of the input \r\n%\r\n% Output:\r\n% pro project structure\r\n%\r\n% ------------------------------------------------------------------------\r\n% See also \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 28-01-2011\r\n%\r\n% History:\r\n% 1.0 28-01-2011 First release.\r\n%%\r\n \r\nfunction pro = pro_AddInput(pro, inputpdf, name)\r\n\r\npro.Inputs.pdfs{end+1} = inputpdf;\r\npro.Inputs.Names{end+1} = name;\r\n\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "fnc_FAST_getInputs.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_FAST_getInputs.m", "size": 1359, "source_encoding": "utf_8", "md5": "7170eb2a936173aa963f7daecb42c0b6", "text": "%% fnc_FAST_getInputs: transform the normed input in the real range inputs\r\n%\r\n% Usage:\r\n% X = fnc_FAST_getInputs(pro, NormedX)\r\n%\r\n% Inputs:\r\n% pro project structure\r\n% NormedX normed inputs \r\n%\r\n% Output:\r\n% X inputs in the correct ranges\r\n%\r\n% ------------------------------------------------------------------------\r\n% See also \r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 01-05-2011\r\n% \r\n% History:\r\n% 1.0 01-05-2011 First release.\r\n% 06-01-2014 Added comments.\r\n%%\r\n\r\nfunction X = fnc_FAST_getInputs(pro, NormedX)\r\n\r\n% get the number of the input variables\r\nninputs = length(pro.Inputs.pdfs);\r\n\r\nN = size(NormedX,1);\r\n\r\nRanges = [];\r\n\r\n% retrieve the ranges for all the input variables\r\nfor i=1:ninputs\r\n if ~isempty(strfind(func2str(pro.Inputs.pdfs{i}),'pdf_Sobol'))\r\n Ranges = [Ranges; pro.Inputs.pdfs{i}()];\r\n else\r\n Ranges = [Ranges; pro.Inputs.pdfs{i}(0)];\r\n end\r\nend\r\n\r\nm = zeros(1,size(NormedX,2));min(NormedX);\r\nM = ones(1,size(NormedX,2));max(NormedX);\r\n\r\na = repmat(m,N,1);\r\nb = repmat(M,N,1);\r\n\r\nr = repmat(Ranges(:,1)',N,1);\r\nR = repmat(Ranges(:,2)',N,1);\r\n\r\n% map the normalized input variables into real input variables for the\r\n% model defined in pro\r\nX = (NormedX-a).*(R-r)./(b-a) + r;\r\n\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "fnc_getSobolSetMatlab.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_getSobolSetMatlab.m", "size": 789, "source_encoding": "utf_8", "md5": "98add8889dc4652506337915fefc47ae", "text": "%% fnc_getSobolSetMatlab: give a set of sobol quasi-random by using Matlab \r\n% implemented functions\r\n%\r\n% Usage:\r\n% X = fnc_getSobolSetMatlab(dim, N)\r\n%\r\n% Inputs:\r\n% dim number of variables, the MAX number of variables is 40\r\n% N number of samples\r\n%\r\n% Output:\r\n% X matrix [N x dim] with the quasti-random samples\r\n%\r\n% ------------------------------------------------------------------------\r\n%\r\n%\r\n% Author : Flavio Cannavo'\r\n% e-mail: flavio(dot)cannavo(at)gmail(dot)com\r\n% Release: 1.0\r\n% Date : 07-02-2011\r\n%\r\n% History:\r\n% 1.0 07-02-2011 First release.\r\n%\r\n%\r\n%\r\n\r\n%%\r\n\r\nfunction X = fnc_getSobolSetMatlab(dim, N)\r\n\r\np = sobolset(dim);\r\np = scramble(p,'MatousekAffineOwen');\r\nX = net(p,N);\r\n "} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "TestModel2.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/TestModel2.m", "size": 129, "source_encoding": "utf_8", "md5": "361d787c542bcf214a94be2b91094ddd", "text": "% Ishigami test function (section 3.0.1)\r\nfunction g = TestModel2(x)\r\n\r\ng = sin(x(1))+5*(sin(x(2))^2) + 0.1*(x(3)^4)*sin(x(1));\r\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Random_Walks_in_2D_Lattice.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walks_in_2D_Lattice.m", "size": 2718, "source_encoding": "utf_8", "md5": "a8dd0d3f7dc769ae3b3541802bfb2661", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Computes Random Walks in 2D to compute root-mean-squared\n% distance from starting point.\n%\n%\n% Author: Nick Battista\n% Institution: TCNJ\n% Created: April 8, 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Random_Walks_in_2D_Lattice()\n\nM = 10000; % # of Random Walkers\n\nN = 300; % # of steps for each walker\n\nds = 0.1; % size of step (step-size)\n\nx = 0; % initial x-Position\ny = 0; % initial y-Position\n\n% Perform a Random Walk for Each Walker\nfor i=1:M\n \n % Do Random Walk for i-th random walker\n [xDist,yDist,rSqr] = do_Random_Walk(N,ds,x,y);\n \n % Store displacement distance from starting point (can be + or -)\n xDist_Vec(i) = xDist;\n yDist_Vec(i) = yDist;\n\n % Store squared displacement distance from starting point (must be +)\n rSqr_Vec(i) = rSqr;\n \nend\n\n\n% Compute Avg. of Squared-Displacement Distance from Starting Pt.\nrSqr_Avg = mean(rSqr_Vec);\n\n% Compute root-mean-squared displacement (take sqrt of avg. r-Squared Displacement Vector)\nRMS = sqrt( rSqr_Avg );\n\n\n% Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt.\nfprintf('Avg. Squared-Displacement: %2.4f\\n',RMS);\nfprintf('Theory Says Avg. Displacement = %2.4f\\n',sqrt(N)*ds);\nfprintf('Error: %2.4f\\n\\n\\n',abs( RMS - sqrt(N)*ds));\n\n% Plot ending point (x,y) for each Random Walk\nplot(xDist_Vec,yDist_Vec,'b.','MarkerSize',10); hold on;\nplot(0,0,'r.','MarkerSize',60); hold on;\nxlabel('x');\nylabel('y');\ntitle('2D Random Walks Final Position');\n%axis square;\naxis([-5 5 -5 5]);\nset(gca,'FontSize',18);\ngrid on;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: perform Random Walk starting at \"x,y\" and ending after \"N\" steps\n%\n% Inputs: x,y <-- starting point for x,y\n% N <-- length of Random Walk\n% ds <-- length of a step \n%\n% Outputs:\n% xDist: displacement distance from starting point (can be + or -)\n% xSqr: squared displacement distance from starting point (must be +)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xDist,yDist,rSqr] = do_Random_Walk(N,ds,x,y)\n\n\n% Perform the Random Walk\nfor i=1:N\n \n coin = rand(1); \n \n if (coin <= 0.25)\n \n x = x - ds;\n \n elseif (coin <= 0.5)\n \n x = x + ds;\n \n elseif (coin <=0.75)\n \n y = y - ds;\n \n else\n \n y = y + ds;\n end\n \nend\n\n% Store final positions of (x,y) for Random Walker \nxDist = x;\nyDist = y;\n\n% Store squared displacement distance from origin \nrSqr = x^2 + y^2;\n\n\n\n\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Diffusion_2D.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Diffusion_2D.m", "size": 6405, "source_encoding": "utf_8", "md5": "bf1c5c526159fdbe6422092a07528cf6", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: solves Diffusion Equation in 2D and compares to Random Walkers\n% in 2D on a lattice\n%\n%\n% Author: Nick Battista\n% Institution: TCNJ\n% Created: April 8, 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Diffusion_2D()\n\n\nL=10; % size of domain [0,L]x[0,L]\n\nds = 0.05; % ds = dx = dy (step-size)\n\nM = 250; % # of random walkers\n\ndt = 1e-3; % time-step size\n\nx0 = L/2; % Initial x-Position of Random Walkers\n\ny0 = L/2; % Initial y-Position of Random Walkers\n\ndumpInt = 50; % storing dump interval\n\nTFinal = 5; % final simulation time\n\nD = ( ds^2 + ds^2 ) / (5*dt); % diffusion coefficient\n\n%\n% Solve Diffusion Equation\nfprintf('\\n\\n...Solving 2D Diffusion PDE...\\n\\n');\n[U_store,X,Y,numStored] = please_Solve_Diffusion(L,ds,dt,TFinal,D,dumpInt,M);\nfprintf('\\n\\nFinished solving 2D Diffusion PDE...\\n');\n\npause();\n\n%\n% Perform Random Walks\nfprintf('\\n\\n\\n...Computing Random Walks...\\n\\n');\n[xMat,yMat,RMS_Sims,RMS_Theory] = please_Perform_Random_Walk(x0,y0,ds,dt,dumpInt,TFinal,M);\n\n\n\n%\n% Compute Circles of where RMS-Distance is for Simulation\nNpts = 100;\nfor j=2:length(RMS_Sims)\n xC(:,j) = ( -RMS_Sims(j):2*RMS_Sims(j)/Npts:RMS_Sims(j) )';\n yC_T(:,j) = sqrt( RMS_Sims(j)^2 - xC(:,j).^2 );\n \n xC(:,j) = xC(:,j);\n yC_T(:,j) = yC_T(:,j);\nend\n\n\n%\n% Plot Solutions\nfor j=1:numStored\n\n uD = U_store(:,:,j);\n \n figure(1)\n \n % Plot Contours for Diffusion and RMS-Simulation Distance Contour\n subplot(1,3,1)\n contourf(X,Y,uD,4,'ShowText','on'); hold on;\n if j==1\n plot(x0,y0,'r.','MarkerSize',20); hold on;\n else\n plot(xC(:,j)+x0,yC_T(:,j)+y0,'r-','LineWidth',6); hold on;\n plot(xC(:,j)+x0,-yC_T(:,j)+y0,'r-','LineWidth',6); hold on;\n end\n axis square;\n \n % Plot Surface in 3D for Diffusion\n subplot(1,3,2)\n surf(X(1,:),Y(:,1),uD); \n %surf(X,Y,uD,'EdgeColor', 'None', 'facecolor', 'interp'); view(2);\n %axis square;\n \n % Plot Contours for Diffusion and Random Walkers after same amount of time-steps\n subplot(1,3,3)\n contourf(X,Y,uD,4); hold on;\n plot(xMat(:,j),yMat(:,j),'r.','MarkerSize',20); hold on;\n axis square;\n \n % For Class Demonstration\n if j==1\n pause();\n else\n pause(0.5);\n end\n clf;\n \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: perform Random Walks!\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xMat,yMat,RMS_SimVec,RMS_Theory] = please_Perform_Random_Walk(x0,y0,ds,dt,dumpInt,TFinal,M)\n\nnumSteps = TFinal / dt; % # of steps for Random Walk\n\nct = 1; % counter for storing values\nxVec = x0*ones(M,1); % initial starting places in x-Position\nyVec = y0*ones(M,1); % initial starting places in y-Position\nxMat = zeros(M,1); % initialize storage\nyMat = xMat; % initialize storage\nxMat(:,ct) = xVec; % store initial starting places in x-Position\nyMat(:,ct) = yVec; % store initial starting places in x-Position\nRMS_SimVec(ct) = 0;\nRMS_Theory(ct) = 0;\n\nfor i=1:numSteps\n \n rand_Vec = rand(M);\n \n for j=1:M\n \n % Random Walker Has Choice to Stay in Same Place w/ equal probabiltiy\n if rand_Vec(j) <= 0.20\n xVec(j) = xVec(j) + ds;\n elseif rand_Vec(j) <= 0.4\n xVec(j) = xVec(j) - ds;\n elseif rand_Vec(j) <= 0.6\n yVec(j) = yVec(j) + ds;\n elseif rand_Vec(j) <= 0.8\n yVec(j) = yVec(j) - ds;\n end\n \n end\n \n if mod(i,dumpInt)==0\n ct = ct + 1;\n xMat(:,ct) = xVec;\n yMat(:,ct) = yVec;\n aux = (xVec-x0).^2 + (yVec-y0).^2;\n RMS_SimVec(ct) = sqrt( mean( aux ) );\n RMS_Theory(ct) = sqrt(i)*ds;\n \n fprintf('%d of %d Steps in Random Walk\\n',i,numSteps);\n \n end\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: solve Diffusion PDE in 2D and returns solution and mesh grid\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [U_store,X,Y,ct] = please_Solve_Diffusion(L,ds,dt,TFinal,D,dumpInt,M)\n\n% \n% Give Initial Background Grid for Diffusion\n[U,X,Y] = give_Me_Initial_Condition(L,ds,M);\n\n%\n% Solve Diffusion Equation\nct = 1; % counter for storage\nU_store(:,:,ct) = U; % Store initial configuration\nt = 0; % time in simulatio\nn = 0; % number of total time-steps\n%\nwhile t 0.5\n \n x = x - ds;\n \n else\n \n x = x + ds;\n end\n \nend\n\nxDist = x;\n\nxSqr = x^2;\n\n\n\n\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Random_Walks_in_2D.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walks_in_2D.m", "size": 2452, "source_encoding": "utf_8", "md5": "b9b682be6e347f675e29b4a3d65b7c76", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Computes Random Walks in 2D to compute root-mean-squared\n% distance from starting point.\n%\n%\n% Author: Nick Battista\n% Institution: TCNJ\n% Created: April 8, 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Random_Walks_in_2D()\n\nM = 10000; % # of Random Walkers\n\nN = 50; % # of steps for each walker\n\nds = 0.1; % size of step (step-size)\n\nx = 0; % initial x-Position\ny = 0; % initial y-Position\n\n% Perform a Random Walk for Each Walker\nfor i=1:M\n \n % Do Random Walk for i-th random walker\n [xFinal,yFinal,rSqr] = do_Random_Walk(N,ds,x,y);\n \n % Store x,y-Final positions\n xFinal_Vec(i) = xFinal;\n yFinal_Vec(i) = yFinal;\n \n % Store squared displacement distance from starting point (must be +)\n rSqr_Vec(i) = rSqr;\n \nend\n\n\n% Compute Avg. of Squared-Displacement Distance from Starting Pt.\nRMS = sqrt( mean( rSqr_Vec ) );\n\n\n% Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt.\nfprintf('Avg. Squared-Displacement: %2.4f\\n',RMS);\nfprintf('Theory Says Avg. Displacement = %2.4f\\n',sqrt(N)*ds);\nfprintf('Error: %2.4f\\n\\n\\n',abs(RMS - sqrt(N)*ds));\n\n% Plot ending point (x,y) for each Random Walk\nfigure(2)\nplot(xFinal_Vec,yFinal_Vec,'b.','MarkerSize',10); hold on;\nplot(0,0,'r.','MarkerSize',50); hold on;\nxlabel('x');\nylabel('y');\ntitle('2D Random Walks Final Position');\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: perform Random Walk starting at \"x,y\" and ending after \"N\" steps\n%\n% Inputs: x,y <-- starting point for x,y\n% N <-- length of Random Walk\n% ds <-- length of a step \n%\n% Outputs:\n% xDist: displacement distance from starting point (can be + or -)\n% xSqr: squared displacement distance from starting point (must be +)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xFinal,yFinal,rSqr] = do_Random_Walk(N,ds,x,y)\n\n\n% Perform the Random Walk\nfor i=1:N\n \n % Get random angle between 0 and 2*pi\n ang = 2*pi*rand(1); \n \n % Move in x-direction (based on trig relations)\n x = x + ds*cos(ang);\n \n % Move in y-direction (based on trig relations)\n y = y + ds*sin(ang);\n \nend\n\n% Define final positions of (x,y) for output\nxFinal = x;\nyFinal = y;\n\n% Save r^2 value\nrSqr = x^2 + y^2;\n\n\n\n\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "compute_Random_Walks_2D_Lattice_Convergence.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walker_Convergence/compute_Random_Walks_2D_Lattice_Convergence.m", "size": 3765, "source_encoding": "utf_8", "md5": "ac300c7f03a5c71f66adff56efeb17c9", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Computes error btwn simulation and theory for different numbers\n% of random walkers in 2D. As # of RWs goes up, error goes down.\n%\n% Author: Nick Battista\n% Institution: TCNJ\n% Created: April 8, 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction compute_Random_Walks_2D_Lattice_Convergence()\n\n% Vector of all #'s of Random Walker Trials to Do\nMVec = [10:10:90 100:100:900 1e3:1e3:9e3 1e4:1e4:9e4 1e5:1e5:5e5];\n\nfor i=1:length(MVec)\n \n % Define # of Random Walkers for Trial\n M = MVec(i);\n \n % Print Simulation Case Info to Screen\n fprintf('Simulation Case w/ M=%d\\n',M);\n \n % Call Random Walk Function that Returns Error btwn theory and simulation for RMS\n err = Random_Walks_in_2D_Lattice(M);\n \n % Store RMS Error for Simulation with M random walkers\n errVec(i) = err;\n \nend\n\nfigure(2)\nlw=4;\nms=24;\nloglog(MVec,errVec,'-.','MarkerSize',ms,'LineWidth',lw);\nxlabel('# of Random Walkers');\nylabel('RMS Error');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: perform Random Walk with M-Random Walkers to compute avg. \n% error in RMS\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction errRMS = Random_Walks_in_2D_Lattice(M)\n\n%M = 10000; % # of Random Walkers\n\nN = 25; % # of steps for each walker\n\nds = 0.1; % size of step (step-size)\n\nx = 0; % initial x-Position\ny = 0; % initial y-Position\n\n% Perform a Random Walk for Each Walker\nfor i=1:M\n \n % Do Random Walk for i-th random walker\n [xDist,yDist,rSqr] = do_Random_Walk(N,ds,x,y);\n \n % Store displacement distance from starting point (can be + or -)\n xDist_Vec(i) = xDist;\n yDist_Vec(i) = yDist;\n\n % Store squared displacement distance from starting point (must be +)\n rSqr_Vec(i) = rSqr;\n \nend\n\n\n% Compute Avg. of Squared-Displacement Distance from Starting Pt.\nrSqr_Avg = mean(rSqr_Vec);\n\n% Compute root-mean-squared displacement (take sqrt of avg. r-Squared Displacement Vector)\nRMS_Avg = sqrt( rSqr_Avg );\n\n% Store RMS Error between average RMS from simulation and theory\nerrRMS = abs( RMS_Avg - sqrt(N)*ds);\n\n% Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt.\n% fprintf('Avg. Squared-Displacement: %2.4f\\n',RMS_Avg);\n% fprintf('Theory Says Avg. Displacement = %2.4f\\n',sqrt(N)*ds);\n% fprintf('Error: %2.4f\\n\\n\\n',errRMS);\n\n% Plot ending point (x,y) for each Random Walk\n% plot(xDist_Vec,yDist_Vec,'b.','MarkerSize',10); hold on;\n% plot(0,0,'r.','MarkerSize',50); hold on;\n% xlabel('x');\n% ylabel('y');\n% title('2D Random Walks Final Position');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: perform Random Walk starting at \"x,y\" and ending after \"N\" steps\n%\n% Inputs: x,y <-- starting point for x,y\n% N <-- length of Random Walk\n% ds <-- length of a step \n%\n% Outputs:\n% xDist: displacement distance from starting point (can be + or -)\n% xSqr: squared displacement distance from starting point (must be +)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xDist,yDist,rSqr] = do_Random_Walk(N,ds,x,y)\n\n\n% Perform the Random Walk\nfor i=1:N\n \n coin = rand(1); \n \n if (coin <= 0.25)\n \n x = x - ds;\n \n elseif (coin <= 0.5)\n \n x = x + ds;\n \n elseif (coin <=0.75)\n \n y = y - ds;\n \n else\n \n y = y + ds;\n end\n \nend\n\n% Store final positions of (x,y) for Random Walker \nxDist = x;\nyDist = y;\n\n% Store squared displacement distance from origin \nrSqr = x^2 + y^2;\n\n\n\n\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "compute_Random_Walks_2D_Convergence.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walker_Convergence/compute_Random_Walks_2D_Convergence.m", "size": 3553, "source_encoding": "utf_8", "md5": "596fbde1f0dba70b0fff6afa4fe5e5d1", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Computes error btwn simulation and theory for different numbers\n% of random walkers in 2D. As # of RWs goes up, error goes down.\n%\n% Author: Nick Battista\n% Institution: TCNJ\n% Created: April 8, 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction compute_Random_Walks_2D_Convergence()\n\n% Vector of all #'s of Random Walker Trials to Do\nMVec = [10:10:90 100:100:900 1e3:1e3:9e3 1e4:1e4:9e4 1e5:1e5:5e5];\n\nfor i=1:length(MVec)\n \n % Define # of Random Walkers for Trial\n M = MVec(i);\n \n % Print Simulation Case Info to Screen\n fprintf('Simulation Case w/ M=%d\\n',M);\n \n % Call Random Walk Function that Returns Error btwn theory and simulation for RMS\n err = Random_Walks_in_2D(M);\n \n % Store RMS Error for Simulation with M random walkers\n errVec(i) = err;\n \nend\n\nfigure(2)\nlw=4;\nms=24;\nloglog(MVec,errVec,'-.','MarkerSize',ms,'LineWidth',lw);\nxlabel('# of Random Walkers');\nylabel('RMS Error');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: perform Random Walk with M-Random Walkers to compute avg. \n% error in RMS\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction errRMS = Random_Walks_in_2D(M)\n\n%M = 10000; % # of Random Walkers\n\nN = 25; % # of steps for each walker\n\nds = 0.1; % size of step (step-size)\n\nx = 0; % initial x-Position\ny = 0; % initial y-Position\n\n% Perform a Random Walk for Each Walker\nfor i=1:M\n \n % Do Random Walk for i-th random walker\n [xFinal,yFinal,rSqr] = do_Random_Walk(N,ds,x,y);\n \n % Store x,y-Final positions\n xFinal_Vec(i) = xFinal;\n yFinal_Vec(i) = yFinal;\n \n % Store squared displacement distance from starting point (must be +)\n rSqr_Vec(i) = rSqr;\n \nend\n\n\n% Compute Avg. of Squared-Displacement Distance from Starting Pt.\nRMS_Avg = sqrt( mean( rSqr_Vec ) );\n\n% Store RMS Error between average RMS from simulation and theory\nerrRMS = abs( RMS_Avg - sqrt(N)*ds);\n\n% Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt.\n% fprintf('Avg. Squared-Displacement: %2.4f\\n',RMS_Avg);\n% fprintf('Theory Says Avg. Displacement = %2.4f\\n',sqrt(N)*ds);\n% fprintf('Error: %2.4f\\n\\n\\n',errRMS);\n\n% Plot ending point (x,y) for each Random Walk\n% figure(2)\n% plot(xFinal_Vec,yFinal_Vec,'b.','MarkerSize',10); hold on;\n% plot(0,0,'r.','MarkerSize',50); hold on;\n% xlabel('x');\n% ylabel('y');\n% title('2D Random Walks Final Position');\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: perform Random Walk starting at \"x,y\" and ending after \"N\" steps\n%\n% Inputs: x,y <-- starting point for x,y\n% N <-- length of Random Walk\n% ds <-- length of a step \n%\n% Outputs:\n% xDist: displacement distance from starting point (can be + or -)\n% xSqr: squared displacement distance from starting point (must be +)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xFinal,yFinal,rSqr] = do_Random_Walk(N,ds,x,y)\n\n\n% Perform the Random Walk\nfor i=1:N\n \n % Get random angle between 0 and 2*pi\n ang = 2*pi*rand(1); \n \n % Move in x-direction (based on trig relations)\n x = x + ds*cos(ang);\n \n % Move in y-direction (based on trig relations)\n y = y + ds*sin(ang);\n \nend\n\n% Define final positions of (x,y) for output\nxFinal = x;\nyFinal = y;\n\n% Save r^2 value\nrSqr = x^2 + y^2;\n\n\n\n\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "compute_Random_Walks_1D_Convergence.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walker_Convergence/compute_Random_Walks_1D_Convergence.m", "size": 3601, "source_encoding": "utf_8", "md5": "d6a7d4a9214e792641f99db6c5944701", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Computes error btwn simulation and theory for different numbers\n% of random walkers in 1D. As # of RWs goes up, error goes down.\n%\n% Author: Nick Battista\n% Institution: TCNJ\n% Created: April 8, 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction compute_Random_Walks_1D_Convergence()\n\n% Vector of all #'s of Random Walker Trials to Do\nMVec = [10:10:90 100:100:900 1e3:1e3:9e3 1e4:1e4:9e4 1e5:1e5:5e5];\n\nfor i=1:length(MVec)\n \n % Define # of Random Walkers for Trial\n M = MVec(i);\n \n % Print Simulation Case Info to Screen\n fprintf('Simulation Case w/ M=%d\\n',M);\n \n % Call Random Walk Function that Returns Error btwn theory and simulation for RMS\n err = Random_Walks_in_1D(M);\n \n % Store RMS Error for Simulation with M random walkers\n errVec(i) = err;\n \nend\n\nfigure(2)\nlw=4;\nms=24;\nloglog(MVec,errVec,'-.','MarkerSize',ms,'LineWidth',lw);\nxlabel('# of Random Walkers');\nylabel('RMS Error');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: perform Random Walk with M-Random Walkers to compute avg. \n% error in RMS\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction errRMS = Random_Walks_in_1D(M)\n\n%M = 1000; % # of Random Walkers\n\nN = 20; % # of steps for each walker\n\ndx = 0.1; % size of step (step-size)\n\nx = 0; % initial position\n\n% Perform a Random Walk for Each Walker\nfor i=1:M\n \n % Do Random Walk for i-th random walker\n [xDist,xSqr] = do_Random_Walk(N,dx,x);\n \n % Store displacement distance from starting point (can be + or -)\n xDist_Vec(i) = xDist;\n \n % Store squared displacement distance from starting point (must be +)\n xSqr_Vec(i) = xSqr;\n \nend\n\n% Compute Avg. of Displacement Distances from Starting Pt.\nxDist_Avg = mean(xDist_Vec);\n\n% Compute Avg. of Squared-Displacement Distance from Starting Pt.\nRMS_Avg = sqrt(mean(xSqr_Vec));\n\n% Store RMS Error between average RMS from simulation and theory\nerrRMS = abs( RMS_Avg - sqrt(N)*dx);\n\n% Print Information to Screen for Avg. Displacement From Starting Pt.\n%fprintf('\\n\\nAvg. Displacement: %2.4f\\n',xDist_Avg);\n%fprintf('Theory Says Avg. Displacement = 0\\n');\n%fprintf('Error: %2.4f\\n\\n\\n',abs(xDist_Avg));\n\n% Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt.\n%fprintf('Avg. Squared-Displacement: %2.4f\\n',RMS_Avg);\n%fprintf('Theory Says Avg. Displacement = %2.4f\\n',sqrt(N)*dx);\n%fprintf('Error: %2.4f\\n\\n\\n',errRMS);\n\n\n% Plot ending point (x,y) for each Random Walk\n%plot(0,0,'r.','MarkerSize',50); hold on;\n%plot(xDist_Vec,zeros(length(xDist_Vec)),'b.','MarkerSize',10); hold on;\n%xlabel('x');\n%ylabel('y');\n%title('1D Random Walks Final Position');\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: perform Random Walk starting at \"x\" and ending after \"N\" steps\n%\n% Inputs: x <-- starting point\n% N <-- length of Random Walk\n% dx <-- length of a step \n%\n% Outputs:\n% xDist: displacement distance from starting point (can be + or -)\n% xSqr: squared displacement distance from starting point (must be +)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [xDist,xSqr] = do_Random_Walk(N,dx,x)\n\n\n% Perform the Random Walk\nfor i=1:N\n \n coin = rand(1); \n \n if coin > 0.5\n \n x = x - dx;\n \n else\n \n x = x + dx;\n end\n \nend\n\nxDist = x;\n\nxSqr = x^2;\n\n\n\n\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "go_Go_Zombie_Model.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Discrete_Dynamical_Systems/go_Go_Zombie_Model.m", "size": 2590, "source_encoding": "utf_8", "md5": "bf0679b2de0eff1d2feb30b51765dc86", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Models a Zombie outbreak using Dynamical Systems\n%\n% Author: Nick Battista\n% Created: Jan. 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction go_Go_Zombie_Model(TFinal)\n\n%\n% Time Information / Initialization\n%TFinal = 100; % Simulation runs until TFinal\ndt = 1e-3; % Time-Step\nTimeVec = 0:dt:TFinal; % TimeVector = (1,2,3,...,TFinal+1)\nH = zeros( TFinal, 1); % Initializing storage for populations\nP = H;\nZ = H;\n\n%\n% Human birth and death rates\n%\nb1 = 0.000040; % Human birth rate (2016)\nd1 = 0.000019; % Natural human death rate (2016)\n\n%\n% Human-Zombie Interaction Parameters\n%\nbeta1 = 0.5; % Human-Zombie Interaction 'Probability' (human -> zombie)\nbeta2 = 0.05; % Human-Zombie Interaction 'Probability' (human dies, no turning)\nbeta3 = 0.05; % Human-Zombie Interaction 'Probability' (human kills pre-Zombie)\nbeta4 = 0.025; % Human-Zombie Interaction 'Probability' (human kills zombie)\n\n%\n% pre-Zombie residence time before turning full zombie\n%\nc1 = 0.1; % Lag time before pre-Zombie (post-Human) turns Zombie\n\n%\n% Zombie death rates\n%\nd2 = d1*3; % Zombie \"natural\" death rate\n\n\n%\n% Initial \"Populations\" (population %)\n%\nH(1) = 0.99;\nP(1) = 0;\nZ(1) = 0.01;\n\n\nfor n=1:1:TFinal/dt % TFinal b/c of the way we are array indexing (index 1 = initial time)\n \n % How Human Population Changes\n H(n+1) = H(n) + dt * ( (b1-d1)*H(n) - beta1*H(n)*Z(n) - beta2*H(n)*Z(n) );\n \n % How pre-Zombie Population Changes\n P(n+1) = P(n) + dt * ( - c1*P(n) + beta1*H(n)*Z(n) - beta3*H(n)*P(n) );\n \n % How Zombie Population Changes\n Z(n+1) = Z(n) + dt * ( c1*P(n) - beta4*H(n)*Z(n) - d2*Z(n) );\n \nend\n\n\n%\n% PRINT SIMULATION INFO TO SCREEN\n%\nfprintf('\\n\\n --- ZOMBIE MODEL RESULTS --- \\n\\n');\nfprintf('Human Pop. Percentage: %.3f\\n\\n', 100*H(end) );\nfprintf('pre-Zombie Pop. Percentage: %.3f\\n\\n', 100*P(end) );\nfprintf('Zombie Pop. Percentage: %.3f\\n\\n', 100*Z(end) );\nfprintf('Percent Loss (not humans, pre-Z, or Zombies): %.3f\\n\\n\\n', 100*(1-H(end)-P(end)-Z(end) ) );\n\n\n%\n% FIGURE 1: POPULATIONS VS. TIME\n%\nms = 30; % MarkerSize for plotting\nlw = 4; % LineWidth for plotting\nfs = 18;\n%\nplot(TimeVec,H,'b.-','MarkerSize',ms,'LineWidth',lw); hold on; \nplot(TimeVec,P,'k.-','MarkerSize',ms,'LineWidth',lw); hold on;\nplot(TimeVec,Z,'r.-','MarkerSize',ms,'LineWidth',lw); hold on;\nxlabel('Time (hours)');\nylabel('Population %'); \nleg = legend('Humans','pre-Zombies','Zombies');\nset(gca,'FontSize',fs);\nset(leg,'FontSize',fs);\n\n\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Population_Ecology.m", "ext": ".m", "path": "Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Discrete_Dynamical_Systems/Ecology/Population_Ecology.m", "size": 1858, "source_encoding": "utf_8", "md5": "34aa6f090b803ab05f6a29af3c707ea3", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Solves Discrete Dynamical Systems in Population Ecology\n%\n% Author: Nick Battista\n% Institution: TCNJ\n% Created: March 2019\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction Population_Ecology(TFinal)\n\n%\n% Clears any previous plots that are open in MATLAB\nclf;\n\n%\n% Time Information / Initialization\n%\n%TFinal = 100; % Simulation runs until TFinal\nTimeVec = 1:1:TFinal; % TimeVector = (1,2,3,...,TFinal+1)\n\n\n%\n% Initializing storage for populations\n%\nX = zeros( TFinal, 1); % Initializing storage for population X\nY = X; % Initializing storage for population Y\n\n\n%\n% Initial Values\n%\nX(1) = 25;\nY(1) = 2;\n\n\n%\n% Parameter Values\n%\nk = 0.75; % growth rate\nC = 250; % carrying capacity\nb1 = 0.008; % death parameter for prey from predator interactions\nb2 = 0.00825; % growth parameter for predator from prey interactions\n\n%\n% For-loop that iteratively solves the discrete dynamical system\n%\nfor n=1:TFinal\n \n X(n+1) = X(n) + k*X(n)*( 1 - X(n)/C ) - b1*X(n)*Y(n); \n Y(n+1) = b2*X(n)*Y(n);\n \nend\n\n%\n% Plot Attributes\n%\nlw = 4; % LineWidth (how thick the lines should be)\nms = 25; % MarkerSize (how big the plot points should be)\nfs = 18; % FontSize (how big the font should be for labels)\n\n%\n% PLOT 1: Populations vs. Time\n%\nfigure(1)\nplot(TimeVec,X(1:end-1),'b.-','LineWidth',lw,'MarkerSize',ms); hold on;\nplot(TimeVec,Y(1:end-1),'r.-','LineWidth',lw,'MarkerSize',ms); hold on;\nxlabel('Time');\nylabel('Population');\nleg = legend('Prey','Predator');\nset(gca,'FontSize',fs);\nset(leg,'FontSize',fs);\n\n\n%\n% PLOT 2: Phase Plane Plot\n%\nfigure(2)\nplot(X(200:end),Y(200:end),'b.-','LineWidth',lw,'MarkerSize',ms); hold on;\nxlabel('Prey Population');\nylabel('Predator Population');\nset(gca,'FontSize',fs);\n"} +{"plateform": "github", "repo_name": "nickabattista/Ark-master", "name": "Eulers.m", "ext": ".m", "path": "Ark-master/Euler_Method/Eulers.m", "size": 9009, "source_encoding": "utf_8", "md5": "bd348d60b6ed1b254925695e7b547e95", "text": "function Eulers()\n\n%Author: Nicholas Battista\n%Created: August 12, 2014\n%Date of Last Revision: August 23, 2014\n%\n%This function solves the following ODE:\n%dy/dt = f(t,y)\n%y(0) = y0\n%using Eulers Method. It then does a convergence study for various h values. \n%\n%Note: It performs the convergence study for the known ODEs,\n%\n%dy/dt = y, with y(0) = 1; w/ exact solution is: y(t) = e^t\n%and\n%dy/dt = 2*pi*cos(2*pi*t), w/ y(0)=1 w/ exact solution y(t) = sin(2*pi*t)+1\n\nprint_info();\n\ny0 = 1; %Initial Condition, y(0)=y0\n\ntS = 0; %Starting Time for Simulation\ntE = 2.0; %End Time for Simulation\n\n%Makes vector of time iterates for convergence study\nNVec = give_Me_NumberOfGridPts(); \n\n%Allocate memory to storage vectors\nhVec = zeros(1,length(NVec));\nerr_h = hVec;\nY_SOL = zeros(1e5,5);\nct = 1;\n\n%For loop for convergence study\nfor j=1:length(NVec)\n \n %Begin counting time for integration\n tic\n \n N = NVec(j); %# of time-steps\n h = (tE-tS)/N; %time-step\n hVec(j) = h; %stores time-step\n \n time=tS:h:tE; \n yFOR = zeros(1,length(time));\n yFOR2= yFOR;\n \n %Performs the Euler Method Time-Stepping Scheme\n for i=1:length(time)\n \n if i==1\n yFOR(i) = y0;\n yFOR2(i)= y0;\n else\n yFOR(i) = yFOR(i-1) + h*f(time(i-1),yFOR(i-1),1);\n yFOR2(i)= yFOR2(i-1)+ h*f(time(i-1),yFOR(i-1),2);\n end\n \n end\n\n %Gives Error at each time-step\n err = compute_Error(time,yFOR,y0,1);\n err2= compute_Error(time,yFOR2,y0,2);\n\n %Computes Inf-Norm of Error\n err_h(j) = max( abs(err) );\n err_h2(j) = max( abs(err2) );\n\n %Stores time for computation\n timeV(j) = toc/2;\n \n %Stores numerical solution / info for plotting soln.\n if ( ( (mod(j,3)==0) && (j<10) ) || (j==11) || (j==14) )\n Y_SOL(1:N+1,ct) = yFOR;\n Y_SOL2(1:N+1,ct)= yFOR2;\n hVecPlot(ct) = h;\n NVecPlot(ct) = N;\n errMat(1:N+1,ct) = err;\n errMat2(1:N+1,ct) = err2;\n ct = ct+1;\n end\n clear h; \n clear time;\n clear yFOR;\n\nend %Ends looping over different h-values\n\n%Plot Solution vs. Exact\nplot_Solution(Y_SOL,Y_SOL2,NVecPlot,hVecPlot,tE,tS,y0,errMat,errMat2)\n\n\n%Plots Convergence Study\nplot_Convergence_Study(hVec,err_h,err_h2);\n\n%Plots time study\nplot_Time_Study(NVec,timeV)\n\nfprintf('\\nWelp, thats it folks!\\n\\n');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function that plots the numerical soln. vs. exact solution for different\n% time-step sizes, h, as well as for two different ODEs.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Solution(Y_Sol,Y_Sol2,NVec2,hVec2,tE,tS,y0,errMat,errMat2)\n\nfprintf('\\nplotting numerical vs. exact solutions...\\n\\n');\n\nfigure(1)\nsubplot(2,2,1);\nstrColor = {'k-','-','m-','g-','c-'};\nfor i=1:length(Y_Sol(1,:))\n h = hVec2(i);\n hVec{i} = strcat('h = ',num2str(h));\n N= NVec2(i);\n t = tS:h:tE;\n str = strColor{i};\n plot(t,Y_Sol(1:N+1,i),str,'LineWidth',2); hold on;\nend\nt=tS:0.005:tE;\nfor i=1:length(t)\n yExact(i) = Exact(t(i),y0,1);\nend\nplot(t,yExact,'r-','LineWidth',3); hold on;\nlegend(hVec{1},hVec{2},hVec{3},hVec{4},hVec{5},'Exact Solution','Location','NorthWest');\ntitle('Exact Solns vs Numerical Solns for y(t)=y0*exp(y)');\nxlabel('t');\nylabel('y(t)');\n%\n%\nsubplot(2,2,2)\nfor i=1:length(Y_Sol(1,:))\n N= NVec2(i);\n h = hVec2(i);\n t = tS:h:tE;\n err = abs ( errMat(1:N+1,i) );\n str = strColor{i};\n plot(t,err,str,'LineWidth',2); hold on;\nend\nlegend(hVec{1},hVec{2},hVec{3},hVec{4},hVec{5},'Location','NorthWest');\ntitle('ERROR(t) for various h values for y(t)=y0*exp(y)');\nxlabel('t');\nylabel('error(t)');\n%\n%\n%\nsubplot(2,2,3);\nfor i=1:length(Y_Sol2(1,:))\n h = hVec2(i);\n N= NVec2(i);\n t = tS:h:tE;\n str = strColor{i};\n plot(t,Y_Sol2(1:N+1,i),str,'LineWidth',2); hold on;\nend\nt=tS:0.005:tE;\nfor i=1:length(t)\n yExact(i) = Exact(t(i),y0,2);\nend\nplot(t,yExact,'r-','LineWidth',3); hold on;\nlegend(hVec{1},hVec{2},hVec{3},hVec{4},hVec{5},'Exact Solution','Location','NorthEast');\ntitle('Exact Solns vs Numerical Solns for y(t)=sin(2*pi*t)+1');\nxlabel('t');\nylabel('y(t)');\n%\n%\nsubplot(2,2,4)\nfor i=1:length(Y_Sol(1,:))\n N= NVec2(i);\n h = hVec2(i);\n t = tS:h:tE;\n err = abs ( errMat2(1:N+1,i) );\n str = strColor{i};\n plot(t,err,str,'LineWidth',2); hold on;\nend\nlegend(hVec{1},hVec{2},hVec{3},hVec{4},hVec{5},'Location','NorthEast');\ntitle('ERROR(t) for various h values for y(t)=sin(2*pi*t)+1');\nxlabel('t');\nylabel('error(t)');\n\nfprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\\n');\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function that plots the computational time vs. time iterates for [0,T]\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Time_Study(Nvec,time)\n\nfprintf('\\nplotting computational time study...\\n\\n');\n\n\nfigure(3)\nloglog(Nvec,time,'ro-'); hold on;\nxlabel('Number of Time-Steps on [tS,tE]');\nylabel('Log(Time for Each Integration)');\ntitle('Computational Time Study');\n\nfprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\\n');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function that plots the convergence study, i.e., Error vs. h\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction plot_Convergence_Study(hVec,err_h,err_h2)\n\nfprintf('\\nplotting convergence studies...\\n\\n');\n\nfigure(2)\nsubplot(3,4,1)\nplot(hVec,err_h,'*'); hold on;\nxlabel('h');\nylabel('Inf-Norm Error');\ntitle('Convergence Study: y(t) = exp(t)');\n\nsubplot(3,4,2)\nsemilogx(hVec,err_h,'*'); hold on;\nxlabel('Log(h)');\nylabel('Inf-Norm Error');\ntitle('Convergence Study: y(t) = exp(t)');\n\nsubplot(3,4,[5,6,9,10])\nloglog(hVec,err_h,'*'); hold on;\nxlabel('Log(h)');\nylabel('Log(Inf-Norm Error)');\ntitle('Convergence Study: y(t) = exp(t)');\n\nfigure(2)\nsubplot(3,4,3)\nplot(hVec,err_h2,'*'); hold on;\nxlabel('h');\nylabel('Inf-Norm Error');\ntitle('Convergence Study: y(t) = sin(2*pi*t)+1');\n\nsubplot(3,4,4)\nsemilogx(hVec,err_h2,'*'); hold on;\nxlabel('Log(h)');\nylabel('Inf-Norm Error');\ntitle('Convergence Study: y(t) = sin(2*pi*t)+1');\n\nsubplot(3,4,[7,8,11,12])\nloglog(hVec,err_h2,'*'); hold on;\nxlabel('Log(h)');\nylabel('Log(Inf-Norm Error)');\ntitle('Convergence Study: y(t) = sin(2*pi*t)+1');\n\nfprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\\n');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function that computes Error\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction error = compute_Error(time,y,y0,flag)\n\n%Computes Error During Simulation\n\nexact_sol = zeros(1,length(time));\nfor i=1:length(time)\n exact_sol(i) = Exact(time(i),y0,flag); \nend\n\nerror = y - exact_sol;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% This is the RHS of the ODE: y' = f(t,y)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = f(t,y,flag)\n\n%y' = f(t,y)\n\nif flag == 1\n val = y;\nelseif flag==2\n val = 2*pi*cos(2*pi*t);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% This is the Exact Sol'n\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = Exact(t,y0,flag)\n\n%Exact sol'n to ODE\nif flag == 1\n val = y0*exp(t);\nelseif flag == 2\n val = sin(2*pi*t)+1; \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% This function tells you how many time-steps you have for the simulation\n% (This is used for the convergence study)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction NVec = give_Me_NumberOfGridPts()\n\nN1 = 1:1:9;\nN2 = 10:10:90;\nN3 = 100:100:900;\nN4 = 1000:1000:9*1e3;\nN5 = 1e4:1e4:9*1e4;\nN6 = 1e5:1e5:9*1e5;\n\nNVec = [N1 N2 N3 N4 N5 N6];\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function that prints the info about the simulation\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_info()\n\nfprintf('\\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\\n');\n\nfprintf('\\nAuthor: Nicholas Battista\\n');\nfprintf('Created: August 12, 2014\\n');\nfprintf('Date of Last Revision: August 23, 2014\\n\\n');\n\nfprintf('This function solves the following ODE:\\n\\n');\nfprintf('dy/dt = f(t,y)\\n');\nfprintf('y(0) = y0\\n\\n');\nfprintf('using Eulers Method. It then does a convergence study for various h values \\n\\n');\nfprintf('Note: It performs the convergence study for the known ODEs,\\n\\n');\n\nfprintf('dy/dt = y, with y(0) = 1; so exact solution is: y(t) = e^t\\n\\n');\nfprintf('and\\n\\n');\nfprintf('dy/dt = 2*pi*cos(2*pi*t), w/ y(0)=1 w/ exact solution y(t) = sin(2*pi*t)+1\\n\\n');\n\nfprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\\n');\n\n"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "gasBunsen.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/gasBunsen.m", "size": 1856, "source_encoding": "utf_8", "md5": "94c0adfe3ec20268a6a2ebbb53528cf7", "text": "% beta = gasBunsen(SP,pt,gas)\n% Function to calculate Bunsen coefficient\n%\n% USAGE:-------------------------------------------------------------------\n% beta=gasBunsen(SP,pt,gas)\n%\n% DESCRIPTION:-------------------------------------------------------------\n% Calculate the Bunsen coefficient, which is defined as the volume of pure\n% gas at standard temperature and pressure (0 degC, 1 atm) that will\n% dissolve into a volume of water at equilibrium when exposed to a\n% pressure of 1 atm of the gas. \n%\n% INPUTS:------------------------------------------------------------------\n% SP: Practical salinity (PSS)\n% pt: Potential temperature (deg C)\n% gas: code for gas (He, Ne, Ar, Kr, Xe, N2, or O2)\n%\n% OUTPUTS:-----------------------------------------------------------------\n% beta: Bunsen coefficient (L gas)/(L soln * atm gas)\n%\n% REFERENCE:---------------------------------------------------------------\n%\n% See references for individual gas solubility functions.\n%\n% AUTHORS:-----------------------------------------------------------------\n% Cara Manning (cmanning@whoi.edu) Woods Hole Oceanographic Institution\n% David Nicholson (dnicholson@whoi.edu)\n% Version: 1.0 // September 2015\n%\n% COPYRIGHT:---------------------------------------------------------------\n%\n% Copyright 2015 Cara Manning \n%\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License, which \n% is available at http://www.apache.org/licenses/LICENSE-2.0\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction beta=gasBunsen(SP,pt,gas)\n\npdry = 1 - vpress(SP,pt); % pressure of dry air for 1 atm total pressure\n\n% equilib solubility in mol/m3\nGeq = gasmoleq(SP,pt,gas);\n\n% calc beta \nbeta = Geq.*(gasmolvol(gas)./1000)./(pdry.*gasmolfract(gas));\nend\n"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "kgas.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/kgas.m", "size": 4654, "source_encoding": "utf_8", "md5": "20a6385160fb787a02149b3afb863af9", "text": "% =========================================================================\r\n% KGAS - gas transfer coefficient for a range of windspeed-based\r\n% parameterizations\r\n%\r\n% [kv] = kgas(u10,Sc,param)\r\n%\r\n% -------------------------------------------------------------------------\r\n% INPUTS:\r\n% -------------------------------------------------------------------------\r\n% u10 10-m windspeed (m/s)\r\n% Sc Schmidt number \r\n% param abbreviation for parameterization:\r\n% W92a = Wanninkhof 1992 - averaged winds\r\n% W92b = Wanninkhof 1992 - instantaneous or steady winds\r\n% Sw07 = Sweeney et al. 2007\r\n% Ho06 = Ho et al. 2006\r\n% Ng00 = Nightingale et al. 2000\r\n% LM86 = Liss and Merlivat 1986\r\n%\r\n% -------------------------------------------------------------------------\r\n% OUTPUTS:\r\n% -------------------------------------------------------------------------\r\n% kv Gas transfer velocity in m s-1\r\n%\r\n% -------------------------------------------------------------------------\r\n% USAGE:\r\n% -------------------------------------------------------------------------\r\n% k = kgas(10,1000,'W92b')\r\n% k = 6.9957e-05\r\n%\r\n% -------------------------------------------------------------------------\r\n% REFERENCES:\r\n% -------------------------------------------------------------------------\r\n% Wanninkhof, R. (1992). Relationship between wind speed and gas exchange.\r\n% J. Geophys. Res, 97(25), 7373-7382.\r\n%\r\n% Sweeney, C., Gloor, E., Jacobson, A. R., Key, R. M., McKinley, G.,\r\n% Sarmiento, J. L., & Wanninkhof, R. (2007). Constraining global air?sea\r\n% gas exchange for CO2 with recent bomb 14C measurements. Global\r\n% Biogeochem. Cy.,21(2).\r\n%\r\n% Ho, D. T., Law, C. S., Smith, M. J., Schlosser, P., Harvey, M., & Hill,\r\n% P. (2006). Measurements of air?sea gas exchange at high wind speeds in\r\n% the Southern Ocean: Implications for global parameterizations. Geophys.\r\n% Res. Lett., 33(16).\r\n%\r\n% Nightingale, P. D., Malin, G., Law, C. S., Watson, A. J., Liss, P. S.,\r\n% Liddicoat, M. I., et al. (2000). In situ evaluation of air-sea gas\r\n% exchange parameterizations using novel conservative and volatile tracers.\r\n% Global Biogeochem. Cy., 14(1), 373-387.\r\n%\r\n% Liss, P. S., & Merlivat, L. (1986). Air-sea gas exchange rates:\r\n% Introduction and synthesis. In The role of air-sea exchange in\r\n% geochemical cycling (pp. 113-127). Springer Netherlands.\r\n%\r\n% -------------------------------------------------------------------------\r\n% AUTHORS\r\n% -------------------------------------------------------------------------\r\n% David Nicholson dnicholson@whoi.edu, Woods Hole Oceanographic Institution\r\n% Modified by Cara Manning cmanning@whoi.edu\r\n% Version 2.0\r\n%\r\n% -------------------------------------------------------------------------\r\n% COPYRIGHT\r\n% -------------------------------------------------------------------------\r\n% Copyright 2015 David Nicholson and Cara Manning \r\n%\r\n% Licensed under the Apache License, Version 2.0 (the \"License\");\r\n% you may not use this file except in compliance with the License.\r\n% You may obtain a copy of the License at\r\n%\r\n% http://www.apache.org/licenses/LICENSE-2.0\r\n%\r\n% Unless required by applicable law or agreed to in writing, software\r\n% distributed under the License is distributed on an \"AS IS\" BASIS,\r\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n% See the License for the specific language governing permissions and\r\n% limitations under the License.\r\n%\r\n% =========================================================================\r\n\r\nfunction [kv] = kgas(u10,Sc,param)\r\n\r\nquadratics = {'W92a','W92b','Sw07','Ho06'};\r\n% should be case insensitive\r\nif ismember(upper(param),upper(quadratics))\r\n if strcmpi(param,'W92a')\r\n A = 0.39;\r\n elseif strcmpi(param,'W92b')\r\n A = 0.31;\r\n elseif strcmpi(param,'Sw07')\r\n A = 0.27;\r\n elseif strcmpi(param,'Ho06')\r\n A = 0.254; %k_600 = 0.266\r\n else\r\n error('parameterization not found');\r\n end\r\n k_cm = A*u10.^2.*(Sc./660).^-0.5; %cm/h\r\n kv = k_cm./(100*60*60); %m/s\r\nelseif strcmpi(param,'Ng00')\r\n k600 = 0.222.*u10.^2 + 0.333.*u10;\r\n k_cm = k600.*(Sc./600).^-0.5; % cm/h\r\n kv = k_cm./(100*60*60); % m/s\r\nelseif strcmpi(param,'LM86')\r\n k600 = zeros(1,length(u10)); \r\n \r\n l = find(u10 <= 3.6);\r\n k600(l) = 0.17.*u10(l);\r\n \r\n m = find(u10 > 3.6 & u10 <= 13);\r\n k600(m) = 2.85.*u10(m)-9.65;\r\n \r\n h = find(u10 > 13);\r\n k600(h) = 5.9.*u10(h)-49.3;\r\n \r\n k_cm = k600.*(Sc./600).^-0.5;\r\n k_cm(l) = k600(l).*(Sc./600).^(-2/3);\r\n kv = k_cm./(100*60*60); % m/s\r\nend"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "fas_L13.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/fas_L13.m", "size": 6356, "source_encoding": "utf_8", "md5": "bc2b614f86938e6d5b49f9c201f44c0a", "text": "% Function to calculate air-sea fluxes with Liang 2013 parameterization\r\n%\r\n% USAGE:-------------------------------------------------------------------\r\n% \r\n% [Fd, Fp, Fc, Deq] = fas_L13(0.282,10,35,10,1,'O2')\r\n% >Fd = 2.2559e-08\r\n% >Fp = 6.8604e-08\r\n% >Fc = 2.9961e-08\r\n% >Deq = 0.0062 \r\n%\r\n% DESCRIPTION:-------------------------------------------------------------\r\n%\r\n% Calculate air-sea fluxes and steady-state supersat based on:\r\n% Liang, J.-H., C. Deutsch, J. C. McWilliams, B. Baschek, P. P. Sullivan, \r\n% and D. Chiba (2013), Parameterizing bubble-mediated air-sea gas exchange \r\n% and its effect on ocean ventilation, Global Biogeochem. Cycles, 27, \r\n% 894?905, doi:10.1002/gbc.20080.\r\n%\r\n% INPUTS:------------------------------------------------------------------\r\n% C: gas concentration (mol m-3)\r\n% u10: 10 m wind speed (m/s)\r\n% SP: Sea surface salinity (PSS)\r\n% pt: Sea surface temperature (deg C)\r\n% pslp: sea level pressure (atm)\r\n% gas: two letter code for gas (He, Ne, Ar, Kr, Xe, N2, or O2) \r\n% rh: relative humidity as a fraction of saturation (0.5 = 50% RH)\r\n% rh is an optional but recommended argument. If not provided, it\r\n% will be automatically set to 0.8.\r\n%\r\n% Code Gas name Reference\r\n% ---- ---------- -----------\r\n% He Helium Weiss 1971\r\n% Ne Neon Hamme and Emerson 2004\r\n% Ar Argon Hamme and Emerson 2004\r\n% Kr Krypton Weiss and Keiser 1978\r\n% Xe Xenon Wood and Caputi 1966\r\n% N2 Nitrogen Hamme and Emerson 2004 \r\n% O2 Oxygen Garcia and Gordon 1992 \r\n%\r\n% OUTPUTS:-----------------------------------------------------------------\r\n%\r\n% Fd: Surface gas flux (mol m-2 s-1)\r\n% Fp: Flux from partially collapsing large bubbles (mol m-2 s-1)\r\n% Fc: Flux from fully collapsing small bubbles (mol m-2 s-1)\r\n% Deq: Equilibrium supersaturation (unitless (%sat/100))\r\n%\r\n% REFERENCE:---------------------------------------------------------------\r\n%\r\n% Liang, J.-H., C. Deutsch, J. C. McWilliams, B. Baschek, P. P. Sullivan, \r\n% and D. Chiba (2013), Parameterizing bubble-mediated air-sea gas \r\n% exchange and its effect on ocean ventilation, Global Biogeochem. Cycles, \r\n% 27, 894?905, doi:10.1002/gbc.20080.\r\n%\r\n% AUTHOR:---------------------------------------------------------------\r\n% Written by David Nicholson dnicholson@whoi.edu\r\n% Modified by Cara Manning cmanning@whoi.edu\r\n% Woods Hole Oceanographic Institution\r\n% Version: 2.0 // September 2015\r\n%\r\n% COPYRIGHT:---------------------------------------------------------------\r\n%\r\n% Copyright 2015 David Nicholson and Cara Manning \r\n%\r\n% Licensed under the Apache License, Version 2.0 (the \"License\");\r\n% you may not use this file except in compliance with the License, which \r\n% is available at http://www.apache.org/licenses/LICENSE-2.0\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [ Fd, Fp, Fc, Deq, Ks] = fas_L13(C,u10,SP,pt,pslp,gas,rh)\r\n% -------------------------------------------------------------------------\r\n% Conversion factors\r\n% -------------------------------------------------------------------------\r\nm2cm = 100; % cm in a meter\r\nh2s = 3600; % sec in hour\r\natm2Pa = 1.01325e5; % Pascals per atm\r\n\r\n% -------------------------------------------------------------------------\r\n% Calculate water vapor pressure and adjust sea level pressure\r\n% -------------------------------------------------------------------------\r\n\r\n% if humidity is not provided, set to 0.8 for all values\r\nif nargin == 6\r\n rh =0.8.*ones(size(C));\r\nend\r\n\r\nph2oveq = vpress(SP,pt);\r\nph2ov = rh.*ph2oveq;\r\n\r\n% slpc = (observed dry air pressure)/(reference dry air pressure)\r\n% see Description section in header of fas_N11.m\r\npslpc = (pslp - ph2ov)./(1 - ph2oveq);\r\n\r\n% -------------------------------------------------------------------------\r\n% Parameters for COARE 3.0 calculation\r\n% -------------------------------------------------------------------------\r\n\r\n% Calculate potential density at surface\r\nSA = SP.*35.16504./35;\r\nCT = gsw_CT_from_pt(SA,pt);\r\nrhow = gsw_sigma0(SA,CT)+1000;\r\nrhoa = 1.0;\r\n\r\nlam = 13.3;\r\nA = 1.3;\r\nphi = 1;\r\ntkt = 0.01;\r\nhw=lam./A./phi;\r\nha=lam;\r\n\r\n% air-side schmidt number\r\nScA = 0.9;\r\n\r\nR = 8.314; % units: m3 Pa K-1 mol-1\r\n\r\n% -------------------------------------------------------------------------\r\n% Calculate gas physical properties\r\n% -------------------------------------------------------------------------\r\nxG = gasmolfract(gas);\r\nGeq = gasmoleq(SP,pt,gas);\r\nalc = (Geq/atm2Pa).*R.*(pt+273.15);\r\n\r\nGsat = C./Geq;\r\n[~, ScW] = gasmoldiff(SP,pt,gas);\r\n\r\n% -------------------------------------------------------------------------\r\n% Calculate COARE 3.0 and gas transfer velocities\r\n% -------------------------------------------------------------------------\r\n% ustar\r\ncd10 = cdlp81(u10);\r\nustar = u10.*sqrt(cd10);\r\n\r\n% water-side ustar\r\nustarw = ustar./sqrt(rhow./rhoa);\r\n\r\n% water-side resistance to transfer\r\nrwt = sqrt(rhow./rhoa).*(hw.*sqrt(ScW)+(log(.5./tkt)/.4));\r\n\r\n% air-side resistance to transfer\r\nrat = ha.*sqrt(ScA)+1./sqrt(cd10)-5+.5*log(ScA)/.4;\r\n\r\n% diffusive gas transfer coefficient (L13 eqn 9)\r\nKs = ustar./(rwt+rat.*alc);\r\n\r\n% bubble transfer velocity (L13 eqn 14)\r\nKb = 1.98e6.*ustarw.^2.76.*(ScW./660).^(-2/3)./(m2cm.*h2s);\r\n\r\n% overpressure dependence on windspeed (L13 eqn 16)\r\ndP = 1.5244.*ustarw.^1.06;\r\n\r\n\r\n% -------------------------------------------------------------------------\r\n% Calculate air-sea fluxes\r\n% -------------------------------------------------------------------------\r\n\r\nFd = Ks.*Geq.*(pslpc-Gsat); % Fs in L13 eqn 3\r\nFp = Kb.*Geq.*((1+dP).*pslpc-Gsat); % Fp in L13 eqn 3\r\nFc = xG.*5.56.*ustarw.^3.86; % L13 eqn 15\r\n\r\n% -------------------------------------------------------------------------\r\n% Calculate steady-state supersaturation \r\n% -------------------------------------------------------------------------\r\nDeq = (Kb.*Geq.*dP.*pslpc+Fc)./((Kb+Ks).*Geq.*pslpc); % L13 eqn 5\r\n\r\nend\r\n\r\nfunction [ cd ] = cdlp81( u10)\r\n% Calculates drag coefficient from u10, wind speed at 10 m height\r\n\r\ncd = (4.9e-4 + 6.5e-5 * u10);\r\ncd(u10 <= 11) = 0.0012;\r\ncd(u10 >= 20) = 0.0018;\r\n\r\nend"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "fas_S09.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/fas_S09.m", "size": 6754, "source_encoding": "utf_8", "md5": "f6e99dc7f66955ce601e76053f538654", "text": "% [Fd, Fc, Fp, Deq] = fas_S09(C,u10,S,T,slp,gas,rh)\r\n% Function to calculate air-sea gas exchange flux using Stanley 09\r\n% parameterization\r\n%\r\n% USAGE:-------------------------------------------------------------------\r\n% [Fd, Fc, Fp, Deq] = fas_S09(C,u10,S,T,slp,gas,rh)\r\n% [Fd, Fc, Fp, Deq] = fas_S09(0.01410,5,35,10,1,'Ar',0.9)\r\n% > Fd = -4.9960e-09\r\n% > Fc = 7.3493e-10\r\n% > Fp = 1.8653e-13\r\n% > Deq = 0.0027\r\n%\r\n% DESCRIPTION:-------------------------------------------------------------\r\n% Calculate air-sea fluxes and steady-state supersaturation based on:\r\n% Stanley, R.H., Jenkins, W.J., Lott, D.E., & Doney, S.C. (2009). Noble\r\n% gas constraints on air-sea gas exchange and bubble fluxes. Journal of\r\n% Geophysical Research: Oceans, 114(C11), doi: 10.1029/2009JC005396\r\n%\r\n% These estimates are valid over the range of wind speeds observed at\r\n% Bermuda (0-13 m/s) and for open ocean, oligotrophic waters low in\r\n% surfactants. Additionally, the estimates were determined using QuikSCAT\r\n% winds, and if using another global wind product (e.g., NCEP reanalysis),\r\n% a correction for biases between the wind products may be appropriate.\r\n% Contact Rachel Stanley (rachel.stanley@wellesley.edu) with questions.\r\n%\r\n% Explanation of slpc:\r\n% slpc = (observed dry air pressure)/(reference dry air pressure)\r\n% slpc is a pressure correction factor to convert from reference to\r\n% observed conditions. Equilibrium gas concentration in gasmoleq is\r\n% referenced to 1 atm total air pressure, including saturated water vapor\r\n% (RH=1), but observed sea level pressure is usually different from 1 atm,\r\n% and humidity in the marine boundary layer is usually less than\r\n% saturation. Thus, the observed sea level pressure of each gas will\r\n% usually be different from the reference.\r\n%\r\n% INPUTS:------------------------------------------------------------------\r\n% C: gas concentration (mol/m^3)\r\n% u10: 10 m wind speed (m/s)\r\n% S: Sea surface salinity (PSS)\r\n% T: Sea surface temperature (deg C)\r\n% slp: sea level pressure (atm)\r\n% gas: two letter code for gas (He, Ne, Ar, Kr, Xe, N2, or O2)\r\n% rh: relative humidity in the marine boundary layer as a fraction of\r\n% saturation (0.5 = 50% RH).\r\n% rh is an optional but recommended argument. If not provided, it\r\n% will be automatically set to 0.8.\r\n%\r\n% OUTPUTS:-----------------------------------------------------------------\r\n% Fd: Diffusive air-sea flux (mol m-2 s-1)\r\n% Fp: Flux from partially collapsing large bubbles (mol m-2 s-1)\r\n% Fc: Flux from fully collapsing small bubbles (mol m-2 s-1)\r\n% Deq: Equilibrium supersaturation (unitless (%sat/100))\r\n%\r\n% REFERENCE:---------------------------------------------------------------\r\n%\r\n% Stanley, R.H., Jenkins, W.J., Lott, D.E., & Doney, S.C. (2009). Noble\r\n% gas constraints on air-sea gas exchange and bubble fluxes. Journal of\r\n% Geophysical Research: Oceans, 114(C11), doi: 10.1029/2009JC005396\r\n%\r\n% Bubble penetration depth parameterization:\r\n% Graham, A., D. K. Woolf, and A. J. Hall (2004), Aeration due to breaking\r\n% waves. Part I: Bubble populations, J. Phys. Oceanogr., 34(5), 989?1007,\r\n% doi:10.1175/1520-0485(2004)034<0989:ADTBWP>2.0.CO;2.\r\n%\r\n% AUTHOR:------------------------------------------------------------------\r\n%\r\n% Cara Manning (cmanning@whoi.edu) Woods Hole Oceanographic Institution\r\n% Version: 1.0 // September 2015\r\n% Checked and approved by Rachel Stanley on September 20, 2015.\r\n%\r\n% COPYRIGHT:---------------------------------------------------------------\r\n%\r\n% Copyright 2015 Cara Manning \r\n%\r\n% Licensed under the Apache License, Version 2.0 (the \"License\");\r\n% you may not use this file except in compliance with the License, which \r\n% is available at http://www.apache.org/licenses/LICENSE-2.0\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [Fd, Fc, Fp, Deq] = fas_S09(C,u10,S,T,slp,gas,rh)\r\n% -------------------------------------------------------------------------\r\n% Conversion factors and constants\r\n% -------------------------------------------------------------------------\r\natm2Pa = 1.01325e5; % Pascals per atm\r\nR = 8.314; % ideal gas constant in m3 Pa / (K mol)\r\n\r\n% -------------------------------------------------------------------------\r\n% Scaling factors for gas exchange coefficients\r\n% -------------------------------------------------------------------------\r\n\r\nAc = 9.09E-11;\r\nAp = 2.29E-3;\r\ngammaG = 0.97;\r\ndiffexp=2/3; betaexp=1;\r\n\r\n% -------------------------------------------------------------------------\r\n% Check for humidity\r\n% -------------------------------------------------------------------------\r\n\r\n% if humidity is not provided, set to 0.8 for all values\r\nif nargin == 6\r\n rh =0.8.*ones(size(C));\r\nend;\r\n\r\n% -------------------------------------------------------------------------\r\n% Calculate diffusive flux\r\n% -------------------------------------------------------------------------\r\n\r\n[D,Sc] = gasmoldiff(S,T,gas);\r\nGeq = gasmoleq(S,T,gas);\r\n\r\nk = gammaG*kgas(u10,Sc,'W92b'); % k_660 = 0.31 cm/hr\r\n\r\n% slpc = (observed dry air pressure)/(reference dry air pressure)\r\n% see Description section in header\r\nph2oveq = vpress(S,T);\r\nph2ov = rh.*ph2oveq;\r\nslpc = (slp-ph2ov)./(1-ph2oveq);\r\n\r\n% calculate diffusive flux with correction for local humidity\r\nFd = -k.*(C-Geq.*slpc);\r\n\r\n% -------------------------------------------------------------------------\r\n% Calculate complete trapping / air injection flux\r\n% -------------------------------------------------------------------------\r\n\r\n% air injection factor as a function of wind speed\r\n% set to 0 below u10 = 2.27 m/s\r\nwfact=(u10-2.27)^3; \r\nwfact(wfact<0) = 0;\r\n\r\n% calculate dry atmospheric pressure in atm\r\npatmdry=slp-ph2ov; % pressure of dry air in atm \r\n\r\nai=gasmolfract(gas).*wfact.*patmdry*atm2Pa/(R*(273.15+T));\r\nFc = Ac*ai; \r\n\r\n\r\n% -------------------------------------------------------------------------\r\n% Calculate partial trapping / exchange flux\r\n% -------------------------------------------------------------------------\r\n\r\n% calculate bubble penetration depth, Zbub, then calculate hydrostatic\r\n% pressure in atm\r\nZbub = 0.15*u10 - 0.55;\r\nZbub(Zbub<0)=0; \r\nphydro=(gsw_sigma0(S,T)+1000)*9.81*Zbub/atm2Pa; \r\n\r\n% multiply by scaling factor Ap by beta raised to power betaexp and \r\n% diffusivity raised to power diffexp\r\napflux=ai.*Ap.*D.^diffexp.*(gasBunsen(S,T,gas).^betaexp); \r\nFp=apflux.*(phydro./patmdry-C./Geq+1); \r\n\r\n\r\n% -------------------------------------------------------------------------\r\n% Calculate steady-state supersaturation\r\n% -------------------------------------------------------------------------\r\nDeq = ((Fc+Fp)./k)./Geq;\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "fas_N11.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/fas_N11.m", "size": 7418, "source_encoding": "utf_8", "md5": "ca85c60e47fa4e8b77675c14034cc8a1", "text": "<<<<<<< HEAD\n% Function to calculate air-sea bubble flux\n%\n% USAGE:-------------------------------------------------------------------\n% \n% [Fi Fe] = Fbub_N11(8,35,20,1,'O2')\n%\n% > Fi = 9.8910e-08\n% > Fe = 2.3665e-08\n%\n% DESCRIPTION:-------------------------------------------------------------\n%\n% Calculates the equilibrium concentration of gases as a function of\n% temperature and salinity (equilibrium concentration is at 1 atm including\n% atmospheric pressure\n%\n% Finj = Ainj * slp * Xg * u3\n% Fex = Aex * slp * Geq * D^n * u3\n%\n% where u3 = (u-2.27)^3 (and zero for u < 2.27)\n%\n% INPUTS:------------------------------------------------------------------\n% \n% C: gas concentration in mol m-3\n% u10: 10 m wind speed (m/s)\n% S: Sea surface salinity\n% T: Sea surface temperature (deg C)\n% slp: sea level pressure (atm)\n%\n% gas: two letter code for gas\n%\n% Code Gas name Reference\n% ---- ---------- -----------\n% He Helium Weiss 1971\n% Ne Neon Hamme and Emerson 2004\n% Ar Argon Hamme and Emerson 2004\n% Kr Krypton Weiss and Keiser 1978\n% Xe Xenon Wood and Caputi 1966\n% N2 Nitrogen Hamme and Emerson 2004 \n% O2 Oxygen Garcia and Gordon 1992 \n%\n% OUTPUTS:------------------------------------------------------------------\n%\n% Finj and Fex, Injection and exchange bubble flux in mol m-2 s-1\n% Fas: surface air-sea flux based on Sweeney et al. 2007\n% Deq: steady-state supersaturation\n% REFERENCE:---------------------------------------------------------------\n%\n% Nicholson, D., S. Emerson, S. Khatiwala, R. C. Hamme. (2011)\n% An inverse approach to estimate bubble-mediated air-sea gas flux from \n% inert gas measurements. Proceedings on the 6th International Symposium\n% on Gas Transfer at Water Surfaces. Kyoto University Press.\n%\n% AUTHOR:---------------------------------------------------------------\n% David Nicholson dnicholson@whoi.edu\n% Woods Hole Oceanographic Institution\n% Version: September 2014\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [Fas, Finj, Fex, Deq, k] = fas_N11(C,u10,S,T,slp,gas,varargin)\n\nif nargin > 6\n rhum = varargin{1};\nelse\n rhum = 0.8;\nend\nph2oveq = vpress(S,T);\nph2ov = rhum.*ph2oveq;\nAinj = 2.357e-9;\nAex = 1.848e-5;\n\nu3 = (u10-2.27).^3;\nu3(u3 < 0) = 0;\n\n[D,Sc] = gasmoldiff(S,T,gas);\nGeq = gasmoleq(S,T,gas);\n\nk = kgas(u10,Sc,'Sw07');\nFas = k.*(Geq.*(slp-ph2ov)./(1-ph2oveq)-C);\nFinj = Ainj.*slp.*gas_mole_fract(gas).*u3;\nFex = Aex.*slp.*Geq.*D.^0.5.*u3;\nDeq = ((Finj+Fex)./k)./Geq;\n=======\n% Function to calculate air-sea gas exchange flux using Nicholson 11\r\n% parameterization\r\n%\r\n% USAGE:-------------------------------------------------------------------\r\n% \r\n% [Fd, Fc, Fp, Deq] = fas_N11(C,u10,S,T,slp,gas,rh)\r\n% [Fd, Fc, Fp, Deq] = fas_N11(0.01410,5,35,10,1,'Ar',0.9)\r\n%\r\n% > Fd = -4.4860e-09\r\n% > Fc = 3.1432e-10\r\n% > Fp = 9.0980e-11\r\n% > Deq = 1.6882e-03\r\n%\r\n% DESCRIPTION:-------------------------------------------------------------\r\n%\r\n% Calculate air-sea fluxes and steady-state supersaturation based on:\r\n% Nicholson, D., S. Emerson, S. Khatiwala, R. C. Hamme. (in press) \r\n% An inverse approach to estimate bubble-mediated air-sea gas flux from \r\n% inert gas measurements. Proceedings on the 6th International Symposium\r\n% on Gas Transfer at Water Surfaces. Kyoto University Press.\r\n%\r\n% Fc = Ainj * slpc * Xg * u3\r\n% Fp = Aex * slpc * Geq * D^n * u3\r\n%\r\n% where u3 = (u-2.27)^3 (and zero for u < 2.27)\r\n%\r\n% Explanation of slpc:\r\n% slpc = (observed dry air pressure)/(reference dry air pressure)\r\n% slpc is a pressure correction factor to convert from reference to\r\n% observed conditions. Equilibrium gas concentration in gasmoleq is\r\n% referenced to 1 atm total air pressure, including saturated water vapor\r\n% (RH=1), but observed sea level pressure is usually different from 1 atm,\r\n% and humidity in the marine boundary layer is usually less than\r\n% saturation. Thus, the observed sea level pressure of each gas will\r\n% usually be different from the reference.\r\n%\r\n% INPUTS:------------------------------------------------------------------\r\n% \r\n% C: gas concentration in mol m-3\r\n% u10: 10 m wind speed (m/s)\r\n% S: Sea surface salinity (PSS)\r\n% T: Sea surface temperature (deg C)\r\n% slp: sea level pressure (atm)\r\n%\r\n% gas: two letter code for gas\r\n% Code Gas name Reference\r\n% ---- ---------- -----------\r\n% He Helium Weiss 1971\r\n% Ne Neon Hamme and Emerson 2004\r\n% Ar Argon Hamme and Emerson 2004\r\n% Kr Krypton Weiss and Keiser 1978\r\n% Xe Xenon Wood and Caputi 1966\r\n% N2 Nitrogen Hamme and Emerson 2004 \r\n% O2 Oxygen Garcia and Gordon 1992 \r\n%\r\n% varargin: optional but recommended arguments\r\n% rhum: relative humidity as a fraction of saturation (0.5 = 50% RH).\r\n% If not provided, it will be automatically set to 0.8.\r\n%\r\n% OUTPUTS:-----------------------------------------------------------------\r\n% Fd: Surface air-sea diffusive flux based on \r\n% Sweeney et al. 2007 [mol m-2 s-1]\r\n% Fc: Injection bubble flux (complete trapping) [mol m-2 s-1]\r\n% Fp: Exchange bubble flux (partial trapping) [mol m-2 s-1]\r\n% Deq: Steady-state supersaturation [unitless (%sat/100)]\r\n%\r\n% REFERENCE:---------------------------------------------------------------\r\n% Nicholson, D., S. Emerson, S. Khatiwala, R. C. Hamme. (in press) \r\n% An inverse approach to estimate bubble-mediated air-sea gas flux from \r\n% inert gas measurements. Proceedings on the 6th International Symposium\r\n% on Gas Transfer at Water Surfaces. Kyoto University Press.\r\n%\r\n% AUTHORS:-----------------------------------------------------------------\r\n% David Nicholson dnicholson@whoi.edu\r\n% Cara Manning cmanning@whoi.edu\r\n% Woods Hole Oceanographic Institution\r\n% Version 2.0 September 2015\r\n%\r\n% COPYRIGHT:---------------------------------------------------------------\r\n%\r\n% Copyright 2015 David Nicholson and Cara Manning \r\n%\r\n% Licensed under the Apache License, Version 2.0 (the \"License\");\r\n% you may not use this file except in compliance with the License, which \r\n% is available at http://www.apache.org/licenses/LICENSE-2.0\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [Fd, Fc, Fp, Deq] = fas_N11(C,u10,S,T,slp,gas,varargin)\r\n\r\n% 1.5 factor converts from average winds to instantaneous - see N11 ref.\r\nAinj = 2.51e-9./1.5;\r\nAex = 1.15e-5./1.5;\r\n\r\n\r\n% if humidity is not provided, set to 0.8 for all values\r\nif nargin > 6\r\n rhum = varargin{1};\r\nelse\r\n rhum = 0.8;\r\nend\r\n\r\n% slpc = (observed dry air pressure)/(reference dry air pressure)\r\n% see Description section in header\r\nph2oveq = vpress(S,T);\r\nph2ov = rhum.*ph2oveq;\r\nslpc = (slp-ph2ov)./(1-ph2oveq);\r\nslpd = slp-ph2ov;\r\n\r\n[D,Sc] = gasmoldiff(S,T,gas);\r\nGeq = gasmoleq(S,T,gas);\r\n\r\n% calculate wind speed term for bubble flux\r\nu3 = (u10-2.27).^3;\r\nu3(u3 < 0) = 0;\r\n\r\nk = kgas(u10,Sc,'Sw07');\r\nFd = -k.*(C-slpc.*Geq);\r\nFc = Ainj.*slpd.*gasmolfract(gas).*u3;\r\nFp = Aex.*slpc.*Geq.*D.^0.5.*u3;\r\nDeq = ((Fp+Fc)./k)./Geq;\n>>>>>>> cara-gtws\n"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "fas_Sw07.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/fas_Sw07.m", "size": 4246, "source_encoding": "utf_8", "md5": "aabc9958150462fd4140a234ddf0fa24", "text": "% [Fd, Fc, Fp, Deq] = fas_Sw07(C,u10,S,T,slp,gas,rh)\r\n% Function to calculate air-sea gas exchange flux using Sweeney 07\r\n% parameterization (k_660 = 0.27 cm/hr)\r\n%\r\n% USAGE:------------------------------------------------------------------- \r\n% [Fd, Fc, Fp, Deq] = fas_Sw07(C,u10,S,T,slp,gas,rh)\r\n% [Fd, Fc, Fp, Deq] = fas_Sw07(0.01410,5,35,10,1,'Ar',0.9)\r\n% > Fd = -4.4860e-09\r\n% > Fc = 0\r\n% > Fp = 0\r\n% > Deq = 0\r\n% \r\n% DESCRIPTION:-------------------------------------------------------------\r\n% Calculate air-sea fluxes and steady-state supersaturation based on:\r\n% Sweeney, C., Gloor, E., Jacobson, A. R., Key, R. M., McKinley, G.,\r\n% Sarmiento, J. L., & Wanninkhof, R. (2007). Constraining global air?sea\r\n% gas exchange for CO2 with recent bomb 14C measurements. Global\r\n% Biogeochemical Cycles, 21(2).\r\n%\r\n% INPUTS:------------------------------------------------------------------\r\n% \r\n% C: gas concentration in mol m-3\r\n% u10: 10 m wind speed (m/s)\r\n% S: Sea surface salinity\r\n% T: Sea surface temperature (deg C)\r\n% slp: sea level pressure (atm)\r\n% gas: two letter code for gas (He, Ne, Ar, Kr, Xe, O2, N2)\r\n% rh: relative humidity as a fraction of saturation (0.5 = 50% RH)\r\n% rh is an optional but recommended argument. If not provided, it\r\n% will be automatically set to 0.8.\r\n%\r\n% OUTPUTS:-----------------------------------------------------------------\r\n% Fd: Diffusive air-sea flux (mol m-2 s-1)\r\n% Fc: Flux from fully collapsing small bubbles (mol m-2 s-1)\r\n% Fp: Flux from partially collapsing large bubbles (mol m-2 s-1)\r\n% Deq: Equilibrium supersaturation (unitless (%sat/100))\r\n%\r\n% Note: Fp, Fc, and Deq will always be 0 and are included as outputs for\r\n% consistency with the other fas functions.\r\n%\r\n% REFERENCE:---------------------------------------------------------------\r\n% Sweeney, C., Gloor, E., Jacobson, A. R., Key, R. M., McKinley, G.,\r\n% Sarmiento, J. L., & Wanninkhof, R. (2007). Constraining global air?sea\r\n% gas exchange for CO2 with recent bomb 14C measurements. Global\r\n% Biogeochemical Cycles, 21(2).\r\n%\r\n% AUTHOR:---------------------------------------------------------------\r\n% Cara Manning cmanning@whoi.edu\r\n% Woods Hole Oceanographic Institution\r\n% Version: August 2015\r\n%\r\n% COPYRIGHT:---------------------------------------------------------------\r\n%\r\n% Copyright 2015 Cara Manning \r\n%\r\n% Licensed under the Apache License, Version 2.0 (the \"License\");\r\n% you may not use this file except in compliance with the License.\r\n% You may obtain a copy of the License at\r\n%\r\n% http://www.apache.org/licenses/LICENSE-2.0\r\n%\r\n% Unless required by applicable law or agreed to in writing, software\r\n% distributed under the License is distributed on an \"AS IS\" BASIS,\r\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n% See the License for the specific language governing permissions and\r\n% limitations under the License.\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [Fd, Fc, Fp, Deq] = fas_Sw07(C,u10,S,T,slp,gas,rh)\r\n\r\n% -------------------------------------------------------------------------\r\n% Check for humidity, calculate dry pressure\r\n% -------------------------------------------------------------------------\r\n\r\n% if humidity is not provided, set to 0.8 for all values\r\nif nargin == 6\r\n rh = 0.8.*ones(size(C));\r\nend;\r\n\r\n% Equilibrium gas conc is referenced to 1 atm total air pressure, \r\n% including saturated water vapor (rh=1).\r\n% Calculate ratio (observed dry air pressure)/(reference dry air pressure).\r\nph2oveq = vpress(S,T);\r\nph2ov = rh.*ph2oveq;\r\nslpc = (slp-ph2ov)./(1-ph2oveq);\r\n\r\n% -------------------------------------------------------------------------\r\n% Calc gas exchange fluxes\r\n% -------------------------------------------------------------------------\r\n\r\nGeq = gasmoleq(S,T,gas);\r\n[~,Sc] = gasmoldiff(S,T,gas);\r\nk = kgas(u10,Sc,'Sw07');\r\nFd = -k.*(C-Geq.*slpc);\r\n\r\n% Set Finj, Fex to 0. They are included to be consistent with the other\r\n% fas_ functions.\r\nFc = zeros(size(Fd));\r\nFp = zeros(size(Fd));\r\n\r\n% Calculate steady state equilibrium supersaturation. This will also be 0.\r\nDeq = ((Fc+Fp)./k)./Geq;"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "gasmolsol.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/gasmolsol.m", "size": 1341, "source_encoding": "utf_8", "md5": "6e4780f3679e3ea17ac369365f554331", "text": "% =========================================================================\n% GASMOLSOL.M - calculates Henry's Law solubility (for a pure gas)\n% in mol m-3 atm-1 \n%\n% This is a wrapper function. See individual solubility functions for more\n% details.\n%\n% [sol] = gasmolsol(SP,pt,gas)\n%\n% -------------------------------------------------------------------------\n% INPUTS:\n% -------------------------------------------------------------------------\n% SP Practical Salinity\n% pt Potential temperature [degC]\n% gas gas string: He, Ne, Ar, Kr, Xe, O2 or N2\n%\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% -------------------------------------------------------------------------\n% sol Henry's Law solubility in mol m-3 atm-1\n%\n% -------------------------------------------------------------------------\n% USGAGE:\n% -------------------------------------------------------------------------\n% [KH_O2] = gasmolsol(35,20,'O2')\n% KH_O2 = 1.1289\n%\n% Author: David Nicholson dnicholson@whoi.edu\n% Also see: gasmolfract.m, gasmoleq.m\n% =========================================================================\n\nfunction [sol] = gasmolsol(SP,pt,gas)\n\nsoleq = gasmoleq(SP,pt,gas);\n[p_h2o] = vpress(SP,pt);\n% water vapour pressure correction\nsol = soleq./(gasmolfract(gas).*(1-p_h2o));\n\n"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "calc_u10.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/calc_u10.m", "size": 2088, "source_encoding": "utf_8", "md5": "09c687c95196c23b80507092d86febf5", "text": "% u10 = calc_u10(umeas,hmeas)\n%\n% USAGE:-------------------------------------------------------------------\n% \n% [u10] = calc_u10(5,4)\n%\n% >u10 = 5.5302\n%\n% DESCRIPTION:-------------------------------------------------------------\n% Scale wind speed from measurement height to 10 m height\n%\n% INPUTS:------------------------------------------------------------------\n% umeas: measured wind speed (m/s)\n% hmeas: height of measurement (m), can have dimension 1x1 or same as umeas\n%\n% OUTPUTS:-----------------------------------------------------------------\n%\n% Fs: Surface gas flux (mol m-2 s-1)\n% Fp: Flux from partially collapsing large bubbles (mol m-2 s-1)\n% Fc: Flux from fully collapsing small bubbles (mol m-2 s-1)\n% Deq: Equilibrium supersaturation (unitless (%sat/100))\n%\n% REFERENCE:---------------------------------------------------------------\n%\n% Hsu S, Meindl E A and Gilhousen D B (1994) Determining the Power-Law\n% Wind-Profile Exponent under Near-Neutral Stability Conditions at Sea \n% J. Appl. Meteor. 33 757?765\n%\n% AUTHOR:---------------------------------------------------------------\n% Cara Manning cmanning@whoi.edu\n% MIT/WHOI Joint Program in Oceanography\n% Version: 1.0 // September 2015\n%\n% COPYRIGHT:---------------------------------------------------------------\n%\n% Copyright 2015 Cara Manning \n%\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n%\n% http://www.apache.org/licenses/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction u10 = calc_u10(umeas,hmeas)\n\nu10 = umeas.*(10./hmeas).^0.11;\nend"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "gasmoleq.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/gasmoleq.m", "size": 3626, "source_encoding": "utf_8", "md5": "ef6936be137426f8dcab022b7eb2c9a6", "text": "% =========================================================================\r\n% [sol] = gasmoleq(SP,pt,gas)\r\n%\r\n% GASMOLEQ.M - calculates equilibrium solubility of a dissolved gas\r\n% in mol/m^3 at an absolute pressure of 101325 Pa (sea pressure of 0 \r\n% dbar) including saturated water vapor. \r\n%\r\n% This is a wrapper function. See individual solubility functions for more\r\n% details.\r\n%\r\n% This function uses the GSW Toolbox solubility functions when available,\r\n% except for Ne. There is a bug in gsw_Nesol_SP_pt and gsw_Nesol version\r\n% 3.05 (they return solubility in nmol kg-1 instead of umol kg-1), so we\r\n% have provided a correct function for the solubility of Ne.\r\n%\r\n% -------------------------------------------------------------------------\r\n% USAGE:\r\n% -------------------------------------------------------------------------\r\n% [O2eq] = gasmoleq(35,20,'O2')\r\n% O2eq = 0.2311\r\n%\r\n% -------------------------------------------------------------------------\r\n% INPUTS:\r\n% -------------------------------------------------------------------------\r\n% SP Practical salinity [PSS-78]\r\n% pt Potential temperature [degC]\r\n% gas gas string: He, Ne, Ar, Kr, Xe, O2 or N2\r\n%\r\n% -------------------------------------------------------------------------\r\n% OUTPUTS:\r\n% -------------------------------------------------------------------------\r\n% sol gas equilibrium solubility in mol/m^3\r\n%\r\n% -------------------------------------------------------------------------\r\n% REFERENCES:\r\n% -------------------------------------------------------------------------\r\n% IOC, SCOR and IAPSO, 2010: The international thermodynamic equation of \r\n% seawater - 2010: Calculation and use of thermodynamic properties. \r\n% Intergovernmental Oceanographic Commission, Manuals and Guides No. 56,\r\n% UNESCO (English), 196 pp. Available from http://www.TEOS-10.org\r\n%\r\n% See also the references within each solubility function. \r\n%\r\n% -------------------------------------------------------------------------\r\n% AUTHORS:\r\n% -------------------------------------------------------------------------\r\n% Cara Manning, cmanning@whoi.edu\r\n% David Nicholson, dnicholson@whoi.edu\r\n%\r\n% -------------------------------------------------------------------------\r\n% LICENSE:\r\n% -------------------------------------------------------------------------\r\n% Copyright 2015 Cara Manning and David Nicholson \r\n%\r\n% Licensed under the Apache License, Version 2.0 (the \"License\");\r\n% you may not use this file except in compliance with the License, which \r\n% is available at http://www.apache.org/licenses/LICENSE-2.0\r\n%\r\n% =========================================================================\r\n\r\nfunction [sol] = gasmoleq(SP,pt,gas)\r\n\r\n% Calculate potential density at surface\r\nSA = SP.*35.16504./35;\r\nCT = gsw_CT_from_pt(SA,pt);\r\nrho = gsw_sigma0(SA,CT)+1000;\r\n\r\n% calculate equilibrium solubility gas concentration in micro-mol/kg\r\nif strcmpi(gas, 'He')\r\n sol_umolkg = gsw_Hesol_SP_pt(SP,pt);\r\nelseif strcmpi(gas, 'Ne')\r\n % bug in gsw_Nesol... v. 3.05 - returns nmol kg-1 instead of umol kg-1\r\n sol_umolkg = Nesol(SP,pt);\r\nelseif strcmpi(gas, 'Ar')\r\n sol_umolkg = gsw_Arsol_SP_pt(SP,pt);\r\nelseif strcmpi(gas, 'Kr')\r\n sol_umolkg = gsw_Krsol_SP_pt(SP,pt);\r\nelseif strcmpi(gas, 'Xe')\r\n sol_umolkg = Xesol(SP,pt);\r\nelseif strcmpi(gas, 'N2')\r\n sol_umolkg = gsw_N2sol_SP_pt(SP,pt);\r\nelseif strcmpi(gas, 'O2')\r\n sol_umolkg = gsw_O2sol_SP_pt(SP,pt);\r\nelse\r\n error('Gas name must be He, Ne, Ar, Kr, Xe, O2 or N2');\r\nend\r\n\r\n% convert from micro-mol/kg to mol/m3\r\nsol = rho.*sol_umolkg./1e6;\r\n\r\n"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "fas.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/fas.m", "size": 4077, "source_encoding": "utf_8", "md5": "6f31976e074eea8855be4c2d18ef3f34", "text": "% =========================================================================\n% FAS - wrapper function for calculating air-sea gas transfer using a\n% specific GE parameterization\n%\n% [Fs, Fc, Fp, Deq] = fas(C,u10,S,T,slp,gas,param,rh)\n%\n% -------------------------------------------------------------------------\n% USAGE:\n% -------------------------------------------------------------------------\n% [Fd, Fc, Fp, Deq] = fas(C,u10,S,T,slp,gas,param,rh)\n% [Fd, Fc, Fp, Deq] = fas(0.01410,5,35,10,1,'Ar','N11',0.9)\n% > Fd = -4.4859e-09\n% > Fc = 4.4807e-10\n% > Fp = 2.1927e-10\n% > Deq = -0.0168\n%\n% -------------------------------------------------------------------------\n% INPUTS:\n% -------------------------------------------------------------------------\n% C: gas concentration (mol m-3)\n% u10: 10 m wind speed (m/s)\n% S: Sea surface salinity (PSS)\n% T: Sea surface temperature (deg C)\n% slp: sea level pressure (atm)\n% gas: two letter code for gas (He, Ne, Ar, Kr, Xe, O2, or N2)\n% sol: choice of solubility function\n% param: abbreviation for parameterization:\n% Sw07 = Sweeney et al. 2007\n% S09 = Stanley et al. 2009\n% N11 = Nicholson et al. 2011 \n% L13 = Liang et al. 2013 \n% rh: relative humidity expressed as the fraction of saturation \n% (0.5 = 50% RH).\n% rh is an optional but recommended argument. If not provided, it\n% will be set to 0.8 within the function.\n%\n% Code Gas name Reference\n% ---- ---------- -----------\n% He Helium Weiss 1971\n% Ne Neon Hamme and Emerson 2004\n% Ar Argon Hamme and Emerson 2004\n% Kr Krypton Weiss and Keiser 1978\n% Xe Xenon Wood and Caputi 1966\n% N2 Nitrogen Hamme and Emerson 2004 \n% O2 Oxygen Garcia and Gordon 1992 \n%\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% -------------------------------------------------------------------------\n% Fd Diffusive flux (mol m-2 s-1)\n% Fc: Flux from fully collapsing small bubbles (mol m-2 s-1)\n% Fp: Flux from partially collapsing large bubbles (mol m-2 s-1)\n% Deq: Equilibrium supersaturation (unitless (%sat/100))\n%\n% -------------------------------------------------------------------------\n% AUTHOR:\n% -------------------------------------------------------------------------\n% Author: Cara Manning cmanning@whoi.edu \n%\n% COPYRIGHT:---------------------------------------------------------------\n%\n% Copyright 2015 David Nicholson and Cara Manning \n%\n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n%\n% http://www.apache.org/licenses/LICENSE-2.0\n%\n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n%\n% =========================================================================\n\nfunction [Fd, Fc, Fp, Deq] = fas(C,u10,S,T,slp,gas,param,rh)\n\n% if humidity is not provided, set to 0.8 for all values\nif nargin == 8\n if mean(rh) < 0 || mean(rh) > 1\n error('Relative humidity must be 0 <= rh <= 1');\n end\nelse\n rh =0.8.*ones(size(C));\nend\n \n\nswitch upper(param)\n case 'S09'\n [Fd, Fc, Fp, Deq] = fas_S09(C,u10,S,T,slp,gas,rh);\n case 'N11'\n [Fd, Fc, Fp, Deq] = fas_N11(C,u10,S,T,slp,gas,rh);\n case 'SW07'\n [Fd, Fc, Fp, Deq] = fas_Sw07(C,u10,S,T,slp,gas,rh);\n case 'L13'\n [Fd, Fp, Fc, Deq] = fas_L13(C,u10,S,T,slp,gas,rh);\n otherwise\n error('only S09,N11,Sw07 and L13 are supported');\nend\n\n\nend"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "sw_ptmp.m", "ext": ".m", "path": "oce_tools-master/gas_toolbox/other_functions/sw_ptmp.m", "size": 3684, "source_encoding": "utf_8", "md5": "cf912e62bc1cde2044b0471353899d97", "text": "\r\nfunction PT = sw_ptmp(S,T,P,PR)\r\n\r\n% SW_PTMP Potential temperature\r\n%===========================================================================\r\n% SW_PTMP $Id: sw_ptmp.m,v 1.1 2003/12/12 04:23:22 pen078 Exp $\r\n% Copyright (C) CSIRO, Phil Morgan 1992.\r\n%\r\n% USAGE: ptmp = sw_ptmp(S,T,P,PR)\r\n%\r\n% DESCRIPTION:\r\n% Calculates potential temperature as per UNESCO 1983 report.\r\n%\r\n% INPUT: (all must have same dimensions)\r\n% S = salinity [psu (PSS-78) ]\r\n% T = temperature [degree C (ITS-90)]\r\n% P = pressure [db]\r\n% PR = Reference pressure [db]\r\n% (P & PR may have dims 1x1, mx1, 1xn or mxn for S(mxn) )\r\n%\r\n% OUTPUT:\r\n% ptmp = Potential temperature relative to PR [degree C (ITS-90)]\r\n%\r\n% AUTHOR: Phil Morgan 92-04-06, Lindsay Pender (Lindsay.Pender@csiro.au)\r\n%\r\n% DISCLAIMER:\r\n% This software is provided \"as is\" without warranty of any kind.\r\n% See the file sw_copy.m for conditions of use and licence.\r\n%\r\n% REFERENCES:\r\n% Fofonoff, P. and Millard, R.C. Jr\r\n% Unesco 1983. Algorithms for computation of fundamental properties of\r\n% seawater, 1983. _Unesco Tech. Pap. in Mar. Sci._, No. 44, 53 pp.\r\n% Eqn.(31) p.39\r\n%\r\n% Bryden, H. 1973.\r\n% \"New Polynomials for thermal expansion, adiabatic temperature gradient\r\n% and potential temperature of sea water.\"\r\n% DEEP-SEA RES., 1973, Vol20,401-408.\r\n%=========================================================================\r\n\r\n% Modifications\r\n% 99-06-25. Lindsay Pender, Fixed transpose of row vectors.\r\n% 03-12-12. Lindsay Pender, Converted to ITS-90.\r\n\r\n% CALLER: general purpose\r\n% CALLEE: sw_adtg.m\r\n\r\n%-------------\r\n% CHECK INPUTS\r\n%-------------\r\nif nargin ~= 4\r\n error('sw_ptmp.m: Must pass 4 parameters ')\r\nend %if\r\n\r\n% CHECK S,T,P dimensions and verify consistent\r\n[ms,ns] = size(S);\r\n[mt,nt] = size(T);\r\n[mp,np] = size(P);\r\n\r\n[mpr,npr] = size(PR);\r\n\r\n\r\n% CHECK THAT S & T HAVE SAME SHAPE\r\nif (ms~=mt) | (ns~=nt)\r\n error('check_stp: S & T must have same dimensions')\r\nend %if\r\n\r\n% CHECK OPTIONAL SHAPES FOR P\r\nif mp==1 & np==1 % P is a scalar. Fill to size of S\r\n P = P(1)*ones(ms,ns);\r\nelseif np==ns & mp==1 % P is row vector with same cols as S\r\n P = P( ones(1,ms), : ); % Copy down each column.\r\nelseif mp==ms & np==1 % P is column vector\r\n P = P( :, ones(1,ns) ); % Copy across each row\r\nelseif mp==ms & np==ns % PR is a matrix size(S)\r\n % shape ok\r\nelse\r\n error('check_stp: P has wrong dimensions')\r\nend %if\r\n[mp,np] = size(P);\r\n\r\n\r\n% CHECK OPTIONAL SHAPES FOR PR\r\nif mpr==1 & npr==1 % PR is a scalar. Fill to size of S\r\n PR = PR(1)*ones(ms,ns);\r\nelseif npr==ns & mpr==1 % PR is row vector with same cols as S\r\n PR = PR( ones(1,ms), : ); % Copy down each column.\r\nelseif mpr==ms & npr==1 % P is column vector\r\n PR = PR( :, ones(1,ns) ); % Copy across each row\r\nelseif mpr==ms & npr==ns % PR is a matrix size(S)\r\n % shape ok\r\nelse\r\n error('check_stp: PR has wrong dimensions')\r\nend %if\r\n\r\n%***check_stp\r\n\r\n%------\r\n% BEGIN\r\n%------\r\n\r\n% theta1\r\ndel_P = PR - P;\r\ndel_th = del_P.*sw_adtg(S,T,P);\r\nth = T * 1.00024 + 0.5*del_th;\r\nq = del_th;\r\n\r\n% theta2\r\ndel_th = del_P.*sw_adtg(S,th/1.00024,P+0.5*del_P);\r\nth = th + (1 - 1/sqrt(2))*(del_th - q);\r\nq = (2-sqrt(2))*del_th + (-2+3/sqrt(2))*q;\r\n\r\n% theta3\r\ndel_th = del_P.*sw_adtg(S,th/1.00024,P+0.5*del_P);\r\nth = th + (1 + 1/sqrt(2))*(del_th - q);\r\nq = (2 + sqrt(2))*del_th + (-2-3/sqrt(2))*q;\r\n\r\n% theta4\r\ndel_th = del_P.*sw_adtg(S,th/1.00024,P+del_P);\r\nPT = (th + (del_th - 2*q)/6)/1.00024;\r\nreturn\r\n%=========================================================================\r\n\r\n"} +{"plateform": "github", "repo_name": "boom-lab/oce_tools-master", "name": "oc_url.m", "ext": ".m", "path": "oce_tools-master/ocean_color/oc_url.m", "size": 5048, "source_encoding": "utf_8", "md5": "7d60af451fb1283f252c478781e4a8a7", "text": "function [ fname ] = oc_url(t,var,varargin)\n% oc_url\n% -------------------------------------------------------------------------\n% construncts netCDF filename for NASA Ocean Color OpenDAP server\n% link - http://oceandata.sci.gsfc.nasa.gov/opendap/\n% -------------------------------------------------------------------------\n% USAGE:\n% -------------------------------------------------------------------------\n% [fname] = oc_url(t,'par')\n% \n% [fname] = oc_url(t,'par','sensor','VIIRS','trange','DAY','res','4km')\n%\n% -------------------------------------------------------------------------\n% INPUTS:\n% -------------------------------------------------------------------------\n% Required\n% t: datetime or datenum time input - vector or scalar\n% var: string of input variable\n% \n% Optional parameters\n% NAME DEFAULT\n% -- -----\n% sensor: 'MODISA' \n% level: 'L3SMI' \n% trange: '8D' temporal option\n% res: '9km' spatial resolution\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% -------------------------------------------------------------------------\n% fname: full opendap address of requested file\n%\n% -------------------------------------------------------------------------\n% ABOUT: David Nicholson // dnicholson@whoi.edu // 29 JUN 2015\n% -------------------------------------------------------------------------\n\nfroot = 'http://oceandata.sci.gsfc.nasa.gov/opendap';\n%% parse inputs\ndefaultLevel = 'L3SMI';\nexpectedLevel = {'L3SMI'};\ndefaultSensor = 'MODISA';\nexpectedSensor = {'MODISA','MODIST','VIIRS','SeaWiFS','Aquarius'};\ndefaultTrange = '8D';\nexpectedTrange = {'8D','R32','DAY','MO','YR'};\ndefaultRes = '9km';\nexpectedRes = {'4km','9km'};\n%%% parse input parameters\npersistent p\nif isempty(p)\n p = inputParser;\n \n addRequired(p,'t',@(x) isnumeric(x) || isdatetime(x));\n addRequired(p,'var',@isstr);\n \n addParameter(p,'trange',defaultTrange,@(x) any(validatestring(x,expectedTrange)));\n addParameter(p,'res',defaultRes,@(x) any(validatestring(x,expectedRes)));\n addParameter(p,'sensor',defaultSensor,@(x) any(validatestring(x,expectedSensor)));\n addParameter(p,'level',defaultLevel,@(x) any(validatestring(x,expectedLevel)));\nend\nparse(p,t,var,varargin{:});\ninputs = p.Results;\n\n% OPENDAP root directory for sensor and level\nsensor = inputs.sensor;\nlevel = inputs.level;\nres = inputs.res;\ntrange = inputs.trange;\n\nsensorCode = {'A','T','V','S','Q'};\nsensor2code = containers.Map(expectedSensor,sensorCode);\n\n\n%% clean up t and construct full filename\n\n% determine variable suite from variable name\n% valid suites are RRS, CHL, KD490, PAR, PIC, POC, FLH, SST, SST4, and NSST\n% !!! sst shows up twice !!!\nswitch var\n case {'chl_ocx','chlor_a'}\n suite = 'CHL';\n case {'ipar','nflh'}\n suite = 'FLH';\n case {'a_','adg_','aph_','bb_','bbp_'}\n suite = 'IOP';\n case {'Kd_490'}\n suite = 'KD490';\n case 'nsst'\n % call 'nsst' to get 'sst' var from NSST suite\n suite = 'NSST';\n var = 'sst';\n case 'par'\n suite = 'PAR';\n case 'pic'\n suite = 'PIC';\n case 'poc'\n suite = 'POC';\n case strncmpi(var,'RRS_',4)\n suite = 'RRS';\n case 'sst4'\n suite = 'SST4';\n case 'sst'\n suite = 'SST';\n otherwise\n if strncmpi(var,'Rrs_',4)\n suite = 'RRS';\n elseif ismember(var(1:3),{'a_4','a_5','a_6','adg','aph','bb_','bbp'})\n suite = 'IOP';\n else\n error('unsuported/invalid variable name');\n end\nend\n\n% append NPP prefix to VIIRS file path\nif strcmpi(sensor,'VIIRS')\n suite = ['NPP_' suite];\nend\n\n% time in datetime - dateshift ensures there are not artifacts from\n% numerical rounding errors in conversion from datenum\nif ~isdatetime(t)\n dtm = datetime(t, 'ConvertFrom', 'datenum');\nelse\n dtm = t;\nend\ndtm = dateshift(dtm,'start','second','nearest');\n\n% adjust time to nearest date with available data\nsCode = sensor2code(sensor);\nswitch trange\n case {'8D','R32'}\n % round to 8th days (1,9,17,25,....)\n t1 = dtm-rem(day(dtm,'dayofyear'),8) + 1;\n if strcmpi(trange,'8D')\n tStr = [sCode,dstr(t1),dstr(t1+7)];\n else\n tStr = [sCode,dstr(t1),dstr(t1+31)];\n end\n case 'DAY'\n t1 = dtm;\n tStr = [sCode,dstr(dtm)];\n case 'MO'\n t1 = dateshift(dtm,'start','month');\n t2 = dateshift(dtm,'end','month');\n tStr = [sCode,dstr(t1),dstr(t2)];\n case 'YR'\n t1 = dateshift(dtm,'start','year');\n t2 = dateshift(dtm,'end','year');\n tStr = [sCode,dstr(t1),dstr(t2)];\n otherwise\n error('time string is invalid');\nend\n\n\n% construct OPENDAP address string for first file\nfname = fullfile(froot,sensor,level,num2str(year(t1)),...\n num2str(day(t1,'dayofyear'),'%03d'),...\n [tStr,'.L3m_',trange,'_',suite,'_',var,'_',res,'.nc']);\nend\nfunction [outstr] = dstr(t)\n outstr = [num2str(year(t)), num2str(day(t,'dayofyear'),'%03d')];\nend\n\n\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_results.m", "ext": ".m", "path": "spm5-master/spm_config_results.m", "size": 4712, "source_encoding": "utf_8", "md5": "c9c6c0c2c47b93a33eda1a7aadfe4072", "text": "function conf = spm_config_results\n% Configuration file for results reporting\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% $Id: spm_config_results.m 1563 2008-05-07 14:16:43Z ferath $\n\n\n%-------------------------------------------------------------------------\n\nspm.type = 'files';\nspm.name = 'Select SPM.mat';\nspm.tag = 'spmmat';\nspm.num = [1 1];\nspm.filter = 'mat';\nspm.ufilter = '^SPM\\.mat$';\nspm.help = {'Select the SPM.mat file that contains the design specification.'};\n\nprint.type = 'menu';\nprint.name = 'Print results';\nprint.tag = 'print';\nprint.labels = {'Yes','No'};\nprint.values = {1,0};\nprint.val = {1};\n\n%-------------------------------------------------------------------------\n\nthreshdesc.type = 'menu';\nthreshdesc.name = 'Threshold type';\nthreshdesc.tag = 'threshdesc';\nthreshdesc.labels = {'FWE','FDR','none'};\nthreshdesc.values = {'FWE','FDR','none'};\n\nthresh.type = 'entry';\nthresh.name = 'Threshold';\nthresh.tag = 'thresh';\nthresh.strtype = 'e';\nthresh.num = [1 1];\nthresh.val = {.05};\n\nextent.type = 'entry';\nextent.name = 'Extent (voxels)';\nextent.tag = 'extent';\nextent.strtype = 'e';\nextent.num = [1 1];\nextent.val = {0};\n\ntitlestr.type = 'entry';\ntitlestr.name = 'Results Title';\ntitlestr.tag = 'titlestr';\ntitlestr.strtype = 's';\ntitlestr.num = [1 1];\ntitlestr.help = {['Heading on results page - determined automatically if' ...\n\t\t ' left empty']};\ntitlestr.val = {''};\n\ncontrasts.type = 'entry';\ncontrasts.name = 'Contrast(s)';\ncontrasts.tag = 'contrasts';\ncontrasts.strtype = 'e';\ncontrasts.num = [1 Inf];\ncontrasts.help = {['Index of contrast(s). If more than one number is' ...\n\t\t ' entered, analyse a conjunction hypothesis.'], ...\n\t\t '',...\n\t\t ['If only one number is entered, and this number is' ...\n\t\t ' \"Inf\", then results are printed for all contrasts' ...\n\t\t ' found in the SPM.mat file.']};\n\n%-------------------------------------------------------------------------\n\nmthresh = thresh;\nmthresh.name = 'Mask threshold';\n\nmcons = contrasts;\nmcons.help = {'Index of contrast(s) for masking - leave empty for no masking.'};\n\nmtype.type = 'menu';\nmtype.name = 'Nature of mask';\nmtype.tag = 'mtype';\nmtype.labels = {'Inclusive','Exclusive'};\nmtype.values = {0,1};\n\nmask.type = 'branch';\nmask.name = 'Mask definition';\nmask.tag = 'mask';\nmask.val = {mcons, mthresh, mtype};\n\nmasks.type = 'repeat';\nmasks.name = 'Masking';\nmasks.tag = 'masks';\nmasks.values = {mask};\nmasks.num = [0 1];\n\n%-------------------------------------------------------------------------\n\nconspec.type = 'branch';\nconspec.name = 'Contrast query';\nconspec.tag = 'conspec';\nconspec.val = {titlestr, contrasts, threshdesc, thresh, extent, masks};\n\nconspecs.type = 'repeat';\nconspecs.name = 'Contrasts';\nconspecs.tag = 'conspecs';\nconspecs.values = {conspec};\nconspecs.num = [1 Inf];\n\n%-------------------------------------------------------------------------\n\nconf.type = 'branch';\nconf.name = 'Results Report';\nconf.tag = 'results';\nconf.val = {spm,conspecs,print};\nconf.prog = @run_results;\nconf.modality = {'FMRI','PET'};\n\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction run_results(job)\ncspec = job.conspec;\nfor k = 1:numel(cspec)\n job.conspec=cspec(k);\n if (numel(cspec(k).contrasts) == 1) && isinf(cspec(k).contrasts)\n tmp=load(job.spmmat{1});\n for l=1:numel(tmp.SPM.xCon)\n cspec1(l) = cspec(k);\n cspec1(l).contrasts = l;\n end;\n job1 = job;\n job1.print = 1;\n job1.conspec = cspec1;\n run_results(job1);\n else\n xSPM.swd = spm_str_manip(job.spmmat{1},'H');\n xSPM.Ic = job.conspec.contrasts;\n xSPM.u = job.conspec.thresh;\n xSPM.Im = [];\n if ~isempty(job.conspec.mask)\n xSPM.Im = job.conspec.mask.contrasts;\n xSPM.pm = job.conspec.mask.thresh;\n xSPM.Ex = job.conspec.mask.mtype;\n end\n xSPM.thresDesc = job.conspec.threshdesc;\n xSPM.u = job.conspec.thresh;\n xSPM.title = job.conspec.titlestr;\n xSPM.k = job.conspec.extent;\n [hReg xSPM SPM] = spm_results_ui('Setup',xSPM);\n if job.print\n spm_list('List',xSPM,hReg);\n spm_figure('Print');\n end\n assignin('base','hReg',hReg);\n assignin('base','xSPM',xSPM);\n assignin('base','SPM',SPM);\n end\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_datareg.m", "ext": ".m", "path": "spm5-master/spm_eeg_inv_datareg.m", "size": 13392, "source_encoding": "utf_8", "md5": "1618e2bb99be5372a0829b942500f881", "text": "function [varargout] = spm_eeg_inv_datareg(varargin)\n\n%==========================================================================\n% Rigid registration of the EEG/MEG data and sMRI spaces\n%\n% FORMAT D = spm_eeg_inv_datareg(S)\n% rigid co-registration\n% 1: fiducials based (3 landmarks: nasion, left ear, right ear)\n% 2: surface matching between sensor mesh and headshape\n% (starts with a type 1 registration)\n% Input:\n% D - input data struct (optional)\n% Output:\n% D - data struct including the new files and parameters\n%\n% FORMAT [eeg2mri,sen_reg,fid_reg,hsp_reg,orient_reg,mri2eeg,hsp2eeg]\n% = spm_eeg_inv_datareg(sensors,fid_eeg,fid_mri,headshape,scalpvert,megorient,template)\n% Input:\n%\n% sensors - a matrix coordinate of the sensor\n% locations ([Sx1 Sy1 Sz1 ; Sx2 Sy2 Sz2 ; ...])\n% fid_eeg - the fiducial coordinates in sensor\n% space ([Nx Ny Nz ; LEx LEy LEz ; REx REy REz])\n% fid_mri - the fiducial coordinates in sMRI\n% space ([nx ny nz ; lex ley lez ; rex rey rez])\n% headshape - the headshape point coordinates in\n% sensor space ([hx1 hy1 hz1 ; hx2 hy2 hz2 ; ...])\n% scalpvert - the vertices coordinates of the scalp\n% tesselation in mri space ([vx1 vy1 vz1 ; vx2 vy2 vz2 ;\n% ...])\n% megorient - the sensor orientations ([ox1 oy1 oz1 ; ox2 oy2 oz2 ; ...])\n% (MEG only)\n% template - 0/1 switch to enable affine mri2eeg transform\n%\n% IMPORTANT: all the coordinates must be in the same units (mm).\n%\n% Output:\n% eeg2mri - rigid transformation (Rotation + Translation)\n% sen_reg - the registered sensor coordinates in sMRI space\n% fid_reg - the registered fiduicals coordinates in sMRI space\n% hsp_reg - the registered headshap point coordinates in sMRI space\n% orient_reg - the registrated sensor orientations (MEG only)\n%\n% If a template is used, the senor locations are transformed using an\n% affine (rigid body) mapping. If headshape locations are supplied \n% this is generalized to a full twelve parameter affine mapping (n.b.\n% this might not be appropriate for MEG data).\n%==========================================================================\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Jeremie Mattout\n% $Id: spm_eeg_inv_datareg.m 1058 2008-01-03 15:58:02Z guillaume $\n\n% Modified by Rik Henson to handle gradiometers (with two positions/orientations \n% for component coils) 4/6/07\n\n% Check input arguments\n%==========================================================================\n\n% % spm_eeg_inv_datareg(D)\n%--------------------------------------------------------------------------\nif nargin < 3\n try\n [D val] = spm_eeg_inv_check(varargin{:});\n sensors = D.inv{val}.datareg.sensors;\n fid_eeg = D.inv{val}.datareg.fid_eeg;\n fid_mri = D.inv{val}.datareg.fid_mri;\n headshape = D.inv{val}.datareg.headshape;\n scalpvert = D.inv{val}.datareg.scalpvert;\n if strcmp(D.modality,'MEG')\n megorient = D.inv{val}.datareg.megorient;\n else\n megorient = sparse(0,3);\n end\n template = D.inv{val}.mesh.template;\n catch\n D = spm_eeg_inv_datareg_ui(varargin{:});\n D = spm_eeg_inv_datareg(D);\n end\n\n% spm_eeg_inv_datareg(sensors,fid_eeg,fid_mri,headshape,scalpvert,megorient,template)\n%--------------------------------------------------------------------------\nelse\n sensors = varargin{1};\n fid_eeg = varargin{2};\n fid_mri = varargin{3};\n \n try, headshape = varargin{4}; catch, headshape = sparse(0,3); end\n try, scalpvert = varargin{5}; catch, scalpvert = sparse(0,3); end\n try, megorient = varargin{6}; catch, megorient = sparse(0,3); end\n try, template = varargin{7}; catch, template = 0; end\nend\n\n% The fiducial coordinates must be in the same order (usually: NZ & LE, RE)\n%--------------------------------------------------------------------------\nnfid = size(fid_eeg,1);\nif nfid ~= size(fid_mri,1)\n warndlg('Please specify the same number of MRI and EEG/MEG fiducials');\n return\nend\n \n% Estimate-apply rigid body transform to sensor space\n%--------------------------------------------------------------------------\nM1 = spm_eeg_inv_rigidreg(fid_mri', fid_eeg');\nfid_eeg = M1*[fid_eeg'; ones(1,nfid)];\nfid_eeg = fid_eeg(1:3,:)';\n\n\nif template\n \n % constatined affine transform\n %--------------------------------------------------------------------------\n aff = 1;\n for i = 1:16\n \n % scale\n %----------------------------------------------------------------------\n M = pinv(fid_eeg(:))*fid_mri(:);\n M = sparse(1:4,1:4,[M M M 1]);\n fid_eeg = M*[fid_eeg'; ones(1,nfid)];\n fid_eeg = fid_eeg(1:3,:)';\n M1 = M*M1;\n\n % and move\n %----------------------------------------------------------------------\n M = spm_eeg_inv_rigidreg(fid_mri', fid_eeg');\n fid_eeg = M*[fid_eeg'; ones(1,nfid)];\n fid_eeg = fid_eeg(1:3,:)';\n M1 = M*M1;\n\n end\nelse \n aff = 0; \nend\n\n% assume headshape locations are registered to sensor fiducials\n%--------------------------------------------------------------------------\nM2 = M1;\n\n% Surface matching between the scalp vertices in MRI space and\n% the headshape positions in data space\n%--------------------------------------------------------------------------\nif length(headshape)\n\n % load surface locations from sMRI\n %----------------------------------------------------------------------\n if size(headshape,2) > size(headshape,1)\n headshape = headshape';\n end\n if size(scalpvert,2) > size(scalpvert,1)\n scalpvert = scalpvert';\n end\n \n \n % move headshape locations (NB: future code will allow for hsp fiducials)\n %----------------------------------------------------------------------\n % fid_hsp = headshape(1:3,:);\n % M2 = spm_eeg_inv_rigidreg(fid_eeg', fid_hsp');\n headshape = M2*[headshape'; ones(1,size(headshape,1))];\n headshape = headshape(1:3,:)';\n\n % intialise plot\n %----------------------------------------------------------------------\n h = spm_figure('GetWin','Graphics');\n clf(h); figure(h)\n set(h,'DoubleBuffer','on','BackingStore','on');\n Fmri = plot3(scalpvert(:,1),scalpvert(:,2),scalpvert(:,3),'ro','MarkerFaceColor','r');\n hold on;\n Fhsp = plot3(headshape(:,1),headshape(:,2),headshape(:,3),'bs','MarkerFaceColor','b');\n axis off image\n drawnow\n\n % nearest point registration\n %----------------------------------------------------------------------\n M = spm_eeg_inv_icp(scalpvert',headshape',fid_mri',fid_eeg',Fmri,Fhsp,aff);\n \n % transform headshape and eeg fiducials\n %----------------------------------------------------------------------\n headshape = M*[headshape'; ones(1,size(headshape,1))];\n headshape = headshape(1:3,:)';\n fid_eeg = M*[fid_eeg'; ones(1,nfid)];\n fid_eeg = fid_eeg(1:3,:)';\n M1 = M*M1;\n \nend\n\n% Update the sensor locations and orientation\n%--------------------------------------------------------------------------\nif size(sensors,2) == 3\t\t% Only one coil\n sensors = M1*[sensors'; ones(1,size(sensors,1))];\n sensors = sensors(1:3,:)';\n megorient = megorient*M1(1:3,1:3)';\nelseif size(sensors,2) == 6\t% Two coils (eg gradiometer)\n tmp1 = M1*[sensors(:,1:3)'; ones(1,size(sensors,1))];\n tmp2 = M1*[sensors(:,4:6)'; ones(1,size(sensors,1))];\n sensors = [tmp1(1:3,:); tmp2(1:3,:)]';\n tmp1 = megorient(:,1:3)*M1(1:3,1:3)';\n tmp2 = megorient(:,4:6)*M1(1:3,1:3)';\n megorient = [tmp1 tmp2];\nelse\n error('Unknown sensor coil locations')\nend\n\n% grad - for use of fieldtrip leadfield functions\n%--------------------------------------------------------------------------\ntry\n grad = D.inv{val}.datareg.grad;\n grad_coreg.pnt = M1*[grad.pnt'*10; ones(1,size(grad.pnt,1))];\n grad_coreg.pnt = grad_coreg.pnt(1:3,:)'/10;\n grad_coreg.ori = grad.ori*M1(1:3,1:3)';\n grad_coreg.tra = grad.tra;\ncatch\n grad_coreg = [];\nend\n \n% retain valid sensor locations for leadfield computation\n%--------------------------------------------------------------------------\nif nargin < 3\n try\n sens = setdiff(D.channels.eeg, D.channels.Bad);\n catch\n sens = D.channels.eeg;\n D.channels.Bad = [];\n end\n sensors = sensors(sens,:);\n if strcmp(D.modality,'MEG')\n megorient = megorient(sens,:);\n end\nend\n\n% ensure sensors lie outside the scalp\n%--------------------------------------------------------------------------\nif length(scalpvert) && strcmp(D.modality,'EEG')\n tri = delaunayn(scalpvert);\n j = dsearchn(scalpvert, tri, sensors(:,1:3));\n dist = sqrt(sum(sensors(:,1:3).^2,2)./sum(scalpvert(j,:).^2,2));\n dist = min(dist,1);\n sensors(:,1:3) = diag(1./dist)*sensors(:,1:3);\nend\n\n% Ouptut arguments\n%--------------------------------------------------------------------------\nif nargout == 1\n D.inv{val}.datareg.eeg2mri = M1;\n D.inv{val}.datareg.sens_coreg = sensors;\n D.inv{val}.datareg.fid_coreg = fid_eeg;\n D.inv{val}.datareg.hsp_coreg = headshape;\n D.inv{val}.datareg.sens_orient_coreg = megorient;\n D.inv{val}.datareg.sens = sens;\n D.inv{val}.datareg.grad_coreg = grad_coreg;\n\n varargout{1} = D;\nelse\n \n % varargout = {RT,sensors_reg,fid_reg,headshape_reg,orient_reg}\n %----------------------------------------------------------------------\n varargout{1} = M1;\n varargout{2} = sensors;\n varargout{3} = fid_eeg;\n varargout{4} = headshape;\n varargout{5} = megorient;\n\nend\n\nreturn\n\n%==========================================================================\nfunction [M1] = spm_eeg_inv_icp(data1,data2,fid1,fid2,Fmri,Fhsp,aff)\n\n% Iterative Closest Point (ICP) registration algorithm.\n% Surface matching computation: registration from one 3D surface (set data2 = [Dx1 Dy1 Dz1 ; Dx2 Dy2 Dz2 ; ...])\n% onto another 3D surface (set data1 = [dx1 dy1 dz1 ; dx2 dy2 dz2 ; ...])\n%\n% FORMAT [M1] = spm_eeg_inv_icp(data1,data2,fid1,fid2,Fmri,Fhsp,[aff])\n% Input:\n% data1 - locations of the first set of points corresponding to the\n% 3D surface to register onto (p points)\n% data2 - locations of the second set of points corresponding to the\n% second 3D surface to be registered (m points)\n% fid1 - sMRI fiducials\n% fid2 - sens fiducials\n% Fmri - graphics handle for sMRI points\n% Fhsp - graphics handle for headshape\n% aff - flag for 12 - parameter affine transform\n%\n% Output:\n% M1 - 4 x 4 affine transformation matrix for sensor space\n%==========================================================================\n% Adapted from (http://www.csse.uwa.edu.au/~ajmal/icp.m) written by Ajmal Saeed Mian {ajmal@csse.uwa.edu.au}\n% Computer Science, The University of Western Australia.\n\n% Jeremie Mattout & Guillaume Flandin\n\n% Landmarks (fiduciales) based registration\n% Fiducial coordinates must be given in the same order in both files\n\n% use figure and fiducials if specified\n%--------------------------------------------------------------------------\ntry, fid1; catch, fid1 = []; end\ntry, fid2; catch, fid2 = []; end\ntry, aff; catch, aff = 0; end\n\n\n% initialise rotation and translation of sensor space\n%--------------------------------------------------------------------------\nM1 = speye(4,4);\ntri = delaunayn(data1');\nfor i = 1:16\n\n % find nearest neighbours\n %----------------------------------------------------------------------\n [corr, D] = dsearchn(data1', tri, data2');\n corr(:,2) = [1 : length(corr)]';\n i = find(D > 32);\n corr(i,:) = [];\n M = [fid1 data1(:,corr(:,1))];\n S = [fid2 data2(:,corr(:,2))];\n\n % apply and accumlate affine scaling\n %----------------------------------------------------------------------\n if aff\n M = pinv([S' ones(length(S),1)])*M';\n M = [M'; 0 0 0 1];\n \n else\n % 6-parmaeter affine (i.e. rigid body)\n %----------------------------------------------------------------------\n M = spm_eeg_inv_rigidreg(M,S);\n end\n \n data2 = M*[data2; ones(1,size(data2,2))];\n data2 = data2(1:3,:);\n fid2 = M*[fid2; ones(1,size(fid2,2))];\n fid2 = fid2(1:3,:);\n M1 = M*M1;\n\n % plot\n %----------------------------------------------------------------------\n try\n set(Fmri,'XData',data1(1,:),'YData',data1(2,:),'ZData',data1(3,:));\n set(Fhsp,'XData',data2(1,:),'YData',data2(2,:),'ZData',data2(3,:));\n drawnow\n end\n\nend\nreturn\n%==========================================================================\n\n\n%==========================================================================\nfunction [M1] = spm_eeg_inv_rigidreg(data1, data2)\nM = spm_detrend(data1');\nS = spm_detrend(data2');\n[U A V] = svd(S'*M);\nR1 = V*U';\nif det(R1) < 0\n B = eye(3);\n B(3,3) = det(V*U');\n R1 = V*B*U';\nend\nt1 = mean(data1,2) - R1*mean(data2,2);\nM1 = [R1 t1; 0 0 0 1];\n\nreturn\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_vb_ppm_anova.m", "ext": ".m", "path": "spm5-master/spm_vb_ppm_anova.m", "size": 3883, "source_encoding": "utf_8", "md5": "cf4c32a78589f807a84ec4b5826260ab", "text": "function spm_vb_ppm_anova(SPM)\n% Bayesian ANOVA using model comparison\n% FORMAT spm_vb_ppm_anova(SPM)\n%\n% SPM - Data structure corresponding to a full model (ie. one\n% containing all experimental conditions).\n% \n% This function creates images of differences in log evidence\n% which characterise the average effect, main effects and interactions\n% in a factorial design. \n%\n% The factorial design is specified in SPM.factor. For a one-way ANOVA \n% the images \n%\n% avg_effect.img\n% main_effect.img\n%\n% are produced. For a two-way ANOVA the following images are produced\n%\n% avg_effect.img\n% main_effect_'factor1'.img\n% main_effect_'factor2'.img\n% interaction.img\n%\n% These images can then be thresholded. For example a threshold of 4.6 \n% corresponds to a posterior effect probability of [exp(4.6)] = 0.999. \n% See paper VB4 for more details.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Will Penny\n% $Id: spm_vb_ppm_anova.m 300 2005-11-16 21:05:24Z guillaume $\n\n \ndisp('Warning: spm_vb_ppm_anova only works for single session data.');\n\nmodel = spm_vb_models(SPM,SPM.factor);\n\nanalysis_dir = pwd;\nfor m=1:length(model)-1,\n model_subdir = ['model_',int2str(m)];\n mkdir(analysis_dir,model_subdir);\n SPM.swd = fullfile(analysis_dir,model_subdir);\n SPM.Sess(1).U = model(m).U;\n SPM.Sess(1).U = spm_get_ons(SPM,1);\n SPM = spm_fMRI_design(SPM,0); % 0 = don't save SPM.mat\n SPM.PPM.update_F = 1; % Compute evidence for each model\n SPM.PPM.compute_det_D = 1; \n spm_spm_vb(SPM);\nend\n\n% Compute differences in contributions to log-evidence images\n% to assess main effects and interactions\nnf = length(SPM.factor);\nif nf==1\n % For a single factor\n \n % Average effect\n image1 = fullfile(analysis_dir, 'model_1','LogEv.img');\n image2 = fullfile(analysis_dir, 'model_2','LogEv.img');\n imout = fullfile(analysis_dir, 'avg_effect.img');\n img_subtract(image1,image2,imout);\n \n % Main effect of factor\n image1 = fullfile(analysis_dir, 'model_2','LogEv.img');\n image2 = fullfile(analysis_dir, 'LogEv.img');\n imout = fullfile(analysis_dir, 'main_effect.img');\n img_subtract(image1,image2,imout);\n \nelseif nf==2\n % For two factors\n \n % Average effect\n image1 = fullfile(analysis_dir, 'model_1','LogEv.img');\n image2 = fullfile(analysis_dir, 'model_2','LogEv.img');\n imout = fullfile(analysis_dir, 'avg_effect.img');\n img_subtract(image1,image2,imout);\n \n % Main effect of factor 1\n image1 = fullfile(analysis_dir, 'model_2','LogEv.img');\n image2 = fullfile(analysis_dir, 'model_3','LogEv.img');\n imout = fullfile(analysis_dir, ['main_effect_',SPM.factor(1).name,'.img']);\n img_subtract(image1,image2,imout);\n \n % Main effect of factor 2\n image1 = fullfile(analysis_dir, 'model_2','LogEv.img');\n image2 = fullfile(analysis_dir, 'model_4','LogEv.img');\n imout = fullfile(analysis_dir, ['main_effect_',SPM.factor(2).name,'.img']);\n img_subtract(image1,image2,imout);\n \n % Interaction\n image1 = fullfile(analysis_dir, 'model_5','LogEv.img');\n image2 = fullfile(analysis_dir, 'LogEv.img');\n imout = fullfile(analysis_dir, 'interaction.img');\n img_subtract(image1,image2,imout);\n \nend\n \n%-----------------------------------------------------------------------\nfunction img_subtract(image1,image2,image_out)\n% Subtract image 1 from image 2 and write to image out\n% Note: parameters are names of files\n\nVi = spm_vol(strvcat(image1,image2));\nVo = struct(...\n 'fname', image_out,...\n 'dim', [Vi(1).dim(1:3)],...\n 'dt', [spm_type('float32') spm_platform('bigend')],...\n 'mat', Vi(1).mat,...\n 'descrip', 'Difference in Log Evidence');\nf = 'i2-i1';\nflags = {0,0,1};\nVo = spm_imcalc(Vi,Vo,f,flags);\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_vde.m", "ext": ".m", "path": "spm5-master/spm_eeg_inv_vde.m", "size": 4817, "source_encoding": "utf_8", "md5": "fe334e835d70d0ec1f54bf41a895ab9e", "text": "function varargout = spm_eeg_inv_vde(varargin)\n% SPM_EEG_INV_VDE M-file for spm_eeg_inv_vde.fig\n% SPM_EEG_INV_VDE, by itself, creates a new SPM_EEG_INV_VDE or raises the existing\n% singleton*.\n%\n% H = SPM_EEG_INV_VDE returns the handle to a new SPM_EEG_INV_VDE or the handle to\n% the existing singleton*.\n%\n% SPM_EEG_INV_VDE('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SPM_EEG_INV_VDE.M with the given input arguments.\n%\n% SPM_EEG_INV_VDE('Property','Value',...) creates a new SPM_EEG_INV_VDE or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before spm_eeg_inv_vde_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to spm_eeg_inv_vde_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Copyright 2002-2003 The MathWorks, Inc.\n\n% Edit the above text to modify the response to help spm_eeg_inv_vde\n\n% Last Modified by GUIDE v2.5 05-Dec-2006 09:07:07\n\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n% Jeremie Mattout\n% $Id: spm_eeg_inv_vde.m 1039 2007-12-21 20:20:38Z karl $\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @spm_eeg_inv_vde_OpeningFcn, ...\n 'gui_OutputFcn', @spm_eeg_inv_vde_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n% --- Executes just before spm_eeg_inv_vde is made visible.\nfunction spm_eeg_inv_vde_OpeningFcn(hObject, eventdata, handles, varargin)\nhandles.main_handles = varargin{1};\nset(handles.Location,'Enable','on');\nset(handles.Display,'Enable','off');\nhandles.output = hObject;\nguidata(hObject,handles);\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = spm_eeg_inv_vde_OutputFcn(hObject, eventdata, handles) \nvarargout{1} = handles.output;\n\n% --- Executes on button press in Location.\nfunction Location_Callback(hObject, eventdata, handles)\naxes(handles.main_handles.sources_axes);\nvert = handles.main_handles.vert;\nhandles.location = datacursormode(handles.main_handles.figure1);\nset(handles.location,'Enable','on','DisplayStyle','datatip','SnapToDataVertex','off');\nwaitforbuttonpress;\nvde = getCursorInfo(handles.location);\nvde = vde.Position;\ndatacursormode off\nCurrVert = sum(((ones(length(vert),1)*vde - vert).^2)');\nhandles.vde = find(CurrVert == min(CurrVert));\nset(handles.Location,'Enable','off');\nset(handles.Display,'Enable','on');\nguidata(hObject,handles);\n\n\n% --- Executes on button press in Size.\nfunction Size_Callback(hObject, eventdata, handles)\naxes(handles.main_handles.sources_axes);\nvert = handles.main_handles.vert;\nface = handles.main_handles.face;\nNeighbours = FindNeighB(handles.vde,face);\namp = handles.main_handles.srcs_disp;\nampref = amp(handles.vde(1));\nampnew = amp(Neighbours);\namptemp = abs(ampnew - ampref);\nnewsrc = find(amptemp == min(amptemp));\nhandles.vde = [handles.vde Neighbours(newsrc)];\naxes(handles.main_handles.sources_axes);\nhold on;\nhandles.hpts = plot3(vert(handles.vde,1),vert(handles.vde,2),vert(handles.vde,3),'sk','MarkerFaceColor','k','MarkerSize',14);\nguidata(hObject,handles);\n\n% --- Executes on button press in Display\nfunction Display_Callback(hObject, eventdata, handles)\nfigure;\nif length(handles.vde) > 1\n TimeSeries = mean(handles.main_handles.srcs_data(handles.vde,:)); \nelse\n TimeSeries = handles.main_handles.srcs_data(handles.vde,:);\nend\nD = handles.main_handles.D;\nwoi = D.inv{handles.main_handles.val}.inverse.woi;\nXstep = (woi(2) - woi(1))/(handles.main_handles.dimT - 1);\nX = woi(1):Xstep:woi(2);\nplot(X,TimeSeries,'r','LineWidth',3);\nset(handles.hpts,'Visible','off');\nhold off;\nclose(handles.figure1);\naxes(handles.main_handles.sources_axes)\ncameramenu on\n\nfunction Neighbours = FindNeighB(CurrVert,face)\nNeighbours = [];\nfor i = 1:length(CurrVert)\n [Icv,Jcv] = find(face == CurrVert(i));\n CurrNeigh = [];\n for j = 1:length(Icv)\n CurrNeigh = [CurrNeigh face(Icv(j),:)];\n end\n CurrNeigh = unique(CurrNeigh);\n Neighbours = [Neighbours CurrNeigh];\nend\nNeighbours = setdiff(Neighbours,CurrVert);\nreturn\n\nfunction pushbutton1_Callback(hObject,eventdata,handles)"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_ecd_DrawDip.m", "ext": ".m", "path": "spm5-master/spm_eeg_inv_ecd_DrawDip.m", "size": 19637, "source_encoding": "utf_8", "md5": "d19eae00a8f30a0d46d376b1732237a5", "text": "function varargout = spm_eeg_inv_ecd_DrawDip(action,varargin)\n\n%___________________________________________________________________\n%\n% spm_eeg_inv_ecd_DrawDip\n%\n% Function to display the dipoles as obtained from the optim routine.\n%\n% Use it with arguments or not:\n% - spm_eeg_inv_ecd_DrawDip('Init')\n% The routine asks for the dipoles file and image to display\n% - spm_eeg_inv_ecd_DrawDip('Init',sdip)\n% The routine will use the avg152T1 canonical image \n% - spm_eeg_inv_ecd_DrawDip('Init',sdip,P)\n% The routines dispays the dipoles on image P.\n%\n% If multiple seeds have been used, you can select the seeds to display \n% by pressing their index. \n% Given that the sources could have different locations, the slices\n% displayed will be the 3D view at the *average* or *mean* locations of\n% selected sources.\n% If more than 1 dipole was fitted at a time, then selection of source 1 \n% to N is possible through the pull-down selector.\n%\n% The location of the source/cut is displayed in mm and voxel, as well as\n% the underlying image intensity at that location.\n% The cross hair position can be hidden by clicking on its button.\n%\n% Nota_1: If the cross hair is manually moved by clicking in the image or\n% changing its coordinates, the dipole displayed will NOT be at\n% the right displayed location. That's something that needs to be improved...\n%\n% Nota_2: Some seeds may have not converged within the limits fixed,\n% these dipoles are not displayed...\n%\n% Fields needed in sdip structure to plot on an image:\n% + n_seeds: nr of seeds set used, i.e. nr of solutions calculated\n% + n_dip: nr of fitted dipoles on the EEG time series\n% + loc: location of fitted dipoles, cell{1,n_seeds}(3 x n_dip)\n% remember that loc is fixed over the time window.\n% + j: sources amplitude over the time window, \n% cell{1,n_seeds}(3*n_dip x Ntimebins)\n% + Mtb: index of maximum power in EEG time series used\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Christophe Phillips,\n% $Id$\n\nglobal st\nglobal defaults\nsw = warning('off','all');\n\nFig = spm_figure('GetWin','Graphics');\ncolors = strvcat('y','b','g','r','c','m'); % 6 possible colors\nmarker = strvcat('o','x','+','*','s','d','v','p','h'); % 9 possible markers\nNcolors = length(colors);\nNmarker = length(marker);\n\nif nargin == 0, action = 'Init'; end;\n\nswitch lower(action),\n%________________________________________________________________________\ncase 'init'\n%------------------------------------------------------------------------\n% FORMAT spm_eeg_inv_ecd_DrawDip('Init',sdip,P)\n% Initialise the variables with GUI\n% e.g. spm_eeg_inv_ecd_DrawDip('Init')\n%------------------------------------------------------------------------\n\nif nargin < 2\n load(spm_select(1,'^.*S.*dip.*\\.mat$','Select dipole file'));\n if ~exist('sdip') & exist('result')\n sdip = result;\n end\nelse\n sdip = varargin{1};\nend\n\n% if the exit flag is not in the structure, assume everything went ok.\nif ~isfield(sdip,'exitflag')\n sdip.exitflag = ones(1,sdip.n_seeds);\nend\n\ntry\n P = varargin{2};\ncatch\n P = fullfile(spm('dir'),'canonical','avg152T1.nii');\nend\nif ischar(P), P = spm_vol(P); end;\nspm_orthviews('Reset');\nspm_orthviews('Image', P, [0.0 0.45 1 0.55]);\nspm_orthviews('MaxBB');\nst.callback = 'spm_image(''shopos'');';\n\n\nWS = spm('WinScale');\n\n% Build GUI\n%=============================\n% Location:\n%-----------\nuicontrol(Fig,'Style','Frame','Position',[60 25 200 325].*WS,'DeleteFcn','spm_image(''reset'');');\nuicontrol(Fig,'Style','Frame','Position',[70 250 180 90].*WS);\nuicontrol(Fig,'Style','Text', 'Position',[75 320 170 016].*WS,'String','Crosshair Position');\nuicontrol(Fig,'Style','PushButton', 'Position',[75 316 170 006].*WS,...\n\t'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');\n% uicontrol(fg,'Style','PushButton', 'Position',[75 315 170 020].*WS,'String','Crosshair Position',...\n%\t'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');\nuicontrol(Fig,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:');\nuicontrol(Fig,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:');\nuicontrol(Fig,'Style','Text', 'Position',[75 255 75 020].*WS,'String','Img Intens.:');\n\nst.mp = uicontrol(Fig,'Style','edit', 'Position',[110 295 135 020].*WS,'String','','Callback','spm_image(''setposmm'')','ToolTipString','move crosshairs to mm coordinates');\nst.vp = uicontrol(Fig,'Style','edit', 'Position',[110 275 135 020].*WS,'String','','Callback','spm_image(''setposvx'')','ToolTipString','move crosshairs to voxel coordinates');\nst.in = uicontrol(Fig,'Style','Text', 'Position',[150 255 85 020].*WS,'String','');\n\nc = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;';\nuicontrol(Fig,'Style','togglebutton','Position',[95 220 125 20].*WS,...\n\t'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs');\n\n% Dipoles/seeds selection:\n%--------------------------\nuicontrol(Fig,'Style','Frame','Position',[300 25 180 325].*WS);\nsdip.hdl.hcl = uicontrol(Fig,'Style','pushbutton','Position',[310 320 100 20].*WS, ...\n 'String','Clear all','CallBack','spm_eeg_inv_ecd_DrawDip(''ClearAll'')');\n\nsdip.hdl.hseed=zeros(sdip.n_seeds,1);\nfor ii=1:sdip.n_seeds\n if sdip.exitflag(ii)==1\n sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','togglebutton','String',num2str(ii),...\n 'Position',[310+rem(ii-1,8)*20 295-fix((ii-1)/8)*20 20 20].*WS,...\n 'CallBack','spm_eeg_inv_ecd_DrawDip(''ChgSeed'')');\n else\n sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','Text','String',num2str(ii), ...\n 'Position',[310+rem(ii-1,8)*20 293-fix((ii-1)/8)*20 20 20].*WS) ;\n end\nend\n\nuicontrol(Fig,'Style','text','String','Select dipole # :', ...\n 'Position',[310 255-fix((sdip.n_seeds-1)/8)*20 110 20].*WS);\n\ntxt_box = cell(sdip.n_dip,1);\nfor ii=1:sdip.n_dip, txt_box{ii} = num2str(ii); end\ntxt_box{sdip.n_dip+1} = 'all';\nsdip.hdl.hdip = uicontrol(Fig,'Style','popup','String',txt_box, ...\n 'Position',[420 258-fix((sdip.n_seeds-1)/8)*20 40 20].*WS, ...\n 'Callback','spm_eeg_inv_ecd_DrawDip(''ChgDip'')');\n\n% Dipoles orientation and strength:\n%-----------------------------------\nuicontrol(Fig,'Style','Frame','Position',[70 120 180 90].*WS);\nuicontrol(Fig,'Style','Text', 'Position',[75 190 170 016].*WS, ...\n 'String','Dipole orientation & strength');\nuicontrol(Fig,'Style','Text', 'Position',[75 165 65 020].*WS,'String','vn_x_y_z:');\nuicontrol(Fig,'Style','Text', 'Position',[75 145 75 020].*WS,'String','theta, phi:');\nuicontrol(Fig,'Style','Text', 'Position',[75 125 75 020].*WS,'String','Dip intens.:');\n \nsdip.hdl.hor1 = uicontrol(Fig,'Style','Text', 'Position',[140 165 105 020].*WS,'String','a');\nsdip.hdl.hor2 = uicontrol(Fig,'Style','Text', 'Position',[150 145 85 020].*WS,'String','b');\nsdip.hdl.int = uicontrol(Fig,'Style','Text', 'Position',[150 125 85 020].*WS,'String','c');\n \nst.vols{1}.sdip = sdip;\n\n% First plot = all the seeds that converged !\nl_conv = find(sdip.exitflag==1);\nif isempty(l_conv)\n error('No seed converged towards a stable solution, nothing to be displayed !')\nelse\n\tspm_eeg_inv_ecd_DrawDip('DrawDip',l_conv,1)\n\tset(sdip.hdl.hseed(l_conv),'Value',1); % toggle all buttons\nend\n \n% get(sdip.hdl.hseed(1),'Value')\n% for ii=1:sdip.n_seeds, delete(hseed(ii)); end\n% h1 = uicontrol(Fig,'Style','togglebutton','Position',[600 25 10 10].*WS)\n% h2 = uicontrol(Fig,'Style','togglebutton','Position',[620 100 20 20].*WS,'String','1')\n% h2 = uicontrol(Fig,'Style','checkbox','Position',[600 100 10 10].*WS)\n% h3 = uicontrol(Fig,'Style','radiobutton','Position',[600 150 20 20].*WS)\n% h4 = uicontrol(Fig,'Style','radiobutton','Position',[700 150 20 20].*WS)\n% delete(h2),delete(h3),delete(h4),\n% delete(hdip)\n\n%________________________________________________________________________\ncase 'drawdip'\n%------------------------------------------------------------------------\n% FORMAT spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip,sdip)\n% e.g. spm_eeg_inv_ecd_DrawDip('DrawDip',1,1,sdip)\n% e.g. spm_eeg_inv_ecd_DrawDip('DrawDip',[1:5],1,sdip)\n\n% when displaying a set of 'close' dipoles\n% this defines the limit between 'close' and 'far'\n% lim_cl = 10; %mm\n% No more limit. All source displayed as projected on mean 3D cut.\n\nif nargin < 2\n error('At least i_seed')\nend\ni_seed = varargin{1};\nif nargin<3\n i_dip = 1;\nelse\n i_dip = varargin{2}; \nend\n\nif nargin<4\n if isfield(st.vols{1},'sdip')\n sdip = st.vols{1}.sdip;\n else\n error('I can''t find sdip structure');\n end\nelse\n sdip = varargin{3};\n st.vols{1}.sdip = sdip;\nend\n\nif any(i_seed>sdip.n_seeds) | i_dip>(sdip.n_dip+1)\n error('Wrong i_seed or i_dip index in spm_eeg_inv_ecd_DrawDip');\nend\n\n% Note if i_dip==(sdip.n_dip+1) all dipoles are displayed simultaneously\nif i_dip == (sdip.n_dip+1)\n i_dip = 1:sdip.n_dip;\nend\n\n% if seed indexes passed is wrong (no convergence) remove the wrong ones\ni_seed(find(sdip.exitflag(i_seed)~=1)) = [];\nif isempty(i_seed)\n error('You passed the wrong seed indexes...')\nend\nif size(i_seed,2)==1, i_seed=i_seed'; end\n\n% Display business\n%-----------------\nloc_mm = sdip.loc{i_seed(1)}(:,i_dip);\nif length(i_seed)>1\n% unit = ones(1,sdip.n_dip);\n\tfor ii = i_seed(2:end)\n loc_mm = loc_mm + sdip.loc{ii}(:,i_dip);\n end\n loc_mm = loc_mm/length(i_seed);\nend\nif length(i_dip)>1\n loc_mm = mean(loc_mm,2);\nend\n\n% Place the underlying image at right cuts\nspm_orthviews('Reposition',loc_mm);\n\nif length(i_dip)>1\n tabl_seed_dip = [kron(ones(length(i_dip),1),i_seed') ...\n kron(i_dip',ones(length(i_seed),1))];\nelse\n tabl_seed_dip = [i_seed' ones(length(i_seed),1)*i_dip];\nend\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% % First point to consider\n% loc_mm = sdip.loc{i_seed(1)}(:,i_dip);\n% \n% % PLace the underlying image at right cuts\n% spm_orthviews('Reposition',loc_mm);\n% % spm_orthviews('Reposition',loc_vx);\n% % spm_orthviews('Xhairs','off')\n% \n% % if i_seed = set, Are there other dipoles close enough ?\n% tabl_seed_dip=[i_seed(1) i_dip]; % table summarising which set & dip to use.\n% if length(i_seed)>1\n% \tunit = ones(1,sdip.n_dip);\n% \tfor ii = i_seed(2:end)'\n% d2 = sqrt(sum((sdip.loc{ii}-loc_mm*unit).^2));\n% l_cl = find(d2<=lim_cl);\n% if ~isempty(l_cl)\n% for jj=l_cl\n% tabl_seed_dip = [tabl_seed_dip ; [ii jj]];\n% end\n% end\n% \tend\n% end\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Scaling, according to all dipoles in the selected seed sets.\n% The time displayed is the one corresponding to the maximum EEG power !\nMn_j = -1;\nl3 = -2:0;\nfor ii = 1:length(i_seed)\n for jj = 1:sdip.n_dip\n Mn_j = max([Mn_j sqrt(sum(sdip.j{ii}(jj*3+l3,sdip.Mtb).^2))]);\n end\nend\nst.vols{1}.sdip.tabl_seed_dip = tabl_seed_dip;\n\n% Display all dipoles, the 1st one + the ones close enough.\n% Run through the 6 colors and 9 markers to differentiate the dipoles.\n% NOTA: 2 dipoles coming from the same set will have same colour/marker\nind = 1 ;\ndip_h = zeros(6,size(tabl_seed_dip,1),1);\n % each dipole displayed has 6 handles:\n % 2 per view (2*3): one for the line, the other for the circle\njs_m = zeros(3,1);\n\n% Deal with case of multiple i_seed and i_dip displayed.\n% make sure dipole from same i_seed have same colour but different marker.\n\npi_dip = find(diff(tabl_seed_dip(:,2)));\nif isempty(pi_dip)\n % i.e. only one dip displayed per seed, use old fashion\n for ii=1:size(tabl_seed_dip,1)\n if ii>1\n if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1)\n ind = ind+1;\n end\n end\n ic = mod(ind-1,Ncolors)+1;\n im = fix(ind/Ncolors)+1;\n\n loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,tabl_seed_dip(ii,2));\n\n js = sdip.j{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,sdip.Mtb);\n dip_h(:,ii) = add1dip(loc_pl,js/Mn_j*20,marker(im),colors(ic),st.vols{1}.ax,Fig,st.bb);\n js_m = js_m+js;\n end\nelse\n for ii=1:pi_dip(1)\n if ii>1\n if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1)\n ind = ind+1;\n end\n end\n ic = mod(ind-1,Ncolors)+1;\n for jj=1:sdip.n_dip\n im = mod(jj-1,Nmarker)+1;\n \n loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,jj);\n js = sdip.j{tabl_seed_dip(ii,1)}(jj*3+l3,sdip.Mtb);\n js_m = js_m+js;\n dip_h(:,ii+(jj-1)*pi_dip(1)) = ...\n add1dip(loc_pl,js/Mn_j*20,marker(im),colors(ic), ...\n st.vols{1}.ax,Fig,st.bb);\n end\n end\nend\nst.vols{1}.sdip.ax = dip_h;\n\n% Display dipoles orientation and strength\njs_m = js_m/size(tabl_seed_dip,1);\n[th,phi,Ijs_m] = cart2sph(js_m(1),js_m(2),js_m(3));\nNjs_m = round(js_m'/Ijs_m*100)/100;\nAngle = round([th phi]*1800/pi)/10;\n\nset(sdip.hdl.hor1,'String',[num2str(Njs_m(1)),' ',num2str(Njs_m(2)), ...\n ' ',num2str(Njs_m(3))]);\nset(sdip.hdl.hor2,'String',[num2str(Angle(1)),' ',num2str(Angle(2))]);\nset(sdip.hdl.int,'String',Ijs_m);\n\n% Change the colour of toggle button of dipoles actually displayed\nfor ii=tabl_seed_dip(:,1)\n set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 1 .7]);\nend\n\n%________________________________________________________________________\ncase 'clearall'\n%------------------------------------------------------------------------\n% Clears all dipoles, and reset the toggle buttons\n\nif isfield(st.vols{1},'sdip')\n sdip = st.vols{1}.sdip;\nelse\n error('I can''t find sdip structure');\nend\n\ndisp('Clears all dipoles')\nspm_eeg_inv_ecd_DrawDip('ClearDip');\nfor ii=1:st.vols{1}.sdip.n_seeds\n if sdip.exitflag(ii)==1\n set(st.vols{1}.sdip.hdl.hseed(ii),'Value',0);\n end\nend\nset(st.vols{1}.sdip.hdl.hdip,'Value',1);\n\n%________________________________________________________________________\ncase 'chgseed'\n%------------------------------------------------------------------------\n% Changes the seeds displayed\n% disp('Change seed')\n\nsdip = st.vols{1}.sdip;\nif isfield(sdip,'tabl_seed_dip')\n prev_seeds = p_seed(sdip.tabl_seed_dip);\nelse\n prev_seeds = [];\nend\n\nl_seed = zeros(sdip.n_seeds,1);\nfor ii=1:sdip.n_seeds\n if sdip.exitflag(ii)==1\n l_seed(ii) = get(sdip.hdl.hseed(ii),'Value');\n end\nend\nl_seed = find(l_seed);\n\n% Modify the list of seeds displayed\nif length(l_seed)==0\n % Nothing left displayed\n i_seed=[];\nelseif isempty(prev_seeds)\n % Just one dipole added, nothing before\n i_seed=l_seed;\nelseif length(prev_seeds)>length(l_seed)\n % One seed removed\n i_seed = prev_seeds;\n for ii=1:length(l_seed)\n p = find(prev_seeds==l_seed(ii));\n if ~isempty(p)\n prev_seeds(p) = [];\n end % prev_seeds is left with the index of the one removed\n end\n i_seed(find(i_seed==prev_seeds)) = [];\n % Remove the dipole & change the button colour\n spm_eeg_inv_ecd_DrawDip('ClearDip',prev_seeds);\n set(sdip.hdl.hseed(prev_seeds),'BackgroundColor',[.7 .7 .7]);\nelse\n % One dipole added\n i_seed = prev_seeds;\n for ii=1:length(prev_seeds)\n p = find(prev_seeds(ii)==l_seed);\n if ~isempty(p)\n l_seed(p) = [];\n end % l_seed is left with the index of the one added\n end\n i_seed = [i_seed ; l_seed];\nend\n\ni_dip = get(sdip.hdl.hdip,'Value');\nspm_eeg_inv_ecd_DrawDip('ClearDip');\nif ~isempty(i_seed)\n spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip);\nend\n\n%________________________________________________________________________\ncase 'chgdip'\n%------------------------------------------------------------------------\n% Changes the dipole index for the first seed displayed\n\ndisp('Change dipole')\nsdip = st.vols{1}.sdip;\n\ni_dip = get(sdip.hdl.hdip,'Value');\nif isfield(sdip,'tabl_seed_dip')\n i_seed = p_seed(sdip.tabl_seed_dip);\nelse\n i_seed = [];\nend\n\nif ~isempty(i_seed)\n spm_eeg_inv_ecd_DrawDip('ClearDip')\n spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip);\nend\n\n%________________________________________________________________________\ncase 'cleardip'\n%------------------------------------------------------------------------\n% FORMAT spm_eeg_inv_ecd_DrawDip('ClearDip',seed_i)\n% e.g. spm_eeg_inv_ecd_DrawDip('ClearDip')\n% clears all displayed dipoles\n% e.g. spm_eeg_inv_ecd_DrawDip('ClearDip',1)\n% clears the first dipole displayed\n\nif nargin>2\n seed_i = varargin{1};\nelse\n seed_i = 0;\nend\nif isfield(st.vols{1},'sdip')\n sdip = st.vols{1}.sdip;\n else\n return; % I don't do anything, as I can't find sdip strucure\nend\n\nif isfield(sdip,'ax')\n Nax = size(sdip.ax,2);\n else\n return; % I don't do anything, as I can't find axes info\nend\n\nif seed_i==0 % removes everything\n for ii=1:Nax\n for jj=1:6\n delete(sdip.ax(jj,ii));\n end\n end\n for ii=sdip.tabl_seed_dip(:,1)\n set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 .7 .7]);\n\tend\n sdip = rmfield(sdip,'tabl_seed_dip');\n sdip = rmfield(sdip,'ax'); \nelseif seed_i<=Nax % remove one seed only\n l_seed = find(sdip.tabl_seed_dip(:,1)==seed_i);\n for ii=l_seed\n for jj=1:6\n delete(sdip.ax(jj,ii));\n end\n end\n sdip.ax(:,l_seed) = [];\n sdip.tabl_seed_dip(l_seed,:) = [];\nelse\n error('Trying to clear unspecified dipole');\nend\nst.vols{1}.sdip = sdip;\n\n%________________________________________________________________________\notherwise,\n\twarning('Unknown action string')\nend;\nwarning(sw);\nreturn;\n\n%________________________________________________________________________\n%________________________________________________________________________\n%________________________________________________________________________\n%________________________________________________________________________\n%\n% SUBFUNCTIONS\n%________________________________________________________________________\n%________________________________________________________________________\nfunction dh = add1dip(loc,js,mark,col,ax,Fig,bb)\n% Plots the dipoles on the 3 views\n% Then returns the handle to the plots\n\nloc(1,:) = loc(1,:) - bb(1,1)+1;\nloc(2,:) = loc(2,:) - bb(1,2)+1;\nloc(3,:) = loc(3,:) - bb(1,3)+1;\n% +1 added to be like John's orthview code\n\ndh = zeros(6,1);\nfigure(Fig)\n% Transverse slice, # 1\nset(Fig,'CurrentAxes',ax{1}.ax)\nset(ax{1}.ax,'NextPlot','add')\ndh(1) = plot(loc(1),loc(2),[mark,col],'LineWidth',2);\ndh(2) = plot(loc(1)+[0 js(1)],loc(2)+[0 js(2)],col,'LineWidth',2);\nset(ax{1}.ax,'NextPlot','replace')\n\n% Coronal slice, # 2\nset(Fig,'CurrentAxes',ax{2}.ax)\nset(ax{2}.ax,'NextPlot','add')\ndh(3) = plot(loc(1),loc(3),[mark,col],'LineWidth',2);\ndh(4) = plot(loc(1)+[0 js(1)],loc(3)+[0 js(3)],col,'LineWidth',2);\nset(ax{2}.ax,'NextPlot','replace')\n\n% Sagital slice, # 3\nset(Fig,'CurrentAxes',ax{3}.ax)\nset(ax{3}.ax,'NextPlot','add')\n% dh(5) = plot(dim(2)-loc(2),loc(3),[mark,col],'LineWidth',2);\n% dh(6) = plot(dim(2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2);\ndh(5) = plot(bb(2,2)-bb(1,2)-loc(2),loc(3),[mark,col],'LineWidth',2);\ndh(6) = plot(bb(2,2)-bb(1,2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2);\nset(ax{3}.ax,'NextPlot','replace')\n\nreturn\n\n%________________________________________________________________________\nfunction pr_seed = p_seed(tabl_seed_dip)\n% Gets the list of seeds used in the previous display\n\nls = sort(tabl_seed_dip(:,1));\nif length(ls)==1\n pr_seed = ls;\nelse\n\tpr_seed = ls([find(diff(ls)) ; length(ls)]);\nend\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_display_ui.m", "ext": ".m", "path": "spm5-master/spm_eeg_display_ui.m", "size": 25402, "source_encoding": "utf_8", "md5": "25f7e44690f054e724956833781be5da", "text": "function Heeg = spm_eeg_display_ui(varargin)\n% user interface for displaying EEG/MEG channel data.\n% Heeg = spm_eeg_display_ui(varargin)\n%\n% optional argument:\n% S\t\t - struct\n% fields of S:\n% D \t - EEG struct\n% Hfig\t - Figure (or axes) to work in (Defaults to SPM graphics window)\n% rebuild - indicator variable: if defined spm_eeg_display_ui has been\n% called after channel selection\n%\n% output:\n% Heeg\t\t- Handle of resulting figure\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Stefan Kiebel\n% $Id: spm_eeg_display_ui.m 955 2007-10-17 15:15:09Z rik $\n\nif nargin == 1\n S = varargin{1};\nend\n\nif nargin == 0 | ~isfield(S, 'rebuild')\n try\n D = S.D;\n catch\n D = spm_select(1, '\\.mat$', 'Select EEG mat file');\n try\n D = spm_eeg_ldata(D);\n catch\n error(sprintf('Trouble reading file %s', D));\n end\n end\n\n if ~isfield(D.channels, 'Bad')\n D.channels.Bad = [];\n end\n\n\n if D.Nevents == 1 & ~isfield(D.events, 'start')\n errordlg({'Continuous data cannot be displayed (yet).', 'Epoch first please.'});\n return;\n end\n\n % units, default EEG\n if ~isfield(D, 'units')\n D.units = '\\muV';\n end\n\n try\n % Use your own window\n F = S.Hfig;\n catch\n % use SPM graphics window\n F = findobj('Tag', 'Graphics');\n if isempty(F)\n F = spm_figure('create','Graphics','Graphics','on');\n end\n end\n\n set(F, 'SelectionType', 'normal');\n\n handles = guihandles(F);\n\n handles.colour = {[0 0 1], [1 0 0], [0 1 0], [1 0 1]};\n\n % variable needed to store current trial listbox selection\n handles.Tselection = 1;\n\n % fontsize used troughout\n % (better compute that fontsize)\n% FS1 = spm('FontSize', 14);\n FS1 = spm('FontSize', 8);\n\n figure(F);clf\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % setup of GUI elements\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % Slider for trial number\n %------------------------\n if D.Nevents > 1\n\n % text above slider\n uicontrol(F, 'Style', 'text', 'Units', 'normalized',...\n 'String', 'Trial number',...\n 'Position',[0.11 0.072 0.15 0.029],...\n 'HorizontalAlignment', 'right', 'FontSize', FS1,...\n 'BackgroundColor', 'w');\n\n handles.trialslider = uicontrol(F, 'Tag', 'trialslider', 'Style', 'slider',...\n 'Min', 1, 'Max', D.Nevents, 'Value', 1, 'Units',...\n 'normalized', 'Position', [0.05 0.045 0.25 0.03],...\n 'SliderStep', [1/(D.Nevents-1) min(D.Nevents-1, 10/(D.Nevents-1))],...\n 'TooltipString', 'Choose trial number',...\n 'Callback', @trialslider_update,...\n 'Parent', F, 'Interruptible', 'off');\n\n % frame for trialslider text\n uicontrol(F, 'Style','Frame','BackgroundColor',spm('Colour'), 'Units',...\n 'normalized', 'Position',[0.05 0.019 0.25 0.031]);\n\n % trials slider texts\n uicontrol(F, 'Style', 'text', 'Units', 'normalized',...\n 'String', '1',...\n 'Position',[0.06 0.02 0.07 0.029],...\n 'HorizontalAlignment', 'left', 'FontSize', FS1,...\n 'BackgroundColor', spm('Colour'));\n\n handles.trialtext = uicontrol(F, 'Style', 'text', 'Tag', 'trialtext',...\n 'Units', 'normalized',...\n 'String', int2str(get(handles.trialslider, 'Value')),...\n 'Position',[0.14 0.02 0.07 0.029],...\n 'HorizontalAlignment', 'center', 'FontSize', FS1,...\n 'BackgroundColor', spm('Colour'));\n\n uicontrol(F, 'Style', 'text', 'Units', 'normalized',...\n 'String', mat2str(D.Nevents),...\n 'Position',[0.23 0.02 0.06 0.029],...\n 'HorizontalAlignment', 'right', 'FontSize', FS1,...\n 'BackgroundColor', spm('Colour'));\n\n end\n\n % Scaling slider\n %-----------------\n % estimate of maximum scaling value\n if isfield (D,'Nfrequencies')\n handles.scalemax = 2*ceil(max(max(max(abs(D.data(setdiff(D.channels.eeg, D.channels.Bad), :,:, 1))))));\n else\n% handles.scalemax = 2*ceil(max(max(max(abs(D.data(setdiff([1:D.Nchannels], D.channels.Bad), :, :))))));\n handles.scalemax = 2*ceil(max(max(abs(D.data(setdiff(D.channels.eeg, D.channels.Bad), :, 1)))));\n end\n scale = handles.scalemax/2;\n\n % text above slider\n uicontrol(F, 'Style', 'text', 'Units', 'normalized',...\n 'String', 'Scaling',...\n 'Position',[0.37 0.072 0.15 0.029],...\n 'HorizontalAlignment', 'right', 'FontSize', FS1,...\n 'BackgroundColor', 'w');\n\n % slider\n handles.scaleslider = uicontrol('Tag', 'scaleslider', 'Style', 'slider',...\n 'Min', 1, 'Max', handles.scalemax, 'Value', scale, 'Units',...\n 'normalized', 'Position', [0.35 0.045 0.25 0.03],...\n 'SliderStep', [1/(handles.scalemax-1) 10/(handles.scalemax-1)],...\n 'TooltipString', 'Choose scaling',...\n 'Callback', @scaleslider_update,...\n 'Parent', F);\n\n % frame for text\n uicontrol(F, 'Style','Frame','BackgroundColor',spm('Colour'), 'Units',...\n 'normalized', 'Position',[0.35 0.019 0.25 0.031]);\n\n % text\n uicontrol(F, 'Style', 'text', 'Units', 'normalized', 'String', '1',...\n 'Position',[0.36 0.02 0.07 0.029],...\n 'HorizontalAlignment', 'left', 'FontSize', FS1,...\n 'BackgroundColor',spm('Colour'));\n\n handles.scaletext = uicontrol(F, 'Style', 'text', 'Tag', 'scaletext',...\n 'Units', 'normalized',...\n 'String', mat2str(handles.scalemax/2),...\n 'Position',[0.44 0.02 0.07 0.029],...\n 'HorizontalAlignment', 'center', 'FontSize', FS1,...\n 'BackgroundColor',spm('Colour'));\n\n uicontrol(F, 'Style', 'text', 'Units', 'normalized',...\n 'String', mat2str(handles.scalemax),...\n 'Position',[0.52 0.02 0.07 0.029],...\n 'HorizontalAlignment', 'right', 'FontSize', FS1,...\n 'BackgroundColor',spm('Colour'));\n\n\n %---------------------\n % Save pushbutton\n uicontrol('Tag', 'savebutton', 'Style', 'pushbutton',...\n 'Units', 'normalized', 'Position', [0.615 0.02 0.11 0.03],...\n 'String', 'Save', 'FontSize', FS1,...\n 'BackgroundColor', spm('Colour'),...\n 'CallBack', @savebutton_update,...\n 'Parent', F);\n\n % Reject selection pushbutton\n uicontrol('Tag', 'channelselectbutton', 'Style', 'pushbutton',...\n 'Units', 'normalized', 'Position', [0.615 0.05 0.11 0.03],...\n 'String', 'Reject', 'FontSize', FS1,...\n 'BackgroundColor', spm('Colour'),...\n 'CallBack', @rejectbutton_update,...\n 'Parent', F);\n\n % Channel selection pushbutton\n uicontrol('Tag', 'channelselectbutton', 'Style', 'pushbutton',...\n 'Units', 'normalized', 'Position', [0.615 0.08 0.11 0.03],...\n 'String', 'Channels', 'FontSize', FS1,...\n 'BackgroundColor', spm('Colour'),...\n 'CallBack', @channelselectbutton_update,...\n 'Parent', F);\n\n % Topography display pushbutton\n uicontrol('Tag', '3Dtopographybutton', 'Style', 'pushbutton',...\n 'Units', 'normalized', 'Position', [0.615 0.11 0.11 0.03],...\n 'String', 'Topography', 'FontSize', FS1,...\n 'BackgroundColor', spm('Colour'),...\n 'CallBack', @scalp3d_select,...\n 'Parent', F);\n\n % trial listbox\n if D.Nevents > 1\n trialnames = {};\n for i = 1:D.Nevents\n trialnames{i} = [sprintf('%-12s', sprintf('trial %d', i)) sprintf('%-4s', sprintf('%d', D.events.code(i)))];\n if D.events.reject(i)\n trialnames{i} = [trialnames{i} sprintf('%-8s', 'reject')];\n end\n end\n handles.trialnames = trialnames;\n\n handles.triallistbox = uicontrol('Tag', 'triallistbox', 'Style', 'listbox',...\n 'Units', 'normalized', 'Position', [0.74 0.02 0.2 0.2],...\n 'Min', 0, 'Max', 2, 'String', trialnames,...\n 'HorizontalAlignment', 'left',...\n 'Value', 1,...\n 'BackgroundColor', [1 1 1],...\n 'CallBack', @triallistbox_update,...\n 'Parent', F);\n end\n % display file name at top of page\n uicontrol('Style', 'text', 'String', fullfile(D.path, D.fname),...\n 'Units', 'normalized', 'Position', [0.05 0.98 0.8 0.02],...\n 'Background', 'white', 'FontSize', 14, 'HorizontalAlignment', 'Left');\n\n % axes with scaling and ms display\n axes('Position', [0.05 0.15 0.2 0.07]);\n set(gca, 'YLim', [-scale scale], 'XLim', [1 D.Nsamples],...\n 'XTick', [], 'YTick', [], 'LineWidth', 2);\n handles.scaletexttop = text(0, scale, sprintf(' %d', 2*scale), 'Interpreter', 'Tex',...\n 'FontSize', FS1, 'VerticalAlignment', 'top',...\n 'Tag', 'scaletext2');\n ylabel(D.units, 'Interpreter', 'tex', 'FontSize', FS1);\n text(D.Nsamples, -scale, sprintf('%d', round((D.Nsamples-1)*1000/D.Radc)), 'Interpreter', 'Tex',...\n 'FontSize', FS1, 'HorizontalAlignment', 'right', 'VerticalAlignment', 'bottom');\n xlabel('ms', 'Interpreter', 'tex', 'FontSize', FS1);\n\n % Added option to specify in advance only subset of channels to display RH\n % ([] = prompt for channel file; char = load channel file; No error checking yet)\n try\n \tD.gfx.channels = S.chans;\n if isempty(S.chans)\n S.chans = spm_select(1, '\\.mat$', 'Select channel mat file');\n\t S.load = load(S.chans);\n \t D.gfx.channels = S.load.Iselectedchannels;\n elseif ischar(S.chans)\n\t S.load = load(S.chans);\n \t D.gfx.channels = S.load.Iselectedchannels;\n\tend\n catch\n % channels to display, initially exclude bad channels\n D.gfx.channels = setdiff([1:length(D.channels.order)], D.channels.Bad);\n end\n\nelse\n % this is a re-display with different set of selected channels, delete plots\n handles = guidata(S.Hfig);\n delete(handles.Heegaxes);\n handles.Heegaxes = [];\n\n for i = 1:length(handles.Heegfigures)\n if ~isempty(handles.Heegfigures{i})\n delete(handles.Heegfigures{i});\n end\n end\n\n D = S.D;\n F = S.Hfig;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subplots of EEG data\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% position of plotting area for eeg data in graphics figure\nPos = [0.03 0.23 0.95 0.75];\n\n% Compute width of display boxes\n%-------------------------------\nCsetup = load(fullfile(spm('dir'), 'EEGtemplates', D.channels.ctf));\n\n% indices of displayed channels (in order of data)\nhandles.Cselection2 = D.gfx.channels;\n\n% indices of displayed channels (in order of the channel template file)\nhandles.Cselection = D.channels.order(handles.Cselection2);\n\np = Csetup.Cpos(:, handles.Cselection);\nRxy = Csetup.Rxy; % ratio of x- to y-axis lengths\n\nNpos = size(p, 2); % number of positions\n\nif Npos > 1\n % more than 1 channel for display\n for i = 1:Npos\n for j = 1:Npos\n % distance between channels\n d(i,j) = sqrt(sum((p(:,j)-p(:,i)).^2));\n\n % their angle\n alpha(i,j) = acos((p(1,j)-p(1,i))/(d(i,j)+eps));\n end\n end\n d = d/2;\n\n alpha(alpha > pi/2) = pi-alpha(alpha > pi/2);\n Talpha = asin(1/(sqrt(1+Rxy^2)));\n\n for i = 1:Npos\n for j = 1:Npos\n if alpha(i,j) <= Talpha\n x(i,j) = d(i,j)*cos(alpha(i,j));\n else\n x(i,j) = Rxy*d(i,j)*cos(pi/2-alpha(i,j));\n end\n end\n end\n\n\n % half length of axes in x-direction\n Lxrec = min(x(find(x~=0)));\n\nelse\n % only one channel\n Lxrec = 1;\nend\n\n% coordinates of lower left corner of drawing boxes\np(1, :) = p(1, :) - Lxrec;\np(2, :) = p(2, :) - Lxrec/Rxy;\n\n% envelope of coordinates\ne = [min(p(1,:)) max(p(1,:))+2*Lxrec min(p(2,:)) max(p(2,:))+2*Lxrec/Rxy];\n\n% shift coordinates to zero\np(1,:) = p(1,:) - mean(e(1:2));\np(2,:) = p(2,:) - mean(e(3:4));\n\n% scale such that envelope goes from -0.5 to 0.5\nSf = 0.5/max(max(abs(p(1,:))), (max(abs(p(2,:)))));\np = Sf*p;\nLxrec = Sf*Lxrec;\n\n% and back to centre\np = p+0.5;\n\n% translate and scale to fit into drawing area of figure\np(1,:) = Pos(3)*p(1,:)+Pos(1);\np(2,:) = Pos(4)*p(2,:)+Pos(2);\n\nscale = get(handles.scaleslider, 'Value');\n\n% cell vector for figures handles of separate single channel plots\nhandles.Heegfigures = cell(1, Npos);\n\n% cell vector for axes handles of single channel plots\nhandles.Heegaxes2 = cell(1, Npos);\n\n% plot the graphs\nfor i = 1:Npos\n\n % uicontextmenus for axes\n Heegmenus(i) = uicontextmenu;\n if ismember(i, D.channels.Bad)\n labelstring = 'Declare as good';\n else\n labelstring = 'Declare as bad';\n end\n\n uimenu(Heegmenus(i), 'Label',...\n sprintf('%s (%d)', D.channels.name{handles.Cselection2(i)}, handles.Cselection2(i)));\n uimenu(Heegmenus(i), 'Separator', 'on');\n uimenu(Heegmenus(i), 'Label', labelstring,...\n 'CallBack', {@switch_bad, i});\n\n handles.Heegaxes(i) = axes('Position',...\n [p(1,i) p(2,i) 2*Lxrec*Pos(3) 2*Lxrec/Rxy*Pos(4)],...\n 'ButtonDownFcn', {@windowplot, i},...\n 'NextPlot', 'add',...\n 'Parent', F,...\n 'UIContextMenu', Heegmenus(i));\n\n % make axes current\n axes(handles.Heegaxes(i));\n\n for j = 1:length(handles.Tselection)\n\n if isfield(D,'Nfrequencies')\n h = imagesc(squeeze(D.data(handles.Cselection2(i), :,:, handles.Tselection(j))));\n set(h, 'ButtonDownFcn', {@windowplot, i},...\n 'Clipping', 'off', 'UIContextMenu', Heegmenus(i));\n else\n h = plot([-D.events.start:D.events.stop]*1000/D.Radc,...\n D.data(handles.Cselection2(i), :, handles.Tselection(j)),...\n 'Color', handles.colour{j});\n set(h, 'ButtonDownFcn', {@windowplot, i},...\n 'Clipping', 'off', 'UIContextMenu', Heegmenus(i));\n end\n end\n if isfield(D,'Nfrequencies')\n set(gca, 'ZLim', [-scale scale],...\n 'XLim', [1 D.Nsamples], 'YLim', [1 D.Nfrequencies], 'XTick', [], 'YTick', [], 'ZTick', [],'Box', 'off');\n caxis([-scale scale])\n colormap('jet')\n else\n if Lxrec > 0.1\n % boxes are quite large\n set(gca, 'YLim', [-scale scale],...\n 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'Box', 'off', 'Xgrid', 'on');\n else\n % otherwise remove tickmarks\n set(gca, 'YLim', [-scale scale],...\n 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'XTick', [], 'YTick', [], 'Box', 'off');\n end\n end\nend\n\n\nhandles.Lxrec = Lxrec;\nhandles.D = D;\n\n% store handles\nguidata(F, handles);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% callbacks for GUI elements\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction switch_bad(hObject, events, ind)\n% update called from channel contextmenu\n\nhandles = guidata(hObject);\n\n% ind1 = handles.Cselection(ind);\nind2 = handles.Cselection2(ind);\n\nif ismember(ind2, handles.D.channels.Bad)\n handles.D.channels.Bad = setdiff(handles.D.channels.Bad, ind2);\nelse\n handles.D.channels.Bad = unique([handles.D.channels.Bad ind2]);\nend\n\nHeegmenu = uicontextmenu;\nif ismember(ind, handles.D.channels.Bad)\n labelstring = sprintf('Declare %s as good', handles.D.channels.name{ind2});\nelse\n labelstring = sprintf('Declare %s as bad', handles.D.channels.name{ind2});\nend\n\nuimenu(Heegmenu, 'Label', labelstring,...\n 'CallBack', {@switch_bad, ind});\n\nset(handles.Heegaxes(ind), 'UIContextMenu', Heegmenu);\n\nguidata(hObject, handles);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction trialslider_update(hObject, events)\n% update called from trialslider\n\nhandles = guidata(hObject);\n\n% slider value\nind = round(get(hObject, 'Value'));\nset(hObject, 'Value', ind);\n\n% update triallistbox\nset(handles.triallistbox, 'Value', ind);\n\n% Update display of current trial number\nset(handles.trialtext, 'String', mat2str(ind));\n\n% make plots\ndraw_subplots(handles, ind)\n\nhandles.Tselection = ind;\nguidata(hObject, handles);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction triallistbox_update(hObject, events)\n% update called from triallistbox\n\nhandles = guidata(hObject);\n\n% listbox selection\nind = get(hObject, 'Value');\n\nif length(ind) > length(handles.colour)\n warning('Can only display %d different traces', length(handles.colour));\n ind = handles.Tselection;\n set(hObject, 'Value', handles.Tselection);\nelseif length(ind) < 1\n % can happen if user presses with cntl on already selected trial\n ind = handles.Tselection;\n set(hObject, 'Value', handles.Tselection);\nelse\n % update trialslider to minimum of selection\n set(handles.trialslider, 'Value', min(ind));\n\n % Update display of current trial number\n set(handles.trialtext, 'String', mat2str(min(ind)));\n\n handles.Tselection = ind;\n guidata(hObject, handles);\n\n % make plots\n draw_subplots(handles, ind)\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction scaleslider_update(hObject, events)\n% update called from scaleslider\n\nhandles = guidata(hObject);\nD = handles.D;\n\n% slider value\nscale = round(get(hObject, 'Value'));\nset(hObject, 'Value', scale);\n\n% text below slider\nset(handles.scaletext, 'String', mat2str(scale));\n\n% text at top of figure\nset(handles.scaletexttop, 'String', sprintf(' %d', 2*scale));\n\n% rescale plots\nfor i = 1:length(handles.Heegaxes)\n\n % make ith subplot current\n axes(handles.Heegaxes(i));\n\n if isfield(D,'Nfrequencies')\n set(gca, 'ZLim', [0 scale],...\n 'XLim', [1 D.Nsamples], 'YLim', [1 D.Nfrequencies], 'XTick', [], 'YTick', [], 'ZTick', [],'Box', 'off');\n caxis([-scale scale])\n else\n if handles.Lxrec > 0.1\n % boxes are quite large\n set(gca, 'YLim', [-scale scale],...\n 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'Box', 'off', 'Xgrid', 'on');\n else\n % otherwise remove tickmarks\n set(gca, 'YLim', [-scale scale],...\n 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'XTick', [], 'YTick', [], 'Box', 'off');\n end\n end\nend\n\n% rescale separate windows (if there are any)\nfor i = 1:length(handles.Heegfigures)\n if ~isempty(handles.Heegfigures{i})\n\n axes(handles.Heegaxes2{i});\n\n if isfield(D,'Nfrequencies')\n\n caxis([-scale scale])\n else\n set(gca, 'YLim', [-scale scale],...\n 'XLim', [-D.events.start D.events.stop]*1000/D.Radc);\n end\n\n\n % update legend\n legend;\n\n end\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction draw_subplots(handles, ind)\n% This function plots data in the subplots\n\nD = handles.D;\n\nscale = round(get(handles.scaleslider, 'Value'));\n\nfor i = 1:length(handles.Heegaxes)\n\n % make ith subplot current\n axes(handles.Heegaxes(i));\n\n cla\n set(handles.Heegaxes(i), 'NextPlot', 'add');\n\n for j = 1:length(ind)\n if isfield(D,'Nfrequencies')\n h = imagesc(squeeze(D.data(handles.Cselection2(i), :,:, ind(j))));\n set(h, 'ButtonDownFcn', {@windowplot, i},...\n 'Clipping', 'off');\n else\n h = plot([-D.events.start:D.events.stop]*1000/D.Radc,...\n D.data(handles.Cselection2(i), :, ind(j)),...\n 'Color', handles.colour{j});\n set(h, 'ButtonDownFcn', {@windowplot, i},...\n 'Clipping', 'off');\n end\n end\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction windowplot(hObject, events, ind)\n% this function plots data from channel ind in a separate window\n\nst = get(gcf,'SelectionType');\n\n% do nothing for right button click\nif strcmp(st, 'alt')\n return;\nend\n\nhandles = guidata(hObject);\nD = handles.D;\n\nw = handles.Heegfigures{ind};\n\n% index to get the channel name\nif ~isempty(w)\n\n % delete the existing window\n delete(w);\n handles.Heegfigures{ind} = [];\nelse\n handles.Heegfigures{ind} = figure;\n set(gcf,...\n 'Name', (sprintf('Channel %s', D.channels.name{handles.Cselection2(ind)})),...\n 'NumberTitle', 'off',...\n 'DeleteFcn', {@delete_Heegwindows, ind});\n\n handles.Heegaxes2{ind} = gca;\n set(handles.Heegaxes2{ind}, 'NextPlot', 'add');\n\n if isfield(D,'Nfrequencies')\n xlabel('ms', 'FontSize', 16);\n ylabel('Hz', 'FontSize', 16, 'Interpreter', 'Tex')\n\n for i = 1:length(handles.Tselection)\n\n imagesc([-D.events.start:D.events.stop]*1000/D.Radc,D.tf.frequencies,squeeze(D.data(handles.Cselection2(ind), :,:, handles.Tselection(i))));\n\n end\n\n scale = get(handles.scaleslider, 'Value');\n set(gca, 'ZLim', [-scale scale],...\n 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'YLim', [min(D.tf.frequencies) max(D.tf.frequencies)], 'Box', 'on');\n colormap('jet')\n caxis([-scale scale])\n\n else\n xlabel('ms', 'FontSize', 16);\n ylabel(D.units, 'FontSize', 16, 'Interpreter', 'Tex')\n\n for i = 1:length(handles.Tselection)\n plot([-D.events.start:D.events.stop]*1000/D.Radc,...\n D.data(handles.Cselection2(ind), :, handles.Tselection(i)),...\n 'Color', handles.colour{i}, 'LineWidth', 2);\n end\n\n scale = get(handles.scaleslider, 'Value');\n\n set(gca, 'YLim', [-scale scale],...\n 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'Box', 'on');\n grid on\n end\n title(sprintf('%s (%d)', D.channels.name{handles.Cselection2(ind)}, handles.Cselection2(ind)), 'FontSize', 16);\n\n if D.Nevents > 1\n legend(handles.trialnames{handles.Tselection}, 0);\n end\n\n % save handles structure to new figure\n guidata(handles.Heegaxes2{ind}, handles);\nend\n\nguidata(hObject, handles);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction delete_Heegwindows(hObject, events, ind)\n% deletes window of ind-th channel when delete was not via the eeg channel\n% plot in the SPM graphics window\n\n% returns handles structure of the graphics window\nhandles = guidata(hObject);\nhandles = guidata(handles.Graphics);\n\ndelete(handles.Heegfigures{ind});\nhandles.Heegfigures{ind} = [];\n\n% save to handles structure in main Graphics figure\nguidata(handles.Graphics, handles);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction savebutton_update(hObject, events)\n% save updated matfile\nhandles = guidata(hObject);\nD = handles.D;\n\nspm('Pointer', 'Watch');\n\n% remove gfx struct\nD = rmfield(D, 'gfx');\n\nif spm_matlab_version_chk('7') >= 0\n save(fullfile(D.path, D.fname), '-V6', 'D');\nelse\n save(fullfile(D.path, D.fname), 'D');\nend\n\nspm('Pointer', 'Arrow');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction rejectbutton_update(hObject, events)\n% called from reject button\n\nhandles = guidata(hObject);\nD = handles.D;\n\n% listbox selection\nind = handles.Tselection;\n\nif ind > 1\n % toggle first select only\n ind = ind(1);\nend\n\nif D.events.reject(ind) == 0\n % reject this trial\n tmp = [sprintf('%-12s', sprintf('trial %d', ind)) sprintf('%-4s', sprintf('%d', D.events.code(ind)))];\n tmp = [tmp sprintf('%-8s', 'reject')];\n D.events.reject(ind) = 1;\nelse\n % un-reject this trial\n tmp = [sprintf('%-12s', sprintf('trial %d', ind)) sprintf('%-4s', sprintf('%d', D.events.code(ind)))];\n D.events.reject(ind) = 0;\nend\nhandles.trialnames{ind} = tmp;\n\nset(handles.triallistbox, 'String', handles.trialnames);\nhandles.D = D;\n\nguidata(hObject, handles);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction channelselectbutton_update(hObject, events)\nhandles = guidata(hObject);\nD = handles.D;\n\nind = spm_eeg_select_channels(D);\n\nD.gfx.channels = ind;\nS.D = D;\nS.rebuild = 1;\nS.Hfig = handles.Graphics;\n\nspm_eeg_display_ui(S);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction scalp3d_select(hObject, events)\n% ask user for peri-stimulus time and call scalp3d\n\nhandles = guidata(hObject);\nD = handles.D;\n\nok = 0;\nwhile ~ok\n try\n answer = spm_eeg_scalp_dlg;\n catch\n return\n end\n t = answer{1};\n s = answer{2};\n for n=1:length(t)\n if t(n) >= -D.events.start*1000/D.Radc...\n & t(n) <= D.events.stop*1000/D.Radc...\n & (strcmpi(s, '2d') | strcmpi(s, '3d'))\n ok = 1;\n end\n end\nend\n\n% call scalp2d or 3d\n%--------------------------------------------------------------------------\nspm('Pointer', 'Watch');drawnow;\nif strcmpi(s, '2d')\n spm_eeg_scalp2d_ext(D, t, handles.Tselection(1));\nelse\n % change time for james' function\n t=round(t/1000*D.Radc)+D.events.start+1;\n if length(t) == 1\n d = squeeze(D.data(D.channels.eeg, t, handles.Tselection(1)));\n else\n d = squeeze(mean(D.data(D.channels.eeg, t, handles.Tselection(1)), 2));\n end\n if strmatch(D.channels.ctf,'bdf_setup.mat')\n spm_eeg_scalp3d(d);\n else\n errordlg({'This can only be used for 128 channel BDF data at the moment'});\n return;\n end\n\n\nend\nspm('Pointer', 'Arrow');drawnow;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_select_channels.m", "ext": ".m", "path": "spm5-master/spm_eeg_select_channels.m", "size": 10356, "source_encoding": "utf_8", "md5": "a742f19989b2763640c0d4fb074fcadd", "text": "function varargout = spm_eeg_select_channels(varargin)\n% SPM_EEG_SELECT_CHANNELS M-file for spm_eeg_select_channels.fig\n% SPM_EEG_SELECT_CHANNELS, by itself, creates a new SPM_EEG_SELECT_CHANNELS or raises the existing\n% singleton*.\n%\n% H = SPM_EEG_SELECT_CHANNELS returns the handle to a new SPM_EEG_SELECT_CHANNELS or the handle to\n% the existing singleton*.\n%\n% SPM_EEG_SELECT_CHANNELS('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SPM_EEG_SELECT_CHANNELS.M with the given input arguments.\n%\n% SPM_EEG_SELECT_CHANNELS('Property','Value',...) creates a new SPM_EEG_SELECT_CHANNELS or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before spm_eeg_select_channels_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to spm_eeg_select_channels_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help spm_eeg_select_channels\n\n% Last Modified by GUIDE v2.5 13-Jul-2005 14:18:07\n\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Stefan Kiebel\n% $Id: spm_eeg_select_channels.m 716 2007-01-16 21:13:50Z karl $\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @spm_eeg_select_channels_OpeningFcn, ...\n 'gui_OutputFcn', @spm_eeg_select_channels_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin & isstr(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before spm_eeg_select_channels is made visible.\nfunction spm_eeg_select_channels_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to spm_eeg_select_channels (see VARARGIN)\n\n% Choose default command line output for spm_eeg_select_channels\nhandles.output = hObject;\n\n\n% display graph of channels\nD = varargin{1};\nP = fullfile(spm('dir'), 'EEGtemplates', D.channels.ctf);\nload(P)\n\n% correct Cnames (channel template file entries can have more than one\n% entry per channel)\nfor i = 1:Nchannels\n if iscell(Cnames{i})\n Cnames{i} = Cnames{i}{1};\n end\nend\n\nfigure(handles.figure1);\n\nXrec = [-0.01 0.01 0.01 -0.01];\nYrec = [-0.01 -0.01 0.01 0.01];\n\nHpatch = cell(1, Nchannels);\nHtext = cell(1, Nchannels);\n\nCselect = [1 1 1];\nCdeselect = [0.5 0.5 0.5];\n\nind = zeros(1,length(D.channels.order));\nind(D.gfx.channels) = 1;\ntmp = D.channels.order; % if D.channels.order isn't replaced by this variable -> strange error in 7.04\n\nfor i = 1:length(D.channels.order)\n if ~ind(i)\n Hpatch{i} = patch(Xrec+Cpos(1,tmp(i)), Yrec+Cpos(2,tmp(i)), Cdeselect, 'EdgeColor', 'none');\n else\n Hpatch{i} = patch(Xrec+Cpos(1,tmp(i)), Yrec+Cpos(2,tmp(i)), Cselect, 'EdgeColor', 'none'); \n end\n Hpatch{i};\n xy = get(Hpatch{i}, 'Vertices');\n Htext{i} = text(min(xy(:,1)), max(xy(:,2)), Cnames{D.channels.order(i)});\n set(Htext{i}, 'VerticalAlignment', 'middle', 'HorizontalAlignment', 'left');\nend\naxis square\naxis off\n\n% listbox\nset(handles.listbox1, 'String', Cnames(D.channels.order([1:length(ind)])));\nset(handles.listbox1, 'Value', find(ind));\n\nhandles.D = D;\nhandles.ind = ind;\nhandles.Cnames = Cnames;\nhandles.Cpos = Cpos;\nhandles.Nchannels = Nchannels;\nhandles.Hpatch = Hpatch;\nhandles.Htext = Htext;\nhandles.Cselect = Cselect;\nhandles.Cdeselect = Cdeselect;\n\nfor i = 1:length(D.gfx.channels)\n % callbacks for patches and text\n if D.gfx.channels(i) ~=0\n set(Hpatch{i}, 'ButtonDownFcn', {@patch_select, handles, i});\n set(Htext{i}, 'ButtonDownFcn', {@patch_select, handles, i});\n end\nend\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes spm_eeg_select_channels wait for user response (see UIRESUME)\nuiwait(handles.figure1);\n\nfunction patch_select(obj, eventdata, handles, i, ind);\n\ns = get(handles.listbox1, 'Value');\nh = handles.Hpatch{i};\n\nif ~ismember(i, s)\n set(h, 'FaceColor', handles.Cselect);\n set(handles.listbox1, 'Value', sort([s, i]));\nelse\n set(h, 'FaceColor', handles.Cdeselect);\n set(handles.listbox1, 'Value', setdiff(s, i));\nend\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = spm_eeg_select_channels_OutputFcn(hObject, eventdata, handles)\n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nvarargout{1} = handles.output;\nclose(handles.figure1);\n\n\n% --- Executes during object creation, after setting all properties.\nfunction listbox1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to listbox1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: listbox controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n% --- Executes on selection change in listbox1.\nfunction listbox1_Callback(hObject, eventdata, handles)\n% hObject handle to listbox1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = get(hObject,'String') returns listbox1 contents as cell array\n% contents{get(hObject,'Value')} returns selected item from listbox1\n\ns = get(handles.listbox1, 'Value');\n\nfor i = 1:length(handles.ind)\n if ismember(i, s)\n set(handles.Hpatch{i}, 'FaceColor', handles.Cselect);\n else\n set(handles.Hpatch{i}, 'FaceColor', handles.Cdeselect);\n end\nend\n\n% --- Executes on button press in select.\nfunction select_Callback(hObject, eventdata, handles)\n% hObject handle to select (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Cycle through patch elements and recolour\nfor i = 1:length(handles.ind)\n set(handles.Hpatch{i}, 'FaceColor', handles.Cselect);\nend\n\n% set all listbox entries to selected\nset(handles.listbox1, 'Value', [1:length(handles.ind)]);\n\n% --- Executes on button press in deselect.\nfunction deselect_Callback(hObject, eventdata, handles)\n% hObject handle to deselect (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Cycle through patch elements and recolour\nfor i = 1:length(handles.ind)\n set(handles.Hpatch{i}, 'FaceColor', handles.Cdeselect);\nend\n\n% remove all listbox entries\nset(handles.listbox1, 'Value', []);\n\n% --- Executes on button press in load.\nfunction load_Callback(hObject, eventdata, handles)\n% hObject handle to load (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n[P1, P2] = uigetfile('*.mat', 'Select file to load from');\nload(fullfile(P2, P1), 'Iselectedchannels');\n\nif ~exist('Iselectedchannels', 'var')\n errordlg('This file doesn''t contain channel indices', 'Wrong file?');\nelse\n if max(Iselectedchannels) > length(handles.ind)\n errordlg('This file doesn''t channel indices for these data', 'Wrong file?');\n else\n set(handles.listbox1, 'Value', Iselectedchannels);\n \n for i = 1:handles.Nchannels\n if isempty(find(Iselectedchannels == i))\n set(handles.Hpatch{i}, 'FaceColor', handles.Cdeselect);\n else\n set(handles.Hpatch{i}, 'FaceColor', handles.Cselect);\n end\n end\n end\nend\n\n% --- Executes on button press in save.\nfunction save_Callback(hObject, eventdata, handles)\n% hObject handle to save (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nIselectedchannels = get(handles.listbox1, 'Value');\n\n[P1, P2] = uiputfile('*.mat', 'Choose file name to save to');\n\nif spm_matlab_version_chk('7') >= 0\n save(fullfile(P2, P1), '-V6', 'Iselectedchannels');\nelse\n save(fullfile(P2, P1), 'Iselectedchannels');\nend\n\n% --- Executes on button press in ok.\nfunction ok_Callback(hObject, eventdata, handles)\n% hObject handle to ok (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% returns vector of channel indices that are to be displayed\nif isempty(get(handles.listbox1, 'Value'))\n h = errordlg('Must select at least one channel!', 'Selection error', 'modal');\nelse\n % return indices of selected channels\n handles.output = get(handles.listbox1, 'Value');\n guidata(hObject, handles);\n uiresume;\nend\n\n% --- Executes on button press in removebad.\nfunction removebad_Callback(hObject, eventdata, handles)\n% hObject handle to removebad (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nD = handles.D;\n\ns = get(handles.listbox1, 'Value');\n\ns = setdiff(s, D.channels.Bad);\n\nset(handles.listbox1, 'Value', s);\n\nfor i = 1:handles.Nchannels\n if isempty(find(s == i))\n set(handles.Hpatch{i}, 'FaceColor', handles.Cdeselect);\n else\n set(handles.Hpatch{i}, 'FaceColor', handles.Cselect);\n end\nend\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_spm_ui.m", "ext": ".m", "path": "spm5-master/spm_eeg_spm_ui.m", "size": 6241, "source_encoding": "utf_8", "md5": "06838efc9f6f9ed245832834e9095dd7", "text": "function [SPM] = spm_eeg_spm_ui(SPM)\n% user interface for calling general linear model specification for EEG\n% data\n% FORMAT [SPM] = spm_eeg_spm_ui(SPM)\n%\n%_______________________________________________________________________\n%\n% Specification of M/EEG designs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Stefan Kiebel, Karl Friston\n% $Id: spm_eeg_spm_ui.m 539 2006-05-19 17:59:30Z Darren $\n\n%-GUI setup\n%-----------------------------------------------------------------------\n[Finter, Fgraph, CmdLine] = spm('FnUIsetup', 'EEG stats model setup', 0);\nspm_help('!ContextHelp', mfilename)\n\n\n% get design matrix and/or data\n%=======================================================================\nif ~nargin\n\tstr = 'specify design or data';\n\tif spm_input(str, 1, 'b', {'design','data'}, [1 0]);\n\t\t% specify a design\n\t\t%-------------------------------------------------------\n\t\tif sf_abort, spm_clf(Finter), return, end\n \n % choose either normal design specification or shortcut\n Oanalysis = spm_input('Choose design options', 1,'m',{'all options', 'ERP/ERF'}, [0 1]);\n SPM.eeg.Oanalysis = Oanalysis;\n\n\t\tSPM = spm_eeg_design(SPM);\n\n\t\treturn\n\telse\n\t\t% get design\n\t\t%-------------------------------------------------------\n\t\tload(spm_select(1,'^SPM\\.mat$','Select SPM.mat'));\n\tend\nelse\n\t% get design matrix\n\t%---------------------------------------------------------------\n\tSPM = spm_eeg_design(SPM);\nend\n\n% check data are specified\n%-----------------------------------------------------------------------\ntry \n if ~nargin\n % was called by GUI, i.e. user _wants_ to input data\n SPM.xY = rmfield(SPM.xY, 'P');\n end\n \n\tSPM.xY.P;\n \ncatch\n if SPM.eeg.Oanalysis == 1\n % ERP analysis, only 2 factors (condition and time)\n Nobs = SPM.eeg.Nlevels{1}; % Nerps\n tmp = spm_select(Nobs, 'image', 'Select ERPs (1st frame only)');\n clear q\n for i = 1:Nobs\n [p1, p2, p3] = spm_fileparts(deblank(tmp(i, :)));\n q{i} = fullfile(p1, [p2 p3]); % removes ,1\n end\n P = strvcat(q);\n else\n % defaults to normal design specification\n % get filenames\n %---------------------------------------------------------------\n \n % Number of observations of factor 1\n Nobs = size(SPM.eeg.Xind{end-1}, 1);\n \n P = [];\n oldpwd = pwd;\n \n for i = 1:Nobs\n str = sprintf('Select images for ');\n for j = 1:SPM.eeg.Nfactors-1\n str = [str sprintf('%s(%d)', SPM.eeg.factor{j}, SPM.eeg.Xind{end-1}(i, j))];\n if j < SPM.eeg.Nfactors-1, str = [str ', ']; end\n end\n Nimages = sum(all(kron(ones(size(SPM.eeg.Xind{end}, 1), 1), SPM.eeg.Xind{end-1}(i, :)) == SPM.eeg.Xind{end}(:, 1:end-1), 2));\n \n q = spm_select(Nimages, 'image', str, '', oldpwd);\n P = strvcat(P, q);\n end\n end\n\t% place in data field\n\t%---------------------------------------------------------------\n\tSPM.xY.P = P;\n\nend\n\n% Assemble remaining design parameters\n%=======================================================================\nspm_help('!ContextHelp',mfilename)\n\n%=======================================================================\n% - C O N F I G U R E D E S I G N\n%=======================================================================\nspm_clf(Finter);\nspm('FigName','Configuring, please wait...',Finter,CmdLine);\nspm('Pointer','Watch');\n\n\n% get file identifiers\n%=======================================================================\n\n%-Map files\n%-----------------------------------------------------------------------\nfprintf('%-40s: ','Mapping files') \t %-#\nVY = spm_vol(SPM.xY.P);\nfprintf('%30s\\n','...done') \t %-#\n\n%-check internal consistency of images\n%-----------------------------------------------------------------------\nspm_check_orientations(VY);\n\n%-place in xY\n%-----------------------------------------------------------------------\nSPM.xY.VY = VY;\n\n%-Only implicit mask\n%=======================================================================\nSPM.xM = struct('T',\tones(length(VY), 1),...\n\t\t\t'TH',\t-inf*ones(length(VY), 1),...\n\t\t\t'I',\t0,...\n\t\t\t'VM',\t{[]},...\n\t\t\t'xs',\tstruct('Masking','analysis threshold'));\n\t\n%-Design description - for saving and display\n%=======================================================================\n% SPM.xsDes = struct(...\n% \t'Basis_functions',\tSPM.xBF.name,...\n% \t'Number_of_ERPs',\tsprintf('%d', sum(SPM.eeg.Nsub)*SPM.eeg.Ntypes),...\n% \t'Sampling_frequency',\tsprintf('%0.2f {s}',SPM.xY.RT)...\n% \t);\n% \n\n%-Save SPM.mat\n%-----------------------------------------------------------------------\nfprintf('%-40s: ','Saving SPM configuration') %-#\nif spm_matlab_version_chk('7') >= 0\n save('SPM', 'SPM', '-V6');\nelse\n save('SPM', 'SPM');\nend\nfprintf('%30s\\n','...SPM.mat saved') %-#\n\n \n%-Display Design report\n%=======================================================================\nfprintf('%-40s: ','Design reporting') %-#\nfname = cat(1,{SPM.xY.VY.fname}');\n% spm_DesRep('DesMtx',SPM.xX, SPM.xY.P);\nfprintf('%30s\\n','...done') %-#\n\n\n%-End: Cleanup GUI\n%=======================================================================\nspm_clf(Finter)\nspm('FigName','Stats: configured',Finter,CmdLine);\nspm('Pointer','Arrow')\nfprintf('\\n\\n')\n\n\n%=======================================================================\n%- S U B - F U N C T I O N S\n%=======================================================================\n\nfunction abort = sf_abort\n%=======================================================================\nif exist(fullfile('.','SPM.mat'))\n\tstr = {\t'Current directory contains existing SPM file:',...\n\t\t'Continuing will overwrite existing file!'};\n\n\tabort = spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);\n\tif abort, fprintf('%-40s: %30s\\n\\n',...\n\t\t'Abort... (existing SPM files)',spm('time')), end\nelse\n\tabort = 0;\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_vol_check.m", "ext": ".m", "path": "spm5-master/spm_vol_check.m", "size": 1690, "source_encoding": "utf_8", "md5": "210f1146cb0cf92ed4da535629b23c27", "text": "function [samef, msg, chgf] = spm_vol_check(varargin)\n% FORMAT [samef, msg, chgf] = spm_vol_check(V1, V2, ...)\n% checks spm_vol structs are in same space\n%\n% V1, V2, etc - arrays of spm_vol structs\n%\n% samef - true if images have same dims, mats\n% msg - cell array containing helpful message if not\n% chgf - logical Nx2 array of difference flags\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Matthew Brett\n% $Id: spm_vol_check.m 184 2005-05-31 13:23:32Z john $\n\n\n[fnames samef msg] = deal({},1,{});\n\nif nargin < 1,\n\treturn;\nend;\n\nfor i = 1:numel(varargin),\n\tvols = varargin{i};\n\tif ~isempty(vols),\n\t\tif i == 1,\n\t\t\tdims = cat(3,vols(:).dim);\n\t\t\tmats = cat(3,vols(:).mat);\n\t\telse,\n\t\t\tdims = cat(3,dims,vols(:).dim);\n\t\t\tmats = cat(3,mats,vols(:).mat);\n\t\tend;\n\t\tfnames = {fnames{:}, vols(:).fname};\n\tend;\nend;\n \nnimgs = size(dims, 3);\nif nimgs < 2,\n\treturn;\nend;\n\nlabs = {'dimensions', 'orientation & voxel size'};\n\ndimf = any(diff(dims(:,1:3,:),1,3));\nmatf = any(any(diff(mats,1,3)));\nchgf = logical([dimf(:) matf(:)]);\nchgi = find(any(chgf, 2));\nif ~isempty(chgi),\n\tsamef = 0;\n\te1 = chgi(1);\n\tmsg = {['Images don''t all have the same ' ...\n\t\t sepcat(labs(chgf(e1,:)),', ')],...\n\t\t'First difference between image pair:',...\n\t\tfnames{e1},...\n\t\tfnames{e1+1}};\nend;\nreturn;\n\nfunction s = sepcat(strs, sep)\n% returns cell array of strings as one char string, separated by sep\nif nargin < 2,\n\tsep = ';';\nend\nif isempty(strs),\n\ts = '';\n\treturn;\nend\nstrs = strs(:)';\nstrs = [strs; repmat({sep}, 1, length(strs))];\ns = [strs{1:end-1}];\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_rdata_CTF275.m", "ext": ".m", "path": "spm5-master/spm_eeg_rdata_CTF275.m", "size": 7267, "source_encoding": "utf_8", "md5": "b651bcf377a7a29b4661c27a68df88d3", "text": "function D = spm_eeg_rdata_CTF275(S)\n%%%% function to read in CTF data to Matlab\n\ntry\n\ttimewindow = S.tw;\ncatch\n\ttimewindow = spm_input('do you want to read in all the data','+1','yes|no',[1 0]);\nend\nif timewindow ==1 \n timeperiod='all';\nelse\n try\n timeperiod=S.timeperiod;\n catch\n [Finter,Fgraph,CmdLine] = spm('FnUIsetup','MEG data conversion ',0);\n str = 'time window';\n YPos = -1;\n while 1\n if YPos == -1\n YPos = '+1';\n end\n [timeperiod, YPos] = spm_input(str, YPos, 'r');\n if timeperiod(1) < timeperiod(2), break, end\n str = sprintf('window must increase with time');\n end\n end\nend\ntry\n pre_data = ctf_read(S.Fdata,[],timeperiod,[],0);\ncatch\n error('wrong folder name')\nend\n\ntry\n Fchannels = S.Fchannels;\ncatch\n Fchannels = spm_select(1, '\\.mat$', 'Select channel template file', {}, fullfile(spm('dir'), 'EEGtemplates'));\nend\n\n\nD.channels.ctf = spm_str_manip(Fchannels, 't');\n\nD.channels.Bad = [];\n\n% compatibility with some preprocessing functions\nD.channels.heog = 0;\nD.channels.veog = 0;\nD.channels.reference = 0;\n\nI = STRMATCH('UPPT0',pre_data.sensor.label)\nif isempty(I)\n warning(sprintf('No parallel port event channel was found in the CTF file: your data will be read without events'))\n D.events.time=[];\n D.events.code=[];\nelse\n if length(I)==1\n PP1=squeeze(pre_data.data(:,I(1)));\n else\n PP1=squeeze(pre_data.data(:,I(1)));\n PP2=squeeze(pre_data.data(:,I(2)));\n end\n D.events.time=[];\n D.events.code=[];\n inds=find(diff(PP1)>0);\n if ~isempty(inds)\n if length(PP1)1\n inds=find(diff(PP2)<0);\n if ~isempty(inds)\n D.events.code=[D.events.code,PP2(inds+1)'+255];\n \n D.events.time=[D.events.time,inds'+1];\n end\n end\n \n [X,I]=sort(D.events.time);\n D.events.time=D.events.time(I);\n D.events.code=D.events.code(I);\nend\nsens=strmatch('M',pre_data.sensor.label);\nD.channels.name=pre_data.sensor.label(sens);\nD.channels.order=[1:length(sens)];\nD.Nchannels=length(sens);\nD.channels.eeg=[1:length(sens)];\nD.Radc=pre_data.setup.sample_rate;\nD.Nsamples=pre_data.setup.number_samples;\nD.Nevents=pre_data.setup.number_trials;\n[pathstr,name,ext,versn]=spm_fileparts(pre_data.folder);\nD.datatype= 'float';\nD.fname=[name,'.mat'];\nD.path=pwd;\nD.fnamedat=[name,'.dat'];\nif D.Nevents>1\n D.events.start=pre_data.setup.pretrigger_samples;\n D.events.stop=D.Nsamples-pre_data.setup.pretrigger_samples-1;\n D.events.reject=zeros(1,D.Nevents);\n D.events.code=ones(1,D.Nevents);\n D.events.types=1;\n D.events.Ntypes=1;\nend\nD.scale = ones(D.Nchannels, 1, D.Nevents);\n\nfpd = fopen(fullfile(D.path, D.fnamedat), 'w');\nfor ev=1:D.Nevents\n for n=1:D.Nsamples\n\t\n\t\tfwrite(fpd, pre_data.data(n,sens,ev).*1e15, 'float');\n\t\n end\nend\n\n\n \nfclose(fpd);\n\n% --- Save coil/sensor positions and orientations for source reconstruction (in mm) ---\n\n% - channel locations and orientations\nSensLoc = [];\nSensOr = [];\nfor i = 1:length(pre_data.sensor.location);\n if any(pre_data.sensor.location(:,i)) & pre_data.sensor.label{i}(1) == 'M'\n SensLoc = [SensLoc; pre_data.sensor.location(:,i)'];\n SensOr = [SensOr ; pre_data.sensor.orientation(:,i)'];\n end\nend\nSensLoc = 10*SensLoc; % convertion from cm to mm\nif length(SensLoc) > 275\n warning(sprintf('Found more than 275 channels!\\n'));\nend\n\n[pth,nam,ext] = fileparts(D.fname);\nfic_sensloc = fullfile(D.path,[nam '_sensloc.mat']);\nfic_sensorient = fullfile(D.path,[nam '_sensorient.mat']);\nsave(fic_sensloc, 'SensLoc');\nsave(fic_sensorient, 'SensOr');\nclear SensLoc\n\n% for DCM/ERF: Use fieldtrip functions to retrieve sensor location and\n% orientation structure\nhdr = read_ctf_res4(findres4file(S.Fdata));\ngrad = fieldtrip_ctf2grad(hdr);\nD.channels.grad = grad;\n\n% - coil locations (in this order - NZ:nazion , LE: left ear , RE: right ear)\nCurrentDir = pwd;\ncd(pre_data.folder);\nhc_files = dir('*.hc');\nif isempty(hc_files)\n warning(sprintf('Impossible to find head coil file\\n'));\nelseif length(hc_files) > 1\n hc_file = spm_select(1, '\\.hc$', 'Select head coil file');\nelse\n hc_file = fullfile(pre_data.folder,hc_files.name);\nend\nclear hc_files\nfor coils=1:3\n fid = fopen(hc_file,'r');\n testlines = fgetl(fid);\n t=0;\n while t==0\n if coils==1 & strmatch('measured nasion coil position relative to head (cm):',testlines);\n t=1;\n for i = 1:3 % Nazion coordinates\n UsedLine = fgetl(fid);\n UsedLine = fliplr(deblank(fliplr(UsedLine)));\n [A,COUNT,ERRMSG,NEXTINDEX] = sscanf(UsedLine,'%c = %f');\n if ~isempty(ERRMSG) | (COUNT ~= 2)\n warning(sprintf('Unable to read head coil file\\n'));\n else\n NZ(i) = A(2);\n end\n end\n end\n if coils==2 & strmatch('measured left ear coil position relative to head (cm):',testlines);\n t=1;\n for i = 1:3 % Nazion coordinates\n UsedLine = fgetl(fid);\n UsedLine = fliplr(deblank(fliplr(UsedLine)));\n [A,COUNT,ERRMSG,NEXTINDEX] = sscanf(UsedLine,'%c = %f');\n if ~isempty(ERRMSG) | (COUNT ~= 2)\n warning(sprintf('Unable to read head coil file\\n'));\n else\n LE(i) = A(2);\n end\n end\n end\n if coils==3 & strmatch('measured right ear coil position relative to head (cm):',testlines);\n t=1;\n for i = 1:3 % Nazion coordinates\n UsedLine = fgetl(fid);\n UsedLine = fliplr(deblank(fliplr(UsedLine)));\n [A,COUNT,ERRMSG,NEXTINDEX] = sscanf(UsedLine,'%c = %f');\n if ~isempty(ERRMSG) | (COUNT ~= 2)\n warning(sprintf('Unable to read head coil file\\n'));\n else\n RE(i) = A(2);\n end\n end\n end\n testlines = fgetl(fid);\n end\n fclose(fid);\nend\n\n\nCoiLoc = 10*[NZ ; LE ; RE]; % convertion from cm to mm\ncd(CurrentDir);\n\nfic_sensloc = fullfile(D.path,[nam '_fidloc_meeg.mat']);\nsave(fic_sensloc,'CoiLoc');\nclear hc_file CoiLoc UnusedLines UsedLine A COUNT ERRMSG NEXTINDEX\n% -------\n\nD.modality = 'MEG';\nD.units = 'femto T';\n\nif spm_matlab_version_chk('7') >= 0\n save(fullfile(D.path, D.fname), '-V6', 'D');\nelse\n\tsave(fullfile(D.path, D.fname), 'D');\nend\n\n% find file name if truncated or with uppercase extension\n% added by Arnaud Delorme June 15, 2004\n% -------------------------------------------------------\nfunction res4name = findres4file( folder )\n\nres4name = dir([ folder filesep '*.res4' ]);\nif isempty(res4name)\n res4name = dir([ folder filesep '*.RES4' ]);\nend\n\nif isempty(res4name)\n error('No file with extension .res4 or .RES4 in selected folder');\nelse\n res4name = [ folder filesep res4name.name ];\nend;\nreturn\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_fmri_spm_ui.m", "ext": ".m", "path": "spm5-master/spm_fmri_spm_ui.m", "size": 18967, "source_encoding": "utf_8", "md5": "66b6af6d5d22fc23cfbb10e11fcf0d6f", "text": "function [SPM] = spm_fmri_spm_ui(SPM)\n% Setting up the general linear model for fMRI time-series\n% FORMAT [SPM] = spm_fmri_spm_ui(SPM)\n%\n% creates SPM with the following fields\n%\n% xY: [1x1 struct] - data stucture\n% nscan: [double] - vector of scans per session\n% xBF: [1x1 struct] - Basis function stucture (see spm_fMRI_design)\n% Sess: [1x1 struct] - Session stucture (see spm_fMRI_design)\n% xX: [1x1 struct] - Design matric stucture (see spm_fMRI_design)\n% xGX: [1x1 struct] - Global variate stucture\n% xVi: [1x1 struct] - Non-sphericity stucture\n% xM: [1x1 struct] - Masking stucture\n% xsDes: [1x1 struct] - Design description stucture\n%\n%\n% SPM.xY \n% P: [n x ? char] - filenames\n% VY: [n x 1 struct] - filehandles\n% RT: Repeat time\n%\n% SPM.xGX\n%\n% iGXcalc: {'none'|'Scaling'} - Global normalization option \n% sGXcalc: 'mean voxel value' - Calculation method\n% sGMsca: 'session specific' - Grand mean scaling\n% rg: [n x 1 double] - Global estimate\n% GM: 100 - Grand mean\n% gSF: [n x 1 double] - Global scaling factor\n%\n% SPM.xVi\n% Vi: {[n x n sparse]..} - covariance components\n% form: {'none'|'AR(1)'} - form of non-sphericity\n%\n% SPM.xM \n% T: [n x 1 double] - Masking index\n% TH: [n x 1 double] - Threshold\n% I: 0\n% VM: - Mask filehandles\n% xs: [1x1 struct] - cellstr description\n%\n% (see also spm_spm_ui)\n%\n%____________________________________________________________________________\n%\n% spm_fmri_spm_ui configures the design matrix, data specification and\n% filtering that specify the ensuing statistical analysis. These\n% arguments are passed to spm_spm that then performs the actual parameter\n% estimation.\n%\n% The design matrix defines the experimental design and the nature of\n% hypothesis testing to be implemented. The design matrix has one row\n% for each scan and one column for each effect or explanatory variable.\n% (e.g. regressor or stimulus function). The parameters are estimated in\n% a least squares sense using the general linear model. Specific profiles\n% within these parameters are tested using a linear compound or contrast\n% with the T or F statistic. The resulting statistical map constitutes \n% an SPM. The SPM{T}/{F} is then characterized in terms of focal or regional\n% differences by assuming that (under the null hypothesis) the components of\n% the SPM (i.e. residual fields) behave as smooth stationary Gaussian fields.\n%\n% spm_fmri_spm_ui allows you to (i) specify a statistical model in terms\n% of a design matrix, (ii) associate some data with a pre-specified design\n% [or (iii) specify both the data and design] and then proceed to estimate\n% the parameters of the model.\n% Inferences can be made about the ensuing parameter estimates (at a first\n% or fixed-effect level) in the results section, or they can be re-entered\n% into a second (random-effect) level analysis by treating the session or \n% subject-specific [contrasts of] parameter estimates as new summary data.\n% Inferences at any level obtain by specifying appropriate T or F contrasts\n% in the results section to produce SPMs and tables of p values and statistics.\n%\n% spm_fmri_spm calls spm_fMRI_design which allows you to configure a\n% design matrix in terms of events or epochs. \n%\n% spm_fMRI_design allows you to build design matrices with separable\n% session-specific partitions. Each partition may be the same (in which\n% case it is only necessary to specify it once) or different. Responses\n% can be either event- or epoch related, The only distinction is the duration\n% of the underlying input or stimulus function. Mathematically they are both\n% modeled by convolving a series of delta (stick) or box functions (u),\n% indicating the onset of an event or epoch with a set of basis\n% functions. These basis functions model the hemodynamic convolution,\n% applied by the brain, to the inputs. This convolution can be first-order\n% or a generalized convolution modeled to second order (if you specify the \n% Volterra option). [The same inputs are used by the hemodynamic model or\n% or dynamic causal models which model the convolution explicitly in terms of \n% hidden state variables (see spm_hdm_ui and spm_dcm_ui).]\n% Basis functions can be used to plot estimated responses to single events \n% once the parameters (i.e. basis function coefficients) have\n% been estimated. The importance of basis functions is that they provide\n% a graceful transition between simple fixed response models (like the\n% box-car) and finite impulse response (FIR) models, where there is one\n% basis function for each scan following an event or epoch onset. The\n% nice thing about basis functions, compared to FIR models, is that data\n% sampling and stimulus presentation does not have to be synchronized\n% thereby allowing a uniform and unbiased sampling of peri-stimulus time.\n% \n% Event-related designs may be stochastic or deterministic. Stochastic\n% designs involve one of a number of trial-types occurring with a\n% specified probably at successive intervals in time. These\n% probabilities can be fixed (stationary designs) or time-dependent\n% (modulated or non-stationary designs). The most efficient designs\n% obtain when the probabilities of every trial type are equal.\n% A critical issue in stochastic designs is whether to include null events\n% If you wish to estimate the evoke response to a specific event\n% type (as opposed to differential responses) then a null event must be\n% included (even if it is not modeled explicitly).\n% \n% The choice of basis functions depends upon the nature of the inference\n% sought. One important consideration is whether you want to make\n% inferences about compounds of parameters (i.e. contrasts). This is\n% the case if (i) you wish to use a SPM{T} to look separately at\n% activations and deactivations or (ii) you with to proceed to a second\n% (random-effect) level of analysis. If this is the case then (for\n% event-related studies) use a canonical hemodynamic response function\n% (HRF) and derivatives with respect to latency (and dispersion). Unlike\n% other bases, contrasts of these effects have a physical interpretation\n% and represent a parsimonious way of characterising event-related\n% responses. Bases such as a Fourier set require the SPM{F} for\n% inference.\n% \n% See spm_fMRI_design for more details about how designs are specified.\n%\n% Serial correlations in fast fMRI time-series are dealt with as\n% described in spm_spm. At this stage you need to specify the filtering\n% that will be applied to the data (and design matrix) to give a\n% generalized least squares (GLS) estimate of the parameters required.\n% This filtering is important to ensure that the GLS estimate is\n% efficient and that the error variance is estimated in an unbiased way.\n% \n% The serial correlations will be estimated with a ReML (restricted\n% maximum likelihood) algorithm using an autoregressive AR(1) model \n% during parameter estimation. This estimate assumes the same\n% correlation structure for each voxel, within each session. The ReML\n% estimates are then used to correct for non-sphericity during inference\n% by adjusting the statistics and degrees of freedom appropriately. The\n% discrepancy between estimated and actual intrinsic (i.e. prior to\n% filtering) correlations are greatest at low frequencies. Therefore\n% specification of the high-pass filter is particularly important.\n%\n% High-pass filtering is implemented at the level of the\n% filtering matrix K (as opposed to entering as confounds in the design\n% matrix). The default cutoff period is 128 seconds. Use 'explore design'\n% to ensure this cutof is not removing too much experimental variance.\n% Note that high-pass filtering uses a residual forming matrix (i.e.\n% it is not a convolution) and is simply to a way to remove confounds\n% without estimating their parameters explicitly. The constant term\n% is also incorporated into this filter matrix.\n%\n%-----------------------------------------------------------------------\n% Refs:\n%\n% Friston KJ, Holmes A, Poline J-B, Grasby PJ, Williams SCR, Frackowiak\n% RSJ & Turner R (1995) Analysis of fMRI time-series revisited. NeuroImage\n% 2:45-53\n%\n% Worsley KJ and Friston KJ (1995) Analysis of fMRI time-series revisited -\n% again. NeuroImage 2:178-181\n%\n% Friston KJ, Frith CD, Frackowiak RSJ, & Turner R (1995) Characterising\n% dynamic brain responses with fMRI: A multivariate approach NeuroImage -\n% 2:166-172\n%\n% Frith CD, Turner R & Frackowiak RSJ (1995) Characterising evoked \n% hemodynamics with fMRI Friston KJ, NeuroImage 2:157-165\n%\n% Josephs O, Turner R and Friston KJ (1997) Event-related fMRI, Hum. Brain\n% Map. 0:00-00\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Karl Friston, Jean-Baptiste Poline & Christian Buchel\n% $Id: spm_fmri_spm_ui.m 592 2006-08-14 18:36:21Z Darren $\n\nSCCSid = '$Rev: 592 $';\n\n%-GUI setup\n%-----------------------------------------------------------------------\n[Finter,Fgraph,CmdLine] = spm('FnUIsetup','fMRI stats model setup',0);\nspm_help('!ContextHelp',mfilename)\n\nglobal defaults\n\n% get design matrix and/or data\n%=======================================================================\nif ~nargin\n\n\tstr = 'specify design or data';\n\tif spm_input(str,1,'b',{'design','data'},[1 0]);\n\n\t\t% specify a design\n\t\t%-------------------------------------------------------\n\t\tif sf_abort, spm_clf(Finter), return, end\n\t\tSPM = spm_fMRI_design;\n\t\tspm_fMRI_design_show(SPM);\n\t\treturn\n\n\telse\n\n\t\t% get design\n\t\t%-------------------------------------------------------\n\t\tload(spm_select(1,'^SPM\\.mat$','Select SPM.mat'));\n\n\tend\n\nelse\n\n\t% get design matrix\n\t%---------------------------------------------------------------\n\tSPM = spm_fMRI_design(SPM);\n\nend\n\n% get Repeat time\n%-----------------------------------------------------------------------\ntry\n\tRT = SPM.xY.RT;\ncatch\n\tRT = spm_input('Interscan interval {secs}','+1');\n\tSPM.xY.RT = RT;\nend\n\n\n% session and scan number\n%-----------------------------------------------------------------------\nnscan = SPM.nscan;\nnsess = length(nscan);\n\n% check data are specified\n%-----------------------------------------------------------------------\ntry \n\tSPM.xY.P;\ncatch\n\n\t% get filenames\n\t%---------------------------------------------------------------\n\tP = [];\n\tfor i = 1:nsess\n\t\tstr = sprintf('select scans for session %0.0f',i);\n\t\tq = spm_select(nscan(i),'image',str);\n\t\tP = strvcat(P,q);\n\tend\n\n\t% place in data field\n\t%---------------------------------------------------------------\n\tSPM.xY.P = P;\n\nend\n\n\n\n% Assemble remaining design parameters\n%=======================================================================\nspm_help('!ContextHelp',mfilename)\nSPM.SPMid = spm('FnBanner',mfilename,SCCSid);\n\n\n% Global normalization\n%-----------------------------------------------------------------------\nnsess = length(SPM.nscan);\ntry \n\tSPM.xGX.iGXcalc;\ncatch\n\tspm_input('Global intensity normalisation...',1,'d',mfilename)\n\tstr = 'remove Global effects';\n\tSPM.xGX.iGXcalc = spm_input(str,'+1','scale|none',{'Scaling' 'None'});\nend\nSPM.xGX.sGXcalc = 'mean voxel value';\nSPM.xGX.sGMsca = 'session specific';\n\n\n% High-pass filtering and serial correlations\n%=======================================================================\n\n% low frequency confounds\n%-----------------------------------------------------------------------\ntry\n myLastWarn = 0;\n HParam = [SPM.xX.K(:).HParam];\n if ( length(HParam) == 1 )\n HParam = HParam*ones(1,nsess);\n elseif ( length(HParam) ~= nsess )\n % Uh Oh - somehow the number of specified HParam values and\n % sessions don't match. Throw an error, continue with manual HPF\n % specification, and alert! the user.\n % go to the catch block\n myLastWarn = 1;\n error;\n end\ncatch\n % specify low frequency confounds\n %---------------------------------------------------------------\n spm_input('Temporal autocorrelation options','+1','d',mfilename)\n switch spm_input('High-pass filter?','+1','b','none|specify');\n\n case 'specify' % default 128 seconds\n %-------------------------------------------------------\n HParam = 128*ones(1,nsess);\n str = 'cutoff period (secs)';\n HParam = spm_input(str,'+1','e',HParam,[1 nsess]);\n\n case 'none' % Inf seconds (i.e. constant term only)\n %-------------------------------------------------------\n HParam = Inf*ones(1,nsess);\n end\n % This avoids displaying the warning if we had existed the try block\n % at the level of accessing HParam.\n if myLastWarn\n warning('SPM:InvalidHighPassFilterSpec',...\n ['Different number of High-pass filter values and sessions.\\n',...\n 'HPF filter configured manually. Design setup will proceed.']);\n clear myLastWarn\n end\nend\n\n% create and set filter struct\n%---------------------------------------------------------------\nfor i = 1:nsess\n\tK(i) = struct(\t'HParam',\tHParam(i),...\n\t\t\t'row',\t\tSPM.Sess(i).row,...\n\t\t\t'RT',\t\tSPM.xY.RT);\nend\nSPM.xX.K = spm_filter(K);\n\n\n% intrinsic autocorrelations (Vi)\n%-----------------------------------------------------------------------\ntry \n\tcVi = SPM.xVi.form;\ncatch\n\t% Contruct Vi structure for non-sphericity ReML estimation\n\t%===============================================================\n\tstr = 'Correct for serial correlations?';\n\tcVi = {'none','AR(1)'};\n\tcVi = spm_input(str,'+1','b',cVi);\nend\n\n% create Vi struct\n%-----------------------------------------------------------------------\n\nif ~ischar(cVi)\t% AR coeficient[s] specified\n%-----------------------------------------------------------------------\n\tSPM.xVi.Vi = spm_Ce(nscan,cVi(1:3));\n\tcVi = ['AR( ' sprintf('%0.1f ',cVi) ')'];\n\nelse\n switch lower(cVi)\n\n\tcase 'none'\t\t% xVi.V is i.i.d\n\t%---------------------------------------------------------------\n\tSPM.xVi.V = speye(sum(nscan));\n\tcVi = 'i.i.d';\n\n\n\totherwise\t\t% otherwise assume AR(0.2) in xVi.Vi\n\t%---------------------------------------------------------------\n\tSPM.xVi.Vi = spm_Ce(nscan,0.2);\n\tcVi = 'AR(0.2)';\n\n end\nend\nSPM.xVi.form = cVi;\n\n\n\n%=======================================================================\n% - C O N F I G U R E D E S I G N\n%=======================================================================\nspm_clf(Finter);\nspm('FigName','Configuring, please wait...',Finter,CmdLine);\nspm('Pointer','Watch');\n\n\n% get file identifiers\n%=======================================================================\n\n%-Map files\n%-----------------------------------------------------------------------\nfprintf('%-40s: ','Mapping files') \t %-#\nVY = spm_vol(SPM.xY.P);\nfprintf('%30s\\n','...done') \t %-#\n\n\n%-check internal consistency of images\n%-----------------------------------------------------------------------\nspm_check_orientations(VY);\n\n%-place in xY\n%-----------------------------------------------------------------------\nSPM.xY.VY = VY;\n\n\n%-Compute Global variate\n%=======================================================================\nGM = 100;\nq = length(VY);\ng = zeros(q,1);\nfprintf('%-40s: %30s','Calculating globals',' ') %-#\nfor i = 1:q\n\tfprintf('%s%30s',repmat(sprintf('\\b'),1,30),sprintf('%4d/%-4d',i,q)) %-#\n\tg(i) = spm_global(VY(i));\nend\nfprintf('%s%30s\\n',repmat(sprintf('\\b'),1,30),'...done') %-#\n\n% scale if specified (otherwise session specific grand mean scaling)\n%-----------------------------------------------------------------------\ngSF = GM./g;\nif strcmp(lower(SPM.xGX.iGXcalc),'none')\n\tfor i = 1:nsess\n\t\tgSF(SPM.Sess(i).row) = GM./mean(g(SPM.Sess(i).row));\n\tend\nend\n\n%-Apply gSF to memory-mapped scalefactors to implement scaling\n%-----------------------------------------------------------------------\nfor i = 1:q\n\tSPM.xY.VY(i).pinfo(1:2,:) = SPM.xY.VY(i).pinfo(1:2,:)*gSF(i);\nend\n\n%-place global variates in global structure\n%-----------------------------------------------------------------------\nSPM.xGX.rg = g;\nSPM.xGX.GM = GM;\nSPM.xGX.gSF = gSF;\n\n\n%-Masking structure automatically set to 80% of mean\n%=======================================================================\ntry\n\tTH = g.*gSF*defaults.mask.thresh;\ncatch\n\tTH = g.*gSF*0.8;\nend\nSPM.xM = struct(\t'T',\tones(q,1),...\n\t\t\t'TH',\tTH,...\n\t\t\t'I',\t0,...\n\t\t\t'VM',\t{[]},...\n\t\t\t'xs',\tstruct('Masking','analysis threshold'));\n\n\n%-Design description - for saving and display\n%=======================================================================\nfor i = 1:nsess, ntr(i) = length(SPM.Sess(i).U); end\nFstr = sprintf('[min] Cutoff period %d seconds',min(HParam));\nSPM.xsDes = struct(...\n\t'Basis_functions',\tSPM.xBF.name,...\n\t'Number_of_sessions',\tsprintf('%d',nsess),...\n\t'Trials_per_session',\tsprintf('%-3d',ntr),...\n\t'Interscan_interval',\tsprintf('%0.2f {s}',SPM.xY.RT),...\n\t'High_pass_Filter',\tsprintf('Cutoff: %d {s}',SPM.xX.K(1).HParam),...\n\t'Global_calculation',\tSPM.xGX.sGXcalc,...\n\t'Grand_mean_scaling',\tSPM.xGX.sGMsca,...\n\t'Global_normalisation',\tSPM.xGX.iGXcalc);\n\n\n%-Save SPM.mat\n%-----------------------------------------------------------------------\nfprintf('%-40s: ','Saving SPM configuration') %-#\nif spm_matlab_version_chk('7') >= 0,\n\tsave('SPM', 'SPM', '-V6');\nelse\n\tsave('SPM', 'SPM');\nend;\nfprintf('%30s\\n','...SPM.mat saved') %-#\n\n \n%-Display Design report\n%=======================================================================\nfprintf('%-40s: ','Design reporting') %-#\nfname = cat(1,{SPM.xY.VY.fname}');\nspm_DesRep('DesMtx',SPM.xX,fname,SPM.xsDes)\nfprintf('%30s\\n','...done') %-#\n\n\n%-End: Cleanup GUI\n%=======================================================================\nspm_clf(Finter)\nspm('FigName','Stats: configured',Finter,CmdLine);\nspm('Pointer','Arrow')\nfprintf('\\n\\n')\n\n\n%=======================================================================\n%- S U B - F U N C T I O N S\n%=======================================================================\n\nfunction abort = sf_abort\n%=======================================================================\nif exist(fullfile('.','SPM.mat'))\n\tstr = {\t'Current directory contains existing SPM file:',...\n\t\t'Continuing will overwrite existing file!'};\n\n\tabort = spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);\n\tif abort, fprintf('%-40s: %30s\\n\\n',...\n\t\t'Abort... (existing SPM files)',spm('time')), end\nelse\n\tabort = 0;\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_input.m", "ext": ".m", "path": "spm5-master/spm_input.m", "size": 83619, "source_encoding": "utf_8", "md5": "7a6922167daf9947097ce8acfb9902eb", "text": "function varargout = spm_input(varargin)\n% Comprehensive graphical and command line input function\n% FORMATs (given in Programmers Help)\n%_______________________________________________________________________\n%\n% spm_input handles most forms of interactive user input for SPM.\n% (File selection is handled by spm_select.m)\n%\n% There are five types of input: String, Evaluated, Conditions, Buttons\n% and Menus: These prompt for string input; string input which is\n% evaluated to give a numerical result; selection of one item from a\n% set of buttons; selection of an item from a menu.\n%\n% - STRING, EVALUATED & CONDITION input -\n% For STRING, EVALUATED and CONDITION input types, a prompt is\n% displayed adjacent to an editable text entry widget (with a lilac\n% background!). Clicking in the entry widget allows editing, pressing\n% or enters the result. You must enter something,\n% empty answers are not accepted. A default response may be pre-specified\n% in the entry widget, which will then be outlined. Clicking the border\n% accepts the default value.\n%\n% Basic editing of the entry widget is supported *without* clicking in\n% the widget, provided no other graphics widget has the focus. (If a\n% widget has the focus, it is shown highlighted with a thin coloured\n% line. Clicking on the window background returns the focus to the\n% window, enabling keyboard accelerators.). This enables you to type\n% responses to a sequence of questions without having to repeatedly\n% click the mouse in the text widgets. Supported are BackSpace and\n% Delete, line kill (^U). Other standard ASCII characters are appended\n% to the text in the entry widget. Press or to submit\n% your response.\n%\n% A ContextMenu is provided (in the figure background) giving access to\n% relevant utilities including the facility to load input from a file\n% (see spm_load.m and examples given below): Click the right button on\n% the figure background.\n%\n% For EVALUATED input, the string submitted is evaluated in the base\n% MatLab workspace (see MatLab's `eval` command) to give a numerical\n% value. This permits the entry of numerics, matrices, expressions,\n% functions or workspace variables. I.e.:\n% i) - a number, vector or matrix e.g. \"[1 2 3 4]\"\n% \"[1:4]\"\n% \"1:4\"\n% ii) - an expression e.g. \"pi^2\"\n% \"exp(-[1:36]/5.321)\"\n% iii) - a function (that will be invoked) e.g. \"spm_load('tmp.dat')\"\n% (function must be on MATLABPATH) \"input_cov(36,5.321)\"\n% iv) - a variable from the base workspace\n% e.g. \"tmp\"\n%\n% The last three options provide a great deal of power: spm_load will\n% load a matrix from an ASCII data file and return the results. When\n% called without an argument, spm_load will pop up a file selection\n% dialog. Alternatively, this facility can be gained from the\n% ContextMenu. The second example assummes a custom funcion called\n% input_cov has been written which expects two arguments, for example\n% the following file saved as input_cov.m somewhere on the MATLABPATH\n% (~/matlab, the matlab subdirectory of your home area, and the current\n% directory, are on the MATLABPATH by default):\n%\n% function [x] = input_cov(n,decay)\n% % data input routine - mono-exponential covariate\n% % FORMAT [x] = input_cov(n,decay)\n% % n - number of time points\n% % decay - decay constant\n% x = exp(-[1:n]/decay);\n%\n% Although this example is trivial, specifying large vectors of\n% empirical data (e.g. reaction times for 72 scans) is efficient and\n% reliable using this device. In the last option, a variable called tmp\n% is picked up from the base workspace. To use this method, set the\n% variables in the MatLab base workspace before starting an SPM\n% procedure (but after starting the SPM interface). E.g.\n% >> tmp=exp(-[1:36]/5.321)\n%\n% Occasionally a vector of a specific length will be required: This\n% will be indicated in the prompt, which will start with \"[#]\", where\n% # is the length of vector(s) required. (If a matrix is entered then\n% at least one dimension should equal #.)\n%\n% Occasionally a specific type of number will be required. This should\n% be obvious from the context. If you enter a number of the wrong type,\n% you'll be alerted and asked to re-specify. The types are i) Real\n% numbers; ii) Integers; iii) Whole numbers [0,1,2,3,...] & iv) Natural\n% numbers [1,2,3,...]\n%\n% CONDITIONS type input is for getting indicator vectors. The features\n% of evaluated input described above are complimented as follows:\n% v) - a compressed list of digits 0-9 e.g. \"12121212\"\n% ii) - a list of indicator characters e.g. \"abababab\"\n% a-z mapped to 1-26 in alphabetical order, *except* r (\"rest\")\n% which is mapped to zero (case insensitive, [A:Z,a:z] only)\n% ...in addition the response is checked to ensure integer condition indices.\n% Occasionally a specific number of conditions will be required: This\n% will be indicated in the prompt, which will end with (#), where # is\n% the number of conditions required.\n%\n% CONTRAST type input is for getting contrast weight vectors. Enter\n% contrasts as row-vectors. Contrast weight vectors will be padded with\n% zeros to the correct length, and checked for validity. (Valid\n% contrasts are estimable, which are those whose weights vector is in\n% the row-space of the design matrix.)\n%\n% Errors in string evaluation for EVALUATED & CONDITION types are\n% handled gracefully, the user notified, and prompted to re-enter.\n%\n% - BUTTON input -\n% For Button input, the prompt is displayed adjacent to a small row of\n% buttons. Press the approprate button. The default button (if\n% available) has a dark outline. Keyboard accelerators are available\n% (provided no graphics widget has the focus): or \n% selects the default button (if available). Typing the first character\n% of the button label (case insensitive) \"presses\" that button. (If\n% these Keys are not unique, then the integer keys 1,2,... \"press\" the\n% appropriate button.)\n%\n% The CommandLine variant presents a simple menu of buttons and prompts\n% for a selection. Any default response is indicated, and accepted if\n% an empty line is input.\n%\n%\n% - MENU input -\n% For Menu input, the prompt is displayed in a pull down menu widget.\n% Using the mouse, a selection is made by pulling down the widget and\n% releasing the mouse on the appropriate response. The default response\n% (if set) is marked with an asterisk. Keyboard accelerators are\n% available (provided no graphic widget has the focus) as follows: 'f',\n% 'n' or 'd' move forward to next response down; 'b', 'p' or 'u' move\n% backwards to the previous response up the list; the number keys jump\n% to the appropriate response number; or slelects the\n% currently displayed response. If a default is available, then\n% pressing or when the prompt is displayed jumps to\n% the default response.\n%\n% The CommandLine variant presents a simple menu and prompts for a selection.\n% Any default response is indicated, and accepted if an empty line is\n% input.\n%\n%\n% - Combination BUTTON/EDIT input -\n% In this usage, you will be presented with a set of buttons and an\n% editable text widget. Click one of the buttons to choose that option,\n% or type your response in the edit widget. Any default response will\n% be shown in the edit widget. The edit widget behaves in the same way\n% as with the STRING/EVALUATED input, and expects a single number.\n% Keypresses edit the text widget (rather than \"press\" the buttons)\n% (provided no other graphics widget has the focus). A default response\n% can be selected with the mouse by clicking the thick border of the\n% edit widget.\n%\n%\n% - Comand line -\n% If YPos is 0 or global CMDLINE is true, then the command line is used.\n% Negative YPos overrides CMDLINE, ensuring the GUI is used, at\n% YPos=abs(YPos). Similarly relative YPos beginning with '!'\n% (E.g.YPos='!+1') ensures the GUI is used.\n%\n% spm_input uses the SPM 'Interactive' window, which is 'Tag'ged\n% 'Interactive'. If there is no such window, then the current figure is\n% used, or an 'Interactive' window created if no windows are open.\n%\n%-----------------------------------------------------------------------\n% Programers help is contained in the main body of spm_input.m\n%-----------------------------------------------------------------------\n% See : input.m (MatLab Reference Guide)\n% See also : spm_select.m (SPM file selector dialog)\n% : spm_input.m (Input wrapper function - handles batch mode)\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Andrew Holmes\n% $Id: spm_input.m 2818 2009-03-03 11:04:15Z guillaume $\n\n\n%=======================================================================\n% - FORMAT specifications for programers\n%=======================================================================\n% generic - [p,YPos] = spm_input(Prompt,YPos,Type,...)\n% string - [p,YPos] = spm_input(Prompt,YPos,'s',DefStr)\n% string+ - [p,YPos] = spm_input(Prompt,YPos,'s+',DefStr)\n% evaluated - [p,YPos] = spm_input(Prompt,YPos,'e',DefStr,n)\n% - natural - [p,YPos] = spm_input(Prompt,YPos,'n',DefStr,n,mx)\n% - whole - [p,YPos] = spm_input(Prompt,YPos,'w',DefStr,n,mx)\n% - integer - [p,YPos] = spm_input(Prompt,YPos,'i',DefStr,n)\n% - real - [p,YPos] = spm_input(Prompt,YPos,'r',DefStr,n,mm)\n% condition - [p,YPos] = spm_input(Prompt,YPos,'c',DefStr,n,m)\n% contrast - [p,YPos] = spm_input(Prompt,YPos,'x',DefStr,n,X)\n% permutation- [p,YPos] = spm_input(Prompt,YPos,'p',DefStr,P,n)\n% button - [p,YPos] = spm_input(Prompt,YPos,'b',Labels,Values,DefItem)\n% button/edit combo's (edit for string or typed scalar evaluated input)\n% [p,YPos] = spm_input(Prompt,YPos,'b?1',Labels,Values,DefStr,mx)\n% ...where ? in b?1 specifies edit widget type as with string & eval'd input\n% - [p,YPos] = spm_input(Prompt,YPos,'n1',DefStr,mx)\n% - [p,YPos] = spm_input(Prompt,YPos,'w1',DefStr,mx)\n% button dialog \n% - [p,YPos] = spm_input(Prompt,YPos,'bd',...\n% Labels,Values,DefItem,Title)\n% menu - [p,YPos] = spm_input(Prompt,YPos,'m',Labels,Values,DefItem)\n% display - spm_input(Message,YPos,'d',Label)\n% display - (GUI only) spm_input(Alert,YPos,'d!',Label)\n%\n% yes/no - [p,YPos] = spm_input(Prompt,YPos,'y/n',Values,DefItem)\n% buttons (shortcut) where Labels is a bar delimited string\n% - [p,YPos] = spm_input(Prompt,YPos,Labels,Values,DefItem)\n%\n% NB: Natural numbers are [1:Inf), Whole numbers are [0:Inf)\n% \n% -- Parameters (input) --\n%\n% Prompt - prompt string\n% - Defaults (missing or empty) to 'Enter an expression'\n%\n% YPos - (numeric) vertical position {1 - 12}\n% - overriden by global CMDLINE\n% - 0 for command line\n% - negative to force GUI\n% - (string) relative vertical position E.g. '+1'\n% - relative to last position used\n% - overriden by global CMDLINE\n% - YPos(1)=='!' forces GUI E.g. '!+1'\n% - '_' is a shortcut for the lowest GUI position\n% - Defaults (missing or empty) to '+1'\n%\n% Type - type of interrogation\n% - 's'tring\n% - 's+' multi-line string\n% - p returned as cellstr (nx1 cell array of strings)\n% - DefStr can be a cellstr or string matrix\n% - 'e'valuated string\n% - 'n'atural numbers\n% - 'w'hole numbers\n% - 'i'ntegers\n% - 'r'eals\n% - 'c'ondition indicator vector\n% - 'x' - contrast entry\n% - If n(2) or design matrix X is specified, then\n% contrast matrices are padded with zeros to have\n% correct length.\n% - if design matrix X is specified, then contrasts are\n% checked for validity (i.e. in the row-space of X)\n% (checking handled by spm_SpUtil)\n% - 'b'uttons\n% - 'bd' - button dialog: Uses MatLab's questdlg\n% - For up to three buttons\n% - Prompt can be a cellstr with a long multiline message\n% - CmdLine support as with 'b' type\n% - button/edit combo's: 'be1','bn1','bw1','bi1','br1'\n% - second letter of b?1 specifies type for edit widget\n% - 'n1' - single natural number (buttons 1,2,... & edit)\n% - 'w1' - single whole number (buttons 0,1,... & edit)\n% - 'm'enu pulldown\n% - 'y/n' : Yes or No buttons\n% (See shortcuts below)\n% - bar delimited string : buttons with these labels\n% (See shortcuts below)\n% - Defaults (missing or empty) to 'e'\n%\n% DefStr - Default string to be placed in entry widget for string and\n% evaluated types\n% - Defaults to ''\n%\n% n ('e', 'c' & 'p' types)\n% - Size of matrix requred\n% - NaN for 'e' type implies no checking - returns input as evaluated\n% - length of n(:) specifies dimension - elements specify size\n% - Inf implies no restriction\n% - Scalar n expanded to [n,1] (i.e. a column vector)\n% (except 'x' contrast type when it's [n,np] for np\n% - E.g: [n,1] & [1,n] (scalar n) prompt for an n-vector,\n% returned as column or row vector respectively\n% [1,Inf] & [Inf,1] prompt for a single vector,\n% returned as column or row vector respectively\n% [n,Inf] & [Inf,n] prompts for any number of n-vectors,\n% returned with row/column dimension n respectively.\n% [a,b] prompts for an 2D matrix with row dimension a and\n% column dimension b\n% [a,Inf,b] prompt for a 3D matrix with row dimension a,\n% page dimension b, and any column dimension.\n% - 'c' type can only deal with single vectors\n% - NaN for 'c' type treated as Inf\n% - Defaults (missing or empty) to NaN\n%\n% n ('x'type)\n% - Number of contrasts required by 'x' type (n(1))\n% ( n(2) can be used specify length of contrast vectors if )\n% ( a design matrix isn't passed )\n% - Defaults (missing or empty) to 1 - vector contrast\n%\n% mx ('n', 'w', 'n1', 'w1', 'bn1' & 'bw1' types)\n% - Maximum value (inclusive)\n%\n% mm ('r' type)\n% - Maximum and minimum values (inclusive)\n%\n% m - Number of unique conditions required by 'c' type\n% - Inf implies no restriction\n% - Defaults (missing or empty) to Inf - no restriction\n%\n% P - set (vector) of numbers of which a permutation is required\n%\n% X - Design matrix for contrast checking in 'x' type\n% - Can be either a straight matrix or a space structure (see spm_sp)\n% - Column dimension of design matrix specifies length of contrast\n% vectors (overriding n(2) is specified).\n%\n% Title - Title for questdlg in 'bd' type\n%\n% Labels - Labels for button and menu types.\n% - string matrix, one label per row\n% - bar delimited string\n% E.g. 'AnCova|Scaling|None'\n%\n% Values - Return values corresponding to Labels for button and menu types\n% - j-th row is returned if button / menu item j is selected\n% (row vectors are transposed)\n% - Defaults (missing or empty) to - (button) Labels\n% - ( menu ) menu item numbers\n%\n% DefItem - Default item number, for button and menu types.\n%\n% -- Parameters (output) --\n% p - results\n% YPos - Optional second output argument returns GUI position just used\n%\n%-----------------------------------------------------------------------\n% WINDOWS:\n%\n% spm_input uses the SPM 'Interactive' 'Tag'ged window. If this isn't\n% available and no figures are open, an 'Interactive' SPM window is\n% created (`spm('CreateIntWin')`). If figures are available, then the\n% current figure is used *unless* it is 'Tag'ged.\n%\n%-----------------------------------------------------------------------\n% SHORTCUTS:\n%\n% Buttons SHORTCUT - If the Type parameter is a bar delimited string, then\n% the Type is taken as 'b' with the specified labels, and the next parameter\n% (if specified) is taken for the Values.\n%\n% Yes/No question shortcut - p = spm_input(Prompt,YPos,'y/n') expands\n% to p = spm_input(Prompt,YPos,'b','yes|no',...), enabling easy use of\n% spm_input for yes/no dialogue. Values defaults to 'yn', so 'y' or 'n'\n% is returned as appropriate.\n%\n%-----------------------------------------------------------------------\n% EXAMPLES:\n% ( Specified YPos is overriden if global CMDLINE is )\n% ( true, when the command line versions are used. )\n%\n% p = spm_input\n% Command line input of an evaluated string, default prompt.\n% p = spm_input('Enter a value',1)\n% Evaluated string input, prompted by 'Enter a value', in\n% position 1 of the dialog figure.\n% p = spm_input(str,'+1','e',0.001)\n% Evaluated string input, prompted by contents of string str,\n% in next position of the dialog figure.\n% Default value of 0.001 offered.\n% p = spm_input(str,2,'e',[],5)\n% Evaluated string input, prompted by contents of string str,\n% in second position of the dialog figure.\n% Vector of length 5 required - returned as column vector\n% p = spm_input(str,2,'e',[],[Inf,5])\n% ...as above, but can enter multiple 5-vectors in a matrix,\n% returned with 5-vectors in rows\n% p = spm_input(str,0,'c','ababab')\n% Condition string input, prompted by contents of string str\n% Uses command line interface.\n% Default string of 'ababab' offered.\n% p = spm_input(str,0,'c','010101')\n% As above, but default string of '010101' offered.\n% [p,YPos] = spm_input(str,'0','s','Image')\n% String input, same position as last used, prompted by str,\n% default of 'Image' offered. YPos returns GUI position used.\n% p = spm_input(str,'-1','y/n')\n% Yes/No buttons for question with prompt str, in position one \n% before the last used Returns 'y' or 'n'.\n% p = spm_input(str,'-1','y/n',[1,0],2)\n% As above, but returns 1 for yes response, 0 for no,\n% with 'no' as the default response\n% p = spm_input(str,4,'AnCova|Scaling')\n% Presents two buttons labelled 'AnCova' & 'Scaling', with \n% prompt str, in position 4 of the dialog figure. Returns the \n% string on the depresed button, where buttons can be pressed \n% with the mouse or by the respective keyboard accelerators\n% 'a' & 's' (or 'A' & 'S').\n% p = spm_input(str,-4,'b','AnCova|Scaling',[],2)\n% As above, but makes \"Scaling\" the default response, and\n% overrides global CMDLINE\n% p = spm_input(str,0,'b','AnCova|Scaling|None',[1,2,3])\n% Prompts for [A]ncova / [S]caling / [N]one in MatLab command\n% window, returns 1, 2, or 3 according to the first character\n% of the entered string as one of 'a', 's', or 'n' (case \n% insensitive).\n% p = spm_input(str,1,'b','AnCova',1)\n%\t\tSince there's only one button, this just displays the response\n%\t\tin GUI position 1 (or on the command line if global CMDLINE\n%\t\tis true), and returns 1.\n%\tp = spm_input(str,'+0','br1','None|Mask',[-Inf,NaN],0.8)\n% Presents two buttons labelled \"None\" & \"Mask\" (which return\n% -Inf & NaN if clicked), together with an editable text widget\n% for entry of a single real number. The default of 0.8 is\n% initially presented in the edit window, and can be selected by\n% pressing return.\n%\t\tUses the previous GUI position, unless global CMDLINE is true,\n% in which case a command-line equivalent is used.\n%\tp = spm_input(str,'+0','w1')\n%\t\tPrompts for a single whole number using a combination of\n%\t\tbuttons and edit widget, using the previous GUI position,\n%\t\tor the command line if global CMDLINE is true.\n% p = spm_input(str,'!0','m','Single Subject|Multi Subject|Multi Study')\n% Prints the prompt str in a pull down menu containing items\n% 'Single Subject', 'Multi Subject' & 'Multi Study'. When OK is\n% clicked p is returned as the index of the choice, 1,2, or 3 \n% respectively. Uses last used position in GUI, irrespective of \n% global CMDLINE\n% p = spm_input(str,5,'m',...\n% 'Single Subject|Multi Subject|Multi Study',...\n% ['SS';'MS';'SP'],2)\n% As above, but returns strings 'SS', 'MS', or 'SP' according to\n% the respective choice, with 'MS; as the default response.\n% p = spm_input(str,0,'m',...\n% 'Single Subject|Multi Subject|Multi Study',...\n% ['SS';'MS';'SP'],2)\n% As above, but the menu is presented in the command window\n% as a numbered list.\n% spm_input('AnCova, GrandMean scaling',0,'d')\n% Displays message in a box in the MatLab command window\n% [null,YPos]=spm_input('Session 1','+1','d!','fMRI')\n%\t\tDisplays 'fMRI: Session 1' in next GUI position of the\n% 'Interactive' window. If CMDLINE is 1, then nothing is done.\n% Position used is returned in YPos.\n%\n%-----------------------------------------------------------------------\n% FORMAT h = spm_input(Prompt,YPos,'m!',Labels,cb,UD,XCB);\n% GUI PullDown menu utility - creates a pulldown menu in the Interactive window\n% FORMAT H = spm_input(Prompt,YPos,'b!',Labels,cb,UD,XCB);\n% GUI Buttons utility - creates GUI buttons in the Interactive window\n%\n% Prompt, YPos, Labels - as with 'm'enu/'b'utton types\n% cb - CallBack string\n% UD - UserData\n% XCB - Extended CallBack handling - allows different CallBack for each item,\n% and use of UD in CallBack strings. [Defaults to 1 for PullDown type\n% when multiple CallBacks specified, 0 o/w.]\n% H - Handle of 'PullDown' uicontrol / 'Button's\n%\n% In \"normal\" mode (when XCB is false), this is essentially a utility\n% to create a PullDown menu widget or set of buttons in the SPM\n% 'Interactive' figure, using positioning and Label definition\n% conveniences of the spm_input 'm'enu & 'b'utton types. If Prompt is\n% not empty, then the PullDown/Buttons appears on the right, with the\n% Prompt on the left, otherwise the PullDown/Buttons use the whole\n% width of the Interactive figure. The PopUp's CallBack string is\n% specified in cb, and [optional] UserData may be passed as UD.\n%\n% For buttons, a separate callback can be specified for each button, by\n% passing the callbacks corresponding to the Labels as rows of a\n% cellstr or string matrix.\n%\n% This \"different CallBacks\" facility can also be extended to the\n% PullDown type, using the \"extended callback\" mode (when XCB is\n% true). % In addition, in \"extended callback\", you can use UD to\n% refer to the UserData argument in the CallBack strings. (What happens\n% is this: The cb & UD are stored as fields in the PopUp's UserData\n% structure, and the PopUp's callback is set to spm_input('!m_cb'),\n% which reads UD into the functions workspace and eval's the\n% appropriate CallBack string. Note that this means that base\n% workspace variables are inaccessible (put what you need in UD), and\n% that any return arguments from CallBack functions are not passed back\n% to the base workspace).\n% \n%\n%-----------------------------------------------------------------------\n% UTILITY FUNCTIONS:\n%\n% FORMAT colour = spm_input('!Colour')\n% Returns colour for input widgets, as specified in COLOUR parameter at \n% start of code.\n% colour - [r,g,b] colour triple\n%\n% FORMAT [iCond,msg] = spm_input('!iCond',str,n,m)\n% Parser for special 'c'ondition type: Handles digit strings and\n% strings of indicator chars.\n% str - input string\n% n - length of condition vector required\t[defaut Inf - no restriction]\n% m - number of conditions required\t[default Inf - no restrictions]\n% iCond - Integer condition indicator vector\n% msg - status message\n%\n% FORMAT hM = spm_input('!InptConMen',Finter,H)\n% Sets a basic Input ContextMenu for the figure\n% Finter - figure to set menu in\n% H - handles of objects to delete on \"crash out\" option\n% hM - handle of UIContextMenu\n%\n% FORMAT [CmdLine,YPos] = spm_input('!CmdLine',YPos)\n% Sorts out whether to use CmdLine or not & canonicalises YPos\n% CmdLine - Binary flag\n% YPos - Position index\n%\n% FORMAT Finter = spm_input('!GetWin',F)\n% Locates (or creates) figure to work in\n% F - Interactive Figure, defaults to 'Interactive'\n% Finter - Handle of figure to use\n%\n% FORMAT [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp)\n% Raise window & jump pointer over question\n% RRec - Response rectangle of current question\n% F - Interactive Figure, Defaults to 'Interactive'\n% XDisp - X-displacement of cursor relative to RRec\n% PLoc - Pointer location before jumping\n% cF - Current figure before making F current.\n%\n% FORMAT [PLoc,cF] = spm_input('!PointerJumpBack',PLoc,cF)\n% Replace pointer and reset CurrentFigure back\n% PLoc - Pointer location before jumping\n% cF - Previous current figure\n%\n% FORMAT spm_input('!PrntPrmpt',Prompt,TipStr,Title)\n% Print prompt for CmdLine questioning\n% Prompt - prompt string, callstr, or string matrix\n% TipStr - tip string\n% Title - title string\n%\n% FORMAT [Frec,QRec,PRec,RRec] = spm_input('!InputRects',YPos,rec,F)\n% Returns rectangles (pixels) used in GUI\n% YPos - Position index\n% rec - Rectangle specifier: String, one of 'Frec','QRec','PRec','RRec'\n% Defaults to '', which returns them all.\n% F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive')\n% FRec - Position of interactive window\n% QRec - Position of entire question\n% PRec - Position of prompt\n% RRec - Position of response\n%\n% FORMAT spm_input('!DeleteInputObj',F)\n% Deltes input objects (only) from figure F\n% F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive')\n%\n% FORMAT [CPos,hCPos] = spm_input('!CurrentPos',F)\n% Returns currently used GUI question positions & their handles\n% F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive')\n% CPos - Vector of position indices\n% hCPos - (n x CPos) matrix of object handles\n%\n% FORMAT h = spm_input('!FindInputObj',F)\n% Returns handles of input GUI objects in figure F\n% F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive')\n% h - vector of object handles\n%\n% FORMAT [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine)\n% Returns next position index, specified by YPos\n% YPos - Absolute (integer) or relative (string) position index\n% Defaults to '+1'\n% F - Interactive Figure, defaults to spm_figure('FindWin','Interactive')\n% CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos)\n% NPos - Next position index\n% CPos & hCPos - as for !CurrentPos\n%\n% FORMAT NPos = spm_input('!SetNextPos',YPos,F,CmdLine)\n% Sets up for input at next position index, specified by YPos. This utility\n% function can be used stand-alone to implicitly set the next position\n% by clearing positions NPos and greater.\n% YPos - Absolute (integer) or relative (string) position index\n% Defaults to '+1'\n% F - Interactive Figure, defaults to spm_figure('FindWin','Interactive')\n% CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos)\n% NPos - Next position index\n%\n% FORMAT MPos = spm_input('!MaxPos',F,FRec3)\n% Returns maximum position index for figure F\n% F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive')\n%\t Not required if FRec3 is specified\n% FRec3 - Length of interactive figure in pixels\n% \n% FORMAT spm_input('!EditableKeyPressFcn',h,ch)\n% KeyPress callback for GUI string / eval input\n%\n% FORMAT spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch)\n% KeyPress callback for GUI buttons\n%\n% FORMAT spm_input('!PullDownKeyPressFcn',h,ch,DefItem)\n% KeyPress callback for GUI pulldown menus\n%\n% FORMAT spm_input('!m_cb')\n% Extended CallBack handler for 'p' PullDown utility type\n%\n% FORMAT spm_input('!dScroll',h,str)\n% Scroll text string in object h\n% h - handle of text object\n% Prompt - Text to scroll (Defaults to 'UserData' of h)\n%\n%-----------------------------------------------------------------------\n% SUBFUNCTIONS:\n%\n% FORMAT [Keys,Labs] = sf_labkeys(Labels)\n% Make unique character keys for the Labels, ignoring case.\n% Used with 'b'utton types.\n%\n% FORMAT [p,msg] = sf_eEval(str,Type,n,m)\n% Common code for evaluating various input types.\n%\n% FORMAT str = sf_SzStr(n,l)\n% Common code to construct prompt strings for pre-specified vector/matrix sizes\n%\n% FORMAT [p,msg] = sf_SzChk(p,n,msg)\n% Common code to check (& canonicalise) sizes of input vectors/matrices\n%\n%_______________________________________________________________________\n% @(#)spm_input.m\t2.8 Andrew Holmes 03/03/04\n\n\n%-Parameters\n%=======================================================================\nCOLOUR = get(0,'defaultUicontrolBackgroundColor');\nPJump = 1;\t\t%-Jumping of pointer to question?\nTTips = 1;\t\t%-Use ToolTipStrings? (which can be annoying!)\nConCrash = 1;\t\t%-Add \"crash out\" option to 'Interactive'fig.ContextMenu\n\n\n%-Condition arguments\n%=======================================================================\nif nargin<1|isempty(varargin{1}), Prompt=''; else, Prompt=varargin{1}; end\n\nif ~isempty(Prompt) & ischar(Prompt) & Prompt(1)=='!'\n\t%-Utility functions have Prompt string starting with '!'\n\tType = Prompt;\nelse\t\t\t%-Should be an input request: get Type & YPos\n\tif nargin<3|isempty(varargin{3}), Type='e'; else, Type=varargin{3}; end\n\tif any(Type=='|'), Type='b|'; end\n\tif nargin<2|isempty(varargin{2}), YPos='+1'; else, YPos=varargin{2}; end\n\n\t[CmdLine,YPos] = spm_input('!CmdLine',YPos);\n\n\tif ~CmdLine\t%-Setup for GUI use\n\t\t%-Locate (or create) figure to work in\n\t\tFinter = spm_input('!GetWin');\n\t\n\t\t%-Find out which Y-position to use, setup for use\n\t\tYPos = spm_input('!SetNextPos',YPos,Finter,CmdLine);\n\t\n\t\t%-Determine position of objects\n\t\t[FRec,QRec,PRec,RRec]=spm_input('!InputRects',YPos,'',Finter);\n\tend\nend\n\n\nswitch lower(Type)\ncase {'s','s+','e','n','w','i','r','c','x','p'} %-String and evaluated input\n%=======================================================================\n%-Condition arguments\nif nargin<6|isempty(varargin{6}), m=[]; else, m=varargin{6}; end\nif nargin<5|isempty(varargin{5}), n=[]; else, n=varargin{5}; end\nif nargin<4, DefStr=''; else, DefStr=varargin{4}; end\nif strcmp(lower(Type),'s+')\n\t%-DefStr should be a cellstr for 's+' type.\n\tif isempty(DefStr), DefStr = {};\n\t\telse, DefStr = cellstr(DefStr); end\n\tDefStr = DefStr(:);\nelse\n\t%-DefStr needs to be a string\n\tif ~ischar(DefStr), DefStr=num2str(DefStr); end\n\tDefStr = DefStr(:)';\nend\n\nstrM='';\nswitch lower(Type)\t\t\t%-Type specific defaults/setup\ncase 's', TTstr='enter string';\ncase 's+',TTstr='enter string - multi-line';\ncase 'e', TTstr='enter expression to evaluate';\ncase 'n', TTstr='enter expression - natural number(s)';\n\tif ~isempty(m), strM=sprintf(' (in [1,%d])',m); TTstr=[TTstr,strM]; end\ncase 'w', TTstr='enter expression - whole number(s)';\n\tif ~isempty(m), strM=sprintf(' (in [0,%d])',m); TTstr=[TTstr,strM]; end\ncase 'i', TTstr='enter expression - integer(s)';\ncase 'r', TTstr='enter expression - real number(s)';\n\tif ~isempty(m), TTstr=[TTstr,sprintf(' in [%g,%g]',min(m),max(m))]; end\ncase 'c', TTstr='enter indicator vector e.g. 0101... or abab...';\n\tif ~isempty(m) & isfinite(m), strM=sprintf(' (%d)',m); end\ncase 'x', TTstr='enter contrast matrix';\ncase 'p',\n\tif isempty(n), error('permutation of what?'), else, P=n(:)'; end\n\tif isempty(m), n = [1,length(P)]; end\n\tm = P;\n\tif ~length(setxor(m,[1:max(m)]))\n\t\tTTstr=['enter permutation of [1:',num2str(max(m)),']'];\n\telse\n\t\tTTstr=['enter permutation of [',num2str(m),']'];\n\tend\notherwise, TTstr='enter expression'; end\n\nstrN = sf_SzStr(n);\n\n\nif CmdLine %-Use CmdLine to get answer\n%-----------------------------------------------------------------------\n\tspm_input('!PrntPrmpt',[Prompt,strN,strM],TTstr)\n\n\t%-Do Eval Types in Base workspace, catch errors\n\tswitch lower(Type), case 's'\n\t\tif ~isempty(DefStr)\n\t\t\tPrompt=[Prompt,' (Default: ',DefStr,' )'];\n\t\tend\n\t\tstr = input([Prompt,' : '],'s');\n\t\tif isempty(str), str=DefStr; end\n\n\t\twhile isempty(str)\n\t\t\tspm('Beep')\n\t\t\tfprintf('! %s : enter something!\\n',mfilename)\n\t\t\tstr = input([Prompt,' : '],'s');\n\t\t\tif isempty(str), str=DefStr; end\n\t\tend\n\t\tp = str; msg = '';\n\n\tcase 's+'\n\t\tfprintf(['Multi-line input: Type ''.'' on a line',...\n\t\t\t' of its own to terminate input.\\n'])\n\t\tif ~isempty(DefStr)\n\t\t\tfprintf('Default : (press return to accept)\\n')\n\t\t\tfprintf(' : %s\\n',DefStr{:})\n\t\tend\n\t\tfprintf('\\n')\n\n\t\tstr = input('l001 : ','s');\n\t\twhile (isempty(str) | strcmp(str,'.')) & isempty(DefStr)\n\t\t\tspm('Beep')\n\t\t\tfprintf('! %s : enter something!\\n',mfilename)\n\t\t\tstr = input('l001 : ','s');\n\t\tend\n\n\t\tif isempty(str)\n\t\t\t%-Accept default\n\t\t\tp = DefStr;\n\t\telse\n\t\t\t%-Got some input, allow entry of additional lines\n\t\t\tp = {str};\n\t\t\tstr = input(sprintf('l%03u : ',length(p)+1),'s');\n\t\t\twhile ~strcmp(str,'.')\n\t\t\t\tp = [p;{str}];\n\t\t\t\tstr = input(sprintf('l%03u : ',length(p)+1),'s');\n\t\t\tend\n\t\tend\n\t\tmsg = '';\n\n\totherwise\n\t\tif ~isempty(DefStr)\n\t\t\tPrompt=[Prompt,' (Default: ',DefStr,' )'];\n\t\tend\n\t\tstr = input([Prompt,' : '],'s');\n\t\tif isempty(str), str=DefStr; end\n\t\t[p,msg] = sf_eEval(str,Type,n,m);\n\n\t\twhile ischar(p)\n\t\t\tspm('Beep'), fprintf('! %s : %s\\n',mfilename,msg)\n\t\t\tstr = input([Prompt,' : '],'s');\n\t\t\tif isempty(str), str=DefStr; end\n\t\t\t[p,msg] = sf_eEval(str,Type,n,m);\n\t\tend\n\tend\n\tif ~isempty(msg), fprintf('\\t%s\\n',msg), end\n\nelse %-Use GUI to get answer\n%-----------------------------------------------------------------------\n\n\t%-Create text and edit control objects\n\t%---------------------------------------------------------------\n\thPrmpt = uicontrol(Finter,'Style','Text',...\n\t\t'String',[strN,Prompt,strM],...\n\t\t'Tag',['GUIinput_',int2str(YPos)],...\n\t\t'UserData','',...\n 'BackgroundColor',COLOUR,...\n\t\t'HorizontalAlignment','Right',...\n\t\t'Position',PRec);\n\n\n\n\t%-Default button surrounding edit widget (if a DefStr given)\n\t%-Callback sets hPrmpt UserData, and EditWidget string, to DefStr\n\t% (Buttons UserData holds handles [hPrmpt,hEditWidget], set later)\n\tcb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',...\n\t\t\t'get(gcbo,''String'')),',...\n\t\t'set(get(gcbo,''UserData'')*[0;1],''String'',',...\n\t\t\t'get(gcbo,''String''))'];\n\tif ~isempty(DefStr)\n\t\tif iscellstr(DefStr), str=[DefStr{1},'...'];\n\t\t\telse, str=DefStr; end\n\t\thDef = uicontrol(Finter,'Style','PushButton',...\n\t\t\t'String',DefStr,...\n\t\t\t'ToolTipString',...\n\t\t\t\t['Click on border to accept default: ' str],...\n\t\t\t'Tag',['GUIinput_',int2str(YPos)],...\n\t\t\t'UserData',[],...\n 'BackgroundColor',COLOUR,...\n\t\t\t'CallBack',cb,...\n\t\t\t'Position',RRec+[-2,-2,+4,+4]);\n\telse\n\t\thDef = [];\n\tend\n\n\t%-Edit widget: Callback puts string into hPrompts UserData\n\tcb = 'set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))';\n\th = uicontrol(Finter,'Style','Edit',...\n\t\t'String',DefStr,...\n\t\t'Max',strcmp(lower(Type),'s+')+1,...\n\t\t'Tag',['GUIinput_',int2str(YPos)],...\n\t\t'UserData',hPrmpt,...\n\t\t'CallBack',cb,...\n\t\t'Horizontalalignment','Left',...\n\t\t'BackgroundColor','w',...\n\t\t'Position',RRec);\n\tset(hDef,'UserData',[hPrmpt,h])\n\tuifocus(h);\n\tif TTips, set(h,'ToolTipString',TTstr), end\n\n\t%-Figure ContextMenu for shortcuts\n\thM = spm_input('!InptConMen',Finter,[hPrmpt,hDef,h]);\n\tcb = [\t'set(get(gcbo,''UserData''),''String'',',...\n\t\t\t'[''spm_load('''''',spm_select(1),'''''')'']), ',...\n\t\t'set(get(get(gcbo,''UserData''),''UserData''),''UserData'',',...\n\t\t\t'get(get(gcbo,''UserData''),''String''))'];\n\tuimenu(hM,'Label','load from text file','Separator','on',...\n\t\t'CallBack',cb,'UserData',h)\n\n\t%-Bring window to fore & jump pointer to edit widget\n\t[PLoc,cF] = spm_input('!PointerJump',RRec,Finter);\n\n\t%-Setup FigureKeyPressFcn for editing of entry widget without clicking\n\tset(Finter,'KeyPressFcn',[...\n\t 'spm_input(''!EditableKeyPressFcn'',',...\n\t 'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',...\n\t \t'''Style'',''edit''),',...\n\t 'get(gcbf,''CurrentCharacter''))'])\n\n\n\t%-Wait for edit, do eval Types in Base workspace, catch errors\n\t%---------------------------------------------------------------\n\twaitfor(hPrmpt,'UserData')\n\tif ~ishandle(hPrmpt), error(['Input window cleared whilst waiting ',...\n\t\t'for response: Bailing out!']), end\n\tstr = get(hPrmpt,'UserData');\n\tswitch lower(Type), case 's'\n\t\tp = str; msg = '';\n\tcase 's+'\n\t\tp = cellstr(str); msg = '';\n\totherwise\n\t\t[p,msg] = sf_eEval(str,Type,n,m);\n\t\twhile ischar(p)\n\t\t\tset(h,'Style','Text',...\n\t\t\t\t'String',msg,'HorizontalAlignment','Center',...\n\t\t\t\t'ForegroundColor','r')\n\t\t\tspm('Beep'), pause(2)\n\t\t\tset(h,'Style','Edit',...\n\t\t\t\t'String',str,...\n\t\t\t\t'HorizontalAlignment','Left',...\n\t\t\t\t'ForegroundColor','k')\n\t\t\t%set(hPrmpt,'UserData','');\n\t\t\twaitfor(hPrmpt,'UserData')\n\t\t\tif ~ishandle(hPrmpt), error(['Input window cleared ',...\n\t\t\t\t'whilst waiting for response: Bailing out!']),end\n\t\t\tstr = get(hPrmpt,'UserData');\n\t\t\t[p,msg] = sf_eEval(str,Type,n,m);\n\t\tend\n\tend\n\n\t%-Fix edit window, clean up, reposition pointer, set CurrentFig back\n\tdelete([hM,hDef]), set(Finter,'KeyPressFcn','')\n\tset(h,'Style','Text','HorizontalAlignment','Center',...\n\t\t'ToolTipString',msg,...\n\t\t'BackgroundColor',COLOUR)\n\tspm_input('!PointerJumpBack',PLoc,cF)\n\tdrawnow\n\nend % (if CmdLine)\n\n%-Return response\n%-----------------------------------------------------------------------\nvarargout = {p,YPos};\n\n\ncase {'b','bd','b|','y/n','be1','bn1','bw1','bi1','br1',...\n\t'-n1','n1','-w1','w1','m'} %-'b'utton & 'm'enu Types\n%=======================================================================\n%-Condition arguments\nswitch lower(Type), case {'b','be1','bi1','br1','m'}\n\tm = []; Title = '';\n\tif nargin<6, DefItem=[]; else, DefItem=varargin{6}; end\n\tif nargin<5, Values=[]; else, Values =varargin{5}; end\n\tif nargin<4, Labels=''; else, Labels =varargin{4}; end\ncase 'bd'\n\tif nargin<7, Title=''; else, Title =varargin{7}; end\n\tif nargin<6, DefItem=[]; else, DefItem=varargin{6}; end\n\tif nargin<5, Values=[]; else, Values =varargin{5}; end\n\tif nargin<4, Labels=''; else, Labels =varargin{4}; end\ncase 'y/n'\n\tTitle = '';\n\tif nargin<5, DefItem=[]; else, DefItem=varargin{5}; end\n\tif nargin<4, Values=[]; else, Values =varargin{4}; end\n\tif isempty(Values), Values='yn'; end\n\tLabels = {'yes','no'};\ncase 'b|'\n\tTitle = '';\n\tif nargin<5, DefItem=[]; else, DefItem=varargin{5}; end\n\tif nargin<4, Values=[]; else, Values =varargin{4}; end\n\tLabels = varargin{3};\ncase 'bn1'\n\tif nargin<7, m=[]; else, m=varargin{7}; end\n\tif nargin<6, DefItem=[]; else, DefItem=varargin{6}; end\n\tif nargin<5, Values=[]; else, Values =varargin{5}; end\n\tif nargin<4, Labels=[1:5]'; Values=[1:5]; Type='-n1';\n\t\telse, Labels=varargin{4}; end\ncase 'bw1'\n\tif nargin<7, m=[]; else, m=varargin{7}; end\n\tif nargin<6, DefItem=[]; else, DefItem=varargin{6}; end\n\tif nargin<5, Values=[]; else, Values =varargin{5}; end\n\tif nargin<4, Labels=[0:4]'; Values=[0:4]; Type='-w1';\n\t\telse, Labels=varargin{4}; end\ncase {'-n1','n1','-w1','w1'}\n\tif nargin<5, m=[]; else, m=varargin{5}; end\n\tif nargin<4, DefItem=[]; else, DefItem=varargin{4}; end\n\tswitch lower(Type)\n\tcase {'n1','-n1'}, Labels=[1:min([5,m])]'; Values=Labels'; Type='-n1';\n\tcase {'w1','-w1'}, Labels=[0:min([4,m])]'; Values=Labels'; Type='-w1';\n\tend\nend\n\n\n%-Check some labels were specified\nif isempty(Labels), error('No Labels specified'), end\n\nif iscellstr(Labels), Labels=char(Labels); end\n\n%-Convert Labels \"option\" string to string matrix if required\nif ischar(Labels) & any(Labels=='|')\n\tOptStr=Labels;\n\tBarPos=find([OptStr=='|',1]);\n\tLabels=OptStr(1:BarPos(1)-1);\n\tfor Bar = 2:sum(OptStr=='|')+1\n\t\tLabels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1));\n\tend\nend\n\n\n%-Set default Values for the Labels\nif isempty(Values)\n\tif strcmp(lower(Type),'m')\n\t\tValues=[1:size(Labels,1)]';\n\telse\n\t\tValues=Labels;\n\tend\nelse\n\t%-Make sure Values are in rows\n\tif size(Labels,1)>1 & size(Values,1)==1, Values = Values'; end\n\t%-Check numbers of Labels and Values match\n\tif (size(Labels,1)~=size(Values,1))\n\t\terror('Labels & Values incompatible sizes'), end\nend\n\n\n%-Numeric Labels to strings\nif isnumeric(Labels)\n\ttmp = Labels; Labels = cell(size(tmp,1),1);\n\tfor i=1:prod(size(tmp)), Labels{i}=num2str(tmp(i,:)); end\n\tLabels=char(Labels);\nend\n\n\nswitch lower(Type), case {'b','bd','b|','y/n'} %-Process button types\n%=======================================================================\n\t\n\t%-Make unique character keys for the Labels, sort DefItem\n\t%---------------------------------------------------------------\n\tnLabels = size(Labels,1);\n\t[Keys,Labs] = sf_labkeys(Labels);\n\n\tif ~isempty(DefItem) & any(DefItem==[1:nLabels])\n\t\tDefKey = Keys(DefItem);\n\telse\n\t\tDefItem = 0;\n\t\tDefKey = '';\n\tend\n\n\tif CmdLine\n\t\t%-Display question prompt\n\t\tspm_input('!PrntPrmpt',Prompt,'',Title)\n\t\t%-Build prompt\n\t\t%-------------------------------------------------------\n\t\tif ~isempty(Labs) \n\t\t Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' '];\n\t\t for i = 2:nLabels\n\t\t Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' '];\n\t\t end\n\t\telse\n\t\t Prmpt = ['[',Keys(1),'] '];\n\t\t for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end\n\t\tend\n\t\tif DefItem\n\t\t Prmpt = [Prmpt,...\n\t\t \t' (Default: ',deblank(Labels(DefItem,:)),')'];\n\t\tend\n\n\t\t%-Ask for user response\n\t\t%-------------------------------------------------------\n\t\tif nLabels==1\n\t\t\t%-Only one choice - auto-pick & display\n\t\t\tk = 1; fprintf('%s: %s\\t(only option)',Prmpt,Labels)\n\t\telse\n\t\t\tstr = input([Prmpt,'? '],'s');\n\t\t\tif isempty(str), str=DefKey; end\n\t\t\twhile isempty(str) | ~any(lower(Keys)==lower(str(1)))\n\t\t\t if ~isempty(str),fprintf('%c\\t!Out of range\\n',7),end\n\t\t\t str = input([Prmpt,'? '],'s');\n\t\t\t if isempty(str), str=DefKey; end\n\t\t\tend\n\t\t\tk = find(lower(Keys)==lower(str(1)));\n\t\tend\n\t\tfprintf('\\n')\n\n\t\tp = Values(k,:); if ischar(p), p=deblank(p); end\n\n\telseif strcmp(lower(Type),'bd')\n\n\t\tif nLabels>3, error('at most 3 labels for GUI ''db'' type'), end\n\n\t\ttmp = cellstr(Labels);\n\t\tif DefItem\n\t\t\ttmp = [tmp; tmp(DefItem)];\n\t\t\tPrompt = cellstr(Prompt); Prompt=Prompt(:);\n\t\t\tPrompt = [Prompt;{' '};...\n\t\t\t\t\t{['[default: ',tmp{DefItem},']']}];\n\t\telse\n\t\t\ttmp = [tmp; tmp(1)];\n\t\tend\n\n\t\tk = min(find(strcmp(tmp,...\n\t\t\tquestdlg(Prompt,sprintf('%s%s: %s...',spm('ver'),...\n\t\t\t\tspm('GetUser',' (%s)'),Title),tmp{:}))));\n\n\t\tp = Values(k,:); if ischar(p), p=deblank(p); end\n\n\telse\n\n\t\tTag = ['GUIinput_',int2str(YPos)];\t%-Tag for widgets\n\n\t\t%-Create text and edit control objects\n\t\t%-'UserData' of prompt contains answer\n\t\t%-------------------------------------------------------\n\t\thPrmpt = uicontrol(Finter,'Style','Text',...\n\t\t\t'String',Prompt,...\n\t\t\t'Tag',Tag,...\n\t\t\t'UserData',[],...\n 'BackgroundColor',COLOUR,...\n\t\t\t'HorizontalAlignment','Right',...\n\t\t\t'Position',PRec);\n\t\n\t\tif nLabels==1\n\t\t\t%-Only one choice - auto-pick\n\t\t\tk = 1;\n\t\telse\n\t\t\t%-Draw buttons and process response\n\t\t\tdX = RRec(3)/nLabels;\n\t\t\t\n\t\t\tif TTips, str = ['select with mouse or use kbd: ',...\n\t\t\t\tsprintf('%c/',Keys(1:end-1)),Keys(end)];\n\t\t\telse, str=''; end\n\t\t\n\t\t\t%-Store button # in buttons 'UserData' property\n\t\t\t%-Store handle of prompt string in buttons 'Max' property\n\t\t\t%-Button callback sets UserData of prompt string to\n\t\t\t% number of pressed button\n\t\t\tcb = ['set(get(gcbo,''Max''),''UserData'',',...\n\t\t\t\t'get(gcbo,''UserData''))'];\n\t\t\tH = [];\n\t\t\tXDisp = [];\n\t\t\tfor i=1:nLabels\n\t\t\t\tif i==DefItem\n\t\t\t\t\t%-Default button, outline it\n\t\t\t\t\th = uicontrol(Finter,'Style','Frame',...\n\t\t\t\t\t\t'BackGroundColor','k',...\n\t\t\t\t\t\t'ForeGroundColor','k',...\n\t\t\t\t\t\t'Tag',Tag,...\n\t\t\t\t\t\t'Position',...\n\t\t\t\t\t\t[RRec(1)+(i-1)*dX ...\n\t\t\t\t\t\t\tRRec(2)-1 dX RRec(4)+2]);\n\t\t\t\t\tXDisp = (i-1/3)*dX;\n\t\t\t\t\tH = [H,h];\n\t\t\t\tend\n\t\t\t\th = uicontrol(Finter,'Style','Pushbutton',...\n\t\t\t\t\t'String',deblank(Labels(i,:)),...\n\t\t\t\t\t'ToolTipString',str,...\n\t\t\t\t\t'Tag',Tag,...\n\t\t\t\t\t'Max',hPrmpt,...\n\t\t\t\t\t'UserData',i,...\n\t\t\t\t\t'BackgroundColor',COLOUR,...\n\t\t\t\t\t'Callback',cb,...\n\t\t\t\t\t'Position',[RRec(1)+(i-1)*dX+1 ...\n\t\t\t\t\t\t\tRRec(2) dX-2 RRec(4)]);\n\t\t\t\tif i == DefItem,\n\t\t\t\t\tuifocus(h);\n\t\t\t\tend\n\t\t\t\tH = [H,h];\n\t\t\tend\n\t\t\n\t\t\t%-Figure ContextMenu for shortcuts\n\t\t\thM = spm_input('!InptConMen',Finter,[hPrmpt,H]);\n\n\t\t\t%-Bring window to fore & jump pointer to default button\n\t\t\t[PLoc,cF]=spm_input('!PointerJump',RRec,Finter,XDisp);\n\t\n\t\t\t%-Callback for KeyPress, to store valid button # in\n\t\t\t% UserData of Prompt, DefItem if (DefItem~=0)\n\t\t\t% & return (ASCII-13) is pressed\n\t\t\tset(Finter,'KeyPressFcn',...\n\t\t\t\t['spm_input(''!ButtonKeyPressFcn'',',...\n\t\t\t\t'findobj(gcf,''Tag'',''',Tag,''',',...\n\t\t\t\t\t'''Style'',''text''),',...\n\t\t\t\t'''',lower(Keys),''',',num2str(DefItem),',',...\n\t\t\t\t'get(gcbf,''CurrentCharacter''))'])\n\n\t\t\t%-Wait for button press, process results\n\t\t\t%-----------------------------------------------\n\t\t\twaitfor(hPrmpt,'UserData')\n\t\t\tif ~ishandle(hPrmpt)\n\t\t\t\terror(['Input objects cleared whilst ',...\n\t\t\t\t'waiting for response: Bailing out!'])\n\t\t\tend\n\t\t\tk = get(hPrmpt,'UserData');\n\t\t\t%-Clean up\n\t\t\tdelete([H,hM]),\tset(Finter,'KeyPressFcn','')\n\t\t\tspm_input('!PointerJumpBack',PLoc,cF)\n\t\tend\n\t\t\n\t\t%-Display answer\n\t\tuicontrol(Finter,'Style','Text',...\n\t\t\t'String',deblank(Labels(k,:)),...\n\t\t\t'Tag',Tag,...\n\t\t\t'Horizontalalignment','Center',...\n\t\t\t'BackgroundColor',COLOUR,...\n\t\t\t'Position',RRec);\n\t\tdrawnow\n\n\t\tp = Values(k,:); if ischar(p), p=deblank(p); end\n\n\tend\n\n\ncase {'be1','bn1','bw1','bi1','br1','-n1','-w1'}\n %-Process button/entry combo types\n%=======================================================================\nif ischar(DefItem), DefStr=DefItem; else, DefStr=num2str(DefItem); end\nif isempty(m), strM=''; else, strM=sprintf(' (<=%d)',m); end\n\nif CmdLine\n\n\t%-Process default item\n\t%---------------------------------------------------------------\n\tif ~isempty(DefItem)\n\t\t[DefVal,msg] = sf_eEval(DefStr,Type(2),1);\n\t\tif ischar(DefVal), error(['Invalid DefItem: ',msg]), end\n\t\tLabels = strvcat(Labels,DefStr);\n\t\tValues = [Values;DefVal];\n\t\tDefItem = size(Labels,1);\n\tend\n\n\t%-Add option to specify...\n\tLabels = strvcat(Labels,'specify...');\n\n\t%-Process options\n\tnLabels = size(Labels,1);\n\t[Keys,Labs] = sf_labkeys(Labels);\n\n\tif ~isempty(DefItem), DefKey = Keys(DefItem); else, DefKey = ''; end\n\n\t%-Print banner prompt\n\t%---------------------------------------------------------------\n\tspm_input('!PrntPrmpt',Prompt)\t\t%-Display question prompt\n\n\n\tif Type(1)=='-'\t\t%-No special buttons - go straight to input\n\n\t\tk = size(Labels,1);\n\n\telse\t\t\t%-Offer buttons, default or \"specify...\"\n\t\n\t\t%-Build prompt\n\t\t%-------------------------------------------------------\n\t\tif ~isempty(Labs) \n\t\t Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' '];\n\t\t for i = 2:nLabels\n\t\t Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' '];\n\t\t end\n\t\telse\n\t\t Prmpt = ['[',Keys(1),'] '];\n\t\t for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end\n\t\tend\n\t\tif DefItem, Prmpt = [Prmpt,...\n\t\t\t' (Default: ',deblank(Labels(DefItem,:)),')']; end\n\t\n\t\t%-Ask for user response\n\t\t%-------------------------------------------------------\n\t\tif nLabels==1\n\t\t\t%-Only one choice - auto-pick & display\n\t\t\tk = 1; fprintf('%s: %s\\t(only option)',Prmpt,Labels)\n\t\telse\n\t\t\tstr = input([Prmpt,'? '],'s');\n\t\t\tif isempty(str), str=DefKey; end\n\t\t\twhile isempty(str) | ~any(lower(Keys)==lower(str(1)))\n\t\t\t if ~isempty(str),fprintf('%c\\t!Invalid response\\n',7),end\n\t\t\t str = input([Prmpt,'? '],'s');\n\t\t\t if isempty(str), str=DefKey; end\n\t\t\tend\n\t\t\tk = find(lower(Keys)==lower(str(1)));\n\t\tend\n\t\tfprintf('\\n')\n\n\tend\n\n\n\t%-Process response: prompt for value if \"specify...\" option chosen\n\t%===============================================================\n\tif k1),',...\n\t\t\t\t'set(gcbo,''UserData'',''Selected''), end'];\n\t\t\thPopUp = uicontrol(Finter,'Style','PopUp',...\n\t\t\t\t'HorizontalAlignment','Left',...\n\t\t\t\t'ForegroundColor','k',...\n\t\t\t\t'BackgroundColor',COLOUR,...\n\t\t\t\t'String',strvcat([Prompt,'...'],Labs),...\n\t\t\t\t'Tag',Tag,...\n\t\t\t\t'UserData',DefItem,...\n\t\t\t\t'CallBack',cb,...\n\t\t\t\t'Position',QRec);\n\t\t\tif TTips, set(hPopUp,'ToolTipString',['select with ',...\n\t\t\t\t'mouse or type option number (1-',...\n\t\t\t\tnum2str(nLabels),') & press return']), end\n\t\n\t\t\t%-Figure ContextMenu for shortcuts\n\t\t\thM = spm_input('!InptConMen',Finter,[hPopUp,H]);\n\n\t\t\t%-Bring window to fore & jump pointer to menu widget\n\t\t\t[PLoc,cF] = spm_input('!PointerJump',RRec,Finter);\n\t\n\t\t\t%-Callback for KeyPresses\n\t\t\tcb=['spm_input(''!PullDownKeyPressFcn'',',...\n\t\t\t\t'findobj(gcf,''Tag'',''',Tag,'''),',...\n\t\t\t\t'get(gcf,''CurrentCharacter''))'];\n\t\t\tset(Finter,'KeyPressFcn',cb)\n\n\t\t\t%-Wait for menu selection\n\t\t\t%-----------------------------------------------\n\t\t\twaitfor(hPopUp,'UserData')\n\t\t\tif ~ishandle(hPopUp), error(['Input object cleared ',...\n\t\t\t\t'whilst waiting for response: Bailing out!']),end\n\t\t\tk = get(hPopUp,'Value')-1;\n\n\t\t\t%-Clean up\n\t\t\tdelete([H,hM]), set(Finter,'KeyPressFcn','')\n\t\t\tset(hPopUp,'Style','Text',...\n\t\t\t\t'Horizontalalignment','Center',...\n\t\t\t\t'String',deblank(Labels(k,:)),...\n\t\t\t\t'BackgroundColor',COLOUR)\n\t\t\tspm_input('!PointerJumpBack',PLoc,cF)\n\t\tend\n\t\n\t\t%-Display answer\n\t\tuicontrol(Finter,'Style','Text',...\n\t\t\t'String',deblank(Labels(k,:)),...\n\t\t\t'Tag',Tag,...\n\t\t\t'Horizontalalignment','Center',...\n\t\t\t'BackgroundColor',COLOUR,...\n\t\t\t'Position',QRec);\n\t\tdrawnow\n\tend\n\n\tp = Values(k,:); if ischar(p), p=deblank(p); end\n\notherwise, error('unrecognised type')\nend % (switch lower(Type) within case {'b','b|','y/n'})\n\n\n%-Log the transaction & return response\n%-----------------------------------------------------------------------\nif exist('spm_log')==2\n\tif iscellstr(Prompt), Prompt=Prompt{1}; end\n\tspm_log([mfilename,' : ',Prompt,': (',deblank(Labels(k,:)),')'],p); end\nvarargout = {p,YPos};\n\n\n\ncase {'m!','b!'} %-GUI PullDown/Buttons utility\n%=======================================================================\n% H = spm_input(Prompt,YPos,'p',Labels,cb,UD,XCB)\n%-Condition arguments\nif nargin<7, XCB = 0; else, XCB = varargin{7}; end\nif nargin<6, UD = []; else, UD = varargin{6}; end\nif nargin<5, cb = ''; else, cb = varargin{5}; end\nif nargin<4, Labels = []; else, Labels = varargin{4}; end\n\nif CmdLine, error('Can''t do CmdLine GUI utilities!'), end\nif isempty(cb), cb = 'disp(''(CallBack not set)'')'; end\nif ischar(cb), cb = cellstr(cb); end\nif length(cb)>1 & strcmp(lower(Type),'m!'), XCB=1; end\n\nif iscellstr(Labels), Labels=char(Labels); end\n%-Convert Labels \"option\" string to string matrix if required\nif any(Labels=='|')\n\tOptStr=Labels;\n\tBarPos=find([OptStr=='|',1]);\n\tLabels=OptStr(1:BarPos(1)-1);\n\tfor Bar = 2:sum(OptStr=='|')+1\n\t\tLabels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1));\n\tend\nend\n\n%-Check #CallBacks\nif ~( length(cb)==1 | (length(cb)==size(Labels,1)) )\n\terror('Labels & Callbacks size mismatch'), end\n\n\n%-Draw Prompt\n%-----------------------------------------------------------------------\nTag = ['GUIinput_',int2str(YPos)];\t\t\t%-Tag for widgets\n\nif ~isempty(Prompt)\n\tuicontrol(Finter,'Style','Text',...\n\t\t'String',Prompt,...\n\t\t'Tag',Tag,...\n\t\t'HorizontalAlignment','Right',...\n 'BackgroundColor',COLOUR,...\n\t\t'Position',PRec)\n\tRec = RRec;\nelse\n\tRec = QRec;\nend\n\n\n%-Sort out UserData for extended callbacks (handled by spm_input('!m_cb')\n%-----------------------------------------------------------------------\nif XCB, if iscell(UD), UD={UD}; end, UD = struct('UD',UD,'cb',{cb}); end\n\n\n%-Draw PullDown or Buttons\n%-----------------------------------------------------------------------\nswitch lower(Type), case 'm!'\n\tif XCB, UD.cb=cb; cb = {'spm_input(''!m_cb'')'}; end\n\tH = uicontrol(Finter,'Style','PopUp',...\n\t\t'HorizontalAlignment','Left',...\n\t\t'ForegroundColor','k',...\n\t\t'BackgroundColor',COLOUR,...\n\t\t'String',Labels,...\n\t\t'Tag',Tag,...\n\t\t'UserData',UD,...\n\t\t'CallBack',char(cb),...\n\t\t'Position',Rec);\n\ncase 'b!'\n\tnLabels = size(Labels,1);\n\tdX = Rec(3)/nLabels;\n\n\tH = [];\n\tfor i=1:nLabels\n\t\tif length(cb)>1, tcb=cb(i); else, tcb=cb; end\n\t\tif XCB, UD.cb=tcb; tcb = {'spm_input(''!m_cb'')'}; end\n\t\th = uicontrol(Finter,'Style','Pushbutton',...\n\t\t\t'String',deblank(Labels(i,:)),...\n\t\t\t'ToolTipString','',...\n\t\t\t'Tag',Tag,...\n\t\t\t'UserData',UD,...\n\t\t\t'BackgroundColor',COLOUR,...\n\t\t\t'Callback',char(tcb),...\n\t\t\t'Position',[Rec(1)+(i-1)*dX+1 ...\n\t\t\t\t\tRec(2) dX-2 Rec(4)]);\n\t\tH = [H,h];\n\tend\n\n\nend\n\n\n%-Bring window to fore & jump pointer to menu widget\n[PLoc,cF] = spm_input('!PointerJump',RRec,Finter);\n\nvarargout = {H};\n\n\n\ncase {'d','d!'} %-Display message\n%=======================================================================\n%-Condition arguments\nif nargin<4, Label=''; else, Label=varargin{4}; end\n\nif CmdLine & strcmp(lower(Type),'d')\n\tfprintf('\\n +-%s%s+',Label,repmat('-',1,57-length(Label)))\n\tPrompt = [Prompt,' '];\n\twhile length(Prompt)>0\n\t\ttmp = length(Prompt);\n\t\tif tmp>56, tmp=min([max(find(Prompt(1:56)==' ')),56]); end\n\t\tfprintf('\\n | %s%s |',Prompt(1:tmp),repmat(' ',1,56-tmp))\n\t\tPrompt(1:tmp)=[];\n\tend\n\tfprintf('\\n +-%s+\\n',repmat('-',1,57))\nelseif ~CmdLine\n\tif ~isempty(Label), Prompt = [Label,': ',Prompt]; end\n\tfigure(Finter)\n\t%-Create text axes and edit control objects\n\t%---------------------------------------------------------------\n\th = uicontrol(Finter,'Style','Text',...\n\t\t'String',Prompt(1:min(length(Prompt),56)),...\n\t\t'FontWeight','bold',...\n\t\t'Tag',['GUIinput_',int2str(YPos)],...\n\t\t'HorizontalAlignment','Left',...\n\t\t'ForegroundColor','k',...\n 'BackgroundColor',COLOUR,...\n\t\t'UserData',Prompt,...\n\t\t'Position',QRec);\n\tif length(Prompt)>56\n\t\tpause(1)\n\t\tset(h,'ToolTipString',Prompt)\n\t\tspm_input('!dScroll',h)\n\t\tuicontrol(Finter,'Style','PushButton','String','>',...\n\t\t\t'ToolTipString','press to scroll message',...\n\t\t\t'Tag',['GUIinput_',int2str(YPos)],...\n\t\t\t'UserData',h,...\n\t\t\t'CallBack',[...\n\t\t\t 'set(gcbo,''Visible'',''off''),',...\n\t\t\t 'spm_input(''!dScroll'',get(gcbo,''UserData'')),',...\n\t\t\t 'set(gcbo,''Visible'',''on'')'],...\n 'BackgroundColor',COLOUR,...\n\t\t\t'Position',[QRec(1)+QRec(3)-10,QRec(2),15,QRec(4)]);\n\tend\nend\nif nargout>0, varargout={[],YPos}; end\n\n\n\n%=======================================================================\n% U T I L I T Y F U N C T I O N S \n%=======================================================================\n\ncase '!colour'\n%=======================================================================\n% colour = spm_input('!Colour')\nvarargout = {COLOUR};\n\n\ncase '!icond'\n%=======================================================================\n% [iCond,msg] = spm_input('!iCond',str,n,m)\n% Parse condition indicator spec strings:\n%\t'2 3 2 3', '0 1 0 1', '2323', '0101', 'abab', 'R A R A'\nif nargin<4, m=Inf; else, m=varargin{4}; end\nif nargin<3, n=NaN; else, n=varargin{3}; end\nif any(isnan(n(:)))\n\tn=Inf;\nelseif (length(n(:))==2 & ~any(n==1)) | length(n(:))>2\n\terror('condition input can only do vectors')\nend\nif nargin<2, i=''; else, i=varargin{2}; end\nif isempty(i), varargout={[],'empty input'}; return, end\nmsg = ''; i=i(:)';\n\nif ischar(i)\n\tif i(1)=='0' & all(ismember(unique(i(:)),setstr(abs('0'):abs('9'))))\n\t\t%-Leading zeros in a digit list\n\t\tmsg = sprintf('%s expanded',i);\n\t\tz = min(find([diff(i=='0'),1]));\n\t\ti = [zeros(1,z), spm_input('!iCond',i(z+1:end))'];\n\telse\n\t\t%-Try an eval, for functions & string #s\n\t\ti = evalin('base',['[',i,']'],'i');\n\tend\nend\n\nif ischar(i)\n\t%-Evaluation error from above: see if it's an 'abab' or 'a b a b' type:\n\t[c,null,i] = unique(lower(i(~isspace(i))));\n\tif all(ismember(c,setstr(abs('a'):abs('z'))))\n\t\t%-Map characters a-z to 1-26, but let 'r' be zero (rest)\n\t\ttmp = c-'a'+1; tmp(tmp=='r'-'a'+1)=0;\n\t\ti = tmp(i);\n\t\tmsg = [sprintf('[%s] mapped to [',c),...\n\t\t\tsprintf('%d,',tmp(1:end-1)),...\n\t\t\tsprintf('%d',tmp(end)),']'];\n\telse\n\t\ti = '!'; msg = 'evaluation error';\n\tend\nelseif ~all(floor(i(:))==i(:))\n\ti = '!'; msg = 'must be integers';\nelseif length(i)==1 & prod(n)>1\n\tmsg = sprintf('%d expanded',i);\n\ti = floor(i./10.^[floor(log10(i)+eps):-1:0]);\n\ti = i-[0,10*i(1:end-1)];\nend\n\n%-Check size of i & #conditions\nif ~ischar(i), [i,msg] = sf_SzChk(i,n,msg); end\nif ~ischar(i) & isfinite(m) & length(unique(i))~=m\n\ti = '!'; msg = sprintf('%d conditions required',m);\nend\n\nvarargout = {i,msg};\n\n\ncase '!inptconmen'\n%=======================================================================\n% hM = spm_input('!InptConMen',Finter,H)\nif nargin<3, H=[]; else, H=varargin{3}; end\nif nargin<2, varargout={[]}; else, Finter=varargin{2}; end\nhM = uicontextmenu('Parent',Finter);\nuimenu(hM,'Label','help on spm_input',...\n\t'CallBack','spm_help(''spm_input.m'')')\nif ConCrash\n\tuimenu(hM,'Label','crash out','Separator','on',...\n\t\t'CallBack','delete(get(gcbo,''UserData''))',...\n\t\t'UserData',[hM,H])\nend\n\nset(Finter,'UIContextMenu',hM)\n\nvarargout={hM};\n\n\ncase '!cmdline'\n%=======================================================================\n% [CmdLine,YPos] = spm_input('!CmdLine',YPos)\n%-Sorts out whether to use CmdLine or not & canonicalises YPos\nif nargin<2, YPos=''; else, YPos=varargin{2}; end\nif isempty(YPos), YPos='+1'; end\n\nCmdLine = [];\n\n%-Special YPos specifications\nif ischar(YPos)\n\tif(YPos(1)=='!'), CmdLine=0; YPos(1)=[]; end\nelseif YPos==0\n\tCmdLine=1;\nelseif YPos<0\n\tCmdLine=0;\n\tYPos=-YPos;\nend\n\nCmdLine = spm('CmdLine',CmdLine);\nif CmdLine, YPos=0; end\n\nvarargout = {CmdLine,YPos};\n\n\ncase '!getwin'\n%=======================================================================\n% Finter = spm_input('!GetWin',F)\n%-Locate (or create) figure to work in (Don't use 'Tag'ged figs)\nif nargin<2, F='Interactive'; else, F=varargin{2}; end\nFinter = spm_figure('FindWin',F);\nif isempty(Finter)\n\tif any(get(0,'Children'))\n\t\tif isempty(get(gcf,'Tag')), Finter = gcf;\n\t\telse, Finter = spm('CreateIntWin'); end\n\telse, Finter = spm('CreateIntWin'); end\nend\nvarargout = {Finter};\n\n\ncase '!pointerjump'\n%=======================================================================\n% [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp)\n%-Raise window & jump pointer over question\nif nargin<4, XDisp=[]; else, XDisp=varargin{4}; end\nif nargin<3, F='Interactive'; else, F=varargin{3}; end\nif nargin<2, error('Insufficient arguments'), else, RRec=varargin{2}; end\nF = spm_figure('FindWin',F);\nPLoc = get(0,'PointerLocation');\ncF = get(0,'CurrentFigure');\nif ~isempty(F)\n\tfigure(F)\n\tFRec = get(F,'Position');\n\tif isempty(XDisp), XDisp=RRec(3)*4/5; end\n\tif PJump, set(0,'PointerLocation',...\n\t\tfloor([(FRec(1)+RRec(1)+XDisp), (FRec(2)+RRec(2)+RRec(4)/3)]));\n\tend\nend\nvarargout = {PLoc,cF};\n\n\ncase '!pointerjumpback'\n%=======================================================================\n% spm_input('!PointerJumpBack',PLoc,cF)\n%-Replace pointer and reset CurrentFigure back\nif nargin<4, cF=[]; else, F=varargin{3}; end\nif nargin<2, error('Insufficient arguments'), else, PLoc=varargin{2}; end\nif PJump, set(0,'PointerLocation',PLoc), end\ncF = spm_figure('FindWin',cF);\nif ~isempty(cF), set(0,'CurrentFigure',cF); end\n\n\ncase '!prntprmpt'\n%=======================================================================\n% spm_input('!PrntPrmpt',Prompt,TipStr,Title)\n%-Print prompt for CmdLine questioning\nif nargin<4, Title = ''; else, Title = varargin{4}; end\nif nargin<3, TipStr = ''; else, TipStr = varargin{3}; end\nif nargin<2, Prompt = ''; else, Prompt = varargin{2}; end\nif isempty(Prompt), Prompt='Enter an expression'; end\n\nPrompt = cellstr(Prompt);\n\nif ~isempty(TipStr)\n tmp = 8 + length(Prompt{end}) + length(TipStr);\n if tmp < 62\n TipStr = sprintf('%s(%s)',repmat(' ',1,70-tmp),TipStr);\n else\n TipStr = sprintf('\\n%s(%s)',repmat(' ',1,max(0,70-length(TipStr))),TipStr);\n end\nend\n\nif isempty(Title)\n\tfprintf('\\n%s\\n',repmat('~',1,72))\nelse\n\tfprintf('\\n= %s %s\\n',Title,repmat('~',1,72-length(Title)-3))\nend\nfprintf('\\t%s',Prompt{1})\nfor i=2:prod(size(Prompt)), fprintf('\\n\\t%s',Prompt{i}), end\nfprintf('%s\\n%s\\n',TipStr,repmat('~',1,72))\n\n\ncase '!inputrects'\n%=======================================================================\n% [Frec,QRec,PRec,RRec,Sz,Se] = spm_input('!InputRects',YPos,rec,F)\nif nargin<4, F='Interactive'; else, F=varargin{4}; end\nif nargin<3, rec=''; else, rec=varargin{3}; end\nif nargin<2, YPos=1; else, YPos=varargin{2}; end\nF = spm_figure('FindWin',F);\nif isempty(F), error('Figure not found'), end\n\nUnits = get(F,'Units');\nset(F,'Units','pixels')\nFRec = get(F,'Position');\nset(F,'Units',Units);\nXdim = FRec(3); Ydim = FRec(4);\n\nWS = spm('WinScale');\nSz = round(22*min(WS));\t%-Height\nPd = Sz/2;\t\t\t%-Pad\nSe = 2*round(25*min(WS)/2);\t%-Seperation\nYo = round(2*min(WS));\t%-Y offset for responses\n\na = 5.5/10;\ny = Ydim - Se*YPos;\nQRec = [Pd y Xdim-2*Pd Sz]; %-Question\nPRec = [Pd y floor(a*Xdim)-2*Pd Sz]; %-Prompt\nRRec = [ceil(a*Xdim) y+Yo floor((1-a)*Xdim)-Pd Sz]; %-Response\n% MRec = [010 y Xdim-50 Sz]; %-Menu PullDown\n% BRec = MRec + [Xdim-50+1, 0+1, 50-Xdim+30, 0]; %-Menu PullDown OK butt\n\nif ~isempty(rec)\n\tvarargout = {eval(rec)};\nelse\n\tvarargout = {FRec,QRec,PRec,RRec,Sz,Se};\nend\n\n\ncase '!deleteinputobj'\n%=======================================================================\n% spm_input('!DeleteInputObj',F)\nif nargin<2, F='Interactive'; else, F=varargin{2}; end\nh = spm_input('!FindInputObj',F);\ndelete(h(h>0))\n\n\ncase {'!currentpos','!findinputobj'}\n%=======================================================================\n% [CPos,hCPos] = spm_input('!CurrentPos',F)\n% h = spm_input('!FindInputObj',F)\n% hPos contains handles: Columns contain handles corresponding to Pos\nif nargin<2, F='Interactive'; else, F=varargin{2}; end\nF = spm_figure('FindWin',F);\n\n%-Find tags and YPos positions of 'GUIinput_' 'Tag'ged objects\nH = [];\nYPos = [];\nfor h = get(F,'Children')'\n\ttmp = get(h,'Tag');\n\tif ~isempty(tmp)\n\t\tif strcmp(tmp(1:min(length(tmp),9)),'GUIinput_')\n\t\t\tH = [H, h];\n\t\t\tYPos = [YPos, eval(tmp(10:end))];\n\t\tend\n\tend\nend\n\nswitch lower(Type), case '!findinputobj'\n\tvarargout = {H};\ncase '!currentpos'\n\tif nargout<2\n\t\tvarargout = {max(YPos),[]};\n\telseif isempty(H)\n\t\tvarargout = {[],[]};\n\telse\n\t\t%-Sort out \n\t\ttmp = sort(YPos);\n\t\tCPos = tmp(find([1,diff(tmp)]));\n\t\tnPos = length(CPos);\n\t\tnPerPos = diff(find([1,diff(tmp),1]));\n\t\thCPos = zeros(max(nPerPos),nPos);\n\t\tfor i = 1:nPos\n\t\t\thCPos(1:nPerPos(i),i) = H(YPos==CPos(i))';\n\t\tend\n\t\tvarargout = {CPos,hCPos};\n\tend\nend\n\ncase '!nextpos'\n%=======================================================================\n% [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine)\n%-Return next position to use\nif nargin<3, F='Interactive'; else, F=varargin{3}; end\nif nargin<2, YPos='+1'; else, YPos=varargin{2}; end\nif nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos);\n\telse, CmdLine=varargin{4}; end\n\nF = spm_figure('FindWin',F);\n\n%-Get current positions\nif nargout<3\n\tCPos = spm_input('!CurrentPos',F);\n\thCPos = [];\nelse\n\t[CPos,hCPos] = spm_input('!CurrentPos',F);\nend\n\nif CmdLine\n\tNPos = 0;\nelse\n\tMPos = spm_input('!MaxPos',F);\n\tif ischar(YPos)\n\t\t%-Relative YPos\n\t\t%-Strip any '!' prefix from YPos\n\t\tif(YPos(1)=='!'), YPos(1)=[]; end\n\t\tif strncmp(YPos,'_',1)\n\t\t\t%-YPos='_' means bottom\n\t\t\tYPos=eval(['MPos+',YPos(2:end)],'MPos');\n\t\telse\n\t\t\tYPos = max([0,CPos])+eval(YPos);\n\t\tend\n\telse\n\t\t%-Absolute YPos\n\t\tYPos=abs(YPos);\n\tend\n\tNPos = min(max(1,YPos),MPos);\nend\nvarargout = {NPos,CPos,hCPos};\n\ncase '!setnextpos'\n%=======================================================================\n% NPos = spm_input('!SetNextPos',YPos,F,CmdLine)\n%-Set next position to use\nif nargin<3, F='Interactive'; else, F=varargin{3}; end\nif nargin<2, YPos='+1'; else, YPos=varargin{2}; end\nif nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos);\n\telse, CmdLine=varargin{4}; end\n\n%-Find out which Y-position to use\n[NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine);\n\n%-Delete any previous inputs using positions NPos and after\nif any(CPos>=NPos), h=hCPos(:,CPos>=NPos); delete(h(h>0)), end\n\nvarargout = {NPos};\n\ncase '!maxpos'\n%=======================================================================\n% MPos = spm_input('!MaxPos',F,FRec3)\n%\nif nargin<3\n\tif nargin<2, F='Interactive'; else, F=varargin{2}; end\n\tF = spm_figure('FindWin',F);\n\tif isempty(F)\n\t\tFRec3=spm('WinSize','Interactive')*[0;0;0;1];\n\telse\n\t\t%-Get figure size\n\t\tUnits = get(F,'Units');\n\t\tset(F,'Units','pixels')\n\t\tFRec3 = get(F,'Position')*[0;0;0;1];\n\t\tset(F,'Units',Units);\n\tend\nend\n\nSe = round(25*min(spm('WinScale')));\nMPos = floor((FRec3-5)/Se);\n\nvarargout = {MPos};\n\n\ncase '!editablekeypressfcn'\n%=======================================================================\n% spm_input('!EditableKeyPressFcn',h,ch,hPrmpt)\nif nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end\nif isempty(h), set(gcbf,'KeyPressFcn','','UserData',[]), return, end\nif nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else, ch=varargin{3};end\nif nargin<4, hPrmpt=get(h,'UserData'); else, hPrmpt=varargin{4}; end\n\ntmp = get(h,'String');\nif isempty(tmp), tmp=''; end\nif iscellstr(tmp) & length(tmp)==1; tmp=tmp{:}; end\n\nif isempty(ch)\t\t\t\t\t%- shift / control / &c. pressed\n\treturn\nelseif any(abs(ch)==[32:126])\t\t\t%-Character\n\tif iscellstr(tmp), return, end\n\ttmp = [tmp, ch];\nelseif abs(ch)==21\t\t\t\t%- ^U - kill\n\ttmp = '';\nelseif any(abs(ch)==[8,127])\t\t\t%-BackSpace or Delete\n\tif iscellstr(tmp), return, end\n\tif length(tmp), tmp(length(tmp))=''; end\nelseif abs(ch)==13\t\t\t\t%-Return pressed\n\tif ~isempty(tmp)\n\t\tset(hPrmpt,'UserData',get(h,'String'))\n\tend\n\treturn\nelse\n\t%-Illegal character\n\treturn\nend\nset(h,'String',tmp)\n\n\ncase '!buttonkeypressfcn'\n%=======================================================================\n% spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch)\n%-Callback for KeyPress, to store valid button # in UserData of Prompt,\n% DefItem if (DefItem~=0) & return (ASCII-13) is pressed\n\n%-Condition arguments\nif nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end\nif isempty(h), set(gcf,'KeyPressFcn','','UserData',[]), return, end\nif nargin<3, error('Insufficient arguments'); else, Keys=varargin{3}; end\nif nargin<4, DefItem=0; else, DefItem=varargin{4}; end\nif nargin<5, ch=get(gcf,'CurrentCharacter'); else, ch=varargin{5}; end\n\nif isempty(ch)\n\t%- shift / control / &c. pressed\n\treturn\nelseif (DefItem & ch==13)\n\tBut = DefItem;\nelse\n\tBut = find(lower(ch)==lower(Keys));\nend\nif ~isempty(But), set(h,'UserData',But), end\n\n\ncase '!pulldownkeypressfcn'\n%=======================================================================\n% spm_input('!PullDownKeyPressFcn',h,ch,DefItem)\nif nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end\nif isempty(h), set(gcf,'KeyPressFcn',''), return, end\nif nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else, ch=varargin{3};end\nif nargin<4, DefItem=get(h,'UserData'); else, ch=varargin{4}; end\n\nPmax = get(h,'Max');\nPval = get(h,'Value');\n\nif Pmax==1, return, end\n\nif isempty(ch)\n\t%- shift / control / &c. pressed\n\treturn\nelseif abs(ch)==13\n\tif Pval==1\n\t\tif DefItem, set(h,'Value',max(2,min(DefItem+1,Pmax))), end\n\telse\n\t\tset(h,'UserData','Selected')\n\tend\nelseif any(ch=='bpu')\n\t%-Move \"b\"ack \"u\"p to \"p\"revious entry\n\tset(h,'Value',max(2,Pval-1))\nelseif any(ch=='fnd')\n\t%-Move \"f\"orward \"d\"own to \"n\"ext entry\n\tset(h,'Value',min(Pval+1,Pmax))\nelseif any(ch=='123456789')\n\t%-Move to entry n\n\tset(h,'Value',max(2,min(eval(ch)+1,Pmax)))\nelse\n\t%-Illegal character\nend\n\n\ncase '!m_cb' %-CallBack handler for extended CallBack 'p'ullDown type\n%=======================================================================\n% spm_input('!m_cb')\n\n%-Get PopUp handle and value\nh = gcbo;\nn = get(h,'Value');\n\n%-Get PopUp's UserData, check cb and UD fields exist, extract cb & UD\ntmp = get(h,'UserData');\nif ~(isfield(tmp,'cb') & isfield(tmp,'UD'))\n\terror('Invalid UserData structure for spm_input extended callback')\nend\ncb = tmp.cb;\nUD = tmp.UD;\n\n%-Evaluate appropriate CallBack string (ignoring any return arguments)\n% NB: Using varargout={eval(cb{n})}; gives an error if the CallBack \n% has no return arguments!\nif length(cb)==1, eval(char(cb)); else, eval(cb{n}); end\n\n\ncase '!dscroll'\n%=======================================================================\n% spm_input('!dScroll',h,Prompt)\n%-Scroll text in object h\nif nargin<2, return, else, h=varargin{2}; end\nif nargin<3, Prompt = get(h,'UserData'); else, Prompt=varargin{3}; end\ntmp = Prompt;\nif length(Prompt)>56\n\twhile length(tmp)>56\n\t\ttic, while(toc<0.1), pause(0.05), end\n\t\ttmp(1)=[];\n\t\tset(h,'String',tmp(1:min(length(tmp),56)))\n\tend\n\tpause(1)\n\tset(h,'String',Prompt(1:min(length(Prompt),56)))\nend\n\n\notherwise\n%=======================================================================\nerror(['Invalid type/action: ',Type])\n\n\n%=======================================================================\nend % (case lower(Type))\n\n\n%=======================================================================\n%- S U B - F U N C T I O N S\n%=======================================================================\n\nfunction [Keys,Labs] = sf_labkeys(Labels)\n%=======================================================================\n%-Make unique character keys for the Labels, ignoring case\nif nargin<1, error('insufficient arguments'), end\nif iscellstr(Labels), Labels = char(Labels); end\nif isempty(Labels), Keys=''; Labs=''; return, end\n\nKeys=Labels(:,1)';\nnLabels = size(Labels,1);\nif any(~diff(abs(sort(lower(Keys)))))\n\tif nLabels<10\n\t\tKeys = sprintf('%d',[1:nLabels]);\n\telseif nLabels<=26\n\t\tKeys = sprintf('%c',abs('a')+[0:nLabels-1]);\n\telse\n\t\terror('Too many buttons!')\n\tend\n\tLabs = Labels;\nelse\n\tLabs = Labels(:,2:end);\nend\n\n\nfunction [p,msg] = sf_eEval(str,Type,n,m)\n%=======================================================================\n%-Evaluation and error trapping of typed input\nif nargin<4, m=[]; end\nif nargin<3, n=[]; end\nif nargin<2, Type='e'; end\nif nargin<1, str=''; end\nif isempty(str), p='!'; msg='empty input'; return, end\nswitch lower(Type)\ncase 's'\n\tp = str; msg = '';\ncase 'e'\n\tp = evalin('base',['[',str,']'],'''!''');\n\tif ischar(p)\n\t\tmsg = 'evaluation error';\n\telse\n\t\t[p,msg] = sf_SzChk(p,n);\n\tend\ncase 'n'\n\tp = evalin('base',['[',str,']'],'''!''');\n\tif ischar(p)\n\t\tmsg = 'evaluation error';\n\telseif any(floor(p(:))~=p(:)|p(:)<1)|~isreal(p)\n\t\tp='!'; msg='natural number(s) required';\n\telseif ~isempty(m) & any(p(:)>m)\n\t\tp='!'; msg=['max value is ',num2str(m)];\n\telse\n\t\t[p,msg] = sf_SzChk(p,n);\n\tend\ncase 'w'\n\tp = evalin('base',['[',str,']'],'''!''');\n\tif ischar(p)\n\t\tmsg = 'evaluation error';\n\telseif any(floor(p(:))~=p(:)|p(:)<0)|~isreal(p)\n\t\tp='!'; msg='whole number(s) required';\n\telseif ~isempty(m) & any(p(:)>m)\n\t\tp='!'; msg=['max value is ',num2str(m)];\n\telse\n\t\t[p,msg] = sf_SzChk(p,n);\n\tend\ncase 'i'\n\tp = evalin('base',['[',str,']'],'''!''');\n\tif ischar(p)\n\t\tmsg = 'evaluation error';\n\telseif any(floor(p(:))~=p(:))|~isreal(p)\n\t\tp='!'; msg='integer(s) required';\n\telse\n\t\t[p,msg] = sf_SzChk(p,n);\n\tend\ncase 'p'\n\tp = evalin('base',['[',str,']'],'''!''');\n\tif ischar(p)\n\t\tmsg = 'evaluation error';\n\telseif length(setxor(p(:)',m))\n\t\tp='!'; msg='invalid permutation';\n\telse\n\t\t[p,msg] = sf_SzChk(p,n);\n\tend\ncase 'r'\n\tp = evalin('base',['[',str,']'],'''!''');\n\tif ischar(p)\n\t\tmsg = 'evaluation error';\n\telseif ~isreal(p)\n\t\tp='!'; msg='real number(s) required';\n\telseif ~isempty(m) & ( max(p)>max(m) | min(p)1, str=' columns'; else, str='s'; end\n\t\t\tmsg = sprintf('right padded with %d zero%s',tmp,str);\n\t\telse\n\t\t\tmsg = '';\n\t\tend\n\n\t\tif size(p,2)>n(2)\n\t\t\tp='!'; msg=sprintf('too long - only %d prams',n(2));\n\t\telseif isfinite(n(1)) & size(p,1)~=n(1)\n\t\t\tp='!';\n\t\t\tif n(1)==1, msg='vector required';\n\t\t\t else, msg=sprintf('%d contrasts required',n(1)); end\n\t\telseif ~isempty(X) & ~spm_SpUtil('allCon',X,p')\n\t\t\tp='!'; msg='invalid contrast';\n\t\tend\n\tend\n\notherwise\n\terror('unrecognised type');\nend\n\n\nfunction str = sf_SzStr(n,l)\n%=======================================================================\n%-Size info string constuction\nif nargin<2, l=0; else, l=1; end\nif nargin<1, error('insufficient arguments'), end\nif isempty(n), n=NaN; end\nn=n(:); if length(n)==1, n=[n,1]; end, dn=length(n);\nif any(isnan(n)) | (prod(n)==1 & dn<=2) | (dn==2 & min(n)==1 & isinf(max(n)))\n\tstr = ''; lstr = '';\nelseif dn==2 & min(n)==1\n\tstr = sprintf('[%d]',max(n));\tlstr = [str,'-vector'];\nelseif dn==2 & sum(isinf(n))==1\n\tstr = sprintf('[%d]',min(n));\tlstr = [str,'-vector(s)'];\nelse\n\tstr=''; for i = 1:dn\n\t\tif isfinite(n(i)), str = sprintf('%s,%d',str,n(i));\n\t\telse, str = sprintf('%s,*',str); end\n\tend\n\tstr = ['[',str(2:end),']'];\tlstr = [str,'-matrix'];\nend\nif l, str=sprintf('\\t%s',lstr); else, str=[str,' ']; end\n\n\nfunction [p,msg] = sf_SzChk(p,n,msg)\n%=======================================================================\n%-Size checking\nif nargin<3, msg=''; end\nif nargin<2, n=[]; end, if isempty(n), n=NaN; else, n=n(:)'; end\nif nargin<1, error('insufficient arguments'), end\n\nif ischar(p) | any(isnan(n(:))), return, end\nif length(n)==1, n=[n,1]; end\n\ndn = length(n);\nsp = size(p);\ndp = ndims(p);\n\nif dn==2 & min(n)==1\n\t%-[1,1], [1,n], [n,1], [1,Inf], [Inf,1] - vector - allow transpose\n\t%---------------------------------------------------------------\n\ti = min(find(n==max(n)));\n\tif n(i)==1 & max(sp)>1\n\t\tp='!'; msg='scalar required';\n\telseif ndims(p)~=2 | ~any(sp==1) | ( isfinite(n(i)) & max(sp)~=n(i) )\n\t\t%-error: Not2D | not vector | not right length\n\t\tif isfinite(n(i)), str=sprintf('%d-',n(i)); else, str=''; end\n\t\tp='!'; msg=[str,'vector required'];\n\telseif sp(i)==1 & n(i)~=1\n\t\tp=p'; msg=[msg,' (input transposed)'];\n\tend\n\nelseif dn==2 & sum(isinf(n))==1\n\t%-[n,Inf], [Inf,n] - n vector(s) required - allow transposing\n\t%---------------------------------------------------------------\n\ti = find(isfinite(n));\n\tif ndims(p)~=2 | ~any(sp==n(i))\n\t\tp='!'; msg=sprintf('%d-vector(s) required',min(n));\n\telseif sp(i)~=n\n\t\tp=p'; msg=[msg,' (input transposed)'];\n\tend\t\n\nelse\n\t%-multi-dimensional matrix required - check dimensions\n\t%---------------------------------------------------------------\n\tif ndims(p)~=dn | ~all( size(p)==n | isinf(n) )\n\t\tp = '!'; msg='';\n\t\tfor i = 1:dn\n\t\t\tif isfinite(n(i)), msg = sprintf('%s,%d',msg,n(i));\n\t\t\telse, msg = sprintf('%s,*',msg); end\n\t\tend\n\t\tmsg = ['[',msg(2:end),']-matrix required'];\n\tend\n\nend\n\n\nfunction uifocus(h)\n%=======================================================================\n% Matlab r14 no longer keeps focus on the uicontrol, unless it is\n% explicitly specified, otherwise control is given to the figure's\n% keypress function. therefore we must explicitly set the focus to\n% a uicontrol or the user is forced to click into the control to\n% enter data or press a button. Matlab 7 has extended the functionality\n% of the uicontrol function. uicontrol(handle) sets the focus\n% to the designated uiontrol's handle.\ntry\n if spm_matlab_version_chk('7') >= 0\n if strcmpi(get(h, 'Style'), 'PushButton') == 1\n uicontrol(gcbo);\n else \n uicontrol(h); \n end\n end\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_minc.m", "ext": ".m", "path": "spm5-master/spm_config_minc.m", "size": 2505, "source_encoding": "utf_8", "md5": "47d6e77ccd421f13aeb57fc2941eccb1", "text": "function opts = spm_config_minc\n% Configuration file for minc import jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_minc.m 1032 2007-12-20 14:45:55Z john $\n\n%_______________________________________________________________________\n\ndata.type = 'files';\ndata.name = 'MINC files';\ndata.tag = 'data';\ndata.filter = 'mnc';\ndata.num = Inf;\ndata.help = {'Select the MINC files to convert.'};\n\ndtype.type = 'menu';\ndtype.name = 'Data Type';\ndtype.tag = 'dtype';\ndtype.labels = {'UINT8 - unsigned char','INT16 - signed short','INT32 - signed int','FLOAT - single prec. float','DOUBLE - double prec. float'};\ndtype.values = {spm_type('uint8'),spm_type('int16'),spm_type('int32'),spm_type('float32'),spm_type('float64')};\ndtype.val = {spm_type('int16')};\ndtype.help = {[...\n'Data-type of output images. '...\n'Note that the number of bits used determines '...\n'the accuracy, and the amount of disk space needed.']};\n\next.type = 'menu';\next.name = 'NIFTI Type';\next.tag = 'ext';\next.labels = {'.nii only','.img + .hdr'};\next.values = {'.nii','.img'};\next.val = {'.img'};\next.help = {[...\n'Output files can be written as .img + .hdr, ',...\n'or the two can be combined into a .nii file.']};\n\nop1.type = 'branch';\nop1.name = 'Options';\nop1.tag = 'opts';\nop1.val = {dtype,ext};\nop1.help = {'Conversion options'};\n\nopts.type = 'branch';\nopts.name = 'MINC Import';\nopts.tag = 'minc';\nopts.val = {data,op1};\nopts.prog = @convert_minc;\nopts.vfiles = @vfiles;\nopts.help = {[...\n'MINC Conversion. MINC is the image data format used for exchanging data '...\n'within the ICBM community, and the format used by the MNI software tools. '...\n'It is based on NetCDF, but due to be superceded by a new version relatively soon. '...\n'MINC is no longer supported for reading images into SPM, so MINC files need to '...\n'be converted to NIFTI format in order to use them. '...\n'See http://www.bic.mni.mcgill.ca/software/ for more information.']};\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction convert_minc(job)\nfor i=1:length(job.data),\n spm_mnc2nifti(job.data{i},job.opts);\nend;\nreturn;\n\nfunction vf = vfiles(job)\nvf = cell(size(job.data));\nfor i=1:numel(job.data),\n [pth,nam,ext,num] = spm_fileparts(job.data{i});\n vf{i} = fullfile(pth,[nam job.opts.ext num]);\nend;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_realign.m", "ext": ".m", "path": "spm5-master/spm_realign.m", "size": 17190, "source_encoding": "utf_8", "md5": "4b1e430488a8aa45f21f252c19f49b04", "text": "function P = spm_realign(P,flags)\n% Estimation of within modality rigid body movement parameters\n% FORMAT P = spm_realign(P,flags)\n%\n% P - matrix of filenames {one string per row}\n% All operations are performed relative to the first image.\n% ie. Coregistration is to the first image, and resampling\n% of images is into the space of the first image.\n% For multiple sessions, P should be a cell array, where each\n% cell should be a matrix of filenames.\n%\n% flags - a structure containing various options. The fields are:\n% quality - Quality versus speed trade-off. Highest quality\n% (1) gives most precise results, whereas lower\n% qualities gives faster realignment.\n% The idea is that some voxels contribute little to\n% the estimation of the realignment parameters.\n% This parameter is involved in selecting the number\n% of voxels that are used.\n%\n% fwhm - The FWHM of the Gaussian smoothing kernel (mm)\n% applied to the images before estimating the\n% realignment parameters.\n%\n% sep - the default separation (mm) to sample the images.\n%\n% rtm - Register to mean. If field exists then a two pass\n% procedure is to be used in order to register the\n% images to the mean of the images after the first\n% realignment.\n%\n% PW - a filename of a weighting image (reciprocal of\n% standard deviation). If field does not exist, then\n% no weighting is done.\n%\n% interp - B-spline degree used for interpolation\n%\n%__________________________________________________________________________\n%\n% Inputs\n% A series of *.img conforming to SPM data format (see 'Data Format').\n%\n% Outputs\n% If no output argument, then an updated voxel to world matrix is written\n% to the headers of the images (a .mat file is created for 4D images).\n% The details of the transformation are displayed in the\n% results window as plots of translation and rotation.\n% A set of realignment parameters are saved for each session, named:\n% rp_*.txt.\n%__________________________________________________________________________\n%\n% The voxel to world mappings.\n%\n% These are simply 4x4 affine transformation matrices represented in the\n% NIFTI headers (see http://nifti.nimh.nih.gov/nifti-1 ).\n% These are normally modified by the `realignment' and `coregistration'\n% modules. What these matrixes represent is a mapping from\n% the voxel coordinates (x0,y0,z0) (where the first voxel is at coordinate\n% (1,1,1)), to coordinates in millimeters (x1,y1,z1).\n% \n% x1 = M(1,1)*x0 + M(1,2)*y0 + M(1,3)*z0 + M(1,4)\n% y1 = M(2,1)*x0 + M(2,2)*y0 + M(2,3)*z0 + M(2,4)\n% z1 = M(3,1)*x0 + M(3,2)*y0 + M(3,3)*z0 + M(3,4)\n%\n% Assuming that image1 has a transformation matrix M1, and image2 has a\n% transformation matrix M2, the mapping from image1 to image2 is: M2\\M1\n% (ie. from the coordinate system of image1 into millimeters, followed\n% by a mapping from millimeters into the space of image2).\n%\n% These matrices allow several realignment or coregistration steps to be\n% combined into a single operation (without the necessity of resampling the\n% images several times). The `.mat' files are also used by the spatial\n% normalisation module.\n%__________________________________________________________________________\n% Ref:\n% Friston KJ, Ashburner J, Frith CD, Poline J-B, Heather JD & Frackowiak\n% RSJ (1995) Spatial registration and normalization of images Hum. Brain\n% Map. 2:165-189\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_realign.m 1030 2007-12-20 11:43:12Z john $\n\n\nif nargin==0, return; end;\n\ndef_flags = struct('quality',1,'fwhm',5,'sep',4,'interp',2,'wrap',[0 0 0],'rtm',0,'PW','','graphics',1,'lkp',1:6);\nif nargin < 2,\n\tflags = def_flags;\nelse\n\tfnms = fieldnames(def_flags);\n\tfor i=1:length(fnms),\n\t\tif ~isfield(flags,fnms{i}),\n\t\t\tflags.(fnms{i}) = def_flags.(fnms{i});\n\t\tend;\n\tend;\nend;\n\nif ~iscell(P), tmp = cell(1); tmp{1} = P; P = tmp; end;\nfor i=1:length(P), if ischar(P{i}), P{i} = spm_vol(P{i}); end; end;\nif ~isempty(flags.PW) && ischar(flags.PW), flags.PW = spm_vol(flags.PW); end;\n\n% Remove empty cells\nPN = {};\nj = 1;\nfor i=1:length(P),\n\tif ~isempty(P{i}), PN{j} = P{i}; j = j+1; end;\nend;\nP = PN;\n\nif isempty(P), warning('Nothing to do'); return; end;\n\nif length(P)==1,\n\tP{1} = realign_series(P{1},flags);\n\tif nargout==0, save_parameters(P{1}); end;\nelse\n\tPtmp = P{1}(1);\n\tfor s=2:numel(P),\n\t\tPtmp = [Ptmp ; P{s}(1)];\n\tend;\n\tPtmp = realign_series(Ptmp,flags);\n\tfor s=1:numel(P),\n\t\tM = Ptmp(s).mat*inv(P{s}(1).mat);\n\t\tfor i=1:numel(P{s}),\n\t\t\tP{s}(i).mat = M*P{s}(i).mat;\n\t\tend;\n\tend;\n\n\tfor s=1:numel(P),\n\t\tP{s} = realign_series(P{s},flags);\n\t\tif nargout==0, save_parameters(P{s}); end;\n\tend;\nend;\n\nif nargout==0, \n\t% Save Realignment Parameters\n\t%---------------------------------------------------------------------------\n\tfor s=1:numel(P),\n\t\tfor i=1:numel(P{s}),\n\t\t\tspm_get_space([P{s}(i).fname ',' num2str(P{s}(i).n)], P{s}(i).mat);\n\t\tend;\n\tend;\nend;\n\nif flags.graphics, plot_parameters(P); end;\n\nif length(P)==1, P=P{1}; end;\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction P = realign_series(P,flags)\n% Realign a time series of 3D images to the first of the series.\n% FORMAT P = realign_series(P,flags)\n% P - a vector of volumes (see spm_vol)\n%-----------------------------------------------------------------------\n% P(i).mat is modified to reflect the modified position of the image i.\n% The scaling (and offset) parameters are also set to contain the\n% optimum scaling required to match the images.\n%_______________________________________________________________________\n\nif numel(P)<2, return; end;\n\nskip = sqrt(sum(P(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;\nd = P(1).dim(1:3); \nlkp = flags.lkp;\nrand('state',0); % want the results to be consistant.\nif d(3) < 3,\n\tlkp = [1 2 6];\n\t[x1,x2,x3] = ndgrid(1:skip(1):d(1)-.5, 1:skip(2):d(2)-.5, 1:skip(3):d(3));\n\tx1 = x1 + rand(size(x1))*0.5;\n\tx2 = x2 + rand(size(x2))*0.5;\nelse\n\t[x1,x2,x3]=ndgrid(1:skip(1):d(1)-.5, 1:skip(2):d(2)-.5, 1:skip(3):d(3)-.5);\n\tx1 = x1 + rand(size(x1))*0.5;\n\tx2 = x2 + rand(size(x2))*0.5;\n\tx3 = x3 + rand(size(x3))*0.5; \nend;\n\nx1 = x1(:);\nx2 = x2(:);\nx3 = x3(:);\n\n% Possibly mask an area of the sample volume.\n%-----------------------------------------------------------------------\nif ~isempty(flags.PW),\n\t[y1,y2,y3]=coords([0 0 0 0 0 0],P(1).mat,flags.PW.mat,x1,x2,x3);\n\twt = spm_sample_vol(flags.PW,y1,y2,y3,1);\n\tmsk = find(wt>0.01);\n\tx1 = x1(msk);\n\tx2 = x2(msk);\n\tx3 = x3(msk);\n\twt = wt(msk);\nelse\n\twt = [];\nend;\n\n% Compute rate of change of chi2 w.r.t changes in parameters (matrix A)\n%-----------------------------------------------------------------------\nV = smooth_vol(P(1),flags.interp,flags.wrap,flags.fwhm);\ndeg = [flags.interp*[1 1 1]' flags.wrap(:)];\n\n[G,dG1,dG2,dG3] = spm_bsplins(V,x1,x2,x3,deg);\nclear V\nA0 = make_A(P(1).mat,x1,x2,x3,dG1,dG2,dG3,wt,lkp);\n\nb = G;\nif ~isempty(wt), b = b.*wt; end;\n\n%-----------------------------------------------------------------------\nif numel(P) > 2,\n\t% Remove voxels that contribute very little to the final estimate.\n\t% Simulated annealing or something similar could be used to\n\t% eliminate a better choice of voxels - but this way will do for\n\t% now. It basically involves removing the voxels that contribute\n\t% least to the determinant of the inverse covariance matrix.\n\n\tspm_chi2_plot('Init','Eliminating Unimportant Voxels',...\n\t\t 'Relative quality','Iteration');\n\tAlpha = spm_atranspa([A0 b]);\n\tdet0 = det(Alpha);\n\tdet1 = det0;\n\tspm_chi2_plot('Set',det1/det0);\n\twhile det1/det0 > flags.quality,\n\t\tdets = zeros(size(A0,1),1);\n\t\tfor i=1:size(A0,1),\n\t\t\tdets(i) = det(Alpha - spm_atranspa([A0(i,:) b(i)]));\n\t\tend;\n\t\t[junk,msk] = sort(det1-dets);\n\t\tmsk = msk(1:round(length(dets)/10));\n\t\t A0(msk,:) = []; b(msk,:) = []; G(msk,:) = [];\n\t\t x1(msk,:) = []; x2(msk,:) = []; x3(msk,:) = [];\n\t\tdG1(msk,:) = []; dG2(msk,:) = []; dG3(msk,:) = [];\n\t\tif ~isempty(wt), wt(msk,:) = []; end;\n\t\tAlpha = spm_atranspa([A0 b]);\n\t\tdet1 = det(Alpha);\n\t\tspm_chi2_plot('Set',single(det1/det0));\n\tend;\n\tspm_chi2_plot('Clear');\nend;\n%-----------------------------------------------------------------------\n\n\nif flags.rtm,\n\tcount = ones(size(b));\n\tave = G;\n\tgrad1 = dG1;\n\tgrad2 = dG2;\n\tgrad3 = dG3;\nend;\n\nspm_progress_bar('Init',length(P)-1,'Registering Images');\n% Loop over images\n%-----------------------------------------------------------------------\nfor i=2:length(P),\n\tV = smooth_vol(P(i),flags.interp,flags.wrap,flags.fwhm);\n\td = [size(V) 1 1];\n\td = d(1:3);\n\tss = Inf;\n\tcountdown = -1;\n\tfor iter=1:64,\n\t\t[y1,y2,y3] = coords([0 0 0 0 0 0],P(1).mat,P(i).mat,x1,x2,x3);\n\t\tmsk = find((y1>=1 & y1<=d(1) & y2>=1 & y2<=d(2) & y3>=1 & y3<=d(3)));\n\t\tif length(msk)<32, error_message(P(i)); end;\n\n\t\tF = spm_bsplins(V, y1(msk),y2(msk),y3(msk),deg);\n\t\tif ~isempty(wt), F = F.*wt(msk); end;\n\n\t\tA = A0(msk,:);\n\t\tb1 = b(msk);\n\t\tsc = sum(b1)/sum(F);\n\t\tb1 = b1-F*sc;\n\t\tsoln = spm_atranspa(A)\\(A'*b1);\n\n\t\tp = [0 0 0 0 0 0 1 1 1 0 0 0];\n\t\tp(lkp) = p(lkp) + soln';\n\t\tP(i).mat = inv(spm_matrix(p))*P(i).mat;\n\n\t\tpss = ss;\n\t\tss = sum(b1.^2)/length(b1);\n\t\tif (pss-ss)/pss < 1e-8 && countdown == -1, % Stopped converging.\n\t\t\tcountdown = 2;\n\t\tend;\n\t\tif countdown ~= -1,\n\t\t\tif countdown==0, break; end;\n\t\t\tcountdown = countdown -1;\n\t\tend;\n\tend;\n\tif flags.rtm,\n\t\t% Generate mean and derivatives of mean\n\t\ttiny = 5e-2; % From spm_vol_utils.c\n\t\tmsk = find((y1>=(1-tiny) & y1<=(d(1)+tiny) &...\n\t\t y2>=(1-tiny) & y2<=(d(2)+tiny) &...\n\t\t y3>=(1-tiny) & y3<=(d(3)+tiny)));\n\t\tcount(msk) = count(msk) + 1;\n\t\t[G,dG1,dG2,dG3] = spm_bsplins(V,y1(msk),y2(msk),y3(msk),deg);\n\t\tave(msk) = ave(msk) + G*sc;\n\t\tgrad1(msk) = grad1(msk) + dG1*sc;\n\t\tgrad2(msk) = grad2(msk) + dG2*sc;\n\t\tgrad3(msk) = grad3(msk) + dG3*sc;\n\tend;\n\tspm_progress_bar('Set',i-1);\nend;\nspm_progress_bar('Clear');\n\nif ~flags.rtm, return; end;\n%_______________________________________________________________________\nM=P(1).mat;\nA0 = make_A(M,x1,x2,x3,grad1./count,grad2./count,grad3./count,wt,lkp);\nif ~isempty(wt), b = (ave./count).*wt;\nelse b = (ave./count); end\n\nclear ave grad1 grad2 grad3\n\n% Loop over images\n%-----------------------------------------------------------------------\nspm_progress_bar('Init',length(P),'Registering Images to Mean');\nfor i=1:length(P),\n\tV = smooth_vol(P(i),flags.interp,flags.wrap,flags.fwhm);\n\td = [size(V) 1 1 1];\n\tss = Inf;\n\tcountdown = -1;\n\tfor iter=1:64,\n\t\t[y1,y2,y3] = coords([0 0 0 0 0 0],M,P(i).mat,x1,x2,x3);\n\t\tmsk = find((y1>=1 & y1<=d(1) & y2>=1 & y2<=d(2) & y3>=1 & y3<=d(3)));\n\t\tif length(msk)<32, error_message(P(i)); end;\n\n\t\tF = spm_bsplins(V, y1(msk),y2(msk),y3(msk),deg);\n\t\tif ~isempty(wt), F = F.*wt(msk); end;\n\n\t\tA = A0(msk,:);\n\t\tb1 = b(msk);\n\t\tsc = sum(b1)/sum(F);\n\t\tb1 = b1-F*sc;\n\t\tsoln = spm_atranspa(A)\\(A'*b1);\n\n\t\tp = [0 0 0 0 0 0 1 1 1 0 0 0];\n\t\tp(lkp) = p(lkp) + soln';\n\t\tP(i).mat = inv(spm_matrix(p))*P(i).mat;\n\n\t\tpss = ss;\n\t\tss = sum(b1.^2)/length(b1);\n\t\tif (pss-ss)/pss < 1e-8 && countdown == -1 % Stopped converging.\n\t\t\t% Do three final iterations to finish off with\n\t\t\tcountdown = 2;\n\t\tend;\n\t\tif countdown ~= -1\n\t\t\tif countdown==0, break; end;\n\t\t\tcountdown = countdown -1;\n\t\tend;\n\tend;\n\tspm_progress_bar('Set',i);\nend;\nspm_progress_bar('Clear');\n\n\n% Since we are supposed to be aligning everything to the first\n% image, then we had better do so\n%-----------------------------------------------------------------------\nM = M/P(1).mat;\nfor i=1:length(P)\n\tP(i).mat = M*P(i).mat;\nend\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [y1,y2,y3]=coords(p,M1,M2,x1,x2,x3)\n% Rigid body transformation of a set of coordinates.\nM = (inv(M2)*inv(spm_matrix(p))*M1);\ny1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);\ny2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);\ny3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction V = smooth_vol(P,hld,wrp,fwhm)\n% Convolve the volume in memory.\ns = sqrt(sum(P.mat(1:3,1:3).^2)).^(-1)*(fwhm/sqrt(8*log(2)));\nx = round(6*s(1)); x = -x:x;\ny = round(6*s(2)); y = -y:y;\nz = round(6*s(3)); z = -z:z;\nx = exp(-(x).^2/(2*(s(1)).^2));\ny = exp(-(y).^2/(2*(s(2)).^2));\nz = exp(-(z).^2/(2*(s(3)).^2));\nx = x/sum(x);\ny = y/sum(y);\nz = z/sum(z);\n\ni = (length(x) - 1)/2;\nj = (length(y) - 1)/2;\nk = (length(z) - 1)/2;\nd = [hld*[1 1 1]' wrp(:)];\nV = spm_bsplinc(P,d);\nspm_conv_vol(V,V,x,y,z,-[i j k]);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction A = make_A(M,x1,x2,x3,dG1,dG2,dG3,wt,lkp)\n% Matrix of rate of change of weighted difference w.r.t. parameter changes\np0 = [0 0 0 0 0 0 1 1 1 0 0 0];\nA = zeros(numel(x1),length(lkp));\nfor i=1:length(lkp)\n\tpt = p0;\n\tpt(lkp(i)) = pt(i)+1e-6;\n\t[y1,y2,y3] = coords(pt,M,M,x1,x2,x3);\n\ttmp = sum([y1-x1 y2-x2 y3-x3].*[dG1 dG2 dG3],2)/(-1e-6);\n\tif ~isempty(wt), A(:,i) = tmp.*wt;\n\telse A(:,i) = tmp; end\nend\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction error_message(P)\nstr = {\t'There is not enough overlap in the images',...\n\t'to obtain a solution.',...\n\t' ',...\n\t'Offending image:',...\n\t P.fname,...\n\t' ',...\n\t'Please check that your header information is OK.',...\n\t'The Check Reg utility will show you the initial',...\n\t'alignment between the images, which must be',...\n\t'within about 4cm and about 15 degrees in order',...\n\t'for SPM to find the optimal solution.'};\nspm('alert*',str,mfilename,sqrt(-1));\nerror('insufficient image overlap')\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction plot_parameters(P)\nfg=spm_figure('FindWin','Graphics');\nif ~isempty(fg),\n\tP = cat(1,P{:});\n\tif length(P)<2, return; end;\n\tParams = zeros(numel(P),12);\n\tfor i=1:numel(P),\n\t\tParams(i,:) = spm_imatrix(P(i).mat/P(1).mat);\n\tend\n\n\t% display results\n\t% translation and rotation over time series\n\t%-------------------------------------------------------------------\n\tspm_figure('Clear','Graphics');\n\tax=axes('Position',[0.1 0.65 0.8 0.2],'Parent',fg,'Visible','off');\n\tset(get(ax,'Title'),'String','Image realignment','FontSize',16,'FontWeight','Bold','Visible','on');\n\tx = 0.1;\n\ty = 0.9;\n\tfor i = 1:min([numel(P) 12])\n\t\ttext(x,y,[sprintf('%-4.0f',i) P(i).fname],'FontSize',10,'Interpreter','none','Parent',ax);\n\t\ty = y - 0.08;\n\tend\n\tif numel(P) > 12\n\t\ttext(x,y,'................ etc','FontSize',10,'Parent',ax); end\n\n\tax=axes('Position',[0.1 0.35 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on');\n\tplot(Params(:,1:3),'Parent',ax)\n\ts = ['x translation';'y translation';'z translation'];\n\t%text([2 2 2], Params(2, 1:3), s, 'Fontsize',10,'Parent',ax)\n\tlegend(ax, s, 0)\n\tset(get(ax,'Title'),'String','translation','FontSize',16,'FontWeight','Bold');\n\tset(get(ax,'Xlabel'),'String','image');\n\tset(get(ax,'Ylabel'),'String','mm');\n\n\n\tax=axes('Position',[0.1 0.05 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on');\n\tplot(Params(:,4:6)*180/pi,'Parent',ax)\n\ts = ['pitch';'roll ';'yaw '];\n\t%text([2 2 2], Params(2, 4:6)*180/pi, s, 'Fontsize',10,'Parent',ax)\n\tlegend(ax, s, 0)\n\tset(get(ax,'Title'),'String','rotation','FontSize',16,'FontWeight','Bold');\n\tset(get(ax,'Xlabel'),'String','image');\n\tset(get(ax,'Ylabel'),'String','degrees');\n\n\t% print realigment parameters\n\tspm_print\nend\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction save_parameters(V)\nfname = [spm_str_manip(prepend(V(1).fname,'rp_'),'s') '.txt'];\nn = length(V);\nQ = zeros(n,6);\nfor j=1:n,\n\tqq = spm_imatrix(V(j).mat/V(1).mat);\n\tQ(j,:) = qq(1:6);\nend;\nsave(fname,'Q','-ascii');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction PO = prepend(PI,pre)\n[pth,nm,xt,vr] = spm_fileparts(deblank(PI));\nPO = fullfile(pth,[pre nm xt vr]);\nreturn;\n%_______________________________________________________________________\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_realign_and_unwarp.m", "ext": ".m", "path": "spm5-master/spm_config_realign_and_unwarp.m", "size": 35460, "source_encoding": "utf_8", "md5": "fbec3386cd1dc0e8d8a2121f0e5d0359", "text": "function opts = spm_config_realign_and_unwarp\n% Configuration file for realign and unwarping jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Darren R. Gitelman\n% $Id: spm_config_realign_and_unwarp.m 1032 2007-12-20 14:45:55Z john $\n\n\n%_______________________________________________________________________\n\n\nquality.type = 'entry';\nquality.name = 'Quality';\nquality.tag = 'quality';\nquality.strtype = 'r';\nquality.num = [1 1];\nquality.def = 'realign.estimate.quality';\nquality.extras = [0 1];\nquality.help = {[...\n 'Quality versus speed trade-off. Highest quality (1) gives most ',...\n 'precise results, whereas lower qualities gives faster realignment. ',...\n 'The idea is that some voxels contribute little to the estimation of ',...\n 'the realignment parameters. This parameter is involved in selecting ',...\n 'the number of voxels that are used.']};\n\n%------------------------------------------------------------------------\n\nweight.type = 'files';\nweight.name = 'Weighting';\nweight.tag = 'weight';\nweight.filter = 'image';\nweight.num = [0 1];\nweight.val = {{}};\nweight.help = {[...\n 'The option of providing a weighting image to weight each voxel ',...\n 'of the reference image differently when estimating the realignment ',...\n 'parameters. The weights are proportional to the inverses of the ',...\n 'standard deviations. ',...\n 'For example, when there is a lot of extra-brain motion - e.g., during ',...\n 'speech, or when there are serious artifacts in a particular region of ',...\n 'the images.']};\n\n%------------------------------------------------------------------------\n\neinterp.type = 'menu';\neinterp.name = 'Interpolation';\neinterp.tag = 'einterp';\neinterp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-spline ',...\n '3rd Degree B-Spline','4th Degree B-Spline','5th Degree B-Spline ',...\n '6th Degree B-Spline','7th Degree B-Spline'};\neinterp.values = {0,1,2,3,4,5,6,7};\neinterp.def = 'realign.estimate.interp';\neinterp.help = {...\n ['The method by which the images are sampled when being written in a ',...\n 'different space. '],...\n [' Nearest Neighbour ',...\n ' - Fastest, but not normally recommended. '],...\n [' Bilinear Interpolation ',...\n ' - OK for PET, or realigned fMRI. '],...\n [' B-spline Interpolation/* \\cite{thevenaz00a} ',...\n ' - Better quality (but slower) interpolation, especially ',...\n ' with higher degree splines. Do not use B-splines when ',...\n ' there is any region of NaN or Inf in the images. ']};\n\n\n%------------------------------------------------------------------------\n\newrap.type = 'menu';\newrap.name = 'Wrapping';\newrap.tag = 'ewrap';\newrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z ',...\n 'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'};\newrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]};\newrap.def = 'realign.estimate.wrap';\newrap.help = {...\n 'These are typically: ',...\n ' No wrapping - for images that have already ',...\n ' been spatially transformed. ',...\n ' Wrap in Y - for (un-resliced) MRI where phase encoding ',...\n ' is in the Y direction (voxel space).'};\n\n%------------------------------------------------------------------------\n\nfwhm.type = 'entry';\nfwhm.name = 'Smoothing (FWHM)';\nfwhm.tag = 'fwhm';\nfwhm.num = [1 1];\nfwhm.strtype = 'e';\np1 = [...\n 'The FWHM of the Gaussian smoothing kernel (mm) applied to the ',...\n 'images before estimating the realignment parameters.'];\n\np2 = ' * PET images typically use a 7 mm kernel.';\np3 = ' * MRI images typically use a 5 mm kernel.';\nfwhm.help = {p1,'',p2,'',p3};\n\n%------------------------------------------------------------------------\n\nsep.type = 'entry';\nsep.name = 'Separation';\nsep.tag = 'sep';\nsep.num = [1 1];\nsep.strtype = 'e';\nsep.val = {4};\nsep.help = {[...\n 'The separation (in mm) between the points sampled in the ',...\n 'reference image. Smaller sampling distances gives more accurate ',...\n 'results, but will be slower.']};\n\n%------------------------------------------------------------------------\n\nrtm.type = 'menu';\nrtm.name = 'Num Passes';\nrtm.tag = 'rtm';\nrtm.labels = {'Register to first','Register to mean'};\nrtm.values = {0,1};\np1 = [...\n 'Register to first: Images are registered to the first image in the series. ',...\n 'Register to mean: A two pass procedure is used in order to register the ',...\n 'images to the mean of the images after the first realignment.'];\np2 = ' * PET images are typically registered to the mean.';\np3 = ' * MRI images are typically registered to the first image.';\nrtm.help = {p1,'',p2,'',p3};\n\n%------------------------------------------------------------------------\n\nbasfcn.type = 'menu';\nbasfcn.name = 'Basis Functions';\nbasfcn.tag = 'basfcn';\nbasfcn.labels = {'8x8x*','10x10x*','12x12x*','14x14x*'};\nbasfcn.values = {[8 8],[10 10],[12 12],[14 14]};\nbasfcn.def = 'unwarp.estimate.basfcn';\nbasfcn.help = {[...\n 'Number of basis functions to use for each dimension. ',...\n 'If the third dimension is left out, the order for that ',...\n 'dimension is calculated to yield a roughly equal spatial ',...\n 'cut-off in all directions. Default: [12 12 *]']};\n\n%------------------------------------------------------------------------\n\nregorder.type = 'menu';\nregorder.name = 'Regularisation';\nregorder.tag = 'regorder';\nregorder.labels = {'0','1','2','3'};\nregorder.values = {0,1,2,3};\nregorder.def = 'unwarp.estimate.regorder';\nregorder.help = {[...\n 'Unwarp looks for the solution that maximises the likelihood ',...\n '(minimises the variance) while simultaneously maximising the ',...\n 'smoothness of the estimated field (c.f. Lagrange multipliers). ',...\n 'This parameter determines how to balance the compromise between ',...\n 'these (i.e. the value of the multiplier). Test it on your own ',...\n 'data (if you can be bothered) or go with the defaults. '],...\n '',[...\n 'Regularisation of derivative fields is based on the regorder''th ',...\n '(spatial) derivative of the field. The choices are ',...\n '0, 1, 2, or 3. Default: 1']};\n\n%------------------------------------------------------------------------\n\nlambda.type = 'menu';\nlambda.name = 'Reg. Factor';\nlambda.tag = 'lambda';\nlambda.labels = {'A little','Medium','A lot'};\nlambda.values = {1e4, 1e5, 1e6,};\nlambda.def = 'unwarp.estimate.regwgt';\nlambda.help = {'Regularisation factor. Default: Medium.'};\n\n%------------------------------------------------------------------------\n\nrem.type = 'menu';\nrem.name = 'Re-estimate movement params';\nrem.tag = 'rem';\nrem.labels = {'Yes','No'};\nrem.values = {1 0};\nrem.def = 'unwarp.estimate.rem';\nrem.help = {[...\n 'Re-estimation means that movement-parameters should be re-estimated ',...\n 'at each unwarping iteration. Default: Yes.']};\n\n%------------------------------------------------------------------------\n\njm.type = 'menu';\njm.name = 'Jacobian deformations';\njm.tag = 'jm';\njm.labels = {'Yes','No'};\njm.values = {1 0};\njm.def = 'unwarp.estimate.jm';\njm.help = {[...\n 'In the defaults there is also an option to include Jacobian ',...\n 'intensity modulation when estimating the fields. \"Jacobian ',...\n 'intensity modulation\" refers to the dilution/concentration ',...\n 'of intensity that ensue as a consequence of the distortions. ',...\n 'Think of a semi-transparent coloured rubber sheet that you ',...\n 'hold against a white background. If you stretch a part of ',...\n 'the sheet (induce distortions) you will see the colour fading ',...\n 'in that particular area. In theory it is a brilliant idea to ',...\n 'include also these effects when estimating the field (see e.g. ',...\n 'Andersson et al, NeuroImage 20:870-888). In practice for this ',...\n 'specific problem it is NOT a good idea. Default: No']};\n\n%------------------------------------------------------------------------\n\nfot.type = 'entry';\nfot.name = 'First-order effects';\nfot.tag = 'fot';\nfot.strtype = 'e';\nfot.num = [1 Inf];\nfot.val = {[4 5]};\np1 = [...\n 'Theoretically (ignoring effects of shimming) one would expect the ',...\n 'field to depend only on subject out-of-plane rotations. Hence the ',...\n 'default choice (\"Pitch and Roll\", i.e., [4 5]). Go with that unless you have very ',...\n 'good reasons to do otherwise'];\np2 = [...\n 'Vector of first order effects to model. Movements to be modelled ',...\n 'are referred to by number. 1= x translation; 2= y translation; 3= z translation ',...\n '4 = x rotation, 5 = y rotation and 6 = z rotation.'];\np3 = 'To model pitch & roll enter: [4 5]';\np4 = 'To model all movements enter: [1:6]';\np5 = 'Otherwise enter a customised set of movements to model';\n\nfot.help = {p1,'',p2,'',p3,'',p4,'',p5};\n\n%------------------------------------------------------------------------\n\nsot.type = 'entry';\nsot.name = 'Second-order effects';\nsot.tag = 'sot';\nsot.strtype = 'e';\nsot.num = [1 Inf];\nsot.val = {[]};\np1 = [...\n 'List of second order terms to model second derivatives of. This is entered ',...\n 'as a vector of movement parameters similar to first order effects, or leave blank for NONE'];\np2 = 'Movements to be modelled are referred to by number:';\np3 = [...\n '1= x translation; 2= y translation; 3= z translation ',...\n '4 = x rotation, 5 = y rotation and 6 = z rotation.'];\np4 = 'To model the interaction of pitch & roll enter: [4 5]';\np5 = 'To model all movements enter: [1:6]';\np6 = [...\n 'The vector will be expanded into an n x 2 matrix of effects. For example ',...\n '[4 5] will be expanded to:'];\np7 = '[ 4 4';\np8 = ' 4 5';\np9 = ' 5 5 ]';\nsot.help = {p1,'',p2,'',p3,'',p4,'',p5,'',p6,'',p7,'',p8,'',p9};\n\n% put the expression in the context of the base workspace.\n% assignin('base','soe',@SOE)\n%----------------------------------------------------------------------\n\nuwfwhm.type = 'entry';\nuwfwhm.name = 'Smoothing for unwarp (FWHM)';\nuwfwhm.tag = 'uwfwhm';\nuwfwhm.num = [1 1];\nuwfwhm.strtype = 'r';\nuwfwhm.def = 'unwarp.estimate.fwhm';\nuwfwhm.help = {...\n'FWHM (mm) of smoothing filter applied to images prior to estimation of deformation fields.'};\n\n%----------------------------------------------------------------------\nnoi.type = 'entry';\nnoi.name = 'Number of Iterations';\nnoi.tag = 'noi';\nnoi.num = [1 1];\nnoi.strtype = 'n';\nnoi.def = 'unwarp.estimate.noi';\nnoi.help = {'Maximum number of iterations. Default: 5.'};\n%----------------------------------------------------------------------\n\nexpround.type = 'menu';\nexpround.name = 'Taylor expansion point';\nexpround.tag = 'expround';\nexpround.labels = {'Average','First','Last'};\nexpround.values = {'Average','First','Last'};\nexpround.def = 'unwarp.estimate.expround';\nexpround.help = {[...\n 'Point in position space to perform Taylor-expansion around. ',...\n 'Choices are (''First'', ''Last'' or ''Average''). ''Average'' should ',...\n '(in principle) give the best variance reduction. If a field-map acquired ',...\n 'before the time-series is supplied then expansion around the ''First'' ',...\n 'MIGHT give a slightly better average geometric fidelity.']};\n\n%----------------------------------------------------------------------\n\n%----------------------------------------------------------------------\n\nunnecessary.type = 'const';\nunnecessary.tag = 'unnecessary';\nunnecessary.val = {[]};\nunnecessary.name = 'No Phase Maps';\nunnecessary.help = {'Precalculated phase maps not included in unwarping.'};\n%----------------------------------------------------------------------\n\n\nglobal defaults\nif ~isempty(defaults) && isfield(defaults,'modality') ...\n && strcmpi(defaults.modality,'pet'),\n fwhm.val = {7};\n rtm.val = {1};\nelse\n fwhm.val = {5};\n rtm.val = {0};\nend;\n\neoptions.type = 'branch';\neoptions.name = 'Estimation Options';\neoptions.tag = 'eoptions';\neoptions.val = {quality,sep,fwhm,rtm,einterp,ewrap,weight};\neoptions.help = {['Various registration options that could be modified to improve the results. ',...\n'Whenever possible, the authors of SPM try to choose reasonable settings, but sometimes they can be improved.']};\n\n%------------------------------------------------------------------------\n\nwhich.type = 'menu';\nwhich.name = 'Resliced images';\nwhich.tag = 'which';\nwhich.labels = {' All Images (1..n)',' Images 2..n ',...\n ' All Images + Mean Image',' Mean Image Only'};\nwhich.values = {[2 0],[1 0],[2 1],[0 1]};\nwhich.val = {[2 1]};\nwhich.help = {...\n 'All Images (1..n) ',...\n [' This reslices all the images - including the first image selected '...\n ' - which will remain in its original position. '],...\n ' ',...\n 'Images 2..n ',...\n [' Reslices images 2..n only. Useful for if you wish to reslice ',...\n ' (for example) a PET image to fit a structural MRI, without ',...\n ' creating a second identical MRI volume. '],...\n ' ',...\n 'All Images + Mean Image ',...\n [' In addition to reslicing the images, it also creates a mean of the ',...\n ' resliced image. '],...\n ' ',...\n 'Mean Image Only ',...\n ' Creates the mean image only.'};\n\n%------------------------------------------------------------------------\n\nuwwhich.type = 'menu';\nuwwhich.name = 'Reslices images (unwarp)?';\nuwwhich.tag = 'uwwhich';\nuwwhich.labels = {' All Images (1..n)',' All Images + Mean Image'};\nuwwhich.values = {[2 0],[2 1]};\nuwwhich.val = {[2 1]};\nuwwhich.help = {...\n 'All Images (1..n) ',...\n ' This reslices and unwarps all the images. ',...\n ' ',...\n 'All Images + Mean Image ',...\n [' In addition to reslicing the images, it also creates a mean ',...\n ' of the resliced images.']};\n%------------------------------------------------------------------------\n\nrinterp.type = 'menu';\nrinterp.name = 'Interpolation';\nrinterp.tag = 'rinterp';\nrinterp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-spline ',...\n '3rd Degree B-Spline','4th Degree B-Spline','5th Degree B-Spline ',...\n '6th Degree B-Spline','7th Degree B-Spline'};\nrinterp.values = {0,1,2,3,4,5,6,7};\nrinterp.def = 'realign.write.interp';\nrinterp.help = {...\n ['The method by which the images are sampled when being written in a ',...\n 'different space. '],...\n [' Nearest Neighbour ',...\n ' - Fastest, but not normally recommended.'],...\n [' Bilinear Interpolation ',...\n ' - OK for PET, or realigned fMRI. ',...\n ' B-spline Interpolation/*\\cite{thevenaz00a}*/'],...\n [' - Better quality (but slower) interpolation, especially ',...\n ' with higher degree splines. Do not use B-splines when ',...\n ' there is any region of NaN or Inf in the images. ']};\n\n%------------------------------------------------------------------------\n\nwrap.type = 'menu';\nwrap.name = 'Wrapping';\nwrap.tag = 'wrap';\nwrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z ',...\n 'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'};\nwrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]};\nwrap.def = 'realign.write.wrap';\nwrap.help = {...\n 'These are typically: ',...\n [' No wrapping - for PET or images that have already ',...\n ' been spatially transformed. '],...\n [' Wrap in Y - for (un-resliced) MRI where phase encoding ',...\n ' is in the Y direction (voxel space).']};\n\n%------------------------------------------------------------------------\n\nmask.type = 'menu';\nmask.name = 'Masking';\nmask.tag = 'mask';\nmask.labels = {'Mask images','Dont mask images'};\nmask.values = {1,0};\nmask.def = 'realign.write.mask';\nmask.help = {[...\n 'Because of subject motion, different images are likely to have different ',...\n 'patterns of zeros from where it was not possible to sample data. ',...\n 'With masking enabled, the program searches through the whole time series ',...\n 'looking for voxels which need to be sampled from outside the original ',...\n 'images. Where this occurs, that voxel is set to zero for the whole set ',...\n 'of images (unless the image format can represent NaN, in which case ',...\n 'NaNs are used where possible).']};\n\n%------------------------------------------------------------------------\n\nuweoptions.type = 'branch';\nuweoptions.name = 'Unwarp Estimation Options';\nuweoptions.tag = 'uweoptions';\nuweoptions.val = {basfcn,regorder,lambda,jm,fot,sot,uwfwhm,rem,noi,expround};\nuweoptions.help = {'Various registration & unwarping estimation options.'};\n\n%------------------------------------------------------------------------\n\nuwroptions.type = 'branch';\nuwroptions.name = 'Unwarp Reslicing Options';\nuwroptions.tag = 'uwroptions';\nuwroptions.val = {uwwhich,rinterp,wrap,mask};\nuwroptions.help = {'Various registration & unwarping estimation options.'};\n%------------------------------------------------------------------------\n\n\nscans.type = 'files';\nscans.name = 'Images';\nscans.tag = 'scans';\nscans.num = [1 Inf];\nscans.filter = 'image';\nscans.help = {...\n 'Select scans for this session. ',[...\n 'In the coregistration step, the sessions are first realigned to ',...\n 'each other, by aligning the first scan from each session to the ',...\n 'first scan of the first session. Then the images within each session ',...\n 'are aligned to the first image of the session. ',...\n 'The parameter estimation is performed this way because it is assumed ',...\n '(rightly or not) that there may be systematic differences ',...\n 'in the images between sessions.']};\n\n%------------------------------------------------------------------------\n\npmscan.type = 'files';\npmscan.name = 'Phase map (vdm* file)';\npmscan.tag = 'pmscan';\npmscan.num = [0 1];\npmscan.val = {{}};\npmscan.filter = 'image';\npmscan.ufilter = '^vdm5_.*';\npmscan.help = {[...\n 'Select pre-calculated phase map, or leave empty for no phase correction. ',...\n 'The vdm* file is assumed to be already in alignment with the first scan ',...\n 'of the first session.']};\n\n%----------------------------------------------------------------------\n\ndata.type = 'branch';\ndata.name = 'Session';\ndata.tag = 'data';\ndata.val = {scans, pmscan};\np2 = [...\n'Only add similar session data to a realign+unwarp branch, i.e., ',...\n'choose Data or Data+phase map for all sessions, but don''t use them ',...\n'interchangeably.'];\np3 = [...\n'In the coregistration step, the sessions are first realigned to ',...\n'each other, by aligning the first scan from each session to the ',...\n'first scan of the first session. Then the images within each session ',...\n'are aligned to the first image of the session. ',...\n'The parameter estimation is performed this way because it is assumed ',...\n'(rightly or not) that there may be systematic differences ',...\n'in the images between sessions.'];\ndata.help = {p2,'',p3};\n\n%------------------------------------------------------------------------\nruwdata.type = 'repeat';\nruwdata.name = 'Data';\nruwdata.tag = 'ruwdata';\nruwdata.values = {data};\nruwdata.num = [1 Inf];\nruwdata.help = {'Data sessions to unwarp.'};\n%------------------------------------------------------------------------\n\nopts.type = 'branch';\nopts.name = 'Realign & Unwarp';\nopts.tag = 'realignunwarp';\nopts.val = {ruwdata,eoptions,uweoptions,uwroptions};\nopts.prog = @realunwarp;\nopts.vfiles = @vfiles_rureslice;\nopts.modality = {'PET','FMRI','VBM'};\nopts.help = {...\n'Within-subject registration and unwarping of time series.',...\n'',...\n[...\n'The realignment part of this routine realigns a time-series of images ',...\n'acquired from the same subject using a least squares approach and a ',...\n'6 parameter (rigid body) spatial transformation. The first image in ',...\n'the list specified by the user is used as a reference to which all ',...\n'subsequent scans are realigned. The reference scan does not have to ',...\n'the the first chronologically and it may be wise to chose a ',...\n'\"representative scan\" in this role.'],...\n'',...\n[...\n'The aim is primarily to remove movement artefact in fMRI and PET ',...\n'time-series (or more generally longitudinal studies). ',...\n'\".mat\" files are written for each of the input images. ',...\n'The details of the transformation are displayed in the results window ',...\n'as plots of translation and rotation. ',...\n'A set of realignment parameters are saved for each session, named ',...\n'rp_*.txt.'],...\n'',...\n[...\n'In the coregistration step, the sessions are first realigned to ',...\n'each other, by aligning the first scan from each session to the ',...\n'first scan of the first session. Then the images within each session ',...\n'are aligned to the first image of the session. ',...\n'The parameter estimation is performed this way because it is assumed ',...\n'(rightly or not) that there may be systematic differences ',...\n'in the images between sessions.'],...\n[...\n'The paper/* \\cite{ja_geometric}*/ is unfortunately a bit old now and describes none of ',...\n'the newer features. Hopefully we''ll have a second paper out any ',...\n'decade now.'],...\n'',...\n[...\n'See also spm_uw_estimate.m for a detailed description of the ',...\n'implementation. ',...\n'Even after realignment there is considerable variance in fMRI time ',...\n'series that covary with, and is most probably caused by, subject ',...\n'movements/* \\cite{ja_geometric}*/. It is also the case that this variance is typically ',...\n'large compared to experimentally induced variance. Anyone interested ',...\n'can include the estimated movement parameters as covariates in the ',...\n'design matrix, and take a look at an F-contrast encompassing those ',...\n'columns. It is quite dramatic. The result is loss of sensitivity, ',...\n'and if movements are correlated to task specificity. I.e. we may ',...\n'mistake movement induced variance for true activations. ',...\n'The problem is well known, and several solutions have been suggested. ',...\n'A quite pragmatic (and conservative) solution is to include the ',...\n'estimated movement parameters (and possibly squared) as covariates ',...\n'in the design matrix. Since we typically have loads of degrees of ',...\n'freedom in fMRI we can usually afford this. The problems occur when ',...\n'movements are correlated with the task, since the strategy above ',...\n'will discard \"good\" and \"bad\" variance alike (i.e. remove also \"true\" ',...\n'activations.'],...\n'',...\n[...\n'The \"covariate\" strategy described above was predicated on a model ',...\n'where variance was assumed to be caused by \"spin history\" effects, ',...\n'but will work pretty much equally good/bad regardless of what the ',...\n'true underlying cause is. Others have assumed that the residual variance ',...\n'is caused mainly by errors introduced by the interpolation kernel in the ',...\n'resampling step of the realignment. One has tried to solve this through ',...\n'higher order resampling (huge Sinc kernels, or k-space resampling). ',...\n'Unwarp is based on a different hypothesis regarding the residual ',...\n'variance. EPI images are not particularly faithful reproductions of ',...\n'the object, and in particular there are severe geometric distortions ',...\n'in regions where there is an air-tissue interface (e.g. orbitofrontal ',...\n'cortex and the anterior medial temporal lobes). In these areas in ',...\n'particular the observed image is a severely warped version of reality, ',...\n'much like a funny mirror at a fair ground. When one moves in front of ',...\n'such a mirror ones image will distort in different ways and ones head ',...\n'may change from very elongated to seriously flattened. If we were to ',...\n'take digital snapshots of the reflection at these different positions ',...\n'it is rather obvious that realignment will not suffice to bring them ',...\n'into a common space.'],...\n'',...\n[...\n'The situation is similar with EPI images, and an image collected for ',...\n'a given subject position will not be identical to that collected at ',...\n'another. We call this effect susceptibility-by-movement interaction. ',...\n'Unwarp is predicated on the assumption that the susceptibility-by- ',...\n'movement interaction is responsible for a sizable part of residual ',...\n'movement related variance.'],...\n'',...\n[...\n'Assume that we know how the deformations change when the subject ',...\n'changes position (i.e. we know the derivatives of the deformations ',...\n'with respect to subject position). That means that for a given time ',...\n'series and a given set of subject movements we should be able to ',...\n'predict the \"shape changes\" in the object and the ensuing variance ',...\n'in the time series. It also means that, in principle, we should be ',...\n'able to formulate the inverse problem, i.e. given the observed ',...\n'variance (after realignment) and known (estimated) movements we should ',...\n'be able to estimate how deformations change with subject movement. ',...\n'We have made an attempt at formulating such an inverse model, and at ',...\n'solving for the \"derivative fields\". A deformation field can be ',...\n'thought of as little vectors at each position in space showing how ',...\n'that particular location has been deflected. A \"derivative field\" ',...\n'is then the rate of change of those vectors with respect to subject ',...\n'movement. Given these \"derivative fields\" we should be able to remove ',...\n'the variance caused by the susceptibility-by-movement interaction. ',...\n'Since the underlying model is so restricted we would also expect ',...\n'experimentally induced variance to be preserved. Our experiments ',...\n'have also shown this to be true.'],...\n'',...\n[...\n'In theory it should be possible to estimate also the \"static\" ',...\n'deformation field, yielding an unwarped (to some true geometry) ',...\n'version of the time series. In practise that doesn''t really seem to ',...\n'work. Hence, the method deals only with residual movement related ',...\n'variance induced by the susceptibility-by-movement interaction. ',...\n'This means that the time-series will be undistorted to some ',...\n'\"average distortion\" state rather than to the true geometry. ',...\n'If one wants additionally to address the issue of anatomical ',...\n'fidelity one should combine Unwarp with a measured fieldmap.'],...\n'',...\n[...\n'The description above can be thought of in terms of a Taylor ',...\n'expansion of the field as a function of subject movement. Unwarp ',...\n'alone will estimate the first (and optionally second, see below) ',...\n'order terms of this expansion. It cannot estimate the zeroth ',...\n'order term (the distortions common to all scans in the time ',...\n'series) since that doesn''t introduce (almost) any variance in ',...\n'the time series. The measured fieldmap takes the role of the ',...\n'zeroth order term. Refer to the FieldMap toolbox and the ',...\n'documents FieldMap.man and FieldMap_principles.man for a ',...\n'description of how to obtain fieldmaps in the format expected ',...\n'by Unwarp.'],...\n'',...\n[...\n'If we think of the field as a function of subject movement it ',...\n'should in principle be a function of six variables since rigid ',...\n'body movement has six degrees of freedom. However, the physics ',...\n'of the problem tells us that the field should not depend on ',...\n'translations nor on rotation in a plane perpendicular to the ',...\n'magnetic flux. Hence it should in principle be sufficient to ',...\n'model the field as a function of out-of-plane rotations (i.e. ',...\n'pitch and roll). One can object to this in terms of the effects ',...\n'of shimming (object no longer immersed in a homogenous field) ',...\n'that introduces a dependence on all movement parameters. In ',...\n'addition SPM/Unwarp cannot really tell if the transversal ',...\n'slices it is being passed are really perpendicular to the flux ',...\n'or not. In practice it turns out thought that it is never (at ',...\n'least we haven''t seen any case) necessary to include more ',...\n'than Pitch and Roll. This is probably because the individual ',...\n'movement parameters are typically highly correlated anyway, ',...\n'which in turn is probably because most heads that we scan ',...\n'are attached to a neck around which rotations occur. ',...\n'On the subject of Taylor expansion we should mention that there ',...\n'is the option to use a second-order expansion (through the ',...\n'defaults) interface. This implies estimating also the ',...\n'rate-of-change w.r.t. to some movement parameter of ',...\n'the rate-of-change of the field w.r.t. some movement parameter ',...\n'(colloquially known as a second derivative). It can be quite ',...\n'interesting to watch (and it is amazing that it is possible) ',...\n'but rarely helpful/necessary.'],...\n'',...\n[...\n'In the defaults there is also an option to include Jacobian ',...\n'intensity modulation when estimating the fields. \"Jacobian ',...\n'intensity modulation\" refers to the dilution/concentration ',...\n'of intensity that ensue as a consequence of the distortions. ',...\n'Think of a semi-transparent coloured rubber sheet that you ',...\n'hold against a white background. If you stretch a part of ',...\n'the sheet (induce distortions) you will see the colour fading ',...\n'in that particular area. In theory it is a brilliant idea to ',...\n'include also these effects when estimating the field (see e.g. ',...\n'Andersson et al, NeuroImage 20:870-888). In practice for this ',...\n'specific problem it is NOT a good idea.'],...\n'',...\n[...\n'It should be noted that this is a method intended to correct ',...\n'data afflicted by a particular problem. If there is little ',...\n'movement in your data to begin with this method will do you little ',...\n'good. If on the other hand there is appreciable movement in your ',...\n'data (>1deg) it will remove some of that unwanted variance. If, ',...\n'in addition, movements are task related it will do so without ',...\n'removing all your \"true\" activations. ',...\n'The method attempts to minimise total (across the image volume) ',...\n'variance in the data set. It should be realised that while ',...\n'(for small movements) a rather limited portion of the total ',...\n'variance is removed, the susceptibility-by-movement interaction ',...\n'effects are quite localised to \"problem\" areas. Hence, for a ',...\n'subset of voxels in e.g. frontal-medial and orbitofrontal cortices ',...\n'and parts of the temporal lobes the reduction can be quite dramatic ',...\n'(>90). ',...\n'The advantages of using Unwarp will also depend strongly on the ',...\n'specifics of the scanner and sequence by which your data has been ',...\n'acquired. When using the latest generation scanners distortions ',...\n'are typically quite small, and distortion-by-movement interactions ',...\n'consequently even smaller. A small check list in terms of ',...\n'distortions is '],...\n'a) Fast gradients->short read-out time->small distortions ',...\n'b) Low field (i.e. <3T)->small field changes->small distortions ',...\n'c) Low res (64x64)->short read-out time->small distortions ',...\n'd) SENSE/SMASH->short read-out time->small distortions ',[...\n'If you can tick off all points above chances are you have minimal ',...\n'distortions to begin with and you can say \"sod Unwarp\" (but not ',...\n'to our faces!).']};...\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\n\nreturn;\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction realunwarp(varargin)\njob = varargin{1};\n\n% assemble flags\n%-----------------------------------------------------------------------\n% assemble realignment estimation flags.\nflags.quality = job.eoptions.quality;\nflags.fwhm = job.eoptions.fwhm;\nflags.sep = job.eoptions.sep;\nflags.rtm = job.eoptions.rtm;\nflags.PW = strvcat(job.eoptions.weight);\nflags.interp = job.eoptions.einterp;\nflags.wrap = job.eoptions.ewrap;\n\nuweflags.order = job.uweoptions.basfcn;\nuweflags.regorder = job.uweoptions.regorder;\nuweflags.lambda = job.uweoptions.lambda;\nuweflags.jm = job.uweoptions.jm;\nuweflags.fot = job.uweoptions.fot;\n\nif ~isempty(job.uweoptions.sot)\n cnt = 1;\n for i=1:size(job.uweoptions.sot,2)\n for j=i:size(job.uweoptions.sot,2)\n sotmat(cnt,1) = job.uweoptions.sot(i);\n sotmat(cnt,2) = job.uweoptions.sot(j);\n cnt = cnt+1;\n end\n end\nelse\n sotmat = [];\nend\nuweflags.sot = sotmat;\nuweflags.fwhm = job.uweoptions.uwfwhm;\nuweflags.rem = job.uweoptions.rem;\nuweflags.noi = job.uweoptions.noi;\nuweflags.exp_round = job.uweoptions.expround;\n\nuwrflags.interp = job.uwroptions.rinterp;\nuwrflags.wrap = job.uwroptions.wrap;\nuwrflags.mask = job.uwroptions.mask;\nuwrflags.which = job.uwroptions.uwwhich(1);\nuwrflags.mean = job.uwroptions.uwwhich(2);\n\nif uweflags.jm == 1\n uwrflags.udc = 2;\nelse\n uwrflags.udc = 1;\nend\n%---------------------------------------------------------------------\n\n% assemble files\n%---------------------------------------------------------------------\nP = {};\nfor i = 1:numel(job.data)\n P{i} = strvcat(job.data(i).scans{:});\n if ~isempty(job.data(i).pmscan)\n sfP{i} = job.data(i).pmscan{1};\n else\n sfP{i} = [];\n end\nend\n% realign\n%----------------------------------------------------------------\nspm_realign(P,flags);\n\nfor i = 1:numel(P)\n uweflags.sfP = sfP{i};\n\n % unwarp estimate\n %----------------------------------------------------------------\n tmpP = spm_vol(P{i}(1,:));\n uweflags.M = tmpP.mat;\n ds = spm_uw_estimate(P{i},uweflags);\n ads(i) = ds;\n [path,name] = fileparts(P{i}(1,:));\n pefile = fullfile(path,[name '_uw.mat']);\n\n if spm_matlab_version_chk('7') >= 0\n save(pefile,'-V6','ds');\n else\n save(pefile,'ds');\n end;\nend;\n% unwarp write - done at the single subject level since Batch\n% forwards one subjects data at a time for analysis, assuming\n% that subjects should be grouped as new spatial nodes. Sessions\n% should be within subjects.\n%----------------------------------------------------------------\nspm_uw_apply(ads,uwrflags);\nreturn;\n\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\n\nfunction vf = vfiles_rureslice(job)\nP = job.data;\nif numel(P)>0 && iscell(P(1).scans),\n P = cat(1,P(:).scans);\nend;\n\nswitch job.uwroptions.uwwhich(1),\n case 0,\n vf = {};\n case 2,\n vf = cell(numel(P),1);\n for i=1:length(vf),\n [pth,nam,ext,num] = spm_fileparts(P{i});\n vf{i} = fullfile(pth,['u', nam, ext, num]);\n end;\nend;\nif job.uwroptions.uwwhich(2),\n [pth,nam,ext,num] = spm_fileparts(P{1});\n vf = {vf{:}, fullfile(pth,['meanu', nam, ext, num])};\nend;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_surf.m", "ext": ".m", "path": "spm5-master/spm_surf.m", "size": 9530, "source_encoding": "utf_8", "md5": "10f87454cf682a1c4a3bac82b13549a0", "text": "function spm_surf(P,mode,thresh)\n% Surface extraction.\n% FORMAT spm_surf\n%\n% This surface extraction is not particularly sophisticated. It simply\n% smooths the data slightly and extracts the surface at a threshold of\n% 0.5. Optionally, a vector of thresholds can be supplied and a surface\n% will be extracted for each threshold. This does only work for extracted\n% surfaces, not for renderings.\n%\n% Inputs:\n% c1xxx.img & c2xxx.img - grey and white matter segments created\n% using the segmentation routine. These can be manually cleaned up\n% first using e.g., MRIcro.\n%\n% Outputs:\n% A \"render_xxx.mat\" file can be produced that can be used for\n% rendering activations on to.\n%\n% A \"surf_xxx.mat\" file can also be written, which is created using\n% Matlab's isosurface function.\n% This extracted brain surface can be viewed using code something\n% like:\n% FV = load(spm_select(1,'^surf_.*\\.mat$','Select surface data'));\n% fg = spm_figure('GetWin','Graphics');\n% ax = axes('Parent',fg);\n% p = patch(FV, 'Parent',ax,...\n% 'FaceColor', [0.8 0.7 0.7], 'FaceVertexCData', [],...\n% 'EdgeColor', 'none',...\n%\t 'FaceLighting', 'phong',...\n% 'SpecularStrength' ,0.7, 'AmbientStrength', 0.1,...\n%\t 'DiffuseStrength', 0.7, 'SpecularExponent', 10);\n% set(0,'CurrentFigure',fg);\n% set(fg,'CurrentAxes',ax);\n% l = camlight(-40, 20); \n% axis image;\n% rotate3d on;\n%\n%\n% The surface can also be save as OBJ format, as used by Alias|Wavefront.\n% See e.g. http://www.nada.kth.se/~asa/Ray/matlabobj.html\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_surf.m 660 2006-10-20 12:22:05Z volkmar $\n\n\nif nargin==0,\n [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Surface');\n\n\tSPMid = spm('FnBanner',mfilename,'$Rev: 660 $');\n\tspm_help('!ContextHelp',mfilename);\n\n\tP = spm_select([1 Inf],'image','Select images');\n\n\tmode = spm_input('Save','+1','m',...\n\t\t['Save Rendering|Save Extracted Surface|'...\n\t\t 'Save Rendering and Surface|Save Surface as OBJ format'],[1 2 3 4],3);\nelse\n CmdLine = 0;\n Finter = spm_figure('GetWin','Interactive');\nend;\n\nif nargin < 3\n thresh = .5;\nend;\n\nspm('FigName','Surface: working',Finter,CmdLine);\ndo_it(P,mode,thresh);\nspm('FigName','Surface: done',Finter,CmdLine);\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction do_it(P,mode,thresh)\n\nspm('Pointer','Watch')\n\nV = spm_vol(P);\nbr = zeros(V(1).dim(1:3));\nfor i=1:V(1).dim(3),\n\tB = spm_matrix([0 0 i]);\n\ttmp = spm_slice_vol(V(1),B,V(1).dim(1:2),1);\n\tfor j=2:length(V),\n\t\tM = V(j).mat\\V(1).mat*B;\n\t\ttmp = tmp + spm_slice_vol(V(j),M,V(1).dim(1:2),1);\n\tend;\n\tbr(:,:,i) = tmp;\nend;\n\n% Build a 3x3x3 seperable smoothing kernel and smooth\n%-----------------------------------------------------------------------\nkx=[0.75 1 0.75];\nky=[0.75 1 0.75];\nkz=[0.75 1 0.75];\nsm=sum(kron(kron(kz,ky),kx))^(1/3);\nkx=kx/sm; ky=ky/sm; kz=kz/sm;\nspm_conv_vol(br,br,kx,ky,kz,-[1 1 1]);\n\n[pth,nam,ext] = fileparts(V(1).fname);\n\nif any(mode==[1 3]),\n\t% Produce rendering\n\t%-----------------------------------------------------------------------\n\tmatname = fullfile(pth,['render_' nam '.mat']);\n\ttmp = struct('dat',br,'dim',size(br),'mat',V(1).mat);\n\trenviews(tmp,matname);\nend;\n\nif any(mode==[2 3 4]),\n\t% Produce extracted surface\n\t%-----------------------------------------------------------------------\n\ttmp = struct('dat',br,'dim',size(br),'mat',V(1).mat);\n for k=1:numel(thresh)\n [faces,vertices] = isosurface(br,thresh(k));\n\n % Swap around x and y because isosurface does for some\n % wierd and wonderful reason.\n Mat = V(1).mat(1:3,:)*[0 1 0 0;1 0 0 0;0 0 1 0; 0 0 0 1];\n vertices = (Mat*[vertices' ; ones(1,size(vertices,1))])';\n if numel(thresh)==1\n nam1 = nam;\n else\n nam1 = sprintf('%s-%d',nam,k);\n end;\n if any(mode==[2 3]),\n\t\tmatname = fullfile(pth,['surf_' nam1 '.mat']);\n\t\tif spm_matlab_version_chk('7.0') >=0,\n save(matname,'-V6','faces','vertices');\n\t\telse\n save(matname,'faces','vertices');\n\t\tend;\n end;\n if any(mode==[4]),\n\t\tfname = fullfile(pth,[nam1 '.obj']);\n\t\tfid = fopen(fname,'w');\n\t\tfprintf(fid,'# Created with SPM5 (%s v %s) on %s\\n', mfilename,'$Rev: 660 $',date);\n\t\tfprintf(fid,'v %.3f %.3f %.3f\\n',vertices');\n\t\tfprintf(fid,'g Cortex\\n'); % Group Cortex\n\t\tfprintf(fid,'f %d %d %d\\n',faces');\n\t\tfprintf(fid,'g\\n');\n\t\tfclose(fid);\n end;\n end;\nend;\nspm('Pointer')\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction renviews(V,oname)\n% Produce images for rendering activations to\n%\n% FORMAT renviews(V,oname)\n% V - mapped image to render, or alternatively\n% a structure of:\n% V.dat - 3D array\n% V.dim - size of 3D array\n% V.mat - affine mapping from voxels to millimeters\n% oname - the name of the render.mat file.\n%_______________________________________________________________________\n%\n% Produces a matrix file \"render_xxx.mat\" which contains everything that\n% \"spm_render\" is likely to need.\n%\n% Ideally, the input image should contain values in the range of zero\n% and one, and be smoothed slightly. A threshold of 0.5 is used to\n% distinguish brain from non-brain.\n%_______________________________________________________________________\n\nlinfun = inline('fprintf([''%-30s%s''],x,[repmat(sprintf(''\\b''),1,30)])','x');\nlinfun('Rendering: ');\n\nlinfun('Rendering: Transverse 1..'); rend{1} = make_struct(V,[pi 0 pi/2]);\nlinfun('Rendering: Transverse 2..'); rend{2} = make_struct(V,[0 0 pi/2]);\nlinfun('Rendering: Saggital 1..'); rend{3} = make_struct(V,[0 pi/2 pi]);\nlinfun('Rendering: Saggital 2..'); rend{4} = make_struct(V,[0 pi/2 0]);\nlinfun('Rendering: Coronal 1..'); rend{5} = make_struct(V,[pi/2 pi/2 0]);\nlinfun('Rendering: Coronal 2..'); rend{6} = make_struct(V,[pi/2 pi/2 pi]);\n\nlinfun('Rendering: Save..');\nif spm_matlab_version_chk('7') >=0\n\tsave(oname,'-V6','rend');\nelse\n\tsave(oname,'rend');\nend;\nlinfun(' ');\ndisp_renderings(rend);\nspm_print;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction str = make_struct(V,thetas)\n\t[D,M] = matdim(V.dim(1:3),V.mat,thetas);\n\t[ren,dep] = make_pic(V,M*V.mat,D);\n\tstr = struct('M',M,'ren',ren,'dep',dep);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [ren,zbuf]=make_pic(V,M,D)\n% A bit of a hack to try and make spm_render_vol produce some slightly\n% prettier output. It kind of works...\nif isfield(V,'dat'), vv = V.dat; else, vv = V; end;\n[REN, zbuf, X, Y, Z] = spm_render_vol(vv, M, D, [0.5 1]);\nfw = max(sqrt(sum(M(1:3,1:3).^2)));\nmsk = find(zbuf==1024);\nbrn = ones(size(X));\nbrn(msk) = 0;\nbrn = spm_conv(brn,fw);\nX(msk) = 0;\nY(msk) = 0;\nZ(msk) = 0;\nmsk = find(brn<0.5);\ntmp = brn;\ntmp(msk) = 100000;\nsX = spm_conv(X,fw)./tmp;\nsY = spm_conv(Y,fw)./tmp;\nsZ = spm_conv(Z,fw)./tmp;\nzbuf = spm_conv(zbuf,fw)./tmp;\nzbuf(msk) = 1024;\n\nvec = [-1 1 3]; % The direction of the lighting.\nvec = vec/norm(vec);\n[t,dx,dy,dz] = spm_sample_vol(vv,sX,sY,sZ,3);\nIM = inv(diag([0.5 0.5 1])*M(1:3,1:3))';\nren = IM(1:3,1:3)*[dx(:)' ; dy(:)' ; dz(:)'];\nlen = sqrt(sum(ren.^2,1))+eps;\nren = [ren(1,:)./len ; ren(2,:)./len ; ren(3,:)./len];\nren = reshape(vec*ren,[size(dx) 1]);\nren(find(ren<0)) = 0;\nren(msk) = ren(msk)-0.2;\nren = ren*0.8+0.2;\nmx = max(ren(:));\nren = ren/mx;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction disp_renderings(rend)\nFgraph = spm_figure('GetWin','Graphics');\nspm_results_ui('Clear',Fgraph);\nhght = 0.95;\nnrow = ceil(length(rend)/2);\nax=axes('Parent',Fgraph,'units','normalized','Position',[0, 0, 1, hght],'Visible','off');\nimage(0,'Parent',ax);\nset(ax,'YTick',[],'XTick',[]);\n\nfor i=1:length(rend),\n\tren = rend{i}.ren;\n\tax=axes('Parent',Fgraph,'units','normalized',...\n\t\t'Position',[rem(i-1,2)*0.5, floor((i-1)/2)*hght/nrow, 0.5, hght/nrow],...\n\t\t'Visible','off');\n\timage(ren*64,'Parent',ax);\n\tset(ax,'DataAspectRatio',[1 1 1], ...\n\t\t'PlotBoxAspectRatioMode','auto',...\n\t\t'YTick',[],'XTick',[],'XDir','normal','YDir','normal');\nend;\ndrawnow;\nreturn;\n%_______________________________________________________________________\nfunction [d,M] = matdim(dim,mat,thetas)\nR = spm_matrix([0 0 0 thetas]);\nbb = [[1 1 1];dim(1:3)];\nc = [ bb(1,1) bb(1,2) bb(1,3) 1\n bb(1,1) bb(1,2) bb(2,3) 1\n bb(1,1) bb(2,2) bb(1,3) 1\n bb(1,1) bb(2,2) bb(2,3) 1\n bb(2,1) bb(1,2) bb(1,3) 1\n bb(2,1) bb(1,2) bb(2,3) 1\n bb(2,1) bb(2,2) bb(1,3) 1\n bb(2,1) bb(2,2) bb(2,3) 1]';\ntc = diag([2 2 1 1])*R*mat*c;\ntc = tc(1:3,:)';\nmx = max(tc);\nmn = min(tc);\nM = spm_matrix(-mn(1:2))*diag([2 2 1 1])*R;\nd = ceil(abs(mx(1:2)-mn(1:2)))+1;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_write_sn.m", "ext": ".m", "path": "spm5-master/spm_write_sn.m", "size": 20095, "source_encoding": "utf_8", "md5": "165d7e8750b57d3108a160ea233ec808", "text": "function VO = spm_write_sn(V,prm,flags,extras)\n% Write Out Warped Images.\n% FORMAT VO = spm_write_sn(V,matname,flags,msk)\n% V - Images to transform (filenames or volume structure).\n% matname - Transformation information (filename or structure).\n% flags - flags structure, with fields...\n% interp - interpolation method (0-7)\n% wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences)\n% vox - voxel sizes (3 element vector - in mm)\n% Non-finite values mean use template vox.\n% bb - bounding box (2x3 matrix - in mm)\n% Non-finite values mean use template bb.\n% preserve - either 0 or 1. A value of 1 will \"modulate\"\n% the spatially normalised images so that total\n% units are preserved, rather than just\n% concentrations.\n% msk - An optional cell array for masking the spatially\n% normalised images (see below).\n%\n% Warped images are written prefixed by \"w\".\n%\n% Non-finite vox or bounding box suggests that values should be derived\n% from the template image.\n%\n% Don't use interpolation methods greater than one for data containing\n% NaNs.\n% _______________________________________________________________________\n%\n% FORMAT msk = spm_write_sn(V,matname,flags,'mask')\n% V - Images to transform (filenames or volume structure).\n% matname - Transformation information (filename or structure).\n% flags - flags structure, with fields...\n% wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences)\n% vox - voxel sizes (3 element vector - in mm)\n% Non-finite values mean use template vox.\n% bb - bounding box (2x3 matrix - in mm)\n% Non-finite values mean use template bb.\n% msk - a cell array for masking a series of spatially normalised\n% images.\n%\n%\n% _______________________________________________________________________\n%\n% FORMAT VO = spm_write_sn(V,prm,'modulate')\n% V - Spatially normalised images to modulate (filenames or\n% volume structure).\n% prm - Transformation information (filename or structure).\n%\n% After nonlinear spatial normalization, the relative volumes of some\n% brain structures will have decreased, whereas others will increase.\n% The resampling of the images preserves the concentration of pixel\n% units in the images, so the total counts from structures that have\n% reduced volumes after spatial normalization will be reduced by an\n% amount proportional to the volume reduction.\n%\n% This routine rescales images after spatial normalization, so that\n% the total counts from any structure are preserved. It was written\n% as an optional step in performing voxel based morphometry.\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_write_sn.m 1020 2007-12-06 20:20:31Z john $\n\n\nif isempty(V), return; end;\n\nif ischar(prm), prm = load(prm); end;\nif ischar(V), V = spm_vol(V); end;\n\nif nargin==3 && ischar(flags) && strcmpi(flags,'modulate'),\n if nargout==0,\n modulate(V,prm);\n else\n VO = modulate(V,prm);\n end;\n return;\nend;\n\ndef_flags = struct('interp',1,'vox',NaN,'bb',NaN,'wrap',[0 0 0],'preserve',0);\n[def_flags.bb, def_flags.vox] = bbvox_from_V(prm.VG(1));\n\nif nargin < 3,\n flags = def_flags;\nelse\n fnms = fieldnames(def_flags);\n for i=1:length(fnms),\n if ~isfield(flags,fnms{i}),\n flags.(fnms{i}) = def_flags.(fnms{i});\n end;\n end;\nend;\n\nif ~all(isfinite(flags.vox(:))), flags.vox = def_flags.vox; end;\nif ~all(isfinite(flags.bb(:))), flags.bb = def_flags.bb; end;\n\n[x,y,z,mat] = get_xyzmat(prm,flags.bb,flags.vox);\n\nif nargin==4,\n if ischar(extras) && strcmpi(extras,'mask'),\n VO = get_snmask(V,prm,x,y,z,flags.wrap);\n return;\n end;\n if iscell(extras),\n msk = extras;\n end;\nend;\n\nif nargout>0 && length(V)>8,\n error('Too many images to save in memory');\nend;\n\nif ~exist('msk','var')\n msk = get_snmask(V,prm,x,y,z,flags.wrap);\nend;\n\nif nargout==0,\n if isempty(prm.Tr),\n affine_transform(V,prm,x,y,z,mat,flags,msk);\n else\n nonlin_transform(V,prm,x,y,z,mat,flags,msk);\n end;\nelse\n if isempty(prm.Tr),\n VO = affine_transform(V,prm,x,y,z,mat,flags,msk);\n else\n VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk);\n end;\nend;\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction VO = affine_transform(V,prm,x,y,z,mat,flags,msk)\n\n[X,Y] = ndgrid(x,y);\nd = [flags.interp*[1 1 1]' flags.wrap(:)];\n\nspm_progress_bar('Init',numel(V),'Resampling','volumes completed');\nfor i=1:numel(V),\n VO = make_hdr_struct(V(i),x,y,z,mat);\n if flags.preserve\n VO.fname = prepend(VO.fname,'m');\n end\n detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat);\n if flags.preserve, VO.pinfo(1:2,:) = VO.pinfo(1:2,:)/detAff; end;\n\n %Dat= zeros(VO.dim(1:3));\n Dat = single(0);\n Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;\n\n C = spm_bsplinc(V(i),d);\n\n for j=1:length(z), % Cycle over planes\n [X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\\prm.VF.mat*prm.Affine);\n dat = spm_bsplins(C,X2,Y2,Z2,d);\n if flags.preserve, dat = dat*detAff; end;\n dat(msk{j}) = NaN;\n\n Dat(:,:,j) = single(dat);\n\n if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end;\n end;\n if nargout~=0,\n VO.pinfo = [1 0]';\n VO.dt = [spm_type('float32') spm_platform('bigend')];\n VO.dat = Dat;\n else\n spm_write_vol(VO, Dat);\n end;\n spm_progress_bar('Set',i);\nend;\nspm_progress_bar('Clear');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk)\n\n[X,Y] = ndgrid(x,y);\nTr = prm.Tr;\nBX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);\nBY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);\nBZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);\nif flags.preserve,\n DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff');\n DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff');\n DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff');\nend;\nd = [flags.interp*[1 1 1]' flags.wrap(:)];\n\nspm_progress_bar('Init',numel(V),'Resampling','volumes completed');\nfor i=1:numel(V),\n VO = make_hdr_struct(V(i),x,y,z,mat);\n if flags.preserve\n VO.fname = prepend(VO.fname,'m');\n end\n detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat);\n\n % Accumulate data\n %Dat= zeros(VO.dim(1:3));\n Dat = single(0);\n Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;\n\n C = spm_bsplinc(V(i),d);\n\n for j=1:length(z), % Cycle over planes\n % Nonlinear deformations\n %----------------------------------------------------------------------------\n tx = get_2Dtrans(Tr(:,:,:,1),BZ,j);\n ty = get_2Dtrans(Tr(:,:,:,2),BZ,j);\n tz = get_2Dtrans(Tr(:,:,:,3),BZ,j);\n X1 = X + BX*tx*BY';\n Y1 = Y + BX*ty*BY';\n Z1 = z(j) + BX*tz*BY';\n\n [X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\\prm.VF.mat*prm.Affine);\n dat = spm_bsplins(C,X2,Y2,Z2,d);\n dat(msk{j}) = NaN;\n\n if ~flags.preserve,\n Dat(:,:,j) = single(dat);\n else\n j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY';\n j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY';\n j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1;\n\n % The determinant of the Jacobian reflects relative volume changes.\n %------------------------------------------------------------------\n dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff;\n Dat(:,:,j) = single(dat);\n end;\n if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end;\n end;\n if nargout==0,\n if flags.preserve, VO = rmfield(VO,'pinfo'); end\n VO = spm_write_vol(VO,Dat);\n else\n VO.pinfo = [1 0]';\n VO.dt = [spm_type('float32') spm_platform('bigend')];\n VO.dat = Dat;\n end;\n spm_progress_bar('Set',i);\nend;\nspm_progress_bar('Clear');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction VO = modulate(V,prm)\n\nspm_progress_bar('Init',numel(V),'Modulating','volumes completed');\nfor i=1:numel(V),\n VO = V(i);\n VO = rmfield(VO,'pinfo');\n VO.fname = prepend(VO.fname,'m');\n detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat);\n %Dat = zeros(VO.dim(1:3));\n Dat = single(0);\n Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;\n [bb, vox] = bbvox_from_V(VO);\n [x,y,z,mat] = get_xyzmat(prm,bb,vox);\n\n if sum((mat(:)-VO.mat(:)).^2)>1e-7, error('Orientations not compatible'); end;\n\n Tr = prm.Tr;\n\n if isempty(Tr),\n for j=1:length(z), % Cycle over planes\n dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0);\n Dat(:,:,j) = single(dat);\n if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end;\n end;\n else\n BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);\n BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);\n BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);\n DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff');\n DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff');\n DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff');\n\n for j=1:length(z), % Cycle over planes\n\n tx = get_2Dtrans(Tr(:,:,:,1),BZ,j);\n ty = get_2Dtrans(Tr(:,:,:,2),BZ,j);\n tz = get_2Dtrans(Tr(:,:,:,3),BZ,j);\n\n j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY';\n j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY';\n j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1;\n\n % The determinant of the Jacobian reflects relative volume changes.\n %------------------------------------------------------------------\n dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0);\n dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff;\n Dat(:,:,j) = single(dat);\n\n if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end;\n end;\n end;\n\n if nargout==0,\n VO = spm_write_vol(VO,Dat);\n else\n VO.pinfo = [1 0]';\n VO.dt = [spm_type('float32') spm_platform('bigend')];\n VO.dat = Dat;\n end;\n spm_progress_bar('Set',i);\nend;\nspm_progress_bar('Clear');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction VO = make_hdr_struct(V,x,y,z,mat)\nVO = V;\nVO.fname = prepend(V.fname,'w');\nVO.mat = mat;\nVO.dim(1:3) = [length(x) length(y) length(z)];\nVO.pinfo = V.pinfo;\nVO.descrip = 'spm - 3D normalized';\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction T2 = get_2Dtrans(T3,B,j)\nd = [size(T3) 1 1 1];\ntmp = reshape(T3,d(1)*d(2),d(3));\nT2 = reshape(tmp*B(j,:)',d(1),d(2));\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction PO = prepend(PI,pre)\n[pth,nm,xt,vr] = spm_fileparts(deblank(PI));\nPO = fullfile(pth,[pre nm xt vr]);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction Mask = getmask(X,Y,Z,dim,wrp)\n% Find range of slice\ntiny = 5e-2;\nMask = true(size(X));\nif ~wrp(1), Mask = Mask & (X >= (1-tiny) & X <= (dim(1)+tiny)); end;\nif ~wrp(2), Mask = Mask & (Y >= (1-tiny) & Y <= (dim(2)+tiny)); end;\nif ~wrp(3), Mask = Mask & (Z >= (1-tiny) & Z <= (dim(3)+tiny)); end;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [X2,Y2,Z2] = mmult(X1,Y1,Z1,Mult)\nif length(Z1) == 1,\n X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + (Mult(1,3)*Z1 + Mult(1,4));\n Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + (Mult(2,3)*Z1 + Mult(2,4));\n Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + (Mult(3,3)*Z1 + Mult(3,4));\nelse\n X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4);\n Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4);\n Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4);\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [bb,vx] = bbvox_from_V(V)\nvx = sqrt(sum(V.mat(1:3,1:3).^2));\nif det(V.mat(1:3,1:3))<0, vx(1) = -vx(1); end;\n\no = V.mat\\[0 0 0 1]';\no = o(1:3)';\nbb = [-vx.*(o-1) ; vx.*(V.dim(1:3)-o)];\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction msk = get_snmask(V,prm,x,y,z,wrap)\n% Generate a mask for where there is data for all images\n%-----------------------------------------------------------------------\nmsk = cell(length(z),1);\nt1 = cat(3,V.mat);\nt2 = cat(1,V.dim);\nt = [reshape(t1,[16 length(V)])' t2(:,1:3)];\nTr = prm.Tr;\n[X,Y] = ndgrid(x,y);\n\nBX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);\nBY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);\nBZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);\n\nif numel(V)>1 && any(any(diff(t,1,1))),\n spm_progress_bar('Init',length(z),'Computing available voxels','planes completed');\n for j=1:length(z), % Cycle over planes\n Count = zeros(length(x),length(y));\n if isempty(Tr),\n % Generate a mask for where there is data for all images\n %----------------------------------------------------------------------------\n for i=1:numel(V),\n [X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\\prm.VF.mat*prm.Affine);\n Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap);\n end;\n else\n % Nonlinear deformations\n %----------------------------------------------------------------------------\n X1 = X + BX*get_2Dtrans(Tr(:,:,:,1),BZ,j)*BY';\n Y1 = Y + BX*get_2Dtrans(Tr(:,:,:,2),BZ,j)*BY';\n Z1 = z(j) + BX*get_2Dtrans(Tr(:,:,:,3),BZ,j)*BY';\n\n % Generate a mask for where there is data for all images\n %----------------------------------------------------------------------------\n for i=1:numel(V),\n [X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\\prm.VF.mat*prm.Affine);\n Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap);\n end;\n end;\n msk{j} = uint32(find(Count ~= numel(V)));\n spm_progress_bar('Set',j);\n end;\n spm_progress_bar('Clear');\nelse\n for j=1:length(z), msk{j} = uint32([]); end;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [x,y,z,mat] = get_xyzmat(prm,bb,vox)\n% The old voxel size and origin notation is used here.\n% This requires that the position and orientation\n% of the template is transverse. It would not be\n% straitforward to account for templates that are\n% in different orientations because the basis functions\n% would no longer be seperable. The seperable basis\n% functions mean that computing the deformation field\n% from the parameters is much faster.\n\n% bb = sort(bb);\n% vox = abs(vox);\n\nmsk = find(vox<0);\nbb = sort(bb);\nbb(:,msk) = flipud(bb(:,msk));\n\n% Adjust bounding box slightly - so it rounds to closest voxel.\n% Comment out if not needed. I chose not to change it because\n% it would lead to being bombarded by questions about spatially\n% normalised images not having the same dimensions.\nbb(:,1) = round(bb(:,1)/vox(1))*vox(1);\nbb(:,2) = round(bb(:,2)/vox(2))*vox(2);\nbb(:,3) = round(bb(:,3)/vox(3))*vox(3);\n\nM = prm.VG(1).mat;\nvxg = sqrt(sum(M(1:3,1:3).^2));\nif det(M(1:3,1:3))<0, vxg(1) = -vxg(1); end;\nogn = M\\[0 0 0 1]';\nogn = ogn(1:3)';\n\n% Convert range into range of voxels within template image\nx = (bb(1,1):vox(1):bb(2,1))/vxg(1) + ogn(1);\ny = (bb(1,2):vox(2):bb(2,2))/vxg(2) + ogn(2);\nz = (bb(1,3):vox(3):bb(2,3))/vxg(3) + ogn(3);\n\nog = -vxg.*ogn;\n\n% Again, chose whether to round to closest voxel.\nof = -vox.*(round(-bb(1,:)./vox)+1);\n%of = bb(1,:)-vox;\n\nM1 = [vxg(1) 0 0 og(1) ; 0 vxg(2) 0 og(2) ; 0 0 vxg(3) og(3) ; 0 0 0 1];\nM2 = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1];\nmat = prm.VG(1).mat*inv(M1)*M2;\n\nLEFTHANDED = true;\nif (LEFTHANDED && det(mat(1:3,1:3))>0) || (~LEFTHANDED && det(mat(1:3,1:3))<0),\n Flp = [-1 0 0 (length(x)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];\n mat = mat*Flp;\n x = flipud(x(:))';\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction VO = write_dets(P,bb,vox)\nif nargin==1,\n job = P;\n P = job.P;\n bb = job.bb;\n vox = job.vox;\nend;\n\nspm_progress_bar('Init',numel(P),'Writing','volumes completed');\n\nfor i=1:numel(V),\n prm = load(deblank(P{i}));\n [x,y,z,mat] = get_xyzmat(prm,bb,vox);\n Tr = prm.Tr;\n BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);\n BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);\n BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);\n DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff');\n DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff');\n DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff');\n\n [pth,nam,ext,nm] = spm_fileparts(P{i});\n VO = struct('fname',fullfile(pth,['jy_' nam ext nm]),...\n 'dim',[numel(x),numel(y),numel(z)],...\n 'dt',[spm_type('float32') spm_platform('bigend')],...\n 'pinfo',[1 0 0]',...\n 'mat',mat,...\n 'n',1,...\n 'descrip','Jacobian determinants');\n VO = spm_create_vol(VO);\n detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat);\n Dat = single(0);\n Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;\n\n for j=1:length(z), % Cycle over planes\n % Nonlinear deformations\n tx = get_2Dtrans(Tr(:,:,:,1),BZ,j);\n ty = get_2Dtrans(Tr(:,:,:,2),BZ,j);\n tz = get_2Dtrans(Tr(:,:,:,3),BZ,j);\n\n %----------------------------------------------------------------------------\n j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY';\n j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY';\n j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1;\n % The determinant of the Jacobian reflects relative volume changes.\n %------------------------------------------------------------------\n dat = (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff;\n Dat(:,:,j) = single(dat);\n if numel(P)<5, spm_progress_bar('Set',i-1+j/length(z)); end;\n end;\n VO = spm_write_vol(VO,Dat);\n spm_progress_bar('Set',i);\nend;\nspm_progress_bar('Clear');\nreturn;\n%_______________________________________________________________________\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_DesMtx.m", "ext": ".m", "path": "spm5-master/spm_DesMtx.m", "size": 30975, "source_encoding": "utf_8", "md5": "fbbb25a149ba004e3f50c2089f236004", "text": "function [X,Pnames,Index,idx,jdx,kdx]=spm_DesMtx(varargin);\n% Design matrix construction from factor level and covariate vectors\n% FORMAT [X,Pnames] = spm_DesMtx( list)\n% FORMAT [X,Pnames,Index,idx,jdx,kdx] = spm_DesMtx(FCLevels,Constraint,FCnames)\n%\n% \n% - set of arguments specifying a portion of design matrix (see below)\n% - FCnames parameter, or Constraint and FCnames parameters, are optional\n% - a list of multiple triples can be\n% \t specified, where FCnames or Constraint-FCnames may be omitted\n% \t within any triple. The program then works recursively.\n%\n% X - design matrix\n% Pnames - paramater names as (constructed from FCnames) - a cellstr\n% Index - integer index of factor levels\n% - only returned when computing a single design matrix partition\n%\n% idx,jdx,kdx - reference vectors mapping I & Index (described below)\n% - only returned when computing a single design matrix partition\n% for unconstrained factor effects ('-' or '~')\n%\n% ----------------\n% - Utilities:\n%\n% FORMAT i = spm_DesMtx('pds',v,m,n)\n% Patterned data setting function - inspired by MINITAB's \"SET\" command\n% v - base pattern vector\n% m - (scalar natural number) #replications of elements of v [default 1]\n% n - (scalar natural number) #repeats of pattern [default 1]\n% i - resultant pattern vector, with v's elements replicated m times,\n% the resulting vector repeated n times.\n%\n% FORMAT [nX,nPnames] = spm_DesMtx('sca',X1,Pnames1,X2,Pnames2,...)\n% Produces a scaled design matrix nX with max(abs(nX(:))<=1, suitable\n% for imaging with: image((nX+1)*32)\n% X1,X2,... - Design matrix partitions\n% Pnames1, Pnames2,... - Corresponding parameter name string mtx/cellstr (opt)\n% nX - Scaled design matrix\n% nPnames - Concatenated parameter names for columns of nX\n%\n% FORMAT Fnames = spm_DesMtx('Fnames',Pnames)\n% Converts parameter names into suitable filenames\n% Pnames - string mtx/cellstr containing parameter names\n% Fnames - filenames derived from Pnames. (cellstr)\n%\n% FORMAT TPnames = spm_DesMtx('TeXnames',Pnames)\n% Removes '*'s and '@'s from Pnames, so TPnames suitable for TeX interpretation\n% Pnames - string mtx/cellstr containing parameter names\n% TPnames - TeX-ified parameter names\n%\n% FORMAT Map = spm_DesMtx('ParMap',aMap)\n% Returns Nx2 cellstr mapping (greek TeX) parameters to English names,\n% using the notation established in the SPMcourse notes.\n% aMap - (optional) Mx2 cellstr of additional or over-ride mappings\n% Map - cellstr of parameter names (col1) and corresponding English names (col2)\n%\n% FORMAT EPnames = spm_DesMtx('ETeXnames',Pnames,aMap)\n% Translates greek (TeX) parameter names into English using mapping given by\n% spm_DesMtx('ParMap',aMap)\n% Pnames - string mtx/cellstr containing parameter names\n% aMap - (optional) Mx2 cellstr of additional or over-ride mappings\n% EPnames - cellstr of converted parameter names\n%_______________________________________________________________________\n%\n% Returns design matrix corresponding to given vectors containing\n% levels of a factor; two way interactions; covariates (n vectors);\n% ready-made sections of design matrix; and factor by covariate\n% interactions.\n%\n% The specification for the design matrix is passed in sets of arguments,\n% each set corresponding to a particular Factor/Covariate/&c., specifying\n% a section of the design matrix. The set of arguments consists of the \n% FCLevels matrix (Factor/Covariate levels), an optional constraint string,\n% and an optional (string) name matrix containing the names of the \n% Factor/Covariate/&c.\n%\n% MAIN EFFECTS: For a main effect, or single factor, the FCLevels\n% matrix is an integer vector whose values represent the levels of the\n% factor. The integer factor levels need not be positive, nor in\n% order. In the '~' constraint types (below), a factor level of zero\n% is ignored (treated as no effect), and no corresponding column of\n% design matrix is created. Effects for the factor levels are entered\n% into the design matrix *in increasing order* of the factor levels.\n% Check Pnames to find out which columns correspond to which levels of\n% the factor.\n%\n% TWO WAY INTERACTIONS: For a two way interaction effect between two\n% factors, the FCLevels matrix is an nx2 integer matrix whose columns\n% indicate the levels of the two factors. An effect is included for\n% each unique combination of the levels of the two factors. Again,\n% factor levels must be integer, though not necessarily positive.\n% Zero levels are ignored in the '~' constraint types described below.\n%\n% CONSTRAINTS: Each FactorLevels vector/matrix may be followed by an \n% (optional) ConstraintString.\n%\n% ConstraintStrings for main effects are:\n% '-' - No Constraint\n% '~' - Ignore zero level of factor\n% (I.e. cornerPoint constraint on zero level,\n% (same as '.0', except zero level is always ignored,\n% (even if factor only has zero level, in which case\n% (an empty DesMtx results and a warning is given\n% '+0' - sum-to-zero constraint\n% '+0m' - Implicit sum-to-zero constraint\n% '.' - CornerPoint constraint\n% '.0' - CornerPoint constraint applied to zero factor level\n% (warns if there is no zero factor level)\n% Constraints for two way interaction effects are\n% '-' - No Constraints\n% '~' - Ignore zero level of any factor\n% (I.e. cornerPoint constraint on zero level,\n% (same as '.ij0', except zero levels are always ignored\n% '+i0','+j0','+ij0' - sum-to-zero constraints\n% '.i', '.j', '.ij' - CornerPoint constraints\n% '.i0','.j0','.ij0' - CornerPoint constraints applied to zero factor level\n% (warns if there is no zero factor level)\n% '+i0m', '+j0m' - Implicit sum-to-zero constraints\n%\n% With the exception of the \"ignore zero\" '~' constraint, constraints\n% are only applied if there are sufficient factor levels. CornerPoint\n% and explicit sum-to-zero Constraints are applied to the last level of\n% the factor.\n%\n% The implicit sum-to-zero constraints \"mean correct\" appropriate rows\n% of the relevant design matrix block. For a main effect, constraint\n% '+0m' \"mean corrects\" the main effect block across columns,\n% corresponding to factor effects B_i, where B_i = B'_i - mean(B'_i) :\n% The B'_i are the fitted parameters, effectively *relative* factor\n% parameters, relative to their mean. This leads to a rank deficient\n% design matrix block. If Matlab's pinv, which implements a\n% Moore-Penrose pseudoinverse, is used to solve the least squares\n% problem, then the solution with smallest L2 norm is found, which has\n% mean(B'_i)=0 provided the remainder of the design is unique (design\n% matrix blocks of full rank). In this case therefore the B_i are\n% identically the B'_i - the mean correction imposes the constraint.\n% \n%\n% COVARIATES: The FCLevels matrix here is an nxc matrix whose columns\n% contain the covariate values. An effect is included for each covariate.\n% Covariates are identified by ConstraintString 'C'.\n%\n%\n% PRE-SPECIFIED DESIGN BLOCKS: ConstraintString 'X' identifies a\n% ready-made bit of design matrix - the effect is the same as 'C'.\n%\n%\n% FACTOR BY COVARIATE INTERACTIONS: are identified by ConstraintString\n% 'FxC'. The last column is understood to contain the covariate. Other\n% columns are taken to contain integer FactorLevels vectors. The\n% (unconstrained) interaction of the factors is interacted with the\n% covariate. Zero factor levels are ignored if ConstraintString '~FxC'\n% is used.\n%\n%\n% NAMES: Each Factor/Covariate can be 'named', by passing a name\n% string. Pass a string matrix, or cell array (vector) of strings,\n% with rows (cells) naming the factors/covariates in the respective\n% columns of the FCLevels matrix. These names default to , ,\n% , &c., and are used in the construction of the Pnames\n% parameter names.\n% E.g. for an interaction, spm_DesMtx([F1,F2],'+ij0',['subj';'cond'])\n% giving parameter names such as subj*cond_{1,2} etc...\n%\n% Pnames returns a string matrix whose successive rows describe the\n% effects parameterised in the corresponding columns of the design\n% matrix. `Fac1*Fac2_{2,3}' would refer to the parameter for the\n% interaction of the two factors Fac1 & Fac2, at the 2nd level of the\n% former and the 3rd level of the latter. Other forms are\n% - Simple main effect (level 1) : _{1}\n% - Three way interaction (level 1,2,3) : **_{1,2,3}\n% - Two way factor interaction by covariate interaction :\n% : @*_{1,1}\n% - Column 3 of prespecified DesMtx block (if unnamed)\n% : [1]\n% The special characters `_*()[]{}' are recognised by the scaling\n% function (spm_DesMtx('sca',...), and should therefore be avoided\n% when naming effects and covariates.\n%\n%\n% INDEX: An Integer Index matrix is returned if only a single block of\n% design matrix is being computed (single set of parameters). It\n% indexes the actual order of the effect levels in the design matrix block.\n% (Factor levels are introduced in order, regardless of order of\n% appearence in the factor index matrices, so that the parameters\n% vector has a sensible order.) This is used to aid recursion.\n%\n% Similarly idx,jdx & kdx are indexes returned for a single block of\n% design matrix consisting of unconstrained factor effects ('-' or '~').\n% These indexes map I and Index (in a similar fashion to the `unique`\n% function) as follows:\n% - idx & jdx are such that I = Index(:,jdx)' and Index = I(idx,:)'\n% where vector I is given as a column vector\n% - If the \"ignore zeros\" constraint '~' is used, then kdx indexes the\n% non-zero (combinations) of factor levels, such that\n% I(kdx,:) = Index(:,jdx)' and Index == I(kdx(idx),:)'\n%\n% ----------------\n%\n% The \"patterned data setting\" (spm_DesMtx('pds'...) is a simple\n% utility for setting patterned indicator vectors, inspired by\n% MINITAB's \"SET\" command.\n%\n% The vector v has it's elements replicated m times, and the resulting\n% vector is itself repeated n times, giving a resultant vector i of\n% length n*m*length(v)\n%\n% Examples:\n% spm_DesMtx('pds',1:3) % = [1,2,3]\n% spm_DesMtx('pds',1:3,2) % = [1,1,2,2,3,3]\n% spm_DesMtx('pds',1:3,2,3) % = [1,1,2,2,3,3,1,1,2,2,3,3,1,1,2,2,3,3]\n% NB: MINITAB's \"SET\" command has syntax n(v)m:\n%\n% ----------------\n%\n% The design matrix scaling feature is designed to return a scaled\n% version of a design matrix, with values in [-1,1], suitable for\n% visualisation. Special care is taken to apply the same normalisation\n% to blocks of design matrix reflecting a single effect, to preserve\n% appropriate relationships between columns. Identification of effects\n% corresponding to columns of design matrix portions is via the parameter\n% names matrices. The design matrix may be passed in any number of\n% parts, provided the corresponding parameter names are given. It is\n% assummed that the block representing an effect is contained within a\n% single partition. Partitions supplied without corresponding parameter\n% names are scaled on a column by column basis, the parameters labelled as\n% in the returned nPnames matrix.\n% \n% Effects are identified using the special characters `_*()[]{}' used in\n% parameter naming as follows: (here ? is a wildcard)\n% - ?(?) - general block (column normalised)\n% - ?[?] - specific block (block normalised)\n% - ?_{?} - main effect or interaction of main effects\n% - ?@?_{?} - factor by covariate interaction\n% Blocks are identified by looking for runs of parameters of the same type\n% with the same names: E.g. a block of main effects for factor 'Fac1'\n% would have names like Fac1_{?}.\n% \n% Scaling is as follows:\n% * fMRI blocks are scaled around zero to lie in [-1,1]\n% * No scaling is carried out if max(abs(tX(:))) is in [.4,1]\n% This protects dummy variables from normalisation, even if\n% using implicit sum-to-zero constraints.\n% * If the block has a single value, it's replaced by 1's\n% * FxC blocks are normalised so the covariate values cover [-1,1]\n% but leaving zeros as zero.\n% * Otherwise, block is scaled to cover [-1,1].\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Andrew Holmes\n% $Id: spm_DesMtx.m 112 2005-05-04 18:20:52Z john $\n\n\n\n%-Parse arguments for recursive construction of design matrices\n%=======================================================================\nif nargin==0 error('Insufficient arguments'), end\n\nif ischar(varargin{1})\n\t%-Non-recursive action string usage\n\tConstraint=varargin{1};\nelseif nargin>=2 & ~(ischar(varargin{2}) | iscell(varargin{2}))\n\t[X1,Pnames1]=spm_DesMtx(varargin{1});\n\t[X2,Pnames2]=spm_DesMtx(varargin{2:end});\n\tX=[X1,X2]; Pnames=[Pnames1;Pnames2];\n\treturn\nelseif nargin>=3 & ~(ischar(varargin{3}) | iscell(varargin{3}))\n\t[X1,Pnames1]=spm_DesMtx(varargin{1:2});\n\t[X2,Pnames2]=spm_DesMtx(varargin{3:end});\n\tX=[X1,X2]; Pnames=[Pnames1;Pnames2];\n\treturn\nelseif nargin>=4\n\t[X1,Pnames1]=spm_DesMtx(varargin{1:3});\n\t[X2,Pnames2]=spm_DesMtx(varargin{4:end});\n\tX=[X1,X2]; Pnames=[Pnames1;Pnames2];\n\treturn\nelse\n\t%-If I is a vector, make it a column vector\n\tI=varargin{1}; if size(I,1)==1, I=I'; end\n\t%-Sort out constraint and Factor/Covariate name parameters\n\tif nargin<2, Constraint='-'; else, Constraint=varargin{2}; end\n\tif isempty(I), Constraint='mt'; end\n\tif nargin<3, FCnames={}; else, FCnames=varargin{3}; end\n\tif char(FCnames), FCnames=cellstr(FCnames); end\nend\n\n\n\nswitch Constraint, case 'mt' %-Empty I case\n%=======================================================================\nX = [];\nPnames = {};\nIndex = [];\n\n\n\ncase {'C','X'} %-Covariate effect, or ready-made design matrix\n%=======================================================================\n%-I contains a covariate (C), or is to be inserted \"as is\" (X)\nX = I;\n\n%-Construct parameter name index\n%-----------------------------------------------------------------------\nif isempty(FCnames)\n\tif strcmp(Constraint,'C'), FCnames={''}; else, FCnames={''}; end\nend\n\nif length(FCnames)==1 & size(X,2)>1\n\tPnames = cell(size(X,2),1);\n\tfor i=1:size(X,2)\n\t\tPnames{i} = sprintf('%s [%d]',FCnames{1},i);\n\tend\nelseif length(FCnames)~=size(X,2)\n\terror('FCnames doesn''t match covariate/X matrix')\nelse\n\tPnames = FCnames;\nend\n\n\n\ncase {'-(1)','~(1)'} %-Simple main effect ('~' ignores zero levels)\n%=======================================================================\n%-Sort out arguments\n%-----------------------------------------------------------------------\nif size(I,2)>1, error('Simple main effect requires vector index'), end\nif any(I~=floor(I)), error('Non-integer indicator vector'), end\nif isempty(FCnames), FCnames = {''};\nelseif length(FCnames)>1, error('Too many FCnames'), end\n\nnXrows = size(I,1);\n\n% Sort out unique factor levels - ignore zero level in '~(1)' usage\n%-----------------------------------------------------------------------\nif Constraint(1)~='~'\n\t[Index,idx,jdx] = unique(I');\n\tkdx = [1:nXrows];\nelse\n\t[Index,idx,jdx] = unique(I(I~=0)');\n\tkdx = find(I~=0)';\n\tif isempty(Index)\n\t\tX=[]; Pnames={}; Index=[];\n\t\twarning(['factor has only zero level - ',...\n\t\t\t'returning empty DesMtx partition'])\n\t\treturn\n\tend\nend\n\n%-Set up unconstrained X matrix & construct parameter name index\n%-----------------------------------------------------------------------\nnXcols = length(Index);\n\n%-Columns in ascending order of corresponding factor level\nX = zeros(nXrows,nXcols);\nPnames = cell(nXcols,1);\nfor ii=1:nXcols\t\t\t%-ii indexes i in Index\n\tX(:,ii) = I==Index(ii);\n\t%-Can't use: for i=Index, X(:,i) = I==i; end\n\t% in case Index has holes &/or doesn't start at 1!\n\tPnames{ii} = sprintf('%s_{%d}',FCnames{1},Index(ii));\nend\n%-Don't append effect level if only one level\nif nXcols==1, Pnames=FCnames; end\n\n\ncase {'-','~'} %-Main effect / interaction ('~' ignores zero levels)\n%=======================================================================\nif size(I,2)==1\n\t%-Main effect - process directly\n\t[X,Pnames,Index,idx,jdx,kdx] = spm_DesMtx(I,[Constraint,'(1)'],FCnames);\n\treturn\nend\n\nif any((I(:))~=floor(I(:))), error('Non-integer indicator vector'), end\n\n% Sort out unique factor level combinations & build design matrix\n%-----------------------------------------------------------------------\n%-Make \"raw\" index to unique effects\nnI = I - ones(size(I,1),1)*min(I);\ntmp = max(I)-min(I)+1;\ntmp = [fliplr(cumprod(tmp(end:-1:2))),1];\nrIndex = sum(nI.*(ones(size(I,1),1)*tmp),2)+1;\n\n%-Ignore combinations where any factor has level zero in '~' usage\nif Constraint(1)=='~'\n\trIndex(any(I==0,2))=0;\n\tif all(rIndex==0)\n\t\tX=[]; Pnames={}; Index=[];\n\t\twarning(['no non-zero factor level combinations - ',...\n\t\t\t'returning empty DesMtx partition'])\n\t\treturn\n\tend\nend\n\n%-Build design matrix based on unique factor combinations\n[X,null,sIndex,idx,jdx,kdx]=spm_DesMtx(rIndex,[Constraint,'(1)']);\n\n%-Sort out Index matrix\nIndex = I(kdx(idx),:)';\n\n%-Construct parameter name index\n%-----------------------------------------------------------------------\nif isempty(FCnames)\n\ttmp = ['',sprintf('*',2:size(I,2))];\nelseif length(FCnames)==size(I,2)\n\ttmp = [FCnames{1},sprintf('*%s',FCnames{2:end})];\nelse\n\terror('#FCnames mismatches #Factors in interaction')\nend\n\nPnames = cell(size(Index,2),1);\nfor c = 1:size(Index,2)\n Pnames{c} = ...\n\t[sprintf('%s_{%d',tmp,Index(1,c)),sprintf(',%d',Index(2:end,c)),'}'];\nend\n\n\n\ncase {'FxC','-FxC','~FxC'} %-Factor dependent covariate effect\n% ('~' ignores zero factor levels)\n%=======================================================================\n%-Check\n%-----------------------------------------------------------------------\nif size(I,2)==1, error('FxC requires multi-column I'), end\n\nF = I(:,1:end-1);\nC = I(:,end);\n\nif ~all(all(F==floor(F),1),2)\n\terror('non-integer indicies in F partition of FxC'), end\n\nif isempty(FCnames)\n\tFnames = '';\n\tCnames = '';\nelseif length(FCnames)==size(I,2)\n\tFnames = FCnames(1:end-1);\n\tCnames = FCnames{end};\nelse\n\terror('#FCnames mismatches #Factors+#Cov in FxC')\nend\n\n%-Set up design matrix X & names matrix - ignore zero levels if '~FxC' use\n%-----------------------------------------------------------------------\nif Constraint(1)~='~',\t[X,Pnames,Index] = spm_DesMtx(F,'-',Fnames);\n\telse,\t\t[X,Pnames,Index] = spm_DesMtx(F,'~',Fnames); end\nX = X.*(C*ones(1,size(X,2)));\nPnames = cellstr([repmat([Cnames,'@'],size(Index,2),1),char(Pnames)]);\n\n\n\ncase {'.','.0','+0','+0m'} %-Constrained simple main effect\n%=======================================================================\n\nif size(I,2)~=1, error('Simple main effect requires vector index'), end\n\n[X,Pnames,Index] = spm_DesMtx(I,'-(1)',FCnames);\n\n%-Impose constraint if more than one effect\n%-----------------------------------------------------------------------\n%-Apply uniqueness constraints ('.' & '+0') to last effect, which is\n% in last column, since column i corresponds to level Index(i)\n%-'.0' corner point constraint is applied to zero factor level only\nnXcols = size(X,2);\nzCol = find(Index==0);\nif nXcols==1 & ~strcmp(Constraint,'.0')\n\terror('only one level: can''t constrain')\nelseif strcmp(Constraint,'.')\n\tX(:,nXcols)=[];\tPnames(nXcols)=[]; Index(nXcols)=[];\nelseif strcmp(Constraint,'.0')\n\tzCol = find(Index==0);\n\tif isempty(zCol),\twarning('no zero level to constrain')\n\telseif nXcols==1,\terror('only one level: can''t constrain'), end\n\tX(:,zCol)=[];\tPnames(zCol)=[]; Index(zCol)=[];\nelseif strcmp(Constraint,'+0')\n\tX(find(X(:,nXcols)),:)=-1;\n\tX(:,nXcols)=[];\tPnames(nXcols)=[]; Index(nXcols)=[];\nelseif strcmp(Constraint,'+0m')\n\tX = X - 1/nXcols;\nend\n\n\n\ncase {'.i','.i0','.j','.j0','.ij','.ij0','+i0','+j0','+ij0','+i0m','+j0m'}\n %-Two way interaction effects\n%=======================================================================\nif size(I,2)~=2, error('Two way interaction requires Nx2 index'), end\n\n[X,Pnames,Index] = spm_DesMtx(I,'-',FCnames);\n\n%-Implicit sum to zero\n%-----------------------------------------------------------------------\nif any(strcmp(Constraint,{'+i0m','+j0m'}))\n\tSumIToZero = strcmp(Constraint,'+i0m');\n\tSumJToZero = strcmp(Constraint,'+j0m');\n\n\tif SumIToZero\t%-impose implicit SumIToZero constraints\n\t\tJs = sort(Index(2,:)); Js = Js([1,1+find(diff(Js))]);\n\t\tfor j = Js\n\t\t\trows = find(I(:,2)==j);\n\t\t\tcols = find(Index(2,:)==j);\n\t\t\tif length(cols)==1\n\t\t\t error('Only one level: Can''t constrain')\n\t\t\tend\n\t\t\tX(rows,cols) = X(rows,cols) - 1/length(cols);\n\t\tend\n\tend\n\n\tif SumJToZero\t%-impose implicit SumJToZero constraints\n\t\tIs = sort(Index(1,:)); Is = Is([1,1+find(diff(Is))]);\n\t\tfor i = Is\n\t\t\trows = find(I(:,1)==i);\n\t\t\tcols = find(Index(1,:)==i);\n\t\t\tif length(cols)==1\n\t\t\t error('Only one level: Can''t constrain')\n\t\t\tend\n\t\t\tX(rows,cols) = X(rows,cols) - 1/length(cols);\n\t\tend\n\tend\n\n%-Explicit sum to zero\n%-----------------------------------------------------------------------\nelseif any(strcmp(Constraint,{'+i0','+j0','+ij0'}))\n\tSumIToZero = any(strcmp(Constraint,{'+i0','+ij0'}));\n\tSumJToZero = any(strcmp(Constraint,{'+j0','+ij0'}));\n\n\tif SumIToZero\t%-impose explicit SumIToZero constraints\n\t\ti = max(Index(1,:));\n\t\tif i==min(Index(1,:))\n\t\t\terror('Only one i level: Can''t constrain'), end\n\t\tcols = find(Index(1,:)==i); %-columns to delete\n\t\tfor c=cols\n\t\t\tj=Index(2,c);\n\t\t\tt_cols=find(Index(2,:)==j);\n\t\t\tt_rows=find(X(:,c));\n\t\t\t%-This ij equals -sum(ij) over other i\n\t\t\t% (j fixed for this col c).\n\t\t\t%-So subtract weight of this ij factor from\n\t\t\t% weights for all other ij factors for this j\n\t\t\t% to impose the constraint.\n\t\t\tX(t_rows,t_cols) = X(t_rows,t_cols)...\n\t\t\t -X(t_rows,c)*ones(1,length(t_cols));\n%-( Next line would do it, but only first time round, when all )\n% ( weights are 1, and only one weight per row for this j. )\n% X(t_rows,t_cols)=-1*ones(length(t_rows),length(t_cols));\n\t\tend\n\t\t%-delete columns\n\t\tX(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];\n\tend\n\n\tif SumJToZero\t%-impose explicit SumJToZero constraints\n\t\tj = max(Index(2,:));\n\t\tif j==min(Index(2,:))\n\t\t\terror('Only one j level: Can''t constrain'), end\n\t\tcols=find(Index(2,:)==j);\n\t\tfor c=cols\n\t\t\ti=Index(1,c);\n\t\t\tt_cols=find(Index(1,:)==i);\n\t\t\tt_rows=find(X(:,c));\n\t\t\tX(t_rows,t_cols) = X(t_rows,t_cols)...\n\t\t\t -X(t_rows,c)*ones(1,length(t_cols));\n\t\tend\n\t\t%-delete columns\n\t\tX(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];\n\tend\n\n%-Corner point constraints\n%-----------------------------------------------------------------------\nelseif any(strcmp(Constraint,{'.i','.i0','.j','.j0','.ij','.ij0'}))\n\tCornerPointI = any(strcmp(Constraint,{'.i','.i0','.ij','.ij0'}));\n\tCornerPointJ = any(strcmp(Constraint,{'.j','.j0','.ij','.ij0'}));\n\n\tif CornerPointI\t%-impose CornerPointI constraints\n\t\tif Constraint(end)~='0',\ti = max(Index(1,:));\n\t\t\telse,\t\t\ti = 0; end\n\t\tcols=find(Index(1,:)==i); %-columns to delete\n\t\tif isempty(cols)\n\t\t\twarning('no zero i level to constrain')\n\t\telseif all(Index(1,:)==i)\n\t\t\terror('only one i level: can''t constrain')\n\t\tend\n\t\t%-delete columns\n\t\tX(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];\n\tend\n\n\tif CornerPointJ\t%-impose CornerPointJ constraints\n\t\tif Constraint(end)~='0',\tj = max(Index(2,:));\n\t\t\telse,\t\t\tj = 0; end\n\t\tcols=find(Index(2,:)==j);\n\t\tif isempty(cols)\n\t\t\twarning('no zero j level to constrain')\n\t\telseif all(Index(2,:)==j)\n\t\t\terror('only one j level: can''t constrain')\n\t\tend\n\t\tX(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];\n\tend\nend\n\n\ncase {'PDS','pds'} %-Patterned data set utility\n%=======================================================================\n% i = spm_DesMtx('pds',v,m,n)\nif nargin<4, n=1; else, n=varargin{4}; end\nif nargin<3, m=1; else, m=varargin{3}; end\nif nargin<2, varargout={[]}, return, else, v=varargin{2}; end\nif any([size(n),size(m)])>1, error('n & m must be scalars'), end\nif any(([m,n]~=floor([m,n]))|([m,n]<1))\n\terror('n & m must be natural numbers'), end\nif sum(size(v)>1)>1, error('v must be a vector'), end\n\n%-Computation\n%-----------------------------------------------------------------------\nsi = ones(1,ndims(v)); si(find(size(v)>1))=n*m*length(v);\nX = reshape(repmat(v(:)',m,n),si);\n\n\n\ncase {'Sca','sca'} %-Scale DesMtx for imaging\n%=======================================================================\nnX = []; nPnames = {}; Carg = 2;\n\n%-Loop through the arguments accumulating scaled design matrix nX\n%-----------------------------------------------------------------------\nwhile(Carg <= nargin)\n rX = varargin{Carg}; Carg=Carg+1;\n if Carg<=nargin & ~isempty(varargin{Carg}) & ...\n \t\t(ischar(varargin{Carg}) | iscellstr(varargin{Carg}))\n\trPnames = char(varargin{Carg}); Carg=Carg+1;\n else\t%-No names to work out blocks from - normalise by column\n\trPnames = repmat('',size(rX,2),1);\n end\n %-Pad out rPnames with 20 spaces to permit looking past line ends\n rPnames = [rPnames,repmat(' ',size(rPnames,1),20)];\n\n\n while(~isempty(rX))\n\tif size(rX,2)>1 & max([1,find(rPnames(1,:)=='(')]) < ...\n\t\t\t\t\tmax([0,find(rPnames(1,:)==')')])\n\t%-Non-specific block: find the rest & column normalise round zero\n\t%===============================================================\n\t\tc1 = max(find(rPnames(1,:)=='('));\n\t\td = any(diff(abs(rPnames(:,1:c1))),2)...\n\t\t\t| ~any(rPnames(2:end,c1+1:end)==')',2);\n\t\tt = min(find([d;1]));\n\n\t\t%-Normalise columns of block around zero\n\t\t%-------------------------------------------------------\n\t\ttmp = size(nX,2);\n\t\tnX = [nX, zeros(size(rX,1),t)];\n\t\tfor i=1:t, nX(:,tmp+i) = rX(:,i)/max(abs(rX(:,i))); end\n\t\tnPnames = [nPnames; cellstr(rPnames(1:t,:))];\n\t\trX(:,1:t) = []; rPnames(1:t,:)=[];\n\n\n\telseif size(rX,2)>1 & max([1,find(rPnames(1,:)=='[')]) < ...\n\t\t\t\t\tmax([0,find(rPnames(1,:)==']')])\n\t%-Block: find the rest & normalise together\n\t%===============================================================\n\t\tc1 = max(find(rPnames(1,:)=='['));\n\t\td = any(diff(abs(rPnames(:,1:c1))),2)...\n\t\t\t| ~any(rPnames(2:end,c1+1:end)==']',2);\n\t\tt = min(find([d;1]));\n\n\t\t%-Normalise block\n\t\t%-------------------------------------------------------\n\t\tnX = [nX,sf_tXsca(rX(:,1:t))];\n\t\tnPnames = [nPnames; cellstr(rPnames(1:t,:))];\n\t\trX(:,1:t) = []; rPnames(1:t,:)=[];\n\n\n\telseif size(rX,2)>1 & max([1,findstr(rPnames(1,:),'_{')]) < ...\n\t\t\t\t\tmax([0,find(rPnames(1,:)=='}')])\n\t%-Factor, interaction of factors, or FxC: find the rest...\n\t%===============================================================\n\t\tc1 = max(findstr(rPnames(1,:),'_{'));\n\t\td = any(diff(abs(rPnames(:,1:c1+1))),2)...\n\t\t\t| ~any(rPnames(2:end,c1+2:end)=='}',2);\n\t\tt = min(find([d;1]));\n\n\t\t%-Normalise block\n\t\t%-------------------------------------------------------\n\t\ttX = rX(:,1:t);\n\t\tif any(rPnames(1,1:c1)=='@')\t%-FxC interaction\n\t\t\tC = tX(tX~=0);\n\t\t\ttX(tX~=0) = 2*(C-min(C))/max(C-min(C))-1;\n\t\t\tnX = [nX,tX];\n\t\telse\t\t\t\t%-Straight interaction\n\t\t\tnX = [nX,sf_tXsca(tX)];\n\t\tend\n\t\tnPnames = [nPnames; cellstr(rPnames(1:t,:))];\n\t\trX(:,1:t) = []; rPnames(1:t,:)=[];\n\n\n\telse %-Dunno! Just column normalise\n\t%===============================================================\n\t\tnX = [nX,sf_tXsca(rX(:,1))];\n\t\tnPnames = [nPnames; cellstr(rPnames(1,:))];\n\t\trX(:,1) = []; rPnames(1,:)=[];\n\n\tend\n end\nend\n\nX = nX;\nPnames = nPnames;\n\n\ncase {'Fnames','fnames'} %-Turn parameter names into valid filenames\n%=======================================================================\n% Fnames = spm_DesMtx('FNames',Pnames)\nif nargin<2, varargout={''}; return, end\nFnames = varargin{2};\nfor i=1:prod(size(Fnames))\n\tstr = Fnames{i};\n\tstr(str==',')='x';\t\t\t%-',' to 'x'\n\tstr(str=='*')='-';\t\t\t%-'*' to '-'\n\tstr(str=='@')='-';\t\t\t%-'@' to '-'\n\tstr(str==' ')='_';\t\t\t%-' ' to '_'\n\tstr(str=='/')='';\t\t\t%- delete '/'\n\tstr(str=='.')='';\t\t\t%- delete '.'\n\tFnames{i} = str;\nend\nFnames = spm_str_manip(Fnames,'v');\t\t%- retain only legal characters\nX = Fnames;\n\n\ncase {'TeXnames','texnames'} %-Remove '@' & '*' for TeX interpretation\n%=======================================================================\n% TPnames = spm_DesMtx('TeXnames',Pnames)\nif nargin<2, varargout={''}; return, end\nTPnames = varargin{2};\nfor i=1:prod(size(TPnames))\n\tstr = TPnames{i};\n\tstr(str=='*')='';\t\t\t%- delete '*'\n\tstr(str=='@')='';\t\t\t%- delete '@'\n\tTPnames{i} = str;\nend\nX = TPnames;\n\n\ncase {'ParMap','parmap'} %-Parameter mappings: greek to english\n%=======================================================================\n% Map = spm_DesMtx('ParMap',aMap)\nMap = {\t'\\mu',\t\t'const';...\n\t'\\theta',\t'repl';...\n\t'\\alpha',\t'cond';...\n\t'\\gamma',\t'subj';...\n\t'\\rho',\t\t'covint';...\n\t'\\zeta',\t'global';...\n\t'\\epsilon',\t'error'};\nif nargin<2, aMap={}; else, aMap = varargin{2}; end\nif isempty(aMap), X=Map; return, end\nif ~(iscellstr(aMap) & ndims(aMap)==2), error('aMap must be an nx2 cellstr'), end\nfor i=1:size(aMap,1)\n\tj = find(strcmp(aMap{i,1},Map(:,1)));\n\tif isempty(j)\n\t\tMap=[aMap(i,:); Map];\n\telse\n\t\tMap(j,2) = aMap(i,2);\n\tend\nend\nX = Map;\n\n\ncase {'ETeXNames','etexnames'} %-Search & replace: for Englishifying TeX\n%=======================================================================\n% EPnames = spm_DesMtx('TeXnames',Pnames,aMap)\nif nargin<2, varargout={''}; return, end\nif nargin<3, aMap={}; else, aMap = varargin{3}; end\nMap = spm_DesMtx('ParMap',aMap);\nEPnames = varargin{2};\nfor i=1:size(Map,1)\n\tEPnames = strrep(EPnames,Map{i,1},Map{i,2});\nend\nX = EPnames;\n\n\notherwise %-Mis-specified arguments - ERROR\n%=======================================================================\nif ischar(varargin{1})\n\terror('unrecognised action string')\nelse\n\terror('unrecognised constraint type')\nend\n\n%=======================================================================\nend\n\n\n\n%=======================================================================\n% - S U B F U N C T I O N S\n%=======================================================================\nfunction nX = sf_tXsca(tX)\nif nargin==0, nX=[]; return, end\nif abs(max(abs(tX(:)))-0.7)<(.3+1e-10)\n\tnX = tX;\nelseif all(tX(:)==tX(1))\n\tnX = ones(size(tX));\nelseif max(abs(tX(:)))<1e-10\n\tnX = zeros(size(tX));\nelse\n\tnX = 2*(tX-min(tX(:)))/max(tX(:)-min(tX(:)))-1;\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_average_TF.m", "ext": ".m", "path": "spm5-master/spm_eeg_average_TF.m", "size": 2660, "source_encoding": "utf_8", "md5": "8918d10a4b4307e86b50c10c90c4de8a", "text": "\nfunction D=spm_eeg_average_TF(S)\n%%% function to average induced TF data if standard average does not work because of out of memeory issues\n\n% James Kilner\n% $Id$\n\ntry\n D = S.D;\ncatch\n D = spm_select(1, '.*\\.mat$', 'Select EEG mat file');\nend\nP = spm_str_manip(D, 'H');\ntry\n D = spm_eeg_ldata(D);\ncatch \n error(sprintf('Trouble reading file %s', D));\nend\ntry\n c = S.c;\ncatch\n % if there is no S.c, assume that user wants default average within\n % trial type\n c = eye(D.events.Ntypes);\nend\nc1=size(D.data,1);\nc2=size(D.data,2);\nc3=size(D.data,3);\nD=rmfield(D,'data');\npack;\nd=zeros(c1,c2,c3,D.events.Ntypes);\nfh=fopen(fullfile(D.path,D.fnamedat),'r');\nni=zeros(1,D.events.Ntypes);\nfor n=1:D.Nevents\n if D.events.reject(n)== 0\n \n [m,i]=find(D.events.types==D.events.code(n)); \n \n data=fread(fh,[1,c1*c2*c3],'short');\n data=reshape(data,c1,c2,c3,1);\n data=data.*repmat(D.scale(:,1,1,n),[1,D.Nfrequencies, D.Nsamples]);\n d(:,:,:,i)=d(:,:,:,i)+data;\n end\nend\n\nD.fnamedat = ['m' D.fnamedat];\n\nfpd = fopen(fullfile(P, D.fnamedat), 'w');\nD.scale = zeros(D.Nchannels, 1, 1, D.events.Ntypes);\n\nfor n=1:D.events.Ntypes\n dat=squeeze(d(:,:,:,n)./length(find(D.events.code==D.events.types(n) & ~D.events.reject)));\n ni(n)=length(find(D.events.code==D.events.types(n) & ~D.events.reject));\n D.scale(:, 1, 1, n) = max(max(squeeze(abs(dat)), [], 3), [], 2)./32767;\n dat = int16(dat./repmat(D.scale(:, 1, 1, n), [1, D.Nfrequencies, D.Nsamples]));\n fwrite(fpd, dat, 'int16');\nend\nfclose (fh)\t;\n\nfclose(fpd);\nD.Nevents = size(c, 2);\nD.events.repl = ni;\ndisp(sprintf('%s: Number of replications per contrast:', D.fname))\ns = [];\nfor i = 1:D.events.Ntypes\n s = [s sprintf('average %d: %d trials', D.events.types(i), D.events.repl(i))];\n if i < D.events.Ntypes\n s = [s sprintf(', ')];\n else\n s = [s '\\n'];\n end\nend \ndisp(sprintf(s))\n% labeling of resulting contrasts, take care to keep numbers of old trial\n% types\n% check this again: can be problematic, when user mixes within-trialtype\n% and over-trial type contrasts\nD.events.code = size(1, size(c, 2));\nfor i = 1:size(c, 2)\n if sum(c(:, i)) == 1 & sum(~c(:, i)) == size(c, 1)-1\n D.events.code(i) = find(c(:, i));\n else\n D.events.code(i) = i;\n end\nend\n\nD.events.time = [];\nD.events.types = D.events.code;\nD.events.Ntypes = length(D.events.types);\nD.data = [];\nD.events.reject = zeros(1, D.Nevents);\nD.events.blinks = zeros(1, D.Nevents);\nD.fname = ['m' D.fname];\nif spm_matlab_version_chk('7') >= 0\n save(fullfile(P, D.fname), '-V6', 'D');\nelse\n save(fullfile(P, D.fname), 'D');\nend\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_imcalc.m", "ext": ".m", "path": "spm5-master/spm_config_imcalc.m", "size": 6138, "source_encoding": "utf_8", "md5": "165df05c2186b3308b46e82029d2c079", "text": "function opts = spm_config_imcalc\n% Configuration file for image calculator\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_imcalc.m 1032 2007-12-20 14:45:55Z john $\n\n \n%_______________________________________________________________________\n \n\ninpt.type = 'files';\ninpt.name = 'Input Images';\ninpt.tag = 'input';\ninpt.filter = 'image';\ninpt.num = [1 Inf];\ninpt.help = {[...\n'These are the images that are used by the calculator. They ',...\n'are referred to as i1, i2, i3, etc in the order that they are ',...\n'specified.']};\n\n\noutpt.type = 'entry';\noutpt.name = 'Output Filename';\noutpt.tag = 'output';\noutpt.strtype = 's';\noutpt.num = [1 Inf];\noutpt.val = {'output.img'};\noutpt.help = {[...\n'The output image is written to current working directory ',...\n'unless a valid full pathname is given. If a path name is given here, the ',...\n 'output directory setting will be ignored.']};\n\noutdir.type = 'files';\noutdir.name = 'Output Directory';\noutdir.tag = 'outdir';\noutdir.filter = 'dir';\noutdir.num = [0 1];\noutdir.val = {''};\noutdir.help = {['Files produced by this function will be written into this ' ...\n\t\t'output directory. If no directory is given, images will be' ...\n\t\t' written to current working directory. If both output' ...\n\t\t' filename and output directory contain a directory, then '...\n\t\t'output filename takes precedence.']};\n\nexpr.type = 'entry';\nexpr.name = 'Expression';\nexpr.tag = 'expression';\nexpr.strtype = 's';\nexpr.num = [2 Inf];\nexpr.val = {'i1'};\nexpr.help = {...\n'Example expressions (f):',...\n' * Mean of six images (select six images)',...\n' f = ''(i1+i2+i3+i4+i5+i6)/6''',...\n' * Make a binary mask image at threshold of 100',...\n' f = ''i1>100''',...\n' * Make a mask from one image and apply to another',...\n' f = ''i2.*(i1>100)''',[...\n' - here the first image is used to make the mask, which is applied to the second image'],...\n' * Sum of n images',...\n' f = ''i1 + i2 + i3 + i4 + i5 + ...''',...\n' * Sum of n images (when reading data into a data-matrix - use dmtx arg)',...\n' f = ''sum(X)'''};\n \ndmtx.type = 'menu';\ndmtx.name = 'Data Matrix';\ndmtx.tag = 'dmtx';\ndmtx.labels = {'No - don''t read images into data matrix','Yes - read images into data matrix'};\ndmtx.values = {0,1};\ndmtx.def = 'imcalc.dmtx';\n%dmtx.val = {0};\ndmtx.help = {[...\n'If the dmtx flag is set, then images are read into a data matrix X ',...\n'(rather than into separate variables i1, i2, i3,...). The data matrix ',...\n' should be referred to as X, and contains images in rows. ',...\n'Computation is plane by plane, so in data-matrix mode, X is a NxK ',...\n'matrix, where N is the number of input images [prod(size(Vi))], and K ',...\n'is the number of voxels per plane [prod(Vi(1).dim(1:2))].']};\n\nmask.type = 'menu';\nmask.name = 'Masking';\nmask.tag = 'mask';\nmask.labels = {'No implicit zero mask','Implicit zero mask','NaNs should be zeroed'};\nmask.values = {0,1,-1};\nmask.def = 'imcalc.mask';\n%mask.val = {0};\nmask.help = {[...\n'For data types without a representation of NaN, implicit zero masking ',...\n'assumes that all zero voxels are to be treated as missing, and ',...\n'treats them as NaN. NaN''s are written as zero (by spm_write_plane), ',...\n'for data types without a representation of NaN.']};\n\nintrp.type = 'menu';\nintrp.name = 'Interpolation';\nintrp.tag = 'interp';\nintrp.labels = {'Nearest neighbour','Trilinear','2nd Degree Sinc',...\n'3rd Degree Sinc','4th Degree Sinc','5th Degree Sinc',...\n'6th Degree Sinc','7th Degree Sinc'};\nintrp.values = {0,1,-2,-3,-4,-5,-6,-7};\nintrp.def = 'imcalc.interp';\n%intrp.val = {1};\nh1 = [...\n'With images of different sizes and orientations, the size and ',...\n'orientation of the first is used for the output image. A warning is ',...\n'given in this situation. Images are sampled into this orientation ',...\n'using the interpolation specified by the hold parameter.'];\nintrp.help = {h1,'',[...\n'The method by which the images are sampled when being written in a ',...\n'different space.'],...\n' Nearest Neighbour',...\n' - Fastest, but not normally recommended.',...\n' Bilinear Interpolation',...\n' - OK for PET, or realigned fMRI.',...\n' Sinc Interpolation',...\n' - Better quality (but slower) interpolation, especially',...\n' with higher degrees.'...\n};\n\ndtype.type = 'menu';\ndtype.name = 'Data Type';\ndtype.tag = 'dtype';\ndtype.labels = {'UINT8 - unsigned char','INT16 - signed short','INT32 - signed int','FLOAT - single prec. float','DOUBLE - double prec. float'};\ndtype.values = {spm_type('uint8'),spm_type('int16'),spm_type('int32'),spm_type('float32'),spm_type('float64')};\ndtype.def = 'imcalc.dtype';\n%dtype.val = {spm_type('int16')};\ndtype.help = {'Data-type of output image'};\n\noptions.type = 'branch';\noptions.name = 'Options';\noptions.tag = 'options';\noptions.val = {dmtx,mask,intrp,dtype};\noptions.help = {'Options for image calculator'};\n\nopts.type = 'branch';\nopts.name = 'Image Calculator';\nopts.tag = 'imcalc';\nopts.val = {inpt,outpt,outdir,expr,options};\nopts.prog = @fun;\nopts.vfiles = @vfiles;\nopts.help = {[...\n'The image calculator is for performing user-specified ',...\n'algebraic manipulations on a set of images, with the result being ',...\n'written out as an image. The user is prompted to supply images to ',...\n'work on, a filename for the output image, and the expression to ',...\n'evaluate. The expression should be a standard MATLAB expression, ',...\n'within which the images should be referred to as i1, i2, i3,... etc.']};\nreturn;\n\nfunction fun(opt)\nflags = {opt.options.dmtx, opt.options.mask, opt.options.dtype, opt.options.interp};\noutfile = vfiles(opt);\nspm_imcalc_ui(strvcat(opt.input{:}),outfile{1},opt.expression,flags);\nreturn;\n\nfunction vf = vfiles(job)\n[p,nam,ext,num] = spm_fileparts(job.output);\nif isempty(p)\n if isempty(job.outdir{1})\n\tp=pwd;\n else\n\tp = job.outdir{1};\n end;\nend;\nif isempty(strfind(ext,','))\n ext=[ext ',1'];\nend;\nvf{1} = fullfile(p,[nam ext num]);\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_imatrix.m", "ext": ".m", "path": "spm5-master/spm_imatrix.m", "size": 1535, "source_encoding": "utf_8", "md5": "e1e622d4cffa69aa616e536b77f85d66", "text": "function P = spm_imatrix(M)\n% returns the parameters for creating an affine transformation\n% FORMAT P = spm_imatrix(M)\n% M - Affine transformation matrix\n% P - Parameters (see spm_matrix for definitions)\n%___________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner & Stefan Kiebel\n% $Id: spm_imatrix.m 184 2005-05-31 13:23:32Z john $\n\n\n% Translations and zooms\n%-----------------------------------------------------------------------\nR = M(1:3,1:3);\nC = chol(R'*R);\nP = [M(1:3,4)' 0 0 0 diag(C)' 0 0 0];\nif det(R)<0, P(7)=-P(7);end % Fix for -ve determinants\n\n% Shears\n%-----------------------------------------------------------------------\nC = diag(diag(C))\\C;\nP(10:12) = C([4 7 8]);\nR0 = spm_matrix([0 0 0 0 0 0 P(7:12)]);\nR0 = R0(1:3,1:3);\nR1 = R/R0;\n\n% This just leaves rotations in matrix R1\n%-----------------------------------------------------------------------\n%[ c5*c6, c5*s6, s5]\n%[-s4*s5*c6-c4*s6, -s4*s5*s6+c4*c6, s4*c5]\n%[-c4*s5*c6+s4*s6, -c4*s5*s6-s4*c6, c4*c5]\n\nP(5) = asin(rang(R1(1,3)));\nif (abs(P(5))-pi/2)^2 < 1e-9,\n\tP(4) = 0;\n\tP(6) = atan2(-rang(R1(2,1)), rang(-R1(3,1)/R1(1,3)));\nelse\n\tc = cos(P(5));\n\tP(4) = atan2(rang(R1(2,3)/c), rang(R1(3,3)/c));\n\tP(6) = atan2(rang(R1(1,2)/c), rang(R1(1,1)/c));\nend;\nreturn;\n\n% There may be slight rounding errors making b>1 or b<-1.\nfunction a = rang(b)\na = min(max(b, -1), 1);\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "ctf_folder.m", "ext": ".m", "path": "spm5-master/ctf_folder.m", "size": 2949, "source_encoding": "utf_8", "md5": "4e051b8e8a1e6ec08c6b7a53e6b37340", "text": "function [ctf] = ctf_folder(folder,ctf);\n\n% ctf_folder - get and check CTF .ds folder name\n%\n% [ctf] = ctf_folder( [folder], [ctf] );\n% \n% folder: The .ds directory of the dataset. It should be a complete path\n% or given relative to the current working directory (given by pwd). The\n% returned value will ensure the complete path is identified. If this\n% argument is empty or not given, a graphical prompt for the folder\n% appears.\n%\n% eg,\n% ctf = ctf_folder;\n% \n% ctf.folder is returned (as a complete path).\n%\n% <>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> %\n% < > % \n% < DISCLAIMER: > %\n% < > %\n% < THIS PROGRAM IS INTENDED FOR RESEARCH PURPOSES ONLY. > %\n% < THIS PROGRAM IS IN NO WAY INTENDED FOR CLINICAL OR > %\n% < OFFICIAL USE. > %\n% < > %\n% <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<> %\n%\n\n\n% $Revision: 1.7 $ $Date: 2005/01/21 02:07:36 $\n\n% Copyright (C) 2004 Darren L. Weber\n% \n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n% Modified: 01/2004, Darren.Weber_at_radiology.ucsf.edu\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nif ~exist('folder','var'), folder = []; end\nif ~exist('ctf','var'), ctf = []; end\n\nif isempty(folder),\n if isfield(ctf,'folder'),\n folder = ctf.folder;\n else\n folder = [];\n end\nend\n\nif exist(folder) ~= 7,\n fprintf('...folder inputs are invalid\\n');\n folder = getfolder;\nend\n\nctf.folder = folder;\n\n% ensure we get the folder path\ncurrent_dir = pwd;\ncd(ctf.folder);\ncd ..\nfolderPath = pwd;\ncd(current_dir);\n\n% check whether the folder path is in the folder already\n[path,file] = fileparts(ctf.folder);\n\n% if findstr(folderPath,ctf.folder),\n % OK the path is already in the folder\n% else\nif isempty(path)\n % Add the folderPath\n ctf.folder = fullfile(folderPath,ctf.folder);\nend\n\n\nreturn\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction folder = getfolder,\n\nfolder = uigetdir(pwd,'locate CTF .ds folder');\nif ~folder,\n error('no folder specified');\nend\n\nreturn"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_affreg.m", "ext": ".m", "path": "spm5-master/spm_affreg.m", "size": 18881, "source_encoding": "utf_8", "md5": "75ec9b5af8f8965af695dc0eb74ed73c", "text": "function [M,scal] = spm_affreg(VG,VF,flags,M,scal)\n% Affine registration using least squares.\n% FORMAT [M,scal] = spm_affreg(VG,VF,flags,M0,scal0)\n%\n% VG - Vector of template volumes.\n% VF - Source volume.\n% flags - a structure containing various options. The fields are:\n% WG - Weighting volume for template image(s).\n% WF - Weighting volume for source image\n% Default to [].\n% sep - Approximate spacing between sampled points (mm).\n% Defaults to 5.\n% regtype - regularisation type. Options are:\n% 'none' - no regularisation\n% 'rigid' - almost rigid body\n% 'subj' - inter-subject registration (default).\n% 'mni' - registration to ICBM templates\n% globnorm - Global normalisation flag (1)\n% M0 - (optional) starting estimate. Defaults to eye(4).\n% scal0 - (optional) starting estimate.\n%\n% M - affine transform, such that voxels in VF map to those in\n% VG by VG.mat\\M*VF.mat\n% scal - scaling factors for VG\n%\n% When only one template is used, then the cost function is approximately\n% symmetric, although a linear combination of templates can be used.\n% Regularisation is based on assuming a multi-normal distribution for the\n% elements of the Henckey Tensor. See:\n% \"Non-linear Elastic Deformations\". R. W. Ogden (Dover), 1984.\n% Weighting for the regularisation is determined approximately according\n% to:\n% \"Incorporating Prior Knowledge into Image Registration\"\n% J. Ashburner, P. Neelin, D. L. Collins, A. C. Evans & K. J. Friston.\n% NeuroImage 6:344-352 (1997).\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_affreg.m 1160 2008-02-20 18:04:09Z john $\n\n\nif nargin<5, scal = ones(length(VG),1); end;\nif nargin<4, M = eye(4); end;\n\ndef_flags = struct('sep',5, 'regtype','subj','WG',[],'WF',[],'globnorm',1,'debug',0);\nif nargin < 2 || ~isstruct(flags),\n\tflags = def_flags;\nelse\n\tfnms = fieldnames(def_flags);\n\tfor i=1:length(fnms),\n\t\tif ~isfield(flags,fnms{i}),\n\t\t\tflags.(fnms{i}) = def_flags.(fnms{i});\n\t\tend;\n\tend;\nend;\n\n% Check to ensure inputs are valid...\n% ---------------------------------------------------------------\nif length(VF)>1, error('Can not use more than one source image'); end;\nif ~isempty(flags.WF),\n\tif length(flags.WF)>1,\n\t\terror('Can only use one source weighting image');\n\tend;\n\tif any(any((VF.mat-flags.WF.mat).^2>1e-8)),\n\t\terror('Source and its weighting image must have same orientation');\n\tend;\n\tif any(any(VF.dim(1:3)-flags.WF.dim(1:3))),\n\t\terror('Source and its weighting image must have same dimensions');\n\tend;\nend;\nif ~isempty(flags.WG),\n\tif length(flags.WG)>1,\n\t\terror('Can only use one template weighting image');\n\tend;\n\ttmp = reshape(cat(3,VG(:).mat,flags.WG.mat),16,length(VG)+length(flags.WG));\nelse\n\ttmp = reshape(cat(3,VG(:).mat),16,length(VG));\nend;\nif any(any(diff(tmp,1,2).^2>1e-8)),\n\terror('Reference images must all have the same orientation');\nend;\nif ~isempty(flags.WG),\n\ttmp = cat(1,VG(:).dim,flags.WG.dim);\nelse\n\ttmp = cat(1,VG(:).dim);\nend;\nif any(any(diff(tmp(:,1:3),1,1))),\n\terror('Reference images must all have the same dimensions');\nend;\n% ---------------------------------------------------------------\n\n% Generate points to sample from, adding some jitter in order to\n% make the cost function smoother.\n% ---------------------------------------------------------------\nrand('state',0); % want the results to be consistant.\ndg = VG(1).dim(1:3);\ndf = VF(1).dim(1:3);\n\nif length(VG)==1,\n\tskip = sqrt(sum(VG(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;\n\t[x1,x2,x3]=ndgrid(1:skip(1):dg(1)-.5, 1:skip(2):dg(2)-.5, 1:skip(3):dg(3)-.5);\n\tx1 = x1 + rand(size(x1))*0.5; x1 = x1(:);\n\tx2 = x2 + rand(size(x2))*0.5; x2 = x2(:);\n\tx3 = x3 + rand(size(x3))*0.5; x3 = x3(:);\nend;\n\nskip = sqrt(sum(VF(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;\n[y1,y2,y3]=ndgrid(1:skip(1):df(1)-.5, 1:skip(2):df(2)-.5, 1:skip(3):df(3)-.5);\ny1 = y1 + rand(size(y1))*0.5; y1 = y1(:);\ny2 = y2 + rand(size(y2))*0.5; y2 = y2(:);\ny3 = y3 + rand(size(y3))*0.5; y3 = y3(:);\n% ---------------------------------------------------------------\n\nif flags.globnorm,\n\t% Scale all images approximately equally\n\t% ---------------------------------------------------------------\n\tfor i=1:length(VG),\n\t\tVG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));\n\tend;\n\tVF(1).pinfo(1:2,:) = VF(1).pinfo(1:2,:)/spm_global(VF(1));\nend;\n% ---------------------------------------------------------------\n\nif length(VG)==1,\n\t[G,dG1,dG2,dG3] = spm_sample_vol(VG(1),x1,x2,x3,1);\n\tif ~isempty(flags.WG),\n\t\tWG = abs(spm_sample_vol(flags.WG,x1,x2,x3,1))+eps;\n\t\tWG(~isfinite(WG)) = 1;\n\tend;\nend;\n\n[F,dF1,dF2,dF3] = spm_sample_vol(VF(1),y1,y2,y3,1);\nif ~isempty(flags.WF),\n\tWF = abs(spm_sample_vol(flags.WF,y1,y2,y3,1))+eps;\n\tWF(~isfinite(WF)) = 1;\nend;\n% ---------------------------------------------------------------\nn_main_its = 0;\nss = Inf;\nW = [Inf Inf Inf];\nest_smo = 1;\n% ---------------------------------------------------------------\n\nfor iter=1:256,\n\tpss = ss;\n\tp0 = [0 0 0 0 0 0 1 1 1 0 0 0];\n\n\t% Initialise the cost function and its 1st and second derivatives\n\t% ---------------------------------------------------------------\n\tn = 0;\n\tss = 0;\n\tBeta = zeros(12+length(VG),1);\n\tAlpha = zeros(12+length(VG));\n\n\tif length(VG)==1,\n\t\t% Make the cost function symmetric\n\t\t% ---------------------------------------------------------------\n\n\t\t% Build a matrix to rotate the derivatives by, converting from\n\t\t% derivatives w.r.t. changes in the overall affine transformation\n\t\t% matrix, to derivatives w.r.t. the parameters p.\n\t\t% ---------------------------------------------------------------\n\t\tdt = 0.0001;\n\t\tR = eye(13);\n\t\tMM0 = inv(VG.mat)*inv(spm_matrix(p0))*VG.mat;\n\t\tfor i1=1:12,\n\t\t\tp1 = p0;\n\t\t\tp1(i1) = p1(i1)+dt;\n\t\t\tMM1 = (inv(VG.mat)*inv(spm_matrix(p1))*(VG.mat));\n\t\t\tR(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);\n\t\tend;\n\t\t% ---------------------------------------------------------------\n\t\t[t1,t2,t3] = coords((M*VF(1).mat)\\VG(1).mat,x1,x2,x3);\n\t\tmsk = find((t1>=1 & t1<=df(1) & t2>=1 & t2<=df(2) & t3>=1 & t3<=df(3)));\n\t\tif length(msk)<32, error_message; end;\n\t\tt1 = t1(msk);\n\t\tt2 = t2(msk);\n\t\tt3 = t3(msk);\n\t\tt = spm_sample_vol(VF(1), t1,t2,t3,1);\n\n\t\t% Get weights\n\t\t% ---------------------------------------------------------------\n\t\tif ~isempty(flags.WF) || ~isempty(flags.WG),\n\t\t\tif isempty(flags.WF),\n\t\t\t\twt = WG(msk);\n\t\t\telse\n\t\t\t\twt = spm_sample_vol(flags.WF(1), t1,t2,t3,1)+eps;\n\t\t\t\twt(~isfinite(wt)) = 1;\n\t\t\t\tif ~isempty(flags.WG), wt = 1./(1./wt + 1./WG(msk)); end;\n\t\t\tend;\n\t\t\twt = sparse(1:length(wt),1:length(wt),wt);\n\t\telse\n\t\t\t% wt = speye(length(msk));\n\t\t\twt = [];\n\t\tend;\n\t\t% ---------------------------------------------------------------\n\t\tclear t1 t2 t3\n\n\t\t% Update the cost function and its 1st and second derivatives.\n\t\t% ---------------------------------------------------------------\n\t\t[AA,Ab,ss1,n1] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,scal^(-2)*t,G(msk)-(1/scal)*t,wt);\n\t\tAlpha = Alpha + R'*AA*R;\n\t\tBeta = Beta + R'*Ab;\n\t\tss = ss + ss1;\n\t\tn = n + n1;\n\t\t% t = G(msk) - (1/scal)*t;\n\tend;\n\n\tif 1,\n\t\t% Build a matrix to rotate the derivatives by, converting from\n\t\t% derivatives w.r.t. changes in the overall affine transformation\n\t\t% matrix, to derivatives w.r.t. the parameters p.\n\t\t% ---------------------------------------------------------------\n\t\tdt = 0.0001;\n\t\tR = eye(12+length(VG));\n\t\tMM0 = inv(M*VF.mat)*spm_matrix(p0)*M*VF.mat;\n\t\tfor i1=1:12,\n\t\t\tp1 = p0;\n\t\t\tp1(i1) = p1(i1)+dt;\n\t\t\tMM1 = (inv(M*VF.mat)*spm_matrix(p1)*M*VF.mat);\n\t\t\tR(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);\n\t\tend;\n\t\t% ---------------------------------------------------------------\n\t\t[t1,t2,t3] = coords(VG(1).mat\\M*VF(1).mat,y1,y2,y3);\n\t\tmsk = find((t1>=1 & t1<=dg(1) & t2>=1 & t2<=dg(2) & t3>=1 & t3<=dg(3)));\n\t\tif length(msk)<32, error_message; end;\n\n\t\tif length(msk)<32, error_message; end;\n\t\tt1 = t1(msk);\n\t\tt2 = t2(msk);\n\t\tt3 = t3(msk);\n\t\tt = zeros(length(t1),length(VG));\n\n\t\t% Get weights\n\t\t% ---------------------------------------------------------------\n\t\tif ~isempty(flags.WF) || ~isempty(flags.WG),\n\t\t\tif isempty(flags.WG),\n\t\t\t\twt = WF(msk);\n else\n\t\t\t\twt = spm_sample_vol(flags.WG(1), t1,t2,t3,1)+eps;\n\t\t\t\twt(~isfinite(wt)) = 1;\n\t\t\t\tif ~isempty(flags.WF), wt = 1./(1./wt + 1./WF(msk)); end;\n\t\t\tend;\n\t\t\twt = sparse(1:length(wt),1:length(wt),wt);\n else\n\t\t\twt = speye(length(msk));\n\t\tend;\n\t\t% ---------------------------------------------------------------\n\n\t\tif est_smo,\n\t\t\t% Compute derivatives of residuals in the space of F\n\t\t\t% ---------------------------------------------------------------\n\t\t\t[ds1,ds2,ds3] = transform_derivs(VG(1).mat\\M*VF(1).mat,dF1(msk),dF2(msk),dF3(msk));\n\t\t\tfor i=1:length(VG),\n\t\t\t\t[t(:,i),dt1,dt2,dt3] = spm_sample_vol(VG(i), t1,t2,t3,1);\n\t\t\t\tds1 = ds1 - dt1*scal(i); clear dt1\n\t\t\t\tds2 = ds2 - dt2*scal(i); clear dt2\n\t\t\t\tds3 = ds3 - dt3*scal(i); clear dt3\n\t\t\tend;\n\t\t\tdss = [ds1'*wt*ds1 ds2'*wt*ds2 ds3'*wt*ds3];\n\t\t\tclear ds1 ds2 ds3\n else\n\t\t\tfor i=1:length(VG),\n\t\t\t\tt(:,i)= spm_sample_vol(VG(i), t1,t2,t3,1);\n\t\t\tend;\n\t\tend;\n\n\t\tclear t1 t2 t3\n\n\t\t% Update the cost function and its 1st and second derivatives.\n\t\t% ---------------------------------------------------------------\n\t\t[AA,Ab,ss2,n2] = costfun(y1,y2,y3,dF1,dF2,dF3,msk,-t,F(msk)-t*scal,wt);\n\t\tAlpha = Alpha + R'*AA*R;\n\t\tBeta = Beta + R'*Ab;\n\t\tss = ss + ss2;\n\t\tn = n + n2;\n\tend;\n\n\tif est_smo,\n\t\t% Compute a smoothness correction from the residuals and their\n\t\t% derivatives. This is analagous to the one used in:\n\t\t% \t\"Analysis of fMRI Time Series Revisited\"\n\t\t% \tFriston KJ, Holmes AP, Poline JB, Grasby PJ, Williams SCR,\n\t\t% \tFrackowiak RSJ, Turner R. Neuroimage 2:45-53 (1995).\n\t\t% ---------------------------------------------------------------\n\t\tvx = sqrt(sum(VG(1).mat(1:3,1:3).^2));\n\t\tpW = W;\n\t\tW = (2*dss/ss2).^(-.5).*vx;\n\t\tW = min(pW,W);\n\t\tif flags.debug, fprintf('\\nSmoothness FWHM: %.3g x %.3g x %.3g mm\\n', W*sqrt(8*log(2))); end;\n\t\tif length(VG)==1, dens=2; else dens=1; end;\n\t\tsmo = prod(min(dens*flags.sep/sqrt(2*pi)./W,[1 1 1]));\n\t\test_smo=0;\n\t\tn_main_its = n_main_its + 1;\n\tend;\n\n\t% Update the parameter estimates\n\t% ---------------------------------------------------------------\n\tnu = n*smo;\n\tsig2 = ss/nu;\n\t[d1,d2] = reg(M,12+length(VG),flags.regtype);\n\n\tsoln = (Alpha/sig2+d2)\\(Beta/sig2-d1);\n\tscal = scal - soln(13:end);\n\tM = spm_matrix(p0 + soln(1:12)')*M;\n\n\tif flags.debug,\n\t\tfprintf('%d\\t%g\\n', iter, ss/n);\n\t\tpiccies(VF,VG,M,scal);\n\tend;\n\n\t% If cost function stops decreasing, then re-estimate smoothness\n\t% and try again. Repeat a few times.\n\t% ---------------------------------------------------------------\n\tss = ss/n;\n\tif iter>1, spm_chi2_plot('Set',ss); end;\n\tif (pss-ss)/pss < 1e-6,\n\t\test_smo = 1;\n\tend;\n\tif n_main_its>3, break; end;\n\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [X1,Y1,Z1] = transform_derivs(Mat,X,Y,Z)\n% Given the derivatives of a scalar function, return those of the\n% affine transformed function\n%_______________________________________________________________________\n\nt1 = Mat(1:3,1:3);\nt2 = eye(3);\nif sum((t1(:)-t2(:)).^2) < 1e-12,\n X1 = X;Y1 = Y; Z1 = Z;\nelse\n X1 = Mat(1,1)*X + Mat(1,2)*Y + Mat(1,3)*Z;\n Y1 = Mat(2,1)*X + Mat(2,2)*Y + Mat(2,3)*Z;\n Z1 = Mat(3,1)*X + Mat(3,2)*Y + Mat(3,3)*Z;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [d1,d2] = reg(M,n,typ)\n% Analytically compute the first and second derivatives of a penalty\n% function w.r.t. changes in parameters.\n\nif nargin<3, typ = 'subj'; end;\nif nargin<2, n = 13; end;\n\n[mu,isig] = priors(typ);\nds = 0.000001;\nd1 = zeros(n,1);\nd2 = zeros(n);\np0 = [0 0 0 0 0 0 1 1 1 0 0 0];\nh0 = penalty(p0,M,mu,isig);\nfor i=7:12, % derivatives are zero w.r.t. rotations and translations\n\tp1 = p0;\n\tp1(i) = p1(i)+ds;\n\th1 = penalty(p1,M,mu,isig);\n\td1(i) = (h1-h0)/ds; % First derivative\n\tfor j=7:12,\n\t\tp2 = p0;\n\t\tp2(j) = p2(j)+ds;\n\t\th2 = penalty(p2,M,mu,isig);\n\t\tp3 = p1;\n\t\tp3(j) = p3(j)+ds;\n\t\th3 = penalty(p3,M,mu,isig);\n\t\td2(i,j) = ((h3-h2)/ds-(h1-h0)/ds)/ds; % Second derivative\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction h = penalty(p,M,mu,isig)\n% Return a penalty based on the elements of an affine transformation,\n% which is given by:\n% \tspm_matrix(p)*M\n%\n% The penalty is based on the 6 unique elements of the Hencky tensor\n% elements being multinormally distributed.\n%_______________________________________________________________________\n\n% Unique elements of symmetric 3x3 matrix.\nels = [1 2 3 5 6 9];\n\nT = spm_matrix(p)*M;\nT = T(1:3,1:3);\nT = 0.5*logm(T'*T);\nT = T(els)' - mu;\nh = T'*isig*T;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [mu,isig] = priors(typ)\n% The parameters for this distribution were derived empirically from 227\n% scans, that were matched to the ICBM space.\n%_______________________________________________________________________\n\nmu = zeros(6,1);\nisig = zeros(6);\nswitch deblank(lower(typ)),\n\ncase 'mni', % For registering with MNI templates...\n\tmu = [0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]';\n\tisig = 1e4 * [\n\t 0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163\n\t -0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116\n\t -0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060\n\t -0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440\n\t -0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062\n\t -0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144];\n\ncase 'rigid', % Constrained to be almost rigid...\n\tmu = zeros(6,1);\n\tisig = eye(6)*1e9;\n\ncase 'isochoric', % Volume preserving...\n\terror('Not implemented');\n\ncase 'isotropic', % Isotropic zoom in all directions...\n\terror('Not implemented');\n\ncase 'subj', % For inter-subject registration...\n\tmu = zeros(6,1);\n\tisig = 1e3 * [\n\t 0.8876 0.0784 0.0784 -0.1749 0.0784 -0.1749\n\t 0.0784 5.3894 0.2655 0.0784 0.2655 0.0784\n\t 0.0784 0.2655 5.3894 0.0784 0.2655 0.0784\n\t -0.1749 0.0784 0.0784 0.8876 0.0784 -0.1749\n\t 0.0784 0.2655 0.2655 0.0784 5.3894 0.0784\n\t -0.1749 0.0784 0.0784 -0.1749 0.0784 0.8876];\n\ncase 'none', % No regularisation...\n\tmu = zeros(6,1);\n\tisig = zeros(6);\n\notherwise,\n\terror(['\"' typ '\" not recognised as type of regularisation.']);\nend;\nreturn;\n\n%_______________________________________________________________________\nfunction [y1,y2,y3]=coords(M,x1,x2,x3)\n% Affine transformation of a set of coordinates.\n%_______________________________________________________________________\n\ny1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);\ny2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);\ny3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction A = make_A(x1,x2,x3,dG1,dG2,dG3,t)\n% Generate part of a design matrix using the chain rule...\n% df/dm = df/dy * dy/dm\n% where\n% \tdf/dm is the rate of change of intensity w.r.t. affine parameters\n% \tdf/dy is the gradient of the image f\n% \tdy/dm crange of position w.r.t. change of parameters\n%_______________________________________________________________________\n\nA = [x1.*dG1 x1.*dG2 x1.*dG3 ...\n\t x2.*dG1 x2.*dG2 x2.*dG3 ...\n\t x3.*dG1 x3.*dG2 x3.*dG3 ...\n\t dG1 dG2 dG3 t];\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [AA,Ab,ss,n] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,lastcols,b,wt)\nchunk = 10240;\nlm = length(msk);\nAA = zeros(12+size(lastcols,2));\nAb = zeros(12+size(lastcols,2),1);\nss = 0;\nn = 0;\n\nfor i=1:ceil(lm/chunk),\n\tind = (((i-1)*chunk+1):min(i*chunk,lm))';\n\tmsk1 = msk(ind);\n\n\tA1 = make_A(x1(msk1),x2(msk1),x3(msk1),dG1(msk1),dG2(msk1),dG3(msk1),lastcols(ind,:));\n\tb1 = b(ind);\n\tif ~isempty(wt),\n\t\twt1 = wt(ind,ind);\n\t\tAA = AA + A1'*wt1*A1;\n\t\t%Ab = Ab + A1'*wt1*b1;\n\t\tAb = Ab + (b1'*wt1*A1)';\n\t\tss = ss + b1'*wt1*b1;\n\t\tn = n + trace(wt1);\n\t\tclear wt1\n else\n\t\tAA = AA + spm_atranspa(A1);\n\t\t%Ab = Ab + A1'*b1;\n\t\tAb = Ab + (b1'*A1)';\n\t\tss = ss + b1'*b1;\n\t\tn = n + length(msk1);\n\tend;\n\tclear A1 b1 msk1 ind\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction error_message\n% Display an error message for when things go wrong.\nstr = {\t'There is not enough overlap in the images',...\n\t'to obtain a solution.',...\n\t' ',...\n\t'Please check that your header information is OK.',...\n\t'The Check Reg utility will show you the initial',...\n\t'alignment between the images, which must be',...\n\t'within about 4cm and about 15 degrees in order',...\n\t'for SPM to find the optimal solution.'};\nspm('alert*',str,mfilename,sqrt(-1));\nerror('insufficient image overlap')\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction piccies(VF,VG,M,scal)\n% This is for debugging purposes.\n% It shows the linear combination of template images, the affine\n% transformed source image, the residual image and a histogram of the\n% residuals.\n%_______________________________________________________________________\n\nfigure(2);\nMt = spm_matrix([0 0 (VG(1).dim(3)+1)/2]);\nM = (M*VF(1).mat)\\VG(1).mat;\nt = zeros(VG(1).dim(1:2));\nfor i=1:length(VG);\n\tt = t + spm_slice_vol(VG(i), Mt,VG(1).dim(1:2),1)*scal(i);\nend;\nu = spm_slice_vol(VF(1),M*Mt,VG(1).dim(1:2),1);\nsubplot(2,2,1);imagesc(t');axis image xy off\nsubplot(2,2,2);imagesc(u');axis image xy off\nsubplot(2,2,3);imagesc(u'-t');axis image xy off\n%subplot(2,2,4);hist(b,50); % Entropy of residuals may be a nice cost function?\ndrawnow;\nreturn;\n%_______________________________________________________________________\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_loaduint8.m", "ext": ".m", "path": "spm5-master/spm_loaduint8.m", "size": 1375, "source_encoding": "utf_8", "md5": "c323020909cc93a83057b28b65305214", "text": "function udat = spm_loaduint8(V)\n% Load data from file indicated by V into an array of unsigned bytes.\n\nif size(V.pinfo,2)==1 && V.pinfo(1) == 2,\n\tmx = 255*V.pinfo(1) + V.pinfo(2);\n\tmn = V.pinfo(2);\nelse,\n\tspm_progress_bar('Init',V.dim(3),...\n\t\t['Computing max/min of ' spm_str_manip(V.fname,'t')],...\n\t\t'Planes complete');\n\tmx = -Inf; mn = Inf;\n\tfor p=1:V.dim(3),\n\t\timg = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n\t\tmx = max([max(img(:))+paccuracy(V,p) mx]);\n\t\tmn = min([min(img(:)) mn]);\n\t\tspm_progress_bar('Set',p);\n\tend;\nend;\nspm_progress_bar('Init',V.dim(3),...\n\t['Loading ' spm_str_manip(V.fname,'t')],...\n\t'Planes loaded');\n\nudat = uint8(0);\nudat(V.dim(1),V.dim(2),V.dim(3))=0;\nrand('state',100);\nfor p=1:V.dim(3),\n\timg = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n\tacc = paccuracy(V,p);\n\tif acc==0,\n\t\tudat(:,:,p) = uint8(round((img-mn)*(255/(mx-mn))));\n\telse,\n\t\t% Add random numbers before rounding to reduce aliasing artifact\n\t\tr = rand(size(img))*acc;\n\t\tudat(:,:,p) = uint8(round((img+r-mn)*(255/(mx-mn))));\n\tend;\n\tspm_progress_bar('Set',p);\nend;\nspm_progress_bar('Clear');\nreturn;\n\nfunction acc = paccuracy(V,p)\n% if ~spm_type(V.dim(4),'intt'),\nif ~spm_type(V.dt(1),'intt'),\n acc = 0;\nelse,\n if size(V.pinfo,2)==1,\n acc = abs(V.pinfo(1,1));\n else,\n acc = abs(V.pinfo(1,p));\n end;\nend;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "savexml.m", "ext": ".m", "path": "spm5-master/savexml.m", "size": 4312, "source_encoding": "utf_8", "md5": "753fabe9a2ec52f53e55248f54e10df9", "text": "function savexml(filename, varargin)\n%SAVEXML Save workspace variables to disk in XML.\n% SAVEXML FILENAME saves all workspace variables to the XML-file\n% named FILENAME.xml. The data may be retrieved with LOADXML. if\n% FILENAME has no extension, .xml is assumed.\n% \n% SAVE, by itself, creates the XML-file named 'matlab.xml'. It is\n% an error if 'matlab.xml' is not writable.\n%\n% SAVE FILENAME X saves only X.\n% SAVE FILENAME X Y Z saves X, Y, and Z. The wildcard '*' can be \n% used to save only those variables that match a pattern.\n%\n% SAVE ... -APPEND adds the variables to an existing file.\n%\n% Use the functional form of SAVE, such as SAVE(filename','var1','var2'),\n% when the filename or variable names are stored in strings.\n%\n% See also SAVE, MAT2XML, XMLTREE.\n\n% Copyright 2003 Guillaume Flandin. \n% $Revision: 112 $ $Date: 2003/07/10 13:50 $\n\n% $Id: savexml.m 112 2005-05-04 18:20:52Z john $\n\nif nargin == 0\n\tfilename = 'matlab.xml';\n\tfprintf('\\nSaving to: %s\\n\\n',filename);\nelse\n\tif ~ischar(filename)\n\t\terror('[SAVEXML] Argument must contain a string.');\n\tend\n\t[pathstr,name,ext] = fileparts(filename);\n\tif isempty(ext)\n\t\tfilename = [filename '.xml'];\n\tend\nend\nif nargin <= 1, varargin = {'*'}; end\n\nif nargout > 0\n\terror('[SAVEXML] Too many output arguments.');\nend\n\nif strcmpi(varargin{end},'-append')\n\tif length(varargin) > 1\n\t\tvarargin = varargin(1:end-1);\n\telse\n\t\tvarargin = {'*'};\n\tend\n\tif exist(filename,'file')\n\t\t% TODO % No need to parse the whole tree ? detect duplicate variables ?\n\t\tt = xmltree(filename);\n\telse\n\t\terror(sprintf(...\n\t\t'[SAVEXML] Unable to write file %s: file does not exist.',filename));\n\tend\nelse\n\tt = xmltree('');\nend\n\nfor i=1:length(varargin)\n\tv = evalin('caller',['whos(''' varargin{i} ''')']);\n\tif isempty(v)\n\t\terror(['[SAVEXML] Variable ''' varargin{i} ''' not found.']);\n\tend\n\tfor j=1:length(v)\n\t\t[t, uid] = add(t,root(t),'element',v(j).name);\n\t\tt = attributes(t,'add',uid,'type',v(j).class);\n\t\tt = attributes(t,'add',uid,'size',xml_num2str(v(j).size));\n\t\tt = xml_var2xml(t,evalin('caller',v(j).name),uid);\n\tend\nend\n\nsave(t,filename);\n\n%=======================================================================\nfunction t = xml_var2xml(t,v,uid)\n\n\tswitch class(v)\n\t\tcase 'double'\n\t\t\tt = add(t,uid,'chardata',xml_num2str(v));\n\t\tcase 'sparse'\n\t\t\t[i,j,s] = find(v);\n\t\t\t[t, uid2] = add(t,uid,'element','row');\n\t\t\tt = attributes(t,'add',uid2,'size',xml_num2str(size(i)));\n\t\t\tt = add(t,uid2,'chardata',xml_num2str(i));\n\t\t\t[t, uid2] = add(t,uid,'element','col');\n\t\t\tt = attributes(t,'add',uid2,'size',xml_num2str(size(j)));\n\t\t\tt = add(t,uid2,'chardata',xml_num2str(j));\n\t\t\t[t, uid2] = add(t,uid,'element','val');\n\t\t\tt = attributes(t,'add',uid2,'size',xml_num2str(size(s)));\n\t\t\tt = add(t,uid2,'chardata',xml_num2str(s));\n\t\tcase 'struct'\n\t\t\tnames = fieldnames(v);\n\t\t\tfor j=1:prod(size(v))\n\t\t\t\tfor i=1:length(names)\n\t\t\t\t\t[t, uid2] = add(t,uid,'element',names{i});\n\t\t\t\t\tt = attributes(t,'add',uid2,'index',num2str(j));\n\t\t\t\t\tt = attributes(t,'add',uid2,'type',...\n\t\t\t\t\t\tclass(getfield(v(j),names{i})));\n\t\t\t\t\tt = attributes(t,'add',uid2,'size', ...\n\t\t\t\t\t\txml_num2str(size(getfield(v(j),names{i}))));\n\t\t\t\t\tt = xml_var2xml(t,getfield(v(j),names{i}),uid2);\n\t\t\t\tend\n\t\t\tend\n\t\tcase 'cell'\n\t\t\tfor i=1:prod(size(v))\n\t\t\t\t[t, uid2] = add(t,uid,'element','cell'); \n\t\t\t\t% TODO % special handling of cellstr ?\n\t\t\t\tt = attributes(t,'add',uid2,'index',num2str(i));\n\t\t\t\tt = attributes(t,'add',uid2,'type',class(v{i}));\n\t\t\t\tt = attributes(t,'add',uid2,'size',xml_num2str(size(v{i})));\n\t\t\t\tt = xml_var2xml(t,v{i},uid2);\n\t\t\tend\n\t\tcase 'char'\n\t\t\t% TODO % char values should be in CData\n\t\t\tt = add(t,uid,'chardata',v);\n\t\tcase {'int8','uint8','int16','uint16','int32','uint32'}\n\t\t\t[t, uid] = add(t,uid,'element',class(v));\n\t\t\t% TODO % Handle integer formats (cannot use sprintf or num2str)\n\t\totherwise\n\t\t\tif ismember('serialize',methods(class(v)))\n\t\t\t\t% TODO % is CData necessary for class output ?\n\t\t\t\tt = add(t,uid,'cdata',serialize(v));\n\t\t\telse\n\t\t\t\twarning(sprintf(...\n\t\t\t\t'[SAVEXML] Cannot convert from %s to XML.',class(v)));\n\t\t\tend\n\tend\n\n%=======================================================================\nfunction s = xml_num2str(n)\n\t% TODO % use format ?\n\tif isempty(n)\n\t\ts = '[]';\n\telse\n\t\ts = ['[' sprintf('%g ',n(1:end-1))];\n\t\ts = [s num2str(n(end)) ']'];\n\tend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_electrset.m", "ext": ".m", "path": "spm5-master/spm_eeg_inv_electrset.m", "size": 16739, "source_encoding": "utf_8", "md5": "16af7781a5ed0427df06e69cbafc0d66", "text": "function [el_sphc,el_name] = spm_eeg_inv_electrset(el_set)\n%------------------------------------------------------------------------\n% FORMAT [el_sphc,el_name] = spm_eeg_inv_electrset(el_set) ;\n% or\n% FORMAT [set_Nel,set_name] = spm_eeg_inv_electrset ;\n% \n% Creates the electrode set on a sphere, set type is defined by 'el_set'.\n% or return the name of the sets available, and the number of electrodes.\n% Electrode coordinates generated are on a unit sphere, with :\n% - nasion at [0 1 0]\n% - left/right ear at [-1 0 0]/[1 0 0]\n% - inion at [0 -1 0]\n% - and Cz at [0 0 1]\n% So the coordinates need to be adapted for any (semi-)realistic head\n% model!\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Christophe Phillips,\n% $Id$\n\nset_name = strvcat('10-20 system with 23 electrodes.', ...\n '10-20 system with 19 electrodes.', ...\n '61 Equidistant electrodes.', ...\n '148 electrodes, Pascual-Marqui''s set.', ...\n '31 electrodes, Rik''s set.', ...\n '10-20 system with 21 electrodes.', ...\n '10-20 system with 29 electrodes.', ...\n '62 electrodes on ext. 10-20 system.', ...\n 'Select BDF from EEGtemplates.', ...\n 'Select CTF from EEGtemplates');\nNr_electr = [23 19 61 148 31 21 29 62 -1];\nif nargin < 1\n el_sphc = Nr_electr;\n el_name = set_name;\nelse\n try\n\t\tswitch el_set\n\t\t\tcase 1\n\t\t\t\tfprintf(['\\n',set_name(el_set,:),'\\n\\n']);\n\t\t\t\t[el_sphc,el_name] = sys1020_23 ;\n\t\t\tcase 2\n\t\t\t\tfprintf(['\\n',set_name(el_set,:),'\\n\\n']);\n\t\t\t\t[el_sphc,el_name] = sys1020_19 ;\n\t\t\tcase 3\n\t\t\t\tfprintf(['\\n',set_name(el_set,:),'\\n\\n']);\n\t\t\t\t[el_sphc,el_name] = sys61 ;\n\t\t\tcase 4\n \t\t\t\tfprintf(['\\n',set_name(el_set,:),'\\n\\n']);\n\t\t\t\t[el_sphc,el_name] = sys148 ;\n\t\t\tcase 5\n \t\t\t\tfprintf(['\\n',set_name(el_set,:),'\\n\\n']);\n\t\t\t\tel_rik = [59 1 14 50 48 33 19 47 31 17 ...\n 46 30 29 44 36 9 22 38 11 24 ...\n 39 26 25 40 42 53 37 49 41 45 8];\n % Subset of electrodes for Rik's expe.\n [el_sphc,el_name] = sys61 ;\n\t\t\t\tel_sphc = el_sphc(:,el_rik) ;\n el_name = el_name(el_rik,:) ;\n\t\t\tcase 6\n\t\t\t\tfprintf(['\\n',set_name(el_set,:),'\\n\\n']);\n el_not_21 = [2 22];\n el_21 = 1:23; el_21(el_not_21) = [];\n [el_sphc,el_name] = sys1020_23 ;\n\t\t\t\tel_sphc = el_sphc(:,el_21) ;\n el_name = el_name(el_21,:) ;\n\t\t\tcase 7\n\t\t\t\tfprintf(['\\n',set_name(el_set,:),'\\n\\n']);\n\t\t\t\t[el_sphc,el_name] = sys1020_29 ;\n case 8\n\t\t\t\tfprintf(['\\n',set_name(el_set,:),'\\n\\n']);\n\t\t\t\t[el_sphc,el_name] = sys1020_62 ;\n case 9\n Fchannels = spm_select(1, '\\.mat$', 'Select channel template file', ...\n {}, fullfile(spm('dir'), 'EEGtemplates'));\n [Fpath,Fname] = fileparts(Fchannels);\n elec = load(Fchannels);\n el_sphc = elec.pos(:,1:3)';\n el_name = elec.allelecs;\n case 10\n Fchannels = spm_select(1, '\\.mat$', 'Select channel template file', ...\n {}, fullfile(spm('dir'), 'EEGtemplates'));\n [Fpath,Fname] = fileparts(Fchannels);\n elec = load(Fchannels);\n try\n [el_sphc,el_name] = treatCTF(elec,Fname);\n catch\n el_sphc = elec.pos3D;\n el_name = elec.Cnames;\n end\n\t\t\totherwise\n\t\t\t\twarning('Unknown electrodes set !!!')\n el_sphc = []; el_name = [];\n\t\tend\n if ~iscell(el_name)\n el_name = cellstr(el_name);\n end\n catch\n error(['Provide the electrode set number : from 1 to ',num2str(length(Nr_electr))])\n end\nend\n\nreturn\n\n%________________________________________________________________________\n%\n% Subfunctions defining the electrode sets\n%\n%________________________________________________________________________\n% FORMAT el_sphc = sysXXXX ;\n%\n% Genrates a set of electrode coordinates on a sphere.\n% Other sets can be added here, as long as the format is respected :\n% \tel_sphc\t: 3xNel coordinates on a radius 1 sphere\n%\tNel\t: nr of electrodes\n%------------------------------------------------------------------------\nfunction [el_sphc,el_name] = sys1020_23 ;\n\n% Classic 10-20 system with 23 usefull electrodes\n% The mastoid electrodes (A1-A2) are located on the hemispheric plane\n\nd2r=pi/180; % converts degrees to radian\nFpz = [ 0 sin(72*d2r) cos(72*d2r) ] ;\nFp1 = [ -sin(72*d2r)*sin(18*d2r) sin(72*d2r)*cos(18*d2r) cos(72*d2r) ] ;\nF7 = [ -sin(72*d2r)*sin(54*d2r) sin(72*d2r)*cos(54*d2r) cos(72*d2r) ] ;\nT3 = [ -sin(72*d2r) 0 cos(72*d2r) ] ;\nC3 = [ -sin(36*d2r) 0 cos(36*d2r) ] ;\nCz = [ 0 0 1 ] ;\nFz = [ 0 sin(36*d2r) cos(36*d2r) ] ;\ntemp=Fz+F7 ;\nF3=temp/norm(temp);\n\nel_sphc=[ Fp1 ;\t\t\t\t\t\t% Fp1\n\tFpz\t\t\t\t\t\t% Fpz\n\t-Fp1(1)\t \tFp1(2) \t\tFp1(3) ;\t% Fp2\n\tF7 ;\t\t\t\t\t\t% F7\n\tF3 ;\t\t\t\t\t\t% F3\n\tFz ;\t\t\t\t\t\t% Fz\n\t-F3(1)\t\tF3(2)\t\tF3(3) ;\t\t% F4\n\t-F7(1)\t\tF7(2) \t\tF7(3) ;\t\t% F8\n\t-1\t\t0\t\t0 ;\t\t% A1\n\tT3 ;\t\t\t\t\t\t% T3\n\tC3 ;\t\t\t\t\t\t% C3\n\tCz ;\t\t\t\t\t\t% Cz\n\t-C3(1)\t\tC3(2)\t\tC3(3) ;\t\t% C4\n\t-T3(1)\t\tT3(2)\t\tT3(3) ;\t\t% T4\n\t1\t\t0\t\t0 ;\t\t% A2\n\tF7(1)\t\t-F7(2)\t\tF7(3) ;\t\t% T5\n\tF3(1)\t\t-F3(2)\t\tF3(3) ;\t\t% P3\n\tFz(1)\t\t-Fz(2) \t\tFz(3) ;\t\t% Pz\n\t-F3(1)\t\t-F3(2)\t\tF3(3) ;\t\t% P4\n\t-F7(1)\t\t-F7(2)\t\tF7(3) ;\t\t% T6\n\tFp1(1)\t \t-Fp1(2)\t \tFp1(3) ;\t% O1\n\tFpz(1)\t\t-Fpz(2) \tFpz(3) ;\t% Oz\n\t-Fp1(1)\t \t-Fp1(2) \tFp1(3) ]' ;\t% O2\nel_name = str2mat('Fp1','Fpz','Fp2', ...\n\t\t 'F7','F3','Fz','F4','F8', ...\n\t\t 'A1','T3','C3','Cz','C4','T4','A2', ...\n\t\t 'T5','P3','Pz','P4','T6', ...\n\t\t 'O1','Oz','O2') ;\nreturn\n%------------------------------------------------------------------------\nfunction [el_sphc,el_name] = sys1020_19 ;\n\n% Classic 10-20 system with 19 usefull electrodes\n% The mastoid electrodes (A1-A2) would be located on the hemispheric plane\n% Compared with the previous set, electrodes Fpz, A1, A2 & Oz are removed\n\nd2r=pi/180; % converts degrees to radian\nFpz = [ 0 sin(72*d2r) cos(72*d2r) ] ;\nFp1 = [ -sin(72*d2r)*sin(18*d2r) sin(72*d2r)*cos(18*d2r) cos(72*d2r) ] ;\nF7 = [ -sin(72*d2r)*sin(54*d2r) sin(72*d2r)*cos(54*d2r) cos(72*d2r) ] ;\nT3 = [ -sin(72*d2r) 0 cos(72*d2r) ] ;\nC3 = [ -sin(36*d2r) 0 cos(36*d2r) ] ;\nCz = [ 0 0 1 ] ;\nFz = [ 0 sin(36*d2r) cos(36*d2r) ] ;\ntemp=Fz+F7 ;\nF3=temp/norm(temp);\n\nel_sphc=[ Fp1 ;\t\t\t\t\t\t% Fp1\n\t-Fp1(1)\t \tFp1(2) \t\tFp1(3) ;\t% Fp2\n\tF7 ;\t\t\t\t\t\t% F7\n\tF3 ;\t\t\t\t\t\t% F3\n\tFz ;\t\t\t\t\t\t% Fz\n\t-F3(1)\t\tF3(2)\t\tF3(3) ;\t\t% F4\n\t-F7(1)\t\tF7(2) \t\tF7(3) ;\t\t% F8\n\tT3 ;\t\t\t\t\t\t% T3\n\tC3 ;\t\t\t\t\t\t% C3\n\tCz ;\t\t\t\t\t\t% Cz\n\t-C3(1)\t\tC3(2)\t\tC3(3) ;\t\t% C4\n\t-T3(1)\t\tT3(2)\t\tT3(3) ;\t\t% T4\n\tF7(1)\t\t-F7(2)\t\tF7(3) ;\t\t% T5\n\tF3(1)\t\t-F3(2)\t\tF3(3) ;\t\t% P3\n\tFz(1)\t\t-Fz(2) \t\tFz(3) ;\t\t% Pz\n\t-F3(1)\t\t-F3(2)\t\tF3(3) ;\t\t% P4\n\t-F7(1)\t\t-F7(2)\t\tF7(3) ;\t\t% T6\n\tFp1(1)\t \t-Fp1(2)\t \tFp1(3) ;\t% O1\n\t-Fp1(1)\t \t-Fp1(2) \tFp1(3) ]' ;\t% O2\nel_name = str2mat('Fp1','Fp2', ...\n\t\t 'F7','F3','Fz','F4','F8', ...\n\t\t 'T3','C3','Cz','C4','T4', ...\n\t\t 'T5','P3','Pz','P4','T6', ...\n\t\t 'O1','O2') ;\nreturn\n%------------------------------------------------------------------------\nfunction [el_sphc,el_name] = sys1020_29 ;\n\n% Classic 10-20 system with 29 useful electrodes\n% The mastoid electrodes (A1-A2) are located on the hemispheric plane\n% Intermediate locations at 10% are used here, hence a few \"classic\"\n% electrodes have different names (EG. T8=T4, P8=T6, T7=T3, P7=T5\n\nd2r=pi/180; % converts degrees to radian\nFpz = [ 0 sin(72*d2r) cos(72*d2r) ] ;\nFp1 = [ -sin(72*d2r)*sin(18*d2r) sin(72*d2r)*cos(18*d2r) cos(72*d2r) ] ;\nF7 = [ -sin(72*d2r)*sin(54*d2r) sin(72*d2r)*cos(54*d2r) cos(72*d2r) ] ;\nT3 = [ -sin(72*d2r) 0 cos(72*d2r) ] ;\nC3 = [ -sin(36*d2r) 0 cos(36*d2r) ] ;\nCz = [ 0 0 1 ] ;\nFz = [ 0 sin(36*d2r) cos(36*d2r) ] ;\nF3 = Fz+F7 ;F3 = F3/norm(F3);\n\nFc5 = F7+F3+T3+C3; Fc5 = Fc5/norm(Fc5);\nFc1 = F3+Fz+C3+Cz; Fc1 = Fc1/norm(Fc1);\n\nel_sphc=[ \t1\t\t0\t\t0 ;\t\t % A2\n\t-F7(1)\t\tF7(2) \t\tF7(3) ;\t\t% F8\n\t-T3(1)\t\tT3(2)\t\tT3(3) ;\t\t% T8=T4 or flipped T3\n\t-F7(1)\t\t-F7(2)\t\tF7(3) ;\t\t% P8=T6\n -Fc5(1) Fc5(2) Fc5(3) ; % Fc6\n -Fc5(1) -Fc5(2) Fc5(3) ; % Cp6\n\t-Fp1(1)\t \tFp1(2) \t\tFp1(3) ;\t% Fp2\n\t-F3(1)\t\tF3(2)\t\tF3(3) ;\t\t% F4\n\t-C3(1)\t\tC3(2)\t\tC3(3) ;\t\t% C4\n \t-F3(1)\t\t-F3(2)\t\tF3(3) ;\t\t% P4\n \t-Fp1(1)\t \t-Fp1(2) \tFp1(3) ;\t% O2\n -Fc1(1) Fc1(2) Fc1(3) ; % Fc2\n -Fc1(1) -Fc1(2) Fc1(3) ; % Cp2\n\tFz ;\t\t\t\t\t\t % Fz\n\tCz ;\t\t\t\t\t\t % Cz\n\tFz(1)\t\t-Fz(2) \t\tFz(3) ;\t\t% Pz\n Fc1 % Fc1\n Fc1(1) -Fc1(2) Fc1(3) ; % Cp1\n Fp1 ;\t\t\t\t\t\t % Fp1\n F3 ;\t\t\t\t\t\t % F3\n\tC3 ;\t\t\t\t\t\t % C3\n\tF3(1)\t\t-F3(2)\t\tF3(3) ;\t\t% P3\n\tFp1(1)\t \t-Fp1(2)\t \tFp1(3) ;\t% O1\n Fc5 ; % Fc5\n Fc5(1) -Fc5(2) Fc5(3) ; % Cp5\n\tF7 ;\t\t\t\t\t\t % F7\n\tT3 ;\t\t\t\t\t\t % T7=T3\n\tF7(1)\t\t-F7(2)\t\tF7(3) ;\t\t% P7=T5\n\t-1\t\t 0\t\t 0 ]' ; % A1\n\nel_name = strvcat('A2','F8','T8','P8','Fc6','Cp6', ...\n 'Fp2','F4','C4','P4','O2','Fc2','Cp2', ...\n 'Fz','Cz','Pz','Fc1','Cp1', ...\n 'Fp1','F3','C3','P3','O1','Fc5','Cp5', ...\n 'F7','T7','P7','A1') ;\nreturn\n%------------------------------------------------------------------------\nfunction [el_sphc,el_name] = sys61 ;\n\n% 61 quasi-equidistant electrodes, as used on the easycap.\n%\n\nd2r = pi/180 ;\nNe_pr = [ 6 12 15 16 14 ] ;\n\t% Number of electrodes per \"ring\", from top to bottom\n\t% Cz is assumed to be perfectly on top [0 0 1]\n\nN_r = length(Ne_pr) ;\ndth = 90 * d2r / N_r ;\n\nel_sphc = [0 0 1] ;\nfor i=1:N_r\n\tthet = i * dth ;\n\tsth = sin(thet) ;\n\tcth = cos(thet) ;\n\tl_phi = (90:-360/Ne_pr(i):-269)*d2r ;\n\tfor phi=l_phi\n\t\tel_sphc = [ el_sphc ; sth*cos(phi) sth*sin(phi) cth ] ;\n\tend\nend\n\n% remove 3 frontal electrodes at the level of eyes.\nel_sphc([51 52 64],:) = [] ;\nel_sphc = el_sphc';\nel_name = num2str((1:61)');\n%figure,plot3(el_sphc(1,:),el_sphc(2,:),el_sphc(3,:),'*');axis vis3d;rotate3d on\nreturn\n%------------------------------------------------------------------------\nfunction [el_sphc,el_name] = sys148 ;\n\n% 148 electrodes spread as in the paper by Pascual-Marqui et al.\n% This si not suitable for a realist head model, as the location of the eyes\n% is ignored...\n\nwarning('This electrode set is not suitable for realistic head model !');\n\nd2r = pi/180 ;\nNe_pr = [ 6 12 17 21 23 24 23 21 ] ;\nel_sphc = [0 0 1] ;\nN_r = length(Ne_pr) ;\ndth = 90 * d2r / (1+length(find(diff(Ne_pr)>0))) ;\n\t% Number of electrodes per \"ring\", from top to bottom\n\t% The nr of electr per ring decreases under the hemispheric line\n\t% Cz is assumed to be perfectly on top [0 0 1]\n\nfor i=1:N_r\n\tthet = i * dth ;\n\tsth = sin(thet) ;\n\tcth = cos(thet) ;\n\tdphi = - 360 / Ne_pr(i) * d2r ;\n\tphi0 = (1-rem(i,2)) * dphi / 2 ;\n\tfor j=1:Ne_pr(i)\n\t\tphi = phi0 + (j-1)*dphi ;\n\t\tel_sphc = [ el_sphc ; -sth*sin(phi) sth*cos(phi) cth ] ;\n\tend\nend\nel_sphc = el_sphc';\nel_name = num2str((1:148)');\n%figure,plot3(el_sphc(1,:),el_sphc(2,:),el_sphc(3,:),'*');axis vis3d;rotate3d on\nreturn\n\n%------------------------------------------------------------------------\nfunction [el_sphc,el_name] = sys1020_62 ;\n\n% Classic 10-20 system with 62 useful electrodes\n% The mastoid electrodes (A1-A2) are located on the hemispheric plane\n% Intermediate locations at 10% are used here, hence a few \"classic\"\n% electrodes have different names (eg. T8=T4, P8=T6, T7=T3, P7=T5\n\nd2r=pi/180; % converts degrees to radian\n\n% Electrodes on the front left quarter\n%-------------------------------------\n% Main electrodes\nFPz = [ 0 sin(72*d2r) cos(72*d2r) ] ;\nFP1 = [ -sin(72*d2r)*sin(18*d2r) sin(72*d2r)*cos(18*d2r) cos(72*d2r) ] ;\nAF7 = [ -sin(72*d2r)*sin(36*d2r) sin(72*d2r)*cos(36*d2r) cos(72*d2r) ] ;\nF7 = [ -sin(72*d2r)*sin(54*d2r) sin(72*d2r)*cos(54*d2r) cos(72*d2r) ] ;\nFT7 = [ -sin(72*d2r)*sin(72*d2r) sin(72*d2r)*cos(72*d2r) cos(72*d2r) ] ;\nT7 = [ -sin(72*d2r) 0 cos(72*d2r) ] ;\nC5 = [ -sin(54*d2r) 0 cos(54*d2r) ] ;\nC3 = [ -sin(36*d2r) 0 cos(36*d2r) ] ;\nC1 = [ -sin(18*d2r) 0 cos(18*d2r) ] ;\nAFz = [ 0 sin(54*d2r) cos(54*d2r) ] ;\nFz = [ 0 sin(36*d2r) cos(36*d2r) ] ;\nRef = [ 0 sin(18*d2r) cos(18*d2r) ] ;\nCz = [ 0 0 1 ] ;\nTP9 = [ -sin(108*d2r) cos(108*d2r) 0 ] ;\n\n% Intermediate electrodes\nAF3 = AF7+AFz ; AF3 = AF3/norm(AF3);\nF3 = Fz+F7 ; F3 = F3 /norm(F3);\nFC3 = FT7+Ref ; FC3 = FC3/norm(FC3);\nF5 = F7+F3 ; F5 = F5 /norm(F5);\nF1 = Fz+F3 ; F1 = F1 /norm(F1);\nFC5 = FT7+FC3 ; FC5 = FC5/norm(FC5);\nFC1 = Ref+FC3 ; FC1 = FC1/norm(FC1);\n\n% Note, there is no A1/A2 inthis montage but TP9 and TP10\n\nel_sphc=[ FP1 ; % Fp1\n FPz ; % Fpz\n\t-FP1(1)\t \tFP1(2) \t\tFP1(3) ;\t% Fp2\n AF7 ; % AF7\n AF3 ; % AF3\n AFz ; % AFz\n -AF3(1) AF3(2) AF3(3) ; % AF4\n -AF7(1) AF7(2) AF7(3) ; % AF8\n F7 ; % F7\n F5 ; % F5\n F3 ;\t\t\t\t\t\t % F3\n F1 ;\t\t\t\t\t\t % F1\n Fz ;\t\t\t\t\t\t % Fz\n\t-F1(1)\t \tF1(2) \t\tF1(3) ;\t % F2\n -F3(1) F3(2) F3(3) ; % F4\n -F5(1) F5(2) F5(3) ; % F6\n -F7(1) F7(2) F7(3) ; % F8\n FT7 ; % FT7\n FC5 ; % FC5\n FC3 ; % FC3\n FC1 ; % FC1\n\t-FC1(1)\t \tFC1(2) \t\tFC1(3) ;\t% FC2\n\t-FC3(1)\t \tFC3(2) \t\tFC3(3) ;\t% FC4\n\t-FC5(1)\t \tFC5(2) \t\tFC5(3) ;\t% FC6\n\t-FT7(1)\t \tFT7(2) \t\tFT7(3) ;\t% FT8\n T7 ; % T7\n C5 ; % C5\n C3 ; % C3\n C1 ; % C1\n\tCz ;\t\t\t\t\t\t % Cz\n\t-C1(1)\t\tC1(2)\t\tC1(3) ;\t\t% C2\n\t-C3(1)\t\tC3(2)\t\tC3(3) ;\t\t% C4\n\t-C5(1)\t\tC5(2)\t\tC5(3) ;\t\t% C6\n -T7(1) T7(2) T7(3) ; % T8 Start posteririor part\n TP9 ; % TP9\n\tFT7(1)\t \t-FT7(2) FT7(3) ;\t% TP7\n\tFC5(1)\t \t-FC5(2)\t\tFC5(3) ;\t% CP5\n\tFC3(1)\t \t-FC3(2) \tFC3(3) ;\t% CP3\n\tFC1(1)\t \t-FC1(2)\t\tFC1(3) ;\t% CP1\n Ref(1) -Ref(2) Ref(3) ; % Cpz\n\t-FC1(1)\t \t-FC1(2)\t\tFC1(3) ;\t% CP2\n\t-FC3(1)\t \t-FC3(2) \tFC3(3) ;\t% CP3\n\t-FC5(1)\t \t-FC5(2)\t\tFC5(3) ;\t% CP6\n\t-FT7(1)\t \t-FT7(2) FT7(3) ;\t% TP8\n -TP9(1) TP9(2) TP9(3) ; % TP10\n F7(1) -F7(2) F7(3) ; % P7\n F5(1) -F5(2) F5(3) ; % P5\n F3(1) -F3(2) F3(3) ; % P3\n\tF1(1)\t \t-F1(2) \t\tF1(3) ;\t % P1\n\tFz(1)\t\t-Fz(2) \t\tFz(3) ;\t\t% Pz \n \t-F1(1)\t \t-F1(2) \t\tF1(3) ;\t % P2\n -F3(1) -F3(2) F3(3) ; % P4\n -F5(1) -F5(2) F5(3) ; % P6\n -F7(1) -F7(2) F7(3) ; % P8\n AF7(1) -AF7(2) AF7(3) ; % PO7\n AF3(1) -AF3(2) AF3(3) ; % PO3\n AFz(1) -AFz(2) AFz(3) ; % POz\n -AF3(1) -AF3(2) AF3(3) ; % PO4\n -AF7(1) -AF7(2) AF7(3) ; % PO8\n\tFP1(1)\t \t-FP1(2)\t \tFP1(3) ;\t% O1\n\tFPz(1)\t \t-FPz(2)\t \tFPz(3) ;\t% Oz\n \t-FP1(1)\t \t-FP1(2) \tFP1(3) ]';\t% O2\n\nel_name = strvcat('FP1','FPz','FP2','AF7','AF3','AFz','AF4','AF8', ...\n 'F7','F5','F3','F1','Fz','F2','F4','F6','F8', ...\n 'FT7','FC5','FC3','FC1','FC2','FC4','FC6','FT8', ...\n 'T7','C5','C3','C1','Cz','C2','C4','C6','T8', ...\n 'TP9','TP7','CP5','CP3','CP1','CPz','CP2','CP4','CP6','TP8','TP10', ...\n 'P7','P5','P3','P1','Pz','P2','P4','P6','P8', ...\n 'PO7','PO3','POz','PO4','PO8','O1','Oz','O2');\n\nreturn\n\n%________________________________________________________________________\n%\n% A few other subfunctions\n%________________________________________________________________________\n\nfunction [el_sphc,el_name] = treatCTF(elec,Fname);\n% Takes the info from the CTF and creates the standard 3D electrode set\n% from the 2D map.\n\nswitch lower(Fname)\ncase 'ctf275_setup'\n xf = elec.Cpos(1,:)-.45;\n\tyf = elec.Cpos(2,:)-.55;\n\trf = sqrt(xf.^2+yf.^2);\n\txf = xf./max(rf)*pi/2;\n\tyf = yf./max(rf)*pi/2;\n chan_to_remove = [] ; % HEOG & VEOG\ncase '61channels'\n xf = elec.Cpos(1,:)-.5;\n\tyf = elec.Cpos(2,:)-.5;\n\trf = sqrt(xf.^2+yf.^2);\n\txf = xf./max(rf)*pi/2;\n\tyf = yf./max(rf)*pi/2; \n chan_to_remove = [1 2] ; % HEOG & VEOG\notherwise\n error('Unknown CTF')\nend\n[ x, y, z ] = FlatToCart(xf, yf);\nel_sphc = [x;y;z]; el_sphc(:,chan_to_remove) = [];\nel_name = elec.Cnames; el_name(chan_to_remove) = [];\n\nreturn\n\n%________________________________________________________________________\nfunction [ x, y, z ] = FlatToCart(xf, yf)\n% Convert 2D Cartesian Flat Map coordinates into Cartesian \n% coordinates on surface of unit sphere \n\ntheta = atan2(yf,xf);\nphi = xf./cos(theta);\n\nz = sqrt(1./(1+tan(phi).^2));\nrh = sqrt(1-z.^2);\nx = rh.*cos(theta);\ny = rh.*sin(theta);\n\nreturn\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_bilinear.m", "ext": ".m", "path": "spm5-master/spm_bilinear.m", "size": 3613, "source_encoding": "utf_8", "md5": "7f238feffb3fabfd9fb371f41cf46a02", "text": "function [H0,H1,H2] = spm_bilinear(A,B,C,D,x0,N,dt)\n% returns global Volterra kernels for a MIMO Bilinear system\n% FORMAT [H0,H1,H2] = spm_bilinear(A,B,C,D,x0,N,dt)\n% A - (n x n) df(x(0),0)/dx - n states\n% B - (n x n x m) d2f(x(0),0)/dxdu - m inputs\n% C - (n x m) df(x(0),0)/du - d2f(x(0),0)/dxdu*x(0)\n% D - (n x 1) f(x(0).0) - df(x(0),0)/dx*x(0)\n% x0 - (n x 1) x(0)\n% N - kernel depth {intervals}\n% dt - interval {seconds}\n%\n% Volterra kernels:\n%\n% H0 - (n) \t = h0(t) = y(t)\n% H1 - (N x n x m) = h1i(t,s1) = dy(t)/dui(t - s1)\n% H2 - (N x N x n x m x m) = h2ij(t,s1,s2) = d2y(t)/dui(t - s1)duj(t - s2)\n%\n% where n = p if modes are specified\n%___________________________________________________________________________\n% Returns Volterra kernels for bilinear systems of the form\n%\n% dx/dt = f(x,u) = A*x + B1*x*u1 + ... Bm*x*um + C1u1 + ... Cmum + D\n% y(t) = x(t)\n%\n%---------------------------------------------------------------------------\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Karl Friston \n% $Id: spm_bilinear.m 112 2005-05-04 18:20:52Z john $\n\n\n% Volterra kernels for bilinear systems\n%===========================================================================\n\n% parameters\n%---------------------------------------------------------------------------\nn = size(A,1);\t\t\t\t\t% state variables\nm = size(C,2);\t\t\t\t\t% inputs\nA = full(A);\nB = full(B);\nC = full(C);\nD = full(D);\n\n% eignvector solution {to reduce M0 to leading diagonal form}\n%---------------------------------------------------------------------------\nM0 = [0 zeros(1,n); D A];\n[U J] = eig(M0);\nV = pinv(U);\n\n% Lie operator {M0}\n%---------------------------------------------------------------------------\nM0 = sparse(J);\nX0 = V*[1; x0];\n\n% 0th order kernel\n%---------------------------------------------------------------------------\nH0 = ex(N*dt*M0)*X0;\n\n% 1st order kernel\n%---------------------------------------------------------------------------\nif nargout > 1\n\n\t% Lie operator {M1}\n\t%-------------------------------------------------------------------\n\tfor i = 1:m\n\t\tM1(:,:,i) = V*[0 zeros(1,n); C(:,i) B(:,:,i)]*U;\n\tend\n\n\t% 1st order kernel\n\t%-------------------------------------------------------------------\n\tH1 = zeros(N,n + 1,m);\n\tfor p = 1:m\n\tfor i = 1:N\n\t\tu1 = N - i + 1;\n\t\tH1(u1,:,p) = ex(u1*dt*M0)*M1(:,:,p)*ex(-u1*dt*M0)*H0;\n\tend\n\tend\nend\n\n% 2nd order kernels\n%---------------------------------------------------------------------------\nif nargout > 2\n\tH2 = zeros(N,N,n + 1,m,m);\n\tfor p = 1:m\n\tfor q = 1:m\n\tfor j = 1:N\n\t\tu2 = N - j + 1;\n\t\tu1 = N - [1:j] + 1;\n\t\tH = ex(u2*dt*M0)*M1(:,:,q)*ex(-u2*dt*M0)*H1(u1,:,p)';\n\t\tH2(u2,u1,:,q,p) = H';\n\t\tH2(u1,u2,:,p,q) = H';\n\tend\n\tend\n\tend\nend\n\n% project to state space and remove kernels associated with the constant \n%---------------------------------------------------------------------------\nif nargout > 0\n\tH0 = real(U*H0);\n\tH0 = H0([1:n] + 1);\nend\nif nargout > 1\n\tfor p = 1:m\n\t\tH1(:,:,p) = real(H1(:,:,p)*U.');\n\tend\n\tH1 = H1(:,[1:n] + 1,:);\nend\nif nargout > 1\n\tfor p = 1:m\n\tfor q = 1:m\n\tfor j = 1:N\n\t\tH2(j,:,:,p,q) = real(squeeze(H2(j,:,:,p,q))*U.');\n\tend\n\tend\n\tend\n\tH2 = H2(:,:,[1:n] + 1,:,:);\nend\n\nreturn\n\n% matrix exponential function (for diagonal matrices)\n%---------------------------------------------------------------------------\nfunction y = ex(x)\nn = length(x);\ny = spdiags(exp(diag(x)),0,n,n);\nreturn\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_powell.m", "ext": ".m", "path": "spm5-master/spm_powell.m", "size": 7978, "source_encoding": "utf_8", "md5": "063a0beec40aebe20cbadf483220393b", "text": "function [p,f] = spm_powell(p,xi,tolsc,func,varargin)\n% Powell optimisation method\n% FORMAT [p,f] = spm_powell(p,xi,tolsc,func,varargin)\n% \tp - Starting parameter values\n%\txi - columns containing directions in which to begin\n% \t searching.\n% \ttolsc - stopping criteria\n% \t - optimisation stops when\n% \t sqrt(sum(((p-p_prev)./tolsc).^2))<1\n% \tfunc - name of evaluated function\n% \tvarargin - remaining arguments to func (after p)\n%\n% \tp - final parameter estimates\n% \tf - function value at minimum\n%\n%_______________________________________________________________________\n% Method is based on Powell's optimisation method described in\n% Numerical Recipes (Press, Flannery, Teukolsky & Vetterling).\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_powell.m 691 2006-11-22 17:44:19Z john $\n\n\np = p(:);\nf = feval(func,p,varargin{:});\nfor iter=1:512,\n\tif numel(p)>1, fprintf('iteration %d...\\n', iter); end;\n\tibig = numel(p); \n\tpp = p;\n\tfp = f;\n\tdel = 0;\n\tfor i=1:length(p),\n\t\tft = f;\n\t\t[p,junk,f] = min1d(p,xi(:,i),func,f,tolsc,varargin{:});\n\t\tif abs(ft-f) > del,\n\t\t\tdel = abs(ft-f);\n\t\t\tibig = i;\n\t\tend;\n\tend;\n\tif numel(p)==1 || sqrt(sum(((p(:)-pp(:))./tolsc(:)).^2))<1, return; end;\n\tft = feval(func,2.0*p-pp,varargin{:});\n\tif ft < f,\n\t\t[p,xi(:,ibig),f] = min1d(p,p-pp,func,f,tolsc,varargin{:});\n\tend;\nend;\nwarning('Too many optimisation iterations');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [p,pi,f] = min1d(p,pi,func,f,tolsc,varargin)\n% Line search for minimum.\n\nglobal lnm % used in funeval\nlnm = struct('p',p,'pi',pi,'func',func,'args',[]);\nlnm.args = varargin;\n\nmin1d_plot('Init', 'Line Minimisation','Function','Parameter Value');\nmin1d_plot('Set', 0, f);\n\ntol = 1/sqrt(sum((pi(:)./tolsc(:)).^2));\nt = bracket(f);\n[f,pmin] = search(t,tol);\npi = pi*pmin;\np = p + pi;\n\nfor i=1:length(p), fprintf('%-8.4g ', p(i)); end;\nfprintf('| %.5g\\n', f);\nmin1d_plot('Clear');\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction f = funeval(p)\n% Reconstruct parameters and evaluate.\n\nglobal lnm % defined in min1d\npt = lnm.p+p.*lnm.pi;\nf = feval(lnm.func,pt,lnm.args{:});\nmin1d_plot('Set',p,f);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction t = bracket(f)\n% Bracket the minimum (t(2)) between t(1) and t(3)\n\ngold = (1+sqrt(5))/2; % Golden ratio\n\nt(1) = struct('p',0,'f',f);\nt(2).p = 1;\nt(2).f = funeval(t(2).p);\n\n% if t(2) not better than t(1) then swap\nif t(2).f > t(1).f,\n\tt(3) = t(1);\n\tt(1) = t(2);\n\tt(2) = t(3);\nend;\n\nt(3).p = t(2).p + gold*(t(2).p-t(1).p);\nt(3).f = funeval(t(3).p);\n\nwhile t(2).f > t(3).f,\n\n\t% fit a polynomial to t\n\ttmp = cat(1,t.p)-t(2).p;\n\tpol = pinv([ones(3,1) tmp tmp.^2])*cat(1,t.f);\n\n\t% minimum is when gradient of polynomial is zero\n\t% sign of pol(3) (the 2nd deriv) should be +ve\n\tif pol(3)>0,\n\t\t% minimum is when gradient of polynomial is zero\n\t\td = -pol(2)/(2*pol(3)+eps);\n\n\t\t% A very conservative constraint on the displacement\n\t\tif d > (1+gold)*(t(3).p-t(2).p),\n\t\t\td = (1+gold)*(t(3).p-t(2).p);\n\t\tend;\n\t\tu.p = t(2).p+d;\n\telse,\n\t\t% sign of pol(3) (the 2nd deriv) is not +ve\n\t\t% so extend out by golden ratio instead\n\t\tu.p = t(3).p+gold*(t(3).p-t(2).p);\n\tend;\n\n\t% FUNCTION EVALUATION\n\tu.f = funeval(u.p);\n\n\tif (t(2).p < u.p) == (u.p < t(3).p),\n\n\t\t% u is between t(2) and t(3)\n\t\tif u.f < t(3).f,\n\t\t\t% minimum between t(2) and t(3) - done\n\t\t\tt(1) = t(2);\n\t\t\tt(2) = u;\n\t\t\treturn;\n\t\telseif u.f > t(2).f,\n\t\t\t% minimum between t(1) and u - done\n\t\t\tt(3) = u;\n\t\t\treturn;\n\t\tend;\n\tend;\n\n\t% Move all 3 points along\n\tt(1) = t(2);\n\tt(2) = t(3);\n\tt(3) = u;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [f,p] = search(t, tol)\n% Brent's method for line searching - given that minimum is bracketed\n\ngold1 = 1-(sqrt(5)-1)/2;\n\n% Current and previous displacements\nd = Inf;\npd = Inf;\n\n% sort t into best first order\n[junk,ind] = sort(cat(1,t.f));\nt = t(ind);\nbrk = [min(cat(1,t.p)) max(cat(1,t.p))];\n\nfor iter=1:128,\n\t% check stopping criterion\n\tif abs(t(1).p - 0.5*(brk(1)+brk(2)))+0.5*(brk(2)-brk(1)) <= 2*tol,\n\t\tp = t(1).p;\n\t\tf = t(1).f;\n\t\treturn;\n\tend;\n\n\t% keep last two displacents\n\tppd = pd;\n\tpd = d;\n\n\t% fit a polynomial to t\n\ttmp = cat(1,t.p)-t(1).p;\n\tpol = pinv([ones(3,1) tmp tmp.^2])*cat(1,t.f);\n\n\t% minimum is when gradient of polynomial is zero\n\td = -pol(2)/(2*pol(3)+eps);\n\tu.p = t(1).p+d;\n\n\t% check so that displacement is less than the last but two,\n\t% that the displaced point is between the brackets\n\t% and that the solution is a minimum rather than a maximum\n\teps2 = 2*eps*abs(t(1).p)+eps;\n\tif abs(d) > abs(ppd)/2 | u.p < brk(1)+eps2 | u.p > brk(2)-eps2 | pol(3)<=0,\n\t\t% if criteria are not met, then golden search into the larger part\n\t\tif t(1).p >= 0.5*(brk(1)+brk(2)),\n\t\t\td = gold1*(brk(1)-t(1).p);\n\t\telse,\n\t\t\td = gold1*(brk(2)-t(1).p);\n\t\tend;\n\t\tu.p = t(1).p+d;\n\tend;\n\n\t% FUNCTION EVALUATION\n\tu.f = funeval(u.p);\n\n\t% Insert the new point into the appropriate position and update\n\t% the brackets if necessary\n\tif u.f <= t(1).f,\n\t\tif u.p >= t(1).p, brk(1)=t(1).p; else, brk(2)=t(1).p; end;\n\t\tt(3) = t(2);\n\t\tt(2) = t(1);\n\t\tt(1) = u;\n\telse,\n\t\tif u.p < t(1).p, brk(1)=u.p; else, brk(2)=u.p; end;\n\t\tif u.f <= t(2).f,\n\t\t\tt(3) = t(2);\n\t\t\tt(2) = u;\n\t\telseif u.f <= t(3).f,\n\t\t\tt(3) = u;\n\t\tend;\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction min1d_plot(action,arg1,arg2,arg3,arg4)\n% Visual output for line minimisation\npersistent min1dplot\n%-----------------------------------------------------------------------\nif (nargin == 0)\n\tmin1d_plot('Init');\nelse\n\t% initialize\n\t%---------------------------------------------------------------\n\tif (strcmp(lower(action),'init'))\n\t\tif (nargin<4)\n\t\t\targ3 = 'Function';\n\t\t\tif (nargin<3)\n\t\t\t\targ2 = 'Value';\n\t\t\t\tif (nargin<2)\n\t\t\t\t\targ1 = 'Line minimisation';\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tfg = spm_figure('FindWin','Interactive');\n\n\t\tif ~isempty(fg)\n\t\t\tmin1dplot = struct('pointer',get(fg,'Pointer'),'name',get(fg,'Name'),'ax',[]);\n\t\t\tmin1d_plot('Clear');\n\t\t\tset(fg,'Pointer','watch');\n\t\t\t% set(fg,'Name',arg1);\n\t\t\tmin1dplot.ax = axes('Position', [0.15 0.1 0.8 0.75],...\n\t\t\t\t'Box', 'on','Parent',fg);\n\t\t\tlab = get(min1dplot.ax,'Xlabel');\n\t\t\tset(lab,'string',arg3,'FontSize',10);\n\t\t\tlab = get(min1dplot.ax,'Ylabel');\n\t\t\tset(lab,'string',arg2,'FontSize',10);\n\t\t\tlab = get(min1dplot.ax,'Title');\n\t\t\tset(lab,'string',arg1);\n\t\t\tline('Xdata',[], 'Ydata',[],...\n\t\t\t\t'LineWidth',2,'Tag','LinMinPlot','Parent',min1dplot.ax,...\n\t\t\t\t'LineStyle','-','Marker','o');\n\t\t\tdrawnow;\n\t\tend\n\n\t% reset\n\t%---------------------------------------------------------------\n\telseif (strcmp(lower(action),'set'))\n\t\tF = spm_figure('FindWin','Interactive');\n\t\tbr = findobj(F,'Tag','LinMinPlot');\n\t\tif (~isempty(br))\n\t\t\t[xd,indx] = sort([get(br,'Xdata') arg1]);\n\t\t\tyd = [get(br,'Ydata') arg2];\n\t\t\tyd = yd(indx);\n\t\t\tset(br,'Ydata',yd,'Xdata',xd);\n\t\t\tdrawnow;\n\t\tend\n\n\t% clear\n\t%---------------------------------------------------------------\n\telseif (strcmp(lower(action),'clear'))\n\t\tfg = spm_figure('FindWin','Interactive');\n\t\tif isstruct(min1dplot),\n\t\t\tif ishandle(min1dplot.ax), delete(min1dplot.ax); end;\n\t\t\tset(fg,'Pointer',min1dplot.pointer);\n\t\t\tset(fg,'Name',min1dplot.name);\n\t\tend;\n\t\tspm_figure('Clear',fg);\n\t\tdrawnow;\n\tend;\nend\n%_______________________________________________________________________\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_vol.m", "ext": ".m", "path": "spm5-master/spm_vol.m", "size": 5542, "source_encoding": "utf_8", "md5": "eb6c5a42448d73ffcb5701c148093c4f", "text": "function V = spm_vol(P)\n% Get header information etc for images.\n% FORMAT V = spm_vol(P)\n% P - a matrix of filenames.\n% V - a vector of structures containing image volume information.\n% The elements of the structures are:\n% V.fname - the filename of the image.\n% V.dim - the x, y and z dimensions of the volume\n% V.dt - A 1x2 array. First element is datatype (see spm_type).\n% The second is 1 or 0 depending on the endian-ness.\n% V.mat - a 4x4 affine transformation matrix mapping from\n% voxel coordinates to real world coordinates.\n% V.pinfo - plane info for each plane of the volume.\n% V.pinfo(1,:) - scale for each plane\n% V.pinfo(2,:) - offset for each plane\n% The true voxel intensities of the jth image are given\n% by: val*V.pinfo(1,j) + V.pinfo(2,j)\n% V.pinfo(3,:) - offset into image (in bytes).\n% If the size of pinfo is 3x1, then the volume is assumed\n% to be contiguous and each plane has the same scalefactor\n% and offset.\n%____________________________________________________________________________\n%\n% The fields listed above are essential for the mex routines, but other\n% fields can also be incorporated into the structure.\n%\n% The images are not memory mapped at this step, but are mapped when\n% the mex routines using the volume information are called.\n%\n% Note that spm_vol can also be applied to the filename(s) of 4-dim\n% volumes. In that case, the elements of V will point to a series of 3-dim\n% images.\n%\n% This is a replacement for the spm_map_vol and spm_unmap_vol stuff of\n% MatLab4 SPMs (SPM94-97), which is now obsolete.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_vol.m 982 2007-10-26 14:01:54Z john $\n\nif nargin==0,\n V = struct('fname', {},...\n 'dim', {},...\n 'dt', {},...\n 'pinfo', {},...\n 'mat', {},...\n 'n', {},...\n 'descrip', {},...\n 'private',{});\n return;\nend;\n\n% If is already a vol structure then just return;\nif isstruct(P), V = P; return; end;\n\nV = subfunc2(P);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction V = subfunc2(P)\nif iscell(P),\n V = cell(size(P));\n for j=1:numel(P),\n if iscell(P{j}),\n V{j} = subfunc2(P{j});\n else\n V{j} = subfunc1(P{j});\n end;\n end;\nelse\n V = subfunc1(P);\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction V = subfunc1(P)\nif isempty(P),\n V = [];\n return;\nend;\n\ncounter = 0;\nfor i=1:size(P,1),\n v = subfunc(P(i,:));\n\t[V(counter+1:counter+size(v, 2),1).fname] = deal('');\n\t[V(counter+1:counter+size(v, 2),1).mat] = deal([0 0 0 0]);\n\t[V(counter+1:counter+size(v, 2),1).mat] = deal(eye(4));\n\t[V(counter+1:counter+size(v, 2),1).mat] = deal([1 0 0]');\n if isempty(v),\n hread_error_message(P(i,:));\n error(['Can''t get volume information for ''' P(i,:) '''']);\n end\n\n f = fieldnames(v);\n for j=1:size(f,1)\n eval(['[V(counter+1:counter+size(v,2),1).' f{j} '] = deal(v.' f{j} ');']);\n end\n counter = counter + size(v,2);\nend\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction V = subfunc(p)\n[pth,nam,ext,n1] = spm_fileparts(deblank(p));\np = fullfile(pth,[nam ext]);\nn = str2num(n1);\nif ~exist(p,'file'),\n existance_error_message(p);\n error('File \"%s\" does not exist.', p);\nend\nswitch ext,\n case {'.nii','.NII'},\n % Do nothing\n\n case {'.img','.IMG'},\n if ~exist(fullfile(pth,[nam '.hdr']),'file') && ~exist(fullfile(pth,[nam '.HDR']),'file'),\n existance_error_message(fullfile(pth,[nam '.hdr'])),\n error('File \"%s\" does not exist.', fullfile(pth,[nam '.hdr']));\n end\n\n case {'.hdr','.HDR'},\n ext = '.img';\n p = fullfile(pth,[nam ext]);\n if ~exist(p,'file'),\n existance_error_message(p),\n error('File \"%s\" does not exist.', p);\n end\n\n otherwise,\n error('File \"%s\" is not of a recognised type.', p);\nend\n\nif isempty(n),\n V = spm_vol_nifti(p);\nelse\n V = spm_vol_nifti(p,n);\nend;\n \nif isempty(n) && length(V.private.dat.dim) > 3\n V0(1) = V;\n for i = 2:V.private.dat.dim(4)\n V0(i) = spm_vol_nifti(p, i);\n end\n V = V0;\nend\nif ~isempty(V), return; end;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction hread_error_message(q)\nstr = {...\n\t'Error reading information on:',...\n\t[' ',spm_str_manip(q,'k40d')],...\n\t' ',...\n\t'Please check that it is in the correct format.'};\nspm('alert*',str,mfilename,sqrt(-1));\nreturn;\n%_______________________________________________________________________\nfunction existance_error_message(q)\nstr = {...\n 'Unable to find file:',...\n [' ',spm_str_manip(q,'k40d')],...\n ' ',...\n 'Please check that it exists.'};\nspm('alert*',str,mfilename,sqrt(-1));\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_jobman.m", "ext": ".m", "path": "spm5-master/spm_jobman.m", "size": 97869, "source_encoding": "utf_8", "md5": "1db2d5463418dcdf0a80c81d7cb7705a", "text": "function varargout = spm_jobman(varargin)\n% UI/Batching stuff\n%_______________________________________________________________________\n% This code is based on an earlier version by Philippe Ciuciu and\n% Guillaume Flandin of Orsay, France.\n%\n% FORMAT spm_jobman\n% spm_jobman('interactive')\n% spm_jobman('interactive',job)\n% spm_jobman('interactive',job,node)\n% spm_jobman('interactive','',node)\n% Runs the user interface in interactive mode.\n%\n% FORMAT spm_jobman('serial')\n% spm_jobman('serial',job)\n% spm_jobman('serial',job,node)\n% spm_jobman('serial','',node)\n% Runs the user interface in serial mode.\n%\n% FORMAT spm_jobman('run',job)\n% Runs a job.\n%\n% FORMAT spm_jobman('run_nogui',job)\n% Runs a job without X11 (as long as there is no graphics output from the\n% job itself).\n%\n% FORMAT spm_jobman('help',node)\n% spm_jobman('help',node,width)\n% Creates a cell array containing help information. This is justified\n% to be 'width' characters wide. e.g.\n% h = spm_jobman('help','jobs.spatial.coreg.estimate');\n% for i=1:numel(h),fprintf('%s\\n',h{i}); end;\n%\n% FORMAT spm_jobman('jobhelp')\n% Creates a cell array containing help information specific for a certain\n% job. Help is only printed for items where job specific help is\n% present. This can be used together with spm_jobman('help') to create a\n% job specific manual. This feature is available only on MATLAB R14SP2\n% and higher.\n%\n% node - indicates which part of the configuration is to be used.\n% For example, it could be 'jobs.spatial.coreg'.\n%\n% job - can be the name of a jobfile (as a .mat or a .xml), or a\n% 'jobs' variable loaded from a jobfile.\n%\n% FORMAT spm_jobman('defaults')\n% Runs the interactive defaults editor.\n%\n% FORMAT spm_jobman('pulldown')\n% Creates a pulldown 'TASKS' menu in the Graphics window.\n%\n% FORMAT spm_jobman('chmod')\n% Changes the modality for the TASKS pulldown.\n%\n% FORMAT [tag, jobs, typ, jobhelps] = spm_jobman('harvest',c)\n% Take a data structure, and extract what is needed to save it\n% as a batch job (for experts only). If c is omitted, use the currently\n% displayed job tree as source.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_jobman.m 1862 2008-06-30 14:12:49Z volkmar $\n\n\nif nargin==0\n setup_ui;\nelse\n switch lower(varargin{1})\n case {'interactive'}\n if nargin>=2\n setup_ui(varargin{2:nargin});\n else\n setup_ui;\n end;\n\n case {'serial'}\n if nargin>=2,\n serial(varargin{2:nargin});\n else\n serial;\n end;\n\n case {'run'}\n if nargin<2\n error('Nothing to run');\n end;\n run_job(varargin{2});\n\n case {'run_nogui'}\n if nargin<2\n error('Nothing to run');\n end;\n run_job(varargin{2},0);\n\n case {'defaults'},\n setup_ui('defaults');\n\n case {'pulldown'}\n pulldown;\n\n case {'chmod'}\n if nargin>1,\n chmod(varargin{2});\n end;\n\n case {'help'}\n if nargin>=2,\n varargout{1} = showdoc(varargin{2:nargin});\n else\n varargout{1} = showdoc;\n end;\n\n case {'jobhelp'}\n varargout{1} = showjobhelp;\n\n case {'harvest'}\n if nargin == 1\n args{1} = get(batch_box,'Userdata');\n else\n args = varargin(2:nargin);\n end;\n [varargout{1:nargout}] = harvest(args{:});\n \n case {'initcfg'}\n\n otherwise\n error(['\"' varargin{1} '\" - unknown option']);\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction defaults_edit(varargin)\nsetup_ui('defaults');\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction interactive(varargin)\nud = get(varargin{1},'UserData');\nif iscell(ud)\n setup_ui(ud{:});\nelse\n setup_ui;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction setup_ui(varargin)\n% Configure the user interface\n\nfg = clearwin;\nfs = getdef('ui.fs');\nif numel(fs)~=1 || ~isnumeric(fs{1}) || numel(fs{1})~=1,\n fs = 12;\nelse\n fs = fs{1};\nend;\n\ncol1 = getdef('ui.colour1');\nif numel(col1)~=1 || ~isnumeric(col1{1}) || numel(col1{1})~=3,\n col1 = [0.8 0.8 1];\nelse\n col1 = col1{1};\nend;\n\ncol2 = getdef('ui.colour2');\nif numel(col2)~=1 || ~isnumeric(col2{1}) || numel(col2{1})~=3,\n col2 = [1 1 0.8];\nelse\n col2 = col2{1};\nend;\n\ncol3 = getdef('ui.colour3');\nif numel(col3)~=1 || ~isnumeric(col3{1}) || numel(col3{1})~=3,\n col3 = [0 0 0];\nelse\n col3 = col3{1};\nend;\n\nt=uicontrol(fg,...\n 'Style','listbox',...\n 'Units','normalized',...\n 'Position',[0.02 0.31 0.48 0.67],...\n 'Callback',@click_batch_box,...\n 'Tag','batch_box',...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col1,...\n 'FontSize',fs,...\n 'Value',1);\nc0 = cntxtmnu(t);\nc1 = uimenu('Label','Exp/Con All', 'Parent',c0);\nuimenu('Label','Expand All', 'Parent',c1,'Callback',@expandall);\nuimenu('Label','Contract All', 'Parent',c1,'Callback',@contractall);\nuimenu('Label','Expand All Undefined Inputs', 'Parent',c1,'Callback',@expandallopen);\n\nt=uicontrol(fg,...\n 'Style','listbox',...\n 'ListBoxTop',1,...\n 'Units','normalized',...\n 'Position',[0.02 0.02 0.96 0.25],...\n 'Tag','help_box',...\n 'FontName','fixedwidth',...\n 'FontSize',fs,...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col2);\nset(t,'Value',[], 'Enable', 'inactive', 'Max',2, 'Min',0);\nworkaround(t);\ncntxtmnu(t);\n\nif spm_matlab_version_chk('7.1')>=0\n t=uibuttongroup('parent',fg,...\n 'units','normalized', ...\n 'position',[.02 .27 .5 .03],...\n 'tag','help_box_switch', ...\n 'SelectionChangeFcn',@click_batch_box);\n t1=uicontrol('parent',t,...\n 'style','radio',...\n 'string','General help', ...\n 'units','normalized',...\n 'position',[0 .05 .5 .95]);\n l2=uicontrol('parent',t,...\n 'style','radio',...\n 'string','Job specific help', ...\n 'units','normalized',...\n 'position',[.5 .05 .5 .95]);\nend;\n\nt=uicontrol(fg,...\n 'Style','listbox',...\n 'Units','normalized',...\n 'Position',[0.51 0.74 0.47 0.24],...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col1,...\n 'FontSize',fs,...\n 'Tag','opts_box');\ncntxtmnu(t);\n\nt=uicontrol(fg,...\n 'Style','listbox',...\n 'Units','normalized',...\n 'Position',[0.51 0.49 0.47 0.24],...\n 'Tag','val_box',...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col2,...\n 'Enable', 'inactive',...\n 'Value',[],...\n 'FontSize',fs,...\n 'Max',2, 'Min',0);\nset(t,'Value',[], 'Enable', 'on', 'Max',2, 'Min',0,'ListBoxTop',1);\ncntxtmnu(t);\n\nt=uicontrol(fg,...\n 'Style','listbox',...\n 'Units','normalized',...\n 'Position',[0.51 0.38 0.47 0.10],...\n 'Tag','msg_box',...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col2,...\n 'Enable', 'inactive',...\n 'Value',[],...\n 'FontSize',fs,...\n 'Max',2, 'Min',0);\ncntxtmnu(t);\n\nif ~(nargin==1 && ischar(varargin{1}) && strcmp(varargin{1},'defaults')),\n t=uicontrol(fg,...\n 'style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.51 0.31 0.15 0.06],...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col1,...\n 'String','Save',...\n 'Callback',@save_job,...\n 'FontSize',fs,...\n 'Tag','save');\n cntxtmnu(t);\n\n t=uicontrol(fg,...\n 'style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.67 0.31 0.15 0.06],...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col1,...\n 'String','Load',...\n 'Callback',@load_job,...\n 'FontSize',fs,...\n 'Tag','load');\n cntxtmnu(t);\n\n t=uicontrol(fg,...\n 'style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.83 0.31 0.15 0.06],...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col1,...\n 'String','Run',...\n 'Callback',@run_struct,...\n 'Tag','run',...\n 'FontSize',fs,...\n 'Enable', 'off');\n cntxtmnu(t);\n if nargin>0\n initialise(varargin{:});\n else\n initialise;\n end;\nelse\n t=uicontrol(fg,...\n 'style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.51 0.31 0.15 0.06],...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col1,...\n 'String','OK',...\n 'FontSize',fs,...\n 'Callback',@ok_defaults);\n cntxtmnu(t);\n\n t=uicontrol(fg,...\n 'style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.67 0.31 0.15 0.06],...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col1,...\n 'String','Reset',...\n 'FontSize',fs,...\n 'Callback',@reset_defaults);\n cntxtmnu(t);\n\n t=uicontrol(fg,...\n 'style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.83 0.31 0.15 0.06],...\n 'ForegroundColor', col3,...\n 'BackgroundColor',col1,...\n 'String','Cancel',...\n 'FontSize',fs,...\n 'Callback',@clearwin);\n cntxtmnu(t);\n initialise('defaults');\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction ok_defaults(varargin)\nharvest_def(get(batch_box,'UserData'));\nclearwin;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction reset_defaults(varargin)\nglobal defaults\n\nmodality = [];\nif isfield(defaults,'modality'),\n modality = defaults.modality;\nend;\nspm_defaults;\nif ~isfield(defaults,'modality') && ~isempty(modality),\n defaults.modality = modality;\nend;\npulldown;\nclearwin;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction fg = clearwin(varargin)\n\nfg = spm_figure('findwin','Graphics');\nif isempty(fg), fg = spm_figure('Create','Graphics'); end;\ndelete(findobj(fg,'Parent',fg));\ndelete(batch_box);\ndelete(opts_box);\nspm('Pointer');\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction expandall(varargin)\nc = expcon(get(batch_box,'UserData'),1);\nstr = get_strings(c);\nval = min(get(batch_box,'Value'),length(str));\nset(batch_box,'String',str,'Value',val,'UserData',c);\nupdate_ui;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction contractall(varargin)\nc = expcon(get(batch_box,'UserData'),0);\nstr = get_strings(c);\nval = min(get(batch_box,'Value'),length(str));\nset(batch_box,'String',str,'Value',val,'UserData',c);\nupdate_ui;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction expandallopen(varargin)\nc = expopen(get(batch_box,'UserData'));\nstr = get_strings(c);\nfop = Inf;\n% find 1st open input\nfor k=1:numel(str)\n op = strfind(str{k},'<-X');\n if ~isempty(op)\n fop=k;\n break;\n end;\nend;\nif isinf(fop)\n val = min(get(batch_box,'Value'),length(str));\nelse\n val = fop;\nend;\nset(batch_box,'String',str,'Value',val,'UserData',c);\nupdate_ui;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [c,sts] = expopen(c)\nsts = 0;\nif ~isstruct(c)||~isfield(c,'type')\n return;\nend;\n\nsts=~all_set(c);\n\nif isfield(c,'val'),\n for i=1:length(c.val),\n [c.val{i} sts1] = expopen(c.val{i});\n sts = sts||sts1;\n end;\nend;\nif isfield(c,'expanded')\n c.expanded = sts;\nend;\nsts = sts||isfield(c,'prog');\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = expcon(c,val)\nif isfield(c,'expanded'), c.expanded = val; end;\nif isfield(c,'val'),\n for i=1:length(c.val),\n c.val{i} = expcon(c.val{i},val);\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction initialise(job,node)\n% load the config file, possibly adding a job\n% to it, and generally tidy it up. The batch box\n% is updated to contain the current structure.\nfiles_select_list('init');\nif nargin<1, job = ''; end;\nif nargin<2, node = 'jobs'; end;\nc = initialise_struct(job);\nset(batch_box,'UserData',start_node(c,node));\nexpandallopen;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction run_job(job,gui)\n% Run a job. This function is not called via the UI.\nif nargin ==1, gui = 1; end\nc = initialise_struct(job);\nif all_set(c),\n run_struct1(c,gui);\nelse\n error('This job is not ready yet');\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction click_batch_box(varargin)\n% Called when the batch box is clicked\n\nremove_string_box;\nif strcmp(get(get(varargin{1},'Parent'),'SelectionType'),'open')\n run_in_current_node(@expand_contract,false);\n str = get_strings(get(batch_box,'UserData'));\n val = min(get(batch_box,'Value'),length(str));\n set(batch_box,'String',str,'Value',val);\nelse\n run_in_current_node(@click_batch_box_fun,false);\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction update_ui\n[str,sts] = get_strings(get(batch_box,'UserData'));\nval = min(get(batch_box,'Value'),length(str));\nset(batch_box,'String',str,'Value',val);\nrun_in_current_node(@click_batch_box_fun,false);\n\nrun_but = findobj(0,'Tag','run');\nif sts\n set(run_but,'Enable', 'on');\nelse\n set(run_but,'Enable', 'off');\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [str,sts] = get_strings(c)\n[unused,str,sts] = start_node(c,@get_strings1,0);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [c,str,sts] = get_strings1(c,l)\n% Return the cell vector of strings displayed in the batch\n% box, and also whether the job is runable. This is a recursive\n% function that a branch of the data structure is passed to.\n\nif isfield(c,'hidden'),\n sts = 1;\n str = '';\n return;\nend;\n\nsts = 1;\nmrk = ' ';\nnam = '';\nif isfield(c,'datacheck') && ~isempty(c.datacheck),\n mrk = ' <-@';\n sts = 0;\nend;\nif isfield(c,'name'), nam = c.name; end;\n\nif isfield(c,'expanded') % && isfield(c,'val') && ~isempty(c.val)\n\n if strcmp(c.type,'repeat') && isfield(c,'num')\n sts = (length(c.val) >= c.num(1)) &&...\n (length(c.val) <= c.num(2));\n if ~sts\n mrk = ' <-X';\n end;\n end;\n\n if c.expanded\n if numel(c.val) == 0\n premark = '';\n else\n premark = '-';\n end\n str = {[repmat('. ',1,l) premark nam]};\n for i=1:length(c.val)\n [c.val{i},str1,sts1] = get_strings1(c.val{i},l+1);\n sts = sts && sts1;\n if ~isempty(str1),\n str = {str{:},str1{:}};\n end;\n end;\n else\n if numel(c.val) == 0\n premark = '';\n else\n premark = '+';\n end\n str = {[repmat('. ',1,l) premark nam]};\n for i=1:length(c.val)\n [c.val{i},unused,sts1] = get_strings1(c.val{i},l+1);\n sts = sts && sts1;\n end;\n if ~sts,\n mrk = ' <-X';\n end;\n end;\n str{1} = [str{1} mrk];\n\nelse\n switch c.type\n case 'files'\n % If files are selected via \"Input to/Output from\" shortcuts,\n % there is no guarantee that an allowed number of files is\n % specified. This is checked here.\n cn = c.num;\n if (numel(cn) == 1)\n if isfinite(cn)\n cn = [cn cn];\n else\n cn = [0 cn];\n\n end;\n end;\n if isempty(c.val) || (numel(c.val{1}) < cn(1)) || ...\n (numel(c.val{1}) > cn(2))\n mrk = ' <-X';\n sts = 0;\n end;\n case {'menu','entry','const','choice'}\n if isempty(c.val)\n mrk = ' <-X';\n sts = 0;\n end;\n case 'repeat' % don't know, whether this ever gets executed\n if isfield(c,'num')\n sts = (length(c.val) >= c.num(1)) &&...\n (length(c.val) <= c.num(2));\n if ~sts\n mrk = ' <-X';\n end;\n end;\n end;\n str = {[repmat('. ',1,l) ' ' nam mrk]};\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction ok = all_set(c)\n% Return whether all the necessary fields have been filled in.\n% This is a recursive function that a branch of the data structure\n% is passed to.\n\nif isfield(c,'hidden'),\n ok = true;\n return;\nend;\n\nok = true;\n\nswitch c.type\n case {'files','menu','entry','const','choice'}\n if isempty(c.val)\n ok = false;\n end;\n\n case {'branch','repeat'}\n if strcmp(c.type,'repeat') && isfield(c,'num')\n ok = ok && (length(c.val) >= c.num(1)) && ...\n (length(c.val) <= c.num(2));\n end;\n if ok,\n for i=1:length(c.val),\n ok1 = all_set(c.val{i});\n ok = ok && ok1;\n if ~ok, break; end;\n end;\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction click_options_box(varargin)\n% The function called when the options box is clicked\n\ndat = get(opts_box,'UserData');\nif ~isempty(dat)\n fun = dat{get(opts_box,'Value')};\n run_in_current_node(fun.fun,true,fun.args{:});\n if fun.redraw, update_ui; end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction varargout = run_in_current_node(varargin)\n% Get the current node, and run a job in it\nvarargout = {};\nc = get(batch_box,'UserData');\nn = get(batch_box,'Value');\nshow_msg('');\nva = {c,@run_in_current_node1,n,varargin{:}};\n[c,unused,varargout{:}] = start_node(va{:});\nset(batch_box,'UserData',c);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [c,varargout] = start_node(c,fun,varargin)\npersistent node;\nif isempty(node)\n node = {'jobs'};\nend;\nvarargout = {};\nif nargin==2\n tmp = [0 find([fun '.']=='.')];\n node = {};\n for i=1:length(tmp)-1\n node = {node{:},fun((tmp(i)+1):(tmp(i+1)-1))};\n end;\n c = make_nodes(c,node);\n return;\nend;\nva = {c,node,fun,varargin{:}};\n[c,unused,varargout{1:nargout-1}] = start_node1(va{:});\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = make_nodes(c,node)\nif isfield(c,'tag') && ~strcmp(gettag(c),node{1})\n return;\nend;\nif isfield(c,'tag')\n node = {node{2:end}};\n if isempty(node), return; end;\nend;\nif isfield(c,'values') && (~isfield(c,'val') ||...\n isempty(c.val) || ~iscell(c.val) ||...\n ~strcmp(gettag(c.val{1}),node{1}))\n for i=1:length(c.values)\n if strcmp(gettag(c.values{i}),node{1})\n c.val = {c.values{i}};\n c.val{1} = make_nodes(c.val{1},node);\n end;\n end;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [c,sts,varargout] = start_node1(c,node,fun,varargin)\nvarargout = {};\nif nargin<4, varargin = {}; end;\nif isfield(c,'tag') && ~strcmp(gettag(c),node{1})\n varargout = cell(1,nargout-2);\n sts = 0;\n return;\nend;\nif isfield(c,'tag'),\n node = {node{2:end}};\nend;\nif isempty(node)\n [c,varargout{1:nargout-2}] = feval(fun,c,varargin{:});\n sts = 1;\n return;\nend;\nif isfield(c,'val'),\n for i=1:length(c.val)\n [c.val{i},sts,varargout{1:nargout-2}] = start_node1(c.val{i},node,fun,varargin{:});\n if sts, return; end;\n end;\nend;\nkeyboard\nerror('No such node'); % Should never execute\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [c,n,varargout] = run_in_current_node1(c,n,fun,modify,varargin)\n% Satellite for run_in_current_node\n\nvarargout = {};\nif nargin<5, varargin = {}; end;\nif isfield(c,'hidden'), return; end;\n\nn = n-1;\nif n<0, return; end;\nif n==0,\n % if ~isfield(c,'datacheck'),\n % show_msg('');\n % else\n % show_msg(c.datacheck);\n % end;\n [c,varargout{:}] = feval(fun,c,varargin{:});\nend;\n\nif isfield(c,'expanded') && ~isempty(c.val)\n if c.expanded,\n val = c.val;\n c.val = {};\n for i=1:length(val)\n [tmp,n,varargout{:}] = run_in_current_node1(val{i},n,fun,modify,varargin{:});\n if ~isempty(tmp)\n if iscell(tmp)\n c.val = {c.val{:}, tmp{:}};\n else\n c.val = {c.val{:}, tmp};\n end;\n end;\n end;\n end;\nend;\nif modify && isfield(c,'check'),\n if all_set(c),\n [unused,val] = harvest(c);\n c.datacheck = feval(c.check,val);\n end;\nend;\nif isfield(c,'datacheck') && ~isempty(c.datacheck),\n show_msg(c.datacheck);\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = click_batch_box_fun(c,unused)\n% Mostly set up the options box, but also update the help and value boxes\n\nif ~isempty(opts_box)\n dat = {};\n str = {};\n\n switch c.type\n case {'const'}\n % do nothing\n\n case {'files'}\n spm('pointer','watch');\n str = {str{:}, 'Specify Files'};\n dat = {dat{:}, struct('fun',@file_select,'args',{{}},'redraw',1)};\n addvfiles(c.id,[],c);\n addinfiles(c);\n [filestr filedat] = files_select_list('listall');\n str = {str{:}, filestr{:}};\n dat = {dat{:}, filedat{:}};\n spm('pointer','arrow');\n\n case {'menu'}\n str = {str{:}, 'Specify Menu Item'};\n dat = {dat{:}, struct('fun',@menu_entry,'args',{{}},'redraw',0)};\n\n case {'entry'}\n str = {str{:}, 'Specify Text'};\n dat = {dat{:}, struct('fun',@text_entry,'args',{{}},'redraw',1)};\n\n case {'branch','choice','repeat'}\n if strcmp(c.type,'repeat')\n for i=1:length(c.values)\n if ~isfield(c.values{i},'hidden'),\n str = {str{:},['New \"' c.values{i}.name '\"']};\n dat = {dat{:}, struct('fun',@series,'args',{{c.values{i}}},'redraw',1)};\n end;\n end;\n\n elseif strcmp(c.type,'choice')\n for i=1:length(c.values)\n if ~isfield(c.values{i},'hidden'),\n str = {str{:},['Choose \"' c.values{i}.name '\"']};\n dat = {dat{:}, struct('fun',@choose,'args',{{c.values{i}}},'redraw',1)};\n end;\n end;\n end;\n end;\n\n if isfield(c,'removable')\n str = {str{:},['Remove Item \"' c.name '\"'],['Replicate Item \"' c.name '\"']};\n dat = {dat{:}, struct('fun',@remove,'args',{{}},'redraw',1),...\n struct('fun',@replicate,'args',{{}},'redraw',1)};\n end;\n\n if ~same(get(opts_box,'String')',str)\n val = 1;\n else\n val = get(opts_box,'Value');\n end;\n val = max(min(length(str),val),min(1,length(str)));\n set(opts_box,'String',str,'UserData',dat,'Callback',@click_options_box,'Value',val);\nend;\n\nshow_value(c);\n\n% Update help\ntxt = '';\nhs=findobj(0, 'tag','help_box_switch');\ncntxt=get(findobj(0,'tag','help_box'),'UIContextMenu');\nif isempty(hs)||strcmp(c.type, 'repeat')||strcmp(c.type, 'choice')\n % No help box switch created, or node type without context help\n set(hs, 'Visible','Off');\n help_box_switch = 2;\nelse\n set(hs, 'Visible','On');\n hc=get(get(hs,'children'));\n help_box_switch = find(cat(1,hc.Value));\nend;\nswitch help_box_switch\n case 2,\n if isfield(c,'help'), txt = c.help; end;\n set(findobj(cntxt,'tag','cntxt_edit_jobhelp'),'Visible','off');\n case 1,\n if isfield(c,'jobhelp'), txt = c.jobhelp; end;\n if isempty(findobj(cntxt,'tag','cntxt_edit_jobhelp'))\n cedit=uimenu('parent',cntxt,...\n 'Label','Edit help',...\n 'Callback',@edit_jobhelp,...\n 'Tag','cntxt_edit_jobhelp');\n else\n set(findobj(cntxt,'tag','cntxt_edit_jobhelp'),'Visible','on');\n end;\nend;\nhelp_box = findobj(0,'tag','help_box');\nif ~isempty(help_box)\n set(help_box,'String',' ');\n workaround(help_box);\n ext = get(help_box,'Extent');\n pos = get(help_box,'position');\n pw = floor(pos(3)/ext(3)*21-4);\n set(help_box,'String',spm_justify(help_box,txt));\n workaround(help_box);\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = expand_contract(c,unused)\n% Expand/contract a node (for visualisation)\n\nif isfield(c,'expanded') && ~isempty(c.val)\n if c.expanded\n c.expanded = false;\n else\n c.expanded = true;\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = menu_entry(c,unused)\n% Setup opts box for menu entry\n\nif isfield(c,'labels') && isfield(c,'values')\n str = {};\n dat = {};\n if ~isempty(c.val)\n val = c.val{1};\n else\n val = '';\n end;\n dv = 1;\n for i=1:length(c.values)\n if ~(ischar(val) && strcmp(val,'')) && same(c.values{i},val)\n str{i} = ['* ' c.labels{i}];\n dv = i;\n else\n str{i} = [' ' c.labels{i}];\n end;\n dat{i} = struct('fun',@menuval,'args',{{c.values{i}}},'redraw',1);\n end;\n set(opts_box,'String',str,'UserData',dat,'Callback',@click_options_box,'Value',dv);\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [c] = file_select(c)\n% Select files\ntry\n set(batch_box,'Enable', 'inactive');\n set(opts_box, 'Enable', 'inactive');\n\n if ~isempty(c.val),\n sel = c.val{1};\n else\n sel = '';\n end;\n if isfield(c,'dir'),\n dr = c.dir;\n else\n dr = pwd;\n end;\n if isfield(c,'ufilter')\n uf = c.ufilter;\n else\n uf = '.*';\n end;\n [s,ok] = spm_select(c.num,c.filter,c.name,sel,dr,uf);\n if ok, c.val{1} = cellstr(s); end;\n files_select_list('addinfiles', sprintf('Input to \"%s\"', c.name), ...\n c.val{1}, c.id);\ncatch\nend;\nspm_select('clearvfiles');\nset(batch_box,'Enable', 'on');\nset(opts_box, 'Enable', 'on');\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = text_entry(c)\n% Create a string box and prompt, while hiding the opts box\n\nopts_box = findobj(gcf,'tag','opts_box');\npos = get(opts_box,'Position');\nset(opts_box,'Visible','off');\nfs = get(opts_box,'FontSize');\nfa = get(opts_box,'FontAngle');\nfw = get(opts_box,'FontWeight');\nclf = get(opts_box,'ForegroundColor');\nclb = get(opts_box,'BackgroundColor');\n\nn = [];\nm = [];\nif isfield(c,'num'), n = c.num; end;\nif isfield(c,'extras'), m = c.extras; end;\n\nnewstring = uicontrol(gcf,...\n 'Style','edit',...\n 'Units','normalized',...\n 'Position',[pos(1:3) pos(4)/2],...\n 'Tag','string_box',...\n 'HorizontalAlignment','left',...\n 'FontSize',fs,...\n 'FontAngle',fa,...\n 'FontWeight',fw,...\n 'ForegroundColor',clf,...\n 'BackgroundColor',clb,...\n 'Callback',@accept_string);\ncntxtmnu(newstring);\n\nstrM='';\nswitch lower(c.strtype)\n case 's', TTstr='enter string';\n case 'e', TTstr='enter expression - evaluated';\n case 'n', TTstr='enter expression - natural number(s)';\n if ~isempty(m), strM=sprintf(' (in [1,%d])',m); TTstr=[TTstr,strM]; end\n case 'w', TTstr='enter expression - whole number(s)';\n if ~isempty(m), strM=sprintf(' (in [0,%d])',m); TTstr=[TTstr,strM]; end\n case 'i', TTstr='enter expression - integer(s)';\n case 'r', TTstr='enter expression - real number(s)';\n if ~isempty(m), TTstr=[TTstr,sprintf(' in [%g,%g]',min(m),max(m))]; end\n case 'c', TTstr='enter indicator vector e.g. 0101... or abab...';\n if ~isempty(m) && isfinite(m), strM=sprintf(' (%d)',m); end\n otherwise, TTstr='enter expression';\nend\n\nif isempty(n), n=NaN; end\nn=n(:); if length(n)==1, n=[n,1]; end; dn=length(n);\nif any(isnan(n)) || (prod(n)==1 && dn<=2) || (dn==2 && min(n)==1 && isinf(max(n)))\n str = '';\n lstr = '';\nelseif dn==2 && min(n)==1\n str = sprintf('[%d]',max(n));\n lstr = [str,'-vector: '];\nelseif dn==2 && sum(isinf(n))==1\n str = sprintf('[%d]',min(n));\n lstr = [str,'-vector(s): '];\nelse\n str='';\n for i = 1:dn,\n if isfinite(n(i)),\n str = sprintf('%s,%d',str,n(i));\n else\n str = sprintf('%s,*',str);\n end\n end\n str = ['[',str(2:end),']'];\n lstr = [str,'-matrix: '];\nend\nstrN = sprintf('%s',lstr);\ncol = get(gcf,'Color');\nuicontrol(gcf,'Style','text',...\n 'Units','normalized',...\n 'BackgroundColor',col,...\n 'String',[strN,strM,TTstr],...\n 'Tag','string_prompt',...\n 'HorizontalAlignment','Left',...\n 'FontSize',fs,...\n 'FontAngle',fa,...\n 'FontWeight',fw,...\n 'Position',[pos(1:3)+[0 pos(4)/2 0] pos(4)/2]);\n\nif isfield(c,'val') && ~isempty(c.val)\n val = c.val{1};\n if ischar(val)\n tmp = val';\n tmp = tmp(:)';\n set(newstring,'String',tmp);\n elseif isnumeric(val)\n if ndims(val)>2,\n set(newstring,'String',['reshape([', num2str(val(:)'), '],[' num2str(size(val)) '])']);\n else\n if size(val,1)==1,\n set(newstring,'String',num2str(val(:)'));\n elseif size(val,2)==1,\n set(newstring,'String',['[' num2str(val(:)') ']''']);\n else\n str = '';\n for i=1:size(val,1),\n str = [str ' ' num2str(val(i,:)) ';'];\n end;\n set(newstring,'String',str);\n end;\n end;\n end;\nend;\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction accept_string(varargin)\n% Accept a typed in string?\nrun_in_current_node(@stringval,true,get(varargin{1},'String'));\nupdate_ui;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction remove_string_box\n% Delete the string box and prompt, making the opts box\n% visible again\ndelete(findobj(0,'Tag','string_box'));\ndelete(findobj(0,'Tag','string_prompt'));\nset(opts_box,'Visible','on');\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction show_value(c)\n% Update the value box\n\nvaltxt = {''};\n% col = [1 0 0];\n\nswitch c.type\n case {'menu'}\n if isfield(c,'val') && ~isempty(c.val)\n if isfield(c,'labels') && isfield(c,'values')\n val = c.val{1};\n for i=1:length(c.values)\n if same(c.values{i},val)\n valtxt = c.labels{i};\n % col = [0 0 0];\n break;\n end;\n end;\n end;\n end;\n\n case {'const','entry'}\n if isfield(c,'val') && ~isempty(c.val)\n val = c.val{1};\n if isempty(val)\n valtxt = '';\n else\n if isnumeric(val)\n sz = size(val);\n if length(sz)>2\n valtxt = sprintf('%dx',sz);\n valtxt = [valtxt(1:(end-1)) ' Numeric Array'];\n else\n valtxt = cell(size(val,1),1);\n for i=1:size(val,1)\n valtxt{i} = sprintf('%14.8g ',val(i,:));\n end;\n end;\n elseif(ischar(val))\n valtxt = val;\n else\n valtxt = 'Can not display';\n end;\n end;\n % col = [0 0 0];\n end;\n\n case {'files'}\n if isfield(c,'val') && ~isempty(c.val)\n if isempty(c.val{1}) || isempty(c.val{1}{1})\n valtxt = '';\n else\n valtxt = c.val{1};\n end;\n % col = [0 0 0];\n end;\n\n case {'choice'}\n if isfield(c,'val') && length(c.val)==1\n valtxt = {'A choice, where',['\"' c.val{1}.name '\"'], 'is selected.'};\n % col = [0.5 0.5 0.5];\n else\n valtxt = {'A choice, with', 'nothing selected.'};\n % col = [0.5 0.5 0.5];\n end;\n\n case {'repeat'}\n ln = length(c.val); s = 's'; if ln==1, s = ''; end;\n valtxt = ['A series containing ' num2str(length(c.val)) ' item' s '.'];\n % col = [0.5 0.5 0.5];\n\n case {'branch'}\n ln = length(c.val); s = 's'; if ln==1, s = ''; end;\n valtxt = {['A branch holding ' num2str(length(c.val)) ' item' s '.']};\n if isfield(c,'prog'),\n valtxt = {valtxt{:}, '', ' User specified values',...\n ' from this branch will be',...\n ' collected and passed to',...\n ' an executable function',...\n ' when the job is run.'};\n end;\n % col = [0.5 0.5 0.5];\n\n otherwise\n valtxt = 'What on earth is this???';\nend;\nval_box = findobj(0,'tag','val_box');\nif ~isempty(val_box)\n % set(val_box,'String',valtxt,'ForegroundColor',col);\n set(val_box,'String',valtxt);\n workaround(val_box);\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = remove(c,varargin)\n% Remove node c\nif strcmp(questdlg(['Remove \"' c.name '\"?'],'Confirm','Yes','No','Yes'),'Yes'),\n c = {};\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = replicate(c,varargin)\n% Replicate node c\nc = {c,uniq_id(c)};\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = choose(c,val)\n% Specify the value of c to be val\nc.val{1} = uniq_id(val);\nc.expanded = true;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = menuval(c,val)\n% Specify the value of c to be val\nc.val{1} = val;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = stringval(c,val)\n% Accept (or not) a typed in string\n\nmsg = 'SUCCESS: Values accepted';\n\nswitch c.strtype\n case {'s'}\n c.val{1} = val;\n show_value(c);\n remove_string_box;\n\n case {'s+'}\n msg = 'FAILURE: Cant do s+ yet';\n beep;\n remove_string_box;\n\n otherwise\n n = Inf;\n if isfield(c,'num')\n n = c.num;\n end;\n if isfield(c,'extras')\n [val,msg] = spm_eeval(val,c.strtype,n,c.extras);\n else\n [val,msg] = spm_eeval(val,c.strtype,n);\n end;\n\n if ischar(val)\n beep;\n msg = ['FAILURE: ' msg];\n else\n c.val{1} = val;\n show_value(c);\n remove_string_box;\n msg = ['SUCCESS: ' msg];\n end;\nend;\nshow_msg(msg);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = series(c,new)\n% Add a new repeat\nc.expanded = true;\nnew.removable = true;\nif isfield(c,'val')\n c.val = {c.val{:},uniq_id(new)};\nelse\n c.val = {uniq_id(new)};\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction setdef(strin,val)\nglobal defaults\n\nif isempty(defaults), spm_defaults; end;\nif ischar(val) && strcmp(val,''), return; end;\no = find(strin=='.');\ndf = cell(1,length(o)+1);\nprev = 1;\nfor i=1:length(o),\n df{i} = strin(prev:(o(i)-1));\n prev = o(i)+1;\nend;\ndf{end} = strin(prev:end);\ndefaults = setdef_sub(defaults,df,val);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction d = setdef_sub(d,df,val)\nif isempty(df),\n d = val;\nelse\n if ~isfield(d,df{1}),d.(df{1}) = []; end;\n d.(df{1}) = setdef_sub(d.(df{1}),df(2:end),val);\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction val = getdef(strin)\n% Get value of one of the SPM defaults\n\nglobal defaults\n\nval = getdef_sub(defaults,strin);\nif ischar(val) && strcmp(val,'')\n val = {};\nelse\n val = {val};\nend;\n%fprintf('%s\\n',strin);\n%disp(val)\n%disp('----');\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = getdef_sub(defs,field)\n% Satellite function for getdef\n\no = find(field=='.');\nif isempty(o)\n if isfield(defs,field)\n c = defs.(field);\n else\n c = '';\n end;\n return;\nend;\nif isfield(defs,field(1:(o-1)))\n c = getdef_sub(defs.(field(1:(o-1))),field((o+1):end));\nelse\n c = '';\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction t = same(a,b)\n% Are two data structures identical?\n\n% Innocent until proven guilty\nt = true;\n\n% Check the dimensions\nif isempty(a) && isempty(b)\n t = true; return;\nend;\nsa = size(a);\nsb = size(b);\nif length(sa) ~= length(sb)\n t = false; return;\nend;\nif ~all(sa==sb)\n t = false; return;\nend;\n\n% Check the classes\nca = class(a);\nif ~strcmp(ca,class(b)), t = false; return; end;\n\n% Recurse through data structure\nswitch ca\n case {'double','single','sparse','char','int8','uint8',...\n 'int16','uint16','int32','uint32','logical'}\n msk = ((a==b) | (isnan(a)&isnan(b)));\n if ~all(msk(:)), t = false; return; end;\n\n case {'struct'}\n fa = fieldnames(a);\n fb = fieldnames(b);\n if length(fa) ~= length(fb), t = false; return; end;\n for i=1:length(fa)\n if ~strcmp(fa{i},fb{i}), t = false; return; end;\n for j=1:length(a)\n if ~same(a(j).(fa{i}),b(j).(fb{i}))\n t = false; return;\n end;\n end;\n end;\n\n case {'cell'}\n for j=1:length(a(:))\n if ~same(a{j},b{j}), t = false; return; end;\n end;\n\n case {'function_handle'}\n if ~strcmp(func2str(a),func2str(b))\n t = false; return;\n end;\n\n otherwise\n warning(['Unknown class \"' ca '\"']);\n t = false;\nend;\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction t = batch_box\nt = findobj(0,'tag','batch_box');\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction t = opts_box\nt = findobj(0,'tag','opts_box');\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction save_job(varargin)\n% Save a batch job\n% if job has been loaded from somewhere, cd into this directory for file selection\nljobs = get(findobj(0,'tag','load'),'Userdata');\ncll = {'*.mat','Matlab .mat file';'*.m','Matlab script file';'*.xml','XML file'};\nif ~isempty(ljobs) && ischar(ljobs)\n [spwd unused defext] = fileparts(ljobs(1,:));\n ccll = false(1,size(cll,1));\n for k = 1:size(cll,1),\n ccll(k) = ~isempty(strfind(cll{k,1},defext));\n end;\n cll = [cll(ccll,:); cll(~ccll,:)];\nelse\n spwd = pwd;\nend;\nopwd = pwd;\ncd(spwd);\n[filename, pathname, FilterIndex] = uiputfile(cll,'Save job as');\ncd(opwd);\nif ischar(filename)\n spm('Pointer','Watch');\n c = get(batch_box,'UserData');\n [unused,jobs,unused,jobhelps] = harvest(c);\n %eval([tag '=val;']);\n [unused,unused,ext] = fileparts(filename);\n if isempty(ext)\n ext = cll{FilterIndex}(2:end);\n filename = [filename ext];\n end\n switch ext\n case '.xml',\n savexml(fullfile(pathname,filename),'jobs','jobhelps');\n case '.mat',\n if spm_matlab_version_chk('7') >= 0,\n save(fullfile(pathname,filename),'-V6','jobs','jobhelps');\n else\n save(fullfile(pathname,filename),'jobs','jobhelps');\n end;\n case '.m',\n treelist('jobs','jobhelps',struct('exps',1, 'dval',2, 'fname', ...\n fullfile(pathname,filename)));\n otherwise\n questdlg(['Unknown extension (' ext ')'],'Nothing saved','OK','OK');\n end;\nend;\nspm('Pointer');\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction load_job(varargin)\n% Load a set of batch jobs and possibly merge it\nljobs = get(findobj(0,'tag','load'),'Userdata');\nif ~isempty(ljobs) && ischar(ljobs)\n spwd = fileparts(ljobs(1,:));\nelse\n spwd = pwd;\nend;\n[jobfiles sts] = spm_select([1 Inf], 'batch', 'Load job file(s)',[],spwd);\nif sts\n spm('Pointer','Watch');\n initialise(jobfiles);\n set(gcbo,'Userdata',jobfiles);\n spm('Pointer');\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction run_struct(varargin,gui)\n% Get data structure from handle, and run it\n% If an error occured, then return to user interface\nif nargin ==1, gui = 1; end\nc = get(batch_box,'UserData');\n[unused,job] = harvest(c);\ntry\n run_struct1(c,gui);\ncatch\n l = lasterror;\n fprintf('\\nError running job: %s\\n', l.message);\n if isfield(l,'stack'), % Does not always exist\n for k = 1:numel(l.stack),\n % Don't blame jobman if some other code crashes\n if strcmp(l.stack(k).name,'run_struct1'), break; end;\n try,\n fp = fopen(l.stack(k).file,'r');\n str = fread(fp,Inf,'*uchar');\n fclose(fp);\n str = char(str(:)');\n re = regexp(str,'\\$Id: \\w+\\.\\w+ ([0-9]+) [0-9][0-9][0-9][0-9].*\\$','tokens');\n if numel(re)>0 && numel(re{1})>0,\n id = [' (v', re{1}{1}, ')'];\n else\n id = ' (???)';\n end\n catch,\n id = '';\n end\n fprintf('In file \"%s\"%s, function \"%s\" at line %d.\\n', ...\n l.stack(k).file, id, l.stack(k).name, l.stack(k).line);\n end\n end\n setup_ui(job);\n %if spm_matlab_version_chk('7') >= 0\n % rethrow(l);\n %else\n % disp(lasterr);\n %end\nend;\ndisp('--------------------------');\ndisp('Done.');\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction run_struct1(c,gui)\n% Run a batch job from a data structure\nif nargin ==1, gui = 1; end\n\nif isfield(c,'prog')\n prog = c.prog;\n [unused,val] = harvest(c);\n disp('--------------------------');\n disp(['Running \"' c.name '\"']);\n if gui\n [Finter,unused,CmdLine] = spm('FnUIsetup',c.name);\n spm('Pointer','Watch');\n spm('FigName',[c.name ': running'],Finter,CmdLine);\n end\n if 0\n try\n feval(prog,val);\n if gui\n spm('FigName',[c.name ': done'],Finter,CmdLine);\n end\n catch\n disp(['An error occurred when running \"' c.name '\"']);\n disp( '--------------------------------');\n disp(lasterr);\n disp( '--------------------------------');\n if gui\n spm('FigName',[c.name ': failed'],Finter,CmdLine);\n end\n errordlg({['An error occurred when running \"' c.name '\"'],lasterr},'SPM Jobs');\n end;\n if gui, spm('Pointer'); end\n else\n feval(prog,val);\n if gui\n spm('FigName',[c.name ': done'],Finter,CmdLine);\n spm('Pointer');\n end\n end;\n\nelse\n if isfield(c,'val')\n for i=1:length(c.val)\n run_struct1(c.val{i},gui);\n end;\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction harvest_def(c)\nswitch c.type,\n case{'const','menu','files','entry'},\n if isfield(c,'def') && numel(c.val)==1,\n setdef(c.def,c.val{1});\n end;\n\n otherwise\n for i=1:length(c.val),\n harvest_def(c.val{i});\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [tag,val,typ,jobhelp] = harvest(c)\n% Take a data structure, and extract what is needed to save it\n% as a batch job\n\ntag = 'unknown';\nval = [];\ntyp = c.type;\nif isfield(c,'jobhelp')\n jobhelp.jobhelp = c.jobhelp;\nelse\n jobhelp = [];\nend;\n\nswitch(typ)\n case {'const','menu','files','entry'}\n tag = gettag(c);\n if ~isempty(c.val)\n val = c.val{1};\n else\n val = '';\n end;\n if isfield(c,'jobhelp')\n jobhelp = c.jobhelp;\n end;\n case {'branch'}\n tag = gettag(c);\n if isfield(c,'val')\n val = [];\n for i=1:length(c.val)\n [tag1,val1,unused,jobhelp1] = harvest(c.val{i});\n val.(tag1) = val1;\n jobhelp.(tag1) = jobhelp1;\n end;\n end;\n\n case {'repeat'}\n tag = gettag(c);\n if length(c.values)==1 && strcmp(c.values{1}.type,'branch'),\n cargs = {};\n for i=1:numel(c.values{1}.val),\n cargs = {cargs{:},gettag(c.values{1}.val{i}),{}};\n end;\n val = struct(cargs{:});\n jobhelp = struct(cargs{:});\n if isfield(c,'val')\n for i=1:length(c.val),\n [tag1,val1,typ1,jobhelp1] = harvest(c.val{i});\n val(i) = val1;\n jobhelp(i) = jobhelp1;\n end;\n end;\n else\n val = {};\n jobhelp = {};\n if isfield(c,'val')\n for i=1:length(c.val),\n [tag1,val1,typ1,jobhelp1] = harvest(c.val{i});\n if length(c.values)>1,\n if iscell(val1)\n val1 = struct(tag1,{val1});\n else\n val1 = struct(tag1,val1);\n end;\n if iscell(jobhelp1)\n jobhelp1 = struct(tag1,{jobhelp1});\n else\n jobhelp1 = struct(tag1,jobhelp1);\n end;\n end;\n val = {val{:}, val1};\n jobhelp = {jobhelp{:}, jobhelp1};\n end;\n end;\n end;\n\n case {'choice'}\n if isfield(c,'tag'), tag = gettag(c); end;\n [tag1,val1,unused,jobhelp1] = harvest(c.val{1});\n if iscell(val1)\n val = struct(tag1,{val1});\n else\n val = struct(tag1,val1);\n end;\n if iscell(jobhelp1)\n jobhelp = struct(tag1,{jobhelp1});\n else\n jobhelp = struct(tag1,jobhelp1);\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction tag = gettag(c)\n% Get a tag field - possibly from one of the kids\n\nif (strcmp(c.type,'repeat') || strcmp(c.type,'choice')) && numel(c.values)>0\n tag = gettag(c.values{1});\n for i=2:length(c.values)\n if ~strcmp(tag,gettag(c.values{i}))\n tag = c.tag;\n return;\n end;\n end;\nelse\n tag = c.tag;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c0 = cntxtmnu(ob)\nc0 = uicontextmenu('Parent',get(ob,'Parent'));\nset(ob,'uicontextmenu',c0);\nc1 = uimenu('Label','Font', 'Parent',c0);\nuimenu('Label','Plain', 'Parent',c1,'Callback','set(gco,''FontWeight'',''normal'',''FontAngle'',''normal'');');\nuimenu('Label','Bold', 'Parent',c1,'Callback','set(gco,''FontWeight'',''bold'', ''FontAngle'',''normal'');');\nuimenu('Label','Italic', 'Parent',c1,'Callback','set(gco,''FontWeight'',''normal'',''FontAngle'',''italic'');');\nuimenu('Label','Bold-Italic','Parent',c1,'Callback','set(gco,''FontWeight'',''bold'', ''FontAngle'',''italic'');');\nc1 = uimenu('Label','Fontsize','Parent',c0);\nfs = [8 9 10 12 14 16 18]; % [20 24 28 32 36 44 48 54 60 66 72 80 88 96];\nfor i=fs,\n uimenu('Label',sprintf('%-3d',i),'Parent',c1,'Callback',@fszoom,'UserData',i);\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction workaround(t)\nset(t,'Value',[], 'Enable', 'on', 'Max',2, 'Min',0,'ListBoxTop',1);\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction addvfiles(id,c,c0)\nif (nargin<2)||isempty(c),\n c = get(batch_box,'UserData');\nend;\nif nargin<3\n c0 = [];\nend;\nfiles_select_list('clearvfiles');\nvf =addvfiles1(c,id,{},c0);\nspm_select('clearvfiles');\nspm_select('addvfiles',vf);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [vf,sts]=addvfiles1(c,id,vf,c0)\nsts = 0;\nif ~isstruct(c) || ~isfield(c,'type'),\n return;\nend;\n\nif isfield(c,'vfiles'),\n if ~find_id(c,id),\n [c,unused,ok] = get_strings1(c,0);\n if ok,\n [unused,job] = harvest(c);\n vf1 = feval(c.vfiles,job);\n if ~isempty(c0)\n files = filter_files(c0, vf1);\n else\n files = vf1;\n end;\n if ~isempty(files)\n files_select_list('addvfiles', sprintf('Output from \"%s\"', ...\n c.name), ...\n files, c.id);\n end;\n vf = {vf{:}, vf1{:}};\n end;\n else\n sts = 1;\n end;\n return;\nend;\n\nswitch c.type,\n case {'repeat','choice','branch'},\n for i=1:length(c.val),\n [vf,sts]=addvfiles1(c.val{i},id,vf,c0);\n if sts, return; end;\n end;\nend;\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction addinfiles(c0,c)\nid = c0.id;\nif nargin<2,\n c = get(batch_box,'UserData');\nend;\nfiles_select_list('clearinfiles');\naddinfiles1(c,id,'',c0);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction sts=addinfiles1(c,id,progname,c0)\nsts = 0;\nif ~isstruct(c) || ~isfield(c,'type'),\n return;\nend;\n\nif find_id(c,id),\n sts = 1;\nend;\n\nswitch c.type,\n case 'files'\n if ~isempty(c.val) && ~isempty(c.val{1})\n files = filter_files(c0,c.val{1});\n if ~isempty(files)\n files_select_list('addinfiles', ...\n sprintf('Input to \"%s->%s\"', ...\n progname, c.name), ...\n files, c.id);\n end;\n end;\n case {'repeat','choice','branch'},\n if isfield(c,'prog')\n progname = c.name;\n oldin = files_select_list('getinnum');\n end;\n for i=1:length(c.val),\n sts=addinfiles1(c.val{i},id,progname,c0);\n if sts, return; end;\n end;\n if isfield(c,'prog')\n newin = files_select_list('getinnum');\n if (newin-oldin > 1)\n files_select_list('allinfiles', ...\n sprintf('All inputs to %s',progname),...\n oldin+1, newin);\n end;\n end;\nend;\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction ffiles = filter_files(c,files)\nif strcmp(c.filter, 'image')||strcmp(c.filter,'dir')\n filter = ['ext' c.filter];\nelse\n filter = c.filter;\nend;\nif isfield(c,'ufilter')\n uf = c.ufilter;\n if uf(1) == '^' % This will not work with full pathnames\n uf=uf(2:end);\n end;\nelse\n uf = '.*';\nend;\nffiles = spm_select('filter', files, ...\n filter, uf);\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction varargout = files_select_list(c,varargin)\npersistent vfstr;\npersistent vfdat;\npersistent vffiles;\npersistent vfid;\npersistent instr;\npersistent indat;\npersistent infiles;\npersistent inid;\nif isstruct(c)\n switch lower(varargin{1})\n case 'getvf'\n c.val{1} = vffiles{varargin{2}};\n case 'getin'\n c.val{1} = infiles{varargin{2}};\n end;\n varargout{1} = c;\n return;\nend;\nif ~iscell(vfstr) && ~strcmp(lower(c),'init')\n files_select_list('init');\nend;\nswitch lower(c)\n case 'init'\n vfstr = {};\n vfdat = {};\n vffiles = {};\n vfid = [];\n instr = {};\n indat = {};\n infiles = {};\n inid = [];\n case 'clearvfiles'\n vfstr = {};\n vfdat = {};\n vffiles = {};\n vfid = [];\n case 'clearinfiles'\n instr = {};\n indat = {};\n infiles = {};\n inid = [];\n case 'addvfiles'\n nvfind = numel(vfstr)+1;\n vfid(nvfind) = varargin{3};\n vfstr{nvfind} = varargin{1};\n vfdat{nvfind} = struct('fun',@files_select_list,'args',{{'getvf', nvfind}}, ...\n 'redraw',1);\n vffiles{nvfind} = varargin{2}(:);\n case 'addinfiles'\n ninind = numel(instr)+1;\n inid(ninind) = varargin{3};\n instr{ninind} = varargin{1};\n indat{ninind} = struct('fun',@files_select_list,'args',{{'getin', ninind}}, ...\n 'redraw',1);\n infiles{ninind} = varargin{2}(:);\n case 'allinfiles'\n ninind = numel(instr)+1;\n inid(ninind) = -1;\n instr{ninind} = varargin{1};\n indat{ninind} = struct('fun',@files_select_list,'args',{{'getin', ninind}}, ...\n 'redraw',1);\n infiles{ninind} = cat(1,infiles{varargin{2}:varargin{3}});\n case 'getinnum'\n varargout{1} = numel(instr);\n case 'listall'\n varargout{1} = {vfstr{:} instr{:}};\n varargout{2} = {vfdat{:} indat{:}};\nend\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction ok = find_id(c,id)\nok = 0;\nif ~isstruct(c) || ~isfield(c,'type'),\n return;\nend;\nif c.id==id,\n ok = 1;\n return;\nend;\nif isfield(c,'val'),\n for i=1:length(c.val),\n ok = find_id(c.val{i},id);\n if ok, return; end;\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = uniq_id(c)\nif ~isstruct(c) || ~isfield(c,'type'),\n return;\nend;\nc.id = rand(1);\nif isfield(c,'val'),\n for i=1:length(c.val),\n c.val{i} = uniq_id(c.val{i});\n end;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction show_msg(txt)\nlb = findobj('tag','msg_box');\nif isempty(txt),\n set(lb,'String',{});\nelse\n msg = get(lb,'String');\n if iscell(txt),\n msg = {msg{:} txt{:}};\n else\n msg = {msg{:} txt};\n end;\n set(lb,'String',msg);\nend;\ndrawnow;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\n%function beep\n%fprintf('%c',7);\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction pulldown\n% Create a pulldown for individual jobs\nc = initialise_struct;\nfg = spm_figure('findwin','Graphics');\nif isempty(fg), return; end;\nset(0,'ShowHiddenHandles','on');\ndelete(findobj(fg,'tag','jobs'));\nset(0,'ShowHiddenHandles','off');\nf0 = uimenu(fg,'Label','TASKS','HandleVisibility','off','tag','jobs');\npulldown1(f0,c,c.tag);\nuimenu(f0,'Label','Batch','CallBack',@interactive,'Separator','on');\nuimenu(f0,'Label','Defaults','CallBack',@defaults_edit,'Separator','off');\nf1 = uimenu(f0,'Label','Sequential');\npulldown2(f1,c,c.tag);\n\nif 0, % Currently unused\n f1 = uimenu(f0,'Label','Modality');\n modalities = {'FMRI','PET','EEG'};\n for i=1:length(modalities)\n tmp = modalities{i};\n if strcmp(tmp,getdef('modality')),\n tmp = ['*' tmp];\n else\n tmp = [' ' tmp];\n end;\n uimenu(f1,'Label',tmp,'CallBack',@chmod);\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction pulldown1(f0,c0,tag0)\nif ~isfield(c0,'values'), return; end;\nfor i=1:length(c0.values),\n c1 = c0.values{i};\n if isstruct(c1) && ~isfield(c1,'hidden'),\n tag1 = tag0;\n if isfield(c1,'tag'),\n tag1 = [tag1 '.' c1.tag];\n end;\n if isfield(c1,'prog'),\n uimenu(f0,'Label',c1.name,'CallBack',@interactive,'UserData',{'',tag1});\n else\n f1 = uimenu(f0,'Label',c1.name);\n pulldown1(f1,c1,tag1);\n end;\n end;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction pulldown2(f0,c0,tag0)\nif ~isfield(c0,'values'), return; end;\nfor i=1:length(c0.values),\n c1 = c0.values{i};\n if isstruct(c1) && ~isfield(c1,'hidden'),\n tag1 = tag0;\n if isfield(c1,'tag'),\n tag1 = [tag1 '.' c1.tag];\n end;\n if isfield(c1,'prog'),\n if findcheck(c1),\n uimenu(f0,'Label',c1.name,'Enable','off');\n else\n uimenu(f0,'Label',c1.name,'CallBack',@run_serial,'UserData',{'',tag1});\n end;\n else\n f1 = uimenu(f0,'Label',c1.name);\n pulldown2(f1,c1,tag1);\n end;\n end;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction hascheck = findcheck(c)\nhascheck = false;\nif ~isstruct(c) || ~isfield(c,'type'), return; end;\nif isfield(c,'check'),\n hascheck = true;\n return;\nend;\nif isfield(c,'values'),\n for i=1:numel(c.values),\n hascheck = findcheck(c.values{i});\n if hascheck, return; end;\n end;\nend;\nif isfield(c,'val'),\n for i=1:numel(c.val),\n hascheck = findcheck(c.val{i});\n if hascheck, return; end;\n end;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction chmod(mod,varargin)\nglobal defaults\nif isempty(defaults), spm_defaults; end;\nif ischar(mod),\n %if strcmpi(defaults.modality,mod),\n % spm('ChMod',mod);\n %end;\n defaults.modality = mod;\nelse\n tmp = get(mod,'Label');\n defaults.modality = tmp(2:end);\nend;\npulldown;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction fszoom(varargin)\nfs = sscanf(get(varargin{1},'Label'),'%d');\nset(gco,'FontSize',fs);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction run_serial(varargin)\nud = get(varargin{1},'UserData');\nif iscell(ud)\n serial(ud{:});\nelse\n serial;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction serial(job,node)\n\nif nargin<2, node = 'jobs'; end;\n\nfg = spm_figure('FindWin','Interactive');\nif isempty(fg), fg = spm('CreateIntWin'); end;\ndelete(findobj(fg,'Parent',fg));\nt=uicontrol(fg,...\n 'Style','listbox',...\n 'Units','normalized',...\n 'Position',[0.02 0.02 0.96 0.62],...\n 'Tag','help_box2',...\n 'FontName','fixedwidth',...\n 'FontSize',12,...\n 'BackgroundColor',[1 1 1]);\nset(t,'Value',[], 'Enable', 'inactive', 'Max',2, 'Min',0);\nworkaround(t);\ncntxtmnu(t);\nspm('Pointer');\ndrawnow;\n\nif nargin>0,\n c = initialise_struct(job);\nelse\n c = initialise_struct;\nend;\n\nc = start_node(c,node);\nc = start_node(c,@run_ui,{});\nspm_input('!DeleteInputObj');\ndelete(findobj(fg,'Parent',fg));\n[unused,jobs] = harvest(c);\n%savexml('job_last.xml','jobs');\nrun_job(jobs);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = run_ui(c,varargin)\n\nnnod=1;\nwhile(1),\n nod = nnod;\n [ci,unused,hlp] = get_node(c,nod);\n if isempty(ci), break; end;\n\n help_box = findobj(0,'tag','help_box2');\n if ~isempty(help_box),\n set(help_box,'String',' ');\n workaround(help_box);\n ext = get(help_box,'Extent');\n pos = get(help_box,'position');\n pw = floor(pos(3)/ext(3)*21-4);\n set(help_box,'String',spm_justify(pw,hlp));\n workaround(help_box);\n\n if isfield(c,'prog'),\n try\n set(help_box,'HandleVisibility','off');\n [Finter,unused,CmdLine] = spm('FnUIsetup',c.name);\n spm('FigName',[c.name ': setup'],Finter,CmdLine);\n catch\n end;\n set(help_box,'HandleVisibility','on');\n end;\n end;\n\n pos = 1;\n\n switch ci.type,\n case {'const','files','menu','entry'}\n nnod = nod + 1;\n\n vl = {''};\n if isfield(ci,'def'), vl = getdef(ci.def); end;\n if numel(vl)~=0 && (~ischar(vl{1}) || ~strcmp(vl{1},'')),\n getit = 0;\n if ~isfield(ci,'val') || ~iscell(ci.val) || isempty(ci.val),\n ci.val = vl;\n end;\n else\n getit = 1;\n end;\n\n switch ci.type,\n case {'const'}\n case {'files'}\n num = ci.num;\n\n if getit,\n if ~isempty(ci.val),\n sel = ci.val{1};\n else\n sel = '';\n end;\n addvfiles(ci.id,c);\n if isfield(ci,'dir'),\n dr = ci.dir;\n else\n dr = pwd;\n end;\n if isfield(ci,'ufilter')\n uf = ci.ufilter;\n else\n uf = '.*';\n end;\n [ci.val{1},ok] = spm_select(num,ci.filter,ci.name,sel,dr,uf);\n if ~ok,\n error('File Selector was deleted.');\n end;\n spm_select('clearvfiles');\n ci.val{1} = cellstr(ci.val{1});\n end;\n\n case {'menu'}\n dv = [];\n if getit,\n if isfield(ci,'val') && ~isempty(ci.val),\n for i=1:length(ci.values)\n if same(ci.values{i},ci.val{1})\n dv = i;\n end;\n end;\n end;\n lab = ci.labels{1};\n for i=2:length(ci.values),\n lab = [lab '|' ci.labels{i}];\n end;\n if isempty(dv),\n ind = spm_input(ci.name,pos,'m',lab,1:length(ci.values));\n else\n ind = spm_input(ci.name,pos,'m',lab,1:length(ci.values),dv);\n end;\n ci.val = {ci.values{ind}};\n end;\n\n case {'entry'}\n n1 = Inf;\n if isfield(ci,'num'), n1 = ci.num; end;\n if getit,\n val = '';\n if isfield(ci,'val') && ~isempty(ci.val) && ~strcmp(ci.val{1},''),\n val = ci.val{1};\n end;\n if isfield(ci,'extras')\n val = spm_input(ci.name,pos,ci.strtype,val,n1,ci.extras);\n else\n val = spm_input(ci.name,pos,ci.strtype,val,n1);\n end;\n ci.val{1} = val;\n end;\n end;\n\n case {'repeat'},\n lab = 'Done';\n for i=1:length(ci.values)\n lab = [lab '|New \"' ci.values{i}.name '\"'];\n end;\n tmp = spm_input(ci.name,pos,'m',lab,0:length(ci.values));\n if tmp,\n ci.val = {ci.val{:}, uniq_id(ci.values{tmp})};\n nnod = nod;\n else\n nnod = nod + 1;\n end;\n\n case {'choice'}\n nnod = nod + 1;\n lab = ci.values{1}.name;\n for i=2:length(ci.values)\n lab = [lab '|' ci.values{i}.name];\n end;\n tmp = spm_input(ci.name,pos,'m',lab,1:length(ci.values));\n ci.val = {uniq_id(ci.values{tmp})};\n otherwise\n error('This should not happen.');\n end;\n c = set_node(c,nod,ci);\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [ci,n,hlp] = get_node(c,n)\nci = [];\nhlp = '';\nswitch c.type,\n case {'const','files','menu','entry'}\n n = n-1;\n if n==0,\n ci = c;\n hlp = {['* ' upper(c.name)],c.help{:},'',''};\n return;\n end;\n\n case 'choice'\n n = n-1;\n if n==0,\n ci = c;\n hlp = {['* ' upper(c.name)],c.help{:},'',''};\n return;\n end;\n [ci,n,hlp] = get_node(c.val{1},n);\n if ~isempty(ci),\n hlp = {hlp{:},repmat('=',1,20),'',['* ' upper(c.name)],c.help{:},'',''};\n return;\n end;\n\n case 'branch',\n for i=1:numel(c.val),\n [ci,n,hlp] = get_node(c.val{i},n);\n if ~isempty(ci),\n hlp = {hlp{:},repmat('=',1,20),'',['* ' upper(c.name)],c.help{:},'',''};\n return;\n end;\n end;\n\n case 'repeat',\n for i=1:numel(c.val),\n [ci,n,hlp] = get_node(c.val{i},n);\n if ~isempty(ci),\n hlp = {hlp{:},repmat('=',1,20),'',['* ' upper(c.name)],c.help{:},'',''};\n return;\n end;\n end;\n n = n-1;\n if n==0,\n ci = c;\n hlp = {['* ' upper(c.name)],c.help{:},'',''};\n return;\n end;\n otherwise\n error('This should not happen');\n\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [c,n] = set_node(c,n,ci)\nswitch c.type,\n case {'const','files','menu','entry'}\n n = n-1;\n if n==0,\n c = ci;\n return;\n end;\n\n case 'choice'\n n = n-1;\n if n==0,\n c = ci;\n return;\n end;\n [c.val{1},n] = set_node(c.val{1},n,ci);\n if n<0,return; end;\n\n case 'branch',\n for i=1:numel(c.val),\n [c.val{i},n] = set_node(c.val{i},n,ci);\n if n<0,return; end;\n end;\n\n case 'repeat',\n for i=1:numel(c.val),\n [c.val{i},n] = set_node(c.val{i},n,ci);\n if n<0,return; end;\n end;\n n = n-1;\n if n==0,\n c = ci;\n return;\n end;\n\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = initialise_struct(job)\n% load the config file, possibly adding a job\n% to it, and generally tidy it up. The batch box\n% is updated to contain the current structure.\n\npersistent c0\nif isempty(c0),\n c0 = spm_config;\n c0 = tidy_struct(c0);\nend;\nc = insert_defs(c0);\nif nargin==1 && ischar(job) && strcmp(job,'defaults'),\n c = defsub(c,{});\n c.name = 'SPM Defaults';\nelse\n c = hide_null_jobs(c);\n if nargin>0 && ~isempty(job),\n if ischar(job)||iscellstr(job)\n % only call fromfile if job(s) are identified by strings\n [job,jobhelp] = fromfile(job);\n else\n % job structure given, we therefore don't have jobhelp\n jobhelp = [];\n end;\n c = job_to_struct(c,job,jobhelp,'jobs');\n c = uniq_id(c);\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [c,defused] = defsub(c,defused)\nif nargin<2, defused = {}; end;\nif isfield(c,'prog'), c = rmfield(c,'prog'); end;\nswitch c.type,\n case {'const'}\n c = [];\n\n case {'menu','entry','files'}\n if ~isfield(c,'def') || any(strcmp(c.def,defused)),\n c = [];\n else\n defused = {defused{:},c.def};\n end;\n\n case {'branch'}\n msk = true(1,length(c.val));\n for i=1:length(c.val),\n [c.val{i},defused] = defsub(c.val{i},defused);\n msk(i) = ~isempty(c.val{i});\n end;\n c.val = c.val(msk);\n if isempty(c.val), c = []; end;\n\n case {'choice','repeat'}\n c.type = 'branch';\n c.val = c.values;\n c = rmfield(c,'values');\n [c,defused] = defsub(c,defused);\n\nend;\nif isfield(c,'vfiles'), c = rmfield(c,'vfiles'); end;\nif isfield(c,'check'), c = rmfield(c,'check'); end;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = insert_defs(c)\n% Recursively descend through the tree structure,\n% and assigning default values.\nif ~isstruct(c) || ~isfield(c,'type'),\n return;\nend;\nswitch c.type\n case {'menu','entry','files'}\n if isfield(c,'def')\n c.val = getdef(c.def);\n if strcmp(c.type,'files') && ~isempty(c.val)\n if ~isempty(c.val{1})\n c.val = {cellstr(c.val{1})};\n else\n c.val = {{}};\n end;\n end;\n end;\n\n case {'repeat','choice'},\n if isfield(c,'values')\n for i=1:numel(c.values)\n c.values{i} = insert_defs(c.values{i});\n end;\n end;\nend;\nif isfield(c,'val')\n for i=1:numel(c.val)\n c.val{i} = insert_defs(c.val{i});\n end;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = tidy_struct(c)\n% Recursively descend through the tree structure, cleaning up\n% fields that may be missing and adding an 'expanded' field\n% where necessary.\n\nif ~isstruct(c) || ~isfield(c,'name') || ~isfield(c,'type')\n return;\nend;\nc.id = rand(1);\n\nif ~isfield(c,'help'), c.help = {}; end;\nif ischar(c.help), c.help = {c.help}; end;\n\nswitch c.type\n case {'const'}\n if ~isfield(c,'tag')\n disp(c); warning(['No tag field for \"' c.name '\"']);\n c.tag = 'unknown';\n end;\n if ~isfield(c,'val')\n disp(c); warning(['No val field for \"' c.name '\"']);\n c.val = {''};\n end;\n\n case {'menu'}\n if ~isfield(c,'tag')\n disp(c); warning(['No tag field for \"' c.name '\"']);\n c.tag = 'unknown';\n end;\n\n if ~isfield(c,'labels') || ~isfield(c,'values')\n disp(c); warning(['No labels and values field for \"' c.name '\"']);\n c.labels = {};\n c.values = {};\n end;\n if length(c.labels) ~= length(c.values)\n disp(c); warning(['Labels and values fields incompatible for \"' c.name '\"']);\n c.labels = {};\n c.values = {};\n end;\n if ~isfield(c,'help'), c.help = {'Option selection by menu'}; end;\n\n case {'entry'}\n if ~isfield(c,'tag')\n disp(c); warning(['No tag field for \"' c.name '\"']);\n c.tag = 'unknown';\n end;\n if ~isfield(c,'strtype')\n disp(c); warning(['No strtype field for \"' c.name '\"']);\n c.strtype = 'e';\n end;\n if ~isfield(c,'num')\n disp(c); warning(['No num field for \"' c.name '\"']);\n c.num = [1 1];\n end;\n if length(c.num)~=2\n disp(c); warning(['Num field for \"' c.name '\" is wrong length']);\n c.num = [Inf 1];\n end;\n if ~isfield(c,'help'), c.help = {'Option selection by text entry'}; end;\n\n case {'files'}\n if ~isfield(c,'tag')\n disp(c); warning(['No tag field for \"' c.name '\"']);\n c.tag = 'unknown';\n end;\n if ~isfield(c,'filter')\n disp(c); warning(['No filter field for \"' c.name '\"']);\n c.filter = '*';\n end;\n if ~isfield(c,'num')\n disp(c); warning(['No num field for \"' c.name '\"']);\n c.num = Inf;\n end;\n if length(c.num)~=1 && length(c.num)~=2\n disp(c); warning(['Num field for \"' c.name '\" is wrong length']);\n c.num = Inf;\n end;\n if isfield(c,'val') && iscell(c.val) && numel(c.val)>=1,\n if ischar(c.val{1})\n c.val{1} = cellstr(c.val{1});\n end;\n end;\n if ~isfield(c,'help'), c.help = {'File selection'}; end;\n\n case {'branch'}\n if ~isfield(c,'tag')\n disp(c); warning(['No tag field for \"' c.name '\"']);\n c.tag = 'unknown';\n end;\n if ~isfield(c,'val')\n disp(c); warning(['No val field for \"' c.name '\"']);\n c.val = {};\n end;\n\n c.expanded = false;\n if ~isfield(c,'help'), c.help = {'Branch structure'}; end;\n\n case {'choice'}\n if ~isfield(c,'tag')\n disp(c); warning(['No tag field for \"' c.name '\"']);\n c.tag = 'unknown';\n end;\n if ~isfield(c,'values') || ~iscell(c.values)\n disp(c); error(['Bad values for \"' c.name '\"']);\n end;\n for i=1:length(c.values)\n c.values{i} = tidy_struct(c.values{i});\n end;\n if ~isfield(c,'val') || ~iscell(c.val) || length(c.val) ~= 1\n c.val = {c.values{1}};\n end;\n c.expanded = true;\n if ~isfield(c,'help'), c.help = {'Choice structure'}; end;\n\n case {'repeat'}\n if ~isfield(c,'values') || ~iscell(c.values)\n disp(c); error(['Bad values for \"' c.name '\"']);\n end;\n for i=1:length(c.values)\n c.values{i} = tidy_struct(c.values{i});\n end;\n if length(c.values)>1 && ~isfield(c,'tag')\n disp(c); warning(['No tag field for \"' c.name '\"']);\n c.tag = 'unknown';\n end;\n if length(c.values)==1 && isfield(c,'tag')\n % disp(c); warning(['\"' c.name '\" has unused tag']);\n c = rmfield(c,'tag');\n end;\n c.expanded = true;\n if ~isfield(c,'help'), c.help = {'Repeated structure'}; end;\n\n if isfield(c,'num') && numel(c.num)==1,\n if isfinite(c.num),\n c.num = [c.num c.num];\n else\n c.num = [0 c.num];\n end;\n end;\n\nend;\n\nif ~isfield(c,'val'), c.val = {}; end;\n\n%switch c.type\n%case {'menu','entry','files'}\n% %if isempty(c.val)\n% if isfield(c,'def')\n% c.val = getdef(c.def);\n% if strcmp(c.type,'files') && ~isempty(c.val)\n% c.val = {cellstr(c.val{1})};\n% end;\n% end;\n% %end;\n%end;\n\nif isfield(c,'val')\n for i=1:length(c.val)\n c.val{i} = tidy_struct(c.val{i});\n end;\nend;\nif isfield(c,'values') && strcmp(c.type,'repeat')\n for i=1:length(c.values)\n c.values{i} = tidy_struct(c.values{i});\n end;\nend;\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [newjobs,newjobhelps] = fromfile(job)\nif ischar(job)\n filenames = cellstr(job);\nelse\n filenames = job;\nend;\nnewjobs = {};\nnewjobhelps = {};\nfor cf = 1:numel(filenames)\n jobhelps = {[]};\n [p,nam,ext] = fileparts(filenames{cf});\n switch ext\n case '.xml',\n spm('Pointer','Watch');\n try\n loadxml(filenames{cf},'jobs');\n catch\n questdlg('LoadXML failed',filenames{cf},'OK','OK');\n return;\n end;\n try\n loadxml(filenames{cf},'jobhelps');\n end;\n spm('Pointer');\n case '.mat'\n try\n S=load(filenames{cf});\n jobs = S.jobs;\n if isfield(S,'jobhelps')\n jobhelps=S.jobhelps;\n end;\n catch\n questdlg('Load failed',filenames{cf},'OK','OK');\n end;\n case '.m'\n opwd = pwd;\n try\n if ~isempty(p)\n cd(p);\n end\n clear(nam);\n eval(nam);\n catch\n questdlg('Load failed',filenames{cf},'OK','OK');\n end;\n cd(opwd);\n otherwise\n questdlg(['Job ' nam ': Unknown extension (' ext ')'],...\n 'This job not loaded','OK','OK');\n end;\n if exist('jobs','var')\n newjobs = {newjobs{:} jobs{:}};\n clear jobs;\n newjobhelps = {newjobhelps{:} jobhelps{:}};\n clear jobhelps;\n else\n questdlg(['No jobs (' nam ext ')'],'No jobs','OK','OK');\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = hide_null_jobs(c)\nc = hide_null_jobs1(c);\nc = hide_null_jobs2(c);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [c,flg] = hide_null_jobs1(c)\nif ~isstruct(c) || ~isfield(c,'type'),\n flg = true;\n return;\nend;\n\nif ~include(c),\n flg = false;\n c.hidden = true;\n return;\nend;\n\nswitch c.type,\n case {'repeat','branch','choice'},\n msk1 = true;\n msk2 = true;\n if isfield(c,'val') && ~isempty(c.val),\n msk1 = true(1,numel(c.val));\n for i=1:length(c.val)\n [c.val{i},msk1(i)] = hide_null_jobs1(c.val{i});\n end;\n end;\n if isfield(c,'values') && ~isempty(c.values),\n msk2 = true(1,numel(c.values));\n for i=1:length(c.values)\n [c.values{i},msk2(i)] = hide_null_jobs1(c.values{i});\n end;\n end;\n flg = any(msk1) || any(msk2);\n if ~flg, c.hidden = true; end;\n otherwise\n flg = true;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction ok = include(c)\n% Check that the modality is OK\nok = true;\nif isfield(c,'modality'),\n mod = getdef('modality');\n if ~isempty(mod),\n mod = mod{1};\n ok = false;\n for i=1:length(c.modality),\n if strcmpi(c.modality{i},mod),\n ok = true;\n return;\n end;\n end;\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction [c,flg] = hide_null_jobs2(c)\nif ~isstruct(c) || ~isfield(c,'type')\n flg = 0;\n return;\nend;\nif isfield(c,'prog'),\n flg = 1;\n return;\nend;\n\nswitch c.type,\n case {'repeat','branch','choice'},\n flg = 0;\n msk1 = [];\n msk2 = [];\n if isfield(c,'val'),\n msk1 = ones(1,numel(c.val));\n for i=1:length(c.val)\n [c.val{i},msk1(i)] = hide_null_jobs2(c.val{i});\n end;\n end;\n if isfield(c,'values'),\n msk2 = ones(1,numel(c.values));\n for i=1:length(c.values)\n [c.values{i},msk2(i)] = hide_null_jobs2(c.values{i});\n end;\n end;\n if (sum(msk1) + sum(msk2))>0, flg = 1; end;\n if ~flg, c.hidden = 1; end;\n otherwise\n flg = 0;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c = job_to_struct(c,job,jobhelp,tag)\n% Modify a structure based on a batch job\nif isstruct(c) && isfield(c,'hidden'),\n return;\nend;\nswitch c.type\n case {'const','menu','files','entry'}\n if ~strcmp(gettag(c),tag), return; end;\n if ischar(job) && strcmp(job,'')\n c.val = {};\n else\n c.val{1} = job;\n end;\n c.jobhelp = jobhelp;\n\n case {'branch'}\n if ~strcmp(gettag(c),tag), return; end;\n if ~isstruct(job), return; end;\n if ~isempty(jobhelp) && isstruct(jobhelp) && isfield(jobhelp, 'jobhelp')\n c.jobhelp = jobhelp.jobhelp;\n end;\n\n tag = fieldnames(job);\n for i=1:length(tag)\n for j=1:length(c.val)\n if strcmp(gettag(c.val{j}),tag{i})\n try\n c.val{j} = job_to_struct(c.val{j},job.(tag{i}),jobhelp.(tag{i}), ...\n tag{i});\n catch\n c.val{j} = job_to_struct(c.val{j},job.(tag{i}),[], ...\n tag{i});\n end;\n break;\n end;\n end;\n end;\n\n case {'choice'}\n if ~strcmp(gettag(c),tag), return; end;\n if ~isstruct(job), return; end;\n tag = fieldnames(job);\n if length(tag)>1, return; end;\n tag = tag{1};\n for j=1:length(c.values)\n if strcmp(gettag(c.values{j}),tag)\n try\n c.val = {job_to_struct(c.values{j},job.(tag),jobhelp.(tag),tag)};\n catch\n c.val = {job_to_struct(c.values{j},job.(tag),[],tag)};\n end;\n end;\n end;\n\n case {'repeat'}\n if ~strcmp(gettag(c),tag), return; end;\n if length(c.values)==1 && strcmp(c.values{1}.type,'branch')\n if ~isstruct(job), return; end;\n c.val = {};\n for i=1:length(job)\n if strcmp(gettag(c.values{1}),tag)\n try\n c.val{i} = job_to_struct(c.values{1},job(i),jobhelp(i), tag);\n catch\n c.val{i} = job_to_struct(c.values{1},job(i),[],tag);\n end;\n c.val{i}.removable = true;\n end;\n end;\n elseif length(c.values)>1\n if ~iscell(job), return; end;\n c.val = {};\n for i=1:length(job)\n tag = fieldnames(job{i});\n if length(tag)>1, return; end;\n tag = tag{1};\n for j=1:length(c.values)\n if strcmp(gettag(c.values{j}),tag)\n try\n c.val{i} = job_to_struct(c.values{j},job{i}.(tag),jobhelp{i}.(tag),tag);\n catch\n c.val{i} = job_to_struct(c.values{j}, job{i}.(tag),[],tag);\n end;\n c.val{i}.removable = true;\n break;\n end;\n end;\n end;\n else\n if ~iscell(job), return; end;\n c.val = {};\n for i=1:length(job)\n try\n c.val{i} = job_to_struct(c.values{1},job{i},jobhelp{i},tag);\n catch\n c.val{i} = job_to_struct(c.values{1},job{i},[],tag);\n end;\n c.val{i}.removable = true;\n end;\n end;\n\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction doc = showdoc(str,wid)\nif nargin<1, str = ''; end;\nif nargin<2, wid = 60; end;\n\ntmp = [0 find([str '.']=='.')];\nnode = {};\nfor i=1:length(tmp)-1,\n tmp1 = str((tmp(i)+1):(tmp(i+1)-1));\n if ~isempty(tmp1),\n node = {node{:},tmp1};\n end;\nend;\nif numel(node)>1 && strcmp(node{1},'jobs'),\n node = node(2:end);\nend;\n\nc = initialise_struct;\ndoc = showdoc1(node,c,wid);\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction doc = showdoc1(node,c,wid)\ndoc = {};\nif isempty(node),\n doc = showdoc2(c,'',wid);\n return;\nend;\n\nif isfield(c,'values'),\n for i=1:numel(c.values),\n if isfield(c.values{i},'tag') && strcmp(node(1),c.values{i}.tag),\n doc = showdoc1(node(2:end),c.values{i},wid);\n return;\n end;\n end;\nend;\n\nif isfield(c,'val'),\n for i=1:numel(c.val),\n if isfield(c.val{i},'tag') && strcmp(node(1),c.val{i}.tag),\n doc = showdoc1(node(2:end),c.val{i},wid);\n return;\n end;\n end;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction doc = showdoc2(c,lev,wid)\ndoc = {''};\nif ~isempty(lev) && sum(lev=='.')==1,\n % doc = {doc{:},repmat('_',1,80),''};\nend;\n\nif isfield(c,'name'),\n str = sprintf('%s %s', lev, c.name);\n %under = repmat('-',1,length(str));\n doc = {doc{:},str};\n % if isfield(c,'modality'),\n % txt = 'Only for ';\n % for i=1:numel(c.modality),\n % txt = [txt ' ' c.modality{i}];\n % end;\n % doc = {doc{:},'',txt, ''};\n %end;\n if isfield(c,'help');\n hlp = spm_justify(wid,c.help);\n doc = {doc{:},hlp{:}};\n end;\n\n switch (c.type),\n case {'repeat'},\n if length(c.values)==1,\n doc = {doc{:}, '', sprintf('Repeat \"%s\", any number of times.',c.values{1}.name)};\n else\n doc = {doc{:}, '', 'Any of the following options can be chosen, any number of times'};\n i = 0;\n for ii=1:length(c.values),\n if isstruct(c.values{ii}) && isfield(c.values{ii},'name'),\n i = i+1;\n doc = {doc{:}, sprintf(' %2d) %s', i,c.values{ii}.name)};\n end;\n end;\n end;\n doc = {doc{:},''};\n\n case {'choice'},\n doc = {doc{:}, '', 'Any one of these options can be selected:'};\n i = 0;\n for ii=1:length(c.values),\n if isstruct(c.values{ii}) && isfield(c.values{ii},'name'),\n i = i+1;\n doc = {doc{:}, sprintf(' %2d) %s', i,c.values{ii}.name)};\n end;\n end;\n doc = {doc{:},''};\n\n case {'branch'},\n doc = {doc{:}, '', sprintf('This item contains %d fields:', length(c.val))};\n i = 0;\n for ii=1:length(c.val),\n if isstruct(c.val{ii}) && isfield(c.val{ii},'name'),\n i = i+1;\n doc = {doc{:}, sprintf(' %2d) %s', i,c.val{ii}.name)};\n end;\n end;\n doc = {doc{:},''};\n\n case {'menu'},\n doc = {doc{:}, '', 'One of these values is chosen:'};\n for k=1:length(c.labels),\n doc = {doc{:}, sprintf(' %2d) %s', k, c.labels{k})};\n end;\n doc = {doc{:},''};\n\n case {'files'},\n if length(c.num)==1 && isfinite(c.num(1)) && c.num(1)>=0,\n tmp = spm_justify(wid,sprintf('A \"%s\" file is selected by the user.',c.filter));\n else\n tmp = spm_justify(wid,sprintf('\"%s\" files are selected by the user.\\n',c.filter));\n end;\n doc = {doc{:}, '', tmp{:}, ''};\n\n case {'entry'},\n switch c.strtype,\n case {'e'},\n d = 'Evaluated statements';\n case {'n'},\n d = 'Natural numbers';\n case {'r'},\n d = 'Real numbers';\n case {'w'},\n d = 'Whole numbers';\n otherwise,\n d = 'Values';\n end;\n tmp = spm_justify(wid,sprintf('%s are entered.',d));\n doc = {doc{:}, '', tmp{:}, ''};\n end;\n\n i = 0;\n doc = {doc{:},''};\n if isfield(c,'values'),\n for ii=1:length(c.values),\n if isstruct(c.values{ii}) && isfield(c.values{ii},'name'),\n i = i+1;\n lev1 = sprintf('%s%d.', lev, i);\n doc1 = showdoc2(c.values{ii},lev1,wid);\n doc = {doc{:}, doc1{:}};\n end;\n end;\n end;\n if isfield(c,'val'),\n for ii=1:length(c.val),\n if isstruct(c.val{ii}) && isfield(c.val{ii},'name'),\n i = i+1;\n lev1 = sprintf('%s%d.', lev, i);\n doc1 = showdoc2(c.val{ii},lev1,wid);\n doc = {doc{:}, doc1{:}};\n end;\n end;\n end;\n doc = {doc{:}, ''};\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction jobhelp = showjobhelp(str,wid)\nif nargin<1, str = ''; end;\nif nargin<2, wid = 60; end;\n\ntmp = [0 find([str '.']=='.')];\nnode = {};\nfor i=1:length(tmp)-1,\n tmp1 = str((tmp(i)+1):(tmp(i+1)-1));\n if ~isempty(tmp1),\n node = {node{:},tmp1};\n end;\nend;\nif numel(node)>1 && strcmp(node{1},'jobs'),\n node = node(2:end);\nend;\n\nc = get(batch_box,'userdata');\njobhelp = showjobhelp1(node,c,wid);\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction jobhelp = showjobhelp1(node,c,wid)\njobhelp = {};\nif isempty(node),\n jobhelp = showjobhelp2(c,'',wid);\n return;\nend;\n\n%if isfield(c,'values'),\n% for i=1:numel(c.values),\n% if isfield(c.values{i},'tag') && strcmp(node(1),c.values{i}.tag),\n% jobhelp = showjobhelp1(node(2:end),c.values{i},wid);\n% return;\n% end;\n% end;\n%end;\n\nif isfield(c,'val'),\n for i=1:numel(c.val),\n if isfield(c.val{i},'tag') && strcmp(node(1),c.val{i}.tag),\n jobhelp = showjobhelp1(node(2:end),c.val{i},wid);\n return;\n end;\n end;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction jobhelp = showjobhelp2(c,lev,wid)\njobhelp = {''};\nif ~isempty(lev) && sum(lev=='.')==1,\n % jobhelp = {jobhelp{:},repmat('_',1,80),''};\nend;\n\nif isfield(c,'name') && isfield(c,'jobhelp'),\n str = sprintf('%s %s', lev, c.name);\n jobhelp = {jobhelp{:},str};\n hlp = spm_justify(wid,c.jobhelp);\n jobhelp = {jobhelp{:},hlp{:}};\n jobhelp = {jobhelp{:}, ''};\nend;\ni = 0;\nif isfield(c,'val'),\n for ii=1:length(c.val),\n if isstruct(c.val{ii}) && isfield(c.val{ii},'name'),\n i = i+1;\n lev1 = sprintf('%s%d.', lev, i);\n jobhelp1 = showjobhelp2(c.val{ii},lev1,wid);\n jobhelp = {jobhelp{:}, jobhelp1{:}};\n end;\n end;\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction edit_jobhelp(varargin)\nh = findobj(0,'tag','help_box');\ncol1 = getdef('ui.colour1');\nif numel(col1)~=1 || ~isnumeric(col1{1}) || numel(col1{1})~=3,\n col1 = [0.8 0.8 1];\nelse\n col1 = col1{1};\nend;\nset(h,'Style','edit','HorizontalAlignment','left', 'Callback', ...\n @edit_jobhelp_accept, 'BackgroundColor',col1);\nrun_in_current_node(@get_jobhelp,0,h);\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c=get_jobhelp(c,h)\n% for editing, use unjustified version of help string\nif isfield(c,'jobhelp')\n set(h,'String',c.jobhelp);\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction edit_jobhelp_accept(varargin)\nh = findobj(0,'tag','help_box');\ncol2 = getdef('ui.colour2');\nif numel(col2)~=1 || ~isnumeric(col2{1}) || numel(col2{1})~=3,\n col2 = [1 1 0.8];\nelse\n col2 = col2{1};\nend;\njobhelp = get(h,'string');\nset(h,'Style','listbox', 'HorizontalAlignment', ...\n 'Center', 'Callback',[], 'BackgroundColor',col2, 'String', ...\n spm_justify(h,jobhelp));\nrun_in_current_node(@set_jobhelp,1,jobhelp);\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction c=set_jobhelp(c,txt)\nc.jobhelp = txt;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_bst_headmodeler.m", "ext": ".m", "path": "spm5-master/spm_bst_headmodeler.m", "size": 82570, "source_encoding": "utf_8", "md5": "3a01e74cf6f9309c284033afc212220a", "text": "function [varargout] = spm_bst_headmodeler(varargin);\n% SPM_BST_HEADMODELER - Solution to the MEG/EEG forward problem\n% function [varargout] = bst_headmodeler(varargin);\n% Authorized syntax:\n% [OPTIONS] = spm_bst_headmodeler;\n% [G, Gxyz, OPTIONS] = spm_bst_headmodeler(OPTIONS);\n%\n% --------------------------------- INPUTS -------------------------------------\n% INPUTS\n%\n% [OPTIONS] = spm_bst_headmodeler; Returns the default values for the OPTIONS\n% parameter structure\n%\n% StudyFile: the name of a BrainStorm study file. We suppose the\n% corresponding BrainStorm channel file is available in the same folder\n% with the conventional file name (e.g., for a study file calls\n% meg_brainstormstudy.mat, BST_HEADMODELER expects to find the\n% corresponding channel file under the name meg_channel.mat). If the\n% channel file were not sitting in the same folder as the study file,\n% OPTIONS.ChannelFile enforces computation of the forward model with the\n% channel information contained in OPTIONS.ChannelFile.\n%\n% If no further input arguments are specified, forward modeling is\n% completed with the default parameters specified below\n%\n% OPTIONS a structure where optional parameters may be specified using the\n% following fields Note: if no options are specified, BST_HEADMODELER will\n% proceed to the computation of the foward problem on a 3D grid of source\n% locations that cover the entire head volume See\n% OPTIONS.VolumeSourceGridSpacing for default settings\n%\n% Important notice: there is no need to define all the following fields\n% when using the OPTIONS argument. The undefined field(s) will be assigned\n% default values.\n%\n% *\n% * Fields Related to forward approach\n% *\n%\n% .Method: is either a character string or a cell array of two strings that\n% specifies the kind of approach to be applied to the compuation\n% of the foward model In case Method is a cell array, it should\n% contain 2 strings, one to specifiy the method to be used for MEG\n% and the other for . If only a single string is specified, the\n% foward computation will be completed on the set of corresponding\n% CHANndx only (i.e. MEG or MEG) Available forward modeling\n% methods and corresponding authorized strings for Method:\n% - MEG\n% 'meg_sphere' (DEFAULT) : Spherical head model designed\n% following the Sarvas analytical formulation (i.e.\n% considering the true orientation\n% of the magnetic field sensors) (see OPTIONS.HeadCenter)\n% 'meg_os' : MEG overlapping sphere forward model\n% 'meg_bem' : Apply BEM computation (see OPTIONS.BEM for details)\n% -\n% 'eeg_sphere' : Single-sphere forward modeling (see\n% OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity)\n% 'eeg_3sphere' : EEG forward modeling with a set of 3\n% concentric spheres (Scalp, Skull, Brain/CSF) (see\n% OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity)\n% 'eeg_3sphereBerg' (DEFAULT) : Same as eeg_3sphere with\n% correction for possible dipoles outside the sphere\n% 'eeg_os' : EEG overlapping sphere head model (see\n% OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity)\n% 'eeg_bem' : Apply BEM computation (see OPIONS.BEM for details)\n%\n% Default is {'meg_sphere','eeg_3sphereBerg'};\n%\n% .HeadModelName : a character string that specifies the name of the\n% headmodel represented by this file, e.g \"Spherical\",\n% \"Overlapping Spheres\", \"Constant Collocation BEM\", etc.\n% Default is \"Default\", meaning it will include the the\n% name(s) of the method(s) used in the MEG and/or EEG\n% forward models\n%\n% *\n% * Fields Related to function's I/O\n% *\n%\n% .HeadModelFile : Specifies the name of the head model file where to store\n% the forward model. If set to 'default', the default\n% nomenclature for BrainStorm's head model file name is\n% used and BST_HEADMODELER creates a file in StudyFile's\n% folder.\n% Default is empty.\n% .ImageGridFile : Specifies the name of the file where to store the full\n% cortical gain matrix file If set to 'default', the\n% default nomenclature for BrainStorm's head model file\n% name is used and BST_HEADMODELER creates a file in\n% StudyFile's folder.\n% Default is empty.\n% .ImageGridBlockSize : Number of sources for which to compute the forward\n% model at a time in a block computation routines\n% (saves memory space). This option is relevant only\n% when some forward modeling on cortical surface is\n% requested (i.e. when .Cortex is specified)\n% Default is 2000\n% .FileNamePrefix : A string that specifies the prefix for all file names\n% (Channel, HeadModel, Gain Matrices) when .HeadModelFile\n% is set to 'default' and .ChannelFile is empty.\n% Default is 'bst_'\n% .Verbose : Toggles verbose mode on/off;\n% Default is 1 (on)\n%\n% *\n% * Fields Related to Head Geometry *\n% *\n%\n% .Scalp : A structure specifying the Scalp surface envelope to serve\n% for parameter adjustment of best-fitting sphere, with\n% following fields:\n% .FileName : A string specifying the name of the BrainStorm\n% tessellation file containing the Scalp\n% tessellation (default is 1);\n% .iGrid : An integer for the index of the Scalp surface in\n% the Faces, Vertices and Comments cell arrays in\n% the tessellation file\n% Default is empty (Best-fitting sphere is\n% computed from the sensor array).\n% .HeadCenter: a 3-element vector specifying the coordinates, in the\n% sensors coordinate system, of the center of the spheres that\n% might be used in the head model.\n% Default is estimated from the center of the best-fitting\n% sphere to the sensor locations\n% .Radii : a 3-element vector containing the radii of the single or 3\n% concentric spheres, when needed;\n% Order must be the following : [Rcsf, Routerskull, Rscalp];\n% Default is estimated from the best-fitting sphere to the\n% sensor locations and OPTIONS.Radii is set to: Rscalp [.88\n% .93 1]. Rscalp is estimated from the radius of the\n% best-fitting sphere;\n% .Conductivity : a 3-element vector containing the values for the\n% conductivity of the tissues in the following order:\n% [Ccsf, Cskull, Cscalp];\n% Default is set to [.33 .0042 .33];\n% .EEGRef : the NAME (not index of the channel file) of the electrode\n% that acts as the reference channel for the EEG. If data is\n% referenced to instantaneous average (i.e. so called\n% average-reference recording) value is 'AVERAGE REF';\n% IMPORTANT NOTICE: When user calls bst_headmodeler with the\n% .ChannelLoc option and .ChannelType = 'EEG'and wants the EEG\n% reference to be e.g. channel 26, then .EEGRef should be set\n% to 'EEG 26'\n% Default is 'AVERAGE REF'.\n%\n% .OS_ComputeParam : if 1, force computation of all sphere parameters when\n% choosing a method based on either the MEG or EEG\n% overlapping-sphere technique, if 0 and when\n% .HeadModelFile is specified, sphere parameters are\n% loaded from the pre-computed HeadModel file.\n% Default is 1.\n%\n% .BEM : Structure that specifies the necessary BEM parameters\n% .Interpolative : Flag indicating whether exact or\n% interpolative approach is used to compute\n% the forward solution using BEM.\n% if set to 1, exact computation is run on a\n% set of points distributed wihtin the inner\n% head volume and any subsequent request for\n% a forward gain vector (e.g. during a\n% volumic source scan using RAP-MUSIC) is\n% computed using an interpolation of the\n% forward gain vectors of the closest volumic\n% grid points. This allows faster computation\n% of the BEM solution during source search.\n% if set to 0, exact computation is required\n% at every source location.\n% We recommend to set it to 0 (default) when\n% sources have fixed location, e.g.\n% constrained on the cortical surface.\n% .EnvelopeNames : a cell array of strutures that specifies\n% the ORDERED tessellated surfaces to be\n% included in the BEM computation.\n% .EnvelopeNames{k}.TessFile : A string for\n% the name of the tessellation file\n% containing the kth surface\n% .EnvelopeNames{k}.TessName : A string for\n% the name of the surface within the\n% tessellation file This string should match\n% one of the Comment strings in the\n% tessellation file. The chosen surfaces must\n% be ordered starting by the the innermost\n% surface (e.g. brain or inner skull\n% surface) and finishing with the outermost\n% layer (e.g. the scalp)\n% .Basis : set to either 'constant' or 'linear' (default)\n% .Test : set to either 'Galerkin' or 'Collocation' (default)\n% .ISA : Isolated-skull approach set to 0 or 1 (default is 1)\n% .NVertMax : Maximum number of vertices per envelope,\n% therefore leading to decimation of orginal\n% surfaces if necessary\n% (default is 1000)\n% .ForceXferComputation: if set to 1, force recomputation of\n% existing transfer matrices in current\n% study folder (replace existing\n% files);\n% Default is 1\n%\n% *\n% * Fields Related to Sensor Information *\n% *\n%\n% .ChannelFile : Specifies the name of the file containing the channel\n% information (needs to be a BrainStorm channel file). If\n% file does not exists and sensor information is provided in\n% .ChannelLoc, a BrainStorm Channl file with name\n% .ChannelFile is created\n% Default is left blank as this information is extracted\n% from the channel file associated to the chosen BrainStorm\n% studyfile.\n% .Channel : A full BrainStorm channel structure if no channel file is\n% specified;\n% Default is empty\n% .ChannelType : A string specifying the type of channel in ChannelLoc. Can\n% be either 'MEG' or 'EEG'. Note that the same channel type\n% is assumed for every channel.\n% Default is empty\n% .ChannelLoc : Specifies the location of the channels where to compute\n% the forward model Can be either a 3xNsens (for EEG or\n% MEG-magnetometer) or 6xNsens matrix (for the\n% MEG-gradiometer case). (for magnetometer or gradiometer\n% MEG - channel weights are set to -1 and 1 for each\n% magnetometer in the gradiometer respectively) Note that\n% in the MEG-gradiometer case, the 3 first (res. last) rows\n% of .ChannelLoc stand for each of the magnetometers of the\n% gradiometer set. In the case of a mixture of MEG magneto\n% and MEG gradio-meters, .ChannelLoc needs to be a 6xNsens\n% matrix where the last 3 rows are filled with NaN for\n% MEG-magnetometers. If ones wants to handle both EEG and MEG\n% sensors, please create a full ChannelFile and use the\n% .ChannelFile option.\n% Default is empty (Information extracted from the ChannelFile).\n% .ChannelOrient : Specifies the orientation of the channels where to\n% compute the EEG or MEG forward model Can be either a\n% 3xNsens (for EEG and magnetometer MEG) or 6xNsens (for\n% gradiometer MEG) matrix or a cell array of such matrices\n% (one cell per type of method selected)\n% Default is empty (Information extracted from the\n% ChannelFile or assume radial orientation when\n% .ChannelLoc is filled).\n%\n% *\n% * Fields Related to Source Models *\n% *\n% .SourceModel : A vector indicating the type of source models to be\n% computed; The following code is enfoced:\n% -1 : Compute the forward fields of Current Dipole sources\n% (available for all forward approaches)\n% 1 : 1st-order Current Multipole Sources\n% (available for sphere-based MEG approaches only)\n% User can set OPTIONS.SourceModel to e.g., [-1 1] to\n% compute forward models from both source models.\n% Default is -1\n%\n%\n% *\n% * Fields Related to Source Localization *\n% *\n% .Cortex : A structure specifying the Cortex surface\n% envelope to serve as an image support with\n% following fields.\n% .FileName : A string specifying the name of\n% the BrainStorm tessellation file\n% containing the Cortex\n% tessellation;\n% .iGrid : An integer for the index of the\n% Cortex surface in the Faces,\n% Vertices and Comments cell arrays\n% in the tessellation file (default\n% is 1)\n% Default is empty.\n% .GridLoc : A 3xNsources matrix that contains the\n% locations of the sources at which the forward\n% model will be computed\n% Default is empty (Information taken from\n% OPTIONS.Cortex or OPTIONS.VolumeSourceGrid);\n% .GridOrient : a 3xNsources matrix that forces the source\n% orientation at every vertex of the .ImageGrid\n% cortical surface;\n% Defaults is empty; this information being\n% extracted from the corresponding tessellated\n% surface.\n% .ApplyGridOrient : if set to 1, force computation of the forward\n% fields by considering the local orientation of\n% the cortical surface;\n% If set to 0, a set of 3 orthogonal dipoles are\n% considered at each vertex location on the\n% tessellated surface.\n% Default is 1.\n% .VolumeSourceGrid : if set to 1, a 3D source grid is designed to\n% fit inside the head volume and will serve as a\n% source space for scannig techniques such as\n% RAP-MUSIC;\n% if set to 0, this grid will be computed at the\n% first call of e.g. RAP-MUSIC);\n% Default is 1\n% .VolumeSourceGridSpacing : Spacing in centimeters between two consecutive\n% sources in the 3D source grid described above;\n% Default is 2 cm.\n% .VolumeSourceGridLoc : a 3xN matrix specifying the locations of the\n% grid points that will be used to design the\n% volumic search grid (see .VolumicSourceGrid)\n% Default is empty (locations are estimated\n% automatically to cover the estimated inner\n% head volume)\n% .SourceLoc : a 3xNsources matrix that contains the\n% locations of the sources at which the forward\n% model will be computed\n% Default is empty (Information taken from\n% OPTIONS.ImageGrid or\n% OPTIONS.VolumeSourceGrid);\n% .SourceOrient : a 3xNsources matrix that contains the\n% orientations of the sources at which the\n% forward model will be computed\n% Default is empty.\n%\n%\n% --------------------------------- OUTPUTS ------------------------------------\n% OUTPUT\n% G if the number of sources (Nsources) if less than\n% .ImageGridBlockSize then G is a gain matrix of dimension\n% Nsensors x Nsources: Each column of G is the forward field\n% created by a dipolar source of unit amplitude. Otherwise, G is\n% the name of the binary file containing the gain matrix. This\n% file can be read using the READ_GAIN function.\n%\n% Gxyz As for G but for each dipole moment\n%\n% OPTIONS Returns the OPTIONS structure with updated fields following the\n% call to BST_HEADMODELER. Can be useful to obtain a full\n% BrainStorm Channel structure when only the .ChannelLoc and\n% possibly .ChannelOrient fields were provided.\n\n% ---------------------- 27-Jun-2005 10:43:31 -----------------------\n% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------\n%\n% CATEGORY: Forward Modeling\n%\n% Alphabetical list of external functions (non-Matlab):\n% toolbox\\bem_gain.m\n% toolbox\\bem_xfer.m\n% toolbox\\berg.m\n% toolbox\\bst_message_window.m\n% toolbox\\colnorm.m\n% toolbox\\get_channel.m\n% toolbox\\get_user_directory.m\n% toolbox\\good_channel.m\n% toolbox\\gridmaker.m\n% toolbox\\inorcol.m\n% toolbox\\norlig.m\n% toolbox\\overlapping_sphere.m\n% toolbox\\rownorm.m\n% toolbox\\save_fieldnames.m\n% toolbox\\source_grids.m\n% toolbox\\view_surface.m\n%\n% Subfunctions in this file, in order of occurrence in file:\n% BEMGaingridFname = bem_GainGrid(DataType,OPTIONS,BEMChanNdx)\n% g = gterm_constant(r,rq)\n%\n% At Check-in: $Author: Silvin $ $Revision: 68 $ $Date: 12/15/05 4:14a $\n%\n% This software is part of BrainStorm Toolbox Version 27-June-2005\n%\n% Principal Investigators and Developers:\n% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,\n% University of Southern California, Los Angeles, CA\n% ** John C. Mosher, PhD, Biophysics Group,\n% Los Alamos National Laboratory, Los Alamos, NM\n% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,\n% CNRS, Hopital de la Salpetriere, Paris, France\n%\n% See BrainStorm website at http://neuroimage.usc.edu for further information.\n%\n% Copyright (c) 2005 BrainStorm by the University of Southern California\n% This software distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPL\n% license can be found at http://www.gnu.org/copyleft/gpl.html .\n%\n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n% ------------------------ 27-Jun-2005 10:43:31 -----------------------\n\n\n\n% /---Script Author--------------------------------------\\\n% | |\n% | *** Sylvain Baillet Ph.D. |\n% | Cognitive Neuroscience & Brain Imaging Laboratory |\n% | CNRS UPR640 - LENA |\n% | Hopital de la Salpetriere, Paris, France |\n% | sylvain.baillet@chups.jussieu.fr |\n% | |\n% \\------------------------------------------------------/\n%\n% Date of creation: March 2002\n\n\n% Default options settings--------------------------------------------------------------------------------------------------\nDefaultMethod = {'meg_sphere','eeg_3sphereBerg'};\n\nReducePatchScalpNVerts = 500;\nBEM_defaults = struct(...\n 'Basis','linear',...\n 'Test','galerkin',...\n 'Interpolative',0,...\n 'ISA',1,...\n 'NVertMax',1000,...\n 'ForceXferComputation', 1, ...\n 'checksurf',0);\n\nDef_OPTIONS = struct(...\n 'ApplyGridOrient',1,...\n 'BEM', BEM_defaults,...\n 'Channel', [],...\n 'ChannelFile', '',...\n 'ChannelLoc', '',...\n 'ChannelOrient', '',...\n 'ChannelType', '',...\n 'Conductivity', [.33 .0042 .33],...\n 'Cortex',[],...\n 'EEGRef','',...\n 'HeadCenter',[],...\n 'HeadModelFile', '',...\n 'HeadModelName','Default',...\n 'ImageGridBlockSize', 2000,...\n 'ImageGridFile', '',...\n 'GridOrient',[],...\n 'Method', {DefaultMethod},...\n 'OS_ComputeParam', 1,...\n 'PrefixFileName','bst_',...\n 'Radii', [],...\n 'Scalp',[],...\n 'SourceLoc',[],...\n 'SourceModel', [-1],...\n 'SourceOrient',[],...\n 'StudyFile','',...\n 'TessellationFile','',...\n 'VolumeSourceGrid',1,...\n 'VolumeSourceGridSpacing', 2,...\n 'VolumeSourceGridLoc', [],...\n 'Verbose', 1 ...\n );\n\nif nargin == 0\n varargout{1} = Def_OPTIONS;\n return\nelse\n OPTIONS = varargin{1};\nend\n\n% Check field names of passed OPTIONS and fill missing ones with default values\nDefFieldNames = fieldnames(Def_OPTIONS);\nfor k = 1:length(DefFieldNames)\n if ~isfield(OPTIONS,DefFieldNames{k}) | strcmp(DefFieldNames{k},'BEM')\n if ~isfield(OPTIONS,DefFieldNames{k})\n\n OPTIONS = setfield(OPTIONS,DefFieldNames{k},getfield(Def_OPTIONS,DefFieldNames{k}));\n\n elseif strcmp(DefFieldNames{k},'BEM')\n\n BEM_DefFieldNames = fieldnames(BEM_defaults);\n for kk = 1:length(BEM_DefFieldNames)\n if ~isfield(OPTIONS.BEM,BEM_DefFieldNames{kk})\n OPTIONS.BEM = setfield(OPTIONS.BEM,BEM_DefFieldNames{kk},getfield(BEM_defaults,BEM_DefFieldNames{kk}));\n end\n end\n end\n end\nend\n\nif isempty(OPTIONS.Conductivity)\n OPTIONS.Conductivity = Def_OPTIONS.Conductivity;\nend\n\nclear Def_OPTIONS\n\nif isempty(OPTIONS.HeadModelFile) & ~isempty(OPTIONS.ImageGridFile)\n % Force creation of a headmodel file\n OPTIONS.HeadModelFile = 'default';\nend\n\nOPTIONS.HeadModelFileOld = OPTIONS.HeadModelFile;\n\n% What type of forward model (MEG and/or EEG) ?\nDataType.MEG = strmatch('meg',OPTIONS.Method); % Rank of the respective forward method in cell array Method (ie could be Method = {'meg_bem','eeg_sphere'} or vice-versa)\nDataType.EEG = strmatch('eeg',OPTIONS.Method);\n\nif ~iscell(OPTIONS.Method)\n OPTIONS.Method = {OPTIONS.Method};\nend\n\nMegMethod = [];\nif ~isempty(DataType.MEG)\n MegMethod = OPTIONS.Method{DataType.MEG}; % String indicating the forward method selected for MEG (res. EEG)\nend\nEegMethod = [];\nif ~isempty(DataType.EEG)\n EegMethod = OPTIONS.Method{DataType.EEG};\nend\n\n\n% Check inputs integrity\n\n%Source models\nif ~isempty(find(OPTIONS.SourceModel == 0)) | ~isempty(find(abs(OPTIONS.SourceModel) > 1)) % unValid source models\n if ~isempty(DataType.MEG)\n errordlg('Valid source model orders for MEG are: -1 (Current Dipole) and 1 (fist-order Current Multipole Expansion)')\n end\n if ~isempty(DataType.EEG)\n errordlg('Valid source model order for EEG is: -1 (Current Dipole) ')\n end\n varargout = cell(nargout,1);\n return\nend\n\n% Source locations\nif isempty(OPTIONS.SourceLoc) & ~OPTIONS.VolumeSourceGrid & isempty(OPTIONS.Cortex) % No source locations were specified\n errordlg('No source locations are specified. Please fill either one of the following fields of OPTIONS: .SourceLoc / .VolumeSourceGrid / .Cortex')\n varargout = cell(nargout,1);\n return\nend\n\n\n%--------------------------------------------------------------------------------------------------------------------------------------------\n%\n% HEAD MODELING BEGINS\n%\n%--------------------------------------------------------------------------------------------------------------------------------------------\n\n% Get Channel Information ------------------------------------------------------------------------------------------------------------------\nif ~isempty(OPTIONS.Channel)\n Channel = OPTIONS.Channel;\nelse\n if isempty(OPTIONS.ChannelFile) & isempty(OPTIONS.ChannelLoc) % Load Channel file in current folder\n\n [Channel, ChannelFile] = get_channel(fullfile(User.STUDIES,OPTIONS.StudyFile));\n OPTIONS.ChannelFile = fullfile(fileparts(fullfile(User.STUDIES,OPTIONS.StudyFile)),ChannelFile);\n\n if isempty(ChannelFile)\n errordlg(sprintf('Channel file %s is missing. Please have it available it the current study folder.',OPTIONS.ChannelFile), 'Missing Channel File')\n return\n end\n\n elseif isempty(OPTIONS.ChannelLoc) & exist(OPTIONS.ChannelFile,'file') % If no specific channel locations are given and channel file exists, load the proper channel file\n\n OPTIONS.rooot = strrep(lower(OPTIONS.ChannelFile),'channel.mat','');\n try\n load(OPTIONS.ChannelFile)\n catch\n cd(User.STUDIES)\n load(OPTIONS.ChannelFile)\n end\n\n else % Create a dummy Channel structure with Channel Locations (res. Orientations) specified in OPTIONS.ChannelLoc (res .ChannelOrient)\n\n if OPTIONS.Verbose, bst_message_window('Creating the channel structure from information in the OPTIONS fields. . .'), end\n\n % Get Channel Locations\n nchan = size(OPTIONS.ChannelLoc,2); % Number of channels\n Channel = struct('Loc',[],'Orient',[],'Comment','','Weight',[],'Type','','Name','');\n Channel(1:nchan) = deal(Channel);\n\n ChanType = upper(OPTIONS.ChannelType);\n if isempty(ChanType)\n errordlg('Please specify a channel type (i.e. MEG or EEG) in the ChannelType field of OPTIONS'),\n bst_message_window('Please specify a channel type (i.e. MEG or EEG) in the ChannelType field of OPTIONS'),\n varargout = cell(nargout,1);\n return\n end\n [Channel(:).Type] = deal(ChanType);\n if size(OPTIONS.ChannelLoc,1) == 6 % MEG Gradiometers or mixture gradio/magneto meters\n OPTIONS.ChannelLoc = reshape(OPTIONS.ChannelLoc,3,nchan*2);\n iGradFlag = 1; % Flag - gradiometer-type sensor set\n else\n iGradFlag = 0; % Flag - EEG or magnetometer-type sensor set\n end\n ichan = 1;\n for k = 1:nchan\n if iGradFlag\n Channel(k).Loc = OPTIONS.ChannelLoc(:,ichan:ichan+1);\n ichan = ichan+2;\n else\n if strcmp(ChanType,'MEG')\n Channel(k).Loc = OPTIONS.ChannelLoc(:,ichan);\n %elseif strcmp(ChanType,'EEG') % Artificially add a dummy column full of zeros to each Channel(k).Loc\n %Channel(k).Loc = [OPTIONS.ChannelLoc(:,ichan) [0 0 0]'];\n elseif strcmp(ChanType,'EEG') % Artificially add a dummy column full of zeros to each Channel(k).Loc\n Channel(k).Loc = [OPTIONS.ChannelLoc(:,ichan)];\n end\n ichan = ichan+1;\n end\n Channel(k).Name = sprintf('%s %d',ChanType,k);\n Channel(k).Comment = int2str(k);\n end\n clear ichan k\n\n % Get Channel Orientations\n if isempty(OPTIONS.ChannelOrient) & strcmp(ChanType,'MEG') % No channel orientation were specified: use radial sensors\n if OPTIONS.Verbose, bst_message_window('Assign radial orientation to all Channels. . .'), end\n if isempty(OPTIONS.HeadCenter)\n if iGradFlag\n Vertices = OPTIONS.ChannelLoc(:,1:2:end)';\n else\n Vertices = OPTIONS.ChannelLoc';\n end\n\n nscalp = size(Vertices,1);\n if nscalp > 500 % 500 points is more than enough to compute scalp's best fitting sphere\n Vertices = Vertices(unique(round(linspace(1,nscalp,500))),:);\n nscalp = size(Vertices,1);\n end\n nmes = size(Vertices,1);\n\n % Run parameters fit --------------------------------------------------------------------------------------------------------------\n mass = mean(Vertices); % center of mass of the scalp vertex locations\n R0 = mean(norlig(Vertices - ones(nscalp,1)*mass)); % Average distance between the center of mass and the scalp points\n vec0 = [mass,R0];\n\n [minn,brp] = fminsearch('dist_sph',vec0,[],Vertices);\n OPTIONS.HeadCenter = minn(1:end-1);\n if isempty(OPTIONS.Radii)\n OPTIONS.Radii = minn(end);\n OPTIONS.Radii = minn(end)*[1/1.14 1/1.08 1];\n end\n\n if OPTIONS.Verbose, bst_message_window({...\n sprintf('Center of the Sphere : %3.1f %3.1f %3.1f (cm)',100*OPTIONS.HeadCenter),...\n sprintf('Radius : %3.1f (cm)',100*OPTIONS.Radii(3)),...\n '-> DONE',' '})\n end\n\n clear minn brp mass R0 Vertices vec0\n end\n\n tmp = [Channel.Loc] - repmat(OPTIONS.HeadCenter',1,nchan*(1+(iGradFlag==1)));\n OPTIONS.ChannelOrient = tmp*inorcol(tmp); % Radial orientation for every channel\n clear tmp\n elseif ~isempty(OPTIONS.ChannelOrient) & strcmp(ChanType,'MEG') & iGradFlag\n OPTIONS.ChannelOrient = reshape(OPTIONS.ChannelOrient,3,nchan*2);\n end\n\n if strcmp(ChanType,'MEG')\n for k=1:nchan\n Channel(k).Orient = OPTIONS.ChannelOrient(:,((1+(iGradFlag==1))*k-1):(1+(iGradFlag==1))*k);\n end\n end\n\n clear k\n\n % Define Weights\n if iGradFlag\n [Channel(:).Weight] = deal([1 -1]);\n else\n [Channel(:).Weight] = deal([1]);\n end\n\n if strcmp(ChanType,'MEG') % Force no reference channels\n Channel(1).irefsens = [];\n end\n\n % New Channel stbemructure completed: save as a new channel file\n if ~isempty(OPTIONS.ChannelFile)\n %OPTIONS.ChannelFile = [OPTIONS.rooot,'channel.mat'];\n save(OPTIONS.ChannelFile,'Channel')\n if OPTIONS.Verbose, bst_message_window({...\n sprintf('Channel file created in : %s',OPTIONS.ChannelFile),...\n '-> DONE',' '}), end\n end\n\n end\n\n %load(OPTIONS.ChannelFile)\n OPTIONS.Channel = Channel;\nend\n\n% Find MEG and EEG channel indices\nMEGndx = good_channel(Channel,[],'MEG');\nEEGndx = good_channel(Channel,[],'EEG');\nEEGREFndx = good_channel(Channel,[],'EEG REF');\n\nMEG = ~isempty(MEGndx) & ~isempty(DataType.MEG); % == 1 if MEG is requested and is available\nEEG = ~isempty(EEGndx) & ~isempty(DataType.EEG);\n\nif ~EEG & ~MEG\n errordlg('Please check that data (MEG or EEG) and channel types are compatible.')\n return\nend\n\nif EEG\n if isempty(OPTIONS.EEGRef)\n % EEG Reference Channel\n EEGREFndx = good_channel(Channel,[],'EEG REF');\n if isempty(EEGREFndx) % Average EEG reference anyway\n [Channel(EEGndx).Comment] = deal('AVERAGE REF');\n end\n else % EEG Reference is specified\n switch(OPTIONS.EEGRef)\n case 'AVERAGE REF'\n [Channel(:).Comment] = deal('AVERAGE REF');\n otherwise\n EEGREFndx = strmatch(OPTIONS.EEGRef,char(Channel(:).Name));\n if isempty(EEGREFndx)\n errordlg(sprintf(...\n 'No channel named ''%s'' was found amongst available EEG channels. Cannot use it as a reference for EEG.',OPTIONS.EEGRef...\n ))\n return\n end\n end\n end\nend\n\n\nif MEG & isempty(MEGndx) % User wants to compute MEG but no MEG data is available\n errordlg('Sorry - No MEG data is available'), return\nend\n\nif EEG & isempty(EEGndx) % User wants to compute EEG but no EEG data is available\n errordlg('Sorry - No EEG data is available'), return\nend\n\n\n% Computation of parameters of the best-fitting sphere --------------------------------------------------------------------------------------------------------------\nif length(findstr('bem',[OPTIONS.Method{:}])) ~= length(OPTIONS.Method)% Only if sphere-based head model is requested in any modality (MEG or EEG)\n\n % Best-fitting sphere parameters --------------------------------------------------------------------------------------------------------------\n if isempty(OPTIONS.HeadCenter) | isempty(OPTIONS.Radii)\n\n if OPTIONS.Verbose, bst_message_window('Estimating Center of the Head. . .'), end\n\n if isempty(OPTIONS.Scalp) % Best-fitting sphere is derived from the sensor array\n % ans = questdlg('No scalp surface was selected - Do you want to use a spherical approximation of the head derived from the sensor locations instead ?',...\n % '','Yes','No','Yes');\n if EEG & length(EEGndx) > 9 % If EEG is available but a reasonable number of electrodes, use it to compute the sphere parameters\n ndx = [EEGndx]; % Compute Sphere parameters from EEG sensors only\n else\n ndx = [MEGndx];\n end\n\n Vertices = zeros(length(ndx),3);\n for k=1:length(ndx)\n Vertices(k,:) = Channel(ndx(k)).Loc(:,1)';\n end\n\n else % Best-fitting sphere is computed from the set of vertices of the scalp surface enveloppe\n\n try\n load(fullfile(User.SUBJECTS,OPTIONS.Scalp.FileName),'Vertices')\n catch\n load(OPTIONS.Scalp.FileName,'Vertices')\n end\n\n if ~isfield(OPTIONS.Scalp,'iGrid') % Apply Default\n OPTIONS.Scalp.iGrid = 1;\n end\n\n try\n Vertices = Vertices{OPTIONS.Scalp.iGrid}';\n catch\n errordlg(sprintf(...\n 'Tessellation file %s does not contain %d enveloppes',...\n OPTIONS.Scalp.FileName,OPTIONS.Scalp.iGrid))\n end\n end\n\n nscalp = size(Vertices,1);\n nmes = size(Vertices,1);\n\n % Run parameters fit --------------------------------------------------------------------------------------------------------------\n mass = mean(Vertices); % center of mass of the scalp vertex locations\n R0 = mean(norlig(Vertices - ones(nscalp,1)*mass)); % Average distance between the center of mass and the scalp points\n vec0 = [mass,R0];\n\n [SphereParams,brp] = fminsearch('dist_sph',vec0,[],Vertices);\n\n end % no head center and sphere radii were specified by user\n\n % Assign default values for sphere parameters\n % if none were specified before\n if isempty(OPTIONS.Radii)\n OPTIONS.Radii = SphereParams(end)*[1/1.14 1/1.08 1];\n end\n\n if isempty(OPTIONS.HeadCenter)\n OPTIONS.HeadCenter = SphereParams(1:end-1)';\n end\n\n if isempty(OPTIONS.Conductivity)\n OPTIONS.Conductivity = [.33 .0042 .33];\n end\n\nend % Use BEM Approach, so proceed to the selection of the envelopes\n\n% ---------------------------------------------------------------------------------------------------------\n%Create HeadModel Param structure\nParam(1:length(Channel)) = deal(struct('Center',[],'Radii',[],'Conductivity',[],'Berg',[]));\n\nif ~isempty(findstr('os',[OPTIONS.Method{:}])) % Overlapping-Sphere EEG or MEG is requested: load the scalp's tessellation\n\n if isempty(OPTIONS.Scalp)\n errordlg('Please specify a subject tessellation file for Scalp enveloppe in OPTIONS.Scalp when using Overlapping-Sphere forward approach');\n return\n end\n\n % load(fullfile(User.SUBJECTS,BrainStorm.SubjectTess),'Faces');\n try\n load(fullfile(User.SUBJECTS,OPTIONS.Scalp.FileName),'Faces','Vertices');\n catch\n load(OPTIONS.Scalp.FileName,'Faces','Vertices');\n end\n\n Faces = Faces{OPTIONS.Scalp.iGrid};\n Vertices = Vertices{OPTIONS.Scalp.iGrid}';\n\n if size(Vertices,1) > ReducePatchScalpNVerts % Reducepatch the scalp tessellation for fastest OS computation\n nfv = reducepatch(Faces,Vertices,2*ReducePatchScalpNVerts);\n if OPTIONS.Verbose, bst_message_window({...\n sprintf('Decimated scalp tessellation from %d to %d vertices.',size(Vertices,1),size(nfv.vertices,1)),...\n ' '});\n end\n clear Faces Vertices\n SubjectFV.vertices = nfv.vertices';\n SubjectFV.faces = nfv.faces;\n clear nfv\n else\n SubjectFV.vertices = Vertices; % Available from the computation of the head center above\n clear Vertices\n SubjectFV.faces = Faces; clear Faces\n end\n\n if length(findstr('os',[OPTIONS.Method{:}])) == 2 % OS approach requested fro both MEG and EEG\n ndx = [MEGndx,EEGndx];\n\n else\n if MEG\n if strcmpi('meg_os',OPTIONS.Method{DataType.MEG}) % OS for MEG only\n ndx = MEGndx;\n end\n end\n\n if EEG\n if strcmpi('eeg_os',OPTIONS.Method{DataType.EEG}) % OS for EEG only\n ndx = [EEGndx, EEGREFndx];\n end\n end\n end\n\n if isempty(OPTIONS.HeadModelFile) | OPTIONS.OS_ComputeParam\n\n % Compute all spheres parameters\n %------------------------------------------------------------------\n Sphere = overlapping_sphere(Channel(ndx),SubjectFV,OPTIONS.Verbose,OPTIONS.Verbose);\n if OPTIONS.Verbose\n bst_message_window({...\n 'Computing Overlapping-sphere model -> DONE',' '})\n end\n [Param(ndx).Center] = deal(Sphere.Center);\n [Param(ndx).Radii] = deal(Sphere.Radius);\n [Param(ndx).Conductivity] = deal(OPTIONS.Conductivity);\n\n elseif exist(OPTIONS.HeadModelFile,'file')\n\n load(OPTIONS.HeadModelFile,'Param') % or use precomputed\n if OPTIONS.Verbose\n bst_message_window({...\n sprintf('Sphere parameters loaded from : %s -> DONE',OPTIONS.HeadModelFile),' '})\n end\n\n else\n\n errordlg(sprintf('Headmodel file %s does not exist in Matlab''s search path',OPTIONS.HeadModelFile))\n return\n\n end\n\nend\n\nif ~isempty(findstr('sphere',[OPTIONS.Method{:}])) % Single or nested-sphere approaches\n\n [Param([MEGndx, EEGndx, EEGREFndx]).Center] = deal(OPTIONS.HeadCenter);\n [Param([MEGndx, EEGndx, EEGREFndx]).Radii] = deal(OPTIONS.Radii);\n [Param([MEGndx, EEGndx, EEGREFndx]).Conductivity] = deal(OPTIONS.Conductivity);\n\n if EEG & strcmpi('eeg_3sphereberg',lower(OPTIONS.Method{DataType.EEG})) % BERG APPROACH\n\n if ~isempty(OPTIONS.HeadModelFile) & exist(OPTIONS.HeadModelFile,'file')\n if OPTIONS.Verbose, bst_message_window('Checking for previous EEG \"BERG\" parameters'), end\n ParamOld = load(OPTIONS.HeadModelFile,'Param');\n iFlag = 0; % Flag\n if isfield(ParamOld.Param,'Berg') & ~isempty(ParamOld.Param(1).Radii)\n % Check if these older parameters were computed with the same as current radii and conductivity values\n if ParamOld.Param(1).Radii ~= Param(1).Radii;\n iFlag = 1;\n end\n if ParamOld.Param(1).Conductivity ~= Param(1).Conductivity;\n iFlag = 1;\n end\n else\n iFlag = 1;\n end\n else\n iFlag = 1;\n end\n\n if iFlag == 1\n if OPTIONS.Verbose , bst_message_window('Computing EEG \"BERG\" Parameters. . .'), end\n [mu_berg_tmp,lam_berg_tmp] = berg(OPTIONS.Radii,OPTIONS.Conductivity);\n Param(EEGndx(1)).Berg.mu = mu_berg_tmp; clear mu_berg_tmp\n Param(EEGndx(1)).Berg.lam = lam_berg_tmp; clear lam_berg_tmp\n if OPTIONS.Verbose, bst_message_window({'Computing EEG \"BERG\" Parameters -> DONE',' '}), end\n else\n if OPTIONS.Verbose , bst_message_window('Using Previous EEG \"BERG\" Parameters'), end\n Param(EEGndx(1)).Berg.mu = ParamOld.Param(1).Berg.mu;\n Param(EEGndx(1)).Berg.lam = ParamOld.Param(1).Berg.lam; clear ParamOld\n end\n [Param.Berg]= deal(Param(EEGndx(1)).Berg);\n\n end\n\nend\n\n\nif ~isempty(findstr('bem',[OPTIONS.Method{:}])) % BEM approaches - Compute transfer matrices\n\n if OPTIONS.BEM.Interpolative==0 & OPTIONS.VolumeSourceGrid %& isempty(OPTIONS.Cortex) % User wants volumic grid : force Interpolative approach\n OPTIONS.BEM.Interpolative = 1; % CBB (SB, 07-May-2004)| Should work also for volumic grid\n hwarn = warndlg('Volumic Source Grid BEM is only available for interpolative BEM. BEM computation will be now forced to interpolative. If you want a non-interpolative BEM on a cortical image grid, first uncheck the Volumic Grid box from headmodeler gui.','Limitation from current BrainStorm version');\n drawnow\n waitfor(hwarn)\n end\n\n if MEG\n if ~isempty(findstr('bem',OPTIONS.Method{DataType.MEG})) % BEM is requested for MEG\n BEMChanNdx{DataType.MEG} = MEGndx;\n end\n end\n\n if EEG\n if ~isempty(findstr('bem',OPTIONS.Method{DataType.EEG})) % BEM is requested for EEG\n BEMChanNdx{DataType.EEG} = sort([EEGndx,EEGREFndx]); % EEGREFndx = [] is average ref\n end\n end\n\n OPTIONS.Param = Param;\n\n if OPTIONS.BEM.Interpolative % Computation of gain matrix over 3D interpolative grid\n if OPTIONS.BEM.ForceXferComputation\n BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx); % Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data\n else\n try\n BEMGaingridFileName = OPTIONS.BEM.GaingridFileName;\n catch\n cd(User.STUDIES)\n BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx); % Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data\n end\n end\n\n if MEG & EEG\n [Param(MEGndx).bem_gaingrid_mfname] = deal(BEMGaingridFileName.MEG);\n [Param([EEGndx]).bem_gaingrid_mfname] = deal(BEMGaingridFileName.EEG);\n else\n [Param(:).bem_gaingrid_mfname] = deal(BEMGaingridFileName);\n end\n\n else % BEM gain matrix computation over cortical surface\n\n\n BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx);\n\n [Param(:).bem_gaingrid_mfname] = deal('');\n\n end\n\n OPTIONS = rmfield(OPTIONS,'Param');\n\n ndx = sort([BEMChanNdx{:}]);\n\n\n [Param(ndx).Center] = deal([]);\n test=0; % this test is nowhere defined ?\n\n if OPTIONS.VolumeSourceGrid\n % Now define the outer scalp envelope for the source volume gridding if requested\n\n if OPTIONS.BEM.ForceXferComputation | ~test\n global nfv\n SubjectFV.vertices = nfv(end).vertices';\n SubjectFV.faces = nfv(end).faces; clear Faces\n else\n% Changed by Rik 4/10/07 to call from SPM without User files\n if exist('User')\n load(fullfile(User.SUBJECTS,fileparts(OPTIONS.Subject),OPTIONS.BEM.EnvelopeNames{end}.TessFile))\n\t else\n load(OPTIONS.BEM.EnvelopeNames{end}.TessFile)\n end\n%%%%%%\n idScalp = find(strcmpi(OPTIONS.BEM.EnvelopeNames{end}.TessName,Comment)); clear Comment\n if isempty(idScalp)\n errodlg(sprintf(...\n 'Scalp tessellation %s was not found in %s.',OPTIONS.BEM.EnvelopeNames{end}.TessName, OPTIONS.BEM.EnvelopeNames{end}.TessFile),...\n 'Error during BEM computation')\n return\n end\n\n SubjectFV.vertices = Vertices{idScalp}'; clear Vertices\n SubjectFV.faces = Faces{idScalp}; clear Faces\n end\n\n end\n\nend % if BEM\n\nif EEG\n\n switch(lower(OPTIONS.Method{DataType.EEG}))\n case 'eeg_sphere'\n [Param(EEGndx).EEGType] = deal('EEG_SINGLE');\n case 'eeg_3sphere'\n [Param(EEGndx).EEGType] = deal('EEG_3SHELL');\n case 'eeg_3sphereberg'\n [Param(EEGndx).EEGType] = deal('EEG_BERG');\n case 'eeg_os'\n [Param(EEGndx).EEGType] = deal('EEG_OS');\n case 'eeg_bem'\n [Param(EEGndx).EEGType] = deal('BEM');\n if EEG & ~MEG\n [Param(EEGndx).bem_gaingrid_mfname] = deal(BEMGaingridFileName);\n end\n end\n\nelse\n\n tmp = [];\n [Param.Conductivity] = deal(tmp);\n [Param.Berg] = deal(tmp);\n [Param.EEGType] = deal(tmp);\n\nend\n\n\n%_________________________________________________________________________________________________________________________________________________________________________\n%\n% The following part is an adaptation of the former HEADMODEL_MAKE script\n%\n% ________________________________________________________________________________________________________________________________________________________________________\n\n\n% Allocate function names depending on the selected forward approaches specified in the Method argument\nFunction = cell(1,length(Channel)); %allocate function names\n\nif MEG\n if ~isempty(findstr('bem',OPTIONS.Method{DataType.MEG})) % MEG BEM\n Function(MEGndx) = deal({'meg_bem'});\n if isfield(Channel(MEGndx(1)),'irefsens')\n Function(Channel(MEGndx(1)).irefsens) = deal({'meg_bem'});\n end\n\n else\n Function(MEGndx) = deal({'os_meg'});\n if isfield(Channel(MEGndx(1)),'irefsens')\n Function(Channel(MEGndx(1)).irefsens) = deal({'os_meg'});\n end\n if isfield(OPTIONS,'BEM')\n OPTIONS = rmfield(OPTIONS,'BEM');\n end\n\n end\nend\n\n\nif EEG\n if ~isempty(findstr('bem',OPTIONS.Method{DataType.EEG})) % MEG BEM\n Function(EEGndx) = deal({'eeg_bem'});\n else\n Function(EEGndx) = deal({'eeg_sph'});\n if isfield(OPTIONS,'BEM')\n OPTIONS = rmfield(OPTIONS,'BEM');\n end\n end\n\nend\n%--------------------------------------------------------------------------\nDIMS = [3 12]; % number of columns for each parametric source model: Current Dipole / Current Multipole\nHeadModel.Param = Param;\nHeadModel.Function = Function;\n\n\n%% -------------------------------------------------------------------------\n%\n% Now proceed to forward modeling of cortical grids or at some other specific source locations\n%\n%% -------------------------------------------------------------------------\n\n\nif ~isempty(OPTIONS.Cortex), % subject has cortical vertices as source supports\n % First make room in memory\n HeadModel.SearchGain = [];\n clear SearchGridLoc SearchGain G\n\n if OPTIONS.Verbose, bst_message_window({...\n 'Computing Gain Matrix '})\n end\n\n % Find the cortical grid where to compute the forward model in the tessellation file\n try\n ImageGrid = load(fullfile(User.SUBJECTS,OPTIONS.Cortex.FileName),'Comment','Vertices');\n catch\n ImageGrid = OPTIONS.Cortex.ImageGrid;\n end\n\n if ~isfield(OPTIONS.Cortex,'iGrid')\n OPTIONS.Cortex.iGrid = 1;\n end\n\n if OPTIONS.Cortex.iGrid > length(ImageGrid.Comment) % Corresponding cortical surface not found\n errordlg(sprintf('Cortical Tessellation file \"%s\" does not contain %d surfaces',...\n OPTIONS.Cortex.FileName,OPTIONS.Cortex.iGrid))\n return\n end\n\n GridLoc = ImageGrid.Vertices{OPTIONS.Cortex.iGrid}; % keep only the desired cell\n ImageGrid = rmfield(ImageGrid,'Vertices');\n\nelseif ~isempty(OPTIONS.SourceLoc) % Specific source locations are provided\n if size(OPTIONS.SourceLoc,1) ~= 3\n OPTIONS.SourceLoc = OPTIONS.SourceLoc';\n end\n GridLoc = OPTIONS.SourceLoc;\n\nelse\n rmfield(OPTIONS,'rooot');\n if nargout == 1\n varargout{1} = OPTIONS;\n else\n varargout{1} = HeadModel;\n varargout{2} = OPTIONS;\n end\n return % No ImageGrid requested\n\nend\n\nif ~isempty(OPTIONS.Cortex)\n GridName{OPTIONS.Cortex.iGrid} = ImageGrid.Comment{OPTIONS.Cortex.iGrid};\n OPTIONS.Cortex.Name = ImageGrid.Comment{OPTIONS.Cortex.iGrid};\nend\n\n\nfor Order = OPTIONS.SourceModel % Compute gain matrices for each requested source models (-1 0 1)\n\n i = 1; % Index to cell in headmodel cell arrays (MMII convention)\n\n switch(Order)\n case -1\n Dims = DIMS(1);% number of columns per source\n case 1\n Dims = DIMS(2);% number of columns per source\n end\n\n if ~isempty(OPTIONS.Cortex) & OPTIONS.ApplyGridOrient % Use cortical grid\n try\n load(OPTIONS.Cortex.FileName,'Faces');\n catch\n Faces = ImageGrid.Faces;\n end\n\n Faces = Faces{OPTIONS.Cortex.iGrid};\n ptch = patch('Vertices',GridLoc','Faces',Faces,'Visible','off');\n set(get(ptch,'Parent'),'Visible','off')\n GridOrient{i} = get(ptch,'VertexNormals')';\n delete(ptch);\n\n end\n\n if isempty(OPTIONS.GridOrient) & isempty(OPTIONS.SourceOrient) % Consider the cortical patch's normals\n\n if isempty(OPTIONS.Cortex) % Specific source locations in .SourceLoc but nohing in. SourceOrient\n OPTIONS.ApplyGridOrient = 0; % No source orientation specified: Force computation of full gain matrix\n else\n [nrm,GridOrient{i}] = colnorm(GridOrient{i});\n % Now because some orientations may be ill-set to [0 0 0] with the get(*,'VertexNormals' command)\n % set these orientation to arbitrary [1 1 1]:\n izero = find(nrm == 0);clear nrm\n if ~isempty(izero)\n GridOrient{i}(:,izero) = repmat([1 1 1]'/norm([1 1 1]),1,length(izero));\n end\n clear izero\n\n end\n\n elseif ~isempty(OPTIONS.GridOrient) % Apply user-defined cortical source orientations\n\n if size(OPTIONS.GridOrient,2) == size(GridLoc,2) % Check size integrity\n GridOrient{i} = OPTIONS.GridOrient;\n [nrm,GridOrient{i}] = colnorm(GridOrient{i});\n clear nrm\n else\n errordlg(sprintf('The source orientations you have provided are for %0.f sources. Considered cortical surface has %0.f sources. Computation aborted',...\n size(OPTIONS.GridOrient,2),size(GridOrient{i},2)));\n return\n end\n\n elseif ~isempty(OPTIONS.SourceOrient) % Apply user-defined specific source orientations\n\n if size(OPTIONS.SourceOrient,2) == size(GridLoc,2) % Check size integrity\n GridOrient{i} = OPTIONS.SourceOrient;\n [nrm,GridOrient{i}] = colnorm(GridOrient{i});\n clear nrm\n else\n errordlg(sprintf('The source orientations you have provided are for %0.f sources. Computation aborted',...\n size(OPTIONS.SourceOrient,2)));\n return\n end\n\n end\n\n nv = size(GridLoc,2); % number of grid points\n jj = 0; % Number of OPTIONS.ImageGridBlockSize\n\n for j = 1:(OPTIONS.ImageGridBlockSize):nv,\n jj = jj+1;\n if 1%OPTIONS.ApplyGridOrient\n ndx = [0:OPTIONS.ImageGridBlockSize-1]+j;\n else\n ndx = [0:3*OPTIONS.ImageGridBlockSize-1]+j;\n end\n\n if 1%OPTIONS.ApplyGridOrient\n if(ndx(end) > nv), % last OPTIONS.ImageGridOPTIONS.ImageGridBlockSizeSize too long\n ndx = [ndx(1):nv];\n end\n else\n if(ndx(end) > 3*nv),\n ndx = [ndx(1):3*nv];\n end\n end\n\n % Compute MEG\n if MEG & ~isempty(MEGndx)\n Gmeg = NaN*zeros(length(MEGndx),Dims*length(ndx));\n if ~isempty(Function{MEGndx(1)})\n\n if MEG & EEG\n clear('gain_bem_interp2'); % Free persistent variables to avoid confusion\n end\n\n if isfield(OPTIONS,'BEM') % BEM computation\n if ~OPTIONS.BEM.Interpolative % ~interpolative : retrieve stored gain matrix\n global GBEM_grid\n tmpndx = [3*(ndx(1)-1)+1:min([3*nv,3*ndx(end)])];%[0:3*OPTIONS.ImageGridBlockSize-1]+j;\n Gmeg = GBEM_grid(MEGndx,tmpndx);\n end\n else\n Gmeg = feval(Function{MEGndx(1)},GridLoc(:,ndx),Channel,Param,Order,OPTIONS.Verbose);\n end\n\n end\n else\n Gmeg = [];\n end\n\n if EEG & ~isempty(EEGndx) & i==1 % % Order -1 only for now in EEG\n\n Geeg = NaN*zeros(length(EEGndx),Dims*length(ndx));\n if ~isempty(Function{EEGndx(1)})\n if MEG & EEG\n clear('gain_bem_interp2'); % Free persistent variables to avoid confusion\n end\n\n if isfield(OPTIONS,'BEM') % BEM computation\n if ~OPTIONS.BEM.Interpolative % ~interpolative : retrieve stored gain matrix\n global GBEM_grid\n %Geeg = GBEM_grid(EEGndx,[j:min([3*nv,j+3*OPTIONS.ImageGridBlockSize-1])]);\n tmpndx = [3*(ndx(1)-1)+1:min([3*nv,3*ndx(end)])];%[0:3*OPTIONS.ImageGridBlockSize-1]+j;\n %min(tmpndx ), max(tmpndx)\n Geeg = GBEM_grid(EEGndx,tmpndx);\n end\n else\n Geeg = feval(Function{EEGndx(1)},GridLoc(:,ndx),Channel,Param,Order,OPTIONS.Verbose);\n end\n\n end\n else\n Geeg = [];\n end\n\n G = NaN*zeros(length(OPTIONS.Channel),length(ndx));\n Gxyz = NaN*zeros(length(OPTIONS.Channel),Dims*length(ndx));\n\n if OPTIONS.ApplyGridOrient\n % Gain matrix with fixed orientation - G\n %------------------------------------------------------------------\n src = 0;\n src_ind = 0;\n for k = 1:Dims:Dims*length(ndx)-2\n src = src+1;\n src_ind = src_ind+1;\n if ~isempty(Gmeg)\n G(MEGndx,src) = Gmeg(:,k:k+2) * GridOrient{1}(:,src_ind);\n end\n\n if ~isempty(Geeg) & (i==1)% % Order -1 only\n G(EEGndx,src) = Geeg(:,k:k+2) * GridOrient{1}(:,src_ind);\n end\n end\n else\n if MEG\n Gxyz(MEGndx,:) = Gmeg;\n end\n if EEG\n Gxyz(EEGndx,:) = Geeg;\n end\n end\n \n % Gain matrix for moments - Gxyz\n %------------------------------------------------------------------\n if MEG\n Gxyz(MEGndx,:) = Gmeg;\n end\n if EEG\n Gxyz(EEGndx,:) = Geeg;\n end\n end\n\nend % Cortical gain matrix for each source model\n\nif nargout == 1\n varargout{1} = OPTIONS;\nend\nif nargout == 2\n varargout{1} = G;\n varargout{2} = Gxyz;\nend\nif nargout == 3\n varargout{1} = G;\n varargout{2} = Gxyz;\n varargout{3} = OPTIONS;\nend\n\n\n%------------------------------------------------------------------------------------------------------------------------------\n%\n% SUB-FUNCTIONS\n%\n%------------------------------------------------------------------------------------------------------------------------------\n\nfunction BEMGaingridFname = bem_GainGrid(DataType,OPTIONS,BEMChanNdx)\n\n% Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data\n% DataType : a structure with fields MEG and EEG. DataType.MEG (res. DataType.EEG) is set to 1 if MEG (res. EEG) data is available\n% OPTIONS : the OPTIONS structure, input argument from bst_headmodeler\n% BEMChanNdx : a cell array of channel indices such that : BEMChanNdx{DataType.EEG} = EEGndx (res. MEG).\n%\n% BEMGaingridFname: a structure with fields:\n% .EEG : string with the name of the file containing the gain matrix of the 3D BEM interpolative grid in EEG\n% .MEG : same as .EEG respectively to MEG BEM model.\n\n\n% Detect the requested BEM computations: MEG and/or EEG___________________________________\n\n%User = get_user_directory;\n%if isempty(User)\n User.STUDIES = pwd;\n User.SUBJECTS = pwd;\n%end\n\nMEG = ~isempty(BEMChanNdx(DataType.MEG)); % == 1 if MEG is requested\nEEG = ~isempty(BEMChanNdx(DataType.EEG)); % == 1 if EEG is requested\nif MEG\n MEGndx = BEMChanNdx{DataType.MEG};\nend\nif EEG\n %EEGndx = BEMChanNdx{DataType.EEG};\n EEGndx = OPTIONS.EEGndx; % EEG sensors (not including EEG reference channel, if any)\n EEGREFndx = good_channel(OPTIONS.Channel,[],'EEG REF');\nend\n\nif MEG & EEG\n [Param(:).mode] = deal(3);\nelseif ~MEG & EEG\n [Param(:).mode] = deal(1);\nelseif MEG & ~EEG\n [Param(:).mode] = deal(2);\nelse\n errordlg('Please check that the method requested for forward modeling has an authorized name');\n return\nend\n\n% BEM parameters ________________________________________________________________________\n% Determine what basis functions to use\nconstant = ~isempty(strmatch('constant',lower(OPTIONS.BEM.Basis)));\nif constant == 0\n [Param(:).basis_opt] = deal(1);\nelse\n [Param(:).basis_opt] = deal(0);\nend\n\n% Determine what Test to operate\ncollocation = ~isempty(strmatch('collocation',lower(OPTIONS.BEM.Test)));\nif collocation == 0\n [Param(:).test_opt] = deal(1);\nelse\n [Param(:).test_opt] = deal(0);\nend\n\n% Insulated-skull approach\nisa = OPTIONS.BEM.ISA;\nif isa == 1\n [Param(:).ISA] = deal(1);\nelse\n [Param(:).ISA] = deal(0);\nend\n\nParam.Ntess_max = OPTIONS.BEM.NVertMax;\nParam.Conductivity = deal(OPTIONS.Conductivity);\n\n%_________________________________________________________________________________________\n\n% Load surface envelopes information______________________________________________________\n\n% Find the indices of the enveloppes selected for BEM computation\nif ~isfield(OPTIONS.BEM,'EnvelopeNames')\n errordlg('Please specify the ordered set of head-tissue envelopes by filling the OPTIONS.BEM.EnvelopeNames field')\n return\nend\nif isempty(OPTIONS.BEM.EnvelopeNames)\n errordlg('Please specify the ordered set of head-tissue envelopes by filling the OPTIONS.BEM.EnvelopeNames field')\n return\nend\nfor k = 1:length(OPTIONS.BEM.EnvelopeNames)\n\n try\n% Changed by Rik 4/10/07 to call from SPM without User files\n load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Comment');\n catch\n try\n load(OPTIONS.BEM.EnvelopeNames{end}.TessFile,'Comment');\n%%%%%%\n catch % Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile\n try\n OPTIONS.BEM.EnvelopeNames{k}.TessFile = [OPTIONS.BEM.EnvelopeNames{k}.TessFile,'.mat'];\n load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Comment');\n catch\n cd(User.SUBJECTS)\n load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Comment');\n end\n end\n end\n\n Comment = strrep(Comment,' ','');\n % find surface in current tessellation file\n OPTIONS.BEM.EnvelopeNames{k}.SurfId = find(strcmpi(OPTIONS.BEM.EnvelopeNames{k}.TessName,Comment));\n IDs(k) = OPTIONS.BEM.EnvelopeNames{k}.SurfId;\n if isempty(OPTIONS.BEM.EnvelopeNames{k}.SurfId)\n errordlg(...\n sprintf('Surface %s was not found in file %s',...\n OPTIONS.BEM.EnvelopeNames{k}.TessName, OPTIONS.BEM.EnvelopeNames{k}.TessFile))\n return\n end\n\n % Load vertex locations\n try\n tmp = load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Vertices');\n catch % Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile\n tmp = load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Vertices');\n end\n Vertices{k} = tmp.Vertices{OPTIONS.BEM.EnvelopeNames{k}.SurfId}';\n\n % Load faces\n try\n tmp = load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Faces');\n catch% Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile\n tmp = load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Faces');\n end\n\n Faces(k) = tmp.Faces(OPTIONS.BEM.EnvelopeNames{k}.SurfId);\nend\nclear Comment tmp\n\ncd(User.STUDIES)\n\n\n%_________________________________________________________________________________________\n\n\n% Channel Parameters______________________________________________________________________\nif MEG\n R_meg1 = zeros(length(MEGndx),3);\n O_meg1 = R_meg1;\n R_meg2 = R_meg1;\n O_meg2 = O_meg1;\n flaggrad = zeros(length(MEGndx),1);% if = 1 - Flag to indicate there are some gradiometers here\n\n i = 0;\n for k = MEGndx\n i = i+1;\n R_meg1(i,:) = OPTIONS.Channel(k).Loc(:,1)';\n O_meg1(i,:) = OPTIONS.Channel(k).Orient(:,1)';\n\n if size(OPTIONS.Channel(k).Loc,2) == 2\n if sum(OPTIONS.Channel(k).Loc(:,1)-OPTIONS.Channel(k).Loc(:,2))~=0 % Gradiometer\n R_meg2(i,:) = OPTIONS.Channel(k).Loc(:,2)';\n O_meg2(i,:) = OPTIONS.Channel(k).Orient(:,2)';\n flaggrad(k-min(MEGndx)+1) = 1;\n end\n end\n\n end\n O_meg1 = (O_meg1' * inorcol(O_meg1'))';\n if exist('O_meg2','var')\n O_meg2 = (O_meg2' * inorcol(O_meg2'))';\n end\n\n % Handle MEG reference channels if necessary\n irefsens = good_channel(OPTIONS.Channel,[],'MEG REF');\n\n if ~isempty(irefsens)\n flaggrad_REF = zeros(length(irefsens),1);% if = 1 - Flag to indicate there are some gradiometers here\n R_meg_REF = zeros(length(irefsens),3);\n O_meg_REF = R_meg_REF;\n R_meg_REF = R_meg_REF;\n O_meg_REF = R_meg_REF;\n\n if ~isempty(irefsens) & ~isempty(OPTIONS.Channel(MEGndx(1)).Comment) % Reference Channels are present\n if OPTIONS.Verbose, bst_message_window('Reference Channels have been detected.'), end\n end\n i = 0;\n for k = irefsens\n i = i+1;\n R_meg_REF(i,:) = OPTIONS.Channel(k).Loc(:,1)';\n O_meg_REF(i,:) = OPTIONS.Channel(k).Orient(:,1)';\n\n if size(OPTIONS.Channel(k).Loc,2) == 2\n if sum(OPTIONS.Channel(k).Loc(:,1)-OPTIONS.Channel(k).Loc(:,2))~=0 % Reference Gradiometer\n R_meg_REF2(i,:) = OPTIONS.Channel(k).Loc(:,2)';\n O_meg_REF2(i,:) = OPTIONS.Channel(k).Orient(:,2)';\n flaggrad_REF(k-min(irefsens)+1) = 1;\n end\n end\n\n end\n\n else\n R_meg_REF = [];\n O_meg_REF = R_meg_REF;\n R_meg_REF = R_meg_REF;\n O_meg_REF = R_meg_REF;\n end\n\n MEGndx_orig = MEGndx;\nelse\n R_meg1 = zeros(length(EEGndx),3); % Use dummy channel locations\n O_meg1 = R_meg1;\n R_meg2 = R_meg1;\n O_meg2 = O_meg1;\nend\n\nif EEG\n R_eeg = zeros(length([EEGREFndx,EEGndx]),3);\n i = 0;\n for k = [EEGREFndx,EEGndx]\n i = i+1;\n R_eeg(i,:) = OPTIONS.Channel(k).Loc(:,1)';\n end\n if ~MEG\n flaggrad = [];\n irefsens = [];\n end\n\nelse\n R_eeg = NaN * zeros(size(R_meg1)); % Dummy coordinates\nend\n\n%_________________________________________________________________________________________\n\n\n%Compute Transfer Matrices__________________________________________________________________\n\nBrainStorm.iscalp = IDs(end); % Index of the outermost surface (scalp, supposedly)\n\neeg_answ = '';\nmeg_answ = '';\n\n% Check whether some transfer-matrix files already exist for current study\n\nfn_eeg = sprintf('%s_eegxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\nfn_meg = sprintf('%s_megxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\nif MEG\n test = exist(fn_meg,'file');\nelseif EEG\n test = exist(fn_eeg,'file');\nelse MEG& EEG\n test = exist(fn_eeg,'file') & exist(fn_meg,'file');\nend\n\nif (OPTIONS.BEM.ForceXferComputation | ~test) | OPTIONS.BEM.Interpolative\n\n % Force (re)computation of transfer matrices, even if files exist in current study folder\n\n % if OPTIONS.Verbose, bst_message_window('Computing the BEM Transfer Matrix (this may take a while)....'), end\n\n global nfv\n nfv = bem_xfer(R_eeg,R_meg1,O_meg1,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...\n Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg,Param.Ntess_max,OPTIONS.Verbose,OPTIONS.BEM.checksurf);\n\n if ~isempty(find(flaggrad))\n if OPTIONS.Verbose, bst_message_window({'Gradiometers detected',...\n 'Computing corresponding Gain Matrix. . .'}), end\n\n %fn_meg_2 = fullfile(pwd,[OPTIONS.rooot,'_megxfer_2.mat']);\n fn_meg_2 = sprintf('%s_megxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n bem_xfer(R_eeg,R_meg2,O_meg2,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...\n Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_2,Param.Ntess_max,0,OPTIONS.BEM.checksurf); % Verbose = 0\n if OPTIONS.Verbose, bst_message_window('Gradiometer Channel Gain Matrix is Completed.'), end\n end\n\n if ~isempty(irefsens) % Do the same for reference channels\n %fn_meg_REF = fullfile(pwd,[OPTIONS.rooot,'_megxfer_REF.mat']);\n fn_meg_REF = sprintf('%s_megREFxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n bem_xfer(R_eeg,R_meg_REF,O_meg_REF,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...\n Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_REF,Param.Ntess_max,0,OPTIONS.BEM.checksurf);% Verbose = 0\n\n if ~isempty(find(flaggrad_REF))\n\n if OPTIONS.Verbose, bst_message_window({'MEG Reference Channels detected',...\n 'Computing corresponding Gain Matrix. . .'}), end\n\n %fn_meg_REF2 = fullfile(pwd,[OPTIONS.rooot,'_megxfer_REF2.mat']);\n fn_meg_REF2 = sprintf('%s_megREFxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n\n bem_xfer(R_eeg,R_meg_REF2,O_meg_REF2,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...\n Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_REF2,Param.Ntess_max,0,OPTIONS.BEM.checksurf);% Verbose = 0\n if OPTIONS.Verbose, bst_message_window('MEG Reference Channel Gain Matrix is Completed.'), end\n end\n end\nend\n\n% Computation of TRANSFER MATRIX Completed ___________________________________________________\n\n\n%%%% THIS PART SPECIFIES PARAMETERS USED TO GENERATE THE 3-D GRID %%%%%%%%%%\n\n\nif OPTIONS.BEM.Interpolative%1%~exist(BEMGridFileName,'file')\n\n if OPTIONS.Verbose, bst_message_window('Computing BEM Interpolative Grid. . .'), end\n\n BEMGridFileName = [OPTIONS.rooot,'grid.mat'];\n\n % update tessellated envelope with surfaces possibly modified by\n % BEM_XFER (downsampling, alignment, embedding etc.)\n Vertices = {nfv(:).vertices};\n Faces = {nfv(:).faces};\n gridmaker(Vertices,Faces,BEMGridFileName,OPTIONS.Verbose);\n\n if OPTIONS.Verbose,\n bst_message_window('Computing BEM Interpolative Grid -> DONE'),\n\n % Visualization of surfaces + grid points\n for k = 1:length(Vertices)\n [hf,hs(k),hl] = view_surface('Head envelopes & a subset of BEM interpolative grid points',Faces{k},Vertices{k});\n view(90,0)\n delete(hl)\n end\n camlight\n rotate3d on\n\n set(hs(1),'FaceAlpha',.3,'edgealpha',.3,'edgecolor','none','facecolor','r')\n set(hs(2),'FaceAlpha',.2,'edgealpha',.2,'edgecolor','none','facecolor','g')\n set(hs(3),'FaceAlpha',.1,'edgealpha',.1,'edgecolor','none','facecolor','b')\n\n hold on\n\n load(BEMGridFileName)\n hgrid = scatter3(Rq_bemgrid(1:10:end,1),Rq_bemgrid(1:10:end,2),Rq_bemgrid(1:10:end,3),'.','filled');\n\n end\n\nelse\n\n global GBEM_grid\n\n % Grid points are the locations of the distributed sources\n if isempty(OPTIONS.Cortex) % CBB (SB, 07-May-2004)| Should work also for volumic grid\n errordlg('Please select a cortical grid for computation of BEM vector fields')\n return\n end\n\n try\n load(OPTIONS.Cortex.FileName); % Load tessellation supporting the source locations and orientations\n catch\n Users = get_user_directory;\n load(fullfile(Users.SUBJECTS,OPTIONS.Cortex.FileName)); % Load tessellation supporting the source locations and orientations\n end\n\n BEMGridFileName.Loc = Vertices{OPTIONS.Cortex.iGrid}; clear Vertices\n\n if OPTIONS.ApplyGridOrient % Take cortex normals into account\n ptch = patch('Vertices',BEMGridFileName.Loc','Faces',Faces{OPTIONS.Cortex.iGrid},'Visible','off');\n set(get(ptch,'Parent'),'Visible','off')\n clear Faces\n BEMGridFileName.Orient = get(ptch,'VertexNormals')';\n delete(ptch);\n [nrm,BEMGridFileName.Orient] = colnorm(BEMGridFileName.Orient);\n % Now because some orientations may be ill-set to [0 0 0] with the get(*,'VertexNormals' command)\n % set these orientation to arbitrary [1 1 1]:\n izero = find(nrm == 0);clear nrm\n if ~isempty(izero)\n BEMGridFileName.Orient(:,izero) = repmat([1 1 1]'/norm([1 1 1]),1,length(izero));\n end\n clear izero\n else\n BEMGridFileName.Orient = [];\n end\n\n %if OPTIONS.Verbose, bst_message_window(sprintf('Loading BEM interpolative grid points from %s', BEMGridFileName)), end\n\nend\n\n\n\n% This part computes the gain matrices defined on precomputed grid------------------------------------------------------------\n\n% Assign file names where to store the gain matrices\nif MEG & ~EEG\n bem_xfer_mfname = {fn_meg};\n %BEMGaingridFname = [OPTIONS.rooot,'_meggain_grid.mat'];\n BEMGaingridFname = sprintf('%s_MEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n test = exist(BEMGaingridFname,'file');\nelseif EEG & ~ MEG\n bem_xfer_mfname = {fn_eeg};\n %BEMGaingridFname = [OPTIONS.rooot,'_eeggain_grid.mat'];\n BEMGaingridFname = sprintf('%s_EEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n test = exist(BEMGaingridFname,'file');\nelseif EEG & MEG\n bem_xfer_mfname = {fn_meg,fn_eeg};\n % BEMGaingridFname.MEG = [OPTIONS.rooot,'_meggain_grid.mat'];\n % BEMGaingridFname.EEG = [OPTIONS.rooot,'_eeggain_grid.mat'];\n BEMGaingridFname.MEG = sprintf('%s_MEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n BEMGaingridFname.EEG = sprintf('%s_EEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n test = exist(BEMGaingridFname.MEG,'file') & exist(BEMGaingridFname.EEG,'file');\nend\n\nif 1%OPTIONS.BEM.ForceXferComputation | ~test% Recompute gain matrices when transfer matrices have been recomputed just before\n\n if OPTIONS.Verbose\n if OPTIONS.BEM.Interpolative\n bst_message_window('Computing the BEM gain matrix for interpolative grid. . .'),\n else\n bst_message_window('Computing the BEM gain matrix for source grid. . .'),\n end\n end\n\n t0 = clock;\n\n if OPTIONS.Verbose,\n if MEG & EEG\n bst_message_window('for MEG and EEG channels. . .')\n elseif EEG\n bst_message_window('for EEG channels. . .')\n elseif MEG\n bst_message_window('for MEG channels. . .')\n end\n end\n\n\n if length(bem_xfer_mfname) == 1 % xor(MEG,EEG)\n bem_gain(BEMGridFileName,bem_xfer_mfname{1},Param(1).ISA,BEMGaingridFname, OPTIONS.Verbose);\n else\n % MEG gaingrid matrix\n bem_gain(BEMGridFileName,bem_xfer_mfname{1},Param(1).ISA,BEMGaingridFname.MEG, OPTIONS.Verbose);\n % EEG gaingrid matrix\n bem_gain(BEMGridFileName,bem_xfer_mfname{2},Param(1).ISA,BEMGaingridFname.EEG, OPTIONS.Verbose);\n end\n\n if OPTIONS.Verbose, bst_message_window('-> DONE'), end\n\n if ~isempty(find(flaggrad)) % Compute forward model on the second set of magnetometers from the gradiometers array\n\n bem_xfer_mfname = sprintf('%s_megxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n bem_gaingrid_mfname_2 = sprintf('%s_MEGGainGrid2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n\n if OPTIONS.Verbose, bst_message_window('MEG - completing gradiometers. . .'), end\n\n bem_gain(BEMGridFileName,bem_xfer_mfname,Param(1).ISA,bem_gaingrid_mfname_2,OPTIONS.Verbose);\n\n if OPTIONS.Verbose, bst_message_window('-> DONE'), end\n\n if MEG & EEG\n G1 = load(BEMGaingridFname.MEG);\n else\n G1 = load(BEMGaingridFname);\n end\n G2 = load(bem_gaingrid_mfname_2);\n % Apply respective weights within the gradiodmeters\n meg_chans = [OPTIONS.Channel(MEGndx(find(flaggrad))).Weight];\n w1 = meg_chans(1:2:end);\n w2 = meg_chans(2:2:end);\n\n G1.GBEM_grid(find(flaggrad),:) = w1'*ones(1,size(G1.GBEM_grid,2)).*G1.GBEM_grid(find(flaggrad),:)...\n + w2' * ones(1,size(G1.GBEM_grid,2)).*G2.GBEM_grid(find(flaggrad),:);\n clear G2\n\n % is there special reference channel considerations?\n if ~isempty(irefsens)\n\n % Forward model on all reference sensors\n bem_xfer_mfname_REF = sprintf('%s_megREFxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n bem_gaingrid_mfname_REF = sprintf('%s_MEGGainGrid_REF_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n\n if OPTIONS.Verbose, bst_message_window('MEG reference channels. . .'), end\n bem_gain(BEMGridFileName,bem_xfer_mfname_REF,Param(1).ISA,bem_gaingrid_mfname_REF,OPTIONS.Verbose);\n if OPTIONS.Verbose, bst_message_window('-> DONE'), end\n\n if ~isempty(find(flaggrad_REF)) % Gradiometers are present in reference channels\n\n bem_xfer_mfname_REF2 = sprintf('%s_megREFxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n bem_gaingrid_mfname_REF2 = sprintf('%s_MEGGainGrid2_REF_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n\n if OPTIONS.Verbose, bst_message_window('MEG reference channels / completing gradiometers. . .'), end\n\n bem_gain(BEMGridFileName,bem_xfer_mfname_REF2,Param(1).ISA,bem_gaingrid_mfname_REF2,OPTIONS.Verbose);\n\n if OPTIONS.Verbose, bst_message_window('-> DONE'), end\n\n GR = load(bem_gaingrid_mfname_REF);\n GR2 = load(bem_gaingrid_mfname_REF2);\n\n meg_chans = [OPTIONS.Channel(irefsens(find(flaggrad_REF))).Weight];\n w1 = meg_chans(1:2:end);\n w2 = meg_chans(2:2:end);\n\n GR.GBEM_grid(find(flaggrad_REF),:) = w1'*ones(1,size(GR.GBEM_grid,2)).*GR.GBEM_grid(find(flaggrad_REF),:)...\n + w2' * ones(1,size(GR.GBEM_grid,2)).*GR2.GBEM_grid(find(flaggrad_REF),:);\n\n %GR.GBEM_grid(find(flaggrad_REF),:) = GR.GBEM_grid(find(flaggrad_REF),:) - GR2.GBEM_grid(find(flaggrad_REF),:);\n clear GR2;\n end\n\n % Apply nth-order gradient correction on good channels only\n %Weight by the current nth-order correction coefficients\n %G1.GBEM_grid = G1.GBEM_grid - Channel(MEGndx(1)).Gcoef(find(ChannelFlag(irefsens)>0),:)*GR.GBEM_grid;\n\n G1.GBEM_grid = G1.GBEM_grid - OPTIONS.Channel(MEGndx(1)).Comment*GR.GBEM_grid;\n\n end\n\n GBEM_grid = 1e-7*G1.GBEM_grid;\n\n if MEG & EEG\n save(BEMGaingridFname.MEG,'GBEM_grid','-append');\n else\n save(BEMGaingridFname,'GBEM_grid','-append');\n end\n\n end\n\n % Detect EEG reference - if none is specified in the .Comment or Type fields,\n % and if none was passed through OPTIONS.EEGRef\n % -> Apply average-referencing of the potentials by default.\n\n if EEG\n % EEG Reference Channel\n EEGREFndx = good_channel(OPTIONS.Channel,[],'EEG REF');\n\n if MEG & EEG\n load(BEMGaingridFname.EEG,'GBEM_grid')\n else\n load(BEMGaingridFname,'GBEM_grid')\n end\n\n\n if isempty(EEGREFndx)% AVERAGE REF\n GBEM_grid = GBEM_grid - repmat(mean(GBEM_grid),size(GBEM_grid,1),1);\n else\n % GBEM_grid = GBEM_grid(setdiff(EEGndx,EEGREFndx)-EEGndx(1)+1,:) - repmat(GBEM_grid(EEGREFndx-EEGndx(1)+1,:),size(GBEM_grid(setdiff(EEGndx,EEGREFndx)-EEGndx(1)+1,:),1),1);\n GBEM_grid = GBEM_grid(2:end,:) - repmat(GBEM_grid(1,:),length(EEGndx),1); % SB : EEG REF is stored as first sensor in GBEM_grid; see line 2226\n end\n\n if MEG\n save(BEMGaingridFname.EEG,'GBEM_grid','-append')\n else\n save(BEMGaingridFname,'GBEM_grid','-append')\n end\n\n end\n\n\n if MEG & EEG\n meg = load(BEMGaingridFname.MEG,'GBEM_grid');\n eeg = load(BEMGaingridFname.EEG,'GBEM_grid');\n GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2));\n GBEM_grid(MEGndx,:)= meg.GBEM_grid; clear meg\n GBEM_grid(EEGndx,:)= eeg.GBEM_grid; clear eeg\n\n elseif MEG\n\n meg = load(BEMGaingridFname,'GBEM_grid');\n% Changed by Rik (to make it work!)\n% GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2));\n GBEM_grid = zeros(length(OPTIONS.Channel),size(meg.GBEM_grid,2));\n GBEM_grid(MEGndx,:)= meg.GBEM_grid; clear meg\n\n elseif EEG\n\n eeg = load(BEMGaingridFname,'GBEM_grid');\n GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2));\n EEGndx = OPTIONS.EEGndx;\n GBEM_grid(EEGndx,:)= eeg.GBEM_grid; clear eeg\n\n %clear GBEM_grid\n % % Now save the combined MEG/EEG gaingrid matrix in a single file\n % MEGEEG_BEMGaingridFname = strrep(BEMGaingridFname.EEG,'eeg','meg_eeg');\n % Gmeg = load(BEMGaingridFname.MEG,'GBEM_grid');\n % GBEM_grid = NaN * zeros(length(OPTIONS.Channel),size(Gmeg.GBEM_grid,2));\n % GBEM_grid(MEGndx,:) = Gmeg.GBEM_grid; clear Gmeg\n % eeg = load(BEMGaingridFname.EEG);\n %\n % save_fieldnames(eeg,MEGEEG_BEMGaingridFname);\n %\n % GBEM_grid(setdiff(EEGndx,EEGREFndx),:) = eeg.GBEM_grid; clear eeg\n %\n % save(MEGEEG_BEMGaingridFname,'GBEM_grid','-append')\n %\n % BEMGaingridFname = MEGEEG_BEMGaingridFname;\n else\n save(BEMGaingridFname,'GBEM_grid','-append')\n end\n\n telap_meg_interp = etime(clock,t0);\n\n\nend\n\n\n\nfunction g = gterm_constant(r,rq)\n%gterm_constant\n% function g = gterm_constant(r,rq)\n\n% -------- 20-Nov-2002 14:06:02 ------------------------------\n% ---- Automatically Generated Comments Block using auto_comments -----------\n%\n% Alphabetical list of external functions (non-Matlab):\n% toolbox\\rownorm.m\n% ---------- 20-Nov-2002 14:06:02 ------------------------------\n\n\nif size(rq,1) == 1 % Just one dipole\n r_rq= [r(:,1)-rq(1),r(:,2)-rq(2),r(:,3)-rq(3)];\n n = rownorm(r_rq).^3;\n g = r_rq./[n,n,n];\nelse\n g = zeros(size(r,1),3*size(rq,1));\n isrc = 1;\n for k = 1:size(rq,1)\n r_rq= [r(:,1)-rq(k,1),r(:,2)-rq(k,2),r(:,3)-rq(k,3)];\n n = rownorm(r_rq).^3;\n g(:,3*(isrc-1)+1: 3*isrc) = r_rq./[n,n,n];\n isrc = isrc + 1;\n end\n\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_slice_timing.m", "ext": ".m", "path": "spm5-master/spm_config_slice_timing.m", "size": 7569, "source_encoding": "utf_8", "md5": "2c1d50399145c9dff01b929a2de64556", "text": "function opts = spm_config_slice_timing\n% configuration file for slice timing\n%____________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Darren Gitelman\n% $Id: spm_config_slice_timing.m 1032 2007-12-20 14:45:55Z john $\n\n% ---------------------------------------------------------------------\nscans.type = 'files';\nscans.name = 'Session';\nscans.tag = 'scans';\nscans.filter = 'image';\nscans.num = [2 Inf];\nscans.help = {'Select images to acquisition correct.'};\n% ---------------------------------------------------------------------\n\ndata.type = 'repeat';\ndata.name = 'Data';\ndata.values = {scans};\ndata.num = [1 Inf];\ndata.help = {[...\n 'Subjects or sessions. The same parameters specified below will ',...\n 'be applied to all sessions.']};\n\n% ---------------------------------------------------------------------\n\nnslices.type = 'entry';\nnslices.name = 'Number of Slices';\nnslices.tag = 'nslices';\nnslices.strtype = 'n';\nnslices.num = [1 1];\nnslices.help = {'Enter the number of slices'};\n% ---------------------------------------------------------------------\n\nrefslice.type = 'entry';\nrefslice.name = 'Reference Slice';\nrefslice.tag = 'refslice';\nrefslice.strtype = 'n';\nrefslice.num = [1 1];\nrefslice.help = {'Enter the reference slice'};\n% ---------------------------------------------------------------------\n\nTR.type = 'entry';\nTR.name = 'TR';\nTR.tag = 'tr';\nTR.strtype = 'r';\nTR.num = [1 1];\nTR.help = {'Enter the TR in seconds'};\n% ---------------------------------------------------------------------\n\nTA.type = 'entry';\nTA.name = 'TA';\nTA.tag = 'ta';\nTA.strtype = 'e';\nTA.num = [1 1];\nTA.help = {['The TA (in seconds) must be entered by the user. ',...\n 'It is usually calculated as TR-(TR/nslices). You can simply enter ',...\n 'this equation with the variables replaced by appropriate numbers.']};\n\n% ---------------------------------------------------------------------\n\nsliceorder.type = 'entry';\nsliceorder.name = 'Slice order';\nsliceorder.tag = 'so';\nsliceorder.strtype = 'e';\nsliceorder.num = [1 Inf];\nsliceorder.help = {...\n['Enter the slice order. Bottom slice = 1. Sequence types ',...\n 'and examples of code to enter are given below.'],...\n '',...\n 'ascending (first slice=bottom): [1:1:nslices]',...\n '',...\n 'descending (first slice=top): [nslices:-1:1]',...\n '',...\n 'interleaved (middle-top):',...\n ' for k = 1:nslices,',...\n ' round((nslices-k)/2 + (rem((nslices-k),2) * (nslices - 1)/2)) + 1,',...\n ' end',...\n '',...\n 'interleaved (bottom -> up): [1:2:nslices 2:2:nslices]',...\n '',...\n 'interleaved (top -> down): [nslices:-2:1, nslices-1:-2:1]'};\n \n% ---------------------------------------------------------------------\n\nopts.type = 'branch';\nopts.name = 'Slice Timing';\nopts.tag = 'st';\nopts.val = {data,nslices,TR,TA,sliceorder,refslice};\nopts.prog = @slicetiming;\nopts.vfiles = @vfiles;\nopts.modality = {'FMRI'};\nopts.help = {...\n['Correct differences in image acquisition time between slices. '...\n'Slice-time corrected files are prepended with an ''a''.'],...\n'',...\n['Note: The sliceorder arg that specifies slice acquisition order is '...\n'a vector of N numbers, where N is the number of slices per volume. '...\n'Each number refers to the position of a slice within the image file. '...\n'The order of numbers within the vector is the temporal order in which '...\n'those slices were acquired. '...\n'To check the order of slices within an image file, use the SPM Display '...\n'option and move the cross-hairs to a voxel co-ordinate of z=1. This '...\n'corresponds to a point in the first slice of the volume.'],...\n'',...\n['The function corrects differences in slice acquisition times. '...\n'This routine is intended to correct for the staggered order of '...\n'slice acquisition that is used during echo-planar scanning. The '...\n'correction is necessary to make the data on each slice correspond '...\n'to the same point in time. Without correction, the data on one '...\n'slice will represent a point in time as far removed as 1/2 the TR '...\n'from an adjacent slice (in the case of an interleaved sequence).'],...\n'',...\n['This routine \"shifts\" a signal in time to provide an output '...\n'vector that represents the same (continuous) signal sampled '...\n'starting either later or earlier. This is accomplished by a simple '...\n'shift of the phase of the sines that make up the signal. '...\n'Recall that a Fourier transform allows for a representation of any '...\n'signal as the linear combination of sinusoids of different '...\n'frequencies and phases. Effectively, we will add a constant '...\n'to the phase of every frequency, shifting the data in time.'],...\n'',...\n['Shifter - This is the filter by which the signal will be convolved '...\n'to introduce the phase shift. It is constructed explicitly in '...\n'the Fourier domain. In the time domain, it may be described as '...\n'an impulse (delta function) that has been shifted in time the '...\n'amount described by TimeShift. '...\n'The correction works by lagging (shifting forward) the time-series '...\n'data on each slice using sinc-interpolation. This results in each '...\n'time series having the values that would have been obtained had '...\n'the slice been acquired at the same time as the reference slice. '...\n'To make this clear, consider a neural event (and ensuing hemodynamic '...\n'response) that occurs simultaneously on two adjacent slices. Values '...\n'from slice \"A\" are acquired starting at time zero, simultaneous to '...\n'the neural event, while values from slice \"B\" are acquired one '...\n'second later. Without correction, the \"B\" values will describe a '...\n'hemodynamic response that will appear to have began one second '...\n'EARLIER on the \"B\" slice than on slice \"A\". To correct for this, '...\n'the \"B\" values need to be shifted towards the Right, i.e., towards '...\n'the last value.'],...\n'',...\n['This correction assumes that the data are band-limited (i.e. there '...\n'is no meaningful information present in the data at a frequency '...\n'higher than that of the Nyquist). This assumption is support by '...\n'the study of Josephs et al (1997, NeuroImage) that obtained '...\n'event-related data at an effective TR of 166 msecs. No physio-'...\n'logical signal change was present at frequencies higher than our '...\n'typical Nyquist (0.25 HZ).'],...\n'',...\n['Written by Darren Gitelman at Northwestern U., 1998. '...\n'Based (in large part) on ACQCORRECT.PRO from Geoff Aguirre and '...\n'Eric Zarahn at U. Penn.']};\n\n\n% ---------------------------------------------------------------------\n\nfunction slicetiming(varargin)\njob = varargin{1};\nSeq = job.so;\nTR = job.tr;\nTA = job.ta;\nnslices = job.nslices;\nrefslice = job.refslice;\ntiming(2) = TR - TA;\ntiming(1) = TA / (nslices -1);\n\nfor i = 1:length(job.scans)\n P = strvcat(job.scans{i});\n spm_slice_timing(P,Seq,refslice,timing)\nend\nreturn;\n% ---------------------------------------------------------------------\n\n% ---------------------------------------------------------------------\nfunction vf = vfiles(varargin)\njob = varargin{1};\nn = 0;\nfor i=1:numel(job.scans), n = n + numel(job.scans{i}); end;\nvf = cell(n,1);\nn = 1;\nfor i=1:numel(job.scans),\n for j = 1:numel(job.scans{i})\n [pth,nam,ext,num] = spm_fileparts(job.scans{i}{j});\n vf{n} = fullfile(pth,['a', nam, ext, num]);\n n = n+1;\n end\nend;\nreturn;\n% ---------------------------------------------------------------------\n\n% ---------------------------------------------------------------------\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "ctf_read_meg4.m", "ext": ".m", "path": "spm5-master/ctf_read_meg4.m", "size": 14622, "source_encoding": "utf_8", "md5": "999fb8dfe3a3dd39bcb904c6d62c1e79", "text": "function [ctf] = ctf_read_meg4(folder,ctf,CHAN,TIME,TRIALS,COEFS);\n\n% ctf_read_meg4 - read meg4 format data from a CTF .ds folder\n%\n% [ctf] = ctf_read_meg4([folder],[ctf],[CHAN],[TIME],[TRIALS]);\n%\n% This function reads all or select portions of the raw meg data matrix in\n% the .meg4 file within any .ds folder. It may call the ctf_read_res4\n% function to identify the relevant parameters of the dataset.\n%\n% The .meg4 file contains the raw numbers sampled from the electronics. In\n% this function, these raw analog2digial numbers are multiplied by the\n% appropriate sensor gains, which are read from the .res4 file. However,\n% note that the data values returned can be very small (10^-12 Tesla),\n% which may be a problem for some computations.\n%\n% INPUTS\n%\n% If you do not wish to specify an input option, use [], but keep the order\n% of the input options as above. Only specify as many input options as\n% required. With no input options, the function will prompt for a folder,\n% call ctf_read_res4 and then read all of the data matrix.\n%\n% folder - the directory of the .ds data set to read. By\n% default, a gui prompts for the folder.\n%\n% ctf - a struct with setup, sensor and data fields. If the setup field is\n% missing or empty, this function calls ctf_read_res4.\n%\n% CHAN - a integer array of channel numbers to read.\n% eg, [30:35] reads channels 30 to 35. Also\n% If CHAN = 'eeg', read only eeg channels/sensorIndices\n% If CHAN = 'meg', read only meg channels/sensorIndices\n% If CHAN = 'ref', read only reference channels/sensorIndices\n% If CHAN = 'other', read only the other channels/sensorIndices\n% If CHAN = 'megeeg', read meg and eeg channels/sensorIndices\n% If CHAN = 'eegmeg', read eeg and meg channels/sensorIndices\n%\n% TIME - eg. [0 5] - the desired time interval to read, in sec.\n% If TIME = 'all', all data is read (the default)\n%\n% TRIALS - If TRIALS = n, the nth trial will be read.\n% If TRIALS = [3,5,8], reads trials 3,5, and 8 such that\n% ctf.data(:,:,1) = data for trial 3,\n% ctf.data(:,:,2) = data for trial 5, and \n% ctf.data(:,:,3) = data for trial 8.\n% If TRIALS = [3:7], reads trials 3 to 7\n% If TRIALS = 'all', reads all data (the default)\n%\n% OUTPUTS\n%\n% ctf.data - matrix of all the data read, such that data(x,y,z)\n% contains sample point x, channel y and trial z. The\n% input options, CHAN, TIME, TRIALS can be used to \n% select subsections of the .meg4 data matrix\n%\n% ctf.sensor - has the following fields:\n% .names - cell array of sensor names\n% .location - array of sensor locations for plotting\n% .orientation - array of sensor orientations\n%\n% ctf.res4 - has the following fields\n% .file - the .res4 file path and file name\n% .header - the format of the .res4 file\n%\n% ctf.meg4 - has the following fields\n% .file - the .meg4 file path and file name\n% .header - the format of the .meg4 file\n%\n%\n% <>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> %\n% < > % \n% < DISCLAIMER: > %\n% < > %\n% < THIS PROGRAM IS INTENDED FOR RESEARCH PURPOSES ONLY. > %\n% < THIS PROGRAM IS IN NO WAY INTENDED FOR CLINICAL OR > %\n% < OFFICIAL USE. > %\n% < > %\n% <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<> %\n%\n\n\n% $Revision: 253 $ $Date: 2004/08/19 03:17:10 $\n\n% Copyright (C) 2003 Darren L. Weber\n% \n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n% Modified: 11/2003, Darren.Weber_at_radiology.ucsf.edu\n% - modified from NIH code simply to allocate data into\n% one large struct (ctf)\n% - modified channel selection section at the end so\n% that it doesn't try to get orientation information for\n% EEG channels\n% - changed ctf.data into a 3D matrix, rather than a\n% cell array of matrices\n% Modified: 07/2004, Arnaud Delorme, fixed reading time interval\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%-----------------------------------------------\n% ensure we have the data parameters\n\nif ~exist('COEFS','var'),\n COEFS = false;\nend\n\nif ~exist('folder','var'),\n if ~exist('ctf','var'),\n ctf = ctf_folder;\n else\n ctf = ctf_folder([],ctf);\n end\nelse\n if ~exist('ctf','var'),\n ctf = ctf_folder(folder);\n else\n ctf = ctf_folder(folder,ctf);\n end\nend\n\nif ~isfield(ctf,'setup'),\n ctf = ctf_read_res4(ctf.folder,1,COEFS);\nend\n\n\n\n\n%--------------------------------------------------------------\nver = '$Revision: 253 $';\nfprintf('\\nCTF_READ_MEG4 [v %s]\\n',ver(11:15)); tic;\n\n\n%----------------------------------------------------------------\n% open the data file\n\n[folderPath,folderName,folderExt] = fileparts(ctf.folder);\nctf.meg4.file = findmeg4file( ctf.folder );\n[fid,message] = fopen(ctf.meg4.file,'rb','s');\nif fid < 0, error('cannot open .meg4 file'); end\n\n\n%----------------------------------------------------------------\n% Read the header\n\n% The data file consists of a header and the raw samples from the\n% electronics. The header is the 8-byte character sequence: MEG41CP+NULL.\n\nheader_bytes = 8;\n\nctf.meg4.header = char(fread(fid,[1,header_bytes],'char'));\n\n% check the format\nif strmatch('MEG41CP',ctf.meg4.header),\n % OK, we can handle this format\nelse\n msg = sprintf('May not read \"%s\" format correctly',ctf.meg4.header);\n warning(msg);\nend\n\n\n\n\n\n%--------------------------------------------------------------\n% check the function input parameters and assign any defaults\n\nif ~exist('CHAN','var'), CHAN = 'all'; end\nif ~exist('TIME','var'), TIME = 'all'; end\nif ~exist('TRIALS','var'), TRIALS = 'all'; end\n\nif isempty(CHAN), CHAN = 'all'; end\nif isempty(TIME), TIME = 'all'; end\nif isempty(TRIALS), TRIALS = 'all'; end\n\n\nCHAN = ctf_channel_select(ctf,CHAN);\n\n\nswitch num2str(TIME),\n case 'all',\n TIME = ctf.setup.time_sec;\n TIME_index = 1:ctf.setup.number_samples;\n otherwise\n % assume the input is a range of times in sec\n % check the range\n if TIME(1) < ctf.setup.time_sec(1),\n fprintf('...setting TIME(1) = ctf.setup.time_sec(1)\\n');\n TIME(1) = ctf.setup.time_sec(1);\n end\n if TIME(end) > ctf.setup.time_sec(end),\n fprintf('...setting TIME(end) = ctf.setup.time_sec(end)\\n');\n TIME(end) = ctf.setup.time_sec(end);\n end\n % now find the nearest indices into the samples matrix\n TIME_index = intersect(find(ctf.setup.time_sec >= TIME(1)), find(ctf.setup.time_sec <= TIME(end)));\n % TIME_index = interp1(ctf.setup.time_sec,1:ctf.setup.number_samples,TIME,'nearest');\n % now ensure that the TIME array is consistent with ctf.setup.time_sec\n TIME = ctf.setup.time_sec(TIME_index);\nend\nTIME = sort(TIME);\n\n% check the duration\nduration = TIME(end) - TIME(1);\nif duration > ctf.setup.duration_trial,\n fprintf('...TIME input too large for trial\\n');\n fprintf('...setting TIME = %g seconds (ctf.setup.duration_trial)',ctf.setup.duration_trial);\n duration = ctf.setup.duration_trial;\nend\nif duration <= 0,\n fprintf('...TIME(end) - TIME(1) is <= 0, quitting now!\\n');\n return\nend\n\n\n% calculate the number of samples selected\nnumber_samples = round((duration) * ctf.setup.sample_rate) + 1;\n\n\n\nswitch num2str(TRIALS),\n case 'all',\n TRIALS = 1:ctf.setup.number_trials;\n otherwise\n % assume the input is an array of trials\nend\nTRIALS = unique(sort(TRIALS));\n\n\n\n\n%----------------------------------------------------------------\n% Calculate sensor gains\n\nmegIndex = ctf.sensor.index.meg_sens;\nrefIndex = ctf.sensor.index.meg_ref;\neegIndex = ctf.sensor.index.eeg_sens;\notherIndex = ctf.sensor.index.other;\n\nchannel_gain = zeros(1,ctf.setup.number_channels);\n\nchannel_gain(megIndex) = [ctf.sensor.info(megIndex).proper_gain] .* [ctf.sensor.info(megIndex).q_gain];\nchannel_gain(refIndex) = [ctf.sensor.info(refIndex).proper_gain] .* [ctf.sensor.info(refIndex).q_gain];\nchannel_gain(eegIndex) = [ctf.sensor.info(eegIndex).q_gain];\nchannel_gain(otherIndex) = [ctf.sensor.info(otherIndex).q_gain];\n\n\n%-------------------------------------------------------------------------\n% Read trial data from .meg4 file\n\n% The data is stored as a sequence of (signed) 4-byte integers, starting\n% with the first trial and first channel, then the first trial and second\n% channel, etc. The number of channels per trial and the number of samples\n% in every trialchannel block are constant per dataset. The constants are\n% found in the general resources stored in the resource file, see 'The\n% Resource File Format'. The numbers stored in the data file are the raw\n% numbers collected from the electronics. For these numbers to be useful,\n% the various gains, stored in the sensor resources, must be applied.\n\nnumber_trials = length(TRIALS);\nnumber_channels = length(CHAN);\n\nctf.data = zeros(number_samples, number_channels, number_trials);\n\n% Calculate trial byte size\ntrial_bytes = 4 * ctf.setup.number_samples * ctf.setup.number_channels;\n\ntrial_count = 0;\nfor trial = 1:length(TRIALS),\n \n trial_number = TRIALS(trial);\n \n if trial > 1,\n fprintf('\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b');\n end\n fprintf('...reading %4d of %4d trials\\n', trial, ctf.setup.number_trials);\n \n % calculate the byte offset in the file for this trial\n trial_offset = header_bytes + ( trial_bytes * ( trial_number - 1 ) );\n \n for channel = 1:length(CHAN),\n \n channel_number = CHAN(channel);\n \n % calculate the channel offset in the current trial\n channel_offset = 4 * ctf.setup.number_samples * ( channel_number - 1 );\n \n % seek to the trial offset, relative to the beginning of the file\n fseek(fid,trial_offset,-1);\n \n % now seek to the channel offset, in the current trial\n fseek(fid,channel_offset,0);\n \n % read the entire set of samples for this channel\n channel_samples = fread(fid, [ctf.setup.number_samples,1], 'int32');\n \n % extract just the selected time array\n channel_samples = channel_samples(TIME_index);\n \n if channel_gain(channel_number),\n channel_samples2tesla = channel_samples ./ channel_gain(channel_number);\n else\n channel_samples2tesla = channel_samples;\n end\n \n % assign the selected time samples into the ctf.data matrix\n ctf.data(:,channel,trial) = channel_samples2tesla;\n \n end\nend\n\nfclose(fid);\n\n\n\n\n\n\n\n\n\n\n%-------------------------------------------------------------------------\n% assign sensor locations and orientations for selected channels, this\n% section will simplify the data allocated by ctf_read_res4\n\nfprintf('...sorting %d from %d sensors\\n',number_channels, ctf.setup.number_channels);\n\nctf.sensor.location = zeros(3,number_channels);\nctf.sensor.orientation = zeros(3,number_channels);\n\nctf.sensor.label = [];\n\nfor c = 1:length(CHAN),\n \n channel = CHAN(c);\n \n % All channels have a label\n if length(ctf.sensor.info(channel).label) <= 5,\n ctf.sensor.label{1,c} = ctf.sensor.info(channel).label;\n else\n ctf.sensor.label{1,c} = ctf.sensor.info(channel).label(1:5);\n end\n \n % All channels have a location\n \n % EEG channels do not have any orientation\n \n switch ctf.sensor.info(channel).index,\n \n case {ctf.sensor.type.meg_sens, ctf.sensor.type.meg_ref},\n %0=Reference Channels, \n %1=More Reference Channels, \n %5=MEG Channels\n \n % MEG channels are radial gradiometers, so they have an inner (1) and\n % an outer (2) location - it might be better to take the average of\n % their locations\n if ~isempty(ctf.sensor.info(channel).location),\n ctf.sensor.location(:,c) = ctf.sensor.info(channel).location(:,1);\n end\n \n if ~isempty(ctf.sensor.info(channel).orientation),\n ctf.sensor.orientation(:,c) = ctf.sensor.info(channel).orientation(:,1);\n end\n \n case ctf.sensor.type.eeg_sens,\n %9=EEG Channels\n \n if ~isempty(ctf.sensor.info(channel).location),\n ctf.sensor.location(:,c) = ctf.sensor.info(channel).location(:,1);\n end\n \n end\nend\n\n\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% NEED TO CHECK ctf.setup parameters here, to adjust for any changes\n% required by the CHAN, TIME, TRIALS inputs\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% modify the setup parameters so they correspond with the data selected\nctf.setup.number_samples = number_samples;\nctf.setup.number_channels = number_channels;\nctf.setup.number_trials = number_trials;\n\nif ctf.setup.number_samples ~= size(ctf.data,1),\n error('ctf.setup.number_samples ~= size(ctf.data,1)');\nend\nif ctf.setup.number_channels ~= size(ctf.data,2),\n error('ctf.setup.number_channels ~= size(ctf.data,2)');\nend\nif ctf.setup.number_trials ~= size(ctf.data,3),\n error('ctf.setup.number_trials ~= size(ctf.data,3)');\nend\n\n\nt = toc; fprintf('...done (%6.2f sec)\\n\\n',t);\n\nreturn\n\n\n\n% find file name if truncated or with uppercase extension\n% added by Arnaud Delorme June 15, 2004\n% -------------------------------------------------------\nfunction meg4name = findmeg4file( folder )\n\nmeg4name = dir([ folder filesep '*.meg4' ]);\nif isempty(meg4name)\n meg4name = dir([ folder filesep '*.MEG4' ]);\nend;\n\nif isempty(meg4name)\n error('No file with extension .meg4 or .MEG4 in selected folder');\nelse\n meg4name = [ folder filesep meg4name.name ];\nend;\n\nreturn\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_uw_apply.m", "ext": ".m", "path": "spm5-master/spm_uw_apply.m", "size": 15337, "source_encoding": "utf_8", "md5": "9eac00bda2d4c00e4062104e135d045a", "text": "function varargout = spm_uw_apply(ds,flags)\n% Reslices images volume by volume\n% FORMAT spm_uw_apply(ds,[flags])\n% or\n% FORMAT P = spm_uw_apply(ds,[flags])\n%\n% \n% ds - a structure created by spm_uw_estimate.m containing the fields:\n% ds can also be an array of structures, each struct corresponding\n% to one sesssion (it hardly makes sense to try and pool fields across\n% sessions since there will have been a reshimming). In that case each\n% session is unwarped separately, unwarped into the distortion space of\n% the average (default) position of that series, and with the first\n% scan on the series defining the pahse encode direction. After that each\n% scan is transformed into the space of the first scan of the first series.\n% Naturally, there is still only one actual resampling (interpolation).\n% It will be assumed that the same unwarping parameters have been used\n% for all sessions (anything else would be truly daft).\n% \n% .P - Images used when estimating deformation field and/or\n% its derivative w.r.t. modelled factors. Note that this\n% struct-array may contain .mat fields that differ from\n% those you would observe with spm_vol(P(1).fname). This\n% is because spm_uw_estimate has an option to re-estimate\n% the movement parameters. The re-estimated parameters are\n% not written to disc (in the form of .mat files), but rather\n% stored in the P array in the ds struct.\n%\n% .order - Number of basis functions to use for each dimension.\n% If the third dimension is left out, the order for \n% that dimension is calculated to yield a roughly\n% equal spatial cut-off in all directions.\n% Default: [8 8 *]\n% .sfP - Static field supplied by the user. It should be a \n% filename or handle to a voxel-displacement map in\n% the same space as the first EPI image of the time-\n% series. If using the FieldMap toolbox, realignment\n% should (if necessary) have been performed as part of\n% the process of creating the VDM. Note also that the\n% VDM mut be in undistorted space, i.e. if it is\n% calculated from an EPI based field-map sequence\n% it should have been inverted before passing it to\n% spm_uw_estimate. Again, the FieldMap toolbox will\n% do this for you.\n% .regorder - Regularisation of derivative fields is based on the\n% regorder'th (spatial) derivative of the field.\n% Default: 1\n% .lambda - Fudge factor used to decide relative weights of\n% data and regularisation.\n% Default: 1e5\n% .jm - Jacobian Modulation. If set, intensity (Jacobian)\n% deformations are included in the model. If zero,\n% intensity deformations are not considered. \n% .fot - List of indexes for first order terms to model\n% derivatives for. Order of parameters as defined\n% by spm_imatrix. \n% Default: [4 5]\n% .sot - List of second order terms to model second \n% derivatives of. Should be an nx2 matrix where\n% e.g. [4 4; 4 5; 5 5] means that second partial\n% derivatives of rotation around x- and y-axis\n% should be modelled.\n% Default: []\n% .fwhm - FWHM (mm) of smoothing filter applied to images prior\n% to estimation of deformation fields.\n% Default: 6\n% .rem - Re-Estimation of Movement parameters. Set to unity means\n% that movement-parameters should be re-estimated at each\n% iteration.\n% Default: 0\n% .noi - Maximum number of Iterations.\n% Default: 5\n% .exp_round - Point in position space to do Taylor expansion around.\n% 'First', 'Last' or 'Average'.\n% .p0 - Average position vector (three translations in mm\n% and three rotations in degrees) of scans in P.\n% .q - Deviations from mean position vector of modelled\n% effects. Corresponds to deviations (and deviations\n% squared) of a Taylor expansion of deformation fields.\n% .beta - Coeffeicents of DCT basis functions for partial\n% derivatives of deformation fields w.r.t. modelled\n% effects. Scaled such that resulting deformation \n% fields have units mm^-1 or deg^-1 (and squares \n% thereof).\n% .SS - Sum of squared errors for each iteration.\n%\n% flags - a structure containing various options. The fields are:\n%\n% mask - mask output images (1 for yes, 0 for no)\n% To avoid artifactual movement-related variance the realigned\n% set of images can be internally masked, within the set (i.e.\n% if any image has a zero value at a voxel than all images have\n% zero values at that voxel). Zero values occur when regions\n% 'outside' the image are moved 'inside' the image during\n% realignment.\n%\n% mean - write mean image\n% The average of all the realigned scans is written to\n% mean*.img.\n%\n% interp - the interpolation method (see e.g. spm_bsplins.m).\n%\n% which - Values of 0 or 1 are allowed.\n% 0 - don't create any resliced images.\n% Useful if you only want a mean resliced image.\n% 1 - reslice all the images.\n%\n% udc - Values 1 or 2 are allowed\n% 1 - Do only unwarping (not correcting \n% for changing sampling density).\n% 2 - Do both unwarping and Jacobian correction.\n%\n%\n% The spatially realigned images are written to the orginal\n% subdirectory with the same filename but prefixed with an 'u'.\n% They are all aligned with the first.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Jesper Andersson\n% $Id: spm_uw_apply.m 1746 2008-05-28 17:43:42Z guillaume $\n\ntiny = 5e-2;\n\nglobal defaults\n\ndef_flags = struct('mask', 1,...\n 'mean', 1,...\n 'interp', 4,...\n 'wrap', [0 1 0],...\n 'which', 1,...\n 'udc', 1);\n\ndefnames = fieldnames(def_flags);\n\n%\n% Replace hardcoded defaults with spm_defaults\n% when exist and defined.\n%\nif exist('defaults','var') && isfield(defaults,'realign') && isfield(defaults.realign,'write')\n wd = defaults.realign.write;\n if isfield(wd,'interp'), def_flags.interp = wd.interp; end\n if isfield(wd,'wrap'), def_flags.wrap = wd.wrap; end\n if isfield(wd,'mask'), def_flags.mask = wd.mask; end\nend\n\nif nargin < 1 || isempty(ds)\n ds = load(spm_select(1,'.*uw\\.mat$','Select Unwarp result file'),'ds');\n ds = ds.ds;\nend\n\n%\n% Default to using Jacobian modulation for the reslicing if it was\n% used during the estimation phase.\n%\nif ds(1).jm ~= 0\n def_flags.udc = 2;\nend\n\n%\n% Replace defaults with user supplied values for all fields\n% defined by user. Also, warn user of any invalid fields,\n% probably reflecting misspellings.\n%\nif nargin < 2 || isempty(flags)\n flags = def_flags;\nend\nfor i=1:length(defnames)\n if ~isfield(flags,defnames{i})\n %flags = setfield(flags,defnames{i},getfield(def_flags,defnames{i}));\n flags.(defnames{i}) = def_flags.(defnames{i});\n end\nend\nflagnames = fieldnames(flags);\nfor i=1:length(flagnames)\n if ~isfield(def_flags,flagnames{i})\n warning('Warning, unknown flag field %s',flagnames{i});\n end\nend\n\nntot = 0;\nfor i=1:length(ds)\n ntot = ntot + length(ds(i).P);\nend\n\nhold = [repmat(flags.interp,1,3) flags.wrap];\n\nlinfun = inline('fprintf(''%-60s%s'', x,repmat(sprintf(''\\b''),1,60))');\n\n%\n% Create empty sfield for all structs.\n%\n[ds.sfield] = deal([]);\n\n%\n% Make space for output P-structs if required\n%\nif nargout > 0\n oP = cell(length(ds),1);\nend\n\n%\n% First, create mask if so required.\n%\n\nif flags.mask || flags.mean,\n linfun('Computing mask..');\n spm_progress_bar('Init',ntot,'Computing available voxels',...\n 'volumes completed');\n [x,y,z] = ndgrid(1:ds(1).P(1).dim(1),1:ds(1).P(1).dim(2),1:ds(1).P(1).dim(3));\n xyz = [x(:) y(:) z(:) ones(prod(ds(1).P(1).dim(1:3)),1)]; clear x y z;\n if flags.mean\n Count = zeros(prod(ds(1).P(1).dim(1:3)),1);\n Integral = zeros(prod(ds(1).P(1).dim(1:3)),1);\n end\n\n % if flags.mask \n msk = zeros(prod(ds(1).P(1).dim(1:3)),1); \n % end\n\n tv = 1;\n for s=1:length(ds)\n def_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2));\n Bx = spm_dctmtx(ds(s).P(1).dim(1),ds(s).order(1));\n By = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2));\n Bz = spm_dctmtx(ds(s).P(1).dim(3),ds(s).order(3));\n if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP)\n T = ds(s).sfP.mat\\ds(1).P(1).mat;\n txyz = xyz * T';\n c = spm_bsplinc(ds(s).sfP,ds(s).hold);\n ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold);\n ds(s).sfield = ds(s).sfield(:);\n clear c txyz;\n end \n for i=1:size(ds(s).beta,2)\n def_array(:,i) = spm_get_def(Bx,By,Bz,ds(s).beta(:,i));\n end\n sess_msk = zeros(prod(ds(1).P(1).dim(1:3)),1);\n for i = 1:numel(ds(s).P)\n T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;\n txyz = xyz * T';\n txyz(:,2) = txyz(:,2) + spm_get_image_def(ds(s).P(i),ds(s),def_array);\n tmp = false(size(txyz,1),1);\n if ~flags.wrap(1), tmp = tmp | txyz(:,1) < (1-tiny) | txyz(:,1) > (ds(s).P(i).dim(1)+tiny); end\n if ~flags.wrap(2), tmp = tmp | txyz(:,2) < (1-tiny) | txyz(:,2) > (ds(s).P(i).dim(2)+tiny); end\n if ~flags.wrap(3), tmp = tmp | txyz(:,3) < (1-tiny) | txyz(:,3) > (ds(s).P(i).dim(3)+tiny); end\n sess_msk = sess_msk + real(tmp);\n spm_progress_bar('Set',tv);\n tv = tv+1;\n end\n msk = msk + sess_msk;\n if flags.mean, Count = Count + repmat(length(ds(s).P),prod(ds(s).P(1).dim(1:3)),1) - sess_msk; end % Changed 23/3-05\n \n %\n % Include static field in estmation of mask.\n %\n if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP)\n T = inv(ds(s).sfP.mat) * ds(1).P(1).mat;\n txyz = xyz * T';\n tmp = false(size(txyz,1),1);\n if ~flags.wrap(1), tmp = tmp | txyz(:,1) < (1-tiny) | txyz(:,1) > (ds(s).sfP.dim(1)+tiny); end\n if ~flags.wrap(2), tmp = tmp | txyz(:,2) < (1-tiny) | txyz(:,2) > (ds(s).sfP.dim(2)+tiny); end\n if ~flags.wrap(3), tmp = tmp | txyz(:,3) < (1-tiny) | txyz(:,3) > (ds(s).sfP.dim(3)+tiny); end\n msk = msk + real(tmp);\n end\n if isfield(ds(s),'sfield') && ~isempty(ds(s).sfield)\n ds(s).sfield = [];\n end\n end\n if flags.mask, msk = find(msk ~= 0); end\nend\n\nlinfun('Reslicing images..');\nspm_progress_bar('Init',ntot,'Reslicing','volumes completed');\n\njP = ds(1).P(1);\njP = rmfield(jP,{'fname','descrip','n','private'});\njP.dim = jP.dim(1:3);\njP.dt = [spm_type('float64'), spm_platform('bigend')];\njP.pinfo = [1 0]';\ntv = 1;\nfor s=1:length(ds)\n def_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2));\n Bx = spm_dctmtx(ds(s).P(1).dim(1),ds(s).order(1));\n By = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2));\n Bz = spm_dctmtx(ds(s).P(1).dim(3),ds(s).order(3));\n if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP)\n T = ds(s).sfP.mat\\ds(1).P(1).mat;\n txyz = xyz * T';\n c = spm_bsplinc(ds(s).sfP,ds(s).hold);\n ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold);\n ds(s).sfield = ds(s).sfield(:);\n clear c txyz;\n end \n for i=1:size(ds(s).beta,2)\n def_array(:,i) = spm_get_def(Bx,By,Bz,ds(s).beta(:,i));\n end\n if flags.udc > 1\n ddef_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2));\n dBy = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2),'diff');\n for i=1:size(ds(s).beta,2)\n ddef_array(:,i) = spm_get_def(Bx,dBy,Bz,ds(s).beta(:,i));\n end\n end\n for i = 1:length(ds(s).P)\n linfun(['Reslicing volume ' num2str(tv) '..']);\n %\n % Read undeformed image.\n %\n T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;\n txyz = xyz * T';\n if flags.udc > 1\n [def,jac] = spm_get_image_def(ds(s).P(i),ds(s),def_array,ddef_array);\n else\n def = spm_get_image_def(ds(s).P(i),ds(s),def_array);\n end\n txyz(:,2) = txyz(:,2) + def;\n if flags.udc > 1\n jP.dat = reshape(jac,ds(s).P(i).dim(1:3));\n jtxyz = xyz * T';\n c = spm_bsplinc(jP.dat,hold);\n jac = spm_bsplins(c,jtxyz(:,1),jtxyz(:,2),jtxyz(:,3),hold);\n end \n c = spm_bsplinc(ds(s).P(i),hold);\n ima = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),hold);\n if flags.udc > 1\n ima = ima .* jac;\n end\n %\n % Write it if so required.\n %\n if flags.which\n PO = ds(s).P(i);\n PO.fname = prepend(PO.fname,'u');\n PO.mat = ds(1).P(1).mat;\n PO.descrip = 'spm - undeformed';\n\t ivol = ima; \n if flags.mask\n\t ivol(msk) = NaN;\n end\n ivol = reshape(ivol,PO.dim(1:3));\n PO = spm_create_vol(PO);\n for ii=1:PO.dim(3),\n PO = spm_write_plane(PO,ivol(:,:,ii),ii);\n end;\n\t if nargout > 0\n\t oP{s}(i) = PO;\n\t end\n end\n %\n % Build up mean image if so required.\n %\n if flags.mean\n Integral = Integral + nan2zero(ima);\n end\n spm_progress_bar('Set',tv);\n tv = tv+1;\n end\n if isfield(ds(s),'sfield') && ~isempty(ds(s).sfield)\n ds(s).sfield = [];\n end\nend\n\nif flags.mean\n % Write integral image (16 bit signed)\n %-----------------------------------------------------------\n sw = warning('off','MATLAB:divideByZero');\n Integral = Integral./Count;\n warning(sw);\n PO = ds(1).P(1);\n [pth,nm,xt,vr] = spm_fileparts(deblank(ds(1).P(1).fname));\n PO.fname = fullfile(pth,['meanu' nm xt vr]);\n PO.pinfo = [max(max(max(Integral)))/32767 0 0]';\n PO.descrip = 'spm - mean undeformed image';\n PO.dt = [4 spm_platform('bigend')];\n ivol = reshape(Integral,PO.dim);\n spm_write_vol(PO,ivol);\nend\n\nlinfun(' ');\nspm_figure('Clear','Interactive');\n\nif nargout > 0\n varargout{1} = oP;\nend\n\nreturn;\n\n\n%_______________________________________________________________________\nfunction PO = prepend(PI,pre)\n[pth,nm,xt,vr] = spm_fileparts(deblank(PI));\nPO = fullfile(pth,[pre nm xt vr]);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vo = nan2zero(vi)\nvo = vi;\nvo(~isfinite(vo)) = 0;\nreturn;\n%_______________________________________________________________________\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_ecat.m", "ext": ".m", "path": "spm5-master/spm_config_ecat.m", "size": 2202, "source_encoding": "utf_8", "md5": "0fa0f021012dd7020140f0082d29bff4", "text": "function opts = spm_config_ecat\n% Configuration file for ecat import jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_ecat.m 512 2006-05-05 08:14:50Z volkmar $\n\n%_______________________________________________________________________\n\ndata.type = 'files';\ndata.name = 'ECAT files';\ndata.tag = 'data';\ndata.ufilter = '.*v';\ndata.filter = 'any';\ndata.num = Inf;\ndata.help = {'Select the ECAT files to convert.'};\n\ndtype.type = 'menu';\ndtype.name = 'Data Type';\ndtype.tag = 'dtype';\ndtype.labels = {'UINT8 - unsigned char','INT16 - signed short','INT32 - signed int','FLOAT - single prec. float','DOUBLE - double prec. float'};\ndtype.values = {spm_type('uint8'),spm_type('int16'),spm_type('int32'),spm_type('float32'),spm_type('float64')};\ndtype.val = {spm_type('int16')};\ndtype.help = {[...\n'Data-type of output images. '...\n'Note that the number of bits used determines '...\n'the accuracy, and the abount of disk space needed.']};\n\next.type = 'menu';\next.name = 'NIFTI Type';\next.tag = 'ext';\next.labels = {'.nii only','.img + .hdr'};\next.values = {'.nii','.img'};\next.val = {'.img'};\next.help = {[...\n'Output files can be written as .img + .hdr, ',...\n'or the two can be combined into a .nii file.']};\n\nop1.type = 'branch';\nop1.name = 'Options';\nop1.tag = 'opts';\nop1.val = {ext};\nop1.help = {'Conversion options'};\n\nopts.type = 'branch';\nopts.name = 'ECAT Import';\nopts.tag = 'ecat';\nopts.val = {data,op1};\nopts.prog = @convert_ecat;\nopts.modality = {'PET'};\n%opts.vfiles = @vfiles;\nopts.help = {[...\n'ECAT 7 Conversion. ECAT 7 is the image data format used by the more recent CTI '...\n'PET scanners.']};\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction convert_ecat(job)\nfor i=1:length(job.data),\n spm_ecat2nifti(job.data{i},job.opts);\nend;\nreturn;\n\n%function vf = vfiles(job)\n%vf = cell(size(job.data));\n%for i=1:numel(job.data),\n% [pth,nam,ext,versn] = fileparts(job.data{i});\n% vf{i} = fullfile(pwd,[nam job.opts.ext versn]);\n%end;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_read_netcdf.m", "ext": ".m", "path": "spm5-master/spm_read_netcdf.m", "size": 3729, "source_encoding": "utf_8", "md5": "f97b5b0974ef8ceb2fe48cbf083b73e2", "text": "function cdf = spm_read_netcdf(fname)\n% Read the header information from a NetCDF file into a data structure.\n% FORMAT cdf = spm_read_netcdf(fname)\n% fname - name of NetCDF file\n% cdf - data structure\n%\n% See: http://www.unidata.ucar.edu/packages/netcdf/\n% _______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_read_netcdf.m 112 2005-05-04 18:20:52Z john $\n\n\ndsiz = [1 1 2 4 4 8];\nfp=fopen(fname,'r','ieee-be');\nif fp==-1,\n\tcdf = [];\n\treturn;\nend;\n\n% Return null if not a CDF file.\n%-----------------------------------------------------------------------\nmgc = fread(fp,4,'uchar')';\nif ~all(['CDF' 1] == mgc),\n\tcdf = [];\n\tfclose(fp);\n\treturn;\nend\n\n% I've no idea what this is for\nnumrecs = fread(fp,1,'uint32');\n\ncdf = struct('numrecs',numrecs,'dim_array',[], 'gatt_array',[], 'var_array', []);\n\ndt = fread(fp,1,'uint32');\nif dt == 10,\n\t% Dimensions\n\tnelem = fread(fp,1,'uint32');\n\tfor j=1:nelem,\n\t\tstr = readname(fp);\n\t\tdim_length = fread(fp,1,'uint32');\n\t\tcdf.dim_array(j).name = str;\n\t\tcdf.dim_array(j).dim_length = dim_length;\n\tend;\n\tdt = fread(fp,1,'uint32');\nend\n\nwhile ~dt, dt = fread(fp,1,'uint32'); end;\n\nif dt == 12,\n\t% Attributes\n\tnelem = fread(fp,1,'uint32');\n\tfor j=1:nelem,\n\t\tstr = readname(fp);\n\t\tnc_type= fread(fp,1,'uint32');\n\t\tnnelem = fread(fp,1,'uint32');\n\t\tval = fread(fp,nnelem,dtypestr(nc_type));\n\t\tif nc_type == 2, val = deblank([val' ' ']); end\n\t\tpadding= fread(fp,ceil(nnelem*dsiz(nc_type)/4)*4-nnelem*dsiz(nc_type),'uchar');\n\t\tcdf.gatt_array(j).name = str;\n\t\tcdf.gatt_array(j).nc_type = nc_type;\n\t\tcdf.gatt_array(j).val = val;\n\tend;\n\tdt = fread(fp,1,'uint32');\nend\n\nwhile ~dt, dt = fread(fp,1,'uint32'); end;\n\nif dt == 11,\n\t% Variables\n\tnelem = fread(fp,1,'uint32');\n\tfor j=1:nelem,\n\t\tstr = readname(fp);\n\t\tnnelem = fread(fp,1,'uint32');\n\t\tval = fread(fp,nnelem,'uint32');\n\t\tcdf.var_array(j).name = str;\n\t\tcdf.var_array(j).dimid = val+1;\n\t\tcdf.var_array(j).nc_type = 0;\n\t\tcdf.var_array(j).vsize = 0;\n\t\tcdf.var_array(j).begin = 0;\n\t\tdt0 = fread(fp,1,'uint32');\n\t\tif dt0 == 12,\n\t\t\tnelem0 = fread(fp,1,'uint32');\n\t\t\tfor jj=1:nelem0,\n\t\t\t\tstr = readname(fp);\n\t\t\t\tnc_type= fread(fp,1,'uint32');\n\t\t\t\tnnelem = fread(fp,1,'uint32');\n\t\t\t\tval = fread(fp,nnelem,dtypestr(nc_type));\n\t\t\t\tif nc_type == 2, val = deblank([val' ' ']); end\n\t\t\t\tpadding= fread(fp,...\n\t\t\t\t\tceil(nnelem*dsiz(nc_type)/4)*4-nnelem*dsiz(nc_type),'uchar');\n\t\t\t\tcdf.var_array(j).vatt_array(jj).name = str;\n\t\t\t\tcdf.var_array(j).vatt_array(jj).nc_type = nc_type;\n\t\t\t\tcdf.var_array(j).vatt_array(jj).val = val;\n\t\t\tend;\n\t\t\tdt0 = fread(fp,1,'uint32');\n\t\tend;\n\t\tcdf.var_array(j).nc_type = dt0;\n\t\tcdf.var_array(j).vsize = fread(fp,1,'uint32');\n\t\tcdf.var_array(j).begin = fread(fp,1,'uint32');\n\tend;\n\tdt = fread(fp,1,'uint32');\nend;\n\nfclose(fp);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction str = dtypestr(i)\n% Returns a string appropriate for reading or writing the CDF data-type.\ntypes = char('uint8','uint8','int16','int32','float32','float64');\nstr = deblank(types(i,:));\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction name = readname(fp)\n% Extracts a name from a CDF file pointed to at the right location by\n% fp.\nstlen = fread(fp,1,'uint32');\nname = deblank([fread(fp,stlen,'uchar')' ' ']);\npadding= fread(fp,ceil(stlen/4)*4-stlen,'uchar');\nreturn;\n%_______________________________________________________________________\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_figure.m", "ext": ".m", "path": "spm5-master/spm_figure.m", "size": 30162, "source_encoding": "utf_8", "md5": "12f9a21067b2333626a8f244f5655211", "text": "function varargout=spm_figure(varargin)\n% Setup and callback functions for Graphics window\n% FORMAT varargout=spm_figure(varargin)\n% - An embedded callback, multi-function function\n% - For detailed programmers comments, see format specifications\n% in main body of code\n%_______________________________________________________________________\n%\n% spm_figure creates and manages the 'Graphics' window. This window and\n% these facilities may be used independently of SPM, and any number of\n% Graphics windows my be used within the same MatLab session. (Though\n% only one SPM 'Graphics' 'Tag'ed window is permitted.\n%\n% The Graphics window is provided with a menu bar at the top that\n% facilitates editing and printing of the current graphic display,\n% enabling interactive editing of graphic output prior to printing\n% (e.g. selection of color maps, deleting, moving and editing graphics\n% objects or adding text). (This menu is also provided as a figure\n% background \"ContextMenu\" - right-clicking on the figure background\n% should bring up the menu.)\n%\n% Print: Graphics windows with multi-page axes are printed page by page.\n%\n% Clear: Clears the Graphics window. If in SPM usage (figure 'Tag'ed as\n% 'Graphics') then all SPM windows are cleared and reset.\n%\n% Colormap options:\n% * gray, hot, pink: Sets the colormap to its default values and loads\n% either a grayscale, 'hot metal' or color map.\n% * gray-hot, etc: Creates a 'split' colormap {128 x 3 matrix}.\n% The lower half is a gray scale and the upper half\n% is 'hot metal' or 'pink'. This color map is used for\n% \t viewing 'rendered' SPMs on a PET, MRI or other background images\n%\n% Colormap effects:\n% * Invert: Inverts (flips) the current color map.\n% * Brighten and Darken: Brighten and Darken the current colourmap\n% \t using the MatLab BRIGHTEN command, with beta's of +0.2 and -0.2\n% \t respectively.\n%\n% Editing: Right button ('alt' button) cancels operations\n% * Cut : Deletes the graphics object next selected (if deletable)\n% Select with middle mouse button to delete blocks of text,\n% or to delete individual elements from a plot.\n% * Move : To re-position a text, uicontrol or axis object using a\n% 'drag and drop' implementation (i.e. depress - move - release)\n% Using the middle 'extend' mouse button on a text object moves\n% the axes containing the text - i.e. blocks of text.\n% * Size : Re-sizes the text, uicontrol or axis object next selected\n% {left button - decrease, middle button - increase} by a factor\n% of 1.24 (or increase/decrease FontSize by 2 dpi)\n% * Text : Creates an editable text widget that produces a text object as\n% its CallBack.\n% The text object is provided with a ContextMenu, obtained by\n% right-clicking ('alt') on the text, allowing text attributes\n% to be changed. Alternatively, the edit facilities on the window\n% menu bar or ContextMenu can be used.\n% * Edit : To edit text, select a text object with the circle cursor,\n% and edit the text in the editable text widget that appears.\n% A middle 'extend' mouse click places a context menu on the text\n% object, facilitating easy modification of text atributes.\n%\n% For SPM usage, the figure should be 'Tag'ed as 'Graphics'.\n%\n% For SPM power users, and programmers, spm_figure provides utility\n% routines for using the SPM graphics interface. Of particular use are\n% the GetWin, FindWin and Clear functions See the embedded callback\n% reference in the main body of spm_figure, below the help text.\n%\n% See also: spm_print, spm_clf\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Andrew Holmes\n% $Id: spm_figure.m 902 2007-08-30 09:29:29Z volkmar $\n\n\n%=======================================================================\n% - FORMAT specifications for embedded CallBack functions\n%=======================================================================\n%( This is a multi function function, the first argument is an action )\n%( string, specifying the particular action function to take. Recall )\n%( MatLab's command-function duality: `spm_figure Create` is )\n%( equivalent to `spm_figure('Create')`. )\n%\n% FORMAT F = spm_figure\n% [ShortCut] Defaults to Action 'Create'\n%\n% FORMAT F = spm_figure(F) - numeric F\n% [ShortCut] Defaults to spm_figure('CreateBar',F)\n%\n% FORMAT F = spm_figure('Create',Tag,Name,Visible)\n% Create a full length WhiteBg figure 'Tag'ed Tag (if specified),\n% with a ToolBar and background context menu.\n% Equivalent to spm_figure('CreateWin','Tag') and spm_figure('CreateBar')\n% Tag\t - 'Tag' string for figure.\n% Name - Name for window\n% Visible - 'on' or 'off'\n% F\t - Figure used\n%\n% FORMAT F = spm_figure('FindWin',F)\n% Finds window with 'Tag' or figure numnber F - returns empty F if not found\n% F\t- (Input) Figure to use [Optional] - 'Tag' string or figure number.\n%\t- Defaults to 'Graphics'\n% F\t- (Output) Figure number (if found) or empty (if not).\n%\n% FORMAT F = spm_figure('GetWin',Tag)\n% Like spm_figure('FindWin',Tag), except that if 'Tag' is 'Graphics' or\n% 'Interactive' and no such 'Tag'ged figure is found, one is created. Further,\n% the \"got\" window is made current.\n% Tag\t- Figure 'Tag' to get, defaults to 'Graphics'\n% F\t- Figure number (if found/created) or empty (if not).\n%\n% FORMAT F = spm_figure('ParentFig',h)\n% Finds window containing the object whose handle is specified\n% h\t- Handle of object whose parent figure is required\n%\t- If a vector, then first object handle is used\n% F\t- Number or parent figure\n%\n% FORMAT spm_figure('Clear',F,Tags)\n% Clears figure, leaving ToolBar (& other objects with invisible handles)\n% Optional third argument specifies 'Tag's of objects to delete.\n% If figure F is 'Tag'ged 'Interactive' (SPM usage), then the window\n% name and pointer are reset.\n% F\t- 'Tag' string or figure number of figure to clear, defaults to gcf\n% Tags - 'Tag's (string matrix or cell array of strings) of objects to delete\n% *regardless* of 'HandleVisibility'. Only these objects are deleted.\n% '!all' denotes all objects\n%\n%\n% FORMAT spm_figure('Print',F)\n% F\t- [Optional] Figure to print. ('Tag' or figure number)\n%\t Defaults to figure 'Tag'ed as 'Graphics'.\n%\t If none found, uses CurrentFigure if avaliable.\n% If objects 'Tag'ed 'NextPage' and 'PrevPage' are found, then the\n% pages are shown and printed in order. In breif, pages are held as\n% seperate axes, with ony one 'Visible' at any one time. The handles of\n% the \"page\" axes are stored in the 'UserData' of the 'NextPage'\n% object, while the 'PrevPage' object holds the current page number.\n% See spm_help('!Disp') for details on setting up paging axes.\n%\n% FORMAT [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',hPage)\n% SPM pagination function: Makes objects with handles hPage paginated\n% Creates pagination buttons if necessary.\n% hPage\t - Handles of objects to stick to this page\n% hNextPage, hPrevPage, hPageNo - Handles of pagination controls\n%\n% FORMAT spm_figure('TurnPage',move,F)\n% SPM pagination function: Turn to specified page\n%\n% FORMAT spm_figure('DeletePageControls',F)\n% SPM pagination function: Deletes page controls\n% F\t- [Optional] Figure in which to attempt to turn the page\n% Defaults to 'Graphics' 'Tag'ged window\n%\n% FORMAT n = spm_figure('#page')\n% Returns the current page number.\n%\n% FORMAT spm_figure('WaterMark',F,str,Tag,Angle,Perm)\n% Adds watermark to figure windows.\n% F\t- Figure for watermark. Defaults to gcf\n% str - Watermark string. Defaults (missing or empty) to SPM\n% Tag - Tag for watermark axes. Defaults to ''\n% Angle - Angle for watermark. Defaults to -45\n% Perm - If specified, then watermark is permanent (HandleVisibility 'off')\n%\n% FORMAT F = spm_figure('CreateWin',Tag,Name,Visible)\n% Creates a full length WhiteBg figure 'Tag'ged Tag (if specified).\n% F\t - Figure created\n% Tag\t - Tag for window\n% Name - Name for window\n% Visible - 'on' or 'off'\n%\n% FORMAT WS = spm_figure('GetWinScale')\n% Returns ratios of current display dimensions to that of a 1152 x 900\n% Sun display. WS=[Xratio,Yratio,Xratio,Yratio]. Used for scaling other\n% GUI elements.\n% (Function duplicated in spm.m, repeated to reduce inter-dependencies.)\n%\n% FORMAT FS = spm_figure('FontSizes',FS)\n% Returns fontsizes FS scaled for the current display.\n% FS - (vector of) Font sizes to scale\n% [default [08,09,11,13,14,6:36]]\n%\n% FORMAT spm_figure('CreateBar',F)\n% Creates toolbar in figure F (defaults to gcf). F can be a 'Tag'\n% If the figure is 'Tag'ed as 'Graphics' (SPM usage), then the Print button\n% callback is set to attempt to clear an 'Interactive' figure too.\n%\n% FORMAT spm_figure('ColorMap')\n% Callback for \"ColorMap\" buttons\n%\n% FORMAT h = spm_figure('GraphicsHandle',F)\n% GUI choose object for handle identification. LeftMouse 'normal' returns\n% handle, MiddleMouse 'extend' returns parents handle, RightMouse 'alt' cancels.\n% F - figure to do a GUI \"handle ID\" in [Default gcbf]\n%_______________________________________________________________________\n\n\n%-Condition arguments\n%-----------------------------------------------------------------------\nif (nargin==0), Action = 'Create'; else Action = varargin{1}; end\n\nswitch lower(Action), case 'create'\n%=======================================================================\n% F = spm_figure('Create',Tag,Name,Visible)\n%-Condition arguments\nif nargin<4, Visible='on'; else Visible=varargin{4}; end\nif nargin<3, Name=''; else, Name=varargin{3}; end\nif nargin<2, Tag=''; else Tag=varargin{2}; end\n\nF = spm_figure('CreateWin',Tag,Name,Visible);\nspm_figure('CreateBar',F);\nspm_figure('FigContextMenu',F);\nvarargout = {F};\n\n\ncase 'findwin'\n%=======================================================================\n% F=spm_figure('FindWin',F)\n% F=spm_figure('FindWin',Tag)\n%-Find window: Find window with FigureNumber# / 'Tag' attribute\n%-Returns empty if window cannot be found - deletes multiple tagged figs.\n\nif nargin<2, F='Graphics'; else F=varargin{2}; end\n\nif isempty(F)\n\t% Leave F empty\nelseif ischar(F)\n\t% Finds Graphics window with 'Tag' string - delete multiples\n\tTag=F;\n\tF = findobj(get(0,'Children'),'Flat','Tag',Tag);\n\tif length(F) > 1\n\t\t% Multiple Graphics windows - close all but most recent\n\t\tclose(F(2:end))\n\t\tF = F(1);\n\tend\nelse\n\t% F is supposed to be a figure number - check it\n\tif ~any(F==get(0,'Children')), F=[]; end\nend\nvarargout = {F};\n\ncase 'getwin'\n%=======================================================================\n% F=spm_figure('GetWin',Tag)\n\nif nargin<2, Tag='Graphics'; else Tag=varargin{2}; end\nF = spm_figure('FindWin',Tag);\n\nif isempty(F)\n\tif ischar(Tag)\n\t\tswitch Tag\n \n case 'Graphics'\n\t\t\tF = spm_figure('Create','Graphics','Graphics');\n case 'DEM'\n\t\t\tF = spm_figure('Create','DEM','Dynamic Expectation Maximisation');\n case 'DFP'\n\t\t\tF = spm_figure('Create','DFP','Variational filtering');\n case 'SI'\n\t\t\tF = spm_figure('Create','SI','System Identification');\n\t\tcase 'Interactive'\n\t\t\tF = spm('CreateIntWin');\n\t\tend\n\tend\nelse\n\tset(0,'CurrentFigure',F);\nend\nvarargout = {F};\n\ncase 'parentfig'\n%=======================================================================\n% F=spm_figure('ParentFig',h)\nif nargin<2, error('No object specified'), else h=varargin{2}; end\nF = get(h(1),'Parent');\nwhile ~strcmp(get(F,'Type'),'figure'), F=get(F,'Parent'); end\nvarargout = {F};\n\n\ncase 'clear'\n%=======================================================================\n% spm_figure('Clear',F,Tags)\n\n%-Sort out arguments\n%-----------------------------------------------------------------------\nif nargin<3, Tags=[]; else Tags=varargin{3}; end\nif nargin<2, F=get(0,'CurrentFigure'); else F=varargin{2}; end\nF = spm_figure('FindWin',F);\nif isempty(F), return, end\n\n%-Clear figure\n%-----------------------------------------------------------------------\nif isempty(Tags)\n\t%-Clear figure of objects with 'HandleVisibility' 'on'\n\tpos = get(F,'Position');\n\tdelete(findobj(get(F,'Children'),'flat','HandleVisibility','on'));\n\tdrawnow\n\tset(F,'Position',pos);\n\n\t%-Reset figures callback functions\n\tset(F,'KeyPressFcn','',...\n\t\t'WindowButtonDownFcn','',...\n\t\t'WindowButtonMotionFcn','',...\n\t\t'WindowButtonUpFcn','')\n\t%-If this is the 'Interactive' window, reset name & UserData\n\tif strcmp(get(F,'Tag'),'Interactive')\n\t\tset(F,'Name','','UserData',[]), end\nelse\n\t%-Clear specified objects from figure\n\tcSHH = get(0,'ShowHiddenHandles');\n\tset(0,'ShowHiddenHandles','on')\n\tif ischar(Tags); Tags=cellstr(Tags); end\n\tif any(strcmp(Tags(:),'!all'))\n\t\tdelete(get(F,'Children'))\n\telse\n\t for tag = Tags(:)'\n\t\tdelete(findobj(get(F,'Children'),'flat','Tag',tag{:}));\n\t end\n\tend\t\n\tset(0,'ShowHiddenHandles',cSHH)\nend\nset(F,'Pointer','Arrow')\nmovegui(F);\n\n\ncase 'print'\n%=======================================================================\n% spm_figure('Print',F,fname)\n\n%-Arguments & defaults\nif nargin<3, fname=''; else fname=varargin{3};end\nif nargin<2, F='Graphics'; else F=varargin{2}; end\n\n%-Find window to print, default to gcf if specified figure not found\n% Return if no figures\nif ~isempty(F), F = spm_figure('FindWin',F); end\nif isempty(F), F = get(0,'CurrentFigure'); end\nif isempty(F), return, end\n\n%-Note current figure, & switch to figure to print\ncF = get(0,'CurrentFigure');\nset(0,'CurrentFigure',F)\n\n%-See if window has paging controls\nhNextPage = findobj(F,'Tag','NextPage');\nhPrevPage = findobj(F,'Tag','PrevPage');\nhPageNo = findobj(F,'Tag','PageNo');\niPaged = ~isempty(hNextPage);\n\n%-Construct print command\n%-----------------------------------------------------------------------\n\n%-Temporarily change all units to normalized prior to printing\n% (Fixes bizzarre problem with stuff jumping around!)\n%-----------------------------------------------------------------------\nH = findobj(get(F,'Children'),'flat','Type','axes');\nif ~isempty(H),\n un = cellstr(get(H,'Units'));\n set(H,'Units','normalized')\nend;\n\n%-Print\n%-----------------------------------------------------------------------\nif ~iPaged\n spm_print(fname)\nelse\n\thPg = get(hNextPage,'UserData');\n\tCpage = get(hPageNo, 'UserData');\n\tnPages = size(hPg,1);\n\n\tset([hNextPage,hPrevPage,hPageNo],'Visible','off')\n\tif Cpage~=1\n\t\tset(hPg{Cpage,1},'Visible','off'), end\n\tfor p = 1:nPages\n\t\tset(hPg{p,1},'Visible','on');\n\t\tspm_print(fname);\n\t\tset(hPg{p,1},'Visible','off')\n\tend\n\tset(hPg{Cpage,1},'Visible','on')\n\tset([hNextPage,hPrevPage,hPageNo],'Visible','on')\nend\nif ~isempty(H), set(H,{'Units'},un); end;\nset(0,'CurrentFigure',cF)\n\n\ncase 'printto'\n%=======================================================================\n%spm_figure('PrintTo',F)\n\n%-Arguments & defaults\nif nargin<2, F='Graphics'; else F=varargin{2}; end\n\n%-Find window to print, default to gcf if specified figure not found\n% Return if no figures\nF=spm_figure('FindWin',F);\nif isempty(F), F = get(0,'CurrentFigure'); end\nif isempty(F), return, end\n\n[fn pn] = uiputfile('*.ps', 'Print to File');\nif fn == 0\n return;\nend;\n\npsname = fullfile(pn, fn);\nspm_figure('Print',F,psname);\n\ncase 'newpage'\n%=======================================================================\n% [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',h)\nif nargin<2 || isempty(varargin{2}) error('No handles to paginate')\nelse h=varargin{2}(:)'; end\n\n%-Work out which figure we're in\nF = spm_figure('ParentFig',h(1));\n\nhNextPage = findobj(F,'Tag','NextPage');\nhPrevPage = findobj(F,'Tag','PrevPage');\nhPageNo = findobj(F,'Tag','PageNo');\n\n%-Create pagination widgets if required\n%-----------------------------------------------------------------------\nif isempty(hNextPage)\n\tWS = spm('WinScale');\n\tFS = spm('FontSizes');\n SatFig = findobj('Tag','Satellite');\n if ~isempty(SatFig)\n SatFigPos = get(SatFig,'Position');\n hNextPagePos = [SatFigPos(3)-25 15 15 15];\n hPrevPagePos = [SatFigPos(3)-40 15 15 15];\n hPageNo = [SatFigPos(3)-40 5 30 10];\n else\n hNextPagePos = [580 022 015 015].*WS;\n hPrevPagePos = [565 022 015 015].*WS;\n hPageNo = [550 005 060 015].*WS;\n end\n \n\thNextPage = uicontrol(F,'Style','Pushbutton',...\n\t\t'HandleVisibility','on',...\n\t\t'String','>','FontSize',FS(10),...\n\t\t'ToolTipString','next page',...\n\t\t'Callback','spm_figure(''TurnPage'',''+1'',gcbf)',...\n\t\t'Position',hNextPagePos,...\n\t\t'ForegroundColor',[0 0 0],...\n\t\t'Tag','NextPage','UserData',[]);\n\thPrevPage = uicontrol(F,'Style','Pushbutton',...\n\t\t'HandleVisibility','on',...\n\t\t'String','<','FontSize',FS(10),...\n\t\t'ToolTipString','previous page',...\n\t\t'Callback','spm_figure(''TurnPage'',''-1'',gcbf)',...\n\t\t'Position',hPrevPagePos,...\n\t\t'Visible','on',...\n\t\t'Enable','off',...\n\t\t'Tag','PrevPage');\n\thPageNo = uicontrol(F,'Style','Text',...\n\t\t'HandleVisibility','on',...\n\t\t'String','1',...\n\t\t'FontSize',FS(6),...\n\t\t'HorizontalAlignment','center',...\n\t\t'BackgroundColor','w',...\n\t\t'Position',hPageNo,...\n\t\t'Visible','on',...\n\t\t'UserData',1,...\n\t\t'Tag','PageNo','UserData',1);\nend\n\n%-Add handles for this page to UserData of hNextPage\n%-Make handles for this page invisible if PageNo>1\n%-----------------------------------------------------------------------\nmVis = strcmp('on',get(h,'Visible'));\nmHit = strcmp('on',get(h,'HitTest'));\nhPg = get(hNextPage,'UserData');\nif isempty(hPg)\n\thPg = {h(mVis), h(~mVis), h(mHit), h(~mHit)};\nelse\n\thPg = [hPg; {h(mVis), h(~mVis), h(mHit), h(~mHit)}];\n\tset(h(mVis),'Visible','off');\n set(h(mHit),'HitTest','off');\nend\nset(hNextPage,'UserData',hPg)\n\n%-Return handles to pagination controls if requested\nif nargout>0, varargout = {[hNextPage, hPrevPage, hPageNo]}; end\n\n\ncase 'turnpage'\n%=======================================================================\n% spm_figure('TurnPage',move,F)\nif nargin<3, F='Graphics'; else F=varargin{3}; end\nif nargin<2, move=1; else move=varargin{2}; end\nF = spm_figure('FindWin',F);\nif isempty(F), error('No Graphics window'), end\n\nhNextPage = findobj(F,'Tag','NextPage');\nhPrevPage = findobj(F,'Tag','PrevPage');\nhPageNo = findobj(F,'Tag','PageNo');\nif isempty(hNextPage), return, end\nhPg = get(hNextPage,'UserData');\nCpage = get(hPageNo, 'UserData');\nnPages = size(hPg,1);\n\n%-Sort out new page number\nif ischar(move), Npage = Cpage+eval(move); else Npage = move; end\nNpage = max(min(Npage,nPages),1);\n\n%-Make current page invisible, new page visible, set page number string\nset(hPg{Cpage,1},'Visible','off');\nset(hPg{Cpage,3},'HitTest','off');\nset(hPg{Npage,1},'Visible','on');\nset(hPg{Npage,3},'HitTest','on');\nset(hPageNo,'UserData',Npage,'String',sprintf('%d / %d',Npage,nPages))\n\nfor k = 1:length(hPg{Npage,1}) % VG\n\tif strcmp(get(hPg{Npage,1}(k),'Type'),'axes')\n\t\taxes(hPg{Npage,1}(k));\n\tend;\nend;\n\n%-Disable appropriate page turning control if on first/last page (for neatness)\nif Npage==1, set(hPrevPage,'Enable','off')\nelse set(hPrevPage,'Enable','on'), end\nif Npage==nPages, set(hNextPage,'Enable','off')\nelse set(hNextPage,'Enable','on'), end\n\n\n\ncase 'deletepagecontrols'\n%=======================================================================\n% spm_figure('DeletePageControls',F)\nif nargin<2, F='Graphics'; else F=varargin{2}; end\nF = spm_figure('FindWin',F);\nif isempty(F), error('No Graphics window'), end\n\nhNextPage = findobj(F,'Tag','NextPage');\nhPrevPage = findobj(F,'Tag','PrevPage');\nhPageNo = findobj(F,'Tag','PageNo');\n\ndelete([hNextPage hPrevPage hPageNo])\n\n\ncase '#page'\n%=======================================================================\n% n = spm_figure('#Page',F)\nif nargin<2, F='Graphics'; else F=varargin{2}; end\nF = spm_figure('FindWin',F);\nif isempty(F), error('No Graphics window'), end\n\nhNextPage = findobj(F,'Tag','NextPage');\nif isempty(hNextPage)\n\tn = 1;\nelse\n\tn = size(get(hNextPage,'UserData'),1)+1;\nend\nvarargout = {n};\n\n\ncase 'watermark'\n%=======================================================================\n% spm_figure('WaterMark',F,str,Tag,Angle,Perm)\nif nargin<6, HVis='on'; else HVis='off'; end\nif nargin<5, Angle=-45; else Angle=varargin{5}; end\nif nargin<4 || isempty(varargin{4}), Tag = 'WaterMark'; else Tag=varargin{4}; end\nif nargin<3 || isempty(varargin{3}), str = 'SPM'; else str=varargin{3}; end\nif nargin<2, if any(get(0,'Children')), F=gcf; else F=''; end\nelse F=varargin{2}; end\nF = spm_figure('FindWin',F);\nif isempty(F), return, end\n\n%-Specify watermark color from background colour\n%-----------------------------------------------------------------------\nColour = get(F,'Color');\n%-Only mess with grayscale backgrounds\nif ~all(Colour==Colour(1)), return, end\n%-Work out colour - lighter unless grey value > 0.9\nColour = Colour+(2*(Colour(1)<0.9)-1)*0.02;\n\ncF = get(0,'CurrentFigure');\nset(0,'CurrentFigure',F)\nUnits=get(F,'Units');\nset(F,'Units','normalized');\nh = axes('Position',[0.45,0.5,0.1,0.1],...\n\t'Units','normalized',...\n\t'Visible','off',...\n\t'Tag',Tag);\nset(F,'Units',Units)\ntext(0.5,0.5,str,...\n\t'FontSize',spm('FontSize',80),...\n\t'FontWeight','Bold',...\n\t'FontName',spm_platform('Font','times'),...\n\t'Rotation',Angle,...\n\t'HorizontalAlignment','Center',...\n\t'VerticalAlignment','middle',...\n\t'Color',Colour,...\n\t'ButtonDownFcn',[...\n\t\t'if strcmp(get(gcbf,''SelectionType''),''open''),',...\n\t\t\t'delete(get(gcbo,''Parent'')),',...\n\t\t'end'])\nset(h,'HandleVisibility',HVis)\nset(0,'CurrentFigure',cF)\n\n\ncase 'createwin'\n%=======================================================================\n% F=spm_figure('CreateWin',Tag,Name,Visible)\n\n%-Condition arguments\n%-----------------------------------------------------------------------\nif nargin<4 || isempty(varargin{4}), Visible='on'; else Visible=varargin{4}; end\nif nargin<3, Name=''; else Name = varargin{3}; end\nif nargin<2, Tag=''; else Tag = varargin{2}; end\n\nWS = spm('WinScale');\t\t\t\t%-Window scaling factors\nFS = spm('FontSizes');\t\t\t%-Scaled font sizes\nPF = spm_platform('fonts');\t\t\t%-Font names (for this platform)\nRect = spm('WinSize','Graphics','raw').*WS;\t%-Graphics window rectangle\n\nF = figure(...\n\t'Tag',Tag,...\n\t'Position',Rect,...\n\t'Resize','off',...\n\t'Color','w',...\n\t'ColorMap',gray(64),...\n\t'DefaultTextColor','k',...\n\t'DefaultTextInterpreter','none',...\n\t'DefaultTextFontName',PF.helvetica,...\n\t'DefaultTextFontSize',FS(10),...\n\t'DefaultAxesColor','w',...\n\t'DefaultAxesXColor','k',...\n\t'DefaultAxesYColor','k',...\n\t'DefaultAxesZColor','k',...\n\t'DefaultAxesFontName',PF.helvetica,...\n\t'DefaultPatchFaceColor','k',...\n\t'DefaultPatchEdgeColor','k',...\n\t'DefaultSurfaceEdgeColor','k',...\n\t'DefaultLineColor','k',...\n\t'DefaultUicontrolFontName',PF.helvetica,...\n\t'DefaultUicontrolFontSize',FS(10),...\n\t'DefaultUicontrolInterruptible','on',...\n\t'PaperType','A4',...\n\t'PaperUnits','normalized',...\n\t'PaperPosition',[.0726 .0644 .854 .870],...\n\t'InvertHardcopy','off',...\n\t'Renderer','painters',...\n\t'Visible','off',...\n\t'Toolbar','none');\nif ~isempty(Name)\n\tset(F,'Name',sprintf('%s%s: %s',spm('ver'),...\n\t\tspm('GetUser',' (%s)'),Name),'NumberTitle','off')\nend\nset(F,'Visible',Visible)\nvarargout = {F};\n\n\ncase 'getwinscale'\n%=======================================================================\n% WS = spm_figure('GetWinScale')\nwarning('spm_figure(''GetWinScale''... is Grandfathered: use spm(''WinScale''')\nvarargout = {spm('WinScale')};\n\n\ncase 'fontsizes'\n%=======================================================================\n% FS = spm_figure('FontSizes',FS)\nwarning('spm_figure(''FontSizes''... is Grandfathered: use spm(''FontSizes''')\nif nargin<2, FS=[08,09,11,13,14,6:36]; else FS=varargin{2}; end\nvarargout = {round(FS*min(spm('WinScale')))};\n\n\n%=======================================================================\n case 'createbar'\n%=======================================================================\n% spm_figure('CreateBar',F)\nif nargin<2, if any(get(0,'Children')), F=gcf; else F=''; end\nelse F=varargin{2}; end\nF = spm_figure('FindWin',F);\nif isempty(F), return, end\n\ncSHH = get(0,'ShowHiddenHandles');\nset(0,'ShowHiddenHandles','on')\n\nt0 = findobj(get(F,'Children'),'Flat','Label','&Help');\nif isempty(t0), t0 = uimenu( F,'Label','&Help'); end;\n\nset(findobj(t0,'Position',1),'Separator','on');\nuimenu(t0,'Position',1,...\n\t'Label','SPM web',...\n\t'CallBack','web(''http://www.fil.ion.ucl.ac.uk/spm/'');');\nuimenu(t0,'Position',1,...\n\t'Label','SPM help','ForegroundColor',[0 1 0],...\n\t'CallBack','spm_help');\n\nt0=uimenu( F,'Label','Colours','HandleVisibility','off');\nt1=uimenu(t0,'Label','ColorMap');\nuimenu(t1,'Label','Gray', 'CallBack','spm_figure(''ColorMap'',''gray'')');\nuimenu(t1,'Label','Hot', 'CallBack','spm_figure(''ColorMap'',''hot'')');\nuimenu(t1,'Label','Pink', 'CallBack','spm_figure(''ColorMap'',''pink'')');\nuimenu(t1,'Label','Jet','CallBack','spm_figure(''ColorMap'',''jet'')');\nuimenu(t1,'Label','Gray-Hot', 'CallBack','spm_figure(''ColorMap'',''gray-hot'')');\nuimenu(t1,'Label','Gray-Cool','CallBack','spm_figure(''ColorMap'',''gray-cool'')');\nuimenu(t1,'Label','Gray-Pink','CallBack','spm_figure(''ColorMap'',''gray-pink'')');\nuimenu(t1,'Label','Gray-Jet', 'CallBack','spm_figure(''ColorMap'',''gray-jet'')');\nt1=uimenu(t0,'Label','Effects');\nuimenu(t1,'Label','Invert','CallBack','spm_figure(''ColorMap'',''invert'')');\nuimenu(t1,'Label','Brighten','CallBack','spm_figure(''ColorMap'',''brighten'')');\nuimenu(t1,'Label','Darken','CallBack','spm_figure(''ColorMap'',''darken'')');\nuimenu( F,'Label','Clear','HandleVisibility','off','CallBack','spm_figure(''Clear'',gcbf)');\nt0=uimenu( F,'Label','SPM-Print','HandleVisibility','off');\n%uimenu( F,'Label','SPM-Print','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)');\nt1=uimenu(t0,'Label','default print file','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)');\nt1=uimenu(t0,'Label','other print file','HandleVisibility','off','CallBack','spm_figure(''PrintTo'',spm_figure(''FindWin'',''Graphics''))');\n\n\n% ### CODE FOR SATELLITE FIGURE ###\n% Code checks if there is a satellite window and if results are currently displayed\n% It assumes that if hReg is invalid then there are no results currently displayed\n% Modified by DRG to display a satellite figure 02/14/01.\ncb = ['global SatWindow,',...\n 'try,',...\n 'tmp = get(hReg);,',...\n 'ResFlag = 1;',...\n 'catch,',...\n 'ResFlag = 0;',...\n 'end,',...\n 'if SatWindow,',...\n 'figure(SatWindow),',...\n 'else,',...\n 'if ResFlag,',...\n 'spm_setup_satfig,',...\n 'end,',...\n 'end'];\nuimenu( F,'Label','Results-Fig','HandleVisibility','off','Callback',cb);\n% ### END NEW CODE ###\n\n\nset(0,'ShowHiddenHandles',cSHH)\nspm_jobman('pulldown');\n%=======================================================================\n\n\ncase 'figcontextmenu'\n%=======================================================================\n% h = spm_figure('FigContextMenu',F)\nif nargin<2\n\tF = get(0,'CurrentFigure');\n\tif isempty(F), error('no figure'), end\nelse\n\tF = spm_figure('FindWin',varargin{2});\n\tif isempty(F), error('no such figure'), end\nend\nh = uicontextmenu('Parent',F,'HandleVisibility','CallBack');\ncSHH = get(0,'ShowHiddenHandles');\nset(0,'ShowHiddenHandles','on')\ncopy_menu(F,h);\nset(0,'ShowHiddenHandles',cSHH)\nset(F,'UIContextMenu',h)\nvarargout = {h};\n\n\ncase 'colormap'\n%=======================================================================\n% spm_figure('ColorMap',ColAction,h)\nif nargin<3, h=[]; else h=varargin{3}; end\nif nargin<2, ColAction='gray'; else ColAction=varargin{2}; end\n\nswitch lower(ColAction), case 'gray'\n\tcolormap(gray(64))\ncase 'hot'\n\tcolormap(hot(64))\ncase 'pink'\n\tcolormap(pink(64))\ncase 'jet'\n\tcolormap(jet(64))\ncase 'gray-hot'\n\ttmp = hot(64 + 16); tmp = tmp((1:64) + 16,:);\n\tcolormap([gray(64); tmp]);\ncase 'gray-cool'\n\tcool = [zeros(10,1) zeros(10,1) linspace(0.5,1,10)';\n\t zeros(31,1) linspace(0,1,31)' ones(31,1);\n\t linspace(0,1,23)' ones(23,1) ones(23,1) ];\n\tcolormap([gray(64); cool]);\ncase 'gray-pink'\n\ttmp = pink(64 + 16); tmp = tmp((1:64) + 16,:);\n\tcolormap([gray(64); tmp]);\ncase 'gray-jet'\n\tcolormap([gray(64); jet(64)]);\ncase 'invert'\n\tcolormap(flipud(colormap));\ncase 'brighten'\n\tcolormap(brighten(colormap, 0.2));\ncase 'darken'\n\tcolormap(brighten(colormap, -0.2));\notherwise\n\terror('Illegal ColAction specification');\nend\n\ncase 'graphicshandle'\n%=======================================================================\n% h = spm_figure('GraphicsHandle',F)\nif nargin<2, F=gcbf; else F=spm_figure('FindWin',varargin{2}); end\nif isempty(F), return, end\n\ntmp = get(F,'Name');\nset(F,'Name',...\n\t'Handle: Select item to identify, MiddleMouse=parent, RightMouse=cancel...');\nset(F,'Pointer','CrossHair')\nwaitforbuttonpress;\nh = gco(F);\nhType = get(h,'Type');\nSelnType = get(gcf,'SelectionType');\nset(F,'Pointer','Arrow','Name',tmp)\n\nif ~strcmp(SelnType,'alt') && ~isempty(h) && gcf==F\n\tstr = sprintf('Selected (%s) object',get(h,'Type'));\n\tif strcmp(SelnType,'normal')\n\t\tstr = sprintf('%s: handle',str);\n\telse\n\t\th = get(h,'Parent');\n\t\tstr = sprintf('%s: handle of parent (%s) object',str,get(h,'Type'));\n\tend\n\tif nargout==0\n\t\tassignin('base','ans',h)\n\t\tfprintf('\\n%s: \\n',str)\n\t\tans = h\n\telse\n\t\tvarargout={h};\n\tend\nelse\n\tvarargout={[]};\nend\n\n\n\notherwise\n%=======================================================================\nwarning(['Illegal Action string: ',Action])\nend\nreturn;\n%=======================================================================\n\n\n%=======================================================================\nfunction copy_menu(F,G)\n%=======================================================================\nhandles = findobj(get(F,'Children'),'Flat','Type','uimenu','Visible','on');\nif isempty(handles), return; end;\nfor F1=handles',\n\tif ~strcmp(get(F1,'Label'),'&Window'),\n\t\tG1 = uimenu(G,'Label',get(F1,'Label'),...\n\t\t\t'CallBack',get(F1,'CallBack'),...\n\t\t\t'Position',get(F1,'Position'),...\n\t\t\t'Separator',get(F1,'Separator'));\n\t\tcopy_menu(F1,G1);\n\tend;\nend;\nreturn;\n%=======================================================================\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_runbatch.m", "ext": ".m", "path": "spm5-master/spm_config_runbatch.m", "size": 1054, "source_encoding": "utf_8", "md5": "c302aa5fcdb0ebe2c500ee8dcace2b9e", "text": "function opts = spm_config_runbatch\n% Configuration file for running batched jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Darren Gitelman\n% $Id: spm_config_runbatch.m 1032 2007-12-20 14:45:55Z john $\n\ndata.type = 'files';\ndata.name = 'Batch Files';\ndata.tag = 'jobs';\ndata.filter = 'batch';\ndata.num = [1 Inf];\ndata.help = {'Select the batch job files to be run.'};\n\nopts.type = 'branch';\nopts.name = 'Execute Batch Jobs';\nopts.tag = 'runbatch';\nopts.val = {data};\nopts.prog = @runbatch;\nopts.help = {[...\n'This facility allows previously created batch jobs to be run. ',...\n'These are simply created by the batch user interface ',...\n'(which you are currently using).']};\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction runbatch(varargin)\njobs = varargin{1}.jobs;\nfor i=1:numel(jobs),\n spm_jobman('run',jobs{i});\nend;\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_P_RF.m", "ext": ".m", "path": "spm5-master/spm_P_RF.m", "size": 5895, "source_encoding": "utf_8", "md5": "93c3a6c9cdea397f20820b00dd056112", "text": "function [P,p,Em,En,EN] = spm_P_RF(c,k,Z,df,STAT,R,n)\n% Returns the [un]corrected P value using unifed EC theory\n% FORMAT [P p Em En EN] = spm_P_RF(c,k,Z,df,STAT,R,n)\n%\n% c - cluster number \n% k - extent {RESELS}\n% Z - height {minimum over n values}\n% df - [df{interest} df{error}]\n% STAT - Statistical field\n%\t\t'Z' - Gaussian field\n%\t\t'T' - T - field\n%\t\t'X' - Chi squared field\n%\t\t'F' - F - field\n% R - RESEL Count {defining search volume}\n% n - number of component SPMs in conjunction\n%\n% P - corrected P value - P(n > kmax}\n% p - uncorrected P value - P(n > k}\n% Em - expected total number of maxima {m}\n% En - expected total number of resels per cluster {n}\n% EN - expected total number of voxels {N}\n%\n%___________________________________________________________________________\n%\n% spm_P_RF returns the probability of c or more clusters with more than\n% k voxels in volume process of R RESELS thresholded at u. All p values\n% can be considered special cases:\n%\n% spm_P_RF(1,0,Z,df,STAT,1,n) = uncorrected p value\n% spm_P_RF(1,0,Z,df,STAT,R,n) = corrected p value {based on height Z)\n% spm_P_RF(1,k,u,df,STAT,R,n) = corrected p value {based on extent k at u)\n% spm_P_RF(c,k,u,df,STAT,R,n) = corrected p value {based on number c at k and u)\n% spm_P_RF(c,0,u,df,STAT,R,n) = omnibus p value {based on number c at u)\n%\n% If n > 1 a conjunction probility over the n values of the statistic\n% is returned\n%\n% Ref: Hasofer AM (1978) Upcrossings of random fields\n% Suppl Adv Appl Prob 10:14-21\n% Ref: Friston et al (1993) Comparing functional images: Assessing\n% the spatial extent of activation foci\n% Ref: Worsley KJ et al 1996, Hum Brain Mapp. 4:58-73\n%___________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Karl Friston\n% $Id: spm_P_RF.m 707 2006-12-06 16:42:20Z volkmar $\n\n\n\n% get expectations\n%===========================================================================\n\n% get EC densities\n%---------------------------------------------------------------------------\nD = max(find(R));\nR = R(1:D);\nG = sqrt(pi)./gamma(([1:D])/2);\nEC = spm_ECdensity(STAT,Z,df);\nEC = EC([1:D]) + eps;\n\n% corrected p value\n%---------------------------------------------------------------------------\nP = triu(toeplitz(EC'.*G))^n;\nP = P(1,:);\nEM = (R./G).*P;\t\t\t% over D dimensions\nEm = sum(EM);\t\t\t% \nEN = P(1)*R(D);\t\t\t% \nEn = EN/EM(D);\t\t\t% En = EN/EM(D);\n\n% get P{n > k}\n%===========================================================================\n\n% assume a Gaussian form for P{n > k} ~ exp(-beta*k^(2/D))\n% Appropriate for SPM{Z} and high d.f. SPM{T}\n%---------------------------------------------------------------------------\nD = D - 1;\nif ~k | ~D\n\n\tp = 1;\n\nelseif STAT == 'Z'\n\n\tbeta = (gamma(D/2 + 1)/En)^(2/D);\n\tp = exp(-beta*(k^(2/D)));\n\nelseif STAT == 'T'\n\n\tbeta = (gamma(D/2 + 1)/En)^(2/D);\n\tp = exp(-beta*(k^(2/D)));\n\nelseif STAT == 'X'\n\n\tbeta = (gamma(D/2 + 1)/En)^(2/D);\n\tp = exp(-beta*(k^(2/D)));\n\nelseif STAT == 'F'\n\n\tbeta = (gamma(D/2 + 1)/En)^(2/D);\n\tp = exp(-beta*(k^(2/D)));\n\nend\n\n% Poisson clumping heuristic {for multiple clusters}\n%===========================================================================\nP = 1 - spm_Pcdf(c - 1,(Em + eps)*p);\n\n\n% set P and p = [] for non-implemented cases\n%+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nif k > 0 & n > 1\n\tP = []; p = [];\nend\nif k > 0 & (STAT == 'X' | STAT == 'F')\n\tP = []; p = [];\nend\n%+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n\n\n% spm_ECdensity\n%===========================================================================\n\nfunction [EC] = spm_ECdensity(STAT,t,df)\n% Returns the EC density\n%___________________________________________________________________________\n%\n% Reference : Worsley KJ et al 1996, Hum Brain Mapp. 4:58-73\n%\n%---------------------------------------------------------------------------\n\n% EC densities (EC}\n%---------------------------------------------------------------------------\nt = t(:)';\nif STAT == 'Z'\n\n\t% Gaussian Field\n\t%-------------------------------------------------------------------\n\ta = 4*log(2);\n\tb = exp(-t.^2/2);\n\n\tEC(1,:) = 1 - spm_Ncdf(t);\n\tEC(2,:) = a^(1/2)/(2*pi)*b;\n\tEC(3,:) = a/((2*pi)^(3/2))*b.*t;\n\tEC(4,:) = a^(3/2)/((2*pi)^2)*b.*(t.^2 - 1);\n\nelseif STAT == 'T'\n\n\t% T - Field\n\t%-------------------------------------------------------------------\n\tv = df(2);\n\ta = 4*log(2);\n\tb = exp(gammaln((v+1)/2) - gammaln(v/2));\n\tc = (1+t.^2/v).^((1-v)/2);\n\n\tEC(1,:) = 1 - spm_Tcdf(t,v);\n\tEC(2,:) = a^(1/2)/(2*pi)*c;\n\tEC(3,:) = a/((2*pi)^(3/2))*c.*t/((v/2)^(1/2))*b;\n\tEC(4,:) = a^(3/2)/((2*pi)^2)*c.*((v-1)*(t.^2)/v - 1);\n\nelseif STAT == 'X'\n\n\t% X - Field\n\t%-------------------------------------------------------------------\n\tv = df(2);\n\ta = (4*log(2))/(2*pi);\n\tb = t.^(1/2*(v - 1)).*exp(-t/2-gammaln(v/2))/2^((v-2)/2);\n\n\tEC(1,:) = 1 - spm_Xcdf(t,v);\n\tEC(2,:) = a^(1/2)*b;\n\tEC(3,:) = a*b.*(t-(v-1));\n\tEC(4,:) = a^(3/2)*b.*(t.^2-(2*v-1)*t+(v-1)*(v-2));\n\nelseif STAT == 'F'\n\n\t% F Field\n\t%-------------------------------------------------------------------\n\tk = df(1);\n\tv = df(2);\n\ta = (4*log(2))/(2*pi);\n\tb = gammaln(v/2) + gammaln(k/2);\n\n\tEC(1,:) = 1 - spm_Fcdf(t,df);\n\tEC(2,:) = a^(1/2)*exp(gammaln((v+k-1)/2)-b)*2^(1/2)...\n\t\t*(k*t/v).^(1/2*(k-1)).*(1+k*t/v).^(-1/2*(v+k-2));\n\tEC(3,:) = a*exp(gammaln((v+k-2)/2)-b)*(k*t/v).^(1/2*(k-2))...\n\t .*(1+k*t/v).^(-1/2*(v+k-2)).*((v-1)*k*t/v-(k-1));\n\tEC(4,:) = a^(3/2)*exp(gammaln((v+k-3)/2)-b)...\n\t\t*2^(-1/2)*(k*t/v).^(1/2*(k-3)).*(1+k*t/v).^(-1/2*(v+k-2))...\n\t .*((v-1)*(v-2)*(k*t/v).^2-(2*v*k-v-k-1)*(k*t/v)+(k-1)*(k-2));\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_dicom_headers.m", "ext": ".m", "path": "spm5-master/spm_dicom_headers.m", "size": 19177, "source_encoding": "utf_8", "md5": "881b6df84445c830fb8c99d036502ce3", "text": "function hdr = spm_dicom_headers(P, essentials)\n% Read header information from DICOM files\n% FORMAT hdr = spm_dicom_headers(P [,essentials])\n% P - array of filenames\n% essentials - if true, then only save the essential parts of the header\n% hdr - cell array of headers, one element for each file.\n%\n% Contents of headers are approximately explained in:\n% http://medical.nema.org/dicom/2001.html\n%\n% This code will not work for all cases of DICOM data, as DICOM is an\n% extremely complicated \"standard\".\n%\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_dicom_headers.m 2300 2008-10-06 11:16:30Z guillaume $\n\nif nargin<2, essentials = false; end\n\ndict = readdict;\nj = 0;\nhdr = {};\nif size(P,1)>1, spm_progress_bar('Init',size(P,1),'Reading DICOM headers','Files complete'); end;\nfor i=1:size(P,1),\n tmp = readdicomfile(P(i,:),dict);\n if ~isempty(tmp),\n if essentials, tmp = spm_dicom_essentials(tmp); end\n j = j + 1;\n hdr{j} = tmp;\n end;\n if size(P,1)>1, spm_progress_bar('Set',i); end;\nend;\nif size(P,1)>1, spm_progress_bar('Clear'); end;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction ret = readdicomfile(P,dict)\nret = [];\nP = deblank(P);\nfp = fopen(P,'r','ieee-le');\nif fp==-1, warning(['Cant open \"' P '\".']); return; end;\n\nfseek(fp,128,'bof');\ndcm = char(fread(fp,4,'uint8')');\nif ~strcmp(dcm,'DICM'),\n % Try truncated DICOM file fomat\n fseek(fp,0,'bof');\n tag.group = fread(fp,1,'ushort');\n tag.element = fread(fp,1,'ushort');\n if isempty(tag.group) || isempty(tag.element),\n fclose(fp);\n warning('Truncated file \"%s\"',P);\n return;\n end;\n %t = dict.tags(tag.group+1,tag.element+1);\n if isempty(find(dict.group==tag.group & dict.element==tag.element,1)) && ~(tag.group==8 && tag.element==0),\n % entry not found in DICOM dict and not from a GE Twin+excite\n % that starts with with an 8/0 tag that I can't find any\n % documentation for.\n fclose(fp);\n warning(['\"' P '\" is not a DICOM file.']);\n return;\n else\n fseek(fp,0,'bof');\n end;\nend;\nret = read_dicom(fp, 'il',dict);\nret.Filename = fopen(fp);\nfclose(fp);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [ret,len] = read_dicom(fp, flg, dict,lim)\nif nargin<4, lim=Inf; end;\n%if lim==2^32-1, lim=Inf; end;\nlen = 0;\nret = [];\ntag = read_tag(fp,flg,dict);\nwhile ~isempty(tag) && ~(tag.group==65534 && tag.element==57357), % && tag.length==0),\n %fprintf('%.4x/%.4x %d\\n', tag.group, tag.element, tag.length);\n if tag.length>0,\n switch tag.name,\n case {'GroupLength'},\n % Ignore it\n fseek(fp,tag.length,'cof');\n case {'PixelData'},\n ret.StartOfPixelData = ftell(fp);\n ret.SizeOfPixelData = tag.length;\n ret.VROfPixelData = tag.vr;\n fseek(fp,tag.length,'cof');\n case {'CSAData'}, % raw data\n ret.StartOfCSAData = ftell(fp);\n ret.SizeOfCSAData = tag.length;\n fseek(fp,tag.length,'cof');\n case {'CSAImageHeaderInfo', 'CSASeriesHeaderInfo','Private_0029_1210','Private_0029_1220'},\n dat = decode_csa(fp,tag.length);\n ret.(tag.name) = dat;\n case {'TransferSyntaxUID'},\n dat = char(fread(fp,tag.length,'uint8')');\n dat = deblank(dat);\n ret.(tag.name) = dat;\n switch dat,\n case {'1.2.840.10008.1.2'}, % Implicit VR Little Endian\n flg = 'il';\n case {'1.2.840.10008.1.2.1'}, % Explicit VR Little Endian\n flg = 'el';\n case {'1.2.840.10008.1.2.1.99'}, % Deflated Explicit VR Little Endian\n warning(['Cant read Deflated Explicit VR Little Endian file \"' fopen(fp) '\".']);\n flg = 'dl';\n return;\n case {'1.2.840.10008.1.2.2'}, % Explicit VR Big Endian\n %warning(['Cant read Explicit VR Big Endian file \"' fopen(fp) '\".']);\n flg = 'eb'; % Unused\n otherwise,\n warning(['Unknown Transfer Syntax UID for \"' fopen(fp) '\".']);\n return;\n end;\n otherwise,\n switch tag.vr,\n case {'UN'},\n % Unknown - read as char\n dat = fread(fp,tag.length,'uint8')';\n case {'AE', 'AS', 'CS', 'DA', 'DS', 'DT', 'IS', 'LO', 'LT',...\n 'PN', 'SH', 'ST', 'TM', 'UI', 'UT'},\n % Character strings\n dat = char(fread(fp,tag.length,'uint8')');\n\n switch tag.vr,\n case {'UI','ST'},\n dat = deblank(dat);\n case {'DS'},\n try\n dat = strread(dat,'%f','delimiter','\\\\')';\n catch\n dat = strread(dat,'%f','delimiter','/')';\n end\n case {'IS'},\n dat = strread(dat,'%d','delimiter','\\\\')';\n case {'DA'},\n dat = strrep(dat,'.',' ');\n [y,m,d] = strread(dat,'%4d%2d%2d');\n dat = datenum(y,m,d);\n case {'TM'},\n if any(dat==':'),\n [h,m,s] = strread(dat,'%d:%d:%f');\n else\n [h,m,s] = strread(dat,'%2d%2d%f');\n end;\n if isempty(h), h = 0; end;\n if isempty(m), m = 0; end;\n if isempty(s), s = 0; end;\n dat = s+60*(m+60*h);\n case {'LO'},\n dat = uscore_subst(dat);\n otherwise,\n end;\n case {'OB'},\n % dont know if this should be signed or unsigned\n dat = fread(fp,tag.length,'uint8')';\n case {'US', 'AT', 'OW'},\n dat = fread(fp,tag.length/2,'uint16')';\n case {'SS'},\n dat = fread(fp,tag.length/2,'int16')';\n case {'UL'},\n dat = fread(fp,tag.length/4,'uint32')';\n case {'SL'},\n dat = fread(fp,tag.length/4,'int32')';\n case {'FL'},\n dat = fread(fp,tag.length/4,'float')';\n case {'FD'},\n dat = fread(fp,tag.length/8,'double')';\n case {'SQ'},\n [dat,len1] = read_sq(fp, flg,dict,tag.length);\n tag.length = len1;\n otherwise,\n dat = '';\n fseek(fp,tag.length,'cof');\n warning(['Unknown VR [' num2str(tag.vr+0) '] in \"'...\n fopen(fp) '\" (offset=' num2str(ftell(fp)) ').']);\n end;\n if ~isempty(tag.name),\n ret.(tag.name) = dat;\n end;\n end;\n end;\n len = len + tag.le + tag.length;\n if len>=lim, return; end;\n tag = read_tag(fp,flg,dict);\nend;\nif ~isempty(tag),\n len = len + tag.le;\n\n % I can't find this bit in the DICOM standard, but it seems to\n % be needed for Philips Integra\n if tag.group==65534 && tag.element==57357 && tag.length~=0,\n fseek(fp,-4,'cof');\n len = len-4;\n end;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [ret,len] = read_sq(fp, flg, dict,lim)\nret = {};\nn = 0;\nlen = 0;\nwhile len0,\n tag.name = dict.values(t).name;\n tag.vr = dict.values(t).vr{1};\nelse\n % Set tag.name = '' in order to restrict the fields to those\n % in the dictionary. With a reduced dictionary, this could\n % speed things up considerably.\n % tag.name = '';\n tag.name = sprintf('Private_%.4x_%.4x',tag.group,tag.element);\n tag.vr = 'UN';\nend;\n\nif flg(2) == 'b',\n [fname,perm,fmt] = fopen(fp);\n if strcmp(fmt,'ieee-le') || strcmp(fmt,'ieee-le.l64'),\n pos = ftell(fp);\n fclose(fp);\n fp = fopen(fname,perm,'ieee-be');\n fseek(fp,pos,'bof');\n end;\nend;\n\nif flg(1) =='e',\n tag.vr = char(fread(fp,2,'uint8')');\n tag.le = 6;\n switch tag.vr,\n case {'OB','OW','SQ','UN','UT'}\n if ~strcmp(tag.vr,'UN') || tag.group~=65534,\n fseek(fp,2,0);\n end;\n tag.length = double(fread(fp,1,'uint'));\n tag.le = tag.le + 6;\n case {'AE','AS','AT','CS','DA','DS','DT','FD','FL','IS','LO','LT','PN','SH','SL','SS','ST','TM','UI','UL','US'},\n tag.length = double(fread(fp,1,'ushort'));\n tag.le = tag.le + 2;\n case char([0 0])\n if (tag.group == 65534) && (tag.element == 57357)\n % at least on GE, ItemDeliminationItem does not have a\n % VR, but 4 bytes zeroes as length\n tag.le = 8;\n tag.length = 0;\n tmp = fread(fp,1,'ushort');\n else\n warning('Don''t know how to handle VR of ''\\0\\0''');\n end;\n otherwise,\n fseek(fp,2,0);\n tag.length = double(fread(fp,1,'uint'));\n tag.le = tag.le + 6;\n end;\nelse\n tag.le = 8;\n tag.length = double(fread(fp,1,'uint'));\nend;\nif isempty(tag.vr) || isempty(tag.length),\n tag = [];\n return;\nend;\n\n\nif rem(tag.length,2),\n if tag.length==4294967295,\n tag.length = Inf;\n return;\n elseif tag.length==13,\n % disp(['Whichever manufacturer created \"' fopen(fp) '\" is taking the p***!']);\n % For some bizarre reason, known only to themselves, they confuse lengths of\n % 13 with lengths of 10.\n tag.length = 10;\n else\n warning(['Unknown odd numbered Value Length (' sprintf('%x',tag.length) ') in \"' fopen(fp) '\".']);\n tag = [];\n end;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction dict = readdict(P)\nif nargin<1, P = 'spm_dicom_dict.mat'; end;\ntry\n dict = load(P);\ncatch\n fprintf('\\nUnable to load the file \"%s\".\\n', P);\n if strcmp(computer,'PCWIN') || strcmp(computer,'PCWIN64'),\n fprintf('This may be because of the way that the .tar.gz files\\n');\n fprintf('were unpacked when the SPM software was installed.\\n');\n fprintf('If installing on a Windows platform, then the software\\n');\n fprintf('used for unpacking may try to be clever and insert\\n');\n fprintf('additional unwanted control characters. If you use\\n');\n fprintf('WinZip, then you should ensure that TAR file smart\\n');\n fprintf('CR/LF conversion is disabled (under the Miscellaneous\\n');\n fprintf('Configuration Options).\\n\\n');\n end;\n rethrow(lasterr);\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction dict = readdict_txt\nfile = textread('spm_dicom_dict.txt','%s','delimiter','\\n','whitespace','');\nclear values\ni = 0;\nfor i0=1:length(file),\n words = strread(file{i0},'%s','delimiter','\\t');\n if length(words)>=5 && ~strcmp(words{1}(3:4),'xx'),\n grp = sscanf(words{1},'%x');\n ele = sscanf(words{2},'%x');\n if ~isempty(grp) && ~isempty(ele),\n i = i + 1;\n group(i) = grp;\n element(i) = ele;\n vr = {};\n for j=1:length(words{4})/2,\n vr{j} = words{4}(2*(j-1)+1:2*(j-1)+2);\n end;\n name = words{3};\n msk = ~(name>='a' & name<='z') & ~(name>='A' & name<='Z') &...\n ~(name>='0' & name<='9') & ~(name=='_');\n name(msk) = '';\n values(i) = struct('name',name,'vr',{vr},'vm',words{5});\n end;\n end;\nend;\n\ntags = sparse(group+1,element+1,1:length(group));\ndict = struct('values',values,'tags',tags);\ndict = desparsify(dict);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction dict = desparsify(dict)\n[group,element] = find(dict.tags);\noffs = zeros(size(group));\nfor k=1:length(group),\n offs(k) = dict.tags(group(k),element(k));\nend;\ndict.group(offs) = group-1;\ndict.element(offs) = element-1;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction t = decode_csa(fp,lim)\n% Decode shadow information (0029,1010) and (0029,1020)\n[fname,perm,fmt] = fopen(fp);\npos = ftell(fp);\nif strcmp(fmt,'ieee-be') || strcmp(fmt,'ieee-be.l64'),\n fclose(fp);\n fp = fopen(fname,perm,'ieee-le');\n fseek(fp,pos,'bof');\nend;\n\nc = fread(fp,4,'uint8');\nfseek(fp,pos,'bof');\n\nif all(c'==[83 86 49 48]), % \"SV10\"\n t = decode_csa2(fp,lim);\nelse\n t = decode_csa1(fp,lim);\nend;\n\nif strcmp(fmt,'ieee-be') || strcmp(fmt,'ieee-be.l64'),\n fclose(fp);\n fp = fopen(fname,perm,fmt);\nend;\nfseek(fp,pos+lim,'bof');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction t = decode_csa1(fp,lim)\nn = fread(fp,1,'uint32');\nif isempty(n) || n>128 || n < 0,\n fseek(fp,lim-4,'cof');\n t = struct('name','JUNK: Don''t know how to read this damned file format');\n return;\nend;\nunused = fread(fp,1,'uint32')'; % Unused \"M\" or 77 for some reason\ntot = 2*4;\nfor i=1:n,\n t(i).name = fread(fp,64,'uint8')';\n msk = find(~t(i).name)-1;\n if ~isempty(msk),\n t(i).name = char(t(i).name(1:msk(1)));\n else\n t(i).name = char(t(i).name);\n end;\n t(i).vm = fread(fp,1,'int32')';\n t(i).vr = fread(fp,4,'uint8')';\n t(i).vr = char(t(i).vr(1:3));\n t(i).syngodt = fread(fp,1,'int32')';\n t(i).nitems = fread(fp,1,'int32')';\n t(i).xx = fread(fp,1,'int32')'; % 77 or 205\n tot = tot + 64+4+4+4+4+4;\n for j=1:t(i).nitems\n % This bit is just wierd\n t(i).item(j).xx = fread(fp,4,'int32')'; % [x x 77 x]\n len = t(i).item(j).xx(1)-t(1).nitems;\n if len<0 || len+tot+4*4>lim,\n t(i).item(j).val = '';\n tot = tot + 4*4;\n break;\n end;\n t(i).item(j).val = char(fread(fp,len,'uint8')');\n fread(fp,4-rem(len,4),'uint8');\n tot = tot + 4*4+len+(4-rem(len,4));\n end;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction t = decode_csa2(fp,lim)\nunused = fread(fp,4,'uint8'); % Unused\nunused = fread(fp,4,'uint8'); % Unused\nn = fread(fp,1,'uint32');\nif n>128 || n < 0,\n fseek(fp,lim-4,'cof');\n t = struct('junk','Don''t know how to read this damned file format');\n return;\nend;\nunused = fread(fp,1,'uint32')'; % Unused \"M\" or 77 for some reason\nfor i=1:n,\n t(i).name = fread(fp,64,'uint8')';\n msk = find(~t(i).name)-1;\n if ~isempty(msk),\n t(i).name = char(t(i).name(1:msk(1)));\n else\n t(i).name = char(t(i).name);\n end;\n t(i).vm = fread(fp,1,'int32')';\n t(i).vr = fread(fp,4,'uint8')';\n t(i).vr = char(t(i).vr(1:3));\n t(i).syngodt = fread(fp,1,'int32')';\n t(i).nitems = fread(fp,1,'int32')';\n t(i).xx = fread(fp,1,'int32')'; % 77 or 205\n for j=1:t(i).nitems\n t(i).item(j).xx = fread(fp,4,'int32')'; % [x x 77 x]\n len = t(i).item(j).xx(2);\n t(i).item(j).val = char(fread(fp,len,'uint8')');\n fread(fp,rem(4-rem(len,4),4),'uint8');\n end;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction str_out = uscore_subst(str_in)\nstr_out = str_in;\npos = findstr(str_in,'+AF8-');\nif ~isempty(pos),\n str_out(pos) = '_';\n str_out(repmat(pos,4,1)+repmat((1:4)',1,numel(pos))) = [];\nend\nreturn;\n%_______________________________________________________________________\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_coreg.m", "ext": ".m", "path": "spm5-master/spm_config_coreg.m", "size": 13182, "source_encoding": "utf_8", "md5": "f9c6e0cc429ce2dacdee008d8a00cc6e", "text": "function opts = spm_config_coreg\n% Configuration file for coregister jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_coreg.m 1032 2007-12-20 14:45:55Z john $\n\nref.type = 'files';\nref.name = 'Reference Image';\nref.tag = 'ref';\nref.filter = 'image';\nref.num = 1;\nref.help = {[...\n'This is the image that is assumed to remain stationary (sometimes ',...\n'known as the target or template image), while the source image ',...\n'is moved to match it.']};\n\n%------------------------------------------------------------------------\n\nsource.type = 'files';\nsource.name = 'Source Image';\nsource.tag = 'source';\nsource.filter = 'image';\nsource.num = 1;\nsource.help = {...\n'This is the image that is jiggled about to best match the reference.'};\n\n%------------------------------------------------------------------------\n\nother.type = 'files';\nother.name = 'Other Images';\nother.tag = 'other';\nother.filter = 'image';\nother.num = [0 Inf];\nother.val = {''};\nother.help = {[...\n'These are any images that need to remain in alignment with the ',...\n'source image.']};\n\n%------------------------------------------------------------------------\n\ncost_fun.type = 'menu';\ncost_fun.name = 'Objective Function';\ncost_fun.tag = 'cost_fun';\ncost_fun.labels = {'Mutual Information','Normalised Mutual Information',...\n'Entropy Correlation Coefficient','Normalised Cross Correlation'};\ncost_fun.values = {'mi','nmi','ecc','ncc'};\ncost_fun.def = 'coreg.estimate.cost_fun';\ncost_fun.help = {[...\n'Registration involves finding parameters that either maximise or ',...\n'minimise some objective function. ',...\n'For inter-modal registration, use Mutual Information\\* \\cite{collignon95,wells96}*/, Normalised Mutual Information/* \\cite{studholme99}*/, or ',...\n'Entropy Correlation Coefficient/* \\cite{maes97}*/.',...\n'For within modality, you could also use Normalised Cross Correlation.']};\n\n%------------------------------------------------------------------------\n\nsep.type = 'entry';\nsep.name = 'Separation';\nsep.tag = 'sep';\nsep.num = [1 Inf];\nsep.strtype = 'e';\nsep.def = 'coreg.estimate.sep';\nsep.help = {[...\n'The average distance between sampled points (in mm). Can be a vector ',...\n'to allow a coarse registration followed by increasingly fine ones.']};\n\n%------------------------------------------------------------------------\n\ntol.type = 'entry';\ntol.name = 'Tolerances';\ntol.tag = 'tol';\ntol.num = [1 12];\ntol.strtype = 'e';\ntol.def = 'coreg.estimate.tol';\ntol.help = {[...\n'The accuracy for each parameter. Iterations stop when differences ',...\n'between successive estimates are less than the required tolerance.']};\n\n%------------------------------------------------------------------------\n\nfwhm.type = 'entry';\nfwhm.name = 'Histogram Smoothing';\nfwhm.tag = 'fwhm';\nfwhm.num = [1 2];\nfwhm.strtype = 'e';\nfwhm.def = 'coreg.estimate.fwhm';\nfwhm.help = {[...\n'Gaussian smoothing to apply to the 256x256 joint histogram. Other ',...\n'information theoretic coregistration methods use fewer bins, but ',...\n'Gaussian smoothing seems to be more elegant.']};\n\n%------------------------------------------------------------------------\n\neoptions.type = 'branch';\neoptions.name = 'Estimation Options';\neoptions.tag = 'eoptions';\neoptions.val = {cost_fun,sep,tol,fwhm};\neoptions.help = {...\n['Various registration options, which are passed to the ',...\n'Powell optimisation algorithm/* \\cite{press92}*/.']};\n\n%------------------------------------------------------------------------\n\nest.type = 'branch';\nest.name = 'Coreg: Estimate';\nest.tag = 'estimate';\nest.val = {ref,source,other,eoptions};\nest.prog = @estimate;\np1 = [...\n'The registration method used here is based on work by Collignon et al/* \\cite{collignon95}*/. ',...\n'The original interpolation method described in this paper has been ',...\n'changed in order to give a smoother cost function. The images are ',...\n'also smoothed slightly, as is the histogram. This is all in order to ',...\n'make the cost function as smooth as possible, to give faster ',...\n'convergence and less chance of local minima.'];\np2 = [...\n'At the end of coregistration, the voxel-to-voxel affine transformation ',...\n'matrix is displayed, along with the histograms for the images in the ',...\n'original orientations, and the final orientations. The registered ',...\n'images are displayed at the bottom.'];\np3 = [...\n'Registration parameters are stored in the headers of the \"source\" ',...\n'and the \"other\" images.'];\n\nest.help = {p1,'',p2,'',p3};\n\n%------------------------------------------------------------------------\n\ninterp.type = 'menu';\ninterp.name = 'Interpolation';\ninterp.tag = 'interp';\ninterp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-Spline',...\n'3rd Degree B-Spline','4th Degree B-Spline','5th Degree B-Spline',...\n'6th Degree B-Spline','7th Degree B-Spline'};\ninterp.values = {0,1,2,3,4,5,6,7};\ninterp.def = 'coreg.write.interp';\ninterp.help = {[...\n'The method by which the images are sampled when being written in a ',...\n'different space. ',...\n'Nearest Neighbour is fastest, but not normally recommended. ',...\n'It can be useful for re-orienting images while preserving the original ',...\n'intensities (e.g. an image consisting of labels). ',...\n'Bilinear Interpolation is OK for PET, or realigned and re-sliced fMRI. ',...\n'If subject movement (from an fMRI time series) is included in the transformations ',...\n'then it may be better to use a higher degree approach. ',...\n'Note that higher degree B-spline interpolation/* \\cite{thevenaz00a,unser93a,unser93b}*/ is slower because it uses more ',...\n'neighbours.']};\n\n%------------------------------------------------------------------------\n\nwrap.type = 'menu';\nwrap.name = 'Wrapping';\nwrap.tag = 'wrap';\nwrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z',...\n'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'};\nwrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]};\nwrap.def = 'coreg.write.wrap';\nwrap.help = {...\n'These are typically:',...\n[' No wrapping - for PET or images that have already',...\n ' been spatially transformed.'],...\n[' Wrap in Y - for (un-resliced) MRI where phase encoding',...\n ' is in the Y direction (voxel space).']};\n\n%------------------------------------------------------------------------\n\nmask.type = 'menu';\nmask.name = 'Masking';\nmask.tag = 'mask';\nmask.labels = {'Mask images','Dont mask images'};\nmask.values = {1,0};\nmask.def = 'coreg.write.mask';\nmask.help = {[...\n'Because of subject motion, different images are likely to have different ',...\n'patterns of zeros from where it was not possible to sample data. ',...\n'With masking enabled, the program searches through the whole time series ',...\n'looking for voxels which need to be sampled from outside the original ',...\n'images. Where this occurs, that voxel is set to zero for the whole set ',...\n'of images (unless the image format can represent NaN, in which case ',...\n'NaNs are used where possible).']};\n\n%------------------------------------------------------------------------\n\nroptions.type = 'branch';\nroptions.name = 'Reslice Options';\nroptions.tag = 'roptions';\nroptions.val = {interp,wrap,mask};\nroptions.help = {'Various reslicing options.'};\n\n%------------------------------------------------------------------------\n\nestwrite.type = 'branch';\nestwrite.name = 'Coreg: Estimate & Reslice';\nestwrite.tag = 'estwrite';\nestwrite.val = {ref,source,other,eoptions,roptions};\nestwrite.prog = @estimate_reslice;\nestwrite.vfiles = @vfiles_estwrite;\np1 = [...\n'The registration method used here is based on work by Collignon et al/* \\cite{collignon95}*/. ',...\n'The original interpolation method described in this paper has been ',...\n'changed in order to give a smoother cost function. The images are ',...\n'also smoothed slightly, as is the histogram. This is all in order to ',...\n'make the cost function as smooth as possible, to give faster ',...\n'convergence and less chance of local minima.'];\np2 = [...\n'At the end of coregistration, the voxel-to-voxel affine transformation ',...\n'matrix is displayed, along with the histograms for the images in the ',...\n'original orientations, and the final orientations. The registered ',...\n'images are displayed at the bottom.'];\np3 = [...\n'Registration parameters are stored in the headers of the \"source\" ',...\n'and the \"other\" images. These images are also resliced to match the ',...\n'source image voxel-for-voxel. The resliced images are named the same as ',...\n'the originals except that they are prefixed by ''r''.'];\nestwrite.help = {p1,'',p2,'',p3};\n\n%------------------------------------------------------------------------\n\nref.type = 'files';\nref.name = 'Image Defining Space';\nref.tag = 'ref';\nref.filter = 'image';\nref.num = 1;\nref.help = {[...\n'This is analogous to the reference image. Images are resliced to match ',...\n'this image (providing they have been coregistered first).']};\n\n%------------------------------------------------------------------------\n \nsource.type = 'files';\nsource.name = 'Images to Reslice';\nsource.tag = 'source';\nsource.filter = 'image';\nsource.num = Inf;\nsource.help = {[...\n'These images are resliced to the same dimensions, voxel sizes, ',...\n'orientation etc as the space defining image.']};\n\n%------------------------------------------------------------------------\n\nwrite.type = 'branch';\nwrite.name = 'Coreg: Reslice';\nwrite.tag = 'write';\nwrite.val = {ref,source,roptions};\nwrite.prog = @reslice;\nwrite.vfiles = @vfiles_write;\nwrite.help = {[...\n'Reslice images to match voxel-for-voxel with an image defining ',...\n'some space. The resliced images are named the same as the originals ',...\n'except that they are prefixed by ''r''.']};\n\n%------------------------------------------------------------------------\n\nopts.type = 'repeat';\nopts.name = 'Coreg';\nopts.tag = 'coreg';\nopts.values = {est,write,estwrite};\nopts.num = [1 Inf];\nopts.modality = {'PET','FMRI','VBM'};\np1 = [...\n'Within-subject registration using a rigid-body model. ',...\n'A rigid-body transformation (in 3D) can be parameterised by three ',...\n'translations and three rotations about the different axes.'];\np2 = [...\n'You get the options of estimating the transformation, reslicing images ',...\n'according to some rigid-body transformations, or estimating and ',...\n'applying rigid-body transformations.'];\nopts.help = {p1,'',p2};\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction estimate(varargin)\njob = varargin{1};\n%disp(job);\n%disp(job.eoptions);\n\nx = spm_coreg(strvcat(job.ref), strvcat(job.source),job.eoptions);\nM = inv(spm_matrix(x));\nPO = strvcat(strvcat(job.source),strvcat(job.other));\nMM = zeros(4,4,size(PO,1));\nfor j=1:size(PO,1),\n\tMM(:,:,j) = spm_get_space(deblank(PO(j,:)));\nend;\nfor j=1:size(PO,1),\n\tspm_get_space(deblank(PO(j,:)), M*MM(:,:,j));\nend;\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction reslice(varargin)\njob = varargin{1};\n\nP = strvcat(strvcat(job.ref),strvcat(job.source));\nflags.mask = job.roptions.mask;\nflags.mean = 0;\nflags.interp = job.roptions.interp;\nflags.which = 1;\nflags.wrap = job.roptions.wrap;\n\nspm_reslice(P,flags);\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction estimate_reslice(varargin)\njob = varargin{1};\n%disp(job);\n%disp(job.eoptions);\n%disp(job.roptions);\n\njob.ref = strvcat(job.ref);\njob.source = strvcat(job.source);\njob.other = strvcat(job.other);\n\nx = spm_coreg(job.ref, job.source,job.eoptions);\nM = inv(spm_matrix(x));\nPO = strvcat(job.source,job.other);\nMM = zeros(4,4,size(PO,1));\nfor j=1:size(PO,1),\n MM(:,:,j) = spm_get_space(deblank(PO(j,:)));\nend;\nfor j=1:size(PO,1),\n spm_get_space(deblank(PO(j,:)), M*MM(:,:,j));\nend;\n\nP = strvcat(job.ref,job.source,job.other);\nflags.mask = job.roptions.mask;\nflags.mean = 0;\nflags.interp = job.roptions.interp;\nflags.which = 1;\nflags.wrap = job.roptions.wrap;\n\nspm_reslice(P,flags);\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction vf = vfiles_write(varargin)\njob = varargin{1};\nvf = cell(size(job.source));\nfor i=1:numel(job.source),\n [pth,nam,ext,num] = spm_fileparts(job.source{i});\n vf{i} = fullfile(pth,['r', nam, ext, num]);\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction vf = vfiles_estwrite(varargin)\njob = varargin{1};\nP = {job.source{:},job.other{:}};\nvf = cell(size(P));\nfor i=1:numel(P),\n [pth,nam,ext,num] = spm_fileparts(P{i});\n vf{i} = fullfile(pth,['r', nam, ext, num]);\nend;\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_image.m", "ext": ".m", "path": "spm5-master/spm_image.m", "size": 20429, "source_encoding": "utf_8", "md5": "891123a6397852f97de13a1b3463ab74", "text": "function spm_image(op,varargin)\n% image and header display\n% FORMAT spm_image\n%_______________________________________________________________________\n%\n% spm_image is an interactive facility that allows orthogonal sections\n% from an image volume to be displayed. Clicking the cursor on either\n% of the three images moves the point around which the orthogonal\n% sections are viewed. The co-ordinates of the cursor are shown both\n% in voxel co-ordinates and millimeters within some fixed framework.\n% The intensity at that point in the image (sampled using the current\n% interpolation scheme) is also given. The position of the crosshairs\n% can also be moved by specifying the co-ordinates in millimeters to\n% which they should be moved. Clicking on the horizontal bar above\n% these boxes will move the cursor back to the origin (analogous to\n% setting the crosshair position (in mm) to [0 0 0]).\n%\n% The images can be re-oriented by entering appropriate translations,\n% rotations and zooms into the panel on the left. The transformations\n% can then be saved by hitting the ``Reorient images...'' button. The\n% transformations that were applied to the image are saved to the\n% ``.mat'' files of the selected images. The transformations are\n% considered to be relative to any existing transformations that may be\n% stored in the ``.mat'' files. Note that the order that the\n% transformations are applied in is the same as in ``spm_matrix.m''.\n%\n% The ``Reset...'' button next to it is for setting the orientation of\n% images back to transverse. It retains the current voxel sizes,\n% but sets the origin of the images to be the centre of the volumes\n% and all rotations back to zero.\n%\n% The right panel shows miscellaneous information about the image.\n% This includes:\n% Dimensions - the x, y and z dimensions of the image.\n% Datatype - the computer representation of each voxel.\n% Intensity - scalefactors and possibly a DC offset.\n% Miscellaneous other information about the image.\n% Vox size - the distance (in mm) between the centres of\n% neighbouring voxels.\n% Origin - the voxel at the origin of the co-ordinate system\n% DIr Cos - Direction cosines. This is a widely used\n% representation of the orientation of an image.\n%\n% There are also a few options for different resampling modes, zooms\n% etc. You can also flip between voxel space (as would be displayed\n% by Analyze) or world space (the orientation that SPM considers the\n% image to be in). If you are re-orienting the images, make sure that\n% world space is specified. Blobs (from activation studies) can be\n% superimposed on the images and the intensity windowing can also be\n% changed.\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_image.m 2526 2008-12-03 11:42:57Z john $\n\n\nglobal st\n\nif nargin == 0,\n\tspm('FnUIsetup','Display',0);\n\tspm('FnBanner',mfilename,'$Rev: 2526 $');\n\tspm_help('!ContextHelp',[mfilename,'.m']);\n\n\t% get the image's filename {P}\n\t%-----------------------------------------------------------------------\n\tP = spm_select(1,'image','Select image',[],0);\n\tspm_image('init',P);\n\treturn;\nend;\n\ntry\n\tif ~strcmp(op,'init') && ~strcmp(op,'reset') && isempty(st.vols{1})\n\t\tmy_reset; warning('Lost all the image information');\n\t\treturn;\n\tend;\ncatch\nend\n\nif strcmp(op,'repos'),\n\t% The widgets for translation rotation or zooms have been modified.\n\t%-----------------------------------------------------------------------\n\tfg = spm_figure('Findwin','Graphics');\n\tset(fg,'Pointer','watch');\n\ti = varargin{1};\n\tst.B(i) = eval(get(gco,'String'),num2str(st.B(i)));\n\tset(gco,'String',st.B(i));\n\tst.vols{1}.premul = spm_matrix(st.B);\n\t% spm_orthviews('MaxBB');\n\tspm_image('zoom_in');\n\tspm_image('update_info');\n\tset(fg,'Pointer','arrow');\n\treturn;\nend;\n\nif strcmp(op,'shopos'),\n\t% The position of the crosshairs has been moved.\n\t%-----------------------------------------------------------------------\n\tif isfield(st,'mp'),\n\t\tfg = spm_figure('Findwin','Graphics');\n\t\tif any(findobj(fg) == st.mp),\n set(st.mp,'String',sprintf('%.1f %.1f %.1f',spm_orthviews('pos')));\n pos = spm_orthviews('pos',1);\n set(st.vp,'String',sprintf('%.1f %.1f %.1f',pos));\n set(st.in,'String',sprintf('%g',spm_sample_vol(st.vols{1},pos(1),pos(2),pos(3),st.hld)));\n else\n\t\t\tst.Callback = ';';\n\t\t\tst = rmfield(st,{'mp','vp','in'});\n\t\tend;\n else\n\t\tst.Callback = ';';\n\tend;\n\treturn;\nend;\n\nif strcmp(op,'setposmm'),\n\t% Move the crosshairs to the specified position\n\t%-----------------------------------------------------------------------\n\tif isfield(st,'mp'),\n\t\tfg = spm_figure('Findwin','Graphics');\n\t\tif any(findobj(fg) == st.mp),\n\t\t\tpos = sscanf(get(st.mp,'String'), '%g %g %g');\n\t\t\tif length(pos)~=3,\n\t\t\t\tpos = spm_orthviews('pos');\n\t\t\tend;\n\t\t\tspm_orthviews('Reposition',pos);\n\t\tend;\n\tend;\n\treturn;\nend;\n\nif strcmp(op,'setposvx'),\n\t% Move the crosshairs to the specified position\n\t%-----------------------------------------------------------------------\n\tif isfield(st,'mp'),\n\t\tfg = spm_figure('Findwin','Graphics');\n\t\tif any(findobj(fg) == st.vp),\n\t\t\tpos = sscanf(get(st.vp,'String'), '%g %g %g');\n\t\t\tif length(pos)~=3,\n\t\t\t\tpos = spm_orthviews('pos',1);\n\t\t\tend;\n\t\t\ttmp = st.vols{1}.premul*st.vols{1}.mat;\n\t\t\tpos = tmp(1:3,:)*[pos ; 1];\n\t\t\tspm_orthviews('Reposition',pos);\n\t\tend;\n\tend;\n\treturn;\nend;\n\n\nif strcmp(op,'addblobs'),\n\t% Add blobs to the image - in full colour\n\tspm_figure('Clear','Interactive');\n\tnblobs = spm_input('Number of sets of blobs',1,'1|2|3|4|5|6',[1 2 3 4 5 6],1);\n\tfor i=1:nblobs,\n\t\t[SPM,VOL] = spm_getSPM;\n\t\tc = spm_input('Colour','+1','m','Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);\n\t\tcolours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];\n\t\tspm_orthviews('addcolouredblobs',1,VOL.XYZ,VOL.Z,VOL.M,colours(c,:));\n\t\tset(st.blobber,'String','Remove Blobs','Callback','spm_image(''rmblobs'');');\n\tend;\n\tspm_orthviews('addcontext',1);\n\tspm_orthviews('Redraw');\nend;\n\nif strcmp(op,'rmblobs'),\n\t% Remove all blobs from the images\n\tspm_orthviews('rmblobs',1);\n\tset(st.blobber,'String','Add Blobs','Callback','spm_image(''addblobs'');');\n\tspm_orthviews('rmcontext',1); \n\tspm_orthviews('Redraw');\nend;\n\nif strcmp(op,'window'),\n\top = get(st.win,'Value');\n\tif op == 1,\n\t\tspm_orthviews('window',1);\n else\n\t\tspm_orthviews('window',1,spm_input('Range','+1','e','',2));\n\tend;\nend;\n\n\nif strcmp(op,'reorient'),\n\t% Time to modify the ``.mat'' files for the images.\n\t% I hope that giving people this facility is the right thing to do....\n\t%-----------------------------------------------------------------------\n\tmat = spm_matrix(st.B);\n\tif det(mat)<=0\n\t\tspm('alert!','This will flip the images',mfilename,0,1);\n\tend;\n\tP = spm_select(Inf, 'image','Images to reorient');\n\tMats = zeros(4,4,size(P,1));\n\tspm_progress_bar('Init',size(P,1),'Reading current orientations',...\n\t\t'Images Complete');\n\tfor i=1:size(P,1),\n\t\tMats(:,:,i) = spm_get_space(P(i,:));\n\t\tspm_progress_bar('Set',i);\n\tend;\n\tspm_progress_bar('Init',size(P,1),'Reorienting images',...\n\t\t'Images Complete');\n\tfor i=1:size(P,1),\n\t\tspm_get_space(P(i,:),mat*Mats(:,:,i));\n\t\tspm_progress_bar('Set',i);\n\tend;\n\tspm_progress_bar('Clear');\n\ttmp = spm_get_space([st.vols{1}.fname ',' num2str(st.vols{1}.n)]);\n\tif sum((tmp(:)-st.vols{1}.mat(:)).^2) > 1e-8,\n\t\tspm_image('init',st.vols{1}.fname);\n\tend;\n\treturn;\nend;\n\nif strcmp(op,'resetorient'),\n\t% Time to modify the ``.mat'' files for the images.\n\t% I hope that giving people this facility is the right thing to do....\n\t%-----------------------------------------------------------------------\n\tP = spm_select(Inf, 'image','Images to reset orientation of');\n\tspm_progress_bar('Init',size(P,1),'Resetting orientations',...\n\t\t'Images Complete');\n\tfor i=1:size(P,1),\n\t\tV = spm_vol(deblank(P(i,:)));\n\t\tM = V.mat;\n\t\tvox = sqrt(sum(M(1:3,1:3).^2));\n\t\tif det(M(1:3,1:3))<0, vox(1) = -vox(1); end;\n\t\torig = (V.dim(1:3)+1)/2;\n off = -vox.*orig;\n M = [vox(1) 0 0 off(1)\n\t\t 0 vox(2) 0 off(2)\n\t\t 0 0 vox(3) off(3)\n\t\t 0 0 0 1];\n\t\tspm_get_space(P(i,:),M);\n\t\tspm_progress_bar('Set',i);\n\tend;\n\tspm_progress_bar('Clear');\n\ttmp = spm_get_space([st.vols{1}.fname ',' num2str(st.vols{1}.n)]);\n\tif sum((tmp(:)-st.vols{1}.mat(:)).^2) > 1e-8,\n\t\tspm_image('init',st.vols{1}.fname);\n\tend;\n\treturn;\nend;\n\nif strcmp(op,'update_info'),\n\t% Modify the positional information in the right hand panel.\n\t%-----------------------------------------------------------------------\n\tmat = st.vols{1}.premul*st.vols{1}.mat;\n\tZ = spm_imatrix(mat);\n\tZ = Z(7:9);\n\n\tset(st.posinf.z,'String', sprintf('%.3g x %.3g x %.3g', Z));\n\n\tO = mat\\[0 0 0 1]'; O=O(1:3)';\n\tset(st.posinf.o, 'String', sprintf('%.3g %.3g %.3g', O));\n\n\tR = spm_imatrix(mat);\n\tR = spm_matrix([0 0 0 R(4:6)]);\n\tR = R(1:3,1:3);\n\n\ttmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(1,1:3)); tmp2(tmp2=='+') = ' ';\n\tset(st.posinf.m1, 'String', tmp2);\n\ttmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(2,1:3)); tmp2(tmp2=='+') = ' ';\n\tset(st.posinf.m2, 'String', tmp2);\n\ttmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(3,1:3)); tmp2(tmp2=='+') = ' ';\n\tset(st.posinf.m3, 'String', tmp2);\n\n\ttmp = [[R zeros(3,1)] ; 0 0 0 1]*diag([Z 1])*spm_matrix(-O) - mat;\n\n\tif sum(tmp(:).^2)>1e-6,\n\t\tset(st.posinf.w, 'String', 'Warning: shears involved');\n else\n\t\tset(st.posinf.w, 'String', '');\n\tend;\n\n\treturn;\nend;\n\nif strcmp(op,'reset'),\n\tmy_reset;\nend;\n\nif strcmp(op,'zoom_in'),\n\top = get(st.zoomer,'Value');\n\tif op==1,\n\t\tspm_orthviews('resolution',1);\n\t\tspm_orthviews('MaxBB');\n else\n\t\tvx = sqrt(sum(st.Space(1:3,1:3).^2));\n\t\tvx = vx.^(-1);\n\t\tpos = spm_orthviews('pos');\n\t\tpos = st.Space\\[pos ; 1];\n\t\tpos = pos(1:3)';\n\t\tif op == 2, st.bb = [pos-80*vx ; pos+80*vx] ; spm_orthviews('resolution',1);\n\t\telseif op == 3, st.bb = [pos-40*vx ; pos+40*vx] ; spm_orthviews('resolution',.5);\n\t\telseif op == 4, st.bb = [pos-20*vx ; pos+20*vx] ; spm_orthviews('resolution',.25);\n\t\telseif op == 5, st.bb = [pos-10*vx ; pos+10*vx] ; spm_orthviews('resolution',.125);\n else st.bb = [pos- 5*vx ; pos+ 5*vx] ; spm_orthviews('resolution',.125);\n\t\tend;\n\tend;\n\treturn;\nend;\n\nif strcmp(op,'init'),\nfg = spm_figure('GetWin','Graphics');\nif isempty(fg), error('Can''t create graphics window'); end\nspm_figure('Clear','Graphics');\n\nP = varargin{1};\nif ischar(P), P = spm_vol(P); end;\nP = P(1);\n\nspm_orthviews('Reset');\nspm_orthviews('Image', P, [0.0 0.45 1 0.55]);\nif isempty(st.vols{1}), return; end;\n\nspm_orthviews('MaxBB');\nst.callback = 'spm_image(''shopos'');';\n\nst.B = [0 0 0 0 0 0 1 1 1 0 0 0];\n\n% locate Graphics window and clear it\n%-----------------------------------------------------------------------\nWS = spm('WinScale');\n\n% Widgets for re-orienting images.\n%-----------------------------------------------------------------------\nuicontrol(fg,'Style','Frame','Position',[60 25 200 325].*WS,'DeleteFcn','spm_image(''reset'');');\nuicontrol(fg,'Style','Text', 'Position',[75 220 100 016].*WS,'String','right {mm}');\nuicontrol(fg,'Style','Text', 'Position',[75 200 100 016].*WS,'String','foward {mm}');\nuicontrol(fg,'Style','Text', 'Position',[75 180 100 016].*WS,'String','up {mm}');\nuicontrol(fg,'Style','Text', 'Position',[75 160 100 016].*WS,'String','pitch {rad}');\nuicontrol(fg,'Style','Text', 'Position',[75 140 100 016].*WS,'String','roll {rad}');\nuicontrol(fg,'Style','Text', 'Position',[75 120 100 016].*WS,'String','yaw {rad}');\nuicontrol(fg,'Style','Text', 'Position',[75 100 100 016].*WS,'String','resize {x}');\nuicontrol(fg,'Style','Text', 'Position',[75 80 100 016].*WS,'String','resize {y}');\nuicontrol(fg,'Style','Text', 'Position',[75 60 100 016].*WS,'String','resize {z}');\n\nuicontrol(fg,'Style','edit','Callback','spm_image(''repos'',1)','Position',[175 220 065 020].*WS,'String','0','ToolTipString','translate');\nuicontrol(fg,'Style','edit','Callback','spm_image(''repos'',2)','Position',[175 200 065 020].*WS,'String','0','ToolTipString','translate');\nuicontrol(fg,'Style','edit','Callback','spm_image(''repos'',3)','Position',[175 180 065 020].*WS,'String','0','ToolTipString','translate');\nuicontrol(fg,'Style','edit','Callback','spm_image(''repos'',4)','Position',[175 160 065 020].*WS,'String','0','ToolTipString','rotate');\nuicontrol(fg,'Style','edit','Callback','spm_image(''repos'',5)','Position',[175 140 065 020].*WS,'String','0','ToolTipString','rotate');\nuicontrol(fg,'Style','edit','Callback','spm_image(''repos'',6)','Position',[175 120 065 020].*WS,'String','0','ToolTipString','rotate');\nuicontrol(fg,'Style','edit','Callback','spm_image(''repos'',7)','Position',[175 100 065 020].*WS,'String','1','ToolTipString','zoom');\nuicontrol(fg,'Style','edit','Callback','spm_image(''repos'',8)','Position',[175 80 065 020].*WS,'String','1','ToolTipString','zoom');\nuicontrol(fg,'Style','edit','Callback','spm_image(''repos'',9)','Position',[175 60 065 020].*WS,'String','1','ToolTipString','zoom');\n\nuicontrol(fg,'Style','Pushbutton','String','Reorient images...','Callback','spm_image(''reorient'')',...\n 'Position',[70 35 125 020].*WS,'ToolTipString','modify position information of selected images');\n\nuicontrol(fg,'Style','Pushbutton','String','Reset...','Callback','spm_image(''resetorient'')',...\n 'Position',[195 35 55 020].*WS,'ToolTipString','reset orientations of selected images');\n\n% Crosshair position\n%-----------------------------------------------------------------------\nuicontrol(fg,'Style','Frame','Position',[70 250 180 90].*WS);\nuicontrol(fg,'Style','Text', 'Position',[75 320 170 016].*WS,'String','Crosshair Position');\nuicontrol(fg,'Style','PushButton', 'Position',[75 316 170 006].*WS,...\n\t'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');\n% uicontrol(fg,'Style','PushButton', 'Position',[75 315 170 020].*WS,'String','Crosshair Position',...\n%\t'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');\nuicontrol(fg,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:');\nuicontrol(fg,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:');\nuicontrol(fg,'Style','Text', 'Position',[75 255 65 020].*WS,'String','Intensity:');\n\nst.mp = uicontrol(fg,'Style','edit', 'Position',[110 295 135 020].*WS,'String','','Callback','spm_image(''setposmm'')','ToolTipString','move crosshairs to mm coordinates');\nst.vp = uicontrol(fg,'Style','edit', 'Position',[110 275 135 020].*WS,'String','','Callback','spm_image(''setposvx'')','ToolTipString','move crosshairs to voxel coordinates');\nst.in = uicontrol(fg,'Style','Text', 'Position',[140 255 85 020].*WS,'String','');\n\n% General information\n%-----------------------------------------------------------------------\nuicontrol(fg,'Style','Frame','Position',[305 25 280 325].*WS);\nuicontrol(fg,'Style','Text','Position' ,[310 330 50 016].*WS,...\n\t'HorizontalAlignment','right', 'String', 'File:');\nuicontrol(fg,'Style','Text','Position' ,[360 330 210 016].*WS,...\n\t'HorizontalAlignment','left', 'String', spm_str_manip(st.vols{1}.fname,'k25'),'FontWeight','bold');\nuicontrol(fg,'Style','Text','Position' ,[310 310 100 016].*WS,...\n\t'HorizontalAlignment','right', 'String', 'Dimensions:');\nuicontrol(fg,'Style','Text','Position' ,[410 310 160 016].*WS,...\n\t'HorizontalAlignment','left', 'String', sprintf('%d x %d x %d', st.vols{1}.dim(1:3)),'FontWeight','bold');\nuicontrol(fg,'Style','Text','Position' ,[310 290 100 016].*WS,...\n\t'HorizontalAlignment','right', 'String', 'Datatype:');\nuicontrol(fg,'Style','Text','Position' ,[410 290 160 016].*WS,...\n\t'HorizontalAlignment','left', 'String', spm_type(st.vols{1}.dt(1)),'FontWeight','bold');\nuicontrol(fg,'Style','Text','Position' ,[310 270 100 016].*WS,...\n\t'HorizontalAlignment','right', 'String', 'Intensity:');\nstr = 'varied';\nif size(st.vols{1}.pinfo,2) == 1,\n\tif st.vols{1}.pinfo(2),\n\t\tstr = sprintf('Y = %g X + %g', st.vols{1}.pinfo(1:2)');\n else\n\t\tstr = sprintf('Y = %g X', st.vols{1}.pinfo(1)');\n\tend;\nend;\nuicontrol(fg,'Style','Text','Position' ,[410 270 160 016].*WS,...\n\t'HorizontalAlignment','left', 'String', str,'FontWeight','bold');\n\nif isfield(st.vols{1}, 'descrip'),\n\tuicontrol(fg,'Style','Text','Position' ,[310 250 260 016].*WS,...\n\t'HorizontalAlignment','center', 'String', st.vols{1}.descrip,'FontWeight','bold');\nend;\n\n\n% Positional information\n%-----------------------------------------------------------------------\nmat = st.vols{1}.premul*st.vols{1}.mat;\nZ = spm_imatrix(mat);\nZ = Z(7:9);\nuicontrol(fg,'Style','Text','Position' ,[310 210 100 016].*WS,...\n\t'HorizontalAlignment','right', 'String', 'Vox size:');\nst.posinf = struct('z',uicontrol(fg,'Style','Text','Position' ,[410 210 160 016].*WS,...\n\t'HorizontalAlignment','left', 'String', sprintf('%.3g x %.3g x %.3g', Z),'FontWeight','bold'));\n\nO = mat\\[0 0 0 1]'; O=O(1:3)';\nuicontrol(fg,'Style','Text','Position' ,[310 190 100 016].*WS,...\n\t'HorizontalAlignment','right', 'String', 'Origin:');\nst.posinf.o = uicontrol(fg,'Style','Text','Position' ,[410 190 160 016].*WS,...\n\t'HorizontalAlignment','left', 'String', sprintf('%.3g %.3g %.3g', O),'FontWeight','bold');\n\nR = spm_imatrix(mat);\nR = spm_matrix([0 0 0 R(4:6)]);\nR = R(1:3,1:3);\n\nuicontrol(fg,'Style','Text','Position' ,[310 170 100 016].*WS,...\n\t'HorizontalAlignment','right', 'String', 'Dir Cos:');\ntmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(1,1:3)); tmp2(tmp2=='+') = ' ';\nst.posinf.m1 = uicontrol(fg,'Style','Text','Position' ,[410 170 160 016].*WS,...\n\t'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');\ntmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(2,1:3)); tmp2(tmp2=='+') = ' ';\nst.posinf.m2 = uicontrol(fg,'Style','Text','Position' ,[410 150 160 016].*WS,...\n\t'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');\ntmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(3,1:3)); tmp2(tmp2=='+') = ' ';\nst.posinf.m3 = uicontrol(fg,'Style','Text','Position' ,[410 130 160 016].*WS,...\n\t'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');\n\ntmp = [[R zeros(3,1)] ; 0 0 0 1]*diag([Z 1])*spm_matrix(-O) - mat;\nst.posinf.w = uicontrol(fg,'Style','Text','Position' ,[310 110 260 016].*WS,...\n\t'HorizontalAlignment','center', 'String', '','FontWeight','bold');\nif sum(tmp(:).^2)>1e-8,\n\tset(st.posinf.w, 'String', 'Warning: shears involved');\nend;\n\n% Assorted other buttons.\n%-----------------------------------------------------------------------\nuicontrol(fg,'Style','Frame','Position',[310 30 270 70].*WS);\nst.zoomer = uicontrol(fg,'Style','popupmenu' ,'Position',[315 75 125 20].*WS,...\n\t'String',char('Full Volume','160x160x160mm','80x80x80mm','40x40x40mm','20x20x20mm','10x10x10mm'),...\n\t'Callback','spm_image(''zoom_in'')','ToolTipString','zoom in by different amounts');\nc = 'if get(gco,''Value'')==1, spm_orthviews(''Space''), else, spm_orthviews(''Space'', 1);end;spm_image(''zoom_in'')';\nuicontrol(fg,'Style','popupmenu' ,'Position',[315 55 125 20].*WS,...\n\t'String',char('World Space','Voxel Space'),...\n\t'Callback',c,'ToolTipString','display in aquired/world orientation');\nc = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;';\nuicontrol(fg,'Style','togglebutton','Position',[450 75 125 20].*WS,...\n\t'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs');\nuicontrol(fg,'Style','popupmenu' ,'Position',[450 55 125 20].*WS,...\n\t'String',char('NN interp','bilin interp','sinc interp'),...\n\t'Callback','tmp_ = [0 1 -4];spm_orthviews(''Interp'',tmp_(get(gco,''Value'')))',...\n\t'Value',2,'ToolTipString','interpolation method for displaying images');\nst.win = uicontrol(fg,'Style','popupmenu','Position',[315 35 125 20].*WS,...\n\t'String',char('Auto Window','Manual Window'),'Callback','spm_image(''window'');','ToolTipString','range of voxel intensities displayed');\n% uicontrol(fg,'Style','pushbutton','Position',[315 35 125 20].*WS,...\n% \t'String','Window','Callback','spm_image(''window'');','ToolTipString','range of voxel intensities % displayed');\nst.blobber = uicontrol(fg,'Style','pushbutton','Position',[450 35 125 20].*WS,...\n\t'String','Add Blobs','Callback','spm_image(''addblobs'');','ToolTipString','superimpose activations');\nend;\nreturn;\n\n\nfunction my_reset\nspm_orthviews('reset');\nspm_figure('Clear','Graphics');\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "bst_message_window.m", "ext": ".m", "path": "spm5-master/bst_message_window.m", "size": 17952, "source_encoding": "utf_8", "md5": "351c51b02858e087e1bb53dae05b3986", "text": "function varargout = bst_message_window(varargin)\n%BST_MESSAGE_WINDOW - Application M-file for bst_message_window.fig, with NON CALLBACKS\n% function varargout = bst_message_window(varargin)\n% FIG = BST_MESSAGE_WINDOW launch bst_message_window GUI.\n% BST_MESSAGE_WINDOW('callback_name', ...) invoke the named callback.\n% NON CALLBACKS:\n% bst_message_window(cellstr) appends cell array of strings cellstr to window \n% bst_message_window('append',str) appends string or cell of strings to window\n% bst_message_window(str) will also append string, unless it is a valid function call\n% bst_message_window('wrap',str) will wrap string or cell of strings to the window\n% bst_message_window('unique',str) will wrap string or cell of strings to a unique window,\n% bst_message_window('process',str) send str to the ProcessLauncher GUI (see also bst_ProcessLauncher)\n% returning the handle to the window, i.e. it won't go to the message window, but rather\n% its own message window.\n% bst_message_window('overwrite',str) overwrites the last line with the new string\n% \n% bst_message_window('close') removes the window, otherise the CloseRequestFcn executes\n% If window does not exist, 'append' will open it\n\n% ---------------------- 27-Jun-2005 10:43:34 -----------------------\n% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------\n%\n% CATEGORY: GUI and Related\n%\n% Alphabetical list of external functions (non-Matlab):\n% toolbox\\bst_color_scheme.m\n% toolbox\\bst_layout.m\n% toolbox\\bst_message_window.m NOTE: Routine calls itself explicitly\n%\n% Subfunctions in this file, in order of occurrence in file:\n% varargout = process(str,fig);\n% varargout = append(str,fig);\n% varargout = unique(str);\n% varargout = wrap(str,fig);\n% varargout = overwrite(rep_str,fig);\n% varargout = close();\n% varargout = Messages_Callback(h, eventdata, handles, varargin)\n% varargout = clear_selected_Callback(h, eventdata, handles, varargin)\n% varargout = clear_all_Callback(h, eventdata, handles, varargin)\n% varargout = BrainStormMessages_CloseRequestFcn(h, eventdata, handles, varargin)\n% varargout = BrainStormMessages_ResizeFcn(h, eventdata, handles, varargin)\n%\n% Application data and their calls in this file:\n% 'BrainStormMessageWindow'\n% 'MAXLength'\n% 'TileType'\n% \n% setappdata(0,'BrainStormMessageWindow',fig);\n% setappdata(fig,'MAXLength',200);\n% setappdata(fig,'TileType','M');\n% setappdata(fig,'TileType','T');\n% \n% MAXLength = getappdata(fig,'MAXLength');\n% delete(getappdata(0,'BrainStormMessageWindow'));\n% fig = getappdata(0,'BrainStormMessageWindow');\n% if(~ishandle(getappdata(0,'BrainStormMessageWindow')))\n%\n% Figure Files opened by this function:\n% mfilename\n%\n% Format of strings below: Type:Style:Tag, \"String\", CallBack Type and Call\n% callback is _Callback by Matlab default\n%\n% Callbacks by figure bst_message_window.fig\n% figure::BrainStormMessages \"\" uses ResizeFcn for \n% uicontrol:listbox:Messages \"BrainStorm Message Window\" uses Callback for \n%\n% At Check-in: $Author: Mosher $ $Revision: 28 $ $Date: 6/27/05 8:59a $\n%\n% This software is part of BrainStorm Toolbox Version 27-June-2005 \n% \n% Principal Investigators and Developers:\n% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,\n% University of Southern California, Los Angeles, CA\n% ** John C. Mosher, PhD, Biophysics Group,\n% Los Alamos National Laboratory, Los Alamos, NM\n% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,\n% CNRS, Hopital de la Salpetriere, Paris, France\n% \n% See BrainStorm website at http://neuroimage.usc.edu for further information.\n% \n% Copyright (c) 2005 BrainStorm by the University of Southern California\n% This software distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPL\n% license can be found at http://www.gnu.org/copyleft/gpl.html .\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n% ------------------------ 27-Jun-2005 10:43:34 -----------------------\n\n\n% ----------------- Change History ------------------------\n% JCM 27 Feb 2002 changed propertyname to BrainStormMessageWindow, handled \"catch\" for string input\n% JCM 3 May 2002 added 'wrap' and 'overwrite' options\n% JCM 10 May 2002 changed CloseRequestFcn to allow non-modal closing.\n% JCM 15 May 2002 updated 'overwrite' to allow multiple lines of overwrite\n% SB 15 Oct 2002 when BrainStorm GUIs are closed (e.g. when using command-line BrainStorm)\n% bst_message_window uses the basic DISP command to display info in \n% Matlab's command window\n% JCM 29 Oct 2002 Preferences should not be erased. Test for presence of taskbar, \n% using getappdata(0,'BrainStormTaskbar'); Fixed MAXLength use, should be\n% an appdata in the message figure, also rolls the last MAXLength lines,\n% rather than clearing. All cases now handle non-gui mode.\n% Redid message window to be along the bottom of the screen.\n% JCM 13 May 2003 Moved message window buttons to new layout_manager, made window\n% compatible with layout manager\n% JCM 09 Jun 2003 Added \"unique\" function to allow use for a convenient message and information window\n% JCM 26 Jan 2005 Felix fixed rep_str typo in overwrite function\n% SB 08 Feb 2005 Added the 'process' option: \n% -> bst_message_window('process',str): send str to the ProcessLauncher GUI (see also bst_ProcessLauncher)\n% JCM 08-Jun-2005 Set fonts in the creation and resize functions to be\n% fixed 8 point size,after running the bst_color_scheme function.\n% ----------------------------------------------------------\n\n% Last Modified by GUIDE v2.5 08-Jun-2005 15:20:15\n\nif nargin == 0 % LAUNCH GUI\n \n \n fig = openfig(mfilename,'reuse');\n \n % Use system color scheme for figure:\n set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));\n \n % Generate a structure of handles to pass to callbacks, and store it. \n handles = guihandles(fig);\n guidata(fig, handles);\n \n if nargout > 0\n varargout{1} = fig;\n end\n \n % BrainStorm specific code here\n bst_color_scheme(fig);\n set(handles.Messages,'fontname','FixedWidth'); % good for tables\n % lock in font units and size to keep from scaling\n set(handles.Messages,'fontunits','points','fontsize',8);\n \n setappdata(fig,'TileType','M'); % message window\n bst_layout('align',fig);\n \n setappdata(0,'BrainStormMessageWindow',fig); % set the handle in the taskbar application data\n \n % ------ SET MAXIMUM NUMBER OF LINES TO BE DISPLAYED ------------------\n setappdata(fig,'MAXLength',200); % Maximum number of lines to be displayed in the message window.\n % too many lines significantly slows down all BsT processes.\n % JCM changed 29 Oct to roll the last 200 lines, not clear.\n \nelseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK\n \n try \n if (nargout)\n [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard\n else\n feval(varargin{:}); % FEVAL switchyard\n end\n catch\n % string was not a valid function call, treat as a string\n try\n append(varargin); % try appending the string\n catch\n disp(lasterr);\n end\n end\n \nelseif iscell(varargin{1}) % input is a cell array\n \n append(varargin{1});\n \nend\n\n\n% ---------------- subfunctions -----------------\n\n% --------------------------------------------------------------------\nfunction varargout = process(str,fig);\n% Send messages to ProcessLauncher GUI\nprocessGUI = findobj(0,'type','figure','tag','bst_ProcessLauncher');\nHprocessGUI = guihandles(processGUI);\nset(HprocessGUI.dProgressReport,'String',str)\n\n% --------------------------------------------------------------------\nfunction varargout = append(str,fig);\n% Call as bst_message_window('append',str)\n% alternatively, if string is unrecognized command, switchyard will call this subfunction\n\nif ischar(str),\n str = {str}; % convert to cell array\nend\n\n% Test whether user is calling BrainStorm routines from command line function calls or GUIs.\n\nif ~isappdata(0,'BrainStormTaskbar')\n % The taskbar does not exists, assume we are in command line mode\n for i = 1:length(str),\n disp(str{i});\n end\n return % break away\nend\n \n% else we are in GUI mode\n\n% get the handle to the message window\nif(~isappdata(0,'BrainStormMessageWindow')), % missing\n bst_message_window; % create it\nend\nif(~ishandle(getappdata(0,'BrainStormMessageWindow')))\n bst_message_window; % invalid handle, create it again\nend\n\n% append a string to the message window. str is either string or cell of strings.\nif(~exist('fig','var')), % caller did not give fig handle (default)\n fig = getappdata(0,'BrainStormMessageWindow');\nend\n\nhandles = guidata(fig); % handles in that figure\n\nMAXLength = getappdata(fig,'MAXLength');\n\nlenstr = length(str); % number of lines being added\n\noldstr = get(handles.Messages,'string');\nif ischar(oldstr)\n oldstr = {oldstr}; % convert to cell array\nend\n\noldstr(end+[1:lenstr]) = str; % add new strings to end of old string\n\nndx = [-MAXLength:0]+length(oldstr); % last MAXLength lines\n\n% ndx may be negative, if length shorter than MAXLength\nndx = ndx(ndx > 0); % keep only the positive ones\n \n%trim\noldstr = oldstr(ndx);\n\n% select all of the new message for visibility to the user\nset(handles.Messages,'string',oldstr,...\n 'val',length(oldstr)+[(1-lenstr):0],...\n 'listboxtop',length(oldstr)); % put in\n\nfigure(fig); % bring to the front\n\ndrawnow\n\nif nargout > 0\n varargout{1} = fig;\nend\n\n\n\n% -------------------------------------------------------------------\nfunction varargout = unique(str);\n% wrap text to a unique message window, not the main window\n% JCM 9-Jun-2003 creating a variant of the message window\n\nfig = openfig(mfilename,'new'); % new unique filename\n\n% Use system color scheme for figure:\nset(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));\n\n% Generate a structure of handles to pass to callbacks, and store it. \nhandles = guihandles(fig);\nguidata(fig, handles);\n\nif nargout > 0\n varargout{1} = fig;\nend\n\n% BrainStorm specific code here\nbst_color_scheme(fig);\nset(handles.Messages,'fontname','FixedWidth'); % good for tables\nsetappdata(fig,'TileType','T'); % tile\nbst_layout('align',fig,1,2,1); % default action, can be set in calling routine as well\n\n% customize for a unique message window\nset(fig,'Name','Information','Tag','Information','CloseRequestFcn','closereq','ResizeFcn',[]);\noverwrite(sprintf('Information Message %s',datestr(now)),fig); % replace the \"BrainStorm Message Window\" line\n\n% ------ SET MAXIMUM NUMBER OF LINES TO BE DISPLAYED ------------------\nsetappdata(fig,'MAXLength',200); % Maximum number of lines to be displayed in the message window.\n% too many lines significantly slows down all BsT processes.\n% JCM changed 29 Oct to roll the last 200 lines, not clear.\n\nwrap(str,fig); % now wrap the text to just this unique fig\n\n\n\n% --------------------------------------------------------------------\nfunction varargout = wrap(str,fig);\n% called as mfilename('wrap',str), wrap string to the window\n\nif ischar(str),\n str = {str}; % convert to cell for consistent handling\nend\n\nif ~isappdata(0,'BrainStormTaskbar')\n % The taskbar does not exists, assume we are in command line mode\n for i = 1:length(str),\n disp(str{i});\n end\n return % break away\nend\n\n% else we are in GUI Mode\n% get the handle to the message window\n\nif(~isappdata(0,'BrainStormMessageWindow')), % missing\n bst_message_window; % create it\nend\nif(~exist('fig','var')), % user did not give as input to this function (default)\n fig = getappdata(0,'BrainStormMessageWindow');\nend\n\nhandles = guidata(fig); % handles in that figure\n\nif(0), % deprecated, user may send cell array of strings\n % first convert str into one long message string, with proper spaces\n msg_str = [];\n for i = 1:length(str),\n msg_str = [msg_str str{i}];\n if(~strcmp(msg_str(end),' ')),\n msg_str(end+1) = ' ';\n end\n end\n msg_str(end) = []; % remove last space\nelse\n msg_str = str; % don't alter\nend\n\n% wrap the text to the message window\n% textwrap in R12.1 is a little too wide\nmesPos = get(handles.Messages,'position');\nmesWidth = mesPos(3); % current width\nset(handles.Messages,'position',[mesPos(1:2) mesWidth*.95 mesPos(4)]); % slightly narrower\noutstring = textwrap(handles.Messages,msg_str); % wrap to columns\nset(handles.Messages,'position',mesPos); % original size\n\nappend(outstring,fig);\n\nif nargout > 0\n varargout{1} = fig;\nend\n\n\n\n% --------------------------------------------------------------------\nfunction varargout = overwrite(rep_str,fig);\n% Overwrite the last lines of the message window with cell array of rep_str\n% if rep_str is a string, overwrite just the last line.\n% Useful for updating a \"Processing . . .\" with a \"Done\"\n% or a pseudo waitbar,\n% bst_message_window('Wait: 1 of 10')\n% for i = 2:10,bst_message_window('overwrite',sprintf('Wait: %.0f of 10',i)),,end\n\nif(ischar(rep_str)),\n rep_str = {rep_str}; % make cell for consistent handling\nend\n\n\nif ~isappdata(0,'BrainStormTaskbar')\n % The taskbar does not exists, assume we are in command line mode\n for i = 1:length(rep_str),\n disp(rep_str{i});\n end\n return % break away\nend\n\n\nNumLines = length(rep_str); % how many lines to replace\n\n% get the handle to the message window\nif(~isappdata(0,'BrainStormMessageWindow')), % missing\n bst_message_window; % create it\nend\n\nif(~exist('fig','var')), % user did not give as input to this function (default)\n fig = getappdata(0,'BrainStormMessageWindow');\nend\nhandles = guidata(fig); % handles in that figure\n\nstr = get(handles.Messages,'string'); %existing strings\n\nif(ischar(str)),\n str = {str}; % make cell for consistent handling\nend\n\nif(length(str) >= NumLines),\n str([(1-NumLines):0]+end) = rep_str;\nelse\n % there are not enough lines in the display, just append\n str(end+[1:NumLines]) = rep_str; \nend\n\nset(handles.Messages,...\n 'string',str,'listboxtop',...\n length(str),'val',length(str)+[(1-NumLines):0]); % put in, with new strings clearly showing\n\nif nargout > 0\n varargout{1} = fig;\nend\n\n\n\n\n% --------------------------------------------------------------------\nfunction varargout = close(); \n% close the message window. Otherwise, the CloseRequestFcn will execute\ndelete(getappdata(0,'BrainStormMessageWindow')); % close the window\nrmappdata(0,'BrainStormMessageWindow'); % clear the application data\n\n\n% -------------- Callback routines -----------------------\n\n% --------------------------------------------------------------------\nfunction varargout = Messages_Callback(h, eventdata, handles, varargin)\n% double clicking will remove a line. Otherwise, no effect\n% doulbe right clicking will remove lots of highlighted lines\n\nstatus = get(handles.BrainStormMessages,'SelectionType');\nswitch status\ncase 'normal' % do nothing\ncase 'open' % user double clicked\n clear_selected_Callback(h,eventdata,handles,varargin);\nend\n\n\n\n\n\n% --------------------------------------------------------------------\nfunction varargout = clear_selected_Callback(h, eventdata, handles, varargin)\n% clear the selected messages, keep the view stable\n\nval = get(handles.Messages,'val'); % vector of lines to delete\nstr = get(handles.Messages,'string'); %existing strings\nlistboxtop = get(handles.Messages,'listboxtop'); %what is showing at the top of window\n\nstr(val) = []; % remove the existing strings\nval = val(1); % set to last string deleted\nval = min(val,length(str)); % in acceptable range\n\nlistboxtop = min(listboxtop,val); % in acceptable range\nlistboxtop = min(listboxtop,length(str)); % in acceptable range\n\nif(length(str) == 0),\n set(handles.Messages,'val',1,'ListBoxTop',1,'string',{'BrainStorm Message Window'})\nelse\n set(handles.Messages,'val',val,'string',str,'listboxtop',listboxtop);\nend\n\n\n\n\n\n% --------------------------------------------------------------------\nfunction varargout = clear_all_Callback(h, eventdata, handles, varargin)\n\n% no longer a button for this 13 May 2003\n% can instead highlight lots of lines, then double right click to remove them\nButtonName = questdlg('Clear all lines?','Message Window','Yes','No','No');\n\nswitch ButtonName\ncase 'Yes'\n set(handles.Messages,'val',1,'ListBoxTop',1,'string',{'BrainStorm Message Window'})\nend\n\n\n\n\n\n% --------------------------------------------------------------------\nfunction varargout = BrainStormMessages_CloseRequestFcn(h, eventdata, handles, varargin)\n\n% since this window now automatically opens when needed, this forced closure\n% is no longer really necessary. JCM 13-May-2002\n\nif(0), % deprecated code\n str = {'','This BrainStorm message window should stay open.',''}; \n bst_message_window('append',str);\n \n ButtonName = questdlg('Close the message window?','Message Window','Yes','No','No');\n \n switch ButtonName\n case 'Yes'\n bst_message_window('close');\n end\nelse % newer code, non-modal closing\n bst_message_window('close');\n disp(' ')\n disp('Generally, the BrainStorm Message Window should remain open.')\n disp('Message window closed.')\nend\n\n\n\n% --------------------------------------------------------------------\nfunction varargout = BrainStormMessages_ResizeFcn(h, eventdata, handles, varargin)\n\n% want to keep the fonts at the same size\n\nbst_color_scheme(handles.BrainStormMessages);\n\nset(handles.Messages,'fontunits','points');\nset(handles.Messages,'fontsize',8);\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_transverse.m", "ext": ".m", "path": "spm5-master/spm_transverse.m", "size": 14752, "source_encoding": "utf_8", "md5": "235f415df5b92c21eb90a49c70ebbcbb", "text": "function spm_transverse(varargin)\n% Rendering of regional effects [SPM{T/F}] on transverse sections\n% FORMAT spm_transverse('set',SPM,hReg)\n% FORMAT spm_transverse('setcoords',xyzmm)\n% FORMAT spm_transverse('clear')\n%\n% SPM - structure containing SPM, distribution & filtering details\n% about the excursion set (xSPM)\n% - required fields are:\n% .Z - minimum of n Statistics {filtered on u and k}\n% .STAT - distribution {Z, T, X or F} \n% .u - height threshold\n% .XYZ - location of voxels {voxel coords}\n% .iM - mm -> voxels matrix\n% .VOX - voxel dimensions {mm}\n% .DIM - image dimensions {voxels}\n%\n% hReg - handle of MIP XYZ registry object (see spm_XYZreg for details)\n%\n% spm_transverse automatically updates its co-ordinates from the\n% registry, but clicking on the slices has no effect on the registry.\n% i.e., the updating is one way only.\n%\n% See also: spm_getSPM\n%_______________________________________________________________________\n%\n% spm_transverse is called by the SPM results section and uses\n% variables in SPM and SPM to create three transverse sections though a\n% background image. Regional foci from the selected SPM{T/F} are\n% rendered on this image.\n%\n% Although the SPM{.} adopts the neurological convention (left = left)\n% the rendered images follow the same convention as the original data.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Karl Friston & John Ashburner\n% $Id: spm_transverse.m 212 2005-08-19 10:50:18Z will $\n\n\nswitch lower(varargin{1})\n\n\tcase 'set'\n\t% draw slices\n\t%---------------------------------------------------------------\n\n\tinit(varargin{2},varargin{3});\n\n\tcase 'setcoords'\n\t% reposition\n\t%---------------------------------------------------------------\n disp('Reposition');\n\n\tcase 'clear'\n\t% clear\n\t%---------------------------------------------------------------\n\tclear_global;\nend;\nreturn;\n\n\n\nfunction init(SPM,hReg)\n\n%-Get figure handles\n%-----------------------------------------------------------------------\nFgraph = spm_figure('GetWin','Graphics');\n\n\n%-Get the image on which to render\n%-----------------------------------------------------------------------\nspms = spm_select(1,'image','Select image for rendering on');\nspm('Pointer','Watch');\n\n%-Delete previous axis and their pagination controls (if any)\n%-----------------------------------------------------------------------\nspm_results_ui('Clear',Fgraph);\n\nglobal transv\ntransv = struct('blob',[],'V',spm_vol(spms),'h',[],'hReg',hReg,'fig',Fgraph);\ntransv.blob = struct('xyz', round(SPM.XYZ), 't',SPM.Z, 'dim',SPM.DIM(1:3),...\n\t 'iM',SPM.iM,...\n\t\t 'vox', sqrt(sum(SPM.M(1:3,1:3).^2)), 'u', SPM.u);\n\n%-Get current location and convert to pixel co-ordinates\n%-----------------------------------------------------------------------\nxyzmm = spm_XYZreg('GetCoords',transv.hReg);\nxyz = round(transv.blob.iM(1:3,:)*[xyzmm; 1]);\n\n% extract data from SPM [at one plane separation]\n% and get background slices\n%----------------------------------------------------------------------\ndim = ceil(transv.blob.dim(1:3)'.*transv.blob.vox);\nA = transv.blob.iM*transv.V.mat;\nhld = 0;\n\nzoomM = inv(spm_matrix([0 0 -1 0 0 0 transv.blob.vox([1 2]) 1]));\nzoomM1 = spm_matrix([0 0 0 0 0 0 transv.blob.vox([1 2]) 1]);\n\nQ = find(abs(transv.blob.xyz(3,:) - xyz(3)) < 0.5);\nT2 = full(sparse(transv.blob.xyz(1,Q),transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));\nT2 = spm_slice_vol(T2,zoomM,dim([1 2]),[hld NaN]);\nQ = find(T2==0) ; T2(Q) = NaN;\nD = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3);0 0 0 1]*A;\nD2 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);\nmaxD = max([max(D2(:)) eps]);\nminD = min([min(D2(:)) eps]);\n\nif transv.blob.dim(3) > 1\n\n\tQ = find(abs(transv.blob.xyz(3,:) - xyz(3)+1) < 0.5);\n\tT1 = full(sparse(transv.blob.xyz(1,Q),...\n\t\t\ttransv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));\n\tT1 = spm_slice_vol(T1,zoomM,dim([1 2]),[hld NaN]);\n\tQ = find(T1==0) ; T1(Q) = NaN;\n\tD = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)+1;0 0 0 1]*A;\n\tD1 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);\n\tmaxD = max([maxD ; D1(:)]);\n\tminD = min([minD ; D1(:)]);\n\n\tQ = find(abs(transv.blob.xyz(3,:) - xyz(3)-1) < 0.5);\n\tT3 = full(sparse(transv.blob.xyz(1,Q),...\n\t\t\ttransv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));\n\tT3 = spm_slice_vol(T3,zoomM,dim([1 2]),[hld NaN]);\n\tQ = find(T3==0) ; T3(Q) = NaN;\n\tD = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)-1;0 0 0 1]*A;\n\tD3 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);\n\tmaxD = max([maxD ; D3(:)]);\n\tminD = min([minD ; D3(:)]);\nend\n\nmx = max([max(T2(:)) eps]);\nmn = min([min(T2(:)) 0]);\nD2 = (D2-minD)/(maxD-minD);\nif transv.blob.dim(3) > 1,\n\tD1 = (D1-minD)/(maxD-minD);\n\tD3 = (D3-minD)/(maxD-minD);\n\tmx = max([mx ; T1(:) ; T3(:) ; eps]);\n\tmn = min([mn ; T1(:) ; T3(:) ; 0]);\nend;\n\n%-Configure {128 level} colormap\n%-----------------------------------------------------------------------\ncmap = get(Fgraph,'Colormap');\nif size(cmap,1) ~= 128\n\tfigure(Fgraph)\n\tspm_figure('Colormap','gray-hot')\n\tcmap = get(Fgraph,'Colormap');\nend\n\nD = length(cmap)/2;\nQ = find(T2(:) > transv.blob.u); T2 = (T2(Q)-mn)/(mx-mn); D2(Q) = 1+1.51/D + T2; T2 = D*D2;\n\nif transv.blob.dim(3) > 1\n Q = find(T1(:) > transv.blob.u); T1 = (T1(Q)-mn)/(mx-mn); D1(Q) = 1+1.51/D + T1; T1 = D*D1;\n Q = find(T3(:) > transv.blob.u); T3 = (T3(Q)-mn)/(mx-mn); D3(Q) = 1+1.51/D + T3; T3 = D*D3;\nend\n\nset(Fgraph,'Units','pixels')\nsiz = get(Fgraph,'Position');\nsiz = siz(3:4);\n\nP = xyz.*transv.blob.vox';\n\n%-Render activation foci on background images\n%-----------------------------------------------------------------------\nif transv.blob.dim(3) > 1\n\tzm = min([(siz(1) - 120)/(dim(1)*3),(siz(2)/2 - 60)/dim(2)]);\n\txo = (siz(1)-(dim(1)*zm*3)-120)/2;\n\tyo = (siz(2)/2 - dim(2)*zm - 60)/2;\n\n\ttransv.h(1) = axes('Units','pixels','Parent',Fgraph,'Position',[20+xo 20+yo dim(1)*zm dim(2)*zm]);\n\ttransv.h(2) = image(rot90(spm_grid(T1)),'Parent',transv.h(1));\n\taxis image; axis off;\n\ttmp = SPM.iM\\[xyz(1:2)' (xyz(3)-1) 1]';\n \n ax=transv.h(1);tpoint=get(ax,'title');\n str=sprintf('z = %0.0fmm',tmp(3));\n\tset(tpoint,'string',str);\n \n\ttransv.h(3) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(1));\n\ttransv.h(4) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(1));\n\n\ttransv.h(5) = axes('Units','pixels','Parent',Fgraph,'Position',[40+dim(1)*zm+xo 20+yo dim(1)*zm dim(2)*zm]);\n\ttransv.h(6) = image(rot90(spm_grid(T2)),'Parent',transv.h(5));\n\taxis image; axis off;\n \n ax=transv.h(5);tpoint=get(ax,'title');\n str=sprintf('z = %0.0fmm',tmp(3));\n\tset(tpoint,'string',str);\n \n transv.h(7) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(5));\n\ttransv.h(8) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(5));\n\n\ttransv.h(9) = axes('Units','pixels','Parent',Fgraph,'Position',[60+dim(1)*zm*2+xo 20+yo dim(1)*zm dim(2)*zm]);\n\ttransv.h(10) = image(rot90(spm_grid(T3)),'Parent',transv.h(9));\n\taxis image; axis off;\n\ttmp = SPM.iM\\[xyz(1:2)' (xyz(3)+1) 1]';\n\n ax=transv.h(9);tpoint=get(ax,'title');\n str=sprintf('z = %0.0fmm',tmp(3));\n\tset(tpoint,'string',str);\n \n\ttransv.h(11) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(9));\n\ttransv.h(12) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(9));\n \n\t% colorbar\n\t%-----------------------------------------------------------------------\n\tq = [80+dim(1)*zm*3+xo 20+yo 20 dim(2)*zm];\n if SPM.STAT=='P'\n str='Effect size';\n else\n str=[SPM.STAT ' value'];\n end\n\ttransv.h(13) = axes('Units','pixels','Parent',Fgraph,'Position',q,'Visible','off');\n\ttransv.h(14) = image([0 mx/32],[mn mx],(1:D)' + D,'Parent',transv.h(13));\n\n ax=transv.h(13);\n tpoint=get(ax,'title');\n set(tpoint,'string',str);\n set(tpoint,'FontSize',9);\n %title(ax,str,'FontSize',9);\n\tset(ax,'XTickLabel',[]);\n axis(ax,'xy');\n\nelse\n\tzm = min([(siz(1) - 80)/dim(1),(siz(2)/2 - 60)/dim(2)]);\n\txo = (siz(1)-(dim(1)*zm)-80)/2;\n\tyo = (siz(2)/2 - dim(2)*zm - 60)/2;\n\n\ttransv.h(1) = axes('Units','pixels','Parent',Fgraph,'Position',[20+xo 20+yo dim(1)*zm dim(2)*zm]);\n\ttransv.h(2) = image(rot90(spm_grid(T2)),'Parent',transv.h(1));\n\taxis image; axis off;\n\ttitle(sprintf('z = %0.0fmm',xyzmm(3)));\n\ttransv.h(3) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(1));\n\ttransv.h(4) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(1));\n \n\t% colorbar\n\t%-----------------------------------------------------------------------\n\tq = [40+dim(1)*zm+xo 20+yo 20 dim(2)*zm];\n\ttransv.h(5) = axes('Units','pixels','Parent',Fgraph,'Position',q,'Visible','off');\n\ttransv.h(6) = image([0 mx/32],[mn mx],(1:D)' + D,'Parent',transv.h(5));\n\tif SPM.STAT=='P'\n str='Effect size';\n else\n str=[SPM.STAT ' value'];\n end\n \n\ttitle(str,'FontSize',9);\n\tset(gca,'XTickLabel',[]);\n axis xy;\n \n \nend;\n\nspm_XYZreg('Add2Reg',transv.hReg,transv.h(1), 'spm_transverse');\n\nfor h=transv.h,\n\tset(h,'DeleteFcn',@clear_global);\nend;\n\n%-Reset pointer\n%-----------------------------------------------------------------------\nspm('Pointer','Arrow')\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction reposition(xyzmm)\nglobal transv\nif ~isstruct(transv), return; end;\n\nspm('Pointer','Watch');\n\n\n%-Get current location and convert to pixel co-ordinates\n%-----------------------------------------------------------------------\n% xyzmm = spm_XYZreg('GetCoords',transv.hReg)\nxyz = round(transv.blob.iM(1:3,:)*[xyzmm; 1]);\n\n% extract data from SPM [at one plane separation]\n% and get background slices\n%----------------------------------------------------------------------\ndim = ceil(transv.blob.dim(1:3)'.*transv.blob.vox);\nA = transv.blob.iM*transv.V.mat;\nhld = 0;\n\nzoomM = inv(spm_matrix([0 0 -1 0 0 0 transv.blob.vox([1 2]) 1]));\nzoomM1 = spm_matrix([0 0 0 0 0 0 transv.blob.vox([1 2]) 1]);\n\nQ = find(abs(transv.blob.xyz(3,:) - xyz(3)) < 0.5);\nT2 = full(sparse(transv.blob.xyz(1,Q),transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));\nT2 = spm_slice_vol(T2,zoomM,dim([1 2]),[hld NaN]);\nQ = find(T2==0) ; T2(Q) = NaN;\nD = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3);0 0 0 1]*A;\nD2 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);\nmaxD = max([max(D2(:)) eps]);\nminD = min([min(D2(:)) 0]);\n\nif transv.blob.dim(3) > 1\n\n\tQ = find(abs(transv.blob.xyz(3,:) - xyz(3)+1) < 0.5);\n\tT1 = full(sparse(transv.blob.xyz(1,Q),...\n\t\t\ttransv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));\n\tT1 = spm_slice_vol(T1,zoomM,dim([1 2]),[hld NaN]);\n\tQ = find(T1==0) ; T1(Q) = NaN;\n\tD = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)+1;0 0 0 1]*A;\n\tD1 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);\n\tmaxD = max([maxD ; D1(:)]);\n\tminD = min([minD ; D1(:)]);\n\n\tQ = find(abs(transv.blob.xyz(3,:) - xyz(3)-1) < 0.5);\n\tT3 = full(sparse(transv.blob.xyz(1,Q),...\n\t\t\ttransv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));\n\tT3 = spm_slice_vol(T3,zoomM,dim([1 2]),[hld NaN]);\n\tQ = find(T3==0) ; T3(Q) = NaN;\n\tD = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)-1;0 0 0 1]*A;\n\tD3 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);\n\tmaxD = max([maxD ; D3(:)]);\n\tminD = min([minD ; D3(:)]);\nend\n\nmx = max([max(T2(:)) eps]);\nmn = min([min(T2(:)) 0]);\nD2 = (D2-minD)/(maxD-minD);\nif transv.blob.dim(3) > 1,\n\tD1 = (D1-minD)/(maxD-minD);\n\tD3 = (D3-minD)/(maxD-minD);\n\tmx = max([mx ; T1(:) ; T3(:) ; eps]);\n\tmn = min([mn ; T1(:) ; T3(:) ; 0]);\nend;\n\n%-Configure {128 level} colormap\n%-----------------------------------------------------------------------\ncmap = get(transv.fig,'Colormap');\nif size(cmap,1) ~= 128\n\tfigure(transv.fig)\n\tspm_figure('Colormap','gray-hot')\n\tcmap = get(transv.fig,'Colormap');\nend\n\nD = length(cmap)/2;\nQ = find(T2(:) > transv.blob.u); T2 = (T2(Q)-mn)/(mx-mn); D2(Q) = 1+1.51/D + T2; T2 = D*D2;\n\nif transv.blob.dim(3) > 1\n Q = find(T1(:) > transv.blob.u); T1 = (T1(Q)-mn)/(mx-mn); D1(Q) = 1+1.51/D + T1; T1 = D*D1;\n Q = find(T3(:) > transv.blob.u); T3 = (T3(Q)-mn)/(mx-mn); D3(Q) = 1+1.51/D + T3; T3 = D*D3;\nend\n\nP = xyz.*transv.blob.vox';\n\n%-Render activation foci on background images\n%-----------------------------------------------------------------------\nif transv.blob.dim(3) > 1\n\n\tset(transv.h(2),'Cdata',rot90(spm_grid(T1)));\n\ttmp = transv.blob.iM\\[xyz(1:2)' (xyz(3)-1) 1]';\n\tset(get(transv.h(1),'Title'),'String',sprintf('z = %0.0fmm',tmp(3)));\n\tset(transv.h(3),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);\n\tset(transv.h(4),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));\n\n\tset(transv.h(6),'Cdata',rot90(spm_grid(T2)));\n\tset(get(transv.h(5),'Title'),'String',sprintf('z = %0.0fmm',xyzmm(3)));\n\tset(transv.h(7),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);\n\tset(transv.h(8),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));\n\n\tset(transv.h(10),'Cdata',rot90(spm_grid(T3)));\n\ttmp = transv.blob.iM\\[xyz(1:2)' (xyz(3)+1) 1]';\n\tset(get(transv.h(9),'Title'),'String',sprintf('z = %0.0fmm',tmp(3)));\n\tset(transv.h(11),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);\n\tset(transv.h(12),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));\n \n\t% colorbar\n\t%-----------------------------------------------------------------------\n\tset(transv.h(14), 'Ydata',[mn mx], 'Cdata',(1:D)' + D);\n\tset(transv.h(13),'XTickLabel',[],'Ylim',[mn mx]);\n \nelse\n\tset(transv.h(2),'Cdata',rot90(spm_grid(T2)));\n\tset(get(transv.h(1),'Title'),'String',sprintf('z = %0.0fmm',xyzmm(3)));\n\tset(transv.h(3),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);\n\tset(transv.h(4),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));\n\n\t% colorbar\n\t%-----------------------------------------------------------------------\n\tset(transv.h(6), 'Ydata',[0 d], 'Cdata',(1:D)' + D);\n\tset(transv.h(5),'XTickLabel',[],'Ylim',[0 d]);\n \nend;\n\n\n%-Reset pointer\n%-----------------------------------------------------------------------\nspm('Pointer','Arrow')\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction clear_global(varargin)\nglobal transv\nif isstruct(transv),\n\tfor h = transv.h,\n\t\tif ishandle(h), set(h,'DeleteFcn',''); end;\n\tend;\n\tfor h = transv.h,\n\t\tif ishandle(h), delete(h); end;\n\tend;\n\ttransv = [];\n\tclear global transv;\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_select.m", "ext": ".m", "path": "spm5-master/spm_select.m", "size": 41694, "source_encoding": "utf_8", "md5": "3afb406cb219867c0fbed6974862cc3a", "text": "function [t,sts] = spm_select(varargin)\n% File selector\n% FORMAT [t,sts] = spm_select(n,typ,mesg,sel,wd,filt,frames)\n% n - Number of files\n% A single value or a range. e.g.\n% 1 - Select one file\n% Inf - Select any number of files\n% [1 Inf] - Select 1 to Inf files\n% [0 1] - select 0 or 1 files\n% [10 12] - select from 10 to 12 files\n% typ - file type\n% 'any' - all files\n% 'image' - Image files (\".img\" and \".nii\")\n% Note that it gives the option to select\n% individual volumes of the images.\n% 'xml' - XML files\n% 'mat' - Matlab .mat files\n% 'batch' - SPM batch files (.mat and XML)\n% 'dir' - select a directory\n% Other strings act as a filter to regexp. This means\n% that e.g. DCM*.mat files should have a typ of '^DCM.*\\.mat$'\n% mesg - a prompt (default 'Select files...')\n% sel - list of already selected files\n% wd - Directory to start off in\n% filt - value for user-editable filter (default '.*')\n% frames - Image frame numbers to include (default '1')\n%\n% t - selected files\n% sts - status (1 means OK, 0 means window quit)\n%\n% Files can be selected from disk, but \"virtual\" files can also be selected.\n% Virtual filenames are passed by\n% spm_select('addvfiles',list)\n% where list is a cell array of filenames\n% The list can be cleared by\n% spm_select('clearvfiles')\n%\n% FORMAT [t,sts] = spm_select('Filter',files,typ,filt,frames)\n% filter the list of files (cell or char array) in the same way as the GUI would do.\n% There is an additional typ 'extimage' which will match images with\n% frame specifications, too. Also, there is a typ 'extdir', which will\n% match canonicalised directory names.\n%\n% FORMAT cpath = spm_select('CPath',path,cwd)\n% function to canonicalise paths: Prepends cwd to relative paths, processes\n% '..' & '.' directories embedded in path.\n% path - string matrix containing path name\n% cwd - current working directory [defaut '.']\n% cpath - conditioned paths, in same format as input path argument\n%\n% FORMAT [files,dirs]=spm_select('List',direc,filt)\n% Returns files matching the filter (filt) and directories within dire\n% direc - directory to search\n% filt - filter to select files with (see regexp) e.g. '^w.*\\.img$'\n% files - files matching 'filt' in directory 'direc'\n% dirs - subdirectories of 'direc'\n% FORMAT [files,dirs]=spm_select('ExtList',direc,filt,frames)\n% As above, but for selecting frames of 4D NIfTI files\n% frames - vector of frames to select (defaults to 1, if not specified)\n% FORMAT [files,dirs]=spm_select('FPList',direc,filt)\n% FORMAT [files,dirs]=spm_select('ExtFPList',direc,filt,frames)\n% As above, but returns files with full paths (i.e. prefixes direc to each)\n%____________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_select.m 1746 2008-05-28 17:43:42Z guillaume $\n\nif nargin > 0 && ischar(varargin{1})\n switch lower(varargin{1})\n case 'addvfiles'\n error(nargchk(2,Inf,nargin));\n vfiles('add',varargin{2:end});\n case 'clearvfiles'\n error(nargchk(1,1,nargin));\n vfiles('clear');\n case 'vfiles'\n error(nargchk(1,1,nargin));\n t = vfiles('all');\n case 'cpath'\n error(nargchk(2,Inf,nargin));\n t = cpath(varargin{2:end});\n case 'filter'\n filt = mk_filter(varargin{3:end});\n cs = iscell(varargin{2});\n if ~cs\n t = cellstr(varargin{2});\n else\n t = varargin{2};\n end;\n [t,sts] = do_filter(t,filt.ext);\n [t,sts] = do_filter(t,filt.filt);\n if ~cs\n t = strvcat(t);\n end;\n case {'list', 'fplist', 'extlist', 'extfplist'}\n if nargin > 3\n frames = varargin{4};\n else\n frames = 1; % (ignored in listfiles if typ==any)\n end;\n if regexpi(varargin{1}, 'ext') % use frames descriptor\n typ = 'extimage';\n else\n typ = 'any';\n end\n filt = mk_filter(typ, varargin{3}, frames);\n [t sts] = listfiles(varargin{2}, filt); % (sts is subdirs here)\n if regexpi(varargin{1}, 'fplist') % return full pathnames\n direc = spm_select('cpath', varargin{2});\n % remove trailing path separator if present\n direc = regexprep(direc, [filesep '$'], '');\n t = strcat(repmat(direc, size(t, 1), 1), filesep, t);\n if nargout > 1\n % subdirs too\n nsd = size(sts, 1);\n sts = strcat(repmat(direc, nsd, 1), filesep, sts);\n % /blah/blah/. and /blah/blah/.. not canonical, fix:\n sts = cellstr(sts);\n mch = [filesep '\\.$'];\n sts = regexprep(sts, mch, '');\n mch = [filesep '[^' filesep ']+' filesep '\\.\\.$'];\n sts = regexprep(sts, mch, '');\n sts = char(sts);\n end\n end\n otherwise\n error('Inappropriate usage.');\n end\nelse\n [t,sts] = selector(varargin{:});\nend\n%=======================================================================\n\n%=======================================================================\nfunction [t,ok] = selector(n,typ,mesg,already,wd,filt,frames,varargin)\nif nargin<7, frames = '1'; end;\nif nargin<6, filt = '.*'; end;\nif nargin<5, wd = pwd; end;\nif nargin<4, already = {''}; end;\nif nargin<3, mesg = 'Select files...'; end;\nif nargin<2, typ = 'any'; end;\nif nargin<1, n = [0 Inf]; end;\nok = 0;\nif numel(n)==1, n = [n n]; end;\nif n(1)>n(2), n = n([2 1]); end;\nif ~isfinite(n(1)), n(1) = 0; end;\nalready = strvcat(already);\n\nt = '';\nsfilt = mk_filter(typ,filt,frames);\n\n[col1,col2,col3,fs] = colours;\n\nfg = figure('IntegerHandle','off',...\n 'Tag','Select',...\n 'Name',strvcat(mesg),...\n 'NumberTitle','off',...\n 'Units','Pixels',...\n 'MenuBar','none',...\n 'DefaultTextInterpreter','none',...\n 'DefaultUicontrolInterruptible','on',...\n 'ResizeFcn',@resize_fun,...\n 'KeyPressFcn',@hitkey);\n\n% Code from Brian Lenoski for dealing with multiple monitors\nif spm_matlab_version_chk('7') >=0\n S = get(0, 'MonitorPosition');\n Rect = get(fg,'Position');\n pointer_loc = get(0,'PointerLocation');\n\n for i = 1:size(S,1), % Loop over monitors\n h_min = S(i,1);\n h_width = S(i,3);\n h_max = h_width + h_min - 1;\n v_min = S(i,2);\n v_len = S(i,4);\n v_max = v_min + v_len;\n\n % Use the monitor containing the pointer\n if pointer_loc(1) >= h_min && pointer_loc(1) < h_max && ...\n pointer_loc(2) >= v_min && pointer_loc(2) < v_max,\n hor_min = h_min;\n hor_width = h_width;\n hor_max = h_max;\n ver_min = v_min;\n ver_len = v_len;\n ver_max = v_max;\n end\n end\n Rect(1) = (hor_max - 0.5*hor_width) - 0.5*Rect(3); % Horizontal\n Rect(2) = (ver_max - 0.5*ver_len) - 0.5*Rect(4); % Vertical\n set(fg,'Position',Rect);\nend\n\n\nfh = 0.05;\n%fs = 10;\n\nsbh = 0.03; % Scroll-bar height. This should be worked out properly\nh1 = (0.96-4*fh-5*0.01)/2;\nif n(2)*fh+sbh= 0 ) && isdeployed,\n ind = findstr(SPMdir,'_mcr')-1;\n [SPMdir,junk] = fileparts(SPMdir(1:ind(1)));\nend;\nprevdirs([SPMdir filesep]);\n[pd,vl] = prevdirs([wd filesep]);\n\n% Selected Files\nhp = 0.02;\nsel = uicontrol(fg,...\n 'style','listbox',...\n 'units','normalized',...\n 'Position',[0.02 hp 0.96 h1],...\n 'FontSize',fs,...\n 'Callback',@unselect,...\n 'tag','selected',...\n 'BackgroundColor',col1,...\n 'ForegroundColor',col3,...\n 'Max',10000,...\n 'Min',0,...\n 'String',already,...\n 'Value',1);\nc0 = uicontextmenu('Parent',fg);\nset(sel,'uicontextmenu',c0);\nuimenu('Label','Unselect All', 'Parent',c0,'Callback',@unselect_all);\n\n% Messages\nhp = hp+h1+0.01;\nuicontrol(fg,...\n 'style','text',...\n 'units','normalized',...\n 'Position',[0.02 hp 0.96 fh],...\n 'FontSize',fs,...\n 'BackgroundColor',get(fg,'Color'),...\n 'ForegroundColor',col3,...\n 'HorizontalAlignment','left',...\n 'Tag','msg',...\n 'String',mesg);\n\nif strcmpi(typ,'image'),\n uicontrol(fg,...\n 'style','edit',...\n 'units','normalized',...\n 'Position',[0.61 hp 0.37 fh],...\n 'Callback',@update_frames,...\n 'tag','frame',...\n 'FontSize',fs,...\n 'BackgroundColor',col1,...\n 'String',frames,'UserData',eval(frames));\n% 'ForegroundGolor',col3,...\nend;\n\n% Help\nhp = hp+fh+0.01;\nuicontrol(fg,...\n 'Style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.02 hp fh fh],...\n 'FontSize',fs,...\n 'Callback',@heelp,...\n 'tag','?',...\n 'ForegroundColor',col3,...\n 'BackgroundColor',col1,...\n 'String','?',...\n 'FontWeight','bold',...\n 'ToolTipString','Show Help',...\n 'FontSize',fs);\n\nuicontrol(fg,...\n 'Style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.03+fh hp fh fh],...\n 'FontSize',fs,...\n 'Callback',@editwin,...\n 'tag','Ed',...\n 'ForegroundColor',col3,...\n 'BackgroundColor',col1,...\n 'String','Ed',...\n 'FontWeight','bold',...\n 'ToolTipString','Edit Selected Files',...\n 'FontSize',fs);\n\nuicontrol(fg,...\n 'Style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.04+2*fh hp fh fh],...\n 'FontSize',fs,...\n 'Callback',@select_rec,...\n 'tag','Rec',...\n 'ForegroundColor',col3,...\n 'BackgroundColor',col1,...\n 'String','Rec',...\n 'FontWeight','bold',...\n 'ToolTipString','Recursively Select Files with Current Filter',...\n 'FontSize',fs);\n\n% Done\ndne = uicontrol(fg,...\n 'Style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.05+3*fh hp 0.45-3*fh fh],...\n 'FontSize',fs,...\n 'Callback',@delete,...\n 'tag','D',...\n 'ForegroundColor',col3,...\n 'BackgroundColor',col1,...\n 'String','Done',...\n 'FontWeight','bold',...\n 'FontSize',fs,...\n 'Enable','off',...\n 'DeleteFcn',@null);\n\nif size(already,1)>=n(1) && size(already,1)<=n(2),\n set(dne,'Enable','on');\nend;\n\n% Filter Button\nuicontrol(fg,...\n 'Style','pushbutton',...\n 'units','normalized',...\n 'Position',[0.51 hp 0.1 fh],...\n 'FontSize',fs,...\n 'ForegroundColor',col3,...\n 'BackgroundColor',col1,...\n 'Callback',@clearfilt,...\n 'String','Filt',...\n 'FontSize',fs);\n\n% Filter\nuicontrol(fg,...\n 'style','edit',...\n 'units','normalized',...\n 'Position',[0.61 hp 0.37 fh],...\n 'ForegroundColor',col3,...\n 'BackgroundColor',col1,...\n 'FontSize',fs,...\n 'Callback',@update,...\n 'tag','regexp',...\n 'String',filt,...\n 'UserData',sfilt);\n\n% Directories\nhp = hp + fh+0.01;\ndb = uicontrol(fg,...\n 'style','listbox',...\n 'units','normalized',...\n 'Position',[0.02 hp 0.47 h2],...\n 'FontSize',fs,...\n 'Callback',@click_dir_box,...\n 'tag','dirs',...\n 'BackgroundColor',col1,...\n 'ForegroundColor',col3,...\n 'Max',1,...\n 'Min',0,...\n 'String','',...\n 'UserData',wd,...\n 'Value',1);\n\n% Files\ntmp = uicontrol(fg,...\n 'style','listbox',...\n 'units','normalized',...\n 'Position',[0.51 hp 0.47 h2],...\n 'FontSize',fs,...\n 'Callback',@click_file_box,...\n 'tag','files',...\n 'BackgroundColor',col1,...\n 'ForegroundColor',col3,...\n 'UserData',n,...\n 'Max',10240,...\n 'Min',0,...\n 'String','',...\n 'Value',1);\nc0 = uicontextmenu('Parent',fg);\nset(tmp,'uicontextmenu',c0);\nuimenu('Label','Select All', 'Parent',c0,'Callback',@select_all);\n\n% Drives\nif strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64'),\n dr = spm_platform('drives');\n drivestr = cell(1,numel(dr));\n for i=1:numel(dr),\n drivestr{i} = [dr(i) ':'];\n end;\n %drivestr = {'A:','B:','C:','D:'};\n sz = get(db,'Position');\n sz(4) = sz(4)-fh-2*0.01;\n set(db,'Position',sz);\n uicontrol(fg,...\n 'style','text',...\n 'units','normalized',...\n 'Position',[0.02 hp+h2-fh-0.01 0.10 fh],...\n 'FontSize',fs,...\n 'BackgroundColor',get(fg,'Color'),...\n 'ForegroundColor',col3,...\n 'String','Drive');\n uicontrol(fg,...\n 'style','popupmenu',...\n 'units','normalized',...\n 'Position',[0.12 hp+h2-fh-0.01 0.37 fh],...\n 'FontSize',fs,...\n 'Callback',@setdrive,...\n 'tag','drive',...\n 'BackgroundColor',col1,...\n 'ForegroundColor',col3,...\n 'String',drivestr,...\n 'Value',1);\nend;\n\n% Previous dirs\nhp = hp+h2+0.01;\nuicontrol(fg,...\n 'style','popupmenu',...\n 'units','normalized',...\n 'Position',[0.12 hp 0.86 fh],...\n 'FontSize',fs,...\n 'Callback',@click_dir_list,...\n 'tag','previous',...\n 'BackgroundColor',col1,...\n 'ForegroundColor',col3,...\n 'String',pd,...\n 'Value',vl);\nuicontrol(fg,...\n 'style','text',...\n 'units','normalized',...\n 'Position',[0.02 hp 0.10 fh],...\n 'FontSize',fs,...\n 'BackgroundColor',get(fg,'Color'),...\n 'ForegroundColor',col3,...\n 'String','Prev');\n\n% Directory\nhp = hp + fh+0.01;\nuicontrol(fg,...\n 'style','edit',...\n 'units','normalized',...\n 'Position',[0.12 hp 0.86 fh],...\n 'FontSize',fs,...\n 'Callback',@edit_dir,...\n 'tag','edit',...\n 'BackgroundColor',col1,...\n 'ForegroundColor',col3,...\n 'String','');\nuicontrol(fg,...\n 'style','text',...\n 'units','normalized',...\n 'Position',[0.02 hp 0.10 fh],...\n 'FontSize',fs,...\n 'BackgroundColor',get(fg,'Color'),...\n 'ForegroundColor',col3,...\n 'String','Dir');\n\nresize_fun(fg);\nupdate(sel,wd)\n\nwaitfor(dne);\ndrawnow;\nif ishandle(sel),\n t = get(sel,'String');\n if sfilt.code == -1 && ~isempty(t)\n % don't canonicalise empty selection\n t = cellstr(t);\n for k = 1:numel(t);\n t{k} = cpath(t{k},pwd);\n end;\n t = char(t);\n end;\n ok = 1;\nend;\nif ishandle(fg), delete(fg); end;\ndrawnow;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction null(varargin)\n%=======================================================================\n\n%=======================================================================\nfunction msg(ob,str)\nob = sib(ob,'msg');\nset(ob,'String',str);\nif nargin>=3,\n set(ob,'ForegroundColor',[1 0 0],'FontWeight','bold');\nelse\n set(ob,'ForegroundColor',[0 0 0],'FontWeight','normal');\nend;\ndrawnow;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction setdrive(ob,varargin)\nst = get(ob,'String');\nvl = get(ob,'Value');\nupdate(ob,st{vl});\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction resize_fun(fg,varargin)\nob = findobj(fg,'String','Filt','Style','pushbutton');\nif ~isempty(ob),\n ofs = get(ob,'FontSize');\n ex = get(ob,'Extent');\n ps = get(ob,'Position');\n fs = floor(ofs*min(ps(4)./ex(4))+1);\n fs = max(min(fs,30),4);\n ob = findobj(fg,'Fontsize',ofs);\n set(ob,'FontSize',fs);\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [d,mch] = prevdirs(d)\npersistent pd\nif ~iscell(pd), pd = {}; end;\nd = deblank(d);\nmch = find(strcmp(d,pd));\nif isempty(mch),\n pd = {pd{:},d};\n mch = length(pd);\nend;\nd = pd;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction clearfilt(ob,varargin)\nset(sib(ob,'regexp'),'String','.*');\nupdate(ob);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction click_dir_list(ob,varargin)\nvl = get(ob,'Value');\nls = get(ob,'String');\nupdate(ob,deblank(ls{vl}));\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction edit_dir(ob,varargin)\nupdate(ob,get(ob,'String'));\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction click_dir_box(lb,varargin)\nupdate(lb,current_dir(lb));\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction dr = current_dir(lb,varargin)\nvl = get(lb,'Value');\nstr = get(lb,'String');\npd = get(sib(lb,'edit'),'String');\nwhile ~isempty(pd) & strcmp(pd(end),filesep) \n pd=pd(1:end-1); % Remove any trailing fileseps\nend \nsel = deblank(str(vl,:));\nif strcmp(sel,'..'), % Parent directory \n dr = fileparts(pd);\nelseif strcmp(sel,'.'), % Current directory \n dr = pd;\nelse\n dr = fullfile(pd,sel); \nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction re = getfilt(ob)\nob = sib(ob,'regexp');\nud = get(ob,'UserData');\nre = struct('code',ud.code,...\n 'frames',get(sib(ob,'frame'),'UserData'),...\n 'ext',{ud.ext},...\n 'filt',{{get(sib(ob,'regexp'),'String')}});\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction update(lb,dr)\nlb = sib(lb,'dirs');\nif nargin<2 || isempty(dr),\n dr = get(lb,'UserData');\nend;\nif ~(strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64'))\n dr = [filesep dr filesep];\nelse\n dr = [dr filesep];\nend;\ndr(findstr([filesep filesep],dr)) = [];\n[f,d] = listfiles(dr,getfilt(lb));\nif isempty(d),\n dr = get(lb,'UserData');\n [f,d] = listfiles(dr,getfilt(lb));\nelse\n set(lb,'UserData',dr);\nend;\nset(lb,'Value',1,'String',d);\nset(sib(lb,'files'),'Value',1,'String',f);\n[ls,mch] = prevdirs(dr);\nset(sib(lb,'previous'),'String',ls,'Value',mch);\nset(sib(lb,'edit'),'String',dr);\n\nif numel(dr)>1 && dr(2)==':',\n str = get(sib(lb,'drive'),'String');\n str = cat(1,char(str));\n mch = find(lower(str(:,1))==lower(dr(1)));\n if ~isempty(mch),\n set(sib(lb,'drive'),'Value',mch);\n end;\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction update_frames(lb,varargin)\nstr = get(lb,'String');\n%r = get(lb,'UserData');\ntry\n r = eval(['[',str,']']);\ncatch\n msg(lb,['Failed to evaluate \"' str '\".'],'r');\n beep;\n return;\nend;\nif ~isnumeric(r),\n msg(lb,['Expression non-numeric \"' str '\".'],'r');\n beep;\nelse\n set(lb,'UserData',r);\n msg(lb,'');\n update(lb);\nend;\n%=======================================================================\n\n%=======================================================================\nfunction select_all(ob,varargin)\nlb = findobj(get(get(ob,'Parent'),'Parent'),'Tag','files');\nstr = get(lb,'String');\nset(lb,'Value',1:size(str,1));\ndrawnow;\nclick_file_box(lb);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction click_file_box(lb,varargin)\nlim = get(lb,'UserData');\nob = sib(lb,'selected');\nstr3 = get(ob,'String');\n\nstr = get(lb,'String');\nvlo = get(lb,'Value');\nlim1 = min(max(lim(2)-size(str3,1),0),length(vlo));\nif isempty(vlo),\n msg(lb,'Nothing selected');\n return;\nend;\nif lim1==0,\n msg(lb,['Selected ' num2str(size(str3,1)) '/' num2str(lim(2)) ' already.']);\n beep;\n set(sib(lb,'D'),'Enable','on');\n return;\nend;\n\nvl = vlo(1:lim1);\nmsk = false(size(str,1),1);\nif vl>0, msk(vl) = true; else msk = []; end;\nstr1 = str( msk,:);\nstr2 = str(~msk,:);\ndr = [current_dir(sib(lb,'dirs')) filesep];\nstr1 = [repmat(dr,size(str1,1),1) str1];\n\nset(lb,'Value',min(vl(1),size(str2,1)),'String',str2);\nr = (1:size(str1,1))+size(str3,1);\nstr3 = deblank(strvcat(str3,str1));\nset(ob,'String',str3,'Value',r);\nif length(vlo)>lim1,\n msg(lb,['Retained ' num2str(lim1) '/' num2str(length(vlo))...\n ' of selection.']);\n beep;\nelseif isfinite(lim(2))\n if lim(1)==lim(2),\n msg(lb,['Selected ' num2str(size(str3,1)) '/' num2str(lim(2)) ' files.']);\n else\n msg(lb,['Selected ' num2str(size(str3,1)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']);\n end;\nelse\n if size(str3,1) == 1, ss = ''; else ss = 's'; end;\n msg(lb,['Selected ' num2str(size(str3,1)) ' file' ss '.']);\nend;\nif ~isfinite(lim(1)) || size(str3,1)>=lim(1),\n set(sib(lb,'D'),'Enable','on');\nend;\n\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction obj = sib(ob,tag)\nobj = findobj(get(ob,'Parent'),'Tag',tag);\nreturn;\n%if isempty(obj),\n% error(['Can''t find object with tag \"' tag '\".']);\n%elseif length(obj)>1,\n% error(['Found ' num2str(length(obj)) ' objects with tag \"' tag '\".']);\n%end;\n%return;\n%=======================================================================\n\n%=======================================================================\nfunction unselect(lb,varargin)\nvl = get(lb,'Value');\nif isempty(vl), return; end;\nstr = get(lb,'String');\nmsk = ones(size(str,1),1);\nif vl~=0, msk(vl) = 0; end;\nstr2 = str(logical(msk),:);\nset(lb,'Value',min(vl(1),size(str2,1)),'String',str2);\nlim = get(sib(lb,'files'),'UserData');\nif size(str2,1)>= lim(1) && size(str2,1)<= lim(2),\n set(sib(lb,'D'),'Enable','on');\nelse \n set(sib(lb,'D'),'Enable','off');\nend;\n\nif size(str2,1) == 1, ss1 = ''; else ss1 = 's'; end;\n%msg(lb,[num2str(size(str2,1)) ' file' ss ' remaining.']);\nif numel(vl) == 1, ss = ''; else ss = 's'; end;\nmsg(lb,['Unselected ' num2str(numel(vl)) ' file' ss '. ' ...\n num2str(size(str2,1)) ' file' ss1 ' remaining.']);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction unselect_all(ob,varargin)\nlb = findobj(get(get(ob,'Parent'),'Parent'),'Tag','selected');\nset(lb,'Value',[],'String','','ListBoxTop',1);\nmsg(lb,'Unselected all files.');\nlim = get(sib(lb,'files'),'UserData');\nif lim(1)>0, set(sib(lb,'D'),'Enable','off'); end;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction varargout = vfiles(option,varargin)\npersistent vfs\nif isempty(vfs),\n vfs = newvfs;\nend;\n\nswitch option,\ncase {'clear'}\n vfs = newvfs;\ncase {'add'}\n for j=1:numel(varargin),\n pth = {};\n fle = {};\n if ischar(varargin{j}),\n for i=1:size(varargin{j},1),\n [pth{i} n e v] = spm_fileparts(deblank(varargin{j}(i,:)));\n fle{i} = [n e v];\n end;\n elseif iscell(varargin{j}),\n for i=1:numel(varargin{j}),\n [pth{i} n e v] = spm_fileparts(deblank(varargin{j}{i}));\n fle{i} = [n e v];\n end;\n end;\n [pu pi pj] = unique(pth);\n for k = 1:numel(pu)\n vfs = addvfile(vfs,pu{k},fle(pj==k));\n end;\n end;\ncase {'list'}\n [varargout{1:3}] = listvfiles(vfs,varargin{:});\ncase {'all'}\n varargout{1} = vfs;\notherwise\n error('Unknown option.');\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction vfs = newvfs(nam)\nif nargin==0, nam = ''; end;\nvfs = struct('name',nam,'dirs',struct('name',{},'dirs',{},'files',{}),'files',struct('name',{},'ind',{}));\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction vfs = addvfile(vfs,pth,fle)\nif isempty(pth),\n for k = 1:numel(fle)\n [unused,nam,ext,num] = spm_fileparts(fle{k});\n if ~isempty(num),\n ind = [str2num(num) 1 1];\n ind = ind(1);\n else\n ind = [];\n end;\n fname = [nam ext];\n mch = strcmp(fname,{vfs.files.name});\n if any(mch),\n mch = find(mch);\n vfs.files(mch).ind = [vfs.files(mch).ind ind];\n else\n vfs.files(end+1).name = fname;\n vfs.files(end).ind = ind;\n end;\n end;\nelse\n ind = find(pth==filesep);\n if isempty(ind)\n dr = pth;\n pth = '';\n else\n if any(ind==1),\n ind = ind(2:end)-1;\n pth = pth(2:end);\n end;\n if isempty(ind)\n dr = pth;\n pth = '';\n else\n dr = pth(1:(ind(1)-1));\n pth = pth((ind(1)+1):end);\n end;\n end;\n mch = strcmp(dr,{vfs.dirs.name});\n if any(mch),\n mch = find(mch);\n else\n mch = numel(vfs.dirs)+1;\n vfs.dirs(mch) = newvfs(dr);\n end;\n vfs.dirs(mch) = addvfile(vfs.dirs(mch),pth,fle);\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [f,d] = listfiles(dr,filt)\nob = gco;\nmsg(ob,'Listing directory...');\nif nargin<2, filt = ''; end;\nif nargin<1, dr = '.'; end;\nde = dir(dr);\nif ~isempty(de),\n d = {de([de.isdir]).name};\n if ~any(strcmp(d, '.'))\n d = {'.', d{:}};\n end;\n if filt.code~=-1,\n f = {de(~[de.isdir]).name};\n else\n % f = d(3:end);\n f = d;\n end;\nelse\n d = {'.','..'};\n f = {};\nend;\n\nmsg(ob,['Filtering ' num2str(numel(f)) ' files...']);\nf = do_filter(f,filt.ext);\nf = do_filter(f,filt.filt);\nii = cell(1,numel(f));\nif filt.code==1 && (numel(filt.frames)~=1 || filt.frames(1)~=1),\n msg(ob,['Reading headers of ' num2str(numel(f)) ' images...']);\n for i=1:numel(f),\n try\n ni = nifti(fullfile(dr,f{i}));\n dm = [ni.dat.dim 1 1 1 1 1];\n d4 = (1:dm(4))';\n catch\n d4 = 1;\n end;\n msk = false(size(filt.frames));\n for j=1:numel(msk), msk(j) = any(d4==filt.frames(j)); end;\n ii{i} = filt.frames(msk);\n end;\nelseif filt.code==1 && (numel(filt.frames)==1 && filt.frames(1)==1),\n for i=1:numel(f),\n ii{i} = 1;\n end;\nend;\n\nmsg(ob,'Listing virtual files...');\n[fv,dv,iv] = vfiles('list',dr);\nif filt.code==-1,\n fv = dv;\n iv = cell(size(fv));\nend;\nmsg(ob,['Filtering ' num2str(numel(fv)) ' virtual files...']);\n[fv,ind] = do_filter(fv,filt.ext);\niv = iv(ind);\n[fv,ind] = do_filter(fv,filt.filt);\niv = iv(ind);\nif filt.code==1,\n for i=1:numel(iv),\n msk = false(size(filt.frames));\n for j=1:numel(msk), msk(j) = any(iv{i}==filt.frames(j)); end;\n iv{i} = filt.frames(msk);\n end;\nend;\n\nd = { d{:},dv{:}};\nf = { f{:},fv{:}};\nii = {ii{:},iv{:}};\n\nmsg(ob,['Listing ' num2str(numel(f)) ' files...']);\n\n[f,ind] = sortrows(f(:));\nii = ii(ind);\nmsk = true(1,numel(f));\nif ~isempty(f), f{1} = deblank(f{1}); end;\nfor i=2:numel(f),\n f{i} = deblank(f{i});\n if strcmp(f{i-1},f{i}),\n if filt.code==1,\n tmp = sort([ii{i}(:) ; ii{i-1}(:)]);\n tmp(~diff(tmp,1)) = [];\n ii{i} = tmp;\n end;\n msk(i-1) = false;\n end;\nend;\nf = f(msk);\nif filt.code==1,\n ii = ii(msk);\n c = cell(size(f));\n for i=1:numel(f),\n c{i} = [repmat([f{i} ','],numel(ii{i}),1) num2str(ii{i}(:)) ];\n end;\n f = c;\nelseif filt.code==-1,\n fs = filesep;\n for i=1:numel(f),\n f{i} = [f{i} fs];\n end;\nend;\nf = strvcat(f{:});\n\nd = sortrows(d(:));\nd = strvcat(d);\nsam = find(~any(diff(d+0,1),2));\nd(sam,:) = [];\n\nmsg(ob,'');\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [f,ind] = do_filter(f,filt)\nt2 = false(numel(f),1);\n% This would be a speedup, but does not work on MATLAB < R14SP3 due to\n% changes in regexp handling\n% filt_or = sprintf('(%s)|',filt{:});\n% t1 = regexp(f,filt_or(1:end-1));\n% if numel(f)==1 && ~iscell(t1), t1 = {t1}; end;\n% for i=1:numel(t1),\n% t2(i) = ~isempty(t1{i});\n% end;\nfor j=1:numel(filt),\n t1 = regexp(f,filt{j});\n if numel(f)==1 && ~iscell(t1), t1 = {t1}; end;\n for i=1:numel(t1),\n t2(i) = t2(i) || ~isempty(t1{i});\n end;\nend;\nind = find(t2);\nf = f(ind);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [f,d,ii] = listvfiles(vfs,dr)\nf = {};\nd = {};\nii = {};\nif isempty(dr),\n f = {vfs.files.name};\n ii = {vfs.files.ind};\n d = {vfs.dirs.name};\nelse\n if dr(1)==filesep, dr = dr(2:end); end;\n ind = find(dr==filesep);\n if isempty(ind),\n d1 = dr;\n d2 = '';\n else\n d1 = dr(1:(ind(1)-1));\n d2 = dr((ind(1)+1):end);\n end;\n for i=1:length(vfs.dirs),\n if strcmp(d1,vfs.dirs(i).name),\n [f,d,ii] = listvfiles(vfs.dirs(i),d2);\n break;\n end;\n end;\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction heelp(ob,varargin)\n[col1,col2,col3,fs] = colours;\nfg = get(ob,'Parent');\nt = uicontrol(fg,...\n 'style','listbox',...\n 'units','normalized',...\n 'Position',[0.01 0.01 0.98 0.98],...\n 'FontSize',fs,...\n 'FontName','FixedWidthFont',...\n 'BackgroundColor',col2,...\n 'ForegroundColor',col3,...\n 'Max',0,...\n 'Min',0,...\n 'tag','HelpWin',...\n 'String',' ');\nc0 = uicontextmenu('Parent',fg);\nset(t,'uicontextmenu',c0);\nuimenu('Label','Done', 'Parent',c0,'Callback',@helpclear);\n\next = get(t,'Extent');\npw = floor(0.98/ext(3)*20-4);\nstr = spm_justify(pw,{[...\n'File Selection help. You can return to selecting files via the right mouse button (the \"Done\" option). ',...\n'Because of a bug in Matlab (on some machines), don''t resize this window when viewing the help.'],...\n'',[...\n'The panel at the bottom shows files that are already selected. ',...\n'Clicking a selected file will un-select it. To un-select several, you can ',...\n'drag the cursor over the files, and they will be gone on release. ',...\n'You can use the right mouse button to un-select everything.'],...\n'',[...\n'Directories are navigated by editing the name of the current directory (where it says \"Dir\"), ',...\n'by going to one of the previously entered directories (\"Prev\"), or by navigating around ',...\n'the parent or subdirectories listed in the left side panel.'],...\n'',[...\n'Files matching the filter (\"Filt\") are shown in the panel on the right. ',...\n'These can be selected by clicking or dragging. Use the right mouse button if ',...\n'you would like to select all files. Note that when selected, the files disappear ',...\n'from this panel. They can be made to reappear by re-specifying the directory ',...\n'or the filter. ',...\n'Note that the syntax of the filter differs from that used by previous versions of ',...\n'SPM. The following is a list of symbols with special meaning for filtering the filenames:'],...\n' ^ start of string',...\n' $ end of string',...\n' . any character',...\n' \\ quote next character',...\n' * match zero or more',...\n' + match one or more',...\n' ? match zero or one, or match minimally',...\n' {} match a range of occurrances',...\n' [] set of characters',...\n' [^] exclude a set of characters',...\n' () group subexpression',...\n' \\w match word [a-z_A-Z0-9]',...\n' \\W not a word [^a-z_A-Z0-9]',...\n' \\d match digit [0-9]',...\n' \\D not a digit [^0-9]',...\n' \\s match white space [ \\t\\r\\n\\f]',...\n' \\S not a white space [^ \\t\\r\\n\\f]',...\n' \\ exact word match',...\n'',[...\n'Individual time frames of image files can also be selected. The frame filter ',...\n'allows specified frames to be shown, which is useful for image files that ',...\n'contain multiple time points. If your images are only single time point, then ',...\n'reading all the image headers can be avoided by specifying a frame filter of \"1\". ',...\n'The filter should contain a list of integers indicating the frames to be used. ',...\n'This can be generated by e.g. \"1:100\", or \"1:2:100\".'],...\n'',[...\n'The recursive selection button (Rec) allows files matching the regular expression to ',...\n'be recursively selected. If there are many directories to search, then this can take ',...\n'a while to run.'],...\n'',[...\n'There is also an edit button (Ed), which allows you to edit your selection of files. ',...\n'When you are done, then use the menu-button of your mouse to either cancel or accept your changes'],''});\npad = cellstr(char(zeros(max(0,floor(1.2/ext(4) - numel(str))),1)));\nstr = {str{:}, pad{:}};\nset(t,'String',str);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction helpclear(ob,varargin)\nob = get(ob,'Parent');\nob = get(ob,'Parent');\nob = findobj(ob,'Tag','HelpWin');\ndelete(ob);\n%=======================================================================\n\n%=======================================================================\nfunction hitkey(fg,varargin)\nch = get(fg,'CurrentCharacter');\nif isempty(ch), return; end;\n\nob = findobj(fg,'Tag','files');\nif ~isempty(ob),\n f = get(ob,'String');\n f = f(:,1);\n fset = find(f>=ch);\n if ~isempty(fset),\n fset = fset(1);\n %cb = get(ob,'Callback');\n %set(ob,'Callback',[]);\n set(ob,'ListboxTop',fset);\n %set(ob,'Callback',cb);\n else\n set(ob,'ListboxTop',length(f));\n end;\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction t = cpath(t,d)\nswitch spm_platform('filesys'),\ncase 'unx',\n mch = '^/';\n fs = '/';\n fs1 = '/';\ncase 'win',\n mch = '^.:\\\\';\n fs = '\\';\n fs1 = '\\\\';\notherwise;\n error('What is this filesystem?');\nend\n\nif isempty(regexp(t,mch,'once')),\n if (nargin<2)||isempty(d), d = pwd; end;\n t = [d fs t];\nend;\n\n% Replace occurences of '/./' by '/' (problems with e.g. /././././././')\nre = [fs1 '\\.' fs1];\nwhile ~isempty(regexp(t,re)),\n t = regexprep(t,re,fs);\nend;\nt = regexprep(t,[fs1 '\\.' '$'], fs);\n\n% Replace occurences of '/abc/../' by '/'\nre = [fs1 '[^' fs1 ']+' fs1 '\\.\\.' fs1];\nwhile ~isempty(regexp(t,re)),\n t = regexprep(t,re,fs,'once');\nend;\nt = regexprep(t,[fs1 '[^' fs1 ']+' fs1 '\\.\\.' '$'],fs,'once');\n\n% Replace '//'\nt = regexprep(t,[fs1 '+'], fs);\n%=======================================================================\n\n%=======================================================================\nfunction editwin(ob,varargin)\n[col1,col2,col3,fs] = colours;\nfg = get(ob,'Parent');\nlb = findobj(fg,'Tag','selected');\nstr = get(lb,'String');\nstr = cellstr(str);\nh = uicontrol(fg,'Style','Edit',...\n 'units','normalized',...\n 'String',str,...\n 'FontSize',16,...\n 'Max',2,...\n 'Tag','EditWindow',...\n 'HorizontalAlignment','Left',...\n 'ForegroundColor',col3,...\n 'BackgroundColor',col1,...\n 'Position',[0.01 0.01 0.98 0.98]);\nc0 = uicontextmenu('Parent',fg);\nset(h,'uicontextmenu',c0);\nuimenu('Label','Cancel', 'Parent',c0,'Callback',@editclear);\nuimenu('Label','Accept', 'Parent',c0,'Callback',@editdone);\n%=======================================================================\n\n%=======================================================================\nfunction editdone(ob,varargin)\nob = get(ob,'Parent');\nob = sib(ob,'EditWindow');\nstr = get(ob,'String');\nstr = deblank(cellstr(strvcat(str)));\nif isempty(str{1}), str = {}; end;\n\nlim = get(sib(ob,'files'),'UserData');\nif numel(str)>lim(2),\n msg(ob,['Retained ' num2str(lim(2)) ' of the ' num2str(numel(str)) ' files.']);\n beep;\n str = str(1:lim(2));\nelseif isfinite(lim(2)),\n if lim(1)==lim(2),\n msg(ob,['Specified ' num2str(numel(str)) '/' num2str(lim(2)) ' files.']);\n else\n msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']);\n end;\nelse\n if numel(str) == 1, ss = ''; else ss = 's'; end;\n msg(ob,['Specified ' num2str(numel(str)) ' file' ss '.']);\nend;\nif ~isfinite(lim(1)) || numel(str)>=lim(1),\n set(sib(ob,'D'),'Enable','on');\nelse\n set(sib(ob,'D'),'Enable','off');\nend;\nset(sib(ob,'selected'),'String',strvcat(str),'Value',[]);\ndelete(ob);\n%=======================================================================\n\n%=======================================================================\nfunction editclear(ob,varargin)\nob = get(ob,'Parent');\nob = get(ob,'Parent');\nob = findobj(ob,'Tag','EditWindow');\ndelete(ob);\n%=======================================================================\n\n%=======================================================================\nfunction [c1,c2,c3,fs] = colours\nglobal defaults\nc1 = [1 1 1];\nc2 = [1 1 1];\nc3 = [0 0 0];\nfs = 14;\nif isfield(defaults,'ui'),\n ui = defaults.ui;\n if isfield(ui,'colour1'), c1 = ui.colour1; end;\n if isfield(ui,'colour2'), c2 = ui.colour2; end;\n if isfield(ui,'colour3'), c3 = ui.colour3; end;\n if isfield(ui,'fs'), fs = ui.fs; end;\nend;\n%=======================================================================\n\n%=======================================================================\nfunction select_rec(ob, varargin)\nsel = [];\ntop = get(ob,'Parent');\nstart = get(findobj(top,'Tag','edit'),'String');\nfilt = get(findobj(top,'Tag','regexp'),'Userdata');\nfilt.filt = {get(findobj(top,'Tag','regexp'), 'String')};\nfob = findobj(top,'Tag','frame');\nif ~isempty(fob)\n filt.frames = get(fob,'Userdata');\nelse\n filt.frames = [];\nend;\nptr = get(top,'Pointer');\ntry,\n set(top,'Pointer','watch');\n sel = select_rec1(start,filt);\ncatch,\n set(top,'Pointer',ptr);\n sel = '';\nend;\nset(top,'Pointer',ptr);\nalready= get(findobj(top,'Tag','selected'),'String');\nfb = sib(ob,'files');\nlim = get(fb,'Userdata');\nlimsel = min(lim(2)-size(already,1),size(sel,1));\nset(findobj(top,'Tag','selected'),'String',strvcat(already,sel(1:limsel,:)),'Value',[]);\nmsg(ob,sprintf('Added %d/%d matching files to selection.', limsel, size(sel,1)));\nif ~isfinite(lim(1)) || size(sel,1)>=lim(1),\n set(sib(ob,'D'),'Enable','on');\nelse\n set(sib(ob,'D'),'Enable','off');\nend;\n%=======================================================================\n\n%=======================================================================\nfunction sel=select_rec1(cdir,filt)\nsel='';\n[t,d] = listfiles(cdir,filt);\nif ~isempty(t)\n sel = [repmat([cdir,filesep],size(t,1),1),t];\nend;\nfor k = 1:size(d,1)\n if ~strcmp(deblank(d(k,:)),'.') && ~strcmp(deblank(d(k,:)),'..')\n sel1 = select_rec1(fullfile(cdir,deblank(d(k,:))),filt);\n if ~isempty(sel1) && ~isempty(sel),\n sel = strvcat(sel, sel1);\n elseif ~isempty(sel1),\n sel = sel1;\n end;\n end;\nend;\n%=======================================================================\n\n%=======================================================================\nfunction sfilt=mk_filter(typ,filt,frames)\nif nargin<3, frames = '1'; end;\nif nargin<2, filt = '.*'; end;\nif nargin<1, typ = 'any'; end;\nswitch lower(typ),\ncase {'any','*'}, code = 0; ext = {'.*'};\ncase {'image'}, code = 1; ext = {'.*\\.nii$','.*\\.img$','.*\\.NII$','.*\\.IMG$'};\ncase {'nifti'}, code = 0; ext = {'.*\\.nii$','.*\\.img$','.*\\.NII$','.*\\.IMG$'};\ncase {'extimage'}, code = 1; ext = {'.*\\.nii(,[0-9]*){0,1}$',...\n '.*\\.img(,[0-9]*){0,1}$',...\n '.*\\.NII(,[0-9]*){0,1}$',...\n '.*\\.IMG(,[0-9]*){0,1}$'};\ncase {'xml'}, code = 0; ext = {'.*\\.xml$','.*\\.XML$'};\ncase {'mat'}, code = 0; ext = {'.*\\.mat$','.*\\.MAT$'};\ncase {'batch'}, code = 0; ext = {'.*\\.mat$','.*\\.MAT$','.*\\.m$','.*\\.M$','.*\\.xml$','.*\\.XML$'};\ncase {'dir'}, code =-1; ext = {'.*'};\ncase {'extdir'}, code =-1; ext = {['.*' filesep '$']};\notherwise, code = 0; ext = {typ};\nend;\nsfilt = struct('code',code,'frames',frames,'ext',{ext},...\n 'filt',{{filt}});\n%=======================================================================\n\n%=======================================================================\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_scalp2d_ext.m", "ext": ".m", "path": "spm5-master/spm_eeg_scalp2d_ext.m", "size": 6685, "source_encoding": "utf_8", "md5": "9cd4f0e11f4b8f2daa8a686d44a20f42", "text": "function varargout = spm_eeg_scalp2d_ext(varargin)\n% SPM_EEG_SCALP2D_EXT M-file for spm_eeg_scalp2d_ext.fig\n% SPM_EEG_SCALP2D_EXT, by itself, creates a new SPM_EEG_SCALP2D_EXT or raises the existing\n% singleton*.\n%\n% H = SPM_EEG_SCALP2D_EXT returns the handle to a new SPM_EEG_SCALP2D_EXT or the handle to\n% the existing singleton*.\n%\n% SPM_EEG_SCALP2D_EXT('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SPM_EEG_SCALP2D_EXT.M with the given input arguments.\n%\n% SPM_EEG_SCALP2D_EXT('Property','Value',...) creates a new SPM_EEG_SCALP2D_EXT or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before spm_eeg_scalp2d_ext_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to spm_eeg_scalp2d_ext_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Copyright 2002-2003 The MathWorks, Inc.\n\n% Edit the above text to modify the response to help spm_eeg_scalp2d_ext\n\n% Last Modified by GUIDE v2.5 22-Nov-2005 17:06:20\n\n% Colon removed so that times output to Matlab window\tDoris Eckstein\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @spm_eeg_scalp2d_ext_OpeningFcn, ...\n 'gui_OutputFcn', @spm_eeg_scalp2d_ext_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before spm_eeg_scalp2d_ext is made visible.\nfunction spm_eeg_scalp2d_ext_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to spm_eeg_scalp2d_ext (see VARARGIN)\n\n% Choose default command line output for spm_eeg_scalp2d_ext\nhandles.output = hObject;\n\nhandles.D = varargin{1};\nhandles.T = varargin{2}; % input in peri-stimulus time (ms)\n\nhandles.ms = [-handles.D.events.start:handles.D.events.stop]*1000/handles.D.Radc;\n\nfor i = 1:length(handles.T)\n\ttmp = (handles.T(i) - handles.ms).^2;\n\t[m, ind(i)] = min(tmp);\nend\n\nhandles.T = ind;\n\n% locations\nCTF = load(fullfile(spm('dir'), 'EEGtemplates', handles.D.channels.ctf));\n%CTF.Cpos = CTF.Cpos(:, handles.D.channels.order(handles.D.channels.eeg));\nhandles.D.gfx.channels = intersect(handles.D.gfx.channels,handles.D.channels.eeg);\t% to ensure EOG not included\nCTF.Cpos = CTF.Cpos(:, handles.D.channels.order(handles.D.gfx.channels));\n\nhandles.x = min(CTF.Cpos(1,:)):0.005:max(CTF.Cpos(1,:));\nhandles.y = min(CTF.Cpos(2,:)):0.005:max(CTF.Cpos(2,:));\n\n[handles.x1, handles.y1] = meshgrid(handles.x, handles.y);\nhandles.xp = CTF.Cpos(1,:)';\nhandles.yp = CTF.Cpos(2,:)';\n\nhandles.event = varargin{3};\n\nif length(handles.T) > 1\n % average, remove slider\n set(handles.slider1, 'Visible', 'off');\n set(handles.text2, 'Visible', 'off');\nelse\n % set slider's range and initial value\n set(handles.slider1, 'min', handles.ms(1));\n set(handles.slider1, 'max', handles.ms(end));\n set(handles.slider1, 'Value', handles.ms(handles.T));\nend\n\n% Update handles structure\nguidata(hObject, handles);\n\nplot_spatial(hObject, handles);\n\n% UIWAIT makes spm_eeg_scalp2d_ext wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = spm_eeg_scalp2d_ext_OutputFcn(hObject, eventdata, handles)\n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on slider movement.\nfunction slider1_Callback(hObject, eventdata, handles)\n% hObject handle to slider1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\n\nT = get(handles.slider1, 'Value')\n\ntmp = (T - handles.ms).^2;\n[m, i] = min(tmp);\n\nhandles.T = i;\n\nguidata(hObject, handles);\n\nplot_spatial(hObject, handles);\n\n% --- Executes during object creation, after setting all properties.\nfunction slider1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to slider1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\nfunction plot_spatial(hObject, handles)\n\nT = handles.T;\nD = handles.D;\nevent = handles.event;\n\n% data\nif length(T) == 1\n d = squeeze(D.data(D.gfx.channels, T, event));\n \n if ~isfield(handles, 'Colourbar')\n handles.CLim1 = min(min(D.data(setdiff(D.gfx.channels, D.channels.Bad), :, event)));\n handles.CLim2 = max(max(D.data(setdiff(D.gfx.channels, D.channels.Bad), :, event)));\n end\nelse\n\td = squeeze(mean(D.data(D.gfx.channels, T, event), 2));\nend\n\n%Exclude bad channels\nbadchan = intersect(D.gfx.channels,D.channels.Bad);\nif ~isempty(badchan)\n d(badchan) = NaN;\nend\n\nz = griddata(handles.xp, handles.yp, d, handles.x1, handles.y1);\n\nif length(T) == 1\n set(handles.text1, 'String', sprintf('%d ms', round(handles.ms(T))));\nelse\n set(handles.text1, 'String', 'average');\nend\n\naxes(handles.axes1);\ncla\nsurface(handles.x, handles.y, z);\naxis off\nshading('interp')\nhold on\nplot3(handles.xp, handles.yp, d, 'k.');\n\nif ~isfield(handles, 'Colourbar')\n set(handles.axes1, 'CLim', [handles.CLim1 handles.CLim2])\n handles.Colourbar = colorbar;\n ylabel(handles.Colourbar, D.units, 'FontSize', 16);\nend\n\nguidata(hObject, handles);\n\ndrawnow\n\n\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_displTes.m", "ext": ".m", "path": "spm5-master/spm_eeg_inv_displTes.m", "size": 3729, "source_encoding": "utf_8", "md5": "8c8ce34a4598902e61b0c9f1559207fe", "text": "function [p,hFig] = spm_eeg_inv_displTes(tsurf,c)\n% FORMAT [p,f] = spm_eeg_inv_displTes(tsurf,c)\n%\n% Display a tessalated surface, with color c if provided : \n% if c is not provided, it uses 1 color for all surface.\n% 'spm_eeg_inv_displTes' returns handle to patch & figure\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Christophe Phillips,\n% $Id$\n\n% mono_c = 1/0 uses monocolor or provided c\n% tri_c = 1/0 , color specified on triangles or vertices\n\nif nargin==0\n Pmod = spm_select(1,'^model.*\\.mat$','Select model to display');\n load(Pmod)\n if length(model.head)>1\n % Select surface to display\n list = '';\n for ii=1:length(model.head)\n list = strvcat(list,model.head(ii).info.str);\n end\n tsurf_i = spm_input('Display which surface','+1','m',list);\n tsurf = model.head(tsurf_i);\n else\n tsurf = model.head(1);\n end\nend\n\n\nNvert = tsurf.nr(1) ;\nNtri = tsurf.nr(2) ;\ntry\n vert = tsurf.M*[tsurf.XYZvx ; ones(1,Nvert)]; vert = vert(1:3,:)';\ncatch\n vert = tsurf.XYZmm';\nend\ntri = tsurf.tri' ;\n\n%colo_skin = [1 .7 .55] ;\n%colo_skin = [1 .5 .45] ;\ncolo_skin = [1 0 0] ;\n\nmono_c = 0 ;\nif nargin<2\n\tc = ones(Ntri,1)*colo_skin ;\n\tmono_c = 1 ;\n\ttri_c = 1 ;\nelseif nargin==2\n\tif (size(c,1)==1) & ((size(c,2)==1)|(size(c,2)==3))\n\t\tmono_c = 1 ;\n\telseif size(c,1)==tsurf.nr(2)\n\t\ttri_c = 1 ;\n\t\tc3 = apply_colormap(c) ;\n\t\tc = c3 ;\n\telseif size(c,1)==tsurf.nr(1)\n\t\ttri_c = 0 ;\n\t\tc3 = apply_colormap(c) ;\n\t\tc = c3 ;\n\telse\n\t\terror('Wrong colour specification') ;\n\tend\nend\n\nhFig = spm_figure('FindWin');\nif isempty(hFig)\n hFig = figure;\nelse\n spm_figure('Clear',hFig);\n spm_figure('ColorMap','jet');\nend\n\nfigure(hFig) ;\n% set(f,'Render','OpenGL')\nset(hFig,'Render','zbuffer')\nif mono_c\n\tp = patch('Vertices',vert,'Faces',tri,'FaceColor',colo_skin) ;\n%\tp = patch('Vertices',vert,'Faces',tri,'FaceColor',[ 0.3 0.8 0.8 ]) ;\n%\tp = patch('Vertices',vert,'Faces',tri,'FaceVertexCData',c) ;\n%\tset(p,'FaceLighting','phong','SpecularStrength',.1,...\n%\t\t'AmbientStrength',.45,'EdgeColor','none') ;\n\t\t% ,'FaceColor','interp') ;\n%\tset(p,'FaceLighting','phong','SpecularStrength',.001,...\n%\t\t'AmbientStrength',.2,'EdgeColor','none',...\n%\t\t'DiffuseStrength',.6,'SpecularExponent',20) ;\n\t\t% ,'FaceColor','interp') ;\nelse\n\tif tri_c\n\t\tp = patch('Vertices',vert,'Faces',tri,'FaceVertexCData',c)\n\t\tset(p,'FaceLighting','phong','SpecularStrength',.1,...\n\t\t\t'AmbientStrength',.45,'EdgeColor','none',...\n\t\t\t'FaceColor','interp') ;\n\telse\n\t\tp = patch('Vertices',vert,'Faces',tri,'FaceVertexCData',c)\n\t\tset(p,'FaceLighting','phong','SpecularStrength',.1,...\n\t\t\t'AmbientStrength',.45,'EdgeColor','none',...\n\t\t\t'FaceColor','interp') ;\n\tend\nend\n\nview(3)\naxis equal\n%axis([1 181 1 217 1 181])\naxis vis3d\nrotate3d on\naxis off\n\nview(135,15)\n\n%h1 = light('Position',[1 3 3]) ;\n%h2 = light('Position',[1 -1 -1]) ;\n%h3 = light('Position',[-3 -1 0]) ;\n\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nfunction c3 = apply_colormap(c)\n\n% Scale between the min and max of the values in c\nmc = min(c) ; Mc = max(c) ; dc = Mc-mc ;\n\n% Scale symetrically around 0 the values of c\n%mc = -max(abs(c)) ; dc = -2*mc ;\n\n% Colormap : white-blue-black-red-white\n%colormap(hot(128)), tmp_scale = colormap ; tmp2 = fliplr(flipud(tmp_scale)) ; col_scale = [tmp2 ; tmp_scale] ;\n\n%colormap(jet(256)), col_scale = colormap ;\n%colormap(gray(256)), col_scale = colormap ;\ncolormap(cool(256)), col_scale = colormap ;\n\n\ncolormap(col_scale)\n\nind_c = round((c-mc)/dc*255+1) ;\n\nc3 = col_scale(ind_c,:) ;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_preproc.m", "ext": ".m", "path": "spm5-master/spm_config_preproc.m", "size": 27234, "source_encoding": "utf_8", "md5": "df3bace7f557a516e2708fbde2621df0", "text": "function job = spm_config_preproc\n% Configuration file for Segment jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_preproc.m 1032 2007-12-20 14:45:55Z john $\n\n\n%_______________________________________________________________________\n\nentry = inline(['struct(''type'',''entry'',''name'',name,'...\n '''tag'',tag,''strtype'',strtype,''num'',num,''help'',{{}})'],...\n 'name','tag','strtype','num');\n\nfiles = inline(['struct(''type'',''files'',''name'',name,'...\n '''tag'',tag,''filter'',fltr,''num'',num,''help'',{{}})'],...\n 'name','tag','fltr','num');\n\nmnu = inline(['struct(''type'',''menu'',''name'',name,'...\n '''tag'',tag,''labels'',{labels},''values'',{values},''help'',{{}})'],...\n 'name','tag','labels','values');\n\nbranch = inline(['struct(''type'',''branch'',''name'',name,'...\n '''tag'',tag,''val'',{val},''help'',{{}})'],...\n 'name','tag','val');\n\n%_______________________________________________________________________\n\ndata = files('Data','data','image',[1 Inf]);\ndata.help = {[...\n'Select scans for processing. ',...\n'This assumes that there is one scan for each subject. ',...\n'Note that multi-spectral (when there are two or more registered ',...\n'images of different contrasts) processing is not yet implemented ',...\n'for this method.']};\n\n%------------------------------------------------------------------------\n\npriors = files('Tissue probability maps','tpm','image',3);\npriors.def = 'preproc.tpm';\npriors.dir = fullfile(spm('Dir'),'tpm');\npriors.help = {...\n[...\n'Select the tissue probability images. '...\n'These should be maps of grey matter, white matter ',...\n'and cerebro-spinal fluid probability. '...\n'A nonlinear deformation field is estimated that best overlays the '...\n'tissue probability maps on the individual subjects'' image. '...\n'The default tissue probability maps are modified versions of the '...\n'ICBM Tissue Probabilistic Atlases.',...\n'These tissue probability maps are kindly provided by the ',...\n'International Consortium for Brain ',...\n'Mapping, John C. Mazziotta and Arthur W. Toga. ',...\n'http://www.loni.ucla.edu/ICBM/ICBM_TissueProb.html. ',...\n'The original data are derived from 452 T1-weighted scans, ',...\n'which were aligned with an atlas space, corrected for scan ',...\n'inhomogeneities, and classified ',...\n'into grey matter, white matter and cerebrospinal fluid. ',...\n'These data were then affine registered to the MNI space and ',...\n'downsampled to 2mm resolution.'],...\n'',...\n[...\n'Rather than assuming stationary prior probabilities based upon mixing '...\n'proportions, additional information is used, based on other subjects'' brain '...\n'images. Priors are usually generated by registering a large number of '...\n'subjects together, assigning voxels to different tissue types and averaging '...\n'tissue classes over subjects. '...\n'Three tissue classes are used: grey matter, white matter and cerebro-spinal fluid. '...\n'A fourth class is also used, which is simply one minus the sum of the first three. '...\n'These maps give the prior probability of any voxel in a registered image '...\n'being of any of the tissue classes - irrespective of its intensity.'],...\n'',...\n[...\n'The model is refined further by allowing the tissue probability maps to be '...\n'deformed according to a set of estimated parameters. '...\n'This allows spatial normalisation and segmentation to be combined into '...\n'the same model. '...\n'This implementation uses a low-dimensional approach, which parameterises '...\n'the deformations by a linear combination of about a thousand cosine '...\n'transform bases. '...\n'This is not an especially precise way of encoding deformations, but it '...\n'can model the variability of overall brain shape. '...\n'Evaluations by Hellier et al have shown that this simple model can achieve '...\n'a registration accuracy comparable to other fully automated methods with '...\n'many more parameters.']};\n\n%------------------------------------------------------------------------\n\nngaus = entry('Gaussians per class','ngaus','n',[4 1]);\nngaus.def = 'preproc.ngaus';\n%ngaus.val = {[2 2 2 4]};\nngaus.help = {[...\n'The number of Gaussians used to represent the intensity distribution '...\n'for each tissue class can be greater than one. '...\n'In other words, a tissue probability map may be shared by several clusters. '...\n'The assumption of a single Gaussian distribution for each class does not '...\n'hold for a number of reasons. '...\n'In particular, a voxel may not be purely of one tissue type, and instead '...\n'contain signal from a number of different tissues (partial volume effects). '...\n'Some partial volume voxels could fall at the interface between different '...\n'classes, or they may fall in the middle of structures such as the thalamus, '...\n'which may be considered as being either grey or white matter. '...\n'Various other image segmentation approaches use additional clusters to '...\n'model such partial volume effects. '...\n'These generally assume that a pure tissue class has a Gaussian intensity '...\n'distribution, whereas intensity distributions for partial volume voxels '...\n'are broader, falling between the intensities of the pure classes. '...\n'Unlike these partial volume segmentation approaches, the model adopted '...\n'here simply assumes that the intensity distribution of each class may '...\n'not be Gaussian, and assigns belonging probabilities according to these '...\n'non-Gaussian distributions. '...\n'Typical numbers of Gaussians could be two for grey matter, two for white '...\n'matter, two for CSF, and four for everything else.']};\n\n%------------------------------------------------------------------------\n\nwarpreg = entry('Warping Regularisation','warpreg','e',[1 1]);\nwarpreg.def = 'preproc.warpreg';\n%warpreg.val = {1};\nwarpreg.help = {[...\n'The objective function for registering the tissue probability maps to the ',...\n'image to process, involves minimising the sum of two terms. ',...\n'One term gives a function of how probable the data is given the warping parameters. ',...\n'The other is a function of how probable the parameters are, and provides a ',...\n'penalty for unlikely deformations. ',...\n'Smoother deformations are deemed to be more probable. ',...\n'The amount of regularisation determines the tradeoff between the terms. ',...\n'Pick a value around one. However, if your normalised images appear ',...\n'distorted, then it may be an idea to increase the amount of ',...\n'regularisation (by an order of magnitude). ',...\n'More regularisation gives smoother deformations, ',...\n'where the smoothness measure is determined by the bending energy of the deformations. ']};\n%------------------------------------------------------------------------\n\nwarpco = entry('Warp Frequency Cutoff','warpco','e',[1 1]);\nwarpco.def = 'preproc.warpco';\n%warpco.val = {25};\nwarpco.help = {[...\n'Cutoff of DCT bases. Only DCT bases of periods longer than the ',...\n'cutoff are used to describe the warps. The number actually used will ',...\n'depend on the cutoff and the field of view of your image. ',...\n'A smaller cutoff frequency will allow more detailed deformations ',...\n'to be modelled, but unfortunately comes at a cost of greatly increasing ',...\n'the amount of memory needed, and the time taken.']};\n\n%------------------------------------------------------------------------\n\nbiasreg = mnu('Bias regularisation','biasreg',{...\n'no regularisation (0)','extremely light regularisation (0.00001)',...\n'very light regularisation (0.0001)','light regularisation (0.001)',...\n'medium regularisation (0.01)','heavy regularisation (0.1)',...\n'very heavy regularisation (1)','extremely heavy regularisation (10)'},...\n{0, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1.0, 10});\nbiasreg.def = 'preproc.biasreg';\n%biasreg.val = {0.0001};\nbiasreg.help = {[...\n'MR images are usually corrupted by a smooth, spatially varying artifact that modulates the intensity ',...\n'of the image (bias). ',...\n'These artifacts, although not usually a problem for visual inspection, can impede automated ',...\n'processing of the images.'],...\n'',...\n[...\n'An important issue relates to the distinction between intensity variations that arise because of ',...\n'bias artifact due to the physics of MR scanning, and those that arise due to different tissue ',...\n'properties. The objective is to model the latter by different tissue classes, while modelling the ',...\n'former with a bias field. ',...\n'We know a priori that intensity variations due to MR physics tend to be spatially smooth, ',...\n'whereas those due to different tissue types tend to contain more high frequency information. ',...\n'A more accurate estimate of a bias field can be obtained by including prior knowledge about ',...\n'the distribution of the fields likely to be encountered by the correction algorithm. ',...\n'For example, if it is known that there is little or no intensity non-uniformity, then it would be wise ',...\n'to penalise large values for the intensity non-uniformity parameters. ',...\n'This regularisation can be placed within a Bayesian context, whereby the penalty incurred is the negative ',...\n'logarithm of a prior probability for any particular pattern of non-uniformity.']};\n\n%------------------------------------------------------------------------\n\nbiasfwhm = mnu('Bias FWHM','biasfwhm',{...\n'30mm cutoff','40mm cutoff','50mm cutoff','60mm cutoff','70mm cutoff',...\n'80mm cutoff','90mm cutoff','100mm cutoff','110mm cutoff','120mm cutoff',...\n'130mm cutoff','140mm cutoff','150mm cutoff','No correction'},...\n{30,40,50,60,70,80,90,100,110,120,130,140,150,Inf});\nbiasfwhm.def = 'preproc.biasfwhm';\n%biasfwhm.val = {60};\nbiasfwhm.help = {[...\n'FWHM of Gaussian smoothness of bias. ',...\n'If your intensity non-uniformity is very smooth, then choose a large ',...\n'FWHM. This will prevent the algorithm from trying to model out intensity variation ',...\n'due to different tissue types. The model for intensity non-uniformity is one ',...\n'of i.i.d. Gaussian noise that has been smoothed by some amount, ',...\n'before taking the exponential. ',...\n'Note also that smoother bias fields need fewer parameters to describe them. ',...\n'This means that the algorithm is faster for smoother intensity non-uniformities.']};\n\n%------------------------------------------------------------------------\n\nregtype = mnu('Affine Regularisation','regtype',...\n {'No Affine Registration','ICBM space template - European brains',...\n 'ICBM space template - East Asian brains', 'Average sized template','No regularisation'},...\n {'','mni','eastern','subj','none'});\nregtype.def = 'preproc.regtype';\nregtype.help = {[...\n'The procedure is a local optimisation, so it needs reasonable initial '...\n'starting estimates. Images should be placed in approximate alignment '...\n'using the Display function of SPM before beginning. '...\n'A Mutual Information affine registration with the tissue '...\n'probability maps (D''Agostino et al, 2004) is used to achieve '...\n'approximate alignment. '...\n'Note that this step does not include any model for intensity non-uniformity. '...\n'This means that if the procedure is to be initialised with the affine '...\n'registration, then the data should not be too corrupted with this artifact.'...\n'If there is a lot of intensity non-uniformity, then manually position your '...\n'image in order to achieve closer starting estimates, and turn off the '...\n'affine registration.'],...\n'',...\n[...\n'Affine registration into a standard space can be made more robust by ',...\n'regularisation (penalising excessive stretching or shrinking). The ',...\n'best solutions can be obtained by knowing the approximate amount of ',...\n'stretching that is needed (e.g. ICBM templates are slightly bigger ',...\n'than typical brains, so greater zooms are likely to be needed). ',...\n'For example, if registering to an image in ICBM/MNI space, then choose this ',...\n'option. If registering to a template that is close in size, then ',...\n'select the appropriate option for this.']};\n\n%------------------------------------------------------------------------\n\nsamp = entry('Sampling distance','samp','e',[1 1]);\nsamp.def = 'preproc.samp';\n%samp.val = {3};\nsamp.help = {[...\n'The approximate distance between sampled points when estimating the ',...\n'model parameters. Smaller values use more of the data, but the procedure ',...\n'is slower.']};\n\n%------------------------------------------------------------------------\nmsk = files('Masking image','msk','image',[0 1]);\nmsk.val = {''};\nmsk.help = {[...\n'The segmentation can be masked by an image that conforms to ',...\n'the same space as the images to be segmented. If an image is selected, then ',...\n'it must match the image(s) voxel-for voxel, and have the same ',...\n'voxel-to-world mapping. Regions containing a value of zero in this image ',...\n'do not contribute when estimating the various parameters. ']};\n\n%------------------------------------------------------------------------\n\nopts = branch('Custom','opts',{priors,ngaus,regtype,warpreg,warpco,biasreg,biasfwhm,samp,msk});\nopts.help = {[...\n'Various options can be adjusted in order to improve the performance of the '...\n'algorithm with your data. Knowing what works best should be a matter '...\n'of empirical exploration. For example, if your data has very little '...\n'intensity non-uniformity artifact, then the bias regularisation should '...\n'be increased. This effectively tells the algorithm that there is very little '...\n'bias in your data, so it does not try to model it.']};\n\n%------------------------------------------------------------------------\n\ncleanup.tag = 'cleanup';\ncleanup.type = 'menu';\ncleanup.name = 'Clean up any partitions';\ncleanup.help = {[...\n'This uses a crude routine for extracting the brain from segmented',...\n'images. It begins by taking the white matter, and eroding it a',...\n'couple of times to get rid of any odd voxels. The algorithm',...\n'continues on to do conditional dilations for several iterations,',...\n'where the condition is based upon gray or white matter being present.',...\n'This identified region is then used to clean up the grey and white',...\n'matter partitions, and has a slight influences on the CSF partition.'],'',[...\n'If you find pieces of brain being chopped out in your data, then you ',...\n'may wish to disable or tone down the cleanup procedure.']};\ncleanup.labels = {'Dont do cleanup','Light Clean','Thorough Clean'};\ncleanup.values = {0 1 2};\ncleanup.val = {0};\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\n\n% bias = struct('type','branch','name','Bias correction','tag','bias','dim',Inf,'val',{{biasreg,biasfwhm}});\n% bias.help = {[...\n% 'This uses a Bayesian framework (again) to model intensity ',...\n% 'inhomogeneities in the image(s). The variance associated with each ',...\n% 'tissue class is assumed to be multiplicative (with the ',...\n% 'inhomogeneities). The low frequency intensity variability is ',...\n% 'modelled by a linear combination of three dimensional DCT basis ',...\n% 'functions (again), using a fast algorithm (again) to generate the ',...\n% 'curvature matrix. The regularisation is based upon minimising the ',...\n% 'integral of square of the fourth derivatives of the modulation field ',...\n% '(the integral of the squares of the first and second derivatives give the ',...\n% 'membrane and bending energies respectively).']};\n\nbiascor = mnu('Bias Corrected','biascor',{'Save Bias Corrected','Don''t Save Corrected'},{1,0});\nbiascor.val = {1};\nbiascor.help = {[...\n'This is the option to produce a bias corrected version of your image. ',...\n'MR images are usually corrupted by a smooth, spatially varying artifact that modulates the intensity ',...\n'of the image (bias). ',...\n'These artifacts, although not usually a problem for visual inspection, can impede automated ',...\n'processing of the images. The bias corrected version should have more uniform intensities within ',...\n'the different types of tissues.']};\n\ngrey = mnu('Grey Matter','GM',{...\n 'None',...\n 'Native Space',...\n 'Unmodulated Normalised',...\n 'Modulated Normalised',...\n 'Native + Unmodulated Normalised',...\n 'Native + Modulated Normalised',...\n 'Native + Modulated + Unmodulated',...\n 'Modulated + Unmodulated Normalised'},...\n {[0 0 0],[0 0 1],[0 1 0],[1 0 0],[0 1 1],[1 0 1],[1 1 1],[1 1 0]});\ngrey.val = {[0 0 1]};\ngrey.help = {'Options to produce grey matter images: c1*.img, wc1*.img and mwc1*.img.'};\nwhite = grey;\nwhite.name = 'White Matter';\nwhite.tag = 'WM';\nwhite.help = {'Options to produce white matter images: c2*.img, wc2*.img and mwc2*.img.'};\ncsf = grey;\ncsf.name = 'Cerebro-Spinal Fluid';\ncsf.tag = 'CSF';\ncsf.val = {[0 0 0]};\ncsf.help = {'Options to produce CSF images: c3*.img, wc3*.img and mwc3*.img.'};\n\noutput = branch('Output Files','output',{grey,white,csf,biascor,cleanup});\noutput.help = {[...\n'This routine produces spatial normalisation parameters (*_seg_sn.mat files) by default. ',...\n'These can be used for writing spatially normalised versions of your data, via the \"Normalise: Write\" option. ',...\n'This mechanism may produce superior results than the \"Normalise: Estimate\" option, although ',...\n'this may need some empirical evaluations.'],...\n'',...\n[...\n'In addition, it also produces files that can be used for doing inverse normalisation. ',...\n'If you have an image of regions defined in the standard space, then the inverse deformations ',...\n'can be used to warp these regions so that it approximately overlay your image. ',...\n'To use this facility, the bounding-box and voxel sizes should be set to non-finite values ',...\n'(e.g. [NaN NaN NaN] for the voxel sizes, and ones(2,3)*NaN for the bounding box. ',...\n'This would be done by the spatial normalisation module, which allows you to select a ',...\n'set of parameters that describe the nonlinear warps, and the images that they should be applied to.'],...\n'',...\n[...\n'There are a number of options about what data you would like the routine to produce. ',...\n'The routine can be used for producing images of tissue classes, as well as bias corrected images. ',...\n'The native space option will produce a tissue class image (c*) that is in alignment with ',...\n'the original/* (see Figure \\ref{seg1})*/. You can also produce spatially normalised versions - both with (mwc*) and without (wc*) ',...\n'modulation/* (see Figure \\ref{seg2})*/. The bounding box and voxel sizes of the spatially normalised versions are the ',...\n'same as that of the tissue probability maps with which they are registered. ',...\n'These can be used for doing voxel-based morphometry with (both un-modulated and modulated). ',...\n'All you need to do is smooth them and do the stats (which means no more questions on the mailing list ',...\n'about how to do \"optimized VBM\").'],...\n'',...\n[...\n'Modulation is to compensate for the effect of spatial normalisation. When warping a series ',...\n'of images to match a template, it is inevitable that volumetric differences will be introduced ',...\n'into the warped images. For example, if one subject''s temporal lobe has half the volume of that of ',...\n'the template, then its volume will be doubled during spatial normalisation. This will also ',...\n'result in a doubling of the voxels labelled grey matter. In order to remove this confound, the ',...\n'spatially normalised grey matter (or other tissue class) is adjusted by multiplying by its relative ',...\n'volume before and after warping. If warping results in a region doubling its volume, then the ',...\n'correction will halve the intensity of the tissue label. This whole procedure has the effect of preserving ',...\n'the total amount of grey matter signal in the normalised partitions.'],...\n['/*',...\n'\\begin{figure} ',...\n'\\begin{center} ',...\n'\\includegraphics[width=150mm]{images/seg1} ',...\n'\\end{center} ',...\n'\\caption{Segmentation results. ',...\n'These are the results that can be obtained in the original space of the image ',...\n'(i.e. the results that are not spatially normalised). ',...\n'Top left: original image (X.img). ',...\n'Top right: bias corrected image (mX.img). ',...\n'Middle and bottom rows: segmented grey matter (c1X.img), ',...\n'white matter (c2X.img) and CSF (c3X.img). \\label{seg1}} ',...\n'\\end{figure} */'],...\n['/*',...\n'\\begin{figure} ',...\n'\\begin{center} ',...\n'\\includegraphics[width=150mm]{images/seg2} ',...\n'\\end{center} ',...\n'\\caption{Segmentation results. ',...\n'These are the spatially normalised results that can be obtained ',...\n'(note that CSF data is not shown). ',...\n'Top row: The tissue probability maps used to guide the segmentation. ',...\n'Middle row: Spatially normalised tissue maps of grey and white matter ',...\n'(wc1X.img and wc2X.img). ',...\n'Bottom row: Modulated spatially normalised tissue maps of grey and ',...\n'white matter (mwc1X.img and mwc2X.img). \\label{seg2}} ',...\n'\\end{figure} */'],...\n[...\n'A deformation field is a vector field, where three values are associated with ',...\n'each location in the field. The field maps from co-ordinates in the ',...\n'normalised image back to co-ordinates in the original image. The value of ',...\n'the field at co-ordinate [x y z] in the normalised space will be the ',...\n'co-ordinate [x'' y'' z''] in the original volume. ',...\n'The gradient of the deformation field at a co-ordinate is its Jacobian ',...\n'matrix, and it consists of a 3x3 matrix:'],...\n'',...\n'% / \\',...\n'% | dx''/dx dx''/dy dx''/dz |',...\n'% | |',...\n'% | dy''/dx dy''/dy dy''/dz |',...\n'% | |',...\n'% | dz''/dx dz''/dy dz''/dz |',...\n'% \\ /',...\n['/* \\begin{eqnarray*}',...\n'\\begin{pmatrix}',...\n'\\frac{dx''}{dx} & \\frac{dx''}{dy} & \\frac{dx''}{dz}\\cr',...\n'\\frac{dy''}{dx} & \\frac{dy''}{dy} & \\frac{dy''}{dz}\\cr',...\n'\\frac{dz''}{dx} & \\frac{dz''}{dy} & \\frac{dz''}{dz}\\cr',...\n'\\end{pmatrix}\\end{eqnarray*}*/'],...\n[...\n'The value of dx''/dy is a measure of how much x'' changes if y is changed by a ',...\n'tiny amount. ',...\n'The determinant of the Jacobian is the measure of relative volumes of warped ',...\n'and unwarped structures. The modulation step simply involves multiplying by ',...\n'the relative volumes /*(see Figure \\ref{seg2})*/.']};\n%------------------------------------------------------------------------\n\njob = branch('Segment','preproc',{data,output,opts});\njob.prog = @execute;\njob.vfiles = @vfiles;\njob.help = {[...\n'Segment, bias correct and spatially normalise - all in the same model/* \\cite{ashburner05}*/. ',...\n'This function can be used for bias correcting, spatially normalising ',...\n'or segmenting your data.'],...\n'',...\n[...\n'Many investigators use tools within older versions of SPM for '...\n'a technique that has become known as \"optimised\" voxel-based '...\n'morphometry (VBM). '...\n'VBM performs region-wise volumetric comparisons among populations of subjects. '...\n'It requires the images to be spatially normalised, segmented into '...\n'different tissue classes, and smoothed, prior to performing '...\n'statistical tests/* \\cite{wright_vbm,am_vbmreview,ashburner00b,john_should}*/. The \"optimised\" pre-processing strategy '...\n'involved spatially normalising subjects'' brain images to a '...\n'standard space, by matching grey matter in these images, to '...\n'a grey matter reference. The historical motivation behind this '...\n'approach was to reduce the confounding effects of non-brain (e.g. scalp) '...\n'structural variability on the registration. '...\n'Tissue classification in older versions of SPM required the images to be registered '...\n'with tissue probability maps. After registration, these '...\n'maps represented the prior probability of different tissue classes '...\n'being found at each location in an image. Bayes rule can '...\n'then be used to combine these priors with tissue type probabilities '...\n'derived from voxel intensities, to provide the posterior probability.'],...\n'',...\n[...\n'This procedure was inherently circular, because the '...\n'registration required an initial tissue classification, and the '...\n'tissue classification requires an initial registration. This circularity '...\n'is resolved here by combining both components into a single '...\n'generative model. This model also includes parameters that account '...\n'for image intensity non-uniformity. '...\n'Estimating the model parameters (for a maximum a posteriori solution) '...\n'involves alternating among classification, bias correction and registration steps. '...\n'This approach provides better results than simple serial applications of each component.'],...\n'',[...\n'Note that multi-spectral segmentation (e.g. from a registered T1 and T2 image) is ',...\n'not yet implemented, but is planned for a future SPM version.']};\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction execute(job)\njob.opts.tpm = strvcat(job.opts.tpm{:});\nif isfield(job.opts,'msk'),\n job.opts.msk = strvcat(job.opts.msk{:});\nend;\nfor i=1:numel(job.data),\n res = spm_preproc(job.data{i},job.opts);\n [sn(i),isn] = spm_prep2sn(res);\n [pth,nam] = spm_fileparts(job.data{i});\n savefields(fullfile(pth,[nam '_seg_sn.mat']),sn(i));\n savefields(fullfile(pth,[nam '_seg_inv_sn.mat']),isn);\nend;\nspm_preproc_write(sn,job.output);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction savefields(fnam,p)\nif length(p)>1, error('Can''t save fields.'); end;\nfn = fieldnames(p);\nif numel(fn)==0, return; end;\nfor i=1:length(fn),\n eval([fn{i} '= p.' fn{i} ';']);\nend;\nif spm_matlab_version_chk('7') >= 0\n save(fnam,'-V6',fn{:});\nelse\n save(fnam,fn{:});\nend;\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction vf = vfiles(job)\nopts = job.output;\nsopts = [opts.GM;opts.WM;opts.CSF];\nvf = cell(numel(job.data),2);\nfor i=1:numel(job.data),\n [pth,nam,ext,num] = spm_fileparts(job.data{i});\n vf{i,1} = fullfile(pth,[nam '_seg_sn.mat']);\n vf{i,2} = fullfile(pth,[nam '_seg_inv_sn.mat']);\n j = 3;\n if opts.biascor,\n vf{i,j} = fullfile(pth,['m' nam ext ',1']);\n j = j + 1;\n end;\n for k1=1:3,\n if sopts(k1,3),\n vf{i,j} = fullfile(pth,[ 'c', num2str(k1), nam, ext, ',1']);\n j = j + 1;\n end;\n if sopts(k1,2),\n vf{i,j} = fullfile(pth,[ 'wc', num2str(k1), nam, ext, ',1']);\n j = j + 1;\n end;\n if sopts(k1,1),\n vf{i,j} = fullfile(pth,['mwc', num2str(k1), nam, ext, ',1']);\n j = j + 1;\n end;\n end;\nend;\nvf = vf(:);\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "bst_headmodeler.m", "ext": ".m", "path": "spm5-master/bst_headmodeler.m", "size": 111935, "source_encoding": "utf_8", "md5": "a5f8e1434768799cd03d003a831e2737", "text": "function [varargout] = bst_headmodeler(varargin);\n%BST_HEADMODELER - Solution to the MEG/EEG forward problem\n% function [varargout] = bst_headmodeler(varargin);\n% Authorized syntax:\n% [G, OPTIONS] = bst_headmodeler(StudyFile, OPTIONS);\n% [G, OPTIONS] = bst_headmodeler(OPTIONS);\n% [OPTIONS] = bst_headmodeler;\n%\n% --------------------------------- INPUTS -------------------------------------\n% INPUTS\n%\n% [OPTIONS] = bst_headmodeler; Returns the default values for the OPTIONS\n% parameter structure\n% \n% StudyFile: the name of a BrainStorm study file. We suppose the\n% corresponding BrainStorm channel file is available in the same folder\n% with the conventional file name (e.g., for a study file calles\n% meg_brainstormstudy.mat, BST_HEADMODELER expects to find the\n% corresponding channel file under the name meg_channel.mat). If the\n% channel file were not sitting in the same folder as the study file,\n% OPTIONS.ChannelFile enforces computation of the forward model with the\n% channel information contained in OPTIONS.ChannelFile.\n% \n% If no further input arguments are specified, forward modeling is\n% completed with the default parameters specified below\n% \n% OPTIONS a structure where optional parameters may be specified using the\n% following fields Note: if no options are specified, BST_HEADMODELER will\n% proceed to the computation of the foward problem on a 3D grid of source\n% locations that cover the entire head volume See\n% OPTIONS.VolumeSourceGridSpacing for default settings\n% \n% Important notice: there is no need to define all the following fields\n% when using the OPTIONS argument. The undefined field(s) will be assigned\n% default values.\n%\n% *\n% * Fields Related to forward approach\n% *\n%\n% .Method: is either a character string or a cell array of two strings that\n% specifies the kind of approach to be applied to the compuation\n% of the foward model In case Method is a cell array, it should\n% contain 2 strings, one to specifiy the method to be used for MEG\n% and the other for . If only a single string is specified, the\n% foward computation will be completed on the set of corresponding\n% CHANndx only (i.e. MEG or MEG) Available forward modeling\n% methods and corresponding authorized strings for Method:\n% - MEG\n% 'meg_sphere' (DEFAULT) : Spherical head model designed\n% following the Sarvas analytical formulation (i.e.\n% considering the true orientation \n% of the magnetic field sensors) (see OPTIONS.HeadCenter)\n% 'meg_os' : MEG overlapping sphere forward model\n% 'meg_bem' : Apply BEM computation (see OPTIONS.BEM for details)\n% - \n% 'eeg_sphere' : Single-sphere forward modeling (see\n% OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity)\n% 'eeg_3sphere' : EEG forward modeling with a set of 3\n% concentric spheres (Scalp, Skull, Brain/CSF) (see\n% OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity)\n% 'eeg_3sphereBerg' (DEFAULT) : Same as eeg_3sphere with\n% correction for possible dipoles outside the sphere\n% 'eeg_os' : EEG overlapping sphere head model (see\n% OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity)\n% 'eeg_bem' : Apply BEM computation (see OPIONS.BEM for details)\n% \n% Default is {'meg_sphere','eeg_3sphereBerg'}; \n%\n% .HeadModelName : a character string that specifies the name of the\n% headmodel represented by this file, e.g \"Spherical\", \n% \"Overlapping Spheres\", \"Constant Collocation BEM\", etc.\n% Default is \"Default\", meaning it will include the the\n% name(s) of the method(s) used in the MEG and/or EEG\n% forward models\n%\n% *\n% * Fields Related to function's I/O\n% *\n% \n% .HeadModelFile : Specifies the name of the head model file where to store\n% the forward model. If set to 'default', the default\n% nomenclature for BrainStorm's head model file name is\n% used and BST_HEADMODELER creates a file in StudyFile's\n% folder.\n% Default is empty. \n% .ImageGridFile : Specifies the name of the file where to store the full\n% cortical gain matrix file If set to 'default', the\n% default nomenclature for BrainStorm's head model file\n% name is used and BST_HEADMODELER creates a file in\n% StudyFile's folder.\n% Default is empty.\n% .ImageGridBlockSize : Number of sources for which to compute the forward\n% model at a time in a block computation routines\n% (saves memory space). This option is relevant only\n% when some forward modeling on cortical surface is\n% requested (i.e. when .Cortex is specified)\n% Default is 2000\n% .FileNamePrefix : A string that specifies the prefix for all file names\n% (Channel, HeadModel, Gain Matrices) when .HeadModelFile\n% is set to 'default' and .ChannelFile is empty.\n% Default is 'bst_'\n% .Verbose : Toggles verbose mode on/off;\n% Default is 1 (on)\n% \n% *\n% * Fields Related to Head Geometry *\n% *\n% \n% .Scalp : A structure specifying the Scalp surface envelope to serve\n% for parameter adjustment of best-fitting sphere, with\n% following fields:\n% .FileName : A string specifying the name of the BrainStorm\n% tessellation file containing the Scalp\n% tessellation (default is 1);\n% .iGrid : An integer for the index of the Scalp surface in\n% the Faces, Vertices and Comments cell arrays in\n% the tessellation file\n% Default is empty (Best-fitting sphere is\n% computed from the sensor array).\n% .HeadCenter: a 3-element vector specifying the coordinates, in the\n% sensors coordinate system, of the center of the spheres that\n% might be used in the head model. \n% Default is estimated from the center of the best-fitting\n% sphere to the sensor locations\n% .Radii : a 3-element vector containing the radii of the single or 3\n% concentric spheres, when needed;\n% Order must be the following : [Rcsf, Routerskull, Rscalp];\n% Default is estimated from the best-fitting sphere to the\n% sensor locations and OPTIONS.Radii is set to: Rscalp [.88\n% .93 1]. Rscalp is estimated from the radius of the\n% best-fitting sphere;\n% .Conductivity : a 3-element vector containing the values for the\n% conductivity of the tissues in the following order:\n% [Ccsf, Cskull, Cscalp];\n% Default is set to [.33 .0042 .33];\n% .EEGRef : the NAME (not index of the channel file) of the electrode\n% that acts as the reference channel for the EEG. If data is\n% referenced to instantaneous average (i.e. so called\n% average-reference recording) value is 'AVERAGE REF'; \n% IMPORTANT NOTICE: When user calls bst_headmodeler with the\n% .ChannelLoc option and .ChannelType = 'EEG'and wants the EEG\n% reference to be e.g. channel 26, then .EEGRef should be set\n% to 'EEG 26' \n% Default is 'AVERAGE REF'.\n% \n% .OS_ComputeParam : if 1, force computation of all sphere parameters when\n% choosing a method based on either the MEG or EEG\n% overlapping-sphere technique, if 0 and when\n% .HeadModelFile is specified, sphere parameters are\n% loaded from the pre-computed HeadModel file.\n% Default is 1.\n%\n% .BEM : Structure that specifies the necessary BEM parameters \n% .Interpolative : Flag indicating whether exact or\n% interpolative approach is used to compute\n% the forward solution using BEM. \n% if set to 1, exact computation is run on a\n% set of points distributed wihtin the inner\n% head volume and any subsequent request for\n% a forward gain vector (e.g. during a\n% volumic source scan using RAP-MUSIC) is\n% computed using an interpolation of the\n% forward gain vectors of the closest volumic\n% grid points. This allows faster computation\n% of the BEM solution during source search.\n% if set to 0, exact computation is required\n% at every source location.\n% We recommend to set it to 0 (default) when\n% sources have fixed location, e.g.\n% constrained on the cortical surface.\n% .EnvelopeNames : a cell array of strutures that specifies\n% the ORDERED tessellated surfaces to be\n% included in the BEM computation. \n% .EnvelopeNames{k}.TessFile : A string for\n% the name of the tessellation file\n% containing the kth surface\n% .EnvelopeNames{k}.TessName : A string for\n% the name of the surface within the\n% tessellation file This string should match\n% one of the Comment strings in the\n% tessellation file. The chosen surfaces must\n% be ordered starting by the the innermost\n% surface (e.g. brain or inner skull\n% surface) and finishing with the outermost\n% layer (e.g. the scalp)\n% .Basis : set to either 'constant' or 'linear' (default)\n% .Test : set to either 'Galerkin' or 'Collocation' (default)\n% .ISA : Isolated-skull approach set to 0 or 1 (default is 1)\n% .NVertMax : Maximum number of vertices per envelope,\n% therefore leading to decimation of orginal\n% surfaces if necessary\n% (default is 1000)\n% .ForceXferComputation: if set to 1, force recomputation of\n% existing transfer matrices in current\n% study folder (replace existing\n% files);\n% Default is 1\n%\n% *\n% * Fields Related to Sensor Information *\n% *\n% \n% .ChannelFile : Specifies the name of the file containing the channel\n% information (needs to be a BrainStorm channel file). If\n% file does not exists and sensor information is provided in\n% .ChannelLoc, a BrainStorm Channl file with name\n% .ChannelFile is created\n% Default is left blank as this information is extracted\n% from the channel file associated to the chosen BrainStorm\n% studyfile.\n% .Channel : A full BrainStorm channel structure if no channel file is\n% specified;\n% Default is empty \n% .ChannelType : A string specifying the type of channel in ChannelLoc. Can\n% be either 'MEG' or 'EEG'. Note that the same channel type\n% is assumed for every channel.\n% Default is empty\n% .ChannelLoc : Specifies the location of the channels where to compute\n% the forward model Can be either a 3xNsens (for EEG or\n% MEG-magnetometer) or 6xNsens matrix (for the\n% MEG-gradiometer case). (for magnetometer or gradiometer\n% MEG - channel weights are set to -1 and 1 for each\n% magnetometer in the gradiometer respectively) Note that\n% in the MEG-gradiometer case, the 3 first (res. last) rows\n% of .ChannelLoc stand for each of the magnetometers of the\n% gradiometer set. In the case of a mixture of MEG magneto\n% and MEG gradio-meters, .ChannelLoc needs to be a 6xNsens\n% matrix where the last 3 rows are filled with NaN for\n% MEG-magnetometers. If ones wants to handle both EEG and MEG\n% sensors, please create a full ChannelFile and use the\n% .ChannelFile option.\n% Default is empty (Information extracted from the ChannelFile).\n% .ChannelOrient : Specifies the orientation of the channels where to\n% compute the EEG or MEG forward model Can be either a\n% 3xNsens (for EEG and magnetometer MEG) or 6xNsens (for\n% gradiometer MEG) matrix or a cell array of such matrices\n% (one cell per type of method selected)\n% Default is empty (Information extracted from the\n% ChannelFile or assume radial orientation when\n% .ChannelLoc is filled).\n%\n% *\n% * Fields Related to Source Models *\n% *\n% .SourceModel : A vector indicating the type of source models to be\n% computed; The following code is enfoced:\n% -1 : Compute the forward fields of Current Dipole sources\n% (available for all forward approaches)\n% 1 : 1st-order Current Multipole Sources \n% (available for sphere-based MEG approaches only)\n% User can set OPTIONS.SourceModel to e.g., [-1 1] to\n% compute forward models from both source models.\n% Default is -1 \n%\n%\n% *\n% * Fields Related to Source Localization *\n% *\n% .Cortex : A structure specifying the Cortex surface\n% envelope to serve as an image support with\n% following fields.\n% .FileName : A string specifying the name of\n% the BrainStorm tessellation file\n% containing the Cortex\n% tessellation;\n% .iGrid : An integer for the index of the\n% Cortex surface in the Faces,\n% Vertices and Comments cell arrays\n% in the tessellation file (default\n% is 1)\n% Default is empty.\n% .GridLoc : A 3xNsources matrix that contains the\n% locations of the sources at which the forward\n% model will be computed\n% Default is empty (Information taken from\n% OPTIONS.Cortex or OPTIONS.VolumeSourceGrid);\n% .GridOrient : a 3xNsources matrix that forces the source\n% orientation at every vertex of the .ImageGrid\n% cortical surface;\n% Defaults is empty; this information being\n% extracted from the corresponding tessellated\n% surface. \n% .ApplyGridOrient : if set to 1, force computation of the forward\n% fields by considering the local orientation of\n% the cortical surface;\n% If set to 0, a set of 3 orthogonal dipoles are\n% considered at each vertex location on the\n% tessellated surface. \n% Default is 1.\n% .VolumeSourceGrid : if set to 1, a 3D source grid is designed to\n% fit inside the head volume and will serve as a\n% source space for scannig techniques such as\n% RAP-MUSIC;\n% if set to 0, this grid will be computed at the\n% first call of e.g. RAP-MUSIC);\n% Default is 1 \n% .VolumeSourceGridSpacing : Spacing in centimeters between two consecutive\n% sources in the 3D source grid described above;\n% Default is 2 cm.\n% .VolumeSourceGridLoc : a 3xN matrix specifying the locations of the\n% grid points that will be used to design the\n% volumic search grid (see .VolumicSourceGrid)\n% Default is empty (locations are estimated\n% automatically to cover the estimated inner\n% head volume)\n% .SourceLoc : a 3xNsources matrix that contains the\n% locations of the sources at which the forward\n% model will be computed\n% Default is empty (Information taken from\n% OPTIONS.ImageGrid or\n% OPTIONS.VolumeSourceGrid);\n% .SourceOrient : a 3xNsources matrix that contains the\n% orientations of the sources at which the\n% forward model will be computed\n% Default is empty.\n%\n%\n% --------------------------------- OUTPUTS ------------------------------------\n% OUTPUT\n% G if the number of sources (Nsources) if less than\n% .ImageGridBlockSize then G is a gain matrix of dimension\n% Nsensors x Nsources: Each column of G is the forward field\n% created by a dipolar source of unit amplitude. Otherwise, G is\n% the name of the binary file containing the gain matrix. This\n% file can be read using the READ_GAIN function.\n% OPTIONS Returns the OPTIONS structure with updated fields following the\n% call to BST_HEADMODELER. Can be useful to obtain a full\n% BrainStorm Channel structure when only the .ChannelLoc and\n% possibly .ChannelOrient fields were provided.\n\n% ---------------------- 27-Jun-2005 10:43:31 -----------------------\n% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------\n%\n% CATEGORY: Forward Modeling\n%\n% Alphabetical list of external functions (non-Matlab):\n% toolbox\\bem_gain.m\n% toolbox\\bem_xfer.m\n% toolbox\\berg.m\n% toolbox\\bst_message_window.m\n% toolbox\\colnorm.m\n% toolbox\\get_channel.m\n% toolbox\\get_user_directory.m\n% toolbox\\good_channel.m\n% toolbox\\gridmaker.m\n% toolbox\\inorcol.m\n% toolbox\\norlig.m\n% toolbox\\overlapping_sphere.m\n% toolbox\\rownorm.m\n% toolbox\\save_fieldnames.m\n% toolbox\\source_grids.m\n% toolbox\\view_surface.m\n%\n% Subfunctions in this file, in order of occurrence in file:\n% BEMGaingridFname = bem_GainGrid(DataType,OPTIONS,BEMChanNdx)\n% g = gterm_constant(r,rq)\n%\n% At Check-in: $Author: Silvin $ $Revision: 68 $ $Date: 12/15/05 4:14a $\n%\n% This software is part of BrainStorm Toolbox Version 27-June-2005 \n% \n% Principal Investigators and Developers:\n% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,\n% University of Southern California, Los Angeles, CA\n% ** John C. Mosher, PhD, Biophysics Group,\n% Los Alamos National Laboratory, Los Alamos, NM\n% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,\n% CNRS, Hopital de la Salpetriere, Paris, France\n% \n% See BrainStorm website at http://neuroimage.usc.edu for further information.\n% \n% Copyright (c) 2005 BrainStorm by the University of Southern California\n% This software distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPL\n% license can be found at http://www.gnu.org/copyleft/gpl.html .\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n% ------------------------ 27-Jun-2005 10:43:31 -----------------------\n\n\n\n% /---Script Author--------------------------------------\\\n% | |\n% | *** Sylvain Baillet Ph.D. |\n% | Cognitive Neuroscience & Brain Imaging Laboratory |\n% | CNRS UPR640 - LENA | \n% | Hopital de la Salpetriere, Paris, France |\n% | sylvain.baillet@chups.jussieu.fr |\n% | |\n% \\------------------------------------------------------/\n% \n% Date of creation: March 2002\n\n\n% ----------------------------- Script History ---------------------------------\n%\n% SB 07-Aug-2002 Fixed GridLoc saving issues - now GridLoc\n% is a cell array of length one which indicates\n% the name of the tessellation file that was\n% used as an imaging support.\n% SB 03-Sep-2002 Fixed minor bugs when function is called from command line\n% Now bst_headmodeler can be called even when Brainstorm is not running\n% SB 05-Sep-2002 BEM can now be called from command line as well. \n% Updated script header\n% SB 06-Sep-2002 Updated EEG BEM : added option for arbitrary reference of the\n% potentials (takes now OPTIONS.EEGRef into account).\n% SB 18-Nov-2002 Updated EEG reference management.\n% SB 21-Nov-2002 Minor fixes for command line calls.\n% SB 21-Nov-2002bis Fixed bug from the get(*,'VertexNormals') command that\n% sometimes returns [0 0 0] at some vertex \n% SB 23-Dec-2002 Correct HeadModelFile name is passed to OPTIONS output argument\n% JCM 27-May-2004 Cleaning comments\n% Found Matlab bug and temp solution.\n% Matlab 6.5.0 bug, Technical Solution Number: 1-19NOK\n% http://www.mathworks.com/support/solutions/data/1-19NOK.html?solution=1-19NOK\n% Must REWIND first before fseek.\n% Apparently fixed in 6.5.1\n% Example:\n% status = fseek(fdest,0,'bof');\n% status = fseek(fdest,offset,'bof');\n% SB 08-Mar-2005 Fixed bug in BEM computation \n% SB 02-Feb-2005 Fixed bug that occured when ChannelLoc field is used to\n% passed EEG channel locations (thanks Jeremie Mattout at the FIL)\n% ----------------------------- Script History ---------------------------------\n\n% Default options settings--------------------------------------------------------------------------------------------------\nDefaultMethod = {'meg_sphere','eeg_3sphereBerg'};\n\nReducePatchScalpNVerts = 500; % Number of vertices the scalp tessellation will be reduced to in OS computations\nBEM_defaults = struct(...\n 'Basis','linear',...\n 'Test','galerkin',...\n 'Interpolative',0,...\n 'ISA',1,...\n 'NVertMax',1000,...\n 'ForceXferComputation', 1, ...\n 'checksurf',0);\n\nDef_OPTIONS = struct(...\n 'ApplyGridOrient',1,...\n 'BEM', BEM_defaults,...\n 'Channel', [],...\n 'ChannelFile', '',...\n 'ChannelLoc', '',...\n 'ChannelOrient', '',...\n 'ChannelType', '',...\n 'Conductivity', [.33 .0042 .33],...\n 'Cortex',[],...\n 'EEGRef','',...\n 'HeadCenter',[],...\n 'HeadModelFile', '',...\n 'HeadModelName','Default',...\n 'ImageGridBlockSize', 2000,...\n 'ImageGridFile', '',...\n 'GridOrient',[],...\n 'Method', {DefaultMethod},...\n 'OS_ComputeParam', 1,... \n 'PrefixFileName','bst_',...\n 'Radii', [],...\n 'Scalp',[],... \n 'SourceLoc',[],...\n 'SourceModel', [-1],...\n 'SourceOrient',[],...\n 'StudyFile','',...\n 'TessellationFile','',...\n 'VolumeSourceGrid',1,...\n 'VolumeSourceGridSpacing', 2,...\n 'VolumeSourceGridLoc', [],...\n 'Verbose', 1 ...\n );\n\nSourceOrderString = {'Current Dipole',...\n 'Unvalid Order (was Magnetic Dipole Moment)',...\n 'Current Multipole Expansion',...\n 'Current Dipole Pairs',...\n 'Unvalid Order (was Magnetic Dipole Moment PAIRS)',... \n 'Current Multipole Expansion Pairs'};\n\nif nargin == 0\n if nargout > 1\n varargout{1} = Def_OPTIONS;\n varargout{2} = Def_OPTIONS;\n else\n varargout{1} = Def_OPTIONS;\n end\n return\nelseif nargin == 1\n if ischar(varargin{1}) % User enters only the studyfile name\n StudyFile = varargin{1};\n OPTIONS = Def_OPTIONS;\n elseif isstruct(varargin{1}) % User enters only the OPTION field\n OPTIONS = varargin{1};\n else\n errordlg('Uncorrect input parameter type, please check the help file'), varargout = cell(nargout,1);\n return, \n end\nelseif nargin == 2 % No options were specified, apply default\n StudyFile = varargin{1};\n OPTIONS = varargin{2};\nelse\n errordlg('Wrong number of arguments when calling head modeler')\n varargout = cell(nargout,1);\n return\nend\n\n% Check field names of passed OPTIONS and fill missing ones with default values\nDefFieldNames = fieldnames(Def_OPTIONS);\nfor k = 1:length(DefFieldNames)\n if ~isfield(OPTIONS,DefFieldNames{k}) | strcmp(DefFieldNames{k},'BEM')\n if ~isfield(OPTIONS,DefFieldNames{k})\n \n OPTIONS = setfield(OPTIONS,DefFieldNames{k},getfield(Def_OPTIONS,DefFieldNames{k}));\n \n elseif strcmp(DefFieldNames{k},'BEM')\n \n BEM_DefFieldNames = fieldnames(BEM_defaults);\n for kk = 1:length(BEM_DefFieldNames)\n if ~isfield(OPTIONS.BEM,BEM_DefFieldNames{kk})\n OPTIONS.BEM = setfield(OPTIONS.BEM,BEM_DefFieldNames{kk},getfield(BEM_defaults,BEM_DefFieldNames{kk}));\n end\n end\n end\n end\nend\n\nif isempty(OPTIONS.Conductivity)\n OPTIONS.Conductivity = Def_OPTIONS.Conductivity;\nend\n\nclear Def_OPTIONS\n\n\nif isempty(OPTIONS.HeadModelFile) & ~isempty(OPTIONS.ImageGridFile)\n % Force creation of a headmodel file\n OPTIONS.HeadModelFile = 'default';\nend\n\nOPTIONS.HeadModelFileOld = OPTIONS.HeadModelFile;\n\n% What type of forward model (MEG and/or EEG) ?\nDataType.MEG = strmatch('meg',OPTIONS.Method); % Rank of the respective forward method in cell array Method (ie could be Method = {'meg_bem','eeg_sphere'} or vice-versa)\nDataType.EEG = strmatch('eeg',OPTIONS.Method);\n\nif ~iscell(OPTIONS.Method)\n OPTIONS.Method = {OPTIONS.Method};\nend\n\nMegMethod = [];\nif ~isempty(DataType.MEG)\n MegMethod = OPTIONS.Method{DataType.MEG}; % String indicating the forward method selected for MEG (res. EEG)\nend\nEegMethod = [];\nif ~isempty(DataType.EEG)\n EegMethod = OPTIONS.Method{DataType.EEG};\nend\n\n\n% Check inputs integrity\n\n%Source models\nif ~isempty(find(OPTIONS.SourceModel == 0)) | ~isempty(find(abs(OPTIONS.SourceModel) > 1)) % unValid source models\n if ~isempty(DataType.MEG)\n errordlg('Valid source model orders for MEG are: -1 (Current Dipole) and 1 (fist-order Current Multipole Expansion)')\n end\n if ~isempty(DataType.EEG)\n errordlg('Valid source model order for EEG is: -1 (Current Dipole) ')\n end\n varargout = cell(nargout,1);\n return\nend\n\n% Source locations\nif isempty(OPTIONS.SourceLoc) & ~OPTIONS.VolumeSourceGrid & isempty(OPTIONS.Cortex) % No source locations were specified\n errordlg('No source locations are specified. Please fill either one of the following fields of OPTIONS: .SourceLoc / .VolumeSourceGrid / .Cortex')\n varargout = cell(nargout,1);\n return\nend\n\n\n%--------------------------------------------------------------------------------------------------------------------------------------------\n%\n% HEAD MODELING BEGINS\n%\n%--------------------------------------------------------------------------------------------------------------------------------------------\n\nif OPTIONS.Verbose, \n \n clockk = fix(clock);\n time0 = clock;\n\n bst_message_window({...\n ' ',...\n '__________________________________________',...\n sprintf(...\n 'Head modeling begins (%s - %dH %dmin %ds)',date,clockk(4:6))...\n })\n \nend\n\nUser = get_user_directory;\nif isempty(User) % Function is called from command line: BrainStorm is not running \n % Use default folders\n User.SUBJECTS = pwd;\n User.STUDIES = pwd;\nend\n\ntry\n cd(User.STUDIES)\ncatch\nend\n\n\n\n% Get all Subject and Study information------------------------------------------------------------------------------------------------------\nif exist('StudyFile','var')\n if OPTIONS.Verbose, bst_message_window('Loading Study and Subject Information...'), end\n try \n load(StudyFile) % Load study information\n [StudyPath,tmp,ext] = fileparts(StudyFile); clear tmp \n catch \n errordlg(['Could not find ',StudyFile,' in current Matlab path'])\n varargout = cell(nargout,1);\n return\n end\n \n if isempty(OPTIONS.StudyFile)\n OPTIONS.StudyFile = StudyFile;\n end\n \n SubjectFile = BrainStormSubject; clear BrainStormSubject\n \n OPTIONS.rooot = findstr(StudyFile,'brainstormstudy.mat');\n if isempty(OPTIONS.rooot)\n errordlg('Study file name should be of the form ''*brainstormstudy.mat''')\n varargout = cell(nargout,1);\n return\n end\n OPTIONS.rooot = strrep(StudyFile,'brainstormstudy.mat','');\n \n Study = load(StudyFile);\n %User = get_user_directory;\n try\n cd(User.SUBJECTS)\n Subject = load(Study.BrainStormSubject);\n catch \n errordlg(sprintf('Please make sure the subject''s information in %s is available on this plateform',Study.BrainStormSubject)); return\n end\n \n if isempty(OPTIONS.TessellationFile) % No Tessellation file was passed to the headmodeler\n if isfield(Subject,'Tesselation')\n OPTIONS.TessellationFile = Subject.Tesselation; % Take default (OBSOLETE as for BsT MMII because we now consider all tessellation files in Subject's folder)\n else\n OPTIONS.TessellationFile = '';\n %[OPTIONS.TessellationFile,DataPopup, Leader] = find_brainstorm_files('tess',fullfile(Users.SUBJECTS,OPTIONS.subjectpath));\n end\n end\nend\n\n% Get Channel Information ------------------------------------------------------------------------------------------------------------------\nif ~isempty(OPTIONS.Channel)\n Channel = OPTIONS.Channel;\nelse\n if isempty(OPTIONS.ChannelFile) & isempty(OPTIONS.ChannelLoc) % Load Channel file in current folder\n \n [Channel, ChannelFile] = get_channel(fullfile(User.STUDIES,OPTIONS.StudyFile));\n OPTIONS.ChannelFile = fullfile(fileparts(fullfile(User.STUDIES,OPTIONS.StudyFile)),ChannelFile);\n \n if isempty(ChannelFile)\n errordlg(sprintf('Channel file %s is missing. Please have it available it the current study folder.',OPTIONS.ChannelFile), 'Missing Channel File')\n return\n end\n \n elseif isempty(OPTIONS.ChannelLoc) & exist(OPTIONS.ChannelFile,'file') % If no specific channel locations are given and channel file exists, load the proper channel file\n \n OPTIONS.rooot = strrep(lower(OPTIONS.ChannelFile),'channel.mat','');\n try\n load(OPTIONS.ChannelFile)\n catch\n cd(User.STUDIES)\n load(OPTIONS.ChannelFile)\n end\n \n else % Create a dummy Channel structure with Channel Locations (res. Orientations) specified in OPTIONS.ChannelLoc (res .ChannelOrient)\n \n if OPTIONS.Verbose, bst_message_window('Creating the channel structure from information in the OPTIONS fields. . .'), end\n \n % Get Channel Locations\n nchan = size(OPTIONS.ChannelLoc,2); % Number of channels\n Channel = struct('Loc',[],'Orient',[],'Comment','','Weight',[],'Type','','Name','');\n Channel(1:nchan) = deal(Channel);\n \n ChanType = upper(OPTIONS.ChannelType);\n if isempty(ChanType)\n errordlg('Please specify a channel type (i.e. MEG or EEG) in the ChannelType field of OPTIONS'), \n bst_message_window('Please specify a channel type (i.e. MEG or EEG) in the ChannelType field of OPTIONS'), \n varargout = cell(nargout,1);\n return\n end\n [Channel(:).Type] = deal(ChanType);\n if size(OPTIONS.ChannelLoc,1) == 6 % MEG Gradiometers or mixture gradio/magneto meters\n OPTIONS.ChannelLoc = reshape(OPTIONS.ChannelLoc,3,nchan*2);\n iGradFlag = 1; % Flag - gradiometer-type sensor set\n else\n iGradFlag = 0; % Flag - EEG or magnetometer-type sensor set\n end\n ichan = 1;\n for k = 1:nchan\n if iGradFlag\n Channel(k).Loc = OPTIONS.ChannelLoc(:,ichan:ichan+1);\n ichan = ichan+2;\n else\n if strcmp(ChanType,'MEG')\n Channel(k).Loc = OPTIONS.ChannelLoc(:,ichan);\n %elseif strcmp(ChanType,'EEG') % Artificially add a dummy column full of zeros to each Channel(k).Loc \n %Channel(k).Loc = [OPTIONS.ChannelLoc(:,ichan) [0 0 0]'];\n elseif strcmp(ChanType,'EEG') % Artificially add a dummy column full of zeros to each Channel(k).Loc \n Channel(k).Loc = [OPTIONS.ChannelLoc(:,ichan)];\n end\n ichan = ichan+1;\n end\n Channel(k).Name = sprintf('%s %d',ChanType,k);\n Channel(k).Comment = int2str(k);\n end\n clear ichan k\n \n % Get Channel Orientations\n if isempty(OPTIONS.ChannelOrient) & strcmp(ChanType,'MEG') % No channel orientation were specified: use radial sensors\n if OPTIONS.Verbose, bst_message_window('Assign radial orientation to all Channels. . .'), end\n if isempty(OPTIONS.HeadCenter)\n if iGradFlag\n Vertices = OPTIONS.ChannelLoc(:,1:2:end)';\n else\n Vertices = OPTIONS.ChannelLoc';\n end\n \n nscalp = size(Vertices,1);\n if nscalp > 500 % 500 points is more than enough to compute scalp's best fitting sphere\n Vertices = Vertices(unique(round(linspace(1,nscalp,500))),:); \n nscalp = size(Vertices,1); \n end\n nmes = size(Vertices,1);\n \n % Run parameters fit --------------------------------------------------------------------------------------------------------------\n mass = mean(Vertices); % center of mass of the scalp vertex locations \n R0 = mean(norlig(Vertices - ones(nscalp,1)*mass)); % Average distance between the center of mass and the scalp points\n vec0 = [mass,R0];\n \n [minn,brp] = fminsearch('dist_sph',vec0,[],Vertices);\n OPTIONS.HeadCenter = minn(1:end-1); \n if isempty(OPTIONS.Radii)\n OPTIONS.Radii = minn(end);\n OPTIONS.Radii = minn(end)*[1/1.14 1/1.08 1];\n end\n \n if OPTIONS.Verbose, bst_message_window({...\n sprintf('Center of the Sphere : %3.1f %3.1f %3.1f (cm)',100*OPTIONS.HeadCenter),...\n sprintf('Radius : %3.1f (cm)',100*OPTIONS.Radii(3)),...\n '-> DONE',' '})\n end\n \n clear minn brp mass R0 Vertices vec0\n end\n \n tmp = [Channel.Loc] - repmat(OPTIONS.HeadCenter',1,nchan*(1+(iGradFlag==1)));\n OPTIONS.ChannelOrient = tmp*inorcol(tmp); % Radial orientation for every channel\n clear tmp\n elseif ~isempty(OPTIONS.ChannelOrient) & strcmp(ChanType,'MEG') & iGradFlag\n OPTIONS.ChannelOrient = reshape(OPTIONS.ChannelOrient,3,nchan*2);\n end\n \n if strcmp(ChanType,'MEG')\n for k=1:nchan\n Channel(k).Orient = OPTIONS.ChannelOrient(:,((1+(iGradFlag==1))*k-1):(1+(iGradFlag==1))*k);\n end\n end\n \n clear k\n \n % Define Weights\n if iGradFlag\n [Channel(:).Weight] = deal([1 -1]);\n else\n [Channel(:).Weight] = deal([1]);\n end\n \n if strcmp(ChanType,'MEG') % Force no reference channels\n Channel(1).irefsens = [];\n end\n \n % New Channel stbemructure completed: save as a new channel file\n if ~isempty(OPTIONS.ChannelFile)\n %OPTIONS.ChannelFile = [OPTIONS.rooot,'channel.mat'];\n save(OPTIONS.ChannelFile,'Channel')\n if OPTIONS.Verbose, bst_message_window({...\n sprintf('Channel file created in : %s',OPTIONS.ChannelFile),...\n '-> DONE',' '}), end\n end\n \n end\n \n %load(OPTIONS.ChannelFile)\n OPTIONS.Channel = Channel;\nend\n\n% Find MEG and EEG channel indices\nMEGndx = good_channel(Channel,[],'MEG');\nEEGndx = good_channel(Channel,[],'EEG');\nEEGREFndx = good_channel(Channel,[],'EEG REF');\n\nMEG = ~isempty(MEGndx) & ~isempty(DataType.MEG); % == 1 if MEG is requested and is available \nEEG = ~isempty(EEGndx) & ~isempty(DataType.EEG); \n\nif ~EEG & ~MEG\n errordlg('Please check that data (MEG or EEG) and channel types are compatible.')\n return\nend\n\n% Test whether CME models are requested for EEG\nif ~isempty(find(OPTIONS.SourceModel == 1)) & EEG\n if MEG\n if OPTIONS.Verbose\n bst_message_window('wrap',...\n {'',...\n 'CME model not available for EEG - Skipping. . .',...\n 'Keeping it for MEG forward modeling only',...\n ''...\n })\n end\n else % EEG only is requested\n errordlg(...\n {'CME model not available for EEG - Skipping. . .',...\n 'Keeping it for MEG forward modeling only'...\n })\n return\n end\n \nend\n\n% Detect EEG reference - if none is specified in the .Comment or Type fields, \n% and if none was passed through OPTIONS.EEGRef \n% -> Apply average-referencing of the potentials by default.\n\nif EEG \n if isempty(OPTIONS.EEGRef)\n \n % EEG Reference Channel\n EEGREFndx = good_channel(Channel,[],'EEG REF');\n if isempty(EEGREFndx) % Average EEG reference anyway\n [Channel(EEGndx).Comment] = deal('AVERAGE REF');\n end\n \n else % EEG Reference is specified\n \n switch(OPTIONS.EEGRef)\n case 'AVERAGE REF'\n [Channel(:).Comment] = deal('AVERAGE REF');\n \n otherwise\n \n EEGREFndx = strmatch(OPTIONS.EEGRef,char(Channel(:).Name));\n if isempty(EEGREFndx)\n errordlg(sprintf(...\n 'No channel named ''%s'' was found amongst available EEG channels. Cannot use it as a reference for EEG.',OPTIONS.EEGRef...\n ))\n return\n end\n \n end\n \n end\n \n % if isempty(EEGREFndx) & ~MEG % No reference electrode was defined for the EEG stop if no MEG to compute...\n % errordlg('Please make sure you have defined a reference for the EEG')\n % return\n % elseif isempty(EEGREFndx) & MEG % Skip EEG forward modeling and proceed to MEG\n % EEG = 0;\n % if OPTIONS.Verbose\n % bst_message_window({...\n % 'No reference was defined for the EEG',...\n % 'Skipping EEG modeling and completing MEG only...',...\n % })\n % end\n % end\n \nend\n\nif OPTIONS.Verbose, \n if EEG & MEG\n if ~isempty(EEGREFndx)\n bst_message_window({'Channel count for current computation:',[int2str(length(MEGndx)), ' MEG Channels'],...\n sprintf('%d EEG Channels with Reference: %s',length(EEGndx),Channel(EEGREFndx).Name),' '})\n else\n bst_message_window({'Channel count for current computation:',[int2str(length(MEGndx)), ' MEG Channels'],...\n sprintf('%d EEG Channels with Average Reference',length(EEGndx)),' '})\n end\n \n elseif MEG\n bst_message_window({'Channel count for current computation:',[int2str(length(MEGndx)), ' MEG Channels'],...\n ' '})\n elseif EEG \n if ~isempty(EEGREFndx)\n bst_message_window({'Channel count for current computation:',...\n sprintf('%d EEG Channels with Reference: %s',length(EEGndx),Channel(EEGREFndx).Name),' '})\n else \n bst_message_window({'Channel count for current computation:',...\n sprintf('%d EEG Channels with Average Reference',length(EEGndx)),' '})\n end\n \n end\nend\n\nif MEG & isempty(MEGndx) % User wants to compute MEG but no MEG data is available\n errordlg('Sorry - No MEG data is available'), return\nend\n\nif EEG & isempty(EEGndx) % User wants to compute EEG but no EEG data is available\n errordlg('Sorry - No EEG data is available'), return\nend\n\n\n% Computation of parameters of the best-fitting sphere --------------------------------------------------------------------------------------------------------------\nif length(findstr('bem',[OPTIONS.Method{:}])) ~= length(OPTIONS.Method)% Only if sphere-based head model is requested in any modality (MEG or EEG)\n \n % Best-fitting sphere parameters --------------------------------------------------------------------------------------------------------------\n if isempty(OPTIONS.HeadCenter) | isempty(OPTIONS.Radii)\n \n if OPTIONS.Verbose, bst_message_window('Estimating Center of the Head. . .'), end\n \n if isempty(OPTIONS.Scalp) % Best-fitting sphere is derived from the sensor array\n % ans = questdlg('No scalp surface was selected - Do you want to use a spherical approximation of the head derived from the sensor locations instead ?',...\n % '','Yes','No','Yes');\n if EEG & length(EEGndx) > 9 % If EEG is available but a reasonable number of electrodes, use it to compute the sphere parameters\n ndx = [EEGndx]; % Compute Sphere parameters from EEG sensors only\n else\n ndx = [MEGndx];\n end\n \n Vertices = zeros(length(ndx),3);\n for k=1:length(ndx)\n Vertices(k,:) = Channel(ndx(k)).Loc(:,1)';\n end\n \n else % Best-fitting sphere is computed from the set of vertices of the scalp surface enveloppe\n \n try\n load(fullfile(User.SUBJECTS,OPTIONS.Scalp.FileName),'Vertices')\n catch\n load(OPTIONS.Scalp.FileName,'Vertices')\n end\n \n if ~isfield(OPTIONS.Scalp,'iGrid') % Apply Default\n OPTIONS.Scalp.iGrid = 1;\n end\n \n try\n Vertices = Vertices{OPTIONS.Scalp.iGrid}';\n catch\n errordlg(sprintf(...\n 'Tessellation file %s does not contain %d enveloppes',...\n OPTIONS.Scalp.FileName,OPTIONS.Scalp.iGrid))\n end\n end\n \n nscalp = size(Vertices,1);\n nmes = size(Vertices,1);\n \n % Run parameters fit --------------------------------------------------------------------------------------------------------------\n mass = mean(Vertices); % center of mass of the scalp vertex locations \n R0 = mean(norlig(Vertices - ones(nscalp,1)*mass)); % Average distance between the center of mass and the scalp points\n vec0 = [mass,R0];\n \n [SphereParams,brp] = fminsearch('dist_sph',vec0,[],Vertices);\n \n \n if OPTIONS.Verbose\n bst_message_window({...\n sprintf('Center of the Sphere : %3.1f %3.1f %3.1f (cm)',100*SphereParams(1:end-1)'),...\n sprintf('Radius : %3.1f (cm)',100*SphereParams(end)),...\n '-> DONE',' '})\n \n end\n \n end % no head center and sphere radii were specified by user\n \n % Assign default values for sphere parameters \n % if none were specified before\n if isempty(OPTIONS.Radii)\n OPTIONS.Radii = SphereParams(end)*[1/1.14 1/1.08 1];\n end\n \n if isempty(OPTIONS.HeadCenter)\n OPTIONS.HeadCenter = SphereParams(1:end-1)'; \n end\n \n if isempty(OPTIONS.Conductivity)\n OPTIONS.Conductivity = [.33 .0042 .33];\n end\n \nend % Use BEM Approach, so proceed to the selection of the envelopes\n\n% ---------------------------------------------------------------------------------------------------------\n%Create HeadModel Param structure\nParam(1:length(Channel)) = deal(struct('Center',[],'Radii',[],'Conductivity',[],'Berg',[]));\n\nif ~isempty(findstr('os',[OPTIONS.Method{:}])) % Overlapping-Sphere EEG or MEG is requested: load the scalp's tessellation\n \n if isempty(OPTIONS.Scalp)\n errordlg('Please specify a subject tessellation file for Scalp enveloppe in OPTIONS.Scalp when using Overlapping-Sphere forward approach');\n return\n end\n \n % load(fullfile(User.SUBJECTS,BrainStorm.SubjectTess),'Faces');\n try\n load(fullfile(User.SUBJECTS,OPTIONS.Scalp.FileName),'Faces','Vertices');\n catch\n load(OPTIONS.Scalp.FileName,'Faces','Vertices');\n end\n\n Faces = Faces{OPTIONS.Scalp.iGrid};\n Vertices = Vertices{OPTIONS.Scalp.iGrid}';\n \n if size(Vertices,1) > ReducePatchScalpNVerts % Reducepatch the scalp tessellation for fastest OS computation\n nfv = reducepatch(Faces,Vertices,2*ReducePatchScalpNVerts);\n if OPTIONS.Verbose, bst_message_window({...\n sprintf('Decimated scalp tessellation from %d to %d vertices.',size(Vertices,1),size(nfv.vertices,1)),...\n ' '});\n end\n clear Faces Vertices\n SubjectFV.vertices = nfv.vertices';\n SubjectFV.faces = nfv.faces; \n clear nfv\n else\n SubjectFV.vertices = Vertices; % Available from the computation of the head center above\n clear Vertices\n SubjectFV.faces = Faces; clear Faces\n end\n \n if length(findstr('os',[OPTIONS.Method{:}])) == 2 % OS approach requested fro both MEG and EEG\n ndx = [MEGndx,EEGndx]; \n \n else\n if MEG\n if strcmpi('meg_os',OPTIONS.Method{DataType.MEG}) % OS for MEG only\n ndx = MEGndx;\n end\n end\n \n if EEG \n if strcmpi('eeg_os',OPTIONS.Method{DataType.EEG}) % OS for EEG only\n ndx = [EEGndx, EEGREFndx];\n end\n end\n end\n if OPTIONS.Verbose\n bst_message_window({...\n ' ', 'Computing Overlapping-sphere model. . .'}) \n end\n \n if isempty(OPTIONS.HeadModelFile) | OPTIONS.OS_ComputeParam\n \n % Compute all spheres parameters\n %------------------------------------------------------------------\n Sphere = overlapping_sphere(Channel(ndx),SubjectFV,OPTIONS.Verbose,OPTIONS.Verbose);\n if OPTIONS.Verbose\n bst_message_window({...\n 'Computing Overlapping-sphere model -> DONE',' '}) \n end\n [Param(ndx).Center] = deal(Sphere.Center);\n [Param(ndx).Radii] = deal(Sphere.Radius);\n [Param(ndx).Conductivity] = deal(OPTIONS.Conductivity);\n \n elseif exist(OPTIONS.HeadModelFile,'file')\n \n load(OPTIONS.HeadModelFile,'Param') % or use precomputed\n if OPTIONS.Verbose\n bst_message_window({...\n sprintf('Sphere parameters loaded from : %s -> DONE',OPTIONS.HeadModelFile),' '}) \n end\n \n else\n \n errordlg(sprintf('Headmodel file %s does not exist in Matlab''s search path',OPTIONS.HeadModelFile))\n return\n \n end\n \nend\n\n% Saving HeadModel's Param structure in the headmodel file\nif strcmp(lower(OPTIONS.HeadModelFile),'default')\n if ~isfield(OPTIONS,'rooot')\n OPTIONS.rooot = OPTIONS.PrefixFileName;\n end\n OPTIONS.HeadModelFile = [OPTIONS.rooot,'headmodel.mat'];\n ifile = 0; \n while exist(OPTIONS.HeadModelFile,'file') % Do not overwrite headmodel files\n ifile = ifile + 1;\n OPTIONS.HeadModelFile = [OPTIONS.rooot,'headmodel_',int2str(ifile),'.mat'];\n end\n \nelseif ~isfield(OPTIONS,'rooot') & ~isempty(OPTIONS.HeadModelFile)\n OPTIONS.rooot = strrep(OPTIONS.HeadModelFile,'headmodel.mat',''); \nend\nif ~isfield(OPTIONS,'rooot') % Last Chance\n OPTIONS.rooot = 'bst_';\nend\n\nif ~isempty(findstr('sphere',[OPTIONS.Method{:}])) % Single or nested-sphere approaches \n \n [Param([MEGndx, EEGndx, EEGREFndx]).Center] = deal(OPTIONS.HeadCenter);\n [Param([MEGndx, EEGndx, EEGREFndx]).Radii] = deal(OPTIONS.Radii);\n [Param([MEGndx, EEGndx, EEGREFndx]).Conductivity] = deal(OPTIONS.Conductivity);\n \n if EEG & strcmpi('eeg_3sphereberg',lower(OPTIONS.Method{DataType.EEG})) % BERG APPROACH\n \n if ~isempty(OPTIONS.HeadModelFile) & exist(OPTIONS.HeadModelFile,'file')\n if OPTIONS.Verbose, bst_message_window('Checking for previous EEG \"BERG\" parameters'), end\n ParamOld = load(OPTIONS.HeadModelFile,'Param');\n iFlag = 0; % Flag\n if isfield(ParamOld.Param,'Berg') & ~isempty(ParamOld.Param(1).Radii)\n % Check if these older parameters were computed with the same as current radii and conductivity values\n if ParamOld.Param(1).Radii ~= Param(1).Radii;\n iFlag = 1;\n end\n if ParamOld.Param(1).Conductivity ~= Param(1).Conductivity;\n iFlag = 1;\n end\n else\n iFlag = 1;\n end\n else\n iFlag = 1;\n end\n \n if iFlag == 1\n if OPTIONS.Verbose , bst_message_window('Computing EEG \"BERG\" Parameters. . .'), end\n [mu_berg_tmp,lam_berg_tmp] = berg(OPTIONS.Radii,OPTIONS.Conductivity);\n Param(EEGndx(1)).Berg.mu = mu_berg_tmp; clear mu_berg_tmp\n Param(EEGndx(1)).Berg.lam = lam_berg_tmp; clear lam_berg_tmp\n if OPTIONS.Verbose, bst_message_window({'Computing EEG \"BERG\" Parameters -> DONE',' '}), end\n else\n if OPTIONS.Verbose , bst_message_window('Using Previous EEG \"BERG\" Parameters'), end\n Param(EEGndx(1)).Berg.mu = ParamOld.Param(1).Berg.mu;\n Param(EEGndx(1)).Berg.lam = ParamOld.Param(1).Berg.lam; clear ParamOld\n end\n [Param.Berg]= deal(Param(EEGndx(1)).Berg); \n \n end \n \nend\n\nif ~isempty(findstr('bem',[OPTIONS.Method{:}])) % BEM approaches - Compute transfer matrices\n\n if OPTIONS.BEM.Interpolative==0 & OPTIONS.VolumeSourceGrid %& isempty(OPTIONS.Cortex) % User wants volumic grid : force Interpolative approach\n OPTIONS.BEM.Interpolative = 1; % CBB (SB, 07-May-2004)| Should work also for volumic grid\n hwarn = warndlg('Volumic Source Grid BEM is only available for interpolative BEM. BEM computation will be now forced to interpolative. If you want a non-interpolative BEM on a cortical image grid, first uncheck the Volumic Grid box from headmodeler gui.','Limitation from current BrainStorm version');\n drawnow\n waitfor(hwarn)\n end\n \n if MEG\n if ~isempty(findstr('bem',OPTIONS.Method{DataType.MEG})) % BEM is requested for MEG\n BEMChanNdx{DataType.MEG} = MEGndx;\n end\n end\n \n if EEG \n if ~isempty(findstr('bem',OPTIONS.Method{DataType.EEG})) % BEM is requested for EEG\n BEMChanNdx{DataType.EEG} = sort([EEGndx,EEGREFndx]); % EEGREFndx = [] is average ref\n end\n end\n \n OPTIONS.Param = Param;\n \n if OPTIONS.BEM.Interpolative % Computation of gain matrix over 3D interpolative grid \n if OPTIONS.BEM.ForceXferComputation\n BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx); % Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data\n else\n try \n BEMGaingridFileName = OPTIONS.BEM.GaingridFileName;\n catch\n cd(User.STUDIES)\n BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx); % Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data\n end\n end\n \n if MEG & EEG\n [Param(MEGndx).bem_gaingrid_mfname] = deal(BEMGaingridFileName.MEG);\n [Param([EEGndx]).bem_gaingrid_mfname] = deal(BEMGaingridFileName.EEG);\n else\n [Param(:).bem_gaingrid_mfname] = deal(BEMGaingridFileName);\n end \n \n else % BEM gain matrix computation over cortical surface\n \n \n BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx); \n \n [Param(:).bem_gaingrid_mfname] = deal('');\n \n end\n\n \n OPTIONS = rmfield(OPTIONS,'Param');\n \n ndx = sort([BEMChanNdx{:}]);\n \n \n [Param(ndx).Center] = deal([]);\n test=0; % this test is nowhere defined ?\n \n if OPTIONS.VolumeSourceGrid\n % Now define the outer scalp envelope for the source volume gridding if requested\n \n if OPTIONS.BEM.ForceXferComputation | ~test\n global nfv\n SubjectFV.vertices = nfv(end).vertices'; \n SubjectFV.faces = nfv(end).faces; clear Faces\n else\n load(fullfile(User.SUBJECTS,fileparts(OPTIONS.Subject),OPTIONS.BEM.EnvelopeNames{end}.TessFile))\n \n idScalp = find(strcmpi(OPTIONS.BEM.EnvelopeNames{end}.TessName,Comment)); clear Comment\n if isempty(idScalp)\n errodlg(sprintf(...\n 'Scalp tessellation %s was not found in %s.',OPTIONS.BEM.EnvelopeNames{end}.TessName, OPTIONS.BEM.EnvelopeNames{end}.TessFile),...\n 'Error during BEM computation')\n return\n end\n \n SubjectFV.vertices = Vertices{idScalp}'; clear Vertices\n SubjectFV.faces = Faces{idScalp}; clear Faces\n end\n \n end\n \nend % if BEM\n\nif EEG\n \n switch(lower(OPTIONS.Method{DataType.EEG}))\n case 'eeg_sphere'\n [Param(EEGndx).EEGType] = deal('EEG_SINGLE');\n case 'eeg_3sphere'\n [Param(EEGndx).EEGType] = deal('EEG_3SHELL');\n case 'eeg_3sphereberg'\n [Param(EEGndx).EEGType] = deal('EEG_BERG');\n case 'eeg_os'\n [Param(EEGndx).EEGType] = deal('EEG_OS');\n case 'eeg_bem'\n [Param(EEGndx).EEGType] = deal('BEM');\n if EEG & ~MEG\n [Param(EEGndx).bem_gaingrid_mfname] = deal(BEMGaingridFileName); \n end\n end\n \nelse\n \n tmp = [];\n [Param.Conductivity] = deal(tmp);\n [Param.Berg] = deal(tmp);\n [Param.EEGType] = deal(tmp); \n \nend\n\n\n%_________________________________________________________________________________________________________________________________________________________________________\n% \n% The following part is an adaptation of the former HEADMODEL_MAKE script \n%\n% ________________________________________________________________________________________________________________________________________________________________________\n\n\n% Allocate function names depending on the selected forward approaches specified in the Method argument\nFunction = cell(1,length(Channel)); %allocate function names\n\nif MEG\n if ~isempty(findstr('bem',OPTIONS.Method{DataType.MEG})) % MEG BEM\n Function(MEGndx) = deal({'meg_bem'});\n if isfield(Channel(MEGndx(1)),'irefsens')\n Function(Channel(MEGndx(1)).irefsens) = deal({'meg_bem'});\n end\n \n else\n Function(MEGndx) = deal({'os_meg'});\n if isfield(Channel(MEGndx(1)),'irefsens')\n Function(Channel(MEGndx(1)).irefsens) = deal({'os_meg'});\n end\n if isfield(OPTIONS,'BEM')\n OPTIONS = rmfield(OPTIONS,'BEM');\n end\n \n end\nend\n\n\nif EEG\n if ~isempty(findstr('bem',OPTIONS.Method{DataType.EEG})) % MEG BEM\n Function(EEGndx) = deal({'eeg_bem'});\n else\n Function(EEGndx) = deal({'eeg_sph'});\n if isfield(OPTIONS,'BEM')\n OPTIONS = rmfield(OPTIONS,'BEM');\n end\n end\n \nend \n% --------------------------------------------------------------------------------------------------------\n\nDIMS = [3 12]; % number of columns for each parametric source model: Current Dipole / Current Multipole\nHeadModel.Param = Param; \nHeadModel.Function = Function;\n\nif OPTIONS.VolumeSourceGrid % if SearchGain matrices are requested\n \n SearchGain = cell(1,6); % One cell for each source order + pairs of sync. sources - keep 2 'phantom' cells for former Magnetic Dipole model\n \n %------------------------------ Computing SearchGridLoc and SearchGain-------------------------------------------\n \n if ~isempty(findstr(MegMethod,'bem')) | (EEG & ~MEG)\n if OPTIONS.Verbose, bst_message_window(...\n {'Forward modeling not available for EEG''s Current Mulipole models or the BEM approach','Computing forward fields for Current Dipole models. . .'...\n ,' '}), end\n %return\n OPTIONS.SourceModel = [-1]; % Force current dipole source model when MEG BEM or any EEG is requested\n end\n \n if OPTIONS.Verbose, bst_message_window(...\n 'Computing the Gain Matrices from the Volumic Search Grid. . .'), end\n \n % Prepare call to source_grids\n \n GUI.VALIDORDER = OPTIONS.SourceModel;\n GUI.SPACING = 10*OPTIONS.VolumeSourceGridSpacing; % Pass it to source_grids in millimeters\n GUI.VERBOSE = OPTIONS.Verbose;\n GUI.MEG = MEG;\n GUI.EEG = EEG;\n \n if ~exist('SubjectFV','var')\n % Create a spherical tessellation of the INNER SKULL surface boundary for source gridding \n \n [x,y,z] = sphere(30);\n %Scale to Radius BrainStorm.R\n [TH,PHI,R] = cart2sph(x,y,z); \n if OPTIONS.Radii(1) == 0 \n error('The sphere radius you have specified is ZERO - please change it to a non null positive value')\n end\n R = OPTIONS.Radii(1) * ones(size(R));\n [x,y,z] = sph2cart(TH,PHI,R);\n \n % Tessellate both hemispheres \n Im = find(z>=0);\n tri = delaunay(x(Im),y(Im));\n \n %Gather everything into the same patch\n SubjectFV.vertices = [x(Im),y(Im),z(Im);...\n x(Im),y(Im),-z(Im)];\n \n % Translate about the head center\n SubjectFV.vertices = SubjectFV.vertices + repmat(OPTIONS.HeadCenter',size(SubjectFV.vertices,1),1);\n \n SubjectFV.faces = [tri;tri(:,[3 2 1])+max(tri(:))];\n \n clear x y z R TH PHI Im tri\n \n end\n \n HeadModel = source_grids(HeadModel,Channel,SubjectFV,GUI); \n clear SubjectFV\n \n if OPTIONS.Verbose, bst_message_window({...\n '-> DONE',...\n 'Now saving HeadModel file. . .'...\n })\n end\n \n % Now save VolumeSourceGrid headmodel(s)\n SaveHeadModel.Param = HeadModel.Param;\n SaveHeadModel.Function = HeadModel.Function;\n \n if strcmpi(OPTIONS.HeadModelName,'Default') % Specify default HeadModelName \n if MEG & EEG\n SaveHeadModel.HeadModelName = sprintf('%s | %s', OPTIONS.Method{DataType.MEG},OPTIONS.Method{DataType.EEG});\n elseif MEG\n SaveHeadModel.HeadModelName = sprintf('%s', OPTIONS.Method{DataType.MEG});\n elseif EEG\n SaveHeadModel.HeadModelName = sprintf('%s', OPTIONS.Method{DataType.EEG});\n end\n else\n SaveHeadModel.HeadModelName = OPTIONS.HeadModelName;\n end\n \n if ~isempty(OPTIONS.HeadModelFile), \n [HeadModelFilePath,HeadModelFile,ext] = fileparts(OPTIONS.HeadModelFile);\n end\n \ntry\n cd(User.STUDIES)\ncatch\nend\n\n \n for k = 1:length(GUI.VALIDORDER) % One file per source order \n \n % Specify Source Model Name and Other Fields \n if GUI.VALIDORDER(k) == -1\n SourceOrderString = 'CD'; % Current Dipole\n elseif GUI.VALIDORDER(k) == 0\n SourceOrderString = 'MD'; % Magnetic Dipole\n elseif GUI.VALIDORDER(k) == 1\n SourceOrderString = 'CME'; % Current Multipole\n end\n \n [SaveHeadModel.Param.Order] = deal(GUI.VALIDORDER(k));\n SaveHeadModel.SourceOrder = GUI.VALIDORDER(k); % Alternative to previous line\n SaveHeadModel.HeadModelType = 'SearchGrid';\n if MEG \n SaveHeadModel.MEGMethod = OPTIONS.Method{DataType.MEG};\n end\n if EEG \n SaveHeadModel.EEGMethod = OPTIONS.Method{DataType.EEG};\n end\n \n SaveHeadModel.GridName = {sprintf('%s Volumic Grid : %3.1f cm spacing',SourceOrderString, OPTIONS.VolumeSourceGridSpacing)};\n SaveHeadModel.GridLoc = HeadModel.GridLoc(GUI.VALIDORDER(k)+2);\n SaveHeadModel.Gain = {single(HeadModel.Gain{GUI.VALIDORDER(k)+2})}; % Convert to single precision gain matrix as in BST MMII convention\n \n % now collect together and save\n if ~isempty(OPTIONS.HeadModelFile), % User has provided a headmodel file name \n SaveHeadModelFile = fullfile(HeadModelFilePath,[HeadModelFile,...\n sprintf('VolGrid_%s',SourceOrderString),...\n ext]);\n ifile = 0;\n while exist(SaveHeadModelFile,'file') % Do not overwrite headmodel files\n ifile = ifile + 1;\n SaveHeadModelFile = fullfile(HeadModelFilePath,[HeadModelFile,...\n sprintf('VolGrid_%s',SourceOrderString),...\n '_',int2str(ifile),ext]);\n end\n \n \n if OPTIONS.Verbose, bst_message_window({...\n sprintf('Writing HeadModel file:'),...\n sprintf('%s', SaveHeadModelFile)...\n })\n end\n \n if strcmp(lower(OPTIONS.HeadModelFileOld),'default')\n OPTIONS.HeadModelFile = SaveHeadModelFile;\n end\n \n save_fieldnames(SaveHeadModel, SaveHeadModelFile);\n \n if OPTIONS.Verbose, bst_message_window(...\n {'-> DONE',' '}), end\n end\n \n end\n \n OPTIONS.HeadModelName = SaveHeadModel.HeadModelName;\n \n if OPTIONS.Verbose, bst_message_window(...\n {'Grid gain matrices are saved','RAP-MUSIC & Least-Squares Fits Approaches are now available',' '})\n end\n \nend\n\n\n%% -------------------------------------------------------------------------\n%\n% Now proceed to forward modeling of cortical grids or at some other specific source locations\n%\n%% -------------------------------------------------------------------------\n\n\nif ~isempty(OPTIONS.Cortex), % subject has cortical vertices as source supports\n % First make room in memory\n HeadModel.SearchGain = [];\n clear SearchGridLoc SearchGain G\n \n if OPTIONS.Verbose, bst_message_window({...\n 'Computing the Image Gain Matrices (this may take a while). . .'})\n end\n \n % Find the cortical grid where to compute the forward model in the tessellation file\n try \n ImageGrid = load(fullfile(User.SUBJECTS,OPTIONS.Cortex.FileName),'Comment','Vertices');\n catch\n ImageGrid = load(OPTIONS.Cortex.FileName,'Comment','Vertices');\n end\n \n if ~isfield(OPTIONS.Cortex,'iGrid')\n OPTIONS.Cortex.iGrid = 1;\n end\n \n if OPTIONS.Cortex.iGrid > length(ImageGrid.Comment) % Corresponding cortical surface not found\n errordlg(sprintf('Cortical Tessellation file \"%s\" does not contain %d surfaces',...\n OPTIONS.Cortex.FileName,OPTIONS.Cortex.iGrid))\n return\n end\n \n GridLoc = ImageGrid.Vertices{OPTIONS.Cortex.iGrid}; % keep only the desired cell\n ImageGrid = rmfield(ImageGrid,'Vertices');\n \nelseif ~isempty(OPTIONS.SourceLoc) % Specific source locations are provided\n if size(OPTIONS.SourceLoc,1) ~= 3\n OPTIONS.SourceLoc = OPTIONS.SourceLoc';\n end\n GridLoc = OPTIONS.SourceLoc;\n \nelse\n rmfield(OPTIONS,'rooot'); \n if nargout == 1\n varargout{1} = OPTIONS;\n else\n varargout{1} = HeadModel;\n varargout{2} = OPTIONS;\n end\n return % No ImageGrid requested\n \nend\n\nif ~isempty(OPTIONS.Cortex)\n GridName{OPTIONS.Cortex.iGrid} = ImageGrid.Comment{OPTIONS.Cortex.iGrid}; \n OPTIONS.Cortex.Name = ImageGrid.Comment{OPTIONS.Cortex.iGrid};\nend\n\n%for i = 1 % CHEAT - Dipoles only here\nfor Order = OPTIONS.SourceModel % Compute gain matrices for each requested source models (-1 0 1)\n \n i = 1; % Index to cell in headmodel cell arrays (MMII convention)\n \n switch(Order)\n case -1\n SourceOrderString = 'CD'; % Current Dipole\n Dims = DIMS(1);% number of columns per source\n case 0\n errordlg(sprintf('Unauthorized Source Model Order %d.',iSrcModel),'Wrong HeadModel parameter assignment')\n return\n %SourceOrderString = 'MD'; % Magnetic Dipole - OBSOLETE\n case 1\n SourceOrderString = 'CME'; % Current Multipole\n Dims = DIMS(2);% number of columns per source\n otherwise\n errordlg(sprintf('Unauthorized Source Model Order %d.',iSrcModel),'Wrong HeadModel parameter assignment')\n return\n end\n \n if OPTIONS.Verbose, \n bst_message_window(...\n 'wrap',...\n sprintf('Computing Gain Matrix for the %s Model',SourceOrderString))\n h = waitbar(0,sprintf('Computing Gain Matrix for the %s Model',SourceOrderString));\n pos = get(h,'position');\n end\n \n if ~isempty(OPTIONS.Cortex) & OPTIONS.ApplyGridOrient % Use cortical grid\n try\n load(OPTIONS.Cortex.FileName,'Faces');\n catch\n Users = get_user_directory;\n load(fullfile(Users.SUBJECTS,OPTIONS.Cortex.FileName),'Faces');\n end\n \n Faces = Faces{OPTIONS.Cortex.iGrid};\n \n ptch = patch('Vertices',GridLoc','Faces',Faces,'Visible','off');\n set(get(ptch,'Parent'),'Visible','off')\n clear Faces\n GridOrient{i} = get(ptch,'VertexNormals')'; % == {1} as of MMII conventions. Most data in HeadModel files are single-cell cell arrays.\n % Cell array structure kept for backward compatibility with BsT2000.\n delete(ptch);\n \n end\n \n if OPTIONS.ApplyGridOrient % Take cortex normals into account\n if isempty(OPTIONS.GridOrient) & isempty(OPTIONS.SourceOrient) % Consider the cortical patch's normals\n \n if isempty(OPTIONS.Cortex) % Specific source locations in .SourceLoc but nohing in. SourceOrient\n OPTIONS.ApplyGridOrient = 0; % No source orientation specified: Force computation of full gain matrix \n else\n [nrm,GridOrient{i}] = colnorm(GridOrient{i});\n % Now because some orientations may be ill-set to [0 0 0] with the get(*,'VertexNormals' command) \n % set these orientation to arbitrary [1 1 1]:\n izero = find(nrm == 0);clear nrm\n if ~isempty(izero)\n GridOrient{i}(:,izero) = repmat([1 1 1]'/norm([1 1 1]),1,length(izero));\n end\n clear izero\n \n end\n \n elseif ~isempty(OPTIONS.GridOrient) % Apply user-defined cortical source orientations\n \n if size(OPTIONS.GridOrient,2) == size(GridLoc,2) % Check size integrity\n GridOrient{i} = OPTIONS.GridOrient;\n [nrm,GridOrient{i}] = colnorm(GridOrient{i});\n clear nrm\n else\n errordlg(sprintf('The source orientations you have provided are for %0.f sources. Considered cortical surface has %0.f sources. Computation aborted',...\n size(OPTIONS.GridOrient,2),size(GridOrient{i},2)));\n return\n end\n \n elseif ~isempty(OPTIONS.SourceOrient) % Apply user-defined specific source orientations\n \n if size(OPTIONS.SourceOrient,2) == size(GridLoc,2) % Check size integrity\n GridOrient{i} = OPTIONS.SourceOrient;\n [nrm,GridOrient{i}] = colnorm(GridOrient{i});\n clear nrm\n else\n errordlg(sprintf('The source orientations you have provided are for %0.f sources. Computation aborted',...\n size(OPTIONS.SourceOrient,2)));\n return\n end\n \n end\n end\n \n nv = size(GridLoc,2); % number of grid points\n \n if ~isempty(OPTIONS.ImageGridFile) % Save cortical gain matrix in a binary file\n \n [PATH,NAME,EXT,VER] = spm_fileparts(OPTIONS.HeadModelFile);\n \n if strcmp(lower(OPTIONS.ImageGridFile),'default') \n if exist('GridName','var') % Cortical support was specified\n destname = [NAME,'_Gain_',strrep(ImageGrid.Comment{OPTIONS.Cortex.iGrid},' ',''),'_',SourceOrderString,'.bin']; % New naming (March, 19 - 2002)\n k = 1;\n try\n while exist(destname,'file') % Don't write over existing .bin gain matrix file\n destname = [NAME,'_Gain_',strrep(ImageGrid.Comment{OPTIONS.Cortex.iGrid},' ',''),'_',SourceOrderString,'_',int2str(k),'.bin']; % New naming (March, 19 - 2002)\n k = k+1;\n end\n catch\n while exist(destname,'file') % Don't write over existing .bin gain matrix file\n destname = [NAME,'_Gain_',strrep(ImageGrid.Comment{OPTIONS.Cortex.iGrid},' ',''),'_',SourceOrderString,'_',int2str(k),'.bin']; % New naming (March, 19 - 2002)\n k = k+1;\n end\n end\n \n clear k \n \n else % Specific location was provided in .SourceLoc\n destname = [NAME,'_Gain_SpecLoc_',SourceOrderString,'.bin']; % Specific location was provided in .SourceLoc\n k = 1;\n while exist(destname,'file') % Don't write over existing .bin gain matrix file\n destname = [NAME,'_Gain_SpecLoc_',SourceOrderString,'_',int2str(k),'.bin']; \n k = k+1;\n end\n clear k\n end\n OPTIONS.ImageGridFile = destname;\n else\n [PATH,destname,ext,ver] = spm_fileparts(OPTIONS.ImageGridFile);\n destname = [destname, ext];\n end\n \n % Check whether this name exists - if yes, don't overwrite\n try\n cd(fullfile(User.STUDIES,PATH))\n catch\n cd(PATH)\n end\n \n hdml = 1;\n while exist(destname,'file')\n if hdml == 1\n destname = strrep(destname,'.bin',['_',int2str(hdml),'.bin']);\n else\n destname = strrep(destname,[int2str(hdml-1),'.bin'],[int2str(hdml),'.bin']);\n end\n \n hdml = hdml+1;\n end\n clear hdml\n \n destnamexyz = [destname(1:end-4) '_xyz.bin'];\n fdest = fopen(destname,'w','ieee-be');\n fdestxyz = fopen(destnamexyz,'w','ieee-be');\n if ((fdest < 0) | (fdestxyz < 0))\n errordlg('Error creating the file for the cortical image forward model; Please check for disk space availability')\n return\n end\n frewind(fdest);\n frewind(fdestxyz)\n \n fwrite(fdest,length([OPTIONS.Channel]),'uint32'); \n fwrite(fdestxyz,length([OPTIONS.Channel]),'uint32'); \n \n % % BEM and non-interpolative, store gain matrix already computed \n % if isfield(OPTIONS,'BEM') % BEM computation\n % if ~OPTIONS.BEM.Interpolative\n % global GBEM_grid\n % end\n % end\n \n if ((fdest < 0) | (fdestxyz < 0)) , errordlg('Please Check Write Permissions', ['Cannot create ',destname]), return, end\n else % If no ImageGridFile was specified\n %OPTIONS.ImageGridBlockSize = nv; % Force a one-time computation of all source forward fields\n end\n \n src_ind = 0;\n jj = 0; % Number of OPTIONS.ImageGridBlockSize \n \n \n for j = 1:(OPTIONS.ImageGridBlockSize):nv, \n jj = jj+1;\n if 1%OPTIONS.ApplyGridOrient\n ndx = [0:OPTIONS.ImageGridBlockSize-1]+j;\n else\n ndx = [0:3*OPTIONS.ImageGridBlockSize-1]+j;\n end\n \n if 1%OPTIONS.ApplyGridOrient\n if(ndx(end) > nv), % last OPTIONS.ImageGridOPTIONS.ImageGridBlockSizeSize too long\n ndx = [ndx(1):nv];\n end\n else\n if(ndx(end) > 3*nv), \n ndx = [ndx(1):3*nv];\n end\n end\n \n % Compute MEG\n if MEG & ~isempty(MEGndx) \n Gmeg = NaN*zeros(length(MEGndx),Dims*length(ndx)); \n if ~isempty(Function{MEGndx(1)})\n \n if MEG & EEG\n clear('gain_bem_interp2'); % Free persistent variables to avoid confusion\n end\n \n if isfield(OPTIONS,'BEM') % BEM computation\n if ~OPTIONS.BEM.Interpolative % ~interpolative : retrieve stored gain matrix \n global GBEM_grid\n tmpndx = [3*(ndx(1)-1)+1:min([3*nv,3*ndx(end)])];%[0:3*OPTIONS.ImageGridBlockSize-1]+j;\n Gmeg = GBEM_grid(MEGndx,tmpndx);\n end\n else\n Gmeg = feval(Function{MEGndx(1)},GridLoc(:,ndx),Channel,Param,Order,OPTIONS.Verbose);\n end\n\n end\n else\n Gmeg = []; \n end\n \n if EEG & ~isempty(EEGndx) & i==1 % % Order -1 only for now in EEG \n \n Geeg = NaN*zeros(length(EEGndx),Dims*length(ndx)); \n if ~isempty(Function{EEGndx(1)})\n if MEG & EEG\n clear('gain_bem_interp2'); % Free persistent variables to avoid confusion\n end\n\n if isfield(OPTIONS,'BEM') % BEM computation\n if ~OPTIONS.BEM.Interpolative % ~interpolative : retrieve stored gain matrix \n global GBEM_grid\n %Geeg = GBEM_grid(EEGndx,[j:min([3*nv,j+3*OPTIONS.ImageGridBlockSize-1])]);\n tmpndx = [3*(ndx(1)-1)+1:min([3*nv,3*ndx(end)])];%[0:3*OPTIONS.ImageGridBlockSize-1]+j;\n %min(tmpndx ), max(tmpndx)\n Geeg = GBEM_grid(EEGndx,tmpndx);\n end\n else\n Geeg = feval(Function{EEGndx(1)},GridLoc(:,ndx),Channel,Param,Order,OPTIONS.Verbose);\n end\n \n end\n else\n Geeg = [];\n end\n \n G = NaN*zeros(length(OPTIONS.Channel),length(ndx));\n Gxyz = NaN*zeros(length(OPTIONS.Channel),Dims*length(ndx));\n \n if OPTIONS.Verbose, bst_message_window(...\n ['Computing Cortical Gain Vectors. . . Block # ',int2str(jj),...\n ' of ',int2str(length(1:OPTIONS.ImageGridBlockSize:nv))])\n \n hh = waitbar(0,['Computing Cortical Gain Vectors. . . Block # ',int2str(jj),...\n ' of ',int2str(length(1:OPTIONS.ImageGridBlockSize:nv))]);\n set(hh,'Position',[pos(1), pos(2)+pos(4),pos(3),pos(4)])\n drawnow\n end\n \n src = 0;\n % Options on cortical source orientation\n% if OPTIONS.ApplyGridOrient % Apply source orientation\n \n for k = 1:Dims:Dims*length(ndx)-2\n src = src+1;\n src_ind = src_ind+1;\n if ~isempty(Gmeg)\n G(MEGndx,src) = Gmeg(:,k:k+2) * GridOrient{1}(:,src_ind); \n end\n \n if ~isempty(Geeg)&(i==1)% % Order -1 only \n G(EEGndx,src) = Geeg(:,k:k+2) * GridOrient{1}(:,src_ind); \n end\n if OPTIONS.Verbose, \n if ~rem(src,5000)\n waitbar(src/length(1:Dims:Dims*length(ndx)-2),hh)\n end\n end\n \n end\n \n% else % Do not apply cortical orientation. Keep full gain matrix at each cortical location\n \n if MEG \n Gxyz(MEGndx,:) = Gmeg; \n end\n if EEG\n Gxyz(EEGndx,:) = Geeg;\n end\n \n% end\n \n if OPTIONS.Verbose, \n if ~rem(src_ind,1000)\n waitbar(src_ind/nv,h)\n end\n \n delete(hh)\n end\n \n clear Gmeg Geeg\n \n if ~isempty(OPTIONS.ImageGridFile) \n % 4 bytes per element, find starting point\n offset = 4 + (ndx(1)-1)*length(Channel)*4;\n \n % Matlab 6.5.0 bug, Technical Solution Number: 1-19NOK\n % http://www.mathworks.com/support/solutions/data/1-19NOK.html?solution=1-19NOK\n % must REWIND first before fseek.\n % Apparently fixed in 6.5.1\n % JCM 27-May-2004\n status = fseek(fdest,0,'bof');\n status = fseek(fdest,offset,'bof');\n if(status == -1),\n errordlg('Error writing Image Gain Matrix file'); return\n end\n\n fwrite(fdest,G,'float32');\n\n %save xyz forward matrix\n offset = 4 + 3*(ndx(1)-1)*length(Channel)*4;\n status = fseek(fdestxyz,0,'bof');\n status = fseek(fdestxyz,offset,'bof');\n if(status == -1),\n errordlg('Error writing Image Gain Matrix file'); return\n end\n fwrite(fdestxyz,Gxyz,'float32');\n \n end\n \n end\n if exist('destname','var') & ~isempty(OPTIONS.Cortex)\n Gain{OPTIONS.Cortex.iGrid}{i} = destname;\n OPTIONS.ImageGridFile = destname; \n end\n \n if OPTIONS.Verbose\n close(h)\n end\n \n if ~isempty(OPTIONS.ImageGridFile) \n fclose(fdest);\n if OPTIONS.Verbose, bst_message_window({...\n sprintf('Computing Gain Matrix for the %s Model -> DONE',SourceOrderString),...\n sprintf('Saved in:'),...\n sprintf('%s',destname)...\n }),\n end\n end\n \n \n % Now save ImageGrid headmodel(s)-----------------------------------------------------------------------------------\n OPTIONS.HeadModelFile = OPTIONS.HeadModelFileOld; % Use original HeadModelFile entry\n if strcmp(lower(OPTIONS.HeadModelFile),'default')\n if ~isfield(OPTIONS,'rooot')\n OPTIONS.rooot = OPTIONS.PrefixFileName;\n end\n OPTIONS.HeadModelFile = [OPTIONS.rooot,'headmodel.mat'];\n ifile = 0; \n while exist(OPTIONS.HeadModelFile,'file') % Do not overwrite headmodel files\n ifile = ifile + 1;\n OPTIONS.HeadModelFile = [OPTIONS.rooot,'headmodel_',int2str(ifile),'.mat'];\n end\n \n elseif ~isfield(OPTIONS,'rooot') & ~isempty(OPTIONS.HeadModelFile)\n OPTIONS.rooot = strrep(OPTIONS.HeadModelFile,'headmodel.mat',''); \n end\n \n SaveHeadModel.Param = HeadModel.Param;\n SaveHeadModel.Function = HeadModel.Function;\n \n if MEG \n SaveHeadModel.MEGMethod = OPTIONS.Method{DataType.MEG};\n end\n if EEG \n SaveHeadModel.EEGMethod = OPTIONS.Method{DataType.EEG};\n end\n \n if strcmpi(OPTIONS.HeadModelName,'Default') % Specify default HeadModelName \n if MEG & EEG\n SaveHeadModel.HeadModelName = sprintf('%s | %s', OPTIONS.Method{DataType.MEG},OPTIONS.Method{DataType.EEG});\n elseif MEG\n SaveHeadModel.HeadModelName = sprintf('%s', OPTIONS.Method{DataType.MEG});\n elseif EEG\n SaveHeadModel.HeadModelName = sprintf('%s', OPTIONS.Method{DataType.EEG});\n end\n else\n SaveHeadModel.HeadModelName = OPTIONS.HeadModelName; \n end\n \n if ~isempty(OPTIONS.HeadModelFile), % and is not empty\n [HeadModelFilePath,HeadModelFile,ext] = fileparts(OPTIONS.HeadModelFile);\n end\n \n % Assign proper GridName\n switch(Order)\n case -1\n SourceOrderString = 'CD'; % Current Dipole\n case 0\n SourceOrderString = 'MD'; % Magnetic Dipole\n case 1\n SourceOrderString = 'CME'; % Current Multipole\n end\n \n [SaveHeadModel.Param.Order] = deal(Order);\n SaveHeadModel.SourceOrder = Order; % Alternative to previous line\n SaveHeadModel.HeadModelType = 'ImageGrid';\n \n \n if ~isempty(OPTIONS.Cortex)\n SaveHeadModel.GridName = {sprintf('%s Surface Grid : %s',SourceOrderString, OPTIONS.Cortex.Name)};\n if ~isempty(OPTIONS.ImageGridFile) \n SaveHeadModel.Gain = {OPTIONS.ImageGridFile}; % Store Image Grid File name in the headmodel.mat file\n end\n \n SaveHeadModel.GainCovar{1} = cell(1); % May compute it later within headmodel_make\n SaveHeadModel.GainCovarName ='';\n SaveHeadModel.GridLoc{1} = OPTIONS.Cortex.FileName;\n if 1%OPTIONS.Cortex.iGrid > 1 % Meaning that cortical support is not the fisrt surface in tessellation file (default in MMII)\n % Add yet another field to headmodel file to specify this information.\n SaveHeadModel.iGrid = OPTIONS.Cortex.iGrid;\n end\n else\n SaveHeadModel.GainCovar = [];\n SaveHeadModel.GainCovarName = [];\n SaveHeadModel.GridName = [];\n SaveHeadModel.GridLoc = {OPTIONS.SourceLoc};\n SaveHeadModel.Gain = {OPTIONS.ImageGridFile};\n end\n if ~OPTIONS.ApplyGridOrient\n SaveHeadModel.GridOrient = [];\n else\n SaveHeadModel.GridOrient = {OPTIONS.SourceOrient};\n end\n \n \n % now collect together and save\n if ~isempty(OPTIONS.HeadModelFile) & exist('destname','var')\n % HeadModel file name\n SaveHeadModelFile = fullfile(HeadModelFilePath,[HeadModelFile,...\n sprintf('SurfGrid_%s',SourceOrderString),...\n ext]);\n ifile = 0;\n while exist(SaveHeadModelFile,'file') % Do not overwrite headmodel files\n ifile = ifile + 1;\n SaveHeadModelFile = fullfile(HeadModelFilePath,[HeadModelFile,...\n sprintf('SurfGrid_%s',SourceOrderString),...\n '_',int2str(ifile),ext]);\n end\n if OPTIONS.Verbose, bst_message_window({...\n sprintf('Writing Cortical Image Support HeadModel file:'),...\n sprintf('%s', SaveHeadModelFile)...\n })\n end\n \n if strcmp(lower(OPTIONS.HeadModelFileOld),'default')\n OPTIONS.HeadModelFile = SaveHeadModelFile;\n end\n \n try\n save_fieldnames(SaveHeadModel, SaveHeadModelFile);\n catch\n cd(User.STUDIES)\n save_fieldnames(SaveHeadModel, SaveHeadModelFile);\n end\n \n \n if OPTIONS.Verbose, bst_message_window(...\n {'-> DONE',' '}), end\n end\n \n % Save completed -----------------------------------------------------------------------------------\n \nend % Cortical gain matrix for each source model\n\n\n%% -------------------------------------------------------------------------\nif isfield(OPTIONS,'rooot')\n OPTIONS = rmfield(OPTIONS,'rooot');\nend\n\nif nargout == 0\n clear G SearchGain\nelseif nargout == 1\n varargout{1} = OPTIONS;\nelse\n if OPTIONS.ImageGridBlockSize < nv\n varargout{1} = OPTIONS.HeadModelFile;\n else\n varargout{1} = G;\n end\n \n varargout{2} = OPTIONS;\nend\n\nfclose('all');\n\nif OPTIONS.Verbose, bst_message_window(...\n {'The head model has been properly designed and written to disk'})\nend\n\nif OPTIONS.Verbose, bst_message_window({...\n sprintf(...\n 'Head modeling ends (%s - %dH %dmin %ds (took %3.2f seconds))',date,clockk(4:6), etime(clock,time0)),...\n '__________________________________________'...\n })\nend\n\n%------------------------------------------------------------------------------------------------------------------------------\n% \n% SUB-FUNCTIONS\n% \n%------------------------------------------------------------------------------------------------------------------------------\n\nfunction BEMGaingridFname = bem_GainGrid(DataType,OPTIONS,BEMChanNdx)\n\n% Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data\n% DataType : a structure with fields MEG and EEG. DataType.MEG (res. DataType.EEG) is set to 1 if MEG (res. EEG) data is available\n% OPTIONS : the OPTIONS structure, input argument from bst_headmodeler\n% BEMChanNdx : a cell array of channel indices such that : BEMChanNdx{DataType.EEG} = EEGndx (res. MEG).\n%\n% BEMGaingridFname: a structure with fields:\n% .EEG : string with the name of the file containing the gain matrix of the 3D BEM interpolative grid in EEG\n% .MEG : same as .EEG respectively to MEG BEM model.\n\n\n% Detect the requested BEM computations: MEG and/or EEG___________________________________\n\nUser = get_user_directory;\nif isempty(User)\n User.STUDIES = pwd;\n User.SUBJECTS = pwd;\nend\n\nMEG = ~isempty(BEMChanNdx(DataType.MEG)); % == 1 if MEG is requested \nEEG = ~isempty(BEMChanNdx(DataType.EEG)); % == 1 if EEG is requested\nif MEG \n MEGndx = BEMChanNdx{DataType.MEG};\nend\nif EEG \n %EEGndx = BEMChanNdx{DataType.EEG};\n EEGndx = OPTIONS.EEGndx; % EEG sensors (not including EEG reference channel, if any)\n EEGREFndx = good_channel(OPTIONS.Channel,[],'EEG REF');\nend\n\nif MEG & EEG\n [Param(:).mode] = deal(3);\nelseif ~MEG & EEG\n [Param(:).mode] = deal(1);\nelseif MEG & ~EEG\n [Param(:).mode] = deal(2);\nelse\n errordlg('Please check that the method requested for forward modeling has an authorized name');\n return\nend\n\n% BEM parameters ________________________________________________________________________\n% Determine what basis functions to use\nconstant = ~isempty(strmatch('constant',lower(OPTIONS.BEM.Basis)));\nif constant == 0\n [Param(:).basis_opt] = deal(1);\nelse\n [Param(:).basis_opt] = deal(0);\nend\n\n% Determine what Test to operate\ncollocation = ~isempty(strmatch('collocation',lower(OPTIONS.BEM.Test)));\nif collocation == 0\n [Param(:).test_opt] = deal(1);\nelse\n [Param(:).test_opt] = deal(0);\nend\n\n% Insulated-skull approach\nisa = OPTIONS.BEM.ISA;\nif isa == 1\n [Param(:).ISA] = deal(1);\nelse\n [Param(:).ISA] = deal(0);\nend\n\nParam.Ntess_max = OPTIONS.BEM.NVertMax;\nParam.Conductivity = deal(OPTIONS.Conductivity);\n\n%_________________________________________________________________________________________\n\n% Load surface envelopes information______________________________________________________\n\n% Find the indices of the enveloppes selected for BEM computation\nif ~isfield(OPTIONS.BEM,'EnvelopeNames')\n errordlg('Please specify the ordered set of head-tissue envelopes by filling the OPTIONS.BEM.EnvelopeNames field')\n return\nend\nif isempty(OPTIONS.BEM.EnvelopeNames)\n errordlg('Please specify the ordered set of head-tissue envelopes by filling the OPTIONS.BEM.EnvelopeNames field')\n return\nend\nfor k = 1:length(OPTIONS.BEM.EnvelopeNames)\n\n try\n load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Comment');\n catch % Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile\n try\n OPTIONS.BEM.EnvelopeNames{k}.TessFile = [OPTIONS.BEM.EnvelopeNames{k}.TessFile,'.mat'];\n load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Comment');\n catch\n cd(User.SUBJECTS)\n load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Comment');\n end\n end\n\n Comment = strrep(Comment,' ','');\n % find surface in current tessellation file\n OPTIONS.BEM.EnvelopeNames{k}.SurfId = find(strcmpi(OPTIONS.BEM.EnvelopeNames{k}.TessName,Comment));\n IDs(k) = OPTIONS.BEM.EnvelopeNames{k}.SurfId;\n if isempty(OPTIONS.BEM.EnvelopeNames{k}.SurfId)\n errordlg(...\n sprintf('Surface %s was not found in file %s',...\n OPTIONS.BEM.EnvelopeNames{k}.TessName, OPTIONS.BEM.EnvelopeNames{k}.TessFile))\n return\n end\n\n % Load vertex locations\n try\n tmp = load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Vertices');\n catch % Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile\n tmp = load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Vertices');\n end\n Vertices{k} = tmp.Vertices{OPTIONS.BEM.EnvelopeNames{k}.SurfId}';\n\n % Load faces\n try\n tmp = load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Faces');\n catch% Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile\n tmp = load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Faces');\n end\n\n Faces(k) = tmp.Faces(OPTIONS.BEM.EnvelopeNames{k}.SurfId);\nend\nclear Comment tmp\n\ncd(User.STUDIES)\n\n\n%_________________________________________________________________________________________\n\n\n% Channel Parameters______________________________________________________________________\nif MEG\n R_meg1 = zeros(length(MEGndx),3);\n O_meg1 = R_meg1;\n R_meg2 = R_meg1;\n O_meg2 = O_meg1;\n flaggrad = zeros(length(MEGndx),1);% if = 1 - Flag to indicate there are some gradiometers here\n\n i = 0;\n for k = MEGndx\n i = i+1;\n R_meg1(i,:) = OPTIONS.Channel(k).Loc(:,1)';\n O_meg1(i,:) = OPTIONS.Channel(k).Orient(:,1)';\n\n if size(OPTIONS.Channel(k).Loc,2) == 2\n if sum(OPTIONS.Channel(k).Loc(:,1)-OPTIONS.Channel(k).Loc(:,2))~=0 % Gradiometer\n R_meg2(i,:) = OPTIONS.Channel(k).Loc(:,2)';\n O_meg2(i,:) = OPTIONS.Channel(k).Orient(:,2)';\n flaggrad(k-min(MEGndx)+1) = 1;\n end\n end\n\n end\n O_meg1 = (O_meg1' * inorcol(O_meg1'))';\n if exist('O_meg2','var')\n O_meg2 = (O_meg2' * inorcol(O_meg2'))';\n end\n\n % Handle MEG reference channels if necessary\n % if isfield(OPTIONS.Channel(MEGndx(1)),'irefsens')\n % irefsens = OPTIONS.Channel(MEGndx(1)).irefsens;\n % else\n % irefsens = [];\n % end\n irefsens = good_channel(OPTIONS.Channel,[],'MEG REF');\n\n if ~isempty(irefsens)\n flaggrad_REF = zeros(length(irefsens),1);% if = 1 - Flag to indicate there are some gradiometers here\n R_meg_REF = zeros(length(irefsens),3);\n O_meg_REF = R_meg_REF;\n R_meg_REF = R_meg_REF;\n O_meg_REF = R_meg_REF;\n\n if ~isempty(irefsens) & ~isempty(OPTIONS.Channel(MEGndx(1)).Comment) % Reference Channels are present\n if OPTIONS.Verbose, bst_message_window('Reference Channels have been detected.'), end\n end\n i = 0;\n for k = irefsens\n i = i+1;\n R_meg_REF(i,:) = OPTIONS.Channel(k).Loc(:,1)';\n O_meg_REF(i,:) = OPTIONS.Channel(k).Orient(:,1)';\n\n if size(OPTIONS.Channel(k).Loc,2) == 2\n if sum(OPTIONS.Channel(k).Loc(:,1)-OPTIONS.Channel(k).Loc(:,2))~=0 % Reference Gradiometer\n R_meg_REF2(i,:) = OPTIONS.Channel(k).Loc(:,2)';\n O_meg_REF2(i,:) = OPTIONS.Channel(k).Orient(:,2)';\n flaggrad_REF(k-min(irefsens)+1) = 1;\n end\n end\n\n end\n\n else\n R_meg_REF = [];\n O_meg_REF = R_meg_REF;\n R_meg_REF = R_meg_REF;\n O_meg_REF = R_meg_REF;\n end\n\n MEGndx_orig = MEGndx;\nelse\n R_meg1 = zeros(length(EEGndx),3); % Use dummy channel locations\n O_meg1 = R_meg1;\n R_meg2 = R_meg1;\n O_meg2 = O_meg1;\nend\n\nif EEG\n R_eeg = zeros(length([EEGREFndx,EEGndx]),3);\n i = 0;\n for k = [EEGREFndx,EEGndx]\n i = i+1;\n R_eeg(i,:) = OPTIONS.Channel(k).Loc(:,1)';\n end\n if ~MEG\n flaggrad = [];\n irefsens = [];\n end\n\nelse\n R_eeg = NaN * zeros(size(R_meg1)); % Dummy coordinates\nend\n\n%_________________________________________________________________________________________\n\n\n%Compute Transfer Matrices__________________________________________________________________\n\nBrainStorm.iscalp = IDs(end); % Index of the outermost surface (scalp, supposedly)\n\neeg_answ = '';\nmeg_answ = '';\n\n% Check whether some transfer-matrix files already exist for current study\n\nfn_eeg = sprintf('%s_eegxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\nfn_meg = sprintf('%s_megxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\nif MEG\n test = exist(fn_meg,'file');\nelseif EEG\n test = exist(fn_eeg,'file');\nelse MEG& EEG\n test = exist(fn_eeg,'file') & exist(fn_meg,'file');\nend\n\nif (OPTIONS.BEM.ForceXferComputation | ~test) | OPTIONS.BEM.Interpolative\n\n % Force (re)computation of transfer matrices, even if files exist in current study folder\n\n % if OPTIONS.Verbose, bst_message_window('Computing the BEM Transfer Matrix (this may take a while)....'), end\n\n global nfv\n nfv = bem_xfer(R_eeg,R_meg1,O_meg1,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...\n Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg,Param.Ntess_max,OPTIONS.Verbose,OPTIONS.BEM.checksurf);\n\n if ~isempty(find(flaggrad))\n if OPTIONS.Verbose, bst_message_window({'Gradiometers detected',...\n 'Computing corresponding Gain Matrix. . .'}), end\n\n %fn_meg_2 = fullfile(pwd,[OPTIONS.rooot,'_megxfer_2.mat']);\n fn_meg_2 = sprintf('%s_megxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n bem_xfer(R_eeg,R_meg2,O_meg2,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...\n Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_2,Param.Ntess_max,0,OPTIONS.BEM.checksurf); % Verbose = 0\n if OPTIONS.Verbose, bst_message_window('Gradiometer Channel Gain Matrix is Completed.'), end\n end\n\n if ~isempty(irefsens) % Do the same for reference channels\n %fn_meg_REF = fullfile(pwd,[OPTIONS.rooot,'_megxfer_REF.mat']);\n fn_meg_REF = sprintf('%s_megREFxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n bem_xfer(R_eeg,R_meg_REF,O_meg_REF,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...\n Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_REF,Param.Ntess_max,0,OPTIONS.BEM.checksurf);% Verbose = 0\n\n if ~isempty(find(flaggrad_REF))\n\n if OPTIONS.Verbose, bst_message_window({'MEG Reference Channels detected',...\n 'Computing corresponding Gain Matrix. . .'}), end\n\n %fn_meg_REF2 = fullfile(pwd,[OPTIONS.rooot,'_megxfer_REF2.mat']);\n fn_meg_REF2 = sprintf('%s_megREFxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n\n bem_xfer(R_eeg,R_meg_REF2,O_meg_REF2,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...\n Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_REF2,Param.Ntess_max,0,OPTIONS.BEM.checksurf);% Verbose = 0\n if OPTIONS.Verbose, bst_message_window('MEG Reference Channel Gain Matrix is Completed.'), end\n end\n end\nend\n\n% Computation of TRANSFER MATRIX Completed ___________________________________________________\n\n\n%%%% THIS PART SPECIFIES PARAMETERS USED TO GENERATE THE 3-D GRID %%%%%%%%%%\n\n\nif OPTIONS.BEM.Interpolative%1%~exist(BEMGridFileName,'file')\n\n if OPTIONS.Verbose, bst_message_window('Computing BEM Interpolative Grid. . .'), end\n\n BEMGridFileName = [OPTIONS.rooot,'grid.mat'];\n\n % update tessellated envelope with surfaces possibly modified by\n % BEM_XFER (downsampling, alignment, embedding etc.)\n Vertices = {nfv(:).vertices};\n Faces = {nfv(:).faces};\n gridmaker(Vertices,Faces,BEMGridFileName,OPTIONS.Verbose);\n\n if OPTIONS.Verbose,\n bst_message_window('Computing BEM Interpolative Grid -> DONE'),\n\n % Visualization of surfaces + grid points\n for k = 1:length(Vertices)\n [hf,hs(k),hl] = view_surface('Head envelopes & a subset of BEM interpolative grid points',Faces{k},Vertices{k});\n view(90,0)\n delete(hl)\n end\n camlight\n rotate3d on\n\n set(hs(1),'FaceAlpha',.3,'edgealpha',.3,'edgecolor','none','facecolor','r')\n set(hs(2),'FaceAlpha',.2,'edgealpha',.2,'edgecolor','none','facecolor','g')\n set(hs(3),'FaceAlpha',.1,'edgealpha',.1,'edgecolor','none','facecolor','b')\n\n hold on\n\n load(BEMGridFileName)\n hgrid = scatter3(Rq_bemgrid(1:10:end,1),Rq_bemgrid(1:10:end,2),Rq_bemgrid(1:10:end,3),'.','filled');\n\n end\n\nelse\n\n global GBEM_grid\n\n % Grid points are the locations of the distributed sources\n if isempty(OPTIONS.Cortex) % CBB (SB, 07-May-2004)| Should work also for volumic grid\n errordlg('Please select a cortical grid for computation of BEM vector fields')\n return\n end\n\n try\n load(OPTIONS.Cortex.FileName); % Load tessellation supporting the source locations and orientations\n catch\n Users = get_user_directory;\n load(fullfile(Users.SUBJECTS,OPTIONS.Cortex.FileName)); % Load tessellation supporting the source locations and orientations\n end\n\n BEMGridFileName.Loc = Vertices{OPTIONS.Cortex.iGrid}; clear Vertices\n\n if OPTIONS.ApplyGridOrient % Take cortex normals into account\n ptch = patch('Vertices',BEMGridFileName.Loc','Faces',Faces{OPTIONS.Cortex.iGrid},'Visible','off');\n set(get(ptch,'Parent'),'Visible','off')\n clear Faces\n BEMGridFileName.Orient = get(ptch,'VertexNormals')';\n delete(ptch);\n [nrm,BEMGridFileName.Orient] = colnorm(BEMGridFileName.Orient);\n % Now because some orientations may be ill-set to [0 0 0] with the get(*,'VertexNormals' command)\n % set these orientation to arbitrary [1 1 1]:\n izero = find(nrm == 0);clear nrm\n if ~isempty(izero)\n BEMGridFileName.Orient(:,izero) = repmat([1 1 1]'/norm([1 1 1]),1,length(izero));\n end\n clear izero\n else\n BEMGridFileName.Orient = [];\n end\n\n %if OPTIONS.Verbose, bst_message_window(sprintf('Loading BEM interpolative grid points from %s', BEMGridFileName)), end\n\nend\n\n\n\n% This part computes the gain matrices defined on precomputed grid------------------------------------------------------------\n\n% Assign file names where to store the gain matrices\nif MEG & ~EEG\n bem_xfer_mfname = {fn_meg};\n %BEMGaingridFname = [OPTIONS.rooot,'_meggain_grid.mat'];\n BEMGaingridFname = sprintf('%s_MEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n test = exist(BEMGaingridFname,'file');\nelseif EEG & ~ MEG\n bem_xfer_mfname = {fn_eeg};\n %BEMGaingridFname = [OPTIONS.rooot,'_eeggain_grid.mat'];\n BEMGaingridFname = sprintf('%s_EEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n test = exist(BEMGaingridFname,'file');\nelseif EEG & MEG\n bem_xfer_mfname = {fn_meg,fn_eeg};\n % BEMGaingridFname.MEG = [OPTIONS.rooot,'_meggain_grid.mat'];\n % BEMGaingridFname.EEG = [OPTIONS.rooot,'_eeggain_grid.mat'];\n BEMGaingridFname.MEG = sprintf('%s_MEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n BEMGaingridFname.EEG = sprintf('%s_EEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n test = exist(BEMGaingridFname.MEG,'file') & exist(BEMGaingridFname.EEG,'file');\nend\n\nif 1%OPTIONS.BEM.ForceXferComputation | ~test% Recompute gain matrices when transfer matrices have been recomputed just before\n\n if OPTIONS.Verbose\n if OPTIONS.BEM.Interpolative\n bst_message_window('Computing the BEM gain matrix for interpolative grid. . .'),\n else\n bst_message_window('Computing the BEM gain matrix for source grid. . .'),\n end\n end\n\n t0 = clock;\n\n if OPTIONS.Verbose,\n if MEG & EEG\n bst_message_window('for MEG and EEG channels. . .')\n elseif EEG\n bst_message_window('for EEG channels. . .')\n elseif MEG\n bst_message_window('for MEG channels. . .')\n end\n end\n\n\n if length(bem_xfer_mfname) == 1 % xor(MEG,EEG)\n bem_gain(BEMGridFileName,bem_xfer_mfname{1},Param(1).ISA,BEMGaingridFname, OPTIONS.Verbose);\n else\n % MEG gaingrid matrix\n bem_gain(BEMGridFileName,bem_xfer_mfname{1},Param(1).ISA,BEMGaingridFname.MEG, OPTIONS.Verbose);\n % EEG gaingrid matrix\n bem_gain(BEMGridFileName,bem_xfer_mfname{2},Param(1).ISA,BEMGaingridFname.EEG, OPTIONS.Verbose);\n end\n\n if OPTIONS.Verbose, bst_message_window('-> DONE'), end\n\n if ~isempty(find(flaggrad)) % Compute forward model on the second set of magnetometers from the gradiometers array\n\n bem_xfer_mfname = sprintf('%s_megxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n bem_gaingrid_mfname_2 = sprintf('%s_MEGGainGrid2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n\n if OPTIONS.Verbose, bst_message_window('MEG - completing gradiometers. . .'), end\n\n bem_gain(BEMGridFileName,bem_xfer_mfname,Param(1).ISA,bem_gaingrid_mfname_2,OPTIONS.Verbose);\n\n if OPTIONS.Verbose, bst_message_window('-> DONE'), end\n\n if MEG & EEG\n G1 = load(BEMGaingridFname.MEG);\n else\n G1 = load(BEMGaingridFname);\n end\n G2 = load(bem_gaingrid_mfname_2);\n % Apply respective weights within the gradiodmeters\n meg_chans = [OPTIONS.Channel(MEGndx(find(flaggrad))).Weight];\n w1 = meg_chans(1:2:end);\n w2 = meg_chans(2:2:end);\n\n G1.GBEM_grid(find(flaggrad),:) = w1'*ones(1,size(G1.GBEM_grid,2)).*G1.GBEM_grid(find(flaggrad),:)...\n + w2' * ones(1,size(G1.GBEM_grid,2)).*G2.GBEM_grid(find(flaggrad),:);\n clear G2\n\n % is there special reference channel considerations?\n if ~isempty(irefsens)\n\n % Forward model on all reference sensors\n bem_xfer_mfname_REF = sprintf('%s_megREFxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n bem_gaingrid_mfname_REF = sprintf('%s_MEGGainGrid_REF_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n\n if OPTIONS.Verbose, bst_message_window('MEG reference channels. . .'), end\n bem_gain(BEMGridFileName,bem_xfer_mfname_REF,Param(1).ISA,bem_gaingrid_mfname_REF,OPTIONS.Verbose);\n if OPTIONS.Verbose, bst_message_window('-> DONE'), end\n\n if ~isempty(find(flaggrad_REF)) % Gradiometers are present in reference channels\n\n bem_xfer_mfname_REF2 = sprintf('%s_megREFxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n bem_gaingrid_mfname_REF2 = sprintf('%s_MEGGainGrid2_REF_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);\n\n if OPTIONS.Verbose, bst_message_window('MEG reference channels / completing gradiometers. . .'), end\n\n bem_gain(BEMGridFileName,bem_xfer_mfname_REF2,Param(1).ISA,bem_gaingrid_mfname_REF2,OPTIONS.Verbose);\n\n if OPTIONS.Verbose, bst_message_window('-> DONE'), end\n\n GR = load(bem_gaingrid_mfname_REF);\n GR2 = load(bem_gaingrid_mfname_REF2);\n\n meg_chans = [OPTIONS.Channel(irefsens(find(flaggrad_REF))).Weight];\n w1 = meg_chans(1:2:end);\n w2 = meg_chans(2:2:end);\n\n GR.GBEM_grid(find(flaggrad_REF),:) = w1'*ones(1,size(GR.GBEM_grid,2)).*GR.GBEM_grid(find(flaggrad_REF),:)...\n + w2' * ones(1,size(GR.GBEM_grid,2)).*GR2.GBEM_grid(find(flaggrad_REF),:);\n\n %GR.GBEM_grid(find(flaggrad_REF),:) = GR.GBEM_grid(find(flaggrad_REF),:) - GR2.GBEM_grid(find(flaggrad_REF),:);\n clear GR2;\n end\n\n % Apply nth-order gradient correction on good channels only\n %Weight by the current nth-order correction coefficients\n %G1.GBEM_grid = G1.GBEM_grid - Channel(MEGndx(1)).Gcoef(find(ChannelFlag(irefsens)>0),:)*GR.GBEM_grid;\n\n G1.GBEM_grid = G1.GBEM_grid - OPTIONS.Channel(MEGndx(1)).Comment*GR.GBEM_grid;\n\n end\n\n GBEM_grid = 1e-7*G1.GBEM_grid;\n\n if MEG & EEG\n save(BEMGaingridFname.MEG,'GBEM_grid','-append');\n else\n save(BEMGaingridFname,'GBEM_grid','-append');\n end\n\n end\n\n % Detect EEG reference - if none is specified in the .Comment or Type fields,\n % and if none was passed through OPTIONS.EEGRef\n % -> Apply average-referencing of the potentials by default.\n\n if EEG\n % EEG Reference Channel\n EEGREFndx = good_channel(OPTIONS.Channel,[],'EEG REF');\n \n if MEG & EEG\n load(BEMGaingridFname.EEG,'GBEM_grid')\n else\n load(BEMGaingridFname,'GBEM_grid')\n end\n \n \n if isempty(EEGREFndx)% AVERAGE REF\n GBEM_grid = GBEM_grid - repmat(mean(GBEM_grid),size(GBEM_grid,1),1);\n else\n % GBEM_grid = GBEM_grid(setdiff(EEGndx,EEGREFndx)-EEGndx(1)+1,:) - repmat(GBEM_grid(EEGREFndx-EEGndx(1)+1,:),size(GBEM_grid(setdiff(EEGndx,EEGREFndx)-EEGndx(1)+1,:),1),1);\n GBEM_grid = GBEM_grid(2:end,:) - repmat(GBEM_grid(1,:),length(EEGndx),1); % SB : EEG REF is stored as first sensor in GBEM_grid; see line 2226\n end\n \n if MEG \n save(BEMGaingridFname.EEG,'GBEM_grid','-append')\n else\n save(BEMGaingridFname,'GBEM_grid','-append') \n end\n \n end\n \n \n if MEG & EEG\n meg = load(BEMGaingridFname.MEG,'GBEM_grid');\n eeg = load(BEMGaingridFname.EEG,'GBEM_grid');\n GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2));\n GBEM_grid(MEGndx,:)= meg.GBEM_grid; clear meg\n GBEM_grid(EEGndx,:)= eeg.GBEM_grid; clear eeg\n \n elseif MEG\n \n meg = load(BEMGaingridFname,'GBEM_grid');\n GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2));\n GBEM_grid(MEGndx,:)= meg.GBEM_grid; clear meg\n \n elseif EEG\n \n eeg = load(BEMGaingridFname,'GBEM_grid');\n GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2));\n EEGndx = OPTIONS.EEGndx;\n GBEM_grid(EEGndx,:)= eeg.GBEM_grid; clear eeg\n \n %clear GBEM_grid\n % % Now save the combined MEG/EEG gaingrid matrix in a single file \n % MEGEEG_BEMGaingridFname = strrep(BEMGaingridFname.EEG,'eeg','meg_eeg');\n % Gmeg = load(BEMGaingridFname.MEG,'GBEM_grid');\n % GBEM_grid = NaN * zeros(length(OPTIONS.Channel),size(Gmeg.GBEM_grid,2));\n % GBEM_grid(MEGndx,:) = Gmeg.GBEM_grid; clear Gmeg \n % eeg = load(BEMGaingridFname.EEG);\n % \n % save_fieldnames(eeg,MEGEEG_BEMGaingridFname);\n % \n % GBEM_grid(setdiff(EEGndx,EEGREFndx),:) = eeg.GBEM_grid; clear eeg\n % \n % save(MEGEEG_BEMGaingridFname,'GBEM_grid','-append')\n % \n % BEMGaingridFname = MEGEEG_BEMGaingridFname;\n else\n save(BEMGaingridFname,'GBEM_grid','-append')\n end\n \n telap_meg_interp = etime(clock,t0);\n \n if OPTIONS.Verbose, bst_message_window(sprintf('Completed in %3.1f seconds', telap_meg_interp),...\n 'Computing the Gain Matrix for the Interpolative Grid Points -> DONE'), end\nelse\n % if MEG & EEG \n % if OPTIONS.Verbose, bst_message_window(sprintf('Loading 3D grid gain matrix from %s', BEMGaingridFname.EEG)),end \n % else\n % if OPTIONS.Verbose, bst_message_window(sprintf('Loading 3D grid gain matrix from %s', BEMGaingridFname)),end \n % end\nend\n\n\n\nfunction g = gterm_constant(r,rq)\n%gterm_constant \n% function g = gterm_constant(r,rq)\n\n% -------- 20-Nov-2002 14:06:02 ------------------------------\n% ---- Automatically Generated Comments Block using auto_comments -----------\n%\n% Alphabetical list of external functions (non-Matlab):\n% toolbox\\rownorm.m\n% ---------- 20-Nov-2002 14:06:02 ------------------------------\n\n\nif size(rq,1) == 1 % Just one dipole\n r_rq= [r(:,1)-rq(1),r(:,2)-rq(2),r(:,3)-rq(3)];\n n = rownorm(r_rq).^3;\n g = r_rq./[n,n,n];\nelse\n g = zeros(size(r,1),3*size(rq,1));\n isrc = 1;\n for k = 1:size(rq,1)\n r_rq= [r(:,1)-rq(k,1),r(:,2)-rq(k,2),r(:,3)-rq(k,3)];\n n = rownorm(r_rq).^3;\n g(:,3*(isrc-1)+1: 3*isrc) = r_rq./[n,n,n];\n isrc = isrc + 1;\n end\n \nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_bias_ui.m", "ext": ".m", "path": "spm5-master/spm_bias_ui.m", "size": 5571, "source_encoding": "utf_8", "md5": "e83510dcfcaf0a173e4edc8fdcceef8e", "text": "function spm_bias_ui(P)\n% Non-uniformity correct images.\n%\n% The objective function is related to minimising the entropy of\n% the image histogram, but is modified slightly.\n% This fixes the problem with the SPM99 non-uniformity correction\n% algorithm, which tends to try to reduce the image intensities. As\n% the field was constrainded to have an average value of one, then\n% this caused the field to bend upwards in regions not included in\n% computations of image non-uniformity.\n%\n%_______________________________________________________________________\n% Ref:\n% J Ashburner. 2002. \"Another MRI Bias Correction Approach\" [abstract].\n% Presented at the 8th International Conference on Functional Mapping of\n% the Human Brain, June 2-6, 2002, Sendai, Japan. Available on CD-Rom\n% in NeuroImage, Vol. 16, No. 2.\n%\n%_______________________________________________________________________\n%\n% The Prompts Explained\n%_______________________________________________________________________\n%\n% 'Scans to correct' - self explanatory\n%\n%_______________________________________________________________________\n%\n% Defaults Options\n%_______________________________________________________________________\n%[ things in square brackets indicate corresponding defaults field ]\n%\n% 'Number of histogram bins?'\n% The probability density of the image intensity is represented by a\n% histogram. The optimum number of bins depends on the number of voxels\n% in the image. More voxels allows a more detailed representation.\n% Another factor is any potential aliasing effect due to there being a\n% discrete number of different intensities in the image. Fewer bins\n% should be used in this case.\n% [defaults.bias.nbins]\n%\n% 'Regularisation?'\n% The importance of smoothness for the estimated bias field. Without\n% any regularisation, the algorithm will attempt to correct for\n% different grey levels arising from different tissue types, rather than\n% just correcting bias artifact.\n% Bias correction uses a Bayesian framework (again) to model intensity\n% inhomogeneities in the image(s). The variance associated with each\n% tissue class is assumed to be multiplicative (with the\n% inhomogeneities). The low frequency intensity variability is\n% modelled by a linear combination of three dimensional DCT basis\n% functions (again), using a fast algorithm (again) to generate the\n% curvature matrix. The regularization is based upon minimizing the\n% integral of square of the fourth derivatives of the modulation field\n% (the integral of the squares of the first and second derivs give the\n% membrane and bending energies respectively).\n% [defaults.bias.reg]\n%\n% 'Cutoff?'\n% Cutoff of DCT bases. Only DCT bases of periods longer than the\n% cutoff are used to describe the warps. The number used will\n% depend on the cutoff and the field of view of the image.\n% [defaults.bias.cutoff]\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_bias_ui.m 184 2005-05-31 13:23:32Z john $\n\n\nglobal defaults\n\nif nargin==1 && strcmpi(P,'defaults');\n\tdefaults.bias = edit_defaults(defaults.bias);\n\treturn;\nend;\nbias_ui(defaults.bias);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction bias_ui(flags)\n% User interface for nonuniformity correction\nspm('FnBanner',mfilename,'$Rev: 184 $');\n[Finter,unused,CmdLine] = spm('FnUIsetup','Flatten');\nspm_help('!ContextHelp',mfilename);\nPP = spm_select(Inf, 'image', 'Scans to correct');\nspm('Pointer','Watch');\nfor i=1:size(PP,1),\n\tspm('FigName',['Flatten: working on scan ' num2str(i)],Finter,CmdLine);\n\tdrawnow;\n\tP = deblank(PP(i,:));\n\tT = spm_bias_estimate(P,flags);\n\t[pth,nm,xt,vr] = spm_fileparts(P);\n\tS = fullfile(pth,['bias_' nm '.mat']);\n\t%S = ['bias_' nm '.mat'];\n\tspm_bias_apply(P,S);\nend;\nif 0,\nfg = spm_figure('FindWin','Interactive');\nif ~isempty(fg), spm_figure('Clear',fg); end;\nend\nspm('FigName','Flatten: done',Finter,CmdLine);\nspm('Pointer');\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction flags = edit_defaults(flags)\n\nnb = [32 64 128 256 512 1024 2048];\ntmp = find(nb == flags.nbins);\nif isempty(tmp), tmp = 6; end;\nflags.nbins = spm_input('Number of histogram bins?','+1','m',...\n [' 32 bins | 64 bins| 128 bins| 256 bins| 512 bins|1024 bins|2048 bins'],...\n nb, tmp);\n\nrg = [0 0.00001 0.0001 0.001 0.01 0.1 1.0 10];\ntmp = find(rg == flags.reg);\nif isempty(tmp), tmp = 4; end;\nflags.reg = spm_input('Regularisation?','+1','m',...\n ['no regularisation (0)|extremely light regularisation (0.00001)|'...\n\t 'very light regularisation (0.0001)|light regularisation (0.001)|',...\n\t 'medium regularisation (0.01)|heavy regularisation (0.1)|'...\n\t 'very heavy regularisation (1)|extremely heavy regularisation (10)'],...\n rg, tmp);\n\nco = [20 25 30 35 40 45 50 60 70 80 90 100];\ntmp = find(co == flags.cutoff);\nif isempty(tmp), tmp = 4; end;\nflags.cutoff = spm_input('Cutoff?','+1','m',...\n\t[' 20mm cutoff| 25mm cutoff| 30mm cutoff| 35mm cutoff| 40mm cutoff|'...\n\t ' 45mm cutoff| 50mm cutoff| 60mm cutoff| 70mm cutoff| 80mm cutoff|'...\n\t ' 90mm cutoff|100mm cutoff'],...\n\tco, tmp);\n\nreturn;\n%=======================================================================\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "eeg_sph.m", "ext": ".m", "path": "spm5-master/eeg_sph.m", "size": 20284, "source_encoding": "utf_8", "md5": "39633c72045d669d24460bbb0e2cee96", "text": "function G = eeg_sph(L,Channel,Param,Order,Verbose,varargin);\n%EEG_SPH - Calculate the electric potential , spherical head, arbitrary orientation\n% function G = eeg_sph(L,Channel,Param,Order,Verbose,varargin);\n% function G = eeg_sph(L,Channel,Param,Order);\n% L is 3 x nL, each column a source location\n% Channel is the channel structure, same for Param\n% Order is \n% -1 current dipole \n% 0 focal(magnetic) dipole % NOT SUPPORTED\n% 1 1st order multipole % NOT SUPPORTED\n% Param is \n% .EEGType is one of {'EEG_SINGLE', 'EEG_BERG', 'EEG_3SHELL'};\n% .Berg is set in Param(1) as\n% .mu\n% .lam\n% .Radii vector of radii, inside to outside\n% .Conductivity vector of sigmas inside to outside\n% .Center the sphere center\n%\n% Verbose : toggle Verbose mode\n%\n% See also BERG\n\n% ---------------------- 27-Jun-2005 10:44:15 -----------------------\n% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------\n%\n% CATEGORY: Forward Modeling\n%\n% Alphabetical list of external functions (non-Matlab):\n% toolbox\\dlegpoly.m\n% toolbox\\dotprod.m\n% toolbox\\good_channel.m\n% toolbox\\rownorm.m\n%\n% Subfunctions in this file, in order of occurrence in file:\n% G = gainp_sph6x(Rq,Re,R,sigma,nmax,method,mu_berg_in,lam_berg_in)\n%\n% At Check-in: $Author: Mosher $ $Revision: 24 $ $Date: 6/27/05 8:59a $\n%\n% This software is part of BrainStorm Toolbox Version 27-June-2005 \n% \n% Principal Investigators and Developers:\n% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,\n% University of Southern California, Los Angeles, CA\n% ** John C. Mosher, PhD, Biophysics Group,\n% Los Alamos National Laboratory, Los Alamos, NM\n% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,\n% CNRS, Hopital de la Salpetriere, Paris, France\n% \n% See BrainStorm website at http://neuroimage.usc.edu for further information.\n% \n% Copyright (c) 2005 BrainStorm by the University of Southern California\n% This software distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPL\n% license can be found at http://www.gnu.org/copyleft/gpl.html .\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n% ------------------------ 27-Jun-2005 10:44:15 -----------------------\n\n\n% /---Script Authors--------------------------------------\\\n% | |\n% | *** John Ermer, Ph.D. |\n% | Signal % Image Processing Institute |\n% | University of Southern California |\n% | Los Angeles, CA, USA |\n% | |\n% | *** John C. Mosher, Ph.D. |\n% | Biophysics Group |\n% | |\n% | *** Sylvain Baillet Ph.D. |\n% | Cognitive Neuroscience & Brain Imaging Laboratory |\n% | CNRS UPR640 - LENA | \n% | Hopital de la Salpetriere, Paris, France |\n% | sylvain.baillet@chups.jussieu.fr |\n% | |\n% \\-------------------------------------------------------/\n% \n% Date of creation: October, 25 1999\n%\n% Script History -----------------------------------------------------------------------------------------------------------\n% SB 19-Nov-2002 : Edited Header\n% Updated management of EEG reference\n% JCM 20-Nov-2002 : Fixed headers to have only one autocomments block\n% SB 09-Mar-2004 : Added verbose mode\n% --------------------------------------------------------------------------------------------------------------------------\n\nif nargin < 5\n Verbose = 1; % Default\nend\n\n%-----------------------------\n\nnmax = 80;\n\n%-----------------------------\n\n% EEG Channels\nEEGndx = good_channel(Channel,[],'EEG');\n\n% Reference Channel\nREFndx = good_channel(Channel,[],'EEG REF');\n\n% EEG Channel locations\n\n% Add EEG reference at the end of Channel and Param structures\nRe = [Channel(EEGndx).Loc,Channel(REFndx).Loc]'; % Electrode location array\nif length(Param) ~= length([EEGndx,REFndx])\n Param(REFndx) = Param(EEGndx(1));\nend\n\nParam = Param([EEGndx,REFndx]);\n\nRq = L';\ncenter = [Param.Center]';\nRe = Re - center;\n\nRq = Rq - repmat(center(1,:),size(Rq,1),1); % Back to origin [0 0 0] for the sensors and the sources\n\nclear tmp \n\nswitch(Param(1).EEGType)\ncase 'EEG_SINGLE'\n R = Param(1).Radii(end);\n sigma = Param(1).Conductivity(end);\notherwise\n R = Param(1).Radii;\n sigma = Param(1).Conductivity;\nend\n\nswitch(Param(1).EEGType)\n \ncase 'EEG_BERG'\n method = 2; \n mu_berg_in = Param(1).Berg.mu;\n lam_berg_in = Param(1).Berg.lam;\ncase 'EEG_3SHELL' \n method = 1; \n mu_berg_in = [];\n lam_berg_in = [];\notherwise\n method = 1; \n mu_berg_in = [];\n lam_berg_in = [];\nend\n\nif 1 % Projection of the EEG sensors on the sphere\n [theta phi Re_sph] = cart2sph(Re(:,1),Re(:,2),Re(:,3));\n Re_sph = R(end)*ones(size(Re_sph));\n [Re(:,1) Re(:,2) Re(:,3)] = sph2cart(theta,phi,Re_sph);\n \nend\n\nGtmp = gainp_sph6x(Rq,Re,R,sigma,nmax,method,mu_berg_in',lam_berg_in');\n\nif isempty(REFndx) % Average Reference\n \n G = NaN * zeros(length(EEGndx),size(Gtmp,2));\n %G(EEGndx,:) = Gtmp - repmat(mean(Gtmp),size(Gtmp,1),1); \n G = Gtmp - repmat(mean(Gtmp),size(Gtmp,1),1); \n clear Gtmp\n \nelse % Specific electrode as reference\n % Remove its lead field from all others\n % Note: reference leadfield is at the end of original G matrix (from gain_sph) \n G = NaN * zeros(length(EEGndx),size(Gtmp,2));\n %G(EEGndx,:) = Gtmp(1:end-1,:) - repmat(Gtmp(end,:),size(Gtmp,1)-1,1); \n %G = G(EEGndx,:);\n G = Gtmp(1:end-1,:) - repmat(Gtmp(end,:),size(Gtmp,1)-1,1); \n \n % % Reference lead field is zero\n % G(REFndx,:) = zeros(1,size(G,2));\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Subfunctions -------------------------------------------------------------------------------\n%\n%\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction G = gainp_sph6x(Rq,Re,R,sigma,nmax,method,mu_berg_in,lam_berg_in)\n\n%GAINP_SPH6X EEG Multilayer Spherical Forward Model\n% function G = gainp_sph6x(Rq,Re,R,sigma,nmax,method,mu_berg_in,lam_berg_in)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% EEG MULTILAYER SPHERICAL FORWARD MODEL (gainp_sph6x.m)\n%\n% This function computes the voltage potential forward gain matrix for an array of \n% EEG electrodes on the outermost layer of a single/multilayer conductive sphere. \n% Each region of the multilayer sphere is assumed to be concentric with \n% isontropic conductivity. EEG sensors are assumed to be located on the surface\n% of the outermost sphere. \n%\n% Calculation of the electric potiential is performed using either (user-specified)\n% of the following methods (Ref: Z. Zhang \"A fast method to compute surface \n% potentials generated by dipoles within multilayer anisotropic spheres\" \n% (Phys. Med. Biol. 40, pp335-349,1995) \n%\n% 1) Closed Form Solution (Single Shell Case Only). See formulas (1H,1H')\n%\n% 2) Series Expansion using Legendre Polynomials. See formulas (1I,2I,3I and 4I)\n%\n% 3) Series Approximiation of a Multilayer Sphere as three dipoles in a \n% single shell using \"Berg/Sherg\" parameter approximation.\n% See formulas (1i',5i\" and 6i)\n%\n% Dipole generator(s) are assumed to be interior to the innermost \"core\" layer. For those \n% dipoles external to the sphere, the dipole \"image\" is computed and used determine the \n% gain function. The exception to this is the Legendre Method where all dipoles MUST be \n% interior to the innermost \"core\" layer.\n%\n% INPUTS (Required):\n% Rq : dipole location(in meters) P x 3\n% Re : EEG sensors(in meters) on the scalp M x 3\n% R : radii(in meters) of sphere from \n% INNERMOST to OUTERMOST NL x 1\n% sigma: conductivity from INNERMOST to OUTERMOST NL x 1\n%\n% INPUTS (Optional):\n% nmax : # of terms used in Truncated Legendre Series scalar\n% If not specified, a default value based on outermost\n% dipole magnitude is computed. (Note: This parameter\n% is ignored when Berg Approximation is commanded)\n% method : Method used for computing forward potential \n% 1=Legendre Series Approx; 2=Berg Parameter Approx\n% (Note: Default and all other values invoke Legendre \n% Series Approx. Exception is single-shell case where\n% closed form solution is always used) scalar \n% mu_berg_in: User specified initial value for Berg eccentricity\n% factors (Required if Berg Method is commanded) 3 x 1\n% lam_berg_in: User specified initial value for Berg magnitude\n% factors (Required if Berg Method is commanded) 3 x 1\n% \n% WHERE: M=# of sensors; P=# of dipoles; NL = # of sphere layers\n%\n% OUTPUTS:\n% G : EEG forward model gain matrix M x (3*P)\n%\n% External Functions and Files:\n% dlegpoly.m; rownorm.m; dotprod.m: USC/LANL MEG/EEG Toolbox\n% zhang_fit.m: External Function used to fit Berg Parameters (Zhang Eq# 5i\")\n% \n% - John Ermer 6/3/99 \n% - 8/9/99: Modified to use EM image for dipoles external to brain\n% (Applies to single-shell and Berg Methods only) (John Ermer)\n% - 10/31/99: Optimized Processing Associated with Dipoles falling outside sphere\n% (Applies to single-shell and Berg Methods only) (John Ermer)\n% - 01/26/00: Corrected minor dimension error which caused program to fault when \n% external dipoles and multiple sensors were present. (John Ermer)\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%% THIS PART CHECKS INPUT PARAMETERS FOR THEIR DIMENSION AND VALIDITY %%%\n%\nNL = length(R); % # of concentric sphere layers\nP = size(Rq,1);\nM = size(Re,1);\n% \nif R(1)~= min(R)\n error('Head radii must be specified from innermost to outmost layer!!! ')\nend\n%\nif size(Rq,2) ~= 3\n error('Dipole location must have three columns!!!')\nend\n%\nif nargin < 6, % Check # of input terms to see if method is specified\n method = 1; % Default Method = Legendre Series Expansion\nelse\n if (method>2)|(method<0)\n method = 0; % Default Method = Legendre Series Expansion\n end\nend\n%\n%%% This part pre-initializes parameters used in future calculations %%%\n%\nG = zeros(M,3*P); % Pre-Allocate Gain Matrix\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% This part computes the potential for a dipole contained within a single-layer\n%%% homogeneous sphere using closed form formula \n%%% The EEG single-shell solution uses the vector form (which avoids computationally\n%%% expensive intrinsic functions) described by Mosher et al (\"EEG and MEG: Forward \n%%% Solutions for inverse problems\" IEEE BME Trans March 1999) \n%\nif NL == 1 % Single Shell Case (Closed Form Solution)\n %\n Re_mag = repmat(R(NL),P,M); %(PxM)\n Re_mag_sq = repmat(R(NL)*R(NL),P,M); %(PxM)\n Rq_mag = rownorm(Rq); %(Px1)\n %\n Rq1 = Rq; %(Px1)\n Rq1_mag = Rq_mag; %(Px1)\n Rq1_mag_sq = Rq_mag.*Rq_mag; %(Px1)\n Re_dot_Rq1 = Rq1*Re'; %(PxM)\n %\n const = 4.0*pi*sigma(NL);\n term = 1./(const*Rq1_mag_sq); %(Px1)\n %\n %%% This part checks for the presence of Berg dipoles which are external to\n %%% the sphere. For those dipoles external to the sphere, the dipole parameters\n %%% are replaced with the electrical image (internal to sphere) of the dipole\n %\n nx = find(Rq1_mag > R(NL));\n %\n if nx>0\n Rq1_temp = Rq1(nx,:);\n Rq1(nx,:) = R(NL)*R(NL)*Rq1_temp./repmat((rownorm(Rq1_temp).*rownorm(Rq1_temp)),1,3);\n Rq1_mag(nx,1) = rownorm(Rq1(nx,:));\n Rq1_mag_sq(nx,1) = Rq1_mag(nx,1).*Rq1_mag(nx,1);\n Re_dot_Rq1(nx,:) = R(NL)*R(NL)*Re_dot_Rq1(nx,:)./repmat((rownorm(Rq1_temp).*rownorm(Rq1_temp)),1,M);\n term(nx,:) = (R(NL)./rownorm(Rq1_temp)).*term(nx,:); \n % was : term(nx,:) = (R(NL)/rownorm(Rq1_temp))'.*term(nx,:); \n \n end\n %\n %%% Calculation of Forward Gain Matrix Contribution due to K-th Berg Dipole\n %\n Rq1_mag = repmat(Rq1_mag,1,M); %(PxM)\n Rq1_mag_sq = repmat(Rq1_mag_sq,1,M); %(PxM)\n term = repmat(term,1,M); %(PxM)\n %\n d_mag = reshape( rownorm(reshape(repmat(Re,1,P)',3,P*M)' ...\n -repmat(Rq1,M,1)) ,P,M); %(PxM)\n d_mag_cub = d_mag.*d_mag.*d_mag; %(PxM)\n F_scalar = d_mag.*(Re_mag.*d_mag+Re_mag_sq-Re_dot_Rq1); %(PxM)\n c1 = term.*(2*( (Re_dot_Rq1-Rq1_mag_sq)./d_mag_cub) ...\n + 1./d_mag - 1./Re_mag); %(PxM)\n c2 = term.*((2./d_mag_cub) + (d_mag+Re_mag)./(Re_mag.*F_scalar));\n %\n G = G + reshape(repmat((c1 - c2.*Re_dot_Rq1)',3,1),M,3*P) ...\n .*repmat(reshape(Rq1',1,3*P),M,1) ...\n + reshape(repmat((c2.*Rq1_mag_sq)',3,1),M,3*P) ...\n .*repmat(Re,1,P);\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n %%% This part computes the potential for a dipole contained within a multi-layer\n %%% isontropic sphere using Legendre Polynomial Expansion (Zhang Eqs 1H, 1H') \n %%% (Code based on gainp_sph.m by CCH, Aug/20/1995)\n %\nelseif (NL>1)&(method==1) % Multi-shell Case Using Legendre Expansion\n %\n Rq_mag = rownorm(Rq);\n %\n if ~all( Rq_mag < R(1)+eps ) % check if dipoles within the brain\n warndlg('Legendre method assumes all dipoles(s) inside brain layer - please modify dipole locations OR use the \"Berg\" approach')\n return\n end\n %\n % compute weights fn. fn depends only on the radii and cdv\n Rq_mag = rownorm(Rq);\n Re_mag = R(NL); % Radius of outermost layer (Sensor distance from origin\n %\n %\n if nargin < 5, % check # of inputs to see if nmax was specified\n nmax = fix(10/(1-max(Rq_mag)/Re_mag)); % Default for # Legendre Series Terms\n end\n %\n Ren = Re/Re_mag;\n Rqn = Rq./[Rq_mag,Rq_mag,Rq_mag];\n for k = 1:NL-1 \n s(k) = sigma(k)/sigma(k+1);\n end\n a = Re_mag./R;\n ainv = R/Re_mag;\n sm1 = s-1;\n twonp1 = 2*[1:nmax]+1;\n twonp1 = twonp1(:);\n f = zeros(nmax,1);\n %\n for n = 1:nmax\n np1 = n+1;\n Mc = eye(2);\n for k = 2:NL-1,\n Mc = Mc*[n+np1*s(k), np1*sm1(k)*a(k)^twonp1(n);...\n n*sm1(k)*ainv(k)^twonp1(n) , np1+n*s(k)];\n end;\n Mc(2,:) = [n*sm1(1)*ainv(1)^twonp1(n) , np1+n*s(1)]*Mc;\n Mc = Mc/(twonp1(n))^(NL-1);\n f(n) = n/(n*Mc(2,2)+np1*Mc(2,1));\n end;\n %\n onevec = ones(M,1);\n wtemp = ((twonp1./[1:nmax]').*f)/(4*pi*sigma(NL)*R(NL)^2); \n n = [1:nmax]';\n nm1 = n-1;\n \n for i = 1:P, % loop over all dipoles\n rqn = [Rqn(i,1)*onevec,Rqn(i,2)*onevec,Rqn(i,3)*onevec];\n cosgamma = dotprod(rqn,Ren); \n rqn = rqn(1,:); \n [Pl,dP] = dlegpoly(nmax,cosgamma); % evaluate legendre poly and its derivative\n ratio = (Rq_mag(i)/Re_mag).^nm1;\n z = Ren- cosgamma*rqn;\n w = wtemp.*ratio;\n \n Gterm1 = Pl'*(w.*n);\n Gterm2 = dP'*w;\n G(:,3*i-2:3*i) = Gterm1*rqn + [z(:,1).*Gterm2,z(:,2).*Gterm2,z(:,3).*Gterm2];\n end\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%----------------------------------------------------------------------------------%%\n %%% This part computes the potential for a dipole contained within a multi-layer\n %%% isontropic sphere using Berg Parameter Approximation (Zhang Eqs 1i',5i\" and 6i)\n %%% The EEG single-shell solution uses the vector form (which avoids computationally\n %%% expensive intrinsic functions) described by Mosher et al (\"EEG and MEG: Forward \n %%% Solutions for inverse problems\" IEEE BME Trans March 1999) \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\nelseif (NL>1)&(method==2)\n %\n if (~exist('mu_berg_in')|~exist('lam_berg_in'))\n error('Berg Parameters have not been specified!!!')\n elseif size(mu_berg_in)~=size(lam_berg_in)\n error('Berg Parameters are of Unequal Lengths!!!')\n else\n J = length(mu_berg_in);\n mu_berg = mu_berg_in;\n lam_berg = lam_berg_in;\n end\n %\n Re_mag = repmat(R(NL),P,M); %(PxM)\n Re_mag_sq = repmat(R(NL)*R(NL),P,M); %(PxM)\n Rq_mag = rownorm(Rq); %(Px1)\n Rq_mag_sq = Rq_mag.*Rq_mag; %(Px1)\n Re_dot_Rq = Rq*Re'; %(PxM)\n %\n for k=1:J\n %\n Rq1 = mu_berg(k)*Rq; %(Px3)\n Rq1_mag = mu_berg(k)*Rq_mag; %(Px1)\n Rq1_mag_sq = (mu_berg(k)*mu_berg(k))*Rq_mag_sq; %(Px1)\n Re_dot_Rq1 = mu_berg(k)*Re_dot_Rq; %(PxM)\n %\n const = 4.0*pi*sigma(NL);\n const1 = const/lam_berg(k);\n term = 1./(const1*Rq1_mag_sq); %(PxM)\n %\n %%% This part checks for the presence of Berg dipoles which are external to\n %%% the sphere. For those dipoles external to the sphere, the dipole parameters\n %%% are replaced with the electrical image (internal to sphere) of the dipole\n %\n nx = find(Rq1_mag > R(NL));\n %\n if nx>0\n Rq1_temp = Rq1(nx,:);\n Rq1(nx,:) = R(NL)*R(NL)*Rq1_temp./repmat((rownorm(Rq1_temp).*rownorm(Rq1_temp)),1,3);\n Rq1_mag(nx,1) = rownorm(Rq1(nx,:));\n Rq1_mag_sq(nx,1) = Rq1_mag(nx,1).*Rq1_mag(nx,1);\n Re_dot_Rq1(nx,:) = R(NL)*R(NL)*Re_dot_Rq1(nx,:)./repmat((rownorm(Rq1_temp).*rownorm(Rq1_temp)),1,M);\n term(nx,:) = (R(NL)/rownorm(Rq1_temp))'.*term(nx,:);\n end\n %\n %%% Calculation of Forward Gain Matrix Contribution due to K-th Berg Dipole\n %\n Rq1_mag = repmat(Rq1_mag,1,M); %(PxM)\n Rq1_mag_sq = repmat(Rq1_mag_sq,1,M); %(PxM)\n term = repmat(term,1,M); %(PxM)\n %\n d_mag = reshape( rownorm(reshape(repmat(Re,1,P)',3,P*M)' ...\n -repmat(Rq1,M,1)) ,P,M); %(PxM)\n d_mag_cub = d_mag.*d_mag.*d_mag; %(PxM)\n %\n F_scalar = d_mag.*(Re_mag.*d_mag+Re_mag_sq-Re_dot_Rq1); %(PxM)\n %\n c1 = term.*(2*( (Re_dot_Rq1-Rq1_mag_sq)./d_mag_cub) ...\n + 1./d_mag - 1./Re_mag); %(PxM)\n c2 = term.*((2./d_mag_cub) + (d_mag+Re_mag)./(Re_mag.*F_scalar));\n %\n G = G + reshape(repmat((c1 - c2.*Re_dot_Rq1)',3,1),M,3*P) ...\n .*repmat(reshape(Rq1',1,3*P),M,1) ...\n + reshape(repmat((c2.*Rq1_mag_sq)',3,1),M,3*P) ...\n .*repmat(Re,1,P);\n end\n %\n %---------------------------------------------------------------------------------------\n %\nend % End of Check for Forward Model Calculation Method\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_realign.m", "ext": ".m", "path": "spm5-master/spm_config_realign.m", "size": 18757, "source_encoding": "utf_8", "md5": "4dc0590fa5df15dcda89cfc0de14114e", "text": "function opts = spm_config_realign\n% Configuration file for realign jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_realign.m 751 2007-02-28 10:56:59Z volkmar $\n\n\n%_______________________________________________________________________\n\nquality.type = 'entry';\nquality.name = 'Quality';\nquality.tag = 'quality';\nquality.strtype = 'r';\nquality.num = [1 1];\nquality.def = 'realign.estimate.quality';\nquality.extras = [0 1];\nquality.help = {[...\n'Quality versus speed trade-off. Highest quality (1) gives most ',...\n'precise results, whereas lower qualities gives faster realignment. ',...\n'The idea is that some voxels contribute little to the estimation of ',...\n'the realignment parameters. This parameter is involved in selecting ',...\n'the number of voxels that are used.']};\n\n%------------------------------------------------------------------------\n\nweight.type = 'files';\nweight.name = 'Weighting';\nweight.tag = 'weight';\nweight.filter = 'image';\nweight.num = [0 1];\nweight.val = {{}};\nweight.help = {[...\n'The option of providing a weighting image to weight each voxel ',...\n'of the reference image differently when estimating the realignment ',...\n'parameters. The weights are proportional to the inverses of the ',...\n'standard deviations. ',...\n'For example, when there is a lot of extra-brain motion - e.g., during ',...\n'speech, or when there are serious artifacts in a particular region of ',...\n'the images.']};\n\n%------------------------------------------------------------------------\n\ninterp.type = 'menu';\ninterp.name = 'Interpolation';\ninterp.tag = 'interp';\ninterp.labels = {'Trilinear (1st Degree)','2nd Degree B-Spline',...\n'3rd Degree B-Spline ','4th Degree B-Spline','5th Degree B-Spline',...\n'6th Degree B-Spline','7th Degree B-Spline'};\ninterp.values = {1,2,3,4,5,6,7};\ninterp.def = 'realign.estimate.interp';\ninterp.help = {...\n['The method by which the images are sampled when estimating the optimum transformation. ',...\n'Higher degree interpolation methods provide the better interpolation, but they are slower ',...\n'because they use more neighbouring voxels /* \\cite{thevenaz00a,unser93a,unser93b}*/. ']};\n \n%------------------------------------------------------------------------\n \nwrap.type = 'menu';\nwrap.name = 'Wrapping';\nwrap.tag = 'wrap';\nwrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z',...\n 'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'};\nwrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]};\nwrap.def = 'realign.estimate.wrap';\nwrap.help = {...\n['This indicates which directions in the volumes the values should wrap around in. ',...\n'For example, in MRI scans, the images wrap around in the phase encode direction, ',...\n'so (e.g.) the subject''s nose may poke into the back of the subject''s head. ',...\n'These are typically:'],...\n[' No wrapping - for PET or images that have already ',...\n ' been spatially transformed. Also the recommended option if ',...\n ' you are not really sure.'],...\n[' Wrap in Y - for (un-resliced) MRI where phase encoding ',...\n ' is in the Y direction (voxel space).']};\n \n%------------------------------------------------------------------------\n\nfwhm.type = 'entry';\nfwhm.name = 'Smoothing (FWHM)';\nfwhm.tag = 'fwhm';\nfwhm.num = [1 1];\nfwhm.def = 'realign.estimate.fwhm';\nfwhm.strtype = 'e';\np1 = [...\n'The FWHM of the Gaussian smoothing kernel (mm) applied to the ',...\n'images before estimating the realignment parameters.'];\np2 = ' * PET images typically use a 7 mm kernel.';\np3 = ' * MRI images typically use a 5 mm kernel.';\nfwhm.help = {p1,'',p2,'',p3};\n\n%------------------------------------------------------------------------\n\nsep.type = 'entry';\nsep.name = 'Separation';\nsep.tag = 'sep';\nsep.num = [1 1];\nsep.strtype = 'e';\nsep.def = 'realign.estimate.sep';\n%sep.val = {4};\nsep.help = {[...\n'The separation (in mm) between the points sampled in the ',...\n'reference image. Smaller sampling distances gives more accurate ',...\n'results, but will be slower.']};\n\n%------------------------------------------------------------------------\n\nrtm.type = 'menu';\nrtm.name = 'Num Passes';\nrtm.tag = 'rtm';\nrtm.labels = {'Register to first','Register to mean'};\nrtm.values = {0,1};\nrtm.def = 'realign.estimate.rtm';\np1 = [...\n'Register to first: Images are registered to the first image in the series. ',...\n'Register to mean: A two pass procedure is used in order to register the ',...\n'images to the mean of the images after the first realignment.'];\np2 = [...\n'PET images are typically registered to the mean. This is because PET data are ',...\n'more noisy than fMRI and there are fewer of them, so time is less of an issue.'];\np3 = [...\n'MRI images are typically registered to the first image. The more accurate way ',...\n'would be to use a two pass procedure, but this probably wouldn''t improve the results ',...\n'so much and would take twice as long to run.'];\nrtm.help = {p1,'',p2,'',p3};\n\n%------------------------------------------------------------------------\n\n% global defaults\n% if ~isempty(defaults) && isfield(defaults,'modality') ...\n% && strcmp(lower(defaults.modality),'pet'),\n% fwhm.val = {7};\n% rtm.val = {1};\n% else\n% fwhm.val = {5};\n% rtm.val = {0};\n% end;\n\neoptions.type = 'branch';\neoptions.name = 'Estimation Options';\neoptions.tag = 'eoptions';\neoptions.val = {quality,sep,fwhm,rtm,interp,wrap,weight};\neoptions.help = {[...\n'Various registration options. ',...\n'If in doubt, simply keep the default values.']};\n\n%------------------------------------------------------------------------\n\nwhich.type = 'menu';\nwhich.name = 'Resliced images';\nwhich.tag = 'which';\nwhich.labels = {' All Images (1..n)','Images 2..n',...\n ' All Images + Mean Image',' Mean Image Only'};\nwhich.values = {[2 0],[1 0],[2 1],[0 1]};\nwhich.val = {[2 1]};\nwhich.help = {...\n['All Images (1..n) : ',...\n' This reslices all the images - including the first image selected ',...\n' - which will remain in its original position.'],...\n'',...\n['Images 2..n : ',...\n' Reslices images 2..n only. Useful for if you wish to reslice ',...\n' (for example) a PET image to fit a structural MRI, without ',...\n' creating a second identical MRI volume.'],...\n'',...\n['All Images + Mean Image : ',...\n' In addition to reslicing the images, it also creates a mean of the ',...\n' resliced image.'],...\n'',...\n['Mean Image Only : ',...\n' Creates the mean resliced image only.']};\n\n%------------------------------------------------------------------------\n \ninterp.type = 'menu';\ninterp.name = 'Interpolation';\ninterp.tag = 'interp';\ninterp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-Spline',...\n'3rd Degree B-Spline','4th Degree B-Spline','5th Degree B-Spline',...\n'6th Degree B-Spline','7th Degree B-Spline','Fourier Interpolation'};\ninterp.values = {0,1,2,3,4,5,6,7,Inf};\ninterp.def = 'realign.write.interp';\ninterp.help = {...\n['The method by which the images are sampled when being written in a ',...\n'different space.',...\n'Nearest Neighbour is fastest, but not recommended for image realignment. ',...\n'Bilinear Interpolation is probably OK for PET, but not so suitable for fMRI because ',...\n'higher degree interpolation generally gives better results/* \\cite{thevenaz00a,unser93a,unser93b}*/. ',...\n'Although higher degree methods provide better interpolation, but they are slower ',...\n'because they use more neighbouring voxels. ',...\n'Fourier Interpolation/* \\cite{eddy96,cox99}*/ is another option, but note that it ',...\n'is only implemented for purely rigid body transformations. Voxel sizes must all be ',...\n'identical and isotropic.']};\n \n%------------------------------------------------------------------------\n \nwrap.type = 'menu';\nwrap.name = 'Wrapping';\nwrap.tag = 'wrap';\nwrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z',...\n'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'};\nwrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]};\nwrap.def = 'realign.write.wrap';\nwrap.help = {...\n['This indicates which directions in the volumes the values should wrap around in. ',...\n'For example, in MRI scans, the images wrap around in the phase encode direction, ',...\n'so (e.g.) the subject''s nose may poke into the back of the subject''s head. ',...\n'These are typically:'],...\n[' No wrapping - for PET or images that have already ',...\n' been spatially transformed.'],...\n[' Wrap in Y - for (un-resliced) MRI where phase encoding ',...\n' is in the Y direction (voxel space).']};\n \n%------------------------------------------------------------------------\n \nmask.type = 'menu';\nmask.name = 'Masking';\nmask.tag = 'mask';\nmask.labels = {'Mask images','Dont mask images'};\nmask.values = {1,0};\nmask.def = 'realign.write.mask';\nmask.help = {[...\n'Because of subject motion, different images are likely to have different ',...\n'patterns of zeros from where it was not possible to sample data. ',...\n'With masking enabled, the program searches through the whole time series ',...\n'looking for voxels which need to be sampled from outside the original ',...\n'images. Where this occurs, that voxel is set to zero for the whole set ',...\n'of images (unless the image format can represent NaN, in which case ',...\n'NaNs are used where possible).']};\n \n%------------------------------------------------------------------------\n \nroptions.type = 'branch';\nroptions.name = 'Reslice Options';\nroptions.tag = 'roptions';\nroptions.val = {which,interp,wrap,mask};\nroptions.help = {'Various reslicing options. If in doubt, simply keep the default values.'};\n\n%------------------------------------------------------------------------\n\nscans.type = 'files';\nscans.name = 'Session';\nscans.tag = 'data';\nscans.num = [1 Inf];\nscans.filter = 'image';\nscans.help = {[...\n'Select scans for this session. ',...\n'In the coregistration step, the sessions are first realigned to ',...\n'each other, by aligning the first scan from each session to the ',...\n'first scan of the first session. Then the images within each session ',...\n'are aligned to the first image of the session. ',...\n'The parameter estimation is performed this way because it is assumed ',...\n'(rightly or not) that there may be systematic differences ',...\n'in the images between sessions.']};\n\n%------------------------------------------------------------------------\n\ndata.type = 'repeat';\ndata.name = 'Data';\n% data.tag = 'data';\ndata.values = {scans};\ndata.num = [1 Inf];\ndata.help = {[...\n'Add new sessions for this subject. ',...\n'In the coregistration step, the sessions are first realigned to ',...\n'each other, by aligning the first scan from each session to the ',...\n'first scan of the first session. Then the images within each session ',...\n'are aligned to the first image of the session. ',...\n'The parameter estimation is performed this way because it is assumed ',...\n'(rightly or not) that there may be systematic differences ',...\n'in the images between sessions.']};\n\n%------------------------------------------------------------------------\n\nest.type = 'branch';\nest.name = 'Realign: Estimate';\nest.tag = 'estimate';\nest.val = {data,eoptions};\nest.prog = @estimate;\nest.vfiles = @vfiles_estimate;\n\np1 = [...\n'This routine realigns a time-series of images acquired from the same ',...\n'subject using a least squares approach and a 6 parameter (rigid body) ',...\n'spatial transformation/* \\cite{friston95a}*/. The first image in the list specified by the ',...\n'user is used as a reference to which all subsequent scans are realigned. ',...\n'The reference scan does not have to the the first chronologically and ',...\n'it may be wise to chose a \"representative scan\" in this role.'];\n\np2 = [...\n'The aim is primarily to remove movement artefact in fMRI and PET ',...\n'time-series (or more generally longitudinal studies). ',...\n'The headers are modified for each of the input images, such that. ',...\n'they reflect the relative orientations of the data. ',...\n'The details of the transformation are displayed in the results window ',...\n'as plots of translation and rotation. ',...\n'A set of realignment parameters are saved for each session, named ',...\n'rp_*.txt. These can be modelled as confounds within the general linear model/* \\cite{friston95a}*/.'];\n\nest.help = {p1,'',p2};\n\n%------------------------------------------------------------------------\n\nscans.type = 'files';\nscans.name = 'Images';\nscans.tag = 'data';\nscans.num = [1 Inf];\nscans.filter = 'image';\nscans.help = {'Select scans to reslice to match the first.'};\n\n%------------------------------------------------------------------------\n\nwrite.type = 'branch';\nwrite.name = 'Realign: Reslice';\nwrite.tag = 'write';\nwrite.val = {scans,roptions};\nwrite.help = {[...\n'This function reslices a series of registered images such that they ',...\n'match the first image selected voxel-for-voxel. The resliced images ',...\n'are named the same as the originals, except that they are prefixed ',...\n'by ''r''.']};\nwrite.prog = @reslice;\nwrite.vfiles = @vfiles_reslice;\n%------------------------------------------------------------------------\n\nestwrit.type = 'branch';\nestwrit.name = 'Realign: Estimate & Reslice';\nestwrit.tag = 'estwrite';\nestwrit.val = {data,eoptions,roptions};\np1 = [...\n'This routine realigns a time-series of images acquired from the same ',...\n'subject using a least squares approach and a 6 parameter (rigid body)',...\n'spatial transformation/* \\cite{friston95a}*/. The first image in the list specified by the ',...\n'user is used as a reference to which all subsequent scans are realigned. ',...\n'The reference scan does not have to the the first chronologically and ',...\n'it may be wise to chose a \"representative scan\" in this role.'];\n\np2 = [...\n'The aim is primarily to remove movement artefact in fMRI and PET ',...\n'time-series (or more generally longitudinal studies) /* \\cite{ashburner97bir}*/. ',...\n'The headers are modified for each of the input images, such that. ',...\n'they reflect the relative orientations of the data. ',...\n'The details of the transformation are displayed in the results window ',...\n'as plots of translation and rotation. ',...\n'A set of realignment parameters are saved for each session, named ',...\n'rp_*.txt. After realignment, the images are resliced ',...\n'such that they match the first image selected voxel-for-voxel. ',...\n'The resliced images are named the same as the originals, except that ',...\n'they are prefixed by ''r''.'];\n\nestwrit.help = {p1,'',p2};\nestwrit.prog = @estwrite_fun;\nestwrit.vfiles = @vfiles_estwrit;\n\n%------------------------------------------------------------------------\n\nopts.type = 'repeat';\nopts.name = 'Realign';\nopts.tag = 'realign';\nopts.values = {est,write,estwrit};\nopts.num = [1 Inf];\nopts.modality = {'PET','FMRI','VBM'};\nopts.help = {...\n'Within-subject registration of image time series.'};\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\n\nreturn;\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction estimate(varargin)\njob = varargin{1};\nP = {};\nfor i=1:length(job.data),\n\tP{i} = strvcat(job.data{i});\nend;\nflags.quality = job.eoptions.quality;\nflags.fwhm = job.eoptions.fwhm;\nflags.sep = job.eoptions.sep;\nflags.rtm = job.eoptions.rtm;\nflags.PW = strvcat(job.eoptions.weight);\nflags.interp = job.eoptions.interp;\nflags.wrap = job.eoptions.wrap;\nspm_realign(P,flags);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction reslice(varargin)\njob = varargin{1};\nP = strvcat(job.data);\nflags.mask = job.roptions.mask;\nflags.mean = job.roptions.which(2);\nflags.interp = job.roptions.interp;\nflags.which = job.roptions.which(1);\nflags.wrap = job.roptions.wrap;\nspm_reslice(P,flags);\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction estwrite_fun(varargin)\njob = varargin{1};\nP = {};\nfor i=1:length(job.data),\n P{i} = strvcat(job.data{i});\nend;\nflags.quality = job.eoptions.quality;\nflags.fwhm = job.eoptions.fwhm;\nflags.sep = job.eoptions.sep;\nflags.rtm = job.eoptions.rtm;\nflags.PW = strvcat(job.eoptions.weight);\nflags.interp = job.eoptions.interp;\nflags.wrap = job.eoptions.wrap;\nspm_realign(P,flags);\n\nP = strvcat(P);\nflags.mask = job.roptions.mask;\nflags.mean = job.roptions.which(2);\nflags.interp = job.roptions.interp;\nflags.which = job.roptions.which(1);\nflags.wrap = job.roptions.wrap;\nspm_reslice(P,flags);\nreturn;\n\n%------------------------------------------------------------------------\n \n%------------------------------------------------------------------------\nfunction vf = vfiles_reslice(job)\nP = job.data;\nif numel(P)>0 && iscell(P{1}),\n P = cat(1,P{:});\nend;\n\nswitch job.roptions.which(1),\ncase 0,\n vf = {};\ncase 1,\n vf = cell(numel(P)-1,1);\n for i=1:length(vf),\n [pth,nam,ext,num] = spm_fileparts(P{i+1});\n vf{i} = fullfile(pth,['r', nam, ext, num]);\n end;\notherwise,\n vf = cell(numel(P),1);\n for i=1:length(vf),\n [pth,nam,ext,num] = spm_fileparts(P{i});\n vf{i} = fullfile(pth,['r', nam, ext, num]);\n end;\nend;\nif job.roptions.which(2),\n [pth,nam,ext,num] = spm_fileparts(P{1});\n vf = {vf{:}, fullfile(pth,['mean', nam, ext, num])};\nend;\n\n%------------------------------------------------------------------------\n \n%------------------------------------------------------------------------\nfunction vf = vfiles_estimate(job)\nP = job.data;\nvf = {};\nif numel(P) > 0\n if ~iscell(P{1})\n\tP = {P};\n end;\n for k = 1:numel(P)\n\t[pth,nam,ext,num] = spm_fileparts(P{k}{1});\n\tvf{k} = fullfile(pth, sprintf('rp_%s.txt', nam));\n end;\nend;\n\n%------------------------------------------------------------------------\n \n%------------------------------------------------------------------------\nfunction vf = vfiles_estwrit(job)\nvf1 = vfiles_estimate(job);\nvf2 = vfiles_reslice(job);\nvf = {vf1{:}, vf2{:}};\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_imag_api.m", "ext": ".m", "path": "spm5-master/spm_eeg_inv_imag_api.m", "size": 15750, "source_encoding": "utf_8", "md5": "8085f6df4d7d941d816f7d6411ecbbdc", "text": "function varargout = spm_eeg_inv_imag_api(varargin)\n% SPM_EEG_INV_IMAG_API M-file for spm_eeg_inv_imag_api.fig\n% FIG = SPM_EEG_INV_IMAG_API launch spm_eeg_inv_imag_api GUI.\n% SPM_EEG_INV_IMAG_API('callback_name', ...) invoke the named callback.\n\n% Last Modified by GUIDE v2.5 09-Jan-2008 16:12:40\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Jeremie Mattout\n% $Id: spm_eeg_inv_imag_api.m 1079 2008-01-11 11:05:48Z guillaume $\n\n\nspm_defaults\nspm('Clear')\n\n% Launch API\n%==========================================================================\nif nargin < 2 \n \n % open figure\n %----------------------------------------------------------------------\n fig = openfig(mfilename,'reuse');\n WS = spm('WinScale');\n Rect = spm('WinSize','Menu','raw').*WS;\n set(fig,'units','pixels');\n Fdim = get(fig,'position');\n set(fig,'position',[Rect(1) Rect(2) Fdim(3) Fdim(4)]);\n handles = guihandles(fig);\n\n % Use system color scheme for figure:\n %----------------------------------------------------------------------\n set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));\n handles.fig = fig;\n guidata(fig,handles);\n \n % intialise with D\n %----------------------------------------------------------------------\n try\n D = spm_eeg_inv_check(varargin{1});\n set(handles.DataFile,'String',D.fname);\n set(handles.Exit,'enable','on')\n cd(D.path);\n handles.D = D;\n Reset(fig, [], handles);\n guidata(fig,handles);\n end\n \n% INVOKE NAMED SUBFUNCTION OR CALLBACK\n%--------------------------------------------------------------------------\nelseif ischar(varargin{1}) \n if nargout\n [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard\n else\n feval(varargin{:}); % FEVAL switchyard\n end\n\nelse\n error(sprintf('Wrong input format\\n'));\nend\n\n% MAIN FUNCTIONS FOR MODEL SEPCIFICATION AND INVERSION\n%==========================================================================\n\n% --- Executes on button press in CreateMeshes.\n%--------------------------------------------------------------------------\nfunction CreateMeshes_Callback(hObject, eventdata, handles)\nhandles.D = spm_eeg_inv_mesh_ui(handles.D);\nset(handles.CreateMeshes,'enable','off')\nset(handles.Reg2tem, 'enable','off')\nReset(hObject, eventdata, handles);\n\n\n% --- Executes on button press in Reg2tem.\n%--------------------------------------------------------------------------\nfunction Reg2tem_Callback(hObject, eventdata, handles)\nstr = 'Mesh size (vertices)';\nhandles.D.inv{handles.D.val}.mesh.Msize = spm_input(str,'+1','3000|4000|5000|7200',[1 2 3 4]);\nhandles.D = spm_eeg_inv_template(handles.D);\nset(handles.CreateMeshes,'enable','off')\nDataReg_Callback(hObject, eventdata, handles);\n\n\n% --- Executes on button press in Data Reg.\n%--------------------------------------------------------------------------\nfunction DataReg_Callback(hObject, eventdata, handles)\nhandles.D = spm_eeg_inv_datareg_ui(handles.D);\nReset(hObject, eventdata, handles);\n\n\n% --- Executes on button press in Forward Model.\n%--------------------------------------------------------------------------\nfunction Forward_Callback(hObject, eventdata, handles)\nhandles.D = spm_eeg_inv_forward_ui(handles.D);\nReset(hObject, eventdata, handles);\n\n\n% --- Executes on button press in Invert.\n%--------------------------------------------------------------------------\nfunction Inverse_Callback(hObject, eventdata, handles)\nif strcmp(handles.D.inv{handles.D.val}.method,'Imaging')\n handles.D = spm_eeg_invert_ui(handles.D);\nelse\n handles.D = spm_eeg_inv_ecd_ui(handles.D);\nend\nReset(hObject, eventdata, handles);\n\n\n% --- Executes on button press in contrast.\n%--------------------------------------------------------------------------\nfunction contrast_Callback(hObject, eventdata, handles)\nhandles.D = spm_eeg_inv_results_ui(handles.D);\nReset(hObject, eventdata, handles);\n\n\n% --- Executes on button press in Image.\n%--------------------------------------------------------------------------\nfunction Image_Callback(hObject, eventdata,handles)\nQstr = 'Please choose';\nTstr = 'Smoothing in mm';\nhandles.D.inv{handles.D.val}.contrast.smooth = str2num(questdlg(Qstr,Tstr,'8','12','16','12'));\nhandles.D.inv{handles.D.val}.contrast.display = 1;\nhandles.D = spm_eeg_inv_Mesh2Voxels(handles.D);\nReset(hObject, eventdata, handles);\n\n\n\n% LOAD AND EXIT\n%==========================================================================\n\n% --- Executes on button press in Load.\n%--------------------------------------------------------------------------\nfunction Load_Callback(hObject, eventdata, handles)\nS = spm_select(1, '.mat', 'Select EEG/MEG mat file');\nD = spm_eeg_ldata(S);\ntry\n D.modality;\ncatch\n D.modality = questdlg('Modality','Please specify','EEG','MEG',1);\nend\n[pth,nam,ext] = fileparts(S);\nD.path = pth;\nD.fname = nam;\nset(handles.DataFile,'String',D.fname);\nset(handles.Exit,'enable','on')\ncd(pth);\nhandles.D = D;\nReset(hObject, eventdata, handles);\n\n\n% --- Executes on button press in Exit.\n%--------------------------------------------------------------------------\nfunction Exit_Callback(hObject, eventdata, handles)\nD = handles.D;\nif spm_matlab_version_chk('7.1') >= 0\n save(fullfile(D.path, D.fname), '-V6', 'D');\nelse\n save(fullfile(D.path, D.fname), 'D');\nend\nvarargout{1} = handles.D;\nassignin('base','D',handles.D)\n\n\n% FUCNTIONS FOR MANAGING DIFFERENT MODELS\n%==========================================================================\n\n% --- Executes on button press in new.\n%--------------------------------------------------------------------------\nfunction new_Callback(hObject, eventdata, handles)\nD = handles.D;\nif ~isfield(D,'inv')\n val = 1;\nelseif ~length(D.inv)\n val = 1;\nelse\n val = length(D.inv) + 1;\n D.inv{val} = D.inv{D.val};\nend\n\n% set D in handles and update analysis specific buttons\n%--------------------------------------------------------------------------\nD.val = val;\nD = set_CommentDate(D);\nhandles.D = D;\nset(handles.CreateMeshes,'enable','on')\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in next.\n%--------------------------------------------------------------------------\nfunction next_Callback(hObject, eventdata, handles)\nif handles.D.val < length(handles.D.inv)\n handles.D.val = handles.D.val + 1;\nend\nReset(hObject, eventdata, handles);\n\n\n% --- Executes on button press in previous.\n%--------------------------------------------------------------------------\nfunction previous_Callback(hObject, eventdata, handles)\nif handles.D.val > 1\n handles.D.val = handles.D.val - 1;\nend\nReset(hObject, eventdata, handles);\n\n\n% --- Executes on button press in clear.\n%--------------------------------------------------------------------------\nfunction clear_Callback(hObject, eventdata, handles)\ntry\n inv.comment = handles.D.inv{handles.D.val}.comment;\n inv.date = handles.D.inv{handles.D.val}.date;\n handles.D.inv{handles.D.val} = inv;\nend\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in delete.\n%--------------------------------------------------------------------------\nfunction delete_Callback(hObject, eventdata, handles)\nif length(handles.D.inv)\n try\n str = handles.D.inv{handles.D.val}.comment;\n warndlg({'you are about to delete:',str{1}});\n uiwait\n end\n handles.D.inv(handles.D.val) = [];\n handles.D.val = handles.D.val - 1;\nend\nReset(hObject, eventdata, handles);\n\n\n\n% Auxillary functions\n%==========================================================================\nfunction Reset(hObject, eventdata, handles)\n\n% Check to see if a new analysis is required\n%--------------------------------------------------------------------------\ntry\n set(handles.DataFile,'String',handles.D.fname);\nend\nif ~isfield(handles.D,'inv')\n new_Callback(hObject, eventdata, handles)\n return\nend\nif ~length(handles.D.inv)\n new_Callback(hObject, eventdata, handles)\n return\nend\ntry\n val = handles.D.val;\n handles.D.inv{val};\ncatch\n handles.D.val = 1;\n val = 1;\nend\n\n% analysis specification buttons\n%--------------------------------------------------------------------------\nQ = handles.D.inv{val};\nset(handles.new, 'enable','on','value',0)\nset(handles.clear, 'enable','on','value',0)\nset(handles.delete, 'enable','on','value',0)\nset(handles.next, 'value',0)\nset(handles.previous, 'value',0)\n\nif val < length(handles.D.inv)\n set(handles.next, 'enable','on')\nend\nif val > 1\n set(handles.previous,'enable','on')\nend\nif val == 1\n set(handles.previous,'enable','off')\nend\nif val == length(handles.D.inv)\n set(handles.next, 'enable','off')\nend\ntry\n str = sprintf('%i: %s',val,Q.comment{1});\ncatch\n try\n str = sprintf('%i: %s',val,Q.comment);\n catch\n str = sprintf('%i',val);\n end\nend\nset(handles.val, 'Value',val,'string',str);\n\n% condition specification\n%--------------------------------------------------------------------------\ntry\n handles.D.con = max(handles.D.con,1);\n if handles.D.con > length(handles.D.inv{val}.inverse.J);\n handles.D.con = 1;\n end\ncatch\n try \n handles.D.con = length(handles.D.inv{val}.inverse.J);\n catch\n handles.D.con = 0;\n end\nend\nif handles.D.con\n str = sprintf('condition %d',handles.D.con);\n set(handles.con,'String',str,'Enable','on','Value',0)\nelse\n set(handles.con,'Enable','off','Value',0)\nend\n\n\n% check anaylsis buttons\n%--------------------------------------------------------------------------\nset(handles.DataReg, 'enable','off')\nset(handles.Forward, 'enable','off')\nset(handles.Inverse, 'enable','off')\nset(handles.contrast,'enable','off')\nset(handles.Image, 'enable','off')\n\nset(handles.CheckReg, 'enable','off','Value',0)\nset(handles.CheckMesh, 'enable','off','Value',0)\nset(handles.CheckForward, 'enable','off','Value',0)\nset(handles.CheckInverse, 'enable','off','Value',0)\nset(handles.CheckContrast,'enable','off','Value',0)\nset(handles.CheckImage, 'enable','off','Value',0)\nset(handles.Movie, 'enable','off','Value',0)\nset(handles.Vis3D, 'enable','off','Value',0)\nset(handles.Image, 'enable','off','Value',0)\n\nif isfield(Q,'mesh')\n set(handles.DataReg, 'enable','on')\n set(handles.CheckMesh,'enable','on')\n if isfield(Q,'datareg')\n set(handles.Forward, 'enable','on')\n set(handles.CheckReg,'enable','on')\n if isfield(Q,'forward')\n set(handles.Inverse, 'enable','on')\n set(handles.CheckForward,'enable','on')\n if isfield(Q,'inverse')\n set(handles.CheckInverse,'enable','on')\n if isfield(Q.inverse,'J')\n set(handles.contrast, 'enable','on')\n set(handles.Movie, 'enable','on')\n set(handles.Vis3D, 'enable','on')\n if isfield(Q,'contrast')\n set(handles.CheckContrast,'enable','on')\n set(handles.Image, 'enable','on')\n if isfield(Q.contrast,'fname')\n set(handles.CheckImage,'enable','on')\n end\n end\n end\n end\n end\n end\nend\ntry\n if strcmp(handles.D.inv{handles.D.val}.method,'Imaging')\n set(handles.CheckInverse,'String','mip');\n set(handles.PST,'Enable','on');\n else\n set(handles.CheckInverse,'String','dip');\n set(handles.PST,'Enable','off');\n end\nend\nset(handles.fig,'Pointer','arrow')\nassignin('base','D',handles.D)\nguidata(hObject,handles);\n\n\n% Set Comment and Date for new inverse analysis\n%--------------------------------------------------------------------------\nfunction S = set_CommentDate(D)\n\nclck = fix(clock);\nif clck(5) < 10\n clck = [num2str(clck(4)) ':0' num2str(clck(5))];\nelse\n clck = [num2str(clck(4)) ':' num2str(clck(5))];\nend\nD.inv{D.val}.date = strvcat(date,clck);\nD.inv{D.val}.comment = inputdlg('Comment/Label for this analysis:');\nS = D;\n\n\n% CHECKS AND DISPLAYS\n%==========================================================================\n\n% --- Executes on button press in CheckMesh.\n%--------------------------------------------------------------------------\nfunction CheckMesh_Callback(hObject, eventdata, handles)\nspm_eeg_inv_checkmeshes(handles.D);\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in CheckReg.\n%--------------------------------------------------------------------------\nfunction CheckReg_Callback(hObject, eventdata, handles)\nspm_eeg_inv_checkdatareg(handles.D);\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in CheckForward.\n%--------------------------------------------------------------------------\nfunction CheckForward_Callback(hObject, eventdata, handles)\nspm_eeg_inv_checkforward(handles.D);\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in CheckInverse.\n%--------------------------------------------------------------------------\nfunction CheckInverse_Callback(hObject, eventdata, handles)\nif strcmp(handles.D.inv{handles.D.val}.method,'Imaging')\n PST = str2num(get(handles.PST,'String'));\n spm_eeg_invert_display(handles.D,PST);\nelse\n resdip = handles.D.inv{handles.D.val}.inverse.resdip;\n sMRI = handles.D.inv{handles.D.val}.mesh.sMRI\n spm_eeg_inv_ecd_DrawDip('Init',resdip,sMRI);\nend\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in Movie.\n%--------------------------------------------------------------------------\nfunction Movie_Callback(hObject, eventdata, handles)\nfigure(spm_figure('GetWin','Graphics'));\nPST(1) = str2num(get(handles.Start,'String'));\nPST(2) = str2num(get(handles.Stop ,'String'));\nspm_eeg_invert_display(handles.D,PST);\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in CheckContrast.\n%--------------------------------------------------------------------------\nfunction CheckContrast_Callback(hObject, eventdata, handles)\nspm_eeg_inv_results_display(handles.D);\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in Vis3D.\n%--------------------------------------------------------------------------\nfunction Vis3D_Callback(hObject, eventdata, handles)\nExit_Callback(hObject, eventdata, handles)\nspm_eeg_inv_visu3D_api(handles.D);\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in CheckImage.\n%--------------------------------------------------------------------------\nfunction CheckImage_Callback(hObject, eventdata, handles)\nspm_eeg_inv_image_display(handles.D)\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in con.\n%--------------------------------------------------------------------------\nfunction con_Callback(hObject, eventdata, handles)\ntry\n handles.D.con = handles.D.con + 1;\n if handles.D.con > length(handles.D.inverse.J);\n handles.D.con = 1\n end\nend\nReset(hObject, eventdata, handles);\n\n% --- Executes on button press in help.\n%--------------------------------------------------------------------------\nfunction help_Callback(hObject, eventdata, handles)\nedit spm_eeg_inv_help\n\n\n% --- Executes on button press in group.\n%--------------------------------------------------------------------------\nfunction group_Callback(hObject, eventdata, handles)\nspm_eeg_inv_group\n\n\n% --- Executes on button press in fusion.\n%--------------------------------------------------------------------------\nfunction fusion_Callback(hObject, eventdata, handles)\nhandles.D = spm_eeg_invert_fuse_ui;\nReset(hObject, eventdata, handles)\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_smoothto8bit.m", "ext": ".m", "path": "spm5-master/spm_smoothto8bit.m", "size": 2376, "source_encoding": "utf_8", "md5": "a51643d7766b47182eafff1948680218", "text": "function VO = spm_smoothto8bit(V,fwhm)\n% 3 dimensional convolution of an image to 8bit data in memory\n% FORMAT VO = spm_smoothto8bit(V,fwhm)\n% V - mapped image to be smoothed\n% fwhm - FWHM of Guassian filter width in mm\n% VO - smoothed volume in a form that can be used by the\n% spm_*_vol.mex* functions.\n%_______________________________________________________________________\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_smoothto8bit.m 946 2007-10-15 16:36:06Z john $\n\n\nif nargin>1 & fwhm>0,\n\tVO = smoothto8bit(V,fwhm);\nelse,\n\tVO = V;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction VO = smoothto8bit(V,fwhm)\n% 3 dimensional convolution of an image to 8bit data in memory\n% FORMAT VO = smoothto8bit(V,fwhm)\n% V - mapped image to be smoothed\n% fwhm - FWHM of Guassian filter width in mm\n% VO - smoothed volume in a form that can be used by the\n% spm_*_vol.mex* functions.\n%_______________________________________________________________________\n\nvx = sqrt(sum(V.mat(1:3,1:3).^2));\ns = (fwhm./vx./sqrt(8*log(2)) + eps).^2;\nr = cell(1,3);\nfor i=1:3,\n\tr{i}.s = ceil(3.5*sqrt(s(i)));\n\tx = -r{i}.s:r{i}.s;\n\tr{i}.k = exp(-0.5 * (x.*x)/s(i))/sqrt(2*pi*s(i));\n\tr{i}.k = r{i}.k/sum(r{i}.k);\nend;\n\nbuff = zeros([V.dim(1:2) r{3}.s*2+1]);\n\nVO = V;\nVO.dt = [spm_type('uint8') spm_platform('bigend')];\nV0.dat = uint8(0);\nV0.dat(VO.dim(1:3)) = uint8(0);\nVO.pinfo = [];\n\nfor i=1:V.dim(3)+r{3}.s,\n\tif i<=V.dim(3),\n\t\timg = spm_slice_vol(V,spm_matrix([0 0 i]),V.dim(1:2),0);\n\t\tmsk = find(~isfinite(img));\n\t\timg(msk) = 0;\n\t\tbuff(:,:,rem(i-1,r{3}.s*2+1)+1) = ...\n\t\t\tconv2(conv2(img,r{1}.k,'same'),r{2}.k','same');\n\telse,\n\t\tbuff(:,:,rem(i-1,r{3}.s*2+1)+1) = 0;\n\tend;\n\n\tif i>r{3}.s,\n\t\tkern = zeros(size(r{3}.k'));\n\t\tkern(rem((i:(i+r{3}.s*2))',r{3}.s*2+1)+1) = r{3}.k';\n\t\timg = reshape(buff,[prod(V.dim(1:2)) r{3}.s*2+1])*kern;\n\t\timg = reshape(img,V.dim(1:2));\n\t\tii = i-r{3}.s;\n\t\tmx = max(img(:));\n\t\tmn = min(img(:));\n\t\tif mx==mn, mx=mn+eps; end;\n\t\tVO.pinfo(1:2,ii) = [(mx-mn)/255 mn]';\n\t\tVO.dat(:,:,ii) = uint8(round((img-mn)*(255/(mx-mn))));\n\tend;\nend;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_fmri_design.m", "ext": ".m", "path": "spm5-master/spm_config_fmri_design.m", "size": 44802, "source_encoding": "utf_8", "md5": "476fe235b583f0a77b9a767e526929e3", "text": "function conf = spm_config_fmri_design\n% Configuration file for specification of fMRI model\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Darren Gitelman and Will Penny\n% $Id: spm_config_fmri_design.m 1016 2007-12-03 12:51:33Z volkmar $\n\n\n% Define inline types.\n%-----------------------------------------------------------------------\n\nentry = inline(['struct(''type'',''entry'',''name'',name,'...\n '''tag'',tag,''strtype'',strtype,''num'',num,''help'',hlp)'],...\n 'name','tag','strtype','num','hlp');\n\nfiles = inline(['struct(''type'',''files'',''name'',name,'...\n '''tag'',tag,''filter'',fltr,''num'',num,''help'',hlp)'],...\n 'name','tag','fltr','num','hlp');\n\nmnu = inline(['struct(''type'',''menu'',''name'',name,'...\n '''tag'',tag,''labels'',{labels},''values'',{values},''help'',hlp)'],...\n 'name','tag','labels','values','hlp');\n\nbranch = inline(['struct(''type'',''branch'',''name'',name,'...\n '''tag'',tag,''val'',{val},''help'',hlp)'],...\n 'name','tag','val','hlp');\n\nrepeat = inline(['struct(''type'',''repeat'',''name'',name,'...\n '''tag'',tag,''values'',{values},''help'',hlp)'],...\n 'name','tag','values','hlp');\n\nchoice = inline(['struct(''type'',''choice'',''name'',name,'...\n '''tag'',tag,''values'',{values},''help'',hlp)'],...\n 'name','tag','values','hlp');\n\n%-----------------------------------------------------------------------\n\nsp_text = [' ',...\n ' '];\n%-----------------------------------------------------------------------\n\nonset = entry('Onsets','onset','e',[Inf 1],'Vector of onsets');\np1 = ['Specify a vector of onset times for this condition type. '];\nonset.help = {p1};\n\n%-------------------------------------------------------------------------\n\nduration = entry('Durations','duration','e',[Inf 1],'Duration/s');\nduration.help = [...\n 'Specify the event durations. Epoch and event-related ',...\n 'responses are modeled in exactly the same way but by specifying their ',...\n 'different durations. Events are ',...\n 'specified with a duration of 0. If you enter a single number for the ',...\n 'durations it will be assumed that all trials conform to this duration. ',...\n 'If you have multiple different durations, then the number must match the ',...\n 'number of onset times.'];\n\n%-------------------------------------------------------------------------\n\ntime_mod = mnu('Time Modulation','tmod',...\n {'No Time Modulation','1st order Time Modulation',...\n '2nd order Time Modulation','3rd order Time Modulation',...\n '4th order Time Modulation','5th order Time Modulation',...\n '6th order Time Modulation'},...\n {0,1,2,3,4,5,6},'');\ntime_mod.val = {0};\np1 = [...\n 'This option allows for the characterisation of linear or nonlinear ',...\n 'time effects. ',...\n 'For example, 1st order modulation ',...\n 'would model the stick functions and a linear change of the stick function ',...\n 'heights over time. Higher order modulation will introduce further columns that ',...\n 'contain the stick functions scaled by time squared, time cubed etc.'];\np2 = [...\n 'Interactions or response modulations can enter at two levels. Firstly ',...\n 'the stick function itself can be modulated by some parametric variate ',...\n '(this can be time or some trial-specific variate like reaction time) ',...\n 'modeling the interaction between the trial and the variate or, secondly ',...\n 'interactions among the trials themselves can be modeled using a Volterra ',...\n 'series formulation that accommodates interactions over time (and therefore ',...\n 'within and between trial types).'];\ntime_mod.help = {p1,'',p2};\n\n%-------------------------------------------------------------------------\n%ply = mnu('Polynomial Expansion','poly',...\n% {'None','1st order','2nd order','3rd order','4th order','5th order','6th order'},...\n% {0,1,2,3,4,5,6},'Polynomial Order');\n%ply.val = {0};\n%-------------------------------------------------------------------------\n\nname = entry('Name','name','s', [1 Inf],'Name of parameter');\nname.val = {'Param'};\nname.help = {'Enter a name for this parameter.'};\n\n%-------------------------------------------------------------------------\n\nparam = entry('Values','param','e',[Inf 1],'Parameter vector');\nparam.help = {'Enter a vector of values, one for each occurence of the event.'};\n\n%-------------------------------------------------------------------------\n\nply = mnu('Polynomial Expansion','poly',...\n {'1st order','2nd order','3rd order','4th order','5th order','6th order'},...\n {1,2,3,4,5,6},'Polynomial Order');\nply.val = {1};\nply.help = {[...\n 'For example, 1st order modulation ',...\n 'would model the stick functions and a linear change of the stick function ',...\n 'heights over different values of the parameter. Higher order modulation will ',...\n 'introduce further columns that ',...\n 'contain the stick functions scaled by parameter squared, cubed etc.']};\n\n%-------------------------------------------------------------------------\n\npother = branch('Parameter','pmod',{name,param,ply},'Custom parameter');\np1 = [...\n 'Model interractions with user specified parameters. ',...\n 'This allows nonlinear effects relating to some other measure ',...\n 'to be modelled in the design matrix.'];\np2 = [...\n 'Interactions or response modulations can enter at two levels. Firstly ',...\n 'the stick function itself can be modulated by some parametric variate ',...\n '(this can be time or some trial-specific variate like reaction time) ',...\n 'modeling the interaction between the trial and the variate or, secondly ',...\n 'interactions among the trials themselves can be modeled using a Volterra ',...\n 'series formulation that accommodates interactions over time (and therefore ',...\n 'within and between trial types).'];\npother.help = {p1,'',p2};\n\n%-------------------------------------------------------------------------\npmod = repeat('Parametric Modulations','pmod',{pother},'');\npmod.help = {[...\n 'The stick function itself can be modulated by some parametric variate ',...\n '(this can be time or some trial-specific variate like reaction time) ',...\n 'modeling the interaction between the trial and the variate. ',...\n 'The events can be modulated by zero or more parameters.']};\n\n%-------------------------------------------------------------------------\n\nname = entry('Name','name','s',[1 Inf],'Condition Name');\nname.val = {'Trial'};\n\n%-------------------------------------------------------------------------\n\ncond = branch('Condition','cond',{name,onset,duration,time_mod,pmod},...\n 'Condition');\ncond.check = @cond_check;\ncond.help = {[...\n 'An array of input functions is contructed, ',...\n 'specifying occurrence events or epochs (or both). ',...\n 'These are convolved with a basis set at a later stage to give ',...\n 'regressors that enter into the design matrix. Interactions of evoked ',...\n 'responses with some parameter (time or a specified variate) enter at ',...\n 'this stage as additional columns in the design matrix with each trial multiplied ',...\n 'by the [expansion of the] trial-specific parameter. ',...\n 'The 0th order expansion is simply the main effect in the first column.']};\n\n%-------------------------------------------------------------------------\n\nconditions = repeat('Conditions','condrpt',{cond},'Conditions');\nconditions.help = {[...\n 'You are allowed to combine both event- and epoch-related ',...\n 'responses in the same model and/or regressor. Any number ',...\n 'of condition (event or epoch) types can be specified. Epoch and event-related ',...\n 'responses are modeled in exactly the same way by specifying their ',...\n 'onsets [in terms of onset times] and their durations. Events are ',...\n 'specified with a duration of 0. If you enter a single number for the ',...\n 'durations it will be assumed that all trials conform to this duration.',...\n 'For factorial designs, one can later associate these experimental conditions ',...\n 'with the appropriate levels of experimental factors. ';]};\n\n%-------------------------------------------------------------------------\n\nmulti = files('Multiple conditions','multi','\\.mat$',[0 1],'');\np1=['Select the *.mat file containing details of your multiple experimental conditions. '];\np2=['If you have multiple conditions then entering the details a condition ',...\n 'at a time is very inefficient. This option can be used to load all the ',...\n 'required information in one go. You will first need to create a *.mat file ',...\n 'containing the relevant information. '];\np3=['This *.mat file must include the following cell arrays (each 1 x n): ',...\n 'names, onsets and durations. eg. names=cell(1,5), onsets=cell(1,5), ',...\n 'durations=cell(1,5), then names{2}=''SSent-DSpeak'', onsets{2}=[3 5 19 222], ',...\n 'durations{2}=[0 0 0 0], contain the required details of the second condition. ',...\n 'These cell arrays may be made available by your stimulus delivery program, ',...\n 'eg. COGENT. The duration vectors can contain a single entry if the durations ',...\n 'are identical for all events.'];\np4=['Time and Parametric effects can also be included. For time modulation ',...\n 'include a cell array (1 x n) called tmod. It should have a have a single ',...\n 'number in each cell. Unused cells may contain either a 0 or be left empty. The number ',...\n 'specifies the order of time modulation from 0 = No Time Modulation to ',...\n '6 = 6th Order Time Modulation. eg. tmod{3} = 1, modulates the 3rd condition ',...\n 'by a linear time effect.'];\np5=['For parametric modulation include a structure array, which is up to 1 x n in size, ',...\n 'called pmod. n must be less than or equal to the number of cells in the ',...\n 'names/onsets/durations cell arrays. The structure array pmod must have the fields: ',...\n 'name, param and poly. Each of these fields is in turn a cell array to allow the ',...\n 'inclusion of one or more parametric effects per column of the design. The field ',...\n 'name must be a cell array containing strings. The field param is a cell array ',...\n 'containing a vector of parameters. Remember each parameter must be the same length as its ',...\n 'corresponding onsets vector. The field poly is a cell array (for consistency) ',...\n 'with each cell containing a single number specifying the order of the polynomial ',...\n 'expansion from 1 to 6.'];\np6=['Note that each condition is assigned its corresponding ',...\n 'entry in the structure array (condition 1 parametric modulators are in pmod(1), ',...\n 'condition 2 parametric modulators are in pmod(2), etc. Within a condition ',...\n 'multiple parametric modulators are accessed via each fields cell arrays. ',...\n 'So for condition 1, parametric modulator 1 would be defined in ',...\n 'pmod(1).name{1}, pmod(1).param{1}, and pmod(1).poly{1}. A second parametric ',...\n 'modulator for condition 1 would be defined as pmod(1).name{2}, pmod(1).param{2} ',...\n 'and pmod(1).poly{2}. If there was also a parametric modulator for condition 2, ',...\n 'then remember the first modulator for that condition is in cell array 1: ',...\n 'pmod(2).name{1}, pmod(2).param{1}, and pmod(2).poly{1}. If some, but not ',...\n 'all conditions are parametrically modulated, then the non-modulated indices ',...\n 'in the pmod structure can be left blank. For example, if conditions 1 and 3 but ',...\n 'not condition 2 are modulated, then specify pmod(1) and pmod(3). ',...\n 'Similarly, if conditions 1 and 2 are modulated but there are 3 conditions ',...\n 'overall, it is only necessary for pmod to be a 1 x 2 structure array.'];\np7=['EXAMPLE:'];\np8=['Make an empty pmod structure: '];\np9=[' pmod = struct(''name'',{''''},''param'',{},''poly'',{});'];\np10=['Specify one parametric regressor for the first condition: '];\np11=[' pmod(1).name{1} = ''regressor1'';'];\np12=[' pmod(1).param{1} = [1 2 4 5 6];'];\np13=[' pmod(1).poly{1} = 1;'];\np14=['Specify 2 parametric regressors for the second condition: '];\np15=[' pmod(2).name{1} = ''regressor2-1'';'];\np16=[' pmod(2).param{1} = [1 3 5 7]; '];\np17=[' pmod(2).poly{1} = 1;'];\np18=[' pmod(2).name{2} = ''regressor2-2'';'];\np19=[' pmod(2).param{2} = [2 4 6 8 10];'];\np20=[' pmod(2).poly{2} = 1;'];\np21=['The parametric modulator should be mean corrected if appropriate. Unused ',...\n 'structure entries should have all fields left empty.'];\n \nmulti.help = {p1,sp_text,p2,sp_text,p3,sp_text,p4,sp_text,p5,sp_text,p6,...\n sp_text,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,sp_text,p21};\nmulti.val={''};\n\n\n%-------------------------------------------------------------------------\n\nname = entry('Name','name','s',[1 Inf],'');\nname.val = {'Regressor'};\np1=['Enter name of regressor eg. First movement parameter'];\nname.help={p1};\n\n%-------------------------------------------------------------------------\n\nval = entry('Value','val','e',[Inf 1],'');\nval.help={['Enter the vector of regressor values']};\n\n%-------------------------------------------------------------------------\n\nregress = branch('Regressor','regress',{name,val},'regressor');\nregressors = repeat('Regressors','regress',{regress},'Regressors');\nregressors.help = {[...\n 'Regressors are additional columns included in the design matrix, ',...\n 'which may model effects that would not be convolved with the ',...\n 'haemodynamic response. One such example would be the estimated movement ',...\n 'parameters, which may confound the data.']};\n\n%-------------------------------------------------------------------------\n\nmulti_reg = files('Multiple regressors','multi_reg','.*',[0 1],'');\np1=['Select the *.mat/*.txt file containing details of your multiple regressors. '];\np2=['If you have multiple regressors eg. realignment parameters, then entering the ',...\n 'details a regressor at a time is very inefficient. ',...\n 'This option can be used to load all the ',...\n 'required information in one go. '];\np3=['You will first need to create a *.mat file ',...\n 'containing a matrix R or a *.txt file containing the regressors. ',...\n 'Each column of R will contain a different regressor. ',...\n 'When SPM creates the design matrix the regressors will be named R1, R2, R3, ..etc.'];\nmulti_reg.help = {p1,sp_text,p2,sp_text,p3};\nmulti_reg.val={''};\n\n%-------------------------------------------------------------------------\n\nnscan = entry('# Scans','nscan','e',[1 1],'');\nnscan.help = {['Specify the number of scans for this session.'...\n 'The actual scans must be specified in a separate '...\n 'batch job ''Specify Data''.']};\n\n%-------------------------------------------------------------------------\n\nhpf = entry('High-pass filter','hpf','e',[1 1],'');\nhpf.val = {128};\nhpf.help = {[...\n 'The default high-pass filter cutoff is 128 seconds.',...\n 'Slow signal drifts with a period longer than this will be removed. ',...\n 'Use ''explore design'' ',...\n 'to ensure this cut-off is not removing too much experimental variance. ',...\n 'High-pass filtering is implemented using a residual forming matrix (i.e. ',...\n 'it is not a convolution) and is simply to a way to remove confounds ',...\n 'without estimating their parameters explicitly. The constant term ',...\n 'is also incorporated into this filter matrix.']};\n\n%-------------------------------------------------------------------------\n\nsess = branch('Subject/Session','sess',{nscan,conditions,multi,regressors,multi_reg,hpf},'Session');\nsess.check = @sess_check;\np1 = [...\n 'The design matrix for fMRI data consists of one or more separable, ',...\n 'session-specific partitions. These partitions are usually either one per ',...\n 'subject, or one per fMRI scanning session for that subject.'];\nsess.help = {p1};\n\n%-------------------------------------------------------------------------\n\nblock = repeat('Data & Design','blocks',{sess},'');\nblock.num = [1 Inf];\np1 = [...\n 'The design matrix defines the experimental design and the nature of ',...\n 'hypothesis testing to be implemented. The design matrix has one row ',...\n 'for each scan and one column for each effect or explanatory variable. ',...\n '(e.g. regressor or stimulus function). '];\np2 = [...\n 'This allows you to build design matrices with separable ',...\n 'session-specific partitions. Each partition may be the same (in which ',...\n 'case it is only necessary to specify it once) or different. Responses ',...\n 'can be either event- or epoch related, where the latter model involves prolonged ',...\n 'and possibly time-varying responses to state-related changes in ',...\n 'experimental conditions. Event-related response are modelled in terms ',...\n 'of responses to instantaneous events. Mathematically they are both ',...\n 'modelled by convolving a series of delta (stick) or box-car functions, ',...\n 'encoding the input or stimulus function. with a set of hemodynamic ',...\n 'basis functions.'];\nblock.help = {p1,'',p2};\n\n% Specification of factorial designs\n\nfname.type = 'entry';\nfname.name = 'Name';\nfname.tag = 'name';\nfname.strtype = 's';\nfname.num = [1 1];\nfname.help = {'Name of factor, eg. ''Repetition'' '};\n\nlevels = entry('Levels','levels','e',[Inf 1],'');\np1=['Enter number of levels for this factor, eg. 2'];\nlevels.help ={p1};\n\nfactor.type = 'branch';\nfactor.name = 'Factor';\nfactor.tag = 'fact';\nfactor.val = {fname,levels};\nfactor.help = {'Add a new factor to your experimental design'};\n\nfactors.type = 'repeat';\nfactors.name = 'Factorial design';\nfactors.tag = 'factors';\nfactors.values = {factor};\np1 = ['If you have a factorial design then SPM can automatically generate ',...\n 'the contrasts necessary to test for the main effects and interactions. '];\np2 = ['This includes the F-contrasts necessary to test for these effects at ',...\n 'the within-subject level (first level) and the simple contrasts necessary ',...\n 'to generate the contrast images for a between-subject (second-level) ',...\n 'analysis.'];\np3 = ['To use this option, create as many factors as you need and provide a name ',...\n 'and number of levels for each. ',...\n 'SPM assumes that the condition numbers of the first factor change slowest, ',...\n 'the second factor next slowest etc. It is best to write down the contingency ',...\n 'table for your design to ensure this condition is met. This table relates the ',...\n 'levels of each factor to the ',...\n 'conditions. '];\np4= ['For example, if you have 2-by-3 design ',...\n ' your contingency table has two rows and three columns where the ',...\n 'the first factor spans the rows, and the second factor the columns. ',...\n 'The numbers of the conditions are 1,2,3 for the first row and 4,5,6 ',...\n 'for the second. '];\n\nfactors.help ={p1,sp_text,p2,sp_text,p3,sp_text,p4};\n\n\n\n%-------------------------------------------------------------------------\n\nglob = mnu('Global normalisation','global',...\n {'Scaling','None'},{'Scaling','None'},{'Global intensity normalisation'});\nglob.val={'None'};\n\n%-------------------------------------------------------------------------\n\nderivs = mnu('Model derivatives','derivs',...\n {'No derivatives', 'Time derivatives', 'Time and Dispersion derivatives'},...\n {[0 0],[1 0],[1 1]},'');\nderivs.val = {[0 0]};\np1=['Model HRF Derivatives. The canonical HRF combined with time and ',...\n 'dispersion derivatives comprise an ''informed'' basis set, as ',...\n 'the shape of the canonical response conforms to the hemodynamic ',...\n 'response that is commonly observed. The incorporation of the derivate ',...\n 'terms allow for variations in subject-to-subject and voxel-to-voxel ',...\n 'responses. The time derivative allows the peak response to vary by plus or ',...\n 'minus a second and the dispersion derivative allows the width of the response ',...\n 'to vary. The informed basis set requires an SPM{F} for inference. T-contrasts ',...\n 'over just the canonical are perfectly valid but assume constant delay/dispersion. ',...\n 'The informed basis set compares ',...\n 'favourably with eg. FIR bases on many data sets. '];\nderivs.help = {p1};\n%-------------------------------------------------------------------------\n\nhrf = branch('Canonical HRF','hrf',{derivs},'Canonical Hemodynamic Response Function');\nhrf.help = {[...\n 'Canonical Hemodynamic Response Function. This is the default option. ',...\n 'Contrasts of these effects have a physical interpretation ',...\n 'and represent a parsimonious way of characterising event-related ',...\n 'responses. This option is also ',...\n 'useful if you wish to ',...\n 'look separately at activations and deactivations (this is implemented using a ',...\n 't-contrast with a +1 or -1 entry over the canonical regressor). ']};\n\n%-------------------------------------------------------------------------\n\nlen = entry('Window length','length','e',[1 1],'');\nlen.help={'Post-stimulus window length (in seconds)'};\norder = entry('Order','order','e',[1 1],'');\norder.help={'Number of basis functions'};\no1 = branch('Fourier Set','fourier',{len,order},'');\no1.help = {'Fourier basis functions. This option requires an SPM{F} for inference.'};\no2 = branch('Fourier Set (Hanning)','fourier_han',{len,order},'');\no2.help = {'Fourier basis functions with Hanning Window - requires SPM{F} for inference.'};\no3 = branch('Gamma Functions','gamma',{len,order},'');\no3.help = {'Gamma basis functions - requires SPM{F} for inference.'};\no4 = branch('Finite Impulse Response','fir',{len,order},'');\no4.help = {'Finite impulse response - requires SPM{F} for inference.'};\n\n%-------------------------------------------------------------------------\n\nbases = choice('Basis Functions','bases',{hrf,o1,o2,o3,o4},'');\nbases.val = {hrf};\nbases.help = {[...\n 'The most common choice of basis function is the Canonical HRF with ',...\n 'or without time and dispersion derivatives. ']};\n\n%-------------------------------------------------------------------------\n\nvolt = mnu('Model Interactions (Volterra)','volt',{'Do not model Interactions','Model Interactions'},{1,2},'');\nvolt.val = {1};\np1 = ['Generalized convolution of inputs (U) with basis set (bf).'];\np2 = [...\n 'For first order expansions the causes are simply convolved ',...\n '(e.g. stick functions) in U.u by the basis functions in bf to create ',...\n 'a design matrix X. For second order expansions new entries appear ',...\n 'in ind, bf and name that correspond to the interaction among the ',...\n 'orginal causes. The basis functions for these efects are two dimensional ',...\n 'and are used to assemble the second order kernel. ',...\n 'Second order effects are computed for only the first column of U.u.'];\np3 = [...\n 'Interactions or response modulations can enter at two levels. Firstly ',...\n 'the stick function itself can be modulated by some parametric variate ',...\n '(this can be time or some trial-specific variate like reaction time) ',...\n 'modeling the interaction between the trial and the variate or, secondly ',...\n 'interactions among the trials themselves can be modeled using a Volterra ',...\n 'series formulation that accommodates interactions over time (and therefore ',...\n 'within and between trial types).'];\nvolt.help = {p1,'',p2,p3};\n\n%-------------------------------------------------------------------------\n\ncdir = files('Directory','dir','dir',1,'');\ncdir.help = {[...\n 'Select a directory where the SPM.mat file containing the ',...\n 'specified design matrix will be written.']};\n\n%-------------------------------------------------------------------------\nfmri_t0 = entry('Microtime onset','fmri_t0','e',[1 1],'');\np1=['The microtime onset, t0, is the first time-bin at which the regressors ',...\n 'are resampled to coincide ',...\n 'with data acquisition. If t0 = 1 then the ',...\n 'regressors will be appropriate for the first slice. If you want to ',...\n 'temporally realign the regressors so that they match responses in the ',...\n 'middle slice then make t0 = t/2 ',...\n '(assuming there is a negligible gap between ',...\n 'volume acquisitions). '];\np2=['Do not change the default setting unless you have a long TR. '];\nfmri_t0.val={1};\nfmri_t0.help={p1,sp_text,p2};\n\nfmri_t = entry('Microtime resolution','fmri_t','e',[1 1],'');\np1=['The microtime resolution, t, is the number of time-bins per ',...\n 'scan used when building regressors. '];\np2=['Do not change this parameter unless you have a long TR and wish to ',...\n 'shift regressors so that they are ',...\n 'aligned to a particular slice. '];\nfmri_t.val={16};\nfmri_t.help={p1,sp_text,p2};\n\nrt = entry('Interscan interval','RT','e',[1 1],'Interscan interval {secs}');\nrt.help = {[...\n 'Interscan interval, TR, (specified in seconds). This is the time between acquiring a plane of one volume ',...\n 'and the same plane in the next volume. It is assumed to be constant throughout.']};\n\n%-------------------------------------------------------------------------\n\nunits = mnu('Units for design','units',{'Scans','Seconds'},{'scans','secs'},'');\np1=['The onsets of events or blocks can be specified in either scans or seconds.'];\nunits.help = {p1};\n\ntiming = branch('Timing parameters','timing',{units,rt,fmri_t,fmri_t0},'');\np1=['Specify various timing parameters needed to construct the design matrix. ',...\n 'This includes the units of the design specification and the interscan interval.'];\n\np2 = ['Also, with longs TRs you may want to shift the regressors so that they are ',...\n 'aligned to a particular slice. This is effected by changing the ',...\n 'microtime resolution and onset. '];\ntiming.help={p1,sp_text,p2};\n\n%-------------------------------------------------------------------------\n\ncvi = mnu('Serial correlations','cvi',{'none','AR(1)'},{'none','AR(1)'},...\n {'Correct for serial correlations'});\ncvi.val={'AR(1)'};\np1 = [...\n 'Serial correlations in fMRI time series due to aliased biorhythms and unmodelled ',...\n 'neuronal activity can be accounted for using an autoregressive AR(1) ',...\n 'model during Classical (ReML) parameter estimation. '];\np2=['This estimate assumes the same ',...\n 'correlation structure for each voxel, within each session. ReML ',...\n 'estimates are then used to correct for non-sphericity during inference ',...\n 'by adjusting the statistics and degrees of freedom appropriately. The ',...\n 'discrepancy between estimated and actual intrinsic (i.e. prior to ',...\n 'filtering) correlations are greatest at low frequencies. Therefore ',...\n 'specification of the high-pass filter is particularly important. '];\np3=[...\n 'Serial correlation can be ignored if you choose the ''none'' option. ',...\n 'Note that the above options only apply if you later specify that your model will be ',...\n 'estimated using the Classical (ReML) approach. If you choose Bayesian estimation ',...\n 'these options will be ignored. For Bayesian estimation, the choice of noise',...\n 'model (AR model order) is made under the estimation options. '];\ncvi.help = {p1,sp_text,p2,sp_text,p3};\n\n%-------------------------------------------------------------------------\n\nconf = branch('fMRI model specification (design only)','fmri_design',...\n {cdir,timing,block,factors,bases,volt,glob,cvi},'fMRI design');\nconf.prog = @run_stats;\nconf.vfiles = @vfiles_stats;\n% conf.check = @check_dir;\nconf.modality = {'FMRI'};\np1=['Statistical analysis of fMRI data uses a mass-univariate approach ',...\n 'based on General Linear Models (GLMs). It comprises the following ',...\n 'steps (1) specification of the GLM design matrix, fMRI data files and filtering ',...\n '(2) estimation of GLM paramaters using classical or ',...\n 'Bayesian approaches and (3) interrogation of results using contrast vectors to ',...\n 'produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs).' ];\np2 = [...\n 'The design matrix defines the experimental design and the nature of ',...\n 'hypothesis testing to be implemented. The design matrix has one row ',...\n 'for each scan and one column for each effect or explanatory variable. ',...\n '(eg. regressor or stimulus function). ',...\n 'You can build design matrices with separable ',...\n 'session-specific partitions. Each partition may be the same (in which ',...\n 'case it is only necessary to specify it once) or different. '];\np3 = ['Responses ',...\n 'can be either event- or epoch related, the only distinction is the duration ',...\n 'of the underlying input or stimulus function. Mathematically they are both ',...\n 'modeled by convolving a series of delta (stick) or box functions (u), ',...\n 'indicating the onset of an event or epoch with a set of basis ',...\n 'functions. These basis functions model the hemodynamic convolution, ',...\n 'applied by the brain, to the inputs. This convolution can be first-order ',...\n 'or a generalized convolution modeled to second order (if you specify the ',...\n 'Volterra option). The same inputs are used by the Hemodynamic model or ',...\n 'Dynamic Causal Models which model the convolution explicitly in terms of ',...\n 'hidden state variables. '];\np4=['Basis functions can be used to plot estimated responses to single events ',...\n 'once the parameters (i.e. basis function coefficients) have ',...\n 'been estimated. The importance of basis functions is that they provide ',...\n 'a graceful transition between simple fixed response models (like the ',...\n 'box-car) and finite impulse response (FIR) models, where there is one ',...\n 'basis function for each scan following an event or epoch onset. The ',...\n 'nice thing about basis functions, compared to FIR models, is that data ',...\n 'sampling and stimulus presentation does not have to be synchronized ',...\n 'thereby allowing a uniform and unbiased sampling of peri-stimulus time.'];\np5 = [...\n 'Event-related designs may be stochastic or deterministic. Stochastic ',...\n 'designs involve one of a number of trial-types occurring with a ',...\n 'specified probability at successive intervals in time. These ',...\n 'probabilities can be fixed (stationary designs) or time-dependent ',...\n '(modulated or non-stationary designs). The most efficient designs ',...\n 'obtain when the probabilities of every trial type are equal. ',...\n 'A critical issue in stochastic designs is whether to include null events ',...\n 'If you wish to estimate the evoked response to a specific event ',...\n 'type (as opposed to differential responses) then a null event must be ',...\n 'included (even if it is not modeled explicitly).'];\np6 = [...\n 'In SPM, analysis of data from multiple subjects typically proceeds in two stages ',...\n 'using models at two ''levels''. The ''first level'' models are used to ',...\n 'implement a within-subject analysis. Typically there will be as many first ',...\n 'level models as there are subjects. Analysis proceeds as described using the ',...\n '''Specify first level'' and ''Estimate'' options. The results of these analyses ',...\n 'can then be presented as ''case studies''. More often, however, one wishes to ',...\n 'make inferences about the population from which the subjects were drawn. This is ',...\n 'an example of a ''Random-Effects (RFX) analysis'' (or, more properly, a mixed-effects ',...\n 'analysis). In SPM, RFX analysis is implemented using the ''summary-statistic'' ',...\n 'approach where contrast images from each subject are used as summary ',...\n 'measures of subject responses. These are then entered as data into a ''second level'' ',...\n 'model. '];\nconf.help = {p1,'',p2,'',p3,'',p4,'',p5,'',p6};\n\nreturn;\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\n% COMMENTED OUT BY DRG. I THINK THIS SUB-FUNCTION WAS A HOLDOVER FROM AN\n% EARLY VERSION OF THIS FILE. PLEASE REMOVE IF REALLY NOT USED. ALSO REMOVE\n% REFERENCE ON LINE 510 (COMMENTED OUT) TO CHECK_DIR\n% function t = check_dir(job)\n% t = {};\n%d = pwd;\n%try,\n% cd(job.dir{1});\n%catch,\n% t = {['Cannot Change to directory \"' job.dir{1} '\".']};\n%end;\n\n%disp('Checking...');\n%disp(fullfile(job.dir{1},'SPM.mat'));\n\n% Should really include a check for a \"virtual\" SPM.mat\n%if exist(fullfile(job.dir{1},'SPM.mat'),'file'),\n% t = {'SPM files exist in the analysis directory.'};\n%end;\n%return;\n% END COMMENTED OUT BY DRG\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\n\nfunction t = cond_check(job)\nt = {};\nif (numel(job.onset) ~= numel(job.duration)) && (numel(job.duration)~=1),\n t = {sprintf('\"%s\": Number of event onsets (%d) does not match the number of durations (%d).',...\n job.name, numel(job.onset),numel(job.duration))};\nend;\nfor i=1:numel(job.pmod),\n if numel(job.onset) ~= numel(job.pmod(i).param),\n t = {t{:}, sprintf('\"%s\" & \"%s\":Number of event onsets (%d) does not equal the number of parameters (%d).',...\n job.name, job.pmod(i).name, numel(job.onset),numel(job.pmod(i).param))};\n end;\nend;\nreturn;\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\n\nfunction t = sess_check(sess)\nt = {};\nfor i=1:numel(sess.regress),\n if sess.nscan ~= numel(sess.regress(i).val),\n t = {t{:}, sprintf('Num scans (%d) ~= Num regress[%d] (%d).',numel(sess.nscan),i,numel(sess.regress(i).val))};\n end;\nend;\nreturn;\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\nfunction my_cd(varargin)\n% jobDir must be the actual directory to change to, NOT the job structure. \njobDir = varargin{1};\nif ~isempty(jobDir)\n try\n cd(char(jobDir));\n fprintf('Changing directory to: %s\\n',char(jobDir));\n catch\n error('Failed to change directory. Aborting run.')\n end\nend\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction run_stats(job)\n% Set up the design matrix and run a design.\n\nspm_defaults;\nglobal defaults\ndefaults.modality='FMRI';\n\noriginal_dir = pwd;\nmy_cd(job.dir);\n\n%-Ask about overwriting files from previous analyses...\n%-------------------------------------------------------------------\nif exist(fullfile(job.dir{1},'SPM.mat'),'file')\n str = {\t'Current directory contains existing SPM file:',...\n 'Continuing will overwrite existing file!'};\n if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);\n fprintf('%-40s: %30s\\n\\n',...\n 'Abort... (existing SPM file)',spm('time'));\n return\n end\nend\n\n% If we've gotten to this point we're committed to overwriting files.\n% Delete them so we don't get stuck in spm_spm\n%------------------------------------------------------------------------\nfiles = {'^mask\\..{3}$','^ResMS\\..{3}$','^RPV\\..{3}$',...\n '^beta_.{4}\\..{3}$','^con_.{4}\\..{3}$','^ResI_.{4}\\..{3}$',...\n '^ess_.{4}\\..{3}$', '^spm\\w{1}_.{4}\\..{3}$'};\n\nfor i=1:length(files)\n j = spm_select('List',pwd,files{i});\n for k=1:size(j,1)\n spm_unlink(deblank(j(k,:)));\n end\nend\n\n% Variables\n%-------------------------------------------------------------\nSPM.xY.RT = job.timing.RT;\n\n% Slice timing\ndefaults.stats.fmri.t=job.timing.fmri_t;\ndefaults.stats.fmri.t0=job.timing.fmri_t0;\n\n% Basis function variables\n%-------------------------------------------------------------\nSPM.xBF.UNITS = job.timing.units;\nSPM.xBF.dt = job.timing.RT/defaults.stats.fmri.t;\nSPM.xBF.T = defaults.stats.fmri.t;\nSPM.xBF.T0 = defaults.stats.fmri.t0;\n\n% Basis functions\n%-------------------------------------------------------------\nif strcmp(fieldnames(job.bases),'hrf')\n if all(job.bases.hrf.derivs == [0 0])\n SPM.xBF.name = 'hrf';\n elseif all(job.bases.hrf.derivs == [1 0])\n SPM.xBF.name = 'hrf (with time derivative)';\n elseif all(job.bases.hrf.derivs == [1 1])\n SPM.xBF.name = 'hrf (with time and dispersion derivatives)';\n else\n error('Unrecognized hrf derivative choices.')\n end\nelse\n nambase = fieldnames(job.bases);\n if ischar(nambase)\n nam=nambase;\n else\n nam=nambase{1};\n end\n switch nam,\n case 'fourier',\n SPM.xBF.name = 'Fourier set';\n case 'fourier_han',\n SPM.xBF.name = 'Fourier set (Hanning)';\n case 'gamma',\n SPM.xBF.name = 'Gamma functions';\n case 'fir',\n SPM.xBF.name = 'Finite Impulse Response';\n otherwise\n error('Unrecognized hrf derivative choices.')\n end\n SPM.xBF.length = job.bases.(nam).length;\n SPM.xBF.order = job.bases.(nam).order;\nend\nSPM.xBF = spm_get_bf(SPM.xBF);\nif isempty(job.sess),\n SPM.xBF.Volterra = false;\nelse\n SPM.xBF.Volterra = job.volt;\nend;\n\nfor i = 1:numel(job.sess),\n sess = job.sess(i);\n\n % Image filenames\n %-------------------------------------------------------------\n SPM.nscan(i) = sess.nscan;\n U = [];\n\n % Augment the singly-specified conditions with the multiple conditions\n % specified in a .mat file provided by the user\n %------------------------------------------------------------\n if ~isempty(sess.multi{1})\n try\n multicond = load(sess.multi{1});\n\tcatch\n error('Cannot load %s',sess.multi{1});\n end\n if ~(isfield(multicond,'names')&&isfield(multicond,'onsets')&&...\n\t isfield(multicond,'durations')) || ...\n\t\t~all([numel(multicond.names),numel(multicond.onsets), ...\n\t\t numel(multicond.durations)]==numel(multicond.names))\n error(['Multiple conditions MAT-file ''%s'' is invalid.\\n',...\n\t\t 'File must contain names, onsets, and durations '...\n\t\t 'cell arrays of equal length.\\n'],sess.multi{1});\n end\n\t\n %-contains three cell arrays: names, onsets and durations\n for j=1:length(multicond.onsets)\n cond.name = multicond.names{j};\n cond.onset = multicond.onsets{j};\n cond.duration = multicond.durations{j};\n \n % ADDED BY DGITELMAN\n % Mutiple Conditions Time Modulation\n %------------------------------------------------------\n % initialize the variable.\n cond.tmod = 0;\n if isfield(multicond,'tmod');\n try\n cond.tmod = multicond.tmod{j};\n catch\n error('Error specifying time modulation.');\n end\n end\n\n % Mutiple Conditions Parametric Modulation\n %------------------------------------------------------\n % initialize the parametric modulation variable.\n cond.pmod = [];\n if isfield(multicond,'pmod')\n % only access existing modulators\n try\n % check if there is a parametric modulator. this allows\n % pmod structures with fewer entries than conditions.\n % then check whether any cells are filled in.\n if (j <= numel(multicond.pmod)) && ...\n ~isempty(multicond.pmod(j).name)\n\n % we assume that the number of cells in each\n % field of pmod is the same (or should be).\n for ii = 1:numel(multicond.pmod(j).name)\n cond.pmod(ii).name = multicond.pmod(j).name{ii};\n cond.pmod(ii).param = multicond.pmod(j).param{ii};\n cond.pmod(ii).poly = multicond.pmod(j).poly{ii};\n end\n end;\n catch\n error('Error specifying parametric modulation.');\n end\n end\n sess.cond(end+1) = cond;\n end\n end\n\n % Configure the input structure array\n %-------------------------------------------------------------\n for j = 1:length(sess.cond),\n cond = sess.cond(j);\n U(j).name = {cond.name};\n U(j).ons = cond.onset(:);\n U(j).dur = cond.duration(:);\n if length(U(j).dur) == 1\n U(j).dur = U(j).dur*ones(size(U(j).ons));\n elseif length(U(j).dur) ~= length(U(j).ons)\n error('Mismatch between number of onset and number of durations.')\n end\n\n P = [];\n q1 = 0;\n if cond.tmod>0,\n % time effects\n P(1).name = 'time';\n P(1).P = U(j).ons*job.timing.RT;\n P(1).h = cond.tmod;\n q1 = 1;\n end;\n if ~isempty(cond.pmod)\n for q = 1:numel(cond.pmod),\n % Parametric effects\n q1 = q1 + 1;\n P(q1).name = cond.pmod(q).name;\n P(q1).P = cond.pmod(q).param(:);\n P(q1).h = cond.pmod(q).poly;\n end;\n end\n if isempty(P)\n P.name = 'none';\n P.h = 0;\n end\n U(j).P = P;\n\n end\n\n SPM.Sess(i).U = U;\n\n\n % User specified regressors\n %-------------------------------------------------------------\n C = [];\n Cname = cell(1,numel(sess.regress));\n for q = 1:numel(sess.regress),\n Cname{q} = sess.regress(q).name;\n C = [C, sess.regress(q).val(:)];\n end\n\n % Augment the singly-specified regressors with the multiple regressors\n % specified in the regressors.mat file\n %------------------------------------------------------------\n if ~strcmp(sess.multi_reg,'')\n tmp=load(char(sess.multi_reg{:}));\n if isstruct(tmp) && isfield(tmp,'R')\n R = tmp.R;\n elseif isnumeric(tmp)\n % load from e.g. text file\n R = tmp;\n else\n warning('Can''t load user specified regressors in %s', ...\n char(sess.multi_reg{:}));\n R = [];\n end\n\n C=[C, R];\n nr=size(R,2);\n nq=length(Cname);\n for inr=1:nr,\n Cname{inr+nq}=['R',int2str(inr)];\n end\n end\n SPM.Sess(i).C.C = C;\n SPM.Sess(i).C.name = Cname;\n\nend\n\n% Factorial design\n%-------------------------------------------------------------\nif isfield(job,'fact')\n if ~isempty(job.fact)\n NC=length(SPM.Sess(1).U); % Number of conditions\n CheckNC=1;\n for i=1:length(job.fact)\n SPM.factor(i).name=job.fact(i).name;\n SPM.factor(i).levels=job.fact(i).levels;\n CheckNC=CheckNC*SPM.factor(i).levels;\n end\n if ~(CheckNC==NC)\n disp('Error in fmri_spec job: factors do not match conditions');\n return\n end\n end\nelse\n SPM.factor=[];\nend\n\n% Globals\n%-------------------------------------------------------------\nSPM.xGX.iGXcalc = job.global;\nSPM.xGX.sGXcalc = 'mean voxel value';\nSPM.xGX.sGMsca = 'session specific';\n\n% High Pass filter\n%-------------------------------------------------------------\nfor i = 1:numel(job.sess),\n SPM.xX.K(i).HParam = job.sess(i).hpf;\nend\n\n% Autocorrelation\n%-------------------------------------------------------------\nSPM.xVi.form = job.cvi;\n\n% Let SPM configure the design\n%-------------------------------------------------------------\nSPM = spm_fMRI_design(SPM);\n\n%-Save SPM.mat\n%-----------------------------------------------------------------------\nfprintf('%-40s: ','Saving SPM configuration') %-#\nif str2num(version('-release'))>=14,\n save('SPM','-V6','SPM');\nelse\n save('SPM','SPM');\nend;\n\nfprintf('%30s\\n','...SPM.mat saved') %-#\n\n\nmy_cd(original_dir); % Change back dir\nfprintf('Done\\n')\nreturn\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\nfunction vf = vfiles_stats(job)\ndirec = job.dir{1};\nvf = {spm_select('CPath','SPM.mat',direc)};\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_defs.m", "ext": ".m", "path": "spm5-master/spm_defs.m", "size": 9319, "source_encoding": "utf_8", "md5": "92fb4adf7d39d590d189b142d2912e4b", "text": "function spm_defs(job)\n% Various deformation field utilities.\n% FORMAT spm_defs(job)\n% job - a job created via spm_config_defs.m and spm_jobman.m\n%\n% See spm_config_defs.m for more information.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_defs.m 991 2007-11-02 14:01:28Z john $\n\n[Def,mat] = get_comp(job.comp);\nsave_def(Def,mat,strvcat(job.ofname));\napply_def(Def,mat,strvcat(job.fnames),job.interp);\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [Def,mat] = get_comp(job)\n% Return the composition of a number of deformation fields.\n\nif isempty(job),\n error('Empty list of jobs in composition');\nend;\n[Def,mat] = get_job(job{1});\nfor i=2:numel(job),\n Def1 = Def;\n mat1 = mat;\n [Def,mat] = get_job(job{i});\n M = inv(mat1);\n for j=1:size(Def{1},3)\n d0 = {double(Def{1}(:,:,j)), double(Def{2}(:,:,j)),double(Def{3}(:,:,j))};\n d{1} = M(1,1)*d0{1}+M(1,2)*d0{2}+M(1,3)*d0{3}+M(1,4);\n d{2} = M(2,1)*d0{1}+M(2,2)*d0{2}+M(2,3)*d0{3}+M(2,4);\n d{3} = M(3,1)*d0{1}+M(3,2)*d0{2}+M(3,3)*d0{3}+M(3,4);\n Def{1}(:,:,j) = single(spm_sample_vol(Def1{1},d{:},[1,NaN]));\n Def{2}(:,:,j) = single(spm_sample_vol(Def1{2},d{:},[1,NaN]));\n Def{3}(:,:,j) = single(spm_sample_vol(Def1{3},d{:},[1,NaN]));\n\n end;\nend;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [Def,mat] = get_job(job)\n% Determine what is required, and pass the relevant bit of the\n% job out to the appropriate function.\n\nfn = fieldnames(job);\nfn = fn{1};\nswitch fn\ncase {'comp'}\n [Def,mat] = get_comp(job.(fn));\ncase {'def'}\n [Def,mat] = get_def(job.(fn));\ncase {'dartel'}\n [Def,mat] = get_dartel(job.(fn)); \ncase {'sn2def'}\n [Def,mat] = get_sn2def(job.(fn));\ncase {'inv'}\n [Def,mat] = get_inv(job.(fn));\ncase {'id'}\n [Def,mat] = get_id(job.(fn));\notherwise\n error('Unrecognised job type');\nend;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [Def,mat] = get_sn2def(job)\n% Convert a SPM _sn.mat file into a deformation field, and return it.\n\nvox = job.vox;\nbb = job.bb;\nsn = load(job.matname{1});\n\n[bb0,vox0] = bbvox_from_V(sn.VG(1));\n\nif any(~isfinite(vox)), vox = vox0; end;\nif any(~isfinite(bb)), bb = bb0; end;\nbb = sort(bb);\nvox = abs(vox);\n\n% Adjust bounding box slightly - so it rounds to closest voxel.\nbb(:,1) = round(bb(:,1)/vox(1))*vox(1);\nbb(:,2) = round(bb(:,2)/vox(2))*vox(2);\nbb(:,3) = round(bb(:,3)/vox(3))*vox(3);\n\nM = sn.VG(1).mat;\nvxg = sqrt(sum(M(1:3,1:3).^2));\nogn = M\\[0 0 0 1]';\nogn = ogn(1:3)';\n\n% Convert range into range of voxels within template image\nx = (bb(1,1):vox(1):bb(2,1))/vxg(1) + ogn(1);\ny = (bb(1,2):vox(2):bb(2,2))/vxg(2) + ogn(2);\nz = (bb(1,3):vox(3):bb(2,3))/vxg(3) + ogn(3);\n\nog = -vxg.*ogn;\nof = -vox.*(round(-bb(1,:)./vox)+1);\nM1 = [vxg(1) 0 0 og(1) ; 0 vxg(2) 0 og(2) ; 0 0 vxg(3) og(3) ; 0 0 0 1];\nM2 = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1];\nmat = sn.VG(1).mat*inv(M1)*M2;\n% dim = [length(x) length(y) length(z)];\n\n[X,Y] = ndgrid(x,y);\n\nst = size(sn.Tr);\n\nif (prod(st) == 0),\n affine_only = true;\n basX = 0;\n basY = 0;\n basZ = 0;\nelse\n affine_only = false;\n basX = spm_dctmtx(sn.VG(1).dim(1),st(1),x-1);\n basY = spm_dctmtx(sn.VG(1).dim(2),st(2),y-1);\n basZ = spm_dctmtx(sn.VG(1).dim(3),st(3),z-1);\nend,\n\nDef = single(0);\nDef(numel(x),numel(y),numel(z)) = 0;\nDef = {Def; Def; Def};\n\nfor j=1:length(z)\n if (~affine_only)\n tx = reshape( reshape(sn.Tr(:,:,:,1),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );\n ty = reshape( reshape(sn.Tr(:,:,:,2),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );\n tz = reshape( reshape(sn.Tr(:,:,:,3),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );\n\n X1 = X + basX*tx*basY';\n Y1 = Y + basX*ty*basY';\n Z1 = z(j) + basX*tz*basY';\n end\n\n Mult = sn.VF.mat*sn.Affine;\n if (~affine_only)\n X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4);\n Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4);\n Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4);\n else\n X2= Mult(1,1)*X + Mult(1,2)*Y + (Mult(1,3)*z(j) + Mult(1,4));\n Y2= Mult(2,1)*X + Mult(2,2)*Y + (Mult(2,3)*z(j) + Mult(2,4));\n Z2= Mult(3,1)*X + Mult(3,2)*Y + (Mult(3,3)*z(j) + Mult(3,4));\n end\n\n Def{1}(:,:,j) = single(X2);\n Def{2}(:,:,j) = single(Y2);\n Def{3}(:,:,j) = single(Z2);\nend;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [bb,vx] = bbvox_from_V(V)\n% Return the default bounding box for an image volume\n\nvx = sqrt(sum(V.mat(1:3,1:3).^2));\no = V.mat\\[0 0 0 1]';\no = o(1:3)';\nbb = [-vx.*(o-1) ; vx.*(V.dim(1:3)-o)];\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [Def,mat] = get_def(job)\n% Load a deformation field saved as an image\n\nP = [repmat(job{:},3,1), [',1,1';',1,2';',1,3']];\nV = spm_vol(P);\nDef = cell(3,1);\nDef{1} = spm_load_float(V(1));\nDef{2} = spm_load_float(V(2));\nDef{3} = spm_load_float(V(3));\nmat = V(1).mat;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [Def,mat] = get_dartel(job)\n% Integrate a DARTEL flow field\nN = nifti(job.flowfield{1});\ny = spm_dartel_integrate(N.dat,job.times,job.K);\nDef = cell(3,1);\nif all(job.times == [0 1]),\n M = single(N.mat);\n mat = N.mat0;\nelse\n M = single(N.mat0);\n mat = N.mat;\nend\nDef{1} = y(:,:,:,1)*M(1,1) + y(:,:,:,2)*M(1,2) + y(:,:,:,3)*M(1,3) + M(1,4);\nDef{2} = y(:,:,:,1)*M(2,1) + y(:,:,:,2)*M(2,2) + y(:,:,:,3)*M(2,3) + M(2,4);\nDef{3} = y(:,:,:,1)*M(3,1) + y(:,:,:,2)*M(3,2) + y(:,:,:,3)*M(3,3) + M(3,4);\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [Def,mat] = get_id(job)\n% Get an identity transform based on an image volume.\nN = nifti(job.space{1});\nd = [size(N.dat),1];\nd = d(1:3);\nmat = N.mat;\nDef = cell(3,1);\n[y1,y2,y3] = ndgrid(1:d(1),1:d(2),1:d(3));\nDef{1} = single(y1*mat(1,1) + y2*mat(1,2) + y3*mat(1,3) + mat(1,4));\nDef{2} = single(y1*mat(2,1) + y2*mat(2,2) + y3*mat(2,3) + mat(2,4));\nDef{3} = single(y1*mat(3,1) + y2*mat(3,2) + y3*mat(3,3) + mat(3,4));\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [Def,mat] = get_inv(job)\n% Invert a deformation field (derived from a composition of deformations)\n\nVT = spm_vol(job.space{:});\n[Def0,mat0] = get_comp(job.comp);\nM0 = mat0;\nM1 = inv(VT.mat);\nM0(4,:) = [0 0 0 1];\nM1(4,:) = [0 0 0 1];\n[Def{1},Def{2},Def{3}] = spm_invdef(Def0{:},VT.dim(1:3),M1,M0);\nmat = VT.mat;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction save_def(Def,mat,ofname)\n% Save a deformation field as an image\n\nif isempty(ofname), return; end;\n\nfname = ['y_' ofname '.nii'];\ndim = [size(Def{1},1) size(Def{1},2) size(Def{1},3) 1 3];\ndtype = 'FLOAT32-BE';\noff = 0;\nscale = 1;\ninter = 0;\ndat = file_array(fname,dim,dtype,off,scale,inter);\n\nN = nifti;\nN.dat = dat;\nN.mat = mat;\nN.mat0 = mat;\nN.mat_intent = 'Aligned';\nN.mat0_intent = 'Aligned';\nN.intent.code = 'VECTOR';\nN.intent.name = 'Mapping';\nN.descrip = 'Deformation field';\ncreate(N);\nN.dat(:,:,:,1,1) = Def{1};\nN.dat(:,:,:,1,2) = Def{2};\nN.dat(:,:,:,1,3) = Def{3};\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction apply_def(Def,mat,fnames,intrp)\n% Warp an image or series of images according to a deformation field\n\nintrp = [intrp*[1 1 1], 0 0 0];\n\nfor i=1:size(fnames,1),\n V = spm_vol(fnames(i,:));\n M = inv(V.mat);\n [pth,nam,ext] = spm_fileparts(fnames(i,:));\n ofname = fullfile(pth,['w',nam,ext]);\n Vo = struct('fname',ofname,...\n 'dim',[size(Def{1},1) size(Def{1},2) size(Def{1},3)],...\n 'dt',V.dt,...\n 'pinfo',V.pinfo,...\n 'mat',mat,...\n 'n',V.n,...\n 'descrip',V.descrip);\n C = spm_bsplinc(V,intrp);\n Vo = spm_create_vol(Vo);\n for j=1:size(Def{1},3)\n d0 = {double(Def{1}(:,:,j)), double(Def{2}(:,:,j)),double(Def{3}(:,:,j))};\n d{1} = M(1,1)*d0{1}+M(1,2)*d0{2}+M(1,3)*d0{3}+M(1,4);\n d{2} = M(2,1)*d0{1}+M(2,2)*d0{2}+M(2,3)*d0{3}+M(2,4);\n d{3} = M(3,1)*d0{1}+M(3,2)*d0{2}+M(3,3)*d0{3}+M(3,4);\n dat = spm_bsplins(C,d{:},intrp);\n Vo = spm_write_plane(Vo,dat,j);\n end;\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_sp.m", "ext": ".m", "path": "spm5-master/spm_sp.m", "size": 38364, "source_encoding": "utf_8", "md5": "adb92133e990f9484e8215c6e97e5080", "text": "function varargout = spm_sp(varargin)\n% Orthogonal (design) matrix space setting & manipulation\n% FORMAT varargout = spm_spc(action,varargin)\n%\n% This function computes the different projectors related to the row\n% and column spaces X. It should be used to avoid redundant computation\n% of svd on large X matrix. It is divided into actions that set up the\n% space, (Create,Set,...) and actions that compute projections (pinv,\n% pinvXpX, pinvXXp, ...) This is motivated by the problem of rounding\n% errors that can invalidate some computation and is a tool to work\n% with spaces.\n%\n% The only thing that is not easily computed is the null space of\n% the line of X (assuming size(X,1) > size(X,2)).\n% To get this space (a basis of it or a projector on it) use spm_sp on X'.\n%\n% The only restriction on the use of the space structure is when X is\n% so big that you can't fit X and its svd in memory at the same time.\n% Otherwise, the use of spm_sp will generally speed up computations and\n% optimise memory use.\n%\n% Note that since the design matrix is stored in the space structure,\n% there is no need to keep a separate copy of it.\n%\n% ----------------\n%\n% The structure is:\n%\tx = struct(...\n%\t\t'X',\t[],...\t\t% Mtx\n%\t\t'tol',\t[],...\t\t% tolerance\n%\t\t'ds',\t[],...\t\t% vectors of singular values \n%\t\t'u',\t[],...\t\t% u as in X = u*diag(ds)*v'\n%\t\t'v',\t[],...\t\t% v as in X = u*diag(ds)*v'\n%\t\t'rk',\t[],...\t\t% rank\n%\t\t'oP',\t[],...\t\t% orthogonal projector on X\n%\t\t'oPp',\t[],...\t\t% orthogonal projector on X'\n%\t\t'ups',\t[],...\t\t% space in which this one is embeded\n%\t\t'sus',\t[]);\t\t% subspace\n%\n% The basic required fields are X, tol, ds, u, v, rk.\n%\n% ======================================================================\n%\n% FORMAT x = spm_sp('Set',X)\n% Set up space structure, storing matrix, singular values, rank & tolerance\n% X - a (design) matrix (2D)\n% x - the corresponding space structure, with basic fields filled in\n% The SVD is an \"economy size\" svd, using MatLab's svd(X,0)\n%\n%\n% FORMAT r = spm_sp('oP',x[,Y])\n% FORMAT r = spm_sp('oPp',x[,Y])\n% Return orthogonal projectors, or orthogonal projection of data Y (if passed)\n% x - space structure of matrix X\n% r - ('oP' usage) ortho. projection matrix projecting into column space of x.X\n% - ('oPp' usage) ortho. projection matrix projecting into row space of x.X\n% Y - data (optional)\n% - If data are specified then the corresponding projection of data is\n% returned. This is usually more efficient that computing and applying\n% the projection matrix directly.\n%\n%\n% FORMAT pX = spm_sp('pinv',x)\n% Returns a pseudo-inverse of X - pinv(X) - computed efficiently\n% x - space structure of matrix X\n% pX - pseudo-inverse of X\n% This is the same as MatLab's pinv - the Moore-Penrose pseudoinverse\n% ( Note that because size(pinv(X)) == size(X'), it is not generally )\n% ( useful to compute pinv(X)*Data sequentially (as is the case for )\n% ( 'res' or 'oP') )\n%\n%\n% FORMAT pXpX = spm_sp('pinvxpx',x)\n% Returns a pseudo-inverse of X'X - pinv(X'*X) - computed efficiently\n% x - space structure of matrix X\n% pXpX - pseudo-inverse of (X'X)\n% ( Note that because size(pinv(X'*X)) == [size(X,2) size(X,2)], )\n% ( it is not useful to compute pinv(X'X)*Data sequentially unless )\n% ( size(X,1) < size(X,2) )\n%\n%\n% FORMAT XpX = spm_sp('xpx',x)\n% Returns (X'X) - computed efficiently\n% x - space structure of matrix X\n% XpX - (X'X)\n%\n%\n% FORMAT pXXp = spm_sp('pinvxxp',x)\n% Returns a pseudo-inverse of XX' - pinv(X*X') - computed efficiently\n% x - space structure of matrix X\n% pXXp - pseudo-inverse of (XX')\n%\n%\n% FORMAT XXp = spm_sp('xxp',x)\n% Returns (XX') - computed efficiently\n% x - space structure of matrix X\n% XXp - (XX')\n%\n%\n% FORMAT b = spm_sp('isinsp',x,c[,tol])\n% FORMAT b = spm_sp('isinspp',x,c[,tol])\n% Check whether vectors c are in the column/row space of X\n% x - space structure of matrix X\n% c - vector(s) (Multiple vectors passed as a matrix)\n% tol - (optional) tolerance (for rounding error)\n% [defaults to tolerance specified in space structure: x.tol]\n% b - ('isinsp' usage) true if c is in the column space of X\n% - ('isinspp' usage) true if c is in the column space of X\n% \n% FORMAT b = spm_sp('eachinsp',x,c[,tol])\n% FORMAT b = spm_sp('eachinspp',x,c[,tol])\n% Same as 'isinsp' and 'isinspp' but returns a logical row vector of\n% length size(c,2).\n%\n% FORMAT N = spm_sp('n',x)\n% Simply returns the null space of matrix X (same as matlab NULL)\n% (Null space = vectors associated with zero eigenvalues)\n% x - space structure of matrix X\n% N - null space\n%\n%\n% FORMAT r = spm_sp('nop',x[,Y])\n% Orthogonal projector onto null space of X, or projection of data Y (if passed)\n% x - space structure of matrix X\n% Y - (optional) data\n% r - (if no Y passed) orthogonal projection matrix into the null space of X\n% - (if Y passed ) orthogonal projection of data into the null space of X\n% ( Note that if xp = spm_sp('set',x.X'), we have: )\n% ( spm_sp('nop',x) == spm_sp('res',xp) )\n% ( or, equivalently: )\n% ( spm_sp('nop',x) + spm_sp('oP',xp) == eye(size(xp.X,1)); )\n%\n%\n% FORMAT r = spm_sp('res',x[,Y])\n% Returns residual formaing matrix wirit column space of X, or residuals (if Y)\n% x - space structure of matrix X\n% Y - (optional) data\n% r - (if no Y passed) residual forming matrix for design matrix X\n% - (if Y passed ) residuals, i.e. residual forming matrix times data\n% ( This will be more efficient than\n% ( spm_sp('res',x)*Data, when size(X,1) > size(X,2)\n% Note that this can also be seen as the orthogonal projector onto the\n% null space of x.X' (which is not generally computed in svd, unless\n% size(X,1) < size(X,2)).\n%\n%\n% FORMAT oX = spm_sp('ox', x)\n% FORMAT oXp = spm_sp('oxp',x)\n% Returns an orthonormal basis for X ('ox' usage) or X' ('oxp' usage)\n% x - space structure of matrix X\n% oX - orthonormal basis for X - same as orth(x.X)\n% xOp - *an* orthonormal for X' (but not the same as orth(x.X'))\n%\n%\n% FORMAT b = spm_sp('isspc',x)\n% Check a variable is a structure with the right fields for a space structure\n% x - candidate variable\n% b - true if x is a structure with fieldnames corresponding to spm_sp('create')\n%\n%\n% FORMAT [b,e] = spm_sp('issetspc',x)\n% Test whether a variable is a space structure with the basic fields set\n% x - candidate variable\n% b - true is x is a structure with fieldnames corresponding to\n% spm_sp('Create'), which has it's basic fields filled in.\n% e - string describing why x fails the issetspc test (if it does)\n% This is simply a gateway function combining spm_sp('isspc',x) with\n% the internal subfunction sf_isset, which checks that the basic fields\n% are not empty. See sf_isset (below).\n%\n%-----------------------------------------------------------------------\n% SUBFUNCTIONS:\n%\n% FORMAT b = sf_isset(x)\n% Checks that the basic fields are non-empty (doesn't check they're right!)\n% x - space structure\n% b - true if the basic fields are non-empty\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Jean-Baptiste Poline\n% $Id: spm_sp.m 112 2005-05-04 18:20:52Z john $\n\n\nif nargin==0\n\terror('Do what? no arguments given...')\nelse\n\taction = varargin{1};\nend\n\n%- check the very basics arguments\n\nswitch lower(action), \ncase {'create','set','issetspc','isspc'}\n\t%- do nothing\notherwise,\n\tif nargin==1, error('No space : can''t do much!'), end\n\t[ok,str] = spm_sp('issetspc',varargin{2}); \n\tif ~ok, error(str), else, sX = varargin{2}; end;\nend;\n\n\n\nswitch lower(action), \n\ncase 'create' %-Create space structure\n%=======================================================================\n% x = spm_sp('Create')\nvarargout = {sf_create};\n\ncase 'set' %-Set singular values, space basis, rank & tolerance\n%=======================================================================\n% x = spm_sp('Set',X)\n\nif nargin==1 error('No design matrix : can''t do much!'), \nelse X = varargin{2}; end\nif isempty(X), varargout = {sf_create}; return, end\n\n%- only sets plain matrices\n%- check X has 2 dim only\n\nif max(size(size(X))) > 2, error('Too many dim in the set'), end \nif ~isnumeric(X), error('only sets numeric matrices'), end\n\nvarargout = {sf_set(X)};\n\n\ncase {'p', 'transp'} %-Transpose space of X\n%=======================================================================\nswitch nargin\ncase 2\t\n\tvarargout = {sf_transp(sX)};\notherwise\n\terror('too many input argument in spm_sp');\n\nend % switch nargin\n\n\ncase {'op', 'op:'} %-Orthogonal projectors on space of X\n%=======================================================================\n% r = spm_sp('oP', sX[,Y]) \n% r = spm_sp('oP:', sX[,Y]) %- set to 0 less than tolerence values\n%\n% if isempty(Y) returns as if Y not given\n%-----------------------------------------------------------------------\n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n case 'op'\n varargout = {sf_op(sX)};\n case 'op:'\n varargout = {sf_tol(sf_op(sX),sX.tol)};\n end %- switch lower(action), \n\ncase 3\n Y = varargin{3};\n if isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;\n\n switch lower(action), \n case 'op'\n varargout = {sf_op(sX)*Y};\n case 'op:'\n varargout = {sf_tol(sf_op(sX)*Y,sX.tol)};\n end % switch lower(action)\n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\ncase {'opp', 'opp:'} %-Orthogonal projectors on space of X'\n%=======================================================================\n% r = spm_sp('oPp',sX[,Y]) \n% r = spm_sp('oPp:',sX[,Y]) %- set to 0 less than tolerence values\n%\n% if isempty(Y) returns as if Y not given\n%-----------------------------------------------------------------------\n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n\tcase 'opp'\n varargout = {sf_opp(sX)};\n\tcase 'opp:'\n varargout = {sf_tol(sf_opp(sX),sX.tol)};\n end %- switch lower(action), \n\ncase 3\n Y = varargin{3};\n if isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;\n\n switch lower(action), \n case 'opp'\n varargout = {sf_opp(sX)*Y};\n case 'opp:'\n varargout = {sf_tol(sf_opp(sX)*Y,sX.tol)};\n end % switch lower(action)\n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\n\ncase {'x-','x-:'} %-Pseudo-inverse of X - pinv(X)\n%=======================================================================\n% = spm_sp('x-',x) \n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n case {'x-'}\n varargout = { sf_pinv(sX) };\n case {'x-:'}\n varargout = {sf_tol( sf_pinv(sX), sf_t(sX) )};\n end\n\ncase 3\n %- check dimensions of Y\t\n Y = varargin{3};\n if isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n if size(Y,1) ~= sf_s1(sX), error(['Dim dont match ' action]); end\n\n switch lower(action), \t\t\n case {'x-'}\n varargout = { sf_pinv(sX)*Y };\n case {'x-:'}\n varargout = {sf_tol( sf_pinv(sX)*Y, sf_t(sX) )};\n end\n\notherwise\n error(['too many input argument in spm_sp ' action]);\n\nend % switch nargin\n\n\ncase {'xp-','xp-:','x-p','x-p:'} %- Pseudo-inverse of X'\n%=======================================================================\n% pX = spm_sp('xp-',x) \n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n case {'xp-','x-p'}\n varargout = { sf_pinvxp(sX) };\n case {'xp-:','x-p:'}\n varargout = {sf_tol( sf_pinvxp(sX), sf_t(sX) )};\n end\n\ncase 3\n %- check dimensions of Y\t\n Y = varargin{3};\n if isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n if size(Y,1) ~= sf_s2(sX), error(['Dim dont match ' action]); end\n\n switch lower(action), \t\t\n case {'xp-','x-p'}\n varargout = { sf_pinvxp(sX)*Y };\n case {'xp-:','x-p:'}\n varargout = {sf_tol( sf_pinvxp(sX)*Y, sf_t(sX) )};\n end\n\notherwise\n error(['too many input argument in spm_sp ' action]);\n\nend % switch nargin\n\n\ncase {'cukxp-','cukxp-:'} %- Coordinates of pinv(X') in the base of uk\n%=======================================================================\n% pX = spm_sp('cukxp-',x) \n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n case {'cukxp-'}\n varargout = { sf_cukpinvxp(sX) };\n case {'cukxp-:'}\n varargout = {sf_tol(sf_cukpinvxp(sX),sX.tol)};\n end\n\ncase 3\n %- check dimensions of Y\t\n Y = varargin{3};\n if isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n if size(Y,1) ~= sf_s2(sX), error(['Dim dont match ' action]); end\n\n switch lower(action), \t\t\n case {'cukxp-'}\n varargout = { sf_cukpinvxp(sX)*Y };\n case {'cukxp-:'}\n varargout = {sf_tol(sf_cukpinvxp(sX)*Y,sX.tol)};\n end\n\notherwise\n error(['too many input argument in spm_sp ' action]);\n\nend % switch nargin\n\n\n\n\ncase {'cukx','cukx:'} %- Coordinates of X in the base of uk \n%=======================================================================\n% pX = spm_sp('cukx',x)\n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n case {'cukx'}\n varargout = { sf_cukx(sX) };\n case {'cukx:'}\n varargout = {sf_tol(sf_cukx(sX),sX.tol)};\n end\n\ncase 3\n %- check dimensions of Y\t\n Y = varargin{3};\n if isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n if size(Y,1) ~= sf_s2(sX), error(['Dim dont match ' action]); end\n\n switch lower(action), \t\t\n case {'cukx'}\n varargout = { sf_cukx(sX)*Y };\n case {'cukx:'}\n varargout = {sf_tol(sf_cukx(sX)*Y,sX.tol)};\n end\n\notherwise\n error(['too many input argument in spm_sp ' action]);\n\nend % switch nargin\n\n\ncase {'rk'} %- Returns rank\n%=======================================================================\nvarargout = { sf_rk(sX) };\n\n\ncase {'ox', 'oxp'} %-Orthonormal basis sets for X / X'\n%=======================================================================\n% oX = spm_sp('ox', x)\n% oXp = spm_sp('oxp',x)\n\nif sf_rk(sX) > 0 \n switch lower(action)\n case 'ox'\n varargout = {sf_uk(sX)};\n case 'oxp'\n varargout = {sf_vk(sX)};\n end\nelse\n switch lower(action)\n case 'ox'\n varargout = {zeros(sf_s1(sX),1)};\n case 'oxp'\n varargout = {zeros(sf_s2(sX),1)};\n end\nend\n\ncase {'x', 'xp'} %- X / X' robust to spm_sp changes\n%=======================================================================\n% X = spm_sp('x', x)\n% X' = spm_sp('xp',x)\n\nswitch lower(action)\n case 'x', varargout = {sX.X};\n case 'xp', varargout = {sX.X'};\nend\n\ncase {'xi', 'xpi'} %- X(:,i) / X'(:,i) robust to spm_sp changes\n%=======================================================================\n% X = spm_sp('xi', x)\n% X' = spm_sp('xpi',x)\n\ni = varargin{3}; % NO CHECKING on i !!! assumes correct\nswitch lower(action)\n case 'xi', varargout = {sX.X(:,i)};\n case 'xpi', varargout = {sX.X(i,:)'};\nend\n\ncase {'uk','uk:'} %- Returns u(:,1:r) \n%=======================================================================\n% pX = spm_sp('uk',x) \n% Notice the difference with 'ox' : 'ox' always returns a basis of the\n% proper siwe while this returns empty if rank is null\n\nwarning('can''t you use ox ?');\n\nswitch nargin\n\ncase 2\t\n switch lower(action), \t\t\n case {'uk'}\n varargout = { sf_uk(sX) };\n case {'uk:'}\n varargout = { sf_tol(sf_uk(sX),sX.tol) };\n end\n\ncase 3\n %- check dimensions of Y\t\n Y = varargin{3};\n if isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n if size(Y,1) ~= sf_rk(sX), error(['Dim dont match ' action]); end\n\n switch lower(action),\t\t\n case {'uk'}\n varargout = { sf_uk(sX)*Y };\n case {'uk:'}\n varargout = {sf_tol(sf_uk(sX)*Y,sX.tol)};\n end\n\notherwise\n error(['too many input argument in spm_sp ' action]);\n\nend % switch nargin\n\n\n\n\ncase {'pinvxpx', 'xpx-', 'pinvxpx:', 'xpx-:',} %- Pseudo-inv of (X'X)\n%=======================================================================\n% pXpX = spm_sp('pinvxpx',x [,Y]) \n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n\tcase {'xpx-','pinvxpx'}\n\t\tvarargout = {sf_pinvxpx(sX)};\n\tcase {'xpx-:','pinvxpx:'}\n varargout = {sf_tol(sf_pinvxpx(sX),sX.tol)};\n end %- \n\ncase 3\n %- check dimensions of Y\t\n Y = varargin{3};\n if isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;\n\n switch lower(action), \t\t\n\tcase {'xpx-','pinvxpx'}\n\t varargout = {sf_pinvxpx(sX)*Y};\n\tcase {'xpx-:','pinvxpx:'}\n varargout = {sf_tol(sf_pinvxpx(sX)*Y,sX.tol)};\n end %-\n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\n\ncase {'xpx','xpx:'} %-Computation of (X'*X)\n%=======================================================================\n% XpX = spm_sp('xpx',x [,Y])\n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n\tcase {'xpx'}\n\t\tvarargout = {sf_xpx(sX)};\n\tcase {'xpx:'}\n varargout = {sf_tol(sf_xpx(sX),sX.tol)};\n end %- \n\ncase 3\n\t%- check dimensions of Y\t\n\tY = varargin{3};\n\tif isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n\tif size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;\n\n switch lower(action), \t\t\n\tcase {'xpx'}\n\t\tvarargout = {sf_xpx(sX)*Y};\n\tcase {'xpx:'}\n varargout = {sf_tol(sf_xpx(sX)*Y,sX.tol)};\n end %-\n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\n\n\n\ncase {'cx->cu','cx->cu:'} %-coordinates in the basis of X -> basis u\n%=======================================================================\n% \n% returns cu such that sX.X*cx == sX.u*cu \n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n\tcase {'cx->cu'}\n\t\tvarargout = {sf_cxtwdcu(sX)};\n\tcase {'cx->cu:'}\n varargout = {sf_tol(sf_cxtwdcu(sX),sX.tol)};\n end %- \n\ncase 3\n\t%- check dimensions of Y\t\n\tY = varargin{3};\n\tif isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n\tif size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;\n\n switch lower(action), \t\t\n\tcase {'cx->cu'}\n\t\tvarargout = {sf_cxtwdcu(sX)*Y};\n\tcase {'cx->cu:'}\n varargout = {sf_tol(sf_cxtwdcu(sX)*Y,sX.tol)};\n end %-\n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\n\n\n\ncase {'xxp-','xxp-:','pinvxxp','pinvxxp:'} %-Pseudo-inverse of (XX')\n%=======================================================================\n% pXXp = spm_sp('pinvxxp',x [,Y])\n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n\tcase {'xxp-','pinvxxp'}\n\t\tvarargout = {sf_pinvxxp(sX)};\n\tcase {'xxp-:','pinvxxp:'}\n varargout = {sf_tol(sf_pinvxxp(sX),sX.tol)};\n end %- \n\ncase 3\n\t%- check dimensions of Y\t\n\tY = varargin{3};\n\tif isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n\tif size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;\n\n switch lower(action), \t\t\n\tcase {'xxp-','pinvxxp'}\n\t\tvarargout = {sf_pinvxxp(sX)*Y};\n\tcase {'xxp-:','pinvxxp:'}\n varargout = {sf_tol(sf_pinvxxp(sX)*Y,sX.tol)};\n end %-\n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\t\n\ncase {'xxp','xxp:'} %-Computation of (X*X')\n%=======================================================================\n% XXp = spm_sp('xxp',x)\n\n\nswitch nargin\ncase 2\t\n switch lower(action), \t\t\n\tcase {'xxp'}\n\t\tvarargout = {sf_xxp(sX)};\n\tcase {'xxp:'}\n varargout = {sf_tol(sf_xxp(sX),sX.tol)};\n end %- \n\ncase 3\n\t%- check dimensions of Y\t\n\tY = varargin{3};\n\tif isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n\tif size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;\n\n switch lower(action), \t\t\n\tcase {'xxp'}\n\t\tvarargout = {sf_xxpY(sX,Y)};\n\tcase {'xxp:'}\n varargout = {sf_tol(sf_xxpY(sX,Y),sX.tol)};\n end %-\n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\n\ncase {'^p','^p:'} %-Computation of v*(diag(s.^n))*v'\n%=======================================================================\n\nswitch nargin\ncase {2,3}\n\tif nargin==2, n = 1; else n = varargin{3}; end;\n\tif ~isnumeric(n), error('~isnumeric(n)'), end;\n\n switch lower(action), \t\t\n\tcase {'^p'}\n\t\tvarargout = {sf_jbp(sX,n)};\n\tcase {'^p:'}\n varargout = {sf_tol(sf_jbp(sX,n),sX.tol)};\n end %- \n\ncase 4\n\tn = varargin{3};\n\tif ~isnumeric(n), error('~isnumeric(n)'), end;\n\tY = varargin{4};\n\tif isempty(Y), varargout = {spm_sp(action,sX,n)}; return, end\n\tif size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;\n\n switch lower(action), \t\t\n\tcase {'^p'}\n\t\tvarargout = {sf_jbp(sX,n)*Y};\n\tcase {'^p:'}\n varargout = {sf_tol(sf_jbp(sX,n)*Y,sX.tol)};\n end %- \n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\n\n\ncase {'^','^:'} %-Computation of v*(diag(s.^n))*v'\n%=======================================================================\n\nswitch nargin\ncase {2,3}\n\tif nargin==2, n = 1; else n = varargin{3}; end;\n\tif ~isnumeric(n), error('~isnumeric(n)'), end;\n\n switch lower(action), \t\t\n\tcase {'^'}\n\t\tvarargout = {sf_jb(sX,n)};\n\tcase {'^:'}\n varargout = {sf_tol(sf_jb(sX,n),sX.tol)};\n end %- \n\ncase 4\n\tn = varargin{3};\n\tif ~isnumeric(n), error('~isnumeric(n)'), end;\n\tY = varargin{4};\n\tif isempty(Y), varargout = {spm_sp(action,sX,n)}; return, end\n\tif size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;\n\n switch lower(action), \t\t\n\tcase {'^'}\n\t\tvarargout = {sf_jbY(sX,n,Y)};\n\tcase {'^:'}\n varargout = {sf_tol(sf_jbY(sX,n,Y),sX.tol)};\n end %- \n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\n\n\ncase {'n'} %-Null space of sX\n%=======================================================================\n\nswitch nargin\ncase 2\t\n\tvarargout = {sf_n(sX)};\notherwise\n error('too many input argument in spm_sp');\nend % switch nargin\n\n\ncase {'np'} %-Null space of sX'\n%=======================================================================\n\nswitch nargin\ncase 2\t\n\tvarargout = {sf_n(sf_transp(sX))};\notherwise\n error('too many input argument in spm_sp');\nend % switch nargin\n\n\ncase {'nop', 'nop:'} %- project(or)(ion) into null space\n%=======================================================================\n%\n%\n% \n\nswitch nargin\n\ncase 2\t\n switch lower(action), \t\t\n\tcase {'nop'}\n\t\tn = sf_n(sX);\n\t\tvarargout = {n*n'};\n\tcase {'nop:'}\n\t\tn = sf_n(sX);\n\t\tvarargout = {sf_tol(n*n',sX.tol)};\n end %-\n\ncase 3\n\t%- check dimensions of Y\t\n\tY = varargin{3};\n\tif isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n\tif size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;\n\n switch lower(action), \t\t\n\tcase {'nop'}\n\t\tn = sf_n(sX);\n\t\tvarargout = {n*(n'*Y)};\n\tcase {'nop:'}\n\t\tn = sf_n(sX);\n\t\tvarargout = {sf_tol(n*(n'*Y),sX.tol)};\n end %-\n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\n\n\ncase {'nopp', 'nopp:'} %- projector(ion) into null space of X'\n%=======================================================================\n%\n%\n\nswitch nargin\n\ncase 2\t\n\tswitch lower(action), \t\t\n\tcase {'nopp'}\n\t\tvarargout = {spm_sp('nop',sf_transp(sX))};\n\tcase {'nopp:'}\n\t\tvarargout = {spm_sp('nop:',sf_transp(sX))};\n\tend %-\ncase 3\t\n\tswitch lower(action), \t\t\n\tcase {'nopp'}\n\t\tvarargout = {spm_sp('nop',sf_transp(sX),varargin{3})};\n\tcase {'nopp:'}\n\t\tvarargout = {spm_sp('nop:',sf_transp(sX),varargin{3})};\n\tend %-\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\n\ncase {'res', 'r','r:'} %-Residual formaing matrix / residuals\n%=======================================================================\n% r = spm_sp('res',sX[,Y])\n%\n%- 'res' will become obsolete : use 'r' or 'r:' instead\n%- At some stage, should be merged with 'nop'\n\n\nswitch nargin\n\ncase 2\t\n\tswitch lower(action) \n\tcase {'r','res'} \n\t\tvarargout = {sf_r(sX)};\n\tcase {'r:','res:'} \n\t\tvarargout = {sf_tol(sf_r(sX),sX.tol)};\n\tend %-\ncase 3\n\n\t%- check dimensions of Y\t\n\tY = varargin{3};\n\tif isempty(Y), varargout = {spm_sp(action,sX)}; return, end\n\tif size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;\n\t\n\tswitch lower(action) \n\tcase {'r','res'} \n\t\tvarargout = {sf_rY(sX,Y)};\n\tcase {'r:','res:'} \n\t\tvarargout = {sf_tol(sf_rY(sX,Y),sX.tol)};\n\tend %-\n\notherwise\n error('too many input argument in spm_sp');\n\nend % switch nargin\n\n\ncase {':'}\n%=======================================================================\n% spm_sp(':',sX [,Y [,tol]])\n\n%- Sets Y and tol according to arguments\n\nif nargin > 4\n\terror('too many input argument in spm_sp'); \n\nelse\n\tif nargin > 3\n\t\tif isnumeric(varargin{4}), tol = varargin{4}; \n\t\telse error('tol must be numeric'); \n\t\tend\n\telse\n\t\ttol = sX.tol;\n\tend\n\tif nargin > 2\n\t\tY = varargin{3}; %- if isempty, returns empty, end\n\telse\n\t\tY = sX.X;\t\n\tend\nend\n\nvarargout = {sf_tol(Y,tol)};\n\n\n\n\ncase {'isinsp', 'isinspp'} %- is in space or is in dual space\n%=======================================================================\n% b = spm_sp('isinsp',x,c[,tol])\n% b = spm_sp('isinspp',x,c[,tol])\n%-Check whether vectors are in row/column space of X\n\n%-Check arguments\n%-----------------------------------------------------------------------\nif nargin<3, error('insufficient arguments - action,x,c required'), end\nc = varargin{3}; %- if isempty(c), dim wont match exept for empty sp.\nif nargin<4, tol=sX.tol; else, tol = varargin{4}; end\n\n%-Compute according to case\n%-----------------------------------------------------------------------\nswitch lower(action)\n\ncase 'isinsp'\n\t%-Check dimensions\n\tif size(sX.X,1) ~= size(c,1) \n\t\twarning('Vector dim don''t match col. dim : not in space !'); \n\t\tvarargout = { 0 }; return;\n\tend\n\tvarargout = {all(all( abs(sf_op(sX)*c - c) <= tol ))};\n\ncase 'isinspp'\n\t%- check dimensions\n\tif size(sX.X,2) ~= size(c,1) \n\t\twarning('Vector dim don''t match row dim : not in space !'); \n\t\tvarargout = { 0 }; return;\n\tend\n\tvarargout = {all(all( abs(sf_opp(sX)*c - c) <= tol ))};\nend\n\n\n\n\ncase {'eachinsp', 'eachinspp'} %- each column of c in space or in dual space\n%=======================================================================\n% b = spm_sp('eachinsp',x,c[,tol])\n% b = spm_sp('eachinspp',x,c[,tol])\n%-Check whether vectors are in row/column space of X\n\n%-Check arguments\n%-----------------------------------------------------------------------\nif nargin<3, error('insufficient arguments - action,x,c required'), end\nc = varargin{3}; %- if isempty(c), dim wont match exept for empty sp.\nif nargin<4, tol=sX.tol; else, tol = varargin{4}; end\n\n%-Compute according to case\n%-----------------------------------------------------------------------\nswitch lower(action)\n\ncase 'eachinsp'\n\t%-Check dimensions\n\tif size(sX.X,1) ~= size(c,1) \n\t\twarning('Vector dim don''t match col. dim : not in space !'); \n\t\tvarargout = { 0 }; return;\n\tend\n\tvarargout = {all( abs(sf_op(sX)*c - c) <= tol )};\n\ncase 'eachinspp'\n\t%- check dimensions\n\tif size(sX.X,2) ~= size(c,1) \n\t\twarning('Vector dim don''t match row dim : not in space !'); \n\t\tvarargout = { 0 }; return;\n\tend\n\tvarargout = {all( abs(sf_opp(sX)*c - c) <= tol )};\nend\n\n\n\n\n\ncase '=='\t\t% test wether two spaces are the same\n%=======================================================================\n% b = spm_sp('==',x1,X2)\nif nargin~=3, error('too few/many input arguments - need 3');\nelse X2 = varargin{3}; end;\n\nif isempty(sX.X)\n if isempty(X2), \n warning('Both spaces empty');\n\t\tvarargout = { 1 };\n else \n warning('one space empty');\n\t\tvarargout = { 0 }; \n\tend;\n\nelse \n\tx2 = spm_sp('Set',X2);\n\tmaxtol = max(sX.tol,x2.tol);\n\tvarargout = { all( spm_sp('isinsp',sX,X2,maxtol)) & ...\n \tall( spm_sp('isinsp',x2,sX.X,maxtol) ) };\n\n\t%- I have encountered one case where the max of tol was needed.\n\nend;\n\ncase 'isspc' %-Space structure check\n%=======================================================================\n% [b,str] = spm_sp('isspc',x)\nif nargin~=2, error('too few/many input arguments - need 2'), end\n\n%-Check we've been passed a structure\nif ~isstruct(varargin{2}), varargout={0}; return, end\n\n%-Go through required field names checking their existance\n% (Get fieldnames once and compare: isfield doesn't work for multiple )\n% (fields, and repeated calls to isfield would result in unnecessary )\n% (replicate calls to fieldnames(varargin{2}). )\n\nb = 1;\nfnames = fieldnames(varargin{2});\nfor str = fieldnames(sf_create)'\n\tb = b & any(strcmp(str,fnames));\n\tif ~b, break, end\nend\nif nargout > 1, \n\tif b, str = 'ok'; else, str = 'not a space'; end;\n\tvarargout = {b,str};\nelse, varargout = {b}; end;\n\n\ncase 'issetspc' %-Is this a completed space structure?\n%=======================================================================\n% [b,e] = spm_sp('issetspc',x)\nif nargin~=2, error('too few/many input arguments - need 2'), end\nif ~spm_sp('isspc',varargin{2})\n\tvarargout = {0,'not a space structure (wrong fieldnames)'};\nelseif ~sf_isset(varargin{2})\n\t%-Basic fields aren't filled in\n\tvarargout = {0,'space not defined (use ''set'')'};\nelse\n\tvarargout = {1,'OK!'};\nend\n\ncase 'size' \t %- gives the size of sX\n%=======================================================================\n% size = spm_sp('size',x,dim)\n%\nif nargin > 3, error('too many input arguments'), end\nif nargin == 2, dim = []; else dim = varargin{3}; end\n\nif ~isempty(dim)\n switch dim\n case 1, varargout = { sf_s1(sX) };\n case 2, varargout = { sf_s2(sX) };\n otherwise, error(['unknown dimension in ' action]);\n end\nelse %- assumes want both dim\nswitch nargout\n case {0,1}\n varargout = { sf_si(sX) };\n case 2\n varargout = { sf_s1(sX), sf_s2(sX) };\n otherwise\n error(['too many output arg in ' mfilename ' ' action]);\n end\nend\n\n\notherwise\n%=======================================================================\nerror(['Invalid action (',action,')'])\n\n%=======================================================================\nend % (case lower(action))\n\n\n%=======================================================================\n%- S U B - F U N C T I O N S\n%=======================================================================\n%\n% The rule I tried to follow is that the space structure is accessed\n% only in this sub function part : any sX.whatever should be \n% prohibited elsewhere .... still a lot to clean !!! \n\n\nfunction x = sf_create\n%=======================================================================\n\nx = struct(...\n\t'X',\t[],...\t\t % Matrix\n\t'tol',\t[],...\t\t% tolerance\n\t'ds',\t[],...\t\t % vectors of singular values \n\t'u',\t[],...\t\t % u as in X = u*diag(ds)*v'\n\t'v',\t[], ...\t\t % v as in X = u*diag(ds)*v'\n\t'rk',\t[],...\t\t % rank\n\t'oP', \t[],...\t\t% orthogonal projector on X\n\t'oPp',\t[],...\t\t% orthogonal projector on X'\n\t'ups',\t[],...\t\t% space in which this one is embeded\n\t'sus',\t[]);\t\t % subspace \n\n\n\nfunction x = sf_set(X)\n%=======================================================================\n\nx = sf_create;\nx.X = X;\n\n%-- Compute the svd with svd(X,0) : find all the singular values of x.X\n%-- SVD(FULL(A)) will usually perform better than SVDS(A,MIN(SIZE(A)))\n\n%- if more column that lines, performs on X'\n\nif size(X,1) < size(X,2)\n\t[x.v, s, x.u] = svd(full(X'),0);\nelse \n\t[x.u, s, x.v] = svd(full(X),0);\nend\n\nx.ds = diag(s); clear s;\n\n%-- compute the tolerance\nx.tol = max(size(x.X))*max(abs(x.ds))*eps;\n\n%-- compute the rank\nx.rk = sum(x.ds > x.tol);\n\n\nfunction x = sf_transp(x)\n%=======================================================================\n%\n%- Tranpspose the space : note that tmp is not touched, therefore\n%- only contains the address, no duplication of data is performed.\n\nx.X \t= x.X';\n\ntmp \t= x.v;\nx.v \t= x.u;\nx.u \t= tmp;\n\ntmp \t= x.oP;\nx.oP \t= x.oPp;\nx.oPp = tmp;\nclear tmp;\n\n\nfunction b = sf_isset(x)\n%=======================================================================\nb = ~(\tisempty(x.X) \t|...\n\tisempty(x.u) \t|...\n\tisempty(x.v) \t|...\n\tisempty(x.ds)\t|...\n\tisempty(x.tol)\t|...\n\tisempty(x.rk)\t);\n\n\n\nfunction s1 = sf_s1(x)\n%=======================================================================\ns1 = size(x.X,1);\n\nfunction s2 = sf_s2(x)\n%=======================================================================\ns2 = size(x.X,2);\n\nfunction si = sf_si(x)\n%=======================================================================\nsi = size(x.X);\n\nfunction r = sf_rk(x)\n%=======================================================================\nr = x.rk;\n\nfunction uk = sf_uk(x)\n%=======================================================================\nuk = x.u(:,1:sf_rk(x));\n\nfunction vk = sf_vk(x)\n%=======================================================================\nvk = x.v(:,1:sf_rk(x));\n\nfunction sk = sf_sk(x)\n%=======================================================================\nsk = x.ds(1:sf_rk(x));\n\nfunction t = sf_t(x)\n%=======================================================================\nt = x.tol;\n\nfunction x = sf_tol(x,t)\n%=======================================================================\nx(abs(x) < t) = 0;\n\n\nfunction op = sf_op(sX)\n%=======================================================================\nif sX.rk > 0 \n\top = sX.u(:,[1:sX.rk])*sX.u(:,[1:sX.rk])';\nelse \n\top = zeros( size(sX.X,1) ); \nend;\n\n%!!!! to implement : a clever version of sf_opY (see sf_rY)\n\n\nfunction opp = sf_opp(sX)\n%=======================================================================\nif sX.rk > 0 \n\topp = sX.v(:,[1:sX.rk])*sX.v(:,[1:sX.rk])';\nelse \n\topp = zeros( size(sX.X,2) ); \nend;\n\n%!!!! to implement : a clever version of sf_oppY (see sf_rY)\n\n\nfunction px = sf_pinv(sX)\n%=======================================================================\nr = sX.rk;\nif r > 0 \n\tpx = sX.v(:,1:r)*diag( ones(r,1)./sX.ds(1:r) )*sX.u(:,1:r)';\nelse \n\tpx = zeros(size(sX.X,2),size(sX.X,1));\nend\n\nfunction px = sf_pinvxp(sX)\n%=======================================================================\nr = sX.rk;\nif r > 0 \n\tpx = sX.u(:,1:r)*diag( ones(r,1)./sX.ds(1:r) )*sX.v(:,1:r)';\nelse \n\tpx = zeros(size(sX.X));\nend\n\nfunction px = sf_pinvxpx(sX)\n%=======================================================================\nr = sX.rk;\nif r > 0 \n\tpx = sX.v(:,1:r)*diag( sX.ds(1:r).^(-2) )*sX.v(:,1:r)';\nelse\n\tpx = zeros(size(sX.X,2));\nend\n\nfunction px = sf_jbp(sX,n)\n%=======================================================================\nr = sX.rk;\nif r > 0 \n\tpx = sX.v(:,1:r)*diag( sX.ds(1:r).^(n) )*sX.v(:,1:r)';\nelse\n\tpx = zeros(size(sX.X,2));\nend\n\nfunction x = sf_jb(sX,n)\n%=======================================================================\nr = sX.rk;\nif r > 0 \n\tx = sX.u(:,1:r)*diag( sX.ds(1:r).^(n) )*sX.u(:,1:r)';\nelse\n\tx = zeros(size(sX.X,1));\nend\n\nfunction y = sf_jbY(sX,n,Y)\n%=======================================================================\nr = sX.rk;\nif r > 0 \n\ty = ( sX.u(:,1:r)*diag(sX.ds(1:r).^n) )*(sX.u(:,1:r)'*Y);\nelse\n\ty = zeros(size(sX.X,1),size(Y,2));\nend\n%!!!! to implement : a clever version of sf_jbY (see sf_rY)\n\n\n\nfunction x = sf_cxtwdcu(sX) \n%=======================================================================\n%- coordinates in sX.X -> coordinates in sX.u(:,1:rk)\n\nx = diag(sX.ds)*sX.v';\n\n\nfunction x = sf_cukpinvxp(sX) \n%=======================================================================\n%- coordinates of pinv(sX.X') in the basis sX.u(:,1:rk)\n\nr = sX.rk;\nif r > 0 \n\tx = diag( ones(r,1)./sX.ds(1:r) )*sX.v(:,1:r)';\nelse \n\tx = zeros( size(sX.X,2) );\nend\n\nfunction x = sf_cukx(sX) \n%=======================================================================\n%- coordinates of sX.X in the basis sX.u(:,1:rk)\n\nr = sX.rk;\nif r > 0 \n\tx = diag( sX.ds(1:r) )*sX.v(:,1:r)';\nelse \n\tx = zeros( size(sX.X,2) );\nend\n\n\nfunction x = sf_xpx(sX)\n%=======================================================================\nr = sX.rk;\nif r > 0 \n\tx = sX.v(:,1:r)*diag( sX.ds(1:r).^2 )*sX.v(:,1:r)';\nelse\n\tx = zeros(size(sX.X,2));\nend\n\nfunction x = sf_xxp(sX)\n%=======================================================================\nr = sX.rk;\nif r > 0 \n\tx = sX.u(:,1:r)*diag( sX.ds(1:r).^2 )*sX.u(:,1:r)';\nelse\n\tx = zeros(size(sX.X,1));\nend\n\nfunction x = sf_xxpY(sX,Y)\n%=======================================================================\nr = sX.rk;\nif r > 0 \n\tx = sX.u(:,1:r)*diag( sX.ds(1:r).^2 )*(sX.u(:,1:r)'*Y);\nelse\n\tx = zeros(size(sX.X,1),size(Y,2));\nend\n\nfunction x = sf_pinvxxp(sX)\n%=======================================================================\nr = sX.rk;\nif r > 0 \n\tx = sX.u(:,1:r)*diag( sX.ds(1:r).^(-2) )*sX.u(:,1:r)';\nelse\n\tx = zeros(size(sX.X,1));\nend\n\nfunction n = sf_n(sX)\n%=======================================================================\n% if the null space is in sX.v, returns it\n% otherwise, performs Gramm Schmidt orthogonalisation.\n% \n%\nr = sX.rk;\n[q p]= size(sX.X);\nif r > 0\n\tif q >= p %- the null space is entirely in v\n\t\tif r == p, n = zeros(p,1); else, n = sX.v(:,r+1:p); end\n\telse %- only part of n is in v: same as computing the null sp of sX'\n\n\t\tn = null(sX.X); \n%----- BUG !!!! in that part ----------------------------------------\n%-\t\tv = zeros(p,p-q); j = 1; i = 1; z = zeros(p,1);\n%-\t\twhile i <= p\n%-\t\t\to = z; o(i) = 1; vpoi = [sX.v(i,:) v(i,1:j-1)]';\n%-\t\t\to = sf_tol(o - [sX.v v(:,1:j-1)]*vpoi,sX.tol);\n%-\t\t\tif any(o), v(:,j) = o/((o'*o)^(1/2)); j = j + 1; end;\n%-\t\t\ti = i + 1; %- if i>p, error('gramm shmidt error'); end;\n%-\t\tend\n%-\t\tn = [sX.v(:,r+1:q) v];\n%--------------------------------------------------------------------\n\tend\nelse \n\tn = eye(p);\nend\n\n\n\nfunction r = sf_r(sX)\n%=======================================================================\n%-\n%- returns the residual forming matrix for the space sX\n%- for internal use. doesn't Check whether oP exist.\n\nr = eye(size(sX.X,1)) - sf_op(sX) ;\n\n\nfunction Y = sf_rY(sX,Y)\n%=======================================================================\n% r = spm_sp('r',sX[,Y])\n% \n%- tries to minimise the computation by looking whether we should do\n%- I - u*(u'*Y) or n*(n'*Y) as in 'nop'\n\nr = sX.rk;\n[q p]= size(sX.X);\n\nif r > 0 %- else returns the input;\n\t\n\tif r < q-r %- we better do I - u*u' \n\t\tY = Y - sX.u(:,[1:r])*(sX.u(:,[1:r])'*Y); % warning('route1');\n\telse\n\t\t%- is it worth computing the n ortho basis ? \n\t\tif size(Y,2) < 5*q\n\t\t\tY = sf_r(sX)*Y; % warning('route2');\n\t\telse \n\t\t\tn = sf_n(sf_transp(sX)); % warning('route3');\n\t\t\tY = n*(n'*Y);\n\t\tend\n\tend\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_dicom.m", "ext": ".m", "path": "spm5-master/spm_config_dicom.m", "size": 5010, "source_encoding": "utf_8", "md5": "a78fea091fd42391c4ba7d36f53f0289", "text": "function opts = spm_config_dicom\n% Configuration file for dicom import jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_dicom.m 2300 2008-10-06 11:16:30Z guillaume $\n\n\n%_______________________________________________________________________\n\ndata.type = 'files';\ndata.name = 'DICOM files';\ndata.tag = 'data';\ndata.filter = '.*';\ndata.num = Inf;\ndata.help = {'Select the DICOM files to convert.'};\n\noutdir.type = 'files';\noutdir.name = 'Output directory';\noutdir.tag = 'outdir';\noutdir.filter = 'dir';\noutdir.num = 1;\noutdir.val = {''};\noutdir.help = {[...\n'Select a directory where files are written. '...\n'Default is current directory.']};\n\nroot.type = 'menu';\nroot.name = 'Directory structure for converted files';\nroot.tag = 'root';\nroot.labels = {'Output directory: ./', ...\n 'Output directory: ./', ...\n 'Output directory: .//', ...\n 'Output directory: ./', ...\n 'No directory hierarchy'};\nroot.values = {'date_time',...\n 'patid', 'patid_date', 'patname','flat'};\nroot.def = 'util.dicom.root';\nroot.help = {['Choose root directory of converted file tree. The options ' ...\n 'are:'], '',...\n ['* Output directory: ./: ' ...\n 'Automatically determine the project name and try to ' ...\n 'convert into the output directory, starting with '... \n 'a StudyDate-StudyTime subdirectory. This option is useful if automatic '... \n 'project recognition fails and one wants to convert data into '...\n 'a project directory.'], '',...\n ['* Output directory: ./: ' ...\n 'Convert into the output directory, starting with '... \n 'a PatientID subdirectory.'], '',...\n ['* Output directory: ./: ' ...\n 'Convert into the output directory, starting with '... \n 'a PatientName subdirectory.'],...\n ['* No directory hierarchy: Convert all files into the output ' ...\n 'directory, without sequence/series subdirectories']};\n\nformat.type = 'menu';\nformat.name = 'Output image format';\nformat.tag = 'format';\nformat.labels = {'Two file (img+hdr) NIfTI', 'Single file (nii) NIfTI'};\nformat.values = {'img', 'nii'};\nformat.val = {'nii'};\nformat.help = {['DICOM conversion can create separate img and hdr files ' ...\n 'or combine them in one file. The single file option will ' ...\n 'help you save space on your hard disk, but may be ' ...\n 'incompatible with programs that are not NIfTI-aware.'],...\n ['In any case, only 3D image files will be produced.']};\n\nicedims.type = 'menu';\nicedims.name = 'Use ICEDims in filename';\nicedims.tag = 'icedims';\nicedims.labels = {'No','Yes'};\nicedims.values = {0, 1};\nicedims.val = {0};\nicedims.help = {['If image sorting fails, one can try using the additional ' ...\n 'SIEMENS ICEDims information to create unique filenames. ' ...\n 'Use this only if there would be multiple volumes with '...\n 'exactly the same file names.']};\n\nconvopts.type = 'branch';\nconvopts.name = 'Conversion options';\nconvopts.tag = 'convopts';\nconvopts.val = {format,icedims};\n\nopts.type = 'branch';\nopts.name = 'DICOM Import';\nopts.tag = 'dicom';\nopts.val = {data,root,outdir,convopts};\nopts.prog = @convert_dicom;\nopts.help = {[...\n'DICOM Conversion. Most scanners produce data in DICOM format. '...\n'This routine attempts to convert DICOM files into SPM compatible '...\n'image volumes, which are written into the current directory by '...\n'default. Note that not all flavours of DICOM can be handled, as '...\n'DICOM is a very complicated format, and some scanner manufacturers '...\n'use their own fields, which are not in the official documentation '...\n'at http://medical.nema.org/']};\n\n% add defaults, if not already set\nglobal defaults\nif isfield(defaults,'util')\n if isfield(defaults.util,'dicom')\n return;\n end;\nend;\ndefaults.util.dicom.root = 'flat';\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction convert_dicom(job)\n\nwd = pwd;\ntry\n if ~isempty(job.outdir{:})\n cd(job.outdir{:});\n fprintf(' Changing directory to: %s\\n', job.outdir{:});\n end\ncatch\n error('Failed to change directory. Aborting DICOM import.');\nend\n\nif job.convopts.icedims\n root_dir = ['ice' job.root];\nelse\n root_dir = job.root;\nend;\n\nhdr = spm_dicom_headers(strvcat(job.data), true);\nspm_dicom_convert(hdr,'all',root_dir,job.convopts.format);\n\nif ~isempty(job.outdir)\n fprintf(' Changing back to directory: %s\\n', wd);\n cd(wd);\nend\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_dicom_essentials.m", "ext": ".m", "path": "spm5-master/spm_dicom_essentials.m", "size": 2998, "source_encoding": "utf_8", "md5": "73532b1b79cbf320fa7ba72709659e78", "text": "function hdr1 = spm_dicom_essentials(hdr0)\n% Remove unused fields from DICOM header\n% FORMAT hdr1 = spm_dicom_essentials(hdr0)\n% hdr0 - original DICOM header\n% hdr1 - Stripped down DICOM header.\n%\n% With lots of DICOM files, the size of all the headers can become too\n% big for all the fields to be saved. The idea here is to strip down\n% the headers to their essentials.\n%\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_dicom_essentials.m 2300 2008-10-06 11:16:30Z guillaume $\n\nused_fields = {...\n 'AcquisitionDate',...\n 'AcquisitionNumber',...\n 'AcquisitionTime',...\n 'BitsAllocated',...\n 'BitsStored',...\n 'CSAImageHeaderInfo',...\n 'Columns',...\n 'EchoNumbers',...\n 'EchoTime',...\n 'Filename',...\n 'FlipAngle',...\n 'HighBit',...\n 'ImageOrientationPatient',...\n 'ImagePositionPatient',...\n 'ImageType',...\n 'InstanceNumber',...\n 'MRAcquisitionType',...\n 'MagneticFieldStrength',...\n 'Modality',...\n 'PatientID',...\n 'PatientsName',...\n 'PixelRepresentation',...\n 'PixelSpacing',...\n 'Private_0029_1210',...\n 'ProtocolName',...\n 'RepetitionTime',...\n 'RescaleIntercept',...\n 'RescaleSlope',...\n 'Rows',...\n 'SOPClassUID',...\n 'SamplesperPixel',...\n 'ScanningSequence',...\n 'SequenceName',...\n 'SeriesDescription',...\n 'SeriesInstanceUID',...\n 'SeriesNumber',...\n 'SliceNormalVector',...\n 'SliceThickness',...\n 'SpacingBetweenSlices',...\n 'StartOfPixelData',...\n 'StudyDate',...\n 'StudyTime',...\n 'TransferSyntaxUID',...\n 'VROfPixelData'};\n\nfnames = fieldnames(hdr0);\nfor i=1:numel(used_fields),\n if any(strmatch(used_fields{i},fnames,'exact')),\n hdr1.(used_fields{i}) = hdr0.(used_fields{i});\n end\nend\n\nif isfield(hdr1,'Private_0029_1210'),\n Private_0029_1210_fields = {...\n 'Columns',...\n 'Rows',...\n 'ImageOrientationPatient',...\n 'ImagePositionPatient',...\n 'SliceThickness',...\n 'PixelSpacing'};\n hdr1.Private_0029_1210 = ...\n getfields(hdr1.Private_0029_1210,...\n Private_0029_1210_fields);\nend\n \nif isfield(hdr1,'CSAImageHeaderInfo'), \n CSAImageHeaderInfo_fields = {...\n 'SliceNormalVector',...\n 'NumberOfImagesInMosaic',...\n 'AcquisitionMatrixText',...\n 'ICE_Dims'};\n hdr1.CSAImageHeaderInfo = ...\n getfields(hdr1.CSAImageHeaderInfo,...\n CSAImageHeaderInfo_fields);\nend\n\nif isfield(hdr1,'CSASeriesHeaderInfo'), \n CSASeriesHeaderInfo_fields = {};\n hdr1.CSASeriesHeaderInfo = ...\n getfields(hdr1.CSASeriesHeaderInfo,...\n CSASeriesHeaderInfo_fields); \nend\n\n\nfunction str1 = getfields(str0,names)\nstr1 = [];\nfor i=1:numel(names)\n for j=1:numel(str0),\n if strcmp(str0(j).name,names{i})\n str1 = [str1,str0(j)];\n end\n end\nend\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_factorial_design.m", "ext": ".m", "path": "spm5-master/spm_config_factorial_design.m", "size": 68674, "source_encoding": "utf_8", "md5": "7f82700d08ffaff7cd9e0dabd4c20de9", "text": "function conf = spm_config_factorial_design\n% Configuration file for specification of factorial designs\n%\n% This function configures the design matrix (describing the general\n% linear model), data specification, and other parameters necessary for\n% the statistical analysis. These parameters are saved in a\n% configuration file (SPM.mat) in the current directory, and are\n% passed on to spm_spm.m (via the Estimate button) which estimates the design.\n% Inference on these estimated parameters is then handled by the SPM\n% results section.\n%\n% This function comprises two parts. The first defines\n% the user interface and the second sets up the necessary SPM structures.\n% The second part has been largely cannibalised from spm_spm_ui.m which\n% we have retained for developmental continuity.\n%\n% It has in common with spm_spm_ui.m its use of the I factor matrix,\n% the H,C,B,G design matrix partitions, the sF,sCFI,CFIforms,sCC,CCforms,\n% sGXcalc,sGloNorm,sGMsca option definition variables and use of the\n% functions spm_DesMtx.m, spm_meanby.m and spm_non_sphericity.m.\n%\n% It departs from spm_spm_ui.m in that it does not use the design\n% definition data structure D. Also, it uses the new SPM.factor field,\n% which for the case of full factorial designs, is used to automatically\n% generate contrasts testing for main effects and interactions.\n%\n% This function departs from spm_spm_ui.m in that it does not provide\n% the same menu of design options (these were hardcoded in D). Instead it\n% provides a number of options for simple designs (1) One-sample t-test,\n% (2) Two-sample t-test, (3) Paired t-test and (4) Multiple regression.\n% Two facilities are provided for specifying more complicated designs\n% (5) Full-factorial and (6) Flexible-factorial. These should be able to\n% specify all design options (and more) that were available in SPM2.\n% For each of these design types one can additionally specify regressors using the\n% `covariates' option.\n%\n% Options (5) and (6) differ in the\n% efficiency (eg. number of key strokes/button presses) with which a given\n% design can be specified. For example, one-way ANOVAs can be specified\n% using either option, but (5) is usually more efficient.\n%\n% Full-factorial designs\n% ______________________\n%\n% This option is best used when you wish to test for all\n% main effects and interactions in one-way, two-way or three-way ANOVAs.\n%\n% Design specification proceeds in 2 stages. Firstly, by creating new\n% factors and specifying the\n% number of levels and name for each. Nonsphericity, ANOVA-by-factor (for PET data)\n% and\n% scaling options (for PET data) can also be specified at this stage. Secondly,\n% scans are assigned separately to each cell. This accomodates unbalanced designs.\n%\n% For example, if you wish to test for a main effect in the population\n% from which your subjects are drawn\n% and have modelled that effect at the first level using K basis functions\n% (eg. K=3 informed basis functions) you can use a one-way ANOVA with K-levels.\n% Create a single factor with K levels and then assign the data to each\n% cell eg. canonical, temporal derivative and dispersion derivative cells,\n% where each cell is assigned scans from multiple subjects.\n%\n% SPM will automatically generate the contrasts necessary to test for all\n% main effects and interactions\n%\n% Flexible-factorial designs\n% __________________________\n%\n% In this option the design matrix is created a block at a time. You can\n% decide whether you wish each block to be a main effect or a (two-way)\n% interaction.\n%\n% This option is best used for one-way, two-way or\n% three-way ANOVAs but where you do not wish to test for all possible\n% main effects and interactions. This is perhaps most useful for PET\n% where there is usually not enough data to test for all possible\n% effects. Or for 3-way ANOVAs where you do not wish to test for all\n% of the two-way interactions. A typical example here would be a\n% group-by-drug-by-task analysis where, perhaps, only (i) group-by-drug or\n% (ii) group-by-task interactions are of interest. In this case it is only\n% necessary to have two-blocks in the design matrix - one for each\n% interaction. The three-way interaction can then be tested for using a\n% contrast that computes the difference between (i) and (ii).\n%\n% Design specification then proceeds in 3 stages. Firstly, factors\n% are created and names specified for each. Nonsphericity, ANOVA-by-factor and\n% scaling options can also be specified at this stage.\n%\n% Secondly, a list of\n% scans is produced along with a factor matrix, I. This is an nscan x 4 matrix\n% of factor level indicators (see xX.I below). The first factor must be\n% 'replication' but the other factors can be anything. Specification of I and\n% the scan list can be achieved in\n% one of two ways (a) the 'Specify All' option allows I\n% to be typed in at the user interface or (more likely) loaded in from the matlab\n% workspace. All of the scans are then selected in one go. (b) the\n% 'Subjects' option allows you to enter scans a subject at a time. The\n% corresponding experimental conditions (ie. levels of factors) are entered\n% at the same time. SPM will then create the factor matrix I. This style of\n% interface is similar to that available in SPM2.\n%\n% Thirdly, the design matrix is built up a block at a time. Each block\n% can be a main effect or a (two-way) interaction.\n%\n%\n% ----------------------------------------------------------------------\n%\n% Variables saved in the SPM stucture\n%\n% xY.VY - nScan x 1 struct array of memory mapped images\n% (see spm_vol for definition of the map structure)\n% xX - structure describing design matrix\n% xX.I - nScan x 4 matrix of factor level indicators\n% I(n,i) is the level of factor i corresponding to image n\n% xX.sF - 1x4 cellstr containing the names of the four factors\n% xX.sF{i} is the name of factor i\n% xX.X - design matrix\n% xX.xVi - correlation constraints for non-spericity correction\n% xX.iH - vector of H partition (condition effects) indices,\n% identifying columns of X correspoding to H\n% xX.iC - vector of C partition (covariates of interest) indices\n% xX.iB - vector of B partition (block effects) indices\n% xX.iG - vector of G partition (nuisance variables) indices\n% xX.name - p x 1 cellstr of effect names corresponding to columns\n% of the design matrix\n%\n% xC - structure array of covariate details\n% xC(i).rc - raw (as entered) i-th covariate\n% xC(i).rcname - name of this covariate (string)\n% xC(i).c - covariate as appears in design matrix (after any scaling,\n% centering of interactions)\n% xC(i).cname - cellstr containing names for effects corresponding to\n% columns of xC(i).c\n% xC(i).iCC - covariate centering option\n% xC(i).iCFI - covariate by factor interaction option\n% xC(i).type - covariate type: 1=interest, 2=nuisance, 3=global\n% xC(i).cols - columns of design matrix corresponding to xC(i).c\n% xC(i).descrip - cellstr containing a description of the covariate\n%\n% xGX - structure describing global options and values\n% xGX.iGXcalc - global calculation option used\n% xGX.sGXcalc - string describing global calculation used\n% xGX.rg - raw globals (before scaling and such like)\n% xGX.iGMsca - grand mean scaling option\n% xGX.sGMsca - string describing grand mean scaling\n% xGX.GM - value for grand mean (/proportional) scaling\n% xGX.gSF - global scaling factor (applied to xGX.rg)\n% xGX.iGC - global covariate centering option\n% xGX.sGC - string describing global covariate centering option\n% xGX.gc - center for global covariate\n% xGX.iGloNorm - Global normalisation option\n% xGX.sGloNorm - string describing global normalisation option\n%\n% xM - structure describing masking options\n% xM.T - Threshold masking value (-Inf=>None,\n% real=>absolute, complex=>proportional (i.e. times global) )\n% xM.TH - nScan x 1 vector of analysis thresholds, one per image\n% xM.I - Implicit masking (0=>none, 1=>implicit zero/NaN mask)\n% xM.VM - struct array of explicit mask images\n% (empty if no explicit masks)\n% xM.xs - structure describing masking options\n% (format is same as for xsDes described below)\n%\n% xsDes - structure of strings describing the design:\n% Fieldnames are essentially topic strings (use \"_\"'s for\n% spaces), and the field values should be strings or cellstr's\n% of information regarding that topic. spm_DesRep.m\n% uses this structure to produce a printed description\n% of the design, displaying the fieldnames (with \"_\"'s\n% converted to spaces) in bold as topics, with\n% the corresponding text to the right%\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Will Penny\n% $Id: spm_config_factorial_design.m 1601 2008-05-12 14:11:02Z guillaume $\n\n% Define inline types.\n%-----------------------------------------------------------------------\n\nentry = inline(['struct(''type'',''entry'',''name'',name,'...\n '''tag'',tag,''strtype'',strtype,''num'',num,''help'',hlp)'],...\n 'name','tag','strtype','num','hlp');\n\nfiles = inline(['struct(''type'',''files'',''name'',name,'...\n '''tag'',tag,''filter'',fltr,''num'',num,''help'',hlp)'],...\n 'name','tag','fltr','num','hlp');\n\nmnu = inline(['struct(''type'',''menu'',''name'',name,'...\n '''tag'',tag,''labels'',{labels},''values'',{values},''help'',hlp)'],...\n 'name','tag','labels','values','hlp');\n\nbranch = inline(['struct(''type'',''branch'',''name'',name,'...\n '''tag'',tag,''val'',{val},''help'',hlp)'],...\n 'name','tag','val','hlp');\n\nrepeat = inline(['struct(''type'',''repeat'',''name'',name,'...\n '''tag'',tag,''values'',{values},''help'',hlp)'],...\n 'name','tag','values','hlp');\n\nchoice = inline(['struct(''type'',''choice'',''name'',name,'...\n '''tag'',tag,''values'',{values},''help'',hlp)'],...\n 'name','tag','values','hlp');\n\n%-----------------------------------------------------------------------\n\nsp_text = [' ',...\n ' '];\n\n%-------------------------------------------------------------------------\n% Covariates for general use\n\niCFI = mnu('Interactions','iCFI',{'None','With Factor 1',...\n 'With Factor 2','With Factor 3'},{1,2,3,4},'');\niCFI.val={1};\np1 = ['For each covariate you have defined, there is an opportunity to ',...\n 'create an additional regressor that is the interaction between the ',...\n 'covariate and a chosen experimental factor. '];\niCFI.help={p1,sp_text};\n\niCC = mnu('Centering','iCC',{'Overall mean','Factor 1 mean',...\n 'Factor 2 mean','Factor 3 mean','No centering',...\n 'User specified value','As implied by ANCOVA',...\n 'GM'},{1,2,3,4,5,6,7,8},'');\niCC.val={1};\np1 = ['The appropriate centering option is usually the one that ',...\n 'corresponds to the interaction chosen, and ensures that main ',...\n 'effects of the interacting factor aren''t affected by the covariate. ',...\n 'You are advised to choose this option, unless you have other ',...\n 'modelling considerations. '];\niCC.help={p1,sp_text};\n\ncname = entry('Name','cname','s', [1 Inf],'Name of covariate');\n\nc = entry('Vector','c','e',[Inf 1],'Vector of covariate values');\n\ncov = branch('Covariate','cov',{c,cname,iCFI,iCC},'Covariate');\n\ncov.help = {'Add a new covariate to your experimental design'};\n\ncovs = repeat('Covariates','covariates',{cov},'');\np1 = ['This option allows for the specification of covariates and ',...\n 'nuisance variables. Unlike SPM94/5/6, where the design was ',...\n 'partitioned into effects of interest and nuisance effects ',...\n 'for the computation of adjusted data and the F-statistic ',...\n '(which was used to thresh out voxels where there appeared to ',...\n 'be no effects of interest), SPM5 does not partition the design ',...\n 'in this way. The only remaining distinction between effects of ',...\n 'interest (including covariates) and nuisance effects is their ',...\n 'location in the design matrix, which we have retained for ',...\n 'continuity. Pre-specified design matrix partitions can be entered. '];\n\ncovs.help={p1,sp_text};\n\n%-------------------------------------------------------------------------\n% Covariates for multiple regression\n\nmiCC = mnu('Centering','iCC',{'Overall mean','No centering'},...\n {1,5},'');\nmiCC.val= {1};\n\nmcov = branch('Covariate','mcov',{c,cname,miCC},'Covariate');\nmcov.help = {'Add a new covariate to your experimental design'};\n\nmcovs = repeat('Covariates','covariates',{mcov},'Covariates');\n\nincint = mnu('Intercept','incint',{'Include Intercept','Omit Intercept'},{1,0},'');\nincint.val = {1};\np1=['By default, an intercept is always added to the model. If the ',...\n 'covariates supplied by the user include a constant effect, the ',...\n 'intercept may be omitted.'];\nincint.help = {p1,sp_text};\n\n%-----------------------------------------------------------------------\n% Specify names of factors, numbers of levels and statistical dependencies\n\nname = entry('Name','name','s',[1 Inf],'');\nname.val = {'Covariate'};\np1=['Enter name of covariate eg. reaction time'];\nname.help={p1};\n\nval = entry('Value','val','e',[Inf 1],'');\nval.help={['Enter the vector of covariate values']};\n\nvariance = mnu('Variance','variance',{'Equal','Unequal'},{0,1},'');\nvariance.val={1};\np1=['By default, the measurements in each level are assumed to have unequal variance. '];\np2=['This violates the assumption of ''sphericity'' and is therefore an example of ',...\n '''non-sphericity''.'];\np3=['This can occur, for example, in a 2nd-level analysis of variance, one ',...\n 'contrast may be scaled differently from another. Another example would ',...\n 'be the comparison of qualitatively different dependent variables ',...\n '(e.g. normals vs. patients). Different variances ',...\n '(heteroscedasticy) induce different error covariance components that ',...\n 'are estimated using restricted maximum likelihood (see below).'];\np4=['Restricted Maximum Likelihood (REML): The ensuing covariance components ',...\n 'will be estimated using ReML in spm_spm (assuming the same for all ',...\n 'responsive voxels) and used to adjust the ',...\n 'statistics and degrees of freedom during inference. By default spm_spm ',...\n 'will use weighted least squares to produce Gauss-Markov or Maximum ',...\n 'likelihood estimators using the non-sphericity structure specified at this ',...\n 'stage. The components will be found in SPM.xVi and enter the estimation ',...\n 'procedure exactly as the serial correlations in fMRI models.'];\nvariance.help = {p1,sp_text,p2,sp_text,p3,sp_text,p4,sp_text};\n\ndept = mnu('Independence','dept',{'Yes','No'},{0,1},'');\ndept.val={0};\np1=['By default, the measurements are assumed to be independent between levels. '];\np2=['If you change this option to allow for dependencies, this will violate ',...\n 'the assumption of sphericity. It would therefore be an example ',...\n 'of non-sphericity. One such example would be where you had repeated ',...\n 'measurements from the same subjects - it may then be the case that, over ',...\n 'subjects, measure 1 is correlated to measure 2. '];\n\ndept.help = {p1,sp_text,p2,sp_text,p4,sp_text};\n\nfname.type = 'entry';\nfname.name = 'Name';\nfname.tag = 'name';\nfname.strtype = 's';\nfname.num = [1 1];\nfname.help = {'Name of factor, eg. ''Repetition'' '};\n\nlevels = entry('Levels','levels','e',[Inf 1],'');\np1=['Enter number of levels for this factor, eg. 2'];\nlevels.help ={p1};\n\ngmsca = mnu('Grand mean scaling','gmsca',...\n {'No','Yes'},{0,1},'');\ngmsca.val={0};\np0=['This option is only used for PET data.'];\n\np1=['Selecting YES will specify ''grand mean scaling by factor'' which could ',...\n 'be eg. ''grand mean scaling by subject'' if the factor is ''subject''. '];\n\np2 =['Since differences between subjects may be due to gain and sensitivity ',...\n 'effects, AnCova by subject could be combined with \"grand mean scaling ',...\n 'by subject\" to obtain a combination of between subject proportional ',...\n 'scaling and within subject AnCova. '];\ngmsca.help={p0,sp_text,p1,sp_text,p2,sp_text};\n\nancova = mnu('ANCOVA','ancova',...\n {'No','Yes'},{0,1},'');\nancova.val={0};\n\np1=['Selecting YES will specify ''ANCOVA-by-factor'' regressors. ',...\n 'This includes eg. ''Ancova by subject'' or ''Ancova by effect''. ',...\n 'These options allow eg. different subjects ',...\n 'to have different relationships between local and global measurements. '];\nancova.help={p0,sp_text,p1,sp_text};\n\nfactor.type = 'branch';\nfactor.name = 'Factor';\nfactor.tag = 'fact';\nfactor.val = {fname,levels,dept,variance,gmsca,ancova};\nfactor.help = {'Add a new factor to your experimental design'};\n\nfactors.type = 'repeat';\nfactors.name = 'Factors';\nfactors.tag = 'factors';\nfactors.values = {factor};\nfactors.num = [1 Inf];\np1 = ['Specify your design a factor at a time. '];\nfactors.help ={p1,sp_text};\n\n%-------------------------------------------------------------------------\n% Associate each cell in factorial design with a list of images\n\nscans = files('Scans','scans','image',[1 Inf],'Select scans');\nscans.help = {[...\n 'Select the images for this cell. They must all have the same ',...\n 'image dimensions, orientation, voxel size etc.']};\n\nlevels = entry('Levels','levels','e',[Inf 1],'');\np1=['Enter a vector or scalar that specifies which cell in the factorial ',...\n 'design these images belong to. The length of this vector should '...\n 'correspond to the number of factors in the design'];\np2=['For example, length 2 vectors should be used for two-factor designs ',...\n 'eg. the vector [2 3] specifies the cell corresponding to the 2nd-level of the first ',...\n 'factor and the 3rd level of the 2nd factor.'];\nlevels.help ={p1,sp_text,p2,sp_text};\n\nicell.type = 'branch';\nicell.name = 'Cell';\nicell.tag = 'icell';\nicell.val = {levels,scans};\nicell.help = {'Enter data for a cell in your design'};\n\ncells.type = 'repeat';\ncells.name = 'Specify cells';\ncells.tag = 'cells';\ncells.values = {icell};\ncells.num = [1 Inf];\np1 = ['Enter the scans a cell at a time'];\ncells.help={p1,sp_text};\n\n%-------------------------------------------------------------------------\n% Create a design block-by-block\n\nfac.type = 'branch';\nfac.name = 'Factor';\nfac.tag = 'fac';\nfac.val = {fname,dept,variance,gmsca,ancova};\np1=['Add a new factor to your design.'];\np2=['If you are using the ''Subjects'' option to specify your scans ',...\n 'and conditions, you may wish to make use of the following facility. ',...\n 'There are two reserved words for the names of factors. These are ',...\n '''subject'' and ''repl'' (standing for replication). If you use these ',...\n 'factor names then SPM can automatically create replication and/or ',...\n 'subject factors without you having to type in an extra entry in the ',...\n 'condition vector.'];\np3=['For example, if you wish to model Subject and Task effects (two factors), ',...\n 'under Subjects->Subject->Conditions you can type in simply ',...\n '[1 2 1 2] to specify eg. just the ''Task'' factor level. You do not need to ',...\n 'eg. for the 4th subject enter the matrix [1 4; 2 4; 1 4; 2 4]. '];\n\nfac.help = {p1,sp_text,p2,sp_text,p3,sp_text};\n\nfacs.type = 'repeat';\nfacs.name = 'Factors';\nfacs.tag = 'facs';\nfacs.values = {fac};\nfacs.num = [1 Inf];\np1=['Specify your design a factor at a time.'];\nfacs.help={p1,sp_text};\n\nfnum = entry('Factor number','fnum','e',[Inf 1],'');\np1=['Enter the number of the factor.'];\nfnum.help ={p1};\n\nfnums = entry('Factor numbers','fnums','e',[2 1],'');\np1=['Enter the numbers of the factors of this (two-way) interaction.'];\nfnums.help ={p1};\n\nfmain.type = 'branch';\nfmain.name = 'Main effect';\nfmain.tag = 'fmain';\nfmain.val = {fnum};\nfmain.help = {'Add a main effect to your design matrix'};\n\ninter.type = 'branch';\ninter.name = 'Interaction';\ninter.tag = 'inter';\ninter.val = {fnums};\ninter.help = {'Add an interaction to your design matrix'};\n\nmaininters.type = 'repeat';\nmaininters.name = 'Main effects & Interactions';\nmaininters.num = [1 Inf];\nmaininters.tag = 'maininters';\nmaininters.values = {fmain, inter};\n\nscans = files('Scans','scans','image',[1 Inf],'Select scans');\nscans.help = {[...\n 'Select the images to be analysed. They must all have the same ',...\n 'image dimensions, orientation, voxel size etc.']};\n\nimatrix = entry('Factor matrix','imatrix','e',[Inf Inf],'');\nimatrix.val = {0};\nimatrix.help = {['Specify factor/level matrix as a nscan-by-4 matrix. Note' ...\n ' that the first row of I is reserved for the internal' ...\n ' replication factor and must not be used for experimental' ...\n ' factors.']};\n\nspecall.type = 'branch';\nspecall.name = 'Specify all';\nspecall.tag = 'specall';\nspecall.val = {scans,imatrix};\np1=['Specify (i) all scans in one go and (ii) all conditions using a ',...\n 'factor matrix, I. This option is for ''power users''. The matrix ',...\n 'I must have four columns and as ',...\n 'as many rows as scans. It has the same format as SPM''s internal ',...\n 'variable SPM.xX.I. '];\np2=['The first column of I denotes the replication number and entries in' ...\n ' the other columns denote the levels of each experimental factor.'];\np3=['So, for eg. a two-factor design the first column ',...\n 'denotes the replication number and columns two and three have entries ',...\n 'like 2 3 denoting the 2nd level of the first factor and 3rd level of ',...\n 'the second factor. The 4th column in I would contain all 1s.'];\nspecall.help = {p1,sp_text,p2,sp_text,p3};\n\nconds = entry('Conditions','conds','e',[Inf Inf],'');\n\nfsubject.type = 'branch';\nfsubject.name = 'Subject';\nfsubject.tag = 'fsubject';\nfsubject.val = {scans,conds};\nfsubject.help = {'Enter data and conditions for a new subject'};\n\nfsubjects.type = 'repeat';\nfsubjects.name = 'Subjects';\nfsubjects.tag = 'fsubjects';\nfsubjects.values = {fsubject};\nfsubjects.num = [1 Inf];\n\nfsuball.type = 'choice';\nfsuball.name = 'Specify Subjects or all Scans & Factors';\nfsuball.tag = 'fsuball';\nfsuball.values = {fsubjects specall};\n\n%-------------------------------------------------------------------------\n% Two-sample t-test\n\nscans1 = files('Group 1 scans','scans1','image',[1 Inf],'Select scans');\nscans1.help = {[...\n 'Select the images from sample 1. They must all have the same ',...\n 'image dimensions, orientation, voxel size etc.']};\n\nscans2 = files('Group 2 scans','scans2','image',[1 Inf],'Select scans');\nscans2.help = {[...\n 'Select the images from sample 2. They must all have the same ',...\n 'image dimensions, orientation, voxel size etc.']};\n\n%-------------------------------------------------------------------------\n% Paired t-test\n\npscans = files('Scans [1,2]','scans','image',[1 2],'Select scans');\npscans.help = {[...\n 'Select the pair of images. ']};\n\npair.type = 'branch';\npair.name = 'Pair';\npair.tag = 'pair';\npair.val = {pscans};\npair.help = {'Add a new pair of scans to your experimental design'};\n\npairs.type = 'repeat';\npairs.name = 'Pairs';\npairs.tag = 'pairs';\npairs.num = [1 Inf];\npairs.values = {pair};\np1 = [' ',...\n ' '];\npairs.help ={p1,sp_text};\n\n%-------------------------------------------------------------------------\n% One sample t-test\n\nt1scans = files('Scans','scans','image',[1 Inf],'Select scans');\nt1scans.help = {[...\n 'Select the images. They must all have the same ',...\n 'image dimensions, orientation, voxel size etc.']};\n\n%-------------------------------------------------------------------------\n% Design menu\n\nt1 = branch('One-sample t-test','t1',...\n {t1scans},'');\n\nt2 = branch('Two-sample t-test','t2',...\n {scans1,scans2,dept,variance,gmsca,ancova},'');\n\npt = branch('Paired t-test','pt',...\n {pairs,dept,variance,gmsca,ancova},'');\n\nmreg = branch('Multiple regression','mreg',...\n {t1scans,mcovs,incint},'');\n\nfblock = branch('Flexible factorial','fblock',...\n {facs,fsuball,maininters},'');\npb1 = ['Create a design matrix a block at a time by specifying which ',...\n 'main effects and interactions you wish to be included.'];\n\n\npb2=['This option is best used for one-way, two-way or ',...\n 'three-way ANOVAs but where you do not wish to test for all possible ',...\n 'main effects and interactions. This is perhaps most useful for PET ',...\n 'where there is usually not enough data to test for all possible ',...\n 'effects. Or for 3-way ANOVAs where you do not wish to test for all ',...\n 'of the two-way interactions. A typical example here would be a ',...\n 'group-by-drug-by-task analysis where, perhaps, only (i) group-by-drug or ',...\n '(ii) group-by-task interactions are of interest. In this case it is only ',...\n 'necessary to have two-blocks in the design matrix - one for each ',...\n 'interaction. The three-way interaction can then be tested for using a ',...\n 'contrast that computes the difference between (i) and (ii).'];\n\npb3=['Design specification then proceeds in 3 stages. Firstly, factors ',...\n 'are created and names specified for each. Nonsphericity, ANOVA-by-factor and ',...\n 'scaling options can also be specified at this stage.'];\n\npb4=['Secondly, a list of ',...\n 'scans is produced along with a factor matrix, I. This is an nscan x 4 matrix ',...\n 'of factor level indicators (see xX.I below). The first factor must be ',...\n '''replication'' but the other factors can be anything. Specification of I and ',...\n 'the scan list can be achieved in ',...\n 'one of two ways (a) the ''Specify All'' option allows I ',...\n 'to be typed in at the user interface or (more likely) loaded in from the matlab ',...\n 'workspace. All of the scans are then selected in one go. (b) the ',...\n '''Subjects'' option allows you to enter scans a subject at a time. The ',...\n 'corresponding experimental conditions (ie. levels of factors) are entered ',...\n 'at the same time. SPM will then create the factor matrix I. This style of ',...\n 'interface is similar to that available in SPM2.'];\n\npb5=['Thirdly, the design matrix is built up a block at a time. Each block ',...\n 'can be a main effect or a (two-way) interaction. '];\nfblock.help={pb1,sp_text,pb2,sp_text,pb3,sp_text,pb4,sp_text,pb5,sp_text};\n\nfd = branch('Full factorial','fd',...\n {factors,cells},'');\npfull1=['This option is best used when you wish to test for all ',...\n 'main effects and interactions in one-way, two-way or three-way ANOVAs. ',...\n 'Design specification proceeds in 2 stages. Firstly, by creating new ',...\n 'factors and specifying the ',...\n 'number of levels and name for each. Nonsphericity, ANOVA-by-factor and ',...\n 'scaling options can also be specified at this stage. Secondly, scans are ',...\n 'assigned separately to each cell. This accomodates unbalanced designs.'];\n\npfull2=['For example, if you wish to test for a main effect in the population ',...\n 'from which your subjects are drawn ',...\n 'and have modelled that effect at the first level using K basis functions ',...\n '(eg. K=3 informed basis functions) you can use a one-way ANOVA with K-levels. ',...\n 'Create a single factor with K levels and then assign the data to each ',...\n 'cell eg. canonical, temporal derivative and dispersion derivative cells, ',...\n 'where each cell is assigned scans from multiple subjects.'];\n\npfull3 = ['SPM will also automatically generate ',...\n 'the contrasts necessary to test for all main effects and interactions. '];\n\nfd.help={pfull1,sp_text,pfull2,sp_text,pfull3,sp_text};\n\n\n\ndes = choice('Design','des',...\n {t1,t2,pt,mreg,fd,fblock},'');\n\n\n%-------------------------------------------------------------------------\n% Masking options\n\nim = mnu('Implicit Mask','im',{'Yes','No'},{1,0},'');\nim.val={1};\np1=['An \"implicit mask\" is a mask implied by a particular voxel ',...\n 'value. Voxels with this mask value are excluded from the ',...\n 'analysis. '];\np2=['For image data-types with a representation of NaN ',...\n '(see spm_type.m), NaN''s is the implicit mask value, (and ',...\n 'NaN''s are always masked out). '];\np3=['For image data-types without a representation of NaN, zero is ',...\n 'the mask value, and the user can choose whether zero voxels ',...\n 'should be masked out or not.'];\np4=['By default, an implicit mask is used. '];\nim.help = {p1,sp_text,p2,sp_text,p3,sp_text,p4,sp_text};\n\nem = files('Explicit Mask','em','image',[0 1],'');\nem.val={''};\nem.help = {['Select an explicit mask ']};\np1=['Explicit masks are other images containing (implicit) masks ',...\n 'that are to be applied to the current analysis.'];\np2=['All voxels with value NaN (for image data-types with a ',...\n 'representation of NaN), or zero (for other data types) are ',...\n 'excluded from the analysis. '];\np3=['Explicit mask images can have any orientation and voxel/image ',...\n 'size. Nearest neighbour interpolation of a mask image is used if ',...\n 'the voxel centers of the input images do not coincide with that ',...\n 'of the mask image.'];\nem.help = {p1,sp_text,p2,sp_text,p3,sp_text};\n\ntm_none.type = 'const';\ntm_none.name = 'None';\ntm_none.tag = 'tm_none';\ntm_none.val = {[]};\ntm_none.help = {'No threshold masking'};\n\nathresh = entry('Threshold','athresh','e',[1 1],'');\nathresh.val={100};\np1=['Enter the absolute value of the threshold.'];\nathresh.help = {p1,sp_text};\n\ntma = branch('Absolute','tma',...\n {athresh},'');\np1=['Images are thresholded at a given value and ',...\n 'only voxels at which all images exceed the threshold are included. '];\np2=['This option allows you to specify the absolute value of the threshold.'];\ntma.help = {p1,sp_text,p2,sp_text};\n\np2=['By default, Relative Threshold Masking is turned off. '];\nrselect.help = {p1,sp_text,p2,sp_text};\n\nrthresh = entry('Threshold','rthresh','e',[1 1],'');\nrthresh.val={0.8};\np1=['Enter the threshold as a proportion of the global value'];\nrthresh.help = {p1,sp_text};\n\ntmr = branch('Relative','tmr',...\n {rthresh},'');\np1=['Images are thresholded at a given value and ',...\n 'only voxels at which all images exceed the threshold are included. '];\np2=['This option allows you to specify the value of the threshold ',...\n 'as a proportion of the global value. '];\ntmr.help = {p1,sp_text,p2,sp_text};\n\ntm = choice('Threshold masking','tm',...\n {tm_none,tma,tmr},'');\np1=['Images are thresholded at a given value and ',...\n 'only voxels at which all images exceed the threshold are included. '];\ntm.help={p1,sp_text};\n\nmasking = branch('Masking','masking',...\n {tm,im,em},'');\np1=['The mask specifies the voxels within the image volume which are to be ',...\n 'assessed. SPM supports three methods of masking (1) Threshold, ',...\n '(2) Implicit and (3) Explicit. The volume analysed ',...\n 'is the intersection of all masks.'];\nmasking.help={p1,sp_text};\n\n%-------------------------------------------------------------------------\n% Global calculation\n\nglobal_uval = entry('Global values','global_uval','e',[Inf 1],'');\np1=['Enter the vector of global values'];\nglobal_uval.val={0};\nglobal_uval.help={p1,sp_text};\n\ng_user = branch('User','g_user',{global_uval},'');\ng_user.help={'User defined global effects (enter your own ',...\n 'vector of global values)'};\n\ng_mean.type = 'const';\ng_mean.name = 'Mean';\ng_mean.tag = 'g_mean';\ng_mean.val = {[]};\np1=['SPM standard mean voxel value'];\np2=['This defines the global mean via a two-step process. Firstly, the overall ',...\n 'mean is computed. Voxels with values less than 1/8 of this value are then ',...\n 'deemed extra-cranial and get masked out. The mean is then recomputed on the ',...\n 'remaining voxels.'];\ng_mean.help = {p1,sp_text,p2,sp_text};\n\ng_omit.type = 'const';\ng_omit.name = 'Omit';\ng_omit.tag = 'g_omit';\ng_omit.val = {[]};\ng_omit.help = {'Omit'};\n\nglobalc = choice('Global calculation','globalc',...\n {g_omit,g_user,g_mean},'');\np1=['There are three methods for estimating global effects ',...\n '(1) Omit (assumming no other options requiring the global value chosen) ',...\n '(2) User defined (enter your own vector of global values) ',...\n '(3) Mean: SPM standard mean voxel value (within per image fullmean/8 mask) '];\nglobalc.help={p0,sp_text,p1,sp_text};\n\n%-------------------------------------------------------------------------\n% Global options\n\ngmsca_no.type = 'const';\ngmsca_no.name = 'No';\ngmsca_no.tag = 'gmsca_no';\ngmsca_no.val = {[]};\ngmsca_no.help = {'No overall grand mean scaling'};\n\ngmscv = entry('Grand mean scaled value','gmscv','e',[Inf 1],'');\ngmscv.val={50};\np1=['The default value of 50, scales the global flow to a physiologically ',...\n 'realistic value of 50ml/dl/min.'];\ngmscv.help={p1,sp_text};\n\ngmsca_yes=branch('Yes','gmsca_yes',{gmscv},'');\np1 =['Scaling of the overall grand mean simply ',...\n 'scales all the data by a common factor such that the mean of all the ',...\n 'global values is the value specified. For qualitative data, this puts ',...\n 'the data into an intuitively accessible scale without altering the ',...\n 'statistics. '];\ngmsca_yes.help={p1,sp_text};\n\ngmsca = choice('Overall grand mean scaling','gmsca',...\n {gmsca_no,gmsca_yes},'');\n\np2=['When proportional scaling global normalisation is used ',...\n 'each image is separately scaled such that it''s global ',...\n 'value is that specified (in which case the grand mean is also ',...\n 'implicitly scaled to that value). ',...\n 'So, to proportionally scale each image so that its global value is ',...\n 'eg. 20, select then type in 20 for the grand mean scaled value.'];\n\np3=['When using AnCova or no global ',...\n 'normalisation, with data from different subjects or sessions, an ',...\n 'intermediate situation may be appropriate, and you may be given the ',...\n 'option to scale group, session or subject grand means separately. '];\ngmsca.help={p1,sp_text,p2,sp_text,p3,sp_text};\n\n\n\nglonorm = mnu('Normalisation','glonorm',...\n {'None','Proportional','ANCOVA'},{1,2,3},'');\nglonorm.val={1};\np1 = ['Global nuisance effects are usually ',...\n 'accounted for either by scaling the images so that they all have the ',...\n 'same global value (proportional scaling), or by including the global ',...\n 'covariate as a nuisance effect in the general linear model (AnCova). ',...\n 'Much has been written on which to use, and when. Basically, since ',...\n 'proportional scaling also scales the variance term, it is appropriate ',...\n 'for situations where the global measurement predominantly reflects ',...\n 'gain or sensitivity. Where variance is constant across the range of ',...\n 'global values, linear modelling in an AnCova approach has more ',...\n 'flexibility, since the model is not restricted to a simple ',...\n 'proportional regression. '];\n\np2=['''Ancova by subject'' or ''Ancova by effect'' options are implemented ',...\n 'using the ANCOVA options provided where each experimental factor ',...\n '(eg. subject or effect), is defined. These allow eg. different subjects ',...\n 'to have different relationships between local and global measurements. '];\n\np3 =['Since differences between subjects may be due to gain and sensitivity ',...\n 'effects, AnCova by subject could be combined with \"grand mean scaling ',...\n 'by subject\" (an option also provided where each experimental factor is ',...\n 'originally defined) to obtain a combination of between subject proportional ',...\n 'scaling and within subject AnCova. '];\nglonorm.help={p1,sp_text,p2,sp_text,p3,sp_text};\n\nglobalm = branch('Global normalisation','globalm',...\n {gmsca,glonorm},'');\nglobalm.help={p0,sp_text,p1,sp_text,p2,sp_text,p3,sp_text};\n\n%-------------------------------------------------------------------------\n% Directory\n\ncdir = files('Directory','dir','dir',1,'');\ncdir.help = {[...\n 'Select a directory where the SPM.mat file containing the ',...\n 'specified design matrix will be written.']};\n\n%-------------------------------------------------------------------------\n% Main routine\n\nconf = branch('Factorial design specification','factorial_design',...\n {des,covs,masking,globalc,globalm,cdir},'');\np1=['This interface is used for setting up analyses of PET data. It is also ',...\n 'used for ''2nd level'' or ''random effects'' analysis which allow ',...\n 'one to make a population inference. First level models can be used to produce ',...\n 'appropriate summary data, which can then be used as raw data for a second-level ',...\n 'analysis. For example, a simple t-test on contrast images from the first-level ',...\n 'turns out to be a random-effects analysis with random subject effects, inferring ',...\n 'for the population based on a particular sample of subjects.'];\n\np2=['This interface configures the design matrix, describing the general ',...\n 'linear model, data specification, and other parameters necessary for ',...\n 'the statistical analysis. These parameters are saved in a ',...\n 'configuration file (SPM.mat), which can then be ',...\n 'passed on to spm_spm.m which estimates the design. This is achieved by ',...\n 'pressing the ''Estimate'' button. Inference on these ',...\n 'estimated parameters is then handled by the SPM results section. '];\n\np3=['A separate interface handles design configuration ',...\n 'for fMRI time series.'];\n\np4=['Various data and parameters need to be supplied to specify the design ',...\n '(1) the image files, (2) indicators of the corresponding condition/subject/group ',...\n '(2) any covariates, nuisance variables, or design matrix partitions ',...\n '(3) the type of global normalisation (if any) ',...\n '(4) grand mean scaling options ',...\n '(5) thresholds and masks defining the image volume to analyse. ',...\n 'The interface supports a comprehensive range of options for all these parameters.'];\n\nconf.help={p1,sp_text,p2,sp_text,p3,sp_text,p4,sp_text};\nconf.prog = @run_stats;\nconf.vfiles = @vfiles_stats;\nreturn;\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\nfunction vf = vfiles_stats(job)\ndirec = job.dir{1};\nvf = {fullfile(direc,'SPM.mat')};\n\n% Should really create a few vfiles for beta images etc here as well.\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\nfunction run_stats(job)\n\nspm_defaults;\n\noriginal_dir = pwd;\ncd(job.dir{1});\n\n%-Ask about overwriting files from previous analyses...\n%-------------------------------------------------------------------\nif exist(fullfile(job.dir{1},'SPM.mat'),'file')\n str = {\t'Current directory contains existing SPM file:',...\n 'Continuing will overwrite existing file!'};\n if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);\n fprintf('%-40s: %30s\\n\\n',...\n 'Abort... (existing SPM file)',spm('time'));\n return\n end\nend\n\n% If we've gotten to this point we're committed to overwriting files.\n% Delete them so we don't get stuck in spm_spm\n%------------------------------------------------------------------------\nfiles = {'^mask\\..{3}$','^ResMS\\..{3}$','^RPV\\..{3}$',...\n '^beta_.{4}\\..{3}$','^con_.{4}\\..{3}$','^ResI_.{4}\\..{3}$',...\n '^ess_.{4}\\..{3}$', '^spm\\w{1}_.{4}\\..{3}$'};\n\nfor i=1:length(files)\n j = spm_select('List',pwd,files{i});\n for k=1:size(j,1)\n spm_unlink(deblank(j(k,:)));\n end\nend\n\n\n%-Option definitions\n%-------------------------------------------------------------------\n%-Generic factor names\nsF = {'sF1','sF2','sF3','sF4'};\n\n%-Covariate by factor interaction options\nsCFI = {'';...\t\t\t\t\t\t\t%-1\n 'with sF1';'with sF2';'with sF3';'with sF4';...\t\t\t%-2:5\n 'with sF2 (within sF4)';'with sF3 (within sF4)'};\t\t%-6,7\n\n%-DesMtx argument components for covariate by factor interaction options\n% (Used for CFI's Covariate Centering (CC), GMscale & Global normalisation)\nCFIforms = {\t'[]',\t\t'C',\t'{}';...\t\t\t%-1\n 'I(:,1)',\t 'FxC',\t'{sF{1}}';...\t\t\t%-2\n 'I(:,2)',\t 'FxC',\t'{sF{2}}';...\t\t\t%-3\n 'I(:,3)',\t 'FxC',\t'{sF{3}}';...\t\t\t%-4\n 'I(:,4)',\t 'FxC',\t'{sF{4}}';...\t\t\t%-5\n 'I(:,[4,2])',\t'FxC',\t'{sF{4},sF{2}}';...\t%-6\n 'I(:,[4,3])',\t'FxC',\t'{sF{4},sF{3}}'\t};\t%-7\n\n%-Centre (mean correction) options for covariates & globals (CC)\n% (options 9-12 are for centering of global when using AnCova GloNorm) (GC)\nsCC = {\t\t'around overall mean';...\t\t\t\t%-1\n 'around sF1 means';...\t\t\t\t\t%-2\n 'around sF2 means';...\t\t\t\t\t%-3\n 'around sF3 means';...\t\t\t\t\t%-4\n 'around sF4 means';...\t\t\t\t\t%-5\n 'around sF2 (within sF4) means';...\t\t\t%-6\n 'around sF3 (within sF4) means';...\t\t\t%-7\n '';...\t\t\t\t\t%-8\n 'around user specified value';...\t\t\t%-9\n '(as implied by AnCova)';...\t\t\t\t%-10\n 'GM';...\t\t\t\t\t\t%-11\n '(redundant: not doing AnCova)'}';\t\t\t%-12\n%-DesMtx I forms for covariate centering options\nCCforms = {'ones(nScan,1)',CFIforms{2:end,1},''}';\n\n%-Global calculation options (GXcalc)\nsGXcalc = {\t'omit';...\t\t\t\t\t\t%-1\n 'user specified';...\t\t\t\t\t%-2\n 'mean voxel value (within per image fullmean/8 mask)'};\t%-3\n\n\n%-Global normalization options (GloNorm)\nsGloNorm = {\t'AnCova';...\t\t\t\t\t\t%-1\n 'AnCova by sF1';...\t\t\t\t\t%-2\n 'AnCova by sF2';...\t\t\t\t\t%-3\n 'AnCova by sF3';...\t\t\t\t\t%-4\n 'AnCova by sF4';...\t\t\t\t\t%-5\n 'AnCova by sF2 (within sF4)';...\t\t\t%-6\n 'AnCova by sF3 (within sF4)';...\t\t\t%-7\n 'proportional scaling';...\t\t\t\t%-8\n ''};\t\t\t\t%-9\n\n\n%-Grand mean scaling options (GMsca)\nsGMsca = {\t'scaling of overall grand mean';...\t\t\t%-1\n 'scaling of sF1 grand means';...\t\t\t%-2\n 'scaling of sF2 grand means';...\t\t\t%-3\n 'scaling of sF3 grand means';...\t\t\t%-4\n 'scaling of sF4 grand means';...\t\t\t%-5\n 'scaling of sF2 (within sF4) grand means';...\t\t%-6\n 'scaling of sF3 (within sF4) grand means';...\t\t%-7\n '(implicit in PropSca global normalisation)';...\t%-8\n ''\t};\t\t\t%-9\n%-NB: Grand mean scaling by subject is redundent for proportional scaling\n\n% Conditions of no interest defaults\nB=[];\nBnames={};\n\nswitch strvcat(fieldnames(job.des)),\n case 't1',\n % One sample t-test\n DesName='One sample t-test';\n\n P=job.des.t1.scans;\n n=length(P);\n I=[1:n]';\n I=[I,ones(n,3)];\n\n [H,Hnames]=spm_DesMtx(I(:,2),'-','mean');\n\n SPM.factor(1).name='Group';\n SPM.factor(1).levels=1;\n SPM.factor(1).variance=0;\n SPM.factor(1).dept=0;\n case 't2',\n % Two-sample t-test\n DesName='Two-sample t-test';\n\n P=job.des.t2.scans1;\n n1=length(job.des.t2.scans1);\n P=[P;job.des.t2.scans2];\n n2=length(job.des.t2.scans2);\n\n I=[];\n I=[1:n1]';\n I=[I;[1:n2]'];\n I=[I,[ones(n1,1);2*ones(n2,1)]];\n I=[I,ones(n1+n2,2)];\n\n [H,Hnames]=spm_DesMtx(I(:,2),'-','Group');\n\n % Names and levels\n SPM.factor(1).name='Group';\n SPM.factor(1).levels=2;\n\n % Ancova options\n SPM.factor(1).gmsca=job.des.t2.gmsca;\n SPM.factor(1).ancova=job.des.t2.ancova;\n\n % Nonsphericity options\n SPM.factor(1).variance=job.des.t2.variance;\n SPM.factor(1).dept=job.des.t2.dept;\n\n case 'pt',\n % Paired t-test\n DesName='Paired t-test';\n\n Npairs=length(job.des.pt.pair);\n P=[];\n for p=1:Npairs,\n P=[P;job.des.pt.pair(p).scans];\n end\n\n I=ones(Npairs*2,1);\n I(:,2)=kron([1:Npairs]',ones(2,1));\n I(:,3)=kron(ones(Npairs,1),[1 2]');\n I(:,4)=I(:,1);\n\n [H,Hnames]=spm_DesMtx(I(:,2),'-','Subject');\n [B,Bnames]=spm_DesMtx(I(:,3),'-','Condition');\n\n % Names and levels\n SPM.factor(1).name='Subject';\n SPM.factor(1).levels=Npairs;\n SPM.factor(2).name='Condition';\n SPM.factor(2).levels=2;\n\n % Ancova options\n SPM.factor(1).gmsca=0;\n SPM.factor(1).ancova=0;\n SPM.factor(2).gmsca=job.des.pt.gmsca;\n SPM.factor(2).ancova=job.des.pt.ancova;\n\n % Nonsphericity options\n SPM.factor(1).variance=0;\n SPM.factor(1).dept=0;\n SPM.factor(2).variance=job.des.pt.variance;\n SPM.factor(2).dept=job.des.pt.dept;\n\n case 'mreg',\n % Multiple regression\n DesName='Multiple regression';\n\n P=job.des.mreg.scans;\n n=length(P);\n I=[1:n]';\n I=[I,ones(n,3)];\n\n % Names and levels\n SPM.factor(1).name='';\n SPM.factor(1).levels=1;\n\n % Nonsphericity options\n SPM.factor(1).variance=0;\n SPM.factor(1).dept=0;\n\n H=[];Hnames=[];\n if job.des.mreg.incint==0\n B = []; Bnames = '';\n else\n [B,Bnames] = spm_DesMtx(I(:,2),'-','mean');\n end\n\n for i=1:length(job.des.mreg.mcov)\n job.cov(end+1).c = job.des.mreg.mcov(i).c;\n job.cov(end).cname = job.des.mreg.mcov(i).cname;\n job.cov(end).iCC = job.des.mreg.mcov(i).iCC;\n job.cov(end).iCFI = 1;\n end\n\n case 'fd',\n % Full Factorial Design\n DesName='Full factorial';\n\n [I,P,H,Hnames] = spm_set_factorial_design (job);\n\n Nfactors=length(job.des.fd.fact);\n for i=1:Nfactors,\n % Names and levels\n SPM.factor(i).name=job.des.fd.fact(i).name;\n SPM.factor(i).levels=job.des.fd.fact(i).levels;\n\n % Ancova options\n SPM.factor(i).gmsca=job.des.fd.fact(i).gmsca;\n SPM.factor(i).ancova=job.des.fd.fact(i).ancova;\n\n % Nonsphericity options\n SPM.factor(i).variance=job.des.fd.fact(i).variance;\n SPM.factor(i).dept=job.des.fd.fact(i).dept;\n\n end\n\n case 'fblock',\n % Flexible factorial design\n DesName='Flexible factorial';\n\n if isfield(job.des.fblock.fsuball,'fsubject')\n nsub=length(job.des.fblock.fsuball.fsubject);\n % Specify design subject-by-subject\n P=[];I=[];\n subj=[];\n for s=1:nsub,\n P = [P; job.des.fblock.fsuball.fsubject(s).scans];\n ns = length(job.des.fblock.fsuball.fsubject(s).scans);\n cc = job.des.fblock.fsuball.fsubject(s).conds;\n\n [ccr,ccc] = size(cc);\n if ~(ccr==ns) && ~(ccc==ns)\n disp(sprintf('Error for subject %d: conditions not specified for each scan',s));\n return\n elseif ~(ccr==ccc) && (ccc==ns)\n warning('spm:transposingConditions',['Condition matrix ',...\n 'appears to be transposed. Transposing back to fix.\\n',...\n 'Alert developers if it is not actually transposed.'])\n cc=cc';\n end\n subj=[subj;s*ones(ns,1)];\n % get real replications within each subject cell\n [unused cci ccj] = unique(cc,'rows');\n repl = zeros(ns, 1);\n for k=1:max(ccj)\n repl(ccj==k) = 1:sum(ccj==k);\n end;\n I = [I; [repl cc]];\n end\n\n nf=length(job.des.fblock.fac);\n subject_factor=0;\n for i=1:nf,\n if strcmpi(job.des.fblock.fac(i).name,'repl')\n % Copy `replications' column to create explicit `replications' factor\n nI=I(:,1:i);\n nI=[nI,I(:,1)];\n nI=[nI,I(:,i+1:end)];\n I=nI;\n end\n if strcmpi(job.des.fblock.fac(i).name,'subject')\n % Create explicit `subject' factor\n nI=I(:,1:i);\n nI=[nI,subj];\n nI=[nI,I(:,i+1:end)];\n I=nI;\n subject_factor=1;\n end\n\n end\n\n % Re-order scans conditions and covariates into standard format\n % This is to ensure compatibility with how variance components are created\n if subject_factor\n U=unique(I(:,2:nf+1),'rows');\n Un=length(U);\n Uc=zeros(Un,1);\n r=1;rj=[];\n for k=1:Un,\n for j=1:size(I,1),\n match=sum(I(j,2:nf+1)==U(k,:))==nf;\n if match\n Uc(k)=Uc(k)+1;\n Ir(r,:)=[Uc(k),I(j,2:end)];\n r=r+1;\n rj=[rj;j];\n end\n end\n end\n P=P(rj); % -scans\n I=Ir; % -conditions\n for k=1:numel(job.cov) % -covariates\n job.cov(k).c = job.cov(k).c(rj);\n end;\n end\n\n else % specify all scans and factor matrix\n [ns,nc]=size(job.des.fblock.fsuball.specall.imatrix);\n if ~(nc==4)\n disp('Error: factor matrix must have four columns');\n return\n end\n I=job.des.fblock.fsuball.specall.imatrix;\n\n % Get number of factors\n nf=length(job.des.fblock.fac);\n % nf=0;\n % for i=1:4,\n % if length(unique(I(:,i)))>1\n % nf=nf+1;\n % end\n % end\n\n P=job.des.fblock.fsuball.specall.scans;\n end\n\n % Pad out factorial matrix to cover the four canonical factors\n [ns,nI]=size(I);\n if nI < 4\n I = [I, ones(ns,4-nI)];\n end\n\n % Sort main effects and interactions\n fmain = struct('fnum',{});\n inter = struct('fnums',{});\n for k=1:numel(job.des.fblock.maininters)\n if isfield(job.des.fblock.maininters{k},'fmain')\n fmain(end+1)=job.des.fblock.maininters{k}.fmain;\n elseif isfield(job.des.fblock.maininters{k},'inter')\n inter(end+1)=job.des.fblock.maininters{k}.inter;\n end;\n end;\n\n % Create main effects\n H=[];Hnames=[];\n nmain=length(fmain);\n for f=1:nmain,\n fcol=fmain(f).fnum;\n fname=job.des.fblock.fac(fcol).name;\n\n % Augment H partition - explicit factor numbers are 1 lower than in I matrix\n [Hf,Hfnames]=spm_DesMtx(I(:,fcol+1),'-',fname);\n H=[H,Hf];\n Hnames=[Hnames;Hfnames];\n end\n\n % Create interactions\n ni=length(inter);\n for i=1:ni,\n % Get the two factors for this interaction\n fnums=inter(i).fnums;\n f1=fnums(1);f2=fnums(2);\n\n % Names\n iname{1}=job.des.fblock.fac(f1).name;\n iname{2}=job.des.fblock.fac(f2).name;\n\n % Augment H partition - explicit factor numbers are 1 lower than in I matrix\n Isub=[I(:,f1+1),I(:,f2+1)];\n [Hf,Hfnames]=spm_DesMtx(Isub,'-',iname);\n H=[H,Hf];\n Hnames=[Hnames;Hfnames];\n\n end\n\n if nmain==0 && ni==0\n disp('Error in design specification: You have not specified any main effects or interactions');\n return\n end\n\n for i=1:nf,\n % Names and levels\n SPM.factor(i).name=job.des.fblock.fac(i).name;\n SPM.factor(i).levels=length(unique(I(:,i+1)));\n\n % Ancova options\n SPM.factor(i).gmsca=job.des.fblock.fac(i).gmsca;\n SPM.factor(i).ancova=job.des.fblock.fac(i).ancova;\n\n % Nonsphericity options\n SPM.factor(i).variance=job.des.fblock.fac(i).variance;\n SPM.factor(i).dept=job.des.fblock.fac(i).dept;\n\n end\n\n\nend\nnScan=size(I,1); %-#obs\n\n% Set up data structures for non-sphericity routine\nSPM.xVi.I=I;\nSPM = spm_get_vc(SPM);\n\n%-Covariate partition(s): interest (C) & nuisance (G) excluding global\n%===================================================================\ndstr = {'covariate','nuisance variable'};\nC = []; Cnames = []; %-Covariate DesMtx partitions & names\nG = []; Gnames = [];\n\nxC = [];\t\t\t %-Struct array to hold raw covariates\n\n% Covariate options:\nnc=length(job.cov); % number of covariates\nfor i=1:nc,\n\n c = job.cov(i).c;\n cname = job.cov(i).cname;\n rc = c; %-Save covariate value\n rcname = cname; %-Save covariate name\n if job.cov(i).iCFI==1,\n iCFI=1;\n else\n % SPMs internal factor numbers are 1 higher than specified in user\n % interface as, internally, the first factor is always `replication'\n iCFI=job.cov(i).iCFI+1;\n end\n switch job.cov(i).iCC,\n case 1\n iCC=1;\n case {2,3,4}\n iCC=job.cov(i).iCC+1;\n otherwise\n iCC=job.cov(i).iCC+3;\n end\n\n %-Centre within factor levels as appropriate\n if any(iCC == [1:7]),\n c = c - spm_meanby(c,eval(CCforms{iCC}));\n end\n\n %-Do any interaction (only for single covariate vectors)\n %-----------------------------------------------------------\n if iCFI > 1\t\t\t\t%-(NB:iCFI=1 if size(c,2)>1)\n tI = [eval(CFIforms{iCFI,1}),c];\n tConst = CFIforms{iCFI,2};\n tFnames = [eval(CFIforms{iCFI,3}),{cname}];\n [c,cname] = spm_DesMtx(tI,tConst,tFnames);\n elseif size(c,2)>1\t\t\t%-Design matrix block\n [null,cname] = spm_DesMtx(c,'X',cname);\n else\n cname = {cname};\n end\n\n %-Store raw covariate details in xC struct for reference\n %-Pack c into appropriate DesMtx partition\n %-----------------------------------------------------------\n %-Construct description string for covariate\n str = {sprintf('%s',rcname)};\n if size(rc,2)>1, str = {sprintf('%s (block of %d covariates)',...\n str{:},size(rc,2))}; end\n if iCC < 8, str=[str;{['used centered ',sCC{iCC}]}]; end\n if iCFI> 1, str=[str;{['fitted as interaction ',sCFI{iCFI}]}]; end\n\n typ = 1;\n tmp = struct(\t'rc',rc,\t'rcname',rcname,...\n 'c',c,\t\t'cname',{cname},...\n 'iCC',iCC,\t'iCFI',iCFI,...\n 'type',typ,...\n 'cols',[1:size(c,2)] + ...\n size([H,C],2) + ...\n size([B,G],2)*min(typ-1,1),...\n 'descrip',{str}\t\t\t\t);\n if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end\n C = [C,c];\n Cnames = [Cnames; cname];\n\nend\nclear c tI tConst tFnames\n\nxGX=[];\nxM=[];\n\n\n\n%===================================================================\n% - C O N F I G U R E D E S I G N -\n%===================================================================\n\n%-Images & image info: Map Y image files and check consistency of\n% dimensions and orientation / voxel size\n%===================================================================\nfprintf('%-40s: ','Mapping files') %-#\nVY = spm_vol(char(P));\n\n%-Check compatability of images (Bombs for single image)\n%-------------------------------------------------------------------\nspm_check_orientations(VY);\n\nfprintf('%30s\\n','...done') %-#\n\n%-Global values, scaling and global normalisation\n%===================================================================\n%-Compute global values\n%-------------------------------------------------------------------\nswitch strvcat(fieldnames(job.globalc))\n case 'g_omit',\n iGXcalc=1;\n case 'g_user',\n iGXcalc=2;\n case 'g_mean',\n iGXcalc=3;\nend\n\nswitch job.globalm.glonorm\n case 1,\n iGloNorm=9;\n case 2,\n iGloNorm=8;\n case 3,\n iGloNorm=1;\nend\nif SPM.factor(1).levels > 1\n % Over-ride if factor-specific ANCOVA has been specified\n for i=1:length(SPM.factor),\n if SPM.factor(i).ancova\n iGloNorm=i+2;\n end\n end\nend\n\n%-Analysis threshold mask\n%-------------------------------------------------------------------\n%-Work out available options:\n% -Inf=>None, real=>absolute, complex=>proportional, (i.e. times global)\nM_T = -Inf;\nswitch strvcat(fieldnames(job.masking.tm)),\n case 'tma',\n % Absolute\n M_T = job.masking.tm.tma.athresh;\n case 'tmr',\n % Relative\n M_T = job.masking.tm.tmr.rthresh*sqrt(-1);\n % Need to force calculation of globals\n if iGXcalc~=2, iGXcalc=3; end\n case 'tm_none'\n % None\n M_T = -Inf;\nend\n\nif (any(iGloNorm == [1:5]) || iGloNorm==8) && iGXcalc==1\n % Over-ride omission of global calculation if we need it\n disp(' ');\n disp(sprintf('For %s, SPM needs estimates of global activity.',sGloNorm{iGloNorm}));\n disp('But you have specified to omit this computation.');\n disp('SPM has overridden this omission and will automatically compute ');\n disp('globals as the mean value of within brain voxels');\n disp(' ');\n iGXcalc=3;\nend\nsGXcalc = sGXcalc{iGXcalc};\n\nswitch iGXcalc,\n case 1\n %-Don't compute => no GMsca (iGMsca==9) or GloNorm (iGloNorm==9)\n g = [];\n case 2\n %-User specified globals\n g = job.globalc.g_user.global_uval;\n case 3\n %-Compute as mean voxel value (within per image fullmean/8 mask)\n g = zeros(nScan,1 );\n fprintf('%-40s: %30s','Calculating globals',' ') %-#\n for i = 1:nScan\n str = sprintf('%3d/%-3d',i,nScan);\n fprintf('%s%30s',repmat(sprintf('\\b'),1,30),str)%-#\n g(i) = spm_global(VY(i));\n end\n fprintf('%s%30s\\n',repmat(sprintf('\\b'),1,30),'...done') %-#\n otherwise\n error('illegal iGXcalc')\nend\nrg = g;\n\nfprintf('%-40s: ','Design configuration') %-#\n\n%-Grand mean scaling options (GMsca)\n%-------------------------------------------------------------------\nif iGloNorm==8\n iGMsca=8;\t%-grand mean scaling implicit in PropSca GloNorm\nelse\n switch strvcat(fieldnames(job.globalm.gmsca))\n case 'gmsca_yes',\n iGMsca=1;\n case 'gmsca_no',\n iGMsca=9;\n end\n if SPM.factor(1).levels > 1\n % Over-ride if factor-specific scaling has been specified\n for i=1:length(SPM.factor),\n if SPM.factor(i).gmsca\n iGMsca=i+2;\n end\n end\n end\nend\n\n%-Value for PropSca / GMsca (GM)\n%-------------------------------------------------------------------\nswitch iGMsca,\n case 9 %-Not scaling (GMsca or PropSca)\n GM = 0; %-Set GM to zero when not scaling\n case 1 %-Ask user value of GM\n GM = job.globalm.gmsca.gmsca_yes.gmscv;\n otherwise\n if iGloNorm==8\n switch strvcat(fieldnames(job.globalm.gmsca))\n case 'gmsca_yes',\n % Proportionally scale to this value\n GM = job.globalm.gmsca.gmsca_yes.gmscv;\n case 'gmsca_no',\n GM = 50;\n end\n else\n % Grand mean scaling by factor eg. scans are scaled so that the\n % mean global value over each level of the factor is set to GM\n GM=50;\n end\nend\n\n%-If GM is zero then don't GMsca! or PropSca GloNorm\nif GM==0,\n iGMsca=9;\n if iGloNorm==8,\n iGloNorm=9;\n end\nend\n\n%-Sort out description strings for GloNorm and GMsca\n%-------------------------------------------------------------------\nsGloNorm = sGloNorm{iGloNorm};\nsGMsca = sGMsca{iGMsca};\nif iGloNorm==8\n sGloNorm = sprintf('%s to %-4g',sGloNorm,GM);\nelseif iGMsca<8\n sGMsca = sprintf('%s to %-4g',sGMsca,GM);\nend\n\n%-Scaling: compute global scaling factors gSF required to implement\n% proportional scaling global normalisation (PropSca) or grand mean\n% scaling (GMsca), as specified by iGMsca (& iGloNorm)\n%-------------------------------------------------------------------\nswitch iGMsca,\n case 8\n %-Proportional scaling global normalisation\n if iGloNorm~=8, error('iGloNorm-iGMsca(8) mismatch for PropSca'), end\n gSF = GM./g;\n g = GM*ones(nScan,1);\n case {1,2,3,4,5,6,7}\n %-Grand mean scaling according to iGMsca\n gSF = GM./spm_meanby(g,eval(CCforms{iGMsca}));\n g = g.*gSF;\n case 9\n %-No grand mean scaling\n gSF = ones(nScan,1);\n otherwise\n error('illegal iGMsca')\nend\n\n\n%-Apply gSF to memory-mapped scalefactors to implement scaling\n%-------------------------------------------------------------------\nfor i = 1:nScan\n VY(i).pinfo(1:2,:) = VY(i).pinfo(1:2,:)*gSF(i);\nend\n\n%-Global centering (for AnCova GloNorm) (GC)\n%-If not doing AnCova then GC is irrelevant\nif ~any(iGloNorm == [1:7])\n iGC = 12;\n gc = [];\nelse\n iGC = 10;\n gc = 0;\nend\n\n%-AnCova: Construct global nuisance covariates partition (if AnCova)\n%-------------------------------------------------------------------\nif any(iGloNorm == [1:7])\n\n %-Centre global covariate as requested\n %---------------------------------------------------------------\n switch iGC, case {1,2,3,4,5,6,7}\t%-Standard sCC options\n gc = spm_meanby(g,eval(CCforms{iGC}));\n case 8\t\t\t\t\t%-No centering\n gc = 0;\n case 9\t\t\t\t\t%-User specified centre\n %-gc set above\n case 10\t\t\t\t\t%-As implied by AnCova option\n gc = spm_meanby(g,eval(CCforms{iGloNorm}));\n case 11\t\t\t\t\t%-Around GM\n gc = GM;\n otherwise\t\t\t\t%-unknown iGC\n error('unexpected iGC value')\n end\n\n %-AnCova - add scaled centred global to DesMtx `G' partition\n %---------------------------------------------------------------\n rcname = 'global';\n tI = [eval(CFIforms{iGloNorm,1}),g - gc];\n tConst = CFIforms{iGloNorm,2};\n tFnames = [eval(CFIforms{iGloNorm,3}),{rcname}];\n [f,gnames] = spm_DesMtx(tI,tConst,tFnames);\n clear tI tConst tFnames\n\n %-Save GX info in xC struct for reference\n %---------------------------------------------------------------\n str = {sprintf('%s: %s',dstr{2},rcname)};\n if any(iGMsca==[1:7]), str=[str;{['(after ',sGMsca,')']}]; end\n if iGC ~= 8, str=[str;{['used centered ',sCC{iGC}]}]; end\n if iGloNorm > 1\n str=[str;{['fitted as interaction ',sCFI{iGloNorm}]}];\n end\n tmp = struct(\t'rc',rg.*gSF,\t\t'rcname',rcname,...\n 'c',f,\t\t\t'cname'\t,{gnames},...\n 'iCC',iGC,\t\t'iCFI'\t,iGloNorm,...\n 'type',\t\t\t3,...\n 'cols',[1:size(f,2)] + size([H C B G],2),...\n 'descrip',\t\t{str}\t\t);\n\n G = [G,f]; Gnames = [Gnames; gnames];\n if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end\n\n\nelseif iGloNorm==8 || iGXcalc>1\n\n %-Globals calculated, but not AnCova: Make a note of globals\n %---------------------------------------------------------------\n if iGloNorm==8\n str = { 'global values: (used for proportional scaling)';...\n '(\"raw\" unscaled globals shown)'};\n elseif isfinite(M_T) && ~isreal(M_T)\n str = { 'global values: (used to compute analysis threshold)'};\n else\n str = { 'global values: (computed but not used)'};\n end\n\n rcname ='global';\n tmp = struct(\t'rc',rg,\t'rcname',rcname,...\n 'c',{[]},\t'cname'\t,{{}},...\n 'iCC',0,\t'iCFI'\t,0,...\n 'type',\t\t3,...\n 'cols',\t\t{[]},...\n 'descrip',\t{str}\t\t\t);\n\n if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end\nend\n\n\n%-Save info on global calculation in xGX structure\n%-------------------------------------------------------------------\nxGX = struct(...\n 'iGXcalc',iGXcalc,\t'sGXcalc',sGXcalc,\t'rg',rg,...\n 'iGMsca',iGMsca,\t'sGMsca',sGMsca,\t'GM',GM,'gSF',gSF,...\n 'iGC',\tiGC,\t\t'sGC',\tsCC{iGC},\t'gc',\tgc,...\n 'iGloNorm',iGloNorm,\t'sGloNorm',sGloNorm);\n\n%-Make a description string\n%-------------------------------------------------------------------\nif isinf(M_T)\n xsM.Analysis_threshold = 'None (-Inf)';\nelseif isreal(M_T)\n xsM.Analysis_threshold = sprintf('images thresholded at %6g',M_T);\nelse\n xsM.Analysis_threshold = sprintf(['images thresholded at %6g ',...\n 'times global'],imag(M_T));\nend\n\n%-Construct masking information structure and compute actual analysis\n% threshold using scaled globals (rg.*gSF)\n%-------------------------------------------------------------------\nif isreal(M_T),\n M_TH = M_T * ones(nScan,1);\t%-NB: -Inf is real\nelse\n M_TH = imag(M_T) * (rg.*gSF);\nend\n\n%-Implicit masking: Ignore zero voxels in low data-types?\n%-------------------------------------------------------------------\n% (Implicit mask is NaN in higher data-types.)\ntype = getfield(spm_vol(P{1,1}),'dt')*[1,0]';\nif ~spm_type(type,'nanrep')\n M_I = job.masking.im; % Implicit mask ?\n if M_I,\n xsM.Implicit_masking = 'Yes: zero''s treated as missing';\n else,\n xsM.Implicit_masking = 'No';\n end\nelse\n M_I = 1;\n xsM.Implicit_masking = 'Yes: NaN''s treated as missing';\nend\n\n%-Explicit masking\n%-------------------------------------------------------------------\nif isempty(job.masking.em{:})\n VM = [];\n xsM.Explicit_masking = 'No';\nelse\n VM = spm_vol(char(job.masking.em));\n xsM.Explicit_masking = 'Yes';\nend\n\nxM = struct('T',M_T, 'TH',M_TH, 'I',M_I, 'VM',{VM}, 'xs',xsM);\n\n%-Construct full design matrix (X), parameter names and structure (xX)\n%===================================================================\nX = [H C B G];\ntmp = cumsum([size(H,2), size(C,2), size(B,2), size(G,2)]);\nxX = struct(\t'X',\t\tX,...\n 'iH',\t\t[1:size(H,2)],...\n 'iC',\t\t[1:size(C,2)] + tmp(1),...\n 'iB',\t\t[1:size(B,2)] + tmp(2),...\n 'iG',\t\t[1:size(G,2)] + tmp(3),...\n 'name',\t\t{[Hnames; Cnames; Bnames; Gnames]},...\n 'I',\t\tI,...\n 'sF',\t\t{sF});\n\n\n%-Design description (an nx2 cellstr) - for saving and display\n%===================================================================\ntmp = {\tsprintf('%d condition, +%d covariate, +%d block, +%d nuisance',...\n size(H,2),size(C,2),size(B,2),size(G,2));...\n sprintf('%d total, having %d degrees of freedom',...\n size(X,2),rank(X));...\n sprintf('leaving %d degrees of freedom from %d images',...\n size(X,1)-rank(X),size(X,1))\t\t\t\t};\nxsDes = struct(\t'Design',\t\t\t{DesName},...\n 'Global_calculation',\t\t{sGXcalc},...\n 'Grand_mean_scaling',\t\t{sGMsca},...\n 'Global_normalisation',\t\t{sGloNorm},...\n 'Parameters',\t\t\t{tmp}\t\t\t);\n\n\nfprintf('%30s\\n','...done') %-#\n\n%-Assemble SPM structure\n%===================================================================\nSPM.xY.P\t= P;\t\t\t% filenames\nSPM.xY.VY\t= VY;\t\t\t% mapped data\nSPM.nscan\t= size(xX.X,1); % scan number\nSPM.xX\t\t= xX;\t\t\t% design structure\nSPM.xC\t\t= xC;\t\t\t% covariate structure\nSPM.xGX\t\t= xGX;\t\t\t% global structure\nSPM.xM\t\t= xM;\t\t\t% mask structure\nSPM.xsDes\t= xsDes;\t\t% description\n\n% Automatic contrast generation only works for 'Full factorials'\nif ~strcmp(DesName,'Full factorial')\n % Remove the .factor field to prevent attempted automatic contrast generation\n SPM=rmfield(SPM,'factor');\nend\n\n%-Save SPM.mat and set output argument\n%-------------------------------------------------------------------\nfprintf('%-40s: ','Saving SPM configuration') %-#\n\nif spm_matlab_version_chk('7') >= 0\n save('SPM', 'SPM', '-V6');\nelse\n save('SPM', 'SPM');\nend;\nfprintf('%30s\\n','...SPM.mat saved') %-#\nvarargout = {SPM};\n\n%-Display Design report\n%===================================================================\nfprintf('%-40s: ','Design reporting') %-#\nfname = cat(1,{SPM.xY.VY.fname}');\nspm_DesRep('DesMtx',SPM.xX,fname,SPM.xsDes)\nfprintf('%30s\\n','...done')\n\ncd(original_dir); % Change back dir\nfprintf('Done\\n')\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_ecat2nifti.m", "ext": ".m", "path": "spm5-master/spm_ecat2nifti.m", "size": 16103, "source_encoding": "utf_8", "md5": "4cc89d7d1ccc8140385d57f70fb567fa", "text": "function N = spm_ecat2nifti(fname,opts)\n% Import ECAT 7 images from CTI PET scanners.\n% FORMAT N = spm_ecat2nifti(fname)\n% fname - name of ECAT file\n% _______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner & Roger Gunn\n% $Id: spm_ecat2nifti.m 112 2005-05-04 18:20:52Z john $\n\n\nif nargin==1,\n opts = struct('ext','.nii');\nend;\n\nfp = fopen(fname,'r','ieee-be');\nif fp == -1,\n error(['Can''t open \"' fname '\".']);\n return;\nend\n\nmh = ECAT7_mheader(fp);\nif ~strcmp(mh.MAGIC_NUMBER,'MATRIX70v') &&...\n ~strcmp(mh.MAGIC_NUMBER,'MATRIX71v') &&...\n ~strcmp(mh.MAGIC_NUMBER,'MATRIX72v'),\n error(['\"' fname '\" does not appear to be ECAT 7 format.']);\n fclose(fp);\n return;\nend\n\nif mh.FILE_TYPE ~= 7,\n error(['\"' fname '\" does not appear to be an image file.']);\n fclose(fp);\n return;\nend\n\nlist = s7_matlist(fp);\nmatches = find((list(:,4) == 1) | (list(:,4) == 2));\nllist = list(matches,:);\n\nfor i=1:size(llist,1),\n sh(i) = ECAT7_sheader(fp,llist(i,2));\nend;\nfclose(fp);\n\nfor i=1:size(llist,1),\n dim = [sh(i).X_DIMENSION sh(i).Y_DIMENSION sh(i).Z_DIMENSION];\n dtype = [4 1];\n off = 512*llist(i,2);\n scale = sh(i).SCALE_FACTOR*mh.ECAT_CALIBRATION_FACTOR;\n inter = 0;\n dati = file_array(fname,dim,dtype,off,scale,inter);\n\n dircos = diag([-1 -1 -1]);\n step = ([sh(i).X_PIXEL_SIZE sh(i).Y_PIXEL_SIZE sh(i).Z_PIXEL_SIZE]*10);\n start = -(dim(1:3)'/2).*step';\n mat = [[dircos*diag(step) dircos*start] ; [0 0 0 1]];\n\n matnum = sprintf('%.8x',list(i,1));\n [pth,nam,ext] = fileparts(fname);\n fnameo = fullfile(pwd,[nam '_' matnum opts.ext]);\n dato = file_array(fnameo,dim,[4 spm_platform('bigend')],0,scale,inter);\n\n N = nifti;\n N.dat = dato;\n N.mat = mat;\n N.mat0 = mat;\n N.mat_intent = 'aligned';\n N.mat0_intent = 'scanner';\n N.descrip = sh(i).ANNOTATION;\n N.timing = struct('toffset',sh(i).FRAME_START_TIME/1000,'tspace',sh(i).FRAME_DURATION/1000);\n create(N);\n for j=1:dim(3),\n N.dat(:,:,j) = dati(:,:,j);\n end;\n N.extras = struct('mh',mh,'sh',sh(i));\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\n%S7_MATLIST List the available matrixes in an ECAT 7 file.\n%\tLIST = S7_MATLIST(FP) lists the available matrixes\n%\tin the file specified by FP.\n%\n%\tColumns in LIST:\n%\t\t1 - Matrix identifier.\n%\t\t2 - Matrix subheader record number\n%\t\t3 - Last record number of matrix data block.\n%\t\t4 - Matrix status:\n%\t\t\t1 - exists - rw\n%\t\t\t2 - exists - ro\n%\t\t\t3 - matrix deleted\n%\nfunction list = s7_matlist(fp)\n\n% I believe fp should be opened with:\n% fp = fopen(filename,'r','ieee-be');\n\nfseek(fp,512,'bof');\nblock = fread(fp,128,'int');\nif size(block,1) ~= 128\n list = [];\n return;\nend;\nblock = reshape(block,4,32);\nlist = [];\nwhile block(2,1) ~= 2,\n if block(1,1)+block(4,1) ~= 31,\n list = []; return;\n end;\n list = [list block(:,2:32)];\n\n fseek(fp,512*(block(2,1)-1),'bof');\n block = fread(fp,128,'int');\n if size(block,1) ~= 128, list = []; return; end;\n block = reshape(block,4,32);\nend\nlist = [list block(:,2:(block(4,1)+1))];\nlist = list';\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction SHEADER=ECAT7_sheader(fid,record)\n%\n% Sub header read routine for ECAT 7 image files\n%\n% Roger Gunn, 260298\noff = (record-1)*512;\nstatus = fseek(fid, off,'bof');\ndata_type = fread(fid,1,'uint16',0);\nnum_dimensions = fread(fid,1,'uint16',0);\nx_dimension = fread(fid,1,'uint16',0);\ny_dimension = fread(fid,1,'uint16',0);\nz_dimension = fread(fid,1,'uint16',0);\nx_offset = fread(fid,1,'float32',0);\ny_offset = fread(fid,1,'float32',0);\nz_offset = fread(fid,1,'float32',0);\nrecon_zoom = fread(fid,1,'float32',0);\nscale_factor = fread(fid,1,'float32',0);\nimage_min = fread(fid,1,'int16',0);\nimage_max = fread(fid,1,'int16',0);\nx_pixel_size = fread(fid,1,'float32',0);\ny_pixel_size = fread(fid,1,'float32',0);\nz_pixel_size = fread(fid,1,'float32',0);\nframe_duration = fread(fid,1,'uint32',0);\nframe_start_time = fread(fid,1,'uint32',0);\nfilter_code = fread(fid,1,'uint16',0);\nx_resolution = fread(fid,1,'float32',0);\ny_resolution = fread(fid,1,'float32',0);\nz_resolution = fread(fid,1,'float32',0);\nnum_r_elements = fread(fid,1,'float32',0);\nnum_angles = fread(fid,1,'float32',0);\nz_rotation_angle = fread(fid,1,'float32',0);\ndecay_corr_fctr = fread(fid,1,'float32',0);\ncorrections_applied = fread(fid,1,'uint32',0);\ngate_duration = fread(fid,1,'uint32',0);\nr_wave_offset = fread(fid,1,'uint32',0);\nnum_accepted_beats = fread(fid,1,'uint32',0);\nfilter_cutoff_frequency = fread(fid,1,'float32',0);\nfilter_resolution = fread(fid,1,'float32',0);\nfilter_ramp_slope = fread(fid,1,'float32',0);\nfilter_order = fread(fid,1,'uint16',0);\nfilter_scatter_fraction = fread(fid,1,'float32',0);\nfilter_scatter_slope = fread(fid,1,'float32',0);\nannotation = fread(fid,40,'char',0);\nmt_1_1 = fread(fid,1,'float32',0);\nmt_1_2 = fread(fid,1,'float32',0);\nmt_1_3 = fread(fid,1,'float32',0);\nmt_2_1 = fread(fid,1,'float32',0);\nmt_2_2 = fread(fid,1,'float32',0);\nmt_2_3 = fread(fid,1,'float32',0);\nmt_3_1 = fread(fid,1,'float32',0);\nmt_3_2 = fread(fid,1,'float32',0);\nmt_3_3 = fread(fid,1,'float32',0);\nrfilter_cutoff = fread(fid,1,'float32',0);\nrfilter_resolution = fread(fid,1,'float32',0);\nrfilter_code = fread(fid,1,'uint16',0);\nrfilter_order = fread(fid,1,'uint16',0);\nzfilter_cutoff = fread(fid,1,'float32',0);\nzfilter_resolution = fread(fid,1,'float32',0);\nzfilter_code = fread(fid,1,'uint16',0);\nzfilter_order = fread(fid,1,'uint16',0);\nmt_4_1 = fread(fid,1,'float32',0);\nmt_4_2 = fread(fid,1,'float32',0);\nmt_4_3 = fread(fid,1,'float32',0);\nscatter_type = fread(fid,1,'uint16',0);\nrecon_type = fread(fid,1,'uint16',0);\nrecon_views = fread(fid,1,'uint16',0);\nfill = fread(fid,1,'uint16',0);\nannotation = deblank(char(annotation.*(annotation>0))');\n\nSHEADER = struct('DATA_TYPE', data_type, ...\n\t'NUM_DIMENSIONS', num_dimensions, ...\n\t'X_DIMENSION', x_dimension, ...\n\t'Y_DIMENSION', y_dimension, ...\n\t'Z_DIMENSION', z_dimension, ...\n\t'X_OFFSET', x_offset, ...\n\t'Y_OFFSET', y_offset, ...\n\t'Z_OFFSET', z_offset, ...\n\t'RECON_ZOOM', recon_zoom, ...\n\t'SCALE_FACTOR', scale_factor, ...\n\t'IMAGE_MIN', image_min, ...\n\t'IMAGE_MAX', image_max, ...\n\t'X_PIXEL_SIZE', x_pixel_size, ...\n\t'Y_PIXEL_SIZE', y_pixel_size, ...\n\t'Z_PIXEL_SIZE', z_pixel_size, ...\n\t'FRAME_DURATION', frame_duration, ...\n\t'FRAME_START_TIME', frame_start_time, ...\n\t'FILTER_CODE', filter_code, ...\n\t'X_RESOLUTION', x_resolution, ...\n\t'Y_RESOLUTION', y_resolution, ...\n\t'Z_RESOLUTION', z_resolution, ...\n\t'NUM_R_ELEMENTS', num_r_elements, ...\n\t'NUM_ANGLES', num_angles, ...\n\t'Z_ROTATION_ANGLE', z_rotation_angle, ...\n\t'DECAY_CORR_FCTR', decay_corr_fctr, ...\n\t'CORRECTIONS_APPLIED', corrections_applied, ...\n\t'GATE_DURATION', gate_duration, ...\n\t'R_WAVE_OFFSET', r_wave_offset, ...\n\t'NUM_ACCEPTED_BEATS', num_accepted_beats, ...\n\t'FILTER_CUTOFF_FREQUENCY', filter_cutoff_frequency, ...\n\t'FILTER_RESOLUTION', filter_resolution, ...\n\t'FILTER_RAMP_SLOPE', filter_ramp_slope, ...\n\t'FILTER_ORDER', filter_order, ...\n\t'FILTER_SCATTER_CORRECTION', filter_scatter_fraction, ...\n\t'FILTER_SCATTER_SLOPE', filter_scatter_slope, ...\n\t'ANNOTATION', annotation, ...\n\t'MT_1_1', mt_1_1, ...\n\t'MT_1_2', mt_1_2, ...\n\t'MT_1_3', mt_1_3, ...\n\t'MT_2_1', mt_2_1, ...\n\t'MT_2_2', mt_2_2, ...\n\t'MT_2_3', mt_2_3, ...\n\t'MT_3_1', mt_3_1, ...\n\t'MT_3_2', mt_3_2, ...\n\t'MT_3_3', mt_3_3, ...\n\t'RFILTER_CUTOFF', rfilter_cutoff, ...\n\t'RFILTER_RESOLUTION', rfilter_resolution, ...\n\t'RFILTER_CODE', rfilter_code, ...\n\t'RFILTER_ORDER', rfilter_order, ...\n\t'ZFILTER_CUTOFF', zfilter_cutoff, ...\n\t'ZFILTER_RESOLUTION', zfilter_resolution, ...\n\t'ZFILTER_CODE', zfilter_code, ...\n\t'ZFILTER_ORDER', zfilter_order, ...\n\t'MT_4_1', mt_4_1, ...\n\t'MT_4_2', mt_4_2, ...\n\t'MT_4_3', mt_4_3, ...\n\t'SCATTER_TYPE', scatter_type, ...\n\t'RECON_TYPE', recon_type, ...\n\t'RECON_VIEWS', recon_views, ...\n\t'FILL', fill);\nreturn;\n%_______________________________________________________________________\nfunction [MHEADER]=ECAT7_mheader(fid)\n%\n% Main header read routine for ECAT 7 image files\n%\n% Roger Gunn, 260298\n\nstatus = fseek(fid, 0,'bof');\nmagic_number = fread(fid,14,'char',0);\noriginal_file_name = fread(fid,32,'char',0);\nsw_version = fread(fid,1,'uint16',0);\nsystem_type = fread(fid,1,'uint16',0);\nfile_type = fread(fid,1,'uint16',0);\nserial_number = fread(fid,10,'char',0);\nscan_start_time = fread(fid,1,'uint32',0);\nisotope_name = fread(fid,8,'char',0);\nisotope_halflife = fread(fid,1,'float32',0);\nradiopharmaceutical = fread(fid,32,'char',0);\ngantry_tilt = fread(fid,1,'float32',0);\ngantry_rotation = fread(fid,1,'float32',0);\nbed_elevation = fread(fid,1,'float32',0);\nintrinsic_tilt = fread(fid,1,'float32',0);\nwobble_speed = fread(fid,1,'uint16',0);\ntransm_source_type = fread(fid,1,'uint16',0);\ndistance_scanned = fread(fid,1,'float32',0);\ntransaxial_fov = fread(fid,1,'float32',0);\nangular_compression = fread(fid,1,'uint16',0);\ncoin_samp_mode = fread(fid,1,'uint16',0);\naxial_samp_mode = fread(fid,1,'uint16',0);\necat_calibration_factor = fread(fid,1,'float32',0);\ncalibration_units = fread(fid,1,'uint16',0);\ncalibration_units_type = fread(fid,1,'uint16',0);\ncompression_code = fread(fid,1,'uint16',0);\nstudy_type = fread(fid,12,'char',0);\npatient_id = fread(fid,16,'char',0);\npatient_name = fread(fid,32,'char',0);\npatient_sex = fread(fid,1,'char',0);\npatient_dexterity = fread(fid,1,'char',0);\npatient_age = fread(fid,1,'float32',0);\npatient_height = fread(fid,1,'float32',0);\npatient_weight = fread(fid,1,'float32',0);\npatient_birth_date = fread(fid,1,'uint32',0);\nphysician_name = fread(fid,32,'char',0);\noperator_name = fread(fid,32,'char',0);\nstudy_description = fread(fid,32,'char',0);\nacquisition_type = fread(fid,1,'uint16',0);\npatient_orientation = fread(fid,1,'uint16',0);\nfacility_name = fread(fid,20,'char',0);\nnum_planes = fread(fid,1,'uint16',0);\nnum_frames = fread(fid,1,'uint16',0);\nnum_gates = fread(fid,1,'uint16',0);\nnum_bed_pos = fread(fid,1,'uint16',0);\ninit_bed_position = fread(fid,1,'float32',0);\nbed_position = zeros(15,1);\nfor bed=1:15,\n tmp = fread(fid,1,'float32',0);\n if ~isempty(tmp), bed_position(bed) = tmp; end;\nend;\nplane_separation = fread(fid,1,'float32',0);\nlwr_sctr_thres = fread(fid,1,'uint16',0);\nlwr_true_thres = fread(fid,1,'uint16',0);\nupr_true_thres = fread(fid,1,'uint16',0);\nuser_process_code = fread(fid,10,'char',0);\nacquisition_mode = fread(fid,1,'uint16',0);\nbin_size = fread(fid,1,'float32',0);\nbranching_fraction = fread(fid,1,'float32',0);\ndose_start_time = fread(fid,1,'uint32',0);\ndosage = fread(fid,1,'float32',0);\nwell_counter_corr_factor = fread(fid,1,'float32',0);\ndata_units = fread(fid,32,'char',0);\nsepta_state = fread(fid,1,'uint16',0);\nfill = fread(fid,1,'uint16',0);\n\t\nmagic_number = deblank(char(magic_number.*(magic_number>32))');\noriginal_file_name = deblank(char(original_file_name.*(original_file_name>0))');\nserial_number = deblank(char(serial_number.*(serial_number>0))');\nisotope_name = deblank(char(isotope_name.*(isotope_name>0))');\nradiopharmaceutical = deblank(char(radiopharmaceutical.*(radiopharmaceutical>0))');\nstudy_type = deblank(char(study_type.*(study_type>0))');\npatient_id = deblank(char(patient_id.*(patient_id>0))');\npatient_name = deblank(char(patient_name.*(patient_name>0))');\npatient_sex = deblank(char(patient_sex.*(patient_sex>0))');\npatient_dexterity = deblank(char(patient_dexterity.*(patient_dexterity>0))');\nphysician_name = deblank(char(physician_name.*(physician_name>0))');\noperator_name = deblank(char(operator_name.*(operator_name>0))');\nstudy_description = deblank(char(study_description.*(study_description>0))');\nfacility_name = deblank(char(facility_name.*(facility_name>0))');\nuser_process_code = deblank(char(user_process_code.*(user_process_code>0))');\ndata_units = deblank(char(data_units.*(data_units>0))');\n\nMHEADER = struct('MAGIC_NUMBER', magic_number, ...\n\t'ORIGINAL_FILE_NAME', original_file_name, ...\n\t'SW_VERSION', sw_version, ...\n\t'SYSTEM_TYPE', system_type, ...\n\t'FILE_TYPE', file_type, ...\n\t'SERIAL_NUMBER', serial_number, ...\n\t'SCAN_START_TIME', scan_start_time, ...\n\t'ISOTOPE_NAME', isotope_name, ...\n\t'ISOTOPE_HALFLIFE', isotope_halflife, ...\n\t'RADIOPHARMACEUTICAL', radiopharmaceutical, ... \n\t'GANTRY_TILT', gantry_tilt, ...\n\t'GANTRY_ROTATION', gantry_rotation, ... \n\t'BED_ELEVATION', bed_elevation, ...\n\t'INTRINSIC_TILT', intrinsic_tilt, ... \n\t'WOBBLE_SPEED', wobble_speed, ...\n\t'TRANSM_SOURCE_TYPE', transm_source_type, ...\n\t'DISTANCE_SCANNED', distance_scanned, ...\n\t'TRANSAXIAL_FOV', transaxial_fov, ...\n\t'ANGULAR_COMPRESSION', angular_compression, ... \n\t'COIN_SAMP_MODE', coin_samp_mode, ...\n\t'AXIAL_SAMP_MODE', axial_samp_mode, ...\n\t'ECAT_CALIBRATION_FACTOR', ecat_calibration_factor, ...\n\t'CALIBRATION_UNITS', calibration_units, ...\n\t'CALIBRATION_UNITS_TYPE', calibration_units_type, ...\n\t'COMPRESSION_CODE', compression_code, ...\n\t'STUDY_TYPE', study_type, ...\n\t'PATIENT_ID', patient_id, ...\n\t'PATIENT_NAME', patient_name, ...\n\t'PATIENT_SEX', patient_sex, ...\n\t'PATIENT_DEXTERITY', patient_dexterity, ...\n\t'PATIENT_AGE', patient_age, ...\n\t'PATIENT_HEIGHT', patient_height, ...\n\t'PATIENT_WEIGHT', patient_weight, ...\n\t'PATIENT_BIRTH_DATE', patient_birth_date, ...\n\t'PHYSICIAN_NAME', physician_name, ...\n\t'OPERATOR_NAME', operator_name, ...\n\t'STUDY_DESCRIPTION', study_description, ...\n\t'ACQUISITION_TYPE', acquisition_type, ...\n\t'PATIENT_ORIENTATION', patient_orientation, ...\n\t'FACILITY_NAME', facility_name, ...\n\t'NUM_PLANES', num_planes, ...\n\t'NUM_FRAMES', num_frames, ...\n\t'NUM_GATES', num_gates, ...\n\t'NUM_BED_POS', num_bed_pos, ...\n\t'INIT_BED_POSITION', init_bed_position, ...\n\t'BED_POSITION', bed_position, ...\n\t'PLANE_SEPARATION', plane_separation, ...\n\t'LWR_SCTR_THRES', lwr_sctr_thres, ...\n\t'LWR_TRUE_THRES', lwr_true_thres, ...\n\t'UPR_TRUE_THRES', upr_true_thres, ...\n\t'USER_PROCESS_CODE', user_process_code, ...\n\t'ACQUISITION_MODE', acquisition_mode, ...\n\t'BIN_SIZE', bin_size, ...\n\t'BRANCHING_FRACTION', branching_fraction, ...\n\t'DOSE_START_TIME', dose_start_time, ...\n\t'DOSAGE', dosage, ...\n\t'WELL_COUNTER_CORR_FACTOR', well_counter_corr_factor, ...\n\t'DATA_UNITS', data_units, ...\n\t'SEPTA_STATE', septa_state, ...\n\t'FILL', fill);\nreturn;\n%_______________________________________________________________________\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_fmri_est.m", "ext": ".m", "path": "spm5-master/spm_config_fmri_est.m", "size": 27815, "source_encoding": "utf_8", "md5": "c8488b2513dccecb54fef8c96cdf60fb", "text": "function conf = spm_config_fmri_est\n% Configuration file for estimation of fMRI model\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Darren Gitelman and Will Penny\n% $Id: spm_config_fmri_est.m 832 2007-06-22 11:33:31Z will $\n\n\n% Define inline types.\n%-----------------------------------------------------------------------\n\nentry = inline(['struct(''type'',''entry'',''name'',name,'...\n '''tag'',tag,''strtype'',strtype,''num'',num,''help'',hlp)'],...\n 'name','tag','strtype','num','hlp');\n\nfiles = inline(['struct(''type'',''files'',''name'',name,'...\n '''tag'',tag,''filter'',fltr,''num'',num,''help'',hlp)'],...\n 'name','tag','fltr','num','hlp');\n\nmnu = inline(['struct(''type'',''menu'',''name'',name,'...\n '''tag'',tag,''labels'',{labels},''values'',{values},''help'',hlp)'],...\n 'name','tag','labels','values','hlp');\n\nbranch = inline(['struct(''type'',''branch'',''name'',name,'...\n '''tag'',tag,''val'',{val},''help'',hlp)'],...\n 'name','tag','val','hlp');\n\nrepeat = inline(['struct(''type'',''repeat'',''name'',name,'...\n '''tag'',tag,''values'',{values},''help'',hlp)'],...\n 'name','tag','values','hlp');\n\nchoice = inline(['struct(''type'',''choice'',''name'',name,'...\n '''tag'',tag,''values'',{values},''help'',hlp)'],...\n 'name','tag','values','hlp');\n\n%-----------------------------------------------------------------------\n\nsp_text = [' ',...\n ' '];\n\n%-------------------------------------------------------------------------\n\nspm.type = 'files';\nspm.name = 'Select SPM.mat';\nspm.tag = 'spmmat';\nspm.num = [1 1];\nspm.filter = 'mat';\nspm.ufilter = '^SPM\\.mat$';\nspm.help = {'Select the SPM.mat file that contains the design specification. ',...\n 'The directory containing this file is known as the input directory.'};\n\n \n% Bayesian estimation over slices or whole volume ?\n\nslices = entry('Slices','Slices','e',[Inf 1],'');\np1=['Enter Slice Numbers. This can be a single slice or multiple slices. ',...\n 'If you select a single slice or only a few slices you must be aware of the ',...\n 'interpolation options when, after estimation, displaying the estimated ',...\n 'images eg. images of contrasts or AR maps. ',...\n 'The default interpolation option may need to be changed to nearest neighbour (NN) ',...\n '(see bottom right hand of graphics window) for you slice maps to be visible.'];\nslices.help={p1};\n\nvolume = struct('type','const','name','Volume','tag','Volume','val',{{1}});\np1=['You have selected the Volume option. SPM will analyse fMRI ',...\n 'time series in all slices of each volume.'];\nvolume.help={p1};\n\nspace = choice('Analysis Space','space',{volume,slices},'');\np1=['Because estimation can be time consuming an option is provided to analyse ',...\n 'selected slices rather than the whole volume.'];\nspace.help={p1};\nspace.val={volume};\n\n% Regression coefficient priors for Bayesian estimation\n\nw_prior = mnu('Signal priors','signal',{'GMRF','LORETA','Global','Uninformative'},...\n {'GMRF','LORETA','Global','Uninformative'},{'Signal priors'});\nw_prior.val={'GMRF'};\np1=['[GMRF] Gaussian Markov Random Field. This spatial prior is the recommended option. ',...\n 'Regression coefficients at a given voxel are (softly) constrained to be similar to those at ',...\n 'nearby voxels. The strength of this constraint is determined by a spatial precision ',...\n 'parameter that is estimated from the data. Different regression coefficients have ',...\n 'different spatial precisions allowing each putative experimental effect to have its ',...\n 'own spatial regularity. '];\np2=['[LORETA] Low resolution Tomography Prior. This spatial prior is very similar to the GMRF ',...\n 'prior and is a standatd choice for EEG source localisation algorithms. It does, however, ',...\n 'have undesirable edge effects.'];\np3=['[Global] Global Shrinkage prior. This is not a spatial prior in the sense that ',...\n 'regression coefficients are constrained to be similar to neighboring voxels. ',...\n 'Instead, the average effect over all voxels (global effect) is assumed to be zero ',...\n 'and all regression coefficients are shrunk towards this value in proporation to the ',...\n 'prior precision. This is the same prior that is used for Bayesian estimation at the ',...\n 'second level models, except that here the prior precision is estimated separaetly ',...\n 'for each slice. '];\np4=['[Uninformative] A flat prior. Essentially, no prior information is used. ',...\n 'If you select this option then VB reduces to Maximum Likelihood (ML)',...\n 'estimation. This option is useful if, for example, you do not wish to ',...\n 'use a spatial prior but wish to take advantage of the voxel-wise AR(P) ',...\n 'modelling of noise processes. In this case, you would apply the algorithm ',...\n 'to images that have been spatially smoothed. For P=0, ML estimation ',...\n 'in turn reduces to Ordinary Least Squares (OLS) estimates, and for P>0 ',...\n 'ML estimation is equivalent to a weighted least squares (WLS) but where the ',...\n 'weights are different at each voxel (reflecting the different noise correlation ',...\n 'at each voxel). '];\nw_prior.help={p1,sp_text,p2,sp_text,p3,sp_text,p4};\n\n% AR model order for Bayesian estimation\n\narp = entry('AR model order','ARP','e',[Inf 1],'Enter AR model order');\narp.val={3};\np1=['An AR model order of 3 is the default. Cardiac and respiratory artifacts ',...\n 'are periodic in nature and therefore require an AR order of at least 2. In ',...\n 'previous work, voxel-wise selection of the optimal model order showed that a ',...\n 'value of 3 was the highest order required. '];\np2=['Higher model orders have little ',...\n 'effect on the estimation time. If you select a model order of zero this ',...\n 'corresponds to the assumption that the errors are IID. This AR specification ',...\n 'overrides any choices that were made in the model specification stage.'];\np3=['Voxel-wise AR models are fitted separately for each session of data. For each ',...\n 'session this therefore produces maps of AR(1), AR(2) etc coefficients in the ',...\n 'output directory. '];\narp.help={p1,sp_text,p2,sp_text,p3};\n\n% AR coefficient priors for Bayesian estimation\n\na_gmrf = struct('type','const','name','GMRF','tag','GMRF','val',{{1}});\np1=['[GMRF] Gaussian Markov Random Field. This is the default option. ',...\n 'This spatial prior is the same as that used for the ',...\n 'regression coefficients. Spatial precisions are estimated separately for each ',...\n 'AR coefficient eg. the AR(1) coefficient over space, AR(2) over space etc. '];\na_gmrf.help={p1};\n\na_loreta = struct('type','const','name','LORETA','tag','LORETA','val',{{1}});\np1=['[LORETA] Low resolution Tomography Prior. See comments on LORETA priors ',...\n 'for regresion coefficients.'];\na_loreta.help={p1};\n\na_tissue_type = files('Tissue-type','tissue_type','image',[1 Inf],'Select tissue-type images');\np1=['[Tissue-type] AR estimates at each voxel are biased towards typical ',...\n 'values for that tissue type (eg. gray, white, CSF). If you select this ',...\n 'option you will need to then ',...\n 'select files that contain tissue type maps (see below). ',...\n 'These are typically chosen to be ',...\n 'Grey Matter, White Matter and CSF images derived from segmentation of ',...\n 'registered structural scans.'];\np2=['Previous work has shown that ',...\n 'there is significant variation in AR values with tissue type. However, GMRF priors ',...\n 'have previously been favoured by Bayesian model comparison.'];\na_tissue_type.help={p1,sp_text,p2};\n\na_robust = struct('type','const','name','Robust','tag','Robust','val',{{1}});\np1=['Robust GLM. Uses Mixture of Gaussians noise model.'];\na_robust.help={p1};\n\na_prior = choice('Noise priors','noise',{a_gmrf,a_loreta,a_tissue_type,a_robust},'Noise priors');\na_prior.val={a_gmrf};\na_prior.help={'There are four noise prior options here (1) GMRF, (2) LORETA ',...\n '(3) Tissue-type and (4) Robust'};\n\n% ANOVA options\n\nfirst = mnu('First level','first',...\n {'No','Yes'},{'No','Yes'},{''});\nfirst.val={'No'};\np1=['This is implemented using Bayesian model comparison. For example, to test for ',...\n 'the main effect of a factor two models are compared, one where the levels are ',...\n 'represented using different regressors and one using the same regressor. ',...\n 'This therefore requires explicit fitting of several models at each voxel and is ',...\n 'computationally demanding (requiring several hours of computation). ',...\n 'The recommended option is therefore NO.'];\np2=['To use this option you must have already specified your factorial design ',...\n 'during the model specification stage. '];\nfirst.help={p1,sp_text,p2};\n\nsecond = mnu('Second level','second',...\n {'No','Yes'},{'No','Yes'},{''});\nsecond.val={'Yes'};\np1=['This option tells SPM to automatically generate ',...\n 'the simple contrasts that are necessary to produce the contrast images ',...\n 'for a second-level (between-subject) ANOVA. Naturally, these contrasts can ',...\n 'also be used to characterise simple effects for each subject. '];\np2= ['With the Bayesian estimation ',...\n 'option it is recommended that contrasts are computed during the parameter ',...\n 'estimation stage (see ''simple contrasts'' below). ',...\n 'The recommended option here is therefore YES.'];\np3=['To use this option you must have already specified your factorial design ',...\n 'during the model specification stage. '];\np4=['If you wish to use these contrast images for a second-level analysis then ',...\n 'you will need to spatially smooth them to take into account between-subject ',...\n 'differences in functional anatomy ie. the fact that one persons V5 may be in ',...\n 'a different position than anothers. '];\nsecond.help={p1,sp_text,p2,sp_text,p3,sp_text,p4};\n\nanova.type = 'branch';\nanova.name = 'ANOVA';\nanova.tag = 'anova';\nanova.val = {first,second};\nanova.help = {'Perform 1st or 2nd level Analysis of Variance.'};\n\n% Contrasts to be computed during Bayesian estimation\n\nname.type = 'entry';\nname.name = 'Name';\nname.tag = 'name';\nname.strtype = 's';\nname.num = [1 1];\nname.help = {'Name of contrast eg. ''Positive Effect'''};\n\ngconvec = entry('Contrast vector','convec','e',[Inf 1],'');\np1=['These contrasts are used to generate PPMs which ',...\n 'characterise effect ',...\n 'sizes at each voxel. This is in contrast to SPMs in which eg. maps of t-statistics ',...\n 'show the ratio of the effect size to effect variability (standard deviation). ',...\n 'SPMs are therefore a-dimensional. This is not the case for PPMs as the size of the ',...\n 'effect is of primary interest. Some care is therefore needed about the scaling of ',...\n 'contrast vectors. For example, if you are interested in the differential effect ',...\n 'size averaged over conditions then the contrast 0.5 0.5 -0.5 -0.5 would be more ',...\n 'suitable than the 1 1 -1 -1 contrast which looks at the differential effect size ',...\n 'summed over conditions. '];\ngconvec.help = {p1};\n \ngcon.type = 'branch';\ngcon.name = 'Simple contrast';\ngcon.tag = 'gcon';\ngcon.val = {name,gconvec};\ngcon.help = {''};\n \ncontrast.type = 'repeat';\ncontrast.name = 'Simple contrasts';\ncontrast.tag = 'contrasts';\ncontrast.values = {gcon};\np1=['''Simple'' contrasts refers to a contrast that spans one-dimension ie. ',...\n 'to assess an effect that is increasing or decreasing.'];\np2 =['If you have a factoral design then the contrasts needed to generate ',...\n 'the contrast images for a 2nd-level ANOVA (or to assess these simple effects ',...\n 'within-subject) can be specified automatically ',...\n 'using the ANOVA->Second level option.'];\np3 =['When using the Bayesian estimation option it is computationally more ',...\n 'efficient to compute the contrasts when the parameters are estimated. ',...\n 'This is because estimated parameter vectors have potentially different ',...\n 'posterior covariance matrices at different voxels ',...\n 'and these matrices are not stored. If you compute contrasts ',...\n 'post-hoc these matrices must be recomputed (an approximate reconstruction ',...\n 'based on a Taylor series expansion is used). ',...\n 'It is therefore recommended to specify as many contrasts as possible ',...\n 'prior to parameter estimation.'];\np4=['If you wish to use these contrast images for a second-level analysis then ',...\n 'you will need to spatially smooth them to take into account between-subject ',...\n 'differences in functional anatomy ie. the fact that one persons V5 may be in ',...\n 'a different position than anothers. '];\ncontrast.help={p1,sp_text,p2,sp_text,p3,sp_text,p4};\n\n% Bayesian estimation\n\nest_bayes2 = struct('type','const','name','Bayesian 2nd-level','tag','Bayesian2','val',{{1}});\np1=['Bayesian estimation of 2nd level models. This option uses the Empirical Bayes ',...\n 'algorithm with global shrinkage priors that was previously implemented in SPM2. ',...\n 'Use of the global shrinkage prior embodies a prior belief that, on average over all ',...\n 'voxels, there is no net experimental effect. Some voxels will respond negatively ',...\n 'and some positively with a variability determined by the prior precision. ',...\n 'This prior precision can be estimated from the data using Empirical Bayes. '];\nest_bayes2.help={p1};\n\nest_bayes1 = branch('Bayesian 1st-level','Bayesian',{space,w_prior,arp,a_prior,anova,contrast},'Bayesian Estimation');\nbayes_1 = ['Model parameters are estimated using Variational Bayes (VB). ',...\n 'This allows you to specify spatial priors for regression coefficients ',...\n 'and regularised voxel-wise AR(P) models for fMRI noise processes. ',...\n 'The algorithm does not require functional images to be spatially smoothed. ',...\n 'Estimation will take about 5 times longer than with the classical approach. ',...\n 'This is why VB is not the default estimation option. '];\np2=['Model estimation using this option is only efficient ',...\n 'if MATLAB can load a whole slice of data into physical memory. With modern PCs ',...\n 'this is usually achieved if the within-plane voxel sizes are 3 by 3 mm. This is therefore ',...\n 'the minimum recommended voxel size that your spatial normalisation process should ',...\n 'produce. Within-plane voxel sizes of 2 by 2 mm usually result in too many voxels per slice and result ',...\n 'in estimation times lasting several hours or days. Such a high resolution is therefore to be ',...\n 'avoided. '];\nbayes_2 = ['After estimation, contrasts are used to find regions with effects larger ',...\n 'than a user-specified size eg. 1 per cent of the global mean signal. ',...\n 'These effects are assessed statistically using a Posterior Probability Map (PPM).'];\nest_bayes1.help={bayes_1,sp_text,p2,sp_text,bayes_2};\n\n% Classical (ReML) estimation\n\nest_class = struct('type','const','name','Classical','tag','Classical','val',{{1}});\nclassical_1 =['Model parameters are estimated using Restricted Maximum ',...\n 'Likelihood (ReML). This assumes the error correlation structure is the ',...\n 'same at each voxel. This correlation can be specified using either an ',...\n 'AR(1) or an Independent and Identically Distributed (IID) error ',...\n 'model. These options are chosen at the model specification stage. ',...\n 'ReML estimation should be applied to spatially ',...\n 'smoothed functional images.'];\nclassical_2 = ['After estimation, specific profiles of parameters are tested using a linear ',...\n 'compound or contrast with the T or F statistic. The resulting statistical map ',...\n 'constitutes an SPM. The SPM{T}/{F} is then characterised in terms of ',...\n 'focal or regional differences by assuming that (under the null hypothesis) ',...\n 'the components of the SPM (ie. residual fields) behave as smooth stationary ',...\n 'Gaussian fields.'];\nest_class.help={classical_1,sp_text,classical_2};\n\n% Select method of estimation - Bayesian or classical\n\nmeth = choice('Method','method',{est_class,est_bayes1,est_bayes2},{'Type of estimation procedure'});\nmeth.val={est_class};\np1=['There are three possible estimation procedures for fMRI models (1) classical (ReML) estimation of ',...\n 'first or second level models, (2) Bayesian estimation of first level models and ',...\n '(3) Bayesian estimation of second level models. ',...\n 'Option (2) uses a Variational Bayes (VB) algorithm that is new to SPM5. ',...\n 'Option (3) uses the Empirical ',...\n 'Bayes algorithm with global shrinkage priors that was also in SPM2. '];\np2=['To use option (3) you must have already estimated the model using option (1). ',...\n 'That is, for second-level models you must run a ReML estimation before ',...\n 'running a Bayesian estimation. This is not necessary for option (2). Bayesian ',...\n 'estimation of 1st-level models using VB does not require a prior ReML estimation.'];\nmeth.help={p1,sp_text,p2};\n\n\n%-------------------------------------------------------------------------\n\nconf = branch('Model estimation','fmri_est',...\n {spm,meth},'Model estimation');\nconf.prog = @run_est;\nconf.vfiles = @vfiles_stats;\nconf.modality = {'FMRI','PET'};\np1 = [...\n 'Model parameters can be estimated using ',...\n 'classical (ReML - Restricted Maximum Likelihood) or Bayesian algorithms. ',...\n 'After parameter estimation, the RESULTS button can be used to specify ',...\n 'contrasts that will produce Statistical Parametric Maps (SPMs) or ',...\n 'Posterior Probability Maps (PPMs) and tables of statistics.'];\n\nconf.help = {p1};\n\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction run_est(job)\n% Set up the design matrix and run a design.\n\nglobal defaults\nif isempty(defaults)\n spm_defaults;\nend;\nif ~isfield(defaults,'modality')\n defaults.modality = 'FMRI';\nend;\n\n%-Load SPM.mat file\n%-----------------------------------------------------------------------\nSPM = [];\nload(job.spmmat{:});\n\noriginal_dir = pwd;\n\n%-Move to the directory where the SPM.mat file is\n%-----------------------------------------------------------------------\ncd(fileparts(job.spmmat{:}));\n\n% COMMENTED OUT BY DRG. THIS SHOULD BE TAKEN CARE OF WITHIN SPM_SPM AND\n% SPM_SPM_BAYES. REMOVE THIS SECTION ONCE THIS HAS BEEN VERIFIED.\n%-If we've gotten to this point we're committed to overwriting files.\n% Delete them so we don't get stuck in spm_spm\n%-----------------------------------------------------------------------\n% files = {'^mask\\..{3}$','^ResMS\\..{3}$','^RPV\\..{3}$',...\n% '^beta_.{4}\\..{3}$','^con_.{4}\\..{3}$','^ResI_.{4}\\..{3}$',...\n% '^ess_.{4}\\..{3}$', '^spm\\w{1}_.{4}\\..{3}$'};\n% \n% for i=1:length(files)\n% j = spm_select('List',pwd,files{i});\n% for k=1:size(j,1)\n% spm_unlink(deblank(j(k,:)));\n% end\n% end\n% END COMMENTED OUT BY DRG\n\n%=======================================================================\n% B A Y E S I A N 2nd L E V E L E S T I M A T I O N\n%=======================================================================\nif isfield(job.method,'Bayesian2')\n SPM = spm_spm_Bayes(SPM);\n cd(original_dir); % Change back\n fprintf('Done\\n');\n return\nend\n\n%=======================================================================\n% R E M L E S T I M A T I O N\n%=======================================================================\nif isfield(job.method,'Classical'),\n \n SPM = spm_spm(SPM);\n \n %-Automatically set up contrasts for factorial designs\n %-------------------------------------------------------------------\n if isfield(SPM,'factor')\n if SPM.factor(1).levels > 1\n\t\t% don't both if you've only got 1 level and 1 factor\n cons = spm_design_contrasts(SPM);\n \n %-Create F-contrasts\n %-----------------------------------------------------------\n for i=1:length(cons)\n con = cons(i).c;\n name = cons(i).name;\n STAT = 'F';\n [c,I,emsg,imsg] = spm_conman('ParseCon',con,SPM.xX.xKXs,STAT);\n if all(I)\n DxCon = spm_FcUtil('Set',name,STAT,'c',c,SPM.xX.xKXs);\n else\n DxCon = [];\n end\n if isempty(SPM.xCon),\n SPM.xCon = DxCon;\n else\n SPM.xCon(end+1) = DxCon;\n end\n SPM = spm_contrasts(SPM,length(SPM.xCon));\n end\n \n %-Create t-contrasts\n %-----------------------------------------------------------\n for i=1:length(cons)\n % Create a t-contrast for each row of each F-contrast\n % The resulting contrast image can be used in a 2nd-level analysis\n Fcon = cons(i).c;\n nrows = size(Fcon,1);\n STAT = 'T';\n for r=1:nrows,\n con = Fcon(r,:); \n str = cons(i).name;\n if ~isempty(strmatch('Interaction',str))\n name = ['Positive ',str,'_',int2str(r)];\n else\n sp1 = min(find(isspace(str))); \n name = ['Positive',str(sp1:end),'_',int2str(r)];\n end\n \n [c,I,emsg,imsg] = spm_conman('ParseCon',con,SPM.xX.xKXs,STAT);\n if all(I)\n DxCon = spm_FcUtil('Set',name,STAT,'c',c,SPM.xX.xKXs);\n else\n DxCon = [];\n end\n if isempty(SPM.xCon),\n SPM.xCon = DxCon;\n else\n SPM.xCon(end+1) = DxCon;\n end\n SPM = spm_contrasts(SPM,length(SPM.xCon));\n end\n end\n end % if SPM.factor(1).levels > 1\n end % if isfield(SPM,'factor')\n \n cd(original_dir); % Change back\n fprintf('Done\\n');\n return\nend\n\n%=======================================================================\n% B A Y E S I A N 1st L E V E L E S T I M A T I O N\n%=======================================================================\n\n%-Analyse specific slices or whole volume\n%-----------------------------------------------------------------------\nif isfield(job.method.Bayesian.space,'Slices')\n SPM.PPM.space_type = 'Slices';\n SPM.PPM.AN_slices = job.method.Bayesian.space.Slices;\nelse\n SPM.PPM.space_type = 'Volume';\nend\n\n%-Regression coefficient priors\n%-----------------------------------------------------------------------\nswitch job.method.Bayesian.signal\n case 'GMRF',\n SPM.PPM.priors.W = 'Spatial - GMRF';\n case 'LORETA',\n SPM.PPM.priors.W = 'Spatial - LORETA';\n case 'Global',\n SPM.PPM.priors.W = 'Voxel - Shrinkage';\n case 'Uninformative',\n SPM.PPM.priors.W = 'Voxel - Uninformative';\n otherwise\n error('Unkown prior for W in spm_config_fmri_est');\nend\n\n%-Number of AR coefficients\n%-----------------------------------------------------------------------\nSPM.PPM.AR_P = job.method.Bayesian.ARP;\n\n%-AR coefficient priors\n%-----------------------------------------------------------------------\nif isfield(job.method.Bayesian.noise,'GMRF')\n SPM.PPM.priors.A = 'Spatial - GMRF';\nelseif isfield(job.method.Bayesian.noise,'LORETA')\n SPM.PPM.priors.A = 'Spatial - LORETA';\nelseif isfield(job.method.Bayesian.noise,'tissue_type')\n SPM.PPM.priors.A = 'Discrete';\n SPM.PPM.priors.SY = job.method.Bayesian.noise.tissue_type;\nelseif isfield(job.method.Bayesian.noise,'Robust')\n SPM.PPM.priors.A = 'Robust';\n SPM.PPM.AR_P=0;\n SPM.PPM.update_F=1;\nend\n\n%-Define an empty contrast\n%-----------------------------------------------------------------------\nNullCon = spm_FcUtil('Set','','P','c',[],1);\nNullCon.X0 = [];\nNullCon.iX0 = [];\nNullCon.X1o = [];\nNullCon.eidf = 1;\n\nSPM.xCon = [];\n%-Set up contrasts for 2nd-level ANOVA\n%-----------------------------------------------------------------------\nif strcmp(job.method.Bayesian.anova.second,'Yes')\n if isfield(SPM,'factor')\n cons=spm_design_contrasts(SPM);\n for i=1:length(cons),\n % Create a simple contrast for each row of each F-contrast\n % The resulting contrast image can be used in a 2nd-level analysis\n Fcon=cons(i).c;\n nrows=size(Fcon,1);\n STAT='P';\n for r=1:nrows,\n con=Fcon(r,:); \n \n % Normalise contrast st. sum of positive elements is 1\n % and sum of negative elements is 1\n s1=length(find(con==1));\n con=con./s1;\n \n % Change name \n str=cons(i).name;\n sp1=min(find(str==' '));\n if strcmp(str(1:11),'Interaction')\n name=['Positive ',str,'_',int2str(r)];\n else\n name=['Positive',str(sp1:end),'_',int2str(r)];\n end\n \n DxCon=NullCon;\n DxCon.name=name;\n DxCon.c=con';\n \n if isempty(SPM.xCon),\n SPM.xCon = DxCon;\n else\n SPM.xCon(end+1) = DxCon;\n end\n end\n end\n end\nend\n\n%-Set up user-specified simple contrasts\n%-----------------------------------------------------------------------\nncon = length(job.method.Bayesian.gcon);\nK = size(SPM.xX.X,2);\nfor c = 1:ncon\n DxCon = NullCon;\n DxCon.name = job.method.Bayesian.gcon(c).name;\n convec = job.method.Bayesian.gcon(c).convec(:);\n if length(convec) == K\n DxCon.c = convec;\n else\n str = ['Error in contrast specification:' ...\n sprintf('\\n contrast has %d entries ', length(convec)) ...\n sprintf('but there are %d regressors !\\n', K)];\n error(str);\n end\n \n if isempty(SPM.xCon),\n SPM.xCon = DxCon;\n else\n SPM.xCon(end+1) = DxCon;\n end\nend\n \n%-1st level Bayesian ANOVA ?\n%-----------------------------------------------------------------------\nbayes_anova = 0;\nif strcmp(job.method.Bayesian.anova.first,'Yes')\n bayes_anova = 1;\n SPM.PPM.update_F = 1; % Compute evidence for each model\n SPM.PPM.compute_det_D = 1; \nend\n\n%-Variational Bayes estimation\n%-----------------------------------------------------------------------\nSPM = spm_spm_vb(SPM);\n\n%-Bayesian ANOVA using model comparison\n%-----------------------------------------------------------------------\nif bayes_anova\n % We don't want to estimate contrasts for each different model\n SPM.xCon = [];\n spm_vb_ppm_anova(SPM);\nend\n\ncd(original_dir); % Change back\nfprintf('Done\\n')\nreturn\n\n\n%=======================================================================\nfunction vf = vfiles_stats(job)\nvf = {job.spmmat{:}};\n\n% Should really create a few vfiles for beta images etc here as well.\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_platform.m", "ext": ".m", "path": "spm5-master/spm_platform.m", "size": 8489, "source_encoding": "utf_8", "md5": "1f602bafb359d64bef775a8d7b66b76d", "text": "function varargout=spm_platform(varargin)\n% Platform specific configuration parameters for SPM\n%\n% FORMAT ans = spm_platform(arg)\n% arg - optional string argument, can be\n% - 'bigend' - return whether this architecture is bigendian\n% - Inf - is not IEEE floating point\n% - 0 - is little end\n% - 1 - big end\n% - 'filesys' - type of filesystem\n% - 'unx' - UNIX\n% - 'win' - DOS\n% - 'mac' - Macintosh\n% - 'vms' - VMS\n% - 'sepchar' - returns directory separator\n% - 'rootlen' - returns number of chars in root directory name\n% - 'user' - returns username\n% - 'tempdir' - returns name of temp directory\n% - 'drives' - returns string containing valid drive letters\n%\n% FORMAT PlatFontNames = spm_platform('fonts')\n% Returns structure with fields named after the generic (UNIX) fonts, the\n% field containing the name of the platform specific font.\n%\n% FORMAT PlatFontName = spm_platform('font',GenFontName)\n% Maps generic (UNIX) FontNames to platform specific FontNames\n%\n% FORMAT PLATFORM = spm_platform('init',comp)\n% Initialises platform specific parameters in persistent PLATFORM\n% (External gateway to init_platform(comp) subfunction)\n% comp - computer to use [defaults to MatLab's `computer`]\n% PLATFORM - copy of persistent PLATFORM\n%\n% FORMAT spm_platform\n% Initialises platform specific parameters in persistent PLATFORM\n% (External gateway to init_platform(computer) subfunction)\n%\n% ----------------\n% SUBFUNCTIONS:\n%\n% FORMAT init_platform(comp)\n% Initialise platform specific parameters in persistent PLATFORM\n% comp - computer to use [defaults to MatLab's `computer`]\n%\n%-----------------------------------------------------------------------\n%\n% Since calls to spm_platform will be made frequently, most platform\n% specific parameters are stored as a structure in the persistent variable\n% PLATFORM. Subsequent calls use the information from this persistent\n% variable, if it exists.\n%\n% Platform specific difinitions are contained in the data structures at\n% the beginning of the init_platform subfunction at the end of this\n% file.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Matthew Brett\n% $Id: spm_platform.m 1962 2008-07-28 15:40:56Z guillaume $\n\n\n\n%-Initialise\n%-----------------------------------------------------------------------\npersistent PLATFORM\nif isempty(PLATFORM), PLATFORM = init_platform; end\n\nif nargin==0, return, end\n\n\nswitch lower(varargin{1}), case 'init' %-(re)initialise\n%=======================================================================\ninit_platform(varargin{2:end})\nvarargout = {PLATFORM};\n \ncase 'bigend' %-Return endian for this architecture\n%=======================================================================\nvarargout = {PLATFORM.bigend};\nif ~isfinite(PLATFORM.bigend),\n\tif isnan(PLATFORM.bigend)\n\t\terror(['I don''t know if \"',computer,'\" is big-endian.'])\n\telse\n\t\terror(['I don''t think that \"',computer,...\n\t\t\t'\" uses IEEE floating point ops.'])\n\tend\nend\n\ncase 'filesys' %-Return file system\n%=======================================================================\nvarargout = {PLATFORM.filesys};\n\ncase 'sepchar' %-Return file separator character\n%=======================================================================\nwarning('use filesep instead (supported by MathWorks)')\nvarargout = {PLATFORM.sepchar};\n\ncase 'rootlen' %-Return length in chars of root directory name \n%=======================================================================\nvarargout = {PLATFORM.rootlen};\n\ncase 'user' %-Return user string\n%=======================================================================\nvarargout = {PLATFORM.user};\n\ncase 'drives' %-Return drives\n%=======================================================================\nvarargout = {PLATFORM.drives};\n\ncase 'tempdir' %-Return temporary directory\n%=======================================================================\ntwd = getenv('SPMTMP');\nif isempty(twd)\n\ttwd = tempdir;\nend \nvarargout = {twd};\n\n\ncase {'font','fonts'} %-Map default font names to platform font names\n%=======================================================================\nif nargin<2, varargout={PLATFORM.font}; return, end\nswitch lower(varargin{2})\ncase 'times'\n\tvarargout = {PLATFORM.font.times};\ncase 'courier'\n\tvarargout = {PLATFORM.font.courier};\ncase 'helvetica'\n\tvarargout = {PLATFORM.font.helvetica};\ncase 'symbol'\n\tvarargout = {PLATFORM.font.symbol};\notherwise\n\twarning(['Unknown font ',varargin{2},', using default'])\n\tvarargout = {PLATFORM.font.helvetica};\nend\n\notherwise %-Unknown Action string\n%=======================================================================\nerror('Unknown Action string')\n\n%=======================================================================\nend\n\n\n\n%=======================================================================\n%- S U B - F U N C T I O N S\n%=======================================================================\n\n\nfunction PLATFORM = init_platform(comp) %-Initialise platform variables\n%=======================================================================\nif nargin<1, comp=computer; end\n\n%-Platform definitions\n%-----------------------------------------------------------------------\nPDefs = {\t'PCWIN',\t'win',\t0;...\n\t\t'PCWIN64',\t'win', 0;...\n\t\t'MAC',\t\t'unx',\t1;...\n\t\t'MACI',\t\t'unx',\t0;...\n\t\t'MACI64',\t'unx',\t0;...\n\t\t'SUN4',\t\t'unx',\t1;...\n\t\t'SOL2',\t\t'unx',\t1;...\n\t\t'SOL64',\t'unx',\t1;...\n\t\t'HP700',\t'unx',\t1;...\n\t\t'SGI',\t\t'unx',\t1;...\n\t\t'SGI64',\t'unx',\t1;...\n\t\t'IBM_RS',\t'unx',\t1;...\n\t\t'ALPHA',\t'unx',\t0;...\n\t\t'AXP_VMSG',\t'vms',\tInf;...\n\t\t'AXP_VMSIEEE',\t'vms',\t0;...\n\t\t'LNX86',\t'unx',\t0;...\n\t\t'GLNX86',\t'unx', 0;...\n\t\t'GLNXA64', 'unx', 0;...\n\t\t'VAX_VMSG',\t'vms',\tInf;...\n\t\t'VAX_VMSD',\t'vms',\tInf\t};\n\nPDefs = cell2struct(PDefs,{'computer','filesys','endian'},2);\n\n\n%-Which computer?\n%-----------------------------------------------------------------------\nci = find(strcmp({PDefs.computer},comp));\nif isempty(ci), error([comp,' not supported architecture for SPM']), end\n\n\n%-Set bigend\n%-----------------------------------------------------------------------\nPLATFORM.bigend = PDefs(ci).endian;\n\n\n%-Set filesys\n%-----------------------------------------------------------------------\nPLATFORM.filesys = PDefs(ci).filesys;\n\n\n%-Set filesystem dependent stuff\n%-----------------------------------------------------------------------\n%-File separators character\n%-Length of root directory strings\n%-User name finding\n%-(mouse button labels?)\nswitch (PLATFORM.filesys)\ncase 'unx'\n\tPLATFORM.sepchar = '/';\n\tPLATFORM.rootlen = 1;\n\tPLATFORM.user = getenv('USER');\ncase 'win'\n\tPLATFORM.sepchar = '\\';\n\tPLATFORM.rootlen = 3;\n\tPLATFORM.user = getenv('USERNAME');\n\tif isempty(PLATFORM.user)\n\t\tPLATFORM.user = 'anon';\n\tend\notherwise\n\terror(['Don''t know filesystem ',PLATFORM.filesys])\nend\n\n%-Drives\n%-----------------------------------------------------------------------\nPLATFORM.drives = '';\nif strcmp(comp,'PCWIN') || strcmp(comp,'PCWIN64'),\n driveLett = cellstr(char(('C':'Z')'));\n for i=1:numel(driveLett),\n if exist([driveLett{i} ':\\']) == 7,\n PLATFORM.drives = [PLATFORM.drives driveLett{i}];\n end\n end\nend\n\n%-Fonts\n%-----------------------------------------------------------------------\nswitch comp\ncase {'SOL2'}\t%-Some Sol2 platforms give segmentation violations with Helvetica\n\tPLATFORM.font.helvetica = 'Lucida';\n\tPLATFORM.font.times = 'Times';\n\tPLATFORM.font.courier = 'Courier';\n\tPLATFORM.font.symbol = 'Symbol';\ncase {'SUN4','SOL2','SOL64','HP700','SGI','SGI64','IBM_RS','ALPHA','LNX86','GLNX86','GLNXA64','MAC','MACI','MACI64'}\n\tPLATFORM.font.helvetica = 'Helvetica';\n\tPLATFORM.font.times = 'Times';\n\tPLATFORM.font.courier = 'Courier';\n\tPLATFORM.font.symbol = 'Symbol';\ncase {'PCWIN','PCWIN64'}\n\tPLATFORM.font.helvetica = 'Arial Narrow';\n\tPLATFORM.font.times = 'Times New Roman';\n\tPLATFORM.font.courier = 'Courier New';\n\tPLATFORM.font.symbol = 'Symbol';\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_fmri_data.m", "ext": ".m", "path": "spm5-master/spm_config_fmri_data.m", "size": 5006, "source_encoding": "utf_8", "md5": "38c392121fbd8c522ef579797945a857", "text": "function conf = spm_config_fmri_data\n% Configuration file for specification of fMRI model\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Darren Gitelman and Will Penny\n% $Id: spm_config_fmri_data.m 766 2007-03-15 14:09:30Z volkmar $\n\n\n% Define inline types.\n%-----------------------------------------------------------------------\n\nentry = inline(['struct(''type'',''entry'',''name'',name,'...\n '''tag'',tag,''strtype'',strtype,''num'',num,''help'',hlp)'],...\n 'name','tag','strtype','num','hlp');\n\nfiles = inline(['struct(''type'',''files'',''name'',name,'...\n '''tag'',tag,''filter'',fltr,''num'',num,''help'',hlp)'],...\n 'name','tag','fltr','num','hlp');\n\nmnu = inline(['struct(''type'',''menu'',''name'',name,'...\n '''tag'',tag,''labels'',{labels},''values'',{values},''help'',hlp)'],...\n 'name','tag','labels','values','hlp');\n\nbranch = inline(['struct(''type'',''branch'',''name'',name,'...\n '''tag'',tag,''val'',{val},''help'',hlp)'],...\n 'name','tag','val','hlp');\n\nrepeat = inline(['struct(''type'',''repeat'',''name'',name,'...\n '''tag'',tag,''values'',{values},''help'',hlp)'],...\n 'name','tag','values','hlp');\n\nchoice = inline(['struct(''type'',''choice'',''name'',name,'...\n '''tag'',tag,''values'',{values},''help'',hlp)'],...\n 'name','tag','values','hlp');\n\n%-----------------------------------------------------------------------\n\nsp_text = [' ',...\n ' '];\n%-----------------------------------------------------------------------\n\nscans = files('Scans','scans','image',[1 Inf],'Select scans');\nscans.help = {[...\n 'Select the fMRI scans for this session. They must all have the same ',...\n 'image dimensions, orientation, voxel size etc.']};\n\n%-------------------------------------------------------------------------\n\nmask = files('Explicit mask','mask','image',[0 1],'Image mask');\nmask.val = {''};\np1=['Specify an image for explicitly masking the analysis. ',...\n 'A sensible option here is to use a segmention of structural images ',...\n 'to specify a within-brain mask. If you select that image as an ',...\n 'explicit mask then only those voxels in the brain will be analysed. ',...\n 'This both speeds the estimation and restricts SPMs/PPMs to within-brain ',...\n 'voxels. Alternatively, if such structural images are unavailble or no ',...\n 'masking is required, then leave this field empty.'];\nmask.help={p1};\n\n%-------------------------------------------------------------------------\n\nspmmat = files('Select SPM.mat','spmmat','mat',1,'');\nspmmat.help = {[...\n 'Select the SPM.mat file containing the ',...\n 'specified design matrix.']};\n\n%-------------------------------------------------------------------------\n\nconf = branch('fMRI data specification','fmri_data',...\n {scans,spmmat,mask},'fMRI data');\nconf.prog = @run_stats;\nconf.vfiles = @vfiles_stats;\nconf.modality = {'FMRI'};\nconf.help = {['Select the data and optional explicit mask for a specified ' ...\n 'design']};\n\nreturn;\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\nfunction my_cd(varargin)\n% jobDir must be the actual directory to change to, NOT the job structure.\njobDir = varargin{1};\nif ~isempty(jobDir)\n try\n cd(char(jobDir));\n fprintf('Changing directory to: %s\\n',char(jobDir));\n catch\n error('Failed to change directory. Aborting run.')\n end\nend\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction run_stats(job)\n% Set up the design matrix and run a design.\n\nspm_defaults;\nglobal defaults\ndefaults.modality='FMRI';\n\noriginal_dir = pwd;\n[p n e v] = fileparts(job.spmmat{1});\nmy_cd(p);\nload(job.spmmat{1}); \n% Image filenames\n%-------------------------------------------------------------\nSPM.xY.P = strvcat(job.scans);\n\n% Let SPM configure the design\n%-------------------------------------------------------------\nSPM = spm_fmri_spm_ui(SPM);\n\nif ~isempty(job.mask)&&~isempty(job.mask{1})\n SPM.xM.VM = spm_vol(job.mask{:});\n SPM.xM.xs.Masking = [SPM.xM.xs.Masking, '+explicit mask'];\nend\n\n%-Save SPM.mat\n%-----------------------------------------------------------------------\nfprintf('%-40s: ','Saving SPM configuration') %-#\nif str2num(version('-release'))>=14,\n save('SPM','-V6','SPM');\nelse\n save('SPM','SPM');\nend;\n\nfprintf('%30s\\n','...SPM.mat saved') %-#\n\n\nmy_cd(original_dir); % Change back dir\nfprintf('Done\\n')\nreturn\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\nfunction vf = vfiles_stats(job)\nvf = job.spmmat;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_preproc.m", "ext": ".m", "path": "spm5-master/spm_preproc.m", "size": 20570, "source_encoding": "utf_8", "md5": "65a2123b974d0b044cd06712ed982964", "text": "function results = spm_preproc(varargin)\n% Combined Segmentation and Spatial Normalisation\n%\n% FORMAT results = spm_preproc(V,opts)\n% V - image to work with\n% opts - options\n% opts.tpm - n tissue probability images for each class\n% opts.ngaus - number of Gaussians per class (n+1 classes)\n% opts.warpreg - warping regularisation\n% opts.warpco - cutoff distance for DCT basis functions\n% opts.biasreg - regularisation for bias correction\n% opts.biasfwhm - FWHM of Gausian form for bias regularisation\n% opts.regtype - regularisation for affine part\n% opts.fudge - a fudge factor\n% opts.msk - unused\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_preproc.m 946 2007-10-15 16:36:06Z john $\n\n\n[dir,nam,ext] = fileparts(which(mfilename));\nopts0.tpm = char(...\n fullfile(dir,'tpm','grey.nii'),...\n fullfile(dir,'tpm','white.nii'),...\n fullfile(dir,'tpm','csf.nii'));\nopts0.ngaus = [2 2 2 4];\nopts0.warpreg = 1;\nopts0.warpco = 25;\nopts0.biasreg = 0.0001;\nopts0.biasfwhm = 75;\nopts0.regtype = 'mni';\nopts0.fudge = 5;\nopts0.samp = 3;\nopts0.msk = '';\n\nif nargin==0\n V = spm_select(1,'image');\nelse\n V = varargin{1};\nend;\nif ischar(V), V = spm_vol(V); end;\n\nif nargin < 2\n opts = opts0;\nelse\n opts = varargin{2};\n fnms = fieldnames(opts0);\n for i=1:length(fnms)\n if ~isfield(opts,fnms{i}), opts.(fnms{i}) = opts0.(fnms{i}); end;\n end;\nend;\n\nif length(opts.ngaus)~= size(opts.tpm,1)+1,\n error('Number of Gaussians per class is not compatible with number of classes');\nend;\nK = sum(opts.ngaus);\nKb = length(opts.ngaus);\nlkp = [];\nfor k=1:Kb,\n lkp = [lkp ones(1,opts.ngaus(k))*k];\nend;\n\nB = spm_vol(opts.tpm);\nb0 = spm_load_priors(B);\n\nd = V(1).dim(1:3);\nvx = sqrt(sum(V(1).mat(1:3,1:3).^2));\nsk = max([1 1 1],round(opts.samp*[1 1 1]./vx));\n[x0,y0,o] = ndgrid(1:sk(1):d(1),1:sk(2):d(2),1);\nz0 = 1:sk(3):d(3);\ntiny = eps;\n\nvx = sqrt(sum(V(1).mat(1:3,1:3).^2));\nkron = inline('spm_krutil(a,b)','a','b');\n\n% BENDING ENERGY REGULARIZATION for warping\n%-----------------------------------------------------------------------\nlam = 0.001;\nd2 = max(round((V(1).dim(1:3).*vx)/opts.warpco),[1 1 1]);\nkx = (pi*((1:d2(1))'-1)/d(1)/vx(1)).^2;\nky = (pi*((1:d2(2))'-1)/d(2)/vx(2)).^2;\nkz = (pi*((1:d2(3))'-1)/d(3)/vx(3)).^2;\nCwarp = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^2,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^0,kx.^2)) +...\n 2*kron(kz.^1,kron(ky.^1,kx.^0)) +...\n 2*kron(kz.^1,kron(ky.^0,kx.^1)) +...\n 2*kron(kz.^0,kron(ky.^1,kx.^1)) );\nCwarp = Cwarp*opts.warpreg;\nCwarp = [Cwarp*vx(1)^4 ; Cwarp*vx(2)^4 ; Cwarp*vx(3)^4];\nCwarp = sparse(1:length(Cwarp),1:length(Cwarp),Cwarp,length(Cwarp),length(Cwarp));\nB3warp = spm_dctmtx(d(3),d2(3),z0);\nB2warp = spm_dctmtx(d(2),d2(2),y0(1,:)');\nB1warp = spm_dctmtx(d(1),d2(1),x0(:,1));\nlmR = speye(size(Cwarp));\nTwarp = zeros([d2 3]);\n\n% GAUSSIAN REGULARISATION for bias correction\n%-----------------------------------------------------------------------\nfwhm = opts.biasfwhm;\nsd = vx(1)*V(1).dim(1)/fwhm; d3(1) = ceil(sd*2); krn_x = exp(-(0:(d3(1)-1)).^2/sd.^2)/sqrt(vx(1));\nsd = vx(2)*V(1).dim(2)/fwhm; d3(2) = ceil(sd*2); krn_y = exp(-(0:(d3(2)-1)).^2/sd.^2)/sqrt(vx(2));\nsd = vx(3)*V(1).dim(3)/fwhm; d3(3) = ceil(sd*2); krn_z = exp(-(0:(d3(3)-1)).^2/sd.^2)/sqrt(vx(3));\nCbias = kron(krn_z,kron(krn_y,krn_x)).^(-2)*opts.biasreg;\nCbias = sparse(1:length(Cbias),1:length(Cbias),Cbias,length(Cbias),length(Cbias));\nB3bias = spm_dctmtx(d(3),d3(3),z0);\nB2bias = spm_dctmtx(d(2),d3(2),y0(1,:)');\nB1bias = spm_dctmtx(d(1),d3(1),x0(:,1));\nlmRb = speye(size(Cbias));\nTbias = zeros(d3);\n\n\n% Fudge Factor - to (approximately) account for\n% non-independence of voxels\nff = opts.fudge;\nff = max(1,ff^3/prod(sk)/abs(det(V.mat(1:3,1:3))));\nCwarp = Cwarp*ff;\nCbias = Cbias*ff;\n\nll = -Inf;\nllr = 0;\nllrb = 0;\ntol1 = 1e-4; % Stopping criterion. For more accuracy, use a smaller value\nd = [size(x0) length(z0)];\n\nf = zeros(d);\nfor z=1:length(z0),\n f(:,:,z) = spm_sample_vol(V,x0,y0,o*z0(z),0);\nend;\n[thresh,mx] = spm_minmax(f);\nmn = zeros(K,1);\nrand('state',0); % give same results each time\nfor k1=1:Kb,\n kk = sum(lkp==k1);\n mn(lkp==k1) = rand(kk,1)*mx;\nend;\nvr = ones(K,1)*mx^2;\nmg = ones(K,1)/K;\n\nif ~isempty(opts.msk),\n VM = spm_vol(opts.msk);\n if sum(sum((VM.mat-V(1).mat).^2)) > 1e-6 || any(VM.dim(1:3) ~= V(1).dim(1:3)),\n error('Mask must have the same dimensions and orientation as the image.');\n end;\nend;\n\nAffine = eye(4);\nif ~isempty(opts.regtype),\n Affine = spm_maff(V,{x0,y0,z0},b0,B(1).mat,Affine,opts.regtype,ff*100);\n Affine = spm_maff(V,{x0,y0,z0},b0,B(1).mat,Affine,opts.regtype,ff);\nend;\nM = B(1).mat\\Affine*V(1).mat;\n\nnm = 0;\nfor z=1:length(z0),\n x1 = M(1,1)*x0 + M(1,2)*y0 + (M(1,3)*z0(z) + M(1,4));\n y1 = M(2,1)*x0 + M(2,2)*y0 + (M(2,3)*z0(z) + M(2,4));\n z1 = M(3,1)*x0 + M(3,2)*y0 + (M(3,3)*z0(z) + M(3,4));\n buf(z).msk = spm_sample_priors(b0{end},x1,y1,z1,1)<(1-1/512);\n fz = f(:,:,z);\n %buf(z).msk = fz>thresh;\n buf(z).msk = buf(z).msk & isfinite(fz) & (fz~=0);\n\n if ~isempty(opts.msk),\n msk = spm_sample_vol(VM,x0,y0,o*z0(z),0);\n buf(z).msk = buf(z).msk & msk;\n end;\n buf(z).nm = sum(buf(z).msk(:));\n buf(z).f = fz(buf(z).msk);\n nm = nm + buf(z).nm;\n buf(z).bf(1:buf(z).nm,1) = single(1);\n buf(z).dat = single(0);\n if buf(z).nm,\n buf(z).dat(buf(z).nm,Kb) = single(0);\n end;\nend;\nclear f\n\nfinalit = 0;\n\nspm_chi2_plot('Init','Processing','Log-likelihood','Iteration');\nfor iter=1:100,\n\n if finalit,\n % THIS CODE MAY BE USED IN FUTURE\n\n % Reload the data for the final iteration. This iteration\n % does not do any registration, so there is no need to\n % mask out the background voxels.\n %------------------------------------------------------------\n llrb = -0.5*Tbias(:)'*Cbias*Tbias(:);\n for z=1:length(z0),\n fz = spm_sample_vol(V,x0,y0,o*z0(z),0);\n buf(z).msk = fz~=0;\n if ~isempty(opts.msk),\n msk = spm_sample_vol(VM,x0,y0,o*z0(z),0);\n buf(z).msk = buf(z).msk & msk;\n end;\n buf(z).nm = sum(buf(z).msk(:));\n buf(z).f = fz(buf(z).msk);\n nm = nm + buf(z).nm;\n buf(z).bf(1:buf(z).nm,1) = single(1);\n buf(z).dat = single(0);\n if buf(z).nm,\n buf(z).dat(buf(z).nm,Kb) = single(0);\n end;\n if buf(z).nm, \n bf = transf(B1bias,B2bias,B3bias(z,:),Tbias);\n tmp = bf(buf(z).msk);\n llrb = llrb + sum(tmp);\n buf(z).bf = single(exp(tmp));\n end;\n end;\n\n % The background won't fit well any more, so increase the\n % variances of these Gaussians in order to give it a chance\n vr(lkp(K)) = vr(lkp(K))*8;\n\n spm_chi2_plot('Init','Processing','Log-likelihood','Iteration');\n end;\n\n % Load the warped prior probability images into the buffer\n %------------------------------------------------------------\n for z=1:length(z0),\n if ~buf(z).nm, continue; end;\n [x1,y1,z1] = defs(Twarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk);\n for k1=1:Kb,\n tmp = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb);\n buf(z).dat(:,k1) = single(tmp);\n end;\n end;\n\n for iter1=1:10,\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Estimate cluster parameters\n %------------------------------------------------------------\n for subit=1:40,\n oll = ll;\n mom0 = zeros(K,1)+tiny;\n mom1 = zeros(K,1);\n mom2 = zeros(K,1);\n mgm = zeros(Kb,1);\n ll = llr+llrb;\n for z=1:length(z0),\n if ~buf(z).nm, continue; end;\n bf = double(buf(z).bf);\n cr = double(buf(z).f).*bf;\n q = zeros(buf(z).nm,K);\n b = zeros(buf(z).nm,Kb);\n s = zeros(buf(z).nm,1)+tiny;\n for k1=1:Kb,\n pr = double(buf(z).dat(:,k1));\n b(:,k1) = pr;\n s = s + pr*sum(mg(lkp==k1));\n end;\n for k1=1:Kb,\n b(:,k1) = b(:,k1)./s;\n end;\n mgm = mgm + sum(b,1)';\n for k=1:K,\n q(:,k) = mg(k)*b(:,lkp(k)) .* exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k));\n end;\n sq = sum(q,2)+tiny;\n ll = ll + sum(log(sq));\n for k=1:K, % Moments\n p1 = q(:,k)./sq; mom0(k) = mom0(k) + sum(p1(:));\n p1 = p1.*cr; mom1(k) = mom1(k) + sum(p1(:));\n p1 = p1.*cr; mom2(k) = mom2(k) + sum(p1(:));\n end;\n end;\n\n % Mixing proportions, Means and Variances\n for k=1:K,\n mg(k) = (mom0(k)+eps)/(mgm(lkp(k))+eps);\n mn(k) = mom1(k)/(mom0(k)+eps);\n vr(k) =(mom2(k)-mom1(k)*mom1(k)/mom0(k)+1e6*eps)/(mom0(k)+eps);\n vr(k) = max(vr(k),eps);\n end;\n\n if subit>1 || (iter>1 && ~finalit),\n spm_chi2_plot('Set',ll);\n end;\nif finalit, fprintf('Mix: %g\\n',ll); end;\n if subit == 1,\n ooll = ll;\n elseif (ll-oll)0,\n for subit=1:40,\n % Compute objective function and its 1st and second derivatives\n Alpha = zeros(prod(d3),prod(d3)); % Second derivatives\n Beta = zeros(prod(d3),1); % First derivatives\n ollrb = llrb;\n oll = ll;\n ll = llr+llrb;\n for z=1:length(z0),\n if ~buf(z).nm, continue; end;\n bf = double(buf(z).bf);\n cr = double(buf(z).f).*bf;\n q = zeros(buf(z).nm,K);\n for k=1:K,\n q(:,k) = double(buf(z).dat(:,lkp(k)))*mg(k);\n end;\n s = sum(q,2)+tiny;\n for k=1:K,\n q(:,k) = q(:,k)./s .* exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k));\n end;\n sq = sum(q,2)+tiny;\n ll = ll + sum(log(sq));\n\n w1 = zeros(buf(z).nm,1);\n w2 = zeros(buf(z).nm,1);\n for k=1:K,\n tmp = q(:,k)./sq/vr(k);\n w1 = w1 + tmp.*(mn(k) - cr);\n w2 = w2 + tmp;\n end;\n wt1 = zeros(d(1:2)); wt1(buf(z).msk) = 1 + cr.*w1;\n wt2 = zeros(d(1:2)); wt2(buf(z).msk) = cr.*(cr.*w2 - w1);\n b3 = B3bias(z,:)';\n Beta = Beta + kron(b3,spm_krutil(wt1,B1bias,B2bias,0));\n Alpha = Alpha + kron(b3*b3',spm_krutil(wt2,B1bias,B2bias,1));\n clear w1 w2 wt1 wt2 b3\n end;\n if finalit, fprintf('Bia: %g\\n',ll); end;\n if subit > 1 && ~(ll>oll),\n % Hasn't improved, so go back to previous solution\n Tbias = oTbias;\n llrb = ollrb;\n for z=1:length(z0),\n if ~buf(z).nm, continue; end;\n bf = transf(B1bias,B2bias,B3bias(z,:),Tbias);\n buf(z).bf = single(exp(bf(buf(z).msk)));\n end;\n break;\n else\n % Accept new solution\n spm_chi2_plot('Set',ll);\n oTbias = Tbias;\n if subit > 1 && ~((ll-oll)>tol1*nm),\n % Improvement is only small, so go to next step\n break;\n else\n % Use new solution and continue the Levenberg-Marquardt iterations\n Tbias = reshape((Alpha + Cbias + lmRb)\\((Alpha+lmRb)*Tbias(:) + Beta),d3);\n llrb = -0.5*Tbias(:)'*Cbias*Tbias(:);\n for z=1:length(z0),\n if ~buf(z).nm, continue; end;\n bf = transf(B1bias,B2bias,B3bias(z,:),Tbias);\n tmp = bf(buf(z).msk);\n llrb = llrb + sum(tmp);\n buf(z).bf = single(exp(tmp));\n end;\n end;\n end;\n end;\n if ~((ll-ooll)>tol1*nm), break; end;\n end;\n end;\n \n if finalit, break; end;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Estimate deformations\n %------------------------------------------------------------\n mg1 = full(sparse(lkp,1,mg));\n ll = llr+llrb;\n for z=1:length(z0),\n if ~buf(z).nm, continue; end;\n bf = double(buf(z).bf);\n cr = double(buf(z).f).*bf;\n q = zeros(buf(z).nm,Kb);\n tmp = zeros(buf(z).nm,1)+tiny;\n s = zeros(buf(z).nm,1)+tiny;\n for k1=1:Kb,\n s = s + mg1(k1)*double(buf(z).dat(:,k1));\n end;\n for k1=1:Kb,\n kk = find(lkp==k1);\n pp = zeros(buf(z).nm,1);\n for k=kk,\n pp = pp + exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k))*mg(k);\n end;\n q(:,k1) = pp;\n tmp = tmp+pp.*double(buf(z).dat(:,k1))./s;\n end;\n ll = ll + sum(log(tmp));\n for k1=1:Kb,\n buf(z).dat(:,k1) = single(q(:,k1));\n end;\n end;\n\n for subit=1:20,\n oll = ll;\n A = cell(3,3);\n A{1,1} = zeros(prod(d2));\n A{1,2} = zeros(prod(d2));\n A{1,3} = zeros(prod(d2));\n A{2,2} = zeros(prod(d2));\n A{2,3} = zeros(prod(d2));\n A{3,3} = zeros(prod(d2));\n Beta = zeros(prod(d2)*3,1);\n\n for z=1:length(z0),\n if ~buf(z).nm, continue; end;\n [x1,y1,z1] = defs(Twarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk);\n b = zeros(buf(z).nm,Kb);\n db1 = zeros(buf(z).nm,Kb);\n db2 = zeros(buf(z).nm,Kb);\n db3 = zeros(buf(z).nm,Kb);\n s = zeros(buf(z).nm,1)+tiny;\n ds1 = zeros(buf(z).nm,1);\n ds2 = zeros(buf(z).nm,1);\n ds3 = zeros(buf(z).nm,1);\n p = zeros(buf(z).nm,1)+tiny;\n dp1 = zeros(buf(z).nm,1);\n dp2 = zeros(buf(z).nm,1);\n dp3 = zeros(buf(z).nm,1);\n\n for k1=1:Kb,\n [b(:,k1),db1(:,k1),db2(:,k1),db3(:,k1)] = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb);\n s = s + mg1(k1)* b(:,k1);\n ds1 = ds1 + mg1(k1)*db1(:,k1);\n ds2 = ds2 + mg1(k1)*db2(:,k1);\n ds3 = ds3 + mg1(k1)*db3(:,k1);\n end;\n for k1=1:Kb,\n b(:,k1) = b(:,k1)./s;\n db1(:,k1) = (db1(:,k1)-b(:,k1).*ds1)./s;\n db2(:,k1) = (db2(:,k1)-b(:,k1).*ds2)./s;\n db3(:,k1) = (db3(:,k1)-b(:,k1).*ds3)./s;\n\n pp = double(buf(z).dat(:,k1));\n p = p + pp.*b(:,k1);\n dp1 = dp1 + pp.*(M(1,1)*db1(:,k1) + M(2,1)*db2(:,k1) + M(3,1)*db3(:,k1));\n dp2 = dp2 + pp.*(M(1,2)*db1(:,k1) + M(2,2)*db2(:,k1) + M(3,2)*db3(:,k1));\n dp3 = dp3 + pp.*(M(1,3)*db1(:,k1) + M(2,3)*db2(:,k1) + M(3,3)*db3(:,k1));\n end;\n\n clear x1 y1 z1 b db1 db2 db3 s ds1 ds2 ds3\n\n tmp = zeros(d(1:2));\n tmp(buf(z).msk) = dp1./p; dp1 = tmp;\n tmp(buf(z).msk) = dp2./p; dp2 = tmp;\n tmp(buf(z).msk) = dp3./p; dp3 = tmp;\n\n b3 = B3warp(z,:)';\n Beta = Beta - [...\n kron(b3,spm_krutil(dp1,B1warp,B2warp,0))\n kron(b3,spm_krutil(dp2,B1warp,B2warp,0))\n kron(b3,spm_krutil(dp3,B1warp,B2warp,0))];\n\n b3b3 = b3*b3';\n A{1,1} = A{1,1} + kron(b3b3,spm_krutil(dp1.*dp1,B1warp,B2warp,1));\n A{1,2} = A{1,2} + kron(b3b3,spm_krutil(dp1.*dp2,B1warp,B2warp,1));\n A{1,3} = A{1,3} + kron(b3b3,spm_krutil(dp1.*dp3,B1warp,B2warp,1));\n A{2,2} = A{2,2} + kron(b3b3,spm_krutil(dp2.*dp2,B1warp,B2warp,1));\n A{2,3} = A{2,3} + kron(b3b3,spm_krutil(dp2.*dp3,B1warp,B2warp,1));\n A{3,3} = A{3,3} + kron(b3b3,spm_krutil(dp3.*dp3,B1warp,B2warp,1));\n\n clear b3 b3b3 tmp p dp1 dp2 dp3\n end;\n\n Alpha = [A{1,1} A{1,2} A{1,3} ; A{1,2} A{2,2} A{2,3}; A{1,3} A{2,3} A{3,3}];\n clear A\n\n for subit1 = 1:3,\n if iter==1,\n nTwarp = (Alpha+lmR*lam + 10*Cwarp)\\((Alpha+lmR*lam)*Twarp(:) - Beta);\n else\n nTwarp = (Alpha+lmR*lam + Cwarp)\\((Alpha+lmR*lam)*Twarp(:) - Beta);\n end;\n nTwarp = reshape(nTwarp,[d2 3]);\n nllr = -0.5*nTwarp(:)'*Cwarp*nTwarp(:);\n nll = nllr+llrb;\n for z=1:length(z0),\n if ~buf(z).nm, continue; end;\n [x1,y1,z1] = defs(nTwarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk);\n sq = zeros(buf(z).nm,1) + tiny;\n b = zeros(buf(z).nm,Kb);\n s = zeros(buf(z).nm,1)+tiny;\n for k1=1:Kb,\n b(:,k1) = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb);\n s = s + mg1(k1)*b(:,k1);\n end;\n for k1=1:Kb,\n sq = sq + double(buf(z).dat(:,k1)).*b(:,k1)./s;\n end;\n clear b\n nll = nll + sum(log(sq));\n clear sq x1 y1 z1\n end;\n if nlltol1*nm),\n finalit = 1;\n break; % This can be commented out.\n end;\nend;\nspm_chi2_plot('Clear');\n\nresults = opts;\nresults.image = V;\nresults.tpm = B;\nresults.Affine = Affine;\nresults.Twarp = Twarp;\nresults.Tbias = Tbias;\nresults.mg = mg;\nresults.mn = mn;\nresults.vr = vr;\nresults.thresh = 0; %thresh;\nresults.ll = ll;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction t = transf(B1,B2,B3,T)\nif ~isempty(T),\n d2 = [size(T) 1];\n t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));\n t = B1*t1*B2';\nelse\n t = zeros(size(B1,1),size(B2,1));\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [x1,y1,z1] = defs(Twarp,z,B1,B2,B3,x0,y0,z0,M,msk)\nx1a = x0 + transf(B1,B2,B3(z,:),Twarp(:,:,:,1));\ny1a = y0 + transf(B1,B2,B3(z,:),Twarp(:,:,:,2));\nz1a = z0(z) + transf(B1,B2,B3(z,:),Twarp(:,:,:,3));\nif nargin>=10,\n x1a = x1a(msk);\n y1a = y1a(msk);\n z1a = z1a(msk);\nend;\nx1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);\ny1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);\nz1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);\nreturn;\n%=======================================================================\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_preproc_write.m", "ext": ".m", "path": "spm5-master/spm_preproc_write.m", "size": 8606, "source_encoding": "utf_8", "md5": "81348572564ad18beb736b2ebde90b4b", "text": "function spm_preproc_write(p,opts)\n% Write out VBM preprocessed data\n% FORMAT spm_preproc_write(p,opts)\n% p - results from spm_prep2sn\n% opts - writing options. A struct containing these fields:\n% biascor - write bias corrected image\n% GM - flags for which images should be written\n% WM - similar to GM\n% CSF - similar to GM\n%____________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_preproc_write.m 1746 2008-05-28 17:43:42Z guillaume $\n\n\nif nargin==1,\n opts = struct('biascor',0,'GM',[0 0 1],'WM',[0 0 1],'CSF',[0 0 0],'cleanup',0);\nend;\nif numel(p)>0,\n b0 = spm_load_priors(p(1).VG);\nend;\nfor i=1:numel(p),\n preproc_apply(p(i),opts,b0);\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction preproc_apply(p,opts,b0)\n\nsopts = [opts.GM ; opts.WM ; opts.CSF];\n\n[pth,nam,ext]=fileparts(p.VF.fname);\nT = p.flags.Twarp;\nbsol = p.flags.Tbias;\nd2 = [size(T) 1];\nd = p.VF.dim(1:3);\n\n[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);\nx3 = 1:d(3);\nd3 = [size(bsol) 1];\nB1 = spm_dctmtx(d(1),d2(1));\nB2 = spm_dctmtx(d(2),d2(2));\nB3 = spm_dctmtx(d(3),d2(3));\nbB3 = spm_dctmtx(d(3),d3(3),x3);\nbB2 = spm_dctmtx(d(2),d3(2),x2(1,:)');\nbB1 = spm_dctmtx(d(1),d3(1),x1(:,1));\n\nmg = p.flags.mg;\nmn = p.flags.mn;\nvr = p.flags.vr;\nK = length(p.flags.mg);\nKb = length(p.flags.ngaus);\n\nfor k1=1:size(sopts,1),\n %dat{k1} = zeros(d(1:3),'uint8');\n dat{k1} = uint8(0);\n dat{k1}(d(1),d(2),d(3)) = 0;\n if sopts(k1,3),\n Vt = struct('fname', fullfile(pth,['c', num2str(k1), nam, ext]),...\n 'dim', p.VF.dim,...\n 'dt', [spm_type('uint8') spm_platform('bigend')],...\n 'pinfo', [1/255 0 0]',...\n 'mat', p.VF.mat,...\n 'n', [1 1],...\n 'descrip', ['Tissue class ' num2str(k1)]);\n Vt = spm_create_vol(Vt);\n VO(k1) = Vt;\n end;\nend;\nif opts.biascor,\n VB = struct('fname', fullfile(pth,['m', nam, ext]),...\n 'dim', p.VF.dim(1:3),...\n 'dt', [spm_type('float32') spm_platform('bigend')],...\n 'pinfo', [1 0 0]',...\n 'mat', p.VF.mat,...\n\t\t 'n', [1 1],...\n 'descrip', 'Bias Corrected');\n VB = spm_create_vol(VB);\nend;\n\nlkp = []; for k=1:Kb, lkp = [lkp ones(1,p.flags.ngaus(k))*k]; end;\n\nspm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed');\nM = p.VG(1).mat\\p.flags.Affine*p.VF.mat;\n\nfor z=1:length(x3),\n\n % Bias corrected image\n f = spm_sample_vol(p.VF,x1,x2,o*x3(z),0);\n cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f;\n if opts.biascor,\n % Write a plane of bias corrected data\n VB = spm_write_plane(VB,cr,z);\n end;\n\n if any(sopts(:)),\n msk = (f==0) | ~isfinite(f);\n [t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M);\n q = zeros([d(1:2) Kb]);\n bt = zeros([d(1:2) Kb]);\n for k1=1:Kb,\n bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb);\n end;\n b = zeros([d(1:2) K]);\n for k=1:K,\n b(:,:,k) = bt(:,:,lkp(k))*mg(k);\n end;\n s = sum(b,3);\n for k=1:K,\n p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps);\n q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s;\n end;\n sq = sum(q,3)+eps;\n sw = warning('off','MATLAB:divideByZero');\n for k1=1:size(sopts,1),\n tmp = q(:,:,k1);\n tmp(msk) = 0;\n tmp = tmp./sq;\n dat{k1}(:,:,z) = uint8(round(255 * tmp));\n end;\n warning(sw);\n end;\n spm_progress_bar('set',z);\nend;\nspm_progress_bar('clear');\n\nif opts.cleanup > 0,\n [dat{1},dat{2},dat{3}] = clean_gwc(dat{1},dat{2},dat{3}, opts.cleanup);\nend;\nif any(sopts(:,3)),\n for z=1:length(x3),\n for k1=1:size(sopts,1),\n if sopts(k1,3),\n tmp = double(dat{k1}(:,:,z))/255;\n spm_write_plane(VO(k1),tmp,z);\n end;\n end;\n end;\nend;\n\nfor k1=1:size(sopts,1),\n if any(sopts(k1,1:2)),\n so = struct('wrap',[0 0 0],'interp',1,'vox',[NaN NaN NaN],...\n 'bb',ones(2,3)*NaN,'preserve',0);\n ovx = abs(det(p.VG(1).mat(1:3,1:3)))^(1/3);\n fwhm = max(ovx./sqrt(sum(p.VF.mat(1:3,1:3).^2))-1,0.1);\n dat{k1} = decimate(dat{k1},fwhm);\n fn = fullfile(pth,['c', num2str(k1), nam, ext]);\n dim = [size(dat{k1}) 1];\n VT = struct('fname',fn,'dim',dim(1:3),...\n 'dt', [spm_type('uint8') spm_platform('bigend')],...\n 'pinfo',[1/255 0]','mat',p.VF.mat,'dat',dat{k1});\n if sopts(k1,2),\n spm_write_sn(VT,p,so);\n end;\n so.preserve = 1;\n if sopts(k1,1),\n VN = spm_write_sn(VT,p,so);\n VN.fname = fullfile(pth,['mwc', num2str(k1), nam, ext]);\n spm_write_vol(VN,VN.dat);\n end;\n end;\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M)\nx1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1));\ny1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2));\nz1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3));\nx1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);\ny1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);\nz1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction t = transf(B1,B2,B3,T)\nif ~isempty(T)\n d2 = [size(T) 1];\n t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));\n t = B1*t1*B2';\nelse\n t = zeros(size(B1,1),size(B2,1),size(B3,1));\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction dat = decimate(dat,fwhm)\n% Convolve the volume in memory (fwhm in voxels).\nlim = ceil(2*fwhm);\nx = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x);\ny = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y);\nz = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z);\ni = (length(x) - 1)/2;\nj = (length(y) - 1)/2;\nk = (length(z) - 1)/2;\nspm_conv_vol(dat,dat,x,y,z,-[i j k]);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [g,w,c] = clean_gwc(g,w,c, level)\nif nargin<4, level = 1; end;\n\nb = w;\nb(1) = w(1);\n\n% Build a 3x3x3 seperable smoothing kernel\n%-----------------------------------------------------------------------\nkx=[0.75 1 0.75];\nky=[0.75 1 0.75];\nkz=[0.75 1 0.75];\nsm=sum(kron(kron(kz,ky),kx))^(1/3);\nkx=kx/sm; ky=ky/sm; kz=kz/sm;\n\nth1 = 0.15;\nif level==2, th1 = 0.2; end;\n% Erosions and conditional dilations\n%-----------------------------------------------------------------------\nniter = 32;\nspm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');\nfor j=1:niter,\n if j>2, th=th1; else th=0.6; end; % Dilate after two its of erosion.\n for i=1:size(b,3),\n gp = double(g(:,:,i));\n wp = double(w(:,:,i));\n bp = double(b(:,:,i))/255;\n bp = (bp>th).*(wp+gp);\n b(:,:,i) = uint8(round(bp));\n end;\n spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);\n spm_progress_bar('Set',j);\nend;\nth = 0.05;\nfor i=1:size(b,3),\n gp = double(g(:,:,i))/255;\n wp = double(w(:,:,i))/255;\n cp = double(c(:,:,i))/255;\n bp = double(b(:,:,i))/255;\n bp = ((bp>th).*(wp+gp))>th;\n g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));\n w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));\n c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));\nend;\nspm_progress_bar('Clear');\nreturn;\n%=======================================================================\n\n%=======================================================================\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_contrasts.m", "ext": ".m", "path": "spm5-master/spm_config_contrasts.m", "size": 31917, "source_encoding": "utf_8", "md5": "38447033c92a1a4cb1f381be46468bc5", "text": "function con = spm_config_contrasts\n% Configuration file for contrast jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Darren Gitelman\n% $Id: spm_config_contrasts.m 948 2007-10-15 21:37:49Z Darren $\n\n\n%_______________________________________________________________________\n\n\nspm.type = 'files';\nspm.name = 'Select SPM.mat';\nspm.tag = 'spmmat';\nspm.num = [1 1];\nspm.filter = 'mat';\nspm.ufilter = '^SPM\\.mat$';\nspm.help = {'Select SPM.mat file for contrasts'};\n\nsessrep.type = 'menu';\nsessrep.name = 'Replicate over sessions';\nsessrep.tag = 'sessrep';\nsessrep.labels = {'Don''t replicate','Replicate','Create per session','Both'};\nsessrep.values = {'none','repl','sess','both'};\nsessrep.val = {'none'};\nsessrep.help = {['If there are multiple sessions with identical conditions, ' ...\n 'one might want to specify contrasts which are identical over ',...\n 'sessions. This can be done automatically based on the contrast '...\n 'spec for one session.'],...\n ['Contrasts can be either replicated (thus testing average ' ...\n 'effects over sessions) or created per session. In both ' ...\n 'cases, zero padding up to the length of each session ' ...\n 'and the block effects is done automatically.']};\n\nname.type = 'entry';\nname.name = 'Name';\nname.tag = 'name';\nname.strtype = 's';\nname.num = [1 1];\nname.help = {'Name of contrast'};\n\ntconvec.type = 'entry';\ntconvec.name = 'T contrast vector';\ntconvec.tag = 'convec';\ntconvec.strtype = 'e';\ntconvec.num = [1 Inf];\ntconvec.help = {[...\n 'Enter T contrast vector. This is done similarly to the ',...\n 'SPM2 contrast manager. A 1 x n vector should be entered ',...\n 'for T-contrasts.']};\n\nfconvec.type = 'entry';\nfconvec.name = 'F contrast vector';\nfconvec.tag = 'convec';\nfconvec.strtype = 'e';\nfconvec.num = [Inf Inf];\nfconvec.help = {[...\n 'Enter F contrast vector. This is done similarly to the ',...\n 'SPM2 contrast manager. One or multiline contrasts ',...\n 'may be entered.']};\n\nfconvecs.type = 'repeat';\nfconvecs.name = 'Contrast vectors';\nfconvecs.tag = 'convecs';\nfconvecs.values = {fconvec};\nfconvecs.help = {...\n'F contrasts are defined by a series of vectors.'};\n\ntcon.type = 'branch';\ntcon.name = 'T-contrast';\ntcon.tag = 'tcon';\ntcon.val = {name,tconvec,sessrep};\ntcon.help = {...\n'* Simple one-dimensional contrasts for an SPM{T}','',[...\n'A simple contrast for an SPM{T} tests the null hypothesis c''B=0 ',...\n'against the one-sided alternative c''B>0, where c is a column vector. '],'',[...\n' Note that throughout SPM, the transpose of the contrast weights is ',...\n'used for display and input. That is, you''ll enter and visualise c''. ',...\n'For an SPM{T} this will be a row vector.'],'',[... \n'For example, if you have a design in which the first two columns of ',...\n'the design matrix correspond to the effects for \"baseline\" and ',...\n'\"active\" conditions respectively, then a contrast with weights ',...\n'c''=[-1,+1,0,...] (with zero weights for any other parameters) tests ',...\n'the hypothesis that there is no \"activation\" (the parameters for both ',...\n'conditions are the same), against the alternative that there is some ',...\n'activation (i.e. the parameter for the \"active\" condition is greater ',...\n'than that for the \"baseline\" condition). The resulting SPM{T} ',...\n'(created by spm_getSPM.m) is a statistic image, with voxel values the ',...\n'value of the t-statistic for the specified contrast at that location. ',...\n'Areas of the SPM{T} with high voxel values indicate evidence for ',...\n'\"activation\". To look for areas of relative \"de-activation\", the ',...\n'inverse contrast could be used c''=[+1,-1,0,...].'],'',[...\n'Similarly, if you have a design where the third column in the design ',...\n'matrix is a covariate, then the corresponding parameter is ',...\n'essentially a regression slope, and a contrast with weights ',...\n'c''=[0,0,1,0,...] (with zero weights for all parameters but the third) ',...\n'tests the hypothesis of zero regression slope, against the ',...\n'alternative of a positive slope. This is equivalent to a test no ',...\n'correlation, against the alternative of positive correlation. If ',...\n'there are other terms in the model beyond a constant term and the ',...\n'covariate, then this correlation is apartial correlation, the ',...\n'correlation between the data Y and the covariate, after accounting ',...\n'for the other effects.']};\n\nfcon.type = 'branch';\nfcon.name = 'F-contrast';\nfcon.tag = 'fcon';\nfcon.val = {name,fconvecs,sessrep};\nfcon.help = {...\n'* Linear constraining matrices for an SPM{F}',...\n'',[...\n'The null hypothesis c''B=0 can be thought of as a (linear) constraint ',...\n'on the full model under consideration, yielding a reduced model. ',...\n'Taken from the viewpoint of two designs, with the full model an ',...\n'extension of the reduced model, the null hypothesis is that the ',...\n'additional terms in the full model are redundent.'],...\n'',[...\n'Statistical inference proceeds by comparing the additional variance ',...\n'explained by full design over and above the reduced design to the ',...\n'error variance (of the full design), an \"Extra Sum-of-Squares\" ',...\n'approach yielding an F-statistic for each voxel, whence an SPM{F}.'],...\n'',...\n'This is useful in a number of situations:',...\n'',...\n'* Two sided tests',...\n'',[...\n'The simplest use of F-contrasts is to effect a two-sided test of a ',...\n'simple linear contrast c''B, where c is a column vector. The SPM{F} is ',...\n'the square of the corresponding SPM{T}. High values of the SPM{F} ',...\n'therefore indicate evidence against the null hypothesis c''B=0 in ',...\n'favour of the two-sided alternative c''B~=0.'],...\n'',...\n'* General linear hypotheses',...\n'',[...\n'Where the contrast weights is a matrix, the rows of the (transposed) ',...\n'contrast weights matrix c'' must define contrasts in their own right, ',...\n'and the test is effectively simultaneously testing the null ',...\n'hypotheses associated with the individual component contrasts with ',...\n'weights defined in the rows. The null hypothesis is still c''B=0, but ',...\n'since c is a matrix, 0 here is a zero vector rather than a scalar ',...\n'zero, asserting that under the null hypothesis all the component ',...\n'hypotheses are true.'],...\n'',[...\n'For example: Suppose you have a language study with 3 word categories ',...\n'(A,B & C), and would like to test whether there is any difference ',...\n'at all between the three levels of the \"word category\" factor.'],...\n'',...\n'The design matrix might look something like:',...\n'',...\n' [ 1 0 0 ..]',...\n' [ : : : ..]',...\n' [ 1 0 0 ..]',...\n' [ 0 1 0 ..]',...\n' X = [ : : : ..]',...\n' [ 0 1 0 ..]',...\n' [ 0 0 1 ..]',...\n' [ : : : ..]',...\n' [ 0 0 1 ..]',...\n' [ 0 0 0 ..]',...\n' [ : : : ..]',...\n'',[...\n' ...with the three levels of the \"word category\" factor modelled in the ',...\n' first three columns of the design matrix.'],...\n'',...\n'The matrix of contrast weights will look like:',...\n'',...\n' c'' = [1 -1 0 ...;',...\n' 0 1 -1 ...]',...\n'',[...\n'Reading the contrasts weights in each row of c'', we see that row 1 ',...\n'states that category A elicits the same response as category B, row 2 ',...\n'that category B elicits the same response as category C, and hence ',...\n'together than categories A, B & C all elicit the same response.'],...\n'',[...\n'The alternative hypothesis is simply that the three levels are not ',...\n'all the same, i.e. that there is some difference in the paraeters for ',...\n'the three levels of the factor: The first and the second categories ',...\n'produce different brain responses, OR the second and third ',...\n'categories, or both.'],...\n'',[...\n'In other words, under the null hypothesis (the categories produce the ',...\n'same brain responses), the model reduces to one in which the three ',...\n'level \"word category\" factor can be replaced by a single \"word\" ',...\n'effect, since there is no difference in the parameters for each ',...\n'category. The corresponding design matrix would have the first three ',...\n'columns replaced by a single column that is the sum (across rows) of ',...\n'the first three columns in the design matric above, modelling the ',...\n'brain response to a word, whatever is the category. The F-contrast ',...\n'above is in fact testing the hypothesis that this reduced design ',...\n'doesn''t account for significantly less variance than the full design ',...\n'with an effect for each word category.'],...\n'',[...\n'Another way of seeing that, is to consider a reparameterisation of ',...\n'the model, where the first column models effects common to all three ',...\n'categories, with the second and third columns modelling the ',...\n'differences between the three conditions, for example:'],...\n'',...\n' [ 1 1 0 ..]',...\n' [ : : : ..]',...\n' [ 1 1 0 ..]',...\n' [ 1 0 1 ..]',...\n' X = [ : : : ..]',...\n' [ 1 0 1 ..]',...\n' [ 1 -1 -1 ..]',...\n' [ : : : ..]',...\n' [ 1 -1 -1 ..]',...\n' [ 0 0 0 ..]',...\n' [ : : : ..]',...\n'',...\n'In this case, an equivalent F contrast is of the form',...\n' c'' = [ 0 1 0 ...;',...\n' 0 0 1 ...]',[...\n'and would be exactly equivalent to the previous contrast applied to ',...\n'the previous design. In this latter formulation, you are asking ',...\n'whewher the two columns modelling the \"interaction space\" account for ',...\n'a significant amount of variation (variance) of the data. Here the ',...\n'component contrasts in the rows of c'' are simply specifying that the ',...\n'parameters for the corresponding rows are are zero, and it is clear ',...\n'that the F-test is comparing this full model with a reduced model in ',...\n'which the second and third columns of X are omitted.'],...\n'',...\n' Note the difference between the following two F-contrasts:',...\n' c'' = [ 0 1 0 ...; (1)',...\n' 0 0 1 ...]',... \n' and',...\n' c'' = [ 0 1 1 ...] (2)',...\n'',[...\n' The first is an F-contrast, testing whether either of the ',... \n'parameters for the effects modelled in the 2nd & 3rd columns of the ',...\n'design matrix are significantly different from zero. Under the null ',...\n'hypothesis c''B=0, the first contrast imposes a two-dimensional ',... \n'constraint on the design. The second contrast tests whether the SUM ',...\n'of the parameters for the 2nd & 3rd columns is significantly ',... \n'different from zero. Under the null hypothesis c''B=0, this second ',...\n'contrast only imposes a one dimensional constraint on the design.'],... \n'',[...\n' An example of the difference between the two is that the first ',... \n'contrast would be sensitive to the situation where the 2nd & 3rd ',...\n'parameters were +a and -a, for some constant a, wheras the second ',...\n'contrast would not detect this, since the parameters sum to zero.'],... \n'',[...\n'The test for an effect of the factor \"word category\" is an F-test ',...\n'with 3-1=2 \"dimensions\", or degrees of freedom.'],...\n'',...\n'* Testing the significance of effects modelled by multiple columns',...\n'',[...\n'A conceptially similar situation arises when one wonders whether a ',...\n'set of coufound effects are explaining any variance in the data. One ',...\n'important advantage of testing the with F contrasts rather than one ',...\n'by one using SPM{T}''s is the following. Say you have two covariates ',...\n'that you would like to know whether they can \"predict\" the brain ',...\n'responses, and these two are correlated (even a small correlation ',...\n'would be important in this instance). Testing one and then the other ',...\n'may lead you to conclude that there is no effect. However, testing ',...\n'with an F test the two covariates may very well show a not suspected ',...\n'effect. This is because by testing one covariate after the other, one ',...\n'never tests for what is COMMON to these covariates (see Andrade et ',...\n'al, Ambiguous results in functional neuroimaging, NeuroImage, 1999).'],...\n'','',[...\n'More generally, F-tests reflect the usual analysis of variance, while ',...\n't-tests are traditionally post hoc tests, useful to see in which ',...\n'direction is an effect going (positive or negative). The introduction ',...\n'of F-tests can also be viewed as a first means to do model selection.'],...\n'','',[...\n'Technically speaking, an F-contrast defines a number of directions ',...\n'(as many as the rank of the contrast) in the space spanned by the ',...\n'column vectors of the design matrix. These directions are simply ',...\n'given by X*c if the vectors of X are orthogonal, if not, the space ',...\n'define by c is a bit more complex and takes care of the correlation ',...\n'within the design matrix. In essence, an F-contrast is defining a ',...\n'reduced model by imposing some linear constraints (that have to be ',...\n'estimable, see below) on the parameters estimates. Sometimes, this ',...\n'reduced model is simply made of a subset of the column of the ',...\n'original design matrix but generally, it is defined by a combination ',...\n'of those columns. (see spm_FcUtil for what (I hope) is an efficient ',...\n'handling of F-contrats computation).']};\n\n\n\n% Column-wise contrast definition for fancy fMRI designs\n%_______________________________________________________________________\n\nconweight.type = 'entry';\nconweight.name = 'Contrast weight';\nconweight.tag = 'conweight';\nconweight.strtype = 'e';\nconweight.num = [1 1];\nconweight.help = {'The contrast weight for the selected column.'};\n\ncolcond.type = 'entry';\ncolcond.name = 'Condition #';\ncolcond.tag = 'colcond';\ncolcond.strtype = 'e';\ncolcond.num = [1 1];\ncolcond.help = {['Select which condition function set is to be contrasted.']};\n\ncolbf.type = 'entry';\ncolbf.name = 'Basis function #';\ncolbf.tag = 'colbf';\ncolbf.strtype = 'e';\ncolbf.num = [1 1];\ncolbf.help = {['Select which basis function from the basis' ...\n\t\t ' function set is to be contrasted.']};\n\ncolmod.type = 'entry';\ncolmod.name = 'Parametric modulation #';\ncolmod.tag = 'colmod';\ncolmod.strtype = 'e';\ncolmod.num = [1 1];\ncolmod.help = {['Select which parametric modulation is to be contrasted.' ...\n\t\t ' If there is no time/parametric modulation, enter' ...\n\t\t ' \"1\". If there are both time and parametric modulations, '...\n\t\t 'then time modulation comes before parametric modulation.']}; \n\ncolmodord.type = 'entry';\ncolmodord.name = 'Parametric modulation order';\ncolmodord.tag = 'colmodord';\ncolmodord.strtype = 'e';\ncolmodord.num = [1 1];\ncolmodord.help = {'Order of parametric modulation to be contrasted. ','', ...\n\t\t '0 - the basis function itself, 1 - 1st order mod etc'};\n\t\t \ncolconds.type = 'branch';\ncolconds.name = 'Contrast entry';\ncolconds.tag = 'colconds';\ncolconds.val = {conweight,colcond,colbf,colmod,colmodord};\n\ncolcondrep.type = 'repeat';\ncolcondrep.name = 'T contrast for conditions';\ncolcondrep.tag = 'colcondrep';\ncolcondrep.values = {colconds};\ncolcondrep.num = [1 Inf];\ncolcondrep.help = {'Assemble your contrast column by column.'};\n\ncolreg = tconvec;\ncolreg.name = 'T contrast for extra regressors';\ncolreg.tag = 'colreg';\ncolreg.help = {...\n['Enter T contrast vector for extra regressors.']};\n\ncoltype.type = 'choice';\ncoltype.name = 'Contrast columns';\ncoltype.tag = 'coltype';\ncoltype.values = {colcondrep, colreg};\ncoltype.help = {...\n['Contrasts can be specified either over conditions or over extra regressors.']};\n\nsessions.type = 'entry';\nsessions.name = 'Session(s)';\nsessions.tag = 'sessions';\nsessions.strtype = 'e';\nsessions.num = [1 Inf];\nsessions.help = {...\n['Enter session number(s) for which this contrast should be created. If' ...\n ' more than one session number is specified, the contrast will be an' ...\n ' average contrast over the specified conditions or regressors from these' ...\n ' sessions.']};\n\ntconsess.type = 'branch';\ntconsess.name = 'T-contrast (cond/sess based)';\ntconsess.tag = 'tconsess';\ntconsess.val = {name,coltype,sessions};\ntconsess.modality = {'FMRI'};\ntconsess.help = {...\n['Define a contrast in terms of conditions or regressors instead of' ...\n ' columns of the design matrix. This allows to create contrasts automatically' ...\n ' even if some columns are not always present (e.g. parametric modulations).'], ...\n'', ...\n'Each contrast column can be addressed by specifying', ...\n'* session number', ...\n'* condition number', ...\n'* basis function number', ...\n'* parametric modulation number and', ...\n'* parametric modulation order.', ...\n'', ...\n['If the design is specified without time or parametric modulation, SPM' ...\n ' creates a \"pseudo-modulation\" with order zero. To put a contrast weight' ...\n ' on a basis function one therefore has to enter \"1\" for parametric' ...\n ' modulation number and \"0\" for parametric modulation order.'], ...\n'', ...\n['Time and parametric modulations are not distinguished internally. If' ...\n ' time modulation is present, it will be parametric modulation \"1\", and' ...\n ' additional parametric modulations will be numbered starting with \"2\".'], ...\n'', ...\ntcon.help{:}};\n\nconsess.type = 'repeat';\nconsess.name = 'Contrast Sessions';\nconsess.tag = 'consess';\nconsess.values = {tcon,fcon,tconsess};\nconsess.help = {'contrast'};\nconsess.help = {[...\n'For general linear model Y = XB + E with data Y, desgin matrix X, ',...\n'parameter vector B, and (independent) errors E, a contrast is a ',...\n'linear combination of the parameters c''B. Usually c is a column ',...\n'vector, defining a simple contrast of the parameters, assessed via an ',...\n'SPM{T}. More generally, c can be a matrix (a linear constraining ',...\n'matrix), defining an \"F-contrast\" assessed via an SPM{F}.'],'',[...\n'The vector/matrix c contains the contrast weights. It is this ',...\n'contrast weights vector/matrix that must be specified to define the ',...\n'contrast. The null hypothesis is that the linear combination c''B is ',...\n'zero. The order of the parameters in the parameter (column) vector B, ',...\n'and hence the order to which parameters are referenced in the ',...\n'contrast weights vector c, is determined by the construction of the ',...\n'design matrix.'],'',[...\n'There are two types of contrast in SPM: simple contrasts for SPM{T}, ',...\n'and \"F-contrasts\" for SPM{F}.'],'',[...\n'For a thorough theoretical treatment, see the Human Brain Function book ',...\n'and the statistical literature referenced therein.'],...\n'','',...\n'* Non-orthogonal designs',...\n'',[...\n'Note that parameters zero-weighted in the contrast are still included ',...\n'in the model. This is particularly important if the design is not ',...\n'orthogonal (i.e. the columns of the design matrix are not ',...\n'orthogonal). In effect, the significance of the contrast is assessed ',...\n'*after* accounting for the other effects in the design matrix. Thus, ',...\n'if two covariates are correlated, testing the significance of the ',...\n'parameter associated with one will only test for the part that is not ',...\n'present in the second covariate. This is a general point that is also ',...\n'true for F-contrasts. See Andrade et al, Ambiguous results in ',...\n'functional neuroimaging, NeuroImage, 1999, for a full description of ',...\n'the effect of non othogonal design testing.'],...\n'','',...\n'* Estimability',...\n'',[...\n'The contrast c''B is estimated by c''b, where b are the parameter ',...\n'estimates given by b=pinv(X)*Y.'],...\n'',[...\n'However, if a design is rank-deficient (i.e. the columns of the ',...\n'design matrix are not linearly independent), then the parameters are ',...\n'not unique, and not all linear combinations of the parameter are ',...\n'valid contrasts, since contrasts must be uniquely estimable.'],...\n'',[...\n'A weights vector defines a valid contrast if and only if it can be ',...\n'constructed as a linear combination of the rows of the design matrix. ',...\n'That is c'' (the transposed contrast vector - a row vector) is in the ',...\n'row-space of the design matrix.'],...\n'',[...\n'Usually, a valid contrast will have weights that sum to zero over the ',...\n'levels of a factor (such as condition).'],...\n'',[...\n'A simple example is a simple two condition design including a ',...\n'constant, with design matrix'],...\n'',...\n' [ 1 0 1 ]',...\n' [ : : : ]',...\n' X = [ 1 0 1 ]',...\n' [ 0 1 1 ]',...\n' [ : : : ]',...\n' [ 0 1 1 ]',...\n'',[...\n'The first column corresponds to condition 1, the second to condition ',...\n'2, and the third to a constant (mean) term. Although there are three ',...\n'columns to the design matrix, the design only has two degrees of ',...\n'freedom, since any one column can be derived from the other two (for ',...\n'instance, the third column is the sum of the first two). There is no ',...\n'unique set of parameters for this model, since for any set of ',...\n'parameters adding a constant to the two condition effects and ',...\n'subtracting it from the constant effect yields another set of viable ',...\n'parameters. However, the difference between the two condition effects ',...\n'is uniquely estimated, so c''=[-1,+1,0] does define a contrast.'],...\n'',[...\n'If a parameter is estimable, then the weights vector with a single ',...\n'\"1\" corresponding to that parameter (and zero elsewhere) defines a ',...\n'valid contrast.'],...\n'','',...\n'* Multiple comparisons',...\n'',[...\n'Note that SPM implements no corrections to account for you looking at ',...\n'multiple contrasts.'],...\n'',[...\n'If you are interested in a set of hypotheses that together define a ',...\n'consistent question, then you should account for this when assessing ',...\n'the individual contrasts. A simple Bonferroni approach would assess N ',...\n'simultaneous contrasts at significance level alpha/N, where alpha is ',...\n'the chosen significance level (usually 0.05).'],...\n'',[...\n'For two sided t-tests using SPM{T}s, the significance level should ',...\n'be halved. When considering both SPM{T}s produced by a contrast and ',...\n'it''s inverse (the contrast with negative weights), to effect a ',...\n'two-sided test to look for both \"increases\" and \"decreases\", you ',...\n'should review each SPM{T} at at level 0.05/2 rather than 0.05. (Or ',...\n'consider an F-contrast!)'],...\n'','',...\n'* Contrast images and ESS images',...\n'',[...\n'For a simple contrast, SPM (spm_getSPM.m) writes a contrast image: ',...\n'con_????.{img,nii}, with voxel values c''b. (The ???? in the image ',...\n'names are replaced with the contrast number.) These contrast images ',...\n'(for appropriate contrasts) are suitable summary images of an effect ',...\n'at this level, and can be used as input at a higher level when ',...\n'effecting a random effects analysis. See spm_RandFX.man for further ',...\n'details.'],...\n'',[...\n'For an F-contrast, SPM (spm_getSPM.m) writes the Extra Sum-of-Squares ',...\n'(the difference in the residual sums of squares for the full and ',...\n'reduced model) as ess_????.{img,nii}. (Note that the ',...\n'ess_????.{img,nii} and SPM{T,F}_????.{img,nii} images are not ',...\n'suitable input for a higher level analysis.)']};\n\ndelete.type = 'menu';\ndelete.name = 'Delete existing contrasts';\ndelete.tag = 'delete';\ndelete.labels = {'Yes', 'No'};\ndelete.values = {1, 0};\ndelete.val = {0};\n\ncon.type = 'branch';\ncon.name = 'Contrast Manager';\ncon.tag = 'con';\ncon.val = {spm,consess,delete};\ncon.prog = @setupcon;\ncon.help = {'Set up T and F contrasts.'};\n\n%-----------------------------------------------------------------------\nfunction setupcon(varargin)\n\nwd = pwd;\njob = varargin{1};\n\n% Change to the analysis directory\n%-----------------------------------------------------------------------\nif ~isempty(job)\n try\n pth = fileparts(job.spmmat{:});\n cd(char(pth));\n fprintf(' Changing directory to: %s\\n',char(pth));\n catch\n error('Failed to change directory. Aborting contrast setup.')\n end\nend\n\n% Load SPM.mat file\n%-----------------------------------------------------------------------\ntmp=load(job.spmmat{:});\nSPM=tmp.SPM;\n\nif ~strcmp(pth,SPM.swd)\n warning(['Path to SPM.mat: %s\\n and SPM.swd: %s\\n differ, using current ' ...\n 'SPM.mat location as new working directory.'], pth, ...\n SPM.swd);\n SPM.swd = pth;\nend;\n\nif job.delete && isfield(SPM,'xCon')\n for k=1:numel(SPM.xCon)\n [p n e v] = spm_fileparts(SPM.xCon(k).Vcon.fname);\n switch e,\n case '.img'\n spm_unlink([n '.img'],[n '.hdr']);\n case '.nii'\n spm_unlink(SPM.xCon(k).Vcon.fname);\n end;\n [p n e v] = spm_fileparts(SPM.xCon(k).Vspm.fname);\n switch e,\n case '.img'\n spm_unlink([n '.img'],[n '.hdr']);\n case '.nii'\n spm_unlink(SPM.xCon(k).Vspm.fname);\n end;\n end;\n SPM.xCon = [];\nend;\n\nbayes_con=isfield(SPM,'PPM');\nif bayes_con\n if ~isfield(SPM.PPM,'xCon')\n % Retrospectively label Bayesian contrasts as T's, if this info is missing\n for ii=1:length(SPM.xCon)\n SPM.PPM.xCon(ii).PSTAT='T';\n end\n end\nend\n\nfor i = 1:length(job.consess)\n if isfield(job.consess{i},'tcon')\n name = job.consess{i}.tcon.name;\n if bayes_con\n STAT = 'P';\n SPM.PPM.xCon(end+1).PSTAT = 'T';\n SPM.xX.V=[];\n else\n STAT = 'T';\n end\n con = job.consess{i}.tcon.convec(:)';\n sessrep = job.consess{i}.tcon.sessrep;\n elseif isfield(job.consess{i},'tconsess')\n job.consess{i}.tconsess = job.consess{i}.tconsess; % save some typing\n name = job.consess{i}.tconsess.name;\n if bayes_con\n STAT = 'P';\n SPM.PPM.xCon(end+1).PSTAT = 'T';\n SPM.xX.V=[];\n else\n STAT = 'T';\n end\n if isfield(job.consess{i}.tconsess.coltype,'colconds')\n ccond = job.consess{i}.tconsess.coltype.colconds;\n con = zeros(1,size(SPM.xX.X,2)); % overall contrast\n for cs = job.consess{i}.tconsess.sessions\n for k=1:numel(ccond)\n if SPM.xBF.order < ccond(k).colbf\n error(['Session-based contrast %d:\\n'...\n 'Basis function order (%d) in design less ' ...\n 'than specified basis function number (%d).'],...\n i, SPM.xBF.order, ccond(k).colbf);\n end;\n % Index into columns belonging to the specified\n % condition\n try\n cind = ccond(k).colbf + ...\n ccond(k).colmodord*SPM.xBF.order ...\n *SPM.Sess(cs).U(ccond(k).colcond).P(ccond(k) ...\n .colmod).i(ccond(k).colmodord+1);\n con(SPM.Sess(cs).col(SPM.Sess(cs).Fc(ccond(k).colcond).i(cind))) ...\n = ccond(k).conweight;\n catch\n error(['Session-based contrast %d:\\n'...\n 'Column \"Cond%d Mod%d Order%d\" does not exist.'],...\n i, ccond(k).colcond, ccond(k).colmod, ccond(k).colmodord);\n end;\n end;\n end;\n else % convec on extra regressors\n con = zeros(1,size(SPM.xX.X,2)); % overall contrast\n for cs = job.consess{i}.tconsess.sessions\n nC = size(SPM.Sess(cs).C.C,2);\n if nC < numel(job.consess{i}.tconsess.coltype.colreg)\n error(['Session-based contrast %d:\\n'...\n 'Contrast vector for extra regressors too long.'],...\n i);\n end;\n ccols = numel(SPM.Sess(cs).col)-(nC-1)+...\n [0:numel(job.consess{i}.tconsess.coltype.colreg)-1];\n con(SPM.Sess(cs).col(ccols)) = job.consess{i}.tconsess.coltype.colreg;\n end;\n end;\n sessrep = 'none';\n else %fcon\n name = job.consess{i}.fcon.name;\n if bayes_con\n STAT = 'P';\n SPM.PPM.xCon(end+1).PSTAT = 'F';\n SPM.xX.V=[];\n else\n STAT = 'F';\n end\n try\n con = cat(1,job.consess{i}.fcon.convec{:});\n catch\n error('Error concatenating F-contrast vectors. Sizes are:\\n %s\\n',... \n num2str(cellfun('length',job.consess{i}.fcon.convec)))\n end\n sessrep = job.consess{i}.fcon.sessrep;\n end\n\n \n if isfield(SPM,'Sess') && ~strcmp(sessrep,'none')\n % assume identical sessions, no check!\n nc = numel(SPM.Sess(1).U);\n nsessions=numel(SPM.Sess);\n rcon = zeros(size(con,1),nc);\n switch sessrep\n case 'repl',\n % within-session zero padding, replication over sessions\n cons{1}= zeros(size(con,1),size(SPM.xX.X,2));\n for sess=1:nsessions\n sfirst=SPM.Sess(sess).col(1);\n cons{1}(:,sfirst:sfirst+size(con,2)-1)=con;\n end\n names{1} = sprintf('%s - All Sessions', name);\n case 'sess',\n for k=1:numel(SPM.Sess)\n cons{k} = [zeros(size(con,1),SPM.Sess(k).col(1)-1) con];\n names{k} = sprintf('%s - Session %d', name, k);\n end;\n case 'both'\n for k=1:numel(SPM.Sess)\n cons{k} = [zeros(size(con,1),SPM.Sess(k).col(1)-1) con];\n names{k} = sprintf('%s - Session %d', name, k);\n end;\n if numel(SPM.Sess) > 1\n % within-session zero padding, replication over sessions\n cons{end+1}= zeros(size(con,1),size(SPM.xX.X,2));\n for sess=1:nsessions\n sfirst=SPM.Sess(sess).col(1);\n cons{end}(:,sfirst:sfirst+size(con,2)-1)=con;\n end\n names{end+1} = sprintf('%s - All Sessions', name);\n end;\n end;\n else\n cons{1} = con;\n names{1} = name;\n end;\n\n % Loop over created contrasts\n %-------------------------------------------------------------------\n for k=1:numel(cons)\n\n % Basic checking of contrast\n %-------------------------------------------------------------------\n [c,I,emsg,imsg] = spm_conman('ParseCon',cons{k},SPM.xX.xKXs,STAT);\n if ~isempty(emsg)\n disp(emsg);\n error('Error in contrast specification');\n else\n disp(imsg);\n end;\n\n % Fill-in the contrast structure\n %-------------------------------------------------------------------\n if all(I)\n DxCon = spm_FcUtil('Set',names{k},STAT,'c',c,SPM.xX.xKXs);\n else\n DxCon = [];\n end\n\n % Append to SPM.xCon. SPM will automatically save any contrasts that\n % evaluate successfully.\n %-------------------------------------------------------------------\n if isempty(SPM.xCon)\n SPM.xCon = DxCon;\n elseif ~isempty(DxCon)\n SPM.xCon(end+1) = DxCon;\n end\n SPM = spm_contrasts(SPM,length(SPM.xCon));\n end\nend;\n% Change back directory\n%-----------------------------------------------------------------------\nfprintf(' Changing back to directory: %s\\n', wd);\ncd(wd); \n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm.m", "ext": ".m", "path": "spm5-master/spm.m", "size": 47017, "source_encoding": "utf_8", "md5": "c70b7f4583a4385043a1d626f2c05867", "text": "function varargout=spm(varargin)\n% SPM: Statistical Parametric Mapping (startup function)\n%_______________________________________________________________________\n% ___ ____ __ __\n% / __)( _ \\( \\/ ) \n% \\__ \\ )___/ ) ( Statistical Parametric Mapping\n% (___/(__) (_/\\/\\_) SPM - http://www.fil.ion.ucl.ac.uk/spm/\n%_______________________________________________________________________\n%\n% SPM (Statistical Parametric Mapping) is a package for the analysis\n% functional brain mapping experiments. It is the in-house package of\n% the Wellcome Department of Cognitive Neurology, and is available to\n% the scientific community as copyright freeware under the terms of the\n% GNU General Public Licence.\n% \n% Theoretical, computational and other details of the package are\n% available in SPM's \"Help\" facility. This can be launched from the\n% main SPM Menu window using the \"Help\" button, or directly from the\n% command line using the command `spm_help`.\n%\n% Details of this release are available via the \"About SPM\" help topic\n% (file spm.man), accessible from the SPM splash screen. (Or type\n% `spm_help spm.man` in the MATLAB command window)\n% \n% This spm function initialises the default parameters, and displays a\n% splash screen with buttons leading to the PET(SPECT) & fMRI\n% modalities Alternatively, `spm('pet')` and `spm('fmri')`\n% (equivalently `spm pet` and `spm mri`) lead directly to the respective\n% modality interfaces.\n%\n% Once the modality is chosen, (and it can be toggled mid-session) the\n% SPM user interface is displayed. This provides a constant visual\n% environment in which data analysis is implemented. The layout has\n% been designed to be simple and at the same time show all the\n% facilities that are available. The interface consists of three\n% windows: A menu window with pushbuttons for the SPM routines (each\n% button has a 'CallBack' string which launches the appropriate\n% function/script); A blank panel used for interaction with the user;\n% And a graphics figure with various editing and print facilities (see\n% spm_figure.m). (These windows are 'Tag'ged 'Menu', 'Interactive', and\n% 'Graphics' respectively, and should be referred to by their tags\n% rather than their figure numbers.)\n%\n% Further interaction with the user is (mainly) via questioning in the\n% 'Interactive' window (managed by spm_input), and file selection\n% (managed by spm_select). See the help on spm_input.m and spm_select.m for\n% details on using these functions.\n%\n% If a \"message of the day\" file named spm_motd.man exists in the SPM\n% directory (alongside spm.m) then it is displayed in the Graphics\n% window on startup.\n%\n% Arguments to this routine (spm.m) lead to various setup facilities,\n% mainly of use to SPM power users and programmers. See programmers\n% FORMAT & help in the main body of spm.m\n%\n%_______________________________________________________________________\n% SPM is developed by members and collaborators of the\n% Wellcome Trust Centre for Neuroimaging\n\n%-SVN ID and authorship of this program...\n%-----------------------------------------------------------------------\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Andrew Holmes\n% $Id: spm.m 1807 2008-06-10 13:39:01Z john $\n\n\n%=======================================================================\n% - FORMAT specifications for embedded CallBack functions\n%=======================================================================\n%( This is a multi function function, the first argument is an action )\n%( string, specifying the particular action function to take. Recall )\n%( MATLAB's command-function duality: `spm Welcome` is equivalent to )\n%( `spm('Welcome')`. )\n%\n% FORMAT spm\n% Defaults to spm('Welcome')\n%\n% FORMAT spm('Welcome')\n% Clears command window, deletes all figures, prints welcome banner and\n% splash screen, sets window defaults.\n%\n% FORMAT spm('AsciiWelcome')\n% Prints ASCII welcome banner in MATLAB command window.\n%\n% FORMAT spm('PET') spm('FMRI') spm('EEG')\n% Closes all windows and draws new Menu, Interactive, and Graphics\n% windows for an SPM session. The buttons in the Menu window launch the\n% main analysis routines.\n%\n% FORMAT Fmenu = spm('CreateMenuWin',Vis)\n% Creates SPM menu window, 'Tag'ged 'Menu'\n% F - handle of figure created\n% Vis - Visibility, 'on' or 'off'\n%\n% Finter = FORMAT spm('CreateIntWin',Vis)\n% Creates an SPM Interactive window, 'Tag'ged 'Interactive'\n% F - handle of figure created\n% Vis - Visibility, 'on' or 'off'\n%\n% FORMAT spm('ChMod',Modality)\n% Changes modality of SPM: Currently SPM supports PET & MRI modalities,\n% each of which have a slightly different Menu window and different\n% defaults. This function switches to the specified modality, setting\n% defaults and displaying the relevant buttons.\n%\n% FORMAT spm('defaults',Modality)\n% Sets default global variables for the specified modality.\n%\n% FORMAT [Modality,ModNum]=spm('CheckModality',Modality)\n% Checks the specified modality against those supported, returns\n% upper(Modality) and the Modality number, it's position in the list of\n% supported Modalities.\n%\n% FORMAT WS=spm('WinScale')\n% Returns ratios of current display dimensions to that of a 1152 x 900\n% Sun display. WS=[Xratio,Yratio,Xratio,Yratio]. Used for scaling other\n% GUI elements.\n% (Function duplicated in spm_figure.m, repeated to reduce inter-dependencies.)\n%\n% FORMAT [FS,sf] = spm('FontSize',FS)\n% FORMAT [FS,sf] = spm('FontSizes',FS)\n% Returns fontsizes FS scaled for the current display.\n% FORMAT sf = spm('FontScale')\n% Returns font scaling factor\n% FS - (vector of) Font sizes to scale [default [1:36]]\n% sf - font scaling factor (FS(out) = floor(FS(in)*sf)\n%\n% Rect = spm('WinSize',Win,raw)\n% Returns sizes and positions for SPM windows.\n% Win - 'Menu', 'Interactive', 'Graphics', or '0'\n% - Window whose position is required. Only first character is\n% examined. '0' returns size of root workspace.\n% raw - If specified, then positions are for a 1152 x 900 Sun display.\n% Otherwise the positions are scaled for the current display.\n%\n% FORMAT SPMdir=spm('Dir',Mfile)\n% Returns the directory containing the version of spm in use,\n% identified as the first in MATLABPATH containing the Mfile spm (this\n% file) (or Mfile if specified).\n%\n% FORMAT [v,c]=spm('Ver',Mfile,ReDo,Cache,Con)\n% Returns the current version (v) & copyright notice, extracted from\n% the top line of the Contents.m file in the directory containing the\n% currently used file Mfile (defaults on omission or empty to 'spm').\n%\n%-The version and copyright information are saved in a global\n% variable called [upper(spm_str_manip(Mfile,'rt')),'_VER'], as a\n% structure with fields 'v' and 'c'. This enables repeat use without\n% recomputation.\n%\n%-If Con [default (missing or empty) 1] is false, then the version\n% information is extracted from Mfile itself, rather than the\n% Contents.m file in the same directory. When using a Contents.m file,\n% the first line is read. For other files, the second line (the H1 help\n% line) is used. This is for consistency with MATLAB's ver and help\n% commands respectively. (This functionality enables toolboxes to be\n% identified by a function rather than a Contents.m file, allowing\n% installation in a directory which already has a Contents.m file.)\n%\n%-If Cache [default (missing or empty) 1] is true, then the version and\n% copyright information cached in the global variable\n% [upper(Mfile),'_VER'], as a structure with fields 'v' and 'c'. This\n% enables repeat use without recomputation.\n%\n%-If ReDo [default (missing or empty) 0] is true, then the version and\n% copyright information are recomputed (regardless of any stored global\n% data).\n%\n% FORMAT xTB = spm('TBs')\n% Identifies installed SPM toolboxes: SPM toolboxes are defined as the\n% contents of sub-directories of fullfile(spm('Dir'),'toolbox') - the\n% SPM toolbox installation directory. For SPM to pick a toolbox up,\n% there must be a single mfile in the directory whose name ends with\n% the toolbox directory name. (I.e. A toolbox called \"test\" would be in\n% the \"test\" subdirectory of spm('Dir'), with a single file named\n% *test.m.) This M-file is regarded as the launch file for the\n% toolbox.\n% xTB - structure array containing toolbox definitions\n% xTB.name - name of toolbox (taken as toolbox directory name)\n% xTB.prog - launch program for toolbox\n% xTB.dir - toolbox directory\n%\n% FORMAT spm('TBlaunch',xTB,i)\n% Launch a toolbox, prepending TBdir to path if necessary\n% xTB - toolbox definition structure (i.e. from spm('TBs')\n% xTB.name - name of toolbox\n% xTB.prog - name of program to launch toolbox\n% xTB.dir - toolbox directory (prepended to path if not on path)\n%\n% FORMAT [c,cName] = spm('Colour')\n% Returns the RGB triple and a description for the current en-vogue SPM\n% colour, the background colour for the Menu and Help windows.\n%\n% FORMAT [v1,v2,...] = spm('GetGlobal',name1,name2,...)\n% Returns values of global variables (without declaring them global)\n% name1, name2,... - name strings of desired globals\n% a1, a2,... - corresponding values of global variables with given names\n% ([] is returned as value if global variable doesn't exist)\n%\n% FORMAT CmdLine = spm('CmdLine',CmdLine)\n% Command line SPM usage?\n% CmdLine (input) - CmdLine preference\n% [defaults (missing or empty) to global defaults.cmdline,]\n% [if it exists, or 0 (GUI) otherwise. ]\n% CmdLine (output) - true if global CmdLine if true,\n% or if on a terminal with no support for graphics windows.\n%\n% FORMAT v = spm('MLver')\n% Returns MATLAB version, truncated to major & minor revision numbers\n%\n% FORMAT spm('PopUpCB',h)\n% Callback handler for PopUp UI menus with multiple callbacks as cellstr UserData\n%\n% FORMAT str = spm('GetUser',fmt)\n% Returns current users login name, extracted from the hosting environment\n% fmt - format string: If USER is defined then sprintf(fmt,USER) is returned\n%\n% FORMAT spm('Beep')\n% Plays the keyboard beep!\n%\n% FORMAT spm('time')\n% Returns the current time and date as hh:mm dd/mm/yyyy\n%\n% FORMAT spm('Pointer',Pointer)\n% Changes pointer on all SPM (HandleVisible) windows to type Pointer\n% Pointer defaults to 'Arrow'. Robust to absence of windows\n%\n% FORMAT h = spm('alert',Message,Title,CmdLine,wait)\n% FORMAT h = spm('alert\"',Message,Title,CmdLine,wait)\n% FORMAT h = spm('alert*',Message,Title,CmdLine,wait)\n% FORMAT h = spm('alert!',Message,Title,CmdLine,wait)\n% Displays an alert, either in a GUI msgbox, or as text in the command window.\n% ( 'alert\"' uses the 'help' msgbox icon, 'alert*' the )\n% ( 'error' icon, 'alert!' the 'warn' icon )\n% Message - string (or cellstr) containing message to print\n% Title - title string for alert\n% CmdLine - CmdLine preference [default spm('CmdLine')]\n% - If CmdLine is complex, then a CmdLine alert is always used,\n% possibly in addition to a msgbox (the latter according\n% to spm('CmdLine').)\n% wait - if true, waits until user dismisses GUI / confirms text alert\n% [default 0] (if doing both GUI & text, waits on GUI alert)\n% h - handle of msgbox created, empty if CmdLine used\n%\n% FORMAT SPMid = spm('FnBanner', Fn,FnV)\n% Prints a function start banner, for version FnV of function Fn, & datestamps\n% FORMAT SPMid = spm('SFnBanner',Fn,FnV)\n% Prints a sub-function start banner\n% FORMAT SPMid = spm('SSFnBanner',Fn,FnV)\n% Prints a sub-sub-function start banner\n% Fn - Function name (string)\n% FnV - Function version (string)\n% SPMid - ID string: [SPMver: Fn (FnV)] \n%\n% FORMAT [Finter,Fgraph,CmdLine] = spm('FnUIsetup',Iname,bGX,CmdLine)\n% Robust UIsetup procedure for functions:\n% Returns handles of 'Interactive' and 'Graphics' figures.\n% Creates 'Interactive' figure if ~CmdLine, creates 'Graphics' figure if bGX.\n% Iname - Name for 'Interactive' window\n% bGX - Need a Graphics window? [default 1]\n% CmdLine - CommandLine usage? [default spm('CmdLine')]\n% Finter - handle of 'Interactive' figure\n% Fgraph - handle of 'Graphics' figure\n% CmdLine - CommandLine usage?\n%\n% FORMAT F = spm('FigName',Iname,F,CmdLine)\n% Set name of figure F to \"SPMver (User): Iname\" if ~CmdLine\n% Robust to absence of figure.\n% Iname - Name for figure\n% F (input) - Handle (or 'Tag') of figure to name [default 'Interactive']\n% CmdLine - CommandLine usage? [default spm('CmdLine')]\n% F (output) - Handle of figure named\n%\n% FORMAT spm('GUI_FileDelete')\n% CallBack for GUI for file deletion, using spm_select and confirmation dialogs\n%\n% FORMAT Fs = spm('Show')\n% Opens all SPM figure windows (with HandleVisibility) using `figure`.\n% Maintains current figure.\n% Fs - vector containing all HandleVisible figures (i.e. get(0,'Children'))\n%\n% FORMAT spm('Clear',Finter, Fgraph)\n% Clears and resets SPM-GUI, clears and timestamps MATLAB command window\n% Finter - handle or 'Tag' of 'Interactive' figure [default 'Interactive']\n% Fgraph - handle or 'Tag' of 'Graphics' figure [default 'Graphics']\n%\n% FORMAT spm('Help',varargin)\n% Merely a gateway to spm_help(varargin) - so you can type \"spm help\"\n% \n%_______________________________________________________________________\n\n\n%-Parameters\n%-----------------------------------------------------------------------\nModalities = {'PET','FMRI','EEG'};\n\n%-Format arguments\n%-----------------------------------------------------------------------\nif nargin == 0, Action = 'Welcome'; else Action = varargin{1}; end\n\n\n%=======================================================================\nswitch lower(Action), case 'welcome' %-Welcome splash screen\n%=======================================================================\n% spm('Welcome')\ncheck_installation;\nspm_defaults;\nglobal defaults\nif isfield(defaults,'modality'), spm(defaults.modality); return; end\n\n%-Open startup window, set window defaults\n%-----------------------------------------------------------------------\n[T, Fwelcome] = evalc('openfig(''spm_Welcome'',''new'',''invisible'');');\nset(Fwelcome,'name',sprintf('%s%s',spm('ver'),spm('GetUser',' (%s)')));\nset(findobj(Fwelcome,'Tag','SPM_VER'),'String',spm('Ver'));\nRectW = spm('WinSize','W',1); Rect0 = spm('WinSize','0',1);\nset(Fwelcome,'Units','pixels', 'Position',...\n [(Rect0(3)-RectW(3))/2 (Rect0(4)-RectW(4))/2 RectW(3) RectW(4)]);\nset(Fwelcome,'Visible','on');\n\n%=======================================================================\ncase 'asciiwelcome' %-ASCII SPM banner welcome\n%=======================================================================\n% spm('AsciiWelcome')\ndisp( ' ___ ____ __ __ ');\ndisp( '/ __)( _ \\( \\/ ) ');\ndisp( '\\__ \\ )___/ ) ( Statistical Parametric Mapping ');\ndisp(['(___/(__) (_/\\/\\_) ',spm('Ver'),' - http://www.fil.ion.ucl.ac.uk/spm/']);\nfprintf('\\n');\n\n\n%=======================================================================\ncase lower(Modalities) %-Initialise SPM in PET, fMRI, EEG modality\n%=======================================================================\n% spm(Modality)\ncheck_installation;\n\n%-Initialisation and workspace canonicalisation\n%-----------------------------------------------------------------------\nlocal_clc;\nspm('AsciiWelcome'); fprintf('\\n\\nInitialising SPM');\nModality = upper(Action); fprintf('.');\ndelete(get(0,'Children')); fprintf('.');\n\n%-Load startup global defaults\n%-----------------------------------------------------------------------\nspm_defaults; fprintf('.');\n\n%-Draw SPM windows\n%-----------------------------------------------------------------------\nFmenu = spm('CreateMenuWin','off'); fprintf('.');\nFinter = spm('CreateIntWin','off'); fprintf('.');\nFgraph = spm_figure('Create','Graphics','Graphics','off'); fprintf('.');\n \nspm_figure('WaterMark',Finter,spm('Ver'),'',45); fprintf('.');\n\nFmotd = fullfile(spm('Dir'),'spm_motd.man');\nif exist(Fmotd,'file'), spm_help('!Disp',Fmotd,'',Fgraph,spm('Ver')); end\n fprintf('.');\n%-Setup for current modality\n%-----------------------------------------------------------------------\nspm('ChMod',Modality); fprintf('.');\n\n%-Reveal windows\n%-----------------------------------------------------------------------\nset([Fmenu,Finter,Fgraph],'Visible','on'); fprintf('done\\n\\n');\n\n%-Print present working directory\n%-----------------------------------------------------------------------\nfprintf('SPM present working directory:\\n\\t%s\\n',pwd)\n\n\n%=======================================================================\ncase 'createmenuwin' %-Create SPM menu window\n%=======================================================================\n% Fmenu = spm('CreateMenuWin',Vis)\n\n%-Close any existing 'Menu' 'Tag'ged windows\n%-----------------------------------------------------------------------\ndelete(spm_figure('FindWin','Menu'))\n[T, Fmenu] = evalc('openfig(''spm_Menu'',''new'',''invisible'');');\nset(Fmenu,'name',sprintf('%s%s',spm('ver'),spm('GetUser',' (%s)')));\nset(Fmenu,'Units','pixels', 'Position',spm('WinSize','M'));\n\n%-Set SPM colour\n%-----------------------------------------------------------------------\nset(findobj(Fmenu,'Tag', 'frame'),'backgroundColor',spm('colour'));\n\n%-Set toolbox\n%-----------------------------------------------------------------------\nxTB = spm('tbs');\nset(findobj(Fmenu,'Tag', 'Toolbox'),'String',{'Toolbox:' xTB.name });\nset(findobj(Fmenu,'Tag', 'Toolbox'),'UserData',xTB);\nvarargout = {Fmenu};\n\n\n%=======================================================================\ncase 'createintwin' %-Create SPM interactive window\n%=======================================================================\n% Finter = spm('CreateIntWin',Vis)\n%-----------------------------------------------------------------------\ndelete(spm_figure('FindWin','Interactive'))\n[T, Finter] = evalc('openfig(''spm_Interactive'',''new'',''invisible'');');\nset(Finter,'name',spm('Ver'));\nset(Finter,'Units','pixels', 'Position',spm('WinSize','I'));\nvarargout = {Finter};\n\n\n%=======================================================================\ncase 'chmod' %-Change SPM modality PET<->fMRI\n%=======================================================================\n% spm('ChMod',Modality)\n%-----------------------------------------------------------------------\n\n%-Sort out arguments\n%-----------------------------------------------------------------------\nif nargin<2, Modality = ''; else Modality = varargin{2}; end\n[Modality,ModNum] = spm('CheckModality',Modality);\n\n%-Sort out global defaults\n%-----------------------------------------------------------------------\nspm('defaults',Modality);\n\n%-Sort out visability of appropriate controls on Menu window\n%-----------------------------------------------------------------------\nFmenu = spm_figure('FindWin','Menu');\nif isempty(Fmenu), error('SPM Menu window not found'), end\n\nif strcmpi(Modality,'PET')\n set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'off');\n set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'off');\n set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'on' );\n set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'on' );\nelseif strcmpi(Modality,'FMRI')\n set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'off');\n set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'off');\n set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'on' );\n set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'on' );\nelse\n set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'off');\n set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'off');\n set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'off');\n set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'on' );\nend\nset(findobj(Fmenu,'Tag','Modality'),'Value',ModNum,'UserData',ModNum);\nspm_jobman('chmod',Modality);\n\n\n%=======================================================================\ncase 'defaults' %-Set SPM defaults (as global variables)\n%=======================================================================\n% spm('defaults',Modality)\n%-----------------------------------------------------------------------\nglobal defaults\nif isempty(defaults), spm_defaults; end\n\n%-Sort out arguments\n%-----------------------------------------------------------------------\nif nargin<2, Modality=''; else Modality=varargin{2}; end\nModality = spm('CheckModality',Modality);\ndefaults.modality = Modality;\ndefaults.SWD = spm('Dir'); % SPM directory\ndefaults.TWD = spm_platform('tempdir'); % Temp directory\n\n%-Set Modality specific default (global variables)\n%-----------------------------------------------------------------------\nglobal UFp\nif strcmpi(defaults.modality,'pet')\n UFp = defaults.stats.pet.ufp; % Upper tail F-prob\nelseif strcmpi(defaults.modality,'fmri')\n UFp = defaults.stats.fmri.ufp; % Upper tail F-prob\nelseif strcmpi(defaults.modality,'eeg')\n ;\nelseif strcmpi(defaults.modality,'unknown')\nelse\n error('Illegal Modality');\nend\n\n\n%=======================================================================\ncase 'quit' %-Quit SPM and clean up\n%=======================================================================\n% spm('Quit')\n%-----------------------------------------------------------------------\ndelete(get(0,'Children'));\nlocal_clc;\nfprintf('Bye for now...\\n\\n');\n\n\n%=======================================================================\ncase 'checkmodality' %-Check & canonicalise modality string\n%=======================================================================\n% [Modality,ModNum] = spm('CheckModality',Modality)\n%-----------------------------------------------------------------------\nif nargin<2, Modality=''; else Modality=upper(varargin{2}); end\nif isempty(Modality)\n global defaults\n if isfield(defaults,'modality'), Modality = defaults.modality;\n else Modality = 'UNKNOWN'; end\nend\nif ischar(Modality)\n ModNum = find(ismember(Modalities,Modality));\nelse\n if ~any(Modality == [1:length(Modalities)])\n Modality = 'ERROR';\n ModNum = [];\n else\n ModNum = Modality;\n Modality = Modalities{ModNum};\n end\nend\n\nif isempty(ModNum), error('Unknown Modality'), end\nvarargout = {upper(Modality),ModNum};\n\n\n%=======================================================================\ncase 'winscale' %-Window scale factors (to fit display)\n%=======================================================================\n% WS = spm('WinScale')\n%-----------------------------------------------------------------------\nif spm_matlab_version_chk('7') >=0\n S0 = get(0, 'MonitorPosition');\nelse\n S0 = get(0,'ScreenSize');\nend\nif all(S0(:)==1), error('Can''t open any graphics windows...'), end\n\nS0 = S0(:,[3 4]) - S0(:,[1 2]) + 1;\nS0 = S0 - rem(S0,2);\n[m,i] = max(prod(S0,2));\nS0 = S0(i,:);\ntmp = [S0(1)/1152 (S0(2)-50)/900];\n\nvarargout = {min(tmp)*[1 1 1 1]};\n\n% Make sure that aspect ratio is about right - for funny shaped screens\n% varargout = {[S0(3)/1152 (S0(4)-50)/900 S0(3)/1152 (S0(4)-50)/900]};\n\n\n%=======================================================================\ncase {'fontsize','fontsizes','fontscale'} %-Font scaling\n%=======================================================================\n% [FS,sf] = spm('FontSize',FS)\n% [FS,sf] = spm('FontSizes',FS)\n% sf = spm('FontScale')\n%-----------------------------------------------------------------------\nif nargin<2, FS=[1:36]; else FS=varargin{2}; end\n\nsf = 1 + 0.85*(min(spm('WinScale'))-1);\n\nif strcmpi(Action,'fontscale')\n varargout = {sf};\nelse\n varargout = {ceil(FS*sf),sf};\nend\n\n\n%=======================================================================\ncase 'winsize' %-Standard SPM window locations and sizes\n%=======================================================================\n% Rect = spm('WinSize',Win,raw)\n%-----------------------------------------------------------------------\nif nargin<3, raw=0; else raw=1; end\nif nargin<2, Win=''; else Win=varargin{2}; end\n\nRect = [[108 466 400 445];...\n [108 045 400 395];...\n [515 015 600 865];...\n [326 310 500 280]];\n\nWS = spm('WinScale');\n\nif isempty(Win)\n WS = ones(3,1)*WS;\nelseif upper(Win(1))=='M'\n %-Menu window\n Rect = Rect(1,:);\nelseif upper(Win(1))=='I'\n %-Interactive window\n Rect = Rect(2,:);\nelseif upper(Win(1))=='G'\n %-Graphics window\n Rect = Rect(3,:);\nelseif upper(Win(1))=='W'\n %-Welcome window\n Rect = Rect(4,:);\nelseif Win(1)=='0'\n %-Root workspace\n if spm_matlab_version_chk('7') >=0\n Rect = get(0, 'MonitorPosition');\n Rect = Rect(1,:);\n else\n Rect = get(0,'ScreenSize');\n end\nelse\n error('Unknown Win type');\nend\n\nif ~raw, Rect = Rect.*WS; end\nvarargout = {Rect};\n\n\n%=======================================================================\ncase 'dir' %-Identify specific (SPM) directory\n%=======================================================================\n% spm('Dir',Mfile)\n%-----------------------------------------------------------------------\nif nargin<2, Mfile='spm'; else Mfile=varargin{2}; end\nSPMdir = which(Mfile);\nif isempty(SPMdir) %-Not found or full pathname given\n if exist(Mfile,'file')==2 %-Full pathname\n SPMdir = Mfile;\n else\n error(['Can''t find ',Mfile,' on MATLABPATH']);\n end\nend\nSPMdir = fileparts(SPMdir);\n\nif exist('isdeployed','builtin') && isdeployed,\n ind = findstr(SPMdir,'_mcr')-1;\n SPMdir = fileparts(SPMdir(1:ind(1)));\nend\nvarargout = {SPMdir};\n\n\n%=======================================================================\ncase 'ver' %-SPM version\n%=======================================================================\n% SPMver = spm('Ver',Mfile,ReDo,Cache,Con)\n%-----------------------------------------------------------------------\nif nargin<5, Con=[]; else Con=varargin{5}; end\nif isempty(Con), Con=1; end\nif nargin<4, Cache=[]; else Cache=varargin{4}; end\nif isempty(Cache), Cache=1; end\nif nargin<3, ReDo=[]; else ReDo=varargin{3}; end\nif isempty(ReDo), ReDo=0; end\nif nargin<2, Mfile=''; else Mfile=varargin{2}; end\nif isempty(Mfile), Mfile='spm'; end\n\nxVname = [upper(spm_str_manip(Mfile,'rt')),'_VER'];\n\n%-See if version info exists in global variable\n%-----------------------------------------------------------------------\nxV = spm('GetGlobal',xVname);\nif ~ReDo && ~isempty(xV)\n if isstruct(xV) && isfield(xV,'v') && isfield(xV,'c')\n varargout = {xV.v,xV.c};\n return\n end\nend\n\n%-Work version out from file\n%-----------------------------------------------------------------------\nif Con\n Vfile = fullfile(spm('Dir',Mfile),'Contents.m');\n skip = 0; %-Don't skip first line\nelse\n Vfile = which(Mfile);\n if isempty(Vfile), error(['Can''t find ',Mfile,' on MATLABPATH']); end\n skip = 1; %-Skip first line\nend\nif exist(Vfile,'file')\n fid = fopen(Vfile,'r');\n str = fgets(fid);\n for i=1:skip, str=fgets(fid); end\n fclose(fid);\n str(1:max(1,min(find(str~='%' & str~=' '))-1))=[];\n tmp = min(find(str==10|str==32));\n v = str(1:tmp-1);\n if str(tmp)==32\n c = str(tmp+1:tmp+min(find(str(tmp+1:end)==10))-1);\n else\n c = '(c) Copyright reserved';\n end\nelse\n v = 'SPM';\n c = '(c) Copyright reserved';\nend\n\n%-Store version info in global variable\n%-----------------------------------------------------------------------\nif Cache\n eval(['global ',xVname])\n eval([xVname,' = struct(''v'',v,''c'',c);'])\nend\n\nvarargout = {v,c};\n\n\n%=======================================================================\ncase 'tbs' %-Identify installed toolboxes\n%=======================================================================\n% xTB = spm('TBs')\n%-----------------------------------------------------------------------\n\n% Toolbox directory\n%-----------------------------------------------------------------------\nTdir = fullfile(spm('Dir'),'toolbox');\n\n%-List of potential installed toolboxes directories\n%-----------------------------------------------------------------------\nif exist(Tdir,'dir')\n d = dir(Tdir); \n d = {d([d.isdir]).name};\n d = {d{cellfun('isempty',regexp(d,'^\\.'))}};\nelse\n d = {};\nend\n\n\n%-Look for a \"main\" M-file in each potential directory\n%-----------------------------------------------------------------------\nxTB = [];\nfor i = 1:length(d)\n tdir = fullfile(Tdir,d{i});\n fn = cellstr(spm_select('List',tdir,['^.*' d{i} '\\.m$']));\n\n if ~isempty(fn{1}),\n xTB(end+1).name = strrep(d{i},'_','');\n xTB(end).prog = spm_str_manip(fn{1},'r');\n xTB(end).dir = tdir;\n end\n\nend\n\nvarargout{1} = xTB;\n\n\n%=======================================================================\ncase 'tblaunch' %-Launch an SPM toolbox\n%=======================================================================\n% xTB = spm('TBlaunch',xTB,i)\n%-----------------------------------------------------------------------\nif nargin < 3, i = 1; else i = varargin{3}; end\nif nargin < 2, xTB = spm('TBs'); else xTB = varargin{2}; end\n\nif i > 0\n %-Addpath (& report)\n %-------------------------------------------------------------------\n if isempty(findstr(xTB(i).dir,path))\n addpath(xTB(i).dir,'-begin');\n spm('alert\"',{'Toolbox directory prepended to Matlab path:',...\n xTB(i).dir},...\n [xTB(i).name,' toolbox'],1);\n end\n\n %-Launch\n %-------------------------------------------------------------------\n evalin('base',xTB(i).prog);\nend\n\n\n%=======================================================================\ncase 'colour' %-SPM interface colour\n%=======================================================================\n% spm('Colour')\n%-----------------------------------------------------------------------\n%-Pre-developmental livery\n% varargout = {[1.0,0.2,0.3],'fightening red'};\n%-Developmental livery\n% varargout = {[0.7,1.0,0.7],'flourescent green'};\n%-Alpha release livery\n% varargout = {[0.9,0.9,0.5],'over-ripe banana'};\n%-Beta release livery\n varargout = {[0.9 0.8 0.9],'blackcurrant purple'};\n%-Distribution livery\n% varargout = {[0.8 0.8 1.0],'vile violet'};\n\nglobal defaults\nif isempty(defaults), spm_defaults; end\nif isfield(defaults,'ui') && isfield(defaults.ui,'colour2')\n varargout{1} = defaults.ui.colour2;\nend\n\n\n%=======================================================================\ncase 'getglobal' %-Get global variable cleanly\n%=======================================================================\n% varargout = spm('GetGlobal',varargin)\n%-----------------------------------------------------------------------\nwg = who('global');\nfor i=1:nargin-1\n if any(strcmp(wg,varargin{i+1}))\n eval(['global ',varargin{i+1},', tmp=',varargin{i+1},';'])\n varargout{i} = tmp;\n else\n varargout{i} = [];\n end\nend\n\n\n%=======================================================================\ncase {'cmdline'} %-SPM command line mode?\n%=======================================================================\n% CmdLine = spm('CmdLine',CmdLine)\n%-----------------------------------------------------------------------\nif nargin<2, CmdLine=[]; else CmdLine = varargin{2}; end\nif isempty(CmdLine)\n global defaults\n if ~isempty(defaults) && isfield(defaults,'cmdline')\n CmdLine = defaults.cmdline;\n else\n CmdLine = 0;\n end\nend\nvarargout = {CmdLine * (get(0,'ScreenDepth')>0)};\n\n\n%=======================================================================\ncase 'mlver' %-MATLAB major & point version number\n%=======================================================================\n% v = spm('MLver')\n%-----------------------------------------------------------------------\nv = version; tmp = find(v=='.');\nif length(tmp)>1, varargout={v(1:tmp(2)-1)}; end\n\n\n%=======================================================================\ncase 'popupcb' %-Callback handling utility for PopUp menus\n%=======================================================================\n% spm('PopUpCB',h)\n%-----------------------------------------------------------------------\nif nargin<2, h=gcbo; else h=varargin{2}; end\nv = get(h,'Value');\nif v==1, return, end\nset(h,'Value',1)\nCBs = get(h,'UserData');\nevalin('base',CBs{v-1})\n\n\n%=======================================================================\ncase 'getuser' %-Get user name\n%=======================================================================\n% str = spm('GetUser',fmt)\n%-----------------------------------------------------------------------\nstr = spm_platform('user');\nif ~isempty(str) && nargin>1, str = sprintf(varargin{2},str); end\nvarargout = {str};\n\n\n%=======================================================================\ncase 'beep' %-Produce beep sound\n%=======================================================================\n% spm('Beep')\n%-----------------------------------------------------------------------\nbeep;\n\n\n%=======================================================================\ncase 'time' %-Return formatted date/time string\n%=======================================================================\n% [timestr, date_vec] = spm('Time')\n%-----------------------------------------------------------------------\ntmp = clock;\nvarargout = {sprintf('%02d:%02d:%02d - %02d/%02d/%4d',...\n tmp(4),tmp(5),floor(tmp(6)),tmp(3),tmp(2),tmp(1)), tmp};\n\n\n%=======================================================================\ncase 'pointer' %-Set mouse pointer in all MATLAB windows\n%=======================================================================\n% spm('Pointer',Pointer)\n%-----------------------------------------------------------------------\nif nargin<2, Pointer='Arrow'; else Pointer=varargin{2}; end\nset(get(0,'Children'),'Pointer',Pointer)\n\n\n%=======================================================================\ncase {'alert','alert\"','alert*','alert!'} %-Alert dialogs\n%=======================================================================\n% h = spm('alert',Message,Title,CmdLine,wait)\n%-----------------------------------------------------------------------\n\n%- Globals \n%-----------------------------------------------------------------------\nif nargin<5, wait = 0; else wait = varargin{5}; end\nif nargin<4, CmdLine = []; else CmdLine = varargin{4}; end\nif nargin<3, Title = ''; else Title = varargin{3}; end\nif nargin<2, Message = ''; else Message = varargin{2}; end\nMessage = cellstr(Message);\n\nif isreal(CmdLine)\n CmdLine = spm('CmdLine',CmdLine);\n CmdLine2 = 0;\nelse\n CmdLine = spm('CmdLine');\n CmdLine2 = 1;\nend\ntimestr = spm('Time');\nSPMv = spm('ver');\n\nswitch(lower(Action))\n case 'alert', icon = 'none'; str = '--- ';\n case 'alert\"', icon = 'help'; str = '~ - ';\n case 'alert*', icon = 'error'; str = '* - ';\n case 'alert!', icon = 'warn'; str = '! - ';\nend\n\nif CmdLine || CmdLine2\n Message(strcmp(Message,'')) = {' '};\n tmp = sprintf('%s: %s',SPMv,Title);\n fprintf('\\n %s%s %s\\n\\n',str,tmp,repmat('-',1,62-length(tmp)))\n fprintf(' %s\\n',Message{:})\n fprintf('\\n %s %s\\n\\n',repmat('-',1,62-length(timestr)),timestr)\n h = [];\nend\n\nif ~CmdLine\n tmp = max(size(char(Message),2),42) - length(SPMv) - length(timestr);\n str = sprintf('%s %s %s',SPMv,repmat(' ',1,tmp-4),timestr);\n h = msgbox([{''};Message(:);{''};{''};{str}],...\n sprintf('%s%s: %s',SPMv,spm('GetUser',' (%s)'),Title),...\n icon,'non-modal');\n drawnow\n set(h,'windowstyle','modal');\nend\n\nif wait\n if isempty(h)\n input(' press ENTER to continue...');\n else\n uiwait(h)\n h = [];\n end\nend\n\nif nargout, varargout = {h}; end\n\n\n%=======================================================================\ncase {'fnbanner','sfnbanner','ssfnbanner'} %-Text banners for functions\n%=======================================================================\n% SPMid = spm('FnBanner', Fn,FnV)\n% SPMid = spm('SFnBanner',Fn,FnV)\n% SPMid = spm('SSFnBanner',Fn,FnV)\n%-----------------------------------------------------------------------\ntime = spm('time');\nstr = spm('ver');\nif nargin>=2, str = [str,': ',varargin{2}]; end\nif nargin>=3, str = [str,' (v',varargin{3},')']; end\n\nswitch lower(Action)\ncase 'fnbanner'\n tab = '';\n wid = 72;\n lch = '=';\ncase 'sfnbanner'\n tab = sprintf('\\t');\n wid = 72-8;\n lch = '-';\ncase 'ssfnbanner'\n tab = sprintf('\\t\\t');\n wid = 72-2*8;\n lch = '-';\nend\n\nfprintf('\\n%s%s',tab,str)\nfprintf('%c',repmat(' ',1,wid-length([str,time])))\nfprintf('%s\\n%s',time,tab)\nfprintf('%c',repmat(lch,1,wid)),fprintf('\\n')\nvarargout = {str};\n\n\n%=======================================================================\ncase 'fnuisetup' %-Robust UI setup for main SPM functions\n%=======================================================================\n% [Finter,Fgraph,CmdLine] = spm('FnUIsetup',Iname,bGX,CmdLine)\n%-----------------------------------------------------------------------\nif nargin<4, CmdLine=spm('CmdLine'); else CmdLine=varargin{4}; end\nif nargin<3, bGX=1; else bGX=varargin{3}; end\nif nargin<2, Iname=''; else Iname=varargin{2}; end\nif CmdLine\n Finter = spm_figure('FindWin','Interactive');\n if ~isempty(Finter), spm_figure('Clear',Finter), end\n %if ~isempty(Iname), fprintf('%s:\\n',Iname), end\nelse\n Finter = spm_figure('GetWin','Interactive');\n spm_figure('Clear',Finter)\n if ~isempty(Iname)\n str = sprintf('%s (%s): %s',spm('ver'),spm('GetUser'),Iname);\n else\n str = '';\n end\n set(Finter,'Name',str)\nend\n\nif bGX\n Fgraph = spm_figure('GetWin','Graphics');\n spm_figure('Clear',Fgraph)\nelse\n Fgraph = spm_figure('FindWin','Graphics');\nend\nvarargout = {Finter,Fgraph,CmdLine};\n\n\n%=======================================================================\ncase 'figname' %-Robust SPM figure naming\n%=======================================================================\n% F = spm('FigName',Iname,F,CmdLine)\n%-----------------------------------------------------------------------\nif nargin<4, CmdLine=spm('CmdLine'); else CmdLine=varargin{4}; end\nif nargin<3, F='Interactive'; else F=varargin{3}; end\nif nargin<2, Iname=''; else Iname=varargin{2}; end\n\n%if ~isempty(Iname), fprintf('\\t%s\\n',Iname), end\nif CmdLine, varargout={[]}; return, end\nF = spm_figure('FindWin',F);\nif ~isempty(F) && ~isempty(Iname)\n set(F,'Name',sprintf('%s (%s): %s',spm('ver'),spm('GetUser'),Iname))\nend\nvarargout={F};\n\n\n%=======================================================================\ncase 'gui_filedelete' %-GUI file deletion\n%=======================================================================\n% spm('GUI_FileDelete')\n%-----------------------------------------------------------------------\nP = cellstr(spm_select(Inf,'.*','Select file(s) to delete'));\nn = numel(P);\nif n==0\n spm('alert\"','Nothing selected to delete!','file delete',0);\n return\nelseif n<4\n str=[{' '};P];\nelseif n<11\n str=[{' '};P;{' ';sprintf('(%d files)',n)}];\nelse\n str=[{' '};P(1:min(n,10));{'...';' ';sprintf('(%d files)',n)}];\nend\nif spm_input(str,-1,'bd','delete|cancel',[1,0],[],'confirm file delete')\n feval(@spm_unlink,P{:});\n spm('alert\"',P,'file delete',1);\nend\n\n\n%=======================================================================\ncase 'show' %-Bring visible MATLAB windows to the fore\n%=======================================================================\n% Fs = spm('Show')\n%-----------------------------------------------------------------------\ncF = get(0,'CurrentFigure');\nFs = get(0,'Children');\nFs = findobj(Fs,'flat','Visible','on');\nfor F=Fs', figure(F), end\nset(0,'CurrentFigure',cF)\nspm('FnBanner','GUI show');\nvarargout={Fs};\n\n\n%=======================================================================\ncase 'clear' %-Clear SPM GUI\n%=======================================================================\n% spm('Clear',Finter, Fgraph)\n%-----------------------------------------------------------------------\nif nargin<3, Fgraph='Graphics'; else Fgraph=varargin{3}; end\nif nargin<2, Finter='Interactive'; else Finter=varargin{2}; end\nspm_figure('Clear',Fgraph)\nspm_figure('Clear',Finter)\nspm('Pointer','Arrow')\nspm_select('clearvfiles');\nspm_conman('Initialise','reset');\nlocal_clc, spm('FnBanner','GUI cleared');\nfprintf('\\n');\n%evalin('base','clear')\n\n\n%=======================================================================\ncase 'clean' %-Clean MATLAB workspace\n%=======================================================================\n% spm('Clean')\n%-----------------------------------------------------------------------\nevalin('base','clear all');\nevalc('clear classes');\n\n\n%=======================================================================\ncase 'help' %-Pass through for spm_help\n%=======================================================================\n% spm('Help',varargin)\n%-----------------------------------------------------------------------\nif nargin>1, spm_help(varargin{2:end}), else spm_help, end\n\n\n%=======================================================================\notherwise %-Unknown action string\n%=======================================================================\nerror('Unknown action string')\n\n%=======================================================================\nend\n\n\n%=======================================================================\nfunction local_clc\n%=======================================================================\nif ~(exist('isdeployed','builtin') && isdeployed),\n clc\nend\n\n%=======================================================================\nfunction check_installation\n%=======================================================================\nif (exist('isdeployed','builtin') && isdeployed),\n return\nend\n\n%-Disable warning messages due to dll files still existing\n%-----------------------------------------------------------------------\nif spm_matlab_version_chk('7') >=0,\n warning('off','MATLAB:dispatcher:ShadowedMEXExtension');\nend\n\n%-Disable Java if necessary\n%-----------------------------------------------------------------------\ntry\n feature('JavaFigures',0);\nend\n\n%-Check installation\n%-----------------------------------------------------------------------\nspm('Ver','spm',1);\nd = spm('Dir');\n\n%-Check the search path\n%-----------------------------------------------------------------------\nif ~ismember(lower(d),lower(strread(path,'%s','delimiter',pathsep)))\n error(sprintf([...\n 'You do not appear to have the MATLAB search path\\n'...\n 'set up to include your SPM5 distribution. This\\n'...\n 'means that you can start SPM in this directory,\\n'...\n 'but if you change to another directory then MATLAB\\n'...\n 'will be unable to find the SPM functions. You\\n'...\n 'can use the editpath command in MATLAB to set it up.\\n'...\n 'For more information, try typing the following:\\n'...\n ' help path\\n help editpath']));\nend\n\n%-Ensure that the original release - as well as the updates - was installed.\n%-----------------------------------------------------------------------\nif ~exist(fullfile(d,'spm_showdoc.m'),'file'), % This is a file that should not have changed\n if isunix,\n error(sprintf([...\n 'There appears to be some problem with the installation.\\n'...\n 'The original spm5.tar.gz distribution should be installed\\n'...\n 'and the updates installed on top of this. Unix commands\\n'...\n 'to do this are:\\n'...\n ' gunzip < spm5.tar.gz | tar xvf -\\n'...\n ' cd spm5\\n'...\n ' gunzip < Updates_????.tar.gz | tar xvf -\\n'...\n 'You may need help from your local network administrator.']));\n else\n error(sprintf([...\n 'There appears to be some problem with the installation.\\n'...\n 'The original spm5.tar.gz distribution should be installed\\n'...\n 'and the updates installed on top of this. If in doubt,\\n'...\n 'consult your local network administrator.']));\n end\nend\n\n%-Ensure that the files were unpacked correctly\n%-----------------------------------------------------------------------\nif ispc\n try\n t = load(fullfile(d,'Split.mat'));\n catch\n error(sprintf([...\n 'There appears to be some problem reading the MATLAB\\n'...\n '.mat files from the SPM distribution. This is probably\\n'...\n 'something to do with the way that the distribution was\\n'...\n 'unpacked. If you used WinZip, then ensure that\\n'...\n 'TAR file smart CR/LF conversion is disabled\\n'...\n '(under the Miscellaneous Configuration Options).']));\n end\n if ~exist(fullfile(d,'toolbox','DARTEL','diffeo3d.c'),'file'),\n error(sprintf([...\n 'There appears to be some problem with the installation.\\n'...\n 'This is probably something to do with the way that the\\n'...\n 'distribution was unbundled from the original .tar.gz files.'...\n 'Please ensure that the files are unpacked so that the\\n'...\n 'directory structure is retained.']));\n end\nend\n\n%-Check the mex files\n%-----------------------------------------------------------------------\ntry\n feval(@spm_atranspa,1);\ncatch\n error(sprintf([...\n 'SPM uses a number of \"mex\" files, which are compiled functions.\\n'...\n 'These need to be compiled for the various platforms on which SPM\\n'...\n 'is run. At the FIL, where SPM is developed, the number of\\n'...\n 'computer platforms is limited. It is therefore not possible to\\n'...\n 'release a version of SPM that will run on all computers. See\\n'...\n ' %s%csrc%cMakefile\\n'...\n 'for information about how to compile mex files for %s\\n'...\n 'in MATLAB %s.'],...\n d,filesep,filesep,computer,version));\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_orthviews.m", "ext": ".m", "path": "spm5-master/spm_orthviews.m", "size": 68912, "source_encoding": "utf_8", "md5": "1dc045bfb0614e8391a168a981d1b05f", "text": "function varargout = spm_orthviews(action,varargin)\n% Display Orthogonal Views of a Normalized Image\n% FORMAT H = spm_orthviews('Image',filename[,position])\n% filename - name of image to display\n% area - position of image\n% - area(1) - position x\n% - area(2) - position y\n% - area(3) - size x\n% - area(4) - size y\n% H - handle for ortho sections\n% FORMAT spm_orthviews('BB',bb)\n% bb - bounding box\n% [loX loY loZ\n% hiX hiY hiZ]\n%\n% FORMAT spm_orthviews('Redraw')\n% Redraws the images\n%\n% FORMAT spm_orthviews('Reposition',centre)\n% centre - X, Y & Z coordinates of centre voxel\n%\n% FORMAT spm_orthviews('Space'[,handle[,M,dim]])\n% handle - the view to define the space by, optionally with extra\n% transformation matrix and dimensions (e.g. one of the blobs\n% of a view)\n% with no arguments - puts things into mm space\n%\n% FORMAT spm_orthviews('MaxBB')\n% sets the bounding box big enough display the whole of all images\n%\n% FORMAT spm_orthviews('Resolution',res)\n% res - resolution (mm)\n%\n% FORMAT spm_orthviews('Delete', handle)\n% handle - image number to delete\n%\n% FORMAT spm_orthviews('Reset')\n% clears the orthogonal views\n%\n% FORMAT spm_orthviews('Pos')\n% returns the co-ordinate of the crosshairs in millimetres in the\n% standard space.\n%\n% FORMAT spm_orthviews('Pos', i)\n% returns the voxel co-ordinate of the crosshairs in the image in the\n% ith orthogonal section.\n%\n% FORMAT spm_orthviews('Xhairs','off') OR spm_orthviews('Xhairs')\n% disables the cross-hairs on the display.\n%\n% FORMAT spm_orthviews('Xhairs','on')\n% enables the cross-hairs.\n%\n% FORMAT spm_orthviews('Interp',hld)\n% sets the hold value to hld (see spm_slice_vol).\n%\n% FORMAT spm_orthviews('AddBlobs',handle,XYZ,Z,mat)\n% Adds blobs from a pointlist to the image specified by the handle(s).\n% handle - image number to add blobs to\n% XYZ - blob voxel locations (currently in millimeters)\n% Z - blob voxel intensities\n% mat - matrix from millimeters to voxels of blob.\n% name - a name for this blob\n% This method only adds one set of blobs, and displays them using a\n% split colour table.\n%\n% FORMAT spm_orthviews('AddColouredBlobs',handle,XYZ,Z,mat,colour,name)\n% Adds blobs from a pointlist to the image specified by the handle(s).\n% handle - image number to add blobs to\n% XYZ - blob voxel locations (currently in millimeters)\n% Z - blob voxel intensities\n% mat - matrix from millimeters to voxels of blob.\n% colour - the 3 vector containing the colour that the blobs should be\n% name - a name for this blob\n% Several sets of blobs can be added in this way, and it uses full colour.\n% Although it may not be particularly attractive on the screen, the colour\n% blobs print well.\n%\n% FORMAT spm_orthviews('AddColourBar',handle,blobno)\n% Adds colourbar for a specified blob set\n% handle - image number\n% blobno - blob number\n%\n% FORMAT spm_orthviews('Register',hReg)\n% See spm_XYZreg for more information.\n%\n% FORMAT spm_orthviews('RemoveBlobs',handle)\n% Removes all blobs from the image specified by the handle(s).\n%\n% spm_orthviews('Register',hReg)\n% hReg - Handle of HandleGraphics object to build registry in.\n% See spm_XYZreg for more information.\n%\n% spm_orthviews('AddContext',handle)\n% handle - image number to add context menu to\n%\n% spm_orthviews('RemoveContext',handle)\n% handle - image number to remove context menu from\n%\n% CONTEXT MENU\n% spm_orthviews offers many of its features in a context menu, which is\n% accessible via the right mouse button in each displayed image.\n%\n% PLUGINS\n% The display capabilities of spm_orthviews can be extended with\n% plugins. These are located in the spm_orthviews subdirectory of the SPM\n% distribution. Currently there are 3 plugins available:\n% quiver Add Quiver plots to a displayed image\n% quiver3d Add 3D Quiver plots to a displayed image\n% roi ROI creation and modification\n% The functionality of plugins can be accessed via calls to\n% spm_orthviews('plugin_name', plugin_arguments). For detailed descriptions\n% of each plugin see help spm_orthviews/spm_ov_'plugin_name'.\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner, Matthew Brett, Tom Nichols and Volkmar Glauche\n% $Id: spm_orthviews.m 2946 2009-03-25 11:17:36Z volkmar $\n\n\n\n% The basic fields of st are:\n% n - the number of images currently being displayed\n% vols - a cell array containing the data on each of the\n% displayed images.\n% Space - a mapping between the displayed images and the\n% mm space of each image.\n% bb - the bounding box of the displayed images.\n% centre - the current centre of the orthogonal views\n% callback - a callback to be evaluated on a button-click.\n% xhairs - crosshairs off/on\n% hld - the interpolation method\n% fig - the figure that everything is displayed in\n% mode - the position/orientation of the sagittal view.\n% - currently always 1\n% \n% st.registry.hReg \\_ See spm_XYZreg for documentation\n% st.registry.hMe /\n% \n% For each of the displayed images, there is a non-empty entry in the\n% vols cell array. Handles returned by \"spm_orthviews('Image',.....)\"\n% indicate the position in the cell array of the newly created ortho-view.\n% Operations on each ortho-view require the handle to be passed.\n% \n% When a new image is displayed, the cell entry contains the information\n% returned by spm_vol (type help spm_vol for more info). In addition,\n% there are a few other fields, some of which I will document here:\n% \n% premul - a matrix to premultiply the .mat field by. Useful\n% for re-orienting images.\n% window - either 'auto' or an intensity range to display the\n% image with.\n% mapping- Mapping of image intensities to grey values. Currently\n% one of 'linear', 'histeq', loghisteq',\n% 'quadhisteq'. Default is 'linear'.\n% Histogram equalisation depends on the image toolbox\n% and is only available if there is a license available\n% for it.\n% ax - a cell array containing an element for the three\n% views. The fields of each element are handles for\n% the axis, image and crosshairs.\n% \n% blobs - optional. Is there for using to superimpose blobs.\n% vol - 3D array of image data\n% mat - a mapping from vox-to-mm (see spm_vol, or\n% help on image formats).\n% max - maximum intensity for scaling to. If it\n% does not exist, then images are auto-scaled.\n% \n% There are two colouring modes: full colour, and split\n% colour. When using full colour, there should be a\n% 'colour' field for each cell element. When using\n% split colourscale, there is a handle for the colorbar\n% axis.\n% \n% colour - if it exists it contains the\n% red,green,blue that the blobs should be\n% displayed in.\n% cbar - handle for colorbar (for split colourscale).\n%\n% PLUGINS\n% The plugin concept has been developed to extend the display capabilities\n% of spm_orthviews without the need to rewrite parts of it. Interaction\n% between spm_orthviews and plugins takes place\n% a) at startup: The subfunction 'reset_st' looks for files with a name\n% spm_ov_PLUGINNAME.m in the directory 'SWD/spm_orthviews'.\n% For each such file, PLUGINNAME will be added to the list\n% st.plugins{:}.\n% The subfunction 'add_context' calls each plugin with\n% feval(['spm_ov_', st.plugins{k}], ...\n%\t\t\t 'context_menu', i, parent_menu)\n% Each plugin may add its own submenu to the context\n% menu.\n% b) at redraw: After images and blobs of st.vols{i} are drawn, the\n% struct st.vols{i} is checked for field names that occur in\n% the plugin list st.plugins{:}. For each matching entry, the\n% corresponding plugin is called with the command 'redraw':\n% feval(['spm_ov_', st.plugins{k}], ...\n%\t\t\t 'redraw', i, TM0, TD, CM0, CD, SM0, SD);\n% The values of TM0, TD, CM0, CD, SM0, SD are defined in the\n% same way as in the redraw subfunction of spm_orthviews.\n% It is up to the plugin to do all necessary redraw\n% operations for its display contents. Each displayed item\n% must have set its property 'HitTest' to 'off' to let events\n% go through to the underlying axis, which is responsible for\n% callback handling. The order in which plugins are called is\n% undefined.\n\nglobal st;\n\nif isempty(st), reset_st; end;\n\nspm('Pointer','watch');\n\nif nargin == 0, action = ''; end;\naction = lower(action);\n\nswitch lower(action),\ncase 'image',\n\tH = specify_image(varargin{1});\n\tif ~isempty(H)\n\t\tst.vols{H}.area = [0 0 1 1];\n\t\tif length(varargin)>=2, st.vols{H}.area = varargin{2}; end;\n\t\tif isempty(st.bb), st.bb = maxbb; end;\n\t\tbbox;\n\t\tcm_pos;\n\tend;\n\tvarargout{1} = H;\n\tst.centre = mean(maxbb);\n\tredraw_all\n\ncase 'bb',\n\tif length(varargin)> 0 && all(size(varargin{1})==[2 3]), st.bb = varargin{1}; end;\n\tbbox;\n\tredraw_all;\n\ncase 'redraw',\n\tredraw_all;\n\teval(st.callback);\n\tif isfield(st,'registry'),\n\t\tspm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe);\n\tend;\n\ncase 'reposition',\n\tif length(varargin)<1, tmp = findcent;\n\telse tmp = varargin{1}; end;\n\tif length(tmp)==3,\n h = valid_handles(st.snap);\n if ~isempty(h)\n tmp=st.vols{h(1)}.mat*...\n round(inv(st.vols{h(1)}.mat)*[tmp; ...\n 1]);\n end;\n st.centre = tmp(1:3); \n\tend;\n\tredraw_all;\n\teval(st.callback);\n\tif isfield(st,'registry'),\n\t\tspm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe);\n\tend;\n\tcm_pos;\n\ncase 'setcoords',\n\tst.centre = varargin{1};\n\tst.centre = st.centre(:);\n\tredraw_all;\n\teval(st.callback);\n\tcm_pos;\n\ncase 'space',\n\tif length(varargin)<1,\n\t\tst.Space = eye(4);\n\t\tst.bb = maxbb;\n\t\tbbox;\n\t\tredraw_all;\n\telse\n\t\tspace(varargin{:});\n\t\tbbox;\n\t\tredraw_all;\n\tend;\n\ncase 'maxbb',\n\tst.bb = maxbb;\n\tbbox;\n\tredraw_all;\n\ncase 'resolution',\n\tresolution(varargin{1});\n\tbbox;\n\tredraw_all;\n\ncase 'window',\n\tif length(varargin)<2,\n\t\twin = 'auto';\n\telseif length(varargin{2})==2,\n\t\twin = varargin{2};\n\tend;\n\tfor i=valid_handles(varargin{1}),\n\t\tst.vols{i}.window = win;\n\tend;\n\tredraw(varargin{1});\n\ncase 'delete',\n\tmy_delete(varargin{1});\n\ncase 'move',\n\tmove(varargin{1},varargin{2});\n\t% redraw_all;\n\ncase 'reset',\n\tmy_reset;\n\ncase 'pos',\n\tif isempty(varargin),\n\t\tH = st.centre(:);\n\telse\n\t\tH = pos(varargin{1});\n\tend;\n\tvarargout{1} = H;\n\ncase 'interp',\n\tst.hld = varargin{1};\n\tredraw_all;\n\ncase 'xhairs',\n\txhairs(varargin{1});\n\ncase 'register',\n\tregister(varargin{1});\n\ncase 'addblobs',\n\taddblobs(varargin{:});\n\t% redraw(varargin{1});\n\ncase 'addcolouredblobs',\n\taddcolouredblobs(varargin{:});\n\t% redraw(varargin{1});\n\ncase 'addimage',\n\taddimage(varargin{1}, varargin{2});\n\t% redraw(varargin{1});\n\ncase 'addcolouredimage',\n\taddcolouredimage(varargin{1}, varargin{2},varargin{3});\n\t% redraw(varargin{1});\n\ncase 'addtruecolourimage',\n\t% spm_orthviews('Addtruecolourimage',handle,filename,colourmap,prop,mx,mn)\n\t% Adds blobs from an image in true colour\n\t% handle - image number to add blobs to [default 1]\n\t% filename of image containing blob data [default - request via GUI]\n\t% colourmap - colormap to display blobs in [GUI input]\n\t% prop - intensity proportion of activation cf grayscale [0.4]\n\t% mx - maximum intensity to scale to [maximum value in activation image]\n\t% mn - minimum intensity to scale to [minimum value in activation image]\n\t%\n\tif nargin < 2\n\t\tvarargin(1) = {1};\n\tend\n\tif nargin < 3\n\t\tvarargin(2) = {spm_select(1, 'image', 'Image with activation signal')};\n\tend\n\tif nargin < 4\n\t\tactc = [];\n\t\twhile isempty(actc)\n\t\t\tactc = getcmap(spm_input('Colourmap for activation image', '+1','s'));\n\t\tend\n\t\tvarargin(3) = {actc};\n\tend\n\tif nargin < 5\n\t\tvarargin(4) = {0.4};\n\tend\n\tif nargin < 6\n\t\tactv = spm_vol(varargin{2});\n\t\tvarargin(5) = {max([eps maxval(actv)])};\n\tend\n\tif nargin < 7\n\t\tvarargin(6) = {min([0 minval(actv)])};\n\tend\n\n\taddtruecolourimage(varargin{1}, varargin{2},varargin{3}, varargin{4}, ...\n\t varargin{5}, varargin{6});\n\t% redraw(varargin{1});\n\ncase 'addcolourbar',\n addcolourbar(varargin{1}, varargin{2});\n \ncase 'rmblobs',\n\trmblobs(varargin{1});\n\tredraw(varargin{1});\n\ncase 'addcontext',\n\tif nargin == 1,\n\t\thandles = 1:24;\n\telse\n\t\thandles = varargin{1};\n\tend;\n\taddcontexts(handles);\n\ncase 'rmcontext',\n\tif nargin == 1,\n\t\thandles = 1:24;\n\telse\n\t\thandles = varargin{1};\n\tend;\n\trmcontexts(handles);\n\ncase 'context_menu',\n\tc_menu(varargin{:});\n\ncase 'valid_handles',\n\tif nargin == 1\n\t\thandles = 1:24;\n\telse\n\t\thandles = varargin{1};\n\tend;\n\tvarargout{1} = valid_handles(handles);\n\notherwise,\n addonaction = strcmp(st.plugins,action);\n if any(addonaction)\n feval(['spm_ov_' st.plugins{addonaction}],varargin{:});\n end;\nend;\n\nspm('Pointer');\nreturn;\n\n\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction addblobs(handle, xyz, t, mat, name)\nglobal st\nif nargin < 5\n name = '';\nend;\nfor i=valid_handles(handle),\n\tif ~isempty(xyz),\n\t\trcp = round(xyz);\n\t\tdim = max(rcp,[],2)';\n\t\toff = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1));\n\t\tvol = zeros(dim)+NaN;\n\t\tvol(off) = t;\n\t\tvol = reshape(vol,dim);\n\t\tst.vols{i}.blobs=cell(1,1);\n\t\tmx = max([eps max(t)]);\n\t\tmn = min([0 min(t)]);\n\t\tst.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'max',mx, 'min',mn,'name',name);\n\t\taddcolourbar(handle,1);\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction addimage(handle, fname)\nglobal st\nfor i=valid_handles(handle),\n\tif isstruct(fname),\n\t\tvol = fname(1);\n\telse\n\t\tvol = spm_vol(fname);\n\tend;\n\tmat = vol.mat;\n\tst.vols{i}.blobs=cell(1,1);\n\tmx = max([eps maxval(vol)]);\n\tmn = min([0 minval(vol)]);\n\tst.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'max',mx,'min',mn);\n\taddcolourbar(handle,1);\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction addcolouredblobs(handle, xyz, t, mat, colour, name)\nif nargin < 6\n name = '';\nend;\nglobal st\nfor i=valid_handles(handle),\n\tif ~isempty(xyz),\n\t\trcp = round(xyz);\n\t\tdim = max(rcp,[],2)';\n\t\toff = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1));\n\t\tvol = zeros(dim)+NaN;\n\t\tvol(off) = t;\n\t\tvol = reshape(vol,dim);\n\t\tif ~isfield(st.vols{i},'blobs'),\n\t\t\tst.vols{i}.blobs=cell(1,1);\n\t\t\tbset = 1;\n\t\telse\n\t\t\tbset = length(st.vols{i}.blobs)+1;\n\t\tend;\n mx = max([eps maxval(vol)]);\n mn = min([0 minval(vol)]);\n\t\tst.vols{i}.blobs{bset} = struct('vol',vol, 'mat',mat, ...\n 'max',mx, 'min',mn, ...\n 'colour',colour, 'name',name);\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction addcolouredimage(handle, fname,colour)\nglobal st\nfor i=valid_handles(handle),\n\tif isstruct(fname),\n\t\tvol = fname(1);\n\telse\n\t\tvol = spm_vol(fname);\n\tend;\n\tmat = vol.mat;\n\tif ~isfield(st.vols{i},'blobs'),\n\t\tst.vols{i}.blobs=cell(1,1);\n\t\tbset = 1;\n\telse\n\t\tbset = length(st.vols{i}.blobs)+1;\n\tend;\n\tmx = max([eps maxval(vol)]);\n\tmn = min([0 minval(vol)]);\n\tst.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx,'min',mn,'colour',colour);\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction addtruecolourimage(handle,fname,colourmap,prop,mx,mn)\n% adds true colour image to current displayed image \nglobal st\nfor i=valid_handles(handle),\n\tif isstruct(fname),\n\t\tvol = fname(1);\n\telse\n\t\tvol = spm_vol(fname);\n\tend;\n\tmat = vol.mat;\n\tif ~isfield(st.vols{i},'blobs'),\n\t\tst.vols{i}.blobs=cell(1,1);\n\t\tbset = 1;\n\telse\n\t\tbset = length(st.vols{i}.blobs)+1;\n\tend;\n\tc = struct('cmap', colourmap,'prop',prop);\n\tst.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx, ...\n 'min',mn,'colour',c);\n\taddcolourbar(handle,bset);\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction addcolourbar(vh,bh)\nglobal st\nif st.mode == 0,\n axpos = get(st.vols{vh}.ax{2}.ax,'Position');\nelse\n axpos = get(st.vols{vh}.ax{1}.ax,'Position');\nend;\nst.vols{vh}.blobs{bh}.cbar = axes('Parent',st.fig,...\n 'Position',[(axpos(1)+axpos(3)+0.05+(bh-1)*.1) (axpos(2)+0.005) 0.05 (axpos(4)-0.01)],...\n 'Box','on', 'YDir','normal', 'XTickLabel',[], 'XTick',[]);\nif isfield(st.vols{vh}.blobs{bh},'name')\n ylabel(st.vols{vh}.blobs{bh}.name,'parent',st.vols{vh}.blobs{bh}.cbar);\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction rmblobs(handle)\nglobal st\nfor i=valid_handles(handle),\n\tif isfield(st.vols{i},'blobs'),\n\t\tfor j=1:length(st.vols{i}.blobs),\n\t\t\tif isfield(st.vols{i}.blobs{j},'cbar') && ishandle(st.vols{i}.blobs{j}.cbar),\n\t\t\t\tdelete(st.vols{i}.blobs{j}.cbar);\n\t\t\tend;\n\t\tend;\n\t\tst.vols{i} = rmfield(st.vols{i},'blobs');\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction register(hreg)\nglobal st\ntmp = uicontrol('Position',[0 0 1 1],'Visible','off','Parent',st.fig);\nh = valid_handles(1:24);\nif ~isempty(h),\n\ttmp = st.vols{h(1)}.ax{1}.ax;\n\tst.registry = struct('hReg',hreg,'hMe', tmp);\n\tspm_XYZreg('Add2Reg',st.registry.hReg,st.registry.hMe, 'spm_orthviews');\nelse\n\twarning('Nothing to register with');\nend;\nst.centre = spm_XYZreg('GetCoords',st.registry.hReg);\nst.centre = st.centre(:);\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction xhairs(arg1)\nglobal st\nst.xhairs = 0;\nopt = 'on';\nif ~strcmp(arg1,'on'),\n\topt = 'off';\nelse\n\tst.xhairs = 1;\nend;\nfor i=valid_handles(1:24),\n\tfor j=1:3,\n\t\tset(st.vols{i}.ax{j}.lx,'Visible',opt);\n\t\tset(st.vols{i}.ax{j}.ly,'Visible',opt); \n\tend; \nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction H = pos(arg1)\nglobal st\nH = [];\nfor arg1=valid_handles(arg1),\n\tis = inv(st.vols{arg1}.premul*st.vols{arg1}.mat);\n\tH = is(1:3,1:3)*st.centre(:) + is(1:3,4);\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction my_reset\nglobal st\nif ~isempty(st) && isfield(st,'registry') && ishandle(st.registry.hMe),\n\tdelete(st.registry.hMe); st = rmfield(st,'registry');\nend;\nmy_delete(1:24);\nreset_st;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction my_delete(arg1)\nglobal st\nfor i=valid_handles(arg1),\n\tkids = get(st.fig,'Children');\n\tfor j=1:3,\n\t\tif any(kids == st.vols{i}.ax{j}.ax),\n\t\t\tset(get(st.vols{i}.ax{j}.ax,'Children'),'DeleteFcn','');\n\t\t\tdelete(st.vols{i}.ax{j}.ax);\n\t\tend;\n\tend;\n\tst.vols{i} = [];\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction resolution(arg1)\nglobal st\nres = arg1/mean(svd(st.Space(1:3,1:3)));\nMat = diag([res res res 1]);\nst.Space = st.Space*Mat;\nst.bb = st.bb/res;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction move(handle,pos)\nglobal st\nfor handle = valid_handles(handle),\n\tst.vols{handle}.area = pos;\nend;\nbbox;\n% redraw(valid_handles(handle));\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction bb = maxbb\nglobal st\nmn = [Inf Inf Inf];\nmx = -mn;\nfor i=valid_handles(1:24),\n\tbb = [[1 1 1];st.vols{i}.dim(1:3)];\n\tc = [\tbb(1,1) bb(1,2) bb(1,3) 1\n\t\tbb(1,1) bb(1,2) bb(2,3) 1\n\t\tbb(1,1) bb(2,2) bb(1,3) 1\n\t\tbb(1,1) bb(2,2) bb(2,3) 1\n\t\tbb(2,1) bb(1,2) bb(1,3) 1\n\t\tbb(2,1) bb(1,2) bb(2,3) 1\n\t\tbb(2,1) bb(2,2) bb(1,3) 1\n\t\tbb(2,1) bb(2,2) bb(2,3) 1]';\n\ttc = st.Space\\(st.vols{i}.premul*st.vols{i}.mat)*c;\n\ttc = tc(1:3,:)';\n\tmx = max([tc ; mx]);\n\tmn = min([tc ; mn]);\nend;\nbb = [mn ; mx];\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction space(arg1,M,dim)\nglobal st\nif ~isempty(st.vols{arg1})\n\tnum = arg1;\n if nargin < 2\n\t M = st.vols{num}.mat;\n\t dim = st.vols{num}.dim(1:3);\n\tend;\n\tMat = st.vols{num}.premul(1:3,1:3)*M(1:3,1:3);\n\tvox = sqrt(sum(Mat.^2));\n\tif det(Mat(1:3,1:3))<0, vox(1) = -vox(1); end;\n\tMat = diag([vox 1]);\n\tSpace = (M)/Mat;\n\tbb = [1 1 1; dim];\n\tbb = [bb [1;1]];\n\tbb=bb*Mat';\n\tbb=bb(:,1:3);\n\tbb=sort(bb);\n\tst.Space = Space;\n\tst.bb = bb;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction H = specify_image(arg1)\nglobal st\nH=[];\nok = true;\nif isstruct(arg1),\n\tV = arg1(1);\nelse\n\ttry\n\t\tV = spm_vol(arg1);\n\tcatch\n\t\tfprintf('Can not use image \"%s\"\\n', arg1);\n\t\treturn;\n\tend;\nend;\n\nii = 1;\nwhile ~isempty(st.vols{ii}), ii = ii + 1; end;\n\nDeleteFcn = ['spm_orthviews(''Delete'',' num2str(ii) ');'];\nV.ax = cell(3,1);\nfor i=1:3,\n\tax = axes('Visible','off','DrawMode','fast','Parent',st.fig,'DeleteFcn',DeleteFcn,...\n\t\t'YDir','normal','ButtonDownFcn',...\n\t\t['if strcmp(get(gcf,''SelectionType''),''normal''),spm_orthviews(''Reposition'');',...\n\t\t'elseif strcmp(get(gcf,''SelectionType''),''extend''),spm_orthviews(''Reposition'');',...\n\t\t'spm_orthviews(''context_menu'',''ts'',1);end;']);\n\td = image(0,'Tag','Transverse','Parent',ax,...\n\t\t'DeleteFcn',DeleteFcn);\n\tset(ax,'Ydir','normal','ButtonDownFcn',...\n\t\t['if strcmp(get(gcf,''SelectionType''),''normal''),spm_orthviews(''Reposition'');',...\n\t\t'elseif strcmp(get(gcf,''SelectionType''),''extend''),spm_orthviews(''reposition'');',...\n\t\t'spm_orthviews(''context_menu'',''ts'',1);end;']);\n\n\tlx = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn);\n\tly = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn);\n\tif ~st.xhairs,\n\t\tset(lx,'Visible','off');\n\t\tset(ly,'Visible','off');\n\tend;\n\tV.ax{i} = struct('ax',ax,'d',d,'lx',lx,'ly',ly);\nend;\nV.premul = eye(4);\nV.window = 'auto';\nV.mapping = 'linear';\nst.vols{ii} = V;\n\nH = ii;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction addcontexts(handles)\nglobal st\nfor ii = valid_handles(handles),\n\tcm_handle = addcontext(ii);\nend;\nspm_orthviews('reposition',spm_orthviews('pos'));\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction rmcontexts(handles)\nglobal st\nfor ii = valid_handles(handles),\n\tfor i=1:3,\n\t\tset(st.vols{ii}.ax{i}.ax,'UIcontextmenu',[]);\n\t\tst.vols{ii}.ax{i} = rmfield(st.vols{ii}.ax{i},'cm');\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction bbox\nglobal st\nDims = diff(st.bb)'+1;\n\nTD = Dims([1 2])';\nCD = Dims([1 3])';\nif st.mode == 0, SD = Dims([3 2])'; else SD = Dims([2 3])'; end;\n\nun = get(st.fig,'Units');set(st.fig,'Units','Pixels');\nsz = get(st.fig,'Position');set(st.fig,'Units',un);\nsz = sz(3:4);\nsz(2) = sz(2)-40;\n\nfor i=valid_handles(1:24),\n\tarea = st.vols{i}.area(:);\n\tarea = [area(1)*sz(1) area(2)*sz(2) area(3)*sz(1) area(4)*sz(2)];\n\tif st.mode == 0,\n\t\tsx = area(3)/(Dims(1)+Dims(3))/1.02;\n\telse\n\t\tsx = area(3)/(Dims(1)+Dims(2))/1.02;\n\tend;\n\tsy = area(4)/(Dims(2)+Dims(3))/1.02;\n\ts = min([sx sy]);\n\n\toffy = (area(4)-(Dims(2)+Dims(3))*1.02*s)/2 + area(2);\n\tsky = s*(Dims(2)+Dims(3))*0.02;\n\tif st.mode == 0,\n\t\toffx = (area(3)-(Dims(1)+Dims(3))*1.02*s)/2 + area(1);\n\t\tskx = s*(Dims(1)+Dims(3))*0.02;\n\telse\n\t\toffx = (area(3)-(Dims(1)+Dims(2))*1.02*s)/2 + area(1);\n\t\tskx = s*(Dims(1)+Dims(2))*0.02;\n\tend;\n\n\tDeleteFcn = ['spm_orthviews(''Delete'',' num2str(i) ');'];\n\n\t% Transverse\n\tset(st.vols{i}.ax{1}.ax,'Units','pixels', ...\n\t\t'Position',[offx offy s*Dims(1) s*Dims(2)],...\n\t\t'Units','normalized','Xlim',[0 TD(1)]+0.5,'Ylim',[0 TD(2)]+0.5,...\n\t\t'Visible','on','XTick',[],'YTick',[]);\n\n\t% Coronal\n\tset(st.vols{i}.ax{2}.ax,'Units','Pixels',...\n\t\t'Position',[offx offy+s*Dims(2)+sky s*Dims(1) s*Dims(3)],...\n\t\t'Units','normalized','Xlim',[0 CD(1)]+0.5,'Ylim',[0 CD(2)]+0.5,...\n\t\t'Visible','on','XTick',[],'YTick',[]);\n\n\t% Sagittal\n\tif st.mode == 0,\n\t\tset(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',...\n\t\t\t'Position',[offx+s*Dims(1)+skx offy s*Dims(3) s*Dims(2)],...\n\t\t\t'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,...\n\t\t\t'Visible','on','XTick',[],'YTick',[]);\n\telse\n\t\tset(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',...\n\t\t\t'Position',[offx+s*Dims(1)+skx offy+s*Dims(2)+sky s*Dims(2) s*Dims(3)],...\n\t\t\t'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,...\n\t\t\t'Visible','on','XTick',[],'YTick',[]);\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction redraw_all\nredraw(1:24);\nreturn;\n%_______________________________________________________________________\nfunction mx = maxval(vol)\nif isstruct(vol),\n\tmx = -Inf;\n\tfor i=1:vol.dim(3),\n\t\ttmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0);\n\t\timx = max(tmp(isfinite(tmp)));\n\t\tif ~isempty(imx),mx = max(mx,imx);end\n\tend;\nelse\n\tmx = max(vol(isfinite(vol)));\nend;\n%_______________________________________________________________________\nfunction mn = minval(vol)\nif isstruct(vol),\n mn = Inf;\n for i=1:vol.dim(3),\n tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0);\n\t\timn = min(tmp(isfinite(tmp)));\n\t\tif ~isempty(imn),mn = min(mn,imn);end\n end;\nelse\n mn = min(vol(isfinite(vol)));\nend;\n\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction redraw(arg1)\nglobal st\nbb = st.bb;\nDims = round(diff(bb)'+1);\nis = inv(st.Space);\ncent = is(1:3,1:3)*st.centre(:) + is(1:3,4);\n\nfor i = valid_handles(arg1),\n\tM = st.vols{i}.premul*st.vols{i}.mat;\n\tTM0 = [\t1 0 0 -bb(1,1)+1\n\t\t0 1 0 -bb(1,2)+1\n\t\t0 0 1 -cent(3)\n\t\t0 0 0 1];\n\tTM = inv(TM0*(st.Space\\M));\n\tTD = Dims([1 2]);\n\n\tCM0 = [\t1 0 0 -bb(1,1)+1\n\t\t0 0 1 -bb(1,3)+1\n\t\t0 1 0 -cent(2)\n\t\t0 0 0 1];\n\tCM = inv(CM0*(st.Space\\M));\n\tCD = Dims([1 3]);\n\n\tif st.mode ==0,\n\t\tSM0 = [\t0 0 1 -bb(1,3)+1\n\t\t\t0 1 0 -bb(1,2)+1\n\t\t\t1 0 0 -cent(1)\n\t\t\t0 0 0 1];\n\t\tSM = inv(SM0*(st.Space\\M)); SD = Dims([3 2]);\n\telse\n\t\tSM0 = [\t0 1 0 -bb(1,2)+1\n\t\t\t0 0 1 -bb(1,3)+1\n\t\t\t1 0 0 -cent(1)\n\t\t\t0 0 0 1];\n\t\tSM0 = [\t0 -1 0 +bb(2,2)+1\n\t\t\t0 0 1 -bb(1,3)+1\n\t\t\t1 0 0 -cent(1)\n\t\t\t0 0 0 1];\n\t\tSM = inv(SM0*(st.Space\\M));\n\t\tSD = Dims([2 3]);\n\tend;\n\n\ttry\n\t\timgt = spm_slice_vol(st.vols{i},TM,TD,st.hld)';\n\t\timgc = spm_slice_vol(st.vols{i},CM,CD,st.hld)';\n\t\timgs = spm_slice_vol(st.vols{i},SM,SD,st.hld)';\n\t\tok = true;\n\tcatch\n\t\tfprintf('Image \"%s\" can not be resampled\\n', st.vols{i}.fname);\n\t\tok = false;\n\tend\n\tif ok,\n % get min/max threshold\n if strcmp(st.vols{i}.window,'auto')\n mn = -Inf;\n mx = Inf;\n else\n mn = min(st.vols{i}.window);\n mx = max(st.vols{i}.window);\n end;\n % threshold images\n imgt = max(imgt,mn); imgt = min(imgt,mx);\n imgc = max(imgc,mn); imgc = min(imgc,mx);\n imgs = max(imgs,mn); imgs = min(imgs,mx);\n % compute intensity mapping, if histeq is available\n if license('test','image_toolbox') == 0\n st.vols{i}.mapping = 'linear';\n end;\n switch st.vols{i}.mapping,\n case 'linear',\n case 'histeq',\n % scale images to a range between 0 and 1\n imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps);\n imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps);\n imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps);\n img = histeq([imgt1(:); imgc1(:); imgs1(:)],1024);\n imgt = reshape(img(1:numel(imgt1)),size(imgt1));\n imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1));\n imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1));\n mn = 0;\n mx = 1;\n case 'quadhisteq',\n % scale images to a range between 0 and 1\n imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps);\n imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps);\n imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps);\n img = histeq([imgt1(:).^2; imgc1(:).^2; imgs1(:).^2],1024);\n imgt = reshape(img(1:numel(imgt1)),size(imgt1));\n imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1));\n imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1));\n mn = 0;\n mx = 1;\n case 'loghisteq',\n sw = warning('off','MATLAB:log:logOfZero');\n imgt = log(imgt-min(imgt(:)));\n imgc = log(imgc-min(imgc(:)));\n imgs = log(imgs-min(imgs(:)));\n warning(sw);\n imgt(~isfinite(imgt)) = 0;\n imgc(~isfinite(imgc)) = 0;\n imgs(~isfinite(imgs)) = 0;\n % scale log images to a range between 0 and 1\n imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps);\n imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps);\n imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps);\n img = histeq([imgt1(:); imgc1(:); imgs1(:)],1024);\n imgt = reshape(img(1:numel(imgt1)),size(imgt1));\n imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1));\n imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1));\n mn = 0;\n mx = 1;\n end;\n % recompute min/max for display\n if strcmp(st.vols{i}.window,'auto')\n mx = -inf; mn = inf;\n end;\n if ~isempty(imgt),\n\t\t\ttmp = imgt(isfinite(imgt));\n mx = max([mx max(max(tmp))]);\n mn = min([mn min(min(tmp))]);\n end;\n if ~isempty(imgc),\n\t\t\ttmp = imgc(isfinite(imgc));\n mx = max([mx max(max(tmp))]);\n mn = min([mn min(min(tmp))]);\n end;\n if ~isempty(imgs),\n\t\t\ttmp = imgs(isfinite(imgs));\n mx = max([mx max(max(tmp))]);\n mn = min([mn min(min(tmp))]);\n end;\n if mx==mn, mx=mn+eps; end;\n\n\t\tif isfield(st.vols{i},'blobs'),\n\t\t\tif ~isfield(st.vols{i}.blobs{1},'colour'),\n\t\t\t\t% Add blobs for display using the split colourmap\n\t\t\t\tscal = 64/(mx-mn);\n\t\t\t\tdcoff = -mn*scal;\n\t\t\t\timgt = imgt*scal+dcoff;\n\t\t\t\timgc = imgc*scal+dcoff;\n\t\t\t\timgs = imgs*scal+dcoff;\n\n\t\t\t\tif isfield(st.vols{i}.blobs{1},'max'),\n\t\t\t\t\tmx = st.vols{i}.blobs{1}.max;\n\t\t\t\telse\n\t\t\t\t\tmx = max([eps maxval(st.vols{i}.blobs{1}.vol)]);\n\t\t\t\t\tst.vols{i}.blobs{1}.max = mx;\n\t\t\t\tend;\n\t\t\t\tif isfield(st.vols{i}.blobs{1},'min'),\n\t\t\t\t\tmn = st.vols{i}.blobs{1}.min;\n\t\t\t\telse\n\t\t\t\t\tmn = min([0 minval(st.vols{i}.blobs{1}.vol)]);\n\t\t\t\t\tst.vols{i}.blobs{1}.min = mn;\n\t\t\t\tend;\n\n\t\t\t\tvol = st.vols{i}.blobs{1}.vol;\n\t\t\t\tM = st.vols{i}.premul*st.vols{i}.blobs{1}.mat;\n\t\t\t\ttmpt = spm_slice_vol(vol,inv(TM0*(st.Space\\M)),TD,[0 NaN])';\n\t\t\t\ttmpc = spm_slice_vol(vol,inv(CM0*(st.Space\\M)),CD,[0 NaN])';\n\t\t\t\ttmps = spm_slice_vol(vol,inv(SM0*(st.Space\\M)),SD,[0 NaN])';\n\n\t\t\t\t%tmpt_z = find(tmpt==0);tmpt(tmpt_z) = NaN;\n\t\t\t\t%tmpc_z = find(tmpc==0);tmpc(tmpc_z) = NaN;\n\t\t\t\t%tmps_z = find(tmps==0);tmps(tmps_z) = NaN;\n\n\t\t\t\tsc = 64/(mx-mn);\n\t\t\t\toff = 65.51-mn*sc;\n\t\t\t\tmsk = find(isfinite(tmpt)); imgt(msk) = off+tmpt(msk)*sc;\n\t\t\t\tmsk = find(isfinite(tmpc)); imgc(msk) = off+tmpc(msk)*sc;\n\t\t\t\tmsk = find(isfinite(tmps)); imgs(msk) = off+tmps(msk)*sc;\n\n\t\t\t\tcmap = get(st.fig,'Colormap');\n\t\t\t\tif size(cmap,1)~=128\n\t\t\t\t\tfigure(st.fig)\n\t\t\t\t\tspm_figure('Colormap','gray-hot')\n\t\t\t\tend;\n redraw_colourbar(i,1,[mn mx],(1:64)'+64); \n\t\t\telseif isstruct(st.vols{i}.blobs{1}.colour),\n\t\t\t\t% Add blobs for display using a defined\n % colourmap\n\n\t\t\t\t% colourmaps\n\t\t\t\tgryc = (0:63)'*ones(1,3)/63;\n\t\t\t\tactc = ...\n\t\t\t\t st.vols{1}.blobs{1}.colour.cmap;\n\t\t\t\tactp = ...\n\t\t\t\t st.vols{1}.blobs{1}.colour.prop;\n\t\t\t\t\n\t\t\t\t% scale grayscale image, not isfinite -> black\n\t\t\t\timgt = scaletocmap(imgt,mn,mx,gryc,65);\n\t\t\t\timgc = scaletocmap(imgc,mn,mx,gryc,65);\n\t\t\t\timgs = scaletocmap(imgs,mn,mx,gryc,65);\n\t\t\t\tgryc = [gryc; 0 0 0];\n\t\t\t\t\n\t\t\t\t% get max for blob image\n\t\t\t\tvol = st.vols{i}.blobs{1}.vol;\n\t\t\t\tmat = st.vols{i}.premul*st.vols{i}.blobs{1}.mat;\n\t\t\t\tif isfield(st.vols{i}.blobs{1},'max'),\n\t\t\t\t\tcmx = st.vols{i}.blobs{1}.max;\n\t\t\t\telse\n\t\t\t\t\tcmx = max([eps maxval(st.vols{i}.blobs{1}.vol)]);\n\t\t\t\tend;\n\t\t\t\tif isfield(st.vols{i}.blobs{1},'min'),\n\t\t\t\t\tcmn = st.vols{i}.blobs{1}.min;\n\t\t\t\telse\n\t\t\t\t\tcmn = -cmx;\n\t\t\t\tend;\n\n\t\t\t\t% get blob data\n\t\t\t\tvol = st.vols{i}.blobs{1}.vol;\n\t\t\t\tM = st.vols{i}.premul*st.vols{i}.blobs{1}.mat;\n\t\t\t\ttmpt = spm_slice_vol(vol,inv(TM0*(st.Space\\M)),TD,[0 NaN])';\n\t\t\t\ttmpc = spm_slice_vol(vol,inv(CM0*(st.Space\\M)),CD,[0 NaN])';\n\t\t\t\ttmps = spm_slice_vol(vol,inv(SM0*(st.Space\\M)),SD,[0 NaN])';\n\t\t\t\t\n\t\t\t\t% actimg scaled round 0, black NaNs\n\t\t\t\ttopc = size(actc,1)+1;\n\t\t\t\ttmpt = scaletocmap(tmpt,cmn,cmx,actc,topc);\n\t\t\t\ttmpc = scaletocmap(tmpc,cmn,cmx,actc,topc);\n\t\t\t\ttmps = scaletocmap(tmps,cmn,cmx,actc,topc);\n\t\t\t\tactc = [actc; 0 0 0];\n\t\t\t\t\n\t\t\t\t% combine gray and blob data to\n\t\t\t\t% truecolour\n\t\t\t\timgt = reshape(actc(tmpt(:),:)*actp+ ...\n\t\t\t\t\t gryc(imgt(:),:)*(1-actp), ...\n\t\t\t\t\t [size(imgt) 3]);\n\t\t\t\timgc = reshape(actc(tmpc(:),:)*actp+ ...\n\t\t\t\t\t gryc(imgc(:),:)*(1-actp), ...\n\t\t\t\t\t [size(imgc) 3]);\n\t\t\t\timgs = reshape(actc(tmps(:),:)*actp+ ...\n\t\t\t\t\t gryc(imgs(:),:)*(1-actp), ...\n\t\t\t\t\t [size(imgs) 3]);\n\t\t\t\t\n redraw_colourbar(i,1,[cmn cmx],(1:64)'+64); \n\t\t\t\t\n\t\t\telse\n\t\t\t\t% Add full colour blobs - several sets at once\n\t\t\t\tscal = 1/(mx-mn);\n\t\t\t\tdcoff = -mn*scal;\n\n\t\t\t\twt = zeros(size(imgt));\n\t\t\t\twc = zeros(size(imgc));\n\t\t\t\tws = zeros(size(imgs));\n\n\t\t\t\timgt = repmat(imgt*scal+dcoff,[1,1,3]);\n\t\t\t\timgc = repmat(imgc*scal+dcoff,[1,1,3]);\n\t\t\t\timgs = repmat(imgs*scal+dcoff,[1,1,3]);\n\n\t\t\t\tcimgt = zeros(size(imgt));\n\t\t\t\tcimgc = zeros(size(imgc));\n\t\t\t\tcimgs = zeros(size(imgs));\n\n\t\t\t\tfor j=1:length(st.vols{i}.blobs), % get colours of all images first\n\t\t\t\t\tif isfield(st.vols{i}.blobs{j},'colour'),\n\t\t\t\t\t\tcolour(j,:) = reshape(st.vols{i}.blobs{j}.colour, [1 3]);\n\t\t\t\t\telse\n\t\t\t\t\t\tcolour(j,:) = [1 0 0];\n\t\t\t\t\tend;\n\t\t\t\tend;\n\t\t\t\t%colour = colour/max(sum(colour));\n\n\t\t\t\tfor j=1:length(st.vols{i}.blobs),\n\t\t\t\t\tif isfield(st.vols{i}.blobs{j},'max'),\n\t\t\t\t\t\tmx = st.vols{i}.blobs{j}.max;\n\t\t\t\t\telse\n\t\t\t\t\t\tmx = max([eps max(st.vols{i}.blobs{j}.vol(:))]);\n\t\t\t\t\t\tst.vols{i}.blobs{j}.max = mx;\n\t\t\t\t\tend;\n\t\t\t\t\tif isfield(st.vols{i}.blobs{j},'min'),\n\t\t\t\t\t\tmn = st.vols{i}.blobs{j}.min;\n\t\t\t\t\telse\n\t\t\t\t\t\tmn = min([0 min(st.vols{i}.blobs{j}.vol(:))]);\n\t\t\t\t\t\tst.vols{i}.blobs{j}.min = mn;\n\t\t\t\t\tend;\n\n\t\t\t\t\tvol = st.vols{i}.blobs{j}.vol;\n\t\t\t\t\tM = st.Space\\st.vols{i}.premul*st.vols{i}.blobs{j}.mat;\n tmpt = spm_slice_vol(vol,inv(TM0*M),TD,[0 NaN])';\n tmpc = spm_slice_vol(vol,inv(CM0*M),CD,[0 NaN])';\n tmps = spm_slice_vol(vol,inv(SM0*M),SD,[0 NaN])';\n % check min/max of sampled image\n % against mn/mx as given in st\n tmpt(tmpt(:)mx) = mx;\n tmpc(tmpc(:)>mx) = mx;\n tmps(tmps(:)>mx) = mx;\n tmpt = (tmpt-mn)/(mx-mn);\n\t\t\t\t\ttmpc = (tmpc-mn)/(mx-mn);\n\t\t\t\t\ttmps = (tmps-mn)/(mx-mn);\n\t\t\t\t\ttmpt(~isfinite(tmpt)) = 0;\n\t\t\t\t\ttmpc(~isfinite(tmpc)) = 0;\n\t\t\t\t\ttmps(~isfinite(tmps)) = 0;\n\n\t\t\t\t\tcimgt = cimgt + cat(3,tmpt*colour(j,1),tmpt*colour(j,2),tmpt*colour(j,3));\n\t\t\t\t\tcimgc = cimgc + cat(3,tmpc*colour(j,1),tmpc*colour(j,2),tmpc*colour(j,3));\n\t\t\t\t\tcimgs = cimgs + cat(3,tmps*colour(j,1),tmps*colour(j,2),tmps*colour(j,3));\n\n\t\t\t\t\twt = wt + tmpt;\n\t\t\t\t\twc = wc + tmpc;\n\t\t\t\t\tws = ws + tmps;\n cdata=permute(shiftdim((1/64:1/64:1)'* ...\n colour(j,:),-1),[2 1 3]);\n redraw_colourbar(i,j,[mn mx],cdata);\n\t\t\t\tend;\n\n\t\t\t\timgt = repmat(1-wt,[1 1 3]).*imgt+cimgt;\n\t\t\t\timgc = repmat(1-wc,[1 1 3]).*imgc+cimgc;\n\t\t\t\timgs = repmat(1-ws,[1 1 3]).*imgs+cimgs;\n\n\t\t\t\timgt(imgt<0)=0; imgt(imgt>1)=1;\n\t\t\t\timgc(imgc<0)=0; imgc(imgc>1)=1;\n\t\t\t\timgs(imgs<0)=0; imgs(imgs>1)=1;\n\t\t\tend;\n\t\telse\n\t\t\tscal = 64/(mx-mn);\n\t\t\tdcoff = -mn*scal;\n\t\t\timgt = imgt*scal+dcoff;\n\t\t\timgc = imgc*scal+dcoff;\n\t\t\timgs = imgs*scal+dcoff;\n\t\tend;\n\n\t\tset(st.vols{i}.ax{1}.d,'HitTest','off', 'Cdata',imgt);\n\t\tset(st.vols{i}.ax{1}.lx,'HitTest','off',...\n\t\t\t'Xdata',[0 TD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1));\n\t\tset(st.vols{i}.ax{1}.ly,'HitTest','off',...\n\t\t\t'Ydata',[0 TD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1));\n\n\t\tset(st.vols{i}.ax{2}.d,'HitTest','off', 'Cdata',imgc);\n\t\tset(st.vols{i}.ax{2}.lx,'HitTest','off',...\n\t\t\t'Xdata',[0 CD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1));\n\t\tset(st.vols{i}.ax{2}.ly,'HitTest','off',...\n\t\t\t'Ydata',[0 CD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1));\n\n\t\tset(st.vols{i}.ax{3}.d,'HitTest','off','Cdata',imgs);\n\t\tif st.mode ==0,\n\t\t\tset(st.vols{i}.ax{3}.lx,'HitTest','off',...\n\t\t\t\t'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1));\n\t\t\tset(st.vols{i}.ax{3}.ly,'HitTest','off',...\n\t\t\t\t'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(cent(3)-bb(1,3)+1));\n\t\telse\n\t\t\tset(st.vols{i}.ax{3}.lx,'HitTest','off',...\n\t\t\t\t'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1));\n\t\t\tset(st.vols{i}.ax{3}.ly,'HitTest','off',...\n\t\t\t\t'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(bb(2,2)+1-cent(2)));\n\t\tend;\n\n\t\tif ~isempty(st.plugins) % process any addons\n\t\t\tfor k = 1:numel(st.plugins),\n\t\t\t\tif isfield(st.vols{i},st.plugins{k}),\n\t\t\t\t\tfeval(['spm_ov_', st.plugins{k}], ...\n\t\t\t\t\t\t'redraw', i, TM0, TD, CM0, CD, SM0, SD);\n\t\t\t\tend;\n\t\t\tend;\n\t\tend;\n\tend;\nend;\ndrawnow;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction redraw_colourbar(vh,bh,interval,cdata)\nglobal st\nif isfield(st.vols{vh}.blobs{bh},'cbar')\n if st.mode == 0,\n axpos = get(st.vols{vh}.ax{2}.ax,'Position');\n else\n axpos = get(st.vols{vh}.ax{1}.ax,'Position');\n end;\n % only scale cdata if we have out-of-range truecolour values\n if ndims(cdata)==3 && max(cdata(:))>1\n cdata=cdata./max(cdata(:));\n end;\n image([0 1],interval,cdata,'Parent',st.vols{vh}.blobs{bh}.cbar);\n set(st.vols{vh}.blobs{bh}.cbar, ...\n 'Position',[(axpos(1)+axpos(3)+0.05+(bh-1)*.1)...\n (axpos(2)+0.005) 0.05 (axpos(4)-0.01)],...\n 'YDir','normal','XTickLabel',[],'XTick',[]);\n if isfield(st.vols{vh}.blobs{bh},'name')\n ylabel(st.vols{vh}.blobs{bh}.name,'parent',st.vols{vh}.blobs{bh}.cbar);\n end;\nend;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction centre = findcent\nglobal st\nobj = get(st.fig,'CurrentObject');\ncentre = [];\ncent = [];\ncp = [];\nfor i=valid_handles(1:24),\n\tfor j=1:3,\n\t\tif ~isempty(obj),\n\t\t\tif (st.vols{i}.ax{j}.ax == obj),\n\t\t\t\tcp = get(obj,'CurrentPoint');\n\t\t\tend;\n\t\tend;\n\t\tif ~isempty(cp),\n\t\t\tcp = cp(1,1:2);\n\t\t\tis = inv(st.Space);\n\t\t\tcent = is(1:3,1:3)*st.centre(:) + is(1:3,4);\n\t\t\tswitch j,\n\t\t\t\tcase 1,\n\t\t\t\tcent([1 2])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,2)-1];\n\t\t\t\tcase 2,\n\t\t\t\tcent([1 3])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,3)-1];\n\t\t\t\tcase 3,\n\t\t\t\tif st.mode ==0,\n\t\t\t\t\tcent([3 2])=[cp(1)+st.bb(1,3)-1 cp(2)+st.bb(1,2)-1];\n\t\t\t\telse\n\t\t\t\t\tcent([2 3])=[st.bb(2,2)+1-cp(1) cp(2)+st.bb(1,3)-1];\n\t\t\t\tend;\n\t\t\tend;\n\t\t\tbreak;\n\t\tend;\n\tend;\n\tif ~isempty(cent), break; end;\nend;\nif ~isempty(cent), centre = st.Space(1:3,1:3)*cent(:) + st.Space(1:3,4); end;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction handles = valid_handles(handles)\nglobal st;\nhandles = handles(:)';\nhandles = handles(handles<=24 & handles>=1 & ~rem(handles,1));\nfor h=handles,\n\tif isempty(st.vols{h}), handles(handles==h)=[]; end;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction reset_st\nglobal st\nfig = spm_figure('FindWin','Graphics');\nbb = []; %[ [-78 78]' [-112 76]' [-50 85]' ];\nst = struct('n', 0, 'vols',[], 'bb',bb,'Space',eye(4),'centre',[0 0 0],'callback',';','xhairs',1,'hld',1,'fig',fig,'mode',1,'plugins',[],'snap',[]);\nst.vols = cell(24,1);\n\npluginpath = fullfile(spm('Dir'),'spm_orthviews');\nif isdir(pluginpath)\n\tpluginfiles = dir(fullfile(pluginpath,'spm_ov_*.m'));\n\tif ~isempty(pluginfiles)\n\t\taddpath(pluginpath);\n\t\t% fprintf('spm_orthviews: Using Plugins in %s\\n', pluginpath);\n\t\tfor k = 1:length(pluginfiles)\n\t\t\t[p, pluginname, e, v] = spm_fileparts(pluginfiles(k).name);\n\t\t\tst.plugins{k} = strrep(pluginname, 'spm_ov_','');\n\t\t\t% fprintf('%s\\n',st.plugins{k});\n\t\tend;\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction img = scaletocmap(inpimg,mn,mx,cmap,miscol)\nif nargin < 5, miscol=1;end\ncml = size(cmap,1);\nscf = (cml-1)/(mx-mn);\nimg = round((inpimg-mn)*scf)+1;\nimg(img<1) = 1; \nimg(img>cml) = cml;\nimg(~isfinite(img)) = miscol;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction cmap = getcmap(acmapname)\n% get colormap of name acmapname\nif ~isempty(acmapname),\n\tcmap = evalin('base',acmapname,'[]');\n\tif isempty(cmap), % not a matrix, is .mat file?\n\t\t[p, f, e] = fileparts(acmapname);\n\t\tacmat = fullfile(p, [f '.mat']);\n\t\tif exist(acmat, 'file'),\n\t\t\ts = struct2cell(load(acmat));\n\t\t\tcmap = s{1};\n\t\tend;\n\tend;\nend;\nif size(cmap, 2)~=3,\n\twarning('Colormap was not an N by 3 matrix')\n\tcmap = [];\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction item_parent = addcontext(volhandle)\nglobal st;\n%create context menu\nfg = spm_figure('Findwin','Graphics');set(0,'CurrentFigure',fg);\n%contextmenu\nitem_parent = uicontextmenu;\n\n%contextsubmenu 0\nitem00 = uimenu(item_parent, 'Label','unknown image', 'Separator','on');\nspm_orthviews('context_menu','image_info',item00,volhandle);\nitem0a = uimenu(item_parent, 'UserData','pos_mm', 'Callback','spm_orthviews(''context_menu'',''repos_mm'');','Separator','on');\nitem0b = uimenu(item_parent, 'UserData','pos_vx', 'Callback','spm_orthviews(''context_menu'',''repos_vx'');');\nitem0c = uimenu(item_parent, 'UserData','v_value');\n\n%contextsubmenu 1\nitem1 = uimenu(item_parent,'Label','Zoom');\nitem1_1 = uimenu(item1, 'Label','Full Volume', 'Callback','spm_orthviews(''context_menu'',''zoom'',6);', 'Checked','on');\nitem1_2 = uimenu(item1, 'Label','160x160x160mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',5);');\nitem1_3 = uimenu(item1, 'Label','80x80x80mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',4);');\nitem1_4 = uimenu(item1, 'Label','40x40x40mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',3);');\nitem1_5 = uimenu(item1, 'Label','20x20x20mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',2);');\nitem1_6 = uimenu(item1, 'Label','10x10x10mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',1);');\n\n%contextsubmenu 2\nchecked={'off','off'};\nchecked{st.xhairs+1} = 'on';\nitem2 = uimenu(item_parent,'Label','Crosshairs');\nitem2_1 = uimenu(item2, 'Label','on', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''on'');','Checked',checked{2});\nitem2_2 = uimenu(item2, 'Label','off', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''off'');','Checked',checked{1});\n\n%contextsubmenu 3\nif st.Space == eye(4)\n\tchecked = {'off', 'on'};\nelse\n\tchecked = {'on', 'off'};\nend;\nitem3 = uimenu(item_parent,'Label','Orientation');\nitem3_1 = uimenu(item3, 'Label','World space', 'Callback','spm_orthviews(''context_menu'',''orientation'',3);','Checked',checked{2});\nitem3_2 = uimenu(item3, 'Label','Voxel space (1st image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',2);','Checked',checked{1});\nitem3_3 = uimenu(item3, 'Label','Voxel space (this image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',1);','Checked','off');\n\n%contextsubmenu 3\nif isempty(st.snap)\n\tchecked = {'off', 'on'};\nelse\n\tchecked = {'on', 'off'};\nend;\nitem3 = uimenu(item_parent,'Label','Snap to Grid');\nitem3_1 = uimenu(item3, 'Label','Don''t snap', 'Callback','spm_orthviews(''context_menu'',''snap'',3);','Checked',checked{2});\nitem3_2 = uimenu(item3, 'Label','Snap to 1st image', 'Callback','spm_orthviews(''context_menu'',''snap'',2);','Checked',checked{1});\nitem3_3 = uimenu(item3, 'Label','Snap to this image', 'Callback','spm_orthviews(''context_menu'',''snap'',1);','Checked','off');\n\n%contextsubmenu 4\nif st.hld == 0,\n\tchecked = {'off', 'off', 'on'};\nelseif st.hld > 0,\n\tchecked = {'off', 'on', 'off'};\nelse\n\tchecked = {'on', 'off', 'off'};\nend;\nitem4 = uimenu(item_parent,'Label','Interpolation');\nitem4_1 = uimenu(item4, 'Label','NN', 'Callback','spm_orthviews(''context_menu'',''interpolation'',3);', 'Checked',checked{3});\nitem4_2 = uimenu(item4, 'Label','Bilin', 'Callback','spm_orthviews(''context_menu'',''interpolation'',2);','Checked',checked{2});\nitem4_3 = uimenu(item4, 'Label','Sinc', 'Callback','spm_orthviews(''context_menu'',''interpolation'',1);','Checked',checked{1});\n\n%contextsubmenu 5\n% item5 = uimenu(item_parent,'Label','Position', 'Callback','spm_orthviews(''context_menu'',''position'');');\n\n%contextsubmenu 6\nitem6 = uimenu(item_parent,'Label','Image','Separator','on');\nitem6_1 = uimenu(item6, 'Label','Window');\nitem6_1_1 = uimenu(item6_1, 'Label','local');\nitem6_1_1_1 = uimenu(item6_1_1, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window'',2);');\nitem6_1_1_2 = uimenu(item6_1_1, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window'',1);');\nitem6_1_2 = uimenu(item6_1, 'Label','global');\nitem6_1_2_1 = uimenu(item6_1_2, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window_gl'',2);');\nitem6_1_2_2 = uimenu(item6_1_2, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window_gl'',1);');\nif license('test','image_toolbox') == 1\n offon = {'off', 'on'};\n checked = offon(strcmp(st.vols{volhandle}.mapping, ...\n {'linear', 'histeq', 'loghisteq', 'quadhisteq'})+1);\n item6_2 = uimenu(item6, 'Label','Intensity mapping');\n item6_2_1 = uimenu(item6_2, 'Label','local');\n item6_2_1_1 = uimenu(item6_2_1, 'Label','Linear', 'Checked',checked{1}, ...\n 'Callback','spm_orthviews(''context_menu'',''mapping'',''linear'');');\n item6_2_1_2 = uimenu(item6_2_1, 'Label','Equalised histogram', 'Checked',checked{2}, ...\n 'Callback','spm_orthviews(''context_menu'',''mapping'',''histeq'');');\n item6_2_1_3 = uimenu(item6_2_1, 'Label','Equalised log-histogram', 'Checked',checked{3}, ...\n 'Callback','spm_orthviews(''context_menu'',''mapping'',''loghisteq'');');\n item6_2_1_4 = uimenu(item6_2_1, 'Label','Equalised squared-histogram', 'Checked',checked{4}, ...\n 'Callback','spm_orthviews(''context_menu'',''mapping'',''quadhisteq'');');\n item6_2_2 = uimenu(item6_2, 'Label','global');\n item6_2_2_1 = uimenu(item6_2_2, 'Label','Linear', 'Checked',checked{1}, ...\n 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''linear'');');\n item6_2_2_2 = uimenu(item6_2_2, 'Label','Equalised histogram', 'Checked',checked{2}, ...\n 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''histeq'');');\n item6_2_2_3 = uimenu(item6_2_2, 'Label','Equalised log-histogram', 'Checked',checked{3}, ...\n 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''loghisteq'');');\n item6_2_2_4 = uimenu(item6_2_2, 'Label','Equalised squared-histogram', 'Checked',checked{4}, ...\n 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''quadhisteq'');');\nend;\n%contextsubmenu 7\nitem7 = uimenu(item_parent,'Label','Blobs');\nitem7_1 = uimenu(item7, 'Label','Add blobs');\nitem7_1_1 = uimenu(item7_1, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',2);');\nitem7_1_2 = uimenu(item7_1, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',1);');\nitem7_2 = uimenu(item7, 'Label','Add image');\nitem7_2_1 = uimenu(item7_2, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_image'',2);');\nitem7_2_2 = uimenu(item7_2, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_image'',1);');\nitem7_3 = uimenu(item7, 'Label','Add colored blobs','Separator','on');\nitem7_3_1 = uimenu(item7_3, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',2);');\nitem7_3_2 = uimenu(item7_3, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',1);');\nitem7_4 = uimenu(item7, 'Label','Add colored image');\nitem7_4_1 = uimenu(item7_4, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',2);');\nitem7_4_2 = uimenu(item7_4, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',1);');\nitem7_5 = uimenu(item7, 'Label','Remove blobs', 'Visible','off','Separator','on');\nitem7_6 = uimenu(item7, 'Label','Remove colored blobs','Visible','off');\nitem7_6_1 = uimenu(item7_6, 'Label','local', 'Visible','on');\nitem7_6_2 = uimenu(item7_6, 'Label','global','Visible','on');\n\nfor i=1:3,\n set(st.vols{volhandle}.ax{i}.ax,'UIcontextmenu',item_parent);\n st.vols{volhandle}.ax{i}.cm = item_parent;\nend;\n\nif ~isempty(st.plugins) % process any plugins\n\tfor k = 1:numel(st.plugins),\n\t\tfeval(['spm_ov_', st.plugins{k}], ...\n\t\t\t'context_menu', volhandle, item_parent);\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction c_menu(varargin)\nglobal st\n\nswitch lower(varargin{1}),\ncase 'image_info',\n\tif nargin <3,\n\t\tcurrent_handle = get_current_handle;\n\telse\n\t\tcurrent_handle = varargin{3};\n\tend;\n\tif isfield(st.vols{current_handle},'fname'),\n\t\t[p,n,e,v] = spm_fileparts(st.vols{current_handle}.fname);\n if isfield(st.vols{current_handle},'n')\n v = sprintf(',%d',st.vols{current_handle}.n);\n end;\n\t\tset(varargin{2}, 'Label',[n e v]);\n\tend;\n\tdelete(get(varargin{2},'children'));\n\tif exist('p','var')\n\t\titem1 = uimenu(varargin{2}, 'Label', p);\n\tend;\n\tif isfield(st.vols{current_handle},'descrip'),\n\t\titem2 = uimenu(varargin{2}, 'Label',...\n\t\tst.vols{current_handle}.descrip);\n\tend;\n\tdt = st.vols{current_handle}.dt(1);\n\titem3 = uimenu(varargin{2}, 'Label', sprintf('Data type: %s', spm_type(dt)));\n\tstr = 'Intensity: varied';\n\tif size(st.vols{current_handle}.pinfo,2) == 1,\n\t\tif st.vols{current_handle}.pinfo(2),\n\t\t\tstr = sprintf('Intensity: Y = %g X + %g',...\n\t\t\t\tst.vols{current_handle}.pinfo(1:2)');\n\t\telse\n\t\t\tstr = sprintf('Intensity: Y = %g X', st.vols{current_handle}.pinfo(1)');\n\t\tend;\n\tend;\n\titem4 = uimenu(varargin{2}, 'Label',str);\n\titem5 = uimenu(varargin{2}, 'Label', 'Image dims', 'Separator','on');\n\titem51 = uimenu(varargin{2}, 'Label',...\n\t\tsprintf('%dx%dx%d', st.vols{current_handle}.dim(1:3)));\n\tprms = spm_imatrix(st.vols{current_handle}.mat);\n\titem6 = uimenu(varargin{2}, 'Label','Voxel size', 'Separator','on');\n\titem61 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', prms(7:9)));\n\titem7 = uimenu(varargin{2}, 'Label','Origin', 'Separator','on');\n\titem71 = uimenu(varargin{2}, 'Label',...\n\t\tsprintf('%.2f %.2f %.2f', prms(1:3)));\n\tR = spm_matrix([0 0 0 prms(4:6)]);\n\titem8 = uimenu(varargin{2}, 'Label','Rotations', 'Separator','on');\n\titem81 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(1,1:3)));\n\titem82 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(2,1:3)));\n\titem83 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(3,1:3)));\n\titem9 = uimenu(varargin{2},...\n\t\t'Label','Specify other image...',...\n\t\t'Callback','spm_orthviews(''context_menu'',''swap_img'');',...\n\t\t'Separator','on');\n\ncase 'repos_mm',\n\toldpos_mm = spm_orthviews('pos');\n\tnewpos_mm = spm_input('New Position (mm)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_mm),3);\n\tspm_orthviews('reposition',newpos_mm);\n\ncase 'repos_vx'\n\tcurrent_handle = get_current_handle;\n\toldpos_vx = spm_orthviews('pos', current_handle);\n\tnewpos_vx = spm_input('New Position (voxels)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_vx),3);\n\tnewpos_mm = st.vols{current_handle}.mat*[newpos_vx;1];\n\tspm_orthviews('reposition',newpos_mm(1:3));\n\ncase 'zoom'\n\tzoom_all(varargin{2});\n\tbbox;\n\tredraw_all;\n\ncase 'xhair',\n\tspm_orthviews('Xhairs',varargin{2});\n\tcm_handles = get_cm_handles;\n\tfor i = 1:length(cm_handles),\n\t\tz_handle = get(findobj(cm_handles(i),'label','Crosshairs'),'Children');\n\t\tset(z_handle,'Checked','off'); %reset check\n\t\tif strcmp(varargin{2},'off'), op = 1; else op = 2; end\n\t\tset(z_handle(op),'Checked','on');\n\tend;\n\ncase 'orientation',\n\tcm_handles = get_cm_handles;\n\tfor i = 1:length(cm_handles),\n\t\tz_handle = get(findobj(cm_handles(i),'label','Orientation'),'Children');\n\t\tset(z_handle,'Checked','off');\n\tend;\n\tif varargin{2} == 3,\n\t\tspm_orthviews('Space');\n\t\tfor i = 1:length(cm_handles),\n\t\t z_handle = findobj(cm_handles(i),'label','World space');\n\t\t set(z_handle,'Checked','on');\n\t\tend;\n\telseif varargin{2} == 2,\n\t\tspm_orthviews('Space',1);\n\t\tfor i = 1:length(cm_handles),\n\t\t z_handle = findobj(cm_handles(i),'label',...\n\t\t\t\t 'Voxel space (1st image)');\n\t\t set(z_handle,'Checked','on');\n\t\tend;\n\telse\n\t\tspm_orthviews('Space',get_current_handle);\n\t\tz_handle = findobj(st.vols{get_current_handle}.ax{1}.cm, ...\n\t\t\t\t 'label','Voxel space (this image)');\n\t\tset(z_handle,'Checked','on');\n\t\treturn;\n\tend;\n\ncase 'snap',\n\tcm_handles = get_cm_handles;\n\tfor i = 1:length(cm_handles),\n\t\tz_handle = get(findobj(cm_handles(i),'label','Snap to Grid'),'Children');\n\t\tset(z_handle,'Checked','off');\n\tend;\n\tif varargin{2} == 3,\n\t\tst.snap = [];\n\telseif varargin{2} == 2,\n\t\tst.snap = 1;\n\telse\n\t\tst.snap = get_current_handle;\n\t\tz_handle = get(findobj(st.vols{get_current_handle}.ax{1}.cm,'label','Snap to Grid'),'Children');\n\t\tset(z_handle(1),'Checked','on');\n\t\treturn;\n\tend;\n\tfor i = 1:length(cm_handles),\n\t\tz_handle = get(findobj(cm_handles(i),'label','Snap to Grid'),'Children');\n\t\tset(z_handle(varargin{2}),'Checked','on');\n\tend;\n\ncase 'interpolation',\n\ttmp = [-4 1 0];\n\tst.hld = tmp(varargin{2});\n\tcm_handles = get_cm_handles;\n\tfor i = 1:length(cm_handles),\n\t\tz_handle = get(findobj(cm_handles(i),'label','Interpolation'),'Children');\n\t\tset(z_handle,'Checked','off');\n\t\tset(z_handle(varargin{2}),'Checked','on');\n\tend;\n\tredraw_all;\n\ncase 'window',\n\tcurrent_handle = get_current_handle;\n\tif varargin{2} == 2,\n\t\tspm_orthviews('window',current_handle);\n\telse\n\t\tif isnumeric(st.vols{current_handle}.window)\n\t\t\tdefstr = sprintf('%.2f %.2f', st.vols{current_handle}.window);\n\t\telse\n\t\t\tdefstr = '';\n\t\tend;\n\t\tspm_orthviews('window',current_handle,spm_input('Range','+1','e',defstr,2));\n\tend;\n\ncase 'window_gl',\n\tif varargin{2} == 2,\n\t\tfor i = 1:length(get_cm_handles),\n\t\t\tst.vols{i}.window = 'auto';\n\t\tend;\n\telse\n\t\tcurrent_handle = get_current_handle;\n\t\tif isnumeric(st.vols{current_handle}.window)\n\t\t\tdefstr = sprintf('%d %d', st.vols{current_handle}.window);\n\t\telse\n\t\t\tdefstr = '';\n\t\tend;\n\t\tdata = spm_input('Range','+1','e',defstr,2);\n\n\t\tfor i = 1:length(get_cm_handles),\n\t\t\tst.vols{i}.window = data;\n\t\tend;\n\tend;\n\tredraw_all;\n \ncase 'mapping',\n checked = strcmp(varargin{2}, ...\n {'linear', 'histeq', 'loghisteq', ...\n 'quadhisteq'});\n checked = checked(end:-1:1); % Handles are stored in inverse order\n\tcurrent_handle = get_current_handle; \n cm_handles = get_cm_handles;\n st.vols{current_handle}.mapping = varargin{2};\n z_handle = get(findobj(cm_handles(current_handle), ...\n 'label','Intensity mapping'),'Children');\n for k = 1:numel(z_handle)\n c_handle = get(z_handle(k), 'Children');\n set(c_handle, 'checked', 'off');\n set(c_handle(checked), 'checked', 'on');\n end;\n redraw_all;\n \ncase 'mapping_gl',\n checked = strcmp(varargin{2}, ...\n {'linear', 'histeq', 'loghisteq', 'quadhisteq'});\n checked = checked(end:-1:1); % Handles are stored in inverse order\n cm_handles = get_cm_handles;\n for k = valid_handles(1:24),\n st.vols{k}.mapping = varargin{2};\n z_handle = get(findobj(cm_handles(k), ...\n 'label','Intensity mapping'),'Children');\n for l = 1:numel(z_handle)\n c_handle = get(z_handle(l), 'Children');\n set(c_handle, 'checked', 'off');\n set(c_handle(checked), 'checked', 'on');\n end;\n end;\n redraw_all;\n \ncase 'swap_img',\n current_handle = get_current_handle;\n newimg = spm_select(1,'image','select new image');\n if ~isempty(newimg)\n\tnew_info = spm_vol(newimg);\n fn = fieldnames(new_info);\n for k=1:numel(fn)\n st.vols{current_handle}.(fn{k}) = new_info.(fn{k});\n end;\n\tspm_orthviews('context_menu','image_info',get(gcbo, 'parent'));\n\tredraw_all;\n end\n\ncase 'add_blobs',\n\t% Add blobs to the image - in split colortable\n\tcm_handles = valid_handles(1:24);\n\tif varargin{2} == 2, cm_handles = get_current_handle; end;\n\tspm_figure('Clear','Interactive');\n\t[SPM,VOL] = spm_getSPM;\n\tfor i = 1:length(cm_handles),\n\t\taddblobs(cm_handles(i),VOL.XYZ,VOL.Z,VOL.M);\n\t\tc_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');\n\t\tset(c_handle,'Visible','on');\n\t\tdelete(get(c_handle,'Children'));\n\t\titem7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);');\n\t\tif varargin{2} == 1,\n\t\t\titem7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);');\n\t\tend;\n\tend;\n\tredraw_all;\n\ncase 'remove_blobs',\n\tcm_handles = valid_handles(1:24);\n\tif varargin{2} == 2, cm_handles = get_current_handle; end;\n\tfor i = 1:length(cm_handles),\n\t\trmblobs(cm_handles(i));\n\t\tc_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');\n\t\tdelete(get(c_handle,'Children'));\n\t\tset(c_handle,'Visible','off');\n\tend;\n\tredraw_all;\n\ncase 'add_image',\n\t% Add blobs to the image - in split colortable\n\tcm_handles = valid_handles(1:24);\n\tif varargin{2} == 2, cm_handles = get_current_handle; end;\n\tspm_figure('Clear','Interactive');\n\tfname = spm_select(1,'image','select image');\n\tfor i = 1:length(cm_handles),\n\t\taddimage(cm_handles(i),fname);\n\t\tc_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');\n\t\tset(c_handle,'Visible','on');\n\t\tdelete(get(c_handle,'Children'));\n\t\titem7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);');\n\t\tif varargin{2} == 1,\n\t\t\titem7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);');\n\t\tend;\n\tend;\n\tredraw_all;\n\ncase 'add_c_blobs',\n\t% Add blobs to the image - in full colour\n\tcm_handles = valid_handles(1:24);\n\tif varargin{2} == 2, cm_handles = get_current_handle; end;\n\tspm_figure('Clear','Interactive');\n\t[SPM,VOL] = spm_getSPM;\n\tc = spm_input('Colour','+1','m',...\n\t\t'Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);\n\tcolours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];\n\tc_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};\n hlabel = sprintf('%s (%s)',VOL.title,c_names{c});\n\tfor i = 1:length(cm_handles),\n\t\taddcolouredblobs(cm_handles(i),VOL.XYZ,VOL.Z,VOL.M,colours(c,:),VOL.title);\n addcolourbar(cm_handles(i),numel(st.vols{cm_handles(i)}.blobs));\n\t\tc_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs');\n\t\tch_c_handle = get(c_handle,'Children');\n\t\tset(c_handle,'Visible','on');\n\t\t%set(ch_c_handle,'Visible',on');\n\t\titem7_4_1 = uimenu(ch_c_handle(2),'Label',hlabel,'ForegroundColor',colours(c,:),...\n\t\t\t'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);',...\n\t\t\t'UserData',c);\n\t\tif varargin{2} == 1,\n\t\t\titem7_4_2 = uimenu(ch_c_handle(1),'Label',hlabel,'ForegroundColor',colours(c,:),...\n\t\t\t\t'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',...\n\t\t\t\t'UserData',c);\n\t\tend;\n\tend;\n\tredraw_all;\n\ncase 'remove_c_blobs',\n cm_handles = valid_handles(1:24);\n if varargin{2} == 2, cm_handles = get_current_handle; end;\n colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];\n c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};\n for i = 1:length(cm_handles),\n if isfield(st.vols{cm_handles(i)},'blobs'),\n for j = 1:length(st.vols{cm_handles(i)}.blobs),\n if all(st.vols{cm_handles(i)}.blobs{j}.colour == colours(varargin{3},:));\n if isfield(st.vols{cm_handles(i)}.blobs{j},'cbar')\n delete(st.vols{cm_handles(i)}.blobs{j}.cbar);\n end\n st.vols{cm_handles(i)}.blobs(j) = [];\n break;\n end;\n end;\n rm_c_menu = findobj(st.vols{cm_handles(i)}.ax{1}.cm,'Label','Remove colored blobs');\n delete(gcbo);\n if isempty(st.vols{cm_handles(i)}.blobs),\n st.vols{cm_handles(i)} = rmfield(st.vols{cm_handles(i)},'blobs');\n set(rm_c_menu, 'Visible', 'off');\n end;\n end;\n end;\n redraw_all;\n\ncase 'add_c_image',\n\t% Add truecolored image\n\tcm_handles = valid_handles(1:24);\n\tif varargin{2} == 2, cm_handles = get_current_handle;end;\n\tspm_figure('Clear','Interactive');\n\tfname = spm_select(1,'image','select image');\n\tc = spm_input('Colour','+1','m','Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);\n\tcolours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];\n\tc_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};\n hlabel = sprintf('%s (%s)',fname,c_names{c});\n\tfor i = 1:length(cm_handles),\n\t\taddcolouredimage(cm_handles(i),fname,colours(c,:));\n addcolourbar(cm_handles(i),numel(st.vols{cm_handles(i)}.blobs));\n\t\tc_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs');\n\t\tch_c_handle = get(c_handle,'Children');\n\t\tset(c_handle,'Visible','on');\n\t\t%set(ch_c_handle,'Visible',on');\n\t\titem7_4_1 = uimenu(ch_c_handle(2),'Label',hlabel,'ForegroundColor',colours(c,:),...\n\t\t\t'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);','UserData',c);\n\t\tif varargin{2} == 1\n\t\t\titem7_4_2 = uimenu(ch_c_handle(1),'Label',hlabel,'ForegroundColor',colours(c,:),...\n\t\t\t\t'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',...\n\t\t\t\t'UserData',c);\n\t\tend\n\tend\n\tredraw_all;\nend;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction current_handle = get_current_handle\ncm_handle = get(gca,'UIContextMenu');\ncm_handles = get_cm_handles;\ncurrent_handle = find(cm_handles==cm_handle);\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction cm_pos\nglobal st\nfor i = 1:length(valid_handles(1:24)),\n\tif isfield(st.vols{i}.ax{1},'cm')\n\t\tset(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_mm'),...\n\t\t\t'Label',sprintf('mm: %.1f %.1f %.1f',spm_orthviews('pos')));\n\t\tpos = spm_orthviews('pos',i);\n\t\tset(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_vx'),...\n\t\t\t'Label',sprintf('vx: %.1f %.1f %.1f',pos));\n\t\tset(findobj(st.vols{i}.ax{1}.cm,'UserData','v_value'),...\n\t\t\t'Label',sprintf('Y = %g',spm_sample_vol(st.vols{i},pos(1),pos(2),pos(3),st.hld)));\n\tend\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction cm_handles = get_cm_handles\nglobal st\ncm_handles = [];\nfor i=valid_handles(1:24),\n\tcm_handles = [cm_handles st.vols{i}.ax{1}.cm];\nend\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction zoom_all(op)\nglobal st\ncm_handles = get_cm_handles;\nres = [.125 .125 .25 .5 1 1];\nif op==6,\n\tst.bb = maxbb;\nelse\n\tvx = sqrt(sum(st.Space(1:3,1:3).^2));\n\tvx = vx.^(-1);\n\tpos = spm_orthviews('pos');\n\tpos = st.Space\\[pos ; 1];\n\tpos = pos(1:3)';\n\tif op == 5, st.bb = [pos-80*vx ; pos+80*vx] ;\n\telseif op == 4, st.bb = [pos-40*vx ; pos+40*vx] ;\n\telseif op == 3, st.bb = [pos-20*vx ; pos+20*vx] ;\n\telseif op == 2, st.bb = [pos-10*vx ; pos+10*vx] ;\n\telseif op == 1; st.bb = [pos- 5*vx ; pos+ 5*vx] ;\n\telse disp('no Zoom possible');\n\tend;\nend\nresolution(res(op));\nredraw_all;\nfor i = 1:length(cm_handles)\n\tz_handle = get(findobj(cm_handles(i),'label','Zoom'),'Children');\n\tset(z_handle,'Checked','off');\n\tset(z_handle(op),'Checked','on');\nend\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_FcUtil.m", "ext": ".m", "path": "spm5-master/spm_FcUtil.m", "size": 30335, "source_encoding": "utf_8", "md5": "e21305cc85524f7992a76dc648ebb11f", "text": "function varargout = spm_FcUtil(varargin)\n% Contrast utilities\n% FORMAT varargout = spm_FcUtil(action,varargin)\n%_______________________________________________________________________\n%\n% spm_FcUtil is a multi-function function containing various utilities\n% for contrast construction and manipulation. In general, it accepts\n% design matrices as plain matrices or as space structures setup by\n% spm_sp (that is preferable in general).\n% \n% The use of spm_FcUtil should help with robustness issues and\n% maintainability of SPM. % Note that when space structures are passed\n% as arguments is is assummed that their basic fields are filled in.\n% See spm_sp for details of (design) space structures and their\n% manipulation.\n%\n%\n% ======================================================================\n% case 'fconfields'\t\t\t\t%- fields of F contrast\n% Fc = spm_FcUtil('FconFields')\n%\n%- simply returns the fields of a contrast structure.\n%\n%=======================================================================\n% case 'set'\t\t\t\t\t%- Create an F contrast\n% Fc = spm_FcUtil('Set',name, STAT, set_action, value, sX)\n%\n%- Set will fill in the contrast structure, in particular \n%- c (in the contrast space), X1o (the space actually tested) and\n%- X0 (the space left untested), such that space([X1o X0]) == sX.\n%- STAT is either 'F' or 'T';\n%- name is a string descibing the contrast.\n%\n%- There are three ways to set a contrast :\n%- set_action is 'c','c+'\t: value can then be zeros.\n%-\t\t\t\t dimensions are in X', \n%- \t\t\t\t f c+ is used, value is projected onto sX';\n%- iX0 is set to 'c' or 'c+';\n%- set_action is 'iX0'\t\t: defines the indices of the columns \n%- \t\t\t\t that will not be tested. Can be empty.\n%- set_action is 'X0'\t\t: defines the space that will remain \n%-\t\t\t\t unchanged. The orthogonal complement is\n%- \t\t\t\t tested; iX0 is set to 'X0';\n%- \t\t\t\t\t\t\t\t\t\n%=======================================================================\n% case 'isfcon'\t\t\t\t\t%- Is it an F contrast ?\n% b = spm_FcUtil('IsFcon',Fc)\n%\n%=======================================================================\n% case 'fconedf'\t\t\t\t\t%- F contrast edf\n% [edf_tsp edf_Xsp] = spm_FcUtil('FconEdf', Fc, sX [, V])\n%\n%- compute the effective degrees of freedom of the numerator edf_tsp\n%- and (optionally) the denominator edf_Xsp of the contrast.\n%\n%=======================================================================\n% case 'hsqr' %-Extra sum of squares sqr matrix for beta's from contrast\n% hsqr = spm_FcUtil('Hsqr',Fc, sX)\n%\n%- This computes the matrix hsqr such that a the numerator of an F test\n%- will be beta'*hsqr'*hsqr*beta\n%\n%=======================================================================\n% case 'h' %-Extra sum of squares matrix for beta's from contrast\n% H = spm_FcUtil('H',Fc, sX)\n%\n%- This computes the matrix H such that a the numerator of an F test\n%- will be beta'*H*beta\n%- \t\t\t\t\t\t\t\t\t\n%=======================================================================\n% case 'yc'\t%- Fitted data corrected for confounds defined by Fc \n% Yc = spm_FcUtil('Yc',Fc, sX, b)\n%\n%- Input : b : the betas \t\t\t\t\t \t\n%- Returns the corrected data Yc for given contrast. Y = Yc + Y0 + error\n%\n%=======================================================================\n% case 'y0'\t%- Confounds data defined by Fc \n% Y0 = spm_FcUtil('Y0',Fc, sX, b)\n%\n%- Input : b : the betas \t\t\t\t \t\t\n%- Returns the confound data Y0 for a given contrast. Y = Yc + Y0 + error\n%\n%=======================================================================\n% case {'|_'} \t%- Fc orthogonalisation \n% Fc = spm_FcUtil('|_',Fc1, sX, Fc2)\n%\n%- Orthogonolise a (list of) contrasts Fc1 wrt a (list of) contrast Fc2\n%- such that the space these contrasts test are orthogonal.\n%- If contrasts are not estimable contrasts, works with the estimable \n%- part. In any case, returns estimable contrasts. \n%\n%=======================================================================\n% case {'|_?'} \t%- Are contrasts orthogonals \n% b = spm_FcUtil('|_?',Fc1, sX [, Fc2])\n%\n%- Tests whether a (list of) contrast is orthogonal. Works with the\n%- estimable part if they are not estimable. With only one argument,\n%- tests whether the list is made of orthogonal contrasts. With Fc2\n%- provided, tests whether the two (list of) contrast are orthogonal. \n%\n%=======================================================================\n% case 'in' %- Fc1 is in list of contrasts Fc2\n% [iFc2 iFc1] = spm_FcUtil('In', Fc1, sX, Fc2)\n%\n%- Tests wether a (list of) contrast Fc1 is in a list of contrast Fc2.\n%- returns the indices iFc2 where element of Fc1 have been found\n%- in Fc2 and the indices iFc1 of the element of Fc1 found in Fc2.\n%- These indices are not necessarily unique.\n%\n%=======================================================================\n% case '~unique' %- Fc list unique \n% idx = spm_FcUtil('~unique', Fc, sX)\n%\n%- returns indices ofredundant contrasts in Fc\n%- such that Fc(idx) = [] makes Fc unique.\n%\n%=======================================================================\n% case {'0|[]','[]|0'} %- Fc is null or empty \n% b = spm_FcUtil('0|[]', Fc, sX)\n%\n%- NB : for the \"null\" part, checks if the contrast is in the null space \n%- of sX (completely non estimable !)\n%=======================================================================\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Jean-Baptiste Poline\n% $Id: spm_FcUtil.m 112 2005-05-04 18:20:52Z john $\n\n\n%-Format arguments\n%-----------------------------------------------------------------------\nif nargin==0, error('do what? no arguments given...')\nelse, action = varargin{1}; end\n\n\nswitch lower(action),\n\ncase 'fconfields'\t\t\t\t%- fields of F contrast\n%=======================================================================\n% Fc = spm_FcUtil('FconFields')\n\nif nargout > 1, error('Too many output arguments: FconFields'), end;\nif nargin > 1, error('Too many input arguments: FconFields'), end;\n\nvarargout = {sf_FconFields;}\n\ncase {'set','v1set'}\t\t\t\t%- Create an F contrast\n%=======================================================================\n% Fc = spm_FcUtil('Set',name, STAT, set_action, value, sX)\n%\n% Sets the contrast structure with set_action either 'c', 'X0' or 'iX0'\n% resp. for a contrast, the null hyp. space or the indices of which.\n% STAT can be 'T' or 'F'.\n%\n% If not set by iX0 (in which case field .iX0 containes the indices),\n% field .iX0 is set as a string containing the set_action: {'X0','c','c+','ukX0'}\n%\n% if STAT is T, then set_action should be 'c' or 'c+' \n% (at the moment, just a warning...)\n% if STAT is T and set_action is 'c' or 'c+', then \n% checks whether it is a real T. \n%\n% 'v1set' is NOT provided for backward compatibility so far ...\n\n%-check # arguments...\n%--------------------------------------------------------------------------\nif nargin<6, error('insufficient arguments'), end;\nif nargout > 1, error('Too many output arguments Set'), end;\n\n%-check arguments...\n%--------------------------------------------------------------------------\nif ~ischar(varargin{2}), error('~ischar(name)'), end;\nif ~(varargin{3}=='F'|varargin{3}=='T'|varargin{3}=='P'), \n\terror('~(STAT==F|STAT==T|STAT==P)'), end;\nif ~ischar(varargin{4}), error('~ischar(varargin{4})'); \nelse set_action = varargin{4}; end;\n\nsX = varargin{6};\nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX);\tend;\nif isempty(sX.X), error('Empty space X in Set'); end;\n\nFc = sf_FconFields;\n%- use the name as a flag to insure that F-contrast has been \n%- properly created;\nFc.name = varargin{2};\n\nFc.STAT = varargin{3};\nif Fc.STAT=='T' & ~(any(strcmp(set_action,{'c+','c'}))) \n warning('enter T stat with contrast - here no check rank == 1');\nend\n\n[sC sL] = spm_sp('size',sX);\n\n%- allow to define the contrast the old (version 1) way ?\n%- NO. v1 = strcmp(action,'v1set');\n\nswitch set_action,\n case {'c','c+'}\n\t Fc.iX0 = set_action;\n c = spm_sp(':', sX, varargin{5});\n\t if isempty(c)\n [Fc.X1o.ukX1o Fc.X0.ukX0] = spm_SpUtil('+c->Tsp',sX,[]);\n \t %- v1 [Fc.X1o Fc.X0] = spm_SpUtil('c->Tsp',sX,[]);\n \t Fc.c = c;\n\t elseif size(c,1) ~= sL, \n\t error(['not contrast dim. in ' mfilename ' ' set_action]); \n\t else\t\n \t if strcmp(set_action,'c+') \n \t if ~spm_sp('isinspp',sX,c), c = spm_sp('oPp:',sX,c); end;\n\t end;\n\t if Fc.STAT=='T' & ~sf_is_T(sX,c)\n %- Could be make more self-correcting by giving back an F\n\t\t error('trying to define a t that looks like an F'); \n\t end\n\t Fc.c = c;\n [Fc.X1o.ukX1o Fc.X0.ukX0] = spm_SpUtil('+c->Tsp',sX,c);\n \t %- v1 [Fc.X1o Fc.X0] = spm_SpUtil('c->Tsp',sX,c);\n\t end;\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n% 'option given for completeness - not for SPM use'\n\n\tcase {'X0'}\n warning(['option given for completeness - not for SPM use']);\n\t Fc.iX0 = set_action;\n\t X0 = spm_sp(':', sX, varargin{5});\n\t if isempty(X0),\n Fc.c = spm_sp('xpx',sX); \n Fc.X1o.ukX1o = spm_sp('cukx',sX);\n Fc.X0.ukX0 = [];\t\n\t elseif size(X0,1) ~= sC, \n error('dimension of X0 wrong in Set');\n\t else \n Fc.c = spm_SpUtil('X0->c',sX,X0);\n\t Fc.X0.ukX0 = spm_sp('ox',sX)'*X0;\t\n Fc.X1o.ukX1o = spm_SpUtil('+c->Tsp',sX,Fc.c);\n\t end\n\n case 'ukX0' \n warning(['option given for completeness - not for SPM use']);\n\t Fc.iX0 = set_action;\n\t if isempty(ukX0), \n Fc.c = spm_sp('xpx',sX); \n Fc.X1o.ukX1o = spm_sp('cukx',sX);\n Fc.X0.ukX0 = [];\t\n\t elseif size(ukX0,1) ~= spm_sp('rk',sX), \n error('dimension of cukX0 wrong in Set');\n\t else \n Fc.c = spm_SpUtil('+X0->c',sX,ukX0);\n\t Fc.X0.ukX0 = ukX0;\t\n Fc.X1o.ukX1o = spm_SpUtil('+c->Tsp',sX,Fc.c);\n\t end \n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\tcase 'iX0'\n\t iX0 \t = varargin{5};\n\t iX0 \t = spm_SpUtil('iX0check',iX0,sL);\n\t Fc.iX0 = iX0;\n Fc.X0.ukX0 = spm_sp('ox',sX)' * spm_sp('Xi',sX,iX0);\n \t if isempty(iX0), \n\t Fc.c = spm_sp('xpx',sX); \n\t Fc.X1o.ukX1o = spm_sp('cukx',sX); \n\t else \t\t\t\n \t Fc.c = spm_SpUtil('i0->c',sX,iX0);\n \t Fc.X1o.ukX1o = spm_SpUtil('+c->Tsp',sX,Fc.c);\n\t end;\n\n\totherwise \n\t error('wrong action in Set '); \n\nend;\nvarargout = {Fc};\n\ncase 'x0' % spm_FcUtil('X0',Fc,sX)\n%=======================================================================\nif nargin ~= 3, \n error('too few/many input arguments - need 2');\nelse \n Fc = varargin{2}; sX = varargin{3};\nend\nif nargout ~= 1, error('too few/many output arguments - need 1'), end\nif ~sf_IsFcon(Fc), error('argument is not a contrast struct'), end\nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;\n\nvarargout = {sf_X0(Fc,sX)};\n\ncase 'x1o' % spm_FcUtil('X1o',Fc,sX)\n%=======================================================================\nif nargin ~= 3, \n error('too few/many input arguments - need 2');\nelse \n Fc = varargin{2}; sX = varargin{3};\nend\nif nargout ~= 1, error('too few/many output arguments - need 1'), end\nif ~sf_IsFcon(Fc), error('argument is not a contrast struct'), end\nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;\n\nvarargout = {sf_X1o(Fc,sX)};\n\n\ncase 'isfcon'\t\t\t\t%- Is it an F contrast ?\n%=======================================================================\n% yes_no = spm_FcUtil('IsFcon',Fc)\n\nif nargin~=2, error('too few/many input arguments - need 2'), end\nif ~isstruct(varargin{2}), varargout={0}; \nelse, varargout = {sf_IsFcon(varargin{2})};\nend\n\n\ncase 'fconedf'\t\t\t\t%- F contrast edf\n%=======================================================================\n% [edf_tsp edf_Xsp] = spm_FcUtil('FconEdf', Fc, sX [, V])\n\nif nargin<3, error('Insufficient arguments'), end\nif nargout >= 3, error('Too many output argument.'), end\nFc = varargin{2};\nsX = varargin{3};\nif nargin == 4, V = varargin{4}; else V = []; end;\n\nif ~sf_IsFcon(Fc), error('Fc must be Fcon'), end\nif ~spm_sp('isspc',sX)\n\tsX = spm_sp('set',sX);\tend;\n\nif ~sf_isempty_X1o(Fc)\n [trMV, trMVMV] = spm_SpUtil('trMV',sf_X1o(Fc,sX),V);\nelse\n trMV = 0;\n trMVMV = 0;\nend\t\nif ~trMVMV, edf_tsp = 0; warning('edf_tsp = 0'), \nelse, edf_tsp = trMV^2/trMVMV; end;\t\n\nif nargout == 2\n\n [trRV, trRVRV] = spm_SpUtil('trRV',sX,V);\n if ~trRVRV, edf_Xsp = 0, warning('edf_Xsp = 0'),\n else, edf_Xsp = trRV^2/trRVRV; end;\n\n varargout = {edf_tsp, edf_Xsp};\nelse \t\n varargout = {edf_tsp};\nend;\n\n\n\n%=======================================================================\n%=======================================================================\n%\t\tparts that use F contrast\n%=======================================================================\n%=======================================================================\n%\n% Quick reference : L : can be lists of ...\n%-------------------------\n% ('Hsqr',Fc, sX) : Out: Hsqr / ESS = b' * Hsqr' * Hsqr * b\n% ('H',Fc, sX) : Out: H / ESS = b' * H * b\n% ('Yc',Fc, sX, b) : Out: Y corrected = X*b - X0*X0- *Y \n% ('Y0',Fc, sX, b) : Out: Y0 = X0*X0- *Y\n% ('|_',LFc1, sX, LFc2) : Out: Fc1 orthog. wrt Fc2 \n% ('|_?',LFc1,sX [,LFc2]): Out: is Fc2 ortho to Fc1 or is Fc1 ortho ? \n% ('In', LFc1, sX, LFc2) : Out: indices of Fc2 if \"in\", 0 otherwise\n% ('~unique', LFc, sX) : Out: indices of redundant contrasts \n% ('0|[]', Fc, sX) : Out: 1 if Fc is zero or empty, 0 otherwise\n\n\ncase 'hsqr' %-Extra sum of squares matrix for beta's from contrast\n%=======================================================================\n% hsqr = spm_FcUtil('Hsqr',Fc, sX)\n\nif nargin<3, error('Insufficient arguments'), end\nif nargout>1, error('Too many output argument.'), end\nFc = varargin{2};\nsX = varargin{3};\n\nif ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end\nif ~sf_IsSet(Fc), error('Fcon must be set'); end; %-\nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX);\tend;\n\nif sf_isempty_X1o(Fc)\n\tif ~sf_isempty_X0(Fc)\n\t\t%- assumes that X0 is sX.X\n\t\t%- warning(' Empty X1o in spm_FcUtil(''Hsqr'',Fc,sX) ');\n\t\tvarargout = { zeros(1,spm_sp('size',sX,2)) };\n\telse \t\n\t\terror(' Fc must be set ');\n\tend\nelse\n\tvarargout = { sf_Hsqr(Fc,sX) };\nend\n\n\ncase 'h' %-Extra sum of squares matrix for beta's from contrast\n%=======================================================================\n% H = spm_FcUtil('H',Fc, sX)\n\n% Empty and zeros dealing : \n% This routine never returns an empty matrix. \n% If sf_isempty_X1o(Fc) | isempty(Fc.c) it explicitly \n% returns a zeros projection matrix.\n\nif nargin<2, error('Insufficient arguments'), end\nif nargout>1, error('Too many output argument.'), end\nFc = varargin{2};\nsX = varargin{3};\n\nif ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end\nif ~sf_IsSet(Fc), error('Fcon must be set'); end; %-\nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX);\tend;\n\nif sf_isempty_X1o(Fc)\n\tif ~sf_isempty_X0(Fc)\n\t\t%- assumes that X0 is sX.X\n\t\t%- warning(' Empty X1o in spm_FcUtil(''H'',Fc,sX) ');\n\t\tvarargout = { zeros(spm_sp('size',sX,2)) };\n\telse \t\n\t\terror(' Fc must be set ');\n\tend\nelse\n\tvarargout = { sf_H(Fc,sX) }; \nend\n\n\n\n\ncase 'yc' %- Fitted data corrected for confounds defined by Fc \n%=======================================================================\n% Yc = spm_FcUtil('Yc',Fc, sX, b)\n\nif nargin < 4, error('Insufficient arguments'), end\nif nargout > 1, error('Too many output argument.'), end\n\nFc = varargin{2}; sX = varargin{3}; b = varargin{4};\n\nif ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end\nif ~sf_IsSet(Fc), error('Fcon must be set'); end; \nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX);\tend;\n% if ~spm_FcUtil('Rcompatible',Fc,sX), ...\n%\terror('sX and Fc must be compatible'), end;\nif spm_sp('size',sX,2) ~= size(b,1), \n\terror('sX and b must be compatible'), end;\n\nif sf_isempty_X1o(Fc)\n\tif ~sf_isempty_X0(Fc)\n\t %- if space of interest empty or null, returns zeros !\n\t varargout = { zeros(spm_sp('size',sX,1),size(b,2)) };\n\telse \t\n\t error(' Fc must be set ');\n\tend\nelse\n\tvarargout = { sf_Yc(Fc,sX,b) }; \nend\n\n\n\ncase 'y0' %- Fitted data corrected for confounds defined by Fc \n%=======================================================================\n% Y0 = spm_FcUtil('Y0',Fc, sX, b)\n\nif nargin < 4, error('Insufficient arguments'), end\nif nargout > 1, error('Too many output argument.'), end\n\nFc = varargin{2}; sX = varargin{3}; b = varargin{4};\n\nif ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end\nif ~sf_IsSet(Fc), error('Fcon must be set'); end; \nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX);\tend;\nif spm_sp('size',sX,2) ~= size(b,1), \n\terror('sX and b must be compatible'), end;\n\nif sf_isempty_X1o(Fc)\n\tif ~sf_isempty_X0(Fc)\n\t %- if space of interest empty or null, returns zeros !\n\t varargout = { sX.X*b };\n\telse \t\n\t error(' Fc must be set ');\n\tend\nelse\n\tvarargout = { sf_Y0(Fc,sX,b) }; \nend\n\n\ncase {'|_'} %- Fc orthogonalisation \n%=======================================================================\n% Fc = spm_FcUtil('|_',Fc1, sX, Fc2)\n\n% returns Fc1 orthogonolised wrt Fc2 \n\nif nargin < 4, error('Insufficient arguments'), end\nif nargout > 1, error('Too many output argument.'), end\nFc1 = varargin{2}; sX = varargin{3}; Fc2 = varargin{4}; \n\n%-check arguments\n%-----------------------------------------------------------------------\nL1 = length(Fc1);\nif ~L1, warning('no contrast given to |_'); varargout = {[]}; return; end\nfor i=1:L1\n if ~sf_IsFcon(Fc1(i)), error('Fc1(i) must be a contrast'), end\nend\nL2 = length(Fc2);\nif ~L2, error('must have at least a contrast in Fc2'); end\nfor i=1:L2\n if ~sf_IsFcon(Fc2(i)), error('Fc2(i) must be a contrast'), end\nend\nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX);\tend;\n\n%-create an F-contrast for all the Fc2\n%--------------------------------------------------------------------------\nstr = Fc2(1).name; for i=2:L2 str = [str ' ' Fc2(i).name]; end;\nFc2 = spm_FcUtil('Set',str,'F','c+',cat(2,Fc2(:).c),sX);\n\nif sf_isempty_X1o(Fc2) | sf_isnull(Fc2,sX)\n\tvarargout = {Fc1};\nelse\n\tfor i=1:L1\n\t\tif sf_isempty_X1o(Fc1(i)) | sf_isnull(Fc1(i),sX)\n\t\t\t%- Fc1(i) is an [] or 0 contrast : ortho to anything; \n\t\t\tout(i) = Fc1(i);\n\t\telse\n\t\t\tout(i) = sf_fcortho(Fc1(i), sX, Fc2);\n\t\tend\n\tend\n\tvarargout = {out}; \nend\n\ncase {'|_?'} \t%- Are contrasts orthogonals \n%=======================================================================\n% b = spm_FcUtil('|_?',Fc1, sX [, Fc2])\n\nif nargin < 3, error('Insufficient arguments'), end\nFc1 = varargin{2}; sX = varargin{3};\nif nargin > 3, Fc2 = varargin{4}; else, Fc2 = []; end;\nif isempty(Fc1), error('give at least one non empty contrast'), end;\n\nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX);\tend;\nfor i=1:length(Fc1)\n\tif ~sf_IsFcon(Fc1(i)), error('Fc1(i) must be a contrast'), end\nend\nfor i=1:length(Fc2)\n\tif ~sf_IsFcon(Fc2(i)), error('Fc2(i) must be a contrast'), end\nend\nvarargout = { sf_Rortho(Fc1,sX,Fc2) };\n\n\ncase 'in' %- Fc1 is in list of contrasts Fc2\n%=======================================================================\n% [iFc2 iFc1] = spm_FcUtil('In', Fc1, sX, Fc2)\n\n% returns indice of Fc2 if \"in\", 0 otherwise \n% NB : If T- stat, the routine checks whether Fc.c is of\n% size one. This is ensure if contrast is set \n% or manipulated (ortho ..) with spm_FcUtil\n% note that the algorithmn works \\emph{only because} Fc2(?).c \n% and Fc1.c are in space(X')\n\nif nargin < 4, error('Insufficient arguments'), end\nif nargout > 2, error('Too many output argument.'), end\n\nFc1 = varargin{2}; Fc2 = varargin{4}; sX = varargin{3};\n\nL1 = length(Fc1);\nif ~L1, warning('no contrast given to in'); \n\t if nargout == 2, varargout = {[] []}; \n\t else, varargout = {[]}; end;\n\t return; \nend\nfor i=1:L1\n if ~sf_IsFcon(Fc1(i)), error('Fc1(i) must be a contrast'), end\nend\nL2 = length(Fc2);\nif ~L2, error('must have at least a contrast in Fc2'); end\nfor i=1:L2\n if ~sf_IsFcon(Fc2(i)), error('Fc2(i) must be F-contrast'), end\nend\nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX);\tend;\n\n\n[idxFc2 idxFc1] = sf_in(Fc1, sX, Fc2);\nif isempty(idxFc2), idxFc2 = 0; end\nif isempty(idxFc1), idxFc1 = 0; end\n\nswitch nargout \n\tcase {0,1}\n\t\tvarargout = { idxFc2 };\n\tcase 2\n\t\tvarargout = { idxFc2 idxFc1 };\n\totherwise \n\t\terror('Too many or not enough output arguments');\nend\n\ncase '~unique' %- Fc list unique \n%=======================================================================\n% idx = spm_FcUtil('~unique', Fc, sX)\n\n%- returns indices of redundant contrasts in Fc\n%- such that Fc(idx) = [] makes Fc unique. \n%- if already unique returns [] \n\nif nargin ~= 3, error('Insufficient/too many arguments'), end\nFc = varargin{2}; sX = varargin{3}; \n\n%----------------------------\nL1 = length(Fc);\nif ~L1, warning('no contrast given '); varargout = {[]}; return; end\nfor i=1:L1\n if ~sf_IsFcon(Fc(i)), error('Fc(i) must be a contrast'), end\nend\nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX);\tend;\n%----------------------------\n\nvarargout = { unique(sf_notunique(Fc, sX))};\n\n\n\ncase {'0|[]','[]|0'} %- Fc is null or empty \n%=======================================================================\n% b = spm_FcUtil('0|[]', Fc, sX)\n\n% returns 1 if F-contrast is empty or null; assumes the contrast is set.\n\nif nargin ~= 3, error('Insufficient/too many arguments'), end\nFc = varargin{2}; sX = varargin{3}; \n\n%----------------------------\nL1 = length(Fc);\nif ~L1, warning('no contrast given to |_'); varargout = {[]}; return; end\nfor i=1:L1\n if ~sf_IsFcon(Fc(i)), error('Fc(i) must be a contrast'), end\nend\nif ~spm_sp('isspc',sX), sX = spm_sp('set',sX);\tend;\n%----------------------------\n\nidx = [];\nfor i=1:L1\n\tif sf_isempty_X1o(Fc(i)) | sf_isnull(Fc(i),sX), idx = [idx i]; end\nend\nif isempty(idx) \n\tvarargout = {0};\nelse \n\tvarargout = {idx};\nend\n\n%=======================================================================\n\notherwise\n%=======================================================================\nerror('Unknown action string in spm_FcUtil')\n\n\nend; %---- switch lower(action),\n\n%=======================================================================\n%=======================================================================\n% Sub Functions\n%=======================================================================\n%=======================================================================\n\n%=======================================================================\n% Fcon = spm_FcUtil('FconFields')\n\nfunction Fc = sf_FconFields\n\nFc = struct(...\n\t'name',\t\t'',...\n\t'STAT',\t\t'',...\n\t'c',\t\t[],...\n\t'X0',\t\tstruct('ukX0',[]),... %!15/10\n\t'iX0',\t\t[],...\n\t'X1o',\t\tstruct('ukX1o',[]),... %!15/10\n\t'eidf',\t\t[],...\n\t'Vcon',\t\t[],...\n\t'Vspm',\t\t[]\t);\n \n%=======================================================================\n% used internally. Minimum contrast structure\n\nfunction minFc = sf_MinFcFields\n\nminFc = struct(...\n\t'name',\t\t'',...\n\t'STAT',\t\t'',...\n\t'c',\t\t[],...\n\t'X0',\t [],...\n\t'X1o',\t []...\n\t);\n\n%=======================================================================\n% yes_no = spm_FcUtil('IsFcon',Fc)\n\nfunction b = sf_IsFcon(Fc)\n\n%- check that minimum fields of a contrast are in Fc \nb \t = 1;\nminnames = fieldnames(sf_MinFcFields);\nFCnames = fieldnames(Fc);\nfor str = minnames'\n b = b & any(strcmp(str,FCnames));\n if ~b, break, end\nend\n\n%=======================================================================\n% used internally; To be set, a contrast structure should have\n% either X1o or X0 non empty. X1o can be non empty because c\n% is non empty.\n\nfunction b = sf_IsSet(Fc)\n\nb = ~sf_isempty_X0(Fc) | ~sf_isempty_X1o(Fc);\n\n%=======================================================================\n% used internally\n%\nfunction v = sf_ver(Fc)\n\nif isstruct(Fc.X0), v = 2; else v = 1; end\n\n%=======================================================================\n% used internally\n\nfunction b = sf_isempty_X1o(Fc)\n\nif sf_ver(Fc) > 1, \n b = isempty(Fc.X1o.ukX1o); \n %- consistency check\n if b ~= isempty(Fc.c), \n Fc.c, Fc.X1o.ukX1o, error('Contrast internally not consistent');\n end\nelse, \n b = isempty(Fc.X1o);\n %- consistency check\n if b ~= isempty(Fc.c), \n Fc.c, Fc.X1o, error('Contrast internally not consistent');\n end\nend\n%=======================================================================\n% used internally\n\nfunction b = sf_X1o(Fc,sX)\n\nif sf_ver(Fc) > 1, \n b = spm_sp('ox',sX)*Fc.X1o.ukX1o; \nelse, \n b = Fc.X1o;\nend\n\n%=======================================================================\n% used internally\n\nfunction b = sf_X0(Fc,sX)\n\nif sf_ver(Fc) > 1, \n b = spm_sp('ox',sX)*Fc.X0.ukX0; \nelse, \n b = Fc.X0;\nend\n\n%=======================================================================\n% used internally\n\nfunction b = sf_isempty_X0(Fc)\n\nif sf_ver(Fc) > 1, \n b = isempty(Fc.X0.ukX0); \nelse, \n b = isempty(Fc.X0);\nend\n\n%=======================================================================\n% Hsqr = spm_Fcutil('Hsqr',Fc,sX)\n\nfunction hsqr = sf_Hsqr(Fc,sX)\n%\n% Notations : H equiv to X1o, H = uk*a1, X = uk*ax, r = rk(sX), \n% sX.X is (n,p), H is (n,q), a1 is (r,q), ax is (r,p)\n% oxa1 is an orthonormal basis for a1, oxa1 is (r,qo<=q)\n% Algorithm : \n% v1 : Y'*H*(H'*H)-*H'*Y = b'*X'*H*(H'*H)-*H'*X*b\n% = b'*X'*oxH*oxH'*X*b\n% so hsrq is set to oxH'*X, a (q,n)*(n,p) op. + computation of oxH \n% v2 : X'*H*(H'*H)-*H'*X = ax'*uk'*uk*a1*(a1'*uk'*uk*a1)-*a1'*uk'*uk*ax\n% = ax'*a1*(a1'*a1)-*a1'*ax\n% = ax'*oxa1*oxa1'*ax\n% \n% so hsrq is set to oxa1'*ax : a (qo,r)*(r,p) operation! -:)) \n% + computation of oxa1.\n\n%-**** fprintf('v%d\\n',sf_ver(Fc));\nif sf_ver(Fc) > 1, \n hsqr = spm_sp('ox',spm_sp('set',Fc.X1o.ukX1o))' * spm_sp('cukx',sX);\nelse, \n hsqr = spm_sp('ox',spm_sp('set',Fc.X1o))'*spm_sp('x',sX);\nend\n%=======================================================================\n% H = spm_FcUtil('H',Fc)\n\nfunction H = sf_H(Fc,sX)\n% \n% Notations : H equiv to X1o, H = uk*a1, X = uk*ax\n% Algorithm : \n% v1 : Y'*H*(H'*H)-*H'*Y = b'*X'*H*(H'*H)-*H'*X*b\n% = b'*c*(H'*H)-*c'*b\n% = b'*c*(c'*(X'*X)-*c)-*c'*b\n%- v1 : Note that pinv(Fc.X1o' * Fc.X1o) is not too bad\n%- because dimensions are only (q,q). See sf_hsqr for notations.\n%- Fc.c and Fc.X1o should match. This is ensure by using FcUtil.\n\n%-**** fprintf('v%d\\n',sf_ver(Fc));\nif sf_ver(Fc) > 1, \n hsqr = sf_Hsqr(Fc,sX);\n H = hsqr' * hsqr;\nelse\n H = Fc.c * pinv(Fc.X1o' * Fc.X1o) * Fc.c';\n % H = {c*spm_sp('x-',spm_sp('Set',c'*spm_sp('xpx-',sX)*c) )*c'}\nend\n\n%=======================================================================\n% Yc = spm_FcUtil('Yc',Fc,sX,b)\n\nfunction Yc = sf_Yc(Fc,sX,b)\n\nYc = sX.X*spm_sp('xpx-',sX)*sf_H(Fc,sX)*b;\n\n%=======================================================================\n% Y0 = spm_FcUtil('Y0',Fc,sX,b)\nfunction Y0 = sf_Y0(Fc,sX,b)\n\nY0 = sX.X*(eye(spm_sp('size',sX,2)) - spm_sp('xpx-',sX)*sf_H(Fc,sX))*b;\n\n%=======================================================================\n% Fc = spm_FcUtil('|_',Fc1, sX, Fc2)\n\nfunction Fc1o = sf_fcortho(Fc1, sX, Fc2)\n\n%--- use the space facility to ensure the proper tolerance dealing...\n\nc1_2 = Fc1.c - sf_H(Fc2,sX)*spm_sp('xpx-:',sX,Fc1.c);\nFc1o = spm_FcUtil('Set',['(' Fc1.name ' |_ (' Fc2.name '))'], ...\n\t\t Fc1.STAT, 'c+',c1_2,sX);\n\n%- In the large (scans) dimension :\n%- c = sX.X'*spm_sp('r:',spm_sp('set',Fc2.X1o),Fc1.X1o);\n%- Fc1o = spm_FcUtil('Set',['(' Fc1.name ' |_ (' Fc2.name '))'], ...\n%-\t\t\t\t\t\t Fc1.STAT, 'c',c,sX);\n\n%=======================================================================\nfunction b = sf_Rortho(Fc1,sX,Fc2);\n\nif isempty(Fc2)\n if length(Fc1) <= 1, b = 0; \n else\n c1 = cat(2,Fc1(:).c); \n b = ~any(any( abs(triu(c1'*spm_sp('xpx-:',sX,c1), 1)) > sX.tol));\n end\nelse \n c1 = cat(2,Fc1(:).c); c2 = cat(2,Fc2(:).c); \n b = ~any(any( abs(c1'*spm_sp('xpx-:',sX,c2)) > sX.tol ));\nend\n\n%=======================================================================\n% b = spm_FcUtil('0|[]', Fc, sX)\n\n%- returns 1 if F-contrast is empty or null; assumes the contrast is set.\n%- Assumes that if Fc.c contains only zeros, so does Fc.X1o. \n%- this is ensured if spm_FcUtil is used\n\nfunction boul = sf_isnull(Fc,sX)\n%\nboul = ~any(any(spm_sp('oPp:',sX,Fc.c)));\n\n%=======================================================================\n% Fc = spm_FcUtil('Set',name, STAT, set_action, value, sX)\n\nfunction boul = sf_is_T(sX,c)\n%- assumes that the dimensions are OK\n%- assumes c is not empty\n%- Does NOT assumes that c is space of sX'\n%- A rank of zero can be defined\n%- if the rank == 1, checks whether same directions\n\nboul = 1;\nif ~spm_sp('isinspp',sX,c), c = spm_sp('oPp:',sX,c); end;\nif rank(c) > 1 | any(any(c'*c < 0)), boul = 0; end;\n\n\n\n\n%=======================================================================\nfunction [idxFc2, idxFc1] = sf_in(Fc1, sX, Fc2);\n\nL2 = length(Fc2);\nL1 = length(Fc1);\n\nidxFc1 = []; idxFc2 = [];\nfor j=1:L1\n %- project Fc1(j).c if not estimable\n if ~spm_sp('isinspp',sX,Fc1(j).c), %- warning ? \n c1 = spm_sp('oPp:',sX,Fc1(j).c); \n else, \n c1 = Fc1(j).c; \n end\n sc1 = spm_sp('Set',c1); \n S = Fc1(j).STAT;\n\n boul = 0; i = 1;\n for i =1:L2,\n if Fc2(i).STAT == S\n %- the same statistics. else just go on to the next contrast\n boul = spm_sp('==',sc1,spm_sp('oPp',sX,Fc2(i).c));\n\n %- if they are the same space and T stat (same direction),\n %- then check wether they are in the same ORIENTATION\n %- works because size(X1o,2) == 1, else .* with (Fc1(j).c'*Fc2(i).c)\n if boul & S == 'T'\n atmp = sf_X1o(Fc1(j),sX);\n btmp = sf_X1o(Fc2(i),sX);\n boul = ~any(any( (atmp' * btmp) < 0 ));\n end\n %- note the indices\n if boul, idxFc1 = [idxFc1 j]; idxFc2 = [idxFc2 i]; end;\n end;\n end\nend %- for j=1:L1\n\n%=======================================================================\nfunction idx = sf_notunique(Fc, sX)\n\n%- works recursively ...\n%- and use the fact that [] + i == []\n%- quite long for large sets ... \n\nl = length(Fc);\nif l == 1, idx = []; \nelse\n idx = [ (1+sf_in(Fc(1),sX,Fc(2:l))) (1+sf_notunique(Fc(2:l), sX))];\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_read_hdr.m", "ext": ".m", "path": "spm5-master/spm_read_hdr.m", "size": 5383, "source_encoding": "utf_8", "md5": "97dd94a3164b5766dcc739ab2cdd041d", "text": "function [hdr,otherendian] = spm_read_hdr(fname)\n% Read (SPM customised) Analyze header\n% FORMAT [hdr,otherendian] = spm_read_hdr(fname)\n% fname - .hdr filename\n% hdr - structure containing Analyze header\n% otherendian - byte swapping necessary flag\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_read_hdr.m 112 2005-05-04 18:20:52Z john $\n\n\nfid = fopen(fname,'r','native');\notherendian = 0;\nif (fid > 0)\n\tdime = read_dime(fid);\n\tif dime.dim(1)<0 | dime.dim(1)>15, % Appears to be other-endian\n\t\t% Re-open other-endian\n\t\tfclose(fid);\n\t\tif spm_platform('bigend'), fid = fopen(fname,'r','ieee-le');\n\t\telse, fid = fopen(fname,'r','ieee-be'); end;\n\t\totherendian = 1;\n\t\tdime = read_dime(fid);\n\tend;\n\thk = read_hk(fid);\n\thist = read_hist(fid);\n\thdr.hk = hk;\n\thdr.dime = dime;\n\thdr.hist = hist;\n\n\t% SPM specific bit - unused\n\t%if hdr.hk.sizeof_hdr > 348,\n\t%\tspmf = read_spmf(fid,dime.dim(5));\n\t%\tif ~isempty(spmf),\n\t%\t\thdr.spmf = spmf;\n\t%\tend;\n\t%end;\n\n\tfclose(fid);\nelse,\n\thdr = [];\n\totherendian = NaN;\n\t%error(['Problem opening header file (' fopen(fid) ').']);\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction hk = read_hk(fid)\n% read (struct) header_key\n%-----------------------------------------------------------------------\nfseek(fid,0,'bof');\nhk.sizeof_hdr \t\t= fread(fid,1,'int32');\nhk.data_type \t\t= mysetstr(fread(fid,10,'uchar'))';\nhk.db_name \t\t= mysetstr(fread(fid,18,'uchar'))';\nhk.extents \t\t= fread(fid,1,'int32');\nhk.session_error\t= fread(fid,1,'int16');\nhk.regular\t\t\t= mysetstr(fread(fid,1,'uchar'))';\nhk.hkey_un0\t\t\t= mysetstr(fread(fid,1,'uchar'))';\nif isempty(hk.hkey_un0), error(['Problem reading \"hk\" of header file (' fopen(fid) ').']); end;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction dime = read_dime(fid)\n% read (struct) image_dimension\n%-----------------------------------------------------------------------\nfseek(fid,40,'bof');\ndime.dim\t\t= fread(fid,8,'int16')';\ndime.vox_units\t= mysetstr(fread(fid,4,'uchar'))';\ndime.cal_units\t= mysetstr(fread(fid,8,'uchar'))';\ndime.unused1\t= fread(fid,1,'int16');\ndime.datatype\t= fread(fid,1,'int16');\ndime.bitpix\t\t= fread(fid,1,'int16');\ndime.dim_un0\t= fread(fid,1,'int16');\ndime.pixdim\t\t= fread(fid,8,'float')';\ndime.vox_offset\t= fread(fid,1,'float');\ndime.funused1\t= fread(fid,1,'float');\ndime.funused2\t= fread(fid,1,'float');\ndime.funused3\t= fread(fid,1,'float');\ndime.cal_max\t= fread(fid,1,'float');\ndime.cal_min\t= fread(fid,1,'float');\ndime.compressed\t= fread(fid,1,'int32');\ndime.verified\t= fread(fid,1,'int32');\ndime.glmax\t\t= fread(fid,1,'int32');\ndime.glmin\t\t= fread(fid,1,'int32');\nif isempty(dime.glmin), error(['Problem reading \"dime\" of header file (' fopen(fid) ').']); end;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction hist = read_hist(fid)\n% read (struct) data_history\n%-----------------------------------------------------------------------\nfseek(fid,148,'bof');\nhist.descrip\t= mysetstr(fread(fid,80,'uchar'))';\nhist.aux_file\t= mysetstr(fread(fid,24,'uchar'))';\nhist.orient\t\t= fread(fid,1,'uchar');\nhist.origin\t\t= fread(fid,5,'int16')';\nhist.generated\t= mysetstr(fread(fid,10,'uchar'))';\nhist.scannum\t= mysetstr(fread(fid,10,'uchar'))';\nhist.patient_id\t= mysetstr(fread(fid,10,'uchar'))';\nhist.exp_date\t= mysetstr(fread(fid,10,'uchar'))';\nhist.exp_time\t= mysetstr(fread(fid,10,'uchar'))';\nhist.hist_un0\t= mysetstr(fread(fid,3,'uchar'))';\nhist.views\t\t= fread(fid,1,'int32');\nhist.vols_added\t= fread(fid,1,'int32');\nhist.start_field= fread(fid,1,'int32');\nhist.field_skip\t= fread(fid,1,'int32');\nhist.omax\t\t= fread(fid,1,'int32');\nhist.omin\t\t= fread(fid,1,'int32');\nhist.smax\t\t= fread(fid,1,'int32');\nhist.smin\t\t= fread(fid,1,'int32');\nif isempty(hist.smin), error(['Problem reading \"hist\" of header file (' fopen(fid) ').']); end;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction spmf = read_spmf(fid,n)\n% Read SPM specific fields\n% This bit may be used in the future for extending the Analyze header.\n\nfseek(fid,348,'bof');\nmgc = fread(fid,1,'int32'); % Magic number\nif mgc ~= 20020417, spmf = []; return; end;\n\nfor j=1:n,\n\tspmf(j).mat = fread(fid,16,'double'); % Orientation information\n\tspmf(j).unused = fread(fid,384,'uchar'); % Extra unused stuff\n\tif length(spmf(j).unused)<384,\n\t\terror(['Problem reading \"spmf\" of header file (' fopen(fid) ').']);\n\tend;\n \tspmf(j).mat = reshape(spmf(j).mat,[4 4]);\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction out = mysetstr(in)\ntmp = find(in == 0);\ntmp = min([min(tmp) length(in)]);\nout = setstr([in(1:tmp)' zeros(1,length(in)-(tmp))])';\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_visu3D_api.m", "ext": ".m", "path": "spm5-master/spm_eeg_inv_visu3D_api.m", "size": 26874, "source_encoding": "utf_8", "md5": "54b206a78840c7f9488c6600fa85999b", "text": "function varargout = spm_eeg_inv_visu3D_api(varargin)\n% SPM_EEG_INV_VISU3D_API M-file for spm_eeg_inv_visu3D_api.fig\n% - FIG = SPM_EEG_INV_VISU3D_API launch spm_eeg_inv_visu3D_api GUI.\n% - D = SPM_EEG_INV_VISU3D_API(D) open with D\n% - SPM_EEG_INV_VISU3D_API(filename) where filename is the eeg/meg .mat file\n% - SPM_EEG_INV_VISU3D_API('callback_name', ...) invoke the named callback.\n%\n% Last Modified by GUIDE v2.5 01-Feb-2007 20:16:13\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n% Jeremie Mattout\n% $Id: spm_eeg_inv_visu3D_api.m 1079 2008-01-11 11:05:48Z guillaume $\n\n% INITIALISATION CODE\n%--------------------------------------------------------------------------\nif nargin == 0 || nargin == 1 % LAUNCH GUI\n\n \n % open new api\n %----------------------------------------------------------------------\n fig = openfig(mfilename,'new');\n handles = guihandles(fig);\n handles.fig = fig;\n guidata(fig,handles);\n set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));\n \n \n % load D if possible and try to open\n %----------------------------------------------------------------------\n try\n handles.D = spm_eeg_inv_check(varargin{1});\n set(handles.DataFile,'String',handles.D.fname)\n spm_eeg_inv_visu3D_api_OpeningFcn(fig, [], handles)\n end\n\n % return figure handle if necessary\n %----------------------------------------------------------------------\n if nargout > 0\n varargout{1} = fig;\n end\n \nelseif ischar(varargin{1})\n\n try\n if (nargout)\n [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard\n else\n feval(varargin{:}); % FEVAL switchyard\n end\n catch\n disp(lasterr);\n end\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --- Executes just before spm_eeg_inv_visu3D_api is made visible.\nfunction spm_eeg_inv_visu3D_api_OpeningFcn(hObject, eventdata, handles)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% LOAD DATA\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ntry\n D = handles.D;\ncatch\n D = spm_eeg_ldata(spm_select(1, '.mat', 'Select EEG/MEG mat file'));\nend\n\nif ~isfield(D,'inv')\n error(sprintf('Please specify and invert a foward model\\n'));\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% GET RESULTS (default: current or last analysis)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfigure(handles.fig);\naxes(handles.sensors_axes);\n\ntry, val = D.val; catch, val = 1; D.val = 1; end\ntry, con = D.con; catch, con = 1; D.con = 1; end\nif D.con > length(D.inv{D.val}.inverse.J)\n con = 1; D.con = 1;\nend\n\nset(handles.DataFile,'String',D.fname);\nset(handles.next,'String',sprintf('model %i',val));\nset(handles.con, 'String',sprintf('condition %i',con));\nset(handles.fig,'name',['Source visualisation -' D.fname])\n\nif strcmp(D.inv{val}.method,'ECD')\n warndlg('Please create an imaging solution');\n guidata(hObject,handles);\n return\nend\nset(handles.LogEv,'String',num2str(D.inv{val}.inverse.F));\nset(handles.LogEv,'Enable','inactive');\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% OBSERVED ACTIVITY\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% start with response\n%--------------------------------------------------------------------------\ntry\n \n % Load Gain or Lead field matrix\n %----------------------------------------------------------------------\n dimT = 256;\n dimS = D.inv{val}.inverse.Nd;\n Is = D.inv{val}.inverse.Is;\n L = D.inv{val}.inverse.L;\n U = D.inv{val}.inverse.U;\n T = D.inv{val}.inverse.T;\n Y = D.inv{val}.inverse.Y{con};\n Ts = ceil(linspace(1,size(T,1),dimT));\n \n % source data\n %----------------------------------------------------------------------\n set(handles.Activity,'Value',1);\n J = sparse(dimS,dimT);\n J(Is,:) = D.inv{val}.inverse.J{con}*T(Ts,:)';\n handles.dimT = dimT;\n handles.dimS = dimS;\n handles.pst = D.inv{val}.inverse.pst(Ts);\n handles.srcs_data = J;\n handles.Nmax = max(abs(J(:)));\n\n % sensor data\n %---------------------------------------------------------------------- \n handles.sens_data = U*Y*T(Ts,:)';\n handles.pred_data = U*L*J(Is,:);\n\ncatch\n warndlg({'Please invert your model';'inverse.J not found'});\n return\nend\n \n% case 'windowed response' or contrast'\n%--------------------------------------------------------------------------\ntry\n JW = sparse(dimS,1);\n GW = sparse(dimS,1);\n JW(Is,:) = D.inv{val}.contrast.JW{con};\n GW(Is,:) = D.inv{val}.contrast.GW{con};\n handles.woi = D.inv{val}.contrast.woi;\n handles.fboi = D.inv{val}.contrast.fboi;\n handles.W = D.inv{val}.contrast.W(Ts,:);\n handles.srcs_data_w = JW;\n handles.sens_data_w = handles.sens_data*handles.W(:,1);\n handles.pred_data_w = handles.pred_data*handles.W(:,1);\n handles.srcs_data_ev = GW;\n handles.sens_data_ev = sum((handles.sens_data*handles.W).^2,2);\n handles.pred_data_ev = sum((handles.pred_data*handles.W).^2,2);\n set(handles.Activity,'enable','on');\ncatch\n set(handles.Activity,'enable','off');\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% LOAD CORTICAL MESH (default: Individual)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ntry\n vert = D.inv{val}.mesh.tess_mni.vert;\n face = D.inv{val}.mesh.tess_mni.face;\n set(handles.Template, 'Value',1);\n set(handles.Individual,'Value',0);\ncatch\n try\n vert = D.inv{val}.mesh.tess_ctx.vert;\n face = D.inv{val}.mesh.tess_ctx.face;\n set(handles.Template, 'Value',0);\n set(handles.Individual,'Value',1);\n catch\n warndlg('There is no mesh associated with these data');\n return\n end\nend\n\nhandles.vert = vert;\nhandles.face = face;\nhandles.grayc = sqrt(sum((vert.^2)')); handles.grayc = handles.grayc'/max(handles.grayc);\nclear vert face\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SLIDER INITIALISATION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nset(handles.slider_transparency,'Min',0,'Max',1,'Value',1,'sliderstep',[0.01 0.05]);\nset(handles.slider_srcs_up, 'Min',0,'Max',1,'Value',0,'sliderstep',[0.01 0.05]);\nset(handles.slider_srcs_down, 'Min',0,'Max',1,'Value',1,'sliderstep',[0.01 0.05]);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% INITIAL SOURCE LEVEL DISPLAY\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naxes(handles.sources_axes);\ncla; axis off\n\nset(handles.slider_time, 'Enable','on');\nset(handles.time_bin, 'Enable','on');\nset(handles.slider_time, 'Value',1);\nset(handles.time_bin, 'String',num2str(fix(handles.pst(1))));\nset(handles.slider_time, 'Min',1,'Max',handles.dimT,'sliderstep',[1/(handles.dimT-1) 2/(handles.dimT-1)]);\nset(handles.checkbox_absv,'Enable','on','Value',1);\nset(handles.checkbox_norm,'Enable','on','Value',0);\n\nsrcs_disp = full(abs(handles.srcs_data(:,1)));\nhandles.fig1 = patch('vertices',handles.vert,'faces',handles.face,'FaceVertexCData',srcs_disp);\n\n% display\n%--------------------------------------------------------------------------\nset(handles.fig1,'FaceColor',[.5 .5 .5],'EdgeColor','none');\nshading interp\nlighting gouraud\ncamlight\nzoom off\nlightangle(0,270);lightangle(270,0),lightangle(0,0),lightangle(90,0);\nmaterial([.1 .1 .4 .5 .4]);\nview(140,15);\naxis image\nhandles.colorbar = colorbar;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% LOAD SENSOR FILE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ntry\n load(fullfile(spm('dir'),'EEGtemplates',D.channels.ctf));\ncatch\n try\n Cpos = D.inv{1}.datareg.sens_coreg(:,[1 2])'; \n catch\n [f,p] = uigetfile({'*.mat'}, 'EEGtemplate file (Cpos)');\n load(fullfile(p,f)) \n end\nend\ntry\n Cpos = Cpos(:,D.channels.order(Cs));\ncatch\n Cpos = Cpos(:,D.channels.order(D.channels.eeg));\nend\nxp = Cpos(1,:)';\nyp = Cpos(2,:)';\nx = linspace(min(xp),max(xp),64);\ny = linspace(min(yp),max(yp),64);\n[xm,ym] = meshgrid(x,y);\nhandles.sens_coord = [xp yp];\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% INITIAL SENSOR LEVEL DISPLAY\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfigure(handles.fig)\naxes(handles.sensors_axes);\ncla; axis off\n\nic = 1:length(handles.sens_coord);\ndisp = full(handles.sens_data(ic,1));\nimagesc(x,y,griddata(xp,yp,disp,xm,ym));\naxis image xy off\nhandles.sens_coord_x = x;\nhandles.sens_coord_y = y;\nhandles.sens_coord2D_X = xm;\nhandles.sens_coord2D_Y = ym;\nhold on\nhandles.sensor_loc = plot(handles.sens_coord(:,1),handles.sens_coord(:,2),'o','MarkerFaceColor',[1 1 1]/2,'MarkerSize',6);\nset(handles.checkbox_sensloc,'Value',1);\nhold off\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% INITIAL SENSOR LEVEL DISPLAY - PREDICTED\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naxes(handles.pred_axes); cla;\ndisp = full(handles.pred_data(ic,1));\nimagesc(x,y,griddata(xp,yp,disp,xm,ym));\naxis image xy off\ndrawnow\n\nguidata(hObject,handles);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% UPDATE SOURCE LEVEL DISPLAY\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction UpDate_Display_SRCS(hObject,handles)\naxes(handles.sources_axes);\n\nif isfield(handles,'fig1')\n ActToDisp = get(handles.Activity,'Value');\n A = get(handles.checkbox_absv,'Value');\n N = get(handles.checkbox_norm,'Value');\n switch ActToDisp\n \n % case 1: response (J)\n %------------------------------------------------------------------\n case 1\n TS = fix(get(handles.slider_time,'Value')); \n if A\n srcs_disp = abs(handles.srcs_data(:,TS));\n else\n srcs_disp = handles.srcs_data(:,TS);\n end\n if N\n if A\n handles.Vmin = 0;\n handles.Vmax = handles.Nmax;\n else\n handles.Vmin = -handles.Nmax;\n handles.Vmax = handles.Nmax;\n end\n else\n handles.Vmin = min(srcs_disp);\n handles.Vmax = max(srcs_disp);\n end\n\n \n % case 2: Windowed response (JW)\n %------------------------------------------------------------------\n case 2\n handles.Vmin = min(handles.srcs_data_w);\n handles.Vmax = max(handles.srcs_data_w);\n srcs_disp = handles.srcs_data_w;\n\n % case 3: Evoked power (JWWJ)\n %------------------------------------------------------------------\n case 3\n handles.Vmin = min(handles.srcs_data_ev);\n handles.Vmax = max(handles.srcs_data_ev);\n srcs_disp = handles.srcs_data_ev;\n\n % case 4: Induced power (JWWJ)\n %------------------------------------------------------------------\n case 4\n handles.Vmin = min(handles.srcs_data_ind);\n handles.Vmax = max(handles.srcs_data_ind);\n srcs_disp = handles.srcs_data_ind;\n end\n set(handles.fig1,'FaceVertexCData',full(srcs_disp));\n set(handles.sources_axes,'CLim',[handles.Vmin handles.Vmax]);\n set(handles.sources_axes,'CLimMode','manual');\n \nend\n\n% Adjust the threshold\n%--------------------------------------------------------------------------\nSet_colormap(hObject, [], handles);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% UPDATE SENSOR LEVEL DISPLAY\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction UpDate_Display_SENS(hObject,handles)\nTypOfDisp = get(handles.sens_display,'Value');\nActToDisp = get(handles.Activity,'Value');\nic = 1:length(handles.sens_coord);\n\n\n% topography\n%--------------------------------------------------------------------------\nif TypOfDisp == 1\n\n % responses at one pst\n %----------------------------------------------------------------------\n if ActToDisp == 1\n\n TS = fix(get(handles.slider_time,'Value'));\n sens_disp = handles.sens_data(ic,TS);\n pred_disp = handles.pred_data(ic,TS);\n \n % contrast\n %----------------------------------------------------------------------\n elseif ActToDisp == 2\n \n sens_disp = handles.sens_data_w;\n pred_disp = handles.pred_data_w;\n\n % power\n %----------------------------------------------------------------------\n elseif ActToDisp == 3\n sens_disp = handles.sens_data_ev;\n pred_disp = handles.pred_data_ev;\n end\n \n axes(handles.sensors_axes); cla\n disp = griddata(handles.sens_coord(:,1),handles.sens_coord(:,2),full(sens_disp),handles.sens_coord2D_X,handles.sens_coord2D_Y);\n imagesc(handles.sens_coord_x,handles.sens_coord_y,disp);\n axis image xy off\n\n axes(handles.pred_axes); cla\n disp = griddata(handles.sens_coord(:,1),handles.sens_coord(:,2),full(pred_disp),handles.sens_coord2D_X,handles.sens_coord2D_Y);\n imagesc(handles.sens_coord_x,handles.sens_coord_y,disp);\n axis image xy off\n\n % add sensor locations\n %----------------------------------------------------------------------\n axes(handles.sensors_axes)\n try, delete(handles.sensor_loc); end\n hold on\n handles.sensor_loc = plot(handles.sens_coord(:,1),handles.sens_coord(:,2),'o','MarkerFaceColor',[1 1 1]/2,'MarkerSize',6);\n hold off\n\n checkbox_sensloc_Callback(hObject, [], handles);\n \n% time series\n%--------------------------------------------------------------------------\nelseif TypOfDisp == 2\n axes(handles.sensors_axes)\n daspect('auto')\n handles.fig2 = ...\n plot(handles.pst,handles.sens_data,'b-.',handles.pst,handles.pred_data,'r:');\n if ActToDisp > 1\n hold on\n Scal = norm(handles.sens_data,1)/norm(handles.W,1);\n plot(handles.pst,handles.W*Scal,'k')\n hold off\n end\n axis on tight;\n axes(handles.pred_axes); cla, axis off\nend\n\n% Adjust the threshold\n%--------------------------------------------------------------------------\nSet_colormap(hObject, [], handles);\nguidata(hObject,handles);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% LOAD DATA FILE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction DataFile_Callback(hObject, eventdata, handles)\nS = get(handles.DataFile,'String');\ntry\n D = spm_eeg_ldata(S);\ncatch\n LoadData_Callback(hObject, eventdata, handles);\nend\n\n% --- Executes on button press in LoadData.\nfunction LoadData_Callback(hObject, eventdata, handles)\nS = spm_select(1, '.mat', 'Select EEG/MEG mat file');\nhandles.D = spm_eeg_ldata(S);\nspm_eeg_inv_visu3D_api_OpeningFcn(hObject, [], handles);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% ACTIVITY TO DISPLAY\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --- Executes on selection change in Activity.\nfunction Activity_Callback(hObject, eventdata, handles)\nActToDisp = get(handles.Activity,'Value');\nif ActToDisp == 1\n set(handles.checkbox_absv, 'Enable','on');\n set(handles.checkbox_norm, 'Enable','on');\n set(handles.slider_time, 'Enable','on');\n set(handles.time_bin, 'Enable','on');\nelse\n set(handles.checkbox_norm, 'Enable','off');\n set(handles.slider_time, 'Enable','off');\n set(handles.time_bin, 'Enable','off');\nend\nif ActToDisp == 2\n set(handles.checkbox_absv, 'Enable','off');\nend\n\n% update displays\n%--------------------------------------------------------------------------\nUpDate_Display_SRCS(hObject,handles);\nUpDate_Display_SENS(hObject,handles);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SWITCH FROM TEMPLATE MESH TO INDIVIDUAL MESH AND BACK\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Individual_Callback(hObject, eventdata, handles)\nset(handles.Template,'Value',0);\ntry\n handles.vert = handles.D.inv{handles.D.val}.mesh.tess_ctx.vert;\n set(handles.Template, 'Value',0);\n set(handles.Individual,'Value',1);\nend\nhandles.grayc = sqrt(sum((handles.vert.^2)')); handles.grayc = handles.grayc'/max(handles.grayc);\nset(handles.fig1,'vertices',handles.vert,'faces',handles.face);\nUpDate_Display_SRCS(hObject,handles);\naxes(handles.sources_axes);\naxis image;\nguidata(hObject,handles);\n\n%--------------------------------------------------------------------------\nfunction Template_Callback(hObject, eventdata, handles)\nset(handles.Individual,'Value',0);\ntry\n handles.vert = handles.D.inv{handles.D.val}.mesh.tess_mni.vert;\n set(handles.Template, 'Value',1);\n set(handles.Individual,'Value',0);\nend\nhandles.grayc = sqrt(sum((handles.vert.^2)')); handles.grayc = handles.grayc'/max(handles.grayc);\nset(handles.fig1,'vertices',handles.vert,'faces',handles.face);\nUpDate_Display_SRCS(hObject,handles);\naxes(handles.sources_axes);\naxis image;\nguidata(hObject,handles);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% THRESHOLD SLIDERS - SOURCE LEVEL\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% upper threshold\n% --- Executes on slider movement.\nfunction slider_srcs_up_Callback(hObject, eventdata, handles)\nSet_colormap(hObject, eventdata, handles);\n\n%%% lower threshold\n% --- Executes on slider movement.\nfunction slider_srcs_down_Callback(hObject, eventdata, handles)\nSet_colormap(hObject, eventdata, handles);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% TRANSPARENCY SLIDER\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --- Executes on slider movement.\nfunction slider_transparency_Callback(hObject, eventdata, handles)\nTransparency = get(hObject,'Value');\nset(handles.fig1,'facealpha',Transparency);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% NORMALISE VALUES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --- Executes on button press in checkbox_norm.\nfunction checkbox_norm_Callback(hObject, eventdata, handles)\nUpDate_Display_SRCS(hObject,handles);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% USE ABSOLUTE VALUES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --- Executes on button press in checkbox_absv.\nfunction checkbox_absv_Callback(hObject, eventdata, handles)\nUpDate_Display_SRCS(hObject,handles);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DISPLAY SENSOR LOCATIONS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --- Executes on button press in checkbox_sensloc.\nfunction checkbox_sensloc_Callback(hObject, eventdata, handles)\ntry\n if get(handles.checkbox_sensloc,'Value')\n set(handles.sensor_loc,'Visible','on');\n else\n set(handles.sensor_loc,'Visible','off');\n end\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% TIME SLIDER - SOURCE & SENSOR LEVEL\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --- Executes on slider movement.\nfunction slider_time_Callback(hObject, eventdata, handles)\nST = fix(handles.pst(fix(get(hObject,'Value'))));\nset(handles.time_bin,'String',num2str(ST));\n\n% Source and sensor space update\n%--------------------------------------------------------------------------\nUpDate_Display_SRCS(hObject,handles);\nUpDate_Display_SENS(hObject,handles);\n\n% --- Callback function\nfunction time_bin_Callback(hObject, eventdata, handles)\n[i ST] = min(abs(handles.pst - str2double(get(hObject,'String'))));\nset(handles.slider_time,'Value',fix(ST));\n\n% Source and sensor space update\n%--------------------------------------------------------------------------\nUpDate_Display_SRCS(hObject,handles);\nUpDate_Display_SENS(hObject,handles);\n\n% --- Executes on button press in movie.\n%--------------------------------------------------------------------------\nfunction movie_Callback(hObject, eventdata, handles)\nglobal MOVIE\nfor t = 1:length(handles.pst)\n set(handles.slider_time,'Value',t);\n ST = fix(handles.pst(t));\n set(handles.time_bin,'String',num2str(ST));\n UpDate_Display_SRCS(hObject,handles);\n \n % record movie if requested\n %----------------------------------------------------------------------\n if MOVIE, M(t) = getframe(handles.sources_axes); end;\nend\nUpDate_Display_SENS(hObject,handles);\ntry\n filename = fullfile(handles.D.path,'SourceMovie');\n movie2avi(M,filename,'compression','Indeo3','FPS',24)\nend\n\n\n\n% --- Executes on button press in movie_sens.\n%--------------------------------------------------------------------------\nfunction movie_sens_Callback(hObject, eventdata, handles)\nglobal MOVIE\nfor t = 1:length(handles.pst)\n set(handles.slider_time,'Value',t);\n ST = fix(handles.pst(t));\n set(handles.time_bin,'String',num2str(ST));\n UpDate_Display_SENS(hObject,handles);\n \n % record movie if requested\n %----------------------------------------------------------------------\n if MOVIE, M(t) = getframe(handles.sensors_axes); end;\n \nend\nUpDate_Display_SRCS(hObject,handles);\ntry\n filename = fullfile(handles.D.path,'SensorMovie');\n movie2avi(M,filename,'compression','Indeo3','FPS',24)\nend\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% TYPE OF SENSOR LEVEL DISPLAY\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% --- Executes on selection change in sens_display.\nfunction sens_display_Callback(hObject, eventdata, handles)\nTypOfDisp = get(handles.sens_display,'Value');\n\n% if time series\n%--------------------------------------------------------------------------\nif TypOfDisp == 2\n set(handles.checkbox_sensloc,'Value',0);\n set(handles.checkbox_sensloc,'Enable','off');\nelse\n set(handles.checkbox_sensloc,'Value',1);\n set(handles.checkbox_sensloc,'Enable','on');\nend\nUpDate_Display_SENS(hObject,handles);\n\n\n% --- Executes on button press in Exit.\n%--------------------------------------------------------------------------\nfunction Exit_Callback(hObject, eventdata, handles)\nspm_eeg_inv_visu3D_api_OutputFcn(hObject, eventdata, handles);\nclose(handles.fig);\n\n\n% --- Executes on button press in Mip.\n%--------------------------------------------------------------------------\nfunction Mip_Callback(hObject, eventdata, handles)\nActToDisp = get(handles.Activity,'Value');\nif get(handles.Activity,'Value') == 1\n PST = str2num(get(handles.time_bin,'String'));\n spm_eeg_invert_display(handles.D,PST);\nelse\n spm_eeg_inv_results_display(handles.D);\nend\n\n% --- Outputs from this function are returned to the command line.\n%--------------------------------------------------------------------------\nfunction varargout = spm_eeg_inv_visu3D_api_OutputFcn(hObject, eventdata, handles)\nD = handles.D;\nif nargout == 1\n varargout{1} = D;\nend\n\n\n% --- rest threshold\n%--------------------------------------------------------------------------\nfunction Set_colormap(hObject, eventdata, handles)\nNewMap = jet;\n\n% unsigned values\n%--------------------------------------------------------------------------\nif get(handles.checkbox_absv,'Value') || get(handles.Activity,'Value') == 3\n \n UpTh = get(handles.slider_srcs_up, 'Value');\n N = length(NewMap);\n Low = fix(N*UpTh);\n Hig = fix(N - N*UpTh);\n i = [ones(Low,1); [1:Hig]'*N/Hig];\n NewMap = NewMap(fix(i),:);\n \n% signed values\n%--------------------------------------------------------------------------\nelse\n\n UpTh = get(handles.slider_srcs_up, 'Value');\n DoTh = 1 - get(handles.slider_srcs_down,'Value');\n N = length(NewMap)/2;\n Low = fix(N - N*DoTh);\n Hig = fix(N - N*UpTh);\n i = [[1:Low]'*N/Low; ones(N + N - Hig - Low,1)*N; [1:Hig]'*N/Hig + N];\n NewMap = NewMap(fix(i),:);\n\nend\ncolormap(NewMap);\ndrawnow\n\n\n% --- Executes on button press in next.\n%--------------------------------------------------------------------------\nfunction next_Callback(hObject, eventdata, handles)\nif length(handles.D.inv) == 1\n set(handles.next,'Value',0);\n return\nend\nhandles.D.val = handles.D.val + 1;\nhandles.D.con = 1;\nif handles.D.val > length(handles.D.inv)\n handles.D.val = 1;\nend\nset(handles.next,'String',sprintf('model %d',handles.D.val),'Value',0);\nspm_eeg_inv_visu3D_api_OpeningFcn(hObject, eventdata, handles)\n\n% --- Executes on button press in previous.\n%--------------------------------------------------------------------------\nfunction con_Callback(hObject, eventdata, handles)\nif length(handles.D.inv{handles.D.val}.inverse.J) == 1\n set(handles.con,'Value',0);\n return\nend\nhandles.D.con = handles.D.con + 1;\nif handles.D.con > length(handles.D.inv{handles.D.val}.inverse.J)\n handles.D.con = 1;\nend\nset(handles.con,'String',sprintf('condition %d',handles.D.con),'Value',0);\nspm_eeg_inv_visu3D_api_OpeningFcn(hObject, eventdata, handles)\n\n \n% --- Executes on button press in VDE.\n%--------------------------------------------------------------------------\nfunction Velec_Callback(hObject, eventdata, handles)\naxes(handles.sources_axes);\ntry\n vde = getCursorInfo(handles.location);\ncatch\n vde = [];\nend\nif ~length(vde)\n handles.location = datacursormode(handles.fig);\n set(handles.location,'Enable','on','DisplayStyle','datatip','SnapToDataVertex','on');\n waitforbuttonpress\n datacursormode off\nend\nvde = getCursorInfo(handles.location);\nspm_eeg_invert_display(handles.D,vde.Position)\nguidata(hObject,handles);\n\n\n% --- Executes on button press in Rot.\nfunction Rot_Callback(hObject, eventdata, handles)\n%--------------------------------------------------------------------------\nrotate3d(handles.sources_axes)\nreturn\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_load.m", "ext": ".m", "path": "spm5-master/spm_load.m", "size": 1192, "source_encoding": "utf_8", "md5": "dd89d9c3959f433fc4eefb539b6c1560", "text": "function [x] = spm_load(f)\n% function to load ascii file data as matrix\n% FORMAT [x] = spm_load(f)\n% f - file {ascii file containing a regular array of numbers\n% x - corresponding data matrix\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Karl Friston\n% $Id: spm_load.m 184 2005-05-31 13:23:32Z john $\n\n\n\n%-Get a filename if none was passed\n%-----------------------------------------------------------------------\nx = [];\nif nargin == 0\n [f,p] = uigetfile({'*.mat';'*.txt';'*.dat'});\n try\n f = fullfile(p,f);\n end\nend\n\n%-Load the data file into double precision matrix x\n%-----------------------------------------------------------------------\ntry\n x = load(f,'-ascii');\n return\nend\ntry\n x = load(f,'-mat');\n x = getdata(x);\nend\n\nif ~isnumeric(x), x = []; end\n\nfunction x = getdata(s)\n% get numberic data x from the fields of structure s\n%--------------------------------------------------------------------------\nx = [];\nf = fieldnames(s);\nfor i = 1:length(f)\n x = s.(f{i});\n if isnumeric(x),return; end\n if isstruct(x), x = getdata(x); end\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_norm.m", "ext": ".m", "path": "spm5-master/spm_config_norm.m", "size": 20935, "source_encoding": "utf_8", "md5": "b8b78e7c46191b433681134e138b9c25", "text": "function opts = spm_config_norm\n% Configuration file for normalise jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_norm.m 1032 2007-12-20 14:45:55Z john $\n\n\n%_______________________________________________________________________\n \n\nsmosrc.type = 'entry';\nsmosrc.name = 'Source Image Smoothing';\nsmosrc.tag = 'smosrc';\nsmosrc.strtype = 'e';\nsmosrc.num = [1 1];\nsmosrc.def = 'normalise.estimate.smosrc';\nsmosrc.help = {[...\n'Smoothing to apply to a copy of the source image. ',...\n'The template and source images should have approximately ',...\n'the same smoothness. Remember that the templates supplied ',...\n'with SPM have been smoothed by 8mm, and that smoothnesses ',...\n'combine by Pythagoras'' rule.']};\n\n%------------------------------------------------------------------------\n\nsmoref.type = 'entry';\nsmoref.name = 'Template Image Smoothing';\nsmoref.tag = 'smoref';\nsmoref.strtype = 'e';\nsmoref.num = [1 1];\nsmoref.def = 'normalise.estimate.smoref';\nsmoref.help = {[...\n'Smoothing to apply to a copy of the template image. ',...\n'The template and source images should have approximately ',...\n'the same smoothness. Remember that the templates supplied ',...\n'with SPM have been smoothed by 8mm, and that smoothnesses ',...\n'combine by Pythagoras'' rule.']};\n\n%------------------------------------------------------------------------\n \nregtype.type = 'menu';\nregtype.name = 'Affine Regularisation';\nregtype.tag = 'regtype';\nregtype.labels = {'ICBM space template', 'Average sized template','No regularisation'};\nregtype.values = {'mni','subj','none'};\nregtype.def = 'normalise.estimate.regtype';\nregtype.help = {[...\n'Affine registration into a standard space can be made more robust by ',...\n'regularisation (penalising excessive stretching or shrinking). The ',...\n'best solutions can be obtained by knowing the approximate amount of ',...\n'stretching that is needed (e.g. ICBM templates are slightly bigger ',...\n'than typical brains, so greater zooms are likely to be needed). ',...\n'If registering to an image in ICBM/MNI space, then choose the first ',...\n'option. If registering to a template that is close in size, then ',...\n'select the second option. If you do not want to regularise, then ',...\n'choose the third.']};\n \n%------------------------------------------------------------------------\n\ntemplate.type = 'files';\ntemplate.name = 'Template Image';\ntemplate.tag = 'template';\ntemplate.filter = 'image';\ntemplate.num = [1 Inf];\ntemplate.help = {[...\n'Specify a template image to match the source image with. ',...\n'The contrast in the template must be similar to that of the ',...\n'source image in order to achieve a good registration. It is ',...\n'also possible to select more than one template, in which case ',...\n'the registration algorithm will try to find the best linear ',...\n'combination of these images in order to best model the intensities ',...\n'in the source image.']};\n%------------------------------------------------------------------------\n\nweight.type = 'files';\nweight.name = 'Template Weighting Image';\nweight.tag = 'weight';\nweight.filter = 'image';\nweight.num = [0 1];\nweight.def = 'normalise.estimate.weight';\np1 = [...\n'Applies a weighting mask to the template(s) during the parameter ',...\n'estimation. With the default brain mask, weights in and around the ',...\n'brain have values of one whereas those clearly outside the brain are ',...\n'zero. This is an attempt to base the normalisation purely upon ',...\n'the shape of the brain, rather than the shape of the head (since ',...\n'low frequency basis functions can not really cope with variations ',...\n'in skull thickness).'];\np2 = [...\n'The option is now available for a user specified weighting image. ',...\n'This should have the same dimensions and mat file as the template ',...\n'images, with values in the range of zero to one.'];\nweight.help = {p1,'',p2};\n \n%------------------------------------------------------------------------\n\ncutoff.type = 'entry';\ncutoff.name = 'Nonlinear Frequency Cutoff';\ncutoff.tag = 'cutoff';\ncutoff.strtype = 'e';\ncutoff.num = [1 1];\ncutoff.def = 'normalise.estimate.cutoff';\ncutoff.help = {[...\n'Cutoff of DCT bases. Only DCT bases of periods longer than the ',...\n'cutoff are used to describe the warps. The number used will ',...\n'depend on the cutoff and the field of view of the template image(s).']};\n\n%------------------------------------------------------------------------\n\nnits.type = 'entry';\nnits.name = 'Nonlinear Iterations';\nnits.tag = 'nits';\nnits.strtype = 'w';\nnits.num = [1 1];\nnits.def = 'normalise.estimate.nits';\nnits.help = {'Number of iterations of nonlinear warping performed.'};\n\n%------------------------------------------------------------------------\n\nreg.type = 'entry';\nreg.name = 'Nonlinear Regularisation';\nreg.tag = 'reg';\nreg.strtype = 'e';\nreg.num = [1 1];\nreg.def = 'normalise.estimate.reg';\nreg.help = {[...\n'The amount of regularisation for the nonlinear part of the spatial ',...\n'normalisation. ',...\n'Pick a value around one. However, if your normalised images appear ',...\n'distorted, then it may be an idea to increase the amount of ',...\n'regularisation (by an order of magnitude) - or even just use an affine ',...\n'normalisation. ',...\n'The regularisation influences the smoothness of the deformation ',...\n'fields.']};\n\n%------------------------------------------------------------------------\n\nwtsrc.type = 'files';\nwtsrc.name = 'Source Weighting Image';\nwtsrc.tag = 'wtsrc';\nwtsrc.filter = 'image';\nwtsrc.num = [0 1];\nwtsrc.val = {{}};\nwtsrc.help = {[...\n'Optional weighting images (consisting of pixel ',...\n'values between the range of zero to one) to be used for registering ',...\n'abnormal or lesioned brains. These images should match the dimensions ',...\n'of the image from which the parameters are estimated, and should contain ',...\n'zeros corresponding to regions of abnormal tissue.']};\n\n%------------------------------------------------------------------------\n\neoptions.type = 'branch';\neoptions.name = 'Estimation Options';\neoptions.tag = 'eoptions';\neoptions.val = {template,weight,smosrc,smoref,regtype,cutoff,nits,reg};\neoptions.help = {'Various settings for estimating warps.'};\n\n%------------------------------------------------------------------------\n\npreserve.type = 'menu';\npreserve.name = 'Preserve';\npreserve.tag = 'preserve';\npreserve.labels = {'Preserve Concentrations','Preserve Amount'};\npreserve.values = {0,1};\npreserve.def = 'normalise.write.preserve';\np1 = ['Preserve Concentrations: ',...\n'Spatially normalised images are not \"modulated\". The warped images ',...\n'preserve the intensities of the original images.'];\np2 = ['Preserve Total: ',...\n'Spatially normalised images are \"modulated\" in order to preserve the ',...\n'total amount of signal in the images. Areas that are expanded during ',...\n'warping are correspondingly reduced in intensity.'];\npreserve.help = {p1,'',p2};\n\n%------------------------------------------------------------------------\n\nbb.type = 'entry';\nbb.name = 'Bounding box';\nbb.tag = 'bb';\nbb.num = [2 3];\nbb.strtype = 'e';\nbb.def = 'normalise.write.bb';\nbb.help = {[...\n'The bounding box (in mm) of the volume which is to be written ',...\n'(relative to the anterior commissure).']};\n\n%------------------------------------------------------------------------\n\nvox.type = 'entry';\nvox.name = 'Voxel sizes';\nvox.tag = 'vox';\nvox.num = [1 3];\nvox.strtype = 'e';\nvox.def = 'normalise.write.vox';\nvox.help = {'The voxel sizes (x, y & z, in mm) of the written normalised images.'};\n\n%------------------------------------------------------------------------\n\ninterp.type = 'menu';\ninterp.name = 'Interpolation';\ninterp.tag = 'interp';\ninterp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-spline',...\n'3rd Degree B-Spline ','4th Degree B-Spline ','5th Degree B-Spline',...\n'6th Degree B-Spline','7th Degree B-Spline'};\ninterp.values = {0,1,2,3,4,5,6,7};\ninterp.def = 'normalise.write.interp';\ninterp.help = {...\n['The method by which the images are sampled when being written in a ',...\n'different space.'],...\n[' Nearest Neighbour: ',...\n' - Fastest, but not normally recommended.'],...\n[' Bilinear Interpolation: ',...\n' - OK for PET, or realigned fMRI.'],...\n[' B-spline Interpolation: ',...\n' - Better quality (but slower) interpolation/* \\cite{thevenaz00a}*/, especially ',...\n' with higher degree splines. Do not use B-splines when ',...\n' there is any region of NaN or Inf in the images. '],...\n};\n\n%------------------------------------------------------------------------\n\nwrap.type = 'menu';\nwrap.name = 'Wrapping';\nwrap.tag = 'wrap';\nwrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z',...\n'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'};\nwrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]};\nwrap.def = 'normalise.write.wrap';\nwrap.help = {...\n'These are typically:',...\n[' No wrapping: for PET or images that have already ',...\n' been spatially transformed. '],...\n[' Wrap in Y: for (un-resliced) MRI where phase encoding ',...\n' is in the Y direction (voxel space).']};\n\n%------------------------------------------------------------------------\n\nroptions.type = 'branch';\nroptions.name = 'Writing Options';\nroptions.tag = 'roptions';\nroptions.val = {preserve,bb,vox,interp,wrap};\nroptions.help = {'Various options for writing normalised images.'};\n\n%------------------------------------------------------------------------\n\nsource.type = 'files';\nsource.name = 'Source Image';\nsource.tag = 'source';\nsource.num = [1 1];\nsource.filter = 'image';\nsource.help = {[...\n'The image that is warped to match the template(s). The result is ',...\n'a set of warps, which can be applied to this image, or any other ',...\n'image that is in register with it.']};\n\nscansr.type = 'files';\nscansr.name = 'Images to Write';\nscansr.tag = 'resample';\nscansr.num = [1 Inf];\nscansr.filter = 'image';\nscansr.help = {[...\n'These are the images for warping according to the estimated parameters. ',...\n'They can be any images that are in register with the \"source\" image used ',...\n'to generate the parameters.']};\n\nmatname.type = 'files';\nmatname.name = 'Parameter File';\nmatname.tag = 'matname';\nmatname.num = [1 1];\nmatname.filter = 'mat';\nmatname.ufilter = '.*_sn\\.mat$';\nmatname.help = {[...\n'Select the ''_sn.mat'' file containing the spatial normalisation ',...\n'parameters for that subject.']};\n\n%------------------------------------------------------------------------\n\nsubj.type = 'branch';\nsubj.name = 'Subject';\nsubj.tag = 'subj';\nsubj.val = {source, wtsrc};\nsubj.help = {'Data for this subject. The same parameters are used within subject.'};\n\ndata.type = 'repeat';\ndata.name = 'Data';\ndata.values = {subj};\ndata.num = [1 Inf];\ndata.help = {'List of subjects. Images of each subject should be warped differently.'};\n\nest.type = 'branch';\nest.name = 'Normalise: Estimate';\nest.tag = 'est';\nest.val = {data,eoptions};\nest.prog = @estimate;\nest.vfiles = @vfiles_estimate;\nest.help = {[...\n'Computes the warp that best registers a source image (or series of ',...\n'source images) to match ',...\n'a template, saving it to a file imagename''_sn.mat''.']};\n\n%------------------------------------------------------------------------\n\nsubj.type = 'branch';\nsubj.name = 'Subject';\nsubj.tag = 'subj';\nsubj.val = {matname,scansr};\nsubj.help = {'Data for this subject. The same parameters are used within subject.'};\n\ndata.type = 'repeat';\ndata.name = 'Data';\ndata.values = {subj};\ndata.num = [1 Inf];\ndata.help = {'List of subjects. Images of each subject should be warped differently.'};\n\nwrit.type = 'branch';\nwrit.name = 'Normalise: Write';\nwrit.tag = 'write';\nwrit.val = {data,roptions};\nwrit.prog = @write;\nwrit.vfiles = @vfiles_write;\nwrit.help = {[...\n'Allows previously estimated warps (stored in imagename''_sn.mat'' files) ',...\n'to be applied to series of images.']};\n\n%------------------------------------------------------------------------\n\nsubj.type = 'branch';\nsubj.name = 'Subject';\nsubj.tag = 'subj';\nsubj.val = {source, wtsrc, scansr};\nsubj.help = {'Data for this subject. The same parameters are used within subject.'};\n\ndata.type = 'repeat';\ndata.name = 'Data';\ndata.values = {subj};\ndata.num = [1 Inf];\ndata.help = {'List of subjects. Images of each subject should be warped differently.'};\n\nestwrit.type = 'branch';\nestwrit.name = 'Normalise: Estimate & Write';\nestwrit.tag = 'estwrite';\nestwrit.val = {data,eoptions,roptions};\nestwrit.prog = @estwrite;\nestwrit.vfiles = @vfiles_estwrite;\nestwrit.help = {[...\n'Computes the warp that best registers a source image (or series of ',...\n'source images) to match ',...\n'a template, saving it to the file imagename''_sn.mat''. ',...\n'This option also allows the contents of the imagename''_sn.mat'' ',...\n'files to be applied to a series of images.']};\n\n%------------------------------------------------------------------------\n\nopts.type = 'repeat';\nopts.name = 'Normalise';\nopts.tag = 'normalise';\nopts.values = {est,writ,estwrit};\nopts.num = [1 Inf];\nopts.modality = {'FMRI','PET','VBM'};\np1 = [...\n'This module spatially (stereotactically) normalises MRI, PET or SPECT ',...\n'images into a standard space defined by some ideal model or template ',...\n'image[s]. The template images supplied with SPM conform to the space ',...\n'defined by the ICBM, NIH P-20 project, and approximate that of the ',...\n'the space described in the atlas of Talairach and Tournoux (1988). ',...\n'The transformation can also be applied to any other image that has ',...\n'been coregistered with these scans.'];\np2 = [...\n'Generally, the algorithms work by minimising the sum of squares ',...\n'difference between the image which is to be normalised, and a linear ',...\n'combination of one or more template images. For the least squares ',...\n'registration to produce an unbiased estimate of the spatial ',...\n'transformation, the image contrast in the templates (or linear ',...\n'combination of templates) should be similar to that of the image from ',...\n'which the spatial normalisation is derived. The registration simply ',...\n'searches for an optimum solution. If the starting estimates are not ',...\n'good, then the optimum it finds may not find the global optimum.'];\np3 = [...\n'The first step of the normalisation is to determine the optimum ',...\n'12-parameter affine transformation. Initially, the registration is ',...\n'performed by matching the whole of the head (including the scalp) to ',...\n'the template. Following this, the registration proceeded by only ',...\n'matching the brains together, by appropriate weighting of the template ',...\n'voxels. This is a completely automated procedure (that does not ',...\n'require ``scalp editing'') that discounts the confounding effects of ',...\n'skull and scalp differences. A Bayesian framework is used, such that ',...\n'the registration searches for the solution that maximises the a ',...\n'posteriori probability of it being correct /* \\cite{ashburner97b} */. i.e., it maximises the ',...\n'product of the likelihood function (derived from the residual squared ',...\n'difference) and the prior function (which is based on the probability ',...\n'of obtaining a particular set of zooms and shears).'];\np4 = [...\n'The affine registration is followed by estimating nonlinear deformations, ',...\n'whereby the deformations are defined by a linear combination of three ',...\n'dimensional discrete cosine transform (DCT) basis functions /* \\cite{ashburner99a} */. The default ',...\n'options result in each of the deformation fields being described by 1176',...\n'parameters, where these represent the coefficients of the deformations in ',...\n'three orthogonal directions. The matching involved simultaneously ',...\n'minimising the membrane energies of the deformation fields and the ',...\n'residual squared difference between the images and template(s).'];\np5 = [...\n'The primarily use is for stereotactic normalisation to facilitate inter-subject ',...\n'averaging and precise characterisation of functional anatomy /* \\cite{ashburner97bir} */. It is ',...\n'not necessary to spatially normalise the data (this is only a ',...\n'pre-requisite for inter-subject averaging or reporting in the ',...\n'Talairach space). If you wish to circumnavigate this step (e.g. if ',...\n'you have single slice data or do not have an appropriate high ',...\n'resolution MRI scan) simply specify where you think the anterior ',...\n'commissure is with the ORIGIN in the header of the first scan ',...\n'(using the ''Display'' facility) and proceed directly to ''Smoothing''',...\n'or ''Statistics''.'];\np6 = [...\n'All normalised *.img scans are written to the same subdirectory as ',...\n'the original *.img, prefixed with a ''w'' (i.e. w*.img). The details ',...\n'of the transformations are displayed in the results window, and the ',...\n'parameters are saved in the \"*_sn.mat\" file.'];\nopts.help = {p1,'',...\np2,'',p3,'',p4,'',...\np5,'',...\np6};\n%------------------------------------------------------------------------\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction estimate(varargin)\njob = varargin{1};\no = job.eoptions;\neflags = struct(...\n\t'smosrc', o.smosrc,...\n\t'smoref', o.smoref,...\n\t'regtype',o.regtype,...\n\t'cutoff', o.cutoff,...\n\t'nits', o.nits,...\n\t'reg', o.reg);\n\nfor i=1:length(job.subj),\n\t[pth,nam,ext,ind] = spm_fileparts(strvcat(job.subj(i).source{:}));\n\tmatname = fullfile(pth,[nam '_sn.mat']);\n\tspm_normalise(strvcat(job.eoptions.template{:}),...\n\t\tstrvcat(job.subj(i).source{:}), matname,...\n\t\tstrvcat(job.eoptions.weight{:}), strvcat(job.subj(i).wtsrc{:}), eflags);\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction write(varargin)\njob = varargin{1};\no = job.roptions;\nrflags = struct(...\n\t'preserve',o.preserve,...\n\t'bb', o.bb,...\n\t'vox', o.vox,...\n\t'interp', o.interp,...\n\t'wrap', o.wrap);\n\nfor i=1:length(job.subj),\n\tspm_write_sn(strvcat(job.subj(i).resample{:}),...\n\t\tstrvcat(job.subj(i).matname{:}),rflags);\nend;\nreturn;\n%------------------------------------------------------------------------\n \n%------------------------------------------------------------------------\nfunction estwrite(varargin)\njob = varargin{1};\no = job.eoptions;\neflags = struct(...\n\t'smosrc', o.smosrc,...\n\t'smoref', o.smoref,...\n\t'regtype',o.regtype,...\n\t'cutoff', o.cutoff,...\n\t'nits', o.nits,...\n\t'reg', o.reg);\no = job.roptions;\nrflags = struct(...\n\t'preserve',o.preserve,...\n\t'bb', o.bb,...\n\t'vox', o.vox,...\n\t'interp', o.interp,...\n\t'wrap', o.wrap);\n\nfor i=1:length(job.subj),\n [ pth,nam ] = spm_fileparts(deblank(job.subj(i).source{:}));\n matname = fullfile(pth,[nam,'_sn.mat']);\n spm_normalise(strvcat(job.eoptions.template{:}),...\n strvcat(job.subj(i).source{:}), matname,...\n strvcat(job.eoptions.weight{:}), strvcat(job.subj(i).wtsrc{:}), eflags);\n spm_write_sn(strvcat(job.subj(i).resample{:}), matname, rflags);\nend;\nreturn;\n%------------------------------------------------------------------------\n \n%------------------------------------------------------------------------\nfunction vf = vfiles_estimate(varargin)\njob = varargin{1};\nvf = cell(length(job.subj),1);\nfor i=1:length(job.subj),\n [pth,nam,ext,num] = spm_fileparts(deblank(job.subj(i).source{:}));\n vf{i} = fullfile(pth,[nam,'_sn.mat']);\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction vf = vfiles_estwrite(varargin)\njob = varargin{1};\nvf = cell(length(job.subj),1);\nfor i=1:length(job.subj),\n [pth,nam,ext,num] = spm_fileparts(deblank(job.subj(i).source{:}));\n vf{i} = fullfile(pth,[nam,'_sn.mat']);\nend;\nfor i=1:length(job.subj),\n res = job.subj(i).resample;\n vf1 = cell(1,length(res));\n for j=1:length(res),\n [pth,nam,ext,num] = spm_fileparts(res{j});\n vf1{j} = fullfile(pth,['w', nam, ext, num]);\n end;\n vf = {vf{:} vf1{:}};\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction vf = vfiles_write(varargin)\njob = varargin{1};\nvf = {};\nfor i=1:length(job.subj),\n res = job.subj(i).resample;\n vf1 = cell(1,length(res));\n for j=1:length(res),\n [pth,nam,ext,num] = spm_fileparts(res{j});\n vf1{j} = fullfile(pth,['w', nam, ext, num]);\n end;\n vf = {vf{:} vf1{:}};\nend;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_reslice.m", "ext": ".m", "path": "spm5-master/spm_reslice.m", "size": 14569, "source_encoding": "utf_8", "md5": "6fed692ad7fdef9eb860ab513323f73d", "text": "function spm_reslice(P,flags)\n% Rigid body reslicing of images\n% FORMAT spm_reslice(P,flags)\n%\n% P - matrix of filenames {one string per row}\n% All operations are performed relative to the first image.\n% ie. Coregistration is to the first image, and resampling\n% of images is into the space of the first image.\n%\n% flags - a structure containing various options. The fields are:\n%\n% mask - mask output images (1 for yes, 0 for no)\n% To avoid artifactual movement-related variance the realigned\n% set of images can be internally masked, within the set (i.e.\n% if any image has a zero value at a voxel than all images have\n% zero values at that voxel). Zero values occur when regions\n% 'outside' the image are moved 'inside' the image during\n% realignment.\n%\n% mean - write mean image (1 for yes, 0 for no)\n% The average of all the realigned scans is written to\n% mean*.img.\n%\n% interp - the B-spline interpolation method. \n% Non-finite values result in Fourier interpolation. Note that\n% Fourier interpolation only works for purely rigid body\n% transformations. Voxel sizes must all be identical and\n% isotropic.\n%\n% which - Values of 0, 1 or 2 are allowed.\n% 0 - don't create any resliced images.\n% Useful if you only want a mean resliced image.\n% 1 - don't reslice the first image.\n% The first image is not actually moved, so it may not be\n% necessary to resample it.\n% 2 - reslice all the images.\n%\n% The spatially realigned images are written to the orginal\n% subdirectory with the same filename but prefixed with an 'r'.\n% They are all aligned with the first.\n%__________________________________________________________________________\n%\n% Inputs\n% A series of *.img conforming to SPM data format (see 'Data Format'). The \n% relative displacement of the images is stored in their \".mat\" files.\n%\n% Outputs\n% The routine uses information in these \".mat\" files and writes the\n% realigned *.img files to the same subdirectory prefixed with an 'r'\n% (i.e. r*.img).\n%__________________________________________________________________________\n%\n% The `.mat' files.\n%\n% This simply contains a 4x4 affine transformation matrix in a variable `M'.\n% These files are normally generated by the `realignment' and\n% `coregistration' modules. What these matrixes contain is a mapping from\n% the voxel coordinates (x0,y0,z0) (where the first voxel is at coordinate\n% (1,1,1)), to coordinates in millimeters (x1,y1,z1). By default, the\n% the new coordinate system is derived from the `origin' and `vox' fields\n% of the image header.\n% \n% x1 = M(1,1)*x0 + M(1,2)*y0 + M(1,3)*z0 + M(1,4)\n% y1 = M(2,1)*x0 + M(2,2)*y0 + M(2,3)*z0 + M(2,4)\n% z1 = M(3,1)*x0 + M(3,2)*y0 + M(3,3)*z0 + M(3,4)\n%\n% Assuming that image1 has a transformation matrix M1, and image2 has a\n% transformation matrix M2, the mapping from image1 to image2 is: M2\\M1\n% (ie. from the coordinate system of image1 into millimeters, followed\n% by a mapping from millimeters into the space of image2).\n%\n% These `.mat' files allow several realignment or coregistration steps to be\n% combined into a single operation (without the necessity of resampling the\n% images several times). The `.mat' files are also used by the spatial\n% normalisation module.\n%__________________________________________________________________________\n% Refs:\n%\n% Friston KJ, Williams SR, Howard R Frackowiak RSJ and Turner R (1995)\n% Movement-related effect in fMRI time-series. Mag. Res. Med. 35:346-355\n%\n% W. F. Eddy, M. Fitzgerald and D. C. Noll (1996) Improved Image\n% Registration by Using Fourier Interpolation. Mag. Res. Med. 36(6):923-931\n%\n% R. W. Cox and A. Jesmanowicz (1999) Real-Time 3D Image Registration\n% for Functional MRI. Submitted to MRM (April 1999) and avaliable from:\n% http://varda.biophysics.mcw.edu/~cox/index.html.\n%\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_reslice.m 1020 2007-12-06 20:20:31Z john $\n\n\n\ndef_flags = struct('interp',1,'mask',1,'mean',1,'which',2,'wrap',[0 0 0]');\nif nargin < 2,\n\tflags = def_flags;\nelse,\n\tfnms = fieldnames(def_flags);\n\tfor i=1:length(fnms),\n\t\tif ~isfield(flags,fnms{i}),\n\t\t\tflags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));\n\t\tend;\n\tend;\nend;\n\nif iscell(P), P = strvcat(P{:}); end;\nif ischar(P), P = spm_vol(P); end;\nreslice_images(P,flags);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction reslice_images(P,flags)\n% Reslices images volume by volume\n% FORMAT reslice_images(P,flags)\n%\n% P - matrix of image handles from spm_vol.\n% All operations are performed relative to the first image.\n% ie. resampling of images is into the space of the first image.\n%\n% flags - a structure containing various options. The fields are:\n%\n% mask - mask output images (1 for yes, 0 for no)\n% To avoid artifactual movement-related variance the realigned\n% set of images can be internally masked, within the set (i.e.\n% if any image has a zero value at a voxel than all images have\n% zero values at that voxel). Zero values occur when regions\n% 'outside' the image are moved 'inside' the image during\n% realignment.\n%\n% mean - write mean image\n% The average of all the realigned scans is written to\n% mean*.img.\n%\n% interp - the B-spline interpolation method (see spm_bsplinc and spm_bsplins).\n% Non-finite values result in Fourier interpolation\n%\n% which - Values of 0, 1 or 2 are allowed.\n% 0 - don't create any resliced images.\n% Useful if you only want a mean resliced image.\n% 1 - don't reslice the first image.\n% The first image is not actually moved, so it may not be\n% necessary to resample it.\n% 2 - reslice all the images.\n% wrap - three values of either 0 or 1, representing wrapping in each of\n% the dimensions. For fMRI, [1 1 0] would be used. For PET, it would\n% be [0 0 0].\n%\n% The spatially realigned images are written to the orginal\n% subdirectory with the same filename but prefixed with an 'r'.\n% They are all aligned with the first.\n\nif ~isfinite(flags.interp), % Use Fourier method\n\t% Check for non-rigid transformations in the matrixes\n\tfor i=1:prod(size(P)),\n\t\tpp = P(1).mat\\P(i).mat;\n\t\tif any(abs(svd(pp(1:3,1:3))-1)>1e-7),\n\t\t\tfprintf('\\n Zooms or shears appear to be needed');\n\t\t\tfprintf('\\n (probably due to non-isotropic voxels).');\n\t\t\tfprintf('\\n These can not yet be done using the');\n\t\t\tfprintf('\\n Fourier reslicing method. Switching to');\n\t\t\tfprintf('\\n 7th degree B-spline interpolation instead.\\n\\n');\n\t\t\tflags.interp = 7;\n\t\t\tbreak;\n\t\tend;\n\tend;\nend;\n\nif flags.mask | flags.mean,\n\tspm_progress_bar('Init',P(1).dim(3),'Computing available voxels','planes completed');\n\tx1 = repmat((1:P(1).dim(1))',1,P(1).dim(2));\n\tx2 = repmat( 1:P(1).dim(2) ,P(1).dim(1),1);\n\tif flags.mean,\n\t\tCount = zeros(P(1).dim(1:3));\n\t\tIntegral = zeros(P(1).dim(1:3));\n\tend;\n\tif flags.mask, msk = cell(P(1).dim(3),1); end;\n\tfor x3 = 1:P(1).dim(3),\n\t\ttmp = zeros(P(1).dim(1:2));\n\t\tfor i = 1:prod(size(P)),\n\t\t\ttmp = tmp + getmask(inv(P(1).mat\\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap);\n\t\tend;\n\t\tif flags.mask, msk{x3} = find(tmp ~= prod(size(P))); end;\n\t\tif flags.mean, Count(:,:,x3) = tmp; end;\n\t\tspm_progress_bar('Set',x3);\n\tend;\nend;\n\nnread = prod(size(P));\nif ~flags.mean,\n\tif flags.which == 1, nread = nread - 1; end;\n\tif flags.which == 0, nread = 0; end;\nend;\nspm_progress_bar('Init',nread,'Reslicing','volumes completed');\n\ntiny = 5e-2; % From spm_vol_utils.c\n\n[x1,x2] = ndgrid(1:P(1).dim(1),1:P(1).dim(2));\n\nPO = P;\nnread = 0;\nd = [flags.interp*[1 1 1]' flags.wrap(:)];\n\nfor i = 1:prod(size(P)),\n\n\tif (i>1 & flags.which==1) | flags.which==2, write_vol = 1; else, write_vol = 0; end;\n\tif write_vol | flags.mean, read_vol = 1; else read_vol = 0; end;\n\n\tif read_vol,\n\t\tif ~isfinite(flags.interp),\n\t\t\tv = abs(kspace3d(spm_bsplinc(P(i),[0 0 0 ; 0 0 0]'),P(1).mat\\P(i).mat));\n\t\t\tfor x3 = 1:P(1).dim(3),\n\t\t\t\tif flags.mean,\n\t\t\t\t\tIntegral(:,:,x3) = Integral(:,:,x3) + ...\n\t\t\t\t\t\tnan2zero(v(:,:,x3).*getmask(inv(P(1).mat\\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap));\n\t\t\t\tend;\n\t\t\t\tif flags.mask, tmp = v(:,:,x3); tmp(msk{x3}) = NaN; v(:,:,x3) = tmp; end;\n\t\t\tend;\n\t\telse,\n\t\t\tC = spm_bsplinc(P(i), d);\n\t\t\tv = zeros(P(1).dim);\n\t\t\tfor x3 = 1:P(1).dim(3),\n\n\t\t\t\t[tmp,y1,y2,y3] = getmask(inv(P(1).mat\\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap);\n\t\t\t\tv(:,:,x3) = spm_bsplins(C, y1,y2,y3, d);\n\t\t\t\t% v(~tmp) = 0;\n\n\t\t\t\tif flags.mean, Integral(:,:,x3) = Integral(:,:,x3) + nan2zero(v(:,:,x3)); end;\n\n\t\t\t\tif flags.mask, tmp = v(:,:,x3); tmp(msk{x3}) = NaN; v(:,:,x3) = tmp; end;\n\t\t\tend;\n\t\tend;\n\t\tif write_vol,\n\t\t\tVO = P(i);\n\t\t\t[pth,nm,xt,vr] = spm_fileparts(deblank(P(i).fname));\n\t\t\tVO.fname = fullfile(pth,['r' nm xt vr]);\n\t\t\tVO.dim = P(1).dim(1:3);\n\t\t\tVO.dt = P(i).dt;\n\t\t\tVO.pinfo = P(i).pinfo;\n\t\t\tVO.mat = P(1).mat;\n\t\t\tVO.descrip = 'spm - realigned';\n\t\t\tVO = spm_write_vol(VO,v);\n\t\tend;\n\n\t\tnread = nread + 1;\n\tend;\n\tspm_progress_bar('Set',nread);\nend;\n\nif flags.mean\n\t% Write integral image (16 bit signed)\n\t%-----------------------------------------------------------\n\tIntegral = Integral./Count;\n\tPO = P(1);\n\tPO = rmfield(PO,'pinfo');\n\t[pth,nm,xt,vr] = spm_fileparts(deblank(P(1).fname));\n\tPO.fname = fullfile(pth,['mean' nm xt]);\n\tPO.pinfo = [max(max(max(Integral)))/32767 0 0]';\n\tPO.descrip = 'spm - mean image';\n\tPO.dt = [4 spm_platform('bigend')];\n\tspm_write_vol(PO,Integral);\nend\n\nspm_figure('Clear','Interactive');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction v = kspace3d(v,M)\n% 3D rigid body transformation performed as shears in 1D Fourier space.\n% FORMAT v1 = kspace3d(v,M)\n% Inputs:\n% v - the image stored as a 3D array.\n% M - the rigid body transformation matrix.\n% Output:\n% v - the transformed image.\n%\n% The routine is based on the excellent papers:\n% R. W. Cox and A. Jesmanowicz (1999)\n% Real-Time 3D Image Registration for Functional MRI\n% Submitted to MRM (April 1999) and avaliable from:\n% http://varda.biophysics.mcw.edu/~cox/index.html.\n% and:\n% W. F. Eddy, M. Fitzgerald and D. C. Noll (1996)\n% Improved Image Registration by Using Fourier Interpolation\n% Magnetic Resonance in Medicine 36(6):923-931\n%_______________________________________________________________________\n\n[S0,S1,S2,S3] = shear_decomp(M);\n\nd = [size(v) 1 1 1];\ng = 2.^ceil(log2(d));\nif any(g~=d),\n\ttmp = v;\n\tv = zeros(g);\n\tv(1:d(1),1:d(2),1:d(3)) = tmp;\n\tclear tmp;\nend;\n\n% XY-shear\ntmp1 = -sqrt(-1)*2*pi*([0:((g(3)-1)/2) 0 (-g(3)/2+1):-1])/g(3);\nfor j=1:g(2),\n\tt = reshape( exp((j*S3(3,2) + S3(3,1)*(1:g(1)) + S3(3,4)).'*tmp1) ,[g(1) 1 g(3)]);\n\tv(:,j,:) = real(ifft(fft(v(:,j,:),[],3).*t,[],3));\nend;\n\n% XZ-shear\ntmp1 = -sqrt(-1)*2*pi*([0:((g(2)-1)/2) 0 (-g(2)/2+1):-1])/g(2);\nfor k=1:g(3),\n\tt = exp( (k*S2(2,3) + S2(2,1)*(1:g(1)) + S2(2,4)).'*tmp1);\n\tv(:,:,k) = real(ifft(fft(v(:,:,k),[],2).*t,[],2));\nend;\n\n% YZ-shear\ntmp1 = -sqrt(-1)*2*pi*([0:((g(1)-1)/2) 0 (-g(1)/2+1):-1])/g(1);\nfor k=1:g(3),\n\tt = exp( tmp1.'*(k*S1(1,3) + S1(1,2)*(1:g(2)) + S1(1,4)));\n\tv(:,:,k) = real(ifft(fft(v(:,:,k),[],1).*t,[],1));\nend;\n\n% XY-shear\ntmp1 = -sqrt(-1)*2*pi*([0:((g(3)-1)/2) 0 (-g(3)/2+1):-1])/g(3);\nfor j=1:g(2),\n\tt = reshape( exp( (j*S0(3,2) + S0(3,1)*(1:g(1)) + S0(3,4)).'*tmp1) ,[g(1) 1 g(3)]);\n\tv(:,j,:) = real(ifft(fft(v(:,j,:),[],3).*t,[],3));\nend;\n\nif any(g~=d), v = v(1:d(1),1:d(2),1:d(3)); end;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [S0,S1,S2,S3] = shear_decomp(A)\n% Decompose rotation and translation matrix A into shears S0, S1, S2 and\n% S3, such that A = S0*S1*S2*S3. The original procedure is documented\n% in:\n% R. W. Cox and A. Jesmanowicz (1999)\n% Real-Time 3D Image Registration for Functional MRI\n\nA0 = A(1:3,1:3);\nif any(abs(svd(A0)-1)>1e-7), error('Can''t decompose matrix'); end;\n\n\nt = A0(2,3); if t==0, t=eps; end;\na0 = pinv(A0([1 2],[2 3])')*[(A0(3,2)-(A0(2,2)-1)/t) (A0(3,3)-1)]';\nS0 = [1 0 0; 0 1 0; a0(1) a0(2) 1];\nA1 = S0\\A0; a1 = pinv(A1([2 3],[2 3])')*A1(1,[2 3])'; S1 = [1 a1(1) a1(2); 0 1 0; 0 0 1];\nA2 = S1\\A1; a2 = pinv(A2([1 3],[1 3])')*A2(2,[1 3])'; S2 = [1 0 0; a2(1) 1 a2(2); 0 0 1];\nA3 = S2\\A2; a3 = pinv(A3([1 2],[1 2])')*A3(3,[1 2])'; S3 = [1 0 0; 0 1 0; a3(1) a3(2) 1];\n\ns3 = A(3,4)-a0(1)*A(1,4)-a0(2)*A(2,4);\ns1 = A(1,4)-a1(1)*A(2,4);\ns2 = A(2,4);\nS0 = [[S0 [0 0 s3]'];[0 0 0 1]];\nS1 = [[S1 [s1 0 0]'];[0 0 0 1]];\nS2 = [[S2 [0 s2 0]'];[0 0 0 1]];\nS3 = [[S3 [0 0 0]'];[0 0 0 1]];\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [Mask,y1,y2,y3] = getmask(M,x1,x2,x3,dim,wrp)\ntiny = 5e-2; % From spm_vol_utils.c\ny1 = M(1,1)*x1+M(1,2)*x2+(M(1,3)*x3+M(1,4));\ny2 = M(2,1)*x1+M(2,2)*x2+(M(2,3)*x3+M(2,4));\ny3 = M(3,1)*x1+M(3,2)*x2+(M(3,3)*x3+M(3,4));\nMask = logical(ones(size(y1)));\nif ~wrp(1), Mask = Mask & (y1 >= (1-tiny) & y1 <= (dim(1)+tiny)); end;\nif ~wrp(2), Mask = Mask & (y2 >= (1-tiny) & y2 <= (dim(2)+tiny)); end;\nif ~wrp(3), Mask = Mask & (y3 >= (1-tiny) & y3 <= (dim(3)+tiny)); end;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vo = nan2zero(vi)\nvo = vi;\nvo(~isfinite(vo)) = 0;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_defs.m", "ext": ".m", "path": "spm5-master/spm_config_defs.m", "size": 9994, "source_encoding": "utf_8", "md5": "2b2b68477701f342d0f333362d8fb2ec", "text": "function conf = spm_config_defs\n% Configuration file for deformation jobs.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_defs.m 1032 2007-12-20 14:45:55Z john $\n\nentry = inline(['struct(''type'',''entry'',''name'',name,'...\n '''tag'',tag,''strtype'',strtype,''num'',num)'],...\n 'name','tag','strtype','num');\n\nfiles = inline(['struct(''type'',''files'',''name'',name,'...\n '''tag'',tag,''filter'',fltr,''num'',num)'],...\n 'name','tag','fltr','num');\n\nbranch = inline(['struct(''type'',''branch'',''name'',name,'...\n '''tag'',tag,''val'',{val})'],...\n 'name','tag','val');\n\nrepeat = inline(['struct(''type'',''repeat'',''name'',name,'...\n '''tag'',tag,''values'',{values})'],...\n 'name','tag','values');\n\nmnu = inline(['struct(''type'',''menu'',''name'',name,'...\n '''tag'',tag,''labels'',{labels},''values'',{values},''help'',{{}})'],...\n 'name','tag','labels','values');\n\n%--------------------------------------------------------------------\nhsummary = {[...\n'This is a utility for working with deformation fields. ',...\n'They can be loaded, inverted, combined etc, and the results ',...\n'either saved to disk, or applied to some image.'],...\n'',[...\n'Note that ideal deformations can be treated as members of a Lie group. ',...\n'Future versions of SPM may base its warping on such principles.']};\n\nhinv = {[...\n'Creates the inverse of a deformation field. ',...\n'Deformations are assumed to be one-to-one, in which case they ',...\n'have a unique inverse. If y'':A->B is the inverse of y:B->A, then ',...\n'y'' o y = y o y'' = Id, where Id is the identity transform.'],...\n'',...\n'Deformations are inverted using the method described in the appendix of:',...\n[' * Ashburner J, Andersson JLR & Friston KJ (2000) ',...\n '\"Image Registration using a Symmetric Prior - in Three-Dimensions.\" ',...\n 'Human Brain Mapping 9(4):212-225']};\n\nhcomp = {[...\n'Deformation fields can be thought of as mappings. ',...\n'These can be combined by the operation of \"composition\", which is ',...\n'usually denoted by a circle \"o\". ',...\n'Suppose x:A->B and y:B->C are two mappings, where A, B and C refer ',...\n'to domains in 3 dimensions. ',...\n'Each element a in A points to element x(a) in B. ',...\n'This in turn points to element y(x(a)) in C, so we have a mapping ',...\n'from A to C. ',...\n'The composition of these mappings is denoted by yox:A->C. ',...\n'Compositions can be combined in an associative way, such that zo(yox) = (zoy)ox.'],...\n'',[...\n'In this utility, the left-to-right order of the compositions is ',...\n'from top to bottom (note that the rightmost deformation would ',...\n'actually be applied first). ',...\n'i.e. ...((first o second) o third)...o last. The resulting deformation field will ',...\n'have the same domain as the first deformation specified, and will map ',...\n'to voxels in the codomain of the last specified deformation field.']};\n\nhsn = {[...\n'Spatial normalisation, and the unified segmentation model of ',...\n'SPM5 save a parameterisation of deformation fields. These consist ',...\n'of a combination of an affine transform, and nonlinear warps that ',...\n'are parameterised by a linear combination of cosine transform ',...\n'basis functions. These are saved in *_sn.mat files, which can be ',...\n'converted to deformation fields.']};\n\nhvox = {[...\n'Specify the voxel sizes of the deformation field to be produced. ',...\n'Non-finite values will default to the voxel sizes of the template image',...\n'that was originally used to estimate the deformation.']};\n\nhbb = {[...\n'Specify the bounding box of the deformation field to be produced. ',...\n'Non-finite values will default to the bounding box of the template image',...\n'that was originally used to estimate the deformation.']};\n\nhimgr = {[...\n'Deformations can be thought of as vector fields. These can be represented ',...\n'by three-volume images.']};\n\nhimgw = {[...\n'Save the result as a three-volume image. \"y_\" will be prepended to the ',...\n'filename. The result will be written to the current directory.']};\n\nhapply = {[...\n'Apply the resulting deformation field to some images. ',...\n'The warped images will be written to the current directory, and the ',...\n'filenames prepended by \"w\". Note that trilinear interpolation is used ',...\n'to resample the data, so the original values in the images will ',...\n'not be preserved.']};\n\nhmatname = {[...\n'Specify the _sn.mat to be used.']};\n\nhimg = {[...\n'Specify the image file on which to base the dimensions, orientation etc.']};\n\nhid = {[...\n'This option generates an identity transform, but this can be useful for '...\n'changing the dimensions of the resulting deformation (and any images that '...\n'are generated from it). Dimensions, orientation etc are derived from '...\n'an image.']};\n\ndef = files('Deformation Field','def','.*y_.*\\.nii$',1);\ndef.help = himgr;\n\nmatname = files('Parameter File','matname','.*_sn\\.mat$',[1 1]);\nmatname.help = hmatname;\n\nvox = entry('Voxel sizes','vox','e',[1 3]);\nvox.val = {[NaN NaN NaN]};\nvox.help = hvox;\n\nbb = entry('Bounding box','bb','e',[2 3]);\nbb.val = {NaN*ones(2,3)};\nbb.help = hbb;\n\nsn2def = branch('Imported _sn.mat','sn2def',{matname,vox,bb});\nsn2def.help = hsn;\n\nimg = files('Image to base Id on','space','image',1);\nimg.help = himg;\nid = branch('Identity','id',{img});\nid.help = hid;\n\nif spm_matlab_version_chk('7') <= 0,\n ffield = files('Flow field','flowfield','nifti',[1 1]);\n ffield.ufilter = '^u_.*';\n ffield.help = {...\n ['The flow field stores the deformation information. '...\n 'The same field can be used for both forward or backward deformations '...\n '(or even, in principle, half way or exaggerated deformations).']};\n %------------------------------------------------------------------------\n forbak = mnu('Forward/Backwards','times',{'Backward','Forward'},{[1 0],[0 1]});\n forbak.val = {[1 0]};\n forbak.help = {[...\n 'The direction of the DARTEL flow. '...\n 'Note that a backward transform will warp an individual subject''s '...\n 'to match the template (ie maps from template to individual). '...\n 'A forward transform will warp the template image to the individual.']};\n %------------------------------------------------------------------------\n K = mnu('Time Steps','K',...\n {'1','2','4','8','16','32','64','128','256','512'},...\n {0,1,2,3,4,5,6,7,8,9});\n K.val = {6};\n K.help = {...\n ['The number of time points used for solving the '...\n 'partial differential equations. A single time point would be '...\n 'equivalent to a small deformation model. '...\n 'Smaller values allow faster computations, '...\n 'but are less accurate in terms '...\n 'of inverse consistency and may result in the one-to-one mapping '...\n 'breaking down.']};\n %------------------------------------------------------------------------\n drtl = branch('DARTEL flow','dartel',{ffield,forbak,K});\n drtl.help = {'Imported DARTEL flow field.'};\n %------------------------------------------------------------------------\n other = {sn2def,drtl,def,id};\nelse\n other = {sn2def,def,id};\nend\n\nimg = files('Image to base inverse on','space','image',1);\nimg.help = himg;\n\ncomp0 = repeat('Composition','comp',other);\ncomp0.help = hcomp;\n\niv0 = branch('Inverse','inv',{comp0,img});\niv0.help = hinv;\n\ncomp1 = repeat('Composition','comp',{other{:},iv0,comp0});\ncomp1.help = hcomp;\ncomp1.check = @check;\n\niv1 = branch('Inverse','inv',{comp1,img});\niv1.help = hinv;\n\ncomp2 = repeat('Composition','comp',{other{:},iv1,comp1});\ncomp2.help = hcomp;\ncomp2.check = @check;\n\niv2 = branch('Inverse','inv',{comp2,img});\niv2.help = hinv;\n\n\ncomp = repeat('Composition','comp',{other{:},iv2,comp2});\ncomp.help = hcomp;\ncomp.check = @check;\n\nsaveas = entry('Save as','ofname','s',[1 Inf]);\nsaveas.val = {''};\nsaveas.help = himgw;\n\napplyto = files('Apply to','fnames','image',[0 Inf]);\napplyto.val = {''};\napplyto.help = happly;\n\ninterp.type = 'menu';\ninterp.name = 'Interpolation';\ninterp.tag = 'interp';\ninterp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-spline',...\n'3rd Degree B-Spline ','4th Degree B-Spline ','5th Degree B-Spline',...\n'6th Degree B-Spline','7th Degree B-Spline'};\ninterp.values = {0,1,2,3,4,5,6,7};\ninterp.def = 'normalise.write.interp';\ninterp.help = {...\n['The method by which the images are sampled when being written in a ',...\n'different space.'],...\n[' Nearest Neighbour: ',...\n' - Fastest, but not normally recommended.'],...\n[' Bilinear Interpolation: ',...\n' - OK for PET, or realigned fMRI.'],...\n[' B-spline Interpolation: ',...\n' - Better quality (but slower) interpolation/* \\cite{thevenaz00a}*/, especially ',...\n' with higher degree splines. Do not use B-splines when ',...\n' there is any region of NaN or Inf in the images. '],...\n};\n\n\nconf = branch('Deformations','defs',{comp,saveas,applyto,interp});\nconf.prog = @spm_defs;\nconf.vfiles = @vfiles;\nconf.help = hsummary;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\n\nfunction str = check(job)\nstr = '';\nif isempty(job),\n str = 'Empty Composition';\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\n\nfunction vf = vfiles(job)\nvf = {};\ns = strvcat(job.ofname);\nif ~isempty(s),\n vf = {vf{:}, fullfile(pwd,['y_' s '.nii,1'])};\nend;\n\ns = strvcat(job.fnames);\nfor i=1:size(s,1),\n [pth,nam,ext,num] = spm_fileparts(s(i,:));\n vf = {vf{:}, fullfile(pwd,['w',nam,ext,num])};\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_showdoc.m", "ext": ".m", "path": "spm5-master/spm_showdoc.m", "size": 4017, "source_encoding": "utf_8", "md5": "63defc367211a2209a2d1710248b6cdc", "text": "function spm_showdoc(c)\n% Show SPM documentation\n%\n% This function extracts and displays SPM documentation.\n%\n% Example usage:\n% diary('spmdoc.txt'); spm_showdoc; diary off\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_showdoc.m 112 2005-05-04 18:20:52Z john $\n\n\nif nargin==0,\n\tc = spm_config;\nend;\nfprintf('\\n\\nSPM DOCUMENTATION\\n\\nTable of Contents\\n----- -- --------\\n');\ncontents(c);\nfprintf('%s\\n%s\\n\\n\\n',repmat('_',1,80),repmat('_',1,80));\nmaintext(c);\nreturn;\n\nfunction contents(c,lev)\nif nargin==1,\n\tlev = '';\nend;\nif isfield(c,'name'),\n\tstr = [lev repmat(' ',1,25-length(lev)) c.name];\n\tfprintf('%s\\n',str);\n i = 0;\n\tif isfield(c,'values'),\n\t\tfor ii=1:length(c.values),\n\t\t\tif isstruct(c.values{ii}) && isfield(c.values{ii},'name'),\n\t\t\t\ti = i+1;\n\t\t\t\tlev1 = sprintf('%s%d.', lev, i);\n\t\t\t\tcontents(c.values{ii},lev1);\n\t\t\tend;\n\t\tend;\n\tend;\n\tif isfield(c,'val'),\n\t\tfor ii=1:length(c.val),\n\t\t\tif isstruct(c.val{ii}) && isfield(c.val{ii},'name'),\n\t\t\t\ti = i+1;\n\t\t\t\tlev1 = sprintf('%s%d.', lev, i);\n\t\t\t\tcontents(c.val{ii},lev1);\n\t\t\tend;\n\t\tend;\n\tend;\nend;\nreturn;\n\nfunction maintext(c, lev)\nif nargin==1,\n\tlev = '';\nend;\nif ~isempty(lev) && sum(lev=='.')==1,\n\tdisp(repmat('_',1,80));\n\tfprintf('\\n');\nend;\nif isfield(c,'name'),\n\tstr = sprintf('%s %s', lev, c.name);\n\tunder = repmat('-',1,length(str));\n\tfprintf('%s\\n%s\\n', str, under);\n\tif isfield(c,'modality'),\n\t\tfprintf('Only for');\n\t\tfor i=1:numel(c.modality),\n\t\t\tfprintf(' %s',c.modality{i});\n\t\tend;\n\t\tfprintf('\\n\\n');\n\tend;\n\tif isfield(c,'help');\n\t\thlp = spm_justify(80,c.help);\n\t\tdisp(strvcat(hlp{:}));\n\tend;\n\n\tswitch (c.type),\n\tcase {'repeat'},\n\t\tif length(c.values)==1,\n\t\t\tfprintf('\\nRepeat \"%s\", any number of times.\\n',c.values{1}.name);\n else\n\t\t\tfprintf('\\nAny of the following options can be chosen, any number of times\\n');\n\t\t\ti = 0;\n\t\t\tfor ii=1:length(c.values),\n\t\t\t\tif isstruct(c.values{ii}) && isfield(c.values{ii},'name'),\n\t\t\t\t\ti = i+1;\n\t\t\t\t\tfprintf(' %2d) %s\\n', i,c.values{ii}.name);\n\t\t\t\tend;\n\t\t\tend;\n\t\tend;\n\t\tfprintf('\\n');\n\n\tcase {'choice'},\n\t\tfprintf('\\nAny one of these options can be selected:\\n');\n\t\ti = 0;\n\t\tfor ii=1:length(c.values),\n\t\t\tif isstruct(c.values{ii}) && isfield(c.values{ii},'name'),\n\t\t\t\ti = i+1;\n\t\t\t\tfprintf(' %2d) %s\\n', i,c.values{ii}.name);\n\t\t\tend;\n\t\tend;\n\t\tfprintf('\\n');\n\tcase {'branch'},\n\t\tfprintf('\\nThis item contains %d fields:\\n', length(c.val));\n\t\ti = 0;\n\t\tfor ii=1:length(c.val),\n\t\t\tif isstruct(c.val{ii}) && isfield(c.val{ii},'name'),\n\t\t\t\ti = i+1;\n\t\t\t\tfprintf(' %2d) %s\\n', i,c.val{ii}.name);\n\t\t\tend;\n\t\tend;\n\t\tfprintf('\\n');\n\tcase {'menu'},\n\t\tfprintf('\\nOne of these values is chosen:\\n');\n\t\tfor k=1:length(c.labels),\n\t\t\tfprintf(' %2d) %s\\n', k, c.labels{k});\n\t\tend;\n\t\tfprintf('\\n');\n\tcase {'files'},\n\t\tif length(c.num)==1 && isfinite(c.num(1)) && c.num(1)>=0,\n\t\t\tfprintf('\\nA \"%s\" file is selected by the user.\\n',c.filter);\n else\n\t\t\tfprintf('\\n\"%s\" files are selected by the user.\\n',c.filter);\n\t\tend;\n\n\tcase {'entry'},\n\t\tswitch c.strtype,\n\t\tcase {'e'},\n\t\t\td = 'Evaluated statements';\n\t\tcase {'n'},\n\t\t\td = 'Natural numbers';\n\t\tcase {'r'},\n\t\t\td = 'Real numbers';\n\t\tcase {'w'},\n\t\t\td = 'Whole numbers';\n\t\totherwise,\n\t\t\td = 'Values';\n\t\tend;\n\t\tfprintf('\\n%s are typed in by the user.\\n',d);\n\tend;\n\n\ti = 0;\n\tfprintf('\\n');\n\tif isfield(c,'values'),\n\t\tfor ii=1:length(c.values),\n\t\t\tif isstruct(c.values{ii}) && isfield(c.values{ii},'name'),\n\t\t\t\ti = i+1;\n\t\t\t\tlev1 = sprintf('%s%d.', lev, i);\n\t\t\t\tmaintext(c.values{ii},lev1);\n\t\t\tend;\n\t\tend;\n\tend;\n if isfield(c,'val'),\n for ii=1:length(c.val),\n if isstruct(c.val{ii}) && isfield(c.val{ii},'name'),\n i = i+1;\n lev1 = sprintf('%s%d.', lev, i);\n maintext(c.val{ii},lev1);\n end;\n end;\n end;\n\tfprintf('\\n');\nend;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_maff.m", "ext": ".m", "path": "spm5-master/spm_maff.m", "size": 11342, "source_encoding": "utf_8", "md5": "137adfbac77cee275f3852ad16738cf3", "text": "function [M,h] = spm_maff(varargin)\n% Affine registration to MNI space using mutual information\n% FORMAT M = spm_maff(P,samp,x,b0,MF,M,regtyp,ff)\n% P - filename or structure handle of image\n% x - cell array of {x1,x2,x3}, where x1 and x2 are\n% co-ordinates (from ndgrid), and x3 is a list of\n% slice numbers to use\n% b0 - a cell array of belonging probability images\n% (see spm_load_priors.m).\n% MF - voxel-to-world transform of belonging probability\n% images\n% M - starting estimates\n% regtype - regularisation type\n% 'mni' - registration of European brains with MNI space\n% 'eastern' - registration of East Asian brains with MNI space\n% 'rigid' - rigid(ish)-body registration\n% 'subj' - inter-subject registration\n% 'none' - no regularisation\n% ff - a fudge factor (derived from the one above)\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_maff.m 2526 2008-12-03 11:42:57Z john $\n\n[buf,MG] = loadbuf(varargin{1:2});\nM = affreg(buf, MG, varargin{2:end});\n\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction [buf,MG] = loadbuf(V,x)\nif ischar(V), V = spm_vol(V); end;\nx1 = x{1};\nx2 = x{2};\nx3 = x{3};\n% Load the image\nV = spm_vol(V);\nd = V(1).dim(1:3);\no = ones(size(x1));\nd = [size(x1) length(x3)];\ng = zeros(d);\nspm_progress_bar('Init',V.dim(3),'Loading volume','Planes loaded');\nfor i=1:d(3)\n g(:,:,i) = spm_sample_vol(V,x1,x2,o*x3(i),0);\n spm_progress_bar('Set',i);\nend;\nspm_progress_bar('Clear');\n\n% Convert the image to unsigned bytes\n[mn,mx] = spm_minmax(g);\nsw = warning('off','all');\nfor z=1:length(x3),\n gz = g(:,:,z);\n buf(z).msk = gz>mn & isfinite(gz);\n buf(z).nm = sum(buf(z).msk(:));\n gz = double(gz(buf(z).msk));\n buf(z).g = uint8(round(gz*(255/mx)));\nend;\nwarning(sw);\nMG = V.mat;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction [M,h0] = affreg(buf,MG,x,b0,MF,M,regtyp,ff)\n% Do the work\n\nx1 = x{1};\nx2 = x{2};\nx3 = x{3};\n[mu,isig] = priors(regtyp);\nisig = isig*ff;\nAlpha0 = isig;\nBeta0 = -isig*mu;\n\nsol = M2P(M);\nsol1 = sol;\nll = -Inf;\nnsmp = sum(cat(1,buf.nm));\npr = struct('b',[],'db1',[],'db2',[],'db3',[]);\nspm_chi2_plot('Init','Registering','Log-likelihood','Iteration');\n\nfor iter=1:200\n penalty = (sol1-mu)'*isig*(sol1-mu);\n T = MF\\P2M(sol1)*MG;\n R = derivs(MF,sol1,MG);\n y1a = T(1,1)*x1 + T(1,2)*x2 + T(1,4);\n y2a = T(2,1)*x1 + T(2,2)*x2 + T(2,4);\n y3a = T(3,1)*x1 + T(3,2)*x2 + T(3,4);\n h0 = zeros(256,length(b0)-1)+eps;\n for i=1:length(x3),\n if ~buf(i).nm, continue; end;\n y1 = y1a(buf(i).msk) + T(1,3)*x3(i);\n y2 = y2a(buf(i).msk) + T(2,3)*x3(i);\n y3 = y3a(buf(i).msk) + T(3,3)*x3(i);\n for k=1:size(h0,2),\n pr(k).b = spm_sample_priors(b0{k},y1,y2,y3,k==length(b0));\n h0(:,k) = h0(:,k) + spm_hist(buf(i).g,pr(k).b);\n end;\n end;\n h1 = (h0+eps);\n ssh = sum(h1(:));\n krn = spm_smoothkern(2,(-256:256)',0);\n h1 = conv2(h1,krn,'same');\n h1 = h1/ssh;\n h2 = log2(h1./(sum(h1,2)*sum(h1,1)));\n ll1 = sum(sum(h0.*h2))/ssh - penalty/ssh;\n spm_chi2_plot('Set',ll1);\n if ll1-ll<1e-5, break; end;\n ll = ll1;\n sol = sol1;\n Alpha = zeros(12);\n Beta = zeros(12,1);\n for i=1:length(x3),\n nz = buf(i).nm;\n if ~nz, continue; end;\n msk = buf(i).msk;\n gi = double(buf(i).g)+1;\n y1 = y1a(msk) + T(1,3)*x3(i);\n y2 = y2a(msk) + T(2,3)*x3(i);\n y3 = y3a(msk) + T(3,3)*x3(i);\n\n dmi1 = zeros(nz,1);\n dmi2 = zeros(nz,1);\n dmi3 = zeros(nz,1);\n for k=1:size(h0,2),\n [pr(k).b, pr(k).db1, pr(k).db2, pr(k).db3] = spm_sample_priors(b0{k},y1,y2,y3,k==length(b0));\n tmp = -h2(gi,k);\n dmi1 = dmi1 + tmp.*pr(k).db1;\n dmi2 = dmi2 + tmp.*pr(k).db2;\n dmi3 = dmi3 + tmp.*pr(k).db3;\n end;\n x1m = x1(msk);\n x2m = x2(msk);\n x3m = x3(i);\n A = [dmi1.*x1m dmi2.*x1m dmi3.*x1m...\n dmi1.*x2m dmi2.*x2m dmi3.*x2m...\n dmi1 *x3m dmi2 *x3m dmi3 *x3m...\n dmi1 dmi2 dmi3];\n Alpha = Alpha + spm_atranspa(A);\n Beta = Beta + sum(A,1)';\n end;\n drawnow;\n Alpha = R'*Alpha*R;\n Beta = R'*Beta;\n\n % Gauss-Newton update\n sol1 = (Alpha+Alpha0)\\(Alpha*sol - Beta - Beta0);\nend;\n\nspm_chi2_plot('Clear');\nM = P2M(sol);\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction P = M2P(M)\n% Polar decomposition parameterisation of affine transform,\n% based on matrix logs\nJ = M(1:3,1:3);\nV = sqrtm(J*J');\nR = V\\J;\n\nlV = logm(V);\nlR = -logm(R);\nif sum(sum(imag(lR).^2))>1e-6, error('Rotations by pi are still a problem.'); end;\nP = zeros(12,1);\nP(1:3) = M(1:3,4);\nP(4:6) = lR([2 3 6]);\nP(7:12) = lV([1 2 3 5 6 9]);\nP = real(P);\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction M = P2M(P)\n% Polar decomposition parameterisation of affine transform,\n% based on matrix logs\n\n% Translations\nD = P(1:3);\nD = D(:);\n\n% Rotation part\nind = [2 3 6];\nT = zeros(3);\nT(ind) = -P(4:6);\nR = expm(T-T');\n\n% Symmetric part (zooms and shears)\nind = [1 2 3 5 6 9];\nT = zeros(3);\nT(ind) = P(7:12);\nV = expm(T+T'-diag(diag(T)));\n\nM = [V*R D ; 0 0 0 1];\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction R = derivs(MF,P,MG)\n% Numerically compute derivatives of Affine transformation matrix w.r.t.\n% changes in the parameters.\nR = zeros(12,12);\nM0 = MF\\P2M(P)*MG;\nM0 = M0(1:3,:);\nfor i=1:12\n dp = 0.000000001;\n P1 = P;\n P1(i) = P1(i) + dp;\n M1 = MF\\P2M(P1)*MG;\n M1 = M1(1:3,:);\n R(:,i) = (M1(:)-M0(:))/dp;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction [mu,isig] = priors(typ)\n% The parameters for this distribution were derived empirically from 227\n% scans, that were matched to the ICBM space.\n\n%% Values can be derived by...\n%sn = spm_select(Inf,'.*seg_inv_sn.mat$');\n%X = zeros(size(sn,1),12);\n%for i=1:size(sn,1),\n% p = load(deblank(sn(i,:)));\n% M = p.VF(1).mat*p.Affine/p.VG(1).mat;\n% J = M(1:3,1:3);\n% V = sqrtm(J*J');\n% R = V\\J;\n% lV = logm(V);\n% lR = -logm(R);\n% P = zeros(12,1);\n% P(1:3) = M(1:3,4);\n% P(4:6) = lR([2 3 6]);\n% P(7:12) = lV([1 2 3 5 6 9]);\n% X(i,:) = P';\n%end;\n%mu = mean(X(:,7:12));\n%XR = X(:,7:12) - repmat(mu,[size(X,1),1]);\n%isig = inv(XR'*XR/(size(X,1)-1))\n\n\nmu = zeros(6,1);\nisig = zeros(6);\nswitch deblank(lower(typ))\n\ncase 'mni', % For registering with MNI templates...\n mu = [0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]';\n isig = 1e4 * [\n 0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163\n -0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116\n -0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060\n -0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440\n -0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062\n -0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144];\n\ncase 'imni', % For registering with MNI templates...\n mu = -[0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]';\n isig = 1e4 * [\n 0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163\n -0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116\n -0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060\n -0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440\n -0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062\n -0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144];\n\ncase 'rigid', % Constrained to be almost rigid...\n mu = zeros(6,1);\n isig = eye(6)*1e8;\n\ncase 'subj', % For inter-subject registration...\n mu = zeros(6,1);\n isig = 1e3 * [\n 0.8876 0.0784 0.0784 -0.1749 0.0784 -0.1749\n 0.0784 5.3894 0.2655 0.0784 0.2655 0.0784\n 0.0784 0.2655 5.3894 0.0784 0.2655 0.0784\n -0.1749 0.0784 0.0784 0.8876 0.0784 -0.1749\n 0.0784 0.2655 0.2655 0.0784 5.3894 0.0784\n -0.1749 0.0784 0.0784 -0.1749 0.0784 0.8876];\n\ncase 'eastern', % For East Asian brains to MNI...\n\tmu = [0.0719 -0.0040 -0.0032 0.1416 0.0601 0.2578]';\n\tisig = 1e4 * [\n\t 0.0757 0.0220 -0.0224 -0.0049 0.0304 -0.0327\n\t 0.0220 0.3125 -0.1555 0.0280 -0.0012 -0.0284\n\t -0.0224 -0.1555 1.9727 0.0196 -0.0019 0.0122\n\t -0.0049 0.0280 0.0196 0.0576 -0.0282 -0.0200\n\t 0.0304 -0.0012 -0.0019 -0.0282 0.2128 -0.0275\n\t -0.0327 -0.0284 0.0122 -0.0200 -0.0275 0.0511];\n\ncase 'none', % No regularisation...\n mu = zeros(6,1);\n isig = zeros(6);\n\notherwise\n error(['\"' typ '\" not recognised as type of regularisation.']);\nend;\nmu = [zeros(6,1) ; mu];\nisig = [zeros(6,12) ; zeros(6,6) isig];\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction [h0,d1] = reg_unused(M)\n% Try to analytically compute the first and second derivatives of a\n% penalty function w.r.t. changes in parameters. It works for first\n% derivatives, but I couldn't make it work for the second derivs - so\n% I gave up and tried a new strategy.\n\nT = M(1:3,1:3);\n[U,S,V] = svd(T);\ns = diag(S);\nh0 = sum(log(s).^2);\nd1s = 2*log(s)./s;\n%d2s = 2./s.^2-2*log(s)./s.^2;\nd1 = zeros(12,1);\n\nfor j=1:3\n for i1=1:9\n T1 = zeros(3,3);\n T1(i1) = 1;\n t1 = U(:,j)'*T1*V(:,j);\n d1(i1) = d1(i1) + d1s(j)*t1;\n end;\nend;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction M = P2M_unused(P)\n% SVD parameterisation of affine transform, based on matrix-logs.\n\n% Translations\nD = P(1:3);\nD = D(:);\n\n% Rotation U\nind = [2 3 6];\nT = zeros(3);\nT(ind) = P(4:6);\nU = expm(T-T');\n\n% Diagonal zooming matrix\nS = expm(diag(P(7:9)));\n\n% Rotation V'\nT(ind) = P(10:12);\nV = expm(T'-T);\n\nM = [U*S*V' D ; 0 0 0 1];\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_movefile.m", "ext": ".m", "path": "spm5-master/spm_config_movefile.m", "size": 2999, "source_encoding": "utf_8", "md5": "5669e37f39c3defe8479460f98d0e80b", "text": "function opts = spm_config_movefile\n% Configuration file for move file function\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Volkmar Glauche\n% $Id: spm_config_movefile.m 549 2006-06-07 12:37:29Z volkmar $\n\n%_______________________________________________________________________\n\n\nsrcfiles.type = 'files';\nsrcfiles.name = 'Files to move';\nsrcfiles.tag = 'srcfiles';\nsrcfiles.filter = '.*';\nsrcfiles.num = [0 Inf];\nsrcfiles.help = {'Select files to move.'};\n\ntargetdir.type = 'files';\ntargetdir.name = 'Target directory';\ntargetdir.tag = 'targetdir';\ntargetdir.filter = 'dir';\ntargetdir.num = 1;\ntargetdir.help = {'Select target directory.'};\n\nopts.type = 'branch';\nopts.name = 'Move Files';\nopts.tag = 'movefile';\nopts.val = {srcfiles,targetdir};\nopts.prog = @my_movefile;\nopts.vfiles = @vfiles_movefile;\nopts.help = {[...\n 'This facilty allows to move files in a batch. Note that moving files ' ...\n 'will not make them disappear from file selection lists. Therefore one' ...\n 'has to be careful not to select the original files after they have ' ...\n 'been programmed to be moved.'],'',...\n ['If image files (.*img or .*nii) are selected, corresponding hdr or mat files will ' ...\n 'be moved as well, if they exist.']};\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction my_movefile(varargin)\njob = varargin{1};\nfor k = 1:numel(job.srcfiles)\n [p n e v] = spm_fileparts(job.srcfiles{k});\n if strncmp(e,'.img',4)||strncmp(e,'.nii',4)\n try_movefile(fullfile(p,[n e]),job.targetdir{1});\n try_movefile(fullfile(p,[n '.mat']),job.targetdir{1});\n try_movefile(fullfile(p,[n '.hdr']),job.targetdir{1});\n else\n try_movefile(job.srcfiles{k},job.targetdir{1});\n end;\nend;\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction try_movefile(src,dest)\n% silently try to move files\ntry\n movefile(src,dest);\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction vf = vfiles_movefile(varargin)\njob = varargin{1};\nvf={};\nfor k = 1:numel(job.srcfiles)\n [p n e v] = spm_fileparts(job.srcfiles{k});\n if strncmp(e,'.img',4)||strncmp(e,'.nii',4)\n vi = strfind(e,',');\n if ~isempty(vi)\n e=e(1:vi-1);\n end;\n vf{end+1} = fullfile(job.targetdir{1},[n e v]);\n if exist(fullfile(p,[n '.mat']),'file')\n vf{end+1} = fullfile(job.targetdir{1},[n '.mat']);\n end;\n if exist(fullfile(p,[n '.hdr']))\n vf{end+1}= fullfile(job.targetdir{1},[n '.hdr']);\n end;\n else\n vf{end+1} = fullfile(job.targetdir{1},[n e v]);\n end;\nend;\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_justify.m", "ext": ".m", "path": "spm5-master/spm_justify.m", "size": 6226, "source_encoding": "utf_8", "md5": "49239b75dcd1c0bebd8523ee21724d50", "text": "function out = spm_justify(varargin)\n% SPM_JUSTIFY Justifies a text string\n% OUT = SPM_JUSTIFY(N,TXT) justifies text string TXT to\n% the length specified by N.\n%\n% OUT = SPM_JUSTIFY(OBJ,TXT) justifies text string to\n% the width of the OBJ in characters - 1.\n%\n% If TXT is a cell array, then each element is treated\n% as a paragraph and justified, otherwise the string is\n% treated as a paragraph and is justified.\n% Non a-z or A-Z characters at the start of a paragraph\n% are used to define any indentation required (such as\n% for enumeration, bullets etc. If less than one line\n% of text is returned, then no formatting is done.\n%\n% Example:\n% out = spm_justify(40,{['Statistical Parametric ',...\n% 'Mapping refers to the construction and ',...\n% 'assessment of spatially extended ',...\n% 'statistical process used to test hypotheses ',...\n% 'about [neuro]imaging data from SPECT/PET & ',...\n% 'fMRI. These ideas have been instantiated ',...\n% 'in software that is called SPM']});\n% strvcat(out{:})\n%\n%------------------------------------------------------------------------\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_justify.m 491 2006-03-31 17:36:45Z john $\n\nout = {};\n\n% DRG added code to estimate the actual size of the listbox and how many\n% characters will fit per line. \nif nargin < 2\n error('Incorrect usage of spm_justify.')\nend\nn = varargin{1};\nif ishandle(n)\n % n is presumably the handle of some object that can deal with text.\n % use try catch statements so that if try fails the\n % UI is returned to its original state.\n h = n;\n oldStr = get(h,'String');\n oldUnits = get(h,'Units');\n try\n set(h,'Units','Characters');\n % Matlab is very inaccurate at estimating the width of single\n % characters, so we'll use 100.\n set(h,'string',repmat(' ',1,100));\n ext = get(h,'extent');\n % calculate width of 1 character.\n ext = ext(3)/100;\n pos = get(h,'position');\n pos = pos(3);\n % hack because Matlab cannot tell us how wide the scrollbar is.\n pos = pos - 5;\n wGuess = floor(pos/ext);\n str = repmat(' ',1,wGuess);\n set(h,'string',str);\n ext = get(h,'extent');\n ext = ext(3);\n if ext > pos\n while ext > pos\n if numel(str) == 1\n error('Too few characters for object handle provided.');\n end\n str = str(1:end-1);\n set(h,'String',str);\n ext = get(h,'extent');\n ext = ext(3);\n end\n n = numel(str);\n else\n while ext < pos\n str = [str(1), str];\n if numel(str) > 200\n error('Too many characters for object handle provided.');\n end\n set(h,'String',str);\n ext = get(h,'extent');\n ext = ext(3);\n end\n n = numel(str)-2;\n end\n set(h,'String',oldStr);\n set(h,'Units',oldUnits);\n catch\n set(h,'String',oldStr);\n set(h,'Units',oldUnits);\n error('Problem estimating characters for object handle provided');\n end\nend\nfor i=2:nargin,\n if iscell(varargin{i}),\n for j=1:numel(varargin{i}),\n para = justify_paragraph(n,varargin{i}{j});\n out = {out{:},para{:}};\n end;\n else\n para = justify_paragraph(n,varargin{i});\n out = {out{:},para{:}};\n end;\nend;\n\nfunction out = justify_paragraph(n,txt)\nif numel(txt)>1 && txt(1)=='%',\n txt = txt(2:end);\nend;\n%txt = regexprep(txt,'/\\*([^(/\\*)]*)\\*/','');\nst1 = findstr(txt,'/*');\nen1 = findstr(txt,'*/');\nst = [];\nen = [];\nfor i=1:numel(st1),\n en1 = en1(en1>st1(i));\n if ~isempty(en1),\n st = [st st1(i)];\n en = [en en1(1)];\n en1 = en1(2:end);\n end;\nend;\n\nstr = [];\npen = 1;\nfor i=1:numel(st),\n str = [str txt(pen:st(i)-1)];\n pen = en(i)+2;\nend;\nstr = [str txt(pen:numel(txt))];\ntxt = str;\n\noff = find((txt'>='a' & txt'<='z') | (txt'>='A' & txt'<='Z'));\noff = off(off1,\n out{1} = [txt(1:(off-1)) para{1}];\n for j=2:numel(para),\n out{j} = [repmat(' ',1,off-1) para{j}];\n end;\n else\n out{1} = txt;\n end;\nend;\nreturn;\n\nfunction out = justify_para(n,varargin)\n% Collect varargs into a single string\nstr = varargin{1};\nfor i=2:length(varargin),\n str = [str ' ' varargin{i}];\nend;\n\nif isempty(str), out = {''}; return; end;\n\n% Remove repeats\nsp = find(str==' ');\nrep = sp(diff(sp)==1);\nstr(rep) = [];\nif str(1) ==' ', str(1) = ''; end;\nif str(end)==' ', str(end) = ''; end;\n\nout = {};\nwhile length(str)>n,\n\n % Break the string into lines\n sp = find(str==' ');\n brk = sp(sp<=n);\n if isempty(brk),\n if isempty(sp),\n brk = length(str)+1;\n else\n brk = sp(1);\n end;\n else\n brk = brk(end);\n end;\n\n % Pad the line to n characters wide\n current = str(1:(brk-1));\n % l = length(current);\n % l = n-l;\n sp = find(current==' ');\n if ~isempty(sp),\n\n % Break into words\n sp = [sp length(current)+1];\n words = {current(1:(sp(1)-1))};\n for i=1:(length(sp)-1),\n words = {words{:}, current((sp(i)+1):(sp(i+1)-1))};\n end;\n\n % Figure out how much padding on average\n nsp = length(sp)-1;\n pad = (n-(length(current)-nsp))/nsp;\n\n % Pad all spaces by the same integer amount\n sp = repmat(floor(pad),1,nsp);\n\n % Pad a random selection of spaces by one\n pad = round((pad-floor(pad))*nsp);\n [unused,ind] = sort(rand(pad,1));\n ind = ind(1:pad);\n sp(ind) = sp(ind)+1;\n\n % Re-construct line from individual words\n current = words{1};\n for i=2:length(words),\n current = [current repmat(' ',1,sp(i-1)) words{i}];\n end;\n end;\n\n out = {out{:},current};\n str = str((brk+1):end);\nend;\n\nout = {out{:},str};\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_diff.m", "ext": ".m", "path": "spm5-master/spm_diff.m", "size": 4445, "source_encoding": "utf_8", "md5": "4511e813264b278c428bfab7ce2324fa", "text": "function [varargout] = spm_diff(varargin)\n% matrix high-order numerical differentiiation\n% FORMAT [dfdx] = spm_diff(f,x,...,n,[V])\n%\n% f - [inline] function f(x{1},...)\n% x - input argument[s]\n% n - arguments to differentiate w.r.t.\n%\n% dfdx - df/dx{i} ; n = i\n% dfdx{p}...{q} - df/dx{i}dx{j}(q)...dx{k}(p) ; n = [i j ... k]\n%\n% V - cell array of matices that allow for differentiation w.r.t.\n% to a linear trasnformation of the parameters: i.e., returns\n% \n% df/dy{i}; x = V{i}y{i}; V = dx(i)/dy(i)\n%\n% - a cunning recursive routine\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Karl Friston\n% $Id: spm_diff.m 1070 2008-01-07 19:03:15Z guillaume $\n\n% create inline object\n%--------------------------------------------------------------------------\nf = varargin{1};\n\n% parse input arguments\n%--------------------------------------------------------------------------\nif iscell(varargin{end})\n x = varargin(2:(end - 2));\n n = varargin{end - 1};\n V = varargin{end};\nelseif isnumeric(varargin{end})\n x = varargin(2:(end - 1));\n n = varargin{end};\n V = cell(1,length(x));\nelse\n error('improper call')\nend\n\n% check transform matrices V = dx.dy\n%--------------------------------------------------------------------------\nfor i = 1:length(x)\n try\n V{i};\n catch\n V{i} = [];\n end\n if ~length(V{i}) && any(n == i);\n V{i} = speye(length(spm_vec(x{i})));\n end\nend\n\n% initialise\n%--------------------------------------------------------------------------\nm = n(end);\nxm = spm_vec(x{m});\ndx = exp(-8);\nJ = cell(1,size(V{m},2));\n\n% proceed to derivatives\n%==========================================================================\nif length(n) == 1\n\n % dfdx\n %----------------------------------------------------------------------\n f0 = feval(f,x{:});\n for i = 1:length(J)\n xi = x;\n xmi = xm + V{m}(:,i)*dx;\n xi{m} = spm_unvec(xmi,x{m});\n fi = feval(f,xi{:});\n J{i} = spm_dfdx(fi,f0,dx);\n end\n \n % return numeric array for first order derivatives\n %======================================================================\n\n % vectorise f\n %----------------------------------------------------------------------\n f = spm_vec(f0);\n\n % if there are no arguments to differentiate w.r.t. ...\n %----------------------------------------------------------------------\n if ~length(xm)\n J = sparse(length(f),0);\n\n % or there are no arguments to differentiate\n %----------------------------------------------------------------------\n elseif ~length(f)\n J = sparse(0,length(xm));\n end\n \n % or differentiation of a vector w.r.t. a vector\n %----------------------------------------------------------------------\n if isvec(f0) && isvec(x{m})\n \n % concatenate into a matrix\n %------------------------------------------------------------------\n if size(f0,2) == 1\n J = spm_cat(J);\n else\n J = spm_cat(J')';\n end\n end\n \n % assign ouput argument and return\n %----------------------------------------------------------------------\n varargout{1} = J;\n varargout{2} = f0;\n\nelse\n\n % dfdxdxdx....\n %----------------------------------------------------------------------\n f0 = cell(1,length(n));\n [f0{:}] = spm_diff(f,x{:},n(1:end - 1),V);\n \n for i = 1:length(J)\n xi = x;\n xmi = xm + V{m}(:,i)*dx;\n xi{m} = spm_unvec(xmi,x{m});\n fi = spm_diff(f,xi{:},n(1:end - 1),V);\n J{i} = spm_dfdx(fi,f0{1},dx);\n end\n varargout = {J f0{:}};\nend\n\n\nfunction dfdx = spm_dfdx(f,f0,dx)\n% cell subtraction\n%--------------------------------------------------------------------------\nif iscell(f)\n dfdx = f;\n for i = 1:length(f(:))\n dfdx{i} = spm_dfdx(f{i},f0{i},dx);\n end\nelse\n dfdx = (f - f0)/dx;\nend\n\n\n\n\n\n%__________________________________________________________________________\n%__________________________________________________________________________\nfunction is = isvec(v)\n% isvector(v) returns true if v is 1-by-n or n-by-1 where n>=0\n\n% vec if just two dimensions, and one (or both) unity\nis = length(size(v)) == 2 && (size(v,1) == 1 || size(v,2) == 1);\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_eeg_filter.m", "ext": ".m", "path": "spm5-master/spm_config_eeg_filter.m", "size": 1124, "source_encoding": "utf_8", "md5": "f4f6f38824ad861a9e282c83b29f1a82", "text": "function S = spm_config_eeg_filter\n% configuration file for EEG Filtering\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n%\n% $Id: spm_config_eeg_filter.m 112 2005-05-04 18:20:52Z john $\n\n\nD = struct('type','files','name','File Name','tag','D',...\n 'filter','mat','num',1,...\n 'help',{{'Select the EEG mat file.'}});\n\ntyp = struct('type','menu','name','Filter type','tag','type',...\n 'labels',{{'Butterworth'}},'values',{{1}},'val',{{1}},...\n 'help', {{'Select the filter type.'}});\n\nPHz = struct('type','entry','name','Cutoff','tag','cutoff',...\n 'strtype','r','num',[1 1],...\n 'help', {{'Enter the filter cutoff'}});\nflt = struct('type','branch','name','Filter','tag','filter','val',{{typ,PHz}});\n\nS = struct('type','branch','name','EEG Filter','tag','eeg_filter',...\n 'val',{{D,flt}},'prog',@eeg_filter,'modality',{{'EEG'}},...\n 'help',{{'Low-pass filters EEG/MEG epoched data.'}});\n\nfunction eeg_filter(S)\nS.D = strvcat(S.D{:});\nspm_eeg_filter(S)\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "os_meg.m", "ext": ".m", "path": "spm5-master/os_meg.m", "size": 29178, "source_encoding": "utf_8", "md5": "a416129ad14306a2e88665ae304c934e", "text": "function G = os_meg(L,Channel,Param,Order,imegsens,irefsens,Verbose);\n%OS_MEG - Calculate the (overlapping) sphere models for MEG\n% function G = os_meg(L,Channel,Param,Order,imegsens,irefsens,Verbose);\n% function G = os_meg(L,Channel,Param,Order,imegsens,irefsens);\n% function G = os_meg(L,Channel,Param,Order);\n% Modified for CME, not MME, as Order = 1.\n% Calculate the magnetic field, spherical head, arbitrary orientation\n%\n% INPUTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% L : a 3 x nL array, each column a source location (x y z coordinates); nL sources\n% Channel is a BrainStorm channel structure\n% Param an array of structures:\n% For every channel i:\n% Param(i).Center = a vector of the x, y, z locations for the sphere model \n% (assume the same center for every sphere for the classical spherical head model);\n%\n% Param(i).Radii = a vector containing the radius in meters of the concentric spheres ;\n% Can be a scalar for the single-sphere head model\n%\n% Param(i).EEGType = [] % Leave it empty for MEG; \n%\n% Order: Defines the source order for which to compute the forward problem:\n% -1 current dipole\n% 0 focal(magnetic) dipole\n% 1 1st order current multipole\n%\n% imegsens is the index to the MEG sensors in the Channel information\n% irefsens is the index to the MEG reference sensors in the Channel\n% if imegsens (irefsens) is not given, then routine (expensively)\n% searches the Channel structure for 'MEG' ('MEG REF') values\n%\n% Verbose : toggle verbose mode (1 is default)\n%\n% OUTPUTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% G is the gain matrix: each column is the forward field of each source\n\n% ---------------------- 27-Jun-2005 10:45:21 -----------------------\n% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------\n%\n% CATEGORY: Forward Modeling\n%\n% Alphabetical list of external functions (non-Matlab):\n% toolbox\\blk_diag.m\n% toolbox\\blk_lex.m\n% toolbox\\bst_message_window.m\n% toolbox\\colnorm.m\n% toolbox\\cross_mat.m\n% toolbox\\good_channel.m\n% toolbox\\inorcol.m\n% toolbox\\makeuswait.m\n% toolbox\\mby3check.m\n% toolbox\\norcol.m\n% toolbox\\vec.m\n%\n% Subfunctions in this file, in order of occurrence in file:\n% c = cross(a,b);\n% k = kronmat(a,b);\n% G = sarvas(L,P,Order);\n% G = sarvas_dipole(L,P,Order);\n% D = sarvas_partial(L,P);\n%\n% At Check-in: $Author: Mosher $ $Revision: 35 $ $Date: 6/27/05 9:00a $\n%\n% This software is part of BrainStorm Toolbox Version 27-June-2005 \n% \n% Principal Investigators and Developers:\n% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,\n% University of Southern California, Los Angeles, CA\n% ** John C. Mosher, PhD, Biophysics Group,\n% Los Alamos National Laboratory, Los Alamos, NM\n% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,\n% CNRS, Hopital de la Salpetriere, Paris, France\n% \n% See BrainStorm website at http://neuroimage.usc.edu for further information.\n% \n% Copyright (c) 2005 BrainStorm by the University of Southern California\n% This software distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPL\n% license can be found at http://www.gnu.org/copyleft/gpl.html .\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n% ------------------------ 27-Jun-2005 10:45:21 -----------------------\n\n% NOT OPTIMIZED FOR BRAINSTORM STRUCTURE.\n% But it's a whole lot better now (October 99 version).\n\n% John C. Mosher, Ph.D.\n\n% ------------------------ HISTORY -------------------------------------------\n% 29-Oct-1999 JCM tried to speed up cross products, which are a substantial portion of \n% the total calculation time, for a lot of dipoles.\n% Also added the waitbar feature for big calculations.\n%\n% 28-Nov-2000 SB Modified for updated 3rd-order gradient correction of CTF data \n% 24-Jan-2002 JCM in Paris, modified code to run old partial gradient calculation\n% in this code\n% 20-Feb-2002 JCM fixed missing translocation of the partial gradient location\n% information. Put center shifting into the partial_gradient \n% code itself. Major change to gradient interface to handle\n% head center in different location.\n% 20-Feb-2002 SB Fixed different version to handle case of m x 3 L matrix,\n% force L to be 3 x N or return error.\n% 12-Mar-2002 JCM Force L to be 3 x N or return error.\n% 19-Jun-2002 JCM Realized version differences between toolbox and developers\n% toolbox, carefully merged two version together into toolbox,\n% updated comments, history, switched waitbar to message window\n% 02-Jul-2002 SB Fixed display using the 'overwrite' option of bst_message_window\n% ........... Added progression messages during computation of large CME gain matrices\n% 03-Sep-2002 SB Fixed bug when Channel contains magnetometers and when head center is at origin ([0 0 0])\n% 20-Nov-2002 SB Updated computation with CTF 3rd order gradient correction\n% Now must pass the entire Channel structure to OS_MEG\n% MEG and MEG REF channels are extracted using GOOD_CHANNEL\n% Lightly altered display \n% 21-Oct-2003 JCM added optional imegsens and irefsens indexed inputs\n% 09-Mar-2004 SB added Verbose argument\n% -----------------------------------------------------------------------------\n\n% Which verbose mode ?\nif 0 % deprecated code - get a warning in Matlab 6.5.0 because 'Verbose' is an argument and has to be declared as GLOBAL before first use\n global Verbose % Pass Verbose to subfunctions\nend\n\n\nif nargin == 5\n Verbose = imegsens; \n clear imegsens\nelseif nargin < 7 ^ ~exist('Verbose','var')\n Verbose = 1;% Default\nend\n\n\n% Indices of MEG and MEG REF channels in Channel structure array:\nif ~exist('imegsens','var') | isempty(imegsens),\n imegsens = good_channel(Channel,[],'MEG');\nend\n\nif isempty(imegsens)\n error('No MEG channels available')\nend\n\nif ~exist('irefsens','var'),\n irefsens = good_channel(Channel,[],'MEG REF');\nend\n\nif ~isempty(irefsens)\n ChannelRef = Channel(irefsens); % Fill out a specific channel structure with MEG REF channels only\n [ChannelRef(:).Type] = deal('MEG'); % Ref channels will be treated as regular MEG sensors when Sarvas is called to compute their forward fields\n refFlag = 1;\nelse\n refFlag = 0;\nend\nChannel = Channel(imegsens); % Keep Channel as a MEG-channel only channel set. \nParam = Param(imegsens);\n\n% ----------------------------\n\nNumCoils = size(Channel(1).Loc,2); % number of coils, assumed same for all channels\nNumSensors = length(Channel); % how many channels\n\nif(size([Channel.Loc],2) ~= NumSensors*NumCoils),\n errordlg({'Sorry, OS_MEG not equipped to handle different number of coils'});\n G = [];\n return\nend\n\n% load up the old parameter array\n% P.sensor is 3 x nR,each column a sensor location\n% P.orient is 3 x nR, the sensor orientation\n% P.center is 3 x nR, the sphere center for each sensor\n\n[P(1:NumCoils)] = deal(struct('sensor',zeros(3,NumSensors),...\n 'orient',zeros(3,NumSensors),...\n 'center',zeros(3,NumSensors),'weight',[]));\nAllLocs = [Channel.Loc]; % remap all Locations\nAllLocs = reshape(AllLocs,NumCoils*3,size(AllLocs,2)/NumCoils);\nAllOrient = [Channel.Orient];\nAllOrient = AllOrient*inorcol(AllOrient);\nAllOrient= reshape(AllOrient,NumCoils*3,size(AllOrient,2)/NumCoils);\nAllWeight = [Channel.Weight];\nAllWeight = reshape(AllWeight(:),NumCoils,length(AllWeight(:))/NumCoils);\n% -- modified from original version: JM 30/10/05 --\nAllCenter = [Param.Center];\n%AllCenter = reshape(AllCenter,NumCoils*3,size(AllLocs,2)/NumCoils);\n% Bug fix by Rik Henson 6/6/07\nAllCenter = reshape(AllCenter,NumCoils*3,size(AllCenter,2)/NumCoils);\n\nfor j = 1:NumCoils,\n P(j).sensor = AllLocs([-2:0]+j*3,:);\n P(j).orient = AllOrient([-2:0]+j*3,:);\n P(j).weight = AllWeight(j,:);\n % -- modified from original version: JM 30/10/05 --\n P(j).center = AllCenter([-2:0]+j*3,:);\n% P(j).center = [Param.Center]; %one center for both coils\nend\n\n[m,n] = size(L);\nif(m~=3), % should be 3 x m\n % Old Mosher convention was to give L as m x 3\n % Newer Mathworks convention is for sets of vectors to\n % be 3 x m (except paradoxically the \"patch\" command).\n % Error to user, force correction in calling code.\n if Verbose\n bst_message_window('wrap',{'LOCATION GIVEN AS M X 3.',...\n 'Please adjust calling code to handle new convention'});\n end\n\n error('Matrix not given as 3 x n. Correct calling code');\nend\n\nG = 0;\nfor i = 1:length(P),\n G = G + sarvas(L,P(i),Order); % local call below\nend\n\n% is there special reference channel considerations?\n% See Channel.mat structure description in the ParameterDescriptions document.\nif (refFlag) % Gradient correction is available as well\n \n % read the CTF reference channel information\n meanCenter = mean([Param.Center],2); % mean head center of all of the channels\n % create a temporary parameters file with the same center for all reference channels.\n [RefParam(1:length(irefsens))] = ...\n deal(struct('Center',meanCenter));\n % recursively call\n \n % Forward model on all reference sensors\n % JCM 19-Jun-2002 switched to feval of mfilename\n Gr = feval(mfilename,L,ChannelRef,RefParam,Order,[1:length(irefsens)],[]); % refs now called as MEG\n \n % Apply nth-order gradient correction on good channels only\n \n global ChannelFlag\n if isempty(ChannelFlag)\n ChannelFlag = ones(size(G,1),1); % Take all channels\n end\n \n %Weight by the current nth-order correction coefficients\n try \n G = G - Channel(1).Comment * Gr; \n catch\n errordlg(lasterr,...\n 'Inconsistency detected in MEG data structure')\n makeuswait('stop')\n return\n end\n \nend\n\nclear global Verbose\n\n% ------------- SUBFUNCTIONS, First the simple utilities, then more complicated -----\n% -----------------------------------------------------------------------------------\nfunction c = cross(a,b);\n% fast and simple, and row major should be faster\n% 10/29/99 conversion to row major was slightly faster\n% in the calculation, but overall slower in the transposes needed.\n% retained the column major multiplies below\nc = zeros(size(a));\nc(1,:) = a(2,:).*b(3,:) - a(3,:).*b(2,:);\nc(2,:) = a(3,:).*b(1,:) - a(1,:).*b(3,:);\nc(3,:) = a(1,:).*b(2,:) - a(2,:).*b(1,:);\n\n\n\n\n\n% ----------------------------------------------------------------------------\nfunction k = kronmat(a,b);\n% column by column, not element by matrix\nk = [a([1 1 1],:) .* b; ...\n a([2 2 2],:) .* b; ...\n a([3 3 3],:) .* b];\n\n\n\n\n\n% ----------------------------------------------------------------------\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Local Sarvas functions %%%%%%%%%%%%%%%%%%%%%%%%\n% First, the standard interface to above\n% If the Order is -1 or 0, then same as before. Order 1 is handled separately\n\nfunction G = sarvas(L,P,Order);\n\nglobal Verbose\n\n% Bronzan Sarvas forward model, spherical head\n% Order = -1 is current dipole\n% Order = 0 is magnetic dipole of BST 2000\n% Order = 1 is the new 1st order current multipole\n% L is 3 x nL\n% \n% P.sensor is 3 x nR,each column a sensor location\n% P.orient is 3 x nR, the sensor orientation\n% P.center is 3 x nR, the sphere center for each sensor\n\n\n% January 18, 2002 from sarvas_partial function of 1995\n\n% Used old parameter convention to continue to handle Sylvain's exceptions\n% for the CTF weighting coils\n\n% if P.center in nonexistant or null, then assumed to be\n% all zeros.\n\n%%%%%%%%%%%%%%%%%%%% which multipolar model to run %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nswitch Order\ncase {-1,0} %%%%%%%%%% CURRENT or MAGNETIC DIPOLE %%%%%%%%%%%%%%%%%%%\n \n G = sarvas_dipole(L,P,Order); % BST 2000 function still used here\n \ncase {1} %%%%%%%%%%%%%%%%%%%%%%%%% CURRENT MULTIPOLE MODEL %%%%%%%%%%%%%%%%%%555\n % new CME multipole, not MME multipole\n \n % each set of three columns corresponds to a dipole\n % first call the dipolar term\n % SB 02-Jul-2002\n if(size(L,2) > 5*size(P.sensor,2)) & size(P.sensor,2) > 1 & Verbose, %arbitrary definition of a lot\n MESSAGE = 1; % let's show messages\n else\n MESSAGE = 0; % let's keep quiet\n end\n \n if MESSAGE\n bst_message_window('wrap','Initiating the computation of CME modeling . . .')\n end\n \n Gdip = sarvas_dipole(L,P,-1); \n \n % now call the quadrupole component\n if MESSAGE\n bst_message_window('Refining model . . .') % Not very explicit but gives hint about the progression here - John any better message ?\n end\n \n Gquad = sarvas_partial(L,P); % form the gradient in a local function\n % weights are not applied in this routine, applied separately in the\n % below forloop\n \n % For example:\n % Gquad(4:6,2) is the gradient of the second coil wrt to the second dipole\n % So we must Vec for each coil to get it into the proper format\n \n nR = size(P.sensor,2); % number of sensors\n nL = size(L,2); % number of source points\n \n G = zeros(nR,12*nL); % the full gain matrix\n \n for i = 1:nL, % for each dipole\n ndx = [-11:0]+i*12; % indexer for this source\n G(:,ndx(1:3)) = Gdip(:,[-2:0]+i*3); % map next dipole to the first columns\n temp = Gquad(:,[-2:0]+i*3); % next block of partial gradients \n for j = 1:nR, % for each sensor position, also apply appropriate weight\n G(j,ndx(4:12)) = vec(temp([-2:0]+j*3,:))' * P.weight(j);\n end\n end\n \nend\n\nG = G*1e-7; % mu_o over 4 pi\n\n\n\n\n\n\n\n%--------------------------------------------------------------------------\nfunction G = sarvas_dipole(L,P,Order);\n\nglobal Verbose\n\n% SARVAS MEG Forward Model, spherical head\n\n% if P.center in nonexistant or null, then assumed to be\n% all zeros.\n\nif(~isfield(P,'center')), % user did not provide\n P.center = []; % initialize to null\nend\nif(isempty(P.center)), % user gave as null\n P.center = zeros(size(P.sensor)); % set to coordinate origin\nend\n\nP.sensor = P.sensor - P.center; % shift sensor coordinates\n\n% SB 03-Sep-2002 \n% Now there is the issue of having a sensor array being a mixture of magnetometers and gradiometers.\n% Magnetometers are referred as pseudo-gradiometers: the corresponding .Loc field of the Channel array of structures\n% is still 3x2. For magnetometers though, the 2nd colum is filled with zeros (i.e.: [0 0 0]').\n% Same story holds for the .Orient field.\n% The full gain matrices are computed for these channels located at [0 0 0] but when the orientation vector is applied\n% the net field is set to 0. Therefore, the second call to sarvas_dipole produces a null field which is substracted frim the field \n% from the magnetometer (i.e the fisrt coil of the pseudo-gradiometer).\n% Calculations fail (divide by zero) when head center is also at [0 0 0]. \n% I'm therefore testing this out here and fix things by virtually translating the virtual coils located at [0 0 0]\n% to [1 1 1] (arbitrary). The net field will still be null when the orientation is applied anyway.\n% Any more elegant fix is welcome at this point.\niMag = find(norcol(P.sensor)==0); % Indices of channels located at P.center.\nif ~isempty(iMag)\n P.sensor(:,iMag) = repmat([1 1 1]',1,length(iMag)); % Move them away (arbitrary location).\nend\n\nnR = size(P.sensor,2); % number of sensors\nnL = size(L,2); % number of source points\n\nRn2 = sum(P.sensor.^2,1); % distance to sensor squared\nRn = sqrt(Rn2); % distance\n\nif (nR >= nL), % more sensors than dipoles\n if(Order == 1),\n G = zeros(nR,12*nL); % gain matrix\n else \n G = zeros(nR,3*nL); % gain matrix\n end\n \n for Li = 1:nL,\n Lmat = L(:,Li+zeros(1,nR)); % matrix of location repeated\n Lmat = Lmat - P.center; % each center shifted relative to its center\n D = P.sensor - Lmat; % distance from souce to sensors\n Dn2 = sum(D.^2,1); % distance squared\n Dn = sqrt(Dn2); % distance\n R_dot_D = sum(P.sensor .* D); % dot product of sensor and distance\n R_dot_Dhat = R_dot_D ./ Dn; % dot product of sensor and distance\n \n F = Dn2 .* Rn + Dn .* R_dot_D; % Sarvas' function F\n \n GF_dot_o = Dn2 .* sum(P.sensor.*P.orient) ./ Rn + ...\n (2 * Rn + R_dot_Dhat) .* sum(D.*P.orient) + ...\n Dn .* sum((D+P.sensor).*P.orient);\n \n tempF = GF_dot_o ./ F.^2;\n \n if(Order == -1), % current dipole model\n temp = cross(Lmat,P.orient) ./ F([1 1 1],:) - ...\n cross(Lmat,P.sensor) .* tempF([1 1 1],:);\n G(:,Li*3+[-2 -1 0]) = temp';\n elseif(Order == 0) % magnetic dipole model\n temp = P.sensor .* tempF([1 1 1],:) - P.orient ./ F([1 1 1],:);\n G(:,Li*3+[-2 -1 0]) = temp';\n elseif(Order == 1), % 1st order multipole\n % first the dipole\n temp_m = P.sensor .* tempF([1 1 1],:) - P.orient ./ F([1 1 1],:);\n % then the quadrupole\n temp1 = -(2*Rn + R_dot_Dhat + Dn);\n temp2 = -sum(D.*P.orient) ./ Dn;\n temp3 = -(2*sum(P.sensor.*P.orient)./Rn + sum((D+P.sensor).*P.orient)./Dn - ...\n sum(D.*P.orient).*R_dot_D./(Dn2.*Dn));\n \n GGpF_dot_o = temp1([1 1 1],:) .* P.orient + ...\n temp2([1 1 1],:).*P.sensor + temp3([1 1 1],:) .* D;\n temp1 = -(2*Rn + R_dot_Dhat);\n GpF = temp1([1 1 1],:) .* D - Dn([1 1 1],:) .* P.sensor;\n temp1 = 1 ./ F.^2;\n temp2 = 2*GF_dot_o./F;\n temp_q = temp1(ones(1,9),:) .* (kronmat(GGpF_dot_o,P.sensor) + ...\n kronmat(GpF,P.orient - temp2([1 1 1],:).*P.sensor));\n G(:,Li*12+[-11:0]) = [temp_m;temp_q]'; \n end\n \n end\n \nelse % more dipoles than sensors nL > nR\n if(Order == 1)\n G = zeros(12*nL,nR); % 1st order multipole gain matrix transposed\n else\n G = zeros(3*nL,nR); % gain matrix transposed\n end\n \n % if there are a lot of dipoles, let's watch on the screen\n % JCM 18-Jun-2002 no more waitbar, use message window\n if (nL > 5*nR) & nR > 1 & Verbose, %arbitrary definition of a lot\n MESSAGE = 1; % let's show messages\n % bst_message_window('wrap',sprintf(...\n % 'Making order %.0f matrix of %.0f sensors x %.0f sources',Order,nR,nL));\n % bst_message_window('append','Making first sensor . . .'); % prepare for overwrite\n bst_message_window('overwrite',sprintf(...\n 'Making Current Dipole matrix of %.0f sensors x %.0f sources',nR,nL));\n bst_message_window('append','Making first sensor . . .'); % prepare for overwrite else\n else % SB 03-Sep-2002 : else was probably missing \n MESSAGE = Verbose; % let's be quiet\n end\n \n for Ri = 1:nR,\n if(MESSAGE), % want to show the user progress?\n if(~rem(Ri,30)), % every tenth sensor\n bst_message_window('overwrite',sprintf('Progress report:....... %.0f of %.0f . . .',Ri,nR));\n end\n end\n Rmat = P.sensor(:,Ri+zeros(1,nL)); % matrix of sensor repeated\n Omat = P.orient(:,Ri+zeros(1,nL)); % orientations\n Lmat = L - P.center(:,Ri+zeros(1,nL)); % shift centers to this coordinate\n \n D = Rmat - Lmat;\n Dn2 = sum(D.^2,1); % distance squared\n Dn = sqrt(Dn2); % distance\n R_dot_D = sum(Rmat .* D); % dot product of sensor and distance\n R_dot_Dhat = R_dot_D ./ Dn; % dot product of sensor and distance\n \n F = Dn2 * Rn(Ri) + Dn .* R_dot_D; % Sarvas' function F\n \n GF_dot_o = Dn2 * sum(P.sensor(:,Ri).*P.orient(:,Ri)) / Rn(Ri) + ...\n (2 * Rn(Ri) + R_dot_D ./ Dn) .* sum(D.*Omat) + ...\n Dn .* sum((D+Rmat).*Omat);\n \n tempF = GF_dot_o ./ F.^2;\n \n if(Order == -1), % current dipole model\n temp = cross(Lmat,Omat) ./ F([1 1 1],:) - ...\n cross(Lmat,Rmat) .* tempF([1 1 1],:);\n elseif(Order == 0) % magnetic dipole model\n temp = Rmat .* tempF([1 1 1],:) - Omat ./ F([1 1 1],:);\n elseif(Order == 1), % 1st order multipole\n % first the dipole\n temp_m = Rmat .* tempF([1 1 1],:) - Omat ./ F([1 1 1],:);\n % then the quadrupole\n temp1 = -(2*Rn(Ri) + R_dot_Dhat + Dn);\n temp2 = -sum(D.*Omat) ./ Dn;\n temp3 = -(2*sum(P.sensor(:,Ri).*P.orient(:,Ri))./Rn(Ri) + sum((D+Rmat).*Omat)./Dn - ...\n sum(D.*Omat).*R_dot_D./(Dn2.*Dn));\n \n GGpF_dot_o = temp1([1 1 1],:) .* Omat + ...\n temp2([1 1 1],:).*Rmat + temp3([1 1 1],:) .* D;\n temp1 = -(2*Rn(Ri) + R_dot_Dhat);\n GpF = temp1([1 1 1],:) .* D - Dn([1 1 1],:) .* Rmat;\n temp1 = 1 ./ F.^2;\n temp2 = 2*GF_dot_o./F;\n temp_q = temp1(ones(1,9),:) .* (kronmat(GGpF_dot_o,Rmat) + ...\n kronmat(GpF,Omat - temp2([1 1 1],:).*Rmat));\n temp = [temp_m;temp_q];\n else % unimplemented order\n disp('SARVAS: Unimplemented source order');\n G = [];\n return\n end \n \n G(:,Ri) = temp(:);\n end\n \n G = G';\n \nend\n\nif(isfield(P,'weight')),\n Weights = P.weight(:); %make sure column\n % scale each row by its appropriate weight\n G = Weights(:,ones(1,size(G,2))) .* G;\nend\n\n\n\n\n\n% ----------------------------------------------------------------------------\n%%%%%%%%%%%%%%%%%%%%%% Partial calculation for the sarvas %%%%%%%%%%%%%%%%%%%\n\nfunction D = sarvas_partial(L,P);\n%SARVAS_PARTIAL Calculate the partial of the Sarvas Formula w.r.t L\n% function D = sarvas_partial(L,P);\n% For dipole locations in L and sensor information in R, calculate the\n% partial of the Sarvas formula (dipole in a sphere, arbitrary sensor\n% orientation) with respect to the dipole location. The result is a matrix\n% D of partials information. \n% If there are M sensors and P dipoles, then D\n% is 3*M by 3*P. Let the corresponding moments Q be 3 by M.\n% Then partial = D * blk_diag(Q,1) is 3*M by P. Each column of partial\n% corresponds to a different dipole in L. Each set of three rows\n% corresponds to a different sensor location. Thus partial(4:6,2) is the\n% partial of the Sarvas formula at the second sensor location, with respect\n% to the second dipole.\n%\n% Used to calculate the Cramer-Rao Lower Bounds\n% structure P has fields .weight, length of the number of sensors, which\n% is applied to each row of the gain matrix. Weight is usually 1 or -1\n% Field .center is 3 x number of sensors, head center for each coil.\n% P.sensor and P.orient are the location and orientation information, resp.\n% P.weight is not applied, must be applied separately, see above calling code.\n\n% Author: John C. Mosher, Ph.D.\n% Los Alamos National Laboratory\n% Los Alamos, NM 87545\n% email: mosher@LANL.Gov\n\n% August 15, 1995 author\n% 20 Feb 2002 JCM extensive I/O changes to adapt into os_meg, handle arbitrary \n% head center\n\nL = mby3check(L,0);\t\t% matrices are now 3 x <>, but don't warn if 3 x 3\n\nnumSens = size(P.sensor,2); % number of sensors\nnumDip = size(L,2); % number of source points\n\n% use some older notation for programming reuse below\nR = [P.sensor]; % sensor locations\nRs = [P.orient]; % sensor orientations\n\nif(~isfield(P,'center')), % user did not provide\n P.center = []; % initialize to null\nend\nif(isempty(P.center)), % user gave as null\n P.center = zeros(size(R)); % set to coordinate origin\nend\n\n% each channel coil is shifted to its relative location\nR = R - P.center; % shift sensor coordinates\n\n% SB 03-Sep-2002 \n% Now there is the issue of having a sensor array being a mixture of magnetometers and gradiometers.\n% Magnetometers are referred as pseudo-gradiometers: the corresponding .Loc field of the Channel array of structures\n% is still 3x2. For magnetometers though, the 2nd colum is filled with zeros (i.e.: [0 0 0]').\n% Same story holds for the .Orient field.\n% The full gain matrices are computed for these channels located at [0 0 0] but when the orientation vector is applied\n% the net field is set to 0. Therefore, the second call to sarvas_dipole produces a null field which is substracted frim the field \n% from the magnetometer (i.e the fisrt coil of the pseudo-gradiometer).\n% Calculations fail (divide by zero) when head center is also at [0 0 0]. \n% I'm therefore testing this out here and fix things by virtually translating the virtual coils located at [0 0 0]\n% to [1 1 1] (arbitrary). The net field will still be null when the orientation is applied anyway.\n% Any more elegant fix is welcome at this point.\niMag = find(norcol(R)==0); % Indices of channels located at P.center.\nif ~isempty(iMag)\n R(:,iMag) = repmat([1 1 1]',1,length(iMag)); % Move them away (arbitrary location).\nend\n\nRn = colnorm(R); \t\t% distance to sensor \niRn = 1../Rn;\t\t\t% inverse distance\no3 = ones(3,1);\t\t\t% col vector of three ones\n\n% three by three matrices per sensor and dipole\nD = zeros(numSens*3,3*numDip);\n\nif(size(L,2) > 5*size(R,2)) & size(R,2) > 1 & Verbose, %arbitrary definition of a lot\n MESSAGE = Verbose; % let's show messages\n bst_message_window({...\n 'Computing quadrupolar moments',...\n sprintf('for sources %.0f of %.0f . . .',100,numDip)...\n });\n \nelse\n MESSAGE = Verbose; % let's be quiet\nend\n\nfor Dip = 1:numDip\t\t% foreach dipole,\n\n %################ main loop ########################\n \n % if there are a lot of dipoles, let's watch on the screen\n % SB 02-Jul-2002 no more waitbar, use message window\n \n if(MESSAGE), % want to show the user progress?\n if(~rem(Dip,100)), % every tenth source\n bst_message_window('overwrite',sprintf('for sources %.0f of %.0f . . .',Dip,numDip));\n end\n end\n \n ThisDipole = L(:,Dip);\t\t% next dipole\n Lmat = repmat(ThisDipole,1,numSens); % repeat this dipole for all sensors\n Lmat = Lmat - P.center; % shift each location relative to the sensor's center\n \n % let \"a\" be the same as Sarvas' \"a\", a = sensor - dipole.\n a = R - Lmat;\n an = colnorm(a);\t\t% norm of each a\n ian=1../an;\t\t\t% inverse of norm a\n ian3 = ian.^3;\t\t\t% inverse cubed of norm a\n \n aDotR = sum(a.*R,1);\n \n % Form F\n \n F = (an .* Rn + aDotR) .* an;\n iF = 1../F;\n \n % From gradient F\n \n tmp1 = an.^2 .* iRn + aDotR .* ian + 2*an + 2*Rn;\n tmp1 = tmp1(o3,:).* R;\n tmp2 = an + 2*Rn + aDotR .* ian;\n tmp2 = tmp2(o3,:) .* Lmat;\n \n gradF = tmp1 - tmp2;\n \n % take partials of (Rs dot grad(F)) wrt r_q. Result is 3 by 1 per sensor\n \n tmp1 = aDotR.*ian3 - 2*(iRn+ian);\n tmp1 = (tmp1(o3,:) .* a) - (R .* ian(o3,:));\n tmp1 = tmp1 .* (o3*sum(Rs.*R,1));\n \n tmp2 = an + 2*Rn + ian.*aDotR;\n tmp2 = tmp2(o3,:) .* Rs;\n \n tmp3 = aDotR.*ian3 - ian;\n tmp3 = tmp3(o3,:).*a - (R .* ian(o3,:));\n tmp3 = tmp3 .* (o3*sum(Rs.*Lmat,1));\n \n partRsGradF = tmp1 - tmp2 - tmp3;\n \n \n % take partial of F wrt r_q\n \n tmp1 = aDotR .* ian;\n tmp1 = tmp1(o3,:).*a;\n \n partF = -2*Rn(o3,:).*a - an(o3,:).*R - tmp1;\n \n \n % now take partial of ((gradF dot s) / F^2).\n \n tmp1 = F(o3,:) .* partRsGradF;\n \n tmp2 = 2*sum(gradF.*Rs,1);\n tmp2 = tmp2(o3,:) .* partF;\n \n partGradFdotRsOverF2 = (tmp1 - tmp2) .* iF(o3,:).^3;\n \n \n % now take partial of inverse of F\n \n partInvF = -partF .* iF(o3,:).^2;\n \n \n % Now we are ready to generate the partial of the Sarvas' formula wrt dipole\n % location. The result is a 3 by 1 per sensor location; however, we want\n % to separate out the dipole moment q. So our \"partials matrix\" D is 3 x 3\n % per sensor location. We will concatenate into a 3*M by 3 matrix for each\n % dipole.\n \n % Rs cross q divide by F\n % Want the cross product matrix tensor\n \n tmp1 = blk_diag(cross_mat(Rs),3); % each set of three columns is a tensor\n tmp1 = tmp1 .* kron(iF,ones(3)); % divide each tensor by F\n tmp1 = blk_lex(tmp1,3); \t% now each set of three rows is a tensor\n \n % L cross Rs dot q time partInvF\n % Want the direct (outer) product of partInvF and (L cross Rs)\n \n tmp2 = cross(Lmat,Rs); % cross products\n % each set of three columns is the outer product\n tmp2 = partInvF * blk_diag(tmp2,1)';\n tmp2 = blk_lex(tmp2,3);\t\t% now each set of three rows is a tensor\n \n % (R cross q)*(gradF dot Rs)/F^2\n % Want scalar times the cross product tensor\n \n tmp3 = sum(gradF .* Rs,1) .* iF.^2;\n tmp3 = kron(tmp3,ones(3));\t% repeat scalar for each submatrix\n tmp3 = tmp3 .* blk_diag(cross_mat(R),3);\n tmp3 = blk_lex(tmp3,3);\t\t% vertically stacked now\n \n % ((L cross R) dot q) * partial(gradF dot Rs over F^2)\n % Want direct (outer) product of partGradFdotRsOverF2 and (L cross R)\n \n tmp4 = cross(Lmat,R);\n tmp4 = partGradFdotRsOverF2 * blk_diag(tmp4,1)';\n tmp4 = blk_lex(tmp4,3);\n \n % Now combine into the appropriate columns of D.\n \n D(:,(Dip-1)*3 + [1:3]) = tmp1 + tmp2 - tmp3 - tmp4;\n \n %################ end main loop ########################\nend \t\t\t\t% next dipole\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_Lana.m", "ext": ".m", "path": "spm5-master/spm_eeg_inv_Lana.m", "size": 4801, "source_encoding": "utf_8", "md5": "6c3018b4e87db5b117f417660e7b28bb", "text": "function [Lan,nit]=spm_eeg_inv_Lana(XYZmm,SseXYZ,Rsc,Rsk,Rbr,sigma)\n\n% FUNCTION Lan,nit]=spm_eeg_inv_Lana(XYZmm,SseXYZ,Rsc,Rsk,Rbr)\n% Calculates the leadfield in a 3-shell sphere head model for a set of\n% distributed dipoles. As this is a spherical model, the solution is analytical\n% but it relies on a truncated infinite series.\n% IN :\n% - XYZmm : dipoles location, moved to fit the spherical model.\n% - SseXYZ : coordinates of the electrodes on the \"scalp sphere\".\n% - Rsc,Rsk,Rbr : radii of the scalp, skull, brain spheres.\n% - sigma : conductivities for the scalp, skull and brain volumes.\n% OUT :\n% - Lan : (orientation free) leadfield obtained with the analytical formula\n% - nit : number of terms used in the infinite series\n%\n% Based on formulas found in :\n% James P. Ary, Stanley A. Klein, Derek H. Fender\n% Location of fources of evoked scalp potentials: Corrections for skull\n% and scalp thicknesses\n% IEEE TBME, 28-6, 447452, 1981\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Christophe Phillips,\n% $Id: spm_eeg_inv_Lana.m 1039 2007-12-21 20:20:38Z karl $\n\nif nargin<6\n sigma = [.33 .004 .33];\nend\ne=sigma(2)/sigma(1) ;\nf1=Rbr/Rsc ;\nf2=Rsk/Rsc ;\n\nNdip = size(XYZmm,2) ;\nLan=zeros(size(SseXYZ,2),3*Ndip) ;\nnit =zeros(1,Ndip) ;\n\n% aff=1000 ;\n% fprintf('\\n')\nfor ii=1:Ndip\n\t%\tdisp(['ii = ',num2str(ii)])\n% \tif rem(ii,aff)==0\n% fprintf(' %3.1f%% calculated. \\n',ii/Ndip*100)\n% end\n\txyz_d = XYZmm(:,ii) ;\n % This is not the same spherical coordinates as produced by cart2sph !!!\n % azimuth is expressed as:\n % - in here: phi = angle betwee e_x and proj of point on 'oxy' plane\n % - in cart2sph: *th* = idem\n % elevation is expressed as:\n % - in here: thet = angle between e_z and point \n % - in cartsph : *phi* = angle between point and 'oxy' plane\n % i.e. *phi* = pi/2 - thet\n \n\tno = norm(xyz_d) ;\n\tb=no/Rsc ; % eccentricity\n\tif no==0\n\t\tthet=0 ;\n\telse\n\t\tthet=acos(xyz_d(3)/no) ;\n\tend\n\tphi = atan2(xyz_d(2),xyz_d(1)) ;\n\n\t% Rotation matrix in order to bring the point (i.e. dipole) on e_z\n rotyz = [cos(phi)*cos(thet) sin(phi)*cos(thet) -sin(thet) ;...\n\t\t -sin(phi) cos(phi) 0 ;...\n\t\t cos(phi)*sin(thet) sin(phi)*sin(thet) cos(thet)] ;\n\n % Apply the same rotation on electrode locations\n\tPt_m = rotyz * SseXYZ ;\n % and get their spherical coordinates.\n\talpha_p = acos(Pt_m(3,:)/Rsc)' ;\n\tbeta_p = atan2(Pt_m(2,:),Pt_m(1,:))' ;\n\n\tmx = [ cos(phi)*cos(thet) -sin(phi) sin(thet)*cos(phi) ] ;\n\tmy = [ sin(phi)*cos(thet) cos(phi) sin(thet)*sin(phi)] ;\n\tmz = [ -sin(thet) 0 cos(thet) ] ;\n \n % All data are prepared proceed to main calculation for all electrodes at once.\n\t[VR,VT,nit(ii)] = V1dip(Rsc,f1,f2,e,sigma(1),b,alpha_p) ;\n y = cos(beta_p) ; yy = sin(beta_p) ;\n \n % the source orientation (after rotation) m_xyz is combined here\n % with the potential V for tangent (VT) and radial (VR) dipole\n % and electrodes location beta_p).\n\tLan(:,3*ii-2) = mx(1)*y.*VT + mx(2)*yy.*VT + mx(3)*VR ;\n\tLan(:,3*ii-1) = my(1)*y.*VT + my(2)*yy.*VT + my(3)*VR ;\n\tLan(:,3*ii) = mz(1)*y.*VT + mz(3)*VR ;\nend\n% fprintf('\\n')\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% SUBFUNCTION\n%\nfunction [VR,VT,n] = V1dip(R,f1,f2,e,sig1,b,alpha_p)\n\nx = cos(alpha_p) ; xx = sin(alpha_p) ; \nlim=1e-12 ; nlim=200 ;\n\n% Formula (2a) for d_n\nd1 = e*e + 1 + 2.5*e + (1-2*e*e+e)*(f1^3-f2^3) - (1-e)^2*(f1/f2)^3 ; % n=1\nd2 = 2*e*e + 2 + e*13/3 + (2-3*e*e+e)*(f1^5-f2^5) - 2*(1-e)^2*(f1/f2)^5 ;% n=2\n\n% This correspnonds to the terms using 'n', 'b' & 'e' in (2)\n% (2n+1)/n * e*(2n+1)^2 * b^(n-1) /(d_n*(n+1)) = (2n+1)^3 / ( n*d_n*(n+1) ) * e/b^(n-1)\nw1 = 27/2*e/d1 ; % n=1\nw2 = 125/6*b*e/d2 ; % n=2\n\nP0_1 = x ; P1_1 = xx ;\nP0_2 = .5*(3*x.*x-1) ; P1_2 = 3*xx.*x ;\n\nVtempR = w1*P0_1 + w2*2*P0_2 ;\nVtempT = w1*P1_1 + w2*P1_2 ;\n\nPn_2=P0_1 ; Pn_1=P0_2 ;\nP1n_2=P1_1 ; P1n_1=P1_2 ;\nVtempR_1=VtempR ;\nVtempT_1=VtempT ;\n\nn=3 ; diR=10 ; diT=10 ;\n\nwhile ((max(abs(diR))>lim) & (max(abs(diT))>lim) & (n 1,\n\terror('[LOADXML] Too many output arguments.');\nend\n\nt = xmltree(filename);\n\nuid = children(t,root(t));\n\nif nargout == 1\n\t% varargout{1} = struct([]); % Matlab 6.0 and above\nend\n\nflagfirstvar = 1;\nfor i=1:length(uid)\n\tif strcmp(get(t,uid(i),'type'),'element')\n\t\tvname = get(t,uid(i),'name');\n\t\t% TODO % No need to parse the whole tree \n\t\tif isempty(varargin) | ismember(varargin,vname)\n\t\t\tv = xml_create_var(t,uid(i));\n\t\t\tif nargout == 1\n\t\t\t\tif flagfirstvar\n\t\t\t\t\tvarargout{1} = struct(vname,v);\n\t\t\t\t\tflagfirstvar = 0;\n\t\t\t\telse\n\t\t\t\t\tvarargout{1} = setfield(varargout{1},vname,v);\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tassignin('caller',vname,v);\n\t\t\tend\n\t\tend\n\tend\nend\n\n%=======================================================================\nfunction v = xml_create_var(t,uid)\n\ttype = attributes(t,'get',uid,'type');\n\tsz = str2num(attributes(t,'get',uid,'size'));\n\t\n\tswitch type\n\t\tcase 'double'\n\t\t\tv = str2num(get(t,children(t,uid),'value'));\n\t\t\tif ~isempty(sz)\n\t\t\t\tv = reshape(v,sz);\n\t\t\tend\n\t\tcase 'sparse'\n\t\t\tu = children(t,uid);\n\t\t\tfor k=1:length(u)\n\t\t\t\tif strcmp(get(t,u(k),'name'),'row')\n\t\t\t\t\ti = str2num(get(t,children(t,u(k)),'value'));\n\t\t\t\telseif strcmp(get(t,u(k),'name'),'col')\n\t\t\t\t\tj = str2num(get(t,children(t,u(k)),'value'));\n\t\t\t\telseif strcmp(get(t,u(k),'name'),'val')\n\t\t\t\t\ts = str2num(get(t,children(t,u(k)),'value'));\n\t\t\t\tend \n\t\t\tend\n\t\t v = sparse(i,j,s,sz(1),sz(2));\n\t\tcase 'struct'\n\t\t\tu = children(t,uid);\n\t\t\tv = []; % works with Matlab < 6.0\n\t\t\tfor i=1:length(u)\n\t\t\t\ts(1).type = '()';\n\t\t\t\ts(1).subs = {str2num(attributes(t,'get',u(i),'index'))};\n\t\t\t\ts(2).type = '.';\n\t\t\t\ts(2).subs = get(t,u(i),'name');\n\t\t\t\tv = subsasgn(v,s,xml_create_var(t,u(i)));\n\t\t\tend\n\t\t\tif isempty(u),\n\t\t\t\tv = struct([]); % Need Matlab 6.0 and above\n\t\t\tend\n\t\tcase 'cell'\n\t\t\tv = cell(sz);\n\t\t\tu = children(t,uid);\n\t\t\tfor i=1:length(u)\n\t\t\t\tv{str2num(attributes(t,'get',u(i),'index'))} = ...\n\t\t\t\t\txml_create_var(t,u(i));\n\t\t\tend\n\t\tcase 'char'\n\t\t\tif isempty(children(t,uid))\t\n\t\t\t\tv = '';\n\t\t\telse\n\t\t\t\tv = get(t,children(t,uid),'value');\n\t\t\tend\n\t\tcase {'int8','uint8','int16','uint16','int32','uint32'}\n\t\t\t% TODO % Handle integer formats\n\t\t\twarning(sprintf('%s matrices not handled.',type));\n\t\t\tv = 0;\n\t\totherwise\n\t\t\ttry,\n\t\t\t\tv = feval(class(v),get(t,uid,'value'));\n\t\t\tcatch,\n\t\t\t\twarning(sprintf(...\n\t\t\t\t'[LOADXML] Cannot convert from XML to %s.',type));\n\t\t\tend\n\tend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_make3dimage.m", "ext": ".m", "path": "spm5-master/spm_eeg_make3dimage.m", "size": 842, "source_encoding": "utf_8", "md5": "56786cc3d8080f1ea73122f241ca284c", "text": "\nfunction D = spm_eeg_make3dimage(S)\n% function for converting 2D images to 3D volumes for ERPs\n% FORMAT D = spm_eeg_downsample(S)\n% \n% S\t\t - optional input struct\n% (optional) fields of S:\n% D\t\t\t- filename of EEG mat-file\n\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% James Kilner\n\ntry\n D = S.D;\ncatch\n D = spm_select(1, '\\.img$', 'Select EEG image file');\nend\n\nv=spm_vol([D]);\ndata=zeros(v(1).dim(1),v(1).dim(1),length(v));\nfor n=1:length(v)\n [temp,XYZ]=spm_read_vols(v(n));\n data(:,:,n)=temp;\nend\nV=v(1);\n[pathstr,name,ext,cersn] = spm_fileparts(D) ;\nV.fname = fullfile(pathstr,[name '3d.img']);\nV.dim = [v(1).dim(1) v(1).dim(2) length(v)];\nV.mat = eye(4);\n%V.pinfo = [1 0 0]';\nV = rmfield(V,'pinfo');\n\nspm_write_vol(V, data); \n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "treelist.m", "ext": ".m", "path": "spm5-master/treelist.m", "size": 10461, "source_encoding": "utf_8", "md5": "58343a29b98e2a4ea6134a424ebb9b43", "text": "% TREELIST - Lists data in cell arrays and structs as ascii \"tree\"\n%\n% Version 1.1\n%\n% This functions lists the contents of structs, sub struct, cell arrays\n% and sub cell array with chars: |-\\ viewing the connection in the data.\n% The main differents from the builtin DISP, DISPLAY is that this function\n% lists all levels of sub cell arrays or struct in cells or structs.\n%\n% The syntax is similar to WHOS:\n%\n% treelist varname1 varname2 .....\n%\n% By default, treelist does not show field contents and does not expand\n% struct arrays. This behaviour can be changed by calling treelist as a\n% function:\n%\n% treelist('varname1','varname2',...,flags)\n%\n% where flags is a struct that may contain the following fields: \n% .dval - display values of fields? \n% 0 (default) don't display values\n% 1 display values in tree structure\n% 2 display values in (nearly) MATLAB script syntax, suitable for\n% output to a script file (see fname below) - see BUGs for the\n% limitations to this option\n% .exps - expand struct arrays?\n% 0 (default) don't expand\n% 1 expand each member of struct arrays\n% .fname - output file name. If not empty, output will be redirected to\n% the given file\n%\n% (C) Copyright 2002 Peter Rydesaeter, GNU General Public License.\n% 2004 Modified by Volkmar Glauche to make struct array expansion and\n% value display optional.\n%\n% Se also:\n%\n% WHOS, WHO, DISP, DISPLAY, CELL, STRUCT\n% \n% BUGs:\n% Displaying values as MATLAB code is limited by the following\n% constraints: \n% * Object treatment is implemented only to a limited degree.\n\nfunction treelist(varargin)\n defflags = struct('dval',0, 'exps',0, 'fid',1, 'fname','');\n if isstruct(varargin{end})\n flags = fillstruct(defflags,varargin{end});\n nvars = nargin-1;\n else\n flags = defflags;\n nvars = nargin;\n end;\n if ~isempty(flags.fname)\n flags.fid = fopen(flags.fname,'w');\n end; \n for n=1:nvars,\n try\n v = evalin('caller',varargin{n});\n iname = varargin{n};\n catch\n v = varargin{n};\n iname = inputname(n);\n end;\n % for documentation, list things twice if creating MATLAB code and\n % writing to a file - first listing the variable structure only\n if flags.dval==2 && flags.fid > 2\n flags1=flags;\n flags1.dval=0;\n treelistsub(v,iname,'','',flags1);\n end;\n treelistsub(v,iname,'','',flags);\n end\n if flags.fid > 2\n fclose(flags.fid);\n end;\n return;\n \nfunction treelistsub(dt,name,nameprefix,level,flags)\nif nargin<4, level=''; end\nif nargin<3, nameprefix=''; end\nif nargin<2, name=inputname(1); end\nwhosdt=whos('dt');\nif isobject(dt)\n dtclass='object';\nelse\n dtclass=whosdt.class;\nend;\nswitch dtclass\ncase {'double', 'logical', 'single', 'uint8', 'uint16', 'uint32', 'uint64', ...\n 'int8', 'int16', 'int32', 'int64', 'char'}\n if isempty(dt),\n if flags.dval <= 1\n dtstr={{'[]'}};\n elseif flags.dval == 2\n dtstr={{''}};\n end;\n else\n if (flags.dval == 1) || strcmp(dtclass, 'char')\n dtstr=textscan(evalc('format compact;format long g;disp(full(dt));format'), '%s', ...\n 'delimiter', char(10));\n elseif (flags.dval == 2) && ~strcmp(dtclass, 'char')\n % Display full(dt(:)) and reshape it after printing - this\n % should remedy all problems with sparse and multidim arrays\n dtstr=textscan(evalc('format compact;format long g;disp(full(dt(:)));format'),...\n '%s', 'delimiter', char(10));\n else\n dtstr={{sprintf('%s%d %s', sprintf('%d-x-',whosdt.size(1:end-1)), ...\n whosdt.size(end), dtclass)}};\n end;\n end\n if flags.dval < 2\n if length(level)==0,\n ss=sprintf('%s',name);\n else\n ss=sprintf('%s-%s ',level,name);\n end\n lv=length(level)+20;\n if length(ss) 1\n fprintf(flags.fid,'%s%s = struct([]);\\n',nameprefix,name);\n end;\n return;\n elseif numel(dt)>1,\n if flags.exps\n fprintf(flags.fid,'%% %s-%s \\n',level,name);\n level(find(level=='\\'))=' ';\n if flags.dval > 1\n fprintf(flags.fid,['%%==============================================' ...\n '================\\n']);\n fprintf(flags.fid,'%% %s%s\\n',nameprefix,name);\n fprintf(flags.fid,['%%==============================================' ...\n '================\\n']);\n end;\n % get ndims and size to produce correct indices\n funcstr=get_index_func(dt);\n for m=1:numel(dt),\n eval(funcstr);\n newname = sprintf('%s(%s)',name,msubstr);\n if flags.dval > 1\n fprintf(flags.fid,['%%----------------------------------------------' ...\n '----------------\\n']);\n fprintf(flags.fid,'%% %s%s\\n',nameprefix,newname);\n fprintf(flags.fid,['%%----------------------------------------------' ...\n '----------------\\n']);\n end;\n if m==numel(dt),\n treelistsub(dt(m),newname,nameprefix,[level ' \\'],flags);\n else\n treelistsub(dt(m),newname,nameprefix,[level ' |'],flags);\n end\n end\n else\n dtstr=sprintf('%s-%s %d-x-',level,name,whosdt.size(1:end-1));\n level(find(level=='\\'))=' ';\n dtstr=fprintf(flags.fid,'%% %s%d struct array with fields\\n',dtstr,whosdt.size(end));\n for n=1:numel(fn)\n fprintf(flags.fid,'%%%s %s\\n', level, fn{n});\n end;\n end;\n return;\n else\n if flags.dval<2\n fprintf(flags.fid,'%% %s-%s\\n',level,name);\n end;\n level(find(level=='\\'))=' ';\n ww = warning('off'); %%HACK To remove warning msg\n if flags.dval==2 && strcmp(dtclass,'object')\n fprintf(flags.fid,'%s%s = %s;\\n', ...\n nameprefix,name,whosdt.class);\n end;\n for n=1:numel(fn),\n dts=getfield(dt,fn{n});\n newname=sprintf('%s',fn{n});\n newnameprefix=sprintf('%s%s.',nameprefix,name);\n if n==numel(fn),\n\t treelistsub(dts,newname,newnameprefix,[level ' \\'],flags);\n else\n\t treelistsub(dts,newname,newnameprefix,[level ' |'],flags);\n end\n end;\n warning(ww);\n end\n return;\n case 'cell',\n if numel(dt)==0,\n fprintf(flags.fid,'%% %s-%s Empty CELL\\n',level,name); \n if flags.dval > 1\n fprintf(flags.fid,'%s%s = {};\\n',nameprefix,name);\n end;\n return;\n end\n fprintf(flags.fid,'%% %s-%s \\n',level,name);\n level(find(level=='\\'))=' ';\n % get ndims and size to produce correct indices\n funcstr=get_index_func(dt);\n for m=1:numel(dt),\n eval(funcstr);\n newname=sprintf('%s{%s}',name,msubstr);\n if m==numel(dt),\n\ttreelistsub(dt{m},newname,nameprefix,[level ' \\'],flags);\n else\n\ttreelistsub(dt{m},newname,nameprefix,[level ' |'],flags);\n end\n end\n return;\n otherwise\n fprintf('%% %s-%s Unknown item of class ''%s''\\n', level, name, ...\n whosdt.class);\n end\n return;\n \nfunction funcstr = get_index_func(dt,varargin)\n% produce code to correctly convert linear indexes to subscript indexes\n% for variable dt\n% Assumptions:\n% - index array will be called 'ind'\n% - running variable is called 'm'\n% - printout of subscript index is called 'msubstr'\n\ndefflags = struct('indname','ind', 'runname','m', 'subsname','msubstr');\nif nargin > 1\n flags = fillstruct(defflags,varargin{1});\nelse\n flags = defflags;\nend;\n\n% get ndims and size to produce correct indices\nnddt = ndims(dt);\nszdt = size(dt);\n% omit last dimension for 1-x-N arrays (vectors), but don't do that for\n% N-x-1 arrays. The former ones may be created using assignments like\n% dt(k)=val_of_dt, while the latter ones must have been created with\n% dt(k,1)=val_of_dt and must be assumed to be deliberately assigned to\n% columns instead of rows.\nif szdt(1)==1\n nddt = nddt-1;\n szdt = szdt(2:end);\nend;\nindstr = sprintf(sprintf('%s(%%d),',flags.indname),1:nddt);\nfuncstr = sprintf(['[%s] = ind2sub([%s],%s);%s=sprintf(''%%d,'',%s);' ...\n'%s=%s(1:end-1);'], indstr(1:end-1), num2str(szdt), flags.runname, ...\n flags.subsname, flags.indname, flags.subsname, flags.subsname);\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_normalise.m", "ext": ".m", "path": "spm5-master/spm_normalise.m", "size": 13162, "source_encoding": "utf_8", "md5": "20a4dada77c2a5124d6b3710a07e7d31", "text": "function params = spm_normalise(VG,VF,matname,VWG,VWF,flags)\n% Spatial (stereotactic) normalization\n%\n% FORMAT params = spm_normalise(VG,VF,matname,VWG,VWF,flags)\n% VG - template handle(s)\n% VF - handle of image to estimate params from\n% matname - name of file to store deformation definitions\n% VWG - template weighting image\n% VWF - source weighting image\n% flags - flags. If any field is not passed, then defaults are assumed.\n% smosrc - smoothing of source image (FWHM of Gaussian in mm).\n% Defaults to 8.\n% smoref - smoothing of template image (defaults to 0).\n% regtype - regularisation type for affine registration\n% See spm_affreg.m (default = 'mni').\n% cutoff - Cutoff of the DCT bases. Lower values mean more\n% basis functions are used (default = 30mm).\n% nits - number of nonlinear iterations (default=16).\n% reg - amount of regularisation (default=0.1)\n% ___________________________________________________________________________\n% \n% This module spatially (stereotactically) normalizes MRI, PET or SPECT\n% images into a standard space defined by some ideal model or template\n% image[s]. The template images supplied with SPM conform to the space\n% defined by the ICBM, NIH P-20 project, and approximate that of the\n% the space described in the atlas of Talairach and Tournoux (1988).\n% The transformation can also be applied to any other image that has\n% been coregistered with these scans.\n%\n% \n% Mechanism\n% Generally, the algorithms work by minimising the sum of squares\n% difference between the image which is to be normalised, and a linear\n% combination of one or more template images. For the least squares\n% registration to produce an unbiased estimate of the spatial\n% transformation, the image contrast in the templates (or linear\n% combination of templates) should be similar to that of the image from\n% which the spatial normalization is derived. The registration simply\n% searches for an optimum solution. If the starting estimates are not\n% good, then the optimum it finds may not find the global optimum.\n% \n% The first step of the normalization is to determine the optimum\n% 12-parameter affine transformation. Initially, the registration is\n% performed by matching the whole of the head (including the scalp) to\n% the template. Following this, the registration proceeded by only\n% matching the brains together, by appropriate weighting of the template\n% voxels. This is a completely automated procedure (that does not\n% require ``scalp editing'') that discounts the confounding effects of\n% skull and scalp differences. A Bayesian framework is used, such that\n% the registration searches for the solution that maximizes the a\n% posteriori probability of it being correct. i.e., it maximizes the\n% product of the likelihood function (derived from the residual squared\n% difference) and the prior function (which is based on the probability\n% of obtaining a particular set of zooms and shears).\n% \n% The affine registration is followed by estimating nonlinear deformations,\n% whereby the deformations are defined by a linear combination of three\n% dimensional discrete cosine transform (DCT) basis functions.\n% The parameters represent coefficients of the deformations in\n% three orthogonal directions. The matching involved simultaneously\n% minimizing the bending energies of the deformation fields and the\n% residual squared difference between the images and template(s).\n% \n% An option is provided for allowing weighting images (consisting of pixel\n% values between the range of zero to one) to be used for registering\n% abnormal or lesioned brains. These images should match the dimensions\n% of the image from which the parameters are estimated, and should contain\n% zeros corresponding to regions of abnormal tissue.\n% \n% \n% Uses\n% Primarily for stereotactic normalization to facilitate inter-subject\n% averaging and precise characterization of functional anatomy. It is\n% not necessary to spatially normalise the data (this is only a\n% pre-requisite for intersubject averaging or reporting in the\n% Talairach space).\n% \n% Inputs\n% The first input is the image which is to be normalised. This image\n% should be of the same modality (and MRI sequence etc) as the template\n% which is specified. The same spatial transformation can then be\n% applied to any other images of the same subject. These files should\n% conform to the SPM data format (See 'Data Format'). Many subjects can\n% be entered at once, and there is no restriction on image dimensions\n% or voxel size.\n% \n% Providing that the images have a correct \".mat\" file associated with\n% them, which describes the spatial relationship between them, it is\n% possible to spatially normalise the images without having first\n% resliced them all into the same space. The \".mat\" files are generated\n% by \"spm_realign\" or \"spm_coregister\".\n% \n% Default values of parameters pertaining to the extent and sampling of\n% the standard space can be changed, including the model or template\n% image[s].\n% \n% \n% Outputs\n% All normalized *.img scans are written to the same subdirectory as\n% the original *.img, prefixed with a 'n' (i.e. n*.img). The details\n% of the transformations are displayed in the results window, and the\n% parameters are saved in the \"*_sn.mat\" file.\n% \n% \n%____________________________________________________________________________\n% Refs:\n% K.J. Friston, J. Ashburner, C.D. Frith, J.-B. Poline,\n% J.D. Heather, and R.S.J. Frackowiak\n% Spatial Registration and Normalization of Images.\n% Human Brain Mapping 2:165-189(1995)\n% \n% J. Ashburner, P. Neelin, D.L. Collins, A.C. Evans and K. J. Friston\n% Incorporating Prior Knowledge into Image Registration.\n% NeuroImage 6:344-352 (1997)\n%\n% J. Ashburner and K. J. Friston\n% Nonlinear Spatial Normalization using Basis Functions.\n% Human Brain Mapping 7(4):in press (1999)\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_normalise.m 946 2007-10-15 16:36:06Z john $\n\n\nif nargin<2, error('Incorrect usage.'); end;\nif ischar(VF), VF = spm_vol(VF); end;\nif ischar(VG), VG = spm_vol(VG); end;\nif nargin<3,\n\tif nargout==0,\n\t\t[pth,nm,xt,vr] = spm_fileparts(deblank(VF(1).fname));\n\t\tmatname = fullfile(pth,[nm '_sn.mat']);\n else\n\t\tmatname = '';\n\tend;\nend;\nif nargin<4, VWG = ''; end;\nif nargin<5, VWF = ''; end;\nif ischar(VWG), VWG=spm_vol(VWG); end;\nif ischar(VWF), VWF=spm_vol(VWF); end; \n\n\ndef_flags = struct('smosrc',8,'smoref',0,'regtype','mni',...\n\t'cutoff',30,'nits',16,'reg',0.1,'graphics',1);\nif nargin < 6,\n\tflags = def_flags;\nelse\n\tfnms = fieldnames(def_flags);\n\tfor i=1:length(fnms),\n\t\tif ~isfield(flags,fnms{i}),\n flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));\n end;\n\tend;\nend;\n\nfprintf('Smoothing by %g & %gmm..\\n', flags.smoref, flags.smosrc);\nVF1 = spm_smoothto8bit(VF,flags.smosrc);\n\n% Rescale images so that globals are better conditioned\nVF1.pinfo(1:2,:) = VF1.pinfo(1:2,:)/spm_global(VF1);\nfor i=1:numel(VG),\n VG1(i) = spm_smoothto8bit(VG(i),flags.smoref);\n VG1(i).pinfo(1:2,:) = VG1(i).pinfo(1:2,:)/spm_global(VG(i));\nend;\n\n% Affine Normalisation\n%-----------------------------------------------------------------------\nfprintf('Coarse Affine Registration..\\n');\naflags = struct('sep',max(flags.smoref,flags.smosrc), 'regtype',flags.regtype,...\n\t'WG',[],'WF',[],'globnorm',0);\naflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2))));\naflags.sep = max(aflags.sep,max(sqrt(sum(VF(1).mat(1:3,1:3).^2))));\n\nM = eye(4); %spm_matrix(prms');\nspm_chi2_plot('Init','Affine Registration','Mean squared difference','Iteration');\n[M,scal] = spm_affreg(VG1, VF1, aflags, M);\n \nfprintf('Fine Affine Registration..\\n');\naflags.WG = VWG;\naflags.WF = VWF;\naflags.sep = aflags.sep/2;\n[M,scal] = spm_affreg(VG1, VF1, aflags, M,scal);\nAffine = inv(VG(1).mat\\M*VF1(1).mat);\nspm_chi2_plot('Clear');\n\n% Basis function Normalisation\n%-----------------------------------------------------------------------\nfov = VF1(1).dim(1:3).*sqrt(sum(VF1(1).mat(1:3,1:3).^2));\nif any(fov<15*flags.smosrc/2 & VF1(1).dim(1:3)<15),\n\tfprintf('Field of view too small for nonlinear registration\\n');\n\tTr = [];\nelseif isfinite(flags.cutoff) && flags.nits && ~isinf(flags.reg),\n fprintf('3D CT Norm...\\n');\n\tTr = snbasis(VG1,VF1,VWG,VWF,Affine,...\n\t\tmax(flags.smoref,flags.smosrc),flags.cutoff,flags.nits,flags.reg);\nelse\n\tTr = [];\nend;\nclear VF1 VG1\n\nflags.version = 'spm_normalise.m 2.12 04/11/26';\nflags.date = date;\n\nparams = struct('Affine',Affine, 'Tr',Tr, 'VF',VF, 'VG',VG, 'flags',flags);\n\nif flags.graphics, spm_normalise_disp(params,VF); end;\n\n% Remove dat fields before saving\n%-----------------------------------------------------------------------\nif isfield(VF,'dat'), VF = rmfield(VF,'dat'); end;\nif isfield(VG,'dat'), VG = rmfield(VG,'dat'); end;\nif ~isempty(matname),\n\tfprintf('Saving Parameters..\\n');\n if spm_matlab_version_chk('7') >= 0,\n\t\tsave(matname,'-V6','Affine','Tr','VF','VG','flags');\n\telse\n\t\tsave(matname,'Affine','Tr','VF','VG','flags');\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg)\n% 3D Basis Function Normalization\n% FORMAT Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg)\n% VG - Template volumes (see spm_vol).\n% VF - Volume to normalize.\n% VWG - weighting Volume - for template.\n% VWF - weighting Volume - for object.\n% Affine - A 4x4 transformation (in voxel space).\n% fwhm - smoothness of images.\n% cutoff - frequency cutoff of basis functions.\n% nits - number of iterations.\n% reg - regularisation.\n% Tr - Discrete cosine transform of the warps in X, Y & Z.\n%\n% snbasis performs a spatial normalization based upon a 3D\n% discrete cosine transform.\n%\n%______________________________________________________________________\n\nfwhm = [fwhm 30];\n\n% Number of basis functions for x, y & z\n%-----------------------------------------------------------------------\ntmp = sqrt(sum(VG(1).mat(1:3,1:3).^2));\nk = max(round((VG(1).dim(1:3).*tmp)/cutoff),[1 1 1]);\n\n% Scaling is to improve stability.\n%-----------------------------------------------------------------------\nstabilise = 8;\nbasX = spm_dctmtx(VG(1).dim(1),k(1))*stabilise;\nbasY = spm_dctmtx(VG(1).dim(2),k(2))*stabilise;\nbasZ = spm_dctmtx(VG(1).dim(3),k(3))*stabilise;\n\ndbasX = spm_dctmtx(VG(1).dim(1),k(1),'diff')*stabilise;\ndbasY = spm_dctmtx(VG(1).dim(2),k(2),'diff')*stabilise;\ndbasZ = spm_dctmtx(VG(1).dim(3),k(3),'diff')*stabilise;\n\nvx1 = sqrt(sum(VG(1).mat(1:3,1:3).^2));\nvx2 = vx1;\nkx = (pi*((1:k(1))'-1)/VG(1).dim(1)/vx1(1)).^2; ox=ones(k(1),1);\nky = (pi*((1:k(2))'-1)/VG(1).dim(2)/vx1(2)).^2; oy=ones(k(2),1);\nkz = (pi*((1:k(3))'-1)/VG(1).dim(3)/vx1(3)).^2; oz=ones(k(3),1);\n\nif 1,\n % BENDING ENERGY REGULARIZATION\n % Estimate a suitable sparse diagonal inverse covariance matrix for\n % the parameters (IC0).\n %-----------------------------------------------------------------------\n\tIC0 = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +...\n\t 1*kron(kz.^0,kron(ky.^2,kx.^0)) +...\n\t 1*kron(kz.^0,kron(ky.^0,kx.^2)) +...\n\t 2*kron(kz.^1,kron(ky.^1,kx.^0)) +...\n\t 2*kron(kz.^1,kron(ky.^0,kx.^1)) +...\n\t 2*kron(kz.^0,kron(ky.^1,kx.^1)) );\n IC0 = reg*IC0*stabilise^6;\n IC0 = [IC0*vx2(1)^4 ; IC0*vx2(2)^4 ; IC0*vx2(3)^4 ; zeros(prod(size(VG))*4,1)];\n IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0));\nelse\n % MEMBRANE ENERGY (LAPLACIAN) REGULARIZATION\n %-----------------------------------------------------------------------\n IC0 = kron(kron(oz,oy),kx) + kron(kron(oz,ky),ox) + kron(kron(kz,oy),ox);\n IC0 = reg*IC0*stabilise^6;\n IC0 = [IC0*vx2(1)^2 ; IC0*vx2(2)^2 ; IC0*vx2(3)^2 ; zeros(prod(size(VG))*4,1)];\n IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0));\nend;\n\n% Generate starting estimates.\n%-----------------------------------------------------------------------\ns1 = 3*prod(k);\ns2 = s1 + numel(VG)*4;\nT = zeros(s2,1);\nT(s1+(1:4:numel(VG)*4)) = 1;\n\npVar = Inf;\nfor iter=1:nits,\n\tfprintf(' iteration %2d: ', iter);\n\t[Alpha,Beta,Var,fw] = spm_brainwarp(VG,VF,Affine,basX,basY,basZ,dbasX,dbasY,dbasZ,T,fwhm,VWG, VWF);\n\tif Var>pVar, scal = pVar/Var ; Var = pVar; else scal = 1; end;\n\tpVar = Var;\n\tT = (Alpha + IC0*scal)\\(Alpha*T + Beta);\n\tfwhm(2) = min([fw fwhm(2)]);\n\tfprintf(' FWHM = %6.4g Var = %g\\n', fw,Var);\nend;\n\n% Values of the 3D-DCT - for some bizarre reason, this needs to be done\n% as two seperate statements in Matlab 6.5...\n%-----------------------------------------------------------------------\nTr = reshape(T(1:s1),[k 3]);\ndrawnow;\nTr = Tr*stabilise.^3;\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_pf.m", "ext": ".m", "path": "spm5-master/spm_pf.m", "size": 6775, "source_encoding": "utf_8", "md5": "2789f6cf4185c0bae57568078459b24d", "text": "function [qx,qP,qD,xhist] = spm_pf(M,y,U)\n% Particle Filtering for dynamic models\n% FORMAT [qx,qP,qD,xhist] = spm_pf(M,y)\n% M - model specification structure\n% y - output or data (N x T)\n% U - exogenous input\n%\n% M(1).x % initial states\n% M(1).f = inline(f,'x','v','P') % state equation\n% M(1).g = inline(g,'x','v','P') % observer equation\n% M(1).pE % parameters\n% M(1).V % observation noise precision\n%\n% M(2).v % initial process noise\n% M(2).V % process noise precision\n%\n% qx - conditional expectation of states\n% qP - {1 x T} conditional covariance of states\n% qD - full sample\n%__________________________________________________________________________\n% See notes at the end of this script for details and a demo. This routine\n% is based on:\n%\n% var der Merwe R, Doucet A, de Freitas N and Wan E (2000). The\n% unscented particle filter. Technical Report CUED/F-INFENG/TR 380\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Karl Friston\n% $Id: spm_pf.m 894 2007-08-23 18:37:51Z karl $\n\n\n\n\n% check model specification\n%--------------------------------------------------------------------------\nM = spm_DEM_M_set(M);\ndt = M(1).E.dt;\nif length(M) ~=2\n errordlg('spm_pf requires a two-level model')\n return\nend\n\n% INITIALISATION:\n%==========================================================================\nT = length(y); % number of time points\nn = M(2).l; % number of innovations\nN = 200; % number of particles.\n \n% precision of measurement noise\n%--------------------------------------------------------------------------\nR = M(1).V;\nfor i = 1:length(M(1).Q)\n R = R + M(1).Q{i}*exp(M(1).h(i));\nend\nP = M(1).pE; % parameters\nQ = M(2).V.^-.5; % root covariance of innovations\nv = kron(ones(1,N),M(2).v); % innovations\nx = kron(ones(1,N),M(1).x); % hidden states\nv = v + 128*Q*randn(size(v));\n\n% inputs\n%--------------------------------------------------------------------------\nif nargin < 3\n U = sparse(n,T);\nend\n\nfor t = 1:T\n\n % PREDICTION STEP: with the (8x) transition prior as proposal\n %----------------------------------------------------------------------\n for i = 1:N\n v(:,i) = 8*Q*randn(n,1) + U(:,t);\n f = M(1).f(x(:,i),v(:,i),P);\n dfdx = spm_diff(M(1).f,x(:,i),v(:,i),P,1);\n xPred(:,i) = x(:,i) + spm_dx(dfdx,f,dt);\n end\n\n % EVALUATE IMPORTANCE WEIGHTS: and normalise\n %----------------------------------------------------------------------\n for i = 1:N\n yPred = M(1).g(xPred(:,i),v(:,i),P);\n ePred = yPred - y(:,t);\n w(i) = ePred'*R*ePred;\n end\n w = w - min(w);\n w = exp(-w/2);\n w = w/sum(w);\n\n % SELECTION STEP: multinomial resampling.\n %---------------------------------------------------------------------- \n x = xPred(:,multinomial(1:N,w));\n\n % report and record moments\n %----------------------------------------------------------------------\n qx(:,t) = mean(x,2);\n qP{t} = cov(x');\n qX(:,t) = x(:);\n fprintf('PF: time-step = %i : %i\\n',t,T);\nend\n\n% sample density\n%==========================================================================\nif nargout > 3\n xhist = linspace(min(qX(:)),max(qX(:)),32);\n for i = 1:T\n q = hist(qX(:,i),xhist);\n qD(:,i) = q(:);\n end\nend\n\nreturn\n\nfunction I = multinomial(inIndex,q);\n%==========================================================================\n% PURPOSE : Performs the resampling stage of the SIR\n% in order(number of samples) steps.\n% INPUTS : - inIndex = Input particle indices.\n% - q = Normalised importance ratios.\n% OUTPUTS : - I = Resampled indices.\n% AUTHORS : Arnaud Doucet and Nando de Freitas\n\n% MULTINOMIAL SAMPLING:\n% generate S ordered random variables uniformly distributed in [0,1]\n% high speed Niclas Bergman Procedure\n%--------------------------------------------------------------------------\nq = q(:);\nS = length(q); % S = Number of particles.\nN_babies = zeros(1,S);\ncumDist = cumsum(q');\n\nu = fliplr(cumprod(rand(1,S).^(1./(S:-1:1))));\nj = 1;\nfor i = 1:S\n while (u(1,i) > cumDist(1,j))\n j = j + 1;\n end\n N_babies(1,j) = N_babies(1,j) + 1;\nend;\n\n% COPY RESAMPLED TRAJECTORIES:\n%--------------------------------------------------------------------------\nindex = 1;\nfor i = 1:S\n if (N_babies(1,i)>0)\n for j=index:index+N_babies(1,i)-1\n I(j) = inIndex(i);\n end;\n end;\n index = index + N_babies(1,i);\nend\n\nreturn\n%==========================================================================\n\n% notes and demo:\n%==========================================================================\n% The code below generates a nonlinear, non-Gaussian problem (S) comprising\n% a model S.M and data S.Y (c.f. van der Merwe et al 2000))\n%\n% The model is f(x) = dxdt\n% = 1 + sin(0.04*pi*t) - log(2)*x + n\n% y = g(x)\n% = (x.^2)/5 : if t < 30\n% -2 + x/2 : otherwise\n% i.e. the output nonlinearity becomes linear after 30 time steps. In this\n% implementation time is modelled as an auxiliary state variable. n is\n% the process noise, which is modelled as a log-normal variate. e is\n% Gaussian observation noise.\n\n% model specification\n%--------------------------------------------------------------------------\nf = '[1; (1 + sin(P(2)*pi*x(1)) - P(1)*x(2) + exp(v))]';\ng = '(x(1) > 30)*(-2 + x(2)/2) + ~(x(1) > 30)*(x(2).^2)/5';\nM(1).x = [1; 1]; % initial states\nM(1).f = inline(f,'x','v','P'); % state equation\nM(1).g = inline(g,'x','v','P'); % observer equation\nM(1).pE = [log(2) 0.04]; % parameters\nM(1).V = exp(4); % observation noise precision\n\nM(2).v = 0; % initial process log(noise)\nM(2).V = 2.4; % process log(noise) precision\n\n% generate data (output)\n%--------------------------------------------------------------------------\nT = 60; % number of time points\nS = spm_DEM_generate(M,T);\n\n% Particle filtering\n%--------------------------------------------------------------------------\npf_x = spm_pf(M,S.Y);\n\n% plot results\n%--------------------------------------------------------------------------\nx = S.pU.x{1};\nplot([1:T],x(2,:),[1:T],pf_x(2,:))\nlegend({'true','PF'})\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_SpUtil.m", "ext": ".m", "path": "spm5-master/spm_SpUtil.m", "size": 26532, "source_encoding": "utf_8", "md5": "3b40e62f97e91ccb5a8bc1cac222f39d", "text": "function varargout = spm_SpUtil(varargin)\n% Space matrix utilities\n% FORMAT varargout = spm_SpUtil(action,varargin)\n%\n%_______________________________________________________________________\n%\n% spm_SpUtil is a multi-function function containing various utilities\n% for Design matrix and contrast construction and manipulation. In\n% general, it accepts design matrices as plain matrices or as space\n% structures setup by spm_sp.\n%\n% Many of the space utilities are computed using an SVD of the design\n% matrix. The advantage of using space structures is that the svd of\n% the design matrix is stored in the space structure, thereby saving\n% unnecessary repeated computation of the SVD. This presents a\n% considerable efficiency gain for large design matrices.\n%\n% Note that when space structures are passed as arguments is is\n% assummed that their basic fields are filled in. See spm_sp for\n% details of (design) space structures and their manipulation.\n%\n% Quick Reference :\n%---------------------\n% ('isCon',x,c) :\n% ('allCon',x,c) :\n% ('ConR',x,c) :\n% ('ConO',x,c) :\n% ('size',x,dim) :\n% ('iX0check',i0,sL) :\n%---------------------\n% ('i0->c',x,i0) : Out : c\n% ('c->Tsp',x,c) : Out : [X1o [X0]]\n% ('+c->Tsp',x,c) : Out : [ukX1o [ukX0]]\n% ('i0->x1o',x,i0) : Use ('i0->c',x,i0) and ('c->Tsp',X,c)\n% ('+i0->x1o',x,i0) : Use ('i0->c',x,i0) and ('+c->Tsp',X,c)\n% ('X0->c',x,X0) :~ \n% ('+X0->c',x,cukX0) :~ \n%---------------------\n% ('trRV',x[,V]) :\n% ('trMV',x[,V]) :\n% ('i0->edf',x,i0,V) :\n%\n%---------------------\n%\n% Improvement compared to the spm99 beta version :\n%\n% Improvements in df computation using spm_SpUtil('trRV',x[,V]) and\n% spm_SpUtil('trMV',sX [,V]). The degrees of freedom computation requires\n% in general that the trace of RV and of RVRV be computed, where R is a\n% projector onto either a sub space of the design space or the residual\n% space, namely the space that is orthogonal to the design space. V is\n% the (estimated or assumed) variance covariance matrix and is a number\n% of scans by number of scans matrix which can be huge in some cases. We\n% have (thanks to S Rouquette and JB) speed up this computation \n% by using matlab built in functions of the frobenius norm and some theorems\n% on trace computations. \n%\n% ======================================================================\n%\n% FORMAT i = spm_SpUtil('isCon',x,c)\n% Tests whether weight vectors specify contrasts\n% x - Design matrix X, or space structure of X\n% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)\n% Must have column dimension matching that of X\n% [defaults to eye(size(X,2)) to test uniqueness of parameter estimates]\n% i - logical row vector indiciating estimability of contrasts in c\n%\n% A linear combination of the parameter estimates is a contrast if and\n% only if the weight vector is in the space spanned by the rows of X.\n%\n% The algorithm works by regressing the contrast weight vectors using\n% design matrix X' (X transposed). Any contrast weight vectors will be\n% fitted exactly by this procedure, leaving zero residual. Parameter\n% tol is the tolerance applied when searching for zero residuals.\n%\n% Christensen R (1996)\n%\t\"Plane Answers to Complex Questions\"\n%\t 2nd Ed. Springer-Verlag, New York\n%\n% Andrade A, Paradis AL, Rouquette S and Poline JB, NeuroImage 9, 1999\n% ----------------\n%\n% FORMAT i = spm_SpUtil('allCon',x,c)\n% Tests whether all weight vectors specify contrasts:\n% Same as all(spm_SpUtil('isCon',x,c)).\n%\n% ----------------\n%\n% FORMAT r = spm_SpUtil('ConR',x,c)\n% Assess orthogonality of contrasts (wirit the data)\n% x - Design matrix X, or space structure of X\n% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)\n% Must have column dimension matching that of X\n% defaults to eye(size(X,2)) to test independence of parameter estimates\n% r - Contrast correlation matrix, of dimension the number of contrasts.\n%\n% For the general linear model Y = X*B + E, a contrast weight vector c\n% defines a contrast c*B. This is estimated by c*b, where b are the\n% least squares estimates of B given by b=pinv(X)*Y. Thus, c*b = w*Y,\n% where weight vector w is given by w=c*pinv(X); Since the data are\n% assummed independent, two contrasts are indpendent if the\n% corresponding weight vectors are orthogonal.\n%\n% r is the matrix of normalised inner products between the weight\n% vectors corresponding to the contrasts. For iid E, r is the\n% correlation matrix of the contrasts.\n%\n% The logical matrix ~r will be true for orthogonal pairs of contrasts.\n% \n% ----------------\n%\n% FORMAT r = spm_SpUtil('ConO',x,c)\n% Assess orthogonality of contrasts (wirit the data)\n% x - Design matrix X, or space structure of X\n% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)\n% Must have column dimension matching that of X\n% [defaults to eye(size(X,2)) to test uniqueness of parameter estimates]\n% r - Contrast orthogonality matrix, of dimension the number of contrasts.\n%\n% This is the same as ~spm_SpUtil('ConR',X,c), but uses a quicker\n% algorithm by looking at the orthogonality of the subspaces of the\n% design space which are implied by the contrasts:\n% r = abs(c*X'*X*c')c',x,i0)\n% Return F-contrast for specified design matrix partition\n% x - Design matrix X, or space structure of X\n% i0 - column indices of null hypothesis design matrix\n%\n% This functionality returns a rank n mxp matrix of contrasts suitable\n% for an extra-sum-of-squares F-test comparing the design X, with a\n% reduced design. The design matrix for the reduced design is X0 =\n% X(:,i0), a reduction of n degrees of freedom.\n%\n% The algorithm, due to J-B, and derived from Christensen, computes the\n% contrasts as an orthonormal basis set for the rows of the\n% hypothesised redundant columns of the design matrix, after\n% orthogonalisation with respect to X0. For non-unique designs, there\n% are a variety of ways to produce equivalent F-contrasts. This method\n% produces contrasts with non-zero weights only for the hypothesised\n% redundant columns.\n%\n% ----------------\n% \n% case {'x0->c'}\t\t\t\t%- \n% FORMAT c = spm_SpUtil('X0->c',sX,X0)\n% ----------------\n%\n% FORMAT [X1,X0] = spm_SpUtil('c->TSp',X,c)\n% Orthogonalised partitioning of design space implied by F-contrast\n% x - Design matrix X, or space structure of X\n% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)\n% Must have column dimension matching that of X\n% X1o - contrast space - design matrix corresponding according to contrast\n% (orthogonalised wirit X0)\n% X0 - matrix reduced according to null hypothesis\n% (of same size as X but rank deficient)\n% FORMAT [uX1,uX0] = spm_SpUtil('c->TSp+',X,c)\n% + version to deal with the X1o and X0 partitions in the \"uk basis\"\n%\n% ( Note that unless X0 is reduced to a set of linearely independant )\n% ( vectors, c will only be contained in the null space of X0. If X0 )\n% ( is \"reduced\", then the \"parent\" space of c must be reduced as well )\n% ( for c to be the actual null space of X0. )\n%\n% This functionality returns a design matrix subpartition whose columns\n% span the hypothesised null design space of a given contrast. Note\n% that X1 is orthogonal(ised) to X0, reflecting the situation when an\n% F-contrast is tested using the extra sum-of-squares principle (when\n% the extra distance in the hypothesised null space is measured\n% orthogonal to the space of X0).\n%\n% Note that the null space design matrix will probably not be a simple\n% sub-partition of the full design matrix, although the space spanned\n% will be the same.\n%\n% ----------------\n%\n% FORMAT X1 = spm_SpUtil('i0->x1o',X,i0)\n% x - Design matrix X, or space structure of X\n% i0 - Columns of X that make up X0 - the reduced model (Ho:B1=0)\n% X1 - Hypothesised null design space, i.e. that part of X orthogonal to X0\n% This offers the same functionality as the 'c->TSp' option, but for\n% simple reduced models formed from the columns of X.\n%\n% FORMAT X1 = spm_SpUtil('i0->x1o+',X,i0)\n% + version to deal with the X1o and X0 partitions in the \"uk basis\"\n%\n% ----------------\n%\n% FORMAT [trRV,trRVRV] = spm_SpUtil('trRV',x[,V])\n% trace(RV) & trace(RVRV) - used in df calculation\n% x - Design matrix X, or space structure of X\n% V - V matrix [defult eye] (trRV == trRVRV if V==eye, since R idempotent)\n% trRV - trace(R*V), computed efficiently\n% trRVRV - trace(R*V*R*V), computed efficiently\n% This uses the Karl's cunning understanding of the trace:\n% (tr(A*B) = sum(sum(A'*B)).\n% If the space of X is set, then algorithm uses x.u to avoid extra computation.\n%\n% ----------------\n%\n% FORMAT [trMV, trMVMV]] = spm_SpUtil('trMV',x[,V])\n% trace(MV) & trace(MVMV) if two ouput arguments.\n% x - Design matrix X, or space structure of X\n% V - V matrix [defult eye] (trMV == trMVMV if V==eye, since M idempotent)\n% trMV - trace(M*V), computed efficiently\n% trMVMV - trace(M*V*M*V), computed efficiently\n% Again, this uses the Karl's cunning understanding of the trace:\n% (tr(A*B) = sum(sum(A'.*B)).\n% If the space of X is set, then algorithm uses x.u to avoid extra computation.\n%\n% ----------------\n%\n% OBSOLETE use FcUtil('H') for spm_SpUtil('c->H',x,c) \n% Extra sum of squares matrix O for beta's from contrast\n% x - Design matrix X, or space structure of X\n% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)\n% Must have column dimension matching that of X\n% O - Matrix such that b'*O*b = extra sum of squares for F-test of contrast c\n%\n% ----------------\n%\n% OBSOLETE use spm_sp('=='...) for spm_SpUtil('c==X1o',x,c) {or 'cxpequi'}\n% x - Design matrix X, or space structure of X\n% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)\n% Must have column dimension matching that of X\n% b - True is c is a spanning set for space of X\n% (I.e. if contrast and space test the same thing)\n%\n% ----------------\n%\n% FORMAT [df1,df2] = spm_SpUtil('i0->edf',x,i0,V) {or 'edf'}\n% (effective) df1 and df2 the residual df for the projector onto the\n% null space of x' (residual forming projector) and the numerator of\n% the F-test where i0 are the columns for the null hypothesis model.\n% x - Design matrix X, or space structure of X\n% i0 - Columns of X corresponding to X0 partition X = [X1,X0] & with\n% parameters B = [B1;B0]. Ho:B1=0\n% V - V matrix\n%\n% ----------------\n%\n% FORMAT sz = spm_SpUtil('size',x,dim)\n% FORMAT [sz1,sz2,...] = spm_SpUtil('size',x)\n% Returns size of design matrix\n% (Like MatLab's `size`, but copes with design matrices inside structures.)\n% x - Design matrix X, or structure containing design matrix in field X\n% (Structure needn't be a space structure.)\n% dim - dimension which to size\n% sz - size\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Andrew Holmes Jean-Baptiste Poline\n% $Id: spm_SpUtil.m 112 2005-05-04 18:20:52Z john $\n\n% (frobenius norm trick by S. Rouquette)\n\n%-Format arguments\n%-----------------------------------------------------------------------\nif nargin==0, error('do what? no arguments given...')\n\telse, action = varargin{1}; end\n\n\nswitch lower(action), \n\ncase {'iscon','allcon','conr','cono'}\n%=======================================================================\n% i = spm_SpUtil('isCon',x,c)\nif nargin==0, varargout={[]}, error('isCon : no argument specified'), end;\nif nargin==1, \n varargout={[]}; warning('isCon : no contrast specified'); return; \nend;\nif ~spm_sp('isspc',varargin{2})\n\tsX = spm_sp('Set',varargin{2});\nelse, sX = varargin{2}; end\nif nargin==2, c=eye(spm_sp('size',sX,2)); else, c=varargin{3}; end;\nif isempty(c), varargout={[]}; return, end\n\nswitch lower(action)\n\tcase 'iscon'\n\t\tvarargout = { spm_sp('eachinspp',sX,c) };\n\tcase 'allcon'\n\t\tvarargout = {spm_sp('isinspp',sX,c)};\n\tcase 'conr'\n\t\tif size(c,1) ~= spm_sp('size',sX,2) \n\t\t\terror('Contrast not of the right size'), end\n\t\t%-Compute inner products of data weight vectors\n\t\t% (c'b = c'*pinv(X)*Y = w'*Y\n\t\t% (=> w*w' = c'*pinv(X)*pinv(X)'*c == c'*pinv(X'*X)*c\n\t\tr = c'*spm_sp('XpX-',sX)*c;\n\t\t%-normalize by \"cov(r)\" to get correlations\n\t\tr = r./(sqrt(diag(r))*sqrt(diag(r))');\n\t\tr(abs(r) < sX.tol)=0;\t\t%-set near-zeros to zero\n\t\tvarargout = {r};\t\t\t\t%-return r\n\tcase 'cono'\n\t\t%-This is the same as ~spm_SpUtil('ConR',x,c), and so returns\n\t\t% the contrast orthogonality (though not their corelations).\n\t\tvarargout = { abs(c'* spm_sp('XpX',sX) *c) < sX.tol};\nend\n\n\ncase {'+c->tsp','c->tsp'} %- Ortho. partitioning implied by F-contrast\n%=======================================================================\n% spm_SpUtil('c->Tsp',sX,c)\n% + version of 'c->tsp'. \n% The + version returns the same in the base u(:,1:r).\n\n%--------- begin argument check ------------------------------\nif nargin ~= 3, error(['Wrong number of arguments in ' action])\nelse, sX = varargin{2}; c = varargin{3}; end;\nif nargout > 2, error(['Too many output arguments in ' action]), end;\nif ~spm_sp('isspc',sX), sX = spm_sp('set',varargin{2}); end;\nif sX.rk == 0, error('c->Tsp null rank sX == 0'); end;\nif ~isempty(c) & spm_sp('size',sX,2) ~= size(c,1), \n error(' c->TSp matrix & contrast dimensions don''t match'); \nend\n%--------- end argument check ---------------------------------\t\n\n%- project c onto the space of X' if needed \n%-------------------------------------------\nif ~isempty(c) & ~spm_sp('isinspp',sX,c),\n warning([sprintf('\\n') 'c is not a proper contrast in ' action ...\n ' in ' mfilename sprintf('\\n') '!!! projecting...' ]);\n disp('from'), c, disp('to'), c = spm_sp('oPp:',sX,c)\nend\n\ncukFlag = strcmp(lower(action),'+c->tsp');\n\nswitch nargout\n% case 0\n% warning(['no output demanded in ' mfilename ' ' action])\ncase {0,1}\n if ~isempty(c) & any(any(c)) %- c not empty & not null\n if cukFlag, varargout = { spm_sp('cukxp-:',sX,c) };\n else varargout = { spm_sp('xp-:',sX,c) };\n end\n else if isempty(c), varargout = { [] }; %- c empty\n else, %- c null\n if cukFlag, varargout = { spm_sp('cukx',sX,c) }; \n else, varargout = { spm_sp('x',sX)*c };\n end\n end;\n end\n\ncase 2\n if ~isempty(c) & any(any(c)) %- not empty and not null\n if cukFlag,\n varargout = {\t\n\t spm_sp('cukxp-:',sX,c), ...\t\t\t\t%- X1o\n\t spm_sp('cukx',sX,spm_sp('r',spm_sp('set',c))) }; %- X0\n else\n varargout = {\t\n\t spm_sp(':',sX, spm_sp('xp-:',sX,c)), ... %- X1o\n\t spm_sp(':',sX, ...\n spm_sp('x',sX)*spm_sp('r',spm_sp('set',c))) }; %- X0\n end\n else \n if isempty(c), %- empty\n if cukFlag, varargout = { [], spm_sp('cukx',sX) }; \n else, varargout = { [], spm_sp('x',sX) };\n end\n else, %- null\n if cukFlag, \n varargout = { spm_sp(':',sX,spm_sp('cukx',sX,c)), ...\n spm_sp(':',sX,spm_sp('cukx',sX)) }; \n else,\n varargout = { spm_sp('x',sX)*c, spm_sp('x',sX)};\n end\n end;\n end\n\notherwise\n error(['wrong number of output argument in ' action]);\nend\n\n\ncase {'i0->x1o','+i0->x1o'} %- Space tested whilst keeping size of X(i0)\n%=======================================================================\n% X1o = spm_SpUtil('i0->X1o',sX,i0)\n\n% arguments are checked in calls to spm_Util\n%--------------------------------------------\nif nargin<3, error('Insufficient arguments'), \nelse, sX = varargin{2}; i0 = varargin{3}; end;\n\ncukFlag = strcmp(lower(action),'+i0->x1o');\n\nc = spm_SpUtil('i0->c',sX,i0);\n\nif cukFlag, \n varargout = { spm_SpUtil('+c->TSp',sX,c) };\nelse \n varargout = { spm_SpUtil('c->TSp',sX,c) };\nend\n\n\ncase {'i0->c'}\t\t\t %- \n%=======================================================================\n% c = spm_SpUtil('i0->c',sX,i0)\n%\n% if i0 == [] : returns a proper contrast\n% if i0 == [1:size(sX.X,2)] : returns [];\n%\n%- Algorithm : avoids the pinv(X0) and insure consistency\n%- Get the estimable parts of c0 and c1\n%- remove from c1_estimable the estimable part of c0.\n%- Use the rotation making X1o orthog. to X0.\n%- i0 is checked when Fc is created\n%- If i0 defines a space that is the space of X but with\n%- fewer vectors, c is null. \n\n%--------- begin argument check --------------------------------\nif nargin<3, error('Insufficient arguments'), \nelse, sX = varargin{2}; i0 = varargin{3}; end;\nif ~spm_sp('isspc',sX), sX = spm_sp('set',varargin{2}); end;\nif spm_sp('rk',sX) == 0, error('i0->c null rank sX == 0'); end;\nsL\t= spm_sp('size',sX,2);\ni0 \t= sf_check_i0(i0,sL);\n%--------- end argument check ---------------------------------- \n\nc0\t= eye(sL); c0 = c0(:,i0);\nc1\t= eye(sL); c1 = c1(:,setdiff(1:sL,i0));\n\n%- try to avoid the matlab error when doing svd of matrices with\n%- high multiplicities. (svd convergence pb)\n\nif ~ spm_sp('isinspp',sX,c0), c0 = spm_sp('oPp:',sX,c0); end;\nif ~ spm_sp('isinspp',sX,c1), c1 = spm_sp('oPp:',sX,c1); end;\n\nif ~isempty(c1)\n if ~isempty(c0) \n %- varargout = { spm_sp('res',spm_sp('set',opp*c0),opp*c1) };\n %- varargout = { c1 - c0*pinv(c0)*c1 }; NB: matlab pinv uses\n %- svd: will fail if spm_sp('set') fails. \n\n varargout = { spm_sp('r:',spm_sp('set',c0),c1) };\n\n else varargout = { spm_sp('xpx',sX) }; end;\nelse\n varargout = { [] };\t%- not zeros(sL,1) : this is return when \n\t\t\t%- appropriate\nend\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ncase {'+x0->c','x0->c'}\t\t\t\t%- \n%=======================================================================\n% c = spm_SpUtil('X0->c',sX,X0)\n% c = spm_SpUtil('+X0->c',sX,cukX0)\n% + version of 'x0->c'. \n% The + version returns the same in the base u(:,1:r).\n\nwarning('Not tested for release - provided for completeness');\ncukFlag = strcmp(lower(action),'+x0->c');\n\n%--------- begin argument check --------- \nif nargin<3, error('Insufficient arguments'), \nelse, \n sX = varargin{2}; \n if cukFlag, cukX0 = varargin{3}; else, X0 = varargin{3}; end \nend;\nif ~spm_sp('isspc',sX), sX = spm_sp('set',varargin{2}); end;\nif spm_sp('rk',sX) == 0, error(['null rank sX == 0 in ' action]); end;\nif cukFlag\n if ~isempty(cukX0) & spm_sp('rk',sX) ~= size(cukX0,1),\n cukX0, spm_sp('rk',sX),\n error(['cukX0 of wrong size ' mfilename ' ' action]), end;\nelse\n if ~isempty(X0) & spm_sp('size',sX,1) ~= size(X0,1),\n X0, spm_sp('size',sX,1),\n error(['X0 of wrong size ' mfilename ' ' action]),X0, end;\nend\n%--------- end argument check --------- \n\nif cukFlag\n if isempty(cukX0), X0 = []; else, X0 = spm_sp('ox',sX)*cukX0; end\nend\n\nvarargout = { sf_X0_2_c(X0,sX) };\n\n\n\ncase {'c->h','betarc'} %-Extra sum of squares matrix for beta's from \n %- contrast : use F-contrast if possible\n%=======================================================================\n% H = spm_SpUtil('c->H',sX,c)\nerror(' Obsolete : Use F-contrast utilities ''H'' or ''Hsqr''... ');\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n\n%=======================================================================\n%=======================================================================\n%\t\ttrace part\n%=======================================================================\n%=======================================================================\n%\n\ncase 'trrv' %-Traces for (effective) df calculation\n%=======================================================================\n% [trRV,trRVRV]= spm_SpUtil('trRV',x[,V])\n\nif nargin == 1, error('insufficient arguments');\nelse sX = varargin{2}; end;\n\nif ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;\n\nrk = spm_sp('rk',sX);\nsL = spm_sp('size',sX,1);\n\nif sL == 0,\n\twarning('space with no dimension '); \t\n\tif nargout==1, varargout = {[]};\n\telse varargout = {[], []}; end\nelse, \n\n if nargin > 2 & ~isempty(varargin{3})\t\n\n\tV = varargin{3};\n\tu = sX.u(:,1:rk);\n\tclear sX;\n\tif nargout==1\n\t\t%-only trRV needed\n\t\tif rk==0 | isempty(rk), trMV = 0; \n\t\telse,\ttrMV = sum(sum( u .* (V*u) ));\n\t\tend;\n\t\tvarargout = { trace(V) - trMV};\n\telse\n\t\t%-trRVRV is needed as well\n\t\tif rk==0 | isempty(rk), \n\t\t\ttrMV = 0; \n\t\t\ttrRVRV = (norm(V,'fro'))^2;\n trV = trace(V);\n clear V u\n\t\telse \n\t\t Vu = V*u;\n\t\t trV = trace(V);\n\t\t trRVRV = (norm(V,'fro'))^2;\n clear V; \n\t\t trRVRV = trRVRV - 2*(norm(Vu,'fro'))^2;\n\t\t trRVRV = trRVRV + (norm(u'*Vu,'fro'))^2;\n\t\t trMV = sum(sum( u .* Vu ));\n clear u Vu\n\t\tend\n\t\tvarargout = {(trV - trMV), trRVRV};\n\tend\n\t\t \n else %- nargin == 2 | isempty(varargin{3})\n\n\tif nargout==1\n\t\tif rk==0 | isempty(rk), varargout = {sL}; \n\t\telse, varargout = {sL - rk}; \n\t\tend;\n\telse\n\t\tif rk==0 | isempty(rk), varargout = {sL,sL};\n\t\telse, varargout = {sL - rk, sL - rk};\n\t\tend;\t\n\tend\n\n end\nend\t\n\n\ncase 'trmv' %-Traces for (effective) Fdf calculation\n%=======================================================================\n% [trMV, trMVMV]] = spm_SpUtil('trMV',sX [,V])\n%\n% NB : When V is given empty, the routine asssumes it's identity\n% This is used in spm_FcUtil.\n\nif nargin == 1, error('insufficient arguments');\nelse sX = varargin{2}; end;\nif ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;\nrk = spm_sp('rk',sX);\n\nif isempty(rk)\n\twarning('Rank is empty'); \t\n\tif nargout==1, varargout = {[]};\n\telse varargout = {[], []}; end\n\treturn; \nelseif rk==0, warning('Rank is null in spm_SpUtil trMV ');\n\tif nargout==1, varargout = {0};\n\telse varargout = {0, 0}; end\n\treturn; \nend;\n\nif nargin > 2 & ~isempty(varargin{3}) %- V provided, and assumed correct !\n\n\tV = varargin{3};\n\tu = sX.u(:,1:rk);\n\tclear sX;\n\n\tif nargout==1\n\t\t%-only trMV needed\n\t\ttrMV = sum(sum(u' .* (u'*V) ));\n\t\tvarargout = {trMV};\n\telse \n\t\t%-trMVMV is needed as well\n\t\tVu = V*u;\n clear V\n\t\ttrMV = sum(sum( u .* Vu ));\n\t\ttrMVMV = (norm(u'*Vu,'fro'))^2;\n\t clear u Vu\n\t\tvarargout = {trMV, trMVMV};\n\tend\n\nelse % nargin == 2 | isempty(varargin{3}) %-no V specified: trMV == trMVMV\n\tif nargout==1\n\t\tvarargout = {rk};\n\telse\n\t\tvarargout = {rk, rk};\n\tend\nend\n \n\n\ncase {'i0->edf','edf'} %-Effective F degrees of freedom\n%=======================================================================\n% [df1,df2] = spm_SpUtil('i0->edf',sX,i0,V)\n%-----------------------------------------------------------------------\n%--------- begin argument check ---------------------------------------- \nif nargin<3, error('insufficient arguments'),\nelse, i0 = varargin{3}; sX = varargin{2}; end\nif ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;\ni0 \t= sf_check_i0(i0,spm_sp('size',sX,2));\nif nargin == 4, V=varargin{4}; else, V = eye(spm_sp('size',sX,1)); end;\nif nargin>4, error('Too many input arguments'), end;\n%--------- end argument check ------------------------------------------ \n\nwarning(' Use F-contrast utilities if possible ... ');\n\n[trRV,trRVRV] = spm_SpUtil('trRV', sX, V);\n[trMpV,trMpVMpV] = spm_SpUtil('trMV',spm_SpUtil('i0->x1o',sX, i0),V);\nvarargout = {trMpV^2/trMpVMpV, trRV^2/trRVRV};\n\n\n%=======================================================================\n%=======================================================================\n% \t\tUtilities\n%=======================================================================\n%=======================================================================\n\n\ncase 'size' %-Size of design matrix\n%=======================================================================\n% sz = spm_SpUtil('size',x,dim)\n\nif nargin<3, dim=[]; else, dim = varargin{3}; end\nif nargin<2, error('insufficient arguments'), end\n\nif isstruct(varargin{2})\n if isfield(varargin{2},'X')\n\tsz = size(varargin{2}.X);\n else, error('no X field'); end;\t\nelse\n\tsz = size(varargin{2});\nend\n\nif ~isempty(dim)\n\tif dim>length(sz), sz = 1; else, sz = sz(dim); end\n\tvarargout = {sz};\nelseif nargout>1\n\tvarargout = cell(1,min(nargout,length(sz)));\n\tfor i=1:min(nargout,length(sz)), varargout{i} = sz(i); end\nelse\n\tvarargout = {sz};\nend\n\n\ncase 'ix0check' %-\n%=======================================================================\n% i0c = spm_SpUtil('iX0check',i0,sL)\n\nif nargin<3, error('insufficient arguments'),\nelse, i0 = varargin{2}; sL = varargin{3}; end;\n\nvarargout = {sf_check_i0(i0,sL)};\n\n\notherwise\n%=======================================================================\nerror('Unknown action string in spm_SpUtil')\n\n%=======================================================================\nend\n\n\n\n\n%=======================================================================\nfunction i0c = sf_check_i0(i0,sL)\n% NB : [] = sf_check_i0([],SL);\n%\n\nif all(ismember(i0,[0,1])) & length(i0(:))==sL, i0c=find(i0); \nelseif ~isempty(i0) & any(floor(i0)~=i0) | any(i0<1) | any(i0>sL)\n\terror('logical mask or vector of column indices required')\nelse, i0c = i0; end\n\n%=======================================================================\nfunction c = sf_X0_2_c(X0,sX) \n%\n%- Algorithm to avoids the pinv(X0) and insure consistency\n%- Get a contrast that span the space of X0 and is estimable\n%- Get the orthogonal complement and project onto the estimable space\n%- Strip zeros columns and use the rotation making X1o orthog. to X0\n% !!! tolerance dealing ?\n\nif ~isempty(X0)\n\n sc0 = spm_sp('set',spm_sp('x-',sX,X0));\n if sc0.rk\n c = spm_sp('oPp:',sX,spm_sp('r',sc0));\n else \n c = spm_sp('oPp',sX);\n end;\n c = c(:,any(c));\n sL = spm_sp('size',sX,2);\n\n %- why the \"& size(X0,2) ~= sL\" !!!?\n if isempty(c) & size(X0,2) ~= sL\n c = zeros(sL,1);\n end\n\nelse \n c = spm_sp('xpx',sX);\nend\n\n%\n%- c = spm_sp('r',sc0,spm_sp('oxp',sX)); would also works.\n\n\n\n\n\n\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_checkreg.m", "ext": ".m", "path": "spm5-master/spm_config_checkreg.m", "size": 1973, "source_encoding": "utf_8", "md5": "22083b0d66942baadf969c8ccc65c399", "text": "function opts = spm_config_checkreg\n% Configuration file for check-reg jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_checkreg.m 171 2005-05-20 19:20:10Z john $\n\ndata.type = 'files';\ndata.name = 'Images to Display';\ndata.tag = 'data';\ndata.filter = 'image';\ndata.num = [1 15];\ndata.help = {'Images to display.'};\n\nopts.type = 'branch';\nopts.name = 'Check Registration';\nopts.tag = 'checkreg';\nopts.val = {data};\nopts.prog = @dispims;\nopts.help = {[...\n'Orthogonal views of one or more images are displayed. Clicking in '...\n'any image moves the centre of the orthogonal views. Images are '...\n'shown in orientations relative to that of the first selected image. '...\n'The first specified image is shown at the top-left, and the last at '...\n'the bottom right. The fastest increment is in the left-to-right '...\n'direction (the same as you are reading this).'],...\n'',...\n['If you have put your images in the correct file format, ',...\n 'then (possibly after specifying some rigid-body rotations):'],...\n[' The top-left image is coronal with the top (superior) ',...\n 'of the head displayed at the top and the left shown on the left. ',...\n 'This is as if the subject is viewed from behind.'],...\n[' The bottom-left image is axial with the front (anterior) of the ',...\n 'head at the top and the left shown on the left. ',...\n 'This is as if the subject is viewed from above.'],...\n[' The top-right image is sagittal with the front (anterior) of ',...\n 'the head at the left and the top of the head shown at the top. ',...\n 'This is as if the subject is viewed from the left.']};\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction dispims(varargin)\njob = strvcat(varargin{1}.data);\nspm_check_registration(job);\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_dicom_convert.m", "ext": ".m", "path": "spm5-master/spm_dicom_convert.m", "size": 40700, "source_encoding": "utf_8", "md5": "feaec8fcbfd853cc66ad24c8f1367572", "text": "function spm_dicom_convert(hdr,opts,root_dir,format)\n% Convert DICOM images into something that SPM can use\n% FORMAT spm_dicom_convert(hdr,opts,root_dir,format)\n% hdr - a cell array of DICOM headers from spm_dicom_headers\n% opts - options\n% 'all' - all DICOM files (default)\n% 'mosaic' - the mosaic images\n% 'standard' - standard DICOM files\n% 'spect' - SIEMENS Spectroscopy DICOMs (position only)\n% This will write out a mask image volume with 1's\n% set at the position of spectroscopy voxel(s).\n% 'raw' - convert raw FIDs (not implemented)\n% root_dir - 'flat' - SPM5 standard, do not produce file tree\n% With all other options, files will be sorted into\n% directories according to their sequence/protocol names\n% 'date_time' - Place files under ./\n% 'patid' - Place files under ./\n% 'patid_date' - Place files under ./\n% 'name' - Place files under ./\n% format - output format\n% 'img' Two file (hdr+img) NIfTI format\n% 'nii' Single file NIfTI format\n% All images will contain a single 3D dataset, 4D images\n% will not be created.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner & Jesper Andersson\n% $Id: spm_dicom_convert.m 917 2007-09-14 09:28:55Z volkmar $\n\n\nif nargin<2, opts = 'all'; end;\nif nargin<3, root_dir='flat';end;\nif nargin<4, format='img';end;\n\n[images,guff] = select_tomographic_images(hdr);\n[spect,images] = select_spectroscopy_images(images);\n[mosaic,standard] = select_mosaic_images(images);\n\nif (strcmp(opts,'all') || strcmp(opts,'mosaic')) && ~isempty(mosaic),\n convert_mosaic(mosaic,root_dir,format);\nend;\nif (strcmp(opts,'all') || strcmp(opts,'standard')) && ~isempty(standard),\n convert_standard(standard,root_dir,format);\nend;\nif (strcmp(opts,'all') || strcmp(opts,'spect')) && ~isempty(spect),\n convert_spectroscopy(spect,root_dir,format);\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction convert_mosaic(hdr,root_dir,format)\nspm_progress_bar('Init',length(hdr),'Writing Mosaic', 'Files written');\n\nfor i=1:length(hdr),\n\n % Output filename\n %-------------------------------------------------------------------\n fname = getfilelocation(hdr{i},root_dir,'f',format);\n\n % Image dimensions and data\n %-------------------------------------------------------------------\n nc = hdr{i}.Columns;\n nr = hdr{i}.Rows;\n\n dim = [0 0 0];\n dim(3) = read_NumberOfImagesInMosaic(hdr{i});\n np = [nc nr]/ceil(sqrt(dim(3)));\n dim(1:2) = np;\n if ~all(np==floor(np)),\n warning('%s: dimension problem [Num Images=%d, Num Cols=%d, Num Rows=%d].',...\n hdr{i}.Filename,dim(3), nc,nr);\n continue;\n end;\n\n % Apparently, this is not the right way of doing it.\n %np = read_AcquisitionMatrixText(hdr{i});\n %if rem(nc, np(1)) || rem(nr, np(2)),\n %\twarning('%s: %dx%d wont fit into %dx%d.',hdr{i}.Filename,...\n %\t\tnp(1), np(2), nc,nr);\n %\treturn;\n %end;\n %dim = [np read_NumberOfImagesInMosaic(hdr{i})];\n\n mosaic = read_image_data(hdr{i});\n volume = zeros(dim);\n for j=1:dim(3),\n img = mosaic((1:np(1))+np(1)*rem(j-1,nc/np(1)), (np(2):-1:1)+np(2)*floor((j-1)/(nc/np(1))));\n if ~any(img(:)),\n volume = volume(:,:,1:(j-1));\n break;\n end;\n volume(:,:,j) = img;\n end;\n dim = size(volume);\n dt = [spm_type('int16') spm_platform('bigend')];\n\n % Orientation information\n %-------------------------------------------------------------------\n % Axial Analyze voxel co-ordinate system:\n % x increases right to left\n % y increases posterior to anterior\n % z increases inferior to superior\n\n % DICOM patient co-ordinate system:\n % x increases right to left\n % y increases anterior to posterior\n % z increases inferior to superior\n\n % T&T co-ordinate system:\n % x increases left to right\n % y increases posterior to anterior\n % z increases inferior to superior\n\n analyze_to_dicom = [diag([1 -1 1]) [0 (dim(2)-1) 0]'; 0 0 0 1]*[eye(4,3) [-1 -1 -1 1]'];\n\n vox = [hdr{i}.PixelSpacing hdr{i}.SpacingBetweenSlices];\n pos = hdr{i}.ImagePositionPatient';\n orient = reshape(hdr{i}.ImageOrientationPatient,[3 2]);\n orient(:,3) = null(orient');\n if det(orient)<0, orient(:,3) = -orient(:,3); end;\n\n % The image position vector is not correct. In dicom this vector points to\n % the upper left corner of the image. Perhaps it is unlucky that this is\n % calculated in the syngo software from the vector pointing to the center of\n % the slice (keep in mind: upper left slice) with the enlarged FoV.\n dicom_to_patient = [orient*diag(vox) pos ; 0 0 0 1];\n truepos = dicom_to_patient *[(size(mosaic)-dim(1:2))/2 0 1]';\n dicom_to_patient = [orient*diag(vox) truepos(1:3) ; 0 0 0 1];\n patient_to_tal = diag([-1 -1 1 1]);\n mat = patient_to_tal*dicom_to_patient*analyze_to_dicom;\n\n\n\n % Maybe flip the image depending on SliceNormalVector from 0029,1010\n %-------------------------------------------------------------------\n SliceNormalVector = read_SliceNormalVector(hdr{i});\n if det([reshape(hdr{i}.ImageOrientationPatient,[3 2]) SliceNormalVector(:)])<0;\n volume = volume(:,:,end:-1:1);\n mat = mat*[eye(3) [0 0 -(dim(3)-1)]'; 0 0 0 1];\n end;\n\n\n % Possibly useful information\n %-------------------------------------------------------------------\n tim = datevec(hdr{i}.AcquisitionTime/(24*60*60));\n descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g Mosaic',...\n hdr{i}.MagneticFieldStrength, hdr{i}.MRAcquisitionType,...\n deblank(hdr{i}.ScanningSequence),...\n hdr{i}.RepetitionTime,hdr{i}.EchoTime,hdr{i}.FlipAngle,...\n datestr(hdr{i}.AcquisitionDate),tim(4),tim(5),tim(6));\n\n % descrip = [deblank(descrip) ' ' hdr{i}.PatientsName];\n\n if ~true, % LEFT-HANDED STORAGE\n mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];\n volume = flipdim(volume,1);\n end;\n\n %if isfield(hdr{i},'RescaleSlope') && hdr{i}.RescaleSlope ~= 1,\n %\tvolume = volume*hdr{i}.RescaleSlope;\n %end;\n %if isfield(hdr{i},'RescaleIntercept') && hdr{i}.RescaleIntercept ~= 0,\n %\tvolume = volume + hdr{i}.RescaleIntercept;\n %end;\n %V = struct('fname',fname, 'dim',dim, 'dt',dt, 'mat',mat, 'descrip',descrip);\n %spm_write_vol(V,volume);\n\n % Note that data are no longer scaled by the maximum amount.\n % This may lead to rounding errors in smoothed data, but it\n % will get around other problems.\n RescaleSlope = 1;\n RescaleIntercept = 0;\n if isfield(hdr{i},'RescaleSlope') && hdr{i}.RescaleSlope ~= 1,\n RescaleSlope = hdr{i}.RescaleSlope;\n end;\n if isfield(hdr{i},'RescaleIntercept') && hdr{i}.RescaleIntercept ~= 0,\n RescaleIntercept = hdr{i}.RescaleIntercept;\n end;\n N = nifti;\n N.dat = file_array(fname,dim,dt,0,RescaleSlope,RescaleIntercept);\n N.mat = mat;\n N.mat0 = mat;\n N.mat_intent = 'Scanner';\n N.mat0_intent = 'Scanner';\n N.descrip = descrip;\n create(N);\n\n % Write the data unscaled\n dat = N.dat;\n dat.scl_slope = [];\n dat.scl_inter = [];\n % write out volume at once - see spm_write_plane.m for performance comments\n dat(:,:,:) = volume;\n \n spm_progress_bar('Set',i);\nend;\nspm_progress_bar('Clear');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction convert_standard(hdr,root_dir,format)\nhdr = sort_into_volumes(hdr);\nfor i=1:length(hdr),\n write_volume(hdr{i},root_dir,format);\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vol = sort_into_volumes(hdr)\n\n%\n% First of all, sort into volumes based on relevant\n% fields in the header.\n%\n\nvol{1}{1} = hdr{1};\nfor i=2:length(hdr),\n orient = reshape(hdr{i}.ImageOrientationPatient,[3 2]);\n xy1 = hdr{i}.ImagePositionPatient*orient;\n match = 0;\n if isfield(hdr{i},'CSAImageHeaderInfo') && isfield(hdr{i}.CSAImageHeaderInfo,'name')\n ice1 = sscanf( ...\n strrep(get_numaris4_val(hdr{i}.CSAImageHeaderInfo,'ICE_Dims'), ...\n 'X', '-1'), '%i_%i_%i_%i_%i_%i_%i_%i_%i')';\n dimsel = logical([1 1 1 1 1 1 0 0 1]);\n else\n ice1 = [];\n end;\n for j=1:length(vol),\n orient = reshape(vol{j}{1}.ImageOrientationPatient,[3 2]);\n xy2 = vol{j}{1}.ImagePositionPatient*orient;\n dist2 = sum((xy1-xy2).^2);\n \n % This line is a fudge because of some problematic data that Bogdan,\n % Cynthia and Stefan were trying to convert. I hope it won't cause\n % problems for others -JA\n dist2 = 0;\n \n if strcmp(hdr{i}.Modality,'CT') && ...\n strcmp(vol{j}{1}.Modality,'CT') % Our CT seems to have shears in slice positions\n dist2 = 0;\n end;\n if ~isempty(ice1) && isfield(vol{j}{1},'CSAImageHeaderInfo') && isfield(vol{j}{1}.CSAImageHeaderInfo(1),'name')\n % Replace 'X' in ICE_Dims by '-1'\n ice2 = sscanf( ...\n strrep(get_numaris4_val(vol{j}{1}.CSAImageHeaderInfo,'ICE_Dims'), ...\n 'X', '-1'), '%i_%i_%i_%i_%i_%i_%i_%i_%i')';\n if ~isempty(ice2)\n identical_ice_dims=all(ice1(dimsel)==ice2(dimsel));\n else\n identical_ice_dims = 0; % have ice1 but not ice2, ->\n % something must be different\n end,\n else\n identical_ice_dims = 1; % No way of knowing if there is no CSAImageHeaderInfo\n end;\n try\n match = hdr{i}.SeriesNumber == vol{j}{1}.SeriesNumber &&...\n hdr{i}.Rows == vol{j}{1}.Rows &&...\n hdr{i}.Columns == vol{j}{1}.Columns &&...\n sum((hdr{i}.ImageOrientationPatient - vol{j}{1}.ImageOrientationPatient).^2)<1e-5 &&...\n sum((hdr{i}.PixelSpacing - vol{j}{1}.PixelSpacing).^2)<1e-5 && ...\n identical_ice_dims && dist2<1e-3;\n %if (hdr{i}.AcquisitionNumber ~= hdr{i}.InstanceNumber) || ...\n % (vol{j}{1}.AcquisitionNumber ~= vol{j}{1}.InstanceNumber)\n % match = match && (hdr{i}.AcquisitionNumber == vol{j}{1}.AcquisitionNumber)\n %end;\n % For raw image data, tell apart real/complex or phase/magnitude\n if isfield(hdr{i},'ImageType') && isfield(vol{j}{1}, 'ImageType')\n match = match && strcmp(hdr{i}.ImageType, vol{j}{1}.ImageType);\n end;\n if isfield(hdr{i},'SequenceName') && isfield(vol{j}{1}, 'SequenceName')\n match = match && strcmp(hdr{i}.SequenceName,vol{j}{1}.SequenceName);\n end;\n if isfield(hdr{i},'SeriesInstanceUID') && isfield(vol{j}{1}, 'SeriesInstanceUID')\n match = match && strcmp(hdr{i}.SeriesInstanceUID,vol{j}{1}.SeriesInstanceUID);\n end;\n if isfield(hdr{i},'EchoNumbers') && isfield(vol{j}{1}, 'EchoNumbers')\n match = match && hdr{i}.EchoNumbers == vol{j}{1}.EchoNumbers;\n end;\n catch\n match = 0;\n end\n if match\n vol{j}{end+1} = hdr{i};\n break;\n end;\n end;\n if ~match,\n vol{end+1}{1} = hdr{i};\n end;\nend;\n\ndcm = vol;\nsave('dicom_headers.mat','dcm');\n\n%\n% Secondly, sort volumes into ascending/descending\n% slices depending on .ImageOrientationPatient field.\n%\n\nvol2 = {};\nfor j=1:length(vol),\n orient = reshape(vol{j}{1}.ImageOrientationPatient,[3 2]);\n proj = null(orient');\n if det([orient proj])<0, proj = -proj; end;\n\n z = zeros(length(vol{j}),1);\n for i=1:length(vol{j}),\n z(i) = vol{j}{i}.ImagePositionPatient*proj;\n end;\n [z,index] = sort(z);\n vol{j} = vol{j}(index);\n if length(vol{j})>1,\n % dist = diff(z);\n if any(diff(z)==0)\n tmp = sort_into_vols_again(vol{j});\n vol{j} = tmp{1};\n vol2 = {vol2{:} tmp{2:end}};\n end;\n end;\nend;\nvol = {vol{:} vol2{:}};\nfor j=1:length(vol),\n if length(vol{j})>1,\n orient = reshape(vol{j}{1}.ImageOrientationPatient,[3 2]);\n proj = null(orient');\n if det([orient proj])<0, proj = -proj; end;\n z = zeros(length(vol{j}),1);\n for i=1:length(vol{j}),\n z(i) = vol{j}{i}.ImagePositionPatient*proj;\n end;\n [z,index] = sort(z);\n dist = diff(z);\n if sum((dist-mean(dist)).^2)/length(dist)>1e-4,\n fprintf('***************************************************\\n');\n fprintf('* VARIABLE SLICE SPACING *\\n');\n fprintf('* This may be due to missing DICOM files. *\\n');\n if checkfields(vol{j}{1},'PatientID','SeriesNumber','AcquisitionNumber','InstanceNumber'),\n fprintf('* %s / %d / %d / %d \\n',...\n deblank(vol{j}{1}.PatientID), vol{j}{1}.SeriesNumber, ...\n vol{j}{1}.AcquisitionNumber, vol{j}{1}.InstanceNumber);\n fprintf('* *\\n');\n end;\n fprintf('* %20.4g *\\n', dist);\n fprintf('***************************************************\\n');\n end;\n end;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vol2 = sort_into_vols_again(volj)\nif ~isfield(volj{1},'InstanceNumber'),\n fprintf('***************************************************\\n');\n fprintf('* The slices may be all mixed up and the data *\\n');\n fprintf('* not really usable. Talk to your physicists *\\n');\n fprintf('* about this. *\\n');\n fprintf('***************************************************\\n');\n vol2 = {volj};\n return;\nend;\n\nfprintf('***************************************************\\n');\nfprintf('* The AcquisitionNumber counter does not appear *\\n');\nfprintf('* to be changing from one volume to another. *\\n');\nfprintf('* Another possible explanation is that the same *\\n');\nfprintf('* DICOM slices are used multiple times. *\\n');\n%fprintf('* Talk to your MR sequence developers or scanner *\\n');\n%fprintf('* supplier to have this fixed. *\\n');\nfprintf('* The conversion is having to guess how slices *\\n');\nfprintf('* should be arranged into volumes. *\\n');\nif checkfields(volj{1},'PatientID','SeriesNumber','AcquisitionNumber'),\n fprintf('* %s / %d / %d\\n',...\n deblank(volj{1}.PatientID), volj{1}.SeriesNumber, ...\n volj{1}.AcquisitionNumber);\nend;\nfprintf('***************************************************\\n');\n\nz = zeros(length(volj),1);\nt = zeros(length(volj),1);\nd = zeros(length(volj),1);\norient = reshape(volj{1}.ImageOrientationPatient,[3 2]);\nproj = null(orient');\nif det([orient proj])<0, proj = -proj; end;\n\nfor i=1:length(volj),\n z(i) = volj{i}.ImagePositionPatient*proj;\n t(i) = volj{i}.InstanceNumber;\nend;\n% msg = 0;\n[t,index] = sort(t);\nvolj = volj(index);\nz = z(index);\nmsk = find(diff(t)==0);\nif any(msk),\n % fprintf('***************************************************\\n');\n % fprintf('* These files have the same InstanceNumber: *\\n');\n % for i=1:length(msk),\n % [tmp,nam1,ext1] = fileparts(volj{msk(i)}.Filename);\n % [tmp,nam2,ext2] = fileparts(volj{msk(i)+1}.Filename);\n % fprintf('* %s%s = %s%s (%d)\\n', nam1,ext1,nam2,ext2, volj{msk(i)}.InstanceNumber);\n % end;\n % fprintf('***************************************************\\n');\n index = [true ; diff(t)~=0];\n t = t(index);\n z = z(index);\n d = d(index);\n volj = volj(index);\nend;\n\n%if any(diff(sort(t))~=1), msg = 1; end;\n[z,index] = sort(z);\nvolj = volj(index);\nt = t(index);\nvol2 = {};\nwhile ~all(d),\n i = find(~d);\n i = i(1);\n i = find(z==z(i));\n [t(i),si] = sort(t(i));\n volj(i) = volj(i(si));\n for i1=1:length(i),\n if length(vol2)1,\n z = zeros(length(hdr),1);\n for i=1:length(hdr),\n z(i) = hdr{i}.ImagePositionPatient*orient(:,3);\n end;\n z = mean(diff(z));\nelse\n if checkfields(hdr{1},'SliceThickness'),\n z = hdr{1}.SliceThickness;\n else\n z = 1;\n end;\nend;\nvox = [hdr{1}.PixelSpacing z];\npos = hdr{1}.ImagePositionPatient';\ndicom_to_patient = [orient*diag(vox) pos ; 0 0 0 1];\npatient_to_tal = diag([-1 -1 1 1]);\nmat = patient_to_tal*dicom_to_patient*analyze_to_dicom;\nif strcmp(hdr{1}.Modality,'CT') && numel(hdr)>1\n shear = (hdr{1}.ImagePositionPatient-hdr{2}.ImagePositionPatient) ...\n * reshape(hdr{1}.ImageOrientationPatient,[3 2]);\n if shear(1)\n warning('shear(1) = %f not applied\\n', shear(1));\n end;\n warning('shear(2) = %f applied\\n', shear(2));\n try\n prms = spm_imatrix(mat);\n prms(12) = shear(2);\n mat = spm_matrix(prms);\n end;\nend;\n\n% Possibly useful information\n%-------------------------------------------------------------------\nif checkfields(hdr{1},'AcquisitionTime','MagneticFieldStrength','MRAcquisitionType',...\n 'ScanningSequence','RepetitionTime','EchoTime','FlipAngle',...\n 'AcquisitionDate'),\n tim = datevec(hdr{1}.AcquisitionTime/(24*60*60));\n descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g',...\n hdr{1}.MagneticFieldStrength, hdr{1}.MRAcquisitionType,...\n deblank(hdr{1}.ScanningSequence),...\n hdr{1}.RepetitionTime,hdr{1}.EchoTime,hdr{1}.FlipAngle,...\n datestr(hdr{1}.AcquisitionDate),tim(4),tim(5),tim(6));\nelse\n descrip = hdr{1}.Modality;\nend;\n\nif ~true, % LEFT-HANDED STORAGE\n mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];\nend;\n\npinfo = [1 0 0]';\nif isfield(hdr{1},'RescaleSlope') || isfield(hdr{1},'RescaleIntercept'),\n pinfo = repmat(pinfo,1,length(hdr));\n bytepix = spm_type('int16','bits')/8;\n for i=1:length(hdr),\n if isfield(hdr{i},'RescaleSlope'), pinfo(1,i) = hdr{i}.RescaleSlope; end;\n if isfield(hdr{i},'RescaleIntercept'), pinfo(2,i) = hdr{i}.RescaleIntercept; end;\n pinfo(3,i) = dim(1)*dim(2)*(i-1)*bytepix;\n end;\nend;\n\n% Write the image volume\n%-------------------------------------------------------------------\nspm_progress_bar('Init',length(hdr),['Writing ' fname], 'Planes written');\n%V = struct('fname',fname, 'dim',dim, 'dt',dt, 'pinfo',pinfo, 'mat',mat, 'descrip',descrip);\n%V = spm_create_vol(V);\nN = nifti;\nN.dat = file_array(fname,dim,dt,0,pinfo(1),pinfo(2));\nN.mat = mat;\nN.mat0 = mat;\nN.mat_intent = 'Scanner';\nN.mat0_intent = 'Scanner';\nN.descrip = descrip;\ncreate(N);\nvolume = zeros(dim);\n\nfor i=1:length(hdr),\n plane = read_image_data(hdr{i});\n\n if isfield(hdr{i},'RescaleSlope'), plane = plane*hdr{i}.RescaleSlope; end;\n if isfield(hdr{i},'RescaleIntercept'), plane = plane+hdr{i}.RescaleIntercept; end;\n\n plane = fliplr(plane);\n if ~true, plane = flipud(plane); end; % LEFT-HANDED STORAGE\n %V = spm_write_plane(V,plane,i);\n % collect all planes before writing to disk\n volume(:,:,i) = plane;\n spm_progress_bar('Set',i);\nend;\n% write volume at once - see spm_write_plane for performance comments\nN.dat(:,:,:) = volume;\nspm_progress_bar('Clear');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction convert_spectroscopy(hdr,root_dir,format)\n\nfor i=1:length(hdr),\n write_spectroscopy_volume(hdr(i),root_dir,format);\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction write_spectroscopy_volume(hdr,root_dir,format)\n% Output filename\n%-------------------------------------------------------------------\nfname = getfilelocation(hdr{1}, root_dir,'S',format);\n\n% Image dimensions\n%-------------------------------------------------------------------\nnc = get_numaris4_numval(hdr{1}.Private_0029_1210,'Columns');\nnr = get_numaris4_numval(hdr{1}.Private_0029_1210,'Rows');\n\ndim = [nc nr numel(hdr)];\ndt = [spm_type('int16') spm_platform('bigend')];\n\n% Orientation information\n%-------------------------------------------------------------------\n% Axial Analyze voxel co-ordinate system:\n% x increases right to left\n% y increases posterior to anterior\n% z increases inferior to superior\n\n% DICOM patient co-ordinate system:\n% x increases right to left\n% y increases anterior to posterior\n% z increases inferior to superior\n\n% T&T co-ordinate system:\n% x increases left to right\n% y increases posterior to anterior\n% z increases inferior to superior\n\nanalyze_to_dicom = [diag([1 -1 1]) [0 (dim(2)-1) 0]'; 0 0 0 1]*[eye(4,3) [-1 -1 -1 1]'];\norient = reshape(get_numaris4_numval(hdr{1}.Private_0029_1210,...\n 'ImageOrientationPatient'),[3 2]);\norient(:,3) = null(orient');\nif det(orient)<0, orient(:,3) = -orient(:,3); end;\nif length(hdr)>1,\n z = zeros(length(hdr),1);\n for i=1:length(hdr),\n z(i) = get_numaris4_numval(hdr{i}.Private_0029_1210,...\n 'ImagePositionPatient')*orient(:,3);\n end;\n z = mean(diff(z));\nelse\n try\n z = get_numaris4_numval(hdr{1}.Private_0029_1210,...\n 'SliceThickness');\n catch\n z = 1;\n end;\nend;\n\nvox = [get_numaris4_numval(hdr{1}.Private_0029_1210,'PixelSpacing') z];\npos = get_numaris4_numval(hdr{1}.Private_0029_1210,'ImagePositionPatient')';\n%dicom_to_patient = [orient*diag(vox) pos-1.5*orient*([0 vox(2) 0]') ; 0 0 0 1];\ndicom_to_patient = [orient*diag(vox) pos ; 0 0 0 1];\npatient_to_tal = diag([-1 -1 1 1]);\nwarning('Don''t know exactly what positions in spectroscopy files should be - just guessing!')\nmat = patient_to_tal*dicom_to_patient*analyze_to_dicom;\nif strcmp(hdr{1}.Modality,'CT') && numel(hdr)>1\n shear = (hdr{1}.ImagePositionPatient-hdr{2}.ImagePositionPatient) ...\n * reshape(hdr{1}.ImageOrientationPatient,[3 2]);\n if shear(1)\n warning('shear(1) = %f not applied\\n', shear(1));\n end;\n warning('shear(2) = %f applied\\n', shear(2));\n try\n prms = spm_imatrix(mat);\n prms(12) = shear(2);\n mat = spm_matrix(prms);\n end;\nend;\n\n% Possibly useful information\n%-------------------------------------------------------------------\nif checkfields(hdr{1},'AcquisitionTime','MagneticFieldStrength','MRAcquisitionType',...\n 'ScanningSequence','RepetitionTime','EchoTime','FlipAngle',...\n 'AcquisitionDate'),\n tim = datevec(hdr{1}.AcquisitionTime/(24*60*60));\n descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g',...\n hdr{1}.MagneticFieldStrength, hdr{1}.MRAcquisitionType,...\n deblank(hdr{1}.ScanningSequence),...\n hdr{1}.RepetitionTime,hdr{1}.EchoTime,hdr{1}.FlipAngle,...\n datestr(hdr{1}.AcquisitionDate),tim(4),tim(5),tim(6));\nelse\n descrip = hdr{1}.Modality;\nend;\n\nif ~true, % LEFT-HANDED STORAGE\n mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];\nend;\n\npinfo = [1 0 0]';\nif isfield(hdr{1},'RescaleSlope') || isfield(hdr{1},'RescaleIntercept'),\n pinfo = repmat(pinfo,1,length(hdr));\n bytepix = spm_type('int16','bits')/8;\n for i=1:length(hdr),\n if isfield(hdr{i},'RescaleSlope'), pinfo(1,i) = hdr{i}.RescaleSlope; end;\n if isfield(hdr{i},'RescaleIntercept'), pinfo(2,i) = hdr{i}.RescaleIntercept; end;\n pinfo(3,i) = dim(1)*dim(2)*(i-1)*bytepix;\n end;\nend;\n\n% Write the image volume\n%-------------------------------------------------------------------\nspm_progress_bar('Init',length(hdr),['Writing ' fname], 'Planes written');\n%V = struct('fname',fname, 'dim',dim, 'dt',dt, 'pinfo',pinfo, 'mat',mat, 'descrip',descrip);\n%V = spm_create_vol(V);\nN = nifti;\nN.dat = file_array(fname,dim,dt,0,pinfo(1),pinfo(2));\nN.mat = mat;\nN.mat0 = mat;\nN.mat_intent = 'Scanner';\nN.mat0_intent = 'Scanner';\nN.descrip = descrip;\ncreate(N);\nvolume = zeros(dim);\n\nfor i=1:length(hdr),\n plane = read_spect_data(hdr{i});\n\n if isfield(hdr{i},'RescaleSlope'), plane = plane*hdr{i}.RescaleSlope; end;\n if isfield(hdr{i},'RescaleIntercept'), plane = plane+hdr{i}.RescaleIntercept; end;\n\n plane = fliplr(plane);\n if ~true, plane = flipud(plane); end; % LEFT-HANDED STORAGE\n %V = spm_write_plane(V,plane,i);\n % collect all planes before writing to disk\n volume(:,:,i) = plane;\n spm_progress_bar('Set',i);\nend;\n% write volume at once - see spm_write_plane for performance comments\nN.dat(:,:,:) = volume;\nspm_progress_bar('Clear');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [images,guff] = select_tomographic_images(hdr)\nimages = {};\nguff = {};\nfor i=1:length(hdr),\n if ~checkfields(hdr{i},'Modality') || ~(strcmp(hdr{i}.Modality,'MR') ||...\n strcmp(hdr{i}.Modality,'PT') || strcmp(hdr{i}.Modality,'CT'))\n disp(['Cant find appropriate modality information for \"' hdr{i}.Filename '\".']);\n guff = {guff{:},hdr{i}};\n elseif ~checkfields(hdr{i},'StartOfPixelData','SamplesperPixel',...\n 'Rows','Columns','BitsAllocated','BitsStored','HighBit','PixelRepresentation'),\n disp(['Cant find \"Image Pixel\" information for \"' hdr{i}.Filename '\".']);\n guff = {guff{:},hdr{i}};\n elseif isfield(hdr{i},'Private_2001_105f'),\n % This field corresponds to: > Stack Sequence 2001,105F SQ VNAP, COPY\n % http://www.medical.philips.com/main/company/connectivity/mri/index.html\n % No documentation about this private field is yet available.\n disp('Cant yet convert Phillips Intera DICOM.');\n guff = {guff{:},hdr{i}};\n elseif ~(checkfields(hdr{i},'PixelSpacing','ImagePositionPatient','ImageOrientationPatient')||isfield(hdr{i},'Private_0029_1210')),\n disp(['Cant find \"Image Plane\" information for \"' hdr{i}.Filename '\".']);\n guff = {guff{:},hdr{i}};\n elseif ~checkfields(hdr{i},'PatientID','SeriesNumber','AcquisitionNumber','InstanceNumber'),\n disp(['Cant find suitable filename info for \"' hdr{i}.Filename '\".']);\n if ~isfield(hdr{i},'SeriesNumber')\n disp('Setting SeriesNumber to 1');\n hdr{i}.SeriesNumber=1;\n images = {images{:},hdr{i}};\n end;\n if ~isfield(hdr{i},'AcquisitionNumber')\n disp('Setting AcquisitionNumber to 1');\n hdr{i}.AcquisitionNumber=1;\n images = {images{:},hdr{i}};\n end;\n if ~isfield(hdr{i},'InstanceNumber')\n disp('Setting InstanceNumber to 1');\n hdr{i}.InstanceNumber=1;\n images = {images{:},hdr{i}};\n end;\n else\n images = {images{:},hdr{i}};\n end;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [mosaic,standard] = select_mosaic_images(hdr)\nmosaic = {};\nstandard = {};\nfor i=1:length(hdr),\n if ~checkfields(hdr{i},'ImageType','CSAImageHeaderInfo') ||...\n isfield(hdr{i}.CSAImageHeaderInfo,'junk') ||...\n isempty(read_AcquisitionMatrixText(hdr{i})) ||...\n isempty(read_NumberOfImagesInMosaic(hdr{i}))\n standard = {standard{:},hdr{i}};\n else\n mosaic = {mosaic{:},hdr{i}};\n end;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [spect,images] = select_spectroscopy_images(hdr)\nspectsel = zeros(1,numel(hdr));\nfor i=1:length(hdr),\n if isfield(hdr{i},'SOPClassUID') && isfield(hdr{i},'Private_0029_1210')\n spectsel(i) = strcmp(hdr{i}.SOPClassUID,'1.3.12.2.1107.5.9.1');\n end;\nend;\nspect = hdr(logical(spectsel));\nimages= hdr(~logical(spectsel));\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction ok = checkfields(hdr,varargin)\nok = 1;\nfor i=1:(nargin-1),\n if ~isfield(hdr,varargin{i}),\n ok = 0;\n break;\n end;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction clean = strip_unwanted(dirty)\nmsk = find((dirty>='a'&dirty<='z') | (dirty>='A'&dirty<='Z') |...\n (dirty>='0'&dirty<='9') | dirty=='_');\nclean = dirty(msk);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction img = read_image_data(hdr)\nimg = [];\n\nif hdr.SamplesperPixel ~= 1,\n warning([hdr.Filename ': SamplesperPixel = ' num2str(hdr.SamplesperPixel) ' - cant be an MRI']);\n return;\nend;\n\nprec = ['ubit' num2str(hdr.BitsAllocated) '=>' 'uint32'];\n\nif isfield(hdr,'TransferSyntaxUID') && strcmp(hdr.TransferSyntaxUID,'1.2.840.10008.1.2.2') && strcmp(hdr.VROfPixelData,'OW'),\n fp = fopen(hdr.Filename,'r','ieee-be');\nelse\n fp = fopen(hdr.Filename,'r','ieee-le');\nend;\nif fp==-1,\n warning([hdr.Filename ': cant open file']);\n return;\nend;\n\nfseek(fp,hdr.StartOfPixelData,'bof');\nimg = fread(fp,hdr.Rows*hdr.Columns,prec);\nfclose(fp);\nif length(img)~=hdr.Rows*hdr.Columns,\n error([hdr.Filename ': cant read whole image']);\nend;\n\nimg = bitshift(img,hdr.BitsStored-hdr.HighBit-1);\n\nif hdr.PixelRepresentation,\n % Signed data - done this way because bitshift only\n % works with signed data. Negative values are stored\n % as 2s complement.\n neg = logical(bitshift(bitand(img,uint32(2^hdr.HighBit)),-hdr.HighBit));\n msk = (2^hdr.HighBit - 1);\n img = double(bitand(img,msk));\n img(neg) = img(neg)-2^(hdr.HighBit);\nelse\n % Unsigned data\n msk = (2^(hdr.HighBit+1) - 1);\n img = double(bitand(img,msk));\nend;\n\nimg = reshape(img,hdr.Columns,hdr.Rows);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction img = read_spect_data(hdr)\n% Image dimensions\n%-------------------------------------------------------------------\nnc = get_numaris4_numval(hdr.Private_0029_1210,'Columns');\nnr = get_numaris4_numval(hdr.Private_0029_1210,'Rows');\nimg = ones(nr,nc);\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction nrm = read_SliceNormalVector(hdr)\nstr = hdr.CSAImageHeaderInfo;\nval = get_numaris4_val(str,'SliceNormalVector');\nfor i=1:3,\n nrm(i,1) = sscanf(val(i,:),'%g');\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction n = read_NumberOfImagesInMosaic(hdr)\nstr = hdr.CSAImageHeaderInfo;\nval = get_numaris4_val(str,'NumberOfImagesInMosaic');\nn = sscanf(val','%d');\nif isempty(n), n=[]; end;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction dim = read_AcquisitionMatrixText(hdr)\nstr = hdr.CSAImageHeaderInfo;\nval = get_numaris4_val(str,'AcquisitionMatrixText');\ndim = sscanf(val','%d*%d')';\nif length(dim)==1,\n dim = sscanf(val','%dp*%d')';\nend;\nif isempty(dim), dim=[]; end;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction val = get_numaris4_val(str,name)\nname = deblank(name);\nval = {};\nfor i=1:length(str),\n if strcmp(deblank(str(i).name),name),\n for j=1:str(i).nitems,\n if str(i).item(j).xx(1),\n val = {val{:} str(i).item(j).val};\n end;\n end;\n break;\n end;\nend;\nval = strvcat(val{:});\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction val = get_numaris4_numval(str,name)\nval1 = get_numaris4_val(str,name);\nfor k = 1:size(val1,1)\n val(k)=str2num(val1(k,:));\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\n\nfunction fname = getfilelocation(hdr,root_dir,prefix,format)\n\nif nargin < 3\n prefix = 'f';\nend;\n\nif strncmp(root_dir,'ice',3)\n root_dir = root_dir(4:end);\n imtype = textscan(hdr.ImageType,'%s','delimiter','\\\\');\n try\n imtype = imtype{1}{3};\n catch\n imtype = '';\n end;\n prefix = [prefix imtype get_numaris4_val(hdr.CSAImageHeaderInfo,'ICE_Dims')];\nend;\n\nif strcmp(root_dir, 'flat')\n % Standard SPM5 file conversion\n %-------------------------------------------------------------------\n if checkfields(hdr,'SeriesNumber','AcquisitionNumber')\n if checkfields(hdr,'EchoNumbers')\n fname = sprintf('%s%s-%.4d-%.5d-%.6d-%.2d.%s', prefix, strip_unwanted(hdr.PatientID),...\n hdr.SeriesNumber, hdr.AcquisitionNumber, hdr.InstanceNumber,...\n hdr.EchoNumbers, format);\n else\n fname = sprintf('%s%s-%.4d-%.5d-%.6d.%s', prefix, strip_unwanted(hdr.PatientID),...\n hdr.SeriesNumber, hdr.AcquisitionNumber, ...\n hdr.InstanceNumber, format);\n end;\n else\n fname = sprintf('%s%s-%.6d.%s',prefix, ...\n strip_unwanted(hdr.PatientID),hdr.InstanceNumber, format);\n end;\n\n fname = fullfile(pwd,fname);\n return;\nend;\n\n% more fancy stuff - sort images into subdirectories\nif ~isfield(hdr,'ProtocolName')\n if isfield(hdr,'SequenceName')\n hdr.ProtocolName = hdr.SequenceName;\n else\n hdr.ProtocolName='unknown';\n end;\nend;\nif ~isfield(hdr,'SeriesDescription')\n hdr.SeriesDescription = 'unknown';\nend;\nif ~isfield(hdr,'EchoNumbers')\n hdr.EchoNumbers = 0;\nend;\n\nm = sprintf('%02d', floor(rem(hdr.StudyTime/60,60)));\nh = sprintf('%02d', floor(hdr.StudyTime/3600));\nstudydate = sprintf('%s_%s-%s', datestr(hdr.StudyDate,'yyyy-mm-dd'), ...\n h,m);\nswitch root_dir\n case 'date_time',\n\tid = studydate;\n case {'patid', 'patid_date', 'patname'},\n\tid = strip_unwanted(hdr.PatientID);\nend;\nserdes = strrep(strip_unwanted(hdr.SeriesDescription),...\n strip_unwanted(hdr.ProtocolName),'');\nprotname = sprintf('%s%s_%.4d',strip_unwanted(hdr.ProtocolName), ...\n serdes, hdr.SeriesNumber);\nswitch root_dir\n case 'date_time',\n dname = fullfile(pwd, id, protname);\n case 'patid',\n dname = fullfile(pwd, id, protname);\n case 'patid_date',\n dname = fullfile(pwd, id, studydate, protname);\n case 'patname',\n dname = fullfile(pwd, strip_unwanted(hdr.PatientsName), ...\n id, protname);\n otherwise\n error('unknown file root specification');\nend;\nif ~exist(dname,'dir'),\n mkdir_rec(dname);\nend;\n\n% some non-product sequences on SIEMENS scanners seem to have problems\n% with image numbering in MOSAICs - doublettes, unreliable ordering\n% etc. To distinguish, always include Acquisition time in image name\nsa = sprintf('%02d', floor(rem(hdr.AcquisitionTime,60)));\nma = sprintf('%02d', floor(rem(hdr.AcquisitionTime/60,60)));\nha = sprintf('%02d', floor(hdr.AcquisitionTime/3600));\nfname = sprintf('%s%s-%s%s%s-%.5d-%.5d-%d.%s', prefix, id, ha, ma, sa, ...\n\t\thdr.AcquisitionNumber,hdr.InstanceNumber, ...\n\t\thdr.EchoNumbers,format);\n\nfname = fullfile(dname, fname);\n\n%_______________________________________________________________________\n\n%_______________________________________________________________________\n\nfunction suc = mkdir_rec(str)\n% works on full pathnames only\nopwd=pwd;\nif str(end) ~= filesep, str = [str filesep];end;\npos = findstr(str,filesep);\nsuc = zeros(1,length(pos));\nfor g=2:length(pos)\n if ~exist(str(1:pos(g)-1),'dir'),\n cd(str(1:pos(g-1)-1));\n suc(g) = mkdir(str(pos(g-1)+1:pos(g)-1));\n end;\nend;\ncd(opwd);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction ret = read_ascconv(hdr)\n% In SIEMENS data, there is an ASCII text section with\n% additional information items. This section starts with a code\n% ### ASCCONV BEGIN ###\n% and ends with\n% ### ASCCONV END ###\n% It is read by spm_dicom_headers into an entry 'MrProtocol' in CSASeriesHeaderInfo\n% The additional items are assignments in C syntax, here they are just\n% translated according to\n% [] -> ()\n% \" -> '\n% 0xX -> hex2dec('X')\n% and collected in a struct.\nret=struct;\n\n% get ascconv data\nX=get_numaris4_val(hdr.CSASeriesHeaderInfo,'MrProtocol');\n\nascstart = findstr(X,'### ASCCONV BEGIN ###');\nascend = findstr(X,'### ASCCONV END ###');\n\nif ~isempty(ascstart) && ~isempty(ascend)\n tokens = textscan(char(X((ascstart+22):(ascend-1))),'%s', ...\n 'delimiter',char(10));\n for k = 1:numel(tokens{1})\n tokens{1}{k}=regexprep(tokens{1}{k},'\\[([0-9]*)\\]','($1+1)');\n tokens{1}{k}=regexprep(tokens{1}{k},'\"(.*)\"','''$1''');\n tokens{1}{k}=regexprep(tokens{1}{k},'0x([0-9a-fA-F]*)','hex2dec(''$1'')');\n try\n eval(['ret.' tokens{1}{k} ';']);\n catch\n disp(['AscConv: Error evaluating ''ret.' tokens{1}{k} ''';']);\n end;\n end;\nend;\n%_______________________________________________________________________\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_spm_ui.m", "ext": ".m", "path": "spm5-master/spm_spm_ui.m", "size": 96520, "source_encoding": "utf_8", "md5": "bd545cfada5972c76b467ca0170c4274", "text": "function varargout = spm_spm_ui(varargin)\n% Setting up the general linear model for independent data\n% FORMATs (given in Programmers Help)\n%_______________________________________________________________________\n%\n% spm_spm_ui.m configures the design matrix (describing the general\n% linear model), data specification, and other parameters necessary for\n% the statistical analysis. These parameters are saved in a\n% configuration file (SPM.mat) in the current directory, and are\n% passed on to spm_spm.m which estimates the design. Inference on these\n% estimated parameters is then handled by the SPM results section.\n%\n% A separate program (spm_spm_fmri_ui.m) handles design configuration\n% for fMRI time series, though this program can be used for fMRI data\n% when observations can be regarded as independent.\n%\n% ----------------------------------------------------------------------\n%\n% Various data and parameters need to be supplied to specify the design:\n% * the image files\n% * indicators of the corresponding condition/subject/group\n% * any covariates, nuisance variables, or design matrix partitions\n% * the type of global normalisation (if any)\n% * grand mean scaling options\n% * thresholds and masks defining the image volume to analyse\n%\n% The interface supports a comprehensive range of options for all these\n% parameters, which are described below in the order in which the\n% information is requested. Rather than ask for all these parameters,\n% spm_spm_ui.m uses a \"Design Definition\", a structure describing the\n% options and defaults appropriate for a particular analysis. Thus,\n% once the user has chosen a design, a subset of the following prompts\n% will be presented.\n%\n% If the pre-specified design definitions don't quite have the combination\n% of options you want, you can pass a custom design structure D to be used\n% as parameter: spm_spm_ui('cfg',D). The format of the design structure\n% and option definitions are given in the programmers help, at the top of\n% the main body of the code.\n%\n% ----------------\n%\n% Design class & Design type\n% ==========================\n%\n% Unless a design definition is passed to spm_spm_ui.m as a parameter,\n% the user is prompted first to select a design class, and then to\n% select a design type from that class.\n%\n% The designs are split into three classes:\n% i) Basic stats: basic models for simple statistics\n% These specify designs suitable for simple voxel-by-voxel analyses.\n% - one-sample t-test\n% - two-sample t-test\n% - paired t-test\n% - one way Anova\n% - one way Anova (with constant)\n% - one way Anova (within subject)\n% - simple regression (equivalent to correlation)\n% - multiple regression\n% - multiple regression (with constant)\n% - basic AnCova (ANalysis of COVAriance)\n% (essentially a two-sample t-test with a nuisance covariate)\n%\n% ii) PET models: models suitable for analysis of PET/SPECT experiments\n% - Single-subject: conditions & covariates\n% - Single-subject: covariates only\n%\n% - Multi-subj: conditions & covariates\n% - Multi-subj: cond x subj interaction & covariates\n% - Multi-subj: covariates only\n% - Multi-group: conditions & covariates\n% - Multi-group: covariates only\n%\n% - Population main effect: 2 cond's, 1 scan/cond (paired t-test)\n% - Dodgy population main effect: >2 cond's, 1 scan/cond\n% - Compare-populations: 1 scan/subject (two sample t-test)\n% - Compare-populations: 1 scan/subject (AnCova)\n%\n% - The Full Monty... (asks you everything!)\n%\n% iii) SPM96 PET models: models used in SPM96 for PET/SPECT\n% These models are provided for backward compatibility, but as they\n% don't include some of the advanced modelling features, we recommend\n% you switch to the new (SPM99) models at the earliest opportunity.\n% - SPM96:Single-subject: replicated conditions\n% - SPM96:Single-subject: replicated conditions & covariates\n% - SPM96:Single-subject: covariates only\n% - SPM96:Multi-subject: different conditions\n% - SPM96:Multi-subject: replicated conditions\n% - SPM96:Multi-subject: different conditions & covariates\n% - SPM96:Multi-subject: replicated conditions & covariates\n% - SPM96:Multi-subject: covariates only\n% - SPM96:Multi-group: different conditions\n% - SPM96:Multi-group: replicated conditions\n% - SPM96:Multi-group: different conditions & covariates\n% - SPM96:Multi-group: replicated conditions & covariates\n% - SPM96:Multi-group: covariates only\n% - SPM96:Compare-groups: 1 scan per subject\n%\n%\n% Random effects, generalisability, population inference...\n% =========================================================\n%\n% Note that SPM only considers a single component of variance, the\n% residual error variance. When there are repeated measures, all\n% analyses with SPM are fixed effects analyses, and inference only\n% extends to the particular subjects under consideration (at the times\n% they were imaged).\n%\n% In particular, the multi-subject and multi-group designs ignore the\n% variability in response from subject to subject. Since the\n% scan-to-scan (within-condition, within-subject variability is much\n% smaller than the between subject variance which is ignored), this can\n% lead to detection of group effects that are not representative of the\n% population(s) from which the subjects are drawn. This is particularly\n% serious for multi-group designs comparing two groups. If inference\n% regarding the population is required, a random effects analysis is\n% required.\n%\n% However, random effects analyses can be effected by appropriately\n% summarising the data, thereby collapsing the model such that the\n% residual variance for the new model contains precisely the variance\n% components needed for a random effects analysis. In many cases, the\n% fixed effects models here can be used as the first stage in such a\n% two-stage procedure to produce appropriate summary data, which can\n% then be used as raw data for a second-level analysis. For instance,\n% the \"Multi-subj: cond x subj interaction & covariates\" design can be\n% used to write out an image of the activation for each subject. A\n% simple t-test on these activation images then turns out to be\n% equivalent to a mixed-effects analysis with random subject and\n% subject by condition interaction effects, inferring for the\n% population based on this sample of subjects (strictly speaking the\n% design would have to be balanced, with equal numbers of scans per\n% condition per subject, and also only two conditions per subject). For\n% additional details, see spm_RandFX.man.\n%\n% ----------------\n%\n% Selecting image files & indicating conditions\n% =============================================\n%\n% You may now be prompted to specify how many studies, subjects and\n% conditions you have, and then will be promted to select the scans.\n%\n% The data should all have the same orientation and image and voxel size.\n%\n% File selection is handled by spm_select.m - the help for which describes\n% efficient use of the interface.\n%\n% You may be asked to indicate the conditions for a set of scans, with\n% a prompt like \"[12] Enter conditions? (2)\". For this particular\n% example you need to indicate for 12 scans the corresponding\n% condition, in this case from 2 conditions. Enter a vector of\n% indicators, like '0 1 0 1...', or a string of indicators, like\n% '010101010101' or '121212121212', or 'rararararara'. (This\n% \"conditions\" input is handled by spm_input.m, where comprehensive\n% help can be found.)\n%\n% ----------------\n%\n% Covariate & nuisance variable entry\n% ===================================\n%\n% * If applicable, you'll be asked to specify covariates and nuisance\n% variables. Unlike SPM94/5/6, where the design was partitioned into\n% effects of interest and nuisance effects for the computation of\n% adjusted data and the F-statistic (which was used to thresh out\n% voxels where there appeared to be no effects of interest), SPM99 does\n% not partition the design in this way. The only remaining distinction\n% between effects of interest (including covariates) and nuisance\n% effects is their location in the design matrix, which we have\n% retained for continuity. Pre-specified design matrix partitions can\n% be entered. (The number of covariates / nuisance variables specified,\n% is actually the number of times you are prompted for entry, not the\n% number of resulting design matrix columns.) You will be given the\n% opportunity to name the covariate.\n% \n% * Factor by covariate interactions: For covariate vectors, you may be\n% offered a choice of interaction options. (This was called \"covariate\n% specific fits\" in SPM95/6.) The full list of possible options is:\n% - \n% - with replication\n% - with condition (across group)\n% - with subject (across group)\n% - with group\n% - with condition (within group)\n% - with subject (within group)\n%\n% * Covariate centering: At this stage may also be offered \"covariate\n% centering\" options. The default is usually that appropriate for the\n% interaction chosen, and ensures that main effects of the interacting\n% factor aren't affected by the covariate. You are advised to choose\n% the default, unless you have other modelling considerations. The full\n% list of possible options is:\n% - around overall mean\n% - around replication means\n% - around condition means (across group)\n% - around subject means (across group)\n% - around group means\n% - around condition means (within group)\n% - around subject means (within group)\n% - \n%\n% ----------------\n%\n% Global options\n% ==============\n%\n% Depending on the design configuration, you may be offered a selection\n% of global normalisation and scaling options:\n%\n% * Method of global flow calculation\n% - SPM96:Compare-groups: 1 scan per subject\n% - None (assumming no other options requiring the global value chosen)\n% - User defined (enter your own vector of global values)\n% - SPM standard: mean voxel value (within per image fullmean/8 mask)\n%\n% * Grand mean scaling : Scaling of the overall grand mean simply\n% scales all the data by a common factor such that the mean of all the\n% global values is the value specified. For qualitative data, this puts\n% the data into an intuitively accessible scale without altering the\n% statistics. When proportional scaling global normalisation is used\n% (see below), each image is seperately scaled such that it's global\n% value is that specified (in which case the grand mean is also\n% implicitly scaled to that value). When using AnCova or no global\n% normalisation, with data from different subjects or sessions, an\n% intermediate situation may be appropriate, and you may be given the\n% option to scale group, session or subject grand means seperately. The\n% full list of possible options is:\n% - scaling of overall grand mean\n% - caling of replication grand means\n% - caling of condition grand means (across group)\n% - caling of subject grand means (across group)\n% - caling of group grand means\n% - caling of condition (within group) grand means\n% - caling of subject (within group) grand means\n% - implicit in PropSca global normalisation)\n% - no grand Mean scaling>'\n%\n% * Global normalisation option : Global nuisance effects are usually\n% accounted for either by scaling the images so that they all have the\n% same global value (proportional scaling), or by including the global\n% covariate as a nuisance effect in the general linear model (AnCova).\n% Much has been written on which to use, and when. Basically, since\n% proportional scaling also scales the variance term, it is appropriate\n% for situations where the global measurement predominantly reflects\n% gain or sensitivity. Where variance is constant across the range of\n% global values, linear modelling in an AnCova approach has more\n% flexibility, since the model is not restricted to a simple\n% proportional regression.\n%\n% Considering AnCova global normalisation, since subjects are unlikely\n% to have the same relationship between global and local measurements,\n% a subject-specific AnCova (\"AnCova by subject\"), fitting a different\n% slope and intercept for each subject, would be preferred to the\n% single common slope of a straight AnCova. (Assumming there's enough\n% scans per subject to estimate such an effect.) This is basically an\n% interaction of the global covariate with the subject factor. You may\n% be offered various AnCova options, corresponding to interactions with\n% various factors according to the design definition: The full list of\n% possible options is:\n% - AnCova\n% - AnCova by replication\n% - AnCova by condition (across group)\n% - AnCova by subject (across group)\n% - AnCova by group\n% - AnCova by condition (within group)\n% - AnCova by subject (within group)\n% - Proportional scaling\n% - \n%\n% Since differences between subjects may be due to gain and sensitivity\n% effects, AnCova by subject could be combined with \"grand mean scaling\n% by subject\" to obtain a combination of between subject proportional\n% scaling and within subject AnCova.\n%\n% * Global centering: Lastly, for some designs using AnCova, you will\n% be offered a choice of centering options for the global covariate. As\n% with covariate centering, this is only relevant if you have a\n% particular interest in the parameter estimates. Usually, the default\n% of a centering corresponding to the AnCova used is chosen. The full\n% list of possible options is:\n% - around overall mean\n% - around replication means\n% - around condition means (across group)\n% - around subject means (across group)\n% - around group means\n% - around condition means (within group)\n% - around subject means (within group)\n% - \n% - around user specified value\n% - (as implied by AnCova)\n% - GM (The grand mean scaled value)\n% - (redundant: not doing AnCova)\n%\n%\n%\n% Note that this is a logical ordering for the global options, which is\n% not the order used by the interface due to algorithm constraints. The\n% interface asks for the options in this order:\n% - Global normalisation\n% - Grand mean scaling options\n% (if not using proportional scaling global normalisation)\n% - Value for grand mean scaling proportional scaling GloNorm\n% (if appropriate)\n% - Global centering options\n% - Value for global centering (if \"user-defined\" chosen)\n% - Method of calculation\n%\n% ----------------\n%\n% Masking options\n% ===============\n%\n% The mask specifies the voxels within the image volume which are to be\n% assessed. SPM supports three methods of masking. The volume analysed\n% is the intersection of all masks:\n%\n% i) Threshold masking : \"Analysis threshold\"\n% - images are thresholded at a given value and only voxels at\n% which all images exceed the threshold are included in the\n% analysis.\n% - The threshold can be absolute, or a proportion of the global\n% value (after scaling), or \"-Inf\" for no threshold masking.\n% - (This was called \"Grey matter threshold\" in SPM94/5/6)\n%\n% ii) Implicit masking\n% - An \"implicit mask\" is a mask implied by a particular voxel\n% value. Voxels with this mask value are excluded from the\n% analysis.\n% - For image data-types with a representation of NaN\n% (see spm_type.m), NaN's is the implicit mask value, (and\n% NaN's are always masked out).\n% - For image data-types without a representation of NaN, zero is\n% the mask value, and the user can choose whether zero voxels\n% should be masked out or not.\n%\n% iii) Explicit masking\n% - Explicit masks are other images containing (implicit) masks\n% that are to be applied to the current analysis.\n% - All voxels with value NaN (for image data-types with a\n% representation of NaN), or zero (for other data types) are\n% excluded from the analysis.\n% - Explicit mask images can have any orientation and voxel/image\n% size. Nearest neighbour interpolation of a mask image is used if\n% the voxel centers of the input images do not coincide with that\n% of the mask image.\n%\n%\n% ----------------\n%\n% Non-sphericity correction\n% =========================\n%\n% In some instances the i.i.d. assumptions about the errors do not hold:\n%\n% Identity assumption:\n% The identity assumption, of equal error variance (homoscedasticity), can\n% be violated if the levels of a factor do not have the same error variance.\n% For example, in a 2nd-level analysis of variance, one contrast may be scaled\n% differently from another. Another example would be the comparison of\n% qualitatively different dependant variables (e.g. normals vs. patients). If\n% You say no to identity assumptions, you will be asked whether the error\n% variance is the same over levels of each factor. Different variances\n% (heteroscedasticy) induce different error covariance components that\n% are estimated using restricted maximum likelihood (see below).\n%\n% Independence assumption.\n% In some situations, certain factors may contain random effects. These induce\n% dependencies or covariance components in the error terms. If you say no \n% to independence assumptions, you will be asked whether random effects\n% should be modelled for each factor. A simple example of this would be\n% modelling the random effects of subject. These cause correlations among the\n% error terms of observation from the same subject. For simplicity, it is\n% assumed that the random effects of each factor are i.i.d. One can always\n% re-specify the covariance components by hand in SPM.xVi.Vi for more\n% complicated models\n%\n% ReML\n% The ensuing covariance components will be estimated using ReML in spm_spm\n% (assuming the same for all responsive voxels) and used to adjust the \n% statistics and degrees of freedom during inference. By default spm_spm\n% will use weighted least squares to produce Gauss-Markov or Maximum\n% likelihood estimators using the non-sphericity structure specified at this \n% stage. The components will be found in xX.xVi and enter the estimation \n% procedure exactly as the serial correlations in fMRI models.\n% \n% see also: spm_reml.m and spm_non_sphericity.m\n% \n% ----------------\n%\n% Multivariate analyses\n% =====================\n%\n% Mulitvariate analyses with n-variate response variables are supported\n% and automatically invoke a ManCova and CVA in spm_spm. Multivariate\n% designs are, at the moment limited to Basic and PET designs.\n%\n% ----------------------------------------------------------------------\n%\n% Variables saved in the SPM stucture\n%\n% xY.VY - nScan x 1 struct array of memory mapped images\n% (see spm_vol for definition of the map structure)\n% xX - structure describing design matrix\n% xX.D - design definition structure\n% (See definition in main body of spm_spm_ui.m)\n% xX.I - nScan x 4 matrix of factor level indicators\n% I(n,i) is the level of factor i corresponding to image n\n% xX.sF - 1x4 cellstr containing the names of the four factors\n% xX.sF{i} is the name of factor i\n% xX.X - design matrix\n% xX.xVi - correlation constraints for non-spericity correction\n% xX.iH - vector of H partition (condition effects) indices,\n% identifying columns of X correspoding to H\n% xX.iC - vector of C partition (covariates of interest) indices\n% xX.iB - vector of B partition (block effects) indices\n% xX.iG - vector of G partition (nuisance variables) indices\n% xX.name - p x 1 cellstr of effect names corresponding to columns\n% of the design matrix\n% \n% xC - structure array of covariate details\n% xC(i).rc - raw (as entered) i-th covariate\n% xC(i).rcname - name of this covariate (string)\n% xC(i).c - covariate as appears in design matrix (after any scaling,\n% centering of interactions)\n% xC(i).cname - cellstr containing names for effects corresponding to\n% columns of xC(i).c\n% xC(i).iCC - covariate centering option\n% xC(i).iCFI - covariate by factor interaction option\n% xC(i).type - covariate type: 1=interest, 2=nuisance, 3=global\n% xC(i).cols - columns of design matrix corresponding to xC(i).c\n% xC(i).descrip - cellstr containing a description of the covariate\n% \n% xGX - structure describing global options and values\n% xGX.iGXcalc - global calculation option used\n% xGX.sGXcalc - string describing global calculation used\n% xGX.rg - raw globals (before scaling and such like)\n% xGX.iGMsca - grand mean scaling option\n% xGX.sGMsca - string describing grand mean scaling\n% xGX.GM - value for grand mean (/proportional) scaling\n% xGX.gSF - global scaling factor (applied to xGX.rg)\n% xGX.iGC - global covariate centering option\n% xGX.sGC - string describing global covariate centering option\n% xGX.gc - center for global covariate\n% xGX.iGloNorm - Global normalisation option\n% xGX.sGloNorm - string describing global normalisation option\n% \n% xM - structure describing masking options\n% xM.T - Threshold masking value (-Inf=>None,\n% real=>absolute, complex=>proportional (i.e. times global) )\n% xM.TH - nScan x 1 vector of analysis thresholds, one per image\n% xM.I - Implicit masking (0=>none, 1=>implicit zero/NaN mask)\n% xM.VM - struct array of explicit mask images\n% (empty if no explicit masks)\n% xM.xs - structure describing masking options\n% (format is same as for xsDes described below)\n% \n% xsDes - structure of strings describing the design:\n% Fieldnames are essentially topic strings (use \"_\"'s for\n% spaces), and the field values should be strings or cellstr's\n% of information regarding that topic. spm_DesRep.m\n% uses this structure to produce a printed description\n% of the design, displaying the fieldnames (with \"_\"'s \n% converted to spaces) in bold as topics, with\n% the corresponding text to the right\n% \n% SPMid - String identifying SPM and program versions\n%\n% ----------------\n%\n% NB: The SPM.mat file is not very portable: It contains\n% memory-mapped handles for the images, which hardcodes the full file\n% pathname and datatype. Therefore, subsequent to creating the\n% SPM.mat, you cannot move the image files, and cannot move the\n% entire analysis to a system with a different byte-order (even if the\n% full file pathnames are retained. Further, the image scalefactors\n% will have been pre-scaled to effect any grand mean or global\n% scaling.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Andrew Holmes\n% $Id: spm_spm_ui.m 539 2006-05-19 17:59:30Z Darren $\n\nSCCSid = '$Rev: 539 $';\n\n%=======================================================================\n% - FORMAT specifications for programers\n%=======================================================================\n%( This is a multi function function, the first argument is an action )\n%( string, specifying the particular action function to take. )\n%\n% FORMAT spm_spm_ui('CFG',D)\n% Configure design\n% D - design definition structure - see format definition below\n% (If D is a struct array, then the user is asked to choose from the\n% design definitions in the array. If D is not specified as an\n% argument, then user is asked to choose from the standard internal\n% definitions)\n%\n% FORMAT [P,I] = spm_spm_ui('Files&Indices',DsF,Dn,DbaTime)\n% PET/SPECT file & factor level input\n% DsF - 1x4 cellstr of factor names (ie D.sF)\n% Dn - 1x4 vector indicating the number of levels (ie D.n)\n% DbaTime - ask for F3 images in time order, with F2 levels input by user?\n% P - nScan x 1 cellsrt of image filenames\n% I - nScan x 4 matrix of factor level indices\n%\n% FORMAT D = spm_spm_ui('DesDefs_Stats')\n% Design definitions for simple statistics\n% D - struct array of design definitions (see definition below)\n%\n% FORMAT D = spm_spm_ui('DesDefs_PET')\n% Design definitions for PET/SPECT models\n% D - struct array of design definitions (see definition below)\n%\n% FORMAT D = spm_spm_ui('DesDefs_PET96')\n% Design definitions for SPM96 PET/SPECT models\n% D - struct array of design definitions (see definition below)\n\n%=======================================================================\n% Design definitions specification for programers & power users\n%=======================================================================\n% Within spm_spm_ui.m, a definition structure, D, determines the\n% various options, defaults and specifications appropriate for a\n% particular design. Usually one uses one of the pre-specified\n% definitions chosen from the menu, which are specified in the function\n% actions at the end of the program (spm_spm_ui('DesDefs_Stats'),\n% spm_spm_ui('DesDefs_PET'), spm_spm_ui('DesDefs_PET96')). For\n% customised use of spm_spm_ui.m, the design definition structure is\n% shown by the following example:\n%\n% D = struct(...\n% 'DesName','The Full Monty...',...\n% 'n',[Inf Inf Inf Inf], 'sF',{{'repl','cond','subj','group'}},...\n% 'Hform', 'I(:,[4,2]),''-'',{''stud'',''cond''}',...\n% 'Bform', 'I(:,[4,3]),''-'',{''stud'',''subj''}',...\n% 'nC',[Inf,Inf],'iCC',{{[1:8],[1:8]}},'iCFI',{{[1:7],[1:7]}},...\n% 'iGXcalc',[1,2,3],'iGMsca',[1:7],'GM',50,...\n% 'iGloNorm',[1:9],'iGC',[1:11],...\n% 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n% 'b',struct('aTime',1));\n%\n% ( Note that the struct command expands cell arrays to give multiple )\n% ( records, so if you want a cell array as a field value, you have to )\n% ( embed it within another cell, hence the double \"{{\"'s. )\n%\n% ----------------\n%\n% Design structure fields and option definitions\n% ==============================================\n%\n% D.Desname - a string naming the design\n%\n% In general, spm_spm_ui.m accomodates four factors. Usually these are\n% 'group', 'subject', 'condition' & 'replication', but to allow for a\n% flexible interface these are dynamically named for different designs,\n% and are referred to as Factor4, Factor3, Factor2, and Factor1\n% respectively. The first part of the D definition dictates the names\n% and number of factor levels (i.e. number of subjects etc.) relevant\n% for this design, and also how the H (condition) and B (block)\n% partitions of the design matrix should be constructed.\n%\n% D.n - a 1x4 vector, indicating the number of levels. D.n(i)\n% for i in [1:4] is the number of levels for factor i.\n% Specify D.n(i) as 1 to ignore this factor level,\n% otherwise the number of levels can be pre-specified as a\n% given number, or given as Inf to allow the user to\n% choose the number of levels.\n%\n% D.sF - a 1x4 cellstr containing the names of the four\n% factors. D.sF{i} is the name of factor i.\n%\n% D.b.aTime - a binary indicator specifying whether images within F3\n% level (subject) are selected in time order. For time\n% order (D.b.aTime=1), F2 levels are indicated by a user\n% input \"condition\" string (input handled by spm_input's\n% 'c' type). When (D.b.aTime=0), images for each F3 are\n% selected by F2 (condition). The latter was the mode of\n% SPM95 and SPM96. (SPM94 and SPMclassic didn't do\n% replications of conditions.)\n%\n% Once the user has entered the images and indicated the factor levels,\n% a nScan x 4 matrix, I, of indicator variables is constructed\n% specifying for each scan the relevant level of each of the four\n% factors. I(n,i) is the level of factor i corresponding to image n.\n% This I matrix of factor indicators is then used to construct the H\n% and B forms of the design matrix according to the prescripton in the\n% design definition D:\n%\n% D.Hform - a string specifying the form of the H partition of the\n% design matrix. The string is evaluated as an argument\n% string for spm_DesMtx, which builds design matrix\n% partitions from indicator vectors.\n% (eval(['[H,Hnames] = spm_DesMtx(',D.Hform,');']))\n%\n% D.BForm - a string specifying the form of the G partition.\n%\n% ( Note that a constant H partition is dropped if the B partition can )\n% ( model the constant effect. )\n%\n% The next part of the design definition defines covariate options.\n% Covariates are split into covariates (of interest) and nuisance\n% variables. The covariates of interest and nuisance variables are put\n% into the C & G partitions of the design matrox (the final design\n% matrix is [H,C,B,G], where global nuisance covariates are appended to\n% G). In SPM94/5/6 the design matrix was partitioned into effects of\n% interest [H,C] and effects of no interest [B,G], with an F-test for\n% no effects of interest and adjusted data (for effects of no interest)\n% following from these partitions. SPM99 is more freestyle, with\n% adjustments and F-tests specified by contrasts. However, the concept\n% of effects of interest and of no interest has been maintained for\n% continuity, and spm_spm_ui.m computes an F-contrast to test for \"no\n% effects of interest\".\n%\n% D.nC - a 1x2 vector: D.nC(1) is the number of covariates,\n% D.nC(2) the number of nuisance variables. Specify zero\n% to skip covariate entry, the actual number of\n% covariates, or Inf to let the user specify the number of\n% covariates. As with earlier versions, blocks of design\n% matrix can be entered. However, these are now treated as\n% a single covariate entity, so the number of\n% covariates.nuisance variables is now the number of items\n% you are prompted for, regardless of their dimension. (In\n% SPM95-6 this number was the number of covariate vectors\n% that could be entered.)\n%\n% D.iCC - a 1x2 cell array containing two vectors indicating the\n% allowable covariate centering options for this design.\n% These options are defined in the body of spm_spm_ui.m,\n% in variables sCC & CFIforms. Use negative indices to\n% indicate the default, if any - the largest negative\n% wins.\n%\n% D.iCFI - a 1x2 cell array containing two vectors indicating the\n% allowable covariate by factor interactions for this\n% design. Interactions are only offered with a factor if\n% it has multiple levels. The options are defined in the\n% body of spm_spm_ui.m, in variables sCFI & CFIforms. Use\n% negative indicies to indicate a default.\n%\n% The next part defines global options:\n%\n% D.iGXcalc - a vector of possible global calculation options for\n% this design, as listed in the body of spm_spm_ui.m in\n% variable sGXcalc. (If other global options are chosen,\n% then the \"omit\" option is not offered.) Again, negative\n% values indicate a default.\n%\n% D.iGloNorm - a vector of possible global normalisation options for\n% this design, as described in the body of spm_spm_ui.m in\n% variable sGloNorm.\n%\n% D.iGMsca - a vector of possible grand mean scaling options, as\n% described in the body of spm_spm_ui.m in variable\n% sGMsca. (Note that grand mean scaling is redundent when\n% using proportional scaling global flow normalisation.)\n%\n% D.iGC - a vector of possible global covariate centering\n% options, corresponding to the descriptions in variable\n% iCC given in the body of spm_spm_ui.m. This is only\n% relevant for AnCova type global normalisation, and even\n% then only if you're actually interested in constraining\n% the values of the parameters in some useful way.\n% Usually, one chooses option 10, \"as implied by AnCova\".\n%\n% The next component specifies masking options:\n%\n% D.M_.T - a vector defining the analysis threshold: Specify\n% \"-Inf\" as an element to offer \"None\" as an option. If a\n% real element is found, then absolute thresholding is\n% offered, with the first real value proffered as default\n% threshold. If an imaginary element is found, then\n% proportional thresholding if offered (i.e. the threshold\n% is a proportion of the image global), with the (abs of)\n% the first imaginary element proffered as default.\n%\n% D.M_.I - Implicit masking? 0-no, 1-yes, Inf-ask. (This is\n% irrelevant for image types with a representation of NaN,\n% since NaN is then the mask value, and NaN's are always\n% masked.)\n%\n% D.M.X - Explicit masking? 0-no, 1-yes, Inf-ask.\n% \n% ----------------\n%\n% To use a customised design structure D, type spm_spm_ui('cfg',D) in the\n% Matlab command window.\n%\n% The easiest way to generate a customised design definition structure\n% is to tweak one of the pre-defined definitions. The following code\n% will prompt you to select one of the pre-defined designs, and return\n% the design definition structure for you to work on:\n%\n% D = spm_spm_ui(char(spm_input('Select design class...','+1','m',...\n% \t\t{'Basic stats','Standard PET designs','SPM96 PET designs'},...\n% \t\t{'DesDefs_Stats','DesDefs_PET','DesDefs_PET96'},2)));\n% D = D(spm_input('Select design type...','+1','m',{D.DesName}'))\n%\n%_______________________________________________________________________\n% @(#)spm_spm_ui.m\t2.54 Andrew Holmes 04/12/09\n\n\n%-Condition arguments\n%-----------------------------------------------------------------------\nif (nargin==0), Action = 'CFG'; else, Action = varargin{1}; end\n\n\nswitch lower(Action)\ncase 'cfg'\n %===================================================================\n % - C O N F I G U R E D E S I G N\n %===================================================================\n % spm_spm_ui('CFG',D)\n if nargin<2, D = []; else, D = varargin{2}; end\n \n %-GUI setup\n %-------------------------------------------------------------------\n SPMid = spm('FnBanner',mfilename,SCCSid);\n [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Stats: Setup analysis',0);\n spm_help('!ContextHelp',mfilename)\n \n \n %-Ask about overwriting files from previous analyses...\n %-------------------------------------------------------------------\n if exist(fullfile('.','SPM.mat'))\n str = {\t'Current directory contains existing SPM file:',...\n 'Continuing will overwrite existing file!'};\n if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);\n fprintf('%-40s: %30s\\n\\n',...\n 'Abort... (existing SPM file)',spm('time'))\n spm_clf(Finter)\n return\n end\n end\n \n \n \n %-Option definitions\n %-------------------------------------------------------------------\n %-Generic factor names\n sF = {'sF1','sF2','sF3','sF4'};\n \n %-Covariate by factor interaction options\n sCFI = {'';...\t\t\t\t\t\t\t%-1\n 'with sF1';'with sF2';'with sF3';'with sF4';...\t\t\t%-2:5\n 'with sF2 (within sF4)';'with sF3 (within sF4)'};\t\t%-6,7\n \n %-DesMtx argument components for covariate by factor interaction options\n % (Used for CFI's Covariate Centering (CC), GMscale & Global normalisation)\n CFIforms = {\t'[]',\t\t'C',\t'{}';...\t\t\t%-1\n 'I(:,1)',\t 'FxC',\t'{D.sF{1}}';...\t\t\t%-2\n 'I(:,2)',\t 'FxC',\t'{D.sF{2}}';...\t\t\t%-3\n 'I(:,3)',\t 'FxC',\t'{D.sF{3}}';...\t\t\t%-4\n 'I(:,4)',\t 'FxC',\t'{D.sF{4}}';...\t\t\t%-5\n 'I(:,[4,2])',\t'FxC',\t'{D.sF{4},D.sF{2}}';...\t%-6\n 'I(:,[4,3])',\t'FxC',\t'{D.sF{4},D.sF{3}}'\t};\t%-7\n \n %-Centre (mean correction) options for covariates & globals (CC)\n % (options 9-12 are for centering of global when using AnCova GloNorm) (GC)\n sCC = {\t\t'around overall mean';...\t\t\t\t%-1\n 'around sF1 means';...\t\t\t\t\t%-2\n 'around sF2 means';...\t\t\t\t\t%-3\n 'around sF3 means';...\t\t\t\t\t%-4\n 'around sF4 means';...\t\t\t\t\t%-5\n 'around sF2 (within sF4) means';...\t\t\t%-6\n 'around sF3 (within sF4) means';...\t\t\t%-7\n '';...\t\t\t\t\t%-8\n 'around user specified value';...\t\t\t%-9\n '(as implied by AnCova)';...\t\t\t\t%-10\n 'GM';...\t\t\t\t\t\t%-11\n '(redundant: not doing AnCova)'}';\t\t\t%-12\n %-DesMtx I forms for covariate centering options\n CCforms = {'ones(nScan,1)',CFIforms{2:end,1},''}';\n \n \n %-Global normalization options (options 1-7 match CFIforms) (GloNorm)\n sGloNorm = {\t'AnCova';...\t\t\t\t\t\t%-1\n 'AnCova by sF1';...\t\t\t\t\t%-2\n 'AnCova by sF2';...\t\t\t\t\t%-3\n 'AnCova by sF3';...\t\t\t\t\t%-4\n 'AnCova by sF4';...\t\t\t\t\t%-5\n 'AnCova by sF2 (within sF4)';...\t\t\t%-6\n 'AnCova by sF3 (within sF4)';...\t\t\t%-7\n 'proportional scaling';...\t\t\t\t%-8\n ''};\t\t\t\t%-9\n \n %-Grand mean scaling options (GMsca)\n sGMsca = {\t'scaling of overall grand mean';...\t\t\t%-1\n 'scaling of sF1 grand means';...\t\t\t%-2\n 'scaling of sF2 grand means';...\t\t\t%-3\n 'scaling of sF3 grand means';...\t\t\t%-4\n 'scaling of sF4 grand means';...\t\t\t%-5\n 'scaling of sF2 (within sF4) grand means';...\t\t%-6\n 'scaling of sF3 (within sF4) grand means';...\t\t%-7\n '(implicit in PropSca global normalisation)';...\t%-8\n ''\t};\t\t\t%-9\n %-NB: Grand mean scaling by subject is redundent for proportional scaling\n \n \n %-Global calculation options (GXcalc)\n sGXcalc = {\t'omit';...\t\t\t\t\t\t%-1\n 'user specified';...\t\t\t\t\t%-2\n 'mean voxel value (within per image fullmean/8 mask)'};\t%-3\n \n \n \n %===================================================================\n %-D E S I G N P A R A M E T E R S\n %===================================================================\n %-Get design type\n %-------------------------------------------------------------------\n if isempty(D)\n \n D = spm_spm_ui( ...\n char(spm_input('Select design class...','+1','m',...\n {'Basic stats','Standard PET designs','SPM96 PET designs'},...\n {'DesDefs_Stats','DesDefs_PET','DesDefs_PET96'},2)));\n end\n \n D = D(spm_input('Select design type...','+1','m',{D.DesName}'));\n \n \n %-Set factor names for this design\n %-------------------------------------------------------------------\n sCC = sf_estrrep(sCC,[sF',D.sF']);\n sCFI = sf_estrrep(sCFI,[sF',D.sF']);\n sGloNorm = sf_estrrep(sGloNorm,[sF',D.sF']);\n sGMsca = sf_estrrep(sGMsca,[sF',D.sF']);\n \n %-Get filenames & factor indicies\n %-------------------------------------------------------------------\n [P,I] = spm_spm_ui('Files&Indices',D.sF,D.n,D.b.aTime);\n nScan = size(I,1);\t\t\t\t\t\t%-#obs\n \n %-Additional design parameters\n %-------------------------------------------------------------------\n bL = any(diff(I,1),1); \t%-Multiple factor levels?\n % NB: bL(2) might be thrown by user specified f1 levels\n % (D.b.aTime & D.n(2)>1) - assumme user is consistent?\n bFI = [bL(1),bL(2:3)&~bL(4),bL(4),bL([2,3])&bL(4)];\n %-Allowable interactions for covariates\n %-Only offer interactions with multi-level factors, and\n % don't offer by F2|F3 if bL(4)!\n \n %-Build Condition (H) and Block (B) partitions\n %===================================================================\n H=[];Hnames=[];\n B=[];Bnames=[];\n eval(['[H,Hnames] = spm_DesMtx(',D.Hform,');'])\n if rank(H)==nScan, error('unestimable condition effects'), end\n eval(['[B,Bnames] = spm_DesMtx(',D.Bform,');'])\n if rank(B)==nScan, error('unestimable block effects'), end\n \n %-Drop a constant H partition if B partition can model constant\n if size(H,2)>0 & all(H(:)==1) & (rank([H B])==rank(B))\n H = []; Hnames = {};\n warning('Dropping redundant constant H partition')\n end\n \n \n %-Covariate partition(s): interest (C) & nuisance (G) excluding global\n %===================================================================\n nC = D.nC;\t\t\t %-Default #covariates\n C = {[],[]}; Cnames = {{},{}}; %-Covariate DesMtx partitions & names\n xC = [];\t\t\t %-Struct array to hold raw covariates\n \n \n dcname = {'CovInt','NusCov'};\t%-Default root names for covariates\n dstr = {'covariate','nuisance variable'};\n \n GUIpos = spm_input('!NextPos');\n nc = [0,0];\n for i = 1:2\t\t\t% 1:covariates of interest, 2:nuisance variables\n \n if isinf(nC(i)), nC(i)=spm_input(['# ',dstr{i},'s'],GUIpos,'w1'); end\n \n while nc(i) < nC(i)\n \n %-Create prompt, get covariate, get covariate name\n %-----------------------------------------------------------\n if nC(i)==1\n str=dstr{i};\n else\n str=sprintf('%s %d',dstr{i},nc(i)+1);\n end\n c = spm_input(str,GUIpos,'r',[],[nScan,Inf]);\n if any(isnan(c(:))), break, end %-NaN is dummy value to exit\n nc(i) = nc(i)+1; %-#Covariates (so far)\n if nC(i)>1,\ttstr = sprintf('%s^{%d}',dcname{i},nc(i));\n else,\t\ttstr = dcname{i}; end\n cname = spm_input([str,' name?'],'+1','s',tstr);\n rc = c; %-Save covariate value\n rcname = cname; %-Save covariate name\n \n %-Interaction option? (if single covariate vector entered)?\n %-----------------------------------------------------------\n if size(c,2) == 1\n %-User choice of interaction options, default is negative\n %-Only offer interactions for appropriate factor combinations\n if length(D.iCFI{i})>1\n iCFI = intersect(abs(D.iCFI{i}),find([1,bFI]));\n dCFI = max([1,intersect(iCFI,-D.iCFI{i}(D.iCFI{i}<0))]);\n iCFI = spm_input([str,': interaction?'],'+1','m',...\n sCFI(iCFI),iCFI,find(iCFI==dCFI));\n else\n iCFI = abs(D.iCFI{i}); %-AutoSelect default option\n end\n else\n iCFI = 1;\n end\n \n %-Centre covariate(s)? (Default centring to correspond to CFI)\n % Always offer \"no centering\" as default for design matrix blocks\n %-----------------------------------------------------------\n DiCC = D.iCC{i};\n if size(c,2)>1, DiCC = union(DiCC,-8); end\n if length(DiCC)>1\n %-User has a choice of centering options\n %-Only offer factor specific for appropriate factor combinations\n iCC = intersect(abs(DiCC),find([1,bFI,1]) );\n %-Default is max -ve option in D, overridden by iCFI if CFI\n if iCFI == 1, dCC = -DiCC(DiCC<0); else, dCC = iCFI; end\n dCC = max([1,intersect(iCC,dCC)]);\n iCC = spm_input([str,': centre?'],'+1','m',...\n sCC(iCC),iCC,find(iCC==dCC));\n else\n iCC = abs(DiCC);\t%-AutoSelect default option\n end\n %-Centre within factor levels as appropriate\n if any(iCC == [1:7]), c = c - spm_meanby(c,eval(CCforms{iCC})); end\n \n %-Do any interaction (only for single covariate vectors)\n %-----------------------------------------------------------\n if iCFI > 1\t\t\t\t%-(NB:iCFI=1 if size(c,2)>1)\n tI = [eval(CFIforms{iCFI,1}),c];\n tConst = CFIforms{iCFI,2};\n tFnames = [eval(CFIforms{iCFI,3}),{cname}];\n [c,cname] = spm_DesMtx(tI,tConst,tFnames);\n elseif size(c,2)>1\t\t\t%-Design matrix block\n [null,cname] = spm_DesMtx(c,'X',cname);\n else\n cname = {cname};\n end\n \n %-Store raw covariate details in xC struct for reference\n %-Pack c into appropriate DesMtx partition\n %-----------------------------------------------------------\n %-Construct description string for covariate\n str = {sprintf('%s: %s',str,rcname)};\n if size(rc,2)>1, str = {sprintf('%s (block of %d covariates)',...\n str{:},size(rc,2))}; end\n if iCC < 8, str=[str;{['used centered ',sCC{iCC}]}]; end\n if iCFI> 1, str=[str;{['fitted as interaction ',sCFI{iCFI}]}]; end\n \n tmp = struct(\t'rc',rc,\t'rcname',rcname,...\n 'c',c,\t\t'cname',{cname},...\n 'iCC',iCC,\t'iCFI',iCFI,...\n 'type',i,...\n 'cols',[1:size(c,2)] + ...\n size([H,C{1}],2) + ...\n size([B,C{2}],2)*(i-1),...\n 'descrip',{str}\t\t\t\t);\n if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end\n C{i} = [C{i},c];\n Cnames{i} = [Cnames{i}; cname];\n \n end\t% (while)\n \n end % (for)\n clear c tI tConst tFnames\n spm_input('!SetNextPos',GUIpos);\n \n %-Unpack into C & G design matrix sub-partitions\n G = C{2}; Gnames = Cnames{2};\n C = C{1}; Cnames = Cnames{1};\n \n \n %-Options...\n %===================================================================\n %-Global normalization options (GloNorm)\n %-------------------------------------------------------------------\n if length(D.iGloNorm)>1\n %-User choice of global normalisation options, default is negative\n %-Only offer factor specific for appropriate factor combinations\n iGloNorm = intersect(abs(D.iGloNorm),find([1,bFI,1,1]));\n dGloNorm = max([0,intersect(iGloNorm,-D.iGloNorm(D.iGloNorm<0))]);\n iGloNorm = spm_input('GloNorm: Select global normalisation','+1','m',...\n sGloNorm(iGloNorm),iGloNorm,find(iGloNorm==dGloNorm));\n else\n iGloNorm = abs(D.iGloNorm);\n end\n \n \n %-Grand mean scaling options (GMsca)\n %-------------------------------------------------------------------\n if iGloNorm==8\n iGMsca=8;\t%-grand mean scaling implicit in PropSca GloNorm\n elseif length(D.iGMsca)==1\n iGMsca = abs(D.iGMsca);\n else\n %-User choice of grand mean scaling options\n %-Only offer factor specific for appropriate factor combinations\n iGMsca = intersect(abs(D.iGMsca),find([1,bFI,0,1]));\n %-Default is max -ve option in D, overridden by iGloNorm if AnCova\n if iGloNorm==9, dGMsca=-D.iGMsca(D.iGMsca<0); else, dGMsca=iGloNorm; end\n dGMsca = max([0,intersect(iGMsca,dGMsca)]);\n iGMsca = spm_input('GMsca: grand mean scaling','+1','m',...\n sGMsca(iGMsca),iGMsca,find(iGMsca==dGMsca));\n end\n \n \n %-Value for PropSca / GMsca (GM)\n %-------------------------------------------------------------------\n if iGMsca == 9 %-Not scaling (GMsca or PropSca)\n GM = 0; %-Set GM to zero when not scaling\n else %-Ask user value of GM\n if iGloNorm==8\n str = 'PropSca global mean to';\n else\n str = [strrep(sGMsca{iGMsca},'scaling of','scale'),' to'];\n end\n GM = spm_input(str,'+1','r',D.GM,1);\n %-If GM is zero then don't GMsca! or PropSca GloNorm\n if GM==0, iGMsca=9; if iGloNorm==8, iGloNorm=9; end, end\n end\n \n %-Sort out description strings for GloNorm and GMsca\n %-------------------------------------------------------------------\n sGloNorm = sGloNorm{iGloNorm};\n sGMsca = sGMsca{iGMsca};\n if iGloNorm==8\n sGloNorm = sprintf('%s to %-4g',sGloNorm,GM);\n elseif iGMsca<8\n sGMsca = sprintf('%s to %-4g',sGMsca,GM);\n end\n \n \n %-Global centering (for AnCova GloNorm) (GC)\n %-------------------------------------------------------------------\n %-Specify the centering option for the global covariate for AnCova\n %-Basically, if 'GMsca'ling then should centre to GM (iGC=11). Otherwise,\n % should centre in similar fashion to AnCova (i.e. by the same factor(s)),\n % such that models are seperable (iGC=10). This is particularly important\n % for subject specific condition effects if then passed on to a second-level\n % model. (See also spm_adjmean_ui.m) SPM96 (& earlier) used to just centre\n % GX around its (overall) mean (iGC=1).\n \n %-This code allows more general options to be specified (but is complex)\n %-Setting D.iGC=[-10,-11] gives the standard choices above\n \n %-If not doing AnCova then GC is irrelevant\n if ~any(iGloNorm == [1:7])\n iGC = 12;\n gc = [];\n else\n %-Annotate options 10 & 11 with specific details\n %---------------------------------------------------------------\n %-Tag '(as implied by AnCova)' with actual AnCova situation\n sCC{10} = [sCC{iGloNorm},' (<= ',sGloNorm,')'];\n %-Tag 'GM' case with actual GM & GMsca case\n sCC{11} = sprintf('around GM=%g (i.e. %s after grand mean scaling)',...\n GM,strrep(sCC{iGMsca},'around ',''));\n \n %-Constuct vector of allowable iGC\n %---------------------------------------------------------------\n %-Weed out redundent factor combinations from pre-set allowable options\n iGC = intersect(abs(D.iGC),find([1,bFI,1,1,1,1]));\n %-Omit 'GM' option if didn't GMsca (iGMsca~=8 'cos doing AnCova)\n if any(iGMsca==[8,9]), iGC = setdiff(iGC,11); end\n %-Omit 'GM' option if same as '(as implied by AnCova)'\n if iGloNorm==iGMsca, iGC = setdiff(iGC,11); end\n \n %-If there's a choice, set defaults (if any), & get answer\n %---------------------------------------------------------------\n if length(iGC)>1\n dGC = max([0,intersect(iGC,-D.iGC(D.iGC<0))]);\n str = 'Centre global covariate';\n if iGMsca<8, str = [str,' (after grand mean scaling)']; end\n iGC = spm_input(str,'+1','m',sCC(iGC),iGC,find(iGC==dGC));\n elseif isempty(iGC)\n error('Configuration error: empty iGC')\n end\n \n %-If 'user specified' then get value\n %---------------------------------------------------------------\n if iGC==9\n gc = spm_input('Centre globals around','+0','r',D.GM,1);\n sCC{9} = sprintf('%s of %g',sCC{iGC},gc);\n else\n gc = 0;\n end\n end\n \n \n %-Thresholds & masks defining voxels to analyse (MASK)\n %===================================================================\n GUIpos = spm_input('!NextPos');\n \n %-Analysis threshold mask\n %-------------------------------------------------------------------\n %-Work out available options:\n % -Inf=>None, real=>absolute, complex=>proportional, (i.e. times global)\n M_T = D.M_.T; if isempty(M_T), M_T = [-Inf, 100, 0.8*sqrt(-1)]; end\n M_T = {\t'none',\t\tM_T(min(find(isinf(M_T))));...\n 'absolute',\tM_T(min(find(isfinite(M_T)&(M_T==real(M_T)))));...\n 'relative',\tM_T(min(find(isfinite(M_T)&(M_T~=real(M_T)))))\t};\n \n %-Work out available options\n %-If there's a choice between proportional and absolute then ask\n %-------------------------------------------------------------------\n q = ~[isempty(M_T{1,2}), isempty(M_T{2,2}), isempty(M_T{3,2})];\n \n if all(q(2:3))\n tmp = spm_input('Threshold masking',GUIpos,'b',M_T(q,1),find(q));\n q(setdiff([1:3],tmp))=0;\n end\n \n %-Get mask value - note that at most one of q(2:3) is true\n %-------------------------------------------------------------------\n if ~any(q)\t\t\t\t%-Oops - nothing specified!\n M_T = -Inf;\n elseif all(q==[1,0,0])\t\t\t%-no threshold masking\n M_T = -Inf;\n else\t\t\t\t\t%-get mask value\n if q(1),\targs = {'br1','None',-Inf,abs(M_T{1+find(q(2:3)),2})};\n else,\t\targs = {'r',abs(M_T{1+find(q(2:3)),2})}; end\n if q(2)\n M_T = spm_input('threshold',GUIpos,args{:});\n elseif q(3)\n M_T = spm_input('threshold (relative to global)',GUIpos,...\n args{:});\n if isfinite(M_T) & isreal(M_T), M_T=M_T*sqrt(-1); end\n else\n error('Shouldn''t get here!')\n end\n end\n \n %-Make a description string\n %-------------------------------------------------------------------\n if isinf(M_T)\n xsM.Analysis_threshold = 'None (-Inf)';\n elseif isreal(M_T)\n xsM.Analysis_threshold = sprintf('images thresholded at %6g',M_T);\n else\n xsM.Analysis_threshold = sprintf(['images thresholded at %6g ',...\n 'times global'],imag(M_T));\n end\n \n \n %-Implicit masking: Ignore zero voxels in low data-types?\n %-------------------------------------------------------------------\n % (Implicit mask is NaN in higher data-types.)\n type = getfield(spm_vol(P{1,1}),'dt')*[1,0]';\n if ~spm_type(type,'nanrep')\n switch D.M_.I\n case Inf, M_I = spm_input('Implicit mask (ignore zero''s)?',...\n '+1','y/n',[1,0],1);\t\t%-Ask\n case {0,1}, M_I = D.M_.I;\t\t\t%-Pre-specified\n otherwise, error('unrecognised D.M_.I type')\n end\n \n if M_I, xsM.Implicit_masking = 'Yes: zero''s treated as missing';\n else, xsm.Implicit_masking = 'No'; end\n else\n M_I = 1;\n xsM.Implicit_masking = 'Yes: NaN''s treated as missing';\n end\n \n \n %-Explicit mask images (map them later...)\n %-------------------------------------------------------------------\n switch(D.M_.X)\n case Inf, M_X = spm_input('explicitly mask images?','+1','y/n',[1,0],2);\n case {0,1}, M_X = D.M_.X;\n otherwise, error('unrecognised D.M_.X type')\n end\n if M_X, M_P = spm_select(Inf,'image','select mask images'); else, M_P = {}; end\n \n \n %-Global calculation (GXcalc)\n %===================================================================\n iGXcalc = abs(D.iGXcalc);\n %-Only offer \"omit\" option if not doing any GloNorm, GMsca or PropTHRESH\n if ~(iGloNorm==9 & iGMsca==9 & (isinf(M_T)|isreal(M_T)))\n iGXcalc = intersect(iGXcalc,[2:size(sGXcalc,1)]);\n end\n if isempty(iGXcalc)\n error('no GXcalc options')\n elseif length(iGXcalc)>1\n %-User choice of global calculation options, default is negative\n dGXcalc = max([1,intersect(iGXcalc,-D.iGXcalc(D.iGXcalc<0))]);\n iGXcalc = spm_input('Global calculation','+1','m',...\n sGXcalc(iGXcalc),iGXcalc,find(iGXcalc==dGXcalc));\n else\n iGXcalc = abs(D.iGXcalc);\n end\n \n if iGXcalc==2\t\t\t\t%-Get user specified globals\n g = spm_input('globals','+0','r',[],[nScan,1]);\n end\n sGXcalc = sGXcalc{iGXcalc};\n \n \n % Non-sphericity correction (set xVi.var and .dep)\n %===================================================================\n xVi.I = I;\n nL = max(I);\t\t % number of levels\n mL = find(nL > 1);\t\t % multilevel factors\n xVi.var = sparse(1,4); % unequal variances\n xVi.dep = sparse(1,4); % dependencies\n\n if length(mL) > 1\n\n % repeated measures design\n %---------------------------------------------------------------\n if spm_input('non-sphericity correction?','+1','y/n',[1,0],0)\n\n % make menu strings\n %-----------------------------------------------------------\n for i = 1:4\n mstr{i} = sprintf('%s (%i levels)',D.sF{i},nL(i));\n end\n mstr = mstr(mL);\n \n % are errors identical\n %-----------------------------------------------------------\n if spm_input('are errors identical','+1','y/n',[0,1],0)\n str = 'unequal variances are between';\n [i j] = min(nL(mL));\n i = spm_input(str,'+0','m',mstr,[],j);\n\n % set in xVi and eliminate from dependency option\n %-------------------------------------------------------\n xVi.var(mL(i)) = 1;\n mL(i) = [];\n mstr(i) = [];\n end\n \n % are errors independent\n %-----------------------------------------------------------\n if spm_input('are errors independent','+1','y/n',[0,1],0)\n str = ' dependencies are within';\n [i j] = max(nL(mL));\n i = spm_input(str,'+0','m',mstr,[],j);\n\n % set in xVi\n %-------------------------------------------------------\n xVi.dep(mL(i)) = 1;\n end\n\n end\n end\n \n %-Place covariance components Q{:} in xVi.Vi\n %-------------------------------------------------------------------\n xVi = spm_non_sphericity(xVi);\n\n %===================================================================\n % - C O N F I G U R E D E S I G N\n %===================================================================\n spm('FigName','Stats: configuring',Finter,CmdLine);\n spm('Pointer','Watch');\n \n \n %-Images & image info: Map Y image files and check consistency of\n % dimensions and orientation / voxel size\n %===================================================================\n fprintf('%-40s: ','Mapping files') %-#\n VY = spm_vol(char(P));\n \n \n %-Check compatability of images (Bombs for single image)\n %-------------------------------------------------------------------\n spm_check_orientations(VY);\n \n fprintf('%30s\\n','...done') %-#\n \n \n %-Global values, scaling and global normalisation\n %===================================================================\n %-Compute global values\n %-------------------------------------------------------------------\n switch iGXcalc, case 1\n %-Don't compute => no GMsca (iGMsca==9) or GloNorm (iGloNorm==9)\n g = [];\n case 2\n %-User specified globals\n case 3\n %-Compute as mean voxel value (within per image fullmean/8 mask)\n g = zeros(nScan,1 );\n fprintf('%-40s: %30s','Calculating globals',' ') %-#\n for i = 1:nScan\n str = sprintf('%3d/%-3d',i,nScan);\n fprintf('%s%30s',repmat(sprintf('\\b'),1,30),str)%-#\n g(i) = spm_global(VY(i));\n end\n fprintf('%s%30s\\n',repmat(sprintf('\\b'),1,30),'...done') %-#\n otherwise\n error('illegal iGXcalc')\n end\n rg = g;\n \n \n fprintf('%-40s: ','Design configuration') %-#\n \n \n %-Scaling: compute global scaling factors gSF required to implement\n % proportional scaling global normalisation (PropSca) or grand mean\n % scaling (GMsca), as specified by iGMsca (& iGloNorm)\n %-------------------------------------------------------------------\n switch iGMsca, case 8\n %-Proportional scaling global normalisation\n if iGloNorm~=8, error('iGloNorm-iGMsca(8) mismatch for PropSca'), end\n gSF = GM./g;\n g = GM*ones(nScan,1);\n case {1,2,3,4,5,6,7}\n %-Grand mean scaling according to iGMsca\n gSF = GM./spm_meanby(g,eval(CCforms{iGMsca}));\n g = g.*gSF;\n case 9\n %-No grand mean scaling\n gSF = ones(nScan,1);\n otherwise\n error('illegal iGMsca')\n end\n \n \n %-Apply gSF to memory-mapped scalefactors to implement scaling\n %-------------------------------------------------------------------\n for i = 1:nScan\n VY(i).pinfo(1:2,:) = VY(i).pinfo(1:2,:)*gSF(i);\n end\n \n \n %-AnCova: Construct global nuisance covariates partition (if AnCova)\n %-------------------------------------------------------------------\n if any(iGloNorm == [1:7])\n \n %-Centre global covariate as requested\n %---------------------------------------------------------------\n switch iGC, case {1,2,3,4,5,6,7}\t%-Standard sCC options\n gc = spm_meanby(g,eval(CCforms{iGC}));\n case 8\t\t\t\t\t%-No centering\n gc = 0;\n case 9\t\t\t\t\t%-User specified centre\n %-gc set above\n case 10\t\t\t\t\t%-As implied by AnCova option\n gc = spm_meanby(g,eval(CCforms{iGloNorm}));\n case 11\t\t\t\t\t%-Around GM\n gc = GM;\n otherwise\t\t\t\t%-unknown iGC\n error('unexpected iGC value')\n end\n \n \n %-AnCova - add scaled centred global to DesMtx `G' partition\n %---------------------------------------------------------------\n rcname = 'global'; \n tI = [eval(CFIforms{iGloNorm,1}),g - gc];\n tConst = CFIforms{iGloNorm,2};\n tFnames = [eval(CFIforms{iGloNorm,3}),{rcname}];\n [f,gnames] = spm_DesMtx(tI,tConst,tFnames);\n clear tI tConst tFnames\n \n %-Save GX info in xC struct for reference\n %---------------------------------------------------------------\n str = {sprintf('%s: %s',dstr{2},rcname)};\n if any(iGMsca==[1:7]), str=[str;{['(after ',sGMsca,')']}]; end\n if iGC ~= 8, str=[str;{['used centered ',sCC{iGC}]}]; end\n if iGloNorm > 1\n str=[str;{['fitted as interaction ',sCFI{iGloNorm}]}]; \n end\n tmp = struct(\t'rc',rg.*gSF,\t\t'rcname',rcname,...\n 'c',f,\t\t\t'cname'\t,{gnames},...\n 'iCC',iGC,\t\t'iCFI'\t,iGloNorm,...\n 'type',\t\t\t3,...\n 'cols',[1:size(f,2)] + size([H C B G],2),...\n 'descrip',\t\t{str}\t\t);\n \n G = [G,f]; Gnames = [Gnames; gnames];\n if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end\n \n \n elseif iGloNorm==8 | iGXcalc>1\n \n %-Globals calculated, but not AnCova: Make a note of globals\n %---------------------------------------------------------------\n if iGloNorm==8\n str = { 'global values: (used for proportional scaling)';...\n '(\"raw\" unscaled globals shown)'};\n elseif isfinite(M_T) & ~isreal(M_T)\n str = { 'global values: (used to compute analysis threshold)'};\n else\n str = { 'global values: (computed but not used)'};\n end\n \n rcname ='global';\n tmp = struct(\t'rc',rg,\t'rcname',rcname,...\n 'c',{[]},\t'cname'\t,{{}},...\n 'iCC',0,\t'iCFI'\t,0,...\n 'type',\t\t3,...\n 'cols',\t\t{[]},...\n 'descrip',\t{str}\t\t\t);\n \n if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end\n end\n \n \n %-Save info on global calculation in xGX structure\n %-------------------------------------------------------------------\n xGX = struct(...\n 'iGXcalc',iGXcalc,\t'sGXcalc',sGXcalc,\t'rg',rg,...\n 'iGMsca',iGMsca,\t'sGMsca',sGMsca,\t'GM',GM,'gSF',gSF,...\n 'iGC',\tiGC,\t\t'sGC',\tsCC{iGC},\t'gc',\tgc,...\n 'iGloNorm',iGloNorm,\t'sGloNorm',sGloNorm);\n \n \n \n %-Construct masking information structure and compute actual analysis\n % threshold using scaled globals (rg.*gSF)\n %-------------------------------------------------------------------\n if isreal(M_T),\tM_TH = M_T * ones(nScan,1);\t%-NB: -Inf is real\n else,\t\tM_TH = imag(M_T) * (rg.*gSF); end\n \n if ~isempty(M_P)\n VM = spm_vol(char(M_P));\n xsM.Explicit_masking = [{'Yes: mask images :'};{VM.fname}'];\n else\n VM = [];\n xsM.Explicit_masking = 'No';\n end\n xM = struct('T',M_T, 'TH',M_TH, 'I',M_I, 'VM',{VM}, 'xs',xsM);\n \n \n %-Construct full design matrix (X), parameter names and structure (xX)\n %===================================================================\n X = [H C B G];\n tmp = cumsum([size(H,2), size(C,2), size(B,2), size(G,2)]);\n xX = struct(\t'X',\t\tX,...\n 'iH',\t\t[1:size(H,2)],...\n 'iC',\t\t[1:size(C,2)] + tmp(1),...\n 'iB',\t\t[1:size(B,2)] + tmp(2),...\n 'iG',\t\t[1:size(G,2)] + tmp(3),...\n 'name',\t\t{[Hnames; Cnames; Bnames; Gnames]},...\n 'I',\t\tI,...\n 'sF',\t\t{D.sF});\n \n \n %-Design description (an nx2 cellstr) - for saving and display\n %===================================================================\n tmp = {\tsprintf('%d condition, +%d covariate, +%d block, +%d nuisance',...\n size(H,2),size(C,2),size(B,2),size(G,2));...\n sprintf('%d total, having %d degrees of freedom',...\n size(X,2),rank(X));...\n sprintf('leaving %d degrees of freedom from %d images',...\n size(X,1)-rank(X),size(X,1))\t\t\t\t};\n xsDes = struct(\t'Design',\t\t\t{D.DesName},...\n 'Global_calculation',\t\t{sGXcalc},...\n 'Grand_mean_scaling',\t\t{sGMsca},...\n 'Global_normalisation',\t\t{sGloNorm},...\n 'Parameters',\t\t\t{tmp}\t\t\t);\n \n \n fprintf('%30s\\n','...done') %-#\n \n \n \n %-Assemble SPM structure\n %===================================================================\n SPM.xY.P\t= P;\t\t\t% filenames\n SPM.xY.VY\t= VY;\t\t\t% mapped data\n SPM.nscan\t= size(xX.X,1); % scan number\n SPM.xX\t\t= xX;\t\t\t% design structure\n SPM.xC\t\t= xC;\t\t\t% covariate structure\n SPM.xGX\t\t= xGX;\t\t\t% global structure\n SPM.xVi\t\t= xVi;\t\t\t% non-sphericity structure\n SPM.xM\t\t= xM;\t\t\t% mask structure\n SPM.xsDes\t= xsDes;\t\t% description\n SPM.SPMid\t= SPMid;\t\t% version\n \n %-Save SPM.mat and set output argument\n %-------------------------------------------------------------------\n fprintf('%-40s: ','Saving SPM configuration') %-#\n\n if spm_matlab_version_chk('7') >=0\n save('SPM', 'SPM', '-V6');\n else\n save('SPM', 'SPM');\n end;\n fprintf('%30s\\n','...SPM.mat saved') %-#\n varargout = {SPM};\n \n %-Display Design report\n %===================================================================\n fprintf('%-40s: ','Design reporting') %-#\n fname = cat(1,{SPM.xY.VY.fname}');\n spm_DesRep('DesMtx',SPM.xX,fname,SPM.xsDes)\n fprintf('%30s\\n','...done') \n \n \n %-End: Cleanup GUI\n %===================================================================\n spm_clf(Finter)\n spm('Pointer','Arrow')\n fprintf('%-40s: %30s\\n','Completed',spm('time')) %-#\n spm('FigName','Stats: configured',Finter,CmdLine);\n spm('Pointer','Arrow')\n fprintf('\\n\\n')\n \n \n \ncase 'files&indices'\n %===================================================================\n % - Get files and factor indices\n %===================================================================\n % [P,I] = spm_spm_ui('Files&Indices',DsF,Dn,DbaTime,nV)\n % DbaTime=D.b.aTime; Dn=D.n; DsF=D.sF;\n if nargin<5, nV = 1; else, nV = varargin{5}; end\n if nargin<4, DbaTime = 1; else, DbaTime = varargin{4}; end\n if nargin<3, Dn = [Inf,Inf,Inf,Inf]; else, Dn=varargin{3}; end\n if nargin<2, DsF = {'Fac1','Fac2','Fac3','Fac4'}; else, DsF=varargin{2}; end\n \n %-Initialise variables\n %-------------------------------------------------------------------\n i4 = [];\t\t% factor 4 index (usually group)\n i3 = [];\t\t% factor 3 index (usually subject), per f4\n i2 = [];\t\t% factor 2 index (usually condition), per f3/f4\n i1 = [];\t\t% factor 1 index (usually replication), per f2/f3/f4\n P = {};\t\t% cell array of string filenames\n \n %-Accrue filenames and factor level indicator vectors\n %-------------------------------------------------------------------\n bMV = nV>1;\n if isinf(Dn(4)), n4 = spm_input(['#',DsF{4},'''s'],'+1','n1');\n else, n4 = Dn(4); end\n bL4 = n4>1;\n \n ti2 = '';\n GUIpos = spm_input('!NextPos');\n for j4 = 1:n4\n spm_input('!SetNextPos',GUIpos);\n sF4P=''; if bL4, sF4P=[DsF{4},' ',int2str(j4),': ']; end\n if isinf(Dn(3)), n3=spm_input([sF4P,'#',DsF{3},'''s'],'+1','n1');\n else, n3 = Dn(3); end\n bL3 = n3>1;\n \n if DbaTime & Dn(2)>1\n %disp('NB:selecting in time order - manually specify conditions')\n %-NB: This means f2 levels might not be 1:n2\n GUIpos2 = spm_input('!NextPos');\n for j3 = 1:n3\n sF3P=''; if bL3, sF3P=[DsF{3},' ',int2str(j3),': ']; end\n str = [sF4P,sF3P];\n tP = {};\n n21 = Dn(2)*Dn(1);\n for v=1:nV\n vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end\n ttP = cellstr(spm_select(n21,'image',[str,'select images',vstr]));\n n21 = length(ttP);\n tP = [tP,ttP];\n end\n ti2 = spm_input([str,' ',DsF{2},'?'],GUIpos2,'c',ti2',n21,Dn(2));\n %-Work out i1 & check\n [tl2,null,j] = unique(ti2);\n tn1 = zeros(size(tl2)); ti1 = zeros(size(ti2));\n for i=1:length(tl2)\n tn1(i)=sum(j==i); ti1(ti2==tl2(i))=1:tn1(i); end\n if isfinite(Dn(1)) & any(tn1~=Dn(1))\n %-#i1 levels mismatches specification in Dn(1)\n error(sprintf('#%s not %d as pre-specified',DsF{1},Dn(1)))\n end\n P = [P;tP];\n i4 = [i4; j4*ones(n21,1)];\n i3 = [i3; j3*ones(n21,1)];\n i2 = [i2; ti2];\n i1 = [i1; ti1];\n end\n \n else\n \n if isinf(Dn(2))\n n2 = spm_input([sF4P,'#',DsF{2},'''s'],'+1','n1');\n else\n n2 = Dn(2);\n end\n bL2 = n2>1;\n \n if n2==1 & Dn(1)==1 %-single scan per f3 (subj)\n %disp('NB:single scan per f3')\n str = [sF4P,'select images, ',DsF{3},' 1-',int2str(n3)];\n tP = {};\n for v=1:nV\n vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end\n ttP = cellstr(spm_select(n3,'image',[str,vstr]));\n tP = [tP,ttP];\n end\n P = [P;tP];\n i4 = [i4; j4*ones(n3,1)];\n i3 = [i3; [1:n3]'];\n i2 = [i2; ones(n3,1)];\n i1 = [i1; ones(n3,1)];\n else\n %-multi scan per f3 (subj) case\n %disp('NB:multi scan per f3')\n for j3 = 1:n3\n sF3P=''; if bL3, sF3P=[DsF{3},' ',int2str(j3),': ']; end\n if Dn(1)==1\n %-No f1 (repl) within f2 (cond)\n %disp('NB:no f1 within f2')\n str = [sF4P,sF3P,'select images: ',DsF{2},...\n ' 1-',int2str(n2)];\n tP = {};\n for v=1:nV\n vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end\n ttP = cellstr(spm_select(n2,'image',[str,vstr]));\n tP = [tP,ttP];\n end\n P = [P;tP];\n i4 = [i4; j4*ones(n2,1)];\n i3 = [i3; j3*ones(n2,1)];\n i2 = [i2; [1:n2]'];\n i1 = [i1; ones(n2,1)];\n else\n %-multi f1 (repl) within f2 (cond)\n %disp('NB:f1 within f2')\n for j2 = 1:n2\n sF2P='';\n if bL2, sF2P=[DsF{2},' ',int2str(j2),': ']; end\n str = [sF4P,sF3P,sF2P,' select images...'];\n tP = {};\n n1 = Dn(1);\n for v=1:nV\n vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end\n ttP = cellstr(spm_select(n1,'image',[str,vstr]));\n n1 = length(ttP);\n tP = [tP,ttP];\n end\n P = [P;tP];\n i4 = [i4; j4*ones(n1,1)];\n i3 = [i3; j3*ones(n1,1)];\n i2 = [i2; j2*ones(n1,1)];\n i1 = [i1; [1:n1]'];\n end % (for j2)\n end % (if Dn(1)==1)\n end % (for j3)\n end % (if n2==1 &...)\n end % (if DbaTime & Dn(2)>1)\n end % (for j4)\n varargout = {P,[i1,i2,i3,i4]};\n \n \ncase 'desdefs_stats'\n \n %===================================================================\n % - Basic Stats Design definitions...\n %===================================================================\n % D = spm_spm_ui('DesDefs_Stats');\n % These are the basic Stats design definitions...\n \n %-Note: struct expands cell array values to give multiple records:\n % => must embed cell arrays within another cell array!\n %-Negative indices indicate defaults (first used)\n \n D = struct(...\n 'DesName','One sample t-test',...\n 'n',\t[Inf 1 1 1],\t'sF',{{'obs','','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''mean''',...\n 'Bform',\t\t'[]',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...\n 'iGloNorm',9,'iGC',12,...\n 'M_',struct('T',-Inf,'I',Inf,'X',Inf),...\n 'b',struct('aTime',0));\n \n D = [D, struct(...\n 'DesName','Two sample t-test',...\n 'n',\t[Inf 2 1 1],\t'sF',{{'obs','group','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''group''',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...\n 'iGloNorm',9,'iGC',12,...\n 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n 'b',struct('aTime',1))];\n \n D = [D, struct(...\n 'DesName','Paired t-test',...\n 'n',\t[1 2 Inf 1],\t'sF',{{'','cond','pair',''}},...\n 'Hform',\t\t'I(:,2),''-'',''condition''',...\n 'Bform',\t\t'I(:,3),''-'',''\\gamma''',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...\n 'iGloNorm',9,'iGC',12,...\n 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','One way Anova',...\n 'n',\t[Inf Inf 1 1],\t'sF',{{'repl','group','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''group''',...\n 'Bform',\t\t'[]',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...\n 'iGloNorm',9,'iGC',12,...\n 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','One way Anova (with constant)',...\n 'n',\t[Inf Inf 1 1],\t'sF',{{'repl','group','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''group''',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...\n 'iGloNorm',9,'iGC',12,...\n 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','One way Anova (Within-subjects)',...\n 'n',\t[1 Inf Inf 1],'sF',{{'repl','condition','subject',''}},...\n 'Hform',\t\t'I(:,2),''-'',''cond''',...\n 'Bform',\t\t'I(:,3),''-'',''subj''',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...\n 'iGloNorm',9,'iGC',12,...\n 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','Simple regression (correlation)',...\n 'n',\t[Inf 1 1 1],\t'sF',{{'repl','','',''}},...\n 'Hform',\t\t'[]',...\n 'Bform',\t\t'I(:,2),''-'',''\\mu''',...\n 'nC',[1,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...\n 'iGloNorm',9,'iGC',12,...\n 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n 'b',struct('aTime',0))];\n \n \n D = [D, struct(...\n 'DesName','Multiple regression',...\n 'n',\t[Inf 1 1 1],\t'sF',{{'repl','','',''}},...\n 'Hform',\t\t'[]',...\n 'Bform',\t\t'[]',...\n 'nC',[Inf,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...\n 'iGloNorm',9,'iGC',12,...\n 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','Multiple regression (with constant)',...\n 'n',\t[Inf 1 1 1],\t'sF',{{'repl','','',''}},...\n 'Hform',\t\t'[]',...\n 'Bform',\t\t'I(:,2),''-'',''\\mu''',...\n 'nC',[Inf,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...\n 'iGloNorm',9,'iGC',12,...\n 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','AnCova',...\n 'n',\t[Inf Inf 1 1],\t'sF',{{'repl','group','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''group''',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[0,1],'iCC',{{8,1}},'iCFI',{{1,1}},...\n 'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...\n 'iGloNorm',9,'iGC',12,...\n 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n 'b',struct('aTime',0))];\n \n varargout = {D};\n \n \ncase 'desdefs_pet'\n %===================================================================\n % - Standard (SPM99) PET/SPECT Design definitions...\n %===================================================================\n % D = spm_spm_ui('DesDefs_PET');\n % These are the standard PET design definitions...\n \n %-Single subject\n %-------------------------------------------------------------------\n D = struct(...\n 'DesName','Single-subject: conditions & covariates',...\n 'n',\t[Inf Inf 1 1],\t'sF',{{'repl','condition','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''cond''',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[Inf,Inf],'iCC',{{[-1,3,8],[-1,8]}},'iCFI',{{[1,3],1}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...\n 'iGloNorm',[1,8,9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',1));\n \n D = [D, struct(...\n 'DesName','Single-subject: covariates only',...\n 'n',\t[Inf 1 1 1],\t'sF',{{'repl','','',''}},...\n 'Hform',\t\t'[]',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[Inf,Inf],'iCC',{{[-1,8],[-1,8]}},'iCFI',{{1,1}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...\n 'iGloNorm',[1,8,9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',1))];\n \n %-Multi-subject\n %-------------------------------------------------------------------\n D = [D, struct(...\n 'DesName','Multi-subj: conditions & covariates',...\n 'n',[Inf Inf Inf 1],\t'sF',{{'repl','condition','subject',''}},...\n 'Hform',\t\t'I(:,2),''-'',''cond''',...\n 'Bform',\t\t'I(:,3),''-'',''subj''',...\n 'nC',[Inf,Inf],'iCC',{{[1,3,4,8],[1,4,8]}},'iCFI',{{[1,3,-4],[1,-4]}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-4,9],'GM',50,...\n 'iGloNorm',[4,8,9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',1))];\n \n D = [D, struct(...\n 'DesName','Multi-subj: cond x subj interaction & covariates',...\n 'n',[Inf Inf Inf 1],\t'sF',{{'repl','condition','subject',''}},...\n 'Hform',\t\t'I(:,[3,2]),''-'',{''subj'',''cond''}',...\n 'Bform',\t\t'I(:,3),''-'',''subj''',...\n 'nC',[Inf,Inf],'iCC',{{[1,3,4,8],[1,4,8]}},'iCFI',{{[1,3,-4],[1,-4]}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-4,9],'GM',50,...\n 'iGloNorm',[4,8,9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',1))];\n \n D = [D, struct(...\n 'DesName','Multi-subj: covariates only',...\n 'n',[Inf 1 Inf 1],\t'sF',{{'repl','','subject',''}},...\n 'Hform',\t\t'[]',...\n 'Bform',\t\t'I(:,3),''-'',''subj''',...\n 'nC',[Inf,Inf],'iCC',{{[1,4,8],[1,4,8]}},'iCFI',{{[1,-4],[1,-4]}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-4,9],'GM',50,...\n 'iGloNorm',[4,8:9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n %-Multi-group\n %-------------------------------------------------------------------\n D = [D, struct(...\n 'DesName','Multi-group: conditions & covariates',...\n 'n',[Inf Inf Inf Inf],\t'sF',{{'repl','condition','subject','group'}},...\n 'Hform',\t\t'I(:,[4,2]),''-'',{''stud'',''cond''}',...\n 'Bform',\t\t'I(:,[4,3]),''-'',{''stud'',''subj''}',...\n 'nC',[Inf,Inf],'iCC',{{[5:8],[5,7,8]}},'iCFI',{{[1,5,6,-7],[1,5,-7]}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-7,9],'GM',50,...\n 'iGloNorm',[7,8,9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',1))];\n \n D = [D, struct(...\n 'DesName','Multi-group: covariates only',...\n 'n',[Inf 1 Inf Inf],\t'sF',{{'repl','','subject','group'}},...\n 'Hform',\t\t'[]',...\n 'Bform',\t\t'I(:,[4,3]),''-'',{''stud'',''subj''}',...\n 'nC',[Inf,Inf],'iCC',{{[5,7,8],[5,7,8]}},'iCFI',{{[1,5,-7],[1,5,-7]}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-7,9],'GM',50,...\n 'iGloNorm',[7,8,9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n %-Population comparisons\n %-------------------------------------------------------------------\n D = [D, struct(...\n 'DesName',...\n 'Population main effect: 2 cond''s, 1 scan/cond (paired t-test)',...\n 'n',[1 2 Inf 1],\t'sF',{{'','condition','subject',''}},...\n 'Hform',\t\t'I(:,2),''-'',''cond''',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...\n 'iGloNorm',[8,9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName',...\n 'Dodgy population main effect: >2 cond''s, 1 scan/cond',...\n 'n',[1 Inf Inf 1],\t'sF',{{'','condition','subject',''}},...\n 'Hform',\t\t'I(:,2),''-'',''cond''',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...\n 'iGloNorm',[8,9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','Compare-populations: 1 scan/subject (two sample t-test)',...\n 'n',[Inf 2 1 1],\t'sF',{{'subject','group','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''group''',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...\n 'iGloNorm',[8,9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','Compare-populations: 1 scan/subject (AnCova)',...\n 'n',[Inf 2 1 1],\t'sF',{{'subject','group','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''group''',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[0,Inf],'iCC',{{8,1}},'iCFI',{{1,1}},...\n 'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...\n 'iGloNorm',[1,8,9],'iGC',10,...\n 'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n %-The Full Monty!\n %-------------------------------------------------------------------\n D = [D, struct(...\n 'DesName','The Full Monty...',...\n 'n',[Inf Inf Inf Inf],\t'sF',{{'repl','cond','subj','group'}},...\n 'Hform',\t\t'I(:,[4,2]),''-'',{''stud'',''cond''}',...\n 'Bform',\t\t'I(:,[4,3]),''-'',{''stud'',''subj''}',...\n 'nC',[Inf,Inf],'iCC',{{[1:8],[1:8]}},'iCFI',{{[1:7],[1:7]}},...\n 'iGXcalc',[1,2,3],'iGMsca',[1:7],'GM',50,...\n 'iGloNorm',[1:9],'iGC',[1:11],...\n 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...\n 'b',struct('aTime',1))];\n \n \n varargout = {D};\n \ncase 'desdefs_pet96'\n %===================================================================\n % - SPM96 PET/SPECT Design definitions...\n %===================================================================\n % D = spm_spm_ui('DesDefs_PET96');\n \n %-Single subject\n %-------------------------------------------------------------------\n D = struct(...\n 'DesName','SPM96:Single-subject: replicated conditions',...\n 'n',\t[Inf Inf 1 1],\t'sF',{{'repl','condition','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''cond''',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',3,'iGMsca',[1,9],'GM',50,...\n 'iGloNorm',[1,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0));\n \n D = [D, struct(...\n 'DesName','SPM96:Single-subject: replicated conditions & covariates',...\n 'n',\t[Inf Inf 1 1],\t'sF',{{'repl','condition','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''cond''',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{1,1}},...\n 'iGXcalc',3,'iGMsca',[1,9],'GM',50,...\n 'iGloNorm',[1,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','SPM96:Single-subject: covariates only',...\n 'n',\t[Inf 1 1 1],\t'sF',{{'repl','','',''}},...\n 'Hform',\t\t'[]',...\n 'Bform',\t\t'I(:,3),''-'',''\\mu''',...\n 'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{1,1}},...\n 'iGXcalc',3,'iGMsca',[1,9],'GM',50,...\n 'iGloNorm',[1,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n %-Multi-subject\n %-------------------------------------------------------------------\n D = [D, struct(...\n 'DesName','SPM96:Multi-subject: different conditions',...\n 'n',\t[1 Inf Inf 1],\t'sF',{{'','condition','subject',''}},...\n 'Hform',\t\t'I(:,2),''-'',''scancond''',...\n 'Bform',\t\t'I(:,3),''-'',''subj''',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',3,'iGMsca',[1,9],'GM',50,...\n 'iGloNorm',[1,4,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','SPM96:Multi-subject: replicated conditions',...\n 'n',[Inf Inf Inf 1],\t'sF',{{'repl','condition','subject',''}},...\n 'Hform',\t\t'I(:,2),''-'',''cond''',...\n 'Bform',\t\t'I(:,3),''-'',''subj''',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',3,'iGMsca',[1,9],'GM',50,...\n 'iGloNorm',[1,4,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','SPM96:Multi-subject: different conditions & covariates',...\n 'n',\t[1 Inf Inf 1],\t'sF',{{'','condition','subject',''}},...\n 'Hform',\t\t'I(:,2),''-'',''cond''',...\n 'Bform',\t\t'I(:,3),''-'',''subj''',...\n 'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,4],[1,4]}},...\n 'iGXcalc',3,'iGMsca',[1,9],'GM',50,...\n 'iGloNorm',[1,4,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','SPM96:Multi-subject: replicated conditions & covariates',...\n 'n',[Inf Inf Inf 1],\t'sF',{{'repl','condition','subject',''}},...\n 'Hform',\t\t'I(:,2),''-'',''condition''',...\n 'Bform',\t\t'I(:,3),''-'',''subj''',...\n 'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,3,4],[1,4]}},...\n 'iGXcalc',3,'iGMsca',[1,9],'GM',50,...\n 'iGloNorm',[1,4,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','SPM96:Multi-subject: covariates only',...\n 'n',[Inf 1 Inf 1],\t'sF',{{'repl','','subject',''}},...\n 'Hform',\t\t'[]',...\n 'Bform',\t\t'I(:,3),''-'',''subj''',...\n 'nC',[Inf,Inf],'iCC',{{[1,4,8],[1,4,8]}},'iCFI',{{[1,4],[1,4]}},...\n 'iGXcalc',3,'iGMsca',[1,9],'GM',50,...\n 'iGloNorm',[1,4,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n %-Multi-study\n %-------------------------------------------------------------------\n D = [D, struct(...\n 'DesName','SPM96:Multi-study: different conditions',...\n 'n',[1 Inf Inf Inf],\t'sF',{{'','cond','subj','study'}},...\n 'Hform',\t\t'I(:,[4,2]),''-'',{''study'',''cond''}',...\n 'Bform',\t\t'I(:,[4,3]),''-'',{''study'',''subj''}',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...\n 'iGloNorm',[1,5,7,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','SPM96:Multi-study: replicated conditions',...\n 'n',[Inf Inf Inf Inf],\t'sF',{{'repl','cond','subj','study'}},...\n 'Hform',\t\t'I(:,[4,2]),''-'',{''study'',''condition''}',...\n 'Bform',\t\t'I(:,[4,3]),''-'',{''study'',''subj''}',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...\n 'iGloNorm',[1,5,7,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','SPM96:Multi-study: different conditions & covariates',...\n 'n',[1 Inf Inf Inf],\t'sF',{{'','cond','subj','study'}},...\n 'Hform',\t\t'I(:,[4,2]),''-'',{''study'',''cond''}',...\n 'Bform',\t\t'I(:,[4,3]),''-'',{''study'',''subj''}',...\n 'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,5,6,7],[1,5,7]}},...\n 'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...\n 'iGloNorm',[1,5,7,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','SPM96:Multi-study: replicated conditions & covariates',...\n 'n',[Inf Inf Inf Inf],\t'sF',{{'','cond','subj','study'}},...\n 'Hform',\t\t'I(:,[4,2]),''-'',{''study'',''condition''}',...\n 'Bform',\t\t'I(:,[4,3]),''-'',{''study'',''subj''}',...\n 'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,5,6,7],[1,5,7]}},...\n 'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...\n 'iGloNorm',[1,5,7,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n D = [D, struct(...\n 'DesName','SPM96:Multi-study: covariates only',...\n 'n',[Inf 1 Inf Inf],\t'sF',{{'repl','','subj','study'}},...\n 'Hform',\t\t'[]',...\n 'Bform',\t\t'I(:,[4,3]),''-'',{''study'',''subj''}',...\n 'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,5,7],[1,5,7]}},...\n 'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...\n 'iGloNorm',[1,5,7,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n %-Group comparisons\n %-------------------------------------------------------------------\n D = [D, struct(...\n 'DesName','SPM96:Compare-groups: 1 scan per subject',...\n 'n',[Inf Inf 1 1],\t'sF',{{'subject','group','',''}},...\n 'Hform',\t\t'I(:,2),''-'',''group''',...\n 'Bform',\t\t'[]',...\n 'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...\n 'iGXcalc',3,'iGMsca',[1,9],'GM',50,...\n 'iGloNorm',[1,8,9],'iGC',10,...\n 'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...\n 'b',struct('aTime',0))];\n \n varargout = {D};\n \n \notherwise\n %===================================================================\n % - U N K N O W N A C T I O N\n %===================================================================\n warning(['Illegal Action string: ',Action])\n \n %===================================================================\n % - E N D\n %===================================================================\nend\n\n%=======================================================================\n%- S U B - F U N C T I O N S\n%=======================================================================\n\nfunction str = sf_estrrep(str,srstr)\n%=======================================================================\nfor i = 1:size(srstr,1)\n str = strrep(str,srstr{i,1},srstr{i,2});\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_model.m", "ext": ".m", "path": "spm5-master/spm_eeg_inv_model.m", "size": 61788, "source_encoding": "utf_8", "md5": "f4208f6ed03ec4d5192751a4d7c2b53f", "text": "function varargout = spm_eeg_inv_model(action,varargin)\n\n% spm_eeg_inv_model is a multi-purpose routine that deals with the generation\n% of the head model for the solution of the forward problem.\n%\n% Called without arguments :\n%\n% >> model = spm_eeg_inv_model\n% \n% the function calls GUI to select the operation(s) to be performed and\n% to enter/select the required inputs.\n% Here are the main options:\n% - Generate scalp/brain vol & tessalate\n% - Tessalate predefined binarized volume\n% - Project electrodes coord (sphere or real) on scalp/brain surface\n% - Define realistic sphere model\n% - The 4 steps at once\n%\n% A 'model' structure is returned. Depending on the operation executed,\n% the model will contain: surface meshes, electrodes information,\n% realistic sphere model.\n% \n% Most subfunctions can be called individually. Some even have their own\n% little GUI because I used to use them on their own...\n%\n% The various structure formats (model, head, electrodes) are described \n% at the end of this help.\n%\n%__________________________________________________________________________\n% FORMAT [Pvol,Pinv_sn,flags] = spm_eeg_inv_model('GenBin',Pvol,flag_bi);\n%\n% Generate the binarised image of the brain (and scalp if the image allows).\n% \n% Input :\n% Pvol : filename of the image used to build the head model.\n% flag_bi : useful flags\n% * img_type: image type 1=T1 MRI, 2 = PET, 3 = EPI\n% * img_norm: flag indicating if the image is normalised (1) or not (0)\n% * ne,ng : # iteration for erosion and growing\n% * thr_im : threhold applied to binarise image\n% NOTE: these flags are not always necessary anymore...\n% Output :\n% Pvol : file name of the bin images gnerated, scalp and iskull\n% Pinv_sn : file name of mat file containing inverse of the normalisation\n% transform.\n% flags : all the flags with added file names for original image, brain\n% mask and spatial transformation\n%__________________________________________________________________________\n%\n% FORMAT [head,flags] = spm_eeg_inv_model('GenMesh',Pvol,flags);\n%\n% Generate the tesselated surface of the 1 to 3 head volumes\n% (brain-skull-scalp) from the binarized volumes.\n% Input :\n% Pvol : filenames of 3 head volumes 'brain', 'skull' & 'scalp'.\n% flags : various flags\n% * n : (1x3) provides the number of vertices on each surface\n% Npt = n(i)^2*5/4+2\n% * br_only : only use the binarised brain volume (1) or scalp (0, default)\n% * q_elastm: Correct mesh using an elastic model (1, default), or not (0).\n% * q_meased: Measure edges of mesh (1), or not (0, default)\n% * q_4thpt : Determine 4th point central of each traingle (1), or not (0, default)\n% Output :\n% head : head structures with 1 to 3 tesselated surfaces\n% flags : all the flags used\n%__________________________________________________________________________\n%\n% FORMAT [electrodes,flags] = spm_eeg_inv_model('Elec2Scalp',surf,el_loc,el_name,flags);\n%\n% Projecting the electrodes (in spherical or realistic coordinates) \n% on the realistic head model.\n% \n% Input :\n% - surf : surface on which the electrodes are projected, \n% if it's the brain surface, then the scalp-brain width is added\n% - el_loc : provided electrode coordinates, on a standard sphere or\n% real coordinates as measured estimated on the patient's head.\n% - el_name : electrode names.\n% - flags : various option flags and extra bits of information\n% * q_RealLoc : 'el_loc' contains coordinates on a standard sphere (0),\n% or as measured on the patient's head (1)\n% * q_RealNI : nasion/inion coordinates are from the template (0),\n% or as estimated on the patient's image\n% * br_only : only the brain surface is available (1),\n% or the scalp surface can be used (0)\n% * nasion : coordiantes (in mm), on the template (defaults value filled\n% * inion : in if left empty) or as estimated on the patient's image\n% * scbr_w : scalp-brain surface width, in mm. (Default 20)\n% * Mtempl : Affine transform mapping from the patient image space\n% into the template space\n% Output :\n% electrodes : electrode structure\n% flags : all the flags used\n%\n% When dealing with standard electrode locations on a sphere, one uses \n% the coordinates of the nasion and inion to estimate the pitch angle, then\n% the electrode locations are mapped into the patient space\n% When the real (approximate) electrode locations is provided, these are \n% simply adjusted on the scalp surface\n% If the model is 'brain only' (from a PET or EPI scan), the approximate \n% brain-scalp width is required.\n%\n% The electrodes substructure is created at the end.\n%__________________________________________________________________________\n%\n% FORMAT [pt_mm] = spm_eeg_inv_model('vx2mm',pt_vx,M);\n%\n% Transforms point(s) 'pt_vx' voxel coordinates into mm coordinates 'pt_mm'\n% according to the transformation matrix 'M'.\n% 'M' is the 4x4 affine transformation matrix : from vx to mm\n%__________________________________________________________________________\n%\n% FORMAT [pt_vx] = spm_eeg_inv_model('mm2vx',pt_mm,M);\n%\n% Transforms point(s) 'pt_mm' mm coordinates into voxel coordinates 'pt_vx'\n% according to the transformation matrix 'M'.\n% 'M' is the 4x4 affine transformation matrix : from vx to mm\n%__________________________________________________________________________\n%\n% FORMAT [Centre,c_mm] = spm_eeg_inv_model('CtrBin',P);\n%\n% Determine the \"centre of mass\" (vx and mm) of a bin image.\n%__________________________________________________________________________\n%\n% FORMAT [vn,vn_i,S,S_i] = spm_eeg_inv_model('NormTri',l_tr,ts)\n%\n% Calcultates the normal and surface of a triangle on a tesselated surface.\n% If a list of triangle is provided, then the \"mean\" normal and the normals are calculated.\n% Input :\n% l_tr = index of triangle\n% ts = tesselated surface\n% Output:\n% vn = (mean) normalised normal vector\n% vn_i = individual normal vectors\n% S = (mean) surface\n% S_i = individual surfaces\n%__________________________________________________________________________\n%\n% FORMAT ts = spm_eeg_inv_model('TesBin',n,Centre,P,info);\n%\n% Generate a mesh covering a binarized volume\n% 1. Generate a simple spherical mesh\n% 2. The spherical mesh is projected radially on the bin volume\n% Afterwards, \"elastic\" mesh correction can thus be useful to correct \n% some overlong edges.\n%\n% Input : \n% n: number of vertices on each surface Npt = n^2*5/4+2\n% Centre: centre of bin volume for the radial projection\n% P: filename of bin volume\n% info: information string\n%__________________________________________________________________________\n%\n% FORMAT ts = spm_eeg_inv_model('ElastM',ts);\n%\n% Modify the the mesh in order to reduce overlong edges.\n% The procedure uses an elastic model :\n% At each vertex, the neighbouring triangles and vertices connected directly\n% are considered.\n% Each edge is considered elastic and can be lengthened or shortened,\n% depending on their legnth.\n% Algorithm: G.Taubin, A signal processing approach to fair surface design, 1995\n% This is a non-shrinking smoothing algo.\n%\n% Input : \n% ts: tesselated surface\n% Output :\n% ts: tesselated surface with corrected mesh\n%__________________________________________________________________________\n%\n% FORMAT ts = spm_eeg_inv_model('MeasEd',ts);\n%\n% This measures the edges of the mesh.\n% Input : ts\n% Output : ts with measured edges\n%__________________________________________________________________________\n%\n% FORMAT ts = spm_eeg_inv_model('Tr4thPt',ts);\n%\n% Finds the 4th' point of each triangle:\n% a flat triangle is only an approximation of the real underlying volume surface, \n% a 4th point taken at the centre of the triangle is found by approximating\n% the neighbouring triangles in a sphere, to provide an idea of the local curvature.\n% This is used in the BEM solution of the forward problem, to sort out \n% the problem of the auto-solid angle.\n%\n% Input : \n% ts: tesselated surface\n% Output :\n% ts: tesselated surface with 4th point at each triangle\n%__________________________________________________________________________\n%\n% FORMAT tsph = spm_eeg_inv_model('TesSph',n,r);\n%\n% Generate a structure 'tsph' containing a tesselated sphere.\n% Input : \n% n : number of 'latitude' divisions on the sphere. It MUST be even!\n% r : radius of the sphere\n% Output : \n% tsph .vert : vertices coordinates (3 x Nvert)\n%\t\t .tri : triangle patches (3 x Ntri)\n%\t\t .info : info string\n%__________________________________________________________________________\n%\n% FORMAT [Pout/val] = spm_eeg_inv_model('ErodeGrow',P/val,ne,ng,thr_im)\n% \n% It erodes then grows an image after thresholding it.\n% Inputs : P/val,ne,ng,thr_im\n% P : file name of image to erode/grow\n% val : full volume of image (as loaded by spm_read_vols)\n% ne : nr of steps for erosion, default 3\n% ng : nr of steps for growing, default 6\n% thr_im : threshold value to apply, default .8\n% (compared to the maximal value of image)\n% Output : Pout/val\n% Pout : name of the file generated\n% val : full value of eroded-grown image\n% \n% Notes:\n% - if 2 file names are specified in P[input], the 2nd one is used as the name\n% of the generated file otherwise the new filename is creted from P as\n% [P,'_e',num2str(ne),'g',num2str(ng),'.img']\n% - If a file name is passed the output is a filename.\n% If a matrix of values is passed, the output is a matrix of values.\n%\n% IMPORTATNT !!!\n% - It uses brutal force as it loads the whole image into memory !!!\n% things are eased up by usint unsigned integers.\n% - voxels are supposed to be isotropic in size...\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Christophe Phillips,\n% $Id: spm_eeg_inv_model.m 1039 2007-12-21 20:20:38Z karl $\n\n% Format of 'model' structure :\n% #############################\n%\n% model.\n%\thead\t\t: structure of head surfaces (1x3)\n%\telectrodes\t: structure for electrodes\n% Mtempl : affine transformation from the patient into the template space\n%\tsigma\t\t: conductivity values (1x3)\n%\t(IFS\t\t: cells containing Intermediate Forward Solution (1x3),\n%\t\t\t these do NOT depend on the dipoles grid.)\n% Only used for the BEM solution !\n%\n% 'head' sub-structure format\n% ===========================\n% .head(i)\t\t: i=1,2,3 for brain, skull & scalp surfaces\n%\tXYZmm\t\t: coordinates of vertices (3xNv)\n%\ttri\t\t: indices of vertices in triangles (3xNt)\n%\tM\t\t: voxel-to-mm space transformation matrix\n%\tnr\t\t: [nr_of_vertices (Nv) & nr_of_triangles (Nt)]\n%\tpt4.XYZvx\t: coord of projected triangle centre (3xNt)\n%\tedges.\t\t: triangles edges information structure\n%\t\ted\t: edges length, vertices indices and triangles indices\n%\t\tnr\t: [nr_edges mean_length std_length]\n%\tinfo\t\t: informations\n%\n%\n%\tFormat of .edges :\n%\t------------------\n%\t.edges.ed :\t\t\t\t\t\n% \t\ted(:,1) = length,\n%\t\ted(:,[2 3]) = indices of 2 vertices, e.g ind. of a and c\t\n%\t\ted(:,[4 5]) = indices of 2 triangles, e.g ind. of I and II\n%\n%\t\t length\t a x------x b\n%\t\t _______\t /\\ I /\n%\t\t' `\t / o /\n%\t\tx---o---x\t / II \\ /\n%\t\t\t\t d x------x c\n%\n%\t.edges.nr :\n%\t\tnr(1) : number of edges,\n%\t\tnr([2 3]) : mean and std of edges length.\n%\n% 'electrodes' sub-structure format\n% =================================\n% .electrodes.\t\t: structure for electrodes\n%\tvert\t: index of the closest vertex (Nel x 1)\n%\ttri\t\t: index of the triangle beneath each electrode\n%\tnr\t\t: nr of electrodes\n%\tXYZmm\t: coord. of electrodes on the scalp (in voxel)\n%\tM\t\t: voxel-to-mm space transformation matrix\n%\tCnames\t: electrodes names\n%\tinfo\t:\n% nasion :\n% inion :\n\nspm('FigName','Realistic head model');\n\nif nargin == 0, action = 'Init'; end;\n\nswitch lower(action),\n\n%________________________________________________________________________\ncase 'init'\n%------------------------------------------------------------------------\n% Use a GUI.\n%------------------------------------------------------------------------\n\tpos = 1 ;\n\n % Select the operation through the GUI or from passed variable\n if nargin==2 && isnumeric(varargin{1})\n gener = round(varargin{1});\n if gener<1 || gener>5\n gener = 5;\n warning('Wrong options for model, I assume \"generate all at once\"');\n end\n else\n\t\ttext_opt = [...\n 'Generate scalp/brain vol & tessalate|',...\n 'Tessalate predefined binarized volume|',...\n\t\t\t'Project electrodes coord (spher or real) on scalp/brain surface|',...\n\t\t\t'Define realistic sphere model|',...\n 'The 4 steps at once'];\n\t\tgener = spm_input('Generate what ?',pos,'m',text_opt);\n end\n\n % Load required inputs\n %======================\n if gener==1 || gener==5\n % Generate scalp/brain vol & tessalate\n Pvol = spm_select(1,'image','Image to build model');\n% flag_bi.img_type = spm_input('Image type :','+1','T1 MRI|PET|EPI',[1,2,3],1);\n flag_bi.img_type = 1; % Assume it's always a structural MR image.\n% flag_bi.img_norm = spm_input('Image normalised already :','+1','y/n',[1,0],2);\n flag_bi.img_norm = 0; % Assume it is not normalised yet.\n if flag_bi.img_type==1\n flag_te.br_only=0;\n flag_te.Nvol = 2;\n else\n flag_te.br_only=1;\n flag_te.Nvol = 1;\n end\n end\n \n if gener==2\n % Tessalate predefined binarized volume only.\n\t\tPvol = spm_select(Inf,'*_o*.img','1-2-3 bin images to tessalate (br-sk-sc)');\n flag_te.Nvol = size(Pvol,1);\n if flag_te.Nvol==1\n flag_te.br_only = spm_input('Is this the brain bin volume ?','+1','y/n',[1,0],0);\n else\n flag_te.br_only=0;\n end\n if ~isempty(PMtempl)\n load(PMtempl)\n else\n warning('It is assumed that the bin volumes are in the template space !')\n Mtempl = eye(4);\n end\n end\n if gener==1 || gener==2 || gener==5\n % Generate scalp/brain vol & tessalate binarized volume\n if flag_te.Nvol>1 || flag_te.br_only\n% \t\tNpt = spm_input('Approx. nr of vertices on brain surf','+1','e',4000);\n \t\tNpt = 4000; % 4000 seems a \"good\" number for the inner skull surface\n flag_te.n = zeros(1,3); flag_te.n(1) = 2*round((sqrt((Npt-2)*4/5))/2);\n end\n if ~flag_te.br_only \n% \t\tNpt = spm_input('Approx. nr of vertices on sk/sc surf','+1','e',2000);\n \t\tNpt = 4000; % Use also about 4000 vertices for the scalp surface\n if flag_te.Nvol>1 \n flag_te.n(2:3) = 2*round((sqrt((Npt-2)*4/5))/2);\n else\n flag_te.n = 2*round((sqrt((Npt-2)*4/5))/2);\n end\n end\n% flag_te.q_elast_m = spm_input('Correct the projected mesh ?','+1','y/n',[1,0],1) ;\n flag_te.q_elast_m = 1 ; % of course do the \"surface smoothing\".\n [pth,fn,ext,nr] = spm_fileparts(Pvol);\n Pmod = fullfile(pth,['model_head_',fn,'.mat']);\n\tend\n\n\tif gener==3 || gener==5\n % Project electrodes coord (spher or real) on scalp/brain surface\n if gener==3\n Pmod = spm_select(1,'^model.*\\.mat$','Head model file');\n load(Pmod)\n end\n if exist('flag_te') && isfield(flag_te,'br_only')\n flags_el.br_only = flag_te.br_only;\n elseif exist('model') && isfield(model.param,'br_only');\n flags_el.br_only = model.param.br_only;\n else\n if length(model.head)>1\n flags_el.br_only = 0;\n else\n flags_el.br_only = spm_input('Only one surface modeled :','+1',...\n 'scalp|brain',[0,1],1);\n if flags_el.br_only\n flags_el.scbr_w = spm_input('Scalp-brain width :','+1','e',20);\n end\n end\n model.br_only = flags_el.br_only;\n end\n if exist('Mtempl')\n flags_el.Mtempl = Mtempl;\n elseif exist('model') && isfield(model.param,'Mtempl');\n flags_el.Mtempl = model.param.Mtempl;\n else\n warning('It is assumed that your original image was in template space.')\n end\n\n q_StdElec = spm_input('Electrode set :','+1','standard|user defined',[1,0],1);\n if q_StdElec\n % Select standard electrode set, as defined in 'spm_eeg_inv_electrset'\n [set_Nel,set_name] = spm_eeg_inv_electrset;\n\t\t\tel_set = spm_input('Which set of electrodes', ...\n\t\t\t\t\t'+1','m',set_name);\n \t\t[el_sphc,el_name] = spm_eeg_inv_electrset(el_set) ;\n flags_el.q_RealLoc = 0;\n else\n % Enter user defined electrode set.\n el_sphc = spm_input('All electrode coordinates','+1','e')\n el_name = spm_input('Electrod names (cell array)','+1','e')\n flags_el.q_RealLoc = spm_input('Electrode set :','+1', ...\n 'real location|on a sphere',[1,0],1);\n flags_el.q_RealNI = spm_input('Do you have the nasion/inion location',...\n '+1','y/n',[1,0],2);\n if flags_el.q_RealNI\n flags_el.nasion = spm_input('Nasion coordinates (in mm)','+1','e',[],3);\n flags_el.inion = spm_input('Inion coordinates (in mm)','+1','e',[],3);\n end\n end\n\tend\n\n if gener==4\n % Define realistic sphere\n Pmod = spm_select(1,'^model.*\\.mat$','Head model file');\n end\n\n\n % Create things as selected\n %==========================\n if gener == 1 || gener == 5\n % Segment image, and create brain volume\n [Pbin,Pinv_sn,flags_bi] = spm_eeg_inv_model('GenBin',Pvol,flag_bi);\n if gener == 1 \n varargout{1} = Pbin;\n varargout{2} = Pinv_sn;\n varargout{3} = flags_bi;\n end\n end\n \n if gener==1 || gener==2 || gener==5\n % Tessalate predefined binarized volume\n [head,cc,flags_te] = spm_eeg_inv_model('GenMesh',Pbin,flag_te); % n,br_only,q_elast_m\n model.head = head;\n if exist('flags_bi'), model.flags.fl_bin = flags_bi; end\n model.flags.fl_tess = flags_te;\n model.param = struct('br_only',0,'Nvol',1,'Mtempl',[], ...\n 'Pinv_sn','','sigma',[.33 .004 .33]);\n if exist('Mtempl'), model.param.Mtempl = Mtempl; end\n if isfield(flag_te,'br_only'), model.param.br_only = flag_te.br_only; end\n if isfield(flag_te,'Nvol'), model.param.Nvol = flag_te.Nvol; end\n model.fname = Pmod;\n save(Pmod,'model')\n if gener==2 || gener==5\n varargout{1} = model ;\n elseif gener==1\n varargout{4} = model ;\n end\n end\n \n if gener==3 || gener==5\n % Project electrodes coord (spher or real) on scalp/brain surface\n\t\tfname_el = ['el_sphc',num2str(size(el_sphc,2))];\n\t\tsave(fname_el,'el_sphc','el_name');\n [electrodes,flags_el] = spm_eeg_inv_model('Elec2Scalp',model.head(end), ...\n el_sphc,el_name,flags_el);\n model.electrodes = electrodes ;\n model.flags.fl_elec = flags_el ;\n\t\tPmod_s = [spm_str_manip(Pmod,'s'),'_e', ...\n\t\t\t\tnum2str(model.electrodes.nr),'.mat'] ;\n\t\tsave(Pmod_s,'model')\n varargout{1} = model ; \n end\n \n if gener==4 || gener==5\n % Define realistic sphere model\n if gener==4, load(Pmod); end\n if isfield(model,'br_only')\n flags_Rs.br_only = model.flags.fl_tess.br_only;\n else\n flags_Rs.br_only = 0;\n end\n [spheres,a,b,c,flags_Rs] = spm_eeg_inv_Rsph(model,[],flags_Rs);\n model.spheres = spheres;\n model.flags.fl_RealS = flags_Rs;\n\t\tPmod_Rs = [spm_str_manip(Pmod,'s'),'_Rs.mat'] ;\n\t\tsave(Pmod_Rs,'model')\n varargout{1} = model ; \n end\n\n\n%________________________________________________________________________\ncase 'genbin'\n%------------------------------------------------------------------------\n% FORMAT [Pbin,Pinv_sn,flags] = spm_eeg_inv_model('GenBin',Pvol,flag_bi);\n%\n% Generate the binarised image of the brain (and scalp if the image allows).\n% \n% Input :\n% Pvol : filename of the image used to build the head model.\n% flag_bi : useful flags\n% * img_type: image type 1=T1 MRI, 2 = PET, 3 = EPI\n% * img_norm: flag indicating if the image is normalised (1) or not (0)\n% * ne,ng : # iteration for erosion and growing\n% * thr_im : threhold applied to binarise image\n% NOTE: these flags are not always necessary anymore...\n% Output :\n% Pbin : file name of the bin images generated, scalp and iskull\n% Pinv_sn : file name of mat file containing inverse of the normalisation\n% transform.\n% flags : all the flags with added file names for original image, brain\n% mask and spatial transformation\n%------------------------------------------------------------------------\n fprintf('\\n\\n'), fprintf('%c','='*ones(1,80)), fprintf('\\n')\n fprintf(['\\tGenerating binarized volumes from image: Please wait.\\n']);\n Pvol = varargin{1} ;\n def_flags = struct('img_type',1,'img_norm',0,'ne',1,'ng',2,'thr_im',[.5 .1]);\n if nargin<3\n flags = def_flags;\n else\n flags = varargin{2};\n fnms = fieldnames(def_flags);\n\t\tfor i=1:length(fnms),\n\t\t\tif ~isfield(flags,fnms{i}),\n flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));\n end\n\t\tend\n end\n \n load('defaults_eeg_mesh.mat');\n\n% 1.Segment image, and estimate the mapping between template and image space.\n jobs{1}.spatial{1}.preproc.data = Pvol;\n jobs{1}.spatial{1}.preproc.output.biascor = 1;\n jobs{1}.spatial{1}.preproc.output.GM = [0 0 1];\n jobs{1}.spatial{1}.preproc.output.WM = [0 0 1];\n jobs{1}.spatial{1}.preproc.output.CSF = [0 0 1];\n jobs{1}.spatial{1}.preproc.output.cleanup = 0;\n\n res = spm_preproc(Pvol);\n [sn,isn] = spm_prep2sn(res);\n [pth,nam,ext] = spm_fileparts(Pvol);\n Pinv_isn = fullfile(pth,[nam '_vbm_inv_sn.mat']);\n Pinv_sn = fullfile(pth,[nam '_vbm_sn.mat']);\n savefields(Pinv_isn,isn);\n savefields(Pinv_sn,sn);\n spm_preproc_write(sn,jobs{1}.spatial{1}.preproc.output);\n % write the segmented images in native space + bias corrected MRI\n\n% 2.Adds up GM/WM/CSF to produce inner skull surface\n Pin = strvcat(fullfile(pth,['c1',nam,ext]), ...\n fullfile(pth,['c2',nam,ext]), ...\n fullfile(pth,['c3',nam,ext]));\n Pisk = fullfile(pth,[nam,'_iskull',ext]);\n fl_ic = {[],[],'uint8',[]};\n Pisk = spm_imcalc_ui(Pin,Pisk,'i1+i2+i3',fl_ic);\n \n% 3.Use a little bit of erosion/growing to refine the model\n% and write the *_iskull img on disk\n Parg = strvcat(Pisk,Pisk);\n ne = flags.ne(1); ng = flags.ng(1); thr_im = flags.thr_im(1);\n\t[Pout] = spm_eeg_inv_model('ErodeGrow',Parg,ne,ng,thr_im);\n\n if flags.img_type==1\n% 4.Generate the outer-scalp volume, if possible\n Pvolc = fullfile(pth,['m',nam,ext]);\n\t\tVsc = spm_vol(Pvolc);\n\t\tVsc.dat = spm_loaduint8(Vsc);\n% [mnv,mxv] = spm_minmax(Vsc.dat)\n\t\tne = flags.ne(end); ng = flags.ng(end); thr_im = flags.thr_im(end);\n\t\tVsc.dat = spm_eeg_inv_model('ErodeGrow',Vsc.dat,ne,ng,thr_im);\n\t\t\n % The bottom part of the image needs to be masked out, in MNI space.\n% \t\tp1 = [0 85 -50]'; % point below on the nose\n% \t\tp2 = [0 -55 -70]'; % point below the bottom of cerebellum (mm)\n\t\tp1 = [0 110 -105]'; % point below on the nose\n\t\tp2 = [0 -55 -110]'; % point below the bottom of cerebellum (mm)\n\t\tc = [p2(1:2)' ((p1(2)-p2(2))^2+p1(3)^2-p2(3)^2)/(2*(-p2(3)+p1(3)))];\n\t\tR2 = (p2(3)-c(3))^2;\n\t\t% center and radius of sphere to chop off bottom of the head\n\t\t\n\t\tX = (1:Vsc.dim(1))'*ones(1,Vsc.dim(2)); X =X(:)';\n\t\tY = ones(Vsc.dim(1),1)*(1:Vsc.dim(2)); Y = Y(:)';\n\t\tZ = zeros(Vsc.dim(1),Vsc.dim(2)); Z = Z(:)'; \n\t\tUnit = ones(size(Z));\n\t\t% X,Y,X coordinates in vox in original image\n isn_tmp = isn; isn_tmp.Tr = []; % using the simple affine transform should be enough\n\n for pp = 1:Vsc.dim(3)\n XYZ = Vsc.mat*[X ; Y ; Z+pp ; Unit]; % coord in mm of voxels of scalp img\n XYZ = spm_get_orig_coord(XYZ(1:3,:)', isn_tmp)'; \n lz = find(((XYZ(1,:)-c(1)).^2+(XYZ(2,:)-c(2)).^2+(XYZ(3,:)-c(3)).^2-R2)>0);\n val_pp = Vsc.dat(:,:,pp);\n val_pp(lz) = 0;\n Vsc.dat(:,:,pp) = val_pp;\n\t\tend\n\t\t\n % Write the file\n Vsc.fname = fullfile(pth,[nam,'_scalp',ext]);\n Vsc.dt = [2 0];\n Vsc.pinfo = [1/255 0 0]';\n\t\tVsc = spm_create_vol(Vsc);\n\t\tspm_progress_bar('Init',Vsc.dim(3),'Writing Outer-scalp','planes completed');\n\t\tfor pp=1:Vsc.dim(3),\n\t\t\tVsc = spm_write_plane(Vsc,double(Vsc.dat(:,:,pp)),pp);\n % No need to divide by 255 as output from Erode grow is [0 1].\n\t\t\tspm_progress_bar('Set',pp);\n\t\tend;\n\t\tspm_progress_bar('Clear');\n varargout{1} = strvcat(Pisk,Vsc.fname);\n end\n Pinv_sn = strvcat(Pinv_isn,Pinv_sn);\n varargout{2} = Pinv_sn;\n flags.Pinv_sn = Pinv_sn;\n flags.Pimg = Pvol;\n flags.Pisk = Pisk\n varargout{3} = flags;\n \n%________________________________________________________________________\ncase 'vx2mm'\n%------------------------------------------------------------------------\n% FORMAT [pt_mm] = spm_eeg_inv_model('vx2mm',pt_vx,M);\n% Transforms point(s) 'pt_vx' voxel coordinates into mm coordinates 'pt_mm'\n% according to the transformation matrix 'M'.\n% 'M' is the 4x4 affine transformation matrix : from vx to mm\n%------------------------------------------------------------------------\n\tpt_vx = varargin{1} ;\n\tM = varargin{2} ;\n\t\n\tif size(pt_vx,1)==3\n Npt = size(pt_vx,2);\n\telseif size(pt_vx,2)==3;\n pt_vx = pt_vx';\n Npt = size(pt_vx,2);\n\telse\n error('Wrong vectors format !')\n\tend\n\t\n\tpt_mm = M*[pt_vx;ones(1,Npt)];\n\tvarargout{1} = pt_mm(1:3,:);\n%________________________________________________________________________\ncase 'mm2vx'\n%------------------------------------------------------------------------\n% FORMAT [pt_vx] = spm_eeg_inv_model('mm2vx',pt_mm,M);\n% Transforms point(s) 'pt_mm' mm coordinates into voxel coordinates 'pt_vx'\n% according to the transformation matrix 'M'.\n% 'M' is the 4x4 affine transformation matrix : from vx to mm\n%------------------------------------------------------------------------\n\tpt_mm = varargin{1} ;\n\tM = varargin{2} ;\n\t\n\tif size(pt_mm,1)==3\n Npt = size(pt_mm,2);\n\telseif size(pt_mm,2)==3;\n pt_mm = pt_mm';\n Npt = size(pt_mm,2);\n\telse\n error('Wrong vectors format !')\n\tend\n\t\n\tpt_vx = M\\[pt_mm;ones(1,Npt)];\n\tvarargout{1} = pt_vx(1:3,:);\n%________________________________________________________________________\ncase 'ctrbin'\n%------------------------------------------------------------------------\n% FORMAT [Centre,c_mm]=spm_eeg_inv_model('CtrBin',P);\n% Determine the \"centre of mass\" (vx and mm) of a bin image.\n%------------------------------------------------------------------------\n\tif nargin<2\n\t\tP = spm_select(1,'o*.img','Bin image to use');\n else\n P = varargin{1};\n\tend\n\tVp = spm_vol(P) ;\n\n\tVp.dat = spm_loaduint8(Vp);\n\tX = (1:Vp.dim(1))'*ones(1,Vp.dim(2)); X =X(:)';\n\tY = ones(Vp.dim(1),1)*(1:Vp.dim(2)); Y = Y(:)';\n\tZ = zeros(Vp.dim(1),Vp.dim(2)); Z = Z(:)'; \n\tUnit = ones(size(Z));\n\t\n\tc_mm = zeros(1,3); SI = 0;\n\tfor pp=1:Vp.dim(3)\n I_pl = double(Vp.dat(:,:,pp)); I_pl = I_pl(:)*ones(1,3);\n XYZ = Vp.mat*[X ; Y ; Z+pp ; Unit];\n c_mm = c_mm + sum(XYZ(1:3,:)'.*I_pl);\n SI = SI+sum(I_pl(:,1));\n\tend\n\tc_mm = c_mm/SI;\n Centre = spm_eeg_inv_model('mm2vx',c_mm,Vp.mat)';\n varargout{1} = Centre;\n varargout{2} = c_mm;\n \n%________________________________________________________________________\ncase 'elec2scalp'\n%------------------------------------------------------------------------\n% FORMAT [electrodes,flags] = spm_eeg_inv_model('Elec2Scalp',surf,el_loc,el_name,flags);\n%\n% Projecting the electrodes (in spherical or realistic coordinates) \n% on the realistic head model.\n% \n% IN :\n% - surf : surface on which the electrodes are projected, \n% if its the brain surface, then the scalp-brain width is added\n% - el_loc : provided electrode coordinates, on a standard sphere or\n% real coordinates as measured estimated on the patient's head.\n% - el_name : electrode names.\n% - flags : various option flags and extra bits of information\n% * q_RealLoc : 'el_loc' contains coordinates on a standard sphere (0),\n% or as measured on the patient's head (1)\n% * q_RealNI : nasion/inion coordinates are from the template (0),\n% or as estimated on the patient's image\n% * br_only : only the brain surface is available (1),\n% or the scalp surface can be used (0)\n% * nasion : coordiantes (in mm), on the template (defaults value filled\n% * inion : in if left empty) or as estimated on the patient's image\n% * scbr_w : scalp-brain surface width, in mm. (Default 20)\n% * Mtempl : Affine transform mapping from the patient image space\n% into the template space\n%\n% When dealing with standard electrode locations on a sphere, one uses \n% the coordinates of the nasion and inion to estimate the pitch angle, then\n% the electrode locations are mapped into the patient space\n% When the real (approximate) electrode locations is provided, these are \n% simply adjusted on the scalp surface\n% If the model is 'brain only' (from a PET or EPI scan), the approximate \n% brain-scalp width is required.\n%\n% The electrodes substructure is created at the end.\n%------------------------------------------------------------------------\n\tfprintf('\\n'), fprintf('%c','='*ones(1,80)), fprintf('\\n')\n fprintf(['Placing electrodes on the scalp surface.\\n']);\n fprintf('%c','='*ones(1,80)), fprintf('\\n')\n surf = varargin{1};\n\tel_loc = varargin{2};\n\tNel = size(el_loc,2);\n if nargin<4\n [set_Nel,set_name] = spm_eeg_inv_electrset;\n try \n [kk,el_name] = spm_eeg_inv_electrset(find(set_Nel==Nel));\n catch\n el_name = [];\n end\n else\n el_name = varargin{3};\n end\n\n def_flags = struct('q_RealLoc',1,'br_only',0,'nasion',[0 84 -28],'inion',[0 -118 -26], ...\n 'q_RealNI',0,'scbr_w',[16],'Mtempl',eye(4));\n if nargin<5\n flags = def_flags;\n else\n flags = varargin{4};\n fnms = fieldnames(def_flags);\n\t\tfor i=1:length(fnms),\n\t\t\tif ~isfield(flags,fnms{i}),\n flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));\n end\n\t\tend\n end\n \n if ~flags.q_RealLoc\n % Standard electrode set location is used here\n % and they're provided on a simple sphere\n % => need to use nasion and inion to orient them properly.\n\n % Centre translation, scaling factor and pitch angle\n\t % \t-> afine transformation, correcting for the pitch ONLY!\n [na_mm] = flags.nasion;\n [in_mm] = flags.inion;\n \tcNI = (na_mm+in_mm)/2 ;\n \ts = norm(cNI-na_mm) ;\n \ttheta = acos( (na_mm(2)-cNI(2))/s ) ; % pitch angle to apply\n if flags.q_RealNI\n \tTr = spm_matrix([cNI theta 0 0 s s s]) ; % apply pitch correction\n else\n \tTr = inv(flags.Mtempl) * spm_matrix([cNI theta 0 0 s s s]) ;\n % same but takes into account the mapping with template space.\n end \n\n\t\t% Electrodes: \"realistic\" sphere coordinates...\n\t\tel_rsc = Tr * [el_loc ; ones(1,Nel)] ;\n\t\tel_rsc = el_rsc(1:3,:);\n else\n el_rsc = el_loc;\n cNI = surf.Centre;\n end\n % figure, plot3(el_rsc(1,:)',el_rsc(2,:)',el_rsc(3,:)','*'), axis equal, xlabel('axe x'),ylabel('axe y')\n \n\telectrodes.vert = zeros(Nel,1);\n\telectrodes.tri = zeros(Nel,1);\n\tpos_el_mm = zeros(3,Nel);\n\n\t% projection of the el_rsc on the scalp surface.\n\t% The \"closest\" point is detemined by the angle between the electrode_i\n\t% and the scalp vertices from the centre\n\t% Then the supporting triangle is found, such that the electrode_i falls\n\t% within the traingle and the \"exact\" coord of electrode_i is obtained.\n\tXYZmm = surf.XYZmm ;\n\tv_sv = XYZmm-(cNI'*ones(1,size(XYZmm,2))) ;\n\tv_sv = v_sv./( ones(3,1)*sqrt(sum(v_sv.^2)) ) ; % direction of surf vertices from cNI\n\tfor ii=1:Nel\n\t\tv_el = (el_rsc(:,ii)-cNI')/norm(el_rsc(:,ii)-cNI') ;\n\t\t\t% orient vect. of electrode_i\n\t\t\t% orient vect. of scalp vertices\n\t\talpha = acos(v_el'*v_sv) ;\n\t\t[m_a,ind_v] = min(abs(alpha)) ; % Find the vertex with closest orientation\n\t\tlist_t = find( (surf.tri(1,:)==ind_v) | ...\n\t\t\t\t(surf.tri(2,:)==ind_v) | ...\n\t\t\t\t(surf.tri(3,:)==ind_v) ) ; % Triangles linked to that vertex.\n\t\tNlist = length(list_t) ;\n\t\tis_in = zeros(Nlist,1) ;\n\t\tproj_el = zeros(3,Nlist) ;\n\t\tfor j=1:Nlist\n\t\t\tv1 = XYZmm(:,surf.tri(1,list_t(j))) ;\n\t\t\tv2 = XYZmm(:,surf.tri(2,list_t(j))) ;\n\t\t\tv3 = XYZmm(:,surf.tri(3,list_t(j))) ;\n\t\t\tv13 = v3-v1 ; v12 = v2-v1 ;\n\t\t\tA = [v13 v12 v_el] ;\n\t\t\tb = el_rsc(:,ii) - v1;\n\t\t\tx = A\\b ;\n\t\t\tproj_el(:,j) = el_rsc(:,ii) - x(3)*v_el ;\n % In fact, el_rsc(:,ii) = v1 + v13*x(1) + v12*x(2) + v_el*x(3)\n % and proj_el(:,j) = el_rsc(:,i) - x(3)*v_el\n % or proj_el(:,j) = v1 + v13*x(1) + v12*x(2)\n\n\t\t\tv1_pel = v1-proj_el(:,j); no(1) = norm(v1_pel);\n\t\t\tv2_pel = v2-proj_el(:,j); no(2) = norm(v2_pel);\n\t\t\tv3_pel = v3-proj_el(:,j); no(3) = norm(v3_pel);\n if all(no>1e-7) % This is in case one electrode falls exactly on the vertex\n v1_pel = v1_pel/no(1);\n v2_pel = v2_pel/no(2);\n v3_pel = v3_pel/no(3);\n\t\t\t\tsum_angle = real(acos(v1_pel'*v2_pel) + ...\n\t\t\t\t\t\t acos(v2_pel'*v3_pel) + ...\n\t\t\t\t\t\t acos(v3_pel'*v1_pel)) ;\n\t\t\t\tif abs(sum_angle-2*pi)<1e-7\n\t\t\t\t\tis_in(j)=1 ;\n\t\t\t\tend\n else\n is_in(j)=1;\n\t\t\tend\n end\n\t\twhich_tri = find(is_in==1) ;\n\t\t% if the projected electr. location is exactly on an edge, it is in 2 triangles\n\t\t%\t=> keep the 1st one\n\n\t\telectrodes.vert(ii) = ind_v ;\n\t\telectrodes.tri(ii) = list_t(which_tri(1)) ;\n if flags.br_only\n % need to add the br_sc width here\n pos_el_mm(:,ii) = proj_el(:,which_tri(1))+v_el*flags.scbr_w;\n else\n \t\tpos_el_mm(:,ii) = proj_el(:,which_tri(1)) ;\n end\n\tend\n\n\telectrodes.XYZmm = pos_el_mm;\n electrodes.el_loc = el_loc;\n\telectrodes.nr\t = Nel ;\n if flags.br_only\n electrodes.info\t= ['Electr loc projected on brain surface + ',num2str(flags.scbr_w),' mm'];\n else\n \telectrodes.info\t= 'Electrode location projected on scalp surface' ;\n end\n electrodes.names = el_name';\n\n\tvarargout{1} = electrodes;\n varargout{2} = flags;\n%________________________________________________________________________\ncase 'genmesh'\n%------------------------------------------------------------------------\n% FORMAT head = spm_eeg_inv_model('GenMesh',Pvol,flags);\n%\n% Generate the tesselated surface of the 1 to 3 head volumes\n% (brain-skull-scalp) from the binarized volumes.\n% Input :\n% Pvol : filenames of 3 (or 1-2) head volumes 'brain', 'skull' & 'scalp'.\n% flags : various flags\n% * n : (1x3) provides the number of vertices on each surface\n% Npt = n(i)^2*5/4+2\n% * br_only : onlyt use the binarised brain volume (1) or scalp (0, default)\n% * q_elastm: Correct mesh using an elastic model (1, default), or not (0).\n% * q_meased: Measure edges of mesh (1), or not (0, default)\n% * q_4thpt : Determine 4th point central of each traingle (1), or not (0, default)\n% Output :\n% head : head structures with 1 to 3 tesselated surfaces\n%------------------------------------------------------------------------\n fprintf('\\n\\n'), fprintf('%c','='*ones(1,80)), fprintf('\\n')\n fprintf(['\\tGenerate surface meshes from binarized volumes\\n']);\n Pvol = varargin{1};\n \n def_flags = struct('Nvol',1,'n',[32 32 32],'br_only',0, ...\n 'q_elast_m',1,'q_meased',0,'q_4thpt',0);\n if nargin<3\n flags = def_flags;\n else\n flags = varargin{2};\n fnms = fieldnames(def_flags);\n\t\tfor i=1:length(fnms),\n\t\t\tif ~isfield(flags,fnms{i}),\n flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));\n end\n\t\tend\n end\n\n [Centre_vx,Centre_mm]=spm_eeg_inv_model('CtrBin',Pvol(1,:));\n Nbin = size(Pvol,1);\n if length(flags.n)5\n\t\terror('Wrong input arguments for ''TesBin''.') ;\n end\n \n\t% Load volume information\n\t%------------------------\n\tVv = spm_vol(P);\n VOX = sqrt(sum(Vv.mat(1:3,1:3).^2));\n \n\t% A few defintions\n\t%-----------------\n\tho = 1 ; % Trilinear interpolation shoud be enough\n\tn_div = 1000; % # of sample in the radial direction\n\ttrsh_vol = .9; % Thershold for surface detection\n\trad = round(4/3*max(Vv.dim(1:3).*VOX/2)); % Radius (mm) of original sphere\n\tdr = rad/n_div; % size of sampling step (mm)\n\td_li = 0:dr:rad; % Sampling location on radius (mm)\n\tnd_li = length(d_li); unit = ones(1,nd_li);\n \n\t% Create a tessalated sphere\n\t%---------------------------\n\ttsph = spm_eeg_inv_model('TesSph',n,rad); % tesselated sphere of radius rad,\n vert = [tsph.vert ; ones(1,tsph.nr(1))] ; % centered around [0 0 0]\n\tvert = spm_matrix([ctr_vol 0 pi/2 0])*vert ; \n\tvert = vert(1:3,:) ; \n % Rotate the sphere by 90deg around y axis and centre sphere around the \"centre\" of the brain, \n % All this in mm. Leave them as a 3xNvert matrix.\n\t\n\tsrf_vert = zeros(3,tsph.nr(1)) ; % vertices at the surface of brain, in vx !\n spm_progress_bar('Init',tsph.nr(1),\t['Generate ',info ],'Vertices projected');\n\n\tfor i = 1:tsph.nr(1)\n\t\tor = ctr_vol'-vert(:,i) ; or = or/norm(or) ; % direction from the point toward the centre\n\t\tline = vert(:,i)*unit + or*d_li;\n line_vx = spm_eeg_inv_model('mm2vx',line,Vv.mat);\n\t\tval_line = spm_sample_vol(Vv,line_vx(1,:),line_vx(2,:),line_vx(3,:),ho) ;\n\t\tsrf_vert(:,i) = line_vx(:,min(find(val_line>trsh_vol))) ;\n % first point to intercept the surface\n \tspm_progress_bar('Set',i);\n end\n spm_progress_bar('Clear');\n\n\tsrf_vert_mm = spm_eeg_inv_model('vx2mm',srf_vert,Vv.mat);\n\tsurf.XYZmm = srf_vert_mm(1:3,:);\n\tsurf.tri = tsph.tri;\n\tsurf.nr = tsph.nr;\n\tsurf.M = Vv.mat;\n\tsurf.info.str = info;\n surf.info.bin_fn = P;\n surf.Centre = ctr_vol;\n\tvarargout{1} = surf;\n\n%________________________________________________________________________\ncase 'elastm'\n%------------------------------------------------------------------------\n% FORMAT ts = spm_eeg_inv_model('ElastM',ts);\n%\n% Modify the the mesh in order to reduce overlong edges.\n% The procedure uses an elastic model :\n% At each vertex, the neighbouring triangles and vertices connected directly\n% are considered.\n% Each edge is considered elastic and can be lengthened or shortened,\n% depending on their legnth.\n% Refs: G.Taubin, A signal processing approach to fair surface design, 1995\n% This is a non-shrinking smoothing algo.\n%\n% Input : \n% ts: tesselated surface\n% Output :\n% ts: tesselated surface with corrected mesh\n%------------------------------------------------------------------------\n ts = varargin{1};\n\n\tM_con = sparse([ts.tri(1,:)';ts.tri(1,:)';ts.tri(2,:)';ts.tri(3,:)';ts.tri(2,:)';ts.tri(3,:)'], ...\n [ts.tri(2,:)';ts.tri(3,:)';ts.tri(1,:)';ts.tri(1,:)';ts.tri(3,:)';ts.tri(2,:)'], ...\n ones(ts.nr(2)*6,1),ts.nr(1),ts.nr(1));\n % Connection vertex-to-vertex\n \n\tkpb = .1; % Cutt-off frequency\n\tlam = .5; mu = lam/(lam*kpb-1); % Parameters for elasticity.\n\tN = 25; % Number of smoothing steps, the larger, the smoother\n\t\n\tXYZmm = ts.XYZmm;\n\tfor j=1:N\n XYZmm_o = zeros(3,ts.nr(1)) ;\n\t\tXYZmm_o2 = zeros(3,ts.nr(1)) ;\n\t\tfor i=1:ts.nr(1)\n\t\t ln = find(M_con(:,i));\n d_i = sqrt(sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).^2));\n w_i = d_i/sum(d_i);\n XYZmm_o(:,i) = XYZmm(:,i) + ...\n lam * sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).*(ones(3,1)*w_i),2);\n\t\tend\n\t\tfor i=1:ts.nr(1)\n\t\t ln = find(M_con(:,i));\n d_i = sqrt(sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).^2));\n w_i = d_i/sum(d_i);\n XYZmm_o2(:,i) = XYZmm_o(:,i) + ...\n mu * sum((XYZmm_o(:,ln)-XYZmm_o(:,i)*ones(1,length(ln))).*(ones(3,1)*w_i),2);\n\t\tend\n XYZmm = XYZmm_o2;\n\tend\n\tvarargout{1} = ts;\n\tvarargout{1}.XYZmm = XYZmm;\n%________________________________________________________________________\ncase 'meased'\n%------------------------------------------------------------------------\n% FORMAT ts = spm_eeg_inv_model('MeasEd',ts);\n%\n% This measures the edges of the mesh.\n% Input : ts\n% Output : ts with measured edges\n%\n% Format of the '.edges.' sub-structure :\n% \tts.edges.ed :\n% \t\ted(:,1) = length,\n%\t\ted(:,[2 3]) = indexes of 2 points,\n%\t\ted(:,[4 5]) = indexes of 2 triangles.\n%\tts.edges.nr :\n%\t\tnr(1) : number of edges,\n%\t\tnr([2 3]) : mean and std of edges length.\n%------------------------------------------------------------------------\n\nts = varargin{1}; XYZmm = ts.XYZmm;\nNed = 3*ts.nr(2)/2; edges = zeros(Ned,5); i_ed = 1 ;\nfor i=1:ts.nr(2) % Go through all the triangles\n\te1 = ts.tri(1:2,i); % 3 edges of the ith triangle (counter-clock wise)\n\te2 = ts.tri(2:3,i);\n\te3 = ts.tri([3 1],i);\n\tp1 = find((edges(:,2)==e1(2)) && (edges(:,3)==e1(1))); % check if edge was already seen.\n\tp2 = find((edges(:,2)==e2(2)) && (edges(:,3)==e2(1)));\n\tp3 = find((edges(:,2)==e3(2)) && (edges(:,3)==e3(1)));\n\tif isempty(p1) % new edge\n\t\tedges(i_ed,:) = [norm(XYZmm(:,e1(1))-XYZmm(:,e1(2))) e1' i 0] ;\n\t\ti_ed = i_ed+1;\n\telse % 2nd triangle for this edge\n\t\tedges(p1,5) = i;\n\tend\n\tif isempty(p2)\n\t\tedges(i_ed,:) = [norm(XYZmm(:,e2(1))-XYZmm(:,e2(2))) e2' i 0] ;\n\t\ti_ed = i_ed+1 ;\n\telse\n\t\tedges(p2,5) = i;\n\tend\n\tif isempty(p3)\n\t\tedges(i_ed,:) = [norm(XYZmm(:,e3(1))-XYZmm(:,e3(2))) e3' i 0] ;\n\t\ti_ed = i_ed+1 ;\n\telse\n\t\tedges(p3,5) = i;\n\tend\nend\nts.edges.ed = edges; ts.edges.nr = [Ned mean(edges(:,1)) std(edges(:,1))];\nvarargout{1} = ts;\n\n%________________________________________________________________________\ncase 'tr4thpt'\n%------------------------------------------------------------------------\n% FORMAT ts = spm_eeg_inv_model('Tr4thPt',ts);\n%\n% Finds the 4th' point of each triangle:\n% a flat triangle is only an approximation of the real underlying volume surface, \n% a 4th point taken at the centre of the triangle is found by approximating\n% the neighbouring triangles in a sphere, to provide an idea of the local curvature.\n% This is used in the BEM solution of the forward problem, to sort out \n% the problem of the auto-solid angle.\n%\n% Input : \n% ts: tesselated surface\n% Output :\n% ts: tesselated surface with 4th point at each triangle\n%------------------------------------------------------------------------\n\tif nargin==1\n error('Wrong input. You should pass a tess. surface')\n\tend\n ts = varargin{1};\n\tT_con = sparse([ts.edges.ed(:,4),ts.edges.ed(:,5)],[ts.edges.ed(:,5),ts.edges.ed(:,4)], ...\n ones(ts.edges.nr(1)*2,1),ts.nr(2),ts.nr(2),ts.edges.nr(1)*2);\n % Connection Triangle-to-triangle\n\t\n\tXYZmm = ts.XYZmm;\n\t\n\tts.pt4.XYZmm = zeros(3,ts.nr(2)) ;\n\tfor i=1:ts.nr(2)\n l_tr = find(T_con(:,i));\n l_vt = ts.tri(:,l_tr); l_vt = sort(l_vt(:));\n l_vt = [l_vt(find(diff(l_vt)));l_vt(end)]; % Remov vertices listed twice.\n vi = XYZmm(:,l_vt); A = [2*vi' -ones(6,1)]; b = sum(vi.^2)';\n x = A\\b;\n vc = x(1:3);\n R = sqrt(norm(vc)^2-x(4));\n vct = sum(XYZmm(:,ts.tri(:,i)),2)/3; or = vct-vc; or = or/norm(or);\n ts.pt4.XYZmm(:,i) = vc+R*or;\n end\n varargout{1} = ts;\n \n%________________________________________________________________________\ncase 'tessph' \n%------------------------------------------------------------------------\n% FORMAT tsph = spm_eeg_inv_model('TesSph',n,r);\n%\n% Generate a structure 'tsph' containing a tesselated sphere.\n% Input : \n% n : number of 'latitude' divisions on the sphere. It MUST be even!\n% r : radius of the sphere\n% Output : \n% tsph .vert : vertices coordinates (3 x Nvert)\n%\t\t .tri : triangle patches (3 x Ntri)\n%\t\t .info : info string\n% \t\t8 -> 82 points -> 160 triangles\n% \t\t10 -> 127 points -> 250 triangles\n% \t\t12 -> 182 points -> 360 triangles\n% \t\t14 -> 247 points -> 490 triangles\n% \t\t16 -> 322 points -> 640 triangles\n% \t\t18 -> 407 points -> 810 triangles\n% \t\t20 -> 502 points -> 1000 triangles\n% \t\t22 -> 607 points -> 1210 triangles\n% \t\t24 -> 722 points -> 1440 triangles\n% \t\t26 -> 847 points -> 1690 triangles\n% \t\t28 -> 982 points -> 1960 triangles\n% \t\t30 -> 1127 points -> 2250 triangles\n% \t\t32 -> 1282 points -> 2560 triangles\n% \t\t34 -> 1447 points -> 2890 triangles\n% \t\t36 -> 1622 points -> 3240 triangles\n% \t\t40 -> 2002 points -> 4000 triangles\n% \t\t42 -> 2207 points -> 4410 triangles\n% \t\t44 -> 2422 points -> 4840 triangles\n% \t\t46 -> 2647 points -> 5290 triangles\n% \t\t48 -> 2882 points -> 5760 triangles\n% \t\t54 -> 3647 points -> 7290 triangles\n% \t\t56 -> 3922 points -> 7840 triangles\n% \t\t58 -> 4207 points -> 8410 triangles\n% \t\t60 -> 4502 points -> 9000 triangles\n% \t\t62 -> 4807 points -> 9610 triangles\n% \t\t64 -> 5122 points -> 10240 triangles.\n%------------------------------------------------------------------------\n if nargin==1 \n\t\tn = 20 ;\n\t\tr = 1 ;\n\t\tdisp(['default values : n=',num2str(n),' , r=',num2str(r)]) ;\n\telseif nargin==2\n n = varargin{1}\n r = 1 ;\n\t\t disp(['default value : r=',num2str(r)]) ;\n\telseif nargin==3\n n = varargin{1};\n r = varargin{2};\n\telse\n error('Wrong input format 2')\n\tend\n\t\n\t[X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r) ;\n\t[ind_tr] = tri(npt_tr,npt_qr,npt_sph) ;\n\t\n\ttsph.vert = [X_sp ; Y_sp ; Z_sp] ;\n\ttsph.tri = ind_tr ;\n\ttsph.nr = [length(X_sp) size(ind_tr,2)] ;\n\ttsph.info = ['Tes sph : n=',num2str(n),', r=',num2str(r)] ;\n\tvarargout{1} = tsph;\n%__________________________________________________________________________\ncase 'erodegrow' \n%------------------------------------------------------------------------\n%\n% FORMAT [Pout/val] = spm_eeg_inv_model('ErodeGrow',P/val,ne,ng,thr_im)\n% \n% It erodes then grows an image after thresholding it.\n% Inputs : P/val,ne,ng,thr_im\n% P : file name of image to erode/grow\n% val : full volume of image (as loaded by spm_read_vols)\n% ne : nr of steps for erosion, default 3\n% ng : nr of steps for growing, default 6\n% thr_im : threshold value to apply, default .8\n% (compared to the maximal value of image)\n% Output : Pout/val\n% Pout : name of the file generated\n% val : full value of eroded-grown image\n% \n% Notes:\n% - if 2 file names are specified in P[input], the 2nd one is used as the name\n% of the generated file otherwise the new filename is creted from P as\n% [P,'_e',num2str(ne),'g',num2str(ng),'.img']\n% - If a file name is passed the output is a filename.\n% If a matrix of values is passed, the output is a matrix of values.\n%------------------------------------------------------------------------\nfl_rvol = 0; % Need to load (1) or not (0) the volume from a file\nif nargin<2\n P = spm_select(1,'image','Image to erode-grow');\n nPin = size(P,1);\n Vp = spm_vol(P);\n fl_rvol = 1;\n dim = V.dim;\n cr_file = 1; % Create (1) or not (0) a file at the end of the process.\nend\n\nif length(varargin)>=1\n if ischar(varargin{1})\n P = varargin{1};\n nPin = size(P,1);\n Vp = spm_vol(P(1,:));\n fl_rvol = 1;\n dim = Vp.dim;\n cr_file = 1;\n elseif isa(varargin{1},'uint8')\n val = varargin{1};\n dim = size(val);\n cr_file = 0;\n elseif isnumeric(varargin{1})\n val = uint8(varargin{1});\n dim = size(val);\n cr_file = 0;\n else\n error('Wrong data format');\n end\nend\n\nif fl_rvol\n val = spm_loaduint8(Vp);\nend\n\nne = 1; ng = 1; thr_im = .1 ;\nif length(varargin)==4\n ne = varargin{2}; \n ng = varargin{3}; \n thr_im = varargin{4};\nelse\n disp('Using default erode/grow parameters: ne=1, ng=1, thr=.1 !')\nend\np1 = uint8(zeros(1,dim(2),dim(3)));\np2 = uint8(zeros(dim(1),1,dim(3)));\np3 = uint8(zeros(dim(1),dim(2),1));\n\np1_3 = uint8(zeros(1,dim(2),dim(3)-1));\np2_1 = uint8(zeros(dim(1)-1,1,dim(3)));\np3_2 = uint8(zeros(dim(1),dim(2)-1,1));\n\n% Erosion !\n% val = val>thr_im*max(max(max(abs(val)))) ;\nval = uint8(val>thr_im*double(max(val(:)))) ; \n % added uint8 otherwise is considered as a logical variable \n % -> no math operation (addition) possible\nNbin = length(find(val(:)));\nfprintf('\\tOriginal number of voxels %d .\\n',Nbin)\nfor i=1:ne\n temp = val ...\n + cat(1,p1,val(1:end-1,:,:)) + cat(1,val(2:end,:,:),p1) ...\n + cat(2,p2,val(:,1:end-1,:)) + cat(2,val(:,2:end,:),p2) ...\n + cat(3,p3,val(:,:,1:end-1)) + cat(3,val(:,:,2:end),p3) ...\n + cat(1,p1,cat(2,p2_1,val(1:end-1,1:end-1,:))) ...\n + cat(1,p1,cat(2,val(1:end-1,2:end,:),p2_1)) ...\n + cat(1,cat(2,p2_1,val(2:end,1:end-1,:)),p1) ...\n + cat(1,cat(2,val(2:end,2:end,:),p2_1),p1) ... \n + cat(2,p2,cat(3,p3_2,val(:,1:end-1,1:end-1))) ...\n + cat(2,p2,cat(3,val(:,1:end-1,2:end),p3_2)) ...\n + cat(2,cat(3,p3_2,val(:,1:end-1,1:end-1)),p2) ...\n + cat(2,cat(3,val(:,1:end-1,2:end),p3_2),p2) ... \n + cat(3,p3,cat(1,p1_3,val(1:end-1,:,1:end-1))) ...\n + cat(3,p3,cat(1,val(2:end,:,1:end-1),p1_3)) ...\n + cat(3,cat(1,p1_3,val(1:end-1,:,1:end-1)),p3) ...\n + cat(3,cat(1,val(2:end,:,1:end-1),p1_3),p3) ;\n val = uint8(temp>17) ;\n % val = temp>6 ;\n Nbin = length(find(val(:)));\n fprintf('\\tErosion step %d , %d voxels left.\\n',i,Nbin)\nend\n\n%Ve = Vp;\n%Ve.fname = [spm_str_manip(Vp.fname,'r'),'_e',num2str(ne),'.img']\n%Vout_e = spm_write_vol(Ve,val)\n\n% Growing bit !\nfor i=1:ng\n temp = val ...\n + cat(1,p1,val(1:end-1,:,:)) + cat(1,val(2:end,:,:),p1) ...\n + cat(2,p2,val(:,1:end-1,:)) + cat(2,val(:,2:end,:),p2) ...\n + cat(3,p3,val(:,:,1:end-1)) + cat(3,val(:,:,2:end),p3) ...\n + cat(1,p1,cat(2,p2_1,val(1:end-1,1:end-1,:))) ...\n + cat(1,p1,cat(2,val(1:end-1,2:end,:),p2_1)) ...\n + cat(1,cat(2,p2_1,val(2:end,1:end-1,:)),p1) ...\n + cat(1,cat(2,val(2:end,2:end,:),p2_1),p1) ... \n + cat(2,p2,cat(3,p3_2,val(:,1:end-1,1:end-1))) ...\n + cat(2,p2,cat(3,val(:,1:end-1,2:end),p3_2)) ...\n + cat(2,cat(3,p3_2,val(:,1:end-1,1:end-1)),p2) ...\n + cat(2,cat(3,val(:,1:end-1,2:end),p3_2),p2) ... \n + cat(3,p3,cat(1,p1_3,val(1:end-1,:,1:end-1))) ...\n + cat(3,p3,cat(1,val(2:end,:,1:end-1),p1_3)) ...\n + cat(3,cat(1,p1_3,val(1:end-1,:,1:end-1)),p3) ...\n + cat(3,cat(1,val(2:end,:,1:end-1),p1_3),p3) ;\n val = uint8(temp>1) ;\n Nbin = length(find(val(:)));\n fprintf('\\tGrowing step %d , %d voxels left.\\n',i,Nbin)\nend\n\nif cr_file\n Vout = Vp;\n% val = val.*uint8(255);\n Vout.pinfo = [1/255 0 0]';\n if nPin==1\n Vout.fname = [spm_str_manip(Vp.fname,'r'),'_e',num2str(ne),'g',num2str(ng),'.img'];\n else\n Vout.fname = P(2,:);\n end\n spm_write_vol(Vout,val);\n varargout{1} = Vout.fname ;\nelse\n varargout{1} = val ;\nend\n\n\n\n%________________________________________________________________________\notherwise,\n\twarning('Unknown action string')\nend;\n\nreturn;\n\n%________________________________________________________________________\n%________________________________________________________________________\n%________________________________________________________________________\n%________________________________________________________________________\n%\n% SUBFUNCTIONS\n%________________________________________________________________________\n%________________________________________________________________________\n%________________________________________________________________________\n% FORMAT [X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r)\n% Generate a set of points on a sphere.\n% n = the number of latitudes on the sphere, it MUST be even!\n% r = radius of the sphere, 1 by default.\n%------------------------------------------------------------------------\nfunction [X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r)\nd_r = pi/180; dth = 180/n*d_r ;\nX_qr=[] ; Y_qr=[] ; Z_qr=[] ; X_sp=[] ; Y_sp=[] ; Z_sp=[] ;\n\n% Coord of pts on a 5th of sphere WITHOUT the top and bottom points\nfor i=1:n/2 % Upper part\n\tthe = i*dth ;\n\tcth = cos(the) ; sth = sin(the) ;\n\tdphi = 72/i*d_r ;\n\tfor j=1:i\n\t\tphi = (j-1)*dphi ;\n\t\tcph = cos(phi) ; sph = sin(phi) ;\n\t\tX_qr = [X_qr sth*cph] ;\n\t\tY_qr = [Y_qr sth*sph] ;\n\t\tZ_qr = [Z_qr cth] ;\n\tend\nend\nfor i=(n/2+1):(n-1) % Lower part\n\tthe = i*dth ;\n\tcth = cos(the) ; sth = sin(the) ;\n\tii = n-i ;\n\tdphi = 72/ii*d_r ;\n\tfor j=1:ii\n\t\tphi = (j-1)*dphi ;\n\t\tcph = cos(phi) ; sph = sin(phi) ;\n\t\tX_qr = [X_qr sth*cph] ;\n\t\tY_qr = [Y_qr sth*sph] ;\n\t\tZ_qr = [Z_qr cth] ;\n\tend\nend\n% Each part is copied with a 72deg shift\ndphi=-72*d_r ;\nfor i=0:4\n\tphi=i*dphi ;\n\tcph=cos(phi) ;\n\tsph=sin(phi) ;\n\tX_sp=[X_sp cph*X_qr+sph*Y_qr] ;\n\tY_sp=[Y_sp -sph*X_qr+cph*Y_qr] ;\n\tZ_sp=[Z_sp Z_qr] ;\nend\n% add top and bottom points\nX_sp=[0 X_sp 0]*r ;\nY_sp=[0 Y_sp 0]*r ;\nZ_sp=[1 Z_sp -1]*r ;\n\nnpt_tr = [[0:n/2] [n/2-1:-1:0]]; % Nbr of points on each slice for a 5th of sph.\nnpt_qr = sum(npt_tr) ; % total nbr of pts per 5th of sphere\nnpt_sph=5/4*n^2+2 ; % or 5*npt_qr+2 ; % total nbr of pts on sph\nreturn\n\n%________________________________________________________________________\n% FORMAT [ind_tr] = tri(npt_tr,npt_qr,npt_sph)\n%------------------------------------------------------------------------\n% Order the pts created by the function 'point' into triangles\n% Each triangle is represented by 3 indices correponding to the XYZ_sp\n%\n% This works only because I know in wich order the vertices are generated\n% in the 'point' function.\n%------------------------------------------------------------------------\nfunction [ind_tr] = tri(npt_tr,npt_qr,npt_sph)\nn = sqrt(4/5*(npt_sph-2)) ;\n\n% First 5th of sphere only\nfor i=0:(n/2-1) % upper half\n\tif i==0\t\t \t% 1st triangle at the top\n\t\tind_qr=[1 2 2+npt_qr]' ;\n\telse\t\t \t% other triangles\n\t\tfor j=0:npt_tr(i+1)\n\t\t\tif j==npt_tr(i+1)-1\t\t\t% last but 1 pt on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+j+2 ;\n\t\t\t\tx12=x1+npt_tr(i+1) ;\n\t\t\t\tx13=x12+1 ;\n\t\t\t\tx22=x13 ;\n\t\t\t\tx23=sum(npt_tr(1:i))+2+npt_qr ;\n\t\t\t\tind_qr=[ind_qr [x1 x12 x13]' [x1 x22 x23]'] ;\n\t\t\telseif j==npt_tr(i+1)\t\t% last pt on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+2+npt_qr ;\n\t\t\t\tx2=sum(npt_tr(1:(i+1)))+j+2 ;\n\t\t\t\tx3=x1+npt_tr(i+1) ;\n\t\t\t\tind_qr=[ind_qr [x1 x2 x3]'] ;\n\t\t\telse \t\t\t% other pts on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+j+2 ;\n\t\t\t\tx12=x1+npt_tr(i+1) ;\n\t\t\t\tx13=x12+1 ;\n\t\t\t\tx22=x13 ;\n\t\t\t\tx23=x1+1 ;\n\t\t\t\tind_qr=[ind_qr [x1 x12 x13]' [x1 x22 x23]'] ;\n\t\t\tend\n\t\tend\n\tend\nend\nfor i=(n/2+1):n % lower half\n\tif i==n\t \t% last triangle at the bottom\n\t\tind_qr=[ind_qr [5*npt_qr+2 2*npt_qr+1 npt_qr+1]' ] ;\n\telse \t% other triangles\n\t\tfor j=0:npt_tr(i+1)\n\t\t\tif j==npt_tr(i+1)-1\t\t\t% last but 1 pt on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+j+2 ;\n\t\t\t\tx12=x1-npt_tr(i) ;\n\t\t\t\tx13=x12+1 ;\n\t\t\t\tx22=x13 ;\n\t\t\t\tx23=sum(npt_tr(1:i))+2+npt_qr ;\n\t\t\t\tind_qr=[ind_qr [x1 x13 x12]' [x1 x23 x22]'] ;\n\t\t\telseif j==npt_tr(i+1)\t\t% last pt on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+2+npt_qr ;\n\t\t\t\tx2=sum(npt_tr(1:(i-1)))+j+2 ;\n\t\t\t\tx3=x1-npt_tr(i) ;\n\t\t\t\tind_qr=[ind_qr [x1 x3 x2]'] ;\n\t\t\telse \t\t\t% other pts on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+j+2 ;\n\t\t\t\tx12=x1-npt_tr(i) ;\n\t\t\t\tx13=x12+1 ;\n\t\t\t\tx22=x13 ;\n\t\t\t\tx23=x1+1 ;\n\t\t\t\tind_qr=[ind_qr [x1 x13 x12]' [x1 x23 x22]'] ;\n\t\t\tend\n\t\tend\n\tend\nend\n\n\nntr_qr=size(ind_qr,2) ; % nbr of triangle per 5th of sphere\n[S_i,S_j]=find(ind_qr==1) ;\n[B_i,B_j]=find(ind_qr==npt_sph) ;\n[qs_i,qs_j]=find((ind_qr>(npt_qr+1))&(ind_qr<(3*npt_qr))) ;\nind_tr=[] ;\n\n% shift all indices to cover the sphere\nfor i=0:4\n\tind_tr = [ind_tr (ind_qr+i*npt_qr)] ;\n\tind_tr(S_i,S_j+i*ntr_qr) = 1 ;\n\tind_tr(B_i,B_j+i*ntr_qr) = npt_sph ;\nend\nfor i=1:size(qs_i,1)\n\tind_tr(qs_i(i),qs_j(i)+4*ntr_qr) = ...\n\t\tind_tr(qs_i(i),(qs_j(i)+4*ntr_qr))-5*npt_qr ;\nend\nntr_sph = size(ind_tr,2) ;% nbr of triangles on the sphere\n\t% or = 5/2*n^2\nreturn\n\n% %________________________________________________________________________\n% % FORMAT [udat] = loaduint8(V)\n% %------------------------------------------------------------------------\n% % Load data from file indicated by V into an array of unsigned bytes.\n% %------------------------------------------------------------------------\n% \n% function udat = loaduint8(V)\n% % Load data from file indicated by V into an array of unsigned bytes.\n% \n% if size(V.pinfo,2)==1 && V.pinfo(1) == 2,\n% \tmx = 255*V.pinfo(1) + V.pinfo(2);\n% \tmn = V.pinfo(2);\n% else,\n% \tspm_progress_bar('Init',V.dim(3),...\n% \t\t['Computing max/min of ' spm_str_manip(V.fname,'t')],...\n% \t\t'Planes complete');\n% \tmx = -Inf; mn = Inf;\n% \tfor p=1:V.dim(3),\n% \t\timg = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n% \t\tmx = max([max(img(:))+paccuracy(V,p) mx]);\n% \t\tmn = min([min(img(:)) mn]);\n% \t\tspm_progress_bar('Set',p);\n% \tend;\n% end;\n% spm_progress_bar('Init',V.dim(3),...\n% \t['Loading ' spm_str_manip(V.fname,'t')],...\n% \t'Planes loaded');\n% \n% udat = uint8(0);\n% udat(V.dim(1),V.dim(2),V.dim(3))=0;\n% rand('state',100);\n% for p=1:V.dim(3),\n% \timg = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n% \tacc = paccuracy(V,p);\n% \tif acc==0,\n% \t\tudat(:,:,p) = uint8(round((img-mn)*(255/(mx-mn))));\n% \telse,\n% \t\t% Add random numbers before rounding to reduce aliasing artifact\n% \t\tr = rand(size(img))*acc;\n% \t\tudat(:,:,p) = uint8(round((img+r-mn)*(255/(mx-mn))));\n% \tend;\n% \tspm_progress_bar('Set',p);\n% end;\n% spm_progress_bar('Clear');\n% return;\n% \n% function acc = paccuracy(V,p)\n% % if ~spm_type(V.dim(4),'intt'),\n% if ~spm_type(V.dt(1),'intt'),\n% \tacc = 0;\n% else,\n% \tif size(V.pinfo,2)==1,\n% \t\tacc = abs(V.pinfo(1,1));\n% \telse,\n% \t\tacc = abs(V.pinfo(1,p));\n% \tend;\n% end;\n%________________________________________________________________________\n% FORMAT savefields(fnam,p)\n%------------------------------------------------------------------------\n% save the fields of a structure 'p' in a file 'fnam'\n%------------------------------------------------------------------------\nfunction savefields(fnam,p)\nif length(p)>1, error('Can''t save fields.'); end;\nfn = fieldnames(p);\nfor i=1:length(fn),\n eval([fn{i} '= p.' fn{i} ';']);\nend;\nif spm_matlab_version_chk('7') >= 0,\n save(fnam,'-V6',fn{:});\nelse\n save(fnam,fn{:});\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_smooth.m", "ext": ".m", "path": "spm5-master/spm_config_smooth.m", "size": 3092, "source_encoding": "utf_8", "md5": "c0bb069adf47cd5270401fdb50cea707", "text": "function opts = spm_config_smooth\n% Configuration file for smoothing jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_smooth.m 471 2006-03-08 17:46:45Z john $\n\n\n%_______________________________________________________________________\n\ndata.type = 'files';\ndata.name = 'Images to Smooth';\ndata.tag = 'data';\ndata.filter = 'image';\ndata.num = Inf;\ndata.help = {[...\n'Specify the images to smooth. ',...\n'The smoothed images are written to the same subdirectories as the ',...\n'original *.img and are prefixed with a ''s'' (i.e. s*.img).']};\n \n%------------------------------------------------------------------------\n\nfwhm.type = 'entry';\nfwhm.name = 'FWHM';\nfwhm.tag = 'fwhm';\nfwhm.strtype = 'e';\nfwhm.num = [1 3];\nfwhm.val = {[8 8 8]};\nfwhm.help = {[...\n'Specify the full-width at half maximum (FWHM) of the Gaussian smoothing ',...\n'kernel in mm. Three values should be entered, denoting the FWHM in the ',...\n'x, y and z directions.']};\n\n%------------------------------------------------------------------------\n\ndtype.type = 'menu';\ndtype.name = 'Data Type';\ndtype.tag = 'dtype';\ndtype.labels = {'SAME','UINT8 - unsigned char','INT16 - signed short','INT32 - signed int',...\n 'FLOAT - single prec. float','DOUBLE - double prec. float'};\ndtype.values = {0,spm_type('uint8'),spm_type('int16'),spm_type('int32'),...\n spm_type('float32'),spm_type('float64')};\ndtype.val = {0};\ndtype.help = {'Data-type of output images. SAME indicates the same datatype as the original images.'};\n\n%------------------------------------------------------------------------\n\nopts.type = 'branch';\nopts.name = 'Smooth';\nopts.tag = 'smooth';\nopts.val = {data,fwhm,dtype};\nopts.prog = @smooth;\nopts.vfiles = @vfiles;\nopts.help = {...\n['This is for smoothing (or convolving) image volumes ',...\n'with a Gaussian kernel of a specified width. ',...\n'It is used as a preprocessing step to suppress noise and effects due to residual ',...\n'differences in functional and gyral anatomy during inter-subject ',...\n'averaging.']};\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction smooth(varargin)\njob = varargin{1};\n\nP = strvcat(job.data);\ns = job.fwhm;\ndtype = job.dtype;\nn = size(P,1);\n\nspm_progress_bar('Init',n,'Smoothing','Volumes Complete');\nfor i = 1:n\n Q = deblank(P(i,:));\n [pth,nam,xt,nm] = spm_fileparts(deblank(Q));\n U = fullfile(pth,['s' nam xt nm]);\n spm_smooth(Q,U,s,dtype);\n spm_progress_bar('Set',i);\nend\nspm_progress_bar('Clear');\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction vf = vfiles(varargin)\nP = varargin{1}.data;\nvf = cell(size(P));\nfor i=1:numel(P),\n [pth,nam,ext,num] = spm_fileparts(P{i});\n vf{i} = fullfile(pth,['s', nam, ext, num]);\nend;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_mkdir.m", "ext": ".m", "path": "spm5-master/spm_config_mkdir.m", "size": 1528, "source_encoding": "utf_8", "md5": "e2e46a42fd29862a7861a58ae2973cf3", "text": "function opts = spm_config_mkdir\n% Configuration file for making directory function\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Darren Gitelman\n% $Id: spm_config_mkdir.m 472 2006-03-08 17:48:52Z john $\n\n%_______________________________________________________________________\n\n\ndata.type = 'files';\ndata.name = 'Select a base directory';\ndata.tag = 'basedir';\ndata.filter = 'dir';\ndata.num = 1;\ndata.help = {'Select a base directory.'};\n\nname.type = 'entry';\nname.name = 'Enter a directory name';\nname.tag = 'name';\nname.strtype = 's';\nname.num = [1 1];\nname.help = {'Enter a directory name'};\n\nopts.type = 'branch';\nopts.name = 'Make Directory';\nopts.tag = 'md';\nopts.val = {data,name};\nopts.prog = @my_mkdir;\nopts.vfiles = @vdirs_mydirs;\nopts.help = {[...\n'This facilty allows programming a directory change. Directories are ',...\n'selected in the right listbox.']};\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction my_mkdir(varargin)\njob = varargin{1};\nif ~isempty(job.basedir) && ~isempty(job.name)\n mkdir(job.basedir{:},job.name);\nend\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\n\nfunction vd = vdirs_mydirs(varargin)\n\njob = varargin{1};\n\nvd = {fullfile(job.basedir{:},[job.name,filesep])};\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_minmax.m", "ext": ".m", "path": "spm5-master/spm_minmax.m", "size": 3722, "source_encoding": "utf_8", "md5": "5b32b4c6d23de573920ccc06d8d2baa0", "text": "function [mnv,mxv] = spm_minmax(g)\n% Compute a suitable range of intensities for VBM preprocessing stuff\n% FORMAT [mnv,mxv] = spm_minmax(g)\n% g - array of data\n% mnv - minimum value\n% mxv - maximum value\n%\n% A MOG with two Gaussians is fitted to the intensities. The lower\n% Gaussian is assumed to represent background. The lower value is\n% where there is a 50% probability of being above background. The\n% upper value is one that encompases 99.5% of the values.\n%____________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_minmax.m 1746 2008-05-28 17:43:42Z guillaume $\n\n\nd = [size(g) 1];\nmxv = double(max(g(:)));\nh = zeros(256,1);\nspm_progress_bar('Init',d(3),'Initial histogram','Planes loaded');\nsw = warning('off','all');\nfor i=1:d(3)\n h = h + spm_hist(uint8(round(g(:,:,i)*(255/mxv))),ones(d(1)*d(2),1));\n spm_progress_bar('Set',i);\nend;\nwarning(sw);\nspm_progress_bar('Clear');\n\n% Occasional problems with partially masked data because the first Gaussian\n% just fits the big peak at zero. This will fix that one, but cause problems\n% for skull-stripped data.\nh(1) = 0;\n\n% Very crude heuristic to find a suitable lower limit. The large amount\n% of background really messes up mutual information registration.\n% Begin by modelling the intensity histogram with two Gaussians. One\n% for background, and the other for tissue.\n[mn,v,mg] = fithisto((0:255)',h,1000,[1 128],[32 128].^2,[1 1]);\npr = distribution(mn,v,mg,(0:255)');\n\n%fg = spm_figure('FindWin','Interactive');\n%if ~isempty(fg)\n% figure(fg);\n% plot((0:255)',h/sum(h),'b', (0:255)',pr,'r');\n% drawnow;\n%end;\n\n% Find the lowest intensity above the mean of the first Gaussian\n% where there is more than 50% probability of not being background\nmnd = find((pr(:,1)./(sum(pr,2)+eps) < 0.5) & (0:255)' >mn(1));\nif isempty(mnd) || mnd(1)==1 || mn(1)>mn(2),\n mnd = 1;\nelse\n mnd = mnd(1)-1;\nend\nmnv = mnd*mxv/255;\n\n% Upper limit should get 99.5% of the intensities of the\n% non-background region\nch = cumsum(h(mnd:end))/sum(h(mnd:end));\nch = find(ch>0.995)+mnd;\nmxv = ch(1)/255*mxv;\nreturn;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction [mn,v,mg,ll]=fithisto(x,h,maxit,n,v,mg)\n% Fit a mixture of Gaussians to a histogram\nh = h(:);\nx = x(:);\nsml = mean(diff(x))/1000;\nif nargin==4\n mg = sum(h);\n mn = sum(x.*h)/mg;\n v = (x - mn); v = sum(v.*v.*h)/mg*ones(1,n);\n mn = (1:n)'/n*(max(x)-min(x))+min(x);\n mg = mg*ones(1,n)/n;\nelseif nargin==6\n mn = n;\n n = length(mn);\nelse\n error('Incorrect usage');\nend;\n\nll = Inf;\nfor it=1:maxit\n prb = distribution(mn,v,mg,x);\n scal = sum(prb,2)+eps;\n oll = ll;\n ll = -sum(h.*log(scal));\n if it>2 && oll-ll < length(x)/n*1e-9\n break;\n end;\n for j=1:n\n p = h.*prb(:,j)./scal;\n mg(j) = sum(p);\n mn(j) = sum(x.*p)/mg(j);\n vr = x-mn(j);\n v(j) = sum(vr.*vr.*p)/mg(j)+sml;\n end;\n mg = mg + 1e-3;\n mg = mg/sum(mg);\nend;\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction y=distribution(m,v,g,x)\n% Gaussian probability density\nif nargin ~= 4\n error('not enough input arguments');\nend;\nx = x(:);\nm = m(:);\nv = v(:);\ng = g(:);\nif ~all(size(m) == size(v) & size(m) == size(g))\n error('incompatible dimensions');\nend;\n\nfor i=1:size(m,1)\n d = x-m(i);\n amp = g(i)/sqrt(2*pi*v(i));\n y(:,i) = amp*exp(-0.5 * (d.*d)/v(i));\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_create_vol.m", "ext": ".m", "path": "spm5-master/spm_create_vol.m", "size": 4972, "source_encoding": "utf_8", "md5": "ce1923f47d65ec0e52ab0e5f6e15df7f", "text": "function V = spm_create_vol(V,varargin)\n% Create a volume\n% FORMAT V = spm_create_vol(V)\n% V - image volume information (see spm_vol.m)\n%____________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_create_vol.m 1169 2008-02-26 14:53:43Z volkmar $\n\n\nfor i=1:numel(V),\n if nargin>1,\n v = create_vol(V(i),varargin{:});\n else\n v = create_vol(V(i));\n end;\n f = fieldnames(v);\n for j=1:size(f,1),\n V(i).(f{j}) = v.(f{j});\n end;\nend;\n\n\n\nfunction V = create_vol(V,varargin)\nif ~isstruct(V), error('Not a structure.'); end;\nif ~isfield(V,'fname'), error('No \"fname\" field'); end;\n\nif ~isfield(V,'dim'), error('No \"dim\" field'); end;\nif ~all(size(V.dim)==[1 3]),\n error(['\"dim\" field is the wrong size (' num2str(size(V.dim)) ').']);\nend;\n\nif ~isfield(V,'n'),\n V.n = [1 1];\nelse\n V.n = [V.n(:)' 1 1];\n V.n = V.n(1:2);\nend;\n\nif V.n(1)>1 && V.n(2)>1,\n error('Can only do up to 4D data (%s).',V.fname);\nend;\n\nif ~isfield(V,'dt'),\n V.dt = [spm_type('float64') spm_platform('bigend')];\nend;\n\ndt{1} = spm_type(V.dt(1));\nif strcmp(dt{1},'unknown'),\n error(['\"' dt{1} '\" is an unrecognised datatype (' num2str(V.dt(1)) ').']);\nend;\nif V.dt(2), dt{2} = 'BE'; else dt{2} = 'LE'; end;\n\nif ~isfield(V,'pinfo'), V.pinfo = [Inf Inf 0]'; end;\nif size(V.pinfo,1)==2, V.pinfo(3,:) = 0; end;\nV.fname = deblank(V.fname);\n[pth,nam,ext] = fileparts(V.fname);\n\nswitch ext,\ncase {'.img'}\n minoff = 0;\ncase {'.nii'}\n minoff = 352;\notherwise\n error(['\"' ext '\" is not a recognised extension.']);\nend;\nbits = spm_type(V.dt(1),'bits');\nminoff = minoff + ceil(prod(V.dim(1:2))*bits/8)*V.dim(3)*(V.n(1)-1+V.n(2)-1);\nV.pinfo(3,1) = max(V.pinfo(3,:),minoff);\n\nif ~isfield(V,'descrip'), V.descrip = ''; end;\nif ~isfield(V,'private'), V.private = struct; end;\n\ndim = [V.dim(1:3) V.n];\ndat = file_array(V.fname,dim,[dt{1} '-' dt{2}],0,V.pinfo(1),V.pinfo(2));\nN = nifti;\nN.dat = dat;\nN.mat = V.mat;\nN.mat0 = V.mat;\nN.mat_intent = 'Aligned';\nN.mat0_intent = 'Aligned';\nN.descrip = V.descrip;\n\ntry\n N0 = nifti(V.fname);\n\n % Just overwrite if both are single volume files.\n tmp = [N0.dat.dim ones(1,5)];\n if prod(tmp(4:end))==1 && prod(dim(4:end))==1\n N0 = [];\n end;\ncatch\n N0 = [];\nend;\n\nif ~isempty(N0),\n\n % If the dimensions differ, then there is the potential for things to go badly wrong.\n tmp = [N0.dat.dim ones(1,5)];\n if any(tmp(1:3) ~= dim(1:3))\n warning(['Incompatible x,y,z dimensions in file \"' V.fname '\" [' num2str(tmp(1:3)) ']~=[' num2str(dim(1:3)) '].']);\n end;\n if dim(5) > tmp(5) && tmp(4) > 1,\n warning(['Incompatible 4th and 5th dimensions in file \"' V.fname '\" (' num2str([tmp(4:5) dim(4:5)]) ').']);\n end;\n N.dat.dim = [dim(1:3) max(dim(4:5),tmp(4:5))];\n\n if ~strcmp(dat.dtype,N0.dat.dtype),\n warning(['Incompatible datatype in file \"' V.fname '\" ' N0.dat.dtype ' ~= ' dat.dtype '.']);\n end;\n if single(N.dat.scl_slope) ~= single(N0.dat.scl_slope) && (size(N0.dat,4)>1 || V.n(1)>1),\n warning(['Incompatible scalefactor in \"' V.fname '\" ' num2str(N0.dat.scl_slope) '~=' num2str(N.dat.scl_slope) '.']);\n end;\n if single(N.dat.scl_inter) ~= single(N0.dat.scl_inter),\n warning(['Incompatible intercept in \"' V.fname '\" ' num2str(N0.dat.scl_inter) '~=' num2str(N.dat.scl_inter) '.']);\n end;\n if single(N.dat.offset) ~= single(N0.dat.offset),\n warning(['Incompatible intercept in \"' V.fname '\" ' num2str(N0.dat.offset) '~=' num2str(N.dat.offset) '.']);\n end;\n\n if V.n(1)==1,\n\n % Ensure volumes 2..N have the original matrix\n nt = size(N.dat,4);\n if nt>1 && sum(sum((N0.mat-V.mat).^2))>1e-8,\n M0 = N0.mat;\n if ~isfield(N0.extras,'mat'),\n N0.extras.mat = zeros([4 4 nt]);\n else\n if size(N0.extras.mat,4)=1,\n N.extras.mat(:,:,V.n(1)) = V.mat;\n end;\n else\n N.extras.mat(:,:,V.n(1)) = V.mat;\n end;\n\n if ~isempty(N0.extras) && isstruct(N0.extras) && isfield(N0.extras,'mat'),\n N0.extras.mat(:,:,V.n(1)) = N.mat;\n N.extras = N0.extras;\n end;\n if sum((V.mat(:)-N0.mat(:)).^2) > 1e-4,\n N.extras.mat(:,:,V.n(1)) = V.mat;\n end;\nend;\ncreate(N);\nV.private = N;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_fmri_spec.m", "ext": ".m", "path": "spm5-master/spm_config_fmri_spec.m", "size": 45713, "source_encoding": "utf_8", "md5": "fff311b75229cb7ae87d6691191ed016", "text": "function conf = spm_config_fmri_spec\n% Configuration file for specification of fMRI model\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Darren Gitelman and Will Penny\n% $Id: spm_config_fmri_spec.m 1016 2007-12-03 12:51:33Z volkmar $\n\n\n% Define inline types.\n%-----------------------------------------------------------------------\n\nentry = inline(['struct(''type'',''entry'',''name'',name,'...\n '''tag'',tag,''strtype'',strtype,''num'',num,''help'',hlp)'],...\n 'name','tag','strtype','num','hlp');\n\nfiles = inline(['struct(''type'',''files'',''name'',name,'...\n '''tag'',tag,''filter'',fltr,''num'',num,''help'',hlp)'],...\n 'name','tag','fltr','num','hlp');\n\nmnu = inline(['struct(''type'',''menu'',''name'',name,'...\n '''tag'',tag,''labels'',{labels},''values'',{values},''help'',hlp)'],...\n 'name','tag','labels','values','hlp');\n\nbranch = inline(['struct(''type'',''branch'',''name'',name,'...\n '''tag'',tag,''val'',{val},''help'',hlp)'],...\n 'name','tag','val','hlp');\n\nrepeat = inline(['struct(''type'',''repeat'',''name'',name,'...\n '''tag'',tag,''values'',{values},''help'',hlp)'],...\n 'name','tag','values','hlp');\n\nchoice = inline(['struct(''type'',''choice'',''name'',name,'...\n '''tag'',tag,''values'',{values},''help'',hlp)'],...\n 'name','tag','values','hlp');\n\n%-----------------------------------------------------------------------\n\nsp_text = [' ',...\n ' '];\n%-----------------------------------------------------------------------\n\nonset = entry('Onsets','onset','e',[Inf 1],'Vector of onsets');\np1 = ['Specify a vector of onset times for this condition type. '];\nonset.help = {p1};\n\n%-------------------------------------------------------------------------\n\nduration = entry('Durations','duration','e',[Inf 1],'Duration/s');\nduration.help = [...\n 'Specify the event durations. Epoch and event-related ',...\n 'responses are modeled in exactly the same way but by specifying their ',...\n 'different durations. Events are ',...\n 'specified with a duration of 0. If you enter a single number for the ',...\n 'durations it will be assumed that all trials conform to this duration. ',...\n 'If you have multiple different durations, then the number must match the ',...\n 'number of onset times.'];\n\n%-------------------------------------------------------------------------\n\ntime_mod = mnu('Time Modulation','tmod',...\n {'No Time Modulation','1st order Time Modulation',...\n '2nd order Time Modulation','3rd order Time Modulation',...\n '4th order Time Modulation','5th order Time Modulation',...\n '6th order Time Modulation'},...\n {0,1,2,3,4,5,6},'');\ntime_mod.val = {0};\np1 = [...\n 'This option allows for the characterisation of linear or nonlinear ',...\n 'time effects. ',...\n 'For example, 1st order modulation ',...\n 'would model the stick functions and a linear change of the stick function ',...\n 'heights over time. Higher order modulation will introduce further columns that ',...\n 'contain the stick functions scaled by time squared, time cubed etc.'];\np2 = [...\n 'Interactions or response modulations can enter at two levels. Firstly ',...\n 'the stick function itself can be modulated by some parametric variate ',...\n '(this can be time or some trial-specific variate like reaction time) ',...\n 'modeling the interaction between the trial and the variate or, secondly ',...\n 'interactions among the trials themselves can be modeled using a Volterra ',...\n 'series formulation that accommodates interactions over time (and therefore ',...\n 'within and between trial types).'];\ntime_mod.help = {p1,'',p2};\n\n%-------------------------------------------------------------------------\n%ply = mnu('Polynomial Expansion','poly',...\n% {'None','1st order','2nd order','3rd order','4th order','5th order','6th order'},...\n% {0,1,2,3,4,5,6},'Polynomial Order');\n%ply.val = {0};\n%-------------------------------------------------------------------------\n\nname = entry('Name','name','s', [1 Inf],'Name of parameter');\nname.val = {'Param'};\nname.help = {'Enter a name for this parameter.'};\n\n%-------------------------------------------------------------------------\n\nparam = entry('Values','param','e',[Inf 1],'Parameter vector');\nparam.help = {'Enter a vector of values, one for each occurence of the event.'};\n\n%-------------------------------------------------------------------------\n\nply = mnu('Polynomial Expansion','poly',...\n {'1st order','2nd order','3rd order','4th order','5th order','6th order'},...\n {1,2,3,4,5,6},'Polynomial Order');\nply.val = {1};\nply.help = {[...\n 'For example, 1st order modulation ',...\n 'would model the stick functions and a linear change of the stick function ',...\n 'heights over different values of the parameter. Higher order modulation will ',...\n 'introduce further columns that ',...\n 'contain the stick functions scaled by parameter squared, cubed etc.']};\n\n%-------------------------------------------------------------------------\n\npother = branch('Parameter','pmod',{name,param,ply},'Custom parameter');\np1 = [...\n 'Model interractions with user specified parameters. ',...\n 'This allows nonlinear effects relating to some other measure ',...\n 'to be modelled in the design matrix.'];\np2 = [...\n 'Interactions or response modulations can enter at two levels. Firstly ',...\n 'the stick function itself can be modulated by some parametric variate ',...\n '(this can be time or some trial-specific variate like reaction time) ',...\n 'modeling the interaction between the trial and the variate or, secondly ',...\n 'interactions among the trials themselves can be modeled using a Volterra ',...\n 'series formulation that accommodates interactions over time (and therefore ',...\n 'within and between trial types).'];\npother.help = {p1,'',p2};\n\n%-------------------------------------------------------------------------\npmod = repeat('Parametric Modulations','pmod',{pother},'');\npmod.help = {[...\n 'The stick function itself can be modulated by some parametric variate ',...\n '(this can be time or some trial-specific variate like reaction time) ',...\n 'modeling the interaction between the trial and the variate. ',...\n 'The events can be modulated by zero or more parameters.']};\n\n%-------------------------------------------------------------------------\n\nname = entry('Name','name','s',[1 Inf],'Condition Name');\nname.val = {'Trial'};\n\n%-------------------------------------------------------------------------\n\ncond = branch('Condition','cond',{name,onset,duration,time_mod,pmod},...\n 'Condition');\ncond.check = @cond_check;\ncond.help = {[...\n 'An array of input functions is contructed, ',...\n 'specifying occurrence events or epochs (or both). ',...\n 'These are convolved with a basis set at a later stage to give ',...\n 'regressors that enter into the design matrix. Interactions of evoked ',...\n 'responses with some parameter (time or a specified variate) enter at ',...\n 'this stage as additional columns in the design matrix with each trial multiplied ',...\n 'by the [expansion of the] trial-specific parameter. ',...\n 'The 0th order expansion is simply the main effect in the first column.']};\n\n%-------------------------------------------------------------------------\n\nconditions = repeat('Conditions','condrpt',{cond},'Conditions');\nconditions.help = {[...\n 'You are allowed to combine both event- and epoch-related ',...\n 'responses in the same model and/or regressor. Any number ',...\n 'of condition (event or epoch) types can be specified. Epoch and event-related ',...\n 'responses are modeled in exactly the same way by specifying their ',...\n 'onsets [in terms of onset times] and their durations. Events are ',...\n 'specified with a duration of 0. If you enter a single number for the ',...\n 'durations it will be assumed that all trials conform to this duration.',...\n 'For factorial designs, one can later associate these experimental conditions ',...\n 'with the appropriate levels of experimental factors. ';]};\n\n%-------------------------------------------------------------------------\n\nmulti = files('Multiple conditions','multi','\\.mat$',[0 1],'');\np1=['Select the *.mat file containing details of your multiple experimental conditions. '];\np2=['If you have multiple conditions then entering the details a condition ',...\n 'at a time is very inefficient. This option can be used to load all the ',...\n 'required information in one go. You will first need to create a *.mat file ',...\n 'containing the relevant information. '];\np3=['This *.mat file must include the following cell arrays (each 1 x n): ',...\n 'names, onsets and durations. eg. names=cell(1,5), onsets=cell(1,5), ',...\n 'durations=cell(1,5), then names{2}=''SSent-DSpeak'', onsets{2}=[3 5 19 222], ',...\n 'durations{2}=[0 0 0 0], contain the required details of the second condition. ',...\n 'These cell arrays may be made available by your stimulus delivery program, ',...\n 'eg. COGENT. The duration vectors can contain a single entry if the durations ',...\n 'are identical for all events.'];\np4=['Time and Parametric effects can also be included. For time modulation ',...\n 'include a cell array (1 x n) called tmod. It should have a have a single ',...\n 'number in each cell. Unused cells may contain either a 0 or be left empty. The number ',...\n 'specifies the order of time modulation from 0 = No Time Modulation to ',...\n '6 = 6th Order Time Modulation. eg. tmod{3} = 1, modulates the 3rd condition ',...\n 'by a linear time effect.'];\np5=['For parametric modulation include a structure array, which is up to 1 x n in size, ',...\n 'called pmod. n must be less than or equal to the number of cells in the ',...\n 'names/onsets/durations cell arrays. The structure array pmod must have the fields: ',...\n 'name, param and poly. Each of these fields is in turn a cell array to allow the ',...\n 'inclusion of one or more parametric effects per column of the design. The field ',...\n 'name must be a cell array containing strings. The field param is a cell array ',...\n 'containing a vector of parameters. Remember each parameter must be the same length as its ',...\n 'corresponding onsets vector. The field poly is a cell array (for consistency) ',...\n 'with each cell containing a single number specifying the order of the polynomial ',...\n 'expansion from 1 to 6.'];\np6=['Note that each condition is assigned its corresponding ',...\n 'entry in the structure array (condition 1 parametric modulators are in pmod(1), ',...\n 'condition 2 parametric modulators are in pmod(2), etc. Within a condition ',...\n 'multiple parametric modulators are accessed via each fields cell arrays. ',...\n 'So for condition 1, parametric modulator 1 would be defined in ',...\n 'pmod(1).name{1}, pmod(1).param{1}, and pmod(1).poly{1}. A second parametric ',...\n 'modulator for condition 1 would be defined as pmod(1).name{2}, pmod(1).param{2} ',...\n 'and pmod(1).poly{2}. If there was also a parametric modulator for condition 2, ',...\n 'then remember the first modulator for that condition is in cell array 1: ',...\n 'pmod(2).name{1}, pmod(2).param{1}, and pmod(2).poly{1}. If some, but not ',...\n 'all conditions are parametrically modulated, then the non-modulated indices ',...\n 'in the pmod structure can be left blank. For example, if conditions 1 and 3 but ',...\n 'not condition 2 are modulated, then specify pmod(1) and pmod(3). ',...\n 'Similarly, if conditions 1 and 2 are modulated but there are 3 conditions ',...\n 'overall, it is only necessary for pmod to be a 1 x 2 structure array.'];\np7=['EXAMPLE:'];\np8=['Make an empty pmod structure: '];\np9=[' pmod = struct(''name'',{''''},''param'',{},''poly'',{});'];\np10=['Specify one parametric regressor for the first condition: '];\np11=[' pmod(1).name{1} = ''regressor1'';'];\np12=[' pmod(1).param{1} = [1 2 4 5 6];'];\np13=[' pmod(1).poly{1} = 1;'];\np14=['Specify 2 parametric regressors for the second condition: '];\np15=[' pmod(2).name{1} = ''regressor2-1'';'];\np16=[' pmod(2).param{1} = [1 3 5 7]; '];\np17=[' pmod(2).poly{1} = 1;'];\np18=[' pmod(2).name{2} = ''regressor2-2'';'];\np19=[' pmod(2).param{2} = [2 4 6 8 10];'];\np20=[' pmod(2).poly{2} = 1;'];\np21=['The parametric modulator should be mean corrected if appropriate. Unused ',...\n 'structure entries should have all fields left empty.'];\n \nmulti.help = {p1,sp_text,p2,sp_text,p3,sp_text,p4,sp_text,p5,sp_text,p6,...\n sp_text,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,sp_text,p21};\nmulti.val={''};\n\n\n%-------------------------------------------------------------------------\n\nname = entry('Name','name','s',[1 Inf],'');\nname.val = {'Regressor'};\np1=['Enter name of regressor eg. First movement parameter'];\nname.help={p1};\n\n%-------------------------------------------------------------------------\n\nval = entry('Value','val','e',[Inf 1],'');\nval.help={['Enter the vector of regressor values']};\n\n%-------------------------------------------------------------------------\n\nregress = branch('Regressor','regress',{name,val},'regressor');\nregressors = repeat('Regressors','regress',{regress},'Regressors');\nregressors.help = {[...\n 'Regressors are additional columns included in the design matrix, ',...\n 'which may model effects that would not be convolved with the ',...\n 'haemodynamic response. One such example would be the estimated movement ',...\n 'parameters, which may confound the data.']};\n\n%-------------------------------------------------------------------------\n\nmulti_reg = files('Multiple regressors','multi_reg','.*',[0 1],'');\np1=['Select the *.mat/*.txt file containing details of your multiple regressors. '];\np2=['If you have multiple regressors eg. realignment parameters, then entering the ',...\n 'details a regressor at a time is very inefficient. ',...\n 'This option can be used to load all the ',...\n 'required information in one go. '];\np3=['You will first need to create a *.mat file ',...\n 'containing a matrix R or a *.txt file containing the regressors. ',...\n 'Each column of R will contain a different regressor. ',...\n 'When SPM creates the design matrix the regressors will be named R1, R2, R3, ..etc.'];\nmulti_reg.help = {p1,sp_text,p2,sp_text,p3};\nmulti_reg.val={''};\n\n%-------------------------------------------------------------------------\n\nscans = files('Scans','scans','image',[1 Inf],'Select scans');\nscans.help = {[...\n 'Select the fMRI scans for this session. They must all have the same ',...\n 'image dimensions, orientation, voxel size etc.']};\n\n%-------------------------------------------------------------------------\n\nhpf = entry('High-pass filter','hpf','e',[1 1],'');\nhpf.val = {128};\nhpf.help = {[...\n 'The default high-pass filter cutoff is 128 seconds.',...\n 'Slow signal drifts with a period longer than this will be removed. ',...\n 'Use ''explore design'' ',...\n 'to ensure this cut-off is not removing too much experimental variance. ',...\n 'High-pass filtering is implemented using a residual forming matrix (i.e. ',...\n 'it is not a convolution) and is simply to a way to remove confounds ',...\n 'without estimating their parameters explicitly. The constant term ',...\n 'is also incorporated into this filter matrix.']};\n\n%-------------------------------------------------------------------------\n\nsess = branch('Subject/Session','sess',{scans,conditions,multi,regressors,multi_reg,hpf},'Session');\nsess.check = @sess_check;\np1 = [...\n 'The design matrix for fMRI data consists of one or more separable, ',...\n 'session-specific partitions. These partitions are usually either one per ',...\n 'subject, or one per fMRI scanning session for that subject.'];\nsess.help = {p1};\n\n%-------------------------------------------------------------------------\n\nblock = repeat('Data & Design','blocks',{sess},'');\nblock.num = [1 Inf];\np1 = [...\n 'The design matrix defines the experimental design and the nature of ',...\n 'hypothesis testing to be implemented. The design matrix has one row ',...\n 'for each scan and one column for each effect or explanatory variable. ',...\n '(e.g. regressor or stimulus function). '];\np2 = [...\n 'This allows you to build design matrices with separable ',...\n 'session-specific partitions. Each partition may be the same (in which ',...\n 'case it is only necessary to specify it once) or different. Responses ',...\n 'can be either event- or epoch related, where the latter model involves prolonged ',...\n 'and possibly time-varying responses to state-related changes in ',...\n 'experimental conditions. Event-related response are modelled in terms ',...\n 'of responses to instantaneous events. Mathematically they are both ',...\n 'modelled by convolving a series of delta (stick) or box-car functions, ',...\n 'encoding the input or stimulus function. with a set of hemodynamic ',...\n 'basis functions.'];\nblock.help = {p1,'',p2};\n\n% Specification of factorial designs\n\nfname.type = 'entry';\nfname.name = 'Name';\nfname.tag = 'name';\nfname.strtype = 's';\nfname.num = [1 1];\nfname.help = {'Name of factor, eg. ''Repetition'' '};\n\nlevels = entry('Levels','levels','e',[Inf 1],'');\np1=['Enter number of levels for this factor, eg. 2'];\nlevels.help ={p1};\n\nfactor.type = 'branch';\nfactor.name = 'Factor';\nfactor.tag = 'fact';\nfactor.val = {fname,levels};\nfactor.help = {'Add a new factor to your experimental design'};\n\nfactors.type = 'repeat';\nfactors.name = 'Factorial design';\nfactors.tag = 'factors';\nfactors.values = {factor};\np1 = ['If you have a factorial design then SPM can automatically generate ',...\n 'the contrasts necessary to test for the main effects and interactions. '];\np2 = ['This includes the F-contrasts necessary to test for these effects at ',...\n 'the within-subject level (first level) and the simple contrasts necessary ',...\n 'to generate the contrast images for a between-subject (second-level) ',...\n 'analysis.'];\np3 = ['To use this option, create as many factors as you need and provide a name ',...\n 'and number of levels for each. ',...\n 'SPM assumes that the condition numbers of the first factor change slowest, ',...\n 'the second factor next slowest etc. It is best to write down the contingency ',...\n 'table for your design to ensure this condition is met. This table relates the ',...\n 'levels of each factor to the ',...\n 'conditions. '];\np4= ['For example, if you have 2-by-3 design ',...\n ' your contingency table has two rows and three columns where the ',...\n 'the first factor spans the rows, and the second factor the columns. ',...\n 'The numbers of the conditions are 1,2,3 for the first row and 4,5,6 ',...\n 'for the second. '];\n\nfactors.help ={p1,sp_text,p2,sp_text,p3,sp_text,p4};\n\n\n\n%-------------------------------------------------------------------------\n\nglob = mnu('Global normalisation','global',...\n {'Scaling','None'},{'Scaling','None'},{'Global intensity normalisation'});\nglob.val={'None'};\n\n%-------------------------------------------------------------------------\n\nderivs = mnu('Model derivatives','derivs',...\n {'No derivatives', 'Time derivatives', 'Time and Dispersion derivatives'},...\n {[0 0],[1 0],[1 1]},'');\nderivs.val = {[0 0]};\np1=['Model HRF Derivatives. The canonical HRF combined with time and ',...\n 'dispersion derivatives comprise an ''informed'' basis set, as ',...\n 'the shape of the canonical response conforms to the hemodynamic ',...\n 'response that is commonly observed. The incorporation of the derivate ',...\n 'terms allow for variations in subject-to-subject and voxel-to-voxel ',...\n 'responses. The time derivative allows the peak response to vary by plus or ',...\n 'minus a second and the dispersion derivative allows the width of the response ',...\n 'to vary. The informed basis set requires an SPM{F} for inference. T-contrasts ',...\n 'over just the canonical are perfectly valid but assume constant delay/dispersion. ',...\n 'The informed basis set compares ',...\n 'favourably with eg. FIR bases on many data sets. '];\nderivs.help = {p1};\n%-------------------------------------------------------------------------\n\nhrf = branch('Canonical HRF','hrf',{derivs},'Canonical Hemodynamic Response Function');\nhrf.help = {[...\n 'Canonical Hemodynamic Response Function. This is the default option. ',...\n 'Contrasts of these effects have a physical interpretation ',...\n 'and represent a parsimonious way of characterising event-related ',...\n 'responses. This option is also ',...\n 'useful if you wish to ',...\n 'look separately at activations and deactivations (this is implemented using a ',...\n 't-contrast with a +1 or -1 entry over the canonical regressor). ']};\n\n%-------------------------------------------------------------------------\n\nlen = entry('Window length','length','e',[1 1],'');\nlen.help={'Post-stimulus window length (in seconds)'};\norder = entry('Order','order','e',[1 1],'');\norder.help={'Number of basis functions'};\no1 = branch('Fourier Set','fourier',{len,order},'');\no1.help = {'Fourier basis functions. This option requires an SPM{F} for inference.'};\no2 = branch('Fourier Set (Hanning)','fourier_han',{len,order},'');\no2.help = {'Fourier basis functions with Hanning Window - requires SPM{F} for inference.'};\no3 = branch('Gamma Functions','gamma',{len,order},'');\no3.help = {'Gamma basis functions - requires SPM{F} for inference.'};\no4 = branch('Finite Impulse Response','fir',{len,order},'');\no4.help = {'Finite impulse response - requires SPM{F} for inference.'};\n\n%-------------------------------------------------------------------------\n\nbases = choice('Basis Functions','bases',{hrf,o1,o2,o3,o4},'');\nbases.val = {hrf};\nbases.help = {[...\n 'The most common choice of basis function is the Canonical HRF with ',...\n 'or without time and dispersion derivatives. ']};\n\n%-------------------------------------------------------------------------\n\nvolt = mnu('Model Interactions (Volterra)','volt',{'Do not model Interactions','Model Interactions'},{1,2},'');\nvolt.val = {1};\np1 = ['Generalized convolution of inputs (U) with basis set (bf).'];\np2 = [...\n 'For first order expansions the causes are simply convolved ',...\n '(e.g. stick functions) in U.u by the basis functions in bf to create ',...\n 'a design matrix X. For second order expansions new entries appear ',...\n 'in ind, bf and name that correspond to the interaction among the ',...\n 'orginal causes. The basis functions for these efects are two dimensional ',...\n 'and are used to assemble the second order kernel. ',...\n 'Second order effects are computed for only the first column of U.u.'];\np3 = [...\n 'Interactions or response modulations can enter at two levels. Firstly ',...\n 'the stick function itself can be modulated by some parametric variate ',...\n '(this can be time or some trial-specific variate like reaction time) ',...\n 'modeling the interaction between the trial and the variate or, secondly ',...\n 'interactions among the trials themselves can be modeled using a Volterra ',...\n 'series formulation that accommodates interactions over time (and therefore ',...\n 'within and between trial types).'];\nvolt.help = {p1,'',p2,p3};\n\n%-------------------------------------------------------------------------\n\nmask = files('Explicit mask','mask','image',[0 1],'Image mask');\nmask.val = {''};\np1=['Specify an image for explicitly masking the analysis. ',...\n 'A sensible option here is to use a segmention of structural images ',...\n 'to specify a within-brain mask. If you select that image as an ',...\n 'explicit mask then only those voxels in the brain will be analysed. ',...\n 'This both speeds the estimation and restricts SPMs/PPMs to within-brain ',...\n 'voxels. Alternatively, if such structural images are unavailble or no ',...\n 'masking is required, then leave this field empty.'];\nmask.help={p1};\n\n%-------------------------------------------------------------------------\n\ncdir = files('Directory','dir','dir',1,'');\ncdir.help = {[...\n 'Select a directory where the SPM.mat file containing the ',...\n 'specified design matrix will be written.']};\n\n%-------------------------------------------------------------------------\nfmri_t0 = entry('Microtime onset','fmri_t0','e',[1 1],'');\np1=['The microtime onset, t0, is the first time-bin at which the regressors ',...\n 'are resampled to coincide ',...\n 'with data acquisition. If t0 = 1 then the ',...\n 'regressors will be appropriate for the first slice. If you want to ',...\n 'temporally realign the regressors so that they match responses in the ',...\n 'middle slice then make t0 = t/2 ',...\n '(assuming there is a negligible gap between ',...\n 'volume acquisitions). '];\np2=['Do not change the default setting unless you have a long TR. '];\nfmri_t0.val={1};\nfmri_t0.help={p1,sp_text,p2};\n\nfmri_t = entry('Microtime resolution','fmri_t','e',[1 1],'');\np1=['The microtime resolution, t, is the number of time-bins per ',...\n 'scan used when building regressors. '];\np2=['Do not change this parameter unless you have a long TR and wish to ',...\n 'shift regressors so that they are ',...\n 'aligned to a particular slice. '];\nfmri_t.val={16};\nfmri_t.help={p1,sp_text,p2};\n\nrt = entry('Interscan interval','RT','e',[1 1],'Interscan interval {secs}');\nrt.help = {[...\n 'Interscan interval, TR, (specified in seconds). This is the time between acquiring a plane of one volume ',...\n 'and the same plane in the next volume. It is assumed to be constant throughout.']};\n\n%-------------------------------------------------------------------------\n\nunits = mnu('Units for design','units',{'Scans','Seconds'},{'scans','secs'},'');\np1=['The onsets of events or blocks can be specified in either scans or seconds.'];\nunits.help = {p1};\n\ntiming = branch('Timing parameters','timing',{units,rt,fmri_t,fmri_t0},'');\np1=['Specify various timing parameters needed to construct the design matrix. ',...\n 'This includes the units of the design specification and the interscan interval.'];\n\np2 = ['Also, with longs TRs you may want to shift the regressors so that they are ',...\n 'aligned to a particular slice. This is effected by changing the ',...\n 'microtime resolution and onset. '];\ntiming.help={p1,sp_text,p2};\n\n%-------------------------------------------------------------------------\n\ncvi = mnu('Serial correlations','cvi',{'none','AR(1)'},{'none','AR(1)'},...\n {'Correct for serial correlations'});\ncvi.val={'AR(1)'};\np1 = [...\n 'Serial correlations in fMRI time series due to aliased biorhythms and unmodelled ',...\n 'neuronal activity can be accounted for using an autoregressive AR(1) ',...\n 'model during Classical (ReML) parameter estimation. '];\np2=['This estimate assumes the same ',...\n 'correlation structure for each voxel, within each session. ReML ',...\n 'estimates are then used to correct for non-sphericity during inference ',...\n 'by adjusting the statistics and degrees of freedom appropriately. The ',...\n 'discrepancy between estimated and actual intrinsic (i.e. prior to ',...\n 'filtering) correlations are greatest at low frequencies. Therefore ',...\n 'specification of the high-pass filter is particularly important. '];\np3=[...\n 'Serial correlation can be ignored if you choose the ''none'' option. ',...\n 'Note that the above options only apply if you later specify that your model will be ',...\n 'estimated using the Classical (ReML) approach. If you choose Bayesian estimation ',...\n 'these options will be ignored. For Bayesian estimation, the choice of noise',...\n 'model (AR model order) is made under the estimation options. '];\ncvi.help = {p1,sp_text,p2,sp_text,p3};\n\n%-------------------------------------------------------------------------\n\nconf = branch('fMRI model specification','fmri_spec',...\n {cdir,timing,block,factors,bases,volt,glob,mask,cvi},'fMRI design');\nconf.prog = @run_stats;\nconf.vfiles = @vfiles_stats;\n% conf.check = @check_dir;\nconf.modality = {'FMRI'};\np1=['Statistical analysis of fMRI data uses a mass-univariate approach ',...\n 'based on General Linear Models (GLMs). It comprises the following ',...\n 'steps (1) specification of the GLM design matrix, fMRI data files and filtering ',...\n '(2) estimation of GLM paramaters using classical or ',...\n 'Bayesian approaches and (3) interrogation of results using contrast vectors to ',...\n 'produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs).' ];\np2 = [...\n 'The design matrix defines the experimental design and the nature of ',...\n 'hypothesis testing to be implemented. The design matrix has one row ',...\n 'for each scan and one column for each effect or explanatory variable. ',...\n '(eg. regressor or stimulus function). ',...\n 'You can build design matrices with separable ',...\n 'session-specific partitions. Each partition may be the same (in which ',...\n 'case it is only necessary to specify it once) or different. '];\np3 = ['Responses ',...\n 'can be either event- or epoch related, the only distinction is the duration ',...\n 'of the underlying input or stimulus function. Mathematically they are both ',...\n 'modeled by convolving a series of delta (stick) or box functions (u), ',...\n 'indicating the onset of an event or epoch with a set of basis ',...\n 'functions. These basis functions model the hemodynamic convolution, ',...\n 'applied by the brain, to the inputs. This convolution can be first-order ',...\n 'or a generalized convolution modeled to second order (if you specify the ',...\n 'Volterra option). The same inputs are used by the Hemodynamic model or ',...\n 'Dynamic Causal Models which model the convolution explicitly in terms of ',...\n 'hidden state variables. '];\np4=['Basis functions can be used to plot estimated responses to single events ',...\n 'once the parameters (i.e. basis function coefficients) have ',...\n 'been estimated. The importance of basis functions is that they provide ',...\n 'a graceful transition between simple fixed response models (like the ',...\n 'box-car) and finite impulse response (FIR) models, where there is one ',...\n 'basis function for each scan following an event or epoch onset. The ',...\n 'nice thing about basis functions, compared to FIR models, is that data ',...\n 'sampling and stimulus presentation does not have to be synchronized ',...\n 'thereby allowing a uniform and unbiased sampling of peri-stimulus time.'];\np5 = [...\n 'Event-related designs may be stochastic or deterministic. Stochastic ',...\n 'designs involve one of a number of trial-types occurring with a ',...\n 'specified probability at successive intervals in time. These ',...\n 'probabilities can be fixed (stationary designs) or time-dependent ',...\n '(modulated or non-stationary designs). The most efficient designs ',...\n 'obtain when the probabilities of every trial type are equal. ',...\n 'A critical issue in stochastic designs is whether to include null events ',...\n 'If you wish to estimate the evoked response to a specific event ',...\n 'type (as opposed to differential responses) then a null event must be ',...\n 'included (even if it is not modeled explicitly).'];\np6 = [...\n 'In SPM, analysis of data from multiple subjects typically proceeds in two stages ',...\n 'using models at two ''levels''. The ''first level'' models are used to ',...\n 'implement a within-subject analysis. Typically there will be as many first ',...\n 'level models as there are subjects. Analysis proceeds as described using the ',...\n '''Specify first level'' and ''Estimate'' options. The results of these analyses ',...\n 'can then be presented as ''case studies''. More often, however, one wishes to ',...\n 'make inferences about the population from which the subjects were drawn. This is ',...\n 'an example of a ''Random-Effects (RFX) analysis'' (or, more properly, a mixed-effects ',...\n 'analysis). In SPM, RFX analysis is implemented using the ''summary-statistic'' ',...\n 'approach where contrast images from each subject are used as summary ',...\n 'measures of subject responses. These are then entered as data into a ''second level'' ',...\n 'model. '];\nconf.help = {p1,'',p2,'',p3,'',p4,'',p5,'',p6};\n\nreturn;\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\n% COMMENTED OUT BY DRG. I THINK THIS SUB-FUNCTION WAS A HOLDOVER FROM AN\n% EARLY VERSION OF THIS FILE. PLEASE REMOVE IF REALLY NOT USED. ALSO REMOVE\n% REFERENCE ON LINE 523 (COMMENTED OUT) TO CHECK_DIR\n% function t = check_dir(job)\n% t = {};\n%d = pwd;\n%try,\n% cd(job.dir{1});\n%catch,\n% t = {['Cannot Change to directory \"' job.dir{1} '\".']};\n%end;\n\n%disp('Checking...');\n%disp(fullfile(job.dir{1},'SPM.mat'));\n\n% Should really include a check for a \"virtual\" SPM.mat\n%if exist(fullfile(job.dir{1},'SPM.mat'),'file'),\n% t = {'SPM files exist in the analysis directory.'};\n%end;\n%return;\n% END COMMENTED OUT BY DRG\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\n\nfunction t = cond_check(job)\nt = {};\nif (numel(job.onset) ~= numel(job.duration)) && (numel(job.duration)~=1),\n t = {sprintf('\"%s\": Number of event onsets (%d) does not match the number of durations (%d).',...\n job.name, numel(job.onset),numel(job.duration))};\nend;\nfor i=1:numel(job.pmod),\n if numel(job.onset) ~= numel(job.pmod(i).param),\n t = {t{:}, sprintf('\"%s\" & \"%s\":Number of event onsets (%d) does not equal the number of parameters (%d).',...\n job.name, job.pmod(i).name, numel(job.onset),numel(job.pmod(i).param))};\n end;\nend;\nreturn;\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\n\nfunction t = sess_check(sess)\nt = {};\nfor i=1:numel(sess.regress),\n if numel(sess.scans) ~= numel(sess.regress(i).val),\n t = {t{:}, sprintf('Num scans (%d) ~= Num regress[%d] (%d).',numel(sess.scans),i,numel(sess.regress(i).val))};\n end;\nend;\nreturn;\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\nfunction my_cd(varargin)\n% jobDir must be the actual directory to change to, NOT the job structure.\njobDir = varargin{1};\nif ~isempty(jobDir)\n try\n cd(char(jobDir));\n fprintf('Changing directory to: %s\\n',char(jobDir));\n catch\n error('Failed to change directory. Aborting run.')\n end\nend\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction run_stats(job)\n% Set up the design matrix and run a design.\n\nspm_defaults;\nglobal defaults\ndefaults.modality='FMRI';\n\noriginal_dir = pwd;\nmy_cd(job.dir);\n\n%-Ask about overwriting files from previous analyses...\n%-------------------------------------------------------------------\nif exist(fullfile(job.dir{1},'SPM.mat'),'file')\n str = {\t'Current directory contains existing SPM file:',...\n 'Continuing will overwrite existing file!'};\n if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);\n fprintf('%-40s: %30s\\n\\n',...\n 'Abort... (existing SPM file)',spm('time'));\n return\n end\nend\n\n% If we've gotten to this point we're committed to overwriting files.\n% Delete them so we don't get stuck in spm_spm\n%------------------------------------------------------------------------\nfiles = {'^mask\\..{3}$','^ResMS\\..{3}$','^RPV\\..{3}$',...\n '^beta_.{4}\\..{3}$','^con_.{4}\\..{3}$','^ResI_.{4}\\..{3}$',...\n '^ess_.{4}\\..{3}$', '^spm\\w{1}_.{4}\\..{3}$'};\n\nfor i=1:length(files)\n j = spm_select('List',pwd,files{i});\n for k=1:size(j,1)\n spm_unlink(deblank(j(k,:)));\n end\nend\n\n% Variables\n%-------------------------------------------------------------\nSPM.xY.RT = job.timing.RT;\nSPM.xY.P = [];\n\n% Slice timing\ndefaults.stats.fmri.t=job.timing.fmri_t;\ndefaults.stats.fmri.t0=job.timing.fmri_t0;\n\n% Basis function variables\n%-------------------------------------------------------------\nSPM.xBF.UNITS = job.timing.units;\nSPM.xBF.dt = job.timing.RT/defaults.stats.fmri.t;\nSPM.xBF.T = defaults.stats.fmri.t;\nSPM.xBF.T0 = defaults.stats.fmri.t0;\n\n% Basis functions\n%-------------------------------------------------------------\nif strcmp(fieldnames(job.bases),'hrf')\n if all(job.bases.hrf.derivs == [0 0])\n SPM.xBF.name = 'hrf';\n elseif all(job.bases.hrf.derivs == [1 0])\n SPM.xBF.name = 'hrf (with time derivative)';\n elseif all(job.bases.hrf.derivs == [1 1])\n SPM.xBF.name = 'hrf (with time and dispersion derivatives)';\n else\n error('Unrecognized hrf derivative choices.')\n end\nelse\n nambase = fieldnames(job.bases);\n if ischar(nambase)\n nam=nambase;\n else\n nam=nambase{1};\n end\n switch nam,\n case 'fourier',\n SPM.xBF.name = 'Fourier set';\n case 'fourier_han',\n SPM.xBF.name = 'Fourier set (Hanning)';\n case 'gamma',\n SPM.xBF.name = 'Gamma functions';\n case 'fir',\n SPM.xBF.name = 'Finite Impulse Response';\n otherwise\n error('Unrecognized hrf derivative choices.')\n end\n SPM.xBF.length = job.bases.(nam).length;\n SPM.xBF.order = job.bases.(nam).order;\nend\nSPM.xBF = spm_get_bf(SPM.xBF);\nif isempty(job.sess),\n SPM.xBF.Volterra = false;\nelse\n SPM.xBF.Volterra = job.volt;\nend;\n\nfor i = 1:numel(job.sess),\n sess = job.sess(i);\n\n % Image filenames\n %-------------------------------------------------------------\n SPM.nscan(i) = size(sess.scans,1);\n SPM.xY.P = strvcat(SPM.xY.P,sess.scans{:});\n U = [];\n\n % Augment the singly-specified conditions with the multiple\n % conditions specified in a .mat file provided by the user\n %------------------------------------------------------------\n if ~isempty(sess.multi{1})\n try\n multicond = load(sess.multi{1});\n catch\n error('Cannot load %s',sess.multi{1});\n end\n if ~(isfield(multicond,'names')&&isfield(multicond,'onsets')&&...\n\t isfield(multicond,'durations')) || ...\n\t\t~all([numel(multicond.names),numel(multicond.onsets), ...\n\t\t numel(multicond.durations)]==numel(multicond.names))\n error(['Multiple conditions MAT-file ''%s'' is invalid.\\n',...\n\t\t 'File must contain names, onsets, and durations '...\n\t\t 'cell arrays of equal length.\\n'],sess.multi{1});\n end\n\t\n %-contains three cell arrays: names, onsets and durations\n for j=1:length(multicond.onsets)\n cond.name = multicond.names{j};\n cond.onset = multicond.onsets{j};\n cond.duration = multicond.durations{j};\n \n % ADDED BY DGITELMAN\n % Mutiple Conditions Time Modulation\n %------------------------------------------------------\n % initialize the variable.\n cond.tmod = 0;\n if isfield(multicond,'tmod');\n try\n cond.tmod = multicond.tmod{j};\n catch\n error('Error specifying time modulation.');\n end\n end\n\n % Mutiple Conditions Parametric Modulation\n %------------------------------------------------------\n % initialize the parametric modulation variable.\n cond.pmod = [];\n if isfield(multicond,'pmod')\n % only access existing modulators\n try\n % check if there is a parametric modulator. this allows\n % pmod structures with fewer entries than conditions.\n % then check whether any cells are filled in.\n if (j <= numel(multicond.pmod)) && ...\n ~isempty(multicond.pmod(j).name)\n\n % we assume that the number of cells in each\n % field of pmod is the same (or should be).\n for ii = 1:numel(multicond.pmod(j).name)\n cond.pmod(ii).name = multicond.pmod(j).name{ii};\n cond.pmod(ii).param = multicond.pmod(j).param{ii};\n cond.pmod(ii).poly = multicond.pmod(j).poly{ii};\n end\n end;\n catch\n error('Error specifying parametric modulation.');\n end\n end\n sess.cond(end+1) = cond;\n end\n end\n\n % Configure the input structure array\n %-------------------------------------------------------------\n for j = 1:length(sess.cond),\n cond = sess.cond(j);\n U(j).name = {cond.name};\n U(j).ons = cond.onset(:);\n U(j).dur = cond.duration(:);\n if length(U(j).dur) == 1\n U(j).dur = U(j).dur*ones(size(U(j).ons));\n elseif length(U(j).dur) ~= length(U(j).ons)\n error('Mismatch between number of onset and number of durations.')\n end\n\n P = [];\n q1 = 0;\n if cond.tmod>0,\n % time effects\n P(1).name = 'time';\n P(1).P = U(j).ons*job.timing.RT;\n P(1).h = cond.tmod;\n q1 = 1;\n end;\n if ~isempty(cond.pmod)\n for q = 1:numel(cond.pmod),\n % Parametric effects\n q1 = q1 + 1;\n P(q1).name = cond.pmod(q).name;\n P(q1).P = cond.pmod(q).param(:);\n P(q1).h = cond.pmod(q).poly;\n end;\n end\n if isempty(P)\n P.name = 'none';\n P.h = 0;\n end\n U(j).P = P;\n\n end\n\n SPM.Sess(i).U = U;\n\n\n % User specified regressors\n %-------------------------------------------------------------\n C = [];\n Cname = cell(1,numel(sess.regress));\n for q = 1:numel(sess.regress),\n Cname{q} = sess.regress(q).name;\n C = [C, sess.regress(q).val(:)];\n end\n\n % Augment the singly-specified regressors with the multiple regressors\n % specified in the regressors.mat file\n %------------------------------------------------------------\n if ~strcmp(sess.multi_reg,'')\n tmp=load(char(sess.multi_reg{:}));\n if isstruct(tmp) && isfield(tmp,'R')\n R = tmp.R;\n elseif isnumeric(tmp)\n % load from e.g. text file\n R = tmp;\n else\n warning('Can''t load user specified regressors in %s', ...\n char(sess.multi_reg{:}));\n R = [];\n end\n\n C=[C, R];\n nr=size(R,2);\n nq=length(Cname);\n for inr=1:nr,\n Cname{inr+nq}=['R',int2str(inr)];\n end\n end\n SPM.Sess(i).C.C = C;\n SPM.Sess(i).C.name = Cname;\n\nend\n\n% Factorial design\n%-------------------------------------------------------------\nif isfield(job,'fact')\n if ~isempty(job.fact)\n NC=length(SPM.Sess(1).U); % Number of conditions\n CheckNC=1;\n for i=1:length(job.fact)\n SPM.factor(i).name=job.fact(i).name;\n SPM.factor(i).levels=job.fact(i).levels;\n CheckNC=CheckNC*SPM.factor(i).levels;\n end\n if ~(CheckNC==NC)\n disp('Error in fmri_spec job: factors do not match conditions');\n return\n end\n end\nelse\n SPM.factor=[];\nend\n\n% Globals\n%-------------------------------------------------------------\nSPM.xGX.iGXcalc = job.global;\nSPM.xGX.sGXcalc = 'mean voxel value';\nSPM.xGX.sGMsca = 'session specific';\n\n% High Pass filter\n%-------------------------------------------------------------\nfor i = 1:numel(job.sess),\n SPM.xX.K(i).HParam = job.sess(i).hpf;\nend\n\n% Autocorrelation\n%-------------------------------------------------------------\nSPM.xVi.form = job.cvi;\n\n% Let SPM configure the design\n%-------------------------------------------------------------\nSPM = spm_fmri_spm_ui(SPM);\n\nif ~isempty(job.mask)&&~isempty(job.mask{1})\n SPM.xM.VM = spm_vol(job.mask{:});\n SPM.xM.xs.Masking = [SPM.xM.xs.Masking, '+explicit mask'];\nend\n\n%-Save SPM.mat\n%-----------------------------------------------------------------------\nfprintf('%-40s: ','Saving SPM configuration') %-#\nif spm_matlab_version_chk('7') >= 0\n save('SPM','-V6','SPM');\nelse\n save('SPM','SPM');\nend;\n\nfprintf('%30s\\n','...SPM.mat saved') %-#\n\n\nmy_cd(original_dir); % Change back dir\nfprintf('Done\\n')\nreturn\n%-------------------------------------------------------------------------\n\n%-------------------------------------------------------------------------\nfunction vf = vfiles_stats(job)\ndirec = job.dir{1};\nvf = {spm_select('CPath','SPM.mat',direc)};\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_PEB.m", "ext": ".m", "path": "spm5-master/spm_PEB.m", "size": 11436, "source_encoding": "utf_8", "md5": "678306cbfce6892ef9f126270aaaf5f4", "text": "function [C,P,F] = spm_PEB(y,P,OPT)\n% parametric empirical Bayes (PEB) for hierarchical linear models\n% FORMAT [C,P,F] = spm_PEB(y,P,OPT)\n%\n% y - (n x 1) response variable\n%\n% MODEL SPECIFICATION\n%\n% P{i}.X - (n x m) ith level design matrix i.e: constraints on \n% P{i}.C - {q}(n x n) ith level contraints on Cov{e{i}} = Cov{b{i - 1}}\n%\n% OPT - enforces positively constraints on the covariance hyperparameters\n% by adopting a log-normal [flat] hyperprior. default = 0\n%\n% POSTERIOR OR CONDITIONAL ESTIMATES\n%\n% C{i}.E - (n x 1) conditional expectation E{b{i - 1}|y}\n% C{i}.C - (n x n) conditional covariance Cov{b{i - 1}|y} = Cov{e{i}|y}\n% C{i}.M - (n x n) ML estimate of Cov{b{i - 1}} = Cov{e{i}}\n% C{i}.h - (q x 1) ith level ReML hyperparameters for covariance:\n% Cov{e{i}} = P{i}.h(1)*P{i}.C{1} + ...\n%\n% LOG EVIDENCE\n%\n% F - [-ve] free energy F = log evidence = p(y|X,C)\n%\n% If P{i}.C is not a cell the covariance at that level is assumed to be kown\n% and Cov{e{i}} = P{i}.C (i.e. the hyperparameter is fixed at 1)\n%\n% If P{n}.C is not a cell this is taken to indicate that a full Bayesian\n% estimate is required where P{n}.X is the prior expectation and P{n}.C is\n% the known prior covariance. For consistency, with PEB, this is implemented\n% by setting b{n} = 1 through appropriate constraints at level {n + 1}.\n%\n% To implement non-hierarchical Bayes with priors on the parameters use\n% a two level model setting the second level design matrix to zeros.\n%__________________________________________________________________________\n%\n% Returns the moments of the posterior p.d.f. of the parameters of a\n% hierarchical linear observation model under Gaussian assumptions\n%\n% y = X{1}*b{1} + e{1}\n% b{1} = X{2}*b{2} + e{2}\n% ...\n%\n% b{n - 1} = X{n}*b{n} + e{n}\n%\n% e{n} ~ N{0,Ce{n}}\n%\n% using Parametic Emprical Bayes (PEB)\n%\n% Ref: Dempster A.P., Rubin D.B. and Tsutakawa R.K. (1981) Estimation in\n% covariance component models. J. Am. Stat. Assoc. 76;341-353\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Karl Friston\n% $Id: spm_PEB.m 587 2006-08-07 04:38:22Z Darren $\n\n% set default\n%--------------------------------------------------------------------------\ntry\n OPT;\ncatch\n OPT = 0;\nend\n\n% number of levels (p)\n%--------------------------------------------------------------------------\nM = 32; % maximum number of iterations\np = length(P);\n\n% check covariance constraints - assume i.i.d. errors conforming to X{i}\n%--------------------------------------------------------------------------\nfor i = 1:p\n if ~isfield(P{i},'C')\n [n m] = size(P{i}.X);\n if i == 1\n P{i}.C = {speye(n,n)};\n else\n for j = 1:m\n k = find(P{i}.X(:,j));\n P{i}.C{j} = sparse(k,k,1,n,n);\n end\n end\n end\n\nend\n\n% Construct augmented non-hierarchical model\n%==========================================================================\n\n% design matrix and indices\n%--------------------------------------------------------------------------\nI = {0};\nJ = {0};\nK = {0};\nXX = [];\nX = 1;\nfor i = 1:p\n\n % design matrix\n %----------------------------------------------------------------------\n X = X*P{i}.X;\n XX = [XX X];\n\n % indices for ith level parameters\n %----------------------------------------------------------------------\n [n m] = size(P{i}.X);\n I{i} = [1:n] + I{end}(end);\n J{i} = [1:m] + J{end}(end);\n\nend\n\n% augment design matrix and data\n%--------------------------------------------------------------------------\nn = size(XX,2);\nXX = [XX; speye(n,n)];\ny = [y; sparse(n,1)];\n\n% last level constraints\n%--------------------------------------------------------------------------\nn = size(P{p}.X,2);\nI{p + 1} = [1:n] + I{end}(end);\nq = I{end}(end);\nCb = sparse(q,q);\nif ~iscell(P{end}.C)\n\n % Full Bayes: (i.e. Cov(b) = 0, = 1)\n %----------------------------------------------------------------------\n y( I{end}) = sparse(1:n,1,1);\nelse\n\n % Empirical Bayes: uniform priors (i.e. Cov(b) = Inf, = 0)\n %----------------------------------------------------------------------\n Cb(I{end},I{end}) = sparse(1:n,1:n,exp(32));\nend\n\n\n% assemble augmented constraints Q: Cov{e} = Cb + h(i)*Q{i} + ...\n%==========================================================================\nif ~isfield(P{1},'Q')\n\n % covariance contraints Q on Cov{e{i}} = Cov{b{i - 1}}\n %----------------------------------------------------------------------\n h = [];\n Q = {};\n for i = 1:p\n\n % collect constraints on prior covariances - Cov{e{i}}\n %------------------------------------------------------------------\n if iscell(P{i}.C)\n m = length(P{i}.C);\n for j = 1:m\n [u v s] = find(P{i}.C{j});\n u = u + I{i}(1) - 1;\n v = v + I{i}(1) - 1;\n Q{end + 1} = sparse(u,v,s,q,q);\n end\n\n % indices for ith-level hyperparameters\n %--------------------------------------------------------------\n try\n K{i} = [1:m] + K{end}(end);\n catch\n K{i} = [1:m];\n end\n\n else\n\n % unless they are known - augment Cb\n %--------------------------------------------------------------\n [u v s] = find(P{i}.C + speye(length(P{i}.C))*1e-6);\n u = u + I{i}(1) - 1;\n v = v + I{i}(1) - 1;\n Cb = Cb + sparse(u,v,s,q,q);\n\n % indices for ith-level hyperparameters\n %--------------------------------------------------------------\n K{i} = [];\n\n end\n\n end\n\n % note overlapping bases - requiring 2nd order M-Step derivatives\n %----------------------------------------------------------------------\n m = length(Q);\n d = sparse(m,m);\n for i = 1:m\n XQX{i} = XX'*Q{i}*XX;\n end\n for i = 1:m\n for j = i:m\n o = nnz(XQX{i}*XQX{j});\n d(i,j) = o;\n d(j,i) = o;\n end\n end\n\n % log-transform and save\n %----------------------------------------------------------------------\n h = zeros(m,1);\n if OPT\n hP = speye(m,m)/16;\n else\n hP = speye(m,m)/exp(16);\n for i = 1:m\n h(i) = any(diag(Q{i}));\n end\n end\n P{1}.hP = hP;\n P{1}.Cb = Cb;\n P{1}.Q = Q;\n P{1}.h = h;\n P{1}.K = K;\n P{1}.d = d;\n\nend\nhP = P{1}.hP;\nCb = P{1}.Cb;\nQ = P{1}.Q;\nh = P{1}.h;\nK = P{1}.K;\nd = P{1}.d;\n\n% Iterative EM\n%--------------------------------------------------------------------------\nm = length(Q);\ndFdh = zeros(m,1);\ndFdhh = zeros(m,m);\nfor k = 1:M\n\n % inv(Cov(e)) - iC(h)\n %----------------------------------------------------------------------\n Ce = Cb;\n for i = 1:m\n if OPT\n Ce = Ce + Q{i}*exp(h(i));\n else\n Ce = Ce + Q{i}*h(i);\n end\n end\n iC = spm_inv(Ce);\n\n % E-step: conditional mean E{B|y} and covariance cov(B|y)\n %======================================================================\n iCX = iC*XX;\n Cby = spm_inv(XX'*iCX);\n B = Cby*(iCX'*y);\n\n\n % M-step: ReML estimate of hyperparameters (if m > 0)\n %======================================================================\n if m == 0, break, end\n\n % Gradient dF/dh (first derivatives)\n %----------------------------------------------------------------------\n Py = iC*(y - XX*B);\n iCXC = iCX*Cby;\n\n for i = 1:m\n\n % dF/dh = -trace(dF/diC*iC*Q{i}*iC)\n %------------------------------------------------------------------\n PQ{i} = iC*Q{i} - iCXC*(iCX'*Q{i});\n if OPT\n PQ{i} = PQ{i}*exp(h(i));\n end\n dFdh(i) = -trace(PQ{i})/2 + y'*PQ{i}*Py/2;\n\n end\n\n % Expected curvature E{ddF/dhh} (second derivatives)\n %----------------------------------------------------------------------\n for i = 1:m\n for j = i:m\n if d(i,j)\n\n % ddF/dhh = -trace{P*Q{i}*P*Q{j}}\n %----------------------------------------------------------\n dFdhh(i,j) = -sum(sum(PQ{i}.*PQ{j}'))/2;\n dFdhh(j,i) = dFdhh(i,j);\n\n end\n end\n end\n\n % add hyperpriors\n %----------------------------------------------------------------------\n dFdhh = dFdhh - hP;\n \n % Fisher scoring: update dh = -inv(ddF/dhh)*dF/dh\n %----------------------------------------------------------------------\n dh = -pinv(dFdhh)*dFdh;\n h = h + dh;\n\n % Convergence\n %======================================================================\n w = norm(dh,1);\n% fprintf('%-30s: %i %30s%e\\n',' PEB Iteration',k,'...',full(w));\n \n % if dF < 0.01\n %----------------------------------------------------------------------\n if dFdh'*dh < 1e-2, break, end\n \n % if dh^2 < 1e-8\n %----------------------------------------------------------------------\n if w < 1e-4, break, end\n \n % if log-normal hyperpriors and h < exp(-16)\n %----------------------------------------------------------------------\n if OPT && h < -16, break, end\n\nend\n\n% place hyperparameters in P{1} and output structure for {n + 1}\n%--------------------------------------------------------------------------\nP{1}.h = h + exp(-32);\nC{p + 1}.E = B(J{p});\nC{p + 1}.M = Cb(I{end},I{end});\n\n% recursive computation of conditional means E{b|y}\n%--------------------------------------------------------------------------\nfor i = p:-1:2\n C{i}.E = B(J{i - 1}) + P{i}.X*C{i + 1}.E;\nend\n\n% hyperpriors - precision\n%--------------------------------------------------------------------------\nif OPT\n h = exp(h);\nend\n\n% conditional covariances Cov{b|y} and ReML esimtates of Ce{i) = Cb{i - 1}\n%--------------------------------------------------------------------------\nfor i = 1:p\n C{i + 1}.C = Cby(J{i},J{i});\n C{i}.M = Ce(I{i},I{i});\n C{i}.h = h(K{i});\nend\n\n% log evidence = ln p(y|X,C) = F = [-ve] free energy\n%--------------------------------------------------------------------------\nif nargout > 2\n\n % condotional covariance of h\n %----------------------------------------------------------------------\n Ph = -dFdhh;\n\n % log evidence = F\n %----------------------------------------------------------------------\n F = - Py'*Ce*Py/2 ...\n - length(I{1})*log(2*pi)/2 ...\n - spm_logdet(Ce)/2 ...\n - spm_logdet(Ph)/2 ...\n + spm_logdet(hP)/2 ...\n + spm_logdet(Cby)/2;\nend\n\n% warning\n%--------------------------------------------------------------------------\nif k == M, warning('maximum number of iterations exceeded'), end\n\nreturn\n\nfunction [C] = spm_inv(C);\n% inversion of sparse matrices\n%__________________________________________________________________________\n\nC = inv(C + speye(length(C))*exp(-32));\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_firstlevel.m", "ext": ".m", "path": "spm5-master/spm_eeg_firstlevel.m", "size": 15017, "source_encoding": "utf_8", "md5": "fbadc26bae89a983d0b0adc9205ff7dd", "text": "function varargout = spm_eeg_firstlevel(varargin)\n% SPM_EEG_FIRSTLEVEL M-file for spm_eeg_firstlevel.fig\n% SPM_EEG_FIRSTLEVEL, by itself, creates a new SPM_EEG_FIRSTLEVEL or raises the existing\n% singleton*.\n%\n% H = SPM_EEG_FIRSTLEVEL returns the handle to a new SPM_EEG_FIRSTLEVEL or the handle to\n% the existing singleton*.\n%\n% SPM_EEG_FIRSTLEVEL('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SPM_EEG_FIRSTLEVEL.M with the given input arguments.\n%\n% SPM_EEG_FIRSTLEVEL('Property','Value',...) creates a new SPM_EEG_FIRSTLEVEL or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before spm_eeg_firstlevel_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to spm_eeg_firstlevel_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Copyright 2002-2003 The MathWorks, Inc.\n\n% Edit the above text to modify the response to help spm_eeg_firstlevel\n\n% Last Modified by GUIDE v2.5 02-Feb-2006 16:29:08\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @spm_eeg_firstlevel_OpeningFcn, ...\n 'gui_OutputFcn', @spm_eeg_firstlevel_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before spm_eeg_firstlevel is made visible.\nfunction spm_eeg_firstlevel_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to spm_eeg_firstlevel (see VARARGIN)\n\n% Choose default command line output for spm_eeg_firstlevel\nhandles.output = hObject;\n\nhandles.con_types = {};\nhandles.Nt = 0;\nset(handles.listbox1, 'String', {});\nset(handles.listbox2, 'String', {});\n\nspm_defaults;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes spm_eeg_firstlevel wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = spm_eeg_firstlevel_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on selection change in listbox1.\nfunction listbox1_Callback(hObject, eventdata, handles)\n% hObject handle to listbox1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = get(hObject,'String') returns listbox1 contents as cell array\n% contents{get(hObject,'Value')} returns selected item from listbox1\n\n\n% --- Executes during object creation, after setting all properties.\nfunction listbox1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to listbox1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: listbox controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in listbox2.\nfunction listbox2_Callback(hObject, eventdata, handles)\n% hObject handle to listbox2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = get(hObject,'String') returns listbox2 contents as cell array\n% contents{get(hObject,'Value')} returns selected item from listbox2\n\n\n% --- Executes during object creation, after setting all properties.\nfunction listbox2_CreateFcn(hObject, eventdata, handles)\n% hObject handle to listbox2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: listbox controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in addfile.\nfunction addfile_Callback(hObject, eventdata, handles)\n% hObject handle to addfile (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n[filename, pathname, filterindex] = uigetfile('*.img', 'Select an image');\n\nif filename == 0, return, end\n\n[status, Iimg, Limg] = spm_eeg_firstlevel_checkfile(fullfile(pathname, filename), handles.Nt);\n\nif status == 0\n errordlg(sprintf('Can''t add: new file has %d time points, selected have %d', Limg, handles.Nt));\n return\nelse\n handles.Nt = status;\nend\n\n% add image to list\nset(handles.listbox1, 'String', [get(handles.listbox1, 'String'); {fullfile(pathname, filename)}]);\n\nset(handles.Dfile, 'Enable', 'on');\n\n% Update handles structure\nguidata(hObject, handles);\n\n% --- Executes on button press in removefile.\nfunction removefile_Callback(hObject, eventdata, handles)\n% hObject handle to removefile (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nif length(get(handles.listbox1, 'String')) == 0, return, end\n\nind = get(handles.listbox1, 'Value');\ntmp = get(handles.listbox1, 'String');\ntmp(ind) = [];\nset(handles.listbox1, 'Value', max(1, ind-1));\nset(handles.listbox1, 'String', tmp);\n\n% user removed all files?\nif length(get(handles.listbox1, 'String')) == 0\n handles.Nt = 0;\n set(handles.Dfile, 'Enable', 'off');\n set(handles.Dfile, 'String', 'Select SPM M/EEG file');\n handles.Dfilename = [];\n set(handles.mstext, 'String', []);\nend\n\n% Update handles structure\nguidata(hObject, handles);\n\n% --- Executes on button press in addcontrast.\nfunction addcontrast_Callback(hObject, eventdata, handles)\n% hObject handle to addcontrast (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% averages only (add more options soon)\ns = inputdlg({'from', 'to'}, 'Specify peri-stimulus time window for average [ms]');\n\nfrom = str2num(s{1});\nto = str2num(s{2});\n\nstrname = sprintf('Average from %d to %d ms', from, to);\n\n% checks\nif from < handles.ms(1)\n errordlg(sprintf('Start of time window must be later than %d ms.', handles.ms(1)));\n return;\nend\n\nif to > handles.ms(2)\n errordlg(sprintf('End of time window must be earlier than %d ms.', handles.ms(2)));\n return;\nend\n\nif from > to\n errordlg('Start of time window must be earlier than its end.');\n return;\nend\n\n% add contrast to list\nset(handles.listbox2, 'String', [get(handles.listbox2, 'String'); {strname}]);\n\nhandles.con_types = cat(1, handles.con_types, {'average', from, to});\n\nset(handles.compute, 'Enable', 'on');\n\n% Update handles structure\nguidata(hObject, handles);\n\n% --- Executes on button press in removecontrast.\nfunction removecontrast_Callback(hObject, eventdata, handles)\n% hObject handle to removecontrast (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nif length(get(handles.listbox2, 'String')) == 0, return, end\n\nind = get(handles.listbox2, 'Value');\ntmp = get(handles.listbox2, 'String');\ntmp(ind) = [];\nhandles.con_types(ind) = [];\nset(handles.listbox2, 'Value', max(1, ind-1));\nset(handles.listbox2, 'String', tmp);\n\n% user removed all contrasts?\nif length(get(handles.listbox2, 'String')) == 0\n handles.con_types = {};\n set(handles.compute, 'Enable', 'off');\nend\n\n% Update handles structure\nguidata(hObject, handles);\n\n\n% --- Executes on button press in compute.\nfunction compute_Callback(hObject, eventdata, handles)\n% hObject handle to compute (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% make sure images are not flipped\nglobal defaults\ndefaults.analyze.flip = 0;\n\ncon_types = handles.con_types;\nD = handles.D;\n\nms = 1000/D.Radc*[-D.events.start:D.events.stop];\n\n% assemble contrast vectors into matrix\nfor i = 1:size(handles.con_types, 1)\n c = zeros(handles.Nt, 1);\n \n if strcmp(con_types(i, 1), 'average')\n % window in time points\n [tmp, tp(1)] = min((ms-con_types{i, 2}).^2);\n [tmp, tp(2)] = min((ms-con_types{i, 3}).^2);\n\n c(tp(1):tp(2)) = 1./(tp(2)-tp(1)+1);\n C(:,i) = c;\n end\n \nend\nfnames = get(handles.listbox1, 'String');\n\nspm('Pointer', 'Watch');drawnow\n\n% compute and write contrast images\nfor j = 1:size(fnames, 1); % over files\n \n % map file \n Vbeta = nifti(deblank(fnames{j})); \n \n % cd to target directory\n [path, f] = fileparts(fnames{j});\n cd(path);\n \n for i = 1:size(C, 2) % over contrasts\n \n % code taken from spm_contrasts\n fprintf('\\t%-32s: %-10s%20s', sprintf('file %s, contrast %d', fnames{j}, i),...\n '(spm_add)','...initialising') %-#\n\n %-Prepare handle for contrast image\n %-----------------------------------------------------------\n if strcmp(con_types{i, 1}, 'average')\n descrip = sprintf('SPM contrast - average from %d to %d ms',...\n con_types{i, 2}, con_types{i, 3});\n else\n descrip = sprintf('SPM contrast - %d: %s', i, con_type{i, 1});\n end\n \n % prepare nifti image (the usual spm_add doesn't seem to work for\n % many input files under windows)\n Vcon = nifti;\n Vcon.descrip = descrip;\n\n Dcon = file_array;\n Dcon.fname = sprintf('%s_con_%04d.img', f, i);\n Dcon.dtype = spm_type('float32');\n Dcon.offset = ceil(348/8)*8;\n Dcon.dim = Vbeta.dat.dim(1:3);\n\n Vcon.dat = Dcon;\n \n %-Write image\n %-----------------------------------------------------------\n fprintf('%s%20s', repmat(sprintf('\\b'),1,20),'...computing')%-#\n\n % replace loop by one line if possible\n d = zeros(Vbeta.dat.dim(1:3));\n for k = 1:Vbeta.dat.dim(4)\n d = d + Vbeta.dat(:,:,:, k)*C(k,i);\n end\n \n if Vbeta.dat.dim(3) == 1\n Dcon(:,:) = d;\n else\n Dcon.dat(:,:,:) = d;\n end\n \n Vcon.dat = Dcon;\n create(Vcon);\n \n\n fprintf('%s%30s\\n',repmat(sprintf('\\b'),1,30),sprintf(...\n '...written %s',spm_str_manip(Vcon.dat.fname,'t')))%-#\n\n\n end\nend\n\nspm('Pointer', 'Arrow');\n\n% --- Executes on button press in Dfile.\nfunction Dfile_Callback(hObject, eventdata, handles)\n% hObject handle to Dfile (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n[filename, pathname, filterindex] = uigetfile('*.mat', 'Select a SPM M/EEG file');\n\ntry\n D = spm_eeg_ldata(fullfile(pathname, filename));\ncatch\n errordlg('Selected file isn''t a valid SPM M/EEG file.')\n return;\nend\n\ntry\n D.Nsamples;\ncatch\n errordlg('Selected file isn''t a valid SPM M/EEG file.')\n return;\nend\n\nif D.Nsamples ~= handles.Nt\n errordlg(sprintf('Number of time points (%d) different from images (%d).', D.Nsamples, handles.Nt))\n return;\nend\n\n% Dfile is valid\nhandles.Dfilename = fullfile(pathname, filename);\nhandles.D = D;\nset(handles.listbox2, 'Enable', 'on');\nset(handles.addcontrast, 'Enable', 'on');\nset(handles.removecontrast, 'Enable', 'on');\nset(handles.clearcontrasts, 'Enable', 'on');\nhandles.ms = 1000/D.Radc*[-D.events.start D.events.stop];\nset(handles.mstext, 'Enable', 'on');\nset(handles.mstext, 'String', ...\n sprintf('%d to %d ms, %d time points, %.2f ms steps', ...\n handles.ms(1), handles.ms(2), handles.Nt, 1000/D.Radc));\nset(handles.Dfile, 'String', handles.Dfilename);\n \n% Update handles structure\nguidata(hObject, handles);\n\n\n\n% --- Executes on button press in adddir.\nfunction adddir_Callback(hObject, eventdata, handles)\n% hObject handle to adddir (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nd = uigetdir(pwd, 'Select a directory to search for SPM M/EEG-files');\n\nif d == 0, return, end;\n\n[flist] = spm_eeg_firstlevel_searchdir(d, []);\n\nspm('Pointer', 'Watch'); drawnow;\n\n% check for these files that length (time) is the same\nfor i = 1:size(flist,1)\n \n [status, Iimg, Limg] = spm_eeg_firstlevel_checkfile(flist(i,:), handles.Nt);\n\n % suppress error warning that file in list is of unequal length\n\n if status ~= 0\n % add image to list\n set(handles.listbox1, 'String', [get(handles.listbox1, 'String'); {deblank(flist(i, :))}]);\n set(handles.Dfile, 'Enable', 'on'); drawnow;\n handles.Nt = status;\n end\n \n drawnow;\nend\n\nspm('Pointer', 'Arrow');\n\n% Update handles structure\nguidata(hObject, handles);\n\n\n\n\n\n% --- Executes on button press in clearfiles.\nfunction clearfiles_Callback(hObject, eventdata, handles)\n% hObject handle to clearfiles (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nset(handles.listbox1, 'String', []);\n\nhandles.Nt = 0;\nset(handles.Dfile, 'Enable', 'off');\nset(handles.Dfile, 'String', 'Select SPM M/EEG file');\nhandles.Dfilename = [];\nset(handles.mstext, 'String', []);\n\n% Update handles structure\nguidata(hObject, handles);\n\n\n\n% --- Executes on button press in clearcontrasts.\nfunction clearcontrasts_Callback(hObject, eventdata, handles)\n% hObject handle to clearcontrasts (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nset(handles.listbox2, 'String', []);\n\nhandles.con_types = {};\nset(handles.compute, 'Enable', 'off');\n\n% Update handles structure\nguidata(hObject, handles);\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "ctf_read_res4.m", "ext": ".m", "path": "spm5-master/ctf_read_res4.m", "size": 17494, "source_encoding": "utf_8", "md5": "ab874b345fc22ebc68b64b816b438ef9", "text": "function [ctf] = ctf_read_res4(folder,VERBOSE,COEFS);\n\n% ctf_read_res4 - Read a CTF .res4 file\n%\n% ctf = ctf_read_res4( [folder], [verbose], [coefs])\n% \n% This function reads the resource information from a CTF .ds folder. This\n% resource information must be read before reading the .meg4 data file.\n% All input arguments are optional.\n%\n% INPUTS\n%\n% folder: the .ds directory containing the data to be read. With\n% no input, it will prompt with a gui folder locator.\n%\n% verbose: If verbose = 1, display 'ctf.setup' structure (default)\n% If verbose = 0, do not display 'ctf.setup' structure\n%\n% coefs: an option to read the sensory coefficients, which give the\n% weights for calculation of synthetic 2nd or 3rd order\n% gradiometers.\n% If coefs = 1, read the sensor coefficients\n% If coefs = 0, do not read the sensor coefficients (default)\n% \n% OUTPUTS\n%\n% ctf.folder - path of the .ds folder\n%\n% ctf.res4.file - data file path/name\n% ctf.res4.header - data format header\n%\n% ctf.setup - a header structure consisting of date, time, run name, run\n% title, subject, run description, operator, number of channels, number\n% of samples, sample rate, number of trials, duration, pretrigger_samples,\n% sensor filename, head zeroing, and number of filters.\n% \n% ctf.sensor.index - a sensor structure consisting of EEG sensors, MEG\n% sensors, reference sensors, and other sensors.\n% \n% ctf.sensor.info - a structure with gain and offset information consisting\n% of proper gain, Q gain, io gain, io offset, and index.\n%\n% <>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n% < >\n% < DISCLAIMER: >\n% < >\n% < THIS PROGRAM IS INTENDED FOR RESEARCH PURPOSES ONLY. >\n% < THIS PROGRAM IS IN NO WAY INTENDED FOR CLINICAL OR >\n% < OFFICIAL USE. >\n% < >\n% <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>\n%\n\n% $Revision: 253 $ $Date: 2004/08/19 03:17:10 $\n\n% Copyright (C) 2003 Darren L. Weber\n% \n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n% Modified: 11/2003, Darren.Weber_at_radiology.ucsf.edu\n% - modified from NIH code readresfile.m\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nver = '$Revision: 253 $';\nfprintf('\\nCTF_READ_RES4 [v %s]\\n',ver(11:15)); tic;\n\nif ~exist('folder','var'),\n ctf = ctf_folder;\nelse\n ctf = ctf_folder(folder);\nend\n\nif ~exist('VERBOSE','var'), VERBOSE = true; end\nif ~exist('COEFS','var'), COEFS = false; end\n\n[folderPath,folderName,folderExt] = fileparts(ctf.folder);\nctf.res4.file = findres4file(ctf.folder);\n\n%----------------------------------------------------------------\n% open the data file\n\n[fid,message] = fopen(ctf.res4.file,'rb','ieee-be.l64');\nif fid < 0, error('cannot open .res4 file'); end\n\n\n%-------------------------------------------------------------\n% READ HEADER\n\nfseek(fid,0,-1);\nctf.res4.header = char(fread(fid,8,'char'))';\n\n% check for the right format\nif strmatch('MEG41RS',ctf.res4.header),\n % OK, we can handle this format\nelse\n msg = sprintf('This function is designed to read MEG41RS format.\\nIt may not read \"%s\" format correctly',ctf.res4.header);\n warning(msg);\nend\n\n\n%-------------------------------------------------------------\n% READ SETUP\n\n\n%---DATE/TIME\nfseek(fid, 778,-1);\nctf.setup.time = char(fread(fid,255,'char'))';\nfseek(fid,1033,-1);\nctf.setup.date = char(fread(fid,255,'char'))';\n\n%---NUMBER OF SAMPLES\nfseek(fid,1288,-1);\nctf.setup.number_samples = (fread(fid,1,'int32')');\n\n%---NUMBER OF CHANNELS\nfseek(fid,1292,-1);\nctf.setup.number_channels = (fread(fid,1,'int16')');\n\n%---SAMPLE RATE\nfseek(fid,1296,-1);\nctf.setup.sample_rate = fread(fid,1,'double')';\nctf.setup.sample_msec = 1000 / ctf.setup.sample_rate;\nctf.setup.sample_sec = 1 / ctf.setup.sample_rate;\n\n%---NUMBER OF TRIALS\nfseek(fid,1312,-1);\nctf.setup.number_trials = fread(fid,1,'int16')';\nfseek(fid, 776,-1);\nctf.setup.number_trials_averaged = fread(fid,1,'int16');\n\n%---DURATION\nfseek(fid,1304,-1);\nctf.setup.duration_total = fread(fid,1,'double');\nctf.setup.duration_trial = ctf.setup.duration_total / ctf.setup.number_trials;\n\n%---PRE_TRIG POINTS\nfseek(fid,1316,-1);\nctf.setup.pretrigger_samples = fread(fid,1,'int32');\nctf.setup.pretrigger_msec = (ctf.setup.pretrigger_samples / ctf.setup.sample_rate) * 1000;\n\n%---HEAD ZEROING\nfseek(fid,1348,-1);\nh_zero = fread(fid,1,'int32')';\nno_yes = {'no','yes'};\nctf.setup.head_zero = no_yes{h_zero+1};\n\n%---RUN NAME\nfseek(fid,1360,-1);\nctf.setup.run_name = char(fread(fid,32,'char'))';\n\n%---RUN TITLE\nfseek(fid,1392,-1);\nctf.setup.run_title = char(fread(fid,256,'char'))';\n\n%---SUBJECT\nfseek(fid,1712,-1);\nctf.setup.subject = char(fread(fid,32,'char'))';\n\n%---OPERATOR\nfseek(fid,1744,-1);\nctf.setup.operator = char(fread(fid,32,'char'))';\n\n%---SENSOR FILE NAME\nfseek(fid,1776,-1);\nctf.setup.sensor_file_name = char(fread(fid,60,'char'))';\n\n%---RUN DESCRIPTION & FILTERS\nfseek(fid,1836,-1);\nrun_size = fread(fid,1,'int32');\nfseek(fid,1844,-1);\nctf.setup.run_description = char(fread(fid,run_size,'char'));\n\nctf.setup.number_filters = fread(fid,1,'int16');\n\nfor i = 1:ctf.setup.number_filters,\n ctf.setup.filters(i).freq = fread(fid,1,'double');\n ctf.setup.filters(i).class = fread(fid,1,'int32');\n ctf.setup.filters(i).type = fread(fid,1,'int32');\n ctf.setup.filters(i).numparam = fread(fid,1,'int16');\n ctf.setup.filters(i).params = fread(fid,ctf.setup.filters(i).numparam,'double');\nend\n\nif(COEFS)\n b = 1846 + run_size;\n if(ctf.setup.number_filters == 0)\n np = 0;\n else\n np = ctf.setup.filters.numparam;\n warning('3rd gradient + hardware filter parameters not fully tested! let''s see what happens... :)');\n end\n nf = ctf.setup.number_filters;\n f = ( nf * 18 ) + ( np * 8 );\n offset = b + f + ctf.setup.number_channels * 1360;\nend\n\n\n%-------------------------------------------------------------\n% CREATE TIME ARRAYS\n\n% the time arrays must be based on increments of the sample_msec\nctf.setup.time_msec = [0:ctf.setup.number_samples - 1]' * ctf.setup.sample_msec;\nctf.setup.time_msec = ctf.setup.time_msec - ctf.setup.pretrigger_msec;\n\n% adjust the sample point closest to zero so that it is zero, if it\n% is reasonably close to zero, say within 3 decimal places for msec timing\nzero_index = find(abs(ctf.setup.time_msec) == min(abs(ctf.setup.time_msec)));\nzero_value = ctf.setup.time_msec(zero_index);\nif (-0.0001 < zero_value) & (zero_value < 0.0001),\n ctf.setup.time_msec(zero_index) = 0;\nend\n\nctf.setup.start_msec = ctf.setup.time_msec(1);\nctf.setup.end_msec = ctf.setup.time_msec(end);\n\nctf.setup.time_sec = ctf.setup.time_msec / 1000;\nctf.setup.start_sec = ctf.setup.time_sec(1);\nctf.setup.end_sec = ctf.setup.time_sec(end);\n\n\n%-------------------------------------------------------------\n% PRINT SETUP\nif VERBOSE,\n ctf_print_setup(ctf);\nend\n\n\n\n\n\n%-------------------------------------------------------------\n% READ SENSOR INFORMATION\n\nctf.sensor.info = struct(...\n 'proper_gain',[],...\n 'q_gain',[],...\n 'io_gain',[],...\n 'io_offset',[],...\n 'index',[],...\n 'extra',[],...\n 'label',[],...\n 'grad_order_no',[]);\n\n% read channel names (not trivial!)\nfor chan = 1:ctf.setup.number_channels,\n temp = fread(fid,32,'char');\n temp(temp>127) = 0;\n temp(temp<0) = 0;\n temp = strtok(temp,char(0));\n ctf.sensor.info(chan).label = char(temp');\nend\n\nfor chan = 1:ctf.setup.number_channels,\n \n %ftell(fid);\n \n ctf.sensor.info(chan).index = fread(fid,1,'int16');\n ctf.sensor.info(chan).extra = fread(fid,1,'int16');\n id = fread(fid,1,'int32')+1;\n ctf.sensor.info(chan).proper_gain = fread(fid,1,'double');\n ctf.sensor.info(chan).q_gain = fread(fid,1,'double');\n ctf.sensor.info(chan).io_gain = fread(fid,1,'double');\n ctf.sensor.info(chan).io_offset = fread(fid,1,'double');\n fread(fid,1,'int16');\n ctf.sensor.info(chan).grad_order_no = fread(fid,1,'int16');\n fread(fid,1,'int32');\n \n %fseek(fid,ftell(fid)+6,0);\n \n for pos = 1:8,\n ctf.sensor.info(chan).coil(pos).position.x = fread(fid,1,'double');\n ctf.sensor.info(chan).coil(pos).position.y = fread(fid,1,'double');\n ctf.sensor.info(chan).coil(pos).position.z = fread(fid,1,'double');\n fread(fid,1,'double');\n ctf.sensor.info(chan).coil(pos).orient.x = fread(fid,1,'double');\n ctf.sensor.info(chan).coil(pos).orient.y = fread(fid,1,'double');\n ctf.sensor.info(chan).coil(pos).orient.z = fread(fid,1,'double');\n fread(fid,1,'double');\n fread(fid,1,'int16');\n fread(fid,1,'int32');\n fread(fid,1,'int16');\n fread(fid,1,'double');\n \n %fseek(fid,ftell(fid)+56,0);\n %fseek(fid,ftell(fid)-80,0);\n end\n \n for pos = 1:8,\n ctf.sensor.info(chan).hcoil(pos).position.x = fread(fid,1,'double');\n ctf.sensor.info(chan).hcoil(pos).position.y = fread(fid,1,'double');\n ctf.sensor.info(chan).hcoil(pos).position.z = fread(fid,1,'double');\n fread(fid,1,'double');\n ctf.sensor.info(chan).hcoil(pos).orient.x = fread(fid,1,'double');\n ctf.sensor.info(chan).hcoil(pos).orient.y = fread(fid,1,'double');\n ctf.sensor.info(chan).hcoil(pos).orient.z = fread(fid,1,'double');\n fread(fid,1,'double');\n fread(fid,1,'int16');\n fread(fid,1,'int32');\n fread(fid,1,'int16');\n fread(fid,1,'double');\n \n %fseek(fid,ftell(fid)+56,0);\n %fseek(fid,ftell(fid)+80,0);\n end\n %fseek(fid,ftell(fid)+1288,-1);\nend\n\n\n\n\n%-------------------------------------------------------------\n% Find channel types and define channel sets, see the\n% System Administrators .pdf, 'Channel Sets Configuration'\n\nctf = ctf_channel_sets(ctf);\n\n\n\n%-------------------------------------------------------------\n% Channel coordinates, in centimeters, in subject head space\n\nfor chan = 1:ctf.setup.number_channels,\n \n switch ctf.sensor.info(chan).index,\n \n case {0,1,5},\n %0=Reference Magnetometers\n %1=Reference Gradiometers\n %5=MEG Channels\n \n coord = [ctf.sensor.info(chan).hcoil(1:2).position];\n ctf.sensor.info(chan).location = [coord.x; coord.y; coord.z];\n \n orient = [ctf.sensor.info(chan).hcoil(1).orient];\n ctf.sensor.info(chan).orientation = [orient.x; orient.y; orient.z];\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % This ensures that the orientation of the sensor is away from the\n % center of a sphere. It uses the sign of the dot product between\n % the orientation vector and the location vector.\n tmp = ctf.sensor.info(chan).orientation' * ctf.sensor.info(chan).location;\n tmp = sign(tmp(1));\n ctf.sensor.info(chan).orientation = tmp * ctf.sensor.info(chan).orientation;\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n case 9,\n %EEG Channels \n \n coord = [ctf.sensor.info(chan).hcoil(1:2).position];\n ctf.sensor.info(chan).location = [coord.x; coord.y; coord.z];\n ctf.sensor.info(chan).orientation = [];\n \n end\nend\n\n\n\n%%%%%% Coefficient reading appended by SSD %%%%%%\n\nif(COEFS)\n\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t% NUMBER OF COEFFICIENTS, byte offset = b+f+nc*1360, byte size = 1\n\t\n\tfseek(fid,offset,-1);\n\tctf.res4.numberCoefficients = fread(fid,1,'int16');\n\t\n\t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\t% SENSOR COEFFICIENT RECORDS, byte offset = b+f+nc*1360+2, byte size = 1992\n\t\n\tif VERBOSE & ctf.res4.numberCoefficients,\n\t\tfprintf('...reading %d coefficients\\n',ctf.res4.numberCoefficients);\n\tend\n\t\n\tSENSOR_LABEL = 31;\n\tMAX_NUM_COEFS = 50;\n\tMAX_BALANCING = MAX_NUM_COEFS;\n\t\n\thexadef = {'00000000','47314252','47324252','47334252','47324f49','47334f49'};\n\tstrdef = {'NOGRAD','G1BR','G2BR','G3BR','G2OI','G3OI'};\n\t\n\tfor i = 1:ctf.res4.numberCoefficients,\n\t\t\n\t\t% read the sensor name (channel label)\n\t\ttemp = fread(fid,[1,32],'char');\n\t\ttemp(temp>127) = 0;\n\t\ttemp(temp<0) = 0;\n\t\ttemp = strtok(temp,char(0));\n\t\ttemp = strtok(temp,'-');\n\t\tsensorName = char(temp);\n\t\tsensorIndex = strmatch( sensorName, {ctf.sensor.info.label} );\n\t\t\n\t\t% read the coefficient type\n\t\tcoefType = fread(fid,1,'bit32');\n\t\t\n\t\tpadding = fread(fid,1,'int32'); % not sure why this is needed???\n\t\t\n\t\t% read the coefficient record\n\t\tnumberCoefs = fread(fid,1,'int16');\n\t\t\n\t\tif numberCoefs > MAX_NUM_COEFS,\n\t\t\tmsg = sprintf('numberCoefs > MAX_NUM_COEFS\\n');\n\t\t\twarning(msg);\n\t\tend\n \n\t\tsensor_list = char(fread(fid,[SENSOR_LABEL,MAX_BALANCING],'uchar')');\n\t\t% clean-up the sensor_list\n\t\tsensor_list = sensor_list(1:numberCoefs,:);\n\t\tfor j=1:numberCoefs,\n\t\t\ttemp = strtok(sensor_list(j,:),char(0));\n\t\t\ttemp = strtok(temp,'-');\n\t\t\t% check if this sensor is a reference\n\t\t\trefLabels = {ctf.sensor.info(ctf.sensor.index.meg_ref).label};\n\t\t\trefIndex = strmatch(temp,refLabels);\n\t\t\tif refIndex,\n\t\t\t\t% ensure this one has the same label\n\t\t\t\ttemp = refLabels{refIndex};\n\t\t\tend\n \n\t\t\tnew_sensor_list(j) = refIndex;\n\t\tend\n\t\tsensor_list = ctf.sensor.index.meg_ref(:,new_sensor_list)';\n\t\t\n\t\tcoefs_list = fread(fid,MAX_BALANCING,'double');\n\t\t% clean-up the coefs_list\n\t\tcoefs_list = coefs_list(1:numberCoefs,:)';\n\t\t\n\t\t% allocate the coefficient parameters into the ctf struct\n\t\tctf.res4.sensorCoef(i).sensorName = sensorName;\n\t\tctf.res4.sensorCoef(i).coefType = coefType;\n\t\tctf.res4.sensorCoef(i).coefRec.numberCoefs = numberCoefs;\n\t\tctf.res4.sensorCoef(i).coefRec.sensor_list = sensor_list;\n\t\tctf.res4.sensorCoef(i).coefRec.coefs_list = coefs_list;\n\t\t\t\n \n \n\t\t% DLW:\n\t\t% This is a brainstorm variable, note the use of coefType\n\t\t% Not clear why this is checked and allocated as such\n\t\tcoefType = find( hex2dec(hexadef) == coefType );\n\t\tif coefType,\n\t\t\t\tCoefInfo{sensorIndex,coefType-1}.numberCoefs = numberCoefs;\n\t\t\t\tCoefInfo{sensorIndex,coefType-1}.sensor_list = sensor_list;\n\t\t\t\tCoefInfo{sensorIndex,coefType-1}.coefs = coefs_list;\n\t\t\tend\n\t\tend\t\n\t\t\n\t\t\n \n % Channel Gains\n gain_chan = zeros(size(ctf.setup.number_channels,1),1);\n gain_chan(ctf.sensor.index.meg_sens) = ([ctf.sensor.info(ctf.sensor.index.meg_sens).proper_gain]'.*[ctf.sensor.info(ctf.sensor.index.meg_sens).q_gain]');\n gain_chan(ctf.sensor.index.meg_ref) = ([ctf.sensor.info(ctf.sensor.index.meg_ref).proper_gain]'.*[ctf.sensor.info(ctf.sensor.index.meg_ref).q_gain]');\n % gain_chan(ieegsens) = 1./([SensorRes(ieegsens).qGain]'*1e-6);\n\t\t% gain_chan(ieegsens) = 1./([SensorRes(ieegsens).qGain]');\n\t\t% gain_chan(iothersens) = ([SensorRes(iothersens).qGain]'); % Don't know exactly which gain to apply here\n \n \n \n % Calculus of the matrix for nth-order gradient correction\n % Coefficients for unused reference channels are weigthed by zeros in\n % the correction matrix.\n Gcoef = zeros(length(ctf.sensor.index.meg_sens),length(min(ctf.sensor.index.meg_ref):max(ctf.sensor.index.meg_ref)));\n grad_order_no = 3*ones(306,1);\n for k = 1:length(ctf.sensor.index.meg_sens)\n \n % Reference coils for channel k\n if grad_order_no(ctf.sensor.index.meg_sens(k)) == 0\n %Data is saved as RAW\n %Save 3rd order gradient sensor-list for subsequent correction if requested later by the user\n [refs] = (CoefInfo{ctf.sensor.index.meg_sens(k),3}.sensor_list);\n Gcoef(k,refs-min(ctf.sensor.index.meg_ref)+1) = CoefInfo{ctf.sensor.index.meg_sens(k),3}.coefs ... \n .* gain_chan(refs)'/gain_chan(ctf.sensor.index.meg_sens(k)); \n else\n [refs] = (CoefInfo{ctf.sensor.index.meg_sens(k),grad_order_no(ctf.sensor.index.meg_sens(k))}.sensor_list);\n Gcoef(k,refs-min(ctf.sensor.index.meg_ref)+1) = CoefInfo{ctf.sensor.index.meg_sens(k),grad_order_no(ctf.sensor.index.meg_sens(k))}.coefs ... \n .* gain_chan(refs)/gain_chan(ctf.sensor.index.meg_sens(k)); \n end\n ctf.sensor.info(ctf.sensor.index.meg_sens(k)).Gcoef = Gcoef(k,:);\n end\nend %% end COEF block\n\n\nfclose(fid);\n\nt = toc; fprintf('...done (%6.2f sec)\\n\\n',t);\n\nreturn\n\n\n\n% find file name if truncated or with uppercase extension\n% added by Arnaud Delorme June 15, 2004\n% -------------------------------------------------------\nfunction res4name = findres4file( folder )\n\nres4name = dir([ folder filesep '*.res4' ]);\nif isempty(res4name)\n res4name = dir([ folder filesep '*.RES4' ]);\nend\n\nif isempty(res4name)\n error('No file with extension .res4 or .RES4 in selected folder');\nelse\n res4name = [ folder filesep res4name.name ];\nend;\nreturn\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_get_bf.m", "ext": ".m", "path": "spm5-master/spm_get_bf.m", "size": 5267, "source_encoding": "utf_8", "md5": "9d28df048561f174ac8f95eae7f50f11", "text": "function [xBF] = spm_get_bf(xBF)\n% fills in basis function structure\n% FORMAT [xBF] = spm_get_bf(xBF);\n%\n% xBF.dt - time bin length {seconds}\n% xBF.name - description of basis functions specified\n% xBF.length - window length (secs)\n% xBF.order - order\n% xBF.bf - Matrix of basis functions\n%\n% xBF.name\t'hrf'\n%\t\t'hrf (with time derivative)'\n%\t\t'hrf (with time and dispersion derivatives)'\n%\t\t'Fourier set'\n%\t\t'Fourier set (Hanning)'\n%\t\t'Gamma functions'\n%\t\t'Finite Impulse Response'};\n%\n% (any other specifiaction will default to hrf)\n%_______________________________________________________________________\n%\n% spm_get_bf prompts for basis functions to model event or epoch-related\n% responses. The basis functions returned are unitary and orthonormal\n% when defined as a function of peri-stimulus time in time-bins.\n% It is at this point that the distinction between event and epoch-related \n% responses enters.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Karl Friston\n% $Id: spm_get_bf.m 112 2005-05-04 18:20:52Z john $\n\n\n%-GUI setup\n%-----------------------------------------------------------------------\nspm_help('!ContextHelp',mfilename)\n\n% length of time bin\n%-----------------------------------------------------------------------\nif ~nargin\n\tstr = 'time bin for basis functions {secs}';\n\txBF.dt = spm_input(str,'+1','r',1/16,1);\nend\ndt = xBF.dt;\n\n\n% assemble basis functions\n%=======================================================================\n\n% model event-related responses\n%-----------------------------------------------------------------------\nif ~isfield(xBF,'name')\n\tspm_input('Hemodynamic Basis functions...',1,'d')\n\tCtype = {\n\t\t'hrf',...\n\t\t'hrf (with time derivative)',...\n\t\t'hrf (with time and dispersion derivatives)',...\n\t\t'Fourier set',...\n\t\t'Fourier set (Hanning)',...\n\t\t'Gamma functions',...\n\t\t'Finite Impulse Response'};\n\tstr = 'Select basis set';\n\tSel = spm_input(str,2,'m',Ctype);\n\txBF.name = Ctype{Sel};\nend\n\n% get order and length parameters\n%-----------------------------------------------------------------------\nswitch xBF.name\n\n\tcase {\t'Fourier set','Fourier set (Hanning)',...\n\t\t'Gamma functions','Finite Impulse Response'}\n\t%---------------------------------------------------------------\n\ttry,\tl = xBF.length;\n\tcatch,\tl = spm_input('window length {secs}',3,'e',32);\n\t\txBF.length = l;\n\tend\n\ttry,\th = xBF.order;\n\tcatch,\th = spm_input('order',4,'e',4);\n\t\txBF.order = h;\n\tend\nend\n\n\n\n% create basis functions\n%-----------------------------------------------------------------------\nswitch xBF.name\n\n\tcase {'Fourier set','Fourier set (Hanning)'}\n\t%---------------------------------------------------------------\n\tpst = [0:dt:l]';\n\tpst = pst/max(pst);\n\n\t% hanning window\n\t%---------------------------------------------------------------\n\tif strcmp(xBF.name,'Fourier set (Hanning)')\n\t\tg = (1 - cos(2*pi*pst))/2;\n\telse\n\t\tg = ones(size(pst));\n\tend\n\n\t% zeroth and higher Fourier terms\n\t%---------------------------------------------------------------\n\tbf = g;\n\tfor i = 1:h\n\t\tbf = [bf g.*sin(i*2*pi*pst)];\n\t\tbf = [bf g.*cos(i*2*pi*pst)];\t\n\tend\n\n\tcase {'Gamma functions'}\n\t%---------------------------------------------------------------\n\tpst = [0:dt:l]';\n\tbf = spm_gamma_bf(pst,h);\n\n\tcase {'Finite Impulse Response'}\n\t%---------------------------------------------------------------\n\tbin = l/h;\n\tbf = kron(eye(h),ones(round(bin/dt),1));\n\n\tcase {'NONE'}\n\t%---------------------------------------------------------------\n\tbf = 1;\n\notherwise\n\n\t% canonical hemodynaic response function\n\t%---------------------------------------------------------------\n\t[bf p] = spm_hrf(dt);\n\n\t% add time derivative\n\t%---------------------------------------------------------------\n\tif findstr(xBF.name,'time')\n\n\t\tdp = 1;\n\t\tp(6) = p(6) + dp;\n\t\tD = (bf(:,1) - spm_hrf(dt,p))/dp;\n\t\tbf = [bf D(:)];\n\t\tp(6) = p(6) - dp;\n\n\t\t% add dispersion derivative\n\t\t%--------------------------------------------------------\n\t\tif findstr(xBF.name,'dispersion')\n\n\t\t\tdp = 0.01;\n\t\t\tp(3) = p(3) + dp;\n\t\t\tD = (bf(:,1) - spm_hrf(dt,p))/dp;\n\t\t\tbf = [bf D(:)];\n\t\tend\n\tend\n\n\t% length and order\n\t%---------------------------------------------------------------\n\txBF.length = size(bf,1)*dt;\n\txBF.order = size(bf,2);\n\nend\n\n\n% Orthogonalize and fill in basis function structure\n%------------------------------------------------------------------------\nxBF.bf = spm_orth(bf);\n\n\n%=======================================================================\n%- S U B - F U N C T I O N S\n%=======================================================================\n\n% compute Gamma functions functions\n%-----------------------------------------------------------------------\nfunction bf = spm_gamma_bf(u,h)\n% returns basis functions used for Volterra expansion\n% FORMAT bf = spm_gamma_bf(u,h);\n% u - times {seconds}\n% h - order\n% bf - basis functions (mixture of Gammas)\n%_______________________________________________________________________\nu = u(:);\nbf = [];\nfor i = 2:(1 + h)\n m = 2^i;\n s = sqrt(m);\n bf = [bf spm_Gpdf(u,(m/s)^2,m/s^2)];\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_resize_gui.m", "ext": ".m", "path": "spm5-master/spm_resize_gui.m", "size": 481, "source_encoding": "utf_8", "md5": "fa1e00d8d109dabf503b16c4d1b37fb1", "text": "\n% --- Executes when typeAssignmentPanel is resized.\nfunction spm_ResizeFcn(hObject, eventdata, handles)\n% hObject handle to typeAssignmentPanel (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nchildren=findall(hObject);\n\nfor i=1:length(children)\n if children(i)~=hObject\n try\n set(children(i), 'Position', get(children(i), 'Position'));\n end\n end\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeval.m", "ext": ".m", "path": "spm5-master/spm_eeval.m", "size": 8445, "source_encoding": "utf_8", "md5": "26057e63a54232c519c4a78782d28e78", "text": "function [p,msg] = spm_eeval(str,Type,n,m)\n% FORMAT [p,msg] = spm_eeval(str,Type,n,m)\n% Expression evaluation\n% Str - Expression to work with\n%\n% Type - type of evaluation\n% - 's'tring\n% - 'e'valuated string\n% - 'n'atural numbers\n% - 'w'hole numbers\n% - 'i'ntegers\n% - 'r'eals\n% - 'c'ondition indicator vector\n%\n% n ('e', 'c' & 'p' types)\n% - Size of matrix requred\n% - NaN for 'e' type implies no checking - returns input as evaluated\n% - length of n(:) specifies dimension - elements specify size\n% - Inf implies no restriction\n% - Scalar n expanded to [n,1] (i.e. a column vector)\n% (except 'x' contrast type when it's [n,np] for np\n% - E.g: [n,1] & [1,n] (scalar n) prompt for an n-vector,\n% returned as column or row vector respectively\n% [1,Inf] & [Inf,1] prompt for a single vector,\n% returned as column or row vector respectively\n% [n,Inf] & [Inf,n] prompts for any number of n-vectors,\n% returned with row/column dimension n respectively.\n% [a,b] prompts for an 2D matrix with row dimension a and\n% column dimension b\n% [a,Inf,b] prompt for a 3D matrix with row dimension a,\n% page dimension b, and any column dimension.\n% - 'c' type can only deal with single vectors\n% - NaN for 'c' type treated as Inf\n% - Defaults (missing or empty) to NaN\n%\n% m ('n', 'w', 'n1', 'w1', 'bn1' & 'bw1' types)\n% - Maximum value (inclusive)\n%\n% m ('r' type)\n% - Maximum and minimum values (inclusive)\n%\n% m ('c' type)\n% - Number of unique conditions required by 'c' type\n% - Inf implies no restriction\n% - Defaults (missing or empty) to Inf - no restriction\n%\n% p - Result\n%\n% msg - Explanation of why it didn't work\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Andrew Holmes\n% $Id: spm_eeval.m 112 2005-05-04 18:20:52Z john $\n\n\nif nargin<4, m=[]; end\nif nargin<3, n=[]; end\nif nargin<2, Type='e'; end\nif nargin<1, str=''; end\nif isempty(str), p='!'; msg='empty input'; return, end\nswitch lower(Type)\ncase 's'\n p = str; msg = '';\ncase 'e'\n p = evalin('base',['[',str,']'],'''!''');\n if ischar(p)\n msg = 'evaluation error';\n else\n [p,msg] = sf_SzChk(p,n);\n end\ncase 'n'\n p = evalin('base',['[',str,']'],'''!''');\n if ischar(p)\n msg = 'evaluation error';\n elseif any(floor(p(:))~=p(:)|p(:)<1) || ~isreal(p)\n p='!'; msg='natural number(s) required';\n elseif ~isempty(m) && any(p(:)>m)\n p='!'; msg=['max value is ',num2str(m)];\n else\n [p,msg] = sf_SzChk(p,n);\n end\ncase 'w'\n p = evalin('base',['[',str,']'],'''!''');\n if ischar(p)\n msg = 'evaluation error';\n elseif any(floor(p(:))~=p(:)|p(:)<0) || ~isreal(p)\n p='!'; msg='whole number(s) required';\n elseif ~isempty(m) && any(p(:)>m)\n p='!'; msg=['max value is ',num2str(m)];\n else\n [p,msg] = sf_SzChk(p,n);\n end\ncase 'i'\n p = evalin('base',['[',str,']'],'''!''');\n if ischar(p)\n msg = 'evaluation error';\n elseif any(floor(p(:))~=p(:)) || ~isreal(p)\n p='!'; msg='integer(s) required';\n else\n [p,msg] = sf_SzChk(p,n);\n end\ncase 'p'\n p = evalin('base',['[',str,']'],'''!''');\n if ischar(p)\n msg = 'evaluation error';\n elseif length(setxor(p(:)',m))\n p='!'; msg='invalid permutation';\n else\n [p,msg] = sf_SzChk(p,n);\n end\ncase 'r'\n p = evalin('base',['[',str,']'],'''!''');\n if ischar(p)\n msg = 'evaluation error';\n elseif ~isreal(p)\n p='!'; msg='real number(s) required';\n elseif ~isempty(m) && ( max(p)>max(m) || min(p)2\n error('condition input can only do vectors')\nend\nif nargin<2, i=''; end\nif isempty(i), varargout={[],'empty input'}; return, end\nmsg = ''; i=i(:)';\n\nif ischar(i)\n if i(1)=='0' & all(ismember(unique(i(:)),setstr(abs('0'):abs('9'))))\n %-Leading zeros in a digit list\n msg = sprintf('%s expanded',i);\n z = min(find([diff(i=='0'),1]));\n i = [zeros(1,z), icond(i(z+1:end))'];\n else\n %-Try an eval, for functions & string #s\n i = evalin('base',['[',i,']'],'i');\n end\nend\n\nif ischar(i)\n %-Evaluation error from above: see if it's an 'abab' or 'a b a b' type:\n [c,null,i] = unique(lower(i(~isspace(i))));\n if all(ismember(c,setstr(abs('a'):abs('z'))))\n %-Map characters a-z to 1-26, but let 'r' be zero (rest)\n tmp = c-'a'+1; tmp(tmp=='r'-'a'+1)=0;\n i = tmp(i);\n msg = [sprintf('[%s] mapped to [',c),...\n sprintf('%d,',tmp(1:end-1)),...\n sprintf('%d',tmp(end)),']'];\n else\n i = '!'; msg = 'evaluation error';\n end\nelseif ~all(floor(i(:))==i(:))\n i = '!'; msg = 'must be integers';\nelseif length(i)==1 & prod(n)>1\n msg = sprintf('%d expanded',i);\n i = floor(i./10.^[floor(log10(i)+eps):-1:0]);\n i = i-[0,10*i(1:end-1)];\nend\n\n%-Check size of i & #conditions\nif ~ischar(i), [i,msg] = sf_SzChk(i,n,msg); end\nif ~ischar(i) & isfinite(m) & length(unique(i))~=m\n i = '!'; msg = sprintf('%d conditions required',m);\nend\nreturn;\n\nfunction str = sf_SzStr(n,unused)\n%=======================================================================\n%-Size info string constuction\nif nargin<2, l=0; else l=1; end\nif nargin<1, error('insufficient arguments'); end;\nif isempty(n), n=NaN; end\nn=n(:); if length(n)==1, n=[n,1]; end; dn=length(n);\nif any(isnan(n)) || (prod(n)==1 && dn<=2) || (dn==2 && min(n)==1 && isinf(max(n)))\n str = ''; lstr = '';\nelseif dn==2 && min(n)==1\n str = sprintf('[%d]',max(n)); lstr = [str,'-vector'];\nelseif dn==2 && sum(isinf(n))==1\n str = sprintf('[%d]',min(n)); lstr = [str,'-vector(s)'];\nelse\n str=''; for i = 1:dn\n if isfinite(n(i)), str = sprintf('%s,%d',str,n(i));\n else str = sprintf('%s,*',str); end\n end\n str = ['[',str(2:end),']']; lstr = [str,'-matrix'];\nend\nif l, str=sprintf('\\t%s',lstr); else str=[str,' ']; end\n\n\nfunction [p,msg] = sf_SzChk(p,n,msg)\n%=======================================================================\n%-Size checking\nif nargin<3, msg=''; end\nif nargin<2, n=[]; end; if isempty(n), n=NaN; else n=n(:)'; end\nif nargin<1, error('insufficient arguments'), end\n\nif ischar(p) || any(isnan(n(:))), return, end\nif length(n)==1, n=[n,1]; end\n\ndn = length(n);\nsp = size(p);\n\nif dn==2 && min(n)==1\n %-[1,1], [1,n], [n,1], [1,Inf], [Inf,1] - vector - allow transpose\n %---------------------------------------------------------------\n i = min(find(n==max(n)));\n if n(i)==1 && max(sp)>1\n p='!'; msg='scalar required';\n elseif ndims(p)~=2 || ~any(sp==1) || ( isfinite(n(i)) && max(sp)~=n(i) )\n %-error: Not2D | not vector | not right length\n if isfinite(n(i)), str=sprintf('%d-',n(i)); else str=''; end\n p='!'; msg=[str,'vector required'];\n elseif sp(i)==1 && n(i)~=1\n p=p'; msg=[msg,' (input transposed)'];\n end\n\nelseif dn==2 && sum(isinf(n))==1\n %-[n,Inf], [Inf,n] - n vector(s) required - allow transposing\n %---------------------------------------------------------------\n i = find(isfinite(n));\n if ndims(p)~=2 || ~any(sp==n(i))\n p='!'; msg=sprintf('%d-vector(s) required',min(n));\n elseif sp(i)~=n\n p=p'; msg=[msg,' (input transposed)'];\n end\n\nelse\n %-multi-dimensional matrix required - check dimensions\n %---------------------------------------------------------------\n if ndims(p)~=dn || ~all( size(p)==n | isinf(n) )\n p = '!'; msg='';\n for i = 1:dn\n if isfinite(n(i)), msg = sprintf('%s,%d',msg,n(i));\n else msg = sprintf('%s,*',msg); end\n end\n msg = ['[',msg(2:end),']-matrix required'];\n end\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_display.m", "ext": ".m", "path": "spm5-master/spm_config_display.m", "size": 4639, "source_encoding": "utf_8", "md5": "121b20a231bfbafa715cf64cdc9a4819", "text": "function opts = spm_config_display\n% Configuration file for display jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_display.m 1032 2007-12-20 14:45:55Z john $\n\n\n%_______________________________________________________________________\n\ndata.type = 'files';\ndata.name = 'Image to Display';\ndata.tag = 'data';\ndata.filter = 'image';\ndata.num = 1;\ndata.help = {'Image to display.'};\n\nopts.type = 'branch';\nopts.name = 'Display Image';\nopts.tag = 'disp';\nopts.val = {data};\nopts.prog = @dispim;\np1 = [...\n'This is an interactive facility that allows orthogonal sections'...\n' from an image volume to be displayed. Clicking the cursor on either'...\n' of the three images moves the point around which the orthogonal'...\n' sections are viewed. The co-ordinates of the cursor are shown both'...\n' in voxel co-ordinates and millimetres within some fixed framework.'...\n' The intensity at that point in the image (sampled using the current'...\n' interpolation scheme) is also given. The position of the cross-hairs'...\n' can also be moved by specifying the co-ordinates in millimetres to'...\n' which they should be moved. Clicking on the horizontal bar above'...\n' these boxes will move the cursor back to the origin (analogous to'...\n' setting the cross-hair position (in mm) to [0 0 0]).'];\np2 = [...\n'The images can be re-oriented by entering appropriate translations,'...\n' rotations and zooms into the panel on the left. The transformations'...\n' can then be saved by hitting the \"Reorient images...\" button. The'...\n' transformations that were applied to the image are saved to the'...\n' header information of the selected images. The transformations are'...\n' considered to be relative to any existing transformations that may be'...\n' stored. Note that the order that the'...\n' transformations are applied in is the same as in spm_matrix.m.'];\np3 = [...\n'The \"Reset...\" button next to it is for setting the orientation of'...\n' images back to transverse. It retains the current voxel sizes,'...\n' but sets the origin of the images to be the centre of the volumes'...\n' and all rotations back to zero.'];\np4 = [...\n'The right panel shows miscellaneous information about the image.'...\n' This includes:'];\np5 = [...\n'There are also a few options for different resampling modes, zooms'...\n' etc. You can also flip between voxel space (as would be displayed'...\n' by Analyze) or world space (the orientation that SPM considers the'...\n' image to be in). If you are re-orienting the images, make sure that'...\n' world space is specified. Blobs (from activation studies) can be'...\n' superimposed on the images and the intensity windowing can also be'...\n' changed.'];\n\np6 = ['If you have put your images in the correct file format, ',...\n 'then (possibly after specifying some rigid-body rotations):'];\np7 = [' The top-left image is coronal with the top (superior) ',...\n 'of the head displayed at the top and the left shown on the left. ',...\n 'This is as if the subject is viewed from behind.'];\np8 = [' The bottom-left image is axial with the front (anterior) of the ',...\n 'head at the top and the left shown on the left. ',...\n 'This is as if the subject is viewed from above.'];\np9 = [' The top-right image is sagittal with the front (anterior) of ',...\n 'the head at the left and the top of the head shown at the top. ',...\n 'This is as if the subject is viewed from the left.'];\nfg = ['/*',...\n'\\begin{figure} ',...\n'\\begin{center} ',...\n'\\includegraphics[width=150mm]{images/disp1} ',...\n'\\end{center} ',...\n'\\caption{The Display routine. \\label{disp1}}',...\n'\\end{figure} */'];\nopts.help = {p1,'',p2,'',p3,'',p4,...\n' Dimensions - the x, y and z dimensions of the image.',...\n' Datatype - the computer representation of each voxel.',...\n' Intensity - scale-factors and possibly a DC offset.',...\n' Miscellaneous other information about the image.',[...\n' Vox size - the distance (in mm) between the centres of ',...\n' neighbouring voxels.'],...\n' Origin - the voxel at the origin of the co-ordinate system',[...\n' DIr Cos - Direction cosines. This is a widely used',...\n' representation of the orientation of an image.'],...\n'',p5,'','',p6,p7,p8,p9,fg};\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction dispim(varargin)\njob = varargin{1};\nspm_image('init',job.data{1});\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_segment.m", "ext": ".m", "path": "spm5-master/spm_segment.m", "size": 24271, "source_encoding": "utf_8", "md5": "156a8af0663ed1ee884a52b0ecc11e1f", "text": "function [VO,M] = spm_segment(VF,PG,flags)\n% Segment an MR image into Gray, White & CSF.\n%\n% FORMAT VO = spm_segment(PF,PG,flags)\n% PF - name(s) of image(s) to segment (must have same dimensions).\n% PG - name(s) of template image(s) for realignment.\n% - or a 4x4 transformation matrix which maps from the image to\n% the set of templates.\n% flags - a structure normally based on defaults.segment\n% VO - optional output volume\n% M - affine transformation between template and image to segment\n%\n% The algorithm is four step:\n%\n% 1) Determine the affine transform which best matches the image with a\n% template image. If the name of more than one image is passed, then\n% the first image is used in this step. This step is not performed if\n% no template images are specified.\n%\n% 2) Perform Cluster Analysis with a modified Mixture Model and a-priori\n% information about the likelihoods of each voxel being one of a\n% number of different tissue types. If more than one image is passed,\n% then they they are all assumed to be in register, and the voxel\n% values are fitted to multi-normal distributions.\n%\n% 3) Perform morphometric operations on the grey and white partitions\n% in order to more accurately identify brain tissue. This is then used\n% to clean up the grey and white matter segments. \n%\n% 4) If no or 2 output arguments is/are specified, then the segmented \n% images are written to disk. The names of these images have \"c1\", \n% \"c2\" & \"c3\" appended to the name of the first image passed. The \n% 'brainmask' is also created with \"BrMsk_\" as an appendix.\n%\n%_______________________________________________________________________\n% Refs:\n%\n% Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and\n% Partitioning - a Unified Framework. NeuroImage 6:209-217\n%\n%_______________________________________________________________________\n%\n% The template image, and a-priori likelihood images are modified\n% versions of those kindly supplied by Alan Evans, MNI, Canada\n% (ICBM, NIH P-20 project, Principal Investigator John Mazziotta).\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_segment.m 946 2007-10-15 16:36:06Z john $\n\n\n% Create some suitable default values\n%-----------------------------------------------------------------------\n\ndef_flags.estimate.priors = char(...\n fullfile(spm('Dir'),'apriori','grey.nii'),...\n fullfile(spm('Dir'),'apriori','white.nii'),...\n fullfile(spm('Dir'),'apriori','csf.nii'));\ndef_flags.estimate.reg = 0.01;\ndef_flags.estimate.cutoff = 30;\ndef_flags.estimate.samp = 3;\ndef_flags.estimate.bb = [[-88 88]' [-122 86]' [-60 95]'];\ndef_flags.estimate.affreg.smosrc = 8;\ndef_flags.estimate.affreg.regtype = 'mni';\ndef_flags.estimate.affreg.weight = '';\ndef_flags.write.cleanup = 1;\ndef_flags.write.wrt_cor = 1;\ndef_flags.write.wrt_brV = 0;\ndef_flags.graphics = 1;\n\nif nargin<3, flags = def_flags; end;\nif ~isfield(flags,'estimate'), flags.estimate = def_flags.estimate; end;\nif ~isfield(flags.estimate,'priors'), flags.estimate.priors = def_flags.estimate.priors; end;\nif ~isfield(flags.estimate,'reg'), flags.estimate.reg = def_flags.estimate.reg; end;\nif ~isfield(flags.estimate,'cutoff'), flags.estimate.cutoff = def_flags.estimate.cutoff; end;\nif ~isfield(flags.estimate,'samp'), flags.estimate.samp = def_flags.estimate.samp; end;\nif ~isfield(flags.estimate,'bb'), flags.estimate.bb = def_flags.estimate.bb; end;\nif ~isfield(flags.estimate,'affreg'), flags.estimate.affreg = def_flags.estimate.affreg; end;\nif ~isfield(flags.estimate.affreg,'smosrc'),\n\tflags.estimate.affreg.smosrc = def_flags.estimate.affreg.smosrc;\nend;\nif ~isfield(flags.estimate.affreg,'regtype'),\n\tflags.estimate.affreg.regtype = def_flags.estimate.affreg.regtype;\nend;\nif ~isfield(flags.estimate.affreg,'weight'),\n\tflags.estimate.affreg.weight = def_flags.estimate.affreg.weight;\nend;\nif ~isfield(flags,'write'), flags.write = def_flags.write; end;\nif ~isfield(flags.write,'cleanup'), flags.write.cleanup = def_flags.write.cleanup; end;\nif ~isfield(flags.write,'wrt_cor'), flags.write.wrt_cor = def_flags.write.wrt_cor; end;\nif ~isfield(flags.write,'wrt_brV'), flags.write.wrt_brV = def_flags.write.wrt_brV; end;\nif ~isfield(flags,'graphics'), flags.graphics = def_flags.graphics; end;\n\n%-----------------------------------------------------------------------\n\nif ischar(VF), VF= spm_vol(VF); end;\n\nSP = init_sp(flags.estimate,VF,PG);\n[x1,x2,x3] = get_sampling(SP.MM,VF,flags.estimate.samp,flags.estimate.bb);\nBP = init_bp(VF, flags.estimate.cutoff, flags.estimate.reg);\nCP = init_cp(VF,x3);\nsums = zeros(8,1);\n\nfor pp=1:length(x3),\n\t[raw,msk] = get_raw(VF,x1,x2,x3(pp));\n\ts = get_sp(SP,x1,x2,x3(pp));\n\tCP = update_cp_est(CP,s,raw,msk,pp);\n\tsums = sums + reshape(sum(sum(s,1),2),8,1);\nend;\nsums = sums/sum(sums);\nCP = shake_cp(CP);\n\n[CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3);\n\n%save segmentation_results.mat CP BP SP VF sums\n\n[g,w,c] = get_gwc(VF,BP,SP,CP,sums,flags.write.wrt_cor);\nif flags.write.cleanup, [g,w,c,b] = clean_gwc(g,w,c); end;\n\n% Create the segmented images + the brain mask.\n%-----------------------------------------------------------------------\n%offs = cumsum(repmat(prod(VF(1).dim(1:2)),1,VF(1).dim(3)))-prod(VF(1).dim(1:2));\n%pinfo = [repmat([1/255 0]',1,VF(1).dim(3)) ; offs];\n[pth,nm,xt] = fileparts(deblank(VF(1).fname));\n\nif flags.write.wrt_brV\n Nwrt = 4;\nelse\n Nwrt = 3;\nend\nfor j=1:Nwrt,\n\ttmp = fullfile(pth,['c', num2str(j), nm, xt]);\n if j==4, tmp = fullfile(pth,['BrMsk_', nm xt]); end\n\n\tVO(j) = struct(...\n\t\t'fname',tmp,...\n\t\t'dim', VF(1).dim(1:3),...\n\t\t'dt', [spm_type('uint8'), spm_platform('bigend')],...\n\t\t'mat', VF(1).mat,...\n\t\t'pinfo', [1/255 0 0]',...\n\t\t'descrip','Segmented image');\nend;\n\nif nargout==0 || nargout==2,\n\tVO = spm_create_vol(VO);\n\n\tspm_progress_bar('Init',VF(1).dim(3),'Writing Segmented','planes completed');\n\tfor pp=1:VF(1).dim(3),\n\t\tVO(1) = spm_write_plane(VO(1),double(g(:,:,pp))/255,pp);\n\t\tVO(2) = spm_write_plane(VO(2),double(w(:,:,pp))/255,pp);\n\t\tVO(3) = spm_write_plane(VO(3),double(c(:,:,pp))/255,pp);\n if flags.write.wrt_brV\n \t\tVO(4) = spm_write_plane(VO(4),double(b(:,:,pp))/255,pp);\n end\n\t\tspm_progress_bar('Set',pp);\n\tend;\n\tspm_progress_bar('Clear');\nend;\n\nVO(1).dat = g; VO(1).pinfo = VO(1).pinfo(1:2,:);\nVO(2).dat = w; VO(2).pinfo = VO(2).pinfo(1:2,:);\nVO(3).dat = c; VO(3).pinfo = VO(3).pinfo(1:2,:);\nif flags.write.wrt_brV\n VO(4).dat = b; VO(4).pinfo = VO(4).pinfo(1:2,:);\nend\nif nargout==2\n M = SP.MM/VF(1).mat;\nend\n\nif flags.graphics, display_graphics(VF,VO,CP.mn,CP.cv,CP.mg); end;\n\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [y1,y2,y3] = affine_transform(x1,x2,x3,M)\n\ty1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);\n\ty2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);\n\ty3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction display_graphics(VF,VS,mn,cv,mg)\n% Do the graphics\nnb = 3;\nspm_figure('Clear','Graphics');\nfg = spm_figure('FindWin','Graphics');\nif ~isempty(fg),\n\t% Show some text\n\t%-----------------------------------------------------------------------\n\tax = axes('Position',[0.05 0.8 0.9 0.2],'Visible','off','Parent',fg);\n\ttext(0.5,0.80, 'Segmentation','FontSize',16,'FontWeight','Bold',...\n\t\t'HorizontalAlignment','center','Parent',ax);\n\n\ttext(0,0.65, ['Image: ' spm_str_manip(VF(1).fname,'k50d')],...\n\t\t'FontSize',14,'FontWeight','Bold','Parent',ax);\n\n\ttext(0,0.40, 'Means:','FontSize',12,'FontWeight','Bold','Parent',ax);\n\ttext(0,0.30, 'Std devs:' ,'FontSize',12,'FontWeight','Bold','Parent',ax);\n\ttext(0,0.20, 'N vox:','FontSize',12,'FontWeight','Bold','Parent',ax);\n\tfor j=1:nb,\n\t\ttext((j+0.5)/(nb+1),0.40, num2str(mn(1,j)),...\n\t\t\t'FontSize',12,'FontWeight','Bold',...\n\t\t\t'HorizontalAlignment','center','Parent',ax);\n\t\ttext((j+0.5)/(nb+1),0.30, num2str(sqrt(cv(1,1,j))),...\n\t\t\t'FontSize',12,'FontWeight','Bold',...\n\t\t\t'HorizontalAlignment','center','Parent',ax);\n\t\ttext((j+0.5)/(nb+1),0.20, num2str(mg(1,j)/sum(mg(1,:))),...\n\t\t\t'FontSize',12,'FontWeight','Bold',...\n\t\t\t'HorizontalAlignment','center','Parent',ax);\n\tend;\n\tif length(VF) > 1,\n\t\ttext(0,0.10,...\n\t\t'Note: only means and variances for the first image are shown',...\n\t\t'Parent',ax,'FontSize',12);\n\tend;\n\n\tM1 = VS(1).mat;\n\tM2 = VF(1).mat;\n\tfor i=1:5,\n\t\tM = spm_matrix([0 0 i*VF(1).dim(3)/6]);\n\t\timg = spm_slice_vol(VF(1),M,VF(1).dim(1:2),1);\n\t\timg(1,1) = eps;\n\t\tax = axes('Position',...\n\t\t\t[0.05 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...\n\t\t\t'Visible','off','Parent',fg);\n\t\timagesc(rot90(img), 'Parent', ax);\n\t\tset(ax,'Visible','off','DataAspectRatio',[1 1 1]);\n\n\t\tfor j=1:3,\n\t\t\timg = spm_slice_vol(VS(j),M2\\M1*M,VF(1).dim(1:2),1);\n\t\t\tax = axes('Position',...\n\t\t\t\t[0.05+j*0.9/(nb+1) 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...\n\t\t\t\t'Visible','off','Parent',fg);\n\t\t\timage(rot90(img*64), 'Parent', ax);\n\t\t\tset(ax,'Visible','off','DataAspectRatio',[1 1 1]);\n\t\tend;\n\tend;\n\n\tspm_print;\n\tdrawnow;\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction M = get_affine_mapping(VF,VG,aflags)\n\nif ~isempty(VG) && ischar(VG), VG = spm_vol(VG); end;\n\nif ~isempty(VG) && isstruct(VG),\n\t% Affine registration so that a priori images match the image to\n\t% be segmented.\n\t%-----------------------------------------------------------------------\n\n\tVFS = spm_smoothto8bit(VF(1),aflags.smosrc);\n\n\t% Scale all images approximately equally\n\t% ---------------------------------------------------------------\n\tfor i=1:length(VG),\n\t\tVG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));\n\tend;\n\tVFS(1).pinfo(1:2,:) = VFS(1).pinfo(1:2,:)/spm_global(VFS(1));\n\n\tspm_chi2_plot('Init','Affine Registration','Mean squared difference','Iteration');\n\tflags = struct('sep',aflags.smosrc, 'regtype',aflags.regtype,'WG',[],'globnorm',0,'debug',0);\n\tM = eye(4);\n\t[M,scal] = spm_affreg(VG, VFS, flags, M);\n\n\tif ~isempty(aflags.weight), flags.WG = spm_vol(aflags.weight); end;\n\n\tflags.sep = aflags.smosrc/2;\n\tM = spm_affreg(VG, VFS, flags, M,scal);\n\tspm_chi2_plot('Clear');\n\nelseif all(size(VG) == [4 4])\n\t% Assume that second argument is a matrix that will do the job\n\t%-----------------------------------------------------------------------\n\tM = VG;\nelse\n\t% Assume that image is normalized\n\t%-----------------------------------------------------------------------\n\tM = eye(4);\nend\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [x1,x2,x3] = get_sampling(MM,VF,samp,bb1)\n% Voxels to sample during the cluster analysis\n%-----------------------------------------------------------------------\n\n% A bounding box for the brain in Talairach space.\n%bb = [ [-88 88]' [-122 86]' [-60 95]'];\n%c = [bb(1,1) bb(1,2) bb(1,3) 1\n% bb(1,1) bb(1,2) bb(2,3) 1\n% bb(1,1) bb(2,2) bb(1,3) 1\n% bb(1,1) bb(2,2) bb(2,3) 1\n% bb(2,1) bb(1,2) bb(1,3) 1\n% bb(2,1) bb(1,2) bb(2,3) 1\n% bb(2,1) bb(2,2) bb(1,3) 1\n% bb(2,1) bb(2,2) bb(2,3) 1]';\n%tc = MM\\c;\n%tc = tc(1:3,:)';\n%mx = max(tc);\n%mn = min(tc);\n%bb = [mn ; mx];\n%vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));\n%samp = round(max(abs([4 4 4]./vx), [1 1 1]));\n%x1 = bb(1,1):samp(1):bb(2,1);\n%x2 = bb(1,2):samp(2):bb(2,2);\n%x3 = bb(1,3):samp(3):bb(2,3);\n%return;\n\n% A bounding box for the brain in Talairach space.\nif nargin<4, bb1 = [ [-88 88]' [-122 86]' [-60 95]']; end;\n\n% A mapping from a unit radius sphere to a hyper-ellipse\n% that is just enclosed by the bounding box in Talairach\n% space.\nM0 = [diag(diff(bb1)/2) mean(bb1)';[0 0 0 1]];\n\n% The mapping from voxels to Talairach space is MM,\n% so the ellipse in the space of the image becomes:\nM0 = MM\\M0;\n\n% So to work out the bounding box in the space of the\n% image that just encloses the hyper-ellipse.\ntmp = M0(1:3,1:3);\ntmp = diag(tmp*tmp'/diag(sqrt(diag(tmp*tmp'))));\nbb = round([M0(1:3,4)-tmp M0(1:3,4)+tmp])';\nbb = min(max(bb,[1 1 1 ; 1 1 1]),[VF(1).dim(1:3) ; VF(1).dim(1:3)]);\n\n% Want to sample about every 3mm\ntmp = sqrt(sum(VF(1).mat(1:3,1:3).^2))';\nsamp = round(max(abs(tmp.^(-1)*samp), [1 1 1]'));\n\nx1 = bb(1,1):samp(1):bb(2,1);\nx2 = bb(1,2):samp(2):bb(2,2);\nx3 = bb(1,3):samp(3):bb(2,3);\n\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3)\noll = -Inf;\nspm_chi2_plot('Init','Segmenting','Log-likelihood','Iteration #');\n\nfor iter = 1:64,\n\tll= 0;\n\tfor pp = 1:length(x3), % Loop over planes\n\t\tbf = get_bp(BP,x1,x2,x3(pp));\n\t\t[raw,msk] = get_raw(VF,x1,x2,x3(pp));\n\t\ts = get_sp(SP,x1,x2,x3(pp));\n\t\tcor = bf.*raw;\n\t\t[P,ll0] = get_p(cor,msk,s,sums,CP,bf);\n\t\tll = ll + ll0;\n\t\tCP = update_cp_est(CP,P,cor,msk,pp);\n\t\tBP = update_bp_est(BP,P,cor,CP,msk,x1,x2,x3(pp));\n\tend;\n\n\tBP = update_bp(BP);\n\tif iter>1, spm_chi2_plot('Set',ll); end;\n\t%fprintf('\\t%g\\n', ll);\n\n\t% Stopping criterion\n\t%-----------------------------------------------------------------------\n\tif iter == 2,\n\t\tll2 = ll;\n\telseif iter > 2 && abs((ll-oll)/(ll-ll2)) < 0.0001\n\t\tbreak;\n\tend;\n\toll = ll;\nend;\nspm_chi2_plot('Clear');\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction BP = init_bp(VF,co,reg)\nm = length(VF);\ntmp = sqrt(sum(VF(1).mat(1:3,1:3).^2));\nBP.nbas = max(round((VF(1).dim(1:3).*tmp)/co),[1 1 1]);\nBP.B1 = spm_dctmtx(VF(1).dim(1),BP.nbas(1));\nBP.B2 = spm_dctmtx(VF(1).dim(2),BP.nbas(2));\nBP.B3 = spm_dctmtx(VF(1).dim(3),BP.nbas(3));\n\nnbas = BP.nbas;\nif prod(BP.nbas)>1,\n\t% Set up a priori covariance matrix\n\tvx = sqrt(sum(VF(1).mat(1:3,1:3).^2));\n\tkx=(pi*((1:nbas(1))'-1)*pi/vx(1)/VF(1).dim(1)*10).^2;\n\tky=(pi*((1:nbas(2))'-1)*pi/vx(2)/VF(1).dim(2)*10).^2;\n\tkz=(pi*((1:nbas(3))'-1)*pi/vx(3)/VF(1).dim(3)*10).^2;\n\n\t% Cost function based on sum of squares of 4th derivatives\n\tIC0 = (1*kron(kz.^4,kron(ky.^0,kx.^0)) +...\n\t 1*kron(kz.^0,kron(ky.^4,kx.^0)) +...\n\t 1*kron(kz.^0,kron(ky.^0,kx.^4)) +...\n\t 4*kron(kz.^3,kron(ky.^1,kx.^0)) +...\n\t 4*kron(kz.^3,kron(ky.^0,kx.^1)) +...\n\t 4*kron(kz.^1,kron(ky.^3,kx.^0)) +...\n\t 4*kron(kz.^0,kron(ky.^3,kx.^1)) +...\n\t 4*kron(kz.^1,kron(ky.^0,kx.^3)) +...\n\t 4*kron(kz.^0,kron(ky.^1,kx.^3)) +...\n\t 6*kron(kz.^2,kron(ky.^2,kx.^0)) +...\n\t 6*kron(kz.^2,kron(ky.^0,kx.^2)) +...\n\t 6*kron(kz.^0,kron(ky.^2,kx.^2)) +...\n\t 12*kron(kz.^2,kron(ky.^1,kx.^1)) +...\n\t 12*kron(kz.^1,kron(ky.^2,kx.^1)) +...\n\t 12*kron(kz.^1,kron(ky.^1,kx.^2)) )*reg;\n\n\t%IC0(1) = max(IC0);\n\tBP.IC0 = diag(IC0(2:end));\n\n\t% Initial estimate for intensity modulation field\n\tBP.T = zeros(nbas(1),nbas(2),nbas(3),length(VF));\n\t%-----------------------------------------------------------------------\nelse\n\tBP.T = zeros([1 1 1 length(VF)]);\n\tBP.IC0 = [];\nend;\nBP.Alpha = zeros(prod(BP.nbas(1:3)),prod(BP.nbas(1:3)),m);\nBP.Beta = zeros(prod(BP.nbas(1:3)),m);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction BP = update_bp_est(BP,p,cor,CP,msk,x1,x2,x3)\nif prod(BP.nbas)<=1, return; end;\nB1 = BP.B1(x1,:);\nB2 = BP.B2(x2,:);\nB3 = BP.B3(x3,:);\nfor j=1:size(BP.Alpha,3),\n\tcr = cor(:,:,j);\n\tw1 = zeros(size(cr));\n\tw2 = zeros(size(cr));\n\tfor i=[1 2 3 4 5 6 7 8],\n\t\ttmp = p(:,:,i)*CP.cv(j,j,i)^(-1);\n\t\tw1 = w1 + tmp.*(CP.mn(j,i) - cr);\n\t\tw2 = w2 + tmp;\n\tend;\n\twt1 = 1 + cr.*w1;\n\twt2 = cr.*(cr.*w2 - w1);\n\twt1(~msk) = 0;\n\twt2(~msk) = 0;\n\n\tBP.Beta(:,j) = BP.Beta(:,j) + kron(B3',spm_krutil(wt1,B1,B2,0));\n\tBP.Alpha(:,:,j) = BP.Alpha(:,:,j) + kron(B3'*B3,spm_krutil(wt2,B1,B2,1));\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction BP = update_bp(BP)\nif prod(BP.nbas)<=1, return; end;\nfor j=1:size(BP.Alpha,3),\n\tx = BP.T(:,:,:,j);\n\tx = x(:);\n\tx = x(2:end);\n\tAlpha = BP.Alpha(2:end,2:end,j);\n\tBeta = BP.Beta(2:end,j);\n\tx = (Alpha + BP.IC0)\\(Alpha*x + Beta);\n\n\tBP.T(:,:,:,j) = reshape([0 ; x],BP.nbas(1:3));\n\tBP.Alpha = zeros(size(BP.Alpha));\n\tBP.Beta = zeros(size(BP.Beta));\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction bf = get_bp(BP,x1,x2,x3)\nbf = ones(length(x1),length(x2),size(BP.Alpha,3));\nif prod(BP.nbas)<=1, return; end;\nB1 = BP.B1(x1,:);\nB2 = BP.B2(x2,:);\nB3 = BP.B3(x3,:);\nfor i=1:size(BP.Alpha,3),\n\tt = reshape(reshape(BP.T(:,:,:,i),...\n\t\tBP.nbas(1)*BP.nbas(2),BP.nbas(3))*B3', BP.nbas(1), BP.nbas(2));\n\tbf(:,:,i) = exp(B1*t*B2');\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [dat,msk] = get_raw(VF,x1,x2,x3)\n[X1,X2,X3] = ndgrid(x1,x2,x3);\nfor i=1:length(VF),\n\t[Y1,Y2,Y3] = affine_transform(X1,X2,X3,VF(i).mat\\VF(1).mat);\n\tdat(:,:,i) = spm_sample_vol(VF(i),Y1,Y2,Y3,1);\nend;\nmsk = all(dat,3) & all(isfinite(double(dat)),3);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction CP = init_cp(VF,x3)\nn = 8;\nm = length(VF);\np = length(x3);\nCP.mom0 = zeros(1,n,p)+eps;\nCP.mom1 = zeros(m,n,p);\nCP.mom2 = zeros(m,m,n,p)+eps;\n\n% Occasionally the dynamic range of the images is such that many voxels\n% all have the same intensity. Adding cv0 is an attempt to improve the\n% stability of the algorithm if this occurs. The value 0.083 was obtained\n% from var(rand(1000000,1)). It prbably isn't the best way of doing\n% things, but it appears to work.\nCP.cv0 = zeros(m,m);\nfor i=1:m,\n\tif spm_type(VF(i).dt(1),'intt'),\n\t\tCP.cv0(i,i)=0.083*mean(VF(i).pinfo(1,:));\n\tend;\nend;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction CP = shake_cp(CP)\nCP.mom0(:,5,:) = CP.mom0(:,1,:);\nCP.mom0(:,6,:) = CP.mom0(:,2,:);\nCP.mom0(:,7,:) = CP.mom0(:,3,:);\nCP.mom1(:,5,:) = CP.mom1(:,1,:);\nCP.mom1(:,6,:) = CP.mom1(:,2,:);\nCP.mom1(:,7,:) = CP.mom1(:,3,:);\nCP.mom1(:,8,:) = 0;\nCP.mom2(:,:,5,:) = CP.mom2(:,:,1,:);\nCP.mom2(:,:,6,:) = CP.mom2(:,:,2,:);\nCP.mom2(:,:,7,:) = CP.mom2(:,:,3,:);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction CP = update_cp_est(CP,P,dat,msk,p)\nm = size(dat,3);\nd = size(P);\nP = reshape(P,[d(1)*d(2),d(3)]);\ndat = reshape(dat,[d(1)*d(2),m]);\nP(~msk(:),:) = [];\ndat(~msk(:),:) = [];\nfor i=1:size(CP.mom0,2),\n\tCP.mom0(1,i,p) = sum(P(:,i));\n\tCP.mom1(:,i,p) = sum((P(:,i)*ones(1,m)).*dat)';\n\tCP.mom2(:,:,i,p) = ((P(:,i)*ones(1,m)).*dat)'*dat;\nend;\n\nfor i=1:size(CP.mom0,2),\n\tCP.mg(1,i) = sum(CP.mom0(1,i,:),3);\n\tCP.mn(:,i) = sum(CP.mom1(:,i,:),3)/CP.mg(1,i);\n\n\ttmp = (CP.mg(1,i).*CP.mn(:,i))*CP.mn(:,i)';\n\ttmp = tmp-eye(size(tmp))*eps*1e6;\n\tCP.cv(:,:,i) = (sum(CP.mom2(:,:,i,:),4) - tmp)/CP.mg(1,i) + CP.cv0;\nend;\nCP.mg = CP.mg/sum(CP.mg);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [p,ll] = get_p(cor,msk,s,sums,CP,bf)\nd = [size(cor) 1 1];\nn = size(CP.mg,2);\ncor = reshape(cor,d(1)*d(2),d(3));\ncor = cor(msk,:);\np = zeros(d(1)*d(2),n);\nif ~any(msk), p = reshape(p,d(1),d(2),n); ll=0; return; end;\n\nfor i=1:n,\n\tamp = 1/sqrt((2*pi)^d(3) * det(CP.cv(:,:,i)));\n\tdst = (cor-ones(size(cor,1),1)*CP.mn(:,i)')/sqrtm(CP.cv(:,:,i));\n\tdst = sum(dst.*dst,2);\n\ttmp = s(:,:,i);\n\tp(msk,i) = (amp*CP.mg(1,i)/sums(i))*exp(-0.5*dst).*tmp(msk) +eps;\nend;\nsp = sum(p,2);\nll = sum(log(sp(msk).*bf(msk)+eps));\nsp(~msk) = Inf;\nfor i=1:n, p(:,i) = p(:,i)./sp; end;\np = reshape(p,d(1),d(2),n);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction SP = init_sp(flags,VF,PG)\nSP.VB = spm_vol(flags.priors);\nMM = get_affine_mapping(VF,PG,flags.affreg);\n%VF = spm_vol(PF);\nSP.MM = MM*VF(1).mat;\nSP.w = 0.98;\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction s = get_sp(SP,x1,x2,x3)\n[X1,X2,X3] = ndgrid(x1,x2,x3);\n[Y1,Y2,Y3] = affine_transform(X1,X2,X3,SP.VB(1).mat\\SP.MM);\nw1 = SP.w;\nw2 = (1-w1)/2;\ns = zeros([size(Y1),4]);\nfor i=1:3,\n\ts(:,:,i) = spm_sample_vol(SP.VB(i),Y1,Y2,Y3,1)*w1+w2;\nend;\ns(:,:,4:8) = repmat(abs(1-sum(s(:,:,1:3),3))/5,[1 1 5]);\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [g,w,c] = get_gwc(VF,BP,SP,CP,sums,wc)\n\nif wc,\n\tVC = VF;\n\tfor j=1:length(VF),\n\t\t[pth,nm,xt,vr] = spm_fileparts(deblank(VF(j).fname));\n\t\tVC(j).fname = fullfile(pth,['m' nm xt vr]);\n\t\tVC(j).descrip = 'Bias corrected image';\n\tend;\n\tVC = spm_create_vol(VC);\nend;\n\nspm_progress_bar('Init',VF(1).dim(3),'Creating Segmented','planes completed');\nx1 = 1:VF(1).dim(1);\nx2 = 1:VF(1).dim(2);\nx3 = 1:VF(1).dim(3);\n\ng = uint8(0); g(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;\nw = uint8(0); w(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;\nc = uint8(0); c(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;\n\nfor pp=1:length(x3),\n\tbf = get_bp(BP,x1,x2,x3(pp));\n\t[raw,msk] = get_raw(VF,x1,x2,x3(pp));\n\tcor = raw.*bf;\n\tif wc,\n\t\tfor j=1:length(VC),\n\t\t\tVC(j) = spm_write_plane(VC(j),cor(:,:,j),pp);\n\t\tend;\n\tend;\n\ts = get_sp(SP,x1,x2,x3(pp));\n\tp = get_p(cor,msk,s,sums,CP,bf);\n\tg(:,:,pp) = uint8(round(p(:,:,1)*255));\n\tw(:,:,pp) = uint8(round(p(:,:,2)*255));\n\tc(:,:,pp) = uint8(round(p(:,:,3)*255));\n\n\tspm_progress_bar('Set',pp);\nend;\nspm_progress_bar('Clear');\n\nreturn;\n%=======================================================================\n \n%=======================================================================\nfunction [g,w,c,b] = clean_gwc(g,w,c)\nb = w;\nb(1) = w(1);\n\n% Build a 3x3x3 seperable smoothing kernel\n%-----------------------------------------------------------------------\nkx=[0.75 1 0.75];\nky=[0.75 1 0.75];\nkz=[0.75 1 0.75];\nsm=sum(kron(kron(kz,ky),kx))^(1/3);\nkx=kx/sm; ky=ky/sm; kz=kz/sm;\n\n% Erosions and conditional dilations\n%-----------------------------------------------------------------------\nniter = 32;\nspm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');\nfor j=1:niter,\n\tif j>2, th=0.15; else th=0.6; end; % Dilate after two its of erosion.\n\tfor i=1:size(b,3),\n\t\tgp = double(g(:,:,i));\n\t\twp = double(w(:,:,i));\n\t\tbp = double(b(:,:,i))/255;\n\t\tbp = (bp>th).*(wp+gp);\n\t\tb(:,:,i) = uint8(round(bp));\n\tend;\n\tspm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);\n\tspm_progress_bar('Set',j);\nend;\nth = 0.05;\nfor i=1:size(b,3),\n\tgp = double(g(:,:,i))/255;\n\twp = double(w(:,:,i))/255;\n\tcp = double(c(:,:,i))/255;\n\tbp = double(b(:,:,i))/255;\n\tbp = ((bp>th).*(wp+gp))>th;\n\tg(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));\n\tw(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));\n\tc(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));\n b(:,:,i) = uint8(round(255*bp));\nend;\nspm_progress_bar('Clear');\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_cd.m", "ext": ".m", "path": "spm5-master/spm_config_cd.m", "size": 1166, "source_encoding": "utf_8", "md5": "87ed5d6149a086f5d922fb7be08d85d3", "text": "function opts = spm_config_cd\n% Configuration file for changing directory function\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Darren Gitelman\n% $Id: spm_config_cd.m 587 2006-08-07 04:38:22Z Darren $\n\ndata.type = 'files';\ndata.name = 'Select a directory';\ndata.tag = 'directory';\ndata.filter = 'dir';\ndata.num = 1;\ndata.help = {'Select a directory to change to.'};\n\nopts.type = 'branch';\nopts.name = 'Change Directory';\nopts.tag = 'cdir';\nopts.val = {data};\nopts.prog = @my_job_cd;\np1 = [...\n'This facilty allows programming a directory change. Directories are ',...\n'selected in the right listbox.'];\n\nopts.help = {p1};\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction my_job_cd(varargin)\n% job can be a job structure or the directory to change to.\njob = varargin{1};\nif isstruct(job)\n jobDir = job.directory;\nelse\n jobDir = job;\nend\nif ~isempty(jobDir),\n cd(char(jobDir));\n fprintf('New working directory: %s\\n', char(jobDir));\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_bias_estimate.m", "ext": ".m", "path": "spm5-master/spm_bias_estimate.m", "size": 6359, "source_encoding": "utf_8", "md5": "418562b13c25a375ce47e36d439200a8", "text": "function T = spm_bias_estimate(V,flags)\n% Estimate image nonuniformity.\n%\n% FORMAT T = spm_bias_estimate(V,flags)\n% V - filename or vol struct of image\n% flags - a structure containing the following fields\n% nbins - number of bins in histogram (1024)\n% reg - amount of regularisation (1)\n% cutoff - cutoff (in mm) of basis functions (35)\n% T - DCT of bias field.\n%\n% The objective function is related to minimising the entropy of\n% the image histogram, but is modified slightly.\n% This fixes the problem with the SPM99 non-uniformity correction\n% algorithm, which tends to try to reduce the image intensities. As\n% the field was constrainded to have an average value of one, then\n% this caused the field to bend upwards in regions not included in\n% computations of image non-uniformity.\n%\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_bias_estimate.m 184 2005-05-31 13:23:32Z john $\n\n\ndef_flags = struct('nbins',256,'reg',0.01,'cutoff',30);\nif nargin < 2,\n flags = def_flags;\nelse\n fnms = fieldnames(def_flags);\n for i=1:length(fnms),\n if ~isfield(flags,fnms{i}),\n flags.(fnms{i}) = def_flags.(fnms{i});\n end;\n end;\nend;\n\nreg = flags.reg; % Regularisation\nco = flags.cutoff; % Highest wavelength of DCT\nnh = flags.nbins;\n\nif ischar(V), V = spm_vol(V); end;\nmx = 1.1*get_max(V); % Maximum value in histogram\n\ntmp = sqrt(sum(V(1).mat(1:3,1:3).^2));\nnbas = max(round((V(1).dim(1:3).*tmp)/co),[1 1 1]);\nB1 = spm_dctmtx(V(1).dim(1),nbas(1));\nB2 = spm_dctmtx(V(1).dim(2),nbas(2));\nB3 = spm_dctmtx(V(1).dim(3),nbas(3));\n\n[T,IC0] = get_priors(V,nbas,reg,4);\nIC0 = IC0(2:end,2:end);\n%tmp = diag(IC0);\n%tmp = tmp(tmp>0);\n%offset = 0.5*(log(2*pi)*length(tmp) + sum(log(tmp)));\noffset = 0;\nfprintf('*** %s ***\\nmax = %g, Bases = %dx%dx%d\\n', V.fname, mx, nbas);\n\nolpp = Inf;\nx = (0:(nh-1))'*(mx/(nh-1));\nplt = zeros(64,2);\n\nfor iter = 1:128,\n\n\t[Alpha,Beta,ll, h, n] = spm_bias_mex(V,B1,B2,B3,T,[mx nh]);\n\tT = T(:);\n\tT = T(2:end);\n\tAlpha = Alpha(2:end,2:end)/n;\n\tBeta = Beta(2:end)/n;\n\tll = ll/n;\n\tlp = offset + 0.5*(T'*IC0*T);\n\tlpp = lp+ll;\n\tT = (Alpha + IC0)\\(Alpha*T - Beta);\n\tT = reshape([0 ; T],nbas);\n\n\t[pth,nm] = fileparts(deblank(V.fname));\n\tS = fullfile(pth,['bias_' nm '.mat']);\n\t%S = ['bias_' nm '.mat'];\n\tsave(S,'V','T','h');\n\tfprintf('%g %g\\n', ll, lp);\n\n\tif iter==1,\n\t\tfg = spm_figure('FindWin','Interactive');\n\t\tif ~isempty(fg),\n\t\t\tspm_figure('Clear',fg);\n\t\t\tax1 = axes('Position', [0.15 0.1 0.8 0.35],...\n\t\t\t\t'Box', 'on','Parent',fg);\n\t\t\tax2 = axes('Position', [0.15 0.6 0.8 0.35],...\n\t\t\t\t'Box', 'on','Parent',fg);\n\t\tend;\n\t\th0 = h;\n\tend;\n\tif ~isempty(fg),\n\t\tplt(iter,1) = ll;\n\t\tplt(iter,2) = lpp;\n\t\tplot((1:iter)',plt(1:iter,:),'Parent',ax1,'LineWidth',2);\n\t\tset(get(ax1,'Xlabel'),'string','Iteration','FontSize',10);\n\t\tset(get(ax1,'Ylabel'),'string','Negative Log-Likelihood','FontSize',10);\n\t\tset(ax1,'Xlim',[1 iter+1]);\n\n\t\tplot(x,h0,'r', x,h,'b', 'Parent',ax2);\n\t\tset(ax2,'Xlim',[0 x(end)]);\n\t\tset(get(ax2,'Xlabel'),'string','Intensity','FontSize',10);\n\t\tset(get(ax2,'Ylabel'),'string','Frequency','FontSize',10);\n\t\tdrawnow;\n\tend;\n\n\tif olpp-lpp < 1e-5, delete([ax1 ax2]); break; end;\n\tolpp = lpp;\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction mx = get_max(V)\nmx = 0;\nfor i=1:V.dim(3),\n\timg = spm_slice_vol(V,spm_matrix([0 0 i]),V.dim(1:2),0);\n\tmx = max([mx max(img(:))]);\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [T,IC0] = get_priors(VF,nbas,reg,o)\n% Set up a priori covariance matrix\nvx = sqrt(sum(VF(1).mat(1:3,1:3).^2));\nkx = (((1:nbas(1))'-1)*pi/vx(1)/VF(1).dim(1)*10).^2;\nky = (((1:nbas(2))'-1)*pi/vx(2)/VF(1).dim(2)*10).^2;\nkz = (((1:nbas(3))'-1)*pi/vx(3)/VF(1).dim(3)*10).^2;\n\nswitch o,\ncase 0, % Cost function based on sum of squares\nIC0 = kron(kz.^0,kron(ky.^0,kx.^0))*reg;\n\ncase 1, % Cost function based on sum of squared 1st derivatives\nIC0 = ( kron(kz.^1,kron(ky.^0,kx.^0)) +...\n kron(kz.^0,kron(ky.^1,kx.^0)) +...\n kron(kz.^0,kron(ky.^0,kx.^1)) )*reg;\n\ncase 2, % Cost function based on sum of squared 2nd derivatives\nIC0 = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^2,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^0,kx.^2)) +...\n 2*kron(kz.^1,kron(ky.^1,kx.^0)) +...\n 2*kron(kz.^1,kron(ky.^0,kx.^1)) +...\n 2*kron(kz.^0,kron(ky.^1,kx.^1)) )*reg;\n\ncase 3, % Cost function based on sum of squared 3rd derivatives\nIC0 = (1*kron(kz.^3,kron(ky.^0,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^3,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^0,kx.^3)) +...\n 3*kron(kz.^2,kron(ky.^1,kx.^0)) +...\n 3*kron(kz.^2,kron(ky.^0,kx.^1)) +...\n 3*kron(kz.^1,kron(ky.^2,kx.^0)) +...\n 3*kron(kz.^0,kron(ky.^2,kx.^1)) +...\n 3*kron(kz.^1,kron(ky.^0,kx.^2)) +...\n 3*kron(kz.^0,kron(ky.^1,kx.^2)) +...\n 6*kron(kz.^1,kron(ky.^1,kx.^1)) )*reg;\n\ncase 4, % Cost function based on sum of squares of 4th derivatives\nIC0 = (1*kron(kz.^4,kron(ky.^0,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^4,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^0,kx.^4)) +...\n 4*kron(kz.^3,kron(ky.^1,kx.^0)) +...\n 4*kron(kz.^3,kron(ky.^0,kx.^1)) +...\n 4*kron(kz.^1,kron(ky.^3,kx.^0)) +...\n 4*kron(kz.^0,kron(ky.^3,kx.^1)) +...\n 4*kron(kz.^1,kron(ky.^0,kx.^3)) +...\n 4*kron(kz.^0,kron(ky.^1,kx.^3)) +...\n 6*kron(kz.^2,kron(ky.^2,kx.^0)) +...\n 6*kron(kz.^2,kron(ky.^0,kx.^2)) +...\n 6*kron(kz.^0,kron(ky.^2,kx.^2)) +...\n 12*kron(kz.^2,kron(ky.^1,kx.^1)) +...\n 12*kron(kz.^1,kron(ky.^2,kx.^1)) +...\n 12*kron(kz.^1,kron(ky.^1,kx.^2)) )*reg;\notherwise,\nerror('Unknown regularisation form');\nend;\n\nIC0(1) = max([max(IC0) 1e4]);\nIC0 = diag(IC0);\n\n% Initial estimate for intensity modulation field\nT = zeros(nbas(1),nbas(2),nbas(3),1);\nreturn;\n%=======================================================================\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_conman.m", "ext": ".m", "path": "spm5-master/spm_eeg_conman.m", "size": 25044, "source_encoding": "utf_8", "md5": "05a1b8c0a88b56c840fba328224b016f", "text": "function varargout = spm_eeg_conman(varargin)\n% internal function that allows to enter componentwise contrast weights.\n% FORMAT varargout = spm_eeg_conman(varargin)\n% \n%_______________________________________________________________________\n%\n% The following comments are generated by the matlab guide-system:\n% SPM_EEG_CONMAN M-file for spm_eeg_conman.fig\n% SPM_EEG_CONMAN, by itself, creates a new SPM_EEG_CONMAN or raises the existing\n% singleton*.\n%\n% H = SPM_EEG_CONMAN returns the handle to a new SPM_EEG_CONMAN or the handle to\n% the existing singleton*.\n%\n% SPM_EEG_CONMAN('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SPM_EEG_CONMAN.M with the given input arguments.\n%\n% SPM_EEG_CONMAN('Property','Value',...) creates a new SPM_EEG_CONMAN or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before spm_eeg_conman_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to spm_eeg_conman_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n% Edit the above text to modify the response to help spm_eeg_conman\n% Last Modified by GUIDE v2.5 18-Dec-2003 14:21:19\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Stefan Kiebel\n% $Id: spm_eeg_conman.m 539 2006-05-19 17:59:30Z Darren $\n\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @spm_eeg_conman_OpeningFcn, ...\n 'gui_OutputFcn', @spm_eeg_conman_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin & isstr(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before spm_eeg_conman is made visible.\nfunction spm_eeg_conman_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to spm_eeg_conman (see VARARGIN)\n\n% Choose default command line output for spm_eeg_conman\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n\n% start of own code\nif length(varargin) == 0\n try\n % called from contrast manager?\n h = findobj('Tag','ConMan');\n SPM = get(h, 'UserData');\n catch\n P = spm_select(1,'^SPM\\.mat$','Select SPM.mat');\n load(P);\n end\nelse\n SPM = varargin{1};\nend\n\n% SPM colour scheme:\n% background: [0.7 0.7 0.7]\n% edit window background [0.8 0.8 1]\n% buttons: blue: [0 0 1]\n% red: [1 0 0]\n% green: [0 1 0]\n% magenta: [1 0 1]\ncolour.background = [0.7 0.7 0.7];\nset(handles.conman_eeg, 'Color', colour.background);\n\n% code for re-sizing to actual screen size\nWS = spm('WinScale');\t\t\t\t%-Window scaling factors\nFS = spm('FontSizes');\t\t\t\t%-Scaled font sizes\nPF = spm_platform('fonts');\t\t\t%-Font names (for this platform)\nif spm_matlab_version_chk('7') >= 0\t\t%-Screen size\n\tS0 = get(0, 'MonitorPosition');\n\tS0 = S0(1,:);\nelse\n\tS0 = get(0,'ScreenSize');\nend;\n\nnames = fieldnames(handles);\nfor i = 1:length(names)\n if ~strcmpi(names{i}, 'output')\n h = eval(sprintf('handles.%s;', names{i}));\n if length(h) == 1 & isnumeric(h)\n set(h, 'Position', get(h, 'Position').*WS);\n \n if ~strcmpi(get(h, 'Type'), 'figure')\n if strcmpi(get(h, 'Style'), 'Edit') | strcmpi(get(h, 'Style'), 'PushButton') | strcmpi(get(h, 'Style'), 'RadioButton')\n eval(sprintf('set(handles.%s, ''FontSize'', FS(9));', names{i}));\n else\n eval(sprintf('set(handles.%s, ''FontSize'', FS(10));', names{i}));\n end\n end \n end\n end\nend\n\nif ~isfield(SPM, 'eeg')\n error('No design components found. Use the EEG model setup.');\n return;\nend\n\nhandles.current_data = SPM;\nguidata(hObject, handles);\n\n% find out whether user wants t- or F-contrast weights\nif get(findobj('Tag', 'D_TF', 'String', 't-contrast'), 'Value')\n STAT = 'T';\nelseif get(findobj('Tag', 'D_TF', 'String', 'F-contrast'), 'Value')\n STAT = 'F';\nelse\n error('Could not identify STAT');\nend\n\nMfactor = 8;\nif SPM.eeg.Nfactors > Mfactor\n error('The component editor cannot handle more than 8 factors');\nend\n\n% adjust appearance to number of factors\n%-----------------------------------------\n% Hide uicontrols\ns = [1:SPM.eeg.Nfactors];\nfor i = 1:Mfactor\n if ~ismember(i, s)\n eval(sprintf('set(handles.factor%d, ''Visible'', ''off'')', i))\n eval(sprintf('set(handles.factor%d_title, ''Visible'', ''off'')', i))\n eval(sprintf('set(handles.project%d, ''Visible'', ''off'')', i))\n eval(sprintf('set(handles.Generate%d, ''Visible'', ''off'')', i))\n else\n if strcmpi(STAT, 'T')\n eval(sprintf('set(handles.factor%d, ''Max'', 1)', i))\n else\n eval(sprintf('set(handles.factor%d, ''Max'', 2)', i))\n end\n \n % 'project' radiobuttons\n if strcmpi(SPM.eeg.factor{i}, 'time')\n eval(sprintf('set(handles.project%d, ''Value'', get(handles.project%d, ''Max''))', i, i))\n end\n \n % make buttons invisible, if design component identity or constant\n % exception for identity compoment which is titled 'time', i.e.\n % time factor in conventional design\n if strcmpi(SPM.xBF.name_d{1, i}, 'Identity') | strcmpi(SPM.xBF.name_d{1, i}, 'Constant')\n eval(sprintf('set(handles.project%d, ''Visible'', ''off'')', i))\n if ~strcmpi(SPM.eeg.factor{i}, 'time')\n eval(sprintf('set(handles.Generate%d, ''Visible'', ''off'')', i))\n end\n end\n \n end\nend\n\neval(sprintf('pos1 = get(handles.factor%d, ''Position'');', Mfactor));\neval(sprintf('pos3 = get(handles.factor%d, ''Position'');', SPM.eeg.Nfactors));\n\ndy = pos3(2) - pos1(2);\n\nif dy > 0\n % adjust axes and uicontrols\n\n % figure\n pos = get(handles.conman_eeg, 'Position');\n pos(4) = pos(4) - dy;\n set(handles.conman_eeg, 'Position', pos);\n\n % contrast input windows\n for i = 1:SPM.eeg.Nfactors\n eval(sprintf('pos = get(handles.factor%d, ''Position'');', i));\n pos(2) = pos(2) - dy;\n eval(sprintf('set(handles.factor%d, ''Position'', [%f %f %f %f]);', i, pos(1), pos(2), pos(3), pos(4))) \n \n eval(sprintf('pos = get(handles.factor%d_title, ''Position'');', i));\n pos(2) = pos(2) - dy;\n eval(sprintf('set(handles.factor%d_title, ''Position'', [%f %f %f %f]);', i, pos(1), pos(2), pos(3), pos(4))) \n \n eval(sprintf('pos = get(handles.project%d, ''Position'');', i));\n pos(2) = pos(2) - dy;\n eval(sprintf('set(handles.project%d, ''Position'', [%f %f %f %f]);', i, pos(1), pos(2), pos(3), pos(4))) \n\n eval(sprintf('pos = get(handles.Generate%d, ''Position'');', i));\n pos(2) = pos(2) - dy;\n eval(sprintf('set(handles.Generate%d, ''Position'', [%f %f %f %f]);', i, pos(1), pos(2), pos(3), pos(4))) \n\n end\nend\n\nfor i = 1:SPM.eeg.Nfactors\n % rename factor titles and set tooltipstrings\n eval(sprintf('set(handles.factor%d_title, ''String'', '' %s'');', i, SPM.eeg.factor{i}));\n eval(sprintf('set(handles.factor%d, ''ToolTipString'', ''Enter contrast vector/matrix for factor %s'');', i, SPM.eeg.factor{i}));\nend\n\n% switch off contrast weights editor of conventional conman\nset(findobj('Tag', 'D_ConMtx'), 'Enable', 'off');\n\n\n% UIWAIT makes spm_eeg_conman wait for user response (see UIRESUME)\n% uiwait(handles.conman_eeg);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = spm_eeg_conman_OutputFcn(hObject, eventdata, handles)\n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction factor1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to factor1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\nfunction factor1_Callback(hObject, eventdata, handles)\n% hObject handle to factor1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of factor1 as text\n% str2double(get(hObject,'String')) returns contents of factor1 as a double\n\n% --- Executes during object creation, after setting all properties.\nfunction factor2_CreateFcn(hObject, eventdata, handles)\n% hObject handle to factor2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\nfunction factor2_Callback(hObject, eventdata, handles)\n% hObject handle to factor2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of factor2 as text\n% str2double(get(hObject,'String')) returns contents of factor2 as a double\n\n% --- Executes during object creation, after setting all properties.\nfunction factor3_CreateFcn(hObject, eventdata, handles)\n% hObject handle to factor3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction factor3_Callback(hObject, eventdata, handles)\n% hObject handle to factor3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of factor3 as text\n% str2double(get(hObject,'String')) returns contents of factor3 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction factor4_CreateFcn(hObject, eventdata, handles)\n% hObject handle to factor4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\nfunction factor4_Callback(hObject, eventdata, handles)\n% hObject handle to factor4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of factor4 as text\n% str2double(get(hObject,'String')) returns contents of factor4 as a double\n\n% --- Executes during object creation, after setting all properties.\nfunction factor5_CreateFcn(hObject, eventdata, handles)\n% hObject handle to factor5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction factor5_Callback(hObject, eventdata, handles)\n% hObject handle to factor5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of factor5 as text\n% str2double(get(hObject,'String')) returns contents of factor5 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction factor6_CreateFcn(hObject, eventdata, handles)\n% hObject handle to factor6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\nfunction factor6_Callback(hObject, eventdata, handles)\n% hObject handle to factor6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of factor6 as text\n% str2double(get(hObject,'String')) returns contents of factor6 as a double\n\n% --- Executes during object creation, after setting all properties.\nfunction factor7_CreateFcn(hObject, eventdata, handles)\n% hObject handle to factor7 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction factor7_Callback(hObject, eventdata, handles)\n% hObject handle to factor7 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of factor7 as text\n% str2double(get(hObject,'String')) returns contents of factor7 as a double\n\n% --- Executes during object creation, after setting all properties.\nfunction factor8_CreateFcn(hObject, eventdata, handles)\n% hObject handle to factor8 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction factor8_Callback(hObject, eventdata, handles)\n% hObject handle to factor8 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of factor8 as text\n% str2double(get(hObject,'String')) returns contents of factor8 as a double\n\n\n% --- Executes on button press in compute.\nfunction compute_Callback(hObject, eventdata, handles)\n% hObject handle to compute (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% check lengths of all vectors/matrices and compute output\nSPM = handles.current_data;\n\n% get the contrast component vectors/matrices\nfor i = 1:SPM.eeg.Nfactors\n eval(sprintf('c{%d} = getappdata(handles.Generate%d, ''c'');', i, i));\n if isempty(c{i})\n eval(sprintf('str = get(handles.factor%d, ''String'');', i, i));\n\n for j = 1:size(str, 1)\n tmp{j} = str2num(str(j,:));\n end\n ml = 0;\n for j = 1:length(tmp)\n ml = max(ml, length(tmp{j}));\n end\n\n if ml == 0\n spm('alert*', sprintf('Input weights for factor %s', SPM.eeg.factor{i}))\n return;\n end\n\n c{i} = zeros(size(str, 1), ml);\n for j = 1:size(str, 1)\n c{i}(j, 1:length(tmp{j})) = tmp{j};\n end\n end\nend\n\n% check them\nw = 0;\nfor i = 1:SPM.eeg.Nfactors\n eval(sprintf('Sp = get(handles.project%d, ''Value'');', i));\n if Sp\n c{i} = spm_eeg_contrast_project(SPM, i, c{i});\n elseif size(c{i}, 2) < size(SPM.eeg.X_d{1, i}, 2)\n c{i} = [c{i} zeros(size(c,1), size(SPM.eeg.X_d{1, i}, 2) - size(c{i}, 2))];\n eval(sprintf('set(handles.factor%d, ''String'', num2str(c{%d}));', i, i));\n elseif size(c{i}, 2) > size(SPM.eeg.X_d{1, i}, 2)\n warning('Wrong contrast vector length for factor %s', SPM.eeg.factor{i});\n w = 1;\n end\nend\n\nif ~w\n \n xCon = [];\n for i = 1:SPM.eeg.Nfactors\n xCon.eeg.Con{1, i} = c{i};\n end\n \n c_out = spm_eeg_contrast(SPM, xCon);\n\n % output\n handles.output.c_out = c_out;\n handles.output.c = c; % components\n\n % look for edit window of contrast manager\n h = findobj('Tag', 'D_ConMtx');\n if ~isempty(h)\n set(h, 'String', num2str(c_out));\n setappdata(handles.conman_eeg, 'c', c_out)\n spm_conman('D_ConMtx_CB')\n end\nelse\n handles.output = {};\nend\n\n% --- Executes on button press in reset.\nfunction reset_Callback(hObject, eventdata, handles)\n% hObject handle to reset (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nSPM = handles.current_data;\n\nfor i = 1:SPM.eeg.Nfactors\n % remove strings from all factor windows\n eval(sprintf('set(handles.factor%d, ''String'', '''');', i));\n % remove components from Generate pushbuttons\n eval(sprintf('h = handles.Generate%d;', i));\n if isappdata(h, 'c')\n rmappdata(h, 'c');\n end\nend\n\n% --- Executes on button press in cancel.\nfunction cancel_Callback(hObject, eventdata, handles)\n% hObject handle to cancel (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\ndelete(handles.conman_eeg);\nset(findobj('Tag', 'D_ConMtx'), 'Enable', 'on');\n\n\n% --- Executes on key press over conman_eeg with no controls selected.\nfunction conman_eeg_KeyPressFcn(hObject, eventdata, handles)\n% hObject handle to conman_eeg (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in project1.\nfunction project1_Callback(hObject, eventdata, handles)\n% hObject handle to project1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in project2.\nfunction project2_Callback(hObject, eventdata, handles)\n% hObject handle to project2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of project2\n\n\n% --- Executes on button press in radiobutton2.\nfunction radiobutton2_Callback(hObject, eventdata, handles)\n% hObject handle to radiobutton2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of radiobutton2\n\n\n% --- Executes on button press in project3.\nfunction project3_Callback(hObject, eventdata, handles)\n% hObject handle to project3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of project3\n\n\n% --- Executes on button press in project6.\nfunction project6_Callback(hObject, eventdata, handles)\n% hObject handle to project6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of project6\n\n\n% --- Executes on button press in project5.\nfunction project5_Callback(hObject, eventdata, handles)\n% hObject handle to project5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of project5\n\n\n% --- Executes on button press in project7.\nfunction project7_Callback(hObject, eventdata, handles)\n% hObject handle to project7 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of project7\n\n\n% --- Executes on button press in project8.\nfunction project8_Callback(hObject, eventdata, handles)\n% hObject handle to project8 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of project8\n\n\n% --- Executes on button press in project4.\nfunction project4_Callback(hObject, eventdata, handles)\n% hObject handle to project4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of project4\n\n\n% --- Executes on button press in Generate1.\nfunction Generate1_Callback(hObject, eventdata, handles)\n% hObject handle to Generate1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in Generate2.\nfunction Generate2_Callback(hObject, eventdata, handles)\n% hObject handle to Generate2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nSPM = handles.current_data;\n[c, xCon] = spm_eeg_contrast_generate(SPM);\nset(handles.factor2, 'String', num2str(c));\nsetappdata(hObject, 'c', c);\nset(handles.project2, 'Value', get(handles.project2, 'Max'));\n\n% --- Executes on button press in Generate4.\nfunction Generate4_Callback(hObject, eventdata, handles)\n% hObject handle to Generate4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in Generate6.\nfunction Generate6_Callback(hObject, eventdata, handles)\n% hObject handle to Generate6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in Generate8.\nfunction Generate8_Callback(hObject, eventdata, handles)\n% hObject handle to Generate8 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in Generate3.\nfunction Generate3_Callback(hObject, eventdata, handles)\n% hObject handle to Generate3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in Generate5.\nfunction Generate5_Callback(hObject, eventdata, handles)\n% hObject handle to Generate5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in Generate7.\nfunction Generate7_Callback(hObject, eventdata, handles)\n% hObject handle to Generate7 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_reorient.m", "ext": ".m", "path": "spm5-master/spm_config_reorient.m", "size": 3415, "source_encoding": "utf_8", "md5": "d67a3c54751637e0e021b309b433f528", "text": "function opts = spm_config_reorient\n% Configuration file for reorient images\n% Apply a given transformation matrix or reorientation parameters by\n% left-multiplying the original image orientation with it.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Volkmar Glauche\n% $Id: spm_config_movefile.m 549 2006-06-07 12:37:29Z volkmar $\n\n%_______________________________________________________________________\n\n\nsrcfiles.type = 'files';\nsrcfiles.name = 'Images to reorient';\nsrcfiles.tag = 'srcfiles';\nsrcfiles.filter = 'image';\nsrcfiles.num = [0 Inf];\nsrcfiles.help = {'Select images to reorient.'};\n\ntransM.type = 'entry';\ntransM.name = 'Reorientation matrix';\ntransM.tag = 'transM';\ntransM.strtype = 'e';\ntransM.num = [4 4];\np1 = 'Enter a valid 4x4 matrix for reorientation.';\np2 = 'Example: This will L-R flip the images.';\np3 = ' -1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1';\ntransM.help = {p1,'',p2,'',p3};\n\ntransprm.type = 'entry';\ntransprm.name = 'Reorientation parameters';\ntransprm.tag = 'transprm';\ntransprm.strtype = 'e';\ntransprm.num = [1 12];\np0 = 'Enter 12 reorientation parameters.';\np1 = 'P(1) - x translation';\np2 = 'P(2) - y translation';\np3 = 'P(3) - z translation';\np4 = 'P(4) - x rotation about - {pitch} (radians)';\np5 = 'P(5) - y rotation about - {roll} (radians)';\np6 = 'P(6) - z rotation about - {yaw} (radians)';\np7 = 'P(7) - x scaling';\np8 = 'P(8) - y scaling';\np9 = 'P(9) - z scaling';\np10 = 'P(10) - x affine';\np11 = 'P(11) - y affine';\np12 = 'P(12) - z affine';\np13 = 'Parameters are entered as listed above and then processed by spm_matrix.';\np14 = ['Example: This will L-R flip the images (extra spaces are inserted between ',...\n 'each group for illustration purposes).'];\np15 = ' 0 0 0 0 0 0 -1 0 0 0 0 0';\n\ntransprm.help = {p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,'',p14,'',p15,''};\n\ntransform.type = 'choice';\ntransform.name = 'Reorient by';\ntransform.tag = 'transform';\ntransform.values = {transM, transprm};\ntransform.help = {'Specify reorientation method.'};\n\nopts.type = 'branch';\nopts.name = 'Reorient images';\nopts.tag = 'reorient';\nopts.val = {srcfiles,transform};\nopts.prog = @my_reorient;\nopts.vfiles = @vfiles_reorient;\nopts.help = {[...\n 'This facility allows to reorient images in a batch. The reorientation parameters ' ...\n 'can be given either as a 4x4 matrix or as parameters as defined for spm_matrix.m. ' ...\n 'The new image orientation will be computed by PRE-multiplying the original '...\n 'orientation matrix with the supplied matrix.']};\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction my_reorient(varargin)\njob = varargin{1};\nif isfield(job.transform,'transprm')\n job.transform.transM = spm_matrix(job.transform.transprm);\nend;\nspm_progress_bar('Init', numel(job.srcfiles), 'Reorient', 'Images completed');\nfor k = 1:numel(job.srcfiles)\n M = spm_get_space(job.srcfiles{k});\n spm_get_space(job.srcfiles{k},job.transform.transM*M);\n spm_progress_bar('Set',k);\nend;\nspm_progress_bar('Clear');\nreturn;\n%-------------------------------------------------------------------------\n\nfunction vf = vfiles_reorient(job)\nsrcfiles = job.srcfiles{1};\nvf = {spm_select('CPath','image',srcfiles)};\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_latex.m", "ext": ".m", "path": "spm5-master/spm_latex.m", "size": 5190, "source_encoding": "utf_8", "md5": "a6cbdb66e672ce5b277533b297bb6370", "text": "function spm_latex(c)\n% Convert a job configuration structure into a series of LaTeX documents\n%\n% Note that this function works rather better in Matlab 7.x, than it\n% does under Matlab 6.x. This is primarily because of the slightly\n% different usage of the 'regexp' function.\n%____________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_latex.m 949 2007-10-16 08:19:45Z volkmar $\n\nif nargin==0, c = spm_config; end;\n\nfp = fopen('spm_manual.tex','w');\nfprintf(fp,'\\\\documentclass[a4paper,titlepage]{book}\\n');\nfprintf(fp,'\\\\usepackage{epsfig,amsmath,pifont,moreverb,minitoc}\\n');\nfprintf(fp,'%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n',...\n '\\usepackage[colorlinks=true,',...\n 'pdfpagemode=UseOutlines,',...\n 'pdftitle={SPM5 Manual},','pdfauthor={The SPM Team},',...\n 'pdfsubject={Statistical Parametric Mapping},',...\n 'pdfkeywords={neuroimaging, MRI, PET, EEG, MEG, SPM}',...\n ']{hyperref}');\n\nfprintf(fp,'\\\\pagestyle{headings}\\n\\\\bibliographystyle{plain}\\n\\n');\nfprintf(fp,'\\\\hoffset=15mm\\n\\\\voffset=-5mm\\n');\nfprintf(fp,'\\\\oddsidemargin=0mm\\n\\\\evensidemargin=0mm\\n\\\\topmargin=0mm\\n');\nfprintf(fp,'\\\\headheight=12pt\\n\\\\headsep=10mm\\n\\\\textheight=240mm\\n\\\\textwidth=148mm\\n');\nfprintf(fp,'\\\\marginparsep=5mm\\n\\\\marginparwidth=21mm\\n\\\\footskip=10mm\\n\\n');\n\nfprintf(fp,'\\\\title{\\\\huge{SPM5 Manual}}\\n');\nfprintf(fp,'\\\\author{The FIL Methods Group (and honorary members)}\\n');\nfprintf(fp,'\\\\begin{document}\\n');\nfprintf(fp,'\\\\maketitle\\n');\nfprintf(fp,'\\\\dominitoc\\\\tableofcontents\\n\\n');\nfprintf(fp,'\\\\newpage\\n\\\\section*{The SPM5 User Interface}\\n');\nwrite_help(c,fp);\nfor i=1:numel(c.values),\n if isfield(c.values{i},'tag'),\n part(c.values{i},fp);\n end;\nend;\n%fprintf(fp,'\\\\parskip=0mm\\n\\\\bibliography{methods_macros,methods_group,external}\\n\\\\end{document}\\n\\n');\nfprintf(fp,'\\\\parskip=0mm\\n');\nbibcstr = get_bib(fullfile(spm('dir'),'man','biblio'));\n\ntbxlist = dir(fullfile(spm('dir'),'toolbox'));\nfor k = 1:numel(tbxlist)\n if tbxlist(k).isdir,\n bibcstr=[bibcstr(:); get_bib(fullfile(spm('dir'),'toolbox', ...\n tbxlist(k).name))];\n end;\nend;\nbibcstr = strcat(bibcstr,',');\nbibstr = strcat(bibcstr{:});\nfprintf(fp,'\\\\bibliography{%s}\\n',bibstr(1:end-1));\nfprintf(fp,'\\\\end{document}\\n\\n');\nfclose(fp);\nreturn;\n\nfunction part(c,fp)\nif isstruct(c) && isfield(c,'tag'),\n fprintf(fp,'\\\\part{%s}\\n',texify(c.name));\n % write_help(c,fp);\n if isfield(c,'values'),\n for i=1:numel(c.values),\n if isfield(c.values{i},'tag'),\n fprintf(fp,'\\\\include{%s}\\n',c.values{i}.tag);\n chapter(c.values{i});\n end;\n end;\n end;\n if isfield(c,'val'),\n for i=1:numel(c.val),\n if isfield(c.val{i},'tag'),\n if chapter(c.val{i}),\n fprintf(fp,'\\\\include{%s}\\n',c.val{i}.tag);\n end;\n end;\n end;\n end;\nend;\nreturn;\n\nfunction sts = chapter(c)\nfp = fopen([c.tag '.tex'],'w');\nif fp==-1, sts = false; return; end;\n\nfprintf(fp,'\\\\chapter{%s \\\\label{Chap:%s}}\\n\\\\minitoc\\n\\n\\\\vskip 1.5cm\\n\\n',texify(c.name),c.tag);\nwrite_help(c,fp);\n\nswitch c.type,\ncase {'branch'},\n for i=1:numel(c.val),\n section(c.val{i},fp);\n end;\ncase {'repeat','choice'},\n for i=1:numel(c.values),\n section(c.values{i},fp);\n end;\nend;\nfclose(fp);\nsts = true;\nreturn;\n\nfunction section(c,fp,lev)\nif nargin<3, lev = 1; end;\nsec = {'section','subsection','subsubsection','paragraph','subparagraph'};\nif lev<=5,\n fprintf(fp,'\\n\\\\%s{%s}\\n',sec{lev},texify(c.name));\n write_help(c,fp);\n switch c.type,\n case {'branch'},\n for i=1:numel(c.val),\n section(c.val{i},fp,lev+1);\n end;\n case {'repeat','choice'},\n for i=1:numel(c.values),\n section(c.values{i},fp,lev+1);\n end;\n end;\nelse\n warning(['Too many nested levels... ' c.name]);\nend;\nreturn;\n\nfunction write_help(hlp,fp)\nif isstruct(hlp),\n if isfield(hlp,'help'),\n hlp = hlp.help;\n else\n return;\n end;\nend;\nif iscell(hlp),\n for i=1:numel(hlp),\n write_help(hlp{i},fp);\n end;\n return;\nend;\nstr = texify(hlp);\nfprintf(fp,'%s\\n\\n',str);\nreturn;\n\nfunction str = texify(str0)\nst1 = findstr(str0,'/*');\nen1 = findstr(str0,'*/');\nst = [];\nen = [];\nfor i=1:numel(st1),\n en1 = en1(en1>st1(i));\n if ~isempty(en1),\n st = [st st1(i)];\n en = [en en1(1)];\n en1 = en1(2:end);\n end;\nend;\n\nstr = [];\npen = 1;\nfor i=1:numel(st),\n str = [str clean_latex(str0(pen:st(i)-1)) str0(st(i)+2:en(i)-1)];\n pen = en(i)+2;\nend;\nstr = [str clean_latex(str0(pen:numel(str0)))];\nreturn;\n\nfunction str = clean_latex(str)\nstr = strrep(str,'$','\\$');\nstr = strrep(str,'&','\\&');\nstr = strrep(str,'_','\\_');\n%str = strrep(str,'\\','$\\\\$');\nstr = strrep(str,'|','$|$');\nstr = strrep(str,'>','$>$');\nstr = strrep(str,'<','$<$');\nreturn;\n\nfunction bibcstr = get_bib(bibdir)\nbiblist = dir(fullfile(bibdir,'*.bib'));\nbibcstr={};\nfor k = 1:numel(biblist)\n [p n e v] = fileparts(biblist(k).name);\n bibcstr{k} = fullfile(bibdir,n);\nend;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_coreg.m", "ext": ".m", "path": "spm5-master/spm_coreg.m", "size": 13725, "source_encoding": "utf_8", "md5": "443ab4fbbd6c152d6d0f0d385d72356f", "text": "function x = spm_coreg(varargin)\n% Between modality coregistration using information theory\n% FORMAT x = spm_coreg(VG,VF,params)\n% VG - handle for first image (see spm_vol).\n% VF - handle for second image.\n% x - the parameters describing the rigid body rotation.\n% such that a mapping from voxels in G to voxels in F\n% is attained by: VF.mat\\spm_matrix(x(:)')*VG.mat\n% flags - a structure containing the following elements:\n% sep - optimisation sampling steps (mm)\n% default: [4 2]\n% params - starting estimates (6 elements)\n% default: [0 0 0 0 0 0]\n% cost_fun - cost function string:\n% 'mi' - Mutual Information\n% 'nmi' - Normalised Mutual Information\n% 'ecc' - Entropy Correlation Coefficient\n% 'ncc' - Normalised Cross Correlation\n% default: 'nmi'\n% tol - tolerences for accuracy of each param\n% default: [0.02 0.02 0.02 0.001 0.001 0.001]\n% fwhm - smoothing to apply to 256x256 joint histogram\n% default: [7 7]\n%\n% The registration method used here is based on the work described in:\n% A Collignon, F Maes, D Delaere, D Vandermeulen, P Suetens & G Marchal\n% (1995) \"Automated Multi-modality Image Registration Based On\n% Information Theory\". In the proceedings of Information Processing in\n% Medical Imaging (1995). Y. Bizais et al. (eds.). Kluwer Academic\n% Publishers.\n%\n% The original interpolation method described in this paper has been\n% changed in order to give a smoother cost function. The images are\n% also smoothed slightly, as is the histogram. This is all in order to\n% make the cost function as smooth as possible, to give faster\n% convergence and less chance of local minima.\n%\n% References\n% ==========\n% Mutual Information\n% ------------------\n% Collignon, Maes, Delaere, Vandermeulen, Suetens & Marchal (1995).\n% \"Automated multi-modality image registration based on information theory\".\n% In Bizais, Barillot & Di Paola, editors, Proc. Information Processing\n% in Medical Imaging, pages 263--274, Dordrecht, The Netherlands, 1995.\n% Kluwer Academic Publishers.\n%\n% Wells III, Viola, Atsumi, Nakajima & Kikinis (1996).\n% \"Multi-modal volume registration by maximisation of mutual information\".\n% Medical Image Analysis, 1(1):35-51, 1996. \n%\n% Entropy Correlation Coefficient\n% -------------------------------\n% F Maes, A Collignon, D Vandermeulen, G Marchal & P Suetens (1997).\n% \"Multimodality image registration by maximisation of mutual\n% information\". IEEE Transactions on Medical Imaging 16(2):187-198\n%\n% Normalised Mutual Information\n% -----------------------------\n% Studholme, Hill & Hawkes (1998).\n% \"A normalized entropy measure of 3-D medical image alignment\".\n% in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143. \n%\n% Optimisation\n% ------------\n% Press, Teukolsky, Vetterling & Flannery (1992).\n% \"Numerical Recipes in C (Second Edition)\".\n% Published by Cambridge.\n%\n% At the end, the voxel-to-voxel affine transformation matrix is\n% displayed, along with the histograms for the images in the original\n% orientations, and the final orientations. The registered images are\n% displayed at the bottom.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_coreg.m 1007 2007-11-21 12:37:33Z john $\n\n\nif nargin>=4,\n\tx = optfun(varargin{:});\n\treturn;\nend;\n\ndef_flags = struct('sep',[4 2],'params',[0 0 0 0 0 0], 'cost_fun','nmi','fwhm',[7 7],...\n\t'tol',[0.02 0.02 0.02 0.001 0.001 0.001 0.01 0.01 0.01 0.001 0.001 0.001],'graphics',1);\nif nargin < 3,\n\tflags = def_flags;\nelse\n\tflags = varargin{3};\n\tfnms = fieldnames(def_flags);\n\tfor i=1:length(fnms),\n\t\tif ~isfield(flags,fnms{i}), flags.(fnms{i}) = def_flags.(fnms{i}); end;\n\tend;\nend;\n%disp(flags)\n\nif nargin < 1,\n\tVG = spm_vol(spm_select(1,'image','Select reference image'));\nelse\n\tVG = varargin{1};\n\tif ischar(VG), VG = spm_vol(VG); end;\nend;\nif nargin < 2,\n\tVF = spm_vol(spm_select(Inf,'image','Select moved image(s)'));\nelse\n\tVF = varargin{2};\n\tif ischar(VF) || iscellstr(VF), VF = spm_vol(strvcat(VF)); end;\nend;\n\nif ~isfield(VG, 'uint8'),\n\tVG.uint8 = loaduint8(VG);\n\tvxg = sqrt(sum(VG.mat(1:3,1:3).^2));\n\tfwhmg = sqrt(max([1 1 1]*flags.sep(end)^2 - vxg.^2, [0 0 0]))./vxg;\n\tVG = smooth_uint8(VG,fwhmg); % Note side effects\nend;\n\nsc = flags.tol(:)'; % Required accuracy\nsc = sc(1:length(flags.params));\nxi = diag(sc*20);\n\nfor k=1:numel(VF),\n\tVFk = VF(k);\n\tif ~isfield(VFk, 'uint8'),\n\t\tVFk.uint8 = loaduint8(VFk);\n\t\tvxf = sqrt(sum(VFk.mat(1:3,1:3).^2));\n\t\tfwhmf = sqrt(max([1 1 1]*flags.sep(end)^2 - vxf.^2, [0 0 0]))./vxf;\n\t\tVFk = smooth_uint8(VFk,fwhmf); % Note side effects\n\tend;\n\n\txk = flags.params(:);\n\tfor samp=flags.sep(:)',\n\t\txk = spm_powell(xk(:), xi,sc,mfilename,VG,VFk,samp,flags.cost_fun,flags.fwhm);\n\t\tx(k,:) = xk(:)';\n\tend;\n\tif flags.graphics,\n\t\tdisplay_results(VG(1),VFk(1),xk(:)',flags);\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction o = optfun(x,VG,VF,s,cf,fwhm)\n% The function that is minimised.\nif nargin<6, fwhm = [7 7]; end;\nif nargin<5, cf = 'mi'; end;\nif nargin<4, s = [1 1 1]; end;\n\n% Voxel sizes\nvxg = sqrt(sum(VG.mat(1:3,1:3).^2));sg = s./vxg;\n\n% Create the joint histogram\nH = spm_hist2(VG.uint8,VF.uint8, VF.mat\\spm_matrix(x(:)')*VG.mat ,sg);\n\n% Smooth the histogram\nlim = ceil(2*fwhm);\nkrn1 = smoothing_kernel(fwhm(1),-lim(1):lim(1)) ; krn1 = krn1/sum(krn1); H = conv2(H,krn1);\nkrn2 = smoothing_kernel(fwhm(2),-lim(2):lim(2))'; krn2 = krn2/sum(krn2); H = conv2(H,krn2);\n\n% Compute cost function from histogram\nH = H+eps;\nsh = sum(H(:));\nH = H/sh;\ns1 = sum(H,1);\ns2 = sum(H,2);\n\nswitch lower(cf)\n\tcase 'mi',\n\t\t% Mutual Information:\n\t\tH = H.*log2(H./(s2*s1));\n\t\tmi = sum(H(:));\n\t\to = -mi;\n\tcase 'ecc',\n\t\t% Entropy Correlation Coefficient of:\n\t\t% Maes, Collignon, Vandermeulen, Marchal & Suetens (1997).\n\t\t% \"Multimodality image registration by maximisation of mutual\n\t\t% information\". IEEE Transactions on Medical Imaging 16(2):187-198\n\t\tH = H.*log2(H./(s2*s1));\n\t\tmi = sum(H(:));\n\t\tecc = -2*mi/(sum(s1.*log2(s1))+sum(s2.*log2(s2)));\n\t\to = -ecc;\n\tcase 'nmi',\n\t\t% Normalised Mutual Information of:\n\t\t% Studholme, Hill & Hawkes (1998).\n\t\t% \"A normalized entropy measure of 3-D medical image alignment\".\n\t\t% in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143.\n\t\tnmi = (sum(s1.*log2(s1))+sum(s2.*log2(s2)))/sum(sum(H.*log2(H)));\n\t\to = -nmi;\n\tcase 'ncc',\n\t\t% Normalised Cross Correlation\n\t\ti = 1:size(H,1);\n\t\tj = 1:size(H,2);\n\t\tm1 = sum(s2.*i');\n\t\tm2 = sum(s1.*j);\n\t\tsig1 = sqrt(sum(s2.*(i'-m1).^2));\n\t\tsig2 = sqrt(sum(s1.*(j -m2).^2));\n\t\t[i,j] = ndgrid(i-m1,j-m2);\n\t\tncc = sum(sum(H.*i.*j))/(sig1*sig2);\n\t\to = -ncc;\n\totherwise,\n\t\terror('Invalid cost function specified');\nend;\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction udat = loaduint8(V)\n% Load data from file indicated by V into an array of unsigned bytes.\nif size(V.pinfo,2)==1 && V.pinfo(1) == 2,\n\tmx = 255*V.pinfo(1) + V.pinfo(2);\n\tmn = V.pinfo(2);\nelse\n\tspm_progress_bar('Init',V.dim(3),...\n\t\t['Computing max/min of ' spm_str_manip(V.fname,'t')],...\n\t\t'Planes complete');\n\tmx = -Inf; mn = Inf;\n\tfor p=1:V.dim(3),\n\t\timg = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n\t\tmx = max([max(img(:))+paccuracy(V,p) mx]);\n\t\tmn = min([min(img(:)) mn]);\n\t\tspm_progress_bar('Set',p);\n\tend;\nend;\n\n% Another pass to find a maximum that allows a few hot-spots in the data.\nspm_progress_bar('Init',V.dim(3),...\n ['2nd pass max/min of ' spm_str_manip(V.fname,'t')],...\n 'Planes complete');\nnh = 2048;\nh = zeros(nh,1);\nfor p=1:V.dim(3),\n img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n img = img(isfinite(img));\n img = round((img+((mx-mn)/(nh-1)-mn))*((nh-1)/(mx-mn)));\n if spm_matlab_version_chk('7.0')>=0,\n h = h + accumarray(img,1,[nh 1]);\n else\n h = h + full(sparse(img,1,1,nh,1));\n end\n spm_progress_bar('Set',p);\nend;\ntmp = [find(cumsum(h)/sum(h)>0.9999); nh];\nmx = (mn*nh-mx+tmp(1)*(mx-mn))/(nh-1);\n\nspm_progress_bar('Init',V.dim(3),...\n\t['Loading ' spm_str_manip(V.fname,'t')],...\n\t'Planes loaded');\n\n%udat = zeros(V.dim,'uint8'); Needs MATLAB 7 onwards\nudat = uint8(0);\nudat(V.dim(1),V.dim(2),V.dim(3)) = 0;\n\nrand('state',100);\nfor p=1:V.dim(3),\n\timg = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n\tacc = paccuracy(V,p);\n\tif acc==0,\n\t\tudat(:,:,p) = uint8(max(min(round((img-mn)*(255/(mx-mn))),255),0));\n\telse\n\t\t% Add random numbers before rounding to reduce aliasing artifact\n\t\tr = rand(size(img))*acc;\n\t\tudat(:,:,p) = uint8(max(min(round((img+r-mn)*(255/(mx-mn))),255),0));\n\tend;\n\tspm_progress_bar('Set',p);\nend;\nspm_progress_bar('Clear');\nreturn;\n\nfunction acc = paccuracy(V,p)\nif ~spm_type(V.dt(1),'intt'),\n\tacc = 0;\nelse\n\tif size(V.pinfo,2)==1,\n\t\tacc = abs(V.pinfo(1,1));\n\telse\n\t\tacc = abs(V.pinfo(1,p));\n\tend;\nend;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction V = smooth_uint8(V,fwhm)\n% Convolve the volume in memory (fwhm in voxels).\nlim = ceil(2*fwhm);\nx = -lim(1):lim(1); x = smoothing_kernel(fwhm(1),x); x = x/sum(x);\ny = -lim(2):lim(2); y = smoothing_kernel(fwhm(2),y); y = y/sum(y);\nz = -lim(3):lim(3); z = smoothing_kernel(fwhm(3),z); z = z/sum(z);\ni = (length(x) - 1)/2;\nj = (length(y) - 1)/2;\nk = (length(z) - 1)/2;\nspm_conv_vol(V.uint8,V.uint8,x,y,z,-[i j k]);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction krn = smoothing_kernel(fwhm,x)\n\n% Variance from FWHM\ns = (fwhm/sqrt(8*log(2)))^2+eps;\n\n% The simple way to do it. Not good for small FWHM\n% krn = (1/sqrt(2*pi*s))*exp(-(x.^2)/(2*s));\n\n% For smoothing images, one should really convolve a Gaussian\n% with a sinc function. For smoothing histograms, the\n% kernel should be a Gaussian convolved with the histogram\n% basis function used. This function returns a Gaussian\n% convolved with a triangular (1st degree B-spline) basis\n% function.\n\n% Gaussian convolved with 0th degree B-spline\n% int(exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= -0.5..0.5)\n% w1 = 1/sqrt(2*s);\n% krn = 0.5*(erf(w1*(x+0.5))-erf(w1*(x-0.5)));\n\n% Gaussian convolved with 1st degree B-spline\n% int((1-t)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= 0..1)\n% +int((t+1)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t=-1..0)\nw1 = 0.5*sqrt(2/s);\nw2 = -0.5/s;\nw3 = sqrt(s/2/pi);\nkrn = 0.5*(erf(w1*(x+1)).*(x+1) + erf(w1*(x-1)).*(x-1) - 2*erf(w1*x ).* x)...\n +w3*(exp(w2*(x+1).^2) + exp(w2*(x-1).^2) - 2*exp(w2*x.^2));\n\nkrn(krn<0) = 0;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction display_results(VG,VF,x,flags)\nfig = spm_figure('FindWin','Graphics');\nif isempty(fig), return; end;\nset(0,'CurrentFigure',fig);\nspm_figure('Clear','Graphics');\n\n%txt = 'Information Theoretic Coregistration';\nswitch lower(flags.cost_fun)\n\tcase 'mi', txt = 'Mutual Information Coregistration';\n\tcase 'ecc', txt = 'Entropy Correlation Coefficient Registration';\n\tcase 'nmi', txt = 'Normalised Mutual Information Coregistration';\n\tcase 'ncc', txt = 'Normalised Cross Correlation';\n\totherwise, error('Invalid cost function specified');\nend;\n\n% Display text\n%-----------------------------------------------------------------------\nax = axes('Position',[0.1 0.8 0.8 0.15],'Visible','off','Parent',fig);\ntext(0.5,0.7, txt,'FontSize',16,...\n\t'FontWeight','Bold','HorizontalAlignment','center','Parent',ax);\n\nQ = inv(VF.mat\\spm_matrix(x(:)')*VG.mat);\ntext(0,0.5, sprintf('X1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(1,:)),'Parent',ax);\ntext(0,0.3, sprintf('Y1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(2,:)),'Parent',ax);\ntext(0,0.1, sprintf('Z1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(3,:)),'Parent',ax);\n\n% Display joint histograms\n%-----------------------------------------------------------------------\nax = axes('Position',[0.1 0.5 0.35 0.3],'Visible','off','Parent',fig);\nH = spm_hist2(VG.uint8,VF.uint8,VF.mat\\VG.mat,[1 1 1]);\ntmp = log(H+1);\nimage(tmp*(64/max(tmp(:))),'Parent',ax');\nset(ax,'DataAspectRatio',[1 1 1],...\n\t'PlotBoxAspectRatioMode','auto','XDir','normal','YDir','normal',...\n\t'XTick',[],'YTick',[]);\ntitle('Original Joint Histogram','Parent',ax);\nxlabel(spm_str_manip(VG.fname,'k22'),'Parent',ax);\nylabel(spm_str_manip(VF.fname,'k22'),'Parent',ax);\n\nH = spm_hist2(VG.uint8,VF.uint8,VF.mat\\spm_matrix(x(:)')*VG.mat,[1 1 1]);\nax = axes('Position',[0.6 0.5 0.35 0.3],'Visible','off','Parent',fig);\ntmp = log(H+1);\nimage(tmp*(64/max(tmp(:))),'Parent',ax');\nset(ax,'DataAspectRatio',[1 1 1],...\n\t'PlotBoxAspectRatioMode','auto','XDir','normal','YDir','normal',...\n\t'XTick',[],'YTick',[]);\ntitle('Final Joint Histogram','Parent',ax);\nxlabel(spm_str_manip(VG.fname,'k22'),'Parent',ax);\nylabel(spm_str_manip(VF.fname,'k22'),'Parent',ax);\n\n% Display ortho-views\n%-----------------------------------------------------------------------\nspm_orthviews('Reset');\n spm_orthviews('Image',VG,[0.01 0.01 .48 .49]);\nh2 = spm_orthviews('Image',VF,[.51 0.01 .48 .49]);\nglobal st\nst.vols{h2}.premul = inv(spm_matrix(x(:)'));\nspm_orthviews('Space');\n\nspm_print\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_surf.m", "ext": ".m", "path": "spm5-master/spm_config_surf.m", "size": 2252, "source_encoding": "utf_8", "md5": "46cc9f45a635a68da38466624b0ec0d5", "text": "function opts = spm_config_surf\n% Configuration file for surface extraction jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Volkmar Glauche\n% $Id: spm_config_surf.m 775 2007-03-26 16:57:01Z john $\n\ndata.type = 'files';\ndata.name = 'Grey+white matter image';\ndata.tag = 'data';\ndata.filter = 'image';\ndata.num = [1 Inf];\ndata.help = {'Images to create rendering/surface from (grey and white matter segments).'};\n\nmode.type = 'menu';\nmode.name = 'Output';\nmode.tag = 'mode';\nmode.labels = {'Save Rendering', 'Save Extracted Surface',...\n 'Save Rendering and Surface', 'Save Surface as OBJ format'};\nmode.values = {1, 2, 3, 4};\nmode.val = {3};\n\nthresh.type = 'entry';\nthresh.name = 'Surface isovalue(s)';\nthresh.tag = 'thresh';\nthresh.num = [1 Inf];\nthresh.val = {.5};\nthresh.strtype = 'e';\nthresh.help = {['Enter one or more values at which isosurfaces through ' ...\n 'the input images will be computed.']};\n\nopts.type = 'branch';\nopts.name = 'Create Rendering/Surface';\nopts.tag = 'spm_surf';\nopts.val = {data,mode,thresh};\nopts.vfiles = @filessurf;\nopts.prog = @runsurf;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction runsurf(varargin)\nspm_surf(strvcat(varargin{1}.data),varargin{1}.mode,varargin{1}.thresh);\nreturn;\n\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction vfiles=filessurf(varargin)\nvfiles={};\n[pth,nam,ext] = fileparts(varargin{1}.data{1});\n\nif any(varargin{1}.mode==[1 3]),\n\tvfiles{1} = fullfile(pth,['render_' nam '.mat']);\nend;\n\nif any(varargin{1}.mode==[2 3 4]),\n for k=1:numel(varargin{1}.thresh)\n if numel(varargin{1}.thresh) == 1\n nam1 = nam;\n else\n nam1 = sprintf('%s-%d', nam, k);\n end;\n\tif any(varargin{1}.mode==[2 3]),\n\t\tvfiles{end+1} = fullfile(pth,['surf_' nam1 '.mat']);\n end;\n if any(varargin{1}.mode==[4]),\n\t\tvfiles{end+1} = fullfile(pth,[nam1 '.obj']);\n end;\n end;\nend\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_scalp_dlg.m", "ext": ".m", "path": "spm5-master/spm_eeg_scalp_dlg.m", "size": 5509, "source_encoding": "utf_8", "md5": "7cd9ad7846616f2c1e168eac831221ee", "text": "function varargout = spm_eeg_scalp_dlg(varargin)\n% SPM_EEG_SCALP_DLG M-file for spm_eeg_scalp_dlg.fig\n% SPM_EEG_SCALP_DLG, by itself, creates a new SPM_EEG_SCALP_DLG or raises the existing\n% singleton*.\n%\n% H = SPM_EEG_SCALP_DLG returns the handle to a new SPM_EEG_SCALP_DLG or the handle to\n% the existing singleton*.\n%\n% SPM_EEG_SCALP_DLG('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SPM_EEG_SCALP_DLG.M with the given input arguments.\n%\n% SPM_EEG_SCALP_DLG('Property','Value',...) creates a new SPM_EEG_SCALP_DLG or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before spm_eeg_scalp_dlg_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to spm_eeg_scalp_dlg_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Copyright 2002-2003 The MathWorks, Inc.\n\n% Edit the above text to modify the response to help spm_eeg_scalp_dlg\n\n% Last Modified by GUIDE v2.5 21-Nov-2005 18:51:44\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @spm_eeg_scalp_dlg_OpeningFcn, ...\n 'gui_OutputFcn', @spm_eeg_scalp_dlg_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before spm_eeg_scalp_dlg is made visible.\nfunction spm_eeg_scalp_dlg_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to spm_eeg_scalp_dlg (see VARARGIN)\n\n% Choose default command line output for spm_eeg_scalp_dlg\nhandles.output = hObject;\n\nhandles.T = 100;\nhandles.dim = '2D';\nguidata(hObject, handles);\n\n% UIWAIT makes spm_eeg_scalp_dlg wait for user response (see UIRESUME)\nuiwait(handles.figure1);\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = spm_eeg_scalp_dlg_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nif isfield(handles, 'T')\n handles.output = {handles.T handles.dim};\n\n varargout{1} = handles.output;\n close(handles.figure1);\nend\n\nfunction time_Callback(hObject, eventdata, handles)\n% hObject handle to time (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of time as text\n% str2double(get(hObject,'String')) returns contents of time as a double\nhandles.T = str2num(get(handles.time, 'String'));\nguidata(hObject, handles);\n\n\n% --- Executes during object creation, after setting all properties.\nfunction time_CreateFcn(hObject, eventdata, handles)\n% hObject handle to time (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in select.\nfunction select_Callback(hObject, eventdata, handles)\n% hObject handle to select (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = get(hObject,'String') returns select contents as cell array\n% contents{get(hObject,'Value')} returns selected item from select\nS = {'2D', '3D'};\nhandles.dim = S{get(handles.select, 'Value')};\nguidata(hObject, handles);\n\n% --- Executes during object creation, after setting all properties.\nfunction select_CreateFcn(hObject, eventdata, handles)\n% hObject handle to select (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: listbox controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in ok.\nfunction ok_Callback(hObject, eventdata, handles)\n% hObject handle to ok (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nuiresume(handles.figure1);\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_uw_estimate.m", "ext": ".m", "path": "spm5-master/spm_uw_estimate.m", "size": 33867, "source_encoding": "utf_8", "md5": "17b02c89f832b000c9cce52c1529fb6a", "text": "function ds = spm_uw_estimate(P,par)\n%\n% Estimation of partial derivatives of EPI deformation fields.\n%\n% FORMAT [ds] = spm_uw_estimate((P),(par))\n%\n% P - List of file names or headers.\n% par - Structure containing parameters governing the specifics\n% of how to estimate the fields.\n% .M - When performing multi-session realignment and Unwarp we\n% want to realign everything to the space of the first\n% image in the first time-series. M defines the space of\n% that.\n% .order - Number of basis functions to use for each dimension.\n% If the third dimension is left out, the order for \n% that dimension is calculated to yield a roughly\n% equal spatial cut-off in all directions.\n% Default: [12 12 *]\n% .sfP - Static field supplied by the user. It should be a \n% filename or handle to a voxel-displacement map in\n% the same space as the first EPI image of the time-\n% series. If using the FieldMap toolbox, realignment\n% should (if necessary) have been performed as part of\n% the process of creating the VDM. Note also that the\n% VDM mut be in undistorted space, i.e. if it is\n% calculated from an EPI based field-map sequence\n% it should have been inverted before passing it to\n% spm_uw_estimate. Again, the FieldMap toolbox will\n% do this for you.\n% .regorder - Regularisation of derivative fields is based on the\n% regorder'th (spatial) derivative of the field.\n% Default: 1\n% .lambda - Fudge factor used to decide relative weights of\n% data and regularisation.\n% Default: 1e5\n% .jm - Jacobian Modulation. If set, intensity (Jacobian)\n% deformations are included in the model. If zero,\n% intensity deformations are not considered. \n% .fot - List of indexes for first order terms to model\n% derivatives for. Order of parameters as defined\n% by spm_imatrix. \n% Default: [4 5]\n% .sot - List of second order terms to model second \n% derivatives of. Should be an nx2 matrix where\n% e.g. [4 4; 4 5; 5 5] means that second partial\n% derivatives of rotation around x- and y-axis\n% should be modelled.\n% Default: []\n% .fwhm - FWHM (mm) of smoothing filter applied to images prior\n% to estimation of deformation fields.\n% Default: 6\n% .rem - Re-Estimation of Movement parameters. Set to unity means\n% that movement-parameters should be re-estimated at each\n% iteration.\n% Default: 0\n% .noi - Maximum number of Iterations.\n% Default: 5\n% .exp_round - Point in position space to do Taylor expansion around.\n% 'First', 'Last' or 'Average'.\n% Default: 'Average'.\n% ds - The returned structure contains the following fields\n% .P - Copy of P on input.\n% .sfP - Copy of sfP on input (if non-empty).\n% .order - Copy of order on input, or default.\n% .regorder - Copy of regorder on input, or default.\n% .lambda - Copy of lambda on input, or default.\n% .fot - Copy of fot on input, or default.\n% .sot - Copy of sot on input, or default.\n% .fwhm - Copy of fwhm on input, or default.\n% .rem - Copy of rem on input, or default.\n% .p0 - Average position vector (three translations in mm\n% and three rotations in degrees) of scans in P.\n% .q - Deviations from mean position vector of modelled\n% effects. Corresponds to deviations (and deviations\n% squared) of a Taylor expansion of deformation fields.\n% .beta - Coeffeicents of DCT basis functions for partial\n% derivatives of deformation fields w.r.t. modelled\n% effects. Scaled such that resulting deformation \n% fields have units mm^-1 or deg^-1 (and squares \n% thereof).\n% .SS - Sum of squared errors for each iteration.\n%\n%\n% This is a major rewrite which uses some new ideas to speed up\n% the estimation of the field. The time consuming part is the\n% evaluation of A'*A where A is a matrix with the partial\n% derivatives for each scan with respect to the parameters\n% describing the warp-fields. If we denote the derivative\n% matrix for a single scan by Ai, then the estimation of A'*A\n% is A'*A = A1'*A1 + A2'*A2 + ... +An'*An where n is the number\n% of scans in the time-series. If we model the partial-derivative\n% fields w.r.t. two movement parameters (e.g. pitch and roll), each\n% by [8 8 8] basis-functions and the image dimensions are\n% 64x64x64 then each Ai is a 262144x1024 matrix and we need to\n% evaluate and add n of these 1024x1024 matrices. It takes a while.\n%\n% The new idea is based on the realisation that each of these\n% matrices is the kroneceker-product of the relevant movement\n% parameters, our basis set and a linear combination (given by\n% one column of the inverse of the rotation matrix) of the image \n% gradients in the x-, y- and z-directions. This means that \n% they really aren't all that unique, and that the amount of\n% information in these matrices doesn't really warrant all \n% those calculations. After a lot of head-scratching I arrived\n% at the following\n%\n% First some definitions\n%\n% n: no. of voxels\n% m: no. of scans\n% l: no. of effects to model\n% order: [xorder yorder zorder] no. of basis functions\n% q: mxl matrix of scaled realignment parameters for effects to model.\n% T{i}: inv(inv(P(i).mat)*P(1).mat);\n% t(i,:) = T{i}(1:3,2)';\n% B: kron(Bz,By,Bx);\n% Ax = repmat(dx,1,prod(order)).*B;\n% Ay = repmat(dy,1,prod(order)).*B;\n% Az = repmat(dz,1,prod(order)).*B;\n%\n% Now, my hypothesis is that A'*A is given by\n%\n% AtA = kron((q.*kron(ones(1,l),t(:,1)))'*(q.*kron(ones(1,l),t(:,1))),Ax'*Ax) +...\n% kron((q.*kron(ones(1,l),t(:,2)))'*(q.*kron(ones(1,l),t(:,2))),Ay'*Ay) +...\n% kron((q.*kron(ones(1,l),t(:,3)))'*(q.*kron(ones(1,l),t(:,3))),Az'*Az) +...\n% 2*kron((q.*kron(ones(1,l),t(:,1)))'*(q.*kron(ones(1,l),t(:,2))),Ax'*Ay) +...\n% 2*kron((q.*kron(ones(1,l),t(:,1)))'*(q.*kron(ones(1,l),t(:,3))),Ax'*Az) +...\n% 2*kron((q.*kron(ones(1,l),t(:,2)))'*(q.*kron(ones(1,l),t(:,3))),Ay'*Az);\n%\n% Which turns out to be true. This means that regardless of how many\n% scans we have we will always be able to create AtA as a sum of\n% six individual AtAs. It has been tested against the previous\n% implementation and yields exactly identical results.\n%\n% I know this isn't much of a derivation, but there will be a paper soon. Sorry.\n%\n% Other things that are new for the rewrite is\n% 1. We have removed the possibility to try and estimate the \"static\" field.\n% There simply isn't enough information about that field, and for a\n% given time series the estimation is just too likely to fail.\n% 2. New option to pass a static field (e.g. estimated from a dual\n% echo-time measurement) as an input parameter.\n% 3. Re-estimation of the movement parameters at each iteration.\n% Let us say we have a nodding motion in the time series, and\n% at each nod the brain appear to shrink in the phase-encode\n% direction. The realignment will find the nods, but might in\n% addition mistake the \"shrinks\" for translations, leading to\n% biased estimates. We attempt to correct that by, at iteration,\n% updating both parameters pertaining to distortions and to\n% movement. In order to do so in an unbiased fashion we have\n% also switched from sampling of images (and deformation fields)\n% on a grid centered on the voxel-centers, to a grid whith a \n% different sampling frequency. \n% 4. Inclusion of a regularisation term. The speed-up has facilitated\n% using more basis-functions, which makes it neccessary to impose\n% regularisation (i.e. punisihing some order derivative of the\n% deformation field).\n% 5. Change of interpolation model from tri-linear/Sinc to \n% tri-linear/B-spline.\n% 6. Option to include the Jacobian compression/stretching effects\n% in the model for the estimation of the displacement fields.\n% Our tests have indicated that this is NOT a good idea though. \n%\n%_______________________________________________________________________\n%\n% Definition of some of the variables in this routine.\n%\n% \n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Jesper Andersson\n% $Id: spm_uw_estimate.m 471 2006-03-08 17:46:45Z john $\n\n\nglobal defaults\n\nif nargin < 1 | isempty(P), P = spm_select(Inf,'image'); end\nif ~isstruct(P), P = spm_vol(P); end\n\n%\n% Hardcoded default input parameters.\n%\ndefpar = struct('order', [12 12],...\n 'sfP', [],...\n 'M', P(1).mat,...\n 'regorder', 1,...\n 'lambda', 1e5,...\n 'jm', 0,...\n 'fot', [4 5],...\n 'sot', [],...\n 'fwhm', 4,...\n 'rem', 1,...\n 'exp_round', 'Average',...\n 'noi', 5,...\n 'hold', [1 1 1 0 1 0]);\n\ndefnames = fieldnames(defpar);\n\n%\n% Replace hardcoded defaults with spm_defaults\n% when exist and defined.\n%\nif exist('defaults','var') & isfield(defaults,'unwarp') & isfield(defaults.unwarp,'estimate')\n ud = defaults.unwarp.estimate;\n if isfield(ud,'basfcn'), defpar.order = ud.basfcn; end\n if isfield(ud,'regorder'), defpar.regorder = ud.regorder; end\n if isfield(ud,'regwgt'), defpar.lambda = ud.regwgt; end\n if isfield(ud,'jm'), defpar.jm = ud.jm; end\n if isfield(ud,'fwhm'), defpar.fwhm = ud.fwhm; end\n if isfield(ud,'rem'), defpar.rem = ud.rem; end\n if isfield(ud,'noi'), defpar.noi = ud.noi; end\n if isfield(ud,'expround'), defpar.exp_round = ud.expround; end\nend\n\n%\n% Go through input parameters, chosing the default\n% for any parameters that are missing, warning the \n% user if there are \"unknown\" parameters (probably\n% reflecting a misspelling).\n%\n\nif nargin < 2 | isempty(par)\n par = defpar;\nend\nds = [];\nfor i=1:length(defnames)\n if isfield(par,defnames{i}) & ~isempty(getfield(par,defnames{i}))\n ds = setfield(ds,defnames{i},getfield(par,defnames{i}));\n else\n ds = setfield(ds,defnames{i},getfield(defpar,defnames{i}));\n end\nend\nparnames = fieldnames(par);\nfor i=1:length(parnames)\n if ~isfield(defpar,parnames{i})\n warning(sprintf('Unknown par field %s',parnames{i}));\n end\nend\n\n%\n% Resolve ambiguities.\n%\nif length(ds.order) == 2\n mm = sqrt(sum(P(1).mat(1:3,1:3).^2)).*P(1).dim(1:3);\n ds.order(3) = round(ds.order(1)*mm(3)/mm(1));\nend\nif isfield(ds,'sfP') & ~isempty(ds.sfP)\n if ~isstruct(ds.sfP)\n ds.sfP = spm_vol(ds.sfP);\n end\nend\nnscan = length(P);\nnof = prod(size(ds.fot)) + size(ds.sot,1);\nds.P = P;\n\n%\n% Get matrix of 'expansion point'-corrected movement parameters \n% for which we seek partial derivative fields.\n%\n[ds.q,ds.ep] = make_q(P,ds.fot,ds.sot,ds.exp_round);\n\n%\n% Create matrix for regularisation of warps.\n%\nH = make_H(P,ds.order,ds.regorder);\n\n%\n% Create a temporary smooth time series to use for\n% the estimation.\n%\nold_P = P;\nif ds.fwhm ~= 0\n spm_uw_show('SmoothStart',length(P));\n for i=1:length(old_P)\n spm_uw_show('SmoothUpdate',i);\n sfname(i,:) = [tempname '.img,1,1'];\n to_smooth = sprintf('%s,%d,%d',old_P(i).fname,old_P(i).n);\n spm_smooth(to_smooth,sfname(i,:),ds.fwhm);\n end\n P = spm_vol(sfname);\n spm_uw_show('SmoothEnd');\nend\n\n% Now that we have littered the disk with smooth\n% temporary files we should use a try-catch\n% block for the rest of the function, to ensure files\n% get deleted in the event of an error.\n\ntry % Try block starts here\n\n%\n% Initialize some stuff.\n%\nbeta0 = zeros(nof*prod(ds.order),10);\nbeta = zeros(nof*prod(ds.order),1);\nold_beta = zeros(nof*prod(ds.order),1);\n\n%\n% Sample images on irregular grid to avoid biasing\n% re-estimated movement parameters with smoothing\n% effect from voxel-interpolation (See Andersson ,\n% EJNM (1998), 25:575-586.).\n%\n\nss = [1.1 1.1 0.9];\nxs = 1:ss(1):P(1).dim(1); xs = xs + (P(1).dim(1)-xs(end)) / 2;\nys = 1:ss(2):P(1).dim(2); ys = ys + (P(1).dim(2)-ys(end)) / 2;\nzs = 1:ss(3):P(1).dim(3); zs = zs + (P(1).dim(3)-zs(end)) / 2;\nM = spm_matrix([-xs(1)/ss(1)+1 -ys(1)/ss(2)+1 -zs(1)/ss(3)+1])*inv(diag([ss 1]))*eye(4);\nnx = length(xs);\nny = length(ys);\nnz = length(zs);\n[x,y,z] = ndgrid(xs,ys,zs);\nBx = spm_dctmtx(P(1).dim(1),ds.order(1),x(:,1,1));\nBy = spm_dctmtx(P(1).dim(2),ds.order(2),y(1,:,1));\nBz = spm_dctmtx(P(1).dim(3),ds.order(3),z(1,1,:));\ndBy = spm_dctmtx(P(1).dim(2),ds.order(2),y(1,:,1),'diff');\nxyz = [x(:) y(:) z(:) ones(length(x(:)),1)]; clear x y z;\ndef = zeros(size(xyz,1),nof);\nddefa = zeros(size(xyz,1),nof);\n\n%\n% Create file struct for use with spm_orthviews to draw\n% representations of the field.\n%\ndispP = P(1);\ndispP = rmfield(dispP,{'fname','descrip','n','private'});\ndispP.dim = [nx ny nz];\ndispP.dt = [64 spm_platform('bigend')];\ndispP.pinfo = [1 0]';\np = spm_imatrix(dispP.mat); p = p.*[zeros(1,6) ss 0 0 0];\np(1) = -mean(1:nx)*p(7);\np(2) = -mean(1:ny)*p(8);\np(3) = -mean(1:nz)*p(9);\ndispP.mat = spm_matrix(p); clear p;\n\n%\n% We will need to resample the static field (if one was supplied)\n% on the same grid (given by xs, ys and zs) as we are going to use\n% for the time series. We will assume that the fieldmap has been\n% realigned to the space of the first EPI image in the time-series.\n%\nif isfield(ds,'sfP') & ~isempty(ds.sfP)\n T = ds.sfP.mat\\ds.M;\n txyz = xyz*T(1:3,:)';\n c = spm_bsplinc(ds.sfP,ds.hold);\n ds.sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds.hold);\n ds.sfield = ds.sfield(:);\n clear c txyz;\nelse\n ds.sfield = [];\nend\n\nmsk = get_mask(P,xyz,ds,[nx ny nz]);\nssq = [];\n%\n% Here starts iterative search for deformation fields.\n%\nfor iter=1:ds.noi\n spm_uw_show('NewIter',iter);\n\n [ref,dx,dy,dz,P,ds,sf,dispP] = make_ref(ds,def,ddefa,P,xyz,M,msk,beta,dispP);\n AtA = build_AtA(ref,dx,dy,dz,Bx,By,Bz,dBy,ds,P);\n [Aty,yty] = build_Aty(ref,dx,dy,dz,Bx,By,Bz,dBy,ds,P,xyz,beta,sf,def,ddefa,msk);\n\n % Clean up a bit, cause inverting AtA may use a lot of memory\n clear ref dx dy dz\n\n % Check that residual error still decreases.\n if iter > 1 & yty > ssq(iter-1)\n %\n % This means previous iteration was no good,\n % and we should go back to old_beta.\n %\n beta = old_beta;\n break;\n else\n ssq(iter) = yty;\n\n spm_uw_show('StartInv',1);\n\n % Solve for beta\n Aty = Aty + AtA*beta;\n AtA = AtA + ds.lambda * kron(eye(nof),diag(H)) * ssq(iter)/(nscan*sum(msk));\n\n try % Fastest if it works\n beta0(:,iter) = AtA\\Aty;\n catch % Sometimes necessary\n beta0(:,iter) = pinv(AtA)*Aty;\n end\n\n old_beta = beta;\n beta = beta0(:,iter);\n\n for i=1:nof\n def(:,i) = spm_get_def(Bx, By,Bz,beta((i-1)*prod(ds.order)+1:i*prod(ds.order)));\n ddefa(:,i) = spm_get_def(Bx,dBy,Bz,beta((i-1)*prod(ds.order)+1:i*prod(ds.order)));\n end\n\n % If we are re-estimating the movement parameters, remove any DC\n % components from the deformation fields, so that they end up in\n % the movement-parameters instead. It shouldn't make any difference\n % to the variance reduction, but might potentially lead to a better\n % explanation of the variance components.\n % Note that since we sub-sample the images (and the DCT basis set)\n % it is NOT sufficient to reset beta(1) (and beta(prod(order)+1) etc,\n % instead we explicitly subtract the DC component. Note that a DC\n % component does NOT affect the Jacobian.\n %\n if ds.rem ~= 0\n def = def - repmat(mean(def),length(def),1);\n end\n spm_uw_show('EndInv');\n tmp = dispP.mat;\n dispP.mat = P(1).mat;\n spm_uw_show('FinIter',ssq,def,ds.fot,ds.sot,dispP,ds.q);\n dispP.mat = tmp;\n end\n clear AtA\nend\n\nds.P = old_P;\nfor i=1:length(ds.P)\n ds.P(i).mat = P(i).mat; % Save P with new movement parameters.\nend\nds.beta = reshape(refit(P,dispP,ds,def),prod(ds.order),nof);\nds.SS = ssq;\nif isfield(ds,'sfield');\n ds = rmfield(ds,'sfield');\nend\n\ncleanup(P,ds)\nspm_uw_show('FinTot');\n\n% Document outcome\n\nspm_print\n\ncatch % Try block ends here\n cleanup(P,ds)\n spm_uw_show('FinTot');\n fprintf('procedure terminated abnormally:\\n%s',lasterr);\nend % Catch block ends here.\n\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Utility functions.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [q,ep] = make_q(P,fot,sot,exp_round)\n%\n% P : Array of file-handles\n% fot : nx1 array of indicies for first order effect.\n% sot : nx2 matrix of indicies of second order effects.\n% exp_round : Point in position space to perform Taylor-expansion\n% around ('First','Last' or 'Average'). 'Average' should\n% (in principle) give the best variance reduction. If a\n% field-map acquired before the time-series is supplied\n% then expansion around the 'First' MIGHT give a slightly\n% better average geometric fidelity.\n\nif strcmp(lower(exp_round),'average');\n %\n % Get geometric mean of all transformation matrices.\n % This will be used as the zero-point in the space \n % of object position vectors (i.e. the point at which\n % the partial derivatives are estimated). This is presumably\n % a little more correct than taking the average of the\n % parameter estimates. \n %\n mT = zeros(4);\n for i=1:length(P)\n mT = mT+logm(inv(P(i).mat) * P(1).mat);\n end\n mT = real(expm(mT/length(P)));\n\nelseif strcmp(lower(exp_round),'first');\n mT = eye(4);\nelseif strcmp(lower(exp_round),'last');\n mT = inv(P(end).mat) * P(1).mat;\nelse\n warning(sprintf('Unknown expansion point %s',exp_round));\nend\n\n%\n% Rescaling to degrees makes translations and rotations\n% roughly equally scaled. Since the scaling influences\n% strongly the effects of regularisation, it would surely\n% be nice with a more principled approach. Suggestions\n% anyone?\n%\nep = [1 1 1 180/pi 180/pi 180/pi zeros(1,6)] .* spm_imatrix(mT);\n\n%\n% Now, get a nscan-by-nof matrix containing \n% mean (expansion point) corrected values for each effect we\n% model.\n%\nq = zeros(length(P),prod(size(fot)) + size(sot,1));\nfor i=1:length(P)\n p = [1 1 1 180/pi 180/pi 180/pi zeros(1,6)] .*...\n spm_imatrix(inv(P(i).mat) * P(1).mat);\n for j=1:prod(size(fot))\n q(i,j) = p(fot(j)) - ep(fot(j));\n end\n for j=1:size(sot,1)\n q(i,prod(size(fot))+j) = (p(sot(j,1)) - ep(sot(j,1))) * (p(sot(j,2)) - ep(sot(j,2)));\n end\nend\nreturn\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction H = make_H(P,order,regorder)\n% Utility Function to create Regularisation term of AtA.\n\nmm = sqrt(sum(P(1).mat(1:3,1:3).^2)).*P(1).dim(1:3);\nkx=(pi*((1:order(1))'-1)/mm(1)).^2;\nky=(pi*((1:order(2))'-1)/mm(2)).^2;\nkz=(pi*((1:order(3))'-1)/mm(3)).^2;\n\nif regorder == 0\n %\n % Cost function based on sum of squares\n %\n H = (1*kron(kz.^0,kron(ky.^0,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^0,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^0,kx.^0)) );\nelseif regorder == 1\n %\n % Cost function based on sum of squared 1st derivatives\n %\n H = (1*kron(kz.^1,kron(ky.^0,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^1,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^0,kx.^1)) );\nelseif regorder == 2\n %\n % Cost function based on sum of squared 2nd derivatives\n %\n H = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^2,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^0,kx.^2)) +...\n 3*kron(kz.^1,kron(ky.^1,kx.^0)) +...\n 3*kron(kz.^1,kron(ky.^0,kx.^1)) +...\n 3*kron(kz.^0,kron(ky.^1,kx.^1)) );\nelseif regorder == 3\n %\n % Cost function based on sum of squared 3rd derivatives\n %\n H = (1*kron(kz.^3,kron(ky.^0,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^3,kx.^0)) +...\n 1*kron(kz.^0,kron(ky.^0,kx.^3)) +...\n 3*kron(kz.^2,kron(ky.^1,kx.^0)) +...\n 3*kron(kz.^2,kron(ky.^0,kx.^1)) +...\n 3*kron(kz.^1,kron(ky.^2,kx.^0)) +...\n 3*kron(kz.^0,kron(ky.^2,kx.^1)) +...\n 3*kron(kz.^1,kron(ky.^0,kx.^2)) +...\n 3*kron(kz.^0,kron(ky.^1,kx.^2)) +...\n 6*kron(kz.^1,kron(ky.^1,kx.^1)) );\nelse\n error('Invalid order of regularisation');\nend\nreturn\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction AtA = build_AtA(ref,dx,dy,dz,Bx,By,Bz,dBy,ds,P)\n% Now lets build up the design matrix A, or rather A'*A since\n% A itself would be forbiddingly large.\n\nif ds.jm, spm_uw_show('StartAtA',10);\nelse spm_uw_show('StartAtA',6); end\n\nnof = prod(size(ds.fot)) + size(ds.sot,1);\n\nAxtAx = uwAtA1(dx.*dx,Bx,By,Bz); spm_uw_show('NewAtA',1);\nAytAy = uwAtA1(dy.*dy,Bx,By,Bz); spm_uw_show('NewAtA',2);\nAztAz = uwAtA1(dz.*dz,Bx,By,Bz); spm_uw_show('NewAtA',3);\nAxtAy = uwAtA1(dx.*dy,Bx,By,Bz); spm_uw_show('NewAtA',4);\nAxtAz = uwAtA1(dx.*dz,Bx,By,Bz); spm_uw_show('NewAtA',5);\nAytAz = uwAtA1(dy.*dz,Bx,By,Bz); spm_uw_show('NewAtA',6);\n\nif ds.jm\n AjtAj = uwAtA1(ref.*ref,Bx,dBy,Bz); spm_uw_show('NewAtA',7);\n AxtAj = uwAtA2( dx.*ref,Bx, By,Bz,Bx,dBy,Bz); spm_uw_show('NewAtA',8);\n AytAj = uwAtA2( dy.*ref,Bx, By,Bz,Bx,dBy,Bz); spm_uw_show('NewAtA',9);\n AztAj = uwAtA2( dz.*ref,Bx, By,Bz,Bx,dBy,Bz); spm_uw_show('NewAtA',10);\nend\n\nR = zeros(length(P),3);\nfor i=1:length(P)\n tmp = inv(P(i).mat\\P(1).mat);\n R(i,:) = tmp(1:3,2)';\nend\n\ntmp = ones(1,nof);\ntmp1 = ds.q.*kron(tmp,R(:,1));\ntmp2 = ds.q.*kron(tmp,R(:,2));\ntmp3 = ds.q.*kron(tmp,R(:,3));\nAtA = kron(tmp1'*tmp1,AxtAx) + kron(tmp2'*tmp2,AytAy) + kron(tmp3'*tmp3,AztAz) +...\n 2*(kron(tmp1'*tmp2,AxtAy) + kron(tmp1'*tmp3,AxtAz) + kron(tmp2'*tmp3,AytAz));\n\nif ds.jm\n tmp = [ds.q.*kron(tmp,ones(length(P),1))];\n AtA = AtA + kron(tmp'*tmp,AjtAj) +...\n 2*(kron(tmp1'*tmp,AxtAj) + kron(tmp2'*tmp,AytAj) + kron(tmp3'*tmp,AztAj));\nend\nspm_uw_show('EndAtA');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction AtA = uwAtA1(y,Bx,By,Bz)\n% Calculating off-diagonal block of AtA.\n\n[nx,mx] = size(Bx);\n[ny,my] = size(By);\n[nz,mz] = size(Bz);\nAtA = zeros(mx*my*mz);\nfor sl =1:nz\n tmp = reshape(y((sl-1)*nx*ny+1:sl*nx*ny),nx,ny);\n spm_krutil(Bz(sl,:)'*Bz(sl,:),spm_krutil(tmp,Bx,By,1),AtA);\n% AtA = AtA + kron(Bz(sl,:)'*Bz(sl,:),spm_krutil(tmp,Bx,By,1));\nend\nreturn\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction AtA = uwAtA2(y,Bx1,By1,Bz1,Bx2,By2,Bz2)\n% Calculating cross-term of diagonal block of AtA\n% when A is a sum of the type A1+A2 and where both\n% A1 and A2 are possible to express as a kronecker\n% product of lesser matrices.\n\n[nx,mx1] = size(Bx1,1); [nx,mx2] = size(Bx2,1);\n[ny,my1] = size(By1,1); [ny,my2] = size(By2,1);\n[nz,mz1] = size(Bz1,1); [nz,mz2] = size(Bz2,1);\nAtA = zeros(mx1*my1*mz1,mx2*my2*mz2);\nfor sl =1:nz\n tmp = reshape(y((sl-1)*nx*ny+1:sl*nx*ny),nx,ny);\n spm_krutil(Bz1(sl,:)'*Bz2(sl,:),spm_krutil(tmp,Bx1,By1,Bx2,By2),AtA);\n% AtA = AtA + kron(Bz1(sl,:)'*Bz2(sl,:),spm_krutil(tmp,Bx1,By1,Bx2,By2));\nend\nreturn\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [Aty,yty] = build_Aty(ref,dx,dy,dz,Bx,By,Bz,dBy,ds,P,xyz,beta,sf,def,ddefa,msk)\n% Building Aty.\n\nnof = prod(size(ds.fot)) + size(ds.sot,1);\nAty = zeros(nof*prod(ds.order),1);\nyty = 0;\n\nspm_uw_show('StartAty',length(P));\nfor scan = 1:length(P)\n spm_uw_show('NewAty',scan);\n T = P(scan).mat\\ds.M;\n txyz = xyz*T(1:3,:)';\n if ~(all(beta == 0) & isempty(ds.sfield))\n [idef,jac] = spm_get_image_def(scan,ds,def,ddefa);\n txyz(:,2) = txyz(:,2)+idef;\n end;\n c = spm_bsplinc(P(scan),ds.hold);\n y = sf(scan) * spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds.hold);\n if ds.jm & ~(all(beta == 0) & isempty(ds.sfield))\n y = y .* jac;\n end;\n\n y_diff = (ref - y).*msk;\n indx = find(isnan(y));\n y_diff(indx) = 0;\n iTcol = inv(T(1:3,1:3));\n tmpAty = spm_get_def(Bx',By',Bz',([dx dy dz]*iTcol(:,2)).*y_diff);\n if ds.jm ~= 0\n tmpAty = tmpAty + spm_get_def(Bx',dBy',Bz',ref.*y_diff);\n end\n for i=1:nof\n rindx = (i-1)*prod(ds.order)+1:i*prod(ds.order);\n Aty(rindx) = Aty(rindx) + ds.q(scan,i)*tmpAty;\n end\n yty = yty + y_diff'*y_diff;\nend\nspm_uw_show('EndAty');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [ref,dx,dy,dz,P,ds,sf,dispP] = make_ref(ds,def,ddefa,P,xyz,M,msk,beta,dispP)\n% First of all get the mean of all scans given their\n% present deformation fields. When using this as the\n% \"reference\" we will explicitly be minimising variance.\n%\n% First scan in P is still reference in terms of\n% y-direction (in the scanner framework). A single set of\n% image gradients is estimated from the mean of all scans,\n% transformed into the space of P(1), and used for all scans.\n%\nspm_uw_show('StartRef',length(P));\n\nrem = ds.rem;\nif all(beta==0), rem=0; end;\n\nif rem\n [m_ref,D] = get_refD(ds,def,ddefa,P,xyz,msk);\nend\n\nref = zeros(size(xyz,1),1);\nfor i=1:length(P)\n spm_uw_show('NewRef',i);\n T = P(i).mat\\ds.M;\n txyz = xyz*T(1:3,:)';\n if ~(all(beta == 0) & isempty(ds.sfield))\n [idef,jac] = spm_get_image_def(i,ds,def,ddefa);\n txyz(:,2) = txyz(:,2)+idef;\n end;\n c = spm_bsplinc(P(i),ds.hold);\n f = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds.hold);\n if ds.jm ~= 0 && exist('jac')==1\n f = f .* jac;\n end\n indx = find(~isnan(f));\n sf(i) = 1 / (sum(f(indx).*msk(indx)) / sum(msk(indx)));\n ref = ref + f;\n\n if rem\n indx = find(isnan(f)); f(indx) = 0;\n Dty{i} = (((m_ref - sf(i)*f).*msk)'*D)';\n end\nend\nref = ref / length(P);\nref = reshape(ref,dispP.dim(1:3));\nindx = find(~isnan(ref));\n\n% Scale to roughly 100 mean intensity to ensure\n% consistent weighting of regularisation.\ngl = spm_global(ref);\nsf = (100 * (sum(ref(indx).*msk(indx)) / sum(msk(indx))) / gl) * sf;\nref = (100 / gl) * ref;\ndispP.dat = ref;\nc = spm_bsplinc(ref,ds.hold);\ntxyz = xyz*M(1:3,:)';\n[ref,dx,dy,dz] = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds.hold);\nref = ref.*msk;\ndx = dx.*msk;\ndy = dy.*msk;\ndz = dz.*msk;\n\n% Re-estimate (or rather nudge) movement parameters.\nif rem ~= 0\n iDtD = inv(spm_atranspa(D));\n for i=2:length(P)\n P(i).mat = inv(spm_matrix((iDtD*Dty{i})'))*P(i).mat;\n end\n [ds.q,ds.p0] = make_q(P,ds.fot,ds.sot,ds.exp_round);\nend\nspm_uw_show('EndRef');\nreturn\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [m_ref,D] = get_refD(ds,def,ddefa,P,xyz,msk)\n% Get partials w.r.t. movements from first scan.\n\n[idef,jac] = spm_get_image_def(1,ds,def,ddefa);\nT = P(1).mat\\ds.M;\ntxyz = xyz*T';\nc = spm_bsplinc(P(1),ds.hold);\n[m_ref,dx,dy,dz] = spm_bsplins(c,txyz(:,1),...\n txyz(:,2)+idef,txyz(:,3),ds.hold);\nindx = ~isnan(m_ref);\nmref_sf = 1 / (sum(m_ref(indx).*msk(indx)) / sum(msk(indx)));\nm_ref(indx) = m_ref(indx) .* mref_sf; m_ref(~indx) = 0;\ndx(indx) = dx(indx) .* mref_sf; dx(~indx) = 0;\ndy(indx) = dy(indx) .* mref_sf; dy(~indx) = 0;\ndz(indx) = dz(indx) .* mref_sf; dz(~indx) = 0;\nif ds.jm ~= 0\n m_ref = m_ref .* jac;\n dx = dx .* jac;\n dy = dy .* jac;\n dz = dz .* jac;\nend\nD = make_D(dx.*msk,dy.*msk,dz.*msk,txyz,P(1).mat);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction D = make_D(dx,dy,dz,xyz,M)\n% Utility function that creates a matrix of partial\n% derivatives in units of /mm and /radian.\n%\n% dx,dy,dz - Partial derivatives (/pixel) wrt x-, y- and z-translation.\n% xyz - xyz-matrix (original positions).\n% M - Current voxel->world matrix.\n\nD = zeros(length(xyz),6);\ntiny = 0.0001;\nfor i=1:6\n p = [0 0 0 0 0 0 1 1 1 0 0 0];\n p(i) = p(i)+tiny;\n T = M\\spm_matrix(p)*M;\n dxyz = xyz*T';\n dxyz = dxyz(:,1:3)-xyz(:,1:3);\n D(:,i) = sum(dxyz.*[dx dy dz],2)/tiny;\nend\nreturn\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction cleanup(P,ds)\n% Delete temporary smooth files.\n%\nif ~isempty(ds.fwhm) && ds.fwhm > 0\n for i=1:length(P)\n spm_unlink(P(i).fname);\n [fpath,fname,ext] = fileparts(P(i).fname);\n spm_unlink(fullfile(fpath,[fname '.hdr']));\n spm_unlink(fullfile(fpath,[fname '.mat']));\n end\nend\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction beta = refit(P,dispP,ds,def)\n% We have now estimated the fields on a grid that\n% does not coincide with the voxel centers. We must\n% now calculate the betas that correspond to a\n% a grid centered on the voxel centers.\n%\nspm_uw_show('StartRefit',1);\nrsP = P(1);\np = spm_imatrix(rsP.mat);\np = [zeros(1,6) p(7:9) 0 0 0];\np(1) = -mean(1:rsP.dim(1))*p(7);\np(2) = -mean(1:rsP.dim(2))*p(8);\np(3) = -mean(1:rsP.dim(3))*p(9);\nrsP.mat = spm_matrix(p); clear p;\n[x,y,z] = ndgrid(1:rsP.dim(1),1:rsP.dim(2),1:rsP.dim(3));\nxyz = [x(:) y(:) z(:) ones(numel(x),1)];\ntxyz = ((inv(dispP.mat)*rsP.mat)*xyz')';\nBx = spm_dctmtx(rsP.dim(1),ds.order(1));\nBy = spm_dctmtx(rsP.dim(2),ds.order(2));\nBz = spm_dctmtx(rsP.dim(3),ds.order(3));\nnx = rsP.dim(1); mx = ds.order(1);\nny = rsP.dim(2); my = ds.order(2);\nnz = rsP.dim(3); mz = ds.order(3);\nnof = numel(ds.fot) + size(ds.sot,1);\nfor i=1:nof\n dispP.dat = reshape(def(:,i),dispP.dim(1:3));\n c = spm_bsplinc(dispP,ds.hold);\n field = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds.hold);\n indx = isnan(field);\n wgt = ones(size(field));\n wgt(indx) = 0;\n field(indx) = 0;\n AtA = zeros(mx*my*mz);\n Aty = zeros(mx*my*mz,1);\n for sl = 1:nz\n indx = (sl-1)*nx*ny+1:sl*nx*ny;\n tmp1 = reshape(field(indx).*wgt(indx),nx,ny);\n tmp2 = reshape(wgt(indx),nx,ny);\n spm_krutil(Bz(sl,:)'*Bz(sl,:),spm_krutil(tmp2,Bx,By,1),AtA);\n% AtA = AtA + kron(Bz(sl,:)'*Bz(sl,:),spm_krutil(tmp2,Bx,By,1));\n Aty = Aty + kron(Bz(sl,:)',spm_krutil(tmp1,Bx,By,0));\n end\n beta((i-1)*prod(ds.order)+1:i*prod(ds.order)) = AtA\\Aty;\nend\nspm_uw_show('EndRefit');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction msk = get_mask(P,xyz,ds,dm)\n%\n% Create a mask to avoid regions where data doesnt exist\n% for all scans. This mask is slightly less Q&D than that\n% of version 1 of Unwarp. It checks where data exist for\n% all scans with present movement parameters and given\n% (optionally) the static field. It creates a mask with\n% non-zero values only for those voxels, and then does a\n% 3D erode to preempt effects of re-estimated movement\n% parameters and movement-by-susceptibility effects.\n%\nspm_uw_show('MaskStart',length(P));\nmsk = true(length(xyz),1);\nfor i=1:length(P)\n txyz = xyz * (P(i).mat\\ds.M)';\n tmsk = (txyz(:,1)>=1 & txyz(:,1)<=P(1).dim(1) &...\n txyz(:,2)>=1 & txyz(:,2)<=P(1).dim(2) &...\n txyz(:,3)>=1 & txyz(:,3)<=P(1).dim(3));\n msk = msk & tmsk;\n spm_uw_show('MaskUpdate',i);\nend\n%\n% Include static field in mask estimation\n% if one has been supplied.\n%\nif isfield(ds,'sfP') && ~isempty(ds.sfP)\n txyz = xyz * (ds.sfP.mat\\ds.M)';\n tmsk = (txyz(:,1)>=1 & txyz(:,1)<=P(1).dim(1) &...\n txyz(:,2)>=1 & txyz(:,2)<=P(1).dim(2) &...\n txyz(:,3)>=1 & txyz(:,3)<=P(1).dim(3));\n msk = msk & tmsk;\nend\nmsk = erode_msk(msk,dm);\nspm_uw_show('MaskEnd');\n\n% maskP = P(1);\n% [mypath,myname,myext] = fileparts(maskP.fname);\n% maskP.fname = fullfile(mypath,['mask' myext]);\n% maskP.dim = [nx ny nz];\n% maskP.dt = P(1).dt;\n% maskP = spm_write_vol(maskP,reshape(msk,[nx ny nz]));\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction omsk = erode_msk(msk,dim)\nomsk = zeros(dim+[4 4 4]);\nomsk(3:end-2,3:end-2,3:end-2) = reshape(msk,dim);\nomsk = spm_erode(omsk(:),dim+[4 4 4]);\nomsk = reshape(omsk,dim+[4 4 4]);\nomsk = omsk(3:end-2,3:end-2,3:end-2);\nomsk = omsk(:);\nreturn\n%_______________________________________________________________________\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_prep2sn.m", "ext": ".m", "path": "spm5-master/spm_prep2sn.m", "size": 7396, "source_encoding": "utf_8", "md5": "61eb57b5fb967c417d75aa0e5761501b", "text": "function [po,pin] = spm_prep2sn(p)\n% Convert the output from spm_preproc into an sn.mat\n% FORMAT [po,pin] = spm_prep2sn(p)\n% p - the results of spm_preproc\n% po - the output in a form that can be used by\n% spm_write_sn.\n% pin - the inverse transform in a form that can be\n% used by spm_write_sn.\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_prep2sn.m 946 2007-10-15 16:36:06Z john $\n\n\nif ischar(p), p = load(p); end;\n\nVG = p.tpm;\nVF = p.image;\n[Y1,Y2,Y3] = create_def(p.Twarp,VF,VG(1),p.Affine);\n[Y1,Y2,Y3] = spm_invdef(Y1,Y2,Y3,VG(1).dim(1:3),eye(4),eye(4));\nMT = procrustes(Y1,Y2,Y3,VG(1),VF.mat);\nd = size(p.Twarp);\n[Affine,Tr] = reparameterise(Y1,Y2,Y3,VG(1),VF.mat,MT,max(d(1:3)+2,[8 8 8]));\nflags = struct(...\n 'ngaus', p.ngaus,...\n 'mg', p.mg,...\n 'mn', p.mn,...\n 'vr', p.vr,...\n 'warpreg', p.warpreg,...\n 'warpco', p.warpco,...\n 'biasreg', p.biasreg,...\n 'biasfwhm', p.biasfwhm,...\n 'regtype', p.regtype,...\n 'fudge', p.fudge,...\n 'samp', p.samp,...\n 'msk', p.msk,...\n 'Affine', p.Affine,...\n 'Twarp', p.Twarp,...\n 'Tbias', p.Tbias,...\n 'thresh', p.thresh);\n\nif nargout==0,\n [pth,nam,ext] = fileparts(VF.fname);\n fnam = fullfile(pth,[nam '_seg_sn.mat']);\n if spm_matlab_version_chk('7') >= 0,\n save(fnam,'-V6','VG','VF','Tr','Affine','flags');\n else\n save(fnam,'VG','VF','Tr','Affine','flags');\n end;\nelse\n po = struct(...\n 'VG', VG,...\n 'VF', VF,...\n 'Tr', Tr,...\n 'Affine', Affine,...\n 'flags', flags);\nend;\nif nargout>=2,\n % Parameterisation for the inverse\n pin = struct(...\n 'VG', p.image,...\n 'VF', p.tpm(1),...\n 'Tr', p.Twarp,...\n 'Affine', p.tpm(1).mat\\p.Affine*p.image.mat,...\n 'flags', flags);\n % VG = p.image;\n % VF = p.tpm(1);\n % Tr = p.Twarp;\n % Affine = p.tpm(1).mat\\p.Affine*p.image.mat;\n % save('junk_sn.mat','VG','VF','Tr','Affine');\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [Affine,Tr] = reparameterise(Y1,Y2,Y3,B,M2,MT,d2)\n% Take a deformation field and reparameterise in the same form\n% as used by the spatial normalisation routines of SPM\nd = [size(Y1) 1];\n[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);\nx3 = 1:d(3);\nAffine = M2\\MT*B(1).mat;\nA = inv(Affine);\n\nB1 = spm_dctmtx(d(1),d2(1));\nB2 = spm_dctmtx(d(2),d2(2));\nB3 = spm_dctmtx(d(3),d2(3));\npd = prod(d2(1:3));\nAA = eye(pd)*0.01;\nAb = zeros(pd,3);\nspm_progress_bar('init',length(x3),['Reparameterising'],'Planes completed');\nmx = [0 0 0];\nfor z=1:length(x3),\n y1 = double(Y1(:,:,z));\n y2 = double(Y2(:,:,z));\n y3 = double(Y3(:,:,z));\n msk = isfinite(y1);\n w = double(msk);\n y1(~msk) = 0;\n y2(~msk) = 0;\n y3(~msk) = 0;\n z1 = A(1,1)*y1+A(1,2)*y2+A(1,3)*y3 + w.*(A(1,4) - x1);\n z2 = A(2,1)*y1+A(2,2)*y2+A(2,3)*y3 + w.*(A(2,4) - x2);\n z3 = A(3,1)*y1+A(3,2)*y2+A(3,3)*y3 + w *(A(3,4) - z );\n b3 = B3(z,:)';\n Ab(:,1) = Ab(:,1) + kron(b3,spm_krutil(z1,B1,B2,0));\n Ab(:,2) = Ab(:,2) + kron(b3,spm_krutil(z2,B1,B2,0));\n Ab(:,3) = Ab(:,3) + kron(b3,spm_krutil(z3,B1,B2,0));\n AA = AA + kron(b3*b3',spm_krutil(w, B1,B2,1));\n spm_progress_bar('set',z);\nend;\nspm_progress_bar('clear');\nTr = reshape(AA\\Ab,[d2(1:3) 3]); drawnow;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction MT = procrustes(Y1,Y2,Y3,B,M2)\n% Take a deformation field and determine the closest rigid-body\n% transform to match it, with weighing.\n%\n% Example Reference:\n% F. L. Bookstein (1997). \"Landmark Methods for Forms Without\n% Landmarks: Morphometrics of Group Differences in Outline Shape\"\n% Medical Image Analysis 1(3):225-243\n\nM1 = B.mat;\nd = B.dim(1:3);\n[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);\nx3 = 1:d(3);\nc1 = [0 0 0];\nc2 = [0 0 0];\nsw = 0;\nspm_progress_bar('init',length(x3),['Procrustes (1)'],'Planes completed');\nfor z=1:length(x3),\n y1 = double(Y1(:,:,z));\n y2 = double(Y2(:,:,z));\n y3 = double(Y3(:,:,z));\n msk = find(isfinite(y1));\n w = spm_sample_vol(B(1),x1(msk),x2(msk),o(msk)*z,0);\n swz = sum(w(:));\n sw = sw+swz;\n c1 = c1 + [w'*[x1(msk) x2(msk)] swz*z ];\n c2 = c2 + w'*[y1(msk) y2(msk) y3(msk)];\n spm_progress_bar('set',z);\nend;\nspm_progress_bar('clear');\nc1 = c1/sw;\nc2 = c2/sw;\nT1 = [eye(4,3) M1*[c1 1]'];\nT2 = [eye(4,3) M2*[c2 1]'];\nC = zeros(3);\nspm_progress_bar('init',length(x3),['Procrustes (2)'],'Planes completed');\nfor z=1:length(x3),\n y1 = double(Y1(:,:,z));\n y2 = double(Y2(:,:,z));\n y3 = double(Y3(:,:,z));\n msk = find(isfinite(y1));\n w = spm_sample_vol(B(1),x1(msk),x2(msk),o(msk)*z,0);\n C = C + [(x1(msk)-c1(1)).*w (x2(msk)-c1(2)).*w ( z-c1(3))*w ]' * ...\n [(y1(msk)-c2(1)) (y2(msk)-c2(2)) (y3(msk)-c2(3)) ];\n spm_progress_bar('set',z);\nend;\nspm_progress_bar('clear');\n[u,s,v] = svd(M1(1:3,1:3)*C*M2(1:3,1:3)');\nR = eye(4);\nR(1:3,1:3) = v*u';\nMT = T2*R*inv(T1);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [Y1,Y2,Y3] = create_def(T,VG,VF,Affine)\n% Generate a deformation field from its parameterisation.\nd2 = size(T);\nd = VG.dim(1:3);\nM = VF.mat\\Affine*VG.mat;\n[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);\nx3 = 1:d(3);\nB1 = spm_dctmtx(d(1),d2(1));\nB2 = spm_dctmtx(d(2),d2(2));\nB3 = spm_dctmtx(d(3),d2(3));\n[pth,nam,ext] = fileparts(VG.fname);\nspm_progress_bar('init',length(x3),['Creating Def: ' nam],'Planes completed');\nfor z=1:length(x3),\n [y1,y2,y3] = defs(T,z,B1,B2,B3,x1,x2,x3,M);\n Y1(:,:,z) = single(y1);\n Y2(:,:,z) = single(y2);\n Y3(:,:,z) = single(y3);\n spm_progress_bar('set',z);\nend;\nspm_progress_bar('clear');\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M)\nif ~isempty(sol),\n x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1));\n y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2));\n z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3));\nelse\n x1a = x0;\n y1a = y0;\n z1a = z0;\nend;\nx1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);\ny1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);\nz1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction t = transf(B1,B2,B3,T)\nd2 = [size(T) 1];\nt1 = reshape(T, d2(1)*d2(2),d2(3)); drawnow;\nt1 = reshape(t1*B3', d2(1), d2(2)); drawnow;\nt = B1*t1*B2';\nreturn;\n%=======================================================================\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_TesSph.m", "ext": ".m", "path": "spm5-master/spm_eeg_inv_TesSph.m", "size": 5477, "source_encoding": "utf_8", "md5": "b524de0b479cac1e72ad958508ad4ad2", "text": "function tsph = spm_eeg_inv_TesSph(r,n);\n\n%=======================================================================\n% FORMAT tsph = spm_eeg_inv)TesSph(r,n);\n%\n% Generate a structure 'tsph' containing a tesselated sphere.\n%\n% Input : \n% r - radius of the sphere\n% n - number of 'latitude' divisions on the sphere. It MUST be even!\n% ( Nvert = 5/4 * n^2 + 2 )\n%\n% Output : \n% tsph .vert - vertices coordinates (3 x Nvert)\n% .tri - triangle patches (3 x Ntri)\n%\t .info - info string\n%=======================================================================\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Christophe Phillips & Jeremie Mattout\n% $Id: spm_eeg_inv_TesSph.m 716 2007-01-16 21:13:50Z karl $\n\nif nargin == 0 \n n = 40;\n\tr = 1;\nelseif nargin == 1\n n = 40;\nelseif nargin == 2\n n = round( sqrt(4*(n - 2)/5) );\nelse\n error('Error: wrong input format')\nend\n\t\n[X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r) ;\n[ind_tr] = tri(npt_tr,npt_qr,npt_sph) ;\n\t\ntsph.vert = [X_sp ; Y_sp ; Z_sp] ;\ntsph.tri = ind_tr ;\ntsph.nr = [length(X_sp) size(ind_tr,2)] ;\ntsph.info = ['Tes sph : n=',num2str(n),', r=',num2str(r)] ;\nvarargout{1} = tsph;\n\n\n%________________________________________________________________________\n% FORMAT [X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r)\n% Generate a set of points on a sphere.\n% n = the number of latitudes on the sphere, it MUST be even!\n% r = radius of the sphere, 1 by default.\n%------------------------------------------------------------------------\nfunction [X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r)\nd_r = pi/180; dth = 180/n*d_r ;\nX_qr=[] ; Y_qr=[] ; Z_qr=[] ; X_sp=[] ; Y_sp=[] ; Z_sp=[] ;\n\n% Coord of pts on a 5th of sphere WITHOUT the top and bottom points\nfor i=1:n/2 % Upper part\n\tthe = i*dth ;\n\tcth = cos(the) ; sth = sin(the) ;\n\tdphi = 72/i*d_r ;\n\tfor j=1:i\n\t\tphi = (j-1)*dphi ;\n\t\tcph = cos(phi) ; sph = sin(phi) ;\n\t\tX_qr = [X_qr sth*cph] ;\n\t\tY_qr = [Y_qr sth*sph] ;\n\t\tZ_qr = [Z_qr cth] ;\n\tend\nend\nfor i=(n/2+1):(n-1) % Lower part\n\tthe = i*dth ;\n\tcth = cos(the) ; sth = sin(the) ;\n\tii = n-i ;\n\tdphi = 72/ii*d_r ;\n\tfor j=1:ii\n\t\tphi = (j-1)*dphi ;\n\t\tcph = cos(phi) ; sph = sin(phi) ;\n\t\tX_qr = [X_qr sth*cph] ;\n\t\tY_qr = [Y_qr sth*sph] ;\n\t\tZ_qr = [Z_qr cth] ;\n\tend\nend\n% Each part is copied with a 72deg shift\ndphi=-72*d_r ;\nfor i=0:4\n\tphi=i*dphi ;\n\tcph=cos(phi) ;\n\tsph=sin(phi) ;\n\tX_sp=[X_sp cph*X_qr+sph*Y_qr] ;\n\tY_sp=[Y_sp -sph*X_qr+cph*Y_qr] ;\n\tZ_sp=[Z_sp Z_qr] ;\nend\n% add top and bottom points\nX_sp=[0 X_sp 0]*r ;\nY_sp=[0 Y_sp 0]*r ;\nZ_sp=[1 Z_sp -1]*r ;\n\nnpt_tr = [[0:n/2] [n/2-1:-1:0]]; % Nbr of points on each slice for a 5th of sph.\nnpt_qr = sum(npt_tr) ; % total nbr of pts per 5th of sphere\nnpt_sph=5/4*n^2+2 ; % or 5*npt_qr+2 ; % total nbr of pts on sph\nreturn\n\n%________________________________________________________________________\n% FORMAT [ind_tr] = tri(npt_tr,npt_qr,npt_sph)\n% Order the pts created by the function 'point' into triangles\n% Each triangle is represented by 3 indices correponding to the XYZ_sp\n%\n% This works only because I know in wich order the vertices are generated\n% in the 'point' function.\n%------------------------------------------------------------------------\nfunction [ind_tr] = tri(npt_tr,npt_qr,npt_sph)\nn = sqrt(4/5*(npt_sph-2)) ;\n\n% First 5th of sphere only\nfor i=0:(n/2-1) % upper half\n\tif i==0\t\t \t% 1st triangle at the top\n\t\tind_qr=[1 2 2+npt_qr]' ;\n\telse\t\t \t% other triangles\n\t\tfor j=0:npt_tr(i+1)\n\t\t\tif j==npt_tr(i+1)-1\t\t\t% last but 1 pt on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+j+2 ;\n\t\t\t\tx12=x1+npt_tr(i+1) ;\n\t\t\t\tx13=x12+1 ;\n\t\t\t\tx22=x13 ;\n\t\t\t\tx23=sum(npt_tr(1:i))+2+npt_qr ;\n\t\t\t\tind_qr=[ind_qr [x1 x12 x13]' [x1 x22 x23]'] ;\n\t\t\telseif j==npt_tr(i+1)\t\t% last pt on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+2+npt_qr ;\n\t\t\t\tx2=sum(npt_tr(1:(i+1)))+j+2 ;\n\t\t\t\tx3=x1+npt_tr(i+1) ;\n\t\t\t\tind_qr=[ind_qr [x1 x2 x3]'] ;\n\t\t\telse \t\t\t% other pts on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+j+2 ;\n\t\t\t\tx12=x1+npt_tr(i+1) ;\n\t\t\t\tx13=x12+1 ;\n\t\t\t\tx22=x13 ;\n\t\t\t\tx23=x1+1 ;\n\t\t\t\tind_qr=[ind_qr [x1 x12 x13]' [x1 x22 x23]'] ;\n\t\t\tend\n\t\tend\n\tend\nend\nfor i=(n/2+1):n % lower half\n\tif i==n\t \t% last triangle at the bottom\n\t\tind_qr=[ind_qr [5*npt_qr+2 2*npt_qr+1 npt_qr+1]' ] ;\n\telse \t% other triangles\n\t\tfor j=0:npt_tr(i+1)\n\t\t\tif j==npt_tr(i+1)-1\t\t\t% last but 1 pt on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+j+2 ;\n\t\t\t\tx12=x1-npt_tr(i) ;\n\t\t\t\tx13=x12+1 ;\n\t\t\t\tx22=x13 ;\n\t\t\t\tx23=sum(npt_tr(1:i))+2+npt_qr ;\n\t\t\t\tind_qr=[ind_qr [x1 x13 x12]' [x1 x23 x22]'] ;\n\t\t\telseif j==npt_tr(i+1)\t\t% last pt on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+2+npt_qr ;\n\t\t\t\tx2=sum(npt_tr(1:(i-1)))+j+2 ;\n\t\t\t\tx3=x1-npt_tr(i) ;\n\t\t\t\tind_qr=[ind_qr [x1 x3 x2]'] ;\n\t\t\telse \t\t\t% other pts on slice\n\t\t\t\tx1=sum(npt_tr(1:i))+j+2 ;\n\t\t\t\tx12=x1-npt_tr(i) ;\n\t\t\t\tx13=x12+1 ;\n\t\t\t\tx22=x13 ;\n\t\t\t\tx23=x1+1 ;\n\t\t\t\tind_qr=[ind_qr [x1 x13 x12]' [x1 x23 x22]'] ;\n\t\t\tend\n\t\tend\n\tend\nend\n\n\nntr_qr =size(ind_qr,2) ; % nbr of triangle per 5th of sphere\n[S_i,S_j]=find(ind_qr==1) ;\n[B_i,B_j]=find(ind_qr==npt_sph) ;\n[qs_i,qs_j]=find((ind_qr>(npt_qr+1))&(ind_qr<(3*npt_qr))) ;\nind_tr=[] ;\n\n% shift all indices to cover the sphere\nfor i=0:4\n\tind_tr = [ind_tr (ind_qr+i*npt_qr)] ;\n\tind_tr(S_i,S_j+i*ntr_qr) = 1 ;\n\tind_tr(B_i,B_j+i*ntr_qr) = npt_sph ;\nend\nfor i=1:size(qs_i,1)\n\tind_tr(qs_i(i),qs_j(i)+4*ntr_qr) = ...\n\t\tind_tr(qs_i(i),(qs_j(i)+4*ntr_qr))-5*npt_qr ;\nend\nntr_sph = size(ind_tr,2) ;% nbr of triangles on the sphere\n\t% or = 5/2*n^2\nreturn\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_ovhelper_3Dreg.m", "ext": ".m", "path": "spm5-master/spm_orthviews/spm_ovhelper_3Dreg.m", "size": 2312, "source_encoding": "utf_8", "md5": "50f2f405f2da022944b80781d2e481a6", "text": "function spm_ovhelper_3Dreg(cmd, varargin)\n\nif ishandle(varargin{1})\n h = varargin{1};\nelseif ischar(varargin{1})\n h = findobj(0, 'Tag',varargin{1});\n if ~ishandle(h)\n warning([mfilename ':InvalidHandle'], ...\n\t 'No valid graphics handle found');\n return;\n else\n h = get(h(ishandle(h)),'parent');\n end;\nend;\n\nswitch lower(cmd)\n case 'register'\n register(h,varargin{2:end});\n return;\n case 'setcoords'\n setcoords(varargin{1:end});\n return;\n case 'unregister',\n unregister(h,varargin{2:end});\n return;\n case 'xhairson'\n xhairs(h,'on',varargin{2:end});\n return;\n case 'xhairsoff'\n xhairs(h,'off',varargin{2:end});\n return;\nend;\n\nfunction register(h,V,varargin)\ntry\n global st;\n if isstruct(st)\n xyz=spm_orthviews('pos');\n if isfield(st,'registry')\n hreg = st.registry.hReg;\n else\n [hreg xyz]=spm_XYZreg('InitReg', h, V.mat, ...\n V.dim(1:3)',xyz); \n spm_orthviews('register',hreg);\n end;\n spm_XYZreg('Add2Reg',hreg,h,mfilename);\n feval(mfilename,'setcoords',xyz,h);\n set(h, 'DeleteFcn', ...\n\t sprintf('%s(''unregister'',%f);', mfilename, h));\n end;\ncatch\n warning([mfilename ':XYZreg'],...\n 'Unable to register to spm_orthviews display');\n disp(lasterr);\nend; \nreturn;\n\nfunction setcoords(xyz,h,varargin)\nspm('pointer','watch');\nXh = findobj(h,'Tag', 'Xhairs');\nif ishandle(Xh)\n vis = get(Xh(1),'Visible');\n delete(Xh);\nelse\n vis = 'on';\nend;\naxes(findobj(h,'Type','axes'));\nlim = axis;\nXh = line([xyz(1), xyz(1), lim(1);...\n\t xyz(1), xyz(1), lim(2)],...\n\t [lim(3), xyz(2), xyz(2);...\n\t lim(4), xyz(2), xyz(2)],...\n\t [xyz(3), lim(5), xyz(3);...\n\t xyz(3), lim(6), xyz(3)],...\n\t 'Color','b', 'Tag','Xhairs', 'Visible',vis,...\n\t 'Linewidth',2, 'HitTest','off');\nspm('pointer','arrow');\nreturn;\n\nfunction xhairs(h,val,varargin)\nXh = findobj(h, 'Tag', 'Xhairs');\nif ~isempty(Xh)\n set(Xh,'Visible',val);\nend;\n \nfunction unregister(h,varargin)\ntry\n global st;\n if isfield(st,'registry')\n hreg = st.registry.hReg;\n else\n hreg = findobj(0,'Tag','hReg');\n end;\n if h == hreg\n spm_XYZreg('UnInitReg',hreg);\n st = rmfield(st, 'registry');\n else\n spm_XYZreg('Del2Reg',hreg,h);\n end;\ncatch\n warning([mfilename ':XYZreg'],...\n\t 'Unable to unregister');\n disp(lasterr);\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_ov_roi.m", "ext": ".m", "path": "spm5-master/spm_orthviews/spm_ov_roi.m", "size": 29856, "source_encoding": "utf_8", "md5": "0297a491107f32f68e456f0584fa5a5e", "text": "function ret = spm_ov_roi(varargin)\n% ROI tool - plugin for spm_orthviews\n%\n% With ROI tool it is possible to create new or modify existing mask images\n% interactively. ROI tool can be launched via the spm_orthviews image\n% context menu.\n% While ROI tool is active, mouse buttons have the following functions:\n% left Reposition crosshairs\n% middle Perform ROI tool box selection according to selected edit mode at\n% crosshair position\n% right context menu\n% \n% Menu options and prompts explained:\n% Launch Initialise ROI tool in current image\n% 'Load existing ROI image? (yes/no)' \n% If you want to modify an existing mask image (e.g. mask.img from\n% a fMRI analysis), press 'yes'. You will then be prompted to\n% 'Select ROI image'\n% This is the image that will be loaded as initial ROI.\n% If you want to create a new ROI image, you will first be\n% prompted to\n% 'Select image defining ROI space'\n% The image dimensions, voxel sizes and slice orientation will\n% be read from this image. Thus you can edit a ROI based on a\n% image with a resolution and slice orientation different from\n% the underlying displayed image.\n%\n% Once ROI tool is active, the menu consists of three parts: settings,\n% edit operations and load/save operations.\n% Settings\n% --------\n% Selection Operation performed when pressing the middle mouse button or\n% mode by clustering operations.\n% 'Set selection'\n% The selection made with the following commands will\n% be included in your ROI.\n% 'Clear selection' \n% The selection made with the following commands will\n% be excluded from your ROI.\n% Box size Set size of box to be (de)selected when pressing the\n% middle mouse button.\n% Polygon Set number of adjacent slices selected by one polygon\n% slices drawing. \n% Cluster Set minimum cluster size for \"Cleanup clusters\" and\n% size \"Connected cluster\" operations.\n% Erosion/ During erosion/dilation operations, the binary mask will be\n% dilation smoothed. At boundaries, this will result in mask values \n% threshold that are not exactly zero or one, but somewhere in\n% between. Whether a mask will be eroded (i.e. be smaller than\n% the original) or dilated (i.e. grow) depends on this\n% threshold. A threshold below 0.5 dilates, above 0.5 erodes a\n% mask. \n% Edit actions\n% ------------\n% Polygon Draw an outline on one of the 3 section images. Voxels\n% within the outline will be added to the ROI. The same\n% outline can be applied to a user-defined number of\n% consecutive slices around the current crosshair position.\n% Threshold You will be prompted to enter a [min max] threshold. Only\n% those voxels in the ROI image where the intensities of the\n% underlying image are within the [min max] range will survive\n% this operation.\n% Connected Select only voxels that are connected to the voxel at\n% cluster current crosshair position through the ROI.\n% Cleanup Keep only clusters that are larger than a specified cluster \n% clusters size.\n% Erode/ Erode or dilate a mask, using the current erosion/dilation\n% Dilate threshold.\n% Invert Invert currently defined ROI\n% Clear Clear ROI, but keep ROI space information\n% Add ROI from file(s)\n% Add ROIs from file(s) into current ROI set. According to the\n% current edit mode voxels unequal zero will be set or\n% cleared. The image files will be resampled and thus do not\n% need to have the same orientation or voxel size as the\n% original ROI.\n% Save actions\n% ------------\n% Save Save ROI image\n% Save As Save ROI image under a new file name\n% Quit Quit ROI tool\n%\n% This routine is a plugin to spm_orthviews for SPM5. For general help about\n% spm_orthviews and plugins type\n% help spm_orthviews\n% at the matlab prompt.\n%_____________________________________________________________________________\n% $Id: spm_ov_roi.m 2672 2009-01-30 13:32:08Z volkmar $\n\n% Note: This plugin depends on the blobs set by spm_orthviews('addblobs',...) \n% They should not be removed while ROI tool is active and no other blobs be\n% added. This restriction may be removed when switching to MATLAB 6.x and\n% using the 'alpha' property to overlay blobs onto images.\n\nrev = '$Revision: 2672 $';\n\nglobal st;\nif isempty(st)\n error('roi: This routine can only be called as a plugin for spm_orthviews!');\nend;\n\nif nargin < 2\n error('roi: Wrong number of arguments. Usage: spm_orthviews(''roi'', cmd, volhandle, varargin)');\nend;\n\ncmd = lower(varargin{1});\nvolhandle = varargin{2};\n\ntoset = [];\ntoclear = [];\ntochange = [];\nupdate_roi = 0;\n\nswitch cmd\n case 'init'\n spm('pointer','watch');\n Vroi = spm_vol(varargin{3});\n switch varargin{4} % loadasroi\n case 1,\n roi = spm_read_vols(Vroi)>0;\n [x y z] = ndgrid(1:Vroi.dim(1),1:Vroi.dim(2),1:Vroi.dim(3));\n xyz = [x(roi(:))'; y(roi(:))'; z(roi(:))'];\n case {0,2} % ROI space image or SPM mat\n Vroi = rmfield(Vroi,'private');\n roi = zeros(Vroi.dim(1:3));\n Vroi.fname = fileparts(Vroi.fname); % save path\n Vroi.dt(1) = spm_type('uint8');\n xyz = varargin{5};\n if ~isempty(xyz)\n\tind = sub2ind(Vroi.dim(1:3),xyz(1,:),xyz(2,:),xyz(3,:));\n\troi(ind) = 1;\n end;\n end;\n Vroi.pinfo(1:2) = Inf;\n clear x y z\n\n % draw a frame only if ROI volume different from underlying GM volume\n if any(Vroi.dim(1:3)-st.vols{volhandle}.dim(1:3))| ...\n\tany(Vroi.mat(:)-st.vols{volhandle}.mat(:))\n [xx1 yx1 zx1] = ndgrid(1 , 1:Vroi.dim(2), 1:Vroi.dim(3));\n [xx2 yx2 zx2] = ndgrid(Vroi.dim(1) , 1:Vroi.dim(2), 1:Vroi.dim(3));\n [xy1 yy1 zy1] = ndgrid(1:Vroi.dim(1), 1 , 1:Vroi.dim(3));\n [xy2 yy2 zy2] = ndgrid(1:Vroi.dim(1), Vroi.dim(2) , 1:Vroi.dim(3));\n [xz1 yz1 zz1] = ndgrid(1:Vroi.dim(1), 1:Vroi.dim(2), 1);\n [xz2 yz2 zz2] = ndgrid(1:Vroi.dim(1), 1:Vroi.dim(2), Vroi.dim(3));\n \n fxyz = [xx1(:)' xx2(:)' xy1(:)' xy2(:)' xz1(:)' xz2(:)'; ...\n\t yx1(:)' yx2(:)' yy1(:)' yy2(:)' yz1(:)' yz2(:)'; ...\n\t zx1(:)' zx2(:)' zy1(:)' zy2(:)' zz1(:)' zz2(:)'];\n clear xx1 yx1 zx1 xx2 yx2 zx2 xy1 yy1 zy1 xy2 yy2 zy2 xz1 yz1 zz1 xz2 yz2 zz2\n hframe = 1;\n else\n hframe = [];\n fxyz = [];\n end;\n\n for k=1:3\n cb{k}=get(st.vols{volhandle}.ax{k}.ax,'ButtonDownFcn');\n set(st.vols{volhandle}.ax{k}.ax,...\n\t'ButtonDownFcn',...\n\t['switch get(gcf,''SelectionType'')',...\n\t 'case ''normal'', spm_orthviews(''Reposition'');',...\n\t 'case ''extend'', spm_orthviews(''roi'',''edit'',', ...\n\t num2str(volhandle), ');',...\n\t 'case ''alt'', spm_orthviews(''context_menu'',''ts'',1);',...\n\t 'end;']);\n end;\n\n st.vols{volhandle}.roi = struct('Vroi',Vroi, 'xyz',xyz, 'roi',roi,...\n\t\t\t\t 'hroi',1, 'fxyz',fxyz,...\n\t\t\t\t 'hframe',hframe, 'mode','set',...\n\t\t\t\t 'tool', 'box', ...\n\t\t\t\t 'thresh',[60 140], 'box',[4 4 4],...\n\t\t\t\t 'cb',[], 'polyslices',1, 'csize',5,...\n 'erothresh',.5);\n st.vols{volhandle}.roi.cb = cb;\n\n if ~isempty(st.vols{volhandle}.roi.fxyz)\n if isfield(st.vols{volhandle}, 'blobs')\n st.vols{volhandle}.roi.hframe = prod(size(st.vols{volhandle}.blobs))+1;\n end;\n spm_orthviews('addcolouredblobs',volhandle, ...\n\t\t st.vols{volhandle}.roi.fxyz,...\n\t\t ones(size(st.vols{volhandle}.roi.fxyz,2),1), ... \n\t\t st.vols{volhandle}.roi.Vroi.mat,[1 .5 .5]);\n st.vols{volhandle}.blobs{st.vols{volhandle}.roi.hframe}.max=1.3;\n end;\n update_roi=1;\n\n case 'edit'\n switch st.vols{volhandle}.roi.tool\n case 'box'\n\t spm('pointer','watch');\n\t pos = round(inv(st.vols{volhandle}.roi.Vroi.mat)* ...\n\t\t [spm_orthviews('pos'); 1]); \n\t tmp = round((st.vols{volhandle}.roi.box-1)/2);\n\t [sx sy sz] = meshgrid(-tmp(1):tmp(1), -tmp(2):tmp(2), -tmp(3):tmp(3));\n\t sel = [sx(:)';sy(:)';sz(:)']+repmat(pos(1:3), 1,prod(2*tmp+1));\n\t tochange = sel(:, (all(sel>0) &...\n\t\t\t sel(1,:)<=st.vols{volhandle}.roi.Vroi.dim(1) & ...\n\t\t\t sel(2,:)<=st.vols{volhandle}.roi.Vroi.dim(2) & ...\n\t\t\t sel(3,:)<=st.vols{volhandle}.roi.Vroi.dim(3)));\n\t update_roi = 1;\n \n case 'poly'\n \n\t % @COPYRIGHT :\n\t % Copyright 1993,1994 Mark Wolforth and Greg Ward, McConnell\n\t % Brain Imaging Centre, Montreal Neurological Institute, McGill\n\t % University.\n\t % Permission to use, copy, modify, and distribute this software\n\t % and its documentation for any purpose and without fee is\n\t % hereby granted, provided that the above copyright notice\n\t % appear in all copies. The authors and McGill University make\n\t % no representations about the suitability of this software for\n\t % any purpose. It is provided \"as is\" without express or\n\t % implied warranty.\n\t for k = 1:3\n\t if st.vols{volhandle}.ax{k}.ax == gca\n\t\t axhandle = k;\n\t\t break;\n\t end;\n\t end;\n\t line_color = [1 1 0];\n\t axes(st.vols{volhandle}.ax{axhandle}.ax);\n\t \n\t hold on;\n\t Xlimits = get (st.vols{volhandle}.ax{axhandle}.ax,'XLim');\n\t Ylimits = get (st.vols{volhandle}.ax{axhandle}.ax,'YLim');\n\t XLimMode = get(st.vols{volhandle}.ax{axhandle}.ax,'XLimMode');\n\t set(st.vols{volhandle}.ax{axhandle}.ax,'XLimMode','manual');\n\t YLimMode = get(st.vols{volhandle}.ax{axhandle}.ax,'YLimMode');\n\t set(st.vols{volhandle}.ax{axhandle}.ax,'YLimMode','manual');\n\t ButtonDownFcn = get(st.vols{volhandle}.ax{axhandle}.ax,'ButtonDownFcn');\n\t set(st.vols{volhandle}.ax{axhandle}.ax,'ButtonDownFcn','');\n\t UIContextMenu = get(st.vols{volhandle}.ax{axhandle}.ax,'UIContextMenu');\n\t set(st.vols{volhandle}.ax{axhandle}.ax,'UIContextMenu',[]);\n\t set(st.vols{volhandle}.ax{axhandle}.ax,'Selected','on');\n\t disp (['Please mark the ROI outline in the highlighted image' ...\n\t\t ' display.']);\n\t disp ('Points outside the ROI image area will be clipped to');\n\t disp ('the image boundaries.');\n\t disp ('Left-Click on the vertices of the ROI...');\n\t disp ('Middle-Click to finish ROI selection...');\n\t disp ('Right-Click to cancel...');\n\t x=Xlimits(1);\n\t y=Ylimits(1);\n\t i=1;\n\t lineHandle = [];\n\t xc = 0; yc = 0; bc = 0;\n\t while ~isempty(bc)\n\t [xc,yc,bc] = ginput(1);\n\t if isempty(xc) | bc > 1\n\t\t if bc == 3\n\t\t x = []; y=[];\n\t\t end;\n\t\t if bc == 2 | bc == 3\n\t\t bc = [];\n\t\t break;\n\t\t end;\n\t else\n\t\t if xc > Xlimits(2)\n\t\t xc = Xlimits(2);\n\t\t elseif xc < Xlimits(1)\n\t\t xc = Xlimits(1);\n\t\t end;\n\t\t if yc > Ylimits(2)\n\t\t yc = Ylimits(2);\n\t\t elseif yc < Ylimits(1)\n\t\t yc = Ylimits(1);\n\t\t end;\n\t\t x(i) = xc;\n\t\t y(i) = yc;\n\t\t i=i+1;\n\t\t if ishandle(lineHandle)\n\t\t delete(lineHandle);\n\t\t end;\n\t\t lineHandle = line (x,y,ones(1,length(x)), ...\n\t\t\t\t 'Color',line_color,...\n\t\t\t\t 'parent',st.vols{volhandle}.ax{axhandle}.ax,...\n\t\t\t\t 'HitTest','off');\n\t end;\n\t end\n\t \n\t if ishandle(lineHandle)\n\t delete(lineHandle);\n\t end;\n\t if ~isempty(x)\n\t spm('pointer','watch');\n\t x(i)=x(1);\n\t y(i)=y(1);\n\t prms=spm_imatrix(st.vols{volhandle}.roi.Vroi.mat);\n\t % Code from spm_orthviews('redraw') for determining image\n\t % positions\n\t is = inv(st.Space);\n\t cent = is(1:3,1:3)*st.centre(:) + is(1:3,4);\n\t polyoff = [0 0 0];\n\t switch axhandle\n\t\t case 1,\n\t\t M0 = [ 1 0 0 -st.bb(1,1)+1\n\t\t\t 0 1 0 -st.bb(1,2)+1\n\t\t\t 0 0 1 -cent(3)\n\t\t\t 0 0 0 1];\n\t\t polyoff(3) = st.vols{volhandle}.roi.polyslices/2;\n\t\t polythick = prms(9);\n\t\t case 2,\n\t\t M0 = [ 1 0 0 -st.bb(1,1)+1\n\t\t\t 0 0 1 -st.bb(1,3)+1\n\t\t\t 0 1 0 -cent(2)\n\t\t\t 0 0 0 1];\n\t\t polyoff(2) = st.vols{volhandle}.roi.polyslices/2;\n\t\t polythick = prms(8);\n\t\t case 3,\n\t\t if st.mode ==0,\n\t\t\t M0 = [ 0 0 1 -st.bb(1,3)+1\n\t\t\t\t 0 1 0 -st.bb(1,2)+1\n\t\t\t\t 1 0 0 -cent(1)\n\t\t\t\t 0 0 0 1];\n\t\t else,\n\t\t\t M0 = [ 0 -1 0 +st.bb(2,2)+1\n\t\t\t\t 0 0 1 -st.bb(1,3)+1\n\t\t\t\t 1 0 0 -cent(1)\n\t\t\t\t 0 0 0 1];\n\t\t end;\n\t\t polyoff(1) = st.vols{volhandle}.roi.polyslices/2;\n\t\t polythick = abs(prms(7));\n\t end;\n\t polvx = inv(st.vols{volhandle}.roi.Vroi.mat)*st.Space*inv(M0)*...\n\t\t [x(:)';y(:)'; zeros(size(x(:)')); ones(size(x(:)'))];\n\t % Bounding volume for polygon in ROI voxel space\n\t [xbox ybox zbox] = ndgrid(max(min(floor(polvx(1,:)-polyoff(1))),1):...\n\t\t\t\t\tmin(max(ceil(polvx(1,:)+polyoff(1))),...\n\t\t\t\t\t st.vols{volhandle}.roi.Vroi.dim(1)),...\n\t\t\t\t\tmax(min(floor(polvx(2,:)-polyoff(2))),1):...\n\t\t\t\t\tmin(max(ceil(polvx(2,:)+polyoff(2))),...\n\t\t\t\t\t st.vols{volhandle}.roi.Vroi.dim(2)),...\n\t\t\t\t\tmax(min(floor(polvx(3,:)-polyoff(3))),1):...\n\t\t\t\t\tmin(max(ceil(polvx(3,:)+polyoff(3))),...\n\t\t\t\t\t st.vols{volhandle}.roi.Vroi.dim(3)));\n\t % re-transform in polygon plane\n\t xyzbox = M0*is*st.vols{volhandle}.roi.Vroi.mat*[xbox(:)';ybox(:)';zbox(:)';...\n\t\t ones(size(xbox(:)'))];\n\t xyzbox = xyzbox(:,abs(xyzbox(3,:))<=.6*polythick*...\n\t\t\t st.vols{volhandle}.roi.polyslices); % nearest neighbour to polygon\n\t sel = logical(inpolygon(xyzbox(1,:),xyzbox(2,:),x,y));\n\t xyz = inv(st.vols{volhandle}.roi.Vroi.mat)*st.Space*inv(M0)*xyzbox(:,sel);\n\t if ~isempty(xyz)\n\t\t tochange = round(xyz(1:3,:));\n\t\t update_roi = 1;\n\t end;\n\t end;\n\t set(st.vols{volhandle}.ax{axhandle}.ax,...\n\t 'Selected','off', 'XLimMode',XLimMode, 'YLimMode',YLimMode,...\n\t 'ButtonDownFcn',ButtonDownFcn, 'UIContextMenu',UIContextMenu);\n end;\n case 'thresh'\n spm('pointer','watch');\n rind = find(st.vols{volhandle}.roi.roi);\n [x y z]=ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),rind);\n tmp = round(inv(st.vols{volhandle}.mat) * ...\n\t st.vols{volhandle}.roi.Vroi.mat*[x'; y'; z'; ones(size(x'))]); \n dat = spm_sample_vol(st.vols{volhandle}, ...\n\t\t tmp(1,:), tmp(2,:), tmp(3,:), 0);\n sel = ~((st.vols{volhandle}.roi.thresh(1) < dat) & ...\n\t (dat < st.vols{volhandle}.roi.thresh(2)));\n if strcmp(st.vols{volhandle}.roi.mode,'set')\n toclear = [x(sel)'; y(sel)'; z(sel)'];\n else\n toset = [x(sel)'; y(sel)'; z(sel)'];\n toclear = st.vols{volhandle}.roi.xyz;\n end;\n update_roi = 1;\n \ncase 'erodilate'\n spm('pointer','watch');\n V = zeros(size(st.vols{volhandle}.roi.roi));\n spm_smooth(double(st.vols{volhandle}.roi.roi), V, 2);\n [ero(1,:) ero(2,:) ero(3,:)] = ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),...\n find(V(:)>st.vols{volhandle}.roi.erothresh));\n if strcmp(st.vols{volhandle}.roi.mode,'set')\n toset = ero;\n toclear = st.vols{volhandle}.roi.xyz;\n else\n toclear = ero;\n end;\n update_roi = 1;\n \ncase {'connect', 'cleanup'}\n spm('pointer','watch'); \n [V L] = spm_bwlabel(double(st.vols{volhandle}.roi.roi),6);\n sel = [];\n switch cmd\n case 'connect'\n pos = round(inv(st.vols{volhandle}.roi.Vroi.mat)* ...\n [spm_orthviews('pos'); 1]); \n sel = V(pos(1),pos(2),pos(3));\n if sel == 0\n sel = [];\n end;\n case 'cleanup'\n for k = 1:L\n numV(k) = sum(V(:)==k);\n end;\n sel = find(numV>st.vols{volhandle}.roi.csize);\n end;\n if ~isempty(sel)\n ind = [];\n for k=1:numel(sel)\n ind = [ind; find(V(:) == sel(k))];\n end;\n\tconn = zeros(3,numel(ind));\n [conn(1,:) conn(2,:) conn(3,:)] = ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),ind);\n\n if strcmp(st.vols{volhandle}.roi.mode,'set')\n toset = conn;\n toclear = st.vols{volhandle}.roi.xyz;\n else\n toclear = conn;\n end;\n end;\n update_roi = 1;\n \n case 'invert'\n spm('pointer','watch');\n toclear = st.vols{volhandle}.roi.xyz;\n [x y z] = ndgrid(1:st.vols{volhandle}.roi.Vroi.dim(1),...\n\t\t 1:st.vols{volhandle}.roi.Vroi.dim(2),...\n\t\t 1:st.vols{volhandle}.roi.Vroi.dim(3));\n if ~isempty(toclear)\n toset = setdiff([x(:)'; y(:)'; z(:)']', toclear', 'rows')';\n else\n toset = [x(:)'; y(:)'; z(:)'];\n end;\n update_roi = 1;\n clear x y z;\n \n case 'clear'\n spm('pointer','watch');\n st.vols{volhandle}.roi.roi = zeros(size(st.vols{volhandle}.roi.roi));\n st.vols{volhandle}.roi.xyz=[];\n update_roi = 1;\n \ncase 'addfile'\n V = spm_vol(spm_select([1 Inf],'image','Image(s) to add'));\n [x y z] = ndgrid(1:st.vols{volhandle}.roi.Vroi.dim(1),...\n 1:st.vols{volhandle}.roi.Vroi.dim(2),...\n 1:st.vols{volhandle}.roi.Vroi.dim(3));\n xyzmm = st.vols{volhandle}.roi.Vroi.mat*[x(:)';y(:)';z(:)'; ...\n ones(1, prod(st.vols{volhandle}.roi.Vroi.dim(1:3)))];\n msk = zeros(1,prod(st.vols{volhandle}.roi.Vroi.dim(1:3)));\n for k = 1:numel(V)\n xyzvx = inv(V(k).mat)*xyzmm;\n msk = msk | spm_sample_vol(V(k), xyzvx(1,:), xyzvx(2,:), xyzvx(3,:), 0);\n end;\n [tochange(1,:) tochange(2,:) tochange(3,:)] = ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),find(msk));\n clear xyzmm xyzvx msk\n update_roi = 1;\n \ncase {'save','saveas'}\n if strcmp(cmd,'saveas') | ...\n exist(st.vols{volhandle}.roi.Vroi.fname)==7\n flt = {'*.nii','NIfTI (1 file)';'*.img','NIfTI (2 files)'};\n [name pth idx] = uiputfile(flt, 'Output image');\n if ~ischar(pth)\n warning('Save cancelled');\n return;\n end;\n [p n e v] = spm_fileparts(fullfile(pth,name));\n if isempty(e)\n\t e = flt{idx,1}(2:end);\n end;\n st.vols{volhandle}.roi.Vroi.fname = fullfile(p, [n e v]);\n end;\n spm('pointer','watch');\n spm_write_vol(st.vols{volhandle}.roi.Vroi, ...\n\t\tst.vols{volhandle}.roi.roi);\n spm('pointer','arrow');\n return;\n \n case 'redraw'\n % do nothing\n return;\n \n %-------------------------------------------------------------------------\n % Context menu and callbacks\n case 'context_menu' \n item0 = uimenu(varargin{3}, 'Label', 'ROI tool');\n item1 = uimenu(item0, 'Label', 'Launch', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_init'', ', ...\n\t num2str(volhandle), ');'], 'Tag', ['ROI_0_', num2str(volhandle)]);\n item2 = uimenu(item0, 'Label', 'Selection mode', ...\n\t 'Visible', 'off', 'Tag', ['ROI_1_', num2str(volhandle)]);\n item2_1a = uimenu(item2, 'Label', 'Set selection', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_selection'',', ...\n\t num2str(volhandle), ',''set'');'], ...\n\t 'Tag', ['ROI_SELECTION_', num2str(volhandle)], 'Checked','on');\n item2_1b = uimenu(item2, 'Label', 'Clear selection', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_selection'',', ...\n\t num2str(volhandle), ',''clear'');'], ...\n\t 'Tag', ['ROI_SELECTION_', num2str(volhandle)]);\n item3 = uimenu(item0, 'Label', 'Box size', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_box'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item4 = uimenu(item0, 'Label', 'Polygon slices', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_polyslices'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item5 = uimenu(item0, 'Label', 'Cluster size', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_csize'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item6 = uimenu(item0, 'Label', 'Erosion/Dilation threshold', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_erothresh'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item7 = uimenu(item0, 'Label', 'Edit tool', ...\n\t\t 'Visible', 'off', 'Tag', ['ROI_1_', num2str(volhandle)],...\n 'Separator','on');\n item7_1a = uimenu(item7, 'Label', 'Box tool', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_edit'',', ...\n\t num2str(volhandle), ',''box'');'], ...\n\t 'Tag', ['ROI_EDIT_', num2str(volhandle)], 'Checked','on');\n item7_1b = uimenu(item7, 'Label', 'Polygon tool', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_edit'',', ...\n\t num2str(volhandle), ',''poly'');'], ...\n\t 'Tag', ['ROI_EDIT_', num2str(volhandle)]);\n item8 = uimenu(item0, 'Label', 'Threshold', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_thresh'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item9 = uimenu(item0, 'Label', 'Connected cluster', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''connect'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item10 = uimenu(item0, 'Label', 'Cleanup clusters', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''cleanup'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item11 = uimenu(item0, 'Label', 'Erode/Dilate', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''erodilate'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item12 = uimenu(item0, 'Label', 'Invert', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''invert'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item13 = uimenu(item0, 'Label', 'Clear', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''clear'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item14 = uimenu(item0, 'Label', 'Add ROI from file(s)', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''addfile'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item15 = uimenu(item0, 'Label', 'Save', 'Callback', ...\n ['feval(''spm_ov_roi'',''save'', ', ...\n num2str(volhandle), ');'], 'Visible', 'off', ...\n 'Tag', ['ROI_1_', num2str(volhandle)],...\n 'Separator','on');\n item16 = uimenu(item0, 'Label', 'Save As', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''saveas'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item17 = uimenu(item0, 'Label', 'Quit', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_quit'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n item18 = uimenu(item0, 'Label', 'Help', 'Callback', ...\n\t ['feval(''spm_help'',''' mfilename ''');']);\n % add some stuff outside ROI tool menu\n iorient = findobj(st.vols{volhandle}.ax{1}.cm, 'Label', 'Orientation');\n item19 = uimenu(iorient, 'Label', 'ROI Space', 'Callback', ...\n\t ['feval(''spm_ov_roi'',''context_space'', ', ...\n\t num2str(volhandle), ');'], 'Visible', 'off', ...\n\t 'Tag', ['ROI_1_', num2str(volhandle)]);\n return;\n \n case 'context_init'\n Finter = spm_figure('FindWin', 'Interactive');\n spm_input('!DeleteInputObj',Finter);\n loadasroi = spm_input('Initial ROI','!+1','m',{'ROI image',...\n\t\t 'ROI space definition', 'SPM result'},[1 0 2],1);\n xyz = [];\n switch loadasroi\n case 1,\n imfname = spm_select(1, 'image', 'Select ROI image');\n case 0,\n imfname = spm_select(1, 'image', 'Select image defining ROI space');\n [p n e v] = fileparts(imfname);\n case 2,\n [SPM, xSPM] = spm_getSPM;\n xyz = xSPM.XYZ;\n imfname = SPM.Vbeta(1).fname;\n end;\n feval('spm_ov_roi','init',volhandle,imfname,loadasroi,xyz);\n obj = findobj(0, 'Tag', ['ROI_1_', num2str(volhandle)]);\n set(obj, 'Visible', 'on');\n obj = findobj(0, 'Tag', ['ROI_0_', num2str(volhandle)]);\n set(obj, 'Visible', 'off');\n spm_input('!DeleteInputObj',Finter);\n return;\n \n case 'context_selection'\n st.vols{volhandle}.roi.mode = varargin{3};\n obj = findobj(0, 'Tag', ['ROI_SELECTION_', num2str(volhandle)]);\n set(obj, 'Checked', 'off');\n set(gcbo, 'Checked', 'on');\n return;\n \n case 'context_edit'\n st.vols{volhandle}.roi.tool = varargin{3};\n obj = findobj(0, 'Tag', ['ROI_EDIT_', num2str(volhandle)]);\n set(obj, 'Checked', 'off');\n set(gcbo, 'Checked', 'on');\n return;\n \n case 'context_box'\n Finter = spm_figure('FindWin', 'Interactive');\n spm_input('!DeleteInputObj',Finter);\n box = spm_input('Selection size {vx vy vz}','!+1','e', ...\n\t\t num2str(st.vols{volhandle}.roi.box), [1 3]);\n spm_input('!DeleteInputObj',Finter);\n st.vols{volhandle}.roi.box = box;\n return;\n \n case 'context_polyslices'\n Finter = spm_figure('FindWin', 'Interactive');\n spm_input('!DeleteInputObj',Finter);\n polyslices = spm_input('Polygon: slices around current slice','!+1','e', ...\n\t\t num2str(st.vols{volhandle}.roi.polyslices), [1 1]);\n spm_input('!DeleteInputObj',Finter);\n st.vols{volhandle}.roi.polyslices = polyslices;\n return;\n \ncase 'context_csize'\n Finter = spm_figure('FindWin', 'Interactive');\n spm_input('!DeleteInputObj',Finter);\n csize = spm_input('Minimum cluster size (#vx)','!+1','e', ...\n\t\t num2str(st.vols{volhandle}.roi.csize), [1 1]);\n spm_input('!DeleteInputObj',Finter);\n st.vols{volhandle}.roi.csize = csize;\n return;\n\ncase 'context_erothresh'\n Finter = spm_figure('FindWin', 'Interactive');\n spm_input('!DeleteInputObj',Finter);\n erothresh = spm_input('Erosion/Dilation threshold','!+1','e', ...\n\t\t num2str(st.vols{volhandle}.roi.erothresh), [1 1]);\n spm_input('!DeleteInputObj',Finter);\n st.vols{volhandle}.roi.erothresh = erothresh;\n return;\n\n case 'context_space'\n\tspm_orthviews('space', volhandle, ...\n\t\t st.vols{volhandle}.roi.Vroi.mat, ...\n\t\t st.vols{volhandle}.roi.Vroi.dim(1:3));\n\tiorient = get(findobj(0,'Label','Orientation'),'children');\n\tif iscell(iorient)\n\t iorient = cell2mat(iorient);\n\tend;\n\tset(iorient, 'Checked', 'Off');\n\tioroi = findobj(iorient, 'Label','ROI space');\n\tset(ioroi, 'Checked', 'On');\n\treturn;\n\t\n case 'context_thresh'\n Finter = spm_figure('FindWin', 'Interactive');\n spm_input('!DeleteInputObj',Finter);\n thresh = spm_input('Threshold {min max}','!+1','e', ...\n\tnum2str(st.vols{volhandle}.roi.thresh), [1 2]);\n spm_input('!DeleteInputObj',Finter);\n st.vols{volhandle}.roi.thresh = thresh;\n feval('spm_ov_roi', 'thresh', volhandle);\n return;\n \n case 'context_quit'\n obj = findobj(0, 'Tag', ['ROI_1_', num2str(volhandle)]);\n set(obj, 'Visible', 'off');\n obj = findobj(0, 'Tag', ['ROI_0_', num2str(volhandle)]);\n set(obj, 'Visible', 'on');\n spm_orthviews('rmblobs', volhandle);\n for k=1:3\n set(st.vols{volhandle}.ax{k}.ax,'ButtonDownFcn', st.vols{volhandle}.roi.cb{k});\n end;\n st.vols{volhandle} = rmfield(st.vols{volhandle}, 'roi');\n spm_orthviews('redraw');\n return;\n \n otherwise \n fprintf('spm_orthviews(''roi'', ...): Unknown action %s', cmd);\n return;\nend;\n\nif update_roi\n if ~isempty(tochange) % change state according to mode\n if strcmp(st.vols{volhandle}.roi.mode,'set')\n toset = tochange;\n else\n toclear = tochange;\n end;\n end;\n % clear first, then set (needed for connect operation)\n if ~isempty(toclear)\n itoclear = sub2ind(st.vols{volhandle}.roi.Vroi.dim(1:3), ...\n\t toclear(1,:), toclear(2,:), toclear(3,:)); \n st.vols{volhandle}.roi.roi(itoclear) = 0;\n if ~isempty(st.vols{volhandle}.roi.xyz)\n st.vols{volhandle}.roi.xyz = setdiff(st.vols{volhandle}.roi.xyz',toclear','rows')';\n else\n st.vols{volhandle}.roi.xyz = [];\n end;\n end;\n\n if ~isempty(toset)\n % why do we need this round()?? I don't know, but Matlab thinks\n % it is necessary\n itoset = round(sub2ind(st.vols{volhandle}.roi.Vroi.dim(1:3), ...\n toset(1,:), toset(2,:), toset(3,:))); \n st.vols{volhandle}.roi.roi(itoset) = 1;\n if ~isempty(st.vols{volhandle}.roi.xyz)\n st.vols{volhandle}.roi.xyz = union(st.vols{volhandle}.roi.xyz',toset','rows')';\n else\n st.vols{volhandle}.roi.xyz = toset;\n end;\n end;\n\n if isfield(st.vols{volhandle}, 'blobs')\n nblobs=length(st.vols{volhandle}.blobs);\n if nblobs>1\n blobstmp(1:st.vols{volhandle}.roi.hroi-1) = st.vols{volhandle}.blobs(1:st.vols{volhandle}.roi.hroi-1);\n blobstmp(st.vols{volhandle}.roi.hroi:nblobs-1) = st.vols{volhandle}.blobs(st.vols{volhandle}.roi.hroi+1:nblobs);\n st.vols{volhandle}.blobs=blobstmp;\n else\n if isempty(st.vols{volhandle}.roi.hframe) % save frame\n\tst.vols{volhandle}=rmfield(st.vols{volhandle},'blobs');\n end;\n end;\n end;\n if isfield(st.vols{volhandle}, 'blobs')\n st.vols{volhandle}.roi.hroi = prod(size(st.vols{volhandle}.blobs))+1;\n else\n st.vols{volhandle}.roi.hroi = 1;\n end;\n if isempty(st.vols{volhandle}.roi.xyz) % initialised with empty roi\n spm_orthviews('addcolouredblobs', volhandle, ...\n [1; 1; 1], 0, st.vols{volhandle}.roi.Vroi.mat,[1 3 1]); \n else\n spm_orthviews('addcolouredblobs', volhandle, ...\n st.vols{volhandle}.roi.xyz, ones(size(st.vols{volhandle}.roi.xyz,2),1), ... \n st.vols{volhandle}.roi.Vroi.mat,[1 3 1]); % use color that is more intense than standard rgb range\n end;\n st.vols{volhandle}.blobs{st.vols{volhandle}.roi.hroi}.max=2;\n spm_orthviews('redraw');\nend;\n\nspm('pointer','arrow');\n\n\nfunction varargout = stack(cmd, varargin)\n\nswitch cmd\n case 'init'\n varargout{1}.st = cell(varargin{1},1);\n varargout{1}.top= 0;\n\n case 'isempty'\n varargout{1} = (varargin{1}.top==0);\n\n case 'push'\n stck = varargin{1};\n if (stck.top < size(stck.st,1))\n stck.top = stck.top + 1;\n stck.st{stck.top} = varargin{2};\n varargout{1}=stck;\n else\n error('Stack overflow\\n');\n end;\n\n case 'pop'\n if stack('isempty',varargin{1})\n error('Stack underflow\\n');\n else\n varargout{2} = varargin{1}.st{varargin{1}.top};\n varargin{1}.top = varargin{1}.top - 1;\n varargout{1} = varargin{1};\n end;\nend;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_3Dto4D.m", "ext": ".m", "path": "spm5-master/toolbox/spm_config_3Dto4D.m", "size": 1523, "source_encoding": "utf_8", "md5": "c5d8981c24f5a268e730a354d1c1658d", "text": "function c = spm_config_3Dto4D(varargin)\n% Configuration file for concatenation jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_3Dto4D.m 946 2007-10-15 16:36:06Z john $\n\nvols.type = 'files';\nvols.name = '3D Volumes';\nvols.tag = 'vols';\nvols.num = [1 Inf];\nvols.filter = 'image';\nvols.help = {'Select the volumes to concatenate'};\n\nc.type = 'branch';\nc.name = '3D to 4D';\nc.tag = 'cat';\nc.val = {vols};\nc.prog = @spm_3Dto4D;\nc.help = {'Concatenate a number of 3D volumes into a single 4D file.',...\n'Note that output time series are stored as big-endian int16.'};\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction spm_3Dto4D(job)\n\nV = spm_vol(strvcat(job.vols{:}));\nind = cat(1,V.n);\nN = cat(1,V.private);\n\nmx = -Inf;\nmn = Inf;\nfor i=1:numel(V),\n dat = V(i).private.dat(:,:,:,ind(i,1),ind(i,2));\n dat = dat(isfinite(dat));\n mx = max(mx,max(dat(:)));\n mn = min(mn,min(dat(:)));\nend;\n\nsf = max(mx,-mn)/32767;\nni = nifti;\nni.dat = file_array('4D.nii',[V(1).dim numel(V)],'INT16-BE',0,sf,0);\nni.mat = N(1).mat;\nni.mat0 = N(1).mat;\nni.descrip = '4D image';\ncreate(ni);\nfor i=1:size(ni.dat,4),\n ni.dat(:,:,:,i) = N(i).dat(:,:,:,ind(i,1),ind(i,2));\n spm_get_space([ni.dat.fname ',' num2str(i)], V(i).mat);\nend;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_segment_old.m", "ext": ".m", "path": "spm5-master/toolbox/spm_config_segment_old.m", "size": 16323, "source_encoding": "utf_8", "md5": "22130641d1f2170a0451396959a3254c", "text": "function opts = spm_config_segment_old\n% Configuration file for segment jobs\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_segment_old.m 184 2005-05-31 13:23:32Z john $\n\n%_______________________________________________________________________\n\nscans.type = 'files';\nscans.tag = 'scans';\nscans.tag = 'multispec';\nscans.name = 'Subject';\np1 = [...\n'If more than one volume is specified (eg T1 & T2), then they must be ',...\n'in register (same position, size, voxel dims etc..).'];\nscans.help = {'Select scans for this subject.',p1};\nscans.filter = 'image';\nscans.num = [1 Inf];\n\n%------------------------------------------------------------------------\n\nscans2.type = 'repeat';\nscans2.name = 'Multi-spectral images';\nscans2.values = {scans};\nscans2.help = {...\n'Multispectral tissue classification'};\n\n%------------------------------------------------------------------------\n\nscans.type = 'files';\nscans.tag = 'scans';\nscans.tag = 'singlespec';\nscans.name = 'Single-channel images';\nscans.help = {...\n'Select scans for classification. ',...\n'This assumes that there is one scan for each subject'};\nscans.filter = 'image';\nscans.num = [1 Inf];\n\n%------------------------------------------------------------------------\n\ndata = struct('type','choice','name','Data','tag','data','values',{{scans,scans2}});\ndata.help = {[...\n'Classification can be done on either a single image for each subject ',...\n'(single channel) or can be based on two or more registered images ',...\n'(multispectral).']};\n\n%------------------------------------------------------------------------\n\ntemplate.type = 'files';\ntemplate.tag = 'template';\ntemplate.name = 'Template image(s)';\ntemplate.num = [1 5];\ntemplate.filter = 'image';\ntemplate.val = {{fullfile(spm('Dir'),'templates','T1.nii')}};\ntemplate.help = {[...\n'Select one or more template images, which will be used for affine matching. ',...\n'Matching involves minimising the mean squared difference between the image and ',...\n'template, so the tamplate should have the same contrast, or be of the same ',...\n'modality as the image you want to register with it. ',...\n'Note that for multi-spectral classification, the affine transform is only ',...\n'determined from the first image specified for each subject.']};\n\n%------------------------------------------------------------------------\n\nregtype.type = 'menu';\nregtype.name = 'Regularisation';\nregtype.tag = 'regtype';\nregtype.labels = {'ICBM space template', 'Average sized template','No regularisation'};\nregtype.values = {'mni','subj','none'};\nregtype.def = 'segment.estimate.affreg.regtype';\nregtype.help = {[...\n'Affine registration into a standard space can be made more robust by ',...\n'regularisation (penalising excessive stretching or shrinking). The ',...\n'best solutions can be obtained by knowing the approximate amount of ',...\n'stretching that is needed (e.g. ICBM templates are slightly bigger ',...\n'than typical brains, so greater zooms are likely to be needed). ',...\n'If registering to an image in ICBM/MNI space, then choose the first ',...\n'option. If registering to a template that is close in size, then ',...\n'select the second option. If you do not want to regularise, then ',...\n'choose the third.']};\n\n%------------------------------------------------------------------------\n\nweight.type = 'files';\nweight.name = 'Weighting image';\nweight.tag = 'weight';\nweight.filter = 'image';\nweight.num = [0 1];\nweight.def = 'segment.estimate.affreg.weight';\nweight.help = {[...\n'The affine registration can be weighted by an image that conforms to ',...\n'the same space as the template image. If an image is selected, then ',...\n'it must match the template(s) voxel-for voxel, and have the same ',...\n'voxel-to-world mapping.']};\n\n%------------------------------------------------------------------------\n\nsmosrc.type = 'entry';\nsmosrc.name = 'Smoothing FWHM (mm)';\nsmosrc.tag = 'smosrc';\nsmosrc.strtype = 'e';\nsmosrc.num = [1 1];\nsmosrc.def = 'segment.estimate.affreg.smosrc';\nsmosrc.help = {[...\n'This is the full width at half maximum (FWHM - in mm) of the Gaussian ',...\n'smoothing kernel applied to the source image before doing the affine ',...\n'registration. Templates released with SPM are usually smoothed by 8mm ',...\n'so 8mm would normally be the best value to use.']};\n\n%------------------------------------------------------------------------\n\naffreg.type = 'branch';\naffreg.name = 'Affine register';\naffreg.tag = 'affreg';\naffreg.val = {template,weight,regtype,smosrc};\naffreg.help = {'An affine registration needs to be done for non spatially normalised images.'};\n\n%------------------------------------------------------------------------\n\nunnecessary.type = 'const';\nunnecessary.tag = 'unnecessary';\nunnecessary.val = {[]};\nunnecessary.name = 'Already spatially normalised';\nunnecessary.help = {[...\n'If the data are already spatially normalised, then no affine registration ',...\n'is needed in order to overlay the prior probability images.']};\n\n%------------------------------------------------------------------------\n \n%affreg1.type = 'menu';\n%affreg1.tag = 'template';\n%affreg1.name = 'Predefined template';\n%affreg1.labels = {'Register T1 MRI ',...\n%'Register T2 MRI','Register PD MRI','Register EPI MR'};\n%affreg1.values = {...\n%fullfile(spm('Dir'),'templates ', T1.nii'),...\n%fullfile(spm('Dir'),'templates ', T2.nii'),...\n%fullfile(spm('Dir'),'templates ', PD.nii'),...\n%fullfile(spm('Dir'),'templates','EPI.nii')};\n%affreg1.help = {...\n%'Select one of the template images, which will be used for affine matching. ',...\n%'Note that for multi-spectral classification, the affine transform is only ',...\n%'determined from the first image specified for each subject.'};\n\n%------------------------------------------------------------------------\n \noverlay.type = 'choice';\noverlay.tag = 'overlay';\noverlay.name = 'Prior overlay';\noverlay.values = {unnecessary,affreg};\noverlay.help = {'How should the priors be overlayed over the image to segment.'};\n\n%------------------------------------------------------------------------\n\npriors.type = 'files';\npriors.name = 'Prior probability maps';\npriors.tag = 'priors';\npriors.filter = 'image';\npriors.num = 3;\npriors.def = 'segment.estimate.priors';\npriors.help = {[...\n'Prior probability images that are overlayed on the images to segment. ',...\n'These should be prior probability maps of grey matter, white matter ',...\n'and cerebro-spinal fluid.']};\n\n%------------------------------------------------------------------------\n\nsamp.type = 'entry';\nsamp.name = 'Sampling distance';\nsamp.tag = 'samp';\nsamp.num = [1 1];\nsamp.strtype = 'e';\nsamp.def = 'segment.estimate.samp';\nsamp.help = {[...\n'The approximate distance between sampled points when estimating the ',...\n'segmentation parameters.']};\n\n%------------------------------------------------------------------------\n\nbb.type = 'entry';\nbb.name = 'Bounding box';\nbb.tag = 'bb';\nbb.num = [2 3];\nbb.strtype = 'e';\nbb.def = 'segment.estimate.bb';\nbb.help = {[...\n'Bounding box defining the region in which the segmentation parameters ',...\n'are estimated']};\n\n%------------------------------------------------------------------------\n\ncustom.type = 'branch';\ncustom.name = 'Custom';\ncustom.tag = 'custom';\ncustom.val = {priors,bb,samp};\ncustom.help = {'Tweekable things'};\n\n%------------------------------------------------------------------------\n\nreg.tag = 'reg';\nreg.type = 'menu';\nreg.name = 'Bias regularisation';\nreg.help = {[...\n'The importance of smoothness for the estimated bias field. Without ',...\n'any regularisation, the algorithm will attempt to correct for ',...\n'different grey levels arising from different tissue types, rather than ',...\n'just correcting bias artifact. ',...\n'Bias correction uses a Bayesian framework (again) to model intensity ',...\n'inhomogeneities in the image(s). The variance associated with each ',...\n'tissue class is assumed to be multiplicative (with the ',...\n'inhomogeneities). The low frequency intensity variability is ',...\n'modelled by a linear combination of three dimensional DCT basis ',...\n'functions (again), using a fast algorithm (again) to generate the ',...\n'curvature matrix. The regularization is based upon minimizing the ',...\n'integral of square of the fourth derivatives of the modulation field ',...\n'(the integral of the squares of the first and second derivs give the ',...\n'membrane and bending energies respectively).']};\nreg.labels = {'no regularisation (0) ','extremely light regularisation (0.00001)',...\n'very light regularisation (0.0001) ','light regularisation (0.001)',...\n'medium regularisation (0.01) ','heavy regularisation (0.1)',...\n'very heavy regularisation (1)','extremely heavy regularisation (10)'};\nreg.values = {0, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1.0, 10};\nreg.def = 'segment.estimate.reg';\n\n%------------------------------------------------------------------------\n\ncutoff.tag = 'cutoff';\ncutoff.type = 'menu';\ncutoff.name = 'Bias cutoff';\ncutoff.help = {[...\n'Cutoff of DCT bases. Only DCT bases of periods longer than the ',...\n'cutoff are used to describe the bias. The number used will ',...\n'depend on the cutoff and the field of view of the image.']};\ncutoff.labels = {'20mm cutoff','25mm cutoff','30mm cutoff','35mm cutoff',...\n'40mm cutoff','45mm cutoff','50mm cutoff','60mm cutoff','70mm cutoff',...\n'80mm cutoff','90mm cutoff','100mm cutoff','No correction'};\ncutoff.values = {20,25,30,35,40,45,50,60,70,80,90,100,Inf};\ncutoff.def = 'segment.estimate.cutoff';\n\n%------------------------------------------------------------------------\n\ncleanup.tag = 'cleanup';\ncleanup.type = 'menu';\ncleanup.name = 'Clean up the partitions';\ncleanup.help = {[...\n'This uses a crude routine for extracting the brain from segmented ',...\n'images. It begins by taking the white matter, and eroding it a ',...\n'couple of times to get rid of any odd voxels. The algorithm ',...\n'continues on to do conditional dilations for several iterations, ',...\n'where the condition is based upon grey or white matter being present. ',...\n'This identified region is then used to clean up the grey and white ',...\n'matter partitions, and has a slight influences on the CSF partition.']};\ncleanup.labels = {'Clean up the partitions','Dont do cleanup'};\ncleanup.values = {1 0};\ncleanup.def = 'segment.write.cleanup';\n\n%------------------------------------------------------------------------\n\nwrt_cor.tag = 'wrt_cor';\nwrt_cor.type = 'menu';\nwrt_cor.name = 'Write bias correted image';\nwrt_cor.help = {'Write bias correted versions of the images to disk'};\nwrt_cor.labels = {'Write bias corrected','Dont write bias corrected'};\nwrt_cor.values = {1 0};\nwrt_cor.def = 'segment.write.wrt_cor';\n\n%------------------------------------------------------------------------\n\nbias = struct('type','branch','name','Bias correction','tag','bias',...\n 'dim', Inf ,'val',{{reg,cutoff,wrt_cor}});\nbias.help = {[...\n'This uses a Bayesian framework (again) to model intensity ',...\n' inhomogeneities in the image(s). The variance associated with each ',...\n' tissue class is assumed to be multiplicative (with the ',...\n' inhomogeneities). The low frequency intensity variability is ',...\n' modelled by a linear combination of three dimensional DCT basis ',...\n' functions (again), using a fast algorithm (again) to generate the ',...\n' curvature matrix. The regularization is based upon minimizing the ',...\n' integral of square of the fourth derivatives of the modulation field ',...\n' (the integral of the squares of the first and second derivs give the ',...\n' membrane and bending energies respectively).']};\n\n%------------------------------------------------------------------------\n\nopts.type = 'branch';\nopts.tag = 'oldsegment';\nopts.name = 'Old Segment';\nopts.prog = @execute;\nopts.vfiles = @vfiles;\nopts.dim = Inf;\nopts.val = {data,overlay,bias,custom,cleanup};\nopts.help = {...\n'Segment an MR image into Grey, White & CSF.',...\n'',...\n'The algorithm is four step:',...\n[...\n'1) Determine the affine transform which best matches the image with a ',...\n' template image. If the name of more than one image is passed, then ',...\n' the first image is used in this step. This step is not performed if ',...\n' no template images are specified.'],...\n[...\n'2) Perform Cluster Analysis with a modified Mixture Model and a-priori ',...\n' information about the likelihoods of each voxel being one of a ',...\n' number of different tissue types. If more than one image is passed, ',...\n' then they they are all assumed to be in register, and the voxel ',...\n' values are fitted to multi-normal distributions.'],...\n[...\n'3) Do a \"cleanup\" of the partitions, analagous to what ',...\n' followed by with \"i1.*i4./(i1+i2+i3+eps)\" did with SPM99.'],... \n[...\n'4) Write the segmented image. The names of these images have ',...\n' \"c1\", \"c2\" & \"c3\" prepended to the name of the ',...\n' first image passed.'],...\n'',...\n' _______________________________________________________________________ ',...\n' Refs: ',...\n'',...\n[' Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and ',...\n' Partitioning - a Unified Framework. NeuroImage 6:209-217'],...\n'',...\n[' Ashburner J & Friston KJ (2000) Voxel-Based Morphometry - The Methods. ',...\n' NeuroImage 11(6):805-821'],...\n'',...\n[' Ashburner J (2002) \"Another MRI Bias Correction Approach\" [abstract]. ',...\n' Presented at the 8th International Conference on Functional Mapping of ',...\n' the Human Brain, June 2-6, 2002, Sendai, Japan. Available on CD-Rom ',...\n' in NeuroImage, Vol. 16, No. 2.'],...\n'',...\n' _______________________________________________________________________ ',...\n};\n\nreturn;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction execute(varargin)\njob = varargin{1};\n\nflags.estimate.priors = strvcat(job.custom.priors);\nflags.estimate.reg = job.bias.reg;\nflags.estimate.cutoff = job.bias.cutoff;\nflags.estimate.samp = job.custom.samp;\nflags.estimate.bb = job.custom.bb;\nflags.write.cleanup = job.cleanup;\nflags.write.wrt_cor = job.bias.wrt_cor;\n\ndata = {{}};\nif isfield(job.data,'singlespec'),\n\tdata = {};\n\tsinglespec = job.data.singlespec;\n\tfor i=1:length(singlespec),\n\t\tdata = {data{:},deblank(singlespec{i})};\n\tend;\nelseif isfield(job.data,'multispec'),\n\tdata = {};\n\tfor i=1:length(job.data.multispec),\n\t\tdata = {data{:},strvcat(job.data.multispec{i})};\n\tend;\nend;\n\nif isfield(job.overlay,'unnecessary'),\n\tVG = eye(4);\nelse\n\tVG = spm_vol(strvcat(job.overlay.affreg.template));\n\tflags.estimate.affreg.smosrc = job.overlay.affreg.smosrc;\n\tflags.estimate.affreg.regtype = job.overlay.affreg.regtype;\n\tflags.estimate.affreg.weight = strvcat(job.overlay.affreg.weight);\nend;\n\nfor i=1:length(data),\n\tspm_segment(data{i},VG,flags);\nend;\n%------------------------------------------------------------------------\n\n%------------------------------------------------------------------------\nfunction vf = vfiles(varargin)\njob = varargin{1};\nvf = {};\n\nif job.bias.wrt_cor, n=4; else n=3; end;\nif isfield(job.data,'singlespec'),\n vf = cell(n,numel(job.data.singlespec));\n for i=1:numel(job.data.singlespec),\n [pth,nam,ext,num] = spm_fileparts(job.data.singlespec{i});\n sub = {...\n fullfile(pth,['c1', nam, ext, num]),...\n fullfile(pth,['c2', nam, ext, num]),...\n fullfile(pth,['c3', nam, ext, num]),...\n fullfile(pth,['m', nam, ext, num])};\n for j=1:n,\n vf{j,i} = sub{j};\n end;\n end;\nelseif isfield(job.data,'multispec'),\n vf = cell(n,numel(job.data.multispec));\n for i=1:numel(job.data.multispec),\n [pth,nam,ext,num] = spm_fileparts(job.data.multispec{i}{1});\n sub = {...\n fullfile(pth,['c1', nam, ext, num]),...\n fullfile(pth,['c2', nam, ext, num]),...\n fullfile(pth,['c3', nam, ext, num]),...\n fullfile(pth,['m', nam, ext, num])};\n for j=1:n,\n vf{j,i} = sub{j};\n end;\n end;\nend;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_sendmail.m", "ext": ".m", "path": "spm5-master/toolbox/spm_config_sendmail.m", "size": 3827, "source_encoding": "utf_8", "md5": "4f38b83b5b997bf9f13b735dd2b316d7", "text": "function c = spm_config_sendmail(varargin)\n% Configuration file for sending emails\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Guillaume Flandin\n% $Id: spm_config_sendmail.m 302 2005-11-16 21:42:45Z guillaume $\n\nto.type = 'entry';\nto.name = 'Recipient';\nto.tag = 'recipient';\nto.strtype = 's';\nto.num = [1 1];\nto.help = {'User to receive mail.'};\n\nsubject.type = 'entry';\nsubject.name = 'Subject';\nsubject.tag = 'subject';\nsubject.strtype = 's';\nsubject.num = [1 1];\nsubject.val = {['[SPM] [%DATE%] On behalf of ' spm('Ver')]};\nsubject.help = {['The subject line of the message. %DATE% will be ',...\n'replaced by a string containing the time and date when the email is sent.']};\n\nmessage.type = 'entry';\nmessage.name = 'Message';\nmessage.tag = 'message';\nmessage.strtype = 's';\nmessage.num = [1 1];\nmessage.val = {'Hello from SPM!'};\nmessage.help = {'A string containing the message to send.'};\n\nattachments.type = 'files';\nattachments.name = 'Attachments';\nattachments.tag = 'attachments';\nattachments.filter = '.*';\nattachments.num = [0 Inf];\nattachments.val = {{}};\nattachments.help = {'List of files to attach and send along with the message.'};\n\nsmtpserver.type = 'entry';\nsmtpserver.name = 'SMTP Server';\nsmtpserver.tag = 'smtp';\nsmtpserver.strtype = 's';\nsmtpserver.num = [1 1];\ntry\n\tsmtpserver.val = {getpref('Internet','SMTP_Server')};\nend\nsmtpserver.help = {'Your SMTP server. If not specified, look for sendmail help.'};\n\nemail.type = 'entry';\nemail.name = 'E-mail';\nemail.tag = 'email';\nemail.strtype = 's';\nemail.num = [1 1];\ntry\n\temail.val = {getpref('Internet','E_mail')};\nend\nemail.help = {'Your e-mail address. Look in sendmail help how to store it.'};\n\nzipattach.type = 'menu';\nzipattach.name = 'Zip attachments';\nzipattach.tag = 'zip';\nzipattach.labels = {'Yes' 'No'};\nzipattach.values = {'Yes' 'No'};\nzipattach.val = {'No'};\nzipattach.help = {'Zip attachments before being sent along with the message.'};\n\nparameters.type = 'branch';\nparameters.name = 'Parameters';\nparameters.tag = 'params';\nparameters.val = {smtpserver,email,zipattach};\nparameters.help = {['Preferences for your e-mail server (Internet SMTP ',...\n'server) and your e-mail address. MATLAB tries to read the SMTP mail ',...\n'server from your system registry. This should work flawlessly. If you '...\n'encounter any error, identify the outgoing mail server for your ',...\n'electronic mail application, which is usually listed in the ',...\n'application''s preferences, or, consult your e-mail system administrator, ',...\n'and update the parameters. Note that this function does not support ',... \n'e-mail servers that require authentication.']};\n\nc.type = 'branch';\nc.name = 'Sendmail';\nc.tag = 'sendmail';\nc.val = {to,subject,message,attachments,parameters};\nc.prog = @spm_sendmail;\nc.help = {['Send a mail message (attachments optionals) to an ',...\n'address.']};\n\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction spm_sendmail(job)\n\ntry\n\tsetpref('Internet','SMTP_Server',job.params.smtp);\n\tsetpref('Internet','E_mail',job.params.email);\n\n\tsubj = strrep(job.subject,'%DATE%',datestr(now));\n\tmesg = strrep(job.message,'%DATE%',datestr(now));\n\tmesg = [mesg 10 10 '-- ' 10 10 'Statistical Parametric Mapping']; \n\n\tif ~isempty(job.attachments)\n\t\tif strcmpi(job.params.zip,'Yes')\n\t\t\tzipfile = fullfile(tempdir,'spm_sendmail.zip');\n\t\t\tzip(zipfile,job.attachments);\n\t\t\tjob.attachments = {zipfile};\n\t\tend\n\t\tsendmail(job.recipient,subj,mesg,job.attachments);\n\telse\n\t\tsendmail(job.recipient,subj,mesg);\n\tend\ncatch\n\t%- not an error to prevent an analysis to crash because of just that...\n\tfprintf('Sendmail failed...\\n');\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_eeg_inv_ecd_DrawDip.m", "ext": ".m", "path": "spm5-master/toolbox/api_erp/spm_eeg_inv_ecd_DrawDip.m", "size": 19904, "source_encoding": "utf_8", "md5": "6c7ec83ef98b13ced7d98a3fc621b2ab", "text": "function varargout = spm_eeg_inv_ecd_DrawDip(action,varargin)\n\n%___________________________________________________________________\n%\n% spm_eeg_inv_ecd_DrawDip\n%\n% Function to display the dipoles as obtained from the optim routine.\n%\n% Use it with arguments or not:\n% - spm_eeg_inv_ecd_DrawDip('Init')\n% The routine asks for the dipoles file and image to display\n% - spm_eeg_inv_ecd_DrawDip('Init',sdip)\n% The routine will use the avg152T1 canonical image \n% - spm_eeg_inv_ecd_DrawDip('Init',sdip,P)\n% The routines dispays the dipoles on image P.\n%\n% If multiple seeds have been used, you can select the seeds to display \n% by pressing their index. \n% Given that the sources could have different locations, the slices\n% displayed will be the 3D view at the *average* or *mean* locations of\n% selected sources.\n% If more than 1 dipole was fitted at a time, then selection of source 1 \n% to N is possible through the pull-down selector.\n%\n% The location of the source/cut is displayed in mm and voxel, as well as\n% the underlying image intensity at that location.\n% The cross hair position can be hidden by clicking on its button.\n%\n% Nota_1: If the cross hair is manually moved by clicking in the image or\n% changing its coordinates, the dipole displayed will NOT be at\n% the right displayed location. That's something that needs to be improved...\n%\n% Nota_2: Some seeds may have not converged within the limits fixed,\n% these dipoles are not displayed...\n%\n% Fields needed in sdip structure to plot on an image:\n% + n_seeds: nr of seeds set used, i.e. nr of solutions calculated\n% + n_dip: nr of fitted dipoles on the EEG time series\n% + loc: location of fitted dipoles, cell{1,n_seeds}(3 x n_dip)\n% remember that loc is fixed over the time window.\n% + j: sources amplitude over the time window, \n% cell{1,n_seeds}(3*n_dip x Ntimebins)\n% + Mtb: index of maximum power in EEG time series used\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n% Christophe Phillips,\n% $Id: spm_eeg_inv_ecd_DrawDip.m 1040 2007-12-21 20:28:30Z karl $\n\nglobal st\nglobal defaults\n\nFig = spm_figure('FindWin');\ncolors = strvcat('y','b','g','r','c','m'); % 6 possible colors\nmarker = strvcat('o','x','+','*','s','d','v','p','h'); % 9 possible markers\nNcolors = length(colors);\nNmarker = length(marker);\n\nif nargin == 0, action = 'Init'; end;\n\nswitch lower(action),\n%________________________________________________________________________\ncase 'init'\n%------------------------------------------------------------------------\n% FORMAT spm_eeg_inv_ecd_DrawDip('Init',sdip,P)\n% Initialise the variables with GUI\n% e.g. spm_eeg_inv_ecd_DrawDip('Init')\n%------------------------------------------------------------------------\nspm('Clear')\n\nif nargin<2\n load(spm_select(1,'^.*S.*dip.*\\.mat$','Select dipole file'));\n if ~exist('sdip') & exist('result')\n sdip = result;\n end\nelse\n sdip = varargin{1};\nend\n\n% if the exit flag is not in the structure, assume everything went ok.\nif ~isfield(sdip,'exitflag')\n sdip.exitflag = ones(1,sdip.n_seeds);\nend\n\nPcanonical = fullfile(spm('dir'),'canonical','avg152T1.nii');\n\nif nargin<3\n\tif ~isstruct(st)\n% P = spm_select(1,'image','Image to display dipoles on');\n P = Pcanonical;\n\telseif isempty(st.vols{1})\n% P = spm_select(1,'image','Image to display dipoles on');\n P = Pcanonical;\n\tend\nelse\n P = varargin{2};\nend\nif ischar(P), P = spm_vol(P); end;\nspm_orthviews('Reset');\nspm_orthviews('Image', P, [0.0 0.45 1 0.55]);\nspm_orthviews('MaxBB');\nst.callback = 'spm_image(''shopos'');';\n\n\nWS = spm('WinScale');\n\n% Build GUI\n%=============================\n% Location:\n%-----------\nuicontrol(Fig,'Style','Frame','Position',[60 25 200 325].*WS,'DeleteFcn','spm_image(''reset'');');\nuicontrol(Fig,'Style','Frame','Position',[70 250 180 90].*WS);\nuicontrol(Fig,'Style','Text', 'Position',[75 320 170 016].*WS,'String','Crosshair Position');\nuicontrol(Fig,'Style','PushButton', 'Position',[75 316 170 006].*WS,...\n\t'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');\n% uicontrol(fg,'Style','PushButton', 'Position',[75 315 170 020].*WS,'String','Crosshair Position',...\n%\t'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');\nuicontrol(Fig,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:');\nuicontrol(Fig,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:');\nuicontrol(Fig,'Style','Text', 'Position',[75 255 75 020].*WS,'String','Img Intens.:');\n\nst.mp = uicontrol(Fig,'Style','edit', 'Position',[110 295 135 020].*WS,'String','','Callback','spm_image(''setposmm'')','ToolTipString','move crosshairs to mm coordinates');\nst.vp = uicontrol(Fig,'Style','edit', 'Position',[110 275 135 020].*WS,'String','','Callback','spm_image(''setposvx'')','ToolTipString','move crosshairs to voxel coordinates');\nst.in = uicontrol(Fig,'Style','Text', 'Position',[150 255 85 020].*WS,'String','');\n\nc = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;';\nuicontrol(Fig,'Style','togglebutton','Position',[95 220 125 20].*WS,...\n\t'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs');\n\n% Dipoles/seeds selection:\n%--------------------------\nuicontrol(Fig,'Style','Frame','Position',[300 25 180 325].*WS);\nsdip.hdl.hcl = uicontrol(Fig,'Style','pushbutton','Position',[310 320 100 20].*WS, ...\n 'String','Clear all','CallBack','spm_eeg_inv_ecd_DrawDip(''ClearAll'')');\n\nsdip.hdl.hseed=zeros(sdip.n_seeds,1);\nfor ii=1:sdip.n_seeds\n if sdip.exitflag(ii)==1\n sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','togglebutton','String',num2str(ii),...\n 'Position',[310+rem(ii-1,8)*20 295-fix((ii-1)/8)*20 20 20].*WS,...\n 'CallBack','spm_eeg_inv_ecd_DrawDip(''ChgSeed'')');\n else\n sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','Text','String',num2str(ii), ...\n 'Position',[310+rem(ii-1,8)*20 293-fix((ii-1)/8)*20 20 20].*WS) ;\n end\nend\n\nuicontrol(Fig,'Style','text','String','Select dipole # :', ...\n 'Position',[310 255-fix((sdip.n_seeds-1)/8)*20 110 20].*WS);\n\ntxt_box = cell(sdip.n_dip,1);\nfor ii=1:sdip.n_dip, txt_box{ii} = num2str(ii); end\ntxt_box{sdip.n_dip+1} = 'all';\nsdip.hdl.hdip = uicontrol(Fig,'Style','popup','String',txt_box, ...\n 'Position',[420 258-fix((sdip.n_seeds-1)/8)*20 40 20].*WS, ...\n 'Callback','spm_eeg_inv_ecd_DrawDip(''ChgDip'')');\n\n% Dipoles orientation and strength:\n%-----------------------------------\nuicontrol(Fig,'Style','Frame','Position',[70 120 180 90].*WS);\nuicontrol(Fig,'Style','Text', 'Position',[75 190 170 016].*WS, ...\n 'String','Dipole orientation & strength');\nuicontrol(Fig,'Style','Text', 'Position',[75 165 65 020].*WS,'String','vn_x_y_z:');\nuicontrol(Fig,'Style','Text', 'Position',[75 145 75 020].*WS,'String','theta, phi:');\nuicontrol(Fig,'Style','Text', 'Position',[75 125 75 020].*WS,'String','Dip intens.:');\n \nsdip.hdl.hor1 = uicontrol(Fig,'Style','Text', 'Position',[140 165 105 020].*WS,'String','a');\nsdip.hdl.hor2 = uicontrol(Fig,'Style','Text', 'Position',[150 145 85 020].*WS,'String','b');\nsdip.hdl.int = uicontrol(Fig,'Style','Text', 'Position',[150 125 85 020].*WS,'String','c');\n \nst.vols{1}.sdip = sdip;\n\n% First plot = all the seeds that converged !\nl_conv = find(sdip.exitflag==1);\nif isempty(l_conv)\n error('No seed converged towards a stable solution, nothing to be displayed !')\nelse\n\tspm_eeg_inv_ecd_DrawDip('DrawDip',l_conv,1)\n\tset(sdip.hdl.hseed(l_conv),'Value',1); % toggle all buttons\nend\n \n% get(sdip.hdl.hseed(1),'Value')\n% for ii=1:sdip.n_seeds, delete(hseed(ii)); end\n% h1 = uicontrol(Fig,'Style','togglebutton','Position',[600 25 10 10].*WS)\n% h2 = uicontrol(Fig,'Style','togglebutton','Position',[620 100 20 20].*WS,'String','1')\n% h2 = uicontrol(Fig,'Style','checkbox','Position',[600 100 10 10].*WS)\n% h3 = uicontrol(Fig,'Style','radiobutton','Position',[600 150 20 20].*WS)\n% h4 = uicontrol(Fig,'Style','radiobutton','Position',[700 150 20 20].*WS)\n% delete(h2),delete(h3),delete(h4),\n% delete(hdip)\n\n%________________________________________________________________________\ncase 'drawdip'\n%------------------------------------------------------------------------\n% FORMAT spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip,sdip)\n% e.g. spm_eeg_inv_ecd_DrawDip('DrawDip',1,1,sdip)\n% e.g. spm_eeg_inv_ecd_DrawDip('DrawDip',[1:5],1,sdip)\n\n% when displaying a set of 'close' dipoles\n% this defines the limit between 'close' and 'far'\n% lim_cl = 10; %mm\n% No more limit. All source displayed as projected on mean 3D cut.\n\nif nargin<2\n error('At least i_seed')\nend\ni_seed = varargin{1};\nif nargin<3\n i_dip = 1;\nelse\n i_dip = varargin{2}; \nend\n\nif nargin<4\n if isfield(st.vols{1},'sdip')\n sdip = st.vols{1}.sdip;\n else\n error('I can''t find sdip structure');\n end\nelse\n sdip = varargin{3};\n st.vols{1}.sdip = sdip;\nend\n\nif any(i_seed>sdip.n_seeds) | i_dip>(sdip.n_dip+1)\n error('Wrong i_seed or i_dip index in spm_eeg_inv_ecd_DrawDip');\nend\n\n% Note if i_dip==(sdip.n_dip+1) all dipoles are displayed simultaneously\nif i_dip==(sdip.n_dip+1)\n i_dip=1:sdip.n_dip;\nend\n\n% if seed indexes passed is wrong (no convergence) remove the wrong ones\ni_seed(find(sdip.exitflag(i_seed)~=1)) = [];\nif isempty(i_seed)\n error('You passed the wrong seed indexes...')\nend\nif size(i_seed,2)==1, i_seed=i_seed'; end\n\n% Display business\n%-----------------\nloc_mm = sdip.loc{i_seed(1)}(:,i_dip);\nif length(i_seed)>1\n% unit = ones(1,sdip.n_dip);\n\tfor ii = i_seed(2:end)\n loc_mm = loc_mm + sdip.loc{ii}(:,i_dip);\n end\n loc_mm = loc_mm/length(i_seed);\nend\nif length(i_dip)>1\n loc_mm = mean(loc_mm,2);\nend\n\n% Place the underlying image at right cuts\nspm_orthviews('Reposition',loc_mm);\n\nif length(i_dip)>1\n tabl_seed_dip = [kron(ones(length(i_dip),1),i_seed') ...\n kron(i_dip',ones(length(i_seed),1))];\nelse\n tabl_seed_dip = [i_seed' ones(length(i_seed),1)*i_dip];\nend\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% % First point to consider\n% loc_mm = sdip.loc{i_seed(1)}(:,i_dip);\n% \n% % PLace the underlying image at right cuts\n% spm_orthviews('Reposition',loc_mm);\n% % spm_orthviews('Reposition',loc_vx);\n% % spm_orthviews('Xhairs','off')\n% \n% % if i_seed = set, Are there other dipoles close enough ?\n% tabl_seed_dip=[i_seed(1) i_dip]; % table summarising which set & dip to use.\n% if length(i_seed)>1\n% \tunit = ones(1,sdip.n_dip);\n% \tfor ii = i_seed(2:end)'\n% d2 = sqrt(sum((sdip.loc{ii}-loc_mm*unit).^2));\n% l_cl = find(d2<=lim_cl);\n% if ~isempty(l_cl)\n% for jj=l_cl\n% tabl_seed_dip = [tabl_seed_dip ; [ii jj]];\n% end\n% end\n% \tend\n% end\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Scaling, according to all dipoles in the selected seed sets.\n% The time displayed is the one corresponding to the maximum EEG power !\nMn_j = -1;\nl3 = -2:0;\nfor ii = 1:length(i_seed)\n for jj = 1:sdip.n_dip\n Mn_j = max([Mn_j sqrt(sum(sdip.j{ii}(jj*3+l3,sdip.Mtb).^2))]);\n end\nend\nst.vols{1}.sdip.tabl_seed_dip = tabl_seed_dip;\n\n% Display all dipoles, the 1st one + the ones close enough.\n% Run through the 6 colors and 9 markers to differentiate the dipoles.\n% NOTA: 2 dipoles coming from the same set will have same colour/marker\nind = 1 ;\ndip_h = zeros(6,size(tabl_seed_dip,1),1);\n % each dipole displayed has 6 handles:\n % 2 per view (2*3): one for the line, the other for the circle\njs_m = zeros(3,1);\n\n% Deal with case of multiple i_seed and i_dip displayed.\n% make sure dipole from same i_seed have same colour but different marker.\n\npi_dip = find(diff(tabl_seed_dip(:,2)));\nif isempty(pi_dip)\n % i.e. only one dip displayed per seed, use old fashion\n for ii=1:size(tabl_seed_dip,1)\n if ii>1\n if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1)\n ind = ind+1;\n end\n end\n ic = mod(ind-1,Ncolors)+1;\n im = fix(ind/Ncolors)+1;\n\n loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,tabl_seed_dip(ii,2));\n\n js = sdip.j{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,sdip.Mtb);\n dip_h(:,ii) = add1dip(loc_pl,js/(eps+Mn_j*20),marker(im),colors(ic),st.vols{1}.ax,Fig,st.bb);\n js_m = js_m+js;\n end\nelse\n for ii=1:pi_dip(1)\n if ii>1\n if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1)\n ind = ind+1;\n end\n end\n ic = mod(ind-1,Ncolors)+1;\n for jj=1:sdip.n_dip\n im = mod(jj-1,Nmarker)+1;\n \n loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,jj);\n js = sdip.j{tabl_seed_dip(ii,1)}(jj*3+l3,sdip.Mtb);\n js_m = js_m+js;\n dip_h(:,ii+(jj-1)*pi_dip(1)) = ...\n add1dip(loc_pl,js/Mn_j*20,marker(im),colors(ic), ...\n st.vols{1}.ax,Fig,st.bb);\n end\n end\nend\nst.vols{1}.sdip.ax = dip_h;\n\n% Display dipoles orientation and strength\njs_m = js_m/size(tabl_seed_dip,1);\n[th,phi,Ijs_m] = cart2sph(js_m(1),js_m(2),js_m(3));\nNjs_m = round(js_m'/(eps+Ijs_m*100))/100;\nAngle = round([th phi]*1800/pi)/10;\n\nset(sdip.hdl.hor1,'String',[num2str(Njs_m(1)),' ',num2str(Njs_m(2)), ...\n ' ',num2str(Njs_m(3))]);\nset(sdip.hdl.hor2,'String',[num2str(Angle(1)),' ',num2str(Angle(2))]);\nset(sdip.hdl.int,'String',Ijs_m);\n\n% Change the colour of toggle button of dipoles actually displayed\nfor ii=tabl_seed_dip(:,1)\n set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 1 .7]);\nend\n\n%________________________________________________________________________\ncase 'clearall'\n%------------------------------------------------------------------------\n% Clears all dipoles, and reset the toggle buttons\n\nif isfield(st.vols{1},'sdip')\n sdip = st.vols{1}.sdip;\nelse\n error('I can''t find sdip structure');\nend\n\ndisp('Clears all dipoles')\nspm_eeg_inv_ecd_DrawDip('ClearDip');\nfor ii=1:st.vols{1}.sdip.n_seeds\n if sdip.exitflag(ii)==1\n set(st.vols{1}.sdip.hdl.hseed(ii),'Value',0);\n end\nend\nset(st.vols{1}.sdip.hdl.hdip,'Value',1);\n\n%________________________________________________________________________\ncase 'chgseed'\n%------------------------------------------------------------------------\n% Changes the seeds displayed\n% disp('Change seed')\n\nsdip = st.vols{1}.sdip;\nif isfield(sdip,'tabl_seed_dip')\n prev_seeds = p_seed(sdip.tabl_seed_dip);\nelse\n prev_seeds = [];\nend\n\nl_seed = zeros(sdip.n_seeds,1);\nfor ii=1:sdip.n_seeds\n if sdip.exitflag(ii)==1\n l_seed(ii) = get(sdip.hdl.hseed(ii),'Value');\n end\nend\nl_seed = find(l_seed);\n\n% Modify the list of seeds displayed\nif length(l_seed)==0\n % Nothing left displayed\n i_seed=[];\nelseif isempty(prev_seeds)\n % Just one dipole added, nothing before\n i_seed=l_seed;\nelseif length(prev_seeds)>length(l_seed)\n % One seed removed\n i_seed = prev_seeds;\n for ii=1:length(l_seed)\n p = find(prev_seeds==l_seed(ii));\n if ~isempty(p)\n prev_seeds(p) = [];\n end % prev_seeds is left with the index of the one removed\n end\n i_seed(find(i_seed==prev_seeds)) = [];\n % Remove the dipole & change the button colour\n spm_eeg_inv_ecd_DrawDip('ClearDip',prev_seeds);\n set(sdip.hdl.hseed(prev_seeds),'BackgroundColor',[.7 .7 .7]);\nelse\n % One dipole added\n i_seed = prev_seeds;\n for ii=1:length(prev_seeds)\n p = find(prev_seeds(ii)==l_seed);\n if ~isempty(p)\n l_seed(p) = [];\n end % l_seed is left with the index of the one added\n end\n i_seed = [i_seed ; l_seed];\nend\n\ni_dip = get(sdip.hdl.hdip,'Value');\nspm_eeg_inv_ecd_DrawDip('ClearDip');\nif ~isempty(i_seed)\n spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip);\nend\n\n%________________________________________________________________________\ncase 'chgdip'\n%------------------------------------------------------------------------\n% Changes the dipole index for the first seed displayed\n\ndisp('Change dipole')\nsdip = st.vols{1}.sdip;\n\ni_dip = get(sdip.hdl.hdip,'Value');\nif isfield(sdip,'tabl_seed_dip')\n i_seed = p_seed(sdip.tabl_seed_dip);\nelse\n i_seed = [];\nend\n\nif ~isempty(i_seed)\n spm_eeg_inv_ecd_DrawDip('ClearDip')\n spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip);\nend\n\n%________________________________________________________________________\ncase 'cleardip'\n%------------------------------------------------------------------------\n% FORMAT spm_eeg_inv_ecd_DrawDip('ClearDip',seed_i)\n% e.g. spm_eeg_inv_ecd_DrawDip('ClearDip')\n% clears all displayed dipoles\n% e.g. spm_eeg_inv_ecd_DrawDip('ClearDip',1)\n% clears the first dipole displayed\n\nif nargin>2\n seed_i = varargin{1};\nelse\n seed_i = 0;\nend\nif isfield(st.vols{1},'sdip')\n sdip = st.vols{1}.sdip;\n else\n return; % I don't do anything, as I can't find sdip strucure\nend\n\nif isfield(sdip,'ax')\n Nax = size(sdip.ax,2);\n else\n return; % I don't do anything, as I can't find axes info\nend\n\nif seed_i==0 % removes everything\n for ii=1:Nax\n for jj=1:6\n delete(sdip.ax(jj,ii));\n end\n end\n for ii=sdip.tabl_seed_dip(:,1)\n set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 .7 .7]);\n\tend\n sdip = rmfield(sdip,'tabl_seed_dip');\n sdip = rmfield(sdip,'ax'); \nelseif seed_i<=Nax % remove one seed only\n l_seed = find(sdip.tabl_seed_dip(:,1)==seed_i);\n for ii=l_seed\n for jj=1:6\n delete(sdip.ax(jj,ii));\n end\n end\n sdip.ax(:,l_seed) = [];\n sdip.tabl_seed_dip(l_seed,:) = [];\nelse\n error('Trying to clear unspecified dipole');\nend\nst.vols{1}.sdip = sdip;\n\n%________________________________________________________________________\notherwise,\n\twarning('Unknown action string')\nend;\n\nreturn;\n\n%________________________________________________________________________\n%________________________________________________________________________\n%________________________________________________________________________\n%________________________________________________________________________\n%\n% SUBFUNCTIONS\n%________________________________________________________________________\n%________________________________________________________________________\nfunction dh = add1dip(loc,js,mark,col,ax,Fig,bb)\n% Plots the dipoles on the 3 views\n% Then returns the handle to the plots\n\nloc(1,:) = loc(1,:) - bb(1,1)+1;\nloc(2,:) = loc(2,:) - bb(1,2)+1;\nloc(3,:) = loc(3,:) - bb(1,3)+1;\n% +1 added to be like John's orthview code\n\ndh = zeros(6,1);\nfigure(Fig)\n% Transverse slice, # 1\nset(Fig,'CurrentAxes',ax{1}.ax)\nset(ax{1}.ax,'NextPlot','add')\ndh(1) = plot(loc(1),loc(2),[mark,col],'LineWidth',2);\ndh(2) = plot(loc(1)+[0 js(1)],loc(2)+[0 js(2)],col,'LineWidth',2);\nset(ax{1}.ax,'NextPlot','replace')\n\n% Coronal slice, # 2\nset(Fig,'CurrentAxes',ax{2}.ax)\nset(ax{2}.ax,'NextPlot','add')\ndh(3) = plot(loc(1),loc(3),[mark,col],'LineWidth',2);\ndh(4) = plot(loc(1)+[0 js(1)],loc(3)+[0 js(3)],col,'LineWidth',2);\nset(ax{2}.ax,'NextPlot','replace')\n\n% Sagital slice, # 3\nset(Fig,'CurrentAxes',ax{3}.ax)\nset(ax{3}.ax,'NextPlot','add')\n% dh(5) = plot(dim(2)-loc(2),loc(3),[mark,col],'LineWidth',2);\n% dh(6) = plot(dim(2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2);\ndh(5) = plot(bb(2,2)-bb(1,2)-loc(2),loc(3),[mark,col],'LineWidth',2);\ndh(6) = plot(bb(2,2)-bb(1,2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2);\nset(ax{3}.ax,'NextPlot','replace')\n\nreturn\n\n%________________________________________________________________________\nfunction pr_seed = p_seed(tabl_seed_dip)\n% Gets the list of seeds used in the previous display\n\nls = sort(tabl_seed_dip(:,1));\nif length(ls)==1\n pr_seed = ls;\nelse\n\tpr_seed = ls([find(diff(ls)) ; length(ls)]);\nend\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "eeglab_fastif.m", "ext": ".m", "path": "spm5-master/toolbox/api_erp/eeglab_fastif.m", "size": 1367, "source_encoding": "utf_8", "md5": "4d8780482e0ea0bb45ea3e4ea85261cd", "text": "% fastif() - fast if function.\n%\n% Usage:\n% >> res = fastif(test, s1, s2);\n%\n% Input:\n% test - logical test with result 0 or 1\n% s1 - result if 1\n% s2 - result if 0\n%\n% Output:\n% res - s1 or s2 depending on the value of the test\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 2001\n\n%123456789012345678901234567890123456789012345678901234567890123456789012\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n% $Log: fastif.m,v $\n% Revision 1.1 2002/04/05 17:39:45 jorn\n% Initial revision\n%\n% 01-25-02 reformated help & license -ad \n\nfunction res = eeglab_fastif(s1, s2, s3);\n\nif s1\n\tres = s2;\nelse\n\tres = s3;\nend;\nreturn;"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_api_erp.m", "ext": ".m", "path": "spm5-master/toolbox/api_erp/spm_api_erp.m", "size": 29617, "source_encoding": "utf_8", "md5": "14876864a53a1a4695dd23e6782d44cd", "text": "function varargout = spm_api_erp(varargin)\n% SPM_API_ERP Application M-file for spm_api_erp.fig\n% FIG = SPM_API_ERP launch spm_api_erp GUI.\n% SPM_API_ERP('callback_name', ...) invoke the named callback.\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_api_erp.m 1106 2008-01-17 16:57:56Z guillaume $\n\nif nargin == 0 || nargin == 1 % LAUNCH GUI\n\n fig = openfig(mfilename,'reuse');\n Fgraph = spm_figure('GetWin','Graphics');\n % Use system color scheme for figure:\n set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));\n\n % Generate a structure of handles to pass to callbacks, and store it.\n handles = guihandles(fig);\n handles.Fgraph = Fgraph;\n guidata(fig, handles);\n \n if nargin == 1\n load_Callback(fig, [], handles, varargin{1})\n end\n\n if nargout > 0\n varargout{1} = fig;\n end\n\nelseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK\n\n try\n if (nargout)\n [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard\n else\n feval(varargin{:}); % FEVAL switchyard\n end\n catch\n disp(lasterr);\n end\nend\n\n\n% Callbacks\n%==========================================================================\n\n%-DCM files and directories: Load and save\n%==========================================================================\n\n% --- Executes on button press in load.\n% -------------------------------------------------------------------------\nfunction varargout = load_Callback(hObject, eventdata, handles, varargin)\ntry\n DCM = varargin{1};\n [p,f] = fileparts(DCM.name);\ncatch\n [f,p] = uigetfile('*.mat','please select DCM file'); \n cd(p)\n name = fullfile(p,f);\n DCM = load(name,'-mat');\n DCM = DCM.DCM;\n DCM.name = name;\n handles.DCM = DCM;\n guidata(hObject,handles);\nend\n\n\n% Type of model\n%--------------------------------------------------------------------------\n% 'ERP' - (linear NMM slow)\n% 'SEP' - (linear NMM fast)\n% 'NMM' - (bilinear NMM)\n% 'MFM' - (bilinear MFM)\n% 'Induced - (linear NMM)\n\ntry\n model = DCM.options.model;\ncatch\n model = get(handles.ERP,'String');\n model = model{get(handles.ERP,'Value')};\nend\nswitch model\n case{'ERP'}, set(handles.ERP,'Value',1);\n case{'SEP'}, set(handles.ERP,'Value',2);\n case{'NMM'}, set(handles.ERP,'Value',3);\n case{'MFM'}, set(handles.ERP,'Value',4);\n case{'Induced'}, set(handles.ERP,'Value',5);\n otherwise\nend\nhandles = ERP_Callback(hObject, eventdata, handles);\n\n% Filename\n%--------------------------------------------------------------------------\ntry, set(handles.name,'String',f); end\n\n% Source locations\n%--------------------------------------------------------------------------\ntry, DCM.Lpos = DCM.M.dipfit.L.pos; end\n\n% enter options from saved options and execute data_ok and spatial_ok\n%--------------------------------------------------------------------------\ntry, set(handles.Y1, 'String', num2str(DCM.options.trials,'%7.0f')); end\ntry, set(handles.T1, 'String', num2str(DCM.options.Tdcm(1))); end\ntry, set(handles.T2, 'String', num2str(DCM.options.Tdcm(2))); end\ntry, set(handles.Hz1,'String', num2str(DCM.options.Fdcm(1))); end\ntry, set(handles.Hz2,'String', num2str(DCM.options.Fdcm(2))); end\ntry, set(handles.Rft,'String', num2str(DCM.options.Rft)); end\ntry, set(handles.Spatial_type,'Value', DCM.options.type); end\ntry, set(handles.Nmodes, 'Value', DCM.options.Nmodes); end\ntry, set(handles.h, 'Value', DCM.options.h); end\ntry, set(handles.han, 'Value', DCM.options.han); end\ntry, set(handles.D, 'Value', DCM.options.D); end\ntry, set(handles.lock, 'Value', DCM.options.lock); end\ntry, set(handles.design, 'String',num2str(DCM.xU.X','%7.2f')); end\ntry, set(handles.Uname, 'String',DCM.xU.name); end\ntry, set(handles.onset, 'String',num2str(DCM.options.onset)); end\ntry, set(handles.Sname, 'String',strvcat(DCM.Sname)); end\ntry, set(handles.Slocation, 'String',num2str(DCM.Lpos','%4.0f')); end\n\n\n% catch for backwards compatibility\n%--------------------------------------------------------------------------\nif get(handles.Spatial_type,'Value') > length(get(handles.Spatial_type,'String'))\n set(handles.Spatial_type,'Value',1);\nend\n\nif get(handles.Spatial_type,'Value') == 2\n set(handles.render, 'Enable','on' )\n set(handles.Imaging,'Enable','on' )\nelse\n set(handles.render, 'Enable','off' )\n set(handles.Imaging,'Enable','off' )\nend\nset(handles.data_ok,'enable','on')\n\nhandles.DCM = DCM;\nguidata(hObject, handles);\n\n% data specification\n%--------------------------------------------------------------------------\ntry\n handles = data_ok_Callback(hObject, eventdata, handles);\n guidata(hObject, handles);\ncatch\n return\nend\n\n% spatial model specification\n%--------------------------------------------------------------------------\ntry\n handles = spatial_ok_Callback(hObject, eventdata, handles);\n guidata(hObject, handles);\ncatch\n return\nend\n\n% connections specification\n%--------------------------------------------------------------------------\ntry\n connections_Callback(hObject, eventdata, handles);\n set(handles.estimate, 'Enable', 'on');\n set(handles.initialise, 'Enable', 'on');\n guidata(hObject, handles);\ncatch\n return\nend\n\n% estimation and results\n%--------------------------------------------------------------------------\ntry\n handles.DCM.F;\n set(handles.results, 'Enable','on');\n if handles.DCM.options.type == 2\n set(handles.render, 'Enable','on');\n set(handles.Imaging,'Enable','on');\n\n end\ncatch\n set(handles.results, 'Enable','off');\nend\n\n% --- Executes on button press in save.\n% -------------------------------------------------------------------------\nfunction handles = save_Callback(hObject, eventdata, handles)\n\nhandles = reset_Callback(hObject, eventdata, handles);\ntry\n [p,f] = fileparts(handles.DCM.name);\ncatch\n try\n [p,f] = fileparts(handles.DCM.xY.Dfile);\n f = ['DCM_' f];\n catch\n f = ['DCM' date];\n end\nend\n[f,p] = uiputfile(['DCM*.mat'],'DCM file to save',f);\n\nif p\n handles.DCM.name = fullfile(p,f);\n set(handles.name,'String',f);\n DCM = handles.DCM;\n save(DCM.name,'DCM')\n set(handles.estimate, 'Enable', 'on')\n set(handles.initialise, 'Enable', 'on');\nend\n\n% assign in base\n%--------------------------------------------------------------------------\nassignin('base','DCM',handles.DCM)\nguidata(hObject,handles);\n\n% store selections in DCM\n% -------------------------------------------------------------------------\nfunction handles = reset_Callback(hObject, eventdata, handles)\n\nhandles.DCM.options.trials = str2num(get(handles.Y1, 'String'));\nhandles.DCM.options.Tdcm(1) = str2num(get(handles.T1, 'String'));\nhandles.DCM.options.Tdcm(2) = str2num(get(handles.T2, 'String'));\nhandles.DCM.options.Fdcm(1) = str2num(get(handles.Hz1, 'String'));\nhandles.DCM.options.Fdcm(2) = str2num(get(handles.Hz2, 'String'));\nhandles.DCM.options.Rft = str2num(get(handles.Rft, 'String'));\nhandles.DCM.options.onset = str2num(get(handles.onset, 'String'));\nhandles.DCM.options.Nmodes = get(handles.Nmodes, 'Value');\nhandles.DCM.options.h = get(handles.h, 'Value');\nhandles.DCM.options.han = get(handles.han, 'Value');\nhandles.DCM.options.D = get(handles.D, 'Value');\nhandles.DCM.options.type = get(handles.Spatial_type, 'Value');\nhandles.DCM.options.lock = get(handles.lock, 'Value');\n\n\n% save model\n%--------------------------------------------------------------------------\nmodel = get(handles.ERP, 'String');\nmodel = model{get(handles.ERP,'Value')};\nhandles.DCM.options.model = model;\n\nguidata(hObject,handles);\n\n\n% Data selection and design\n%==========================================================================\n\n%-Get trials and data\n%--------------------------------------------------------------------------\nfunction Y1_Callback(hObject, eventdata, handles)\ntry\n trials = str2num(get(handles.Y1,'String'));\n handles.DCM.options.trials = trials;\n set(handles.Y1,'String',num2str(trials,'%7.0f'))\n m = length(handles.DCM.options.trials);\ncatch\n m = 1;\n set(handles.Y1,'String','1')\nend\nhandles = Xdefault(hObject,handles,m);\n\n%-Get new trial data from file\n%--------------------------------------------------------------------------\ntry\n spm_eeg_ldata(handles.DCM.xY.Dfile);\ncatch\n [f,p] = uigetfile({'*.mat'}, 'please select data file');\n handles.DCM.xY.Dfile = fullfile(p,f);\nend\n\n\n% Assemble and display data\n%--------------------------------------------------------------------------\nhandles = reset_Callback(hObject, eventdata, handles);\nhandles.DCM = spm_dcm_erp_data(handles.DCM,handles.DCM.options.h);\n\nset(handles.design,'enable', 'on')\nset(handles.Uname, 'enable', 'on')\nset(handles.Y, 'enable', 'on')\nguidata(hObject,handles);\nwarndlg({'Your design matrix has been re-set'})\n\n% --- Executes on button press in Y to display data\n%--------------------------------------------------------------------------\nfunction Y_Callback(hObject, eventdata, handles)\nhandles = reset_Callback(hObject, eventdata, handles);\ntry\n handles.DCM = spm_dcm_erp_data(handles.DCM,handles.DCM.options.h);\n spm_dcm_erp_results(handles.DCM,'Data');\n set(handles.dt, 'String',sprintf('bins: %.1fms',handles.DCM.xY.dt*1000))\n set(handles.dt, 'Visible','on')\ncatch\n warndlg('please specify data and trials');\nend\nguidata(hObject,handles);\n\n% --- Executes on button press in Uname.\n%--------------------------------------------------------------------------\nfunction Uname_Callback(hObject, eventdata, handles)\ntry\n m = length(handles.DCM.options.trials);\ncatch\n warndlg('please select trials')\n handles = Xdefault(hObject,handles,1);\n return\nend\nStr = get(handles.Uname,'String');\nn = size(handles.DCM.xU.X,2);\nfor i = 1:n\n try\n Uname{i} = Str{i};\n catch\n Uname{i} = sprintf('effect %i',i);\n end\nend\nset(handles.Uname,'string',Uname(:))\nhandles.DCM.xU.name = Uname;\nguidata(hObject,handles);\n\n% --- Executes on button press in design.\n%--------------------------------------------------------------------------\nfunction design_Callback(hObject, eventdata, handles)\ntry\n m = length(handles.DCM.options.trials);\ncatch\n handles = Xdefault(hObject,handles,1);\n warndlg('please select trials')\n return\nend\ntry\n X = str2num(get(handles.design,'String'))';\n handles.DCM.xU.X = X(1:m,:);\n set(handles.design, 'String',num2str(handles.DCM.xU.X','%7.2f'));\ncatch\n handles = Xdefault(hObject,handles,m);\nend\nn = size(handles.DCM.xU.X,2);\nUname = {};\nfor i = 1:n\n try\n Uname{i} = handles.DCM.xU.name{i};\n catch\n Uname{i} = sprintf('effect %i',i);\n end\nend\nset(handles.Uname,'string',Uname(:))\nhandles.DCM.xU.name = Uname;\nguidata(hObject,handles);\n\n\n% Spatial model specification\n%==========================================================================\nfunction handles = spatial_ok_Callback(hObject, eventdata, handles)\nhandles = reset_Callback(hObject, eventdata, handles);\n\n% spatial model\n%--------------------------------------------------------------------------\nDCM = handles.DCM;\ntmp = deblank(get(handles.Sname, 'String'));\nif size(tmp,1) == 0\n errordlg('Please specify the source names'); \n return\nend\nk = 1;\nfor i = 1:size(tmp, 1)\n if ~isempty(deblank(tmp(i,:)))\n Sname{k} = deblank(tmp(i,:));\n k = k + 1;\n end\nend\nNareas = length(Sname);\nNmodes = get(handles.Nmodes,'Value');\nDCM.Sname = Sname;\n\n% switch for spatial forward model\n%--------------------------------------------------------------------------\nDCM.options.type = get(handles.Spatial_type,'Value');\n\n% read location coordinates\n%--------------------------------------------------------------------------\nSlocation = zeros(Nareas, 3);\ntmp = get(handles.Slocation, 'String');\nif ~isempty(tmp) & size(tmp,1) == Nareas\n for i = 1:Nareas\n tmp2 = str2num(tmp(i, :));\n if length(tmp2) ~= 3\n errordlg(sprintf('coordinates of area %d not valid',i)); \n return;\n else\n Slocation(i, :) = tmp2;\n end\n end\n if size(Slocation, 1) ~= Nareas\n errordlg('Number of source names and locations must correspond'); \n return;\n end\nelse\n errordlg(sprintf('Please specify %d source locations.', Nareas)); \n return\nend\n\n% set prior expectations about locations\n%--------------------------------------------------------------------------\nDCM.Lpos = Slocation';\n\n% forward model (spatial)\n%--------------------------------------------------------------------------\nDCM = spm_dcm_erp_dipfit(DCM);\n\nhandles.DCM = DCM;\nset(handles.Spatial_type, 'Enable', 'off');\nset(handles.spatial_ok, 'Enable', 'off');\nset(handles.onset, 'Enable', 'off');\nset(handles.Sname, 'Enable', 'off');\nset(handles.Slocation, 'Enable', 'off');\nset(handles.spatial_back, 'Enable', 'off');\n\nset(handles.con_reset, 'Enable', 'on');\nset(handles.connectivity_back,'Enable', 'on');\nset(handles.Hz1, 'Enable', 'on');\nset(handles.Hz2, 'Enable', 'on');\nset(handles.Rft, 'Enable', 'on');\n\n\n% [re]-set connections\n%--------------------------------------------------------------------------\nhandles = connections_Callback(hObject, eventdata, handles);\nguidata(hObject,handles);\n\n% --- Executes on button press in pos.\n%--------------------------------------------------------------------------\nfunction pos_Callback(hObject, eventdata, handles)\n[f,p] = uigetfile('*.mat','source (n x 3) location file');\nSlocation = load(fullfile(p,f));\nname = fieldnames(Slocation);\nSlocation = getfield(Slocation, name{1});\nset(handles.Slocation,'String',num2str(Slocation,'%4.0f'));\n\n\n%-Executes on button press in data_ok.\n%--------------------------------------------------------------------------\nfunction handles = data_ok_Callback(hObject, eventdata, handles)\nhandles = reset_Callback(hObject, eventdata, handles);\nhandles.DCM = spm_dcm_erp_data(handles.DCM,handles.DCM.options.h);\n\n\n% enable next stage, disable data specification\n%--------------------------------------------------------------------------\nset(handles.Y1, 'Enable', 'off');\nset(handles.T1, 'Enable', 'off');\nset(handles.T2, 'Enable', 'off');\nset(handles.Nmodes, 'Enable', 'off');\nset(handles.h, 'Enable', 'off');\nset(handles.D, 'Enable', 'off');\nset(handles.design, 'Enable', 'off');\nset(handles.Uname, 'Enable', 'off');\nset(handles.data_ok, 'Enable', 'off');\n\nset(handles.Spatial_type, 'Enable', 'on');\nset(handles.plot_dipoles, 'Enable', 'on');\nset(handles.onset, 'Enable', 'on');\nset(handles.Sname, 'Enable', 'on');\nset(handles.Slocation, 'Enable', 'on');\nset(handles.spatial_back, 'Enable', 'on');\nset(handles.spatial_ok, 'Enable', 'on');\n\nguidata(hObject, handles);\n\n\n% --- Executes on button press in spatial_back.\n%----------------------------------------------------------------------\nfunction spatial_back_Callback(hObject, eventdata, handles)\n\nset(handles.Spatial_type, 'Enable', 'off');\nset(handles.spatial_ok, 'Enable', 'off');\nset(handles.onset, 'Enable', 'off');\nset(handles.Sname, 'Enable', 'off');\nset(handles.Slocation, 'Enable', 'off');\nset(handles.spatial_back, 'Enable', 'off');\n\nset(handles.Y, 'Enable', 'on');\nset(handles.Y1, 'Enable', 'on');\nset(handles.T1, 'Enable', 'on');\nset(handles.T2, 'Enable', 'on');\nset(handles.Nmodes, 'Enable', 'on');\nset(handles.h, 'Enable', 'on');\nset(handles.D, 'Enable', 'on');\nset(handles.design, 'Enable', 'on');\nset(handles.Uname, 'Enable', 'on');\nset(handles.data_ok, 'Enable', 'on');\n\nguidata(hObject, handles);\n\n% --- Executes on button press in plot_dipoles.\n%--------------------------------------------------------------------------\nfunction plot_dipoles_Callback(hObject, eventdata, handles)\n\n% read location coordinates\ntmp = get(handles.Slocation, 'String');\nSlocation = [];\nif ~isempty(tmp) \n for i = 1:size(tmp, 1)\n tmp2 = str2num(tmp(i, :))';\n if length(tmp2) == 3\n Slocation = [Slocation tmp2];\n end\n end\nend\n\nNlocations = size(Slocation, 2);\nsdip.n_seeds = 1;\nsdip.n_dip = Nlocations;\nsdip.Mtb = 1;\nsdip.j{1} = zeros(3*Nlocations, 1);\nsdip.loc{1} = Slocation;\nspm_eeg_inv_ecd_DrawDip('Init', sdip)\n\n%-Connectivity\n%==========================================================================\n\n% Draw buttons\n%--------------------------------------------------------------------------\nfunction handles = connections_Callback(hObject, eventdata, handles)\nhandles = reset_Callback(hObject, eventdata, handles);\nDCM = handles.DCM;\nn = length(DCM.Sname); % number of sources\nm = size(DCM.xU.X,2); % number of experimental inputs\nl = length(DCM.options.onset); % number of peristimulus inputs\n\n% remove previous objects\n%--------------------------------------------------------------------------\nh = get(handles.SPM,'Children');\nfor i = 1:length(h)\n if strcmp(get(h(i),'Tag'),'tmp')\n delete(h(i));\n end\nend\n\n\n% no changes in coupling\n%--------------------------------------------------------------------------\nif ~m, B = {}; DCM.B = {}; end\n\n% check DCM.A, DCM.B, ...\n%--------------------------------------------------------------------------\ntry\n if length(DCM.A{1}) ~= n, DCM = rmfield(DCM,'A'); end\n if length(DCM.B) ~= m, DCM = rmfield(DCM,'B'); end\n if size(DCM.C,1) ~= n, DCM = rmfield(DCM,'C'); end\n if size(DCM.C,2) ~= l, DCM = rmfield(DCM,'C'); end\nend\n\n% connection buttons\n%--------------------------------------------------------------------------\nset(handles.con_reset,'Units','Normalized')\np = get(handles.con_reset,'Position');\nx0 = p(1);\ny0 = p(2);\nsx = 1/32;\nsy = 1/64;\nfor i = 1:n\n for j = 1:n\n for k = 1:3\n x = x0 + (j - 1)*sx + (k - 1)*(n + 1)*sx;\n y = y0 - (i + 4)*sy;\n str = sprintf('data.DCM.A{%i}(%i,%i)',k,i,j);\n str = ['data=guidata(gcbo);' str '=get(gcbo,''Value'');guidata(gcbo,data)'];\n A{k}(i,j) = uicontrol(handles.SPM,...\n 'Units','Normalized',...\n 'Position',[x y sx sy],...\n 'Style','radiobutton',...\n 'Tag','tmp',...\n 'Callback',str);\n \n % within region, between frequency coupling for 'Induced'\n %--------------------------------------------------------------\n if i == j\n set(A{k}(i,j),'Enable','off')\n end\n \n % allow nonlinear self-connections (induced responses)\n %--------------------------------------------------------------\n if get(handles.ERP,'value') == 5 && k == 2\n set(A{k}(i,j),'Enable','on')\n end\n try\n set(A{k}(i,j),'Value',DCM.A{k}(i,j));\n catch\n DCM.A{k}(i,j) = get(A{k}(i,j),'Value');\n end\n end\n for k = 1:m\n x = x0 + (j - 1)*sx + (k - 1)*(n + 1)*sx;\n y = y0 - (i + 4)*sy - (n + 1)*sy;\n str = sprintf('data.DCM.B{%i}(%i,%i)',k,i,j); \n str = ['data=guidata(gcbo);' str '=get(gcbo,''Value'');guidata(gcbo,data)'];\n B{k}(i,j) = uicontrol(handles.SPM,...\n 'Units','Normalized',...\n 'Position',[x y sx sy],...\n 'Style','radiobutton',...\n 'Tag','tmp',...\n 'Callback',str);\n % intrinsic modulation of H_e\n %--------------------------------------------------------------\n if i == j\n set(B{k}(i,j),'Enable','on')\n end\n try\n set(B{k}(i,j),'Value',DCM.B{k}(i,j));\n catch\n DCM.B{k}(i,j) = get(B{k}(i,j),'Value');\n end\n end\n end\nend\nfor i = 1:n\n for j = 1:l\n x = x0 + (4 - 1)*(n + 1)*sx +(j - 1)*sx;\n y = y0 - (i + 4)*sy;\n str = sprintf('data.DCM.C(%i,%i)',i,j);\n str = ['data=guidata(gcbo);' str '=get(gcbo,''Value'');guidata(gcbo,data)'];\n C(i,j) = uicontrol(handles.SPM,...\n 'Units','Normalized',...\n 'Position',[x y sx sy],...\n 'Style','radiobutton',...\n 'Tag','tmp',...\n 'Callback',str);\n try\n set(C(i,j),'Value',DCM.C(i,j));\n catch\n DCM.C(i,j) = get(C(i,j),'Value');\n end\n end\nend\n\n% string labels\n%--------------------------------------------------------------------------\nif get(handles.ERP,'Value') ~= 5\n constr = {'A forward' 'A backward' 'A lateral' 'C input'};\nelse\n constr = {'A linear' 'A nonlinear' '(not used)' 'C input'};\nend\nnsx = (n + 1)*sx;\nnsy = 2*sy;\nfor k = 1:4\n x = x0 + (k - 1)*nsx;\n y = y0 - 3*sy;\n str = constr{k};\n S(k) = uicontrol(handles.SPM,...\n 'Units','Normalized',...\n 'Position',[x y nsx nsy],...\n 'HorizontalAlignment','left',...\n 'Style','text',...\n 'String',str,...\n 'Tag','tmp',...\n 'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\nconstr = DCM.xU.name;\nfor k = 1:m\n x = x0 + (k - 1)*nsx;\n y = y0 - 6*sy - 2*(n + 1)*sy;\n str = ['B ' constr{k}];\n S(4 + k) = uicontrol(handles.SPM,...\n 'Units','Normalized',...\n 'Position',[x y nsx nsy],...\n 'HorizontalAlignment','left',...\n 'Style','text',...\n 'String',str,...\n 'Tag','tmp',...\n 'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\nhandles.S = S;\nhandles.A = A;\nhandles.B = B;\nhandles.C = C;\nhandles.DCM = DCM;\n\nset(handles.estimate, 'Enable','on');\nset(handles.initialise, 'Enable','on');\n\nguidata(hObject,handles)\n\n% remove existing buttons and set DCM.A,.. to zero\n%--------------------------------------------------------------------------\nfunction con_reset_Callback(hObject, eventdata, handles)\n\nh = get(handles.SPM,'Children');\nfor i = 1:length(h)\n if strcmp(get(h(i),'Tag'),'tmp')\n delete(h(i));\n end\nend\ntry\n for i = 1:length(handles.DCM.A)\n handles.DCM.A{i}(:) = 0;\n end\n for i = 1:length(handles.DCM.B)\n handles.DCM.B{i}(:) = 0;\n end\n handles.DCM.C(:) = 0;\nend\nhandles = connections_Callback(hObject, eventdata, handles);\nguidata(hObject,handles)\n\n% --- Executes on button press in connectivity_back.\n%--------------------------------------------------------------------------\nfunction connectivity_back_Callback(hObject, eventdata, handles)\n\nset(handles.con_reset, 'Enable', 'off');\nset(handles.connectivity_back, 'Enable', 'off');\nset(handles.Hz1, 'Enable', 'off');\nset(handles.Hz2, 'Enable', 'off');\nset(handles.Rft, 'Enable', 'off');\n\nset(handles.Spatial_type, 'Enable', 'on');\nset(handles.spatial_ok, 'Enable', 'on');\nset(handles.onset, 'Enable', 'on');\nset(handles.Sname, 'Enable', 'on');\nset(handles.Slocation, 'Enable', 'on');\nset(handles.spatial_back, 'Enable', 'on');\n\n% connection buttons\n%--------------------------------------------------------------------------\ntry\n for i = 1:length(handles.A)\n for j = 1:length(handles.A{i})\n for k = 1:length(handles.A{i})\n set(handles.A{i}(j,k), 'Enable', 'off');\n end\n end\n end\n for i = 1:length(handles.B)\n for j = 1:length(handles.B{i})\n for k = 1:length(handles.B{i})\n set(handles.B{i}(j,k), 'Enable', 'off');\n end\n end\n end\n for i = 1:length(handles.C)\n set(handles.C(i), 'Enable', 'off');\n end\nend\n\n%-Estimate, initalise and review\n%==========================================================================\n\n% --- Executes on button press in estimate.\n% -------------------------------------------------------------------------\nfunction varargout = estimate_Callback(hObject, eventdata, handles, varargin)\nset(handles.estimate,'String','Estimating','Foregroundcolor',[1 0 0])\nhandles = reset_Callback(hObject, eventdata, handles);\n\n% initialise if required\n% -------------------------------------------------------------------------\ntry\n Ep = handles.DCM.Ep;\n Str = questdlg('initialize with previous estimates');\n if strcmp(Str,'Yes')\n handles.DCM.M.P = Ep;\n elseif strcmp(Str,'No')\n handles.DCM.M.P = [];\n elseif strcmp(Str,'Cancel')\n return\n end\nend\n\n% invert and save\n% -------------------------------------------------------------------------\nif get(handles.ERP,'Value') == 5\n handles.DCM = spm_dcm_ind(handles.DCM);\nelse\n handles.DCM = spm_dcm_erp(handles.DCM);\nend\nguidata(hObject, handles);\n\nset(handles.results, 'Enable','on' )\nset(handles.save, 'Enable','on')\nset(handles.estimate, 'String','Estimated','Foregroundcolor',[0 0 0])\nif get(handles.Spatial_type,'Value') == 2\n set(handles.render, 'Enable','on' )\n set(handles.Imaging,'Enable','on' )\nend\n\n% --- Executes on button press in results.\n% -------------------------------------------------------------------------\nfunction varargout = results_Callback(hObject, eventdata, handles, varargin)\nAction = get(handles.results, 'String');\nAction = Action{get(handles.results, 'Value')};\nif get(handles.ERP,'Value') == 5\n spm_dcm_ind_results(handles.DCM, Action);\nelse\n spm_dcm_erp_results(handles.DCM, Action);\nend\n\n% --- Executes on button press in initialise.\n% -------------------------------------------------------------------------\nfunction initialise_Callback(hObject, eventdata, handles)\n[f,p] = uigetfile('DCM*.mat','please select estimated DCM');\nDCM = load(fullfile(p,f), '-mat');\nhandles.DCM.M.P = DCM.DCM.Ep;\nguidata(hObject, handles);\n\n% --- Executes on button press in render.\n% -------------------------------------------------------------------------\nfunction render_Callback(hObject, eventdata, handles)\nspm_eeg_inv_visu3D_api(handles.DCM.xY.Dfile)\n\n% --- Executes on button press in Imaging.\n% -------------------------------------------------------------------------\nfunction Imaging_Callback(hObject, eventdata, handles)\nspm_eeg_inv_imag_api(handles.DCM.xY.Dfile)\n\n\n%==========================================================================\nfunction handles = Xdefault(hObject,handles,m)\n% default design matix\n% m - number of trials\nX = eye(m);\nX(:,1) = [];\nname = {};\nfor i = 1:size(X,2)\n name{i,1} = sprintf('effect %i',i);\nend\nhandles.DCM.xU.X = X;\nhandles.DCM.xU.name = name;\nset(handles.design,'String',num2str(handles.DCM.xU.X','%7.2f'));\nset(handles.Uname, 'String',handles.DCM.xU.name);\nreturn\n\n% --- Executes on button press in BMC.\n%--------------------------------------------------------------------------\nfunction BMC_Callback(hObject, eventdata, handles)\nspm_api_bmc\n\n% --- Executes on selection change in ERP.\n%--------------------------------------------------------------------------\nfunction handles = ERP_Callback(hObject, eventdata, handles)\n\n% get model type\n%--------------------------------------------------------------------------\nif get(handles.ERP,'Value') ~= 5\n Action = {\n 'ERPs (mode)',\n 'ERPs (sources)',\n 'coupling (A)',\n 'coupling (B)',\n 'coupling (C)',\n 'trial-specific effects',\n 'Input',\n 'Response',\n 'Response (image)',\n 'Dipoles',\n 'Spatial overview'};\n try\n set(handles.Nmodes, 'Value', handles.DCM.options.Nmodes);\n catch\n set(handles.Nmodes, 'Value', 8);\n end \n set(handles.Spatial_type, 'String', {'ECD','Imaging'});\n set(handles.Wavelet, 'Enable','off');\n \nelse\n Action = {\n 'Frequency modes'\n 'Time-modes'\n 'Time-frequency'\n 'Coupling (A - Hz)'\n 'Coupling (B - Hz)'\n 'Coupling (A - modes)'\n 'Coupling (B - modes)'\n 'Input (C - Hz)'\n 'Input (u - ms)'\n 'Dipoles'};\n try\n set(handles.Nmodes, 'Value', handles.DCM.options.Nmodes);\n catch\n set(handles.Nmodes, 'Value', 4);\n end\n set(handles.Spatial_type, 'Value', 1);\n set(handles.Spatial_type, 'String', {'ECD'});\n set(handles.Wavelet, 'Enable','on');\n\n\n\nend\nset(handles.results,'String',Action);\nhandles = reset_Callback(hObject, eventdata, handles);\nguidata(hObject,handles);\n\n% --- Executes on button press in Wavelet.\nfunction Wavelet_Callback(hObject, eventdata, handles)\n\n% get transform \n%--------------------------------------------------------------------------\nhandles = reset_Callback(hObject, eventdata, handles);\nhandles.DCM = spm_dcm_ind_data(handles.DCM);\n\n% and display\n%--------------------------------------------------------------------------\nspm_dcm_ind_results(handles.DCM,'Wavelet');\nguidata(hObject,handles);\n\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_ind_u.m", "ext": ".m", "path": "spm5-master/toolbox/api_erp/spm_ind_u.m", "size": 1213, "source_encoding": "utf_8", "md5": "4f09a9302079213c9fb56f5f28760353", "text": "function [U] = spm_ind_u(t,P,M)\n% returns the [scalar] input for EEG models\n% FORMAT [U] = spm_ind_u(t,P,M)\n%\n% P - parameter structure\n% P.R - input parameters\n%\n% t - PST (seconds)\n%\n% U - stimulus-related (subcortical) input\n% B - non-specifc background fluctuations\n%\n% See spm_fx_ind.m and spm_ind_priors.m\n%__________________________________________________________________________\n%\n% David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and\n% neuronal dynamics. NeuroImage 20: 1743-1755\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id$\n\n% stimulus - subcortical impulse - a gamma function\n%--------------------------------------------------------------------------\nons = M.ons(:);\ndur = M.dur*1000;\nt = t(:)';\nj = 1:length(t);\nfor i = 1:length(ons)\n m = exp(P.R(i,1))* ons(i);\n v = exp(P.R(i,2))*(dur/16)^2;\n U(i,:) = Gpdf(t*1000,m*m/v,m/v);\nend\n\nfunction f = Gpdf(x,h,l)\n%--------------------------------------------------------------------------\nQ = find(x > 0);\nf = x*0;\nf(Q) = x(Q).^(h - 1).*exp(-l*x(Q))*(l^h)/gamma(h);"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_dcm_erp_viewspatial.m", "ext": ".m", "path": "spm5-master/toolbox/api_erp/spm_dcm_erp_viewspatial.m", "size": 10583, "source_encoding": "utf_8", "md5": "5715dfb79931731bfacb87b4aec2ac32", "text": "function varargout = spm_dcm_erp_viewspatial(varargin)\n% SPM_DCM_ERP_VIEWSPATIAL M-file for spm_dcm_erp_viewspatial.fig\n% SPM_DCM_ERP_VIEWSPATIAL, by itself, creates a new SPM_DCM_ERP_VIEWSPATIAL or raises the existing\n% singleton*.\n%\n% H = SPM_DCM_ERP_VIEWSPATIAL returns the handle to a new SPM_DCM_ERP_VIEWSPATIAL or the handle to\n% the existing singleton*.\n%\n% SPM_DCM_ERP_VIEWSPATIAL('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SPM_DCM_ERP_VIEWSPATIAL.M with the given input arguments.\n%\n% SPM_DCM_ERP_VIEWSPATIAL('Property','Value',...) creates a new SPM_DCM_ERP_VIEWSPATIAL or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before spm_dcm_erp_viewspatial_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to spm_dcm_erp_viewspatial_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help spm_dcm_erp_viewspatial\n\n% Last Modified by GUIDE v2.5 12-Jul-2006 11:06:13\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @spm_dcm_erp_viewspatial_OpeningFcn, ...\n 'gui_OutputFcn', @spm_dcm_erp_viewspatial_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before spm_dcm_erp_viewspatial is made visible.\nfunction spm_dcm_erp_viewspatial_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to spm_dcm_erp_viewspatial (see VARARGIN)\n\n% Choose default command line output for spm_dcm_erp_viewspatial\nhandles.output = hObject;\n\nDCM = varargin{1};\nhandles.DCM = DCM;\nhandles.ms = DCM.xY.Time;\nhandles.T = 1;\n\nM = DCM.M;\n\nload(DCM.xY.Dfile); % ----> returns SPM/EEG struct D\nhandles.D = D;\n\n% locations for plotting\nCTF = load(fullfile(spm('dir'), 'EEGtemplates', D.channels.ctf));\nCTF.Cpos = CTF.Cpos(:, D.channels.order(D.channels.eeg));\n\nhandles.x = min(CTF.Cpos(1,:)):0.01:max(CTF.Cpos(1,:));\nhandles.y = min(CTF.Cpos(2,:)):0.01:max(CTF.Cpos(2,:));\n\n[handles.x1, handles.y1] = meshgrid(handles.x, handles.y);\nhandles.xp = CTF.Cpos(1,:)';\nhandles.yp = CTF.Cpos(2,:)';\n\nNchannels = size(CTF.Cpos, 2);\nhandles.Nchannels = Nchannels;\n\nhandles.y_proj = DCM.xY.y*DCM.M.E;\nhandles.CLim1_yp = min(min(handles.y_proj));\nhandles.CLim2_yp = max(max(handles.y_proj));\n\nhandles.Nt = size(handles.y_proj, 1);\n\n% data and model fit\nhandles.yd = NaN*ones(handles.Nt, Nchannels);\nhandles.ym = NaN*ones(handles.Nt, Nchannels);\nhandles.yd(:, DCM.M.dipfit.Ic) = handles.y_proj*DCM.M.E'; % data (back-projected to channel space)\nhandles.ym(:, DCM.M.dipfit.Ic) = cat(1,DCM.H{:})*DCM.M.E'; % model fit\n\nhandles.CLim1 = min(min([handles.yd handles.ym]));\nhandles.CLim2 = max(max([handles.yd handles.ym]));\n\n% set slider's range and initial value\nset(handles.slider1, 'min', 1);\nset(handles.slider1, 'max', handles.Nt);\nset(handles.slider1, 'Value', 1);\nset(handles.slider1, 'Sliderstep', [1/(handles.Nt-1) 10/(handles.Nt-1)]); % moves slider in dt and 10*dt steps\n\nplot_images(hObject, handles);\nplot_modes(hObject, handles);\nplot_dipoles(hObject, handles);\nplot_components_space(hObject, handles);\ntry\n plot_components_time(hObject, handles);\nend\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes spm_dcm_erp_viewspatial wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = spm_dcm_erp_viewspatial_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on slider movement.\nfunction slider1_Callback(hObject, eventdata, handles)\n% hObject handle to slider1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\n\nhandles.T = round(get(handles.slider1, 'Value'));\n\nplot_images(hObject, handles);\nplot_modes(hObject, handles);\nguidata(hObject, handles);\n\n% --- Executes during object creation, after setting all properties.\nfunction slider1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to slider1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n%--------------------------------------------------------------------\nfunction plot_images(hObject, handles)\n\nT = handles.T;\n\naxes(handles.axes1); cla\nz = griddata(handles.xp, handles.yp, handles.yd(T,:), handles.x1, handles.y1);\nsurface(handles.x, handles.y, z);\naxis off\naxis square\nshading('interp')\nhold on\nplot3(handles.xp, handles.yp, handles.yd, 'k.');\nset(handles.axes1, 'CLim', [handles.CLim1 handles.CLim2])\ntitle('data', 'FontSize', 16);\n\naxes(handles.axes2); cla\nz = griddata(handles.xp, handles.yp, handles.ym(T,:), handles.x1, handles.y1);\nsurface(handles.x, handles.y, z);\naxis off\naxis square\nshading('interp')\nhold on\nplot3(handles.xp, handles.yp, handles.ym, 'k.');\nset(handles.axes2, 'CLim', [handles.CLim1 handles.CLim2])\ntitle('model', 'FontSize', 16);\n\nguidata(hObject, handles);\n\ndrawnow\n%--------------------------------------------------------------------\nfunction plot_modes(hObject, handles)\n% plot temporal expression of modes\n\nDCM = handles.DCM;\nNt = size(DCM.xY.xy{1}, 1);\nNtrials = length(DCM.H);\n\n\nms_all = kron(ones(1, Ntrials), handles.ms);\n\n% data and model prediction, cond 1\naxes(handles.axes3); cla\nplot(ms_all, handles.y_proj);\nhold on\nplot(ms_all, cat(1, DCM.H{:}), '--');\nplot([ms_all(handles.T) ms_all(handles.T)], [handles.CLim1_yp handles.CLim2_yp], 'k', 'LineWidth', 3);\n% set(handles.axes3, 'XLim', [0 handles.ms(end)]);\nset(handles.axes3, 'YLim', [handles.CLim1_yp handles.CLim2_yp]);\nxlabel('ms');\ntitle('Temporal expressions of modes', 'FontSize', 16);\ngrid on\n\n%--------------------------------------------------------------------\nfunction plot_dipoles(hObject, handles)\n\nDCM = handles.DCM;\nNsources = length(DCM.M.pE.A{1});\n% ECD\n%--------------------------------------------------------------------\ntry\n Lpos = handles.DCM.Eg.Lpos;\n Lmom = handles.DCM.Eg.Lmom;\n \n% Imaging\n%--------------------------------------------------------------------\ncatch\n Lpos = handles.DCM.M.dipfit.L.pos;\n Lmom = Lpos*0;\nend\ntry\n elc = handles.DCM.M.dipfit.elc;\n % transform sensor locations to MNI-space\n iMt = inv(DCM.M.dipfit.Mmni2polsphere);\n elc = iMt*[elc'; ones(1, size(elc, 1))];\n elc = elc(1:3, :)';\ncatch\n elc = sparse(0,3);\nend\n\n\n\naxes(handles.axes5);\nfor j = 1:Nsources\n % plot dipoles using small ellipsoids\n [x, y, z] = ellipsoid(handles.axes5,Lpos(1,j), Lpos(2,j), Lpos(3,j), 4, 4,4);\n surf(x, y, z, 'EdgeColor', 'none', 'FaceColor', 'g');\n hold on\n \n % plot dipole moments\n plot3([Lpos(1, j) Lpos(1, j) + 5*Lmom(1, j)],...\n [Lpos(2, j) Lpos(2, j) + 5*Lmom(2, j)],...\n [Lpos(3, j) Lpos(3, j) + 5*Lmom(3, j)], 'b', 'LineWidth', 4);\n \n plot3(elc(:,1), elc(:,2), elc(:,3), 'r.','MarkerSize',18);\n\nend\nxlabel('x'); ylabel('y');\nrotate3d(handles.axes5);\n\naxis equal\n\n%--------------------------------------------------------------------\nfunction plot_components_space(hObject, handles)\n% plots spatial expression of each dipole\nDCM = handles.DCM;\nNsources = length(DCM.M.pE.A{1});\n\nlf = NaN*ones(handles.Nchannels, Nsources);\nlfo = NaN*ones(handles.Nchannels, Nsources);\nx = [0 kron([zeros(1, 8) 1], ones(1, Nsources))];\n\n% unprojected and projected leadfield\n%--------------------------------------------------------------------\nlfo(DCM.M.dipfit.Ic,:) = spm_erp_L(DCM.Ep,DCM.M);\nlf = DCM.M.E*DCM.M.E'*lfo;\n\n\n% use subplots in new figure\nh = figure;\nset(h, 'Name', 'Spatial expression of sources');\nfor j = 1:2\n for i = 1:Nsources\n if j == 1\n % projected\n handles.hcomponents{i} = subplot(2,Nsources, i);\n z = griddata(handles.xp, handles.yp, lf(:, i), handles.x1, handles.y1);\n title(DCM.Sname{i}, 'FontSize', 16);\n \n else\n % not projected\n handles.hcomponents{i} = subplot(2,Nsources, i+Nsources);\n z = griddata(handles.xp, handles.yp, lfo(:, i), handles.x1, handles.y1);\n end \n surface(handles.x, handles.y, z);\n axis off\n axis square\n shading('interp')\n % set(handles.axes1, 'CLim', [handles.CLim1 handles.CLim2])\n end\nend\n\ndrawnow\n\nfunction plot_components_time(hObject, handles)\n\nDCM = handles.DCM;\nLmom = sqrt(sum(DCM.Eg.Lmom).^2);\nNsources = length(DCM.M.pE.A{1});\n\nh = figure;\nset(h, 'Name', 'Effective source amplitudes');\n% multiply with dipole amplitudes\nfor i = 1:Nsources\n handles.hcomponents_time{2*(i-1)+1} = subplot(Nsources, 2, 2*(i-1)+1);\n plot(handles.ms, Lmom(i)*DCM.K{1}(:, i));\n title([handles.DCM.Sname{i} ', ERP 1'], 'FontSize', 16);\n \n try\n handles.hcomponents_time{2*(i-1)+2} = subplot(Nsources, 2, 2*(i-1)+2);\n plot(handles.ms, Lmom(i)*DCM.K{2}(:, i));\n title([handles.DCM.Sname{i} ', ERP 2'], 'FontSize', 16);\n end\nend\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "fieldtrip_meg_leadfield1.m", "ext": ".m", "path": "spm5-master/toolbox/api_erp/fieldtrip_meg_leadfield1.m", "size": 1920, "source_encoding": "utf_8", "md5": "1c068e18288e3095a3effb886c2fb352", "text": "function [lf] = meg_leadfield1(R, Rm, Um);\n\n% MEG_LEADFIELD1 magnetic leadfield for a dipole in a homogenous sphere\n%\n% [lf] = meg_leadfield1(R, pos, ori)\n%\n% with input arguments\n% R\t\tposition dipole\n% pos\t\tposition magnetometers\n% ori\t\torientation magnetometers\n%\n% The center of the homogenous sphere is in the origin, the field \n% of the dipole is not dependent on the sphere radius.\n%\n% This function is also implemented as MEX file.\n\n% adapted from Luetkenhoener, Habilschrift '92\n% optimized for speed using temporary variables\n% the mex implementation is a literary copy of this\n\n% Copyright (C) 2002, Robert Oostenveld\n%\n% $Log: meg_leadfield1.m,v $\n% Revision 1.5 2003/03/28 10:01:15 roberto\n% created mex implementation, updated help and comments\n%\n% Revision 1.4 2003/03/28 09:01:55 roberto\n% fixed important bug (incorrect use of a temporary variable)\n%\n% Revision 1.3 2003/03/12 08:19:45 roberto\n% improved help\n%\n% Revision 1.2 2003/03/11 14:45:37 roberto\n% updated help and copyrights\n%\n\nNchans = size(Rm, 1);\n\nlf = zeros(Nchans,3);\n\ntmp2 = norm(R);\n\nfor i=1:Nchans\n r = Rm(i,:);\n u = Um(i,:);\n\n tmp1 = norm(r);\n % tmp2 = norm(R);\n tmp3 = norm(r-R);\n tmp4 = dot(r,R);\n tmp5 = dot(r,r-R);\n tmp6 = dot(R,r-R);\n tmp7 = (tmp1*tmp2)^2 - tmp4^2;\t% cross(r,R)^2\n\n alpha = 1 / (-tmp3 * (tmp1*tmp3+tmp5));\n A = 1/tmp3 - 2*alpha*tmp2^2 - 1/tmp1;\n B = 2*alpha*tmp4;\n C = -tmp6/(tmp3^3);\n\n if tmp7MNI coordinate transformation, following definition of\n% CTF origin, and axes\n%--------------------------------------------------------------------------\n\n% origin in MNI space\n%--------------------------------------------------------------------------\nPOLorigin = mean(fid_reg(2:3, :));\nPOLvx = (fid_reg(1, :) - POLorigin)/norm((fid_reg(1, :) - POLorigin));\nPOLvz = cross(POLvx, fid_reg(2, :) - fid_reg(3, :));\nPOLvz = POLvz/norm(POLvz); % Vector normal to the NLR plane, pointing upwards\nPOLvy = cross(POLvz,POLvx); POLvy = POLvy/norm(POLvy);\n\n% transformation POL->MNI. Must be the same as computed by registration\n% (file RT).\n%--------------------------------------------------------------------------\ndipfit.Mpol2mni = [[POLvx' POLvy' POLvz' POLorigin']; [0 0 0 1]];\ndipfit.MNIelc = sen_reg;\n\n% original coordinates\n%--------------------------------------------------------------------------\nelc = inv(dipfit.Mpol2mni)*[dipfit.MNIelc'; ones(1, size(dipfit.MNIelc, 1))];\nelc = elc(1:3,:)';\n\n% centre of sphere in POL space\n%--------------------------------------------------------------------------\no = inv(dipfit.Mpol2mni)*[dipfit.vol.o_sphere'; 1];\nelc = elc - kron(ones(size(elc, 1), 1), o(1:3)');\n\n% transformation matrix from MNI-space to sphere in POL space\n%--------------------------------------------------------------------------\nMsphere = eye(4);\nMsphere(1:3,4) = -o(1:3);\ndipfit.Mpol2sphere = Msphere; % in pol-space: translation of origin to zero\ndipfit.Mmni2polsphere = Msphere*inv(dipfit.Mpol2mni); % from MNI-space to pol space (plus translation to origin)\n\n% projecting channels to outer sphere\n%--------------------------------------------------------------------------\ndist = sqrt(sum((elc).^2,2));\ndipfit.elc = dipfit.vol.r(4) * elc ./[dist dist dist];\n\nreturn\n\n\n% used for fitting sphere to sensors\n%==========================================================================\nfunction x = d_elc_sphere(x, elc, r)\n\n% returns sum of squares of distances between sensors elc and sphere.\nNelc = size(elc, 1);\nd = sqrt(sum((elc - repmat(x, Nelc, 1)).^2, 2));\nx = sum((d - r).^2);\n\nreturn\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "eeglab_dipplot.m", "ext": ".m", "path": "spm5-master/toolbox/api_erp/eeglab_dipplot.m", "size": 58861, "source_encoding": "utf_8", "md5": "c21091d730be6500d90bec825a97515b", "text": "% dipplot() - Visualize EEG equivalent-dipole locations and orientations \n% in the MNI average MRI head or in the BESA spherical head model. \n% Usage:\n% >> dipplot( sources, 'key', 'val', ...);\n% >> [sources X Y Z XE YE ZE] = dipplot( sources, 'key', 'val', ...);\n%\n% Inputs:\n% sources - structure array of dipole information: can contain\n% either BESA or DIPFIT dipole information\n% besaexent: BESA eccentricity of the dipole\n% besathloc: BESA azimuth angle of the dipole\n% besaphloc: BESA horizontal angle of the dipole\n% besathori: BESA azimuth angle of the dipole orientation\n% besaphori: BESA horiz. angle of the dipole orientation\n% posxyz: DIPFIT dipole 3-D Cartesian position in mm\n% momxyz: DIPFIT dipole 3-D Cartesian orientation\n% optional fields for BESA and DIPFIT dipole info\n% component: component number\n% rv: residual variance\n% Optional input:\n% 'rvrange' - [min max] Only plot dipoles with residual variace within the\n% given range. Default: plot all dipoles.\n% 'summary' - Build a summary plot with three views (top, back, side)\n% 'image' - ['besa'|'mri'] Background image. \n% 'mri' (or 'fullmri') uses mean-MRI brain images from the Montreal \n% Neurological Institute. This option can also contain a 3-D MRI\n% volume (dim 1: left to right; dim 2: anterior-posterior; dim 3: \n% superior-inferior). Use 'coregist' to coregister electrodes\n% with the MRI. {default: 'mri'} \n% 'coreg' - [cx cy cz scale pitch roll yaw] the electrodes coordinates are\n% rotated in 3-D using pitch (x plane), rool (y plane) and yaw\n% (z plane). They are then scaled using 'scale' and recentered to\n% 3-D coordinates [cx cy cz].\n%\n% Plotting options:\n% 'color' - [cell array of color strings or (1,3) color arrays]. For\n% exemple { 'b' 'g' [1 0 0] } gives blue, green and red. \n% Dipole colors will rotate through the given colors if\n% the number given is less than the number of dipoles to plot.\n% A single number will be used as color index in the jet colormap.\n% 'view' - 3-D viewing angle in cartesian coords.,\n% [0 0 1] gives a sagittal view, [0 -1 0] a view from the rear;\n% [1 0 0] gives a view from the side of the head.\n% 'mesh' - ['on'|'off'] Display spherical mesh. {Default is 'on'}\n% 'axistight' - ['on'|'off'] For MRI only, display the closest MRI\n% slide. {Default is 'off'}\n% 'gui' - ['on'|'off'] Display controls. {Default is 'on'} If gui 'off', \n% a new figure is not created. Useful for incomporating a dipplot \n% into a complex figure.\n% 'num' - ['on'|'off'] Display component number. Take into account\n% dipole size. {Default: 'off'}\n% 'cornermri' - ['on'|'off'] force MRI images to the corner of the MRI volume\n% (usefull when background is not black). Default: 'off'.\n% 'drawedges' - ['on'|'off'] draw edges of the 3-D MRI (black in axistight,\n% white otherwise.) Default is 'off'.\n% 'projimg' - ['on'|'off'] Project dipole(s) onto the 2-D images, for use\n% in making 3-D plots {Default 'off'}\n% 'projlines' - ['on'|'off'] Plot lines connecting dipole with 2-D projection.\n% Color is dashed black for BESA head and dashed black for the\n% MNI brain {Default 'off'}\n% 'projcol' - [color] color for the projected line {Default is same as dipole}\n% 'dipolesize' - Size of the dipole sphere(s) {Default: 30}\n% 'dipolelength' - Length of the dipole bar(s) {Default: 1}\n% 'pointout' - ['on'|'off'] Point the dipoles outward. {Default: 'off'}\n% 'sphere' - [float] radius of sphere corresponding to the skin. Default is 1.\n% 'spheres' - ['on'|'off'] {default: 'off'} plot dipole markers as 3-D spheres. \n% Does not yet interact with gui buttons, produces non-gui mode.\n% 'spheresize' - [real>0] size of spheres (if 'on'). {default: 5}\n% 'normlen' - ['on'|'off'] Normalize length of all dipoles. {Default: 'off'}\n% 'std' - [cell array] plot standard deviation of dipoles. i.e.\n% { [1:6] [7:12] } plot two elipsoids that best fit all the dipoles\n% from 1 to 6 and 7 to 12 with radius 1 standard deviation.\n% { { [1:6] 2 'linewidth' 2 } [7:12] } do the same but now the\n% first elipsoid is 2 standard-dev and the lines are thicker.\n% 'dipnames' - [cell array] cell array of string with a name for each dipole (or\n% pair of dipole).\n% Outputs:\n% sources - EEG.source structure with updated 'X', 'Y' and 'Z' fields\n% X,Y,Z - Locations of dipole heads (Cartesian coordinates). If there is\n% more than one dipole per components, the last dipole is returned.\n% XE,YE,ZE - Locations of dipole ends (Cartesian coordinates). The same\n% remark as above applies.\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 1st July 2002\n%\n% Notes: Visualized locations are not exactly the same as in BESA (because of\n% manual tuning of the size of the head textures). Because of a bug in the \n% Matlab warp() function, the side-view texture cannot be displayed. \n% To diplay head textures, the files 'besarear.pcx' and 'besasagittal.pcx' \n% are required. The Matlab image processing toolbox is also required.\n%\n% Example:\n% % position and orientation of the first dipole\n% sources(1).besaexent= 69.036;\n% sources(1).besathloc= -26.71;\n% sources(1).besaphloc= 19.702;\n% sources(1).besathori= -80.02;\n% sources(1).besaphori= 87.575;\n% sources(1).rv = 0.1;\n% % position and orientation of the second dipole\n% sources(2).besaexent= 69.036;\n% sources(2).besathloc= 46;\n% sources(2).besaphloc= 39;\n% sources(2).besathori= 150;\n% sources(2).besaphori= -3;\n% sources(2).rv = 0.05;\n% % plot of the two dipoles (first in green, second in blue)\n% dipplot( sources, 'color', { 'g' 'b' }); \n%\n% % To make a stereographic plot\n% figure; \n% subplot(1,2,1); dipplot( sources, 'view', [43 10], 'gui', 'off');\n% subplot(1,2,2); dipplot( sources, 'view', [37 10], 'gui', 'off');\n%\n% % To make a summary plot\n% dipplot( sources, 'summary', 'on', 'dipolesize', 15, 'mesh', 'off');\n%\n% See also: eeglab(), dipfit()\n\n%123456789012345678901234567890123456789012345678901234567890123456789012\n\n% Copyright (C) 2002 Arnaud Delorme\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n% README -- Plotting strategy:\n% - All buttons have a tag 'tmp' so they can be removed\n% - The component-number buttons have 'userdata' equal to 'editor' and \n% can be found easily by other buttons find('userdata', 'editor')\n% - All dipoles have a tag 'dipoleX' (X=their number) and can be made \n% visible/invisible\n% - The gcf object 'userdat' field stores the handle of the dipole that \n% is currently being modified\n% - Gca 'userdata' stores imqge names and position\n\n%$Log: dipplot.m,v $\n%Revision 1.104 2004/11/20 02:32:43 scott\n%help msg edits: carthesian -> Cartesian\n%\n%Revision 1.103 2004/11/11 02:34:15 arno\n%fixing dipnames\n%\n%Revision 1.102 2004/11/11 02:11:16 arno\n%dipname -> dipnames\n%\n%Revision 1.101 2004/11/11 01:40:39 arno\n%new dipnames option\n%\n%Revision 1.100 2004/06/15 17:57:06 arno\n%do not know\n%\n%Revision 1.99 2004/06/11 00:16:12 arno\n%change light\n%\n%Revision 1.98 2004/06/09 21:15:01 arno\n%debug projcol\n%\n%Revision 1.97 2004/06/09 21:12:34 arno\n%fixing projcolor\n%\n%Revision 1.96 2004/06/09 16:27:11 arno\n%color debug\n%\n%Revision 1.95 2004/06/02 22:47:38 arno\n%debug color\n%\n%Revision 1.94 2004/06/02 22:44:03 arno\n%projection color decoding\n%\n%Revision 1.93 2004/06/02 22:15:42 arno\n%debug color problem\n%\n%Revision 1.92 2004/06/01 20:37:01 arno\n%fixing projection color\n%\n%Revision 1.91 2004/06/01 18:48:31 arno\n%fixing spheres\n%\n%Revision 1.90 2004/06/01 16:53:35 scott\n%spherecolor now works (undocumented) but gives weird color palette ??\n%\n%Revision 1.89 2004/06/01 15:48:50 scott\n%sphere colors\n%\n%Revision 1.88 2004/06/01 05:03:41 scott\n%sphere color\n%\n%Revision 1.87 2004/06/01 01:06:28 scott\n%still puzzling about spheres colors ...\n%\n%Revision 1.86 2004/05/13 18:57:48 arno\n%plot middle of two dipoles\n%\n%Revision 1.85 2004/05/10 14:37:59 arno\n%image type\n%\n%Revision 1.84 2004/05/05 15:25:41 scott\n%typo\n%\n%Revision 1.83 2004/05/05 15:24:50 scott\n%typo\n%,\n%\n%Revision 1.82 2004/05/05 15:24:00 scott\n%working on sphere coloring -> ????????\n%\n%Revision 1.81 2004/05/05 01:17:27 scott\n%added spheresize\n%\n%Revision 1.80 2004/05/05 00:52:11 scott\n%dipole length 0 + 'spheres' again...\n%\n%Revision 1.79 2004/05/04 17:04:22 scott\n%test for s1, p1 if spheres on\n%\n%Revision 1.78 2004/05/04 05:37:26 scott\n%turn off 'spheres' cylinder plotting if g.dipolelenth == 0\n%\n%Revision 1.77 2004/04/30 18:48:53 scott\n%made default image 'mri' - debugged spheres/cylinders\n%\n%Revision 1.76 2004/04/29 15:35:32 scott\n%adding cylinders for spheres pointers\n%\n%Revision 1.75 2004/04/14 01:40:32 scott\n%hid 'spheres' option\n%\n%Revision 1.74 2004/04/13 18:24:58 scott\n%nothing\n%\n%Revision 1.73 2004/04/12 23:40:50 arno\n%nothing\n%\n%Revision 1.72 2004/03/26 01:39:04 arno\n%only plotting active dipoles\n%\n%Revision 1.71 2004/03/26 01:22:20 arno\n%mricorner with tightview\n%\n%Revision 1.70 2004/03/26 00:57:17 arno\n%read custom mri\n%\n%Revision 1.69 2004/02/27 19:13:25 arno\n%nothing\n%\n%Revision 1.68 2004/02/23 19:17:00 arno\n%remove debug msg\n%\n%Revision 1.67 2004/02/23 19:16:16 arno\n%fixing 2 dipole problem\n%\n%Revision 1.66 2004/02/23 19:09:05 arno\n%*** empty log message ***\n%\n%Revision 1.65 2004/01/28 15:26:14 arno\n%detecting empty dipoles\n%\n%Revision 1.64 2003/11/05 20:30:51 arno\n%nothing\n%\n%Revision 1.63 2003/11/05 18:50:28 arno\n%nothing\n%\n%Revision 1.62 2003/10/31 23:29:29 arno\n%dicreases dipole size for summary mode\n%\n%Revision 1.61 2003/10/31 19:50:38 arno\n%reordering 2 dipoles, delete old edges\n%\n%Revision 1.60 2003/10/31 18:59:41 arno\n%divide rvrange by 100\n%\n%Revision 1.59 2003/10/30 03:25:17 arno\n%adding projection lines\n%\n%Revision 1.58 2003/10/29 23:44:38 arno\n%don't know\n%\n%Revision 1.57 2003/10/27 18:50:06 arno\n%adding edges\n%\n%Revision 1.56 2003/10/09 01:02:12 arno\n%nothing\n%\n%Revision 1.55 2003/09/11 00:53:04 arno\n%same\n%\n%Revision 1.54 2003/09/11 00:52:38 arno\n%documenting new arg cornermri\\\n%\n%Revision 1.53 2003/09/11 00:51:19 arno\n%adding new param cornermri\n%\n%Revision 1.52 2003/08/13 00:46:07 arno\n%*** empty log message ***\n%\n%Revision 1.51 2003/08/04 21:29:06 arno\n%scale besa for summary plot\n%\n%Revision 1.50 2003/08/04 21:15:54 arno\n%num color on MRI\n%\n%Revision 1.49 2003/08/04 19:08:09 arno\n%\u001b[Afixing normlen in summarize mode\n%\n%Revision 1.48 2003/07/31 23:37:07 arno\n%adding property to structure attatched to dipole\n%\n%Revision 1.47 2003/07/31 23:30:05 arno\n%*** empty log message ***\n%\n%Revision 1.46 2003/07/24 17:08:03 arno\n%making component number for dipfit\n%\n%Revision 1.45 2003/07/22 01:10:06 arno\n%*** empty log message ***\n%\n%Revision 1.44 2003/07/21 22:04:09 arno\n%debug for Matlab 5.3\n%\n%Revision 1.43 2003/07/21 21:55:14 arno\n%fixing MNI brain for distribution\n%\n%Revision 1.42 2003/07/16 18:39:14 arno\n%nothing\n%\n%Revision 1.41 2003/07/03 00:02:43 arno\n%undo last change\n%\n%Revision 1.40 2003/07/02 23:48:56 arno\n%changing outputs\n%\n%Revision 1.39 2003/07/02 23:38:58 arno\n%debuging projections and summary\n%\n%Revision 1.38 2003/07/01 23:52:50 arno\n%test for sphere 1 before renormalizing\n%\n%Revision 1.37 2003/07/01 23:49:21 arno\n%try to implement contextual menu: does not work in 3-D\n%\n%Revision 1.36 2003/07/01 22:10:14 arno\n%debuging for 2 dipoles/component\n%\n%Revision 1.35 2003/07/01 19:04:13 arno\n%fixing view problem\n%\n%Revision 1.34 2003/07/01 00:21:18 arno\n%implementing 3-D MNI volume\n%\n%Revision 1.33 2003/06/12 23:49:56 arno\n%dipplot normalization\n%\n%Revision 1.32 2003/06/10 19:04:11 arno\n%nothing\n%\n%Revision 1.31 2003/06/03 16:37:16 arno\n%tag images\n%\n%Revision 1.30 2003/05/30 17:16:22 arno\n%nothing\n%\n%Revision 1.29 2003/05/30 17:09:00 arno\n%for index = 1:size(x, 2);\n% dipstruct(index).posxyz = [x(index) y(index) z(index)];\n% %dipstruct(index).posxyz = tmp(index).posxyz;\n% dipstruct(index).momxyz = [1 1 1];\n% dipstruct(index).component = index;\n% dipstruct(index).rv = 0.1;\n%end;\n%dipplot(dipstruct);\n%making xyz output compatible\n%\n%Revision 1.28 2003/05/30 16:06:27 arno\n%nothing\n%\n%Revision 1.27 2003/05/14 21:36:36 arno\n%nothing\n%\n%Revision 1.26 2003/04/30 18:42:07 arno\n%calibrating roughtly the slice selection\n%\n%Revision 1.25 2003/04/30 16:19:28 arno\n%calibrating infants\n%\n%Revision 1.24 2003/04/30 02:05:24 arno\n%changing axis properties for images\n%\n%Revision 1.23 2003/04/30 01:31:53 arno\n%infant option\n%\n%Revision 1.22 2003/04/23 18:35:11 arno\n%allow to plot elipses\n%\n%Revision 1.21 2003/04/22 21:18:44 arno\n%standard dev\n%\n%Revision 1.20 2003/04/19 01:15:07 arno\n%debugging 2 besa dipoles\n%\n%Revision 1.19 2003/04/19 00:55:53 arno\n%correct normalized dipole length\n%\n%Revision 1.18 2003/04/19 00:46:41 arno\n%correcting projection\n%\n%Revision 1.17 2003/04/19 00:37:43 arno\n%changing dipole size for BESA\n%\n%Revision 1.16 2003/04/11 17:26:45 arno\n%accurate plotting in fullMRI\n%\n%Revision 1.15 2003/04/10 17:37:18 arno\n%multi layer MRI plot\n%\n%Revision 1.14 2003/03/14 17:06:42 arno\n%adding error message if plotting non-BESA dipoles on the BESA head model\n%\n%Revision 1.13 2003/03/14 02:11:33 arno\n%automatic scaling for dipfit\n%\n%Revision 1.12 2003/03/11 23:33:27 arno\n%typo\n%\n%Revision 1.11 2003/03/11 23:27:09 arno\n%adding normlen parameter\n%\n%Revision 1.10 2003/03/11 01:20:32 arno\n%updating default besaextori, debuging summary\n%\n%Revision 1.9 2003/03/07 00:32:53 arno\n%debugging textforgui\n%\n%Revision 1.8 2003/03/06 17:01:10 arno\n%textgui -> textforgui\n%\n%Revision 1.7 2003/03/06 16:50:08 arno\n%adding log message\n%\n\nfunction [outsources, XX, YY, ZZ, XO, YO, ZO] = dipplot( sourcesori, varargin )\n \n DEFAULTVIEW = [0 0 1];\n \n if nargin < 1\n help dipplot;\n return;\n end;\n \n % reading and testing arguments\n % -----------------------------\n sources = sourcesori;\n if ~isstruct(sources)\n updatedipplot(sources(1)); \n % sources countain the figure handler\n return\n end;\n \n % key type range default\n g = finputcheck( varargin, { 'color' '' [] [];\n 'axistight' 'string' { 'on' 'off' } 'off';\n 'coreg' 'real' [] [];\n 'drawedges' 'string' { 'on' 'off' } 'off';\n 'mesh' 'string' { 'on' 'off' } 'off';\n 'gui' 'string' { 'on' 'off' } 'on';\n 'summary' 'string' { 'on' 'off' } 'off';\n 'view' 'real' [] [0 0 1];\n 'rvrange' 'real' [0 Inf] [];\n 'normlen' 'string' { 'on' 'off' } 'off';\n 'num' 'string' { 'on' 'off' } 'off';\n 'cornermri' 'string' { 'on' 'off' } 'off';\n 'std' 'cell' [] {};\n 'dipnames' 'cell' [] {};\n 'projimg' 'string' { 'on' 'off' } 'off';\n 'projcol' '' [] [];\n 'projlines' 'string' { 'on' 'off' } 'off';\n 'pointout' 'string' { 'on' 'off' } 'off';\n 'dipolesize' 'real' [0 Inf] 30;\n 'dipolelength' 'real' [0 Inf] 1;\n 'sphere' 'real' [0 Inf] 1;\n 'spheres' 'string' {'on' 'off'} 'off';\n 'links' 'real' [] [];\n 'image' { 'string' 'real'} [] 'mri' }, ...\n 'dipplot');\n if isstr(g), error(g); end;\n g.zoom = 1500;\n\n % axis image and limits\n % ---------------------\n dat.mode = g.image;\n dat.maxcoord = [ 90 100 100 ]; % location of images in 3-D, Z then Y then X\n dat.axistight = strcmpi(g.axistight, 'on');\n dat.drawedges = g.drawedges;\n dat.coreg = g.coreg;\n dat.cornermri = strcmpi(g.cornermri, 'on');\n radius = 85;\n if isstr(g.image) & strcmpi(g.image, 'besa')\n scaling = 1.05;\n \n % read besa images\n % ----------------\n warning off; imgt = double(imread('besatop.pcx' ))/255; warning on;\n warning off; imgc = double(imread('besarear.pcx'))/255; warning on;\n warning off; imgs = double(imread('besaside.pcx'))/255; warning on;\n dat.imgs = { imgt imgc imgs };\n \n allcoords1 = ([-1.12 1.12]*size(imgt,2)/200+0.01)*radius; \n allcoords2 = ([-1.12 1.12]*size(imgt,1)/200+0.08)*radius;\n allcoords3 = [-1.12 1.12]*size(imgs,1)/200*radius; \n dat.imgcoords = { allcoords3 allcoords2 allcoords1 };\n\n valinion = [ 1 0 0 ]*radius;\n valnasion = [-1 0 0 ]*radius;\n vallear = [ 0 -1 0 ]*radius;\n valrear = [ 0 1 0 ]*radius;\n valvertex = [ 0 0 1 ]*radius;\n dat.tcparams = { valinion valnasion vallear valrear valvertex 0 };\n\n %dat.imageaxis = { -1 1 -1 };\n %dat.imageoffset = { [0.0 0.08 NaN ] [0.01 NaN -0.01] [ NaN -0.01 -0.025 ] };\n %dat.imagemult = { 1.01 1.06 0.96 };\n %dat.axislim = [-1.2 1.2 -1.2 1.2 -1.2 1.2];\n COLORMESH = [.5 .5 .5];\n BACKCOLOR = 'w';\n elseif isstr(g.image)\n fid = fopen('VolumeMNI.bin', 'rb', 'ieee-le');\n if fid == -1\n error('Cannot find MRI data file');\n end;\n V = double(fread(fid, [108 129*129], 'uint8'))/255;\n V = reshape(V, 108, 129, 129);\n fclose(fid);\n \n %V = floatread('VolumeMNI.fdt');\n %load('/home/arno/matlab/MNI/VolumeMNI.mat');\n \n dat.imgs = V; %smooth3(V,'gaussian', [3 3 3]);\n coordinc = 2; % 2 mm\n allcoords1 = [0.5:coordinc:size(V,1)*coordinc]-size(V,1)/2*coordinc; \n allcoords2 = [0.5:coordinc:size(V,2)*coordinc]-size(V,2)/2*coordinc;\n allcoords3 = [0.5:coordinc:size(V,3)*coordinc]-size(V,3)/2*coordinc;\n \n dat.imgcoords = { allcoords3 allcoords2 allcoords1 };\n if strcmpi(g.cornermri, 'on') % make the corner of the MRI volume match\n dat.maxcoord = [max(dat.imgcoords{1}) max(dat.imgcoords{2}) max(dat.imgcoords{3})];\n end;\n\n COLORMESH = 'w';\n BACKCOLOR = 'k';\n %valinion = [ 58.5413 -10.5000 -30.8419 ]*2;\n %valnasion = [-56.8767 -10.5000 -30.9566 ]*2;\n %vallear = [ 0.1040 -59.0000 -30.9000 ]*2;\n %valrear = [ 0.1040 38.0000 -30.9000 ]*2;\n %valvertex = [ 0.0238 -10.5000 49.8341 ]*2;\n valinion = [ 52.5413 -10.5000 -30.8419 ]*2;\n valnasion = [-50.8767 -10.5000 -30.9566 ]*2;\n vallear = [ 0.1040 -51.0000 -30.9000 ]*2;\n valrear = [ 0.1040 31.0000 -30.9000 ]*2;\n valvertex = [ 0.0238 -10.5000 40.8341 ]*2;\n zoffset = 27.1190/(27.1190+radius) * (valvertex(3)-vallear(3));\n dat.tcparams = { valinion valnasion vallear valrear valvertex zoffset };\n \n %plotimgs(IMAGESLOC, IMAGESOFFSET, IMAGESMULT, IMAGESAXIS, AXISLIM, [57 85 65]);\n %view(30, 45); axis equal; return;\n else % custom MRI\n \n V = -g.image;\n dat.imgs = -g.image; %smooth3(V,'gaussian', [3 3 3]);\n valinion = [ 56.5413 0.000 -20.8419 ]*3.5;\n valnasion = [-52.8767 0.000 -20.9566 ]*3.5;\n vallear = [ -3.1040 -53.0000 -20.9000 ]*3.5;\n valrear = [ -3.1040 33.0000 -20.9000 ]*3.5;\n valvertex = [ 0.0238 -10.5000 50.8341 ]*3.5;\n zoffset = 27.1190/(27.1190+radius) * (valvertex(3)-vallear(3));\n dat.tcparams = { valinion valnasion vallear valrear valvertex zoffset };\n dat.coreg = [];\n coordinc = 2; % 2 mm\n allcoords1 = [0.5:coordinc:size(V,1)*coordinc]-size(V,1)/2*coordinc; \n allcoords2 = [0.5:coordinc:size(V,2)*coordinc]-size(V,2)/2*coordinc;\n allcoords3 = [0.5:coordinc:size(V,3)*coordinc]-size(V,3)/2*coordinc;\n dat.imgcoords = { allcoords3 allcoords2 allcoords1 };\n if strcmpi(g.cornermri, 'on') % make the corner of the MRI volume match\n dat.maxcoord = [max(dat.imgcoords{1}) max(dat.imgcoords{2}) max(dat.imgcoords{3})];\n end;\n\n COLORMESH = 'w';\n BACKCOLOR = 'k'; \n end;\n\n % point 0\n % -------\n [xx yy zz] = transcoords(0,0,0, dat.tcparams, dat.coreg);\n dat.zeroloc = [ xx yy zz ];\n \n % conversion\n % ----------\n if strcmpi(g.normlen, 'on')\n if isfield(sources, 'besaextori')\n sources = rmfield(sources, 'besaextori'); \n end;\n end;\n if ~isfield(sources, 'besathloc') & strcmpi(g.image, 'besa') & ~is_sccn\n error(['For copyright reasons, it is not possible to use the BESA ' ...\n 'head model to plot non-BESA dipoles']);\n end;\n \n if isfield(sources, 'besathloc')\n sources = convertbesaoldformat(sources);\n end;\n if ~isfield(sources, 'posxyz')\n sources = computexyzforbesa(sources);\n end; \n if ~isfield(sources, 'component')\n disp('No component indices, making incremental ones...');\n for index = 1:length(sources)\n sources(index).component = index;\n end;\n end; \n\n % normalize position to unit sphere\n % ---------------------------------\n maxi = 0;\n for index = 1:length(sources)\n maxi = max(maxi,max(abs(sources(index).posxyz(:))));\n end;\n if maxi > 1.01 & g.sphere == 1\n disp('Non-normalized dipole positions, normalizing by standard head radius 85 mm'); \n g.sphere = 85;\n fact = 0.1;\n else \n fact = 1;\n end;\n \n % find non-empty sources\n % ----------------------\n noempt = cellfun('isempty', { sources.posxyz } );\n sources = sources( find(~noempt) );\n \n % transform coordinates\n % ---------------------\n outsources = sources;\n for index = 1:length(sources)\n sources(index).posxyz = sources(index).posxyz/g.sphere;\n tmp = sources(index).posxyz(:,1);\n sources(index).posxyz(:,1) = sources(index).posxyz(:,2);\n sources(index).posxyz(:,2) = -tmp;\n sources(index).momxyz = sources(index).momxyz/g.sphere*0.05*fact;\n tmp = sources(index).momxyz(:,1);\n sources(index).momxyz(:,1) = sources(index).momxyz(:,2);\n sources(index).momxyz(:,2) = -tmp;\n if isfield(sources, 'stdX')\n tmp = sources(index).stdX;\n sources(index).stdX = sources(index).stdY;\n sources(index).stdY = -tmp;\n end;\n if strcmpi(g.normlen, 'on')\n warning off;\n sources(index).momxyz(1,:) = 0.2*sources(index).momxyz(1,:)/ norm(abs(sources(index).momxyz(1,:)));\n if size(sources(index).momxyz,1) > 1 & sources(index).momxyz(1) ~= 0\n sources(index).momxyz(2,:) = 0.2*sources(index).momxyz(2,:)/ norm(abs(sources(index).momxyz(2,:)));\n end;\n warning on;\n end;\n end;\n \n % remove sources with out of bound Residual variance\n % --------------------------------------------------\n if isfield(sources, 'rv') & ~isempty(g.rvrange)\n for index = length(sources):-1:1\n if sources(index).rv < g.rvrange(1)/100 | sources(index).rv > g.rvrange(2)/100\n sources(index) = [];\n end;\n end;\n end;\n \n % color array\n % -----------\n if isempty(g.color)\n g.color = { 'g' 'b' 'r' 'm' 'c' 'y' };\n if strcmp(BACKCOLOR, 'w'), g.color = { g.color{:} 'k' }; end;\n end;\n g.color = g.color(mod(0:length(sources)-1, length(g.color)) +1);\n if ~isempty(g.color)\n g.color = strcol2real( g.color, jet(64) );\n end;\n if ~isempty(g.projcol)\n g.projcol = strcol2real( g.projcol, jet(64) );\n g.projcol = g.projcol(mod(0:length(sources)-1, length(g.projcol)) +1); \n else\n g.projcol = g.color;\n for index = 1:length(g.color)\n g.projcol{index} = g.projcol{index}/2;\n end;\n end;\n \n % build summarized figure\n % -----------------------\n if strcmp(g.summary, 'on')\n figure;\n options = { 'gui', 'off', 'dipolesize', g.dipolesize/1.5,'dipolelength', g.dipolelength, 'sphere', g.sphere ...\n 'color', g.color, 'mesh', g.mesh, 'num', g.num, 'image', g.image 'normlen' g.normlen };\n axes('position', [0 0 0.5 0.5]); dipplot(sourcesori, 'view', [1 0 0] , options{:}); axis off; if strcmpi(g.image, 'besa'), scalegca(0.1); end;\n axes('position', [0 0.5 0.5 .5]); dipplot(sourcesori, 'view', [0 0 1] , options{:}); axis off; if strcmpi(g.image, 'besa'), scalegca(0.1); end;\n axes('position', [.5 .5 0.5 .5]); dipplot(sourcesori, 'view', [0 -1 0], options{:}); axis off; if strcmpi(g.image, 'besa'), scalegca(0.1); end;\n axes('position', [0.5 0 0.5 0.5]); \n %p = get(gcf, 'position');\n %p(2) = p(2)+p(4)-800;\n %p(4) = 800;\n %p(3) = 800;\n %set(gcf, 'position', p);\n colorcount = 1;\n if isfield(sources, 'component')\n for index = 1:length(sources)\n if index~=1 \n if sources(index).component ~= sources(index-1).component\n if isempty(g.dipnames)\n textforgui(colorcount) = { sprintf('Component %d (R.V. %3.2f)', ...\n sources(index).component, 100*sources(index).rv) };\n else\n textforgui(colorcount) = { sprintf('%s (R.V. %3.2f)', ...\n g.dipnames{index}, 100*sources(index).rv) };\n end;\n colorcount = colorcount+1;\n end;\n else \n if isempty(g.dipnames)\n textforgui(colorcount) = { sprintf( 'Component %d (R.V. %3.2f)', ...\n sources(index).component, 100*sources(index).rv) };\n else\n textforgui(colorcount) = { sprintf('%s (R.V. %3.2f)', ...\n g.dipnames{index}, 100*sources(index).rv) };\n end;\n colorcount = colorcount+1;\n end;\n end;\n colorcount = colorcount-1;\n allstr = strvcat(textforgui{:});\n h = text(0,0.5, allstr);\n if colorcount >= 15, set(h, 'fontsize', 8);end;\n if colorcount >= 20, set(h, 'fontsize', 6);end;\n if strcmp(BACKCOLOR, 'k'), set(h, 'color', 'w'); end;\n end;\n axis off;\n return;\n end;\n \n % plot head graph in 3D\n % ---------------------\n if strcmp(g.gui, 'on')\n figure; \n pos = get(gca, 'position');\n set(gca, 'position', [pos(1)+0.05 pos(2:end)]);\n end;\n plotimgs( dat, [1 1 1]);\n \n set(gca, 'color', BACKCOLOR);\n %warning off; a = imread('besaside.pcx'); warning on;\n % BECAUSE OF A BUG IN THE WARP FUNCTION, THIS DOES NOT WORK (11/02)\n %hold on; warp([], wy, wz, a);\n % set camera target \n % -----------------\n \n % format axis (BESA or MRI)\n axis equal;\n set(gca, 'cameraviewanglemode', 'manual'); % disable change size\n camzoom(1.2^2);\n view(g.view);\n %set(gca, 'cameratarget', dat.zeroloc); % disable change size\n %set(gca, 'cameraposition', dat.zeroloc+g.view*g.zoom); % disable change size\n axis off;\n \n % plot sphere mesh and nose\n % -------------------------\n SPHEREGRAIN = 20; % 20 is Matlab default\n [x y z] = sphere(SPHEREGRAIN);\n hold on; \n [xx yy zz] = transcoords(x, y, z, dat.tcparams, dat.coreg);\n if strcmpi(COLORMESH, 'w')\n hh = mesh(xx, yy, zz, 'cdata', ones(21,21,3), 'tag', 'mesh'); hidden off;\n else\n hh = mesh(xx, yy, zz, 'cdata', zeros(21,21,3), 'tag', 'mesh'); hidden off;\n end;\n %x = x*100*scaling; y = y*100*scaling; z=z*100*scaling;\n %h = line(xx,yy,zz); set(h, 'color', COLORMESH, 'linestyle', '--', 'tag', 'mesh');\n %h = line(xx,zz,yy); set(h, 'color', COLORMESH, 'linestyle', '--', 'tag', 'mesh');\n %h = line([0 0;0 0],[-1 -1.2; -1.2 -1], [-0.3 -0.7; -0.7 -0.7]);\n %set(h, 'color', COLORMESH, 'linewidth', 3, 'tag', 'noze');\n \n % determine max length if besatextori exist\n % -----------------------------------------\n sizedip = [];\n for index = 1:length(sources)\n sizedip = [ sizedip sources(index).momxyz(3) ]; \n end;\n maxlength = max(sizedip);\n \n % diph = gca; % DEBUG\n % colormap('jet');\n % cbar\n % axes(diph);\n\n for index = 1:length(sources)\n nbdip = 1;\n if size(sources(index).posxyz, 1) > 1 & any(sources(index).posxyz(2,:)) nbdip = 2; end;\n \n % reorder dipoles for plotting\n if nbdip == 2\n if sources(index).posxyz(1,1) > sources(index).posxyz(2,1)\n tmp = sources(index).posxyz(2,:);\n sources(index).posxyz(2,:) = sources(index).posxyz(1,:);\n sources(index).posxyz(1,:) = tmp;\n tmp = sources(index).momxyz(2,:);\n sources(index).momxyz(2,:) = sources(index).momxyz(1,:);\n sources(index).momxyz(1,:) = tmp;\n end;\n if isfield(sources, 'active'),\n nbdip = length(sources(index).active);\n end;\n end;\n \n for dip = 1:nbdip\n \n x = sources(index).posxyz(dip,1);\n y = sources(index).posxyz(dip,2);\n z = sources(index).posxyz(dip,3);\n xo = sources(index).momxyz(dip,1)*g.dipolelength;\n yo = sources(index).momxyz(dip,2)*g.dipolelength;\n zo = sources(index).momxyz(dip,3)*g.dipolelength;\n \n % copy for output\n % ---------------\n XX(index) = -y;\n YY(index) = x;\n ZZ(index) = z;\n XO(index) = -yo;\n YO(index) = xo;\n ZO(index) = zo;\n \n if abs([x+xo,y+yo,z+zo]) >= abs([x,y,z])\n xo1 = x+xo;\n yo1 = y+yo;\n zo1 = z+zo;\n elseif strcmpi(g.pointout,'on')\n xo1 = x-xo; % make dipole point outward from head center\n yo1 = y-yo;\n zo1 = z-zo; \n else\n xo1 = x+xo;\n yo1 = y+yo;\n zo1 = z+zo;\n end\n x = -x; xo1 = -xo1; \n y = -y; yo1 = -yo1; \n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw dipole bar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n tag = [ 'dipole' num2str(index) ];\n [xx yy zz] = transcoords(x, y, z, dat.tcparams, dat.coreg); \n [xxo1 yyo1 zzo1] = transcoords(xo1, yo1, zo1, dat.tcparams, dat.coreg); \n\n if ~strcmpi(g.spheres,'on') % plot dipole direction lines\n h1 = line( [xx xxo1]', [yy yyo1]', [zz zzo1]');\n\n elseif g.dipolelength>0 % plot dipole direction cylinders with end cap patch\n disp('Cannot plot bar with sphere');\n %thetas = 180/pi*atan(sqrt((xxo1-xx).^2+(yyo1-yy).^2)./(zzo1-zz));\n %for k=1:length(xx)\n % [cx cy cz] = cylinder([1 1 1],SPHEREGRAIN);\n % % rotate(h1,[yy(k)-yyo1(k) xxo1(k)-xx(k) 0],thetas(k));\n % cx = cx*g.spheresize/3 + xx(k);\n % cy = cy*g.spheresize/3 + yy(k);\n % cz = cz*g.dipolelength + zz(k);\n % caxis([0 33])\n % cax =caxis;\n % s1 = surf(cx,cy,cz); % draw the 3-D cylinder\n % set(s1,'cdatamapping','direct','FaceColor','r'); % tries to make cylinder red - doesnt work!?!\n % p1 = patch(cx(end,:),cy(end,:),cz(end,:),cax(2)*ones(size(cz(end,:)))); \n %end\n end\n\n dipstruct.pos3d = [xx yy zz]; % value used for fitting MRI\n dipstruct.posxyz = sources(index).posxyz; % value used for other purposes\n if isempty(g.dipnames)\n dipstruct.rv = sprintf('C %d (%3.2f)',sources(index).component,...\n sources(index).rv*100);\n else\n dipstruct.rv = sprintf('%s (%3.2f)',g.dipnames{index}, sources(index).rv*100);\n end;\n if ~strcmpi(g.spheres,'on') % plot disk markers\n set(h1,'userdata',dipstruct,'tag',tag,'color','k','linewidth',g.dipolesize/7.5);\n if strcmp(BACKCOLOR, 'k'), set(h1, 'color', g.color{index}); end;\n end\n \n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw sphere or disk marker %%%%%%%%%%%%%%%%%%%%%%%%%\n %\n hold on;\n if strcmpi(g.spheres,'on') % plot spheres\n if strcmpi(g.projimg, 'on')\n tmpcolor = g.color{index} / 2;\n h = plotsphere([xx yy zz], g.dipolesize/6, 'color', g.color{index}, 'proj', ...\n [-dat.maxcoord(3) dat.maxcoord(2) -dat.maxcoord(1)]*97/100, 'projcol', tmpcolor);\n set(h(2:end), 'userdata', 'proj', 'tag', tag);\n else\n h = plotsphere([xx yy zz], g.dipolesize/6, 'color', g.color{index});\n end; \n set(h(1), 'userdata', dipstruct, 'tag', tag);\n else % plot dipole markers\n h = plot3(xx, yy, zz); \n set(h, 'userdata', dipstruct, 'tag', tag, ...\n 'marker', '.', 'markersize', g.dipolesize, 'color', g.color{index});\n end\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% project onto images %%%%%%%%%%%%%%%%%%%%%%%%%\n %\n if strcmpi(g.projimg, 'on') & strcmpi(g.spheres, 'off')\n tmpcolor = g.projcol{index};\n \n % project onto z axis\n tag = [ 'dipole' num2str(index) ];\n if ~strcmpi(g.image, 'besa')\n h = line( [xx xxo1]', [yy yyo1]', [-1 -1]'*dat.maxcoord(1));\n set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize/7.5);\n end;\n if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;\n h = plot3(xx, yy, -dat.maxcoord(1)); \n set(h, 'userdata', 'proj', 'tag', tag, ...\n 'marker', '.', 'markersize', g.dipolesize, 'color', tmpcolor);\n \n % project onto x axis\n tag = [ 'dipole' num2str(index) ];\n if ~strcmpi(g.image, 'besa')\n h = line( [xx xxo1]', [1 1]'*dat.maxcoord(2), [zz zzo1]');\n set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize/7.5);\n end;\n if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;\n h = plot3(xx, dat.maxcoord(2), zz); \n set(h, 'userdata', 'proj', 'tag', tag, ...\n 'marker', '.', 'markersize', g.dipolesize, 'color', tmpcolor);\n \n % project onto y axis\n tag = [ 'dipole' num2str(index) ];\n if ~strcmpi(g.image, 'besa')\n h = line( [-1 -1]'*dat.maxcoord(3), [yy yyo1]', [zz zzo1]');\n set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize/7.5);\n end;\n if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;\n h = plot3(-dat.maxcoord(3), yy, zz); \n set(h, 'userdata', 'proj', 'tag', tag, ...\n 'marker', '.', 'markersize', g.dipolesize, 'color', tmpcolor);\n end;\n\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% project onto axes %%%%%%%%%%%%%%%%%%%%%%%%%\n %\n if strcmpi(g.projlines, 'on') \n clear h;\n % project onto z axis\n tag = [ 'dipole' num2str(index) ];\n h(1) = line( [xx xx]', [yy yy]', [zz -dat.maxcoord(1)]');\n set(h(1), 'userdata', 'proj', 'linestyle', '--', ...\n 'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize/7.5/5);\n \n % project onto x axis\n tag = [ 'dipole' num2str(index) ];\n h(2) = line( [xx xx]', [yy dat.maxcoord(2)]', [zz zz]');\n set(h(2), 'userdata', 'proj', 'linestyle', '--', ...\n 'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize/7.5/5);\n \n % project onto y axis\n tag = [ 'dipole' num2str(index) ];\n h(3) = line( [xx -dat.maxcoord(3)]', [yy yy]', [zz zz]');\n set(h(3), 'userdata', 'proj', 'linestyle', '--', ...\n 'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize/7.5/5);\n if ~isempty(g.projcol)\n set(h, 'color', g.projcol{index});\n end;\n end;\n % \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw text %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n if isfield(sources, 'component')\n if strcmp(g.num, 'on')\n h = text(xx, yy, zz, [ ' ' int2str(sources(index).component)]);\n set(h, 'userdata', dipstruct, 'tag', tag, 'fontsize', g.dipolesize/2 );\n if ~strcmpi(g.image, 'besa'), set(h, 'color', 'w'); end;\n end;\n end;\n end;\n end;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 3-D settings\n if strcmpi(g.spheres, 'on')\n lighting phong;\n material shiny;\n camlight left;\n camlight right;\n end;\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw elipse for group of dipoles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n if ~isempty(g.std)\n for index = 1:length(g.std)\n if ~iscell(g.std{index})\n plotellipse(sources, g.std{index}, 1, dat.tcparams, dat.coreg);\n else\n sc = plotellipse(sources, g.std{index}{1}, g.std{index}{2}, dat.tcparams, dat.coreg);\n if length( g.std{index} ) > 2\n set(sc, g.std{index}{3:end});\n end;\n end;\n end;\n end;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% buttons %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n nbsrc = int2str(length(sources));\n cbmesh = [ 'if get(gcbo, ''userdata''), ' ...\n ' set(findobj(''parent'', gca, ''tag'', ''mesh''), ''visible'', ''off'');' ...\n ' set(gcbo, ''string'', ''Mesh on'');' ...\n ' set(gcbo, ''userdata'', 0);' ...\n 'else,' ...\n ' set(findobj(''parent'', gca, ''tag'', ''mesh''), ''visible'', ''on'');' ...\n ' set(gcbo, ''string'', ''Mesh off'');' ...\n ' set(gcbo, ''userdata'', 1);' ...\n 'end;' ];\n cbview = [ 'tmpuserdat = get(gca, ''userdata'');' ...\n 'if tmpuserdat.axistight, ' ...\n ' set(gcbo, ''string'', ''Tight view'');' ...\n 'else,' ...\n ' set(gcbo, ''string'', ''Loose view'');' ...\n 'end;' ...\n 'tmpuserdat.axistight = ~tmpuserdat.axistight;' ...\n 'set(gca, ''userdata'', tmpuserdat);' ...\n 'clear tmpuserdat;' ...\n 'dipplot(gcbf);' ];\n viewstyle = eeglab_fastif(strcmpi(dat.mode, 'besa'), 'text', 'pushbutton');\n viewstring = eeglab_fastif(dat.axistight, 'Loose view', 'Tight view');\n \n h = uicontrol( 'unit', 'normalized', 'position', [0 0 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Top view', 'callback', 'view([0 0 1]);');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.05 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Coronal view', 'callback', 'view([0 -1 0]);');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.1 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Sagital view', 'callback', 'view([1 0 0]);');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.15 .15 .05], 'tag', 'tmp', ...\n 'style', 'text', 'string', '');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.2 .15 .05], 'tag', 'tmp', ...\n 'style', viewstyle , 'string', viewstring, 'callback', cbview);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.25 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Mesh on', 'userdata', 0, 'callback', cbmesh);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.3 .15 .05], 'tag', 'tmp', ...\n 'style', 'text', 'string', 'Display:','fontweight', 'bold' );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.35 .15 .05], 'tag', 'tmp', ...\n 'style', 'text', 'string', '');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.4 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'fontweight', 'bold', 'string', 'No controls', 'callback', ...\n 'set(findobj(''parent'', gcbf, ''tag'', ''tmp''), ''visible'', ''off'');');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.45 .15 .05], 'tag', 'tmp', ...\n 'style', 'text', 'string', '');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.50 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Keep|Prev', 'callback', ...\n [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...\n 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))-1));' ...\n 'tmpobj = get(gcf, ''userdata'');' ...\n 'eval(get(editobj, ''callback''));' ...\n 'set(tmpobj, ''visible'', ''on'');' ...\n 'clear editobj tmpobj;' ]);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.55 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Prev', 'callback', ...\n [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...\n 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))-1));' ...\n 'eval(get(editobj, ''callback''));' ...\n 'clear editobj;' ]);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.6 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Next', 'callback', ...\n [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...\n 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))+1));' ...\n 'dipplot(gcbf);' ...\n 'clear editobj;' ]);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.65 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Keep|Next', 'callback', ...\n [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...\n 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))+1));' ...\n 'tmpobj = get(gcf, ''userdata'');' ...\n 'dipplot(gcbf);' ...\n 'set(tmpobj, ''visible'', ''on'');' ...\n 'clear editobj tmpobj;' ]);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.7 .15 .05], 'tag', 'tmp', 'userdata', 'rv', ...\n 'style', 'text', 'string', '');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.75 .15 .05], 'tag', 'tmp', 'userdata', 'editor', ...\n 'style', 'edit', 'string', '1', 'callback', ...\n [ 'dipplot(gcbf);' ] );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.8 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Plot one', 'callback', ...\n \t [ 'for tmpi = 1:' nbsrc ',' ...\n ' set(findobj(''parent'', gca, ''tag'', [ ''dipole'' int2str(tmpi) ]), ''visible'', ''off'');' ...\n 'end; clear tmpi;' ...\n 'dipplot(gcbf);' ]);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.85 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Plot All', 'callback', ...\n [ 'for tmpi = 1:' nbsrc ',' ...\n ' set(findobj(''parent'', gca, ''tag'', [ ''dipole'' int2str(tmpi) ]), ''visible'', ''on'');' ...\n 'end; clear tmpi;' ]);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.9 .15 .05], 'tag', 'tmp', ...\n 'style', 'text', 'string', [num2str(length(sources)) ' dipoles:'], 'fontweight', 'bold' );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.95 .15 .05], 'tag', 'tmp', ...\n 'style', 'text', 'string', ' ' );\n set(gcf, 'userdata', findobj('parent', gca, 'tag', 'dipole1'));\n\n dat.nbsources = length(sources);\n set(gca, 'userdata', dat ); % last param=1 for MRI view tight/loose\n set(gcf, 'color', BACKCOLOR);\n \n if strcmp(g.gui, 'off')\n set(findobj('parent', gcf, 'tag', 'tmp'), 'visible', 'off');\n end;\n if strcmp(g.mesh, 'off')\n set(findobj('parent', gca, 'tag', 'mesh'), 'visible', 'off');\n end;\n updatedipplot(gcf);\n \n rotate3d on;\nreturn;\n\nfunction [xx,yy,zz] = transcoords(x, y, z, TCPARAMS, coreg);\n \n if nargin > 4 & ~isempty(coreg) % custom MRI co-registration\n % rotation scale center\n newcoords = transformcoords( [x(:) y(:) z(:)], coreg(5:7), coreg(4), coreg(1:3) );\n xx = newcoords(:,1); xx = reshape(xx, size(x));\n yy = newcoords(:,2); yy = reshape(yy, size(y));\n zz = newcoords(:,3); zz = reshape(zz, size(z));\n return;\n end;\n \n if iscell(TCPARAMS) % coregistration for MRI template\n \n valinion = TCPARAMS{1};\n valnasion = TCPARAMS{2};\n vallear = TCPARAMS{3};\n valrear = TCPARAMS{4};\n valvertex = TCPARAMS{5};\n zoffset = TCPARAMS{6};\n \n % scale axis\n % ----------\n y = y/2*( valinion(1) - valnasion(1) );\n x = x/2*( valrear(2) - vallear(2) );\n z = z* ( valvertex(3) - vallear(3) - zoffset );\n \n % recenter\n % --------\n yy = y + (vallear (1) + valrear (1))/2;\n xx = x + (valinion(2) + valnasion(2))/2;\n zz = z + (vallear (3) + valrear (3))/2 + zoffset;\n return;\n elseif isnumeric(TCPARAMS)\n yy = y*TCPARAMS;\n xx = x*TCPARAMS;\n zz = z*TCPARAMS; \n end;\n \nfunction sc = plotellipse(sources, ind, nstd, TCPARAMS, coreg);\n\n for i = 1:length(ind)\n tmpval(1,i) = -sources(ind(i)).posxyz(1); \n tmpval(2,i) = -sources(ind(i)).posxyz(2); \n tmpval(3,i) = sources(ind(i)).posxyz(3);\n [tmpval(1,i) tmpval(2,i) tmpval(3,i)] = transcoords(tmpval(1,i), tmpval(2,i), tmpval(3,i), TCPARAMS, coreg);\n end;\n \n % mean and covariance\n C = cov(tmpval');\n M = mean(tmpval,2);\n [U,L] = eig(C);\n \n % For N standard deviations spread of data, the radii of the eliipsoid will\n % be given by N*SQRT(eigenvalues).\n radii = nstd*sqrt(diag(L));\n \n % generate data for \"unrotated\" ellipsoid\n [xc,yc,zc] = ellipsoid(0,0,0,radii(1),radii(2),radii(3), 10);\n \n % rotate data with orientation matrix U and center M\n a = kron(U(:,1),xc); b = kron(U(:,2),yc); c = kron(U(:,3),zc);\n data = a+b+c; n = size(data,2);\n x = data(1:n,:)+M(1); y = data(n+1:2*n,:)+M(2); z = data(2*n+1:end,:)+M(3);\n \n % now plot the rotated ellipse\n c = ones(size(z));\n sc = mesh(x,y,z);\n alpha(0.5)\n \nfunction newsrc = convertbesaoldformat(src);\n newsrc = [];\n count = 1;\n countdip = 1;\n if ~isfield(src, 'besaextori'), src(1).besaextori = []; end;\n for index = 1:length(src)\n \n % convert format\n % --------------\n if isempty(src(index).besaextori), src(index).besaextori = 300; end; % 20 mm\n newsrc(count).possph(countdip,:) = [ src(index).besathloc src(index).besaphloc src(index).besaexent];\n newsrc(count).momsph(countdip,:) = [ src(index).besathori src(index).besaphori src(index).besaextori/300];\n \n % copy other fields\n % -----------------\n if isfield(src, 'stdX')\n newsrc(count).stdX = -src(index).stdY;\n newsrc(count).stdY = src(index).stdX;\n newsrc(count).stdZ = src(index).stdZ;\n end;\n if isfield(src, 'rv')\n newsrc(count).rv = src(index).rv;\n end;\n if isfield(src, 'elecrv')\n newsrc(count).rvelec = src(index).elecrv;\n end;\n if isfield(src, 'component')\n newsrc(count).component = src(index).component;\n if index ~= length(src) & src(index).component == src(index+1).component\n countdip = countdip + 1;\n else\n count = count + 1; countdip = 1;\n end;\n else\n count = count + 1; countdip = 1;\n end;\n end; \n\nfunction src = computexyzforbesa(src);\n \n for index = 1:length( src )\n for index2 = 1:size( src(index).possph, 1 )\n\n % compute coordinates\n % -------------------\n postmp = src(index).possph(index2,:);\n momtmp = src(index).momsph(index2,:);\n \n phi = postmp(1)+90; %% %%%%%%%%%%%%%%% USE BESA COORDINATES %%%%%\n theta = postmp(2); %% %%%%%%%%%%%%%%% USE BESA COORDINATES %%%%%\n phiori = momtmp(1)+90; %% %%%%%%%%%%%% USE BESA COORDINATES %%%%%\n thetaori = momtmp(2); %% %%%%%%%%%%%% USE BESA COORDINATES %%%%%\n % exentricities are in % of the radius of the head sphere\n [x y z] = sph2cart(theta/180*pi, phi/180*pi, postmp(3)/100); \n [xo yo zo] = sph2cart(thetaori/180*pi, phiori/180*pi, momtmp(3)*5); % exentricity scaled for compatibility with DIPFIT\n src(index).posxyz(index2,:) = [-y x z];\n src(index).momxyz(index2,:) = [-yo xo zo];\n \n end;\n end;\n \n% update dipplot (callback call)\n% ------------------------------\nfunction updatedipplot(fig)\n \n % find current dipole index and test for authorized range\n % -------------------------------------------------------\n dat = get(gca, 'userdata');\n editobj = findobj('parent', fig, 'userdata', 'editor');\n tmpnum = str2num(get(editobj(end), 'string'));\n if tmpnum < 1, tmpnum = 1; end;\n if tmpnum > dat.nbsources, tmpnum = dat.nbsources; end;\n set(editobj(end), 'string', num2str(tmpnum));\n \n % hide current dipole, find next dipole and show it\n % -------------------------------------------------\n set(get(gcf, 'userdata'), 'visible', 'off');\n newdip = findobj('parent', gca, 'tag', [ 'dipole' get(editobj(end), 'string')]);\n set(newdip, 'visible', 'on');\n set(gcf, 'userdata', newdip);\n \n % find all dipolar structures\n % ---------------------------\n tmprvobj = findobj('parent', fig, 'userdata', 'rv');\n index = 1;\n count = 1;\n for index = 1:length(newdip)\n if isstruct( get(newdip(index), 'userdata') )\n allpos3d(count,:) = getfield(get(newdip(index), 'userdata'), 'pos3d');\n count = count+1;\n foundind = index;\n end;\n end;\n \n % get residual variance\n % ---------------------\n if exist('foundind')\n rv = getfield(get(newdip(foundind), 'userdata'), 'rv');\n set( tmprvobj(end), 'string', rv);\n end\n \n % adapt the MRI to the dipole depth\n % ---------------------------------\n %if ~strcmpi(dat.mode, 'besa') % not besa mode\n delete(findobj('parent', gca, 'tag', 'img'));\n \n tmpdiv = 1;\n if ~dat.axistight\n [xx yy zz] = transcoords(0,0,0, dat.tcparams, dat.coreg);\n indx = minpos(dat.imgcoords{1}-zz);\n indy = minpos(dat.imgcoords{2}-yy);\n indz = minpos(dat.imgcoords{3}-xx);\n else\n if ~dat.cornermri\n indx = minpos(dat.imgcoords{1} - mean(allpos3d(:,3)) + 4/tmpdiv);\n indy = minpos(dat.imgcoords{2} - mean(allpos3d(:,2)) - 4/tmpdiv);\n indz = minpos(dat.imgcoords{3} - mean(allpos3d(:,1)) + 4/tmpdiv);\n else % no need to shift slice if not ploted close to the dipole\n indx = minpos(dat.imgcoords{1} - mean(allpos3d(:,3)));\n indy = minpos(dat.imgcoords{2} - mean(allpos3d(:,2)));\n indz = minpos(dat.imgcoords{3} - mean(allpos3d(:,1)));\n end;\n end;\n plotimgs( dat, [indx indy indz]);\n %end;\n \t\n% plot images\n% -----------\nfunction plotimgs(dat, index);\n \n % loading images\n % --------------\n if strcmpi(dat.mode, 'besa')\n imgt = dat.imgs{1};\n imgc = dat.imgs{2};\n imgs = dat.imgs{3};\n else\n imgt = rot90(squeeze(dat.imgs(:,:,index(1)))); \n imgc = rot90(squeeze(dat.imgs(:,index(2),:))); \n imgs = rot90(squeeze(dat.imgs(index(3),:,:))); \n end;\n if ndims(imgt) == 2, imgt(:,:,3) = imgt; imgt(:,:,2) = imgt(:,:,1); end;\n if ndims(imgc) == 2, imgc(:,:,3) = imgc; imgc(:,:,2) = imgc(:,:,1); end;\n if ndims(imgs) == 2, imgs(:,:,3) = imgs; imgs(:,:,2) = imgs(:,:,1); end;\n \n % computing coordinates for planes\n % -------------------------------- \n wxt = [min(dat.imgcoords{3}) max(dat.imgcoords{3}); min(dat.imgcoords{3}) max(dat.imgcoords{3})];\n wyt = [min(dat.imgcoords{2}) min(dat.imgcoords{2}); max(dat.imgcoords{2}) max(dat.imgcoords{2})];\n wxc = [min(dat.imgcoords{3}) max(dat.imgcoords{3}); min(dat.imgcoords{3}) max(dat.imgcoords{3})];\n wzc = [max(dat.imgcoords{1}) max(dat.imgcoords{1}); min(dat.imgcoords{1}) min(dat.imgcoords{1})];\n wys = [min(dat.imgcoords{2}) max(dat.imgcoords{2}); min(dat.imgcoords{2}) max(dat.imgcoords{2})];\n wzs = [max(dat.imgcoords{1}) max(dat.imgcoords{1}); min(dat.imgcoords{1}) min(dat.imgcoords{1})];\n if dat.axistight & ~dat.cornermri\n wzt = [ 1 1; 1 1]*dat.imgcoords{1}(index(1));\n wyc = [ 1 1; 1 1]*dat.imgcoords{2}(index(2));\n wxs = [ 1 1; 1 1]*dat.imgcoords{3}(index(3));\n else\n wzt = -[ 1 1; 1 1]*dat.maxcoord(1);\n wyc = [ 1 1; 1 1]*dat.maxcoord(2);\n wxs = -[ 1 1; 1 1]*dat.maxcoord(3);\n end;\n \n % ploting surfaces\n % ----------------\n options = { 'FaceColor','texturemap', 'EdgeColor','none', 'CDataMapping', ...\n 'direct','tag','img', 'facelighting', 'none' };\n hold on;\n surface(wxt, wyt, wzt, imgt(end:-1:1,:,:), options{:});\n surface(wxc, wyc, wzc, imgc , options{:});\n surface(wxs, wys, wzs, imgs , options{:});\n if strcmpi(dat.drawedges, 'on')\n % removing old edges if any\n delete(findobj( gcf, 'tag', 'edges'));\n if dat.axistight & ~dat.cornermri, col = 'k'; else col = [0.5 0.5 0.5]; end;\n h(1) = line([wxs(1) wxs(2)]', [wys(1) wyc(1)]', [wzt(1) wzt(2)]'); % sagital-transverse\n h(2) = line([wxs(1) wxc(3)]', [wyc(1) wyc(2)]', [wzt(1) wzt(2)]'); % coronal-tranverse\n h(3) = line([wxs(1) wxs(2)]', [wyc(1) wyc(2)]', [wzs(1) wzt(1)]'); % sagital-coronal\n set(h, 'color', col, 'linewidth', 2, 'tag', 'edges');\n end;\n \n %%fill3([-2 -2 2 2], [-2 2 2 -2], wz(:)-1, BACKCOLOR);\n %%fill3([-2 -2 2 2], wy(:)-1, [-2 2 2 -2], BACKCOLOR);\n rotate3d on \n\nfunction index = minpos(vals);\n\tvals(find(vals < 0)) = inf;\n\t[tmp index] = min(vals);\n\nfunction scalegca(factor)\n xl = xlim; xf = ( xl(2) - xl(1) ) * factor;\n yl = ylim; yf = ( yl(2) - yl(1) ) * factor;\n zl = zlim; zf = ( zl(2) - zl(1) ) * factor;\n xlim( [ xl(1)-xf xl(2)+xf ]);\n ylim( [ yl(1)-yf yl(2)+yf ]);\n zlim( [ zl(1)-zf zl(2)+zf ]);\n \nfunction color = strcol2real(colorin, colmap)\n if ~iscell(colorin)\n for index = 1:length(colorin)\n color{index} = colmap(colorin(index),:);\n end;\n else\n color = colorin;\n for index = 1:length(colorin)\n if isstr(colorin{index})\n switch colorin{index}\n case 'r', color{index} = [1 0 0];\n case 'g', color{index} = [0 1 0];\n case 'b', color{index} = [0 0 1];\n case 'c', color{index} = [0 1 1];\n case 'm', color{index} = [1 0 1];\n case 'y', color{index} = [1 1 0];\n case 'k', color{index} = [0 0 0];\n case 'w', color{index} = [1 1 1];\n otherwise, error('Unknown color');\n end;\n end;\n end;\n end;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "DEM_demo.m", "ext": ".m", "path": "spm5-master/toolbox/DEM/DEM_demo.m", "size": 5159, "source_encoding": "utf_8", "md5": "2358430b0491bf5053bcbf59718a6a8f", "text": "function varargout = DEM_demo(varargin)\n% DEM_DEMO M-file for DEM_demo.fig\n% DEM_DEMO, by itself, creates a new DEM_DEMO or raises the existing\n% singleton*.\n%\n% H = DEM_DEMO returns the handle to a new DEM_DEMO or the handle to\n% the existing singleton*.\n%\n% DEM_DEMO('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in DEM_DEMO.M with the given input arguments.\n%\n% DEM_DEMO('Property','Value',...) creates a new DEM_DEMO or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before DEM_demo_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to DEM_demo_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help DEM_demo\n\n% Last Modified by GUIDE v2.5 23-Aug-2007 15:32:20\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @DEM_demo_OpeningFcn, ...\n 'gui_OutputFcn', @DEM_demo_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before DEM_demo is made visible.\nfunction DEM_demo_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to DEM_demo (see VARARGIN)\n\n% Choose default command line output for DEM_demo\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes DEM_demo wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = DEM_demo_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\nfunction run_demo_Callback(hObject, handles, file)\nh = help(file);\nstr{1} = [file ':'];\nstr{2} = '______________________________________________________________ ';\nstr{2} = ' ';\nstr{3} = h;\nset(handles.help,'String',str);\neval(file)\n\n\n% --- Executes on button press in pushbutton1.\nfunction pushbutton1_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_GLM')\n\n% --- Executes on button press in pushbutton2.\nfunction pushbutton2_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_PEB')\n\n% --- Executes on button press in pushbutton4.\nfunction pushbutton4_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_factor_analysis')\n\n% --- Executes on button press in pushbutton5.\nfunction pushbutton5_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_OU')\n\n% --- Executes on button press in pushbutton6.\nfunction pushbutton6_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_convolution')\n\n% --- Executes on button press in pushbutton7.\nfunction pushbutton7_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_EM')\n\n% --- Executes on button press in pushbutton8.\nfunction pushbutton8_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_DEM')\n\n% --- Executes on button press in pushbutton9.\nfunction pushbutton9_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_filtering')\n\n% --- Executes on button press in pushbutton10.\nfunction pushbutton10_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_Lorenz')\n\n% --- Executes on button press in pushbutton3.\nfunction pushbutton3_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_DFP')\n\n% --- Executes on button press in pushbutton11.\nfunction pushbutton11_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_hdm')\n\n% --- Executes on button press in pushbutton12.\nfunction pushbutton12_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DEM_demo_double_well')\n\n% --- Executes on button press in pushbutton14.\nfunction pushbutton14_Callback(hObject, eventdata, handles)\nrun_demo_Callback(hObject, handles, 'DFP_demo_double_well')\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_sextract.m", "ext": ".m", "path": "spm5-master/toolbox/SRender/spm_sextract.m", "size": 1949, "source_encoding": "utf_8", "md5": "cece4536d3e43573a233c340010cc490", "text": "function spm_sextract(job)\n% Surface extraction\n%_______________________________________________________________________\n% Copyright (C) 2007 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id$\n\nimages = job.images;\nVi = spm_vol(strvcat(images));\nn = numel(Vi); %-#images\nif n==0, error('no input images specified'), end\n\n[pth,nam,ext] = fileparts(images{1});\n\nfor k=1:numel(job.surface),\n expression = job.surface(k).expression;\n thresh = job.surface(k).thresh;\n\n y = zeros(Vi(1).dim(1:3),'single');\n spm_progress_bar('Init',Vi(1).dim(3),expression,'planes completed');\n for p = 1:Vi(1).dim(3),\n B = spm_matrix([0 0 -p 0 0 0 1 1 1]);\n im = cell(1,n);\n for i=1:n,\n M = inv(B*inv(Vi(1).mat)*Vi(i).mat);\n im{i} = spm_slice_vol(Vi(i),M,Vi(1).dim(1:2),[0,NaN]);\n end\n try,\n y(:,:,p) = real(single(efun(im,expression)));\n catch,\n error(['Can not evaluate \"' expression '\".']);\n end\n spm_progress_bar('Set',p);\n end\n spm_smooth(y,y,[1.5,1.5,1.5]);\n\n [faces,vertices] = isosurface(y,thresh);\n % Swap around x and y because isosurface does for some\n % wierd and wonderful reason.\n Mat = Vi(1).mat(1:3,:)*[0 1 0 0;1 0 0 0;0 0 1 0; 0 0 0 1];\n vertices = (Mat*[vertices' ; ones(1,size(vertices,1))])';\n matname = fullfile(pth,sprintf('surf_%s_%.3d.mat',nam,k));\n if spm_matlab_version_chk('7.0') >=0,\n save(matname,'-V6','faces','vertices','expression','thresh','images');\n else\n save(matname,'faces','vertices','expression','thresh','images');\n end;\n spm_progress_bar('Clear');\nend\nreturn\n%_______________________________________________________________________\n%_______________________________________________________________________\nfunction y = efun(im,f)\nfor i=1:numel(im),\n eval(['i' num2str(i) '= im{i};']);\nend\ny = eval(f);\nreturn\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_srender.m", "ext": ".m", "path": "spm5-master/toolbox/SRender/spm_config_srender.m", "size": 8254, "source_encoding": "utf_8", "md5": "de6b1f8858310acf32bb826b24f5fee6", "text": "function c = spm_config_render\n% Configuration file for surface visualisation\n%_______________________________________________________________________\n% Copyright (C) 2007 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id$\n\nentry = inline(['struct(''type'',''entry'',''name'',name,'...\n '''tag'',tag,''strtype'',strtype,''num'',num,''help'',{{}})'],...\n 'name','tag','strtype','num');\n\nfiles = inline(['struct(''type'',''files'',''name'',name,'...\n '''tag'',tag,''filter'',fltr,''num'',num,''help'',{{}})'],...\n 'name','tag','fltr','num');\n\nmnu = inline(['struct(''type'',''menu'',''name'',name,'...\n '''tag'',tag,''labels'',{labels},''values'',{values},''help'',{{}})'],...\n 'name','tag','labels','values');\n\nbranch = inline(['struct(''type'',''branch'',''name'',name,'...\n '''tag'',tag,''val'',{val},''help'',{{}})'],...\n 'name','tag','val');\nrepeat = inline(['struct(''type'',''repeat'',''name'',name,''tag'',tag,'...\n '''values'',{values})'],'name','tag','values');\n\nRed = mnu('Red','Red',...\n {'0.0','0.2','0.4','0.6','0.8','1.0'},...\n {0,0.2,0.4,0.6,0.8,1});\nRed.val = {1};\nRed.help = {['The intensity of the red colouring (0 to 1).']};\n\nGreen = mnu('Green','Green',...\n {'0.0','0.2','0.4','0.6','0.8','1.0'},...\n {0,0.2,0.4,0.6,0.8,1});\nGreen.val = {1};\nGreen.help = {['The intensity of the green colouring (0 to 1).']};\n\nBlue = mnu('Blue','Blue',...\n {'0.0','0.2','0.4','0.6','0.8','1.0'},...\n {0,0.2,0.4,0.6,0.8,1});\nBlue.val = {1};\nBlue.help = {['The intensity of the blue colouring (0 to 1).']};\n\nColor = branch('Color','Color',{Red,Green,Blue});\nColor.help = {[...\n'Specify the colour using a mixture of red, green and blue. '...\n'For example, white is specified by 1,1,1, black is by 0,0,0 and '...\n'purple by 1,0,1.']};\n\nAmbientStrength = mnu('Ambient Strength','AmbientStrength',...\n {'0.0','0.2','0.4','0.6','0.8','1.0'},...\n {0,0.2,0.4,0.6,0.8,1});\nAmbientStrength.val = {0.2};\nAmbientStrength.help = {[...\n'The strength with which the object reflects ambient '...\n'(non-directional) lighting.']};\n\nDiffuseStrength = mnu('Diffuse Strength','DiffuseStrength',...\n {'0.0','0.2','0.4','0.6','0.8','1.0'},...\n {0,0.2,0.4,0.6,0.8,1});\nDiffuseStrength.val = {0.8};\nDiffuseStrength.help = {[...\n'The strength with which the object diffusely reflects '...\n'light. Mat surfaces reflect light diffusely, whereas '...\n'shiny surfaces reflect speculatively.']};\n\nSpecularStrength = mnu('Specular Strength','SpecularStrength',...\n {'0.0','0.2','0.4','0.6','0.8','1.0'},...\n {0,0.2,0.4,0.6,0.8,1});\nSpecularStrength.val = {0.2};\nSpecularStrength.help = {[...\n'The strength with which the object specularly reflects '...\n'light (i.e. how shiny it is). '...\n'Mat surfaces reflect light diffusely, whereas '...\n'shiny surfaces reflect speculatively.']};\n\nSpecularExponent = mnu('Specular Exponent','SpecularExponent',...\n {'0.01','0.1','10','100'},{0.01,0.1,10,100});\nSpecularExponent.val = {10};\nSpecularExponent.help = {[...\n'A parameter describing the specular reflectance behaviour. '...\n'It relates to the size of the high-lights.']};\n\nSpecularColorReflectance = mnu('Specular Color Reflectance',...\n 'SpecularColorReflectance',...\n {'0.0','0.2','0.4','0.6','0.8','1.0'},...\n {0,0.2,0.4,0.6,0.8,1});\nSpecularColorReflectance.val = {0.8};\nSpecularColorReflectance.help = {[...\n'Another parameter describing the specular reflectance behaviour.']};\n\nFaceAlpha = mnu('Face Alpha','FaceAlpha',...\n {'0.0','0.2','0.4','0.6','0.8','1.0'},...\n {0,0.2,0.4,0.6,0.8,1});\nFaceAlpha.val = {1};\nFaceAlpha.help = {[...\n'The opaqueness of the surface. A value of 1 means it is '...\n'opaque, whereas a value of 0 means it is transparent.']};\n\nfname = files('Surface File','SurfaceFile','mat',1);\nfname.ufilter = '^surf_.*\\.mat';\nfname.help = {[...\n'Filename of the surf_*.mat file containing the rendering information. '...\n'This can be generated via the surface extraction routine in SPM. '...\n'Normally, a surface is extracted from grey and white matter tissue class '...\n'images, but it is also possible to threshold e.g. an spmT image so that '...\n'activations can be displayed.']};\n\nObject = branch('Object','Object',...\n{fname,Color,DiffuseStrength,AmbientStrength,SpecularStrength,SpecularExponent,SpecularColorReflectance,FaceAlpha});\nObject.help = {[...\n'Each object is a surface (from a surf_*.mat file), which may have a '...\n'number of light-reflecting qualities, such as colour and shinyness.']};\n\nObjects = repeat('Objects','Objects',{Object});\nObjects.help = {[...\n'Several surface objects can be displayed together in different colours '...\n'and with different reflective properties.']};\n\n\n\nPosition = entry('Position','Position','e',[1 3]);\nPosition.val = {[100 100 100]};\nPosition.help = {'The position of the light in 3D.'};\n\nLight = branch('Light','Light',{Position,Color});\nLight.help = {'Specification of a light source in terms of position and colour.'};\n\nLights = repeat('Lights','Lights',{Light});\nLights.help = {[...\n'There should be at least one light specified so that the objects '...\n'can be clearly seen.']};\n\nsren = branch('Surface Rendering','SRender',{Objects,Lights});\nsren.prog = @spm_srender;\nsren.help = {[...\n'This utility is for visualising surfaces. Surfaces first need to be '...\n'extracted and saved in surf_*.mat files using the surface extraction '...\n'routine.']};\n\nexpr.type = 'entry';\nexpr.name = 'Expression';\nexpr.tag = 'expression';\nexpr.strtype = 's';\nexpr.num = [2 Inf];\nexpr.val = {'i1'};\nexpr.help = {...\n'Example expressions (f):',...\n' * Mean of six images (select six images)',...\n' f = ''(i1+i2+i3+i4+i5+i6)/6''',...\n' * Make a binary mask image at threshold of 100',...\n' f = ''i1>100''',...\n' * Make a mask from one image and apply to another',...\n' f = ''i2.*(i1>100)''',[...\n' - here the first image is used to make the mask, which is applied to the second image'],...\n' * Sum of n images',...\n' f = ''i1 + i2 + i3 + i4 + i5 + ...'''};\n\nthresh.type = 'entry';\nthresh.name = 'Surface isovalue(s)';\nthresh.tag = 'thresh';\nthresh.num = [1 1];\nthresh.val = {.5};\nthresh.strtype = 'e';\nthresh.help = {['Enter the value at which isosurfaces through ' ...\n 'the resulting image is to be computed.']};\n\nsurf = branch('Surface','surface',{expr,thresh});\nsurf.help = {[...\n'An expression and threshold for each of the surfaces to be generated.']};\n\nsurfaces = repeat('Surfaces','Surfaces',{surf});\nsurfaces.help = {'Multiple surfaces can be created from the same image data.'};\n\ninpt.type = 'files';\ninpt.name = 'Input Images';\ninpt.tag = 'images';\ninpt.filter = 'image';\ninpt.num = [1 Inf];\ninpt.help = {[...\n'These are the images that are used by the calculator. They ',...\n'are referred to as i1, i2, i3, etc in the order that they are ',...\n'specified.']};\n\nopts.type = 'branch';\nopts.name = 'Surface Extraction';\nopts.tag = 'SExtract';\nopts.val = {inpt,surfaces};\nopts.prog = @spm_sextract;\nopts.vfiles = @filessurf;\nopts.help = {[...\n'User-specified ',...\n'algebraic manipulations are performed on a set of images, with the result being ',...\n'used to generate a surface file. The user is prompted to supply images to ',...\n'work on and a number of expressions to ',...\n'evaluate, along with some thresholds. The expression should be a standard matlab expression, ',...\n'within which the images should be referred to as i1, i2, i3,... etc. '...\n'An isosurface file is created from the results at the user-specified threshold.']};\n\nc = repeat('Rendering','render',{opts,sren});\nc.help = {[...\n'This is a toolbox that provides a limited range '...\n'of surface rendering options. The idea is to first extract surfaces from '...\n'image data, which are saved in rend_*.mat files. '...\n'These can then be loaded and displayed as surfaces. '...\n'Note that OpenGL rendering is used, which can be problematic '...\n'on some computers. The tools are limited - and they do what they do.']};\nreturn;\n\n\nfunction vfiles=filessurf(job)\nvfiles={};\n[pth,nam,ext] = fileparts(job.images{1});\nfor k=1:numel(job.surface),\n vfiles{k} = fullfile(pth,sprintf('surf_%s_%.3d.mat',nam,k));\nend;\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "pm_segment.m", "ext": ".m", "path": "spm5-master/toolbox/FieldMap/pm_segment.m", "size": 3379, "source_encoding": "utf_8", "md5": "10c91142a779c74dc0aff191dd254b7c", "text": "function dat = pm_segment(fname)\n% Segment an MR image into Gray, White & CSF.\n%\n% FORMAT dat = pm_segment(fname)\n% fname - name of image to segment.\n% dat - matrix of size MxNxPx3 containing the resulting tissue probabilities\n%_______________________________________________________________________\n% Refs:\n%\n% Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and\n% Partitioning - a Unified Framework. NeuroImage 6:209-217\n%_______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n% John Ashburner\n% $Id: pm_segment.m 1914 2008-07-14 14:40:34Z chloe $\n\nif nargin<1, fname = spm_select(1,'image'); end\nopts.tpm = strvcat(fullfile(spm('dir'),'apriori','grey.nii'),...\n fullfile(spm('dir'),'apriori','white.nii'),...\n fullfile(spm('dir'),'apriori','csf.nii'));\nopts.ngaus = [1 1 1 4];\nopts.regtype = 'mni';\nopts.warpreg = 1;\nopts.warpco = 40;\nopts.biasreg = 1.0000e-04;\nopts.biasfwhm = 80;\nopts.samp = 6;\nopts.msk = '';\n\np = spm_preproc(fname,opts); % RUN THE SEGMENTATION\n\nT = p.Twarp;\nbsol = p.Tbias;\nd2 = [size(T) 1];\nd = p.image.dim(1:3);\n\n[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);\nx3 = 1:d(3);\nd3 = [size(bsol) 1];\nB1 = spm_dctmtx(d(1),d2(1));\nB2 = spm_dctmtx(d(2),d2(2));\nB3 = spm_dctmtx(d(3),d2(3));\nbB3 = spm_dctmtx(d(3),d3(3),x3);\nbB2 = spm_dctmtx(d(2),d3(2),x2(1,:)');\nbB1 = spm_dctmtx(d(1),d3(1),x1(:,1));\n\nmg = p.mg;\nmn = p.mn;\nvr = p.vr;\nK = length(mg);\nKb = length(p.ngaus);\nlkp = []; for k=1:Kb, lkp = [lkp ones(1,p.ngaus(k))*k]; end;\nM = p.tpm(1).mat\\p.Affine*p.image.mat;\nb0 = spm_load_priors(p.tpm);\nfor z=1:length(x3),\n f = spm_sample_vol(p.image,x1,x2,o*x3(z),0);\n cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f;\n [t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M);\n q = zeros([d(1:2) Kb]);\n bt = zeros([d(1:2) Kb]);\n b = zeros([d(1:2) K ]);\n for k1=1:Kb, bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb); end;\n for k=1:K, b(:,:,k ) = bt(:,:,lkp(k))*mg(k); end;\n s = sum(b,3)+eps;\n for k=1:K,\n p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps);\n q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s;\n end;\n s = sum(q,3)+eps;\n for k1=1:3,\n dat(:,:,z,k1) = uint8(round(255 * q(:,:,k1)./s));\n end;\nend;\n\n%=======================================================================\n\n%=======================================================================\nfunction [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M)\nx1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1));\ny1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2));\nz1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3));\nx1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);\ny1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);\nz1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction t = transf(B1,B2,B3,T)\nif ~isempty(T)\n d2 = [size(T) 1];\n t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));\n t = B1*t1*B2';\nelse\n t = zeros(size(B1,1),size(B2,1),size(B3,1));\nend;\nreturn;\n%======================================================================="} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "pm_brain_mask.m", "ext": ".m", "path": "spm5-master/toolbox/FieldMap/pm_brain_mask.m", "size": 4190, "source_encoding": "utf_8", "md5": "e569fc153b4b8c018cc3964a37661614", "text": "function bmask = pm_brain_mask(P,flags)\n% Calculate a brain mask\n% FORMAT bmask = pm_brain_mask(P,flags)\n%\n% P - is a single pointer to a single image\n%\n% flags - structure containing various options\n% template - which template for segmentation\n% fwhm - fwhm of smoothing kernel for generating mask\n% nerode - number of erosions\n% thresh - threshold for smoothed mask \n% ndilate - number of dilations\n%\n%__________________________________________________________________________\n%\n% Inputs\n% A single *.img conforming to SPM data format (see 'Data Format').\n%\n% Outputs\n% Brain mask in a matrix\n%__________________________________________________________________________\n%\n% The brain mask is generated by segmenting the image into GM, WM and CSF, \n% adding these components together then thresholding above zero.\n% A morphological opening is performed to get rid of stuff left outside of\n% the brain. Any leftover holes are filled. \n%\n%__________________________________________________________________________\n% @(#)pm_brain_mask.m\t1.0 Chloe Hutton 05/02/26\n\nif nargin < 2 | isempty(flags)\n %flags.template=fullfile(spm('Dir'),'templates','T1.nii');\n flags.fwhm=5;\n flags.nerode=1;\n flags.ndilate=2;\n flags.thresh=0.5;\n %flags.reg = 0.02;\n %flags.graphics=0;\nend\n\ndisp('Segmenting and extracting brain...');\n%seg_flags.estimate.reg=flags.reg;\n%seg_flags.graphics = flags.graphics;\n%VO=spm_segment(P.fname,flags.template,seg_flags);\n%bmask=double(VO(1).dat)+double(VO(2).dat)+double(VO(3).dat)>0;\ndat = pm_segment(P.fname);\nbmask=double(dat(:,:,:,1))+double(dat(:,:,:,2))+double(dat(:,:,:,3))>0;\nbmask=open_it(bmask,flags.nerode,flags.ndilate); % Do opening to get rid of scalp\n\n% Calculate kernel in voxels:\nvxs = sqrt(sum(P.mat(1:3,1:3).^2));\nfwhm = repmat(flags.fwhm,1,3)./vxs;\nbmask=fill_it(bmask,fwhm,flags.thresh); % Do fill to fill holes\n\nOP=P;\nbrain_mask = [spm_str_manip(P.fname,'h') '/bmask',...\n spm_str_manip(P.fname,'t')];\nOP.fname=brain_mask;\nOP.descrip=sprintf('Mask:erode=%d,dilate=%d,fwhm=%d,thresh=%1.1f',flags.nerode,flags.ndilate,flags.fwhm,flags.thresh);\nspm_write_vol(OP,bmask);\n\n%__________________________________________________________________________\n\n%__________________________________________________________________________\nfunction ovol=open_it(vol,ne,nd)\n% Do a morphological opening. This consists of an erosion, followed by \n% finding the largest connected component, followed by a dilation.\n\nfor i=1:ne\n% Do an erosion then a connected components then a dilation \n% to get rid of stuff outside brain.\n\n evol=spm_erode(double(vol));\n evol=connect_it(evol);\n vol=spm_dilate(double(evol));\nend\n\n% Do some dilations to extend the mask outside the brain\nfor i=1:nd\n vol=spm_dilate(double(vol));\nend\n\novol=vol;\n\n%__________________________________________________________________________\n\n%__________________________________________________________________________\nfunction ovol=fill_it(vol,k,thresh)\n% Do morpholigical fill. This consists of finding the largest connected \n% component and assuming that is outside of the head. All the other \n% components are set to 1 (in the mask). The result is then smoothed by k\n% and thresholded by thresh.\novol=vol;\n\n% Need to find connected components of negative volume\nvol=~vol;\n[vol,NUM]=ip_bwlabel(double(vol),26); \n\n% Now get biggest component and assume this is outside head..\npnc=0;\nmaxnc=1;\nfor i=1:NUM\n nc=size(find(vol==i),1);\n if nc>pnc\n maxnc=i;\n pnc=nc;\n end\nend\n\n% We know maxnc is largest cluster outside brain, so lets make all the\n% others = 1.\nfor i=1:NUM\n if i~=maxnc\n nc=find(vol==i);\n ovol(nc)=1;\n end\nend\n\nspm_smooth(ovol,ovol,k);\novol=ovol>thresh;\n\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction ovol=connect_it(vol)\n% Find connected components and return the largest one.\n\n[vol,NUM]=ip_bwlabel(double(vol),26); \n\n% Get biggest component\npnc=0;\nmaxnc=1;\nfor i=1:NUM\n nc=size(find(vol==i),1);\n if nc>pnc\n maxnc=i;\n pnc=nc;\n end\nend\novol=(vol==maxnc);\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "pm_vdm_apply.m", "ext": ".m", "path": "spm5-master/toolbox/FieldMap/pm_vdm_apply.m", "size": 9736, "source_encoding": "utf_8", "md5": "28012e22b682dfde3d59d9c2c7355c69", "text": "function varargout = pm_vdm_apply(ds,flags)\n%\n% Applies vdm (voxel displacement map) to distortion correct images volume by volume\n% FORMAT pm_vdm_apply(ds,[flags])\n% or\n% FORMAT P = pm_vdm_apply(ds,[flags])\n% \n% ds - a structure the containing the fields:\n% \n% .P - Images to apply correction to.\n%\n% .sfP - Static field supplied by the user. It should be a \n% filename or handle to a voxel-displacement map in\n% the same space as the first EPI image of the time-\n% series. If using the FieldMap toolbox, realignment\n% should (if necessary) have been performed as part of\n% the process of creating the VDM. Note also that the\n% VDM must be in undistorted space, i.e. if it is\n% calculated from an EPI based field-map sequence\n% it should have been inverted before using it to correct \n% images. Again, the FieldMap toolbox will do this for you.\n% .jm - Jacobian Modulation. This option is currently disabled.\n%\n% ds can also be an array of structures, each struct corresponding\n% to one sesssion and containing the corresponding images and\n% fieldmap. A preceding realignment step will ensure that\n% all images are in the space of the first image of the first session\n% and they are all resliced in the space of that image.There will\n% be a vdm file associated with each session but in practice, \n% fieldmaps are not often measured per session. In this case the same\n% fieldmap is used for each session.\n%\n% flags - a structure containing various options. The fields are:\n%\n% mask - mask output images (1 for yes, 0 for no)\n% To avoid artifactual movement-related variance the realigned\n% set of images can be internally masked, within the set (i.e.\n% if any image has a zero value at a voxel than all images have\n% zero values at that voxel). Zero values occur when regions\n% 'outside' the image are moved 'inside' the image during\n% realignment.\n%\n% mean - write mean image\n% The average of all the realigned scans is written to\n% mean*.img.\n%\n% interp - the interpolation method (see e.g. spm_bsplins.m).\n%\n% which - Values of 0 or 1 are allowed.\n% 0 - don't create any resliced images.\n% Useful if you only want a mean resliced image.\n% 1 - reslice all the images.\n%\n% udc - Values 1 or 2 are allowed\n% 1 - Do only unwarping (not correcting \n% for changing sampling density).\n% 2 - Do both unwarping and Jacobian correction.\n%\n%\n% The spatially realigned and corrected images are written to the \n% orginal subdirectory with the same filename but prefixed with an 'c'.\n% They are all aligned with the first.\n%_______________________________________________________________________\n% @(#)spm_vdm_apply.m\t1.0 Chloe Hutton 05/02/25\n\nglobal defaults\n\ndef_flags = struct('mask', 1,...\n 'mean', 1,...\n 'interp', 4,...\n 'wrap', [0 1 0],...\n 'which', 1,...\n 'udc', 1);\n\ndefnames = fieldnames(def_flags);\n\n%\n% Replace hardcoded defaults with spm_defaults\n% when exist and defined.\n%\nif exist('defaults','var') & isfield(defaults,'realign') & isfield(defaults.realign,'write')\n wd = defaults.realign.write;\n if isfield(wd,'interp'), def_flags.interp = wd.interp; end\n if isfield(wd,'wrap'), def_flags.wrap = wd.wrap; end\n if isfield(wd,'mask'), def_flags.mask = wd.mask; end\nend\n\nif nargin < 1 | isempty(ds)\n ds = getfield(load(spm_get(1,'*_c.mat','Select Unwarp result file')),'ds');\nend\n\n%\n% Do not allow Jacobian modulation \n%\nif ds(1).jm ~= 0\n ds(1).jm=0;\n def_flags.udc = 0;\nend\n\n%\n% Replace defaults with user supplied values for all fields\n% defined by user. Also, warn user of any invalid fields,\n% probably reflecting misspellings.\n%\nif nargin < 2 | isempty(flags)\n flags = def_flags;\nend\nfor i=1:length(defnames)\n if ~isfield(flags,defnames{i})\n flags = setfield(flags,defnames{i},getfield(def_flags,defnames{i}));\n end\nend\nflagnames = fieldnames(flags);\nfor i=1:length(flagnames)\n if ~isfield(def_flags,flagnames{i})\n warning(sprintf('Warning, unknown flag field %s',flagnames{i}));\n end\nend\n\nntot = 0;\nfor i=1:length(ds)\n ntot = ntot + length(ds(i).P);\nend\n\nhold = [repmat(flags.interp,1,3) flags.wrap];\n\nlinfun = inline('fprintf(''%-60s%s'', x,repmat(sprintf(''\\b''),1,60))');\n\n%\n% Create empty sfield for all structs.\n%\n[ds.sfield] = deal([]);\n\n%\n% Make space for output P-structs if required\n%\nif nargout > 0\n oP = cell(length(ds),1);\nend\n\n%\n% First, create mask if so required.\n%\n\nif flags.mask | flags.mean,\n linfun('Computing mask..');\n spm_progress_bar('Init',ntot,'Computing available voxels',...\n 'volumes completed');\n [x,y,z] = ndgrid(1:ds(1).P(1).dim(1),1:ds(1).P(1).dim(2),1:ds(1).P(1).dim(3));\n xyz = [x(:) y(:) z(:) ones(prod(ds(1).P(1).dim(1:3)),1)]; clear x y z;\n if flags.mean\n Count = zeros(prod(ds(1).P(1).dim(1:3)),1);\n Integral = zeros(prod(ds(1).P(1).dim(1:3)),1);\n end\n if flags.mask \n msk = zeros(prod(ds(1).P(1).dim(1:3)),1); \n end\n tv = 1;\n for s=1:length(ds)\n\n if isfield(ds(s),'sfP') & ~isempty(ds(s).sfP)\n T = ds(s).sfP.mat\\ds(1).P(1).mat;\n txyz = xyz * T';\n c = spm_bsplinc(ds(s).sfP,ds(s).hold);\n ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold);\n ds(s).sfield = ds(s).sfield(:);\n clear c txyz;\n end \n\n for i = 1:prod(size(ds(s).P))\n T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;\n txyz = xyz * T';\n msk = msk + real(txyz(:,1) < 1 | txyz(:,1) > ds(s).P(1).dim(1) |...\n txyz(:,2) < 1 | txyz(:,2) > ds(s).P(1).dim(2) |...\n txyz(:,3) < 1 | txyz(:,3) > ds(s).P(1).dim(3)); \n spm_progress_bar('Set',tv);\n tv = tv+1;\n end\n\n if flags.mean, Count = Count + repmat(length(ds(s).P),prod(ds(s).P(1).dim(1:3)),1) - msk; end\n\n %\n % Include static field in estimation of mask.\n %\n if isfield(ds(s),'sfP') & ~isempty(ds(s).sfP)\n T = inv(ds(s).sfP.mat) * ds(1).P(1).mat;\n txyz = xyz * T';\n msk = msk + real(txyz(:,1) < 1 | txyz(:,1) > ds(s).sfP.dim(1) |...\n txyz(:,2) < 1 | txyz(:,2) > ds(s).sfP.dim(2) |...\n txyz(:,3) < 1 | txyz(:,3) > ds(s).sfP.dim(3)); \n end\n\n if isfield(ds(s),'sfield') & ~isempty(ds(s).sfield)\n ds(s).sfield = [];\n end\n\n end\n if flags.mask, msk = find(msk ~= 0); end\nend\n\nlinfun('Reslicing fieldmap corrected images..');\nspm_progress_bar('Init',ntot,'Reslicing','volumes completed');\n\ntiny = 5e-2; % From spm_vol_utils.c\n\nPO = ds(1).P(1);\nPO.descrip = 'spm - fieldmap corrected';\njP = ds(1).P(1);\njP = rmfield(jP,{'fname','descrip','n','private'});\njP.dim = [jP.dim(1:3) 64];\njP.pinfo = [1 0]';\ntv = 1;\n\nfor s=1:length(ds)\n\n if isfield(ds(s),'sfP') & ~isempty(ds(s).sfP)\n T = ds(s).sfP.mat\\ds(1).P(1).mat;\n txyz = xyz * T';\n c = spm_bsplinc(ds(s).sfP,ds(s).hold);\n ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold);\n ds(s).sfield = ds(s).sfield(:);\n clear c txyz;\n end \n\n for i = 1:length(ds(s).P)\n linfun(['Reslicing volume ' num2str(tv) '..']);\n\n %\n % Read undeformed image.\n %\n\n T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;\n txyz = xyz * T';\n def = -ds(s).sfield;\n txyz(:,2) = txyz(:,2) + def;\n\n c = spm_bsplinc(ds(s).P(i),hold);\n ima = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),hold);\n \n %\n % Write it if so required.\n %\n if flags.which\n PO.fname = prepend(ds(s).P(i).fname,'c');\n if flags.mask\n ima(msk) = NaN;\n end\n ivol = reshape(ima,PO.dim(1:3));\n tP = spm_write_vol(PO,ivol);\n\t if nargout > 0\n\t oP{s}(i) = tP;\n\t end\n end\n %\n % Build up mean image if so required.\n %\n if flags.mean\n Integral = Integral + nan2zero(ima);\n end\n spm_progress_bar('Set',tv);\n tv = tv+1;\n end\n if isfield(ds(s),'sfield') & ~isempty(ds(s).sfield)\n ds(s).sfield = [];\n end\nend\n\nif flags.mean\n % Write integral image (16 bit signed)\n %-----------------------------------------------------------\n warning off; % Shame on me!\n Integral = Integral./Count;\n warning on;\n PO = ds(1).P(1);\n PO.fname = prepend(ds(1).P(1).fname, 'meanc');\n PO.pinfo = [max(max(max(Integral)))/32767 0 0]';\n PO.descrip = 'spm - mean undeformed image';\n PO.dim(4) = 4;\n ivol = reshape(Integral,PO.dim(1:3));\n spm_write_vol(PO,ivol);\nend\n\nlinfun(' ');\nspm_figure('Clear','Interactive');\n\nif nargout > 0\n varargout{1} = oP;\nend\n\nreturn;\n\n\n%_______________________________________________________________________\nfunction PO = prepend(PI,pre)\n[pth,nm,xt,vr] = spm_fileparts(deblank(PI));\nPO = fullfile(pth,[pre nm xt vr]);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vo = nan2zero(vi)\nvo = vi;\nvo(~isfinite(vo)) = 0;\nreturn;\n%_______________________________________________________________________\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "FieldMap.m", "ext": ".m", "path": "spm5-master/toolbox/FieldMap/FieldMap.m", "size": 75872, "source_encoding": "utf_8", "md5": "341ba2188382a38b6a854983335a641c", "text": "function varargout=FieldMap(varargin)\n%\n% FieldMap is an SPM2 Toolbox for creating field maps and unwarping EPI.\n% A full description of the toolbox and a usage manual can be found in \n% FieldMap.man. This can launched by the toolbox help button or using \n% spm_help FieldMap.man.The theoretical and practical principles behind \n% the toolbox are described in principles.man.\n%\n% FORMAT FieldMap\n%\n% FieldMap launches the gui-based toolbox. Help is available via the \n% help button (which calls spm_help FieldMap.man). FieldMap is a multi \n% function function so that the toolbox routines can also be accessed \n% without using the gui. A description of how to do this can be found \n% in FieldMap_ngui.m\n% \n% Input parameters and the mode in which the toolbox works can be \n% customised using the defaults file called pm_defaults.m. \n% \n% Main data structure:\n%\n% IP.P : 4x1 cell array containing real part short TE,\n% imaginary part short TE, real part long TE and\n% imaginary part long TE.\n% IP.pP : Cell containing pre-calculated phase map. N.B.\n% IP.P and IP.pP are mutually exclusive.\n% IP.epiP : Cell containing EPI image used to demonstrate \n% effects of unwarping.\n% IP.fmagP : Cell containing fieldmap magnitude image used for \n% coregistration\n% IP.wfmagP : Cell containing forward warped fieldmap magnitude \n% image used for coregistration\n% IP.uepiP : Cell containing unwarped EPI image.\n% IP.nwarp : Cell containing non-distorted image.\n% IP.vdmP : Cell containing the voxel displacement map (VDM)\n% IP.et : 2x1 Cell array with short and long echo-time (ms).\n% IP.epifm : Flag indicating EPI based field map (1) or not (0).\n% IP.blipdir : Direction of phase-encode blips for k-space traversal\n% (1 = positive or -1 = negative)\n% IP.ajm : Flag indicating if Jacobian modulation should be applied \n% (1) or not (0).\n% IP.tert : Total epi readout time (ms).\n% IP.maskbrain : Flag indicating whether to mask the brain for fieldmap creation\n% IP.uflags : Struct containing parameters guiding the unwrapping.\n% Further explanations of these parameters are in \n% FieldMap.man and pm_make_fieldmap.m \n% .iformat : 'RI' or 'PM' \n% .method : 'Huttonish', 'Mark3D' or 'Mark2D'\n% .fwhm : FWHM (mm) of Gaussian filter for field map smoothing\n% .pad : Size (in-plane voxels) of padding kernel. \n% .etd : Echo time difference (ms). \n% .bmask \n%\n% IP.mflags : Struct containing parameters for brain maskin\n% .template : Name of template for segmentation.\n% .fwhm : fwhm of smoothing kernel for generating mask.\n% .nerode : number of erosions\n% .ndilate : number of dilations\n% .thresh : threshold for smoothed mask. \n% .reg : bias field regularisation\n% .graphics : display or not\n%\n% IP.fm : Struct containing field map information\n% IP.fm.upm : Phase-unwrapped field map (Hz).\n% IP.fm.mask : Binary mask excluding the noise in the phase map.\n% IP.fm.opm : \"Raw\" field map (Hz) (not unwrapped).\n% IP.fm.fpm : Phase-unwrapped, regularised field map (Hz).\n% IP.fm.jac : Partial derivative of field map in y-direction.\n%\n% IP.vdm : Struct with voxel displacement map information\n% IP.vdm.vdm : Voxel displacement map (scaled version of IP.fm.fpm).\n% IP.vdm.jac : Jacobian-1 of forward transform.\n% IP.vdm.ivdm : Inverse transform of voxel displacement \n% (used to unwarp EPI image if field map is EPI based)\n% (used to warp flash image prior to coregistration when\n% field map is flash based (or other T2 weighting).\n% IP.vdm.ijac : Jacobian-1 of inverse transform.\n% IP.jim : Jacobian sampled in space of EPI.\n%\n% IP.cflags : Struct containing flags for coregistration \n% (these are the default SPM coregistration flags - \n% defaults.coreg).\n% .cost_fun \n% .sep \n% .tol\n% .fwhm \n%\n%_______________________________________________________________________\n% Refs and Background reading:\n%\n% Jezzard P & Balaban RS. 1995. Correction for geometric distortion in\n% echo planar images from Bo field variations. MRM 34:65-73.\n%\n% Hutton C et al. 2002. Image Distortion Correction in fMRI: A Quantitative \n% Evaluation, NeuroImage 16:217-240.\n%\n% Cusack R & Papadakis N. 2002. New robust 3-D phase unwrapping\n% algorithms: Application to magnetic field mapping and\n% undistorting echoplanar images. NeuroImage 16:754-764.\n%\n% Jenkinson M. 2003. Fast, automated, N-dimensional phase-\n% unwrapping algorithm. MRM 49:193-197.\n%\n%_______________________________________________________________________\n% Acknowledegments\n% \n% Wellcome Trust and IBIM Consortium\n%_______________________________________________________________________\n% UPDATE 02/07 \n% Updated version of FieldMap for SPM5. \n%\n% UPDATE 27/01/05\n\n%_______________________________________________________________________\n% FieldMap.m Jesper Andersson and Chloe Hutton 17/12/06 \n\npersistent PF FS WS PM % GUI related constants\npersistent ID % Image display\npersistent IP % Input and results\npersistent DGW % Delete Graphics Window (if we created it)\nglobal st % Global for spm_orthviews\n\n% SPM5 Update\nglobal defaults\nspm_defaults\n\nif nargin == 0\n Action = 'welcome';\nelse\n Action = varargin{1};\nend\n\n%\n% We have tried to divide the Actions into 3 categories:\n% 1) Functions that can be called directly from the GUI are at the\n% beginning. \n% 2) Next come other GUI-related 'utility' functions - ie those that\n% care of the GUI behind the scenes.\n% 3) Finally, call-back functions that are not GUI dependent and can \n% be called from a script are situated towards the end. \n% See FieldMap_ngui.m for details on how to use these.\n%\nswitch lower(Action)\n%=======================================================================\n%\n% Create and initialise GUI for FieldMap toolbox\n%\n%=======================================================================\n\n case 'welcome'\n \n % Unless specified, set visibility to on\n if nargin==2\n if ~strcmp(varargin{2},'off') & ~strcmp(varargin{2},'Off')\n visibility = 'On';\n else\n visibility = 'Off';\n end\n else\n visibility = 'On';\n end\n \n DGW = 0;\n\n % Get all default values (these may effect GUI)\n IP = FieldMap('Initialise');\n %\n % Since we are using persistent variables we better make sure\n % there is no-one else out there.\n %\n if ~isempty(PM)\n figure(PM);\n set(PM,'Visible',visibility);\n return\n end\n \n S = get(0,'ScreenSize');\n WS = spm('WinScale');\t\n FS = spm('FontSizes');\n PF = spm_platform('fonts');\n rect = [100 100 510 520].*WS;\n\n \n PM = figure('IntegerHandle','off',...\n\t 'Name',sprintf('%s%s','FieldMap Toolbox, beta.ver.2.0',...\n spm('GetUser',' (%s)')),...\n\t 'NumberTitle','off',...\n\t 'Tag','FieldMap',...\n\t 'Position',rect,...\n\t 'Resize','off',...\n\t 'Pointer','Arrow',...\n\t 'Color',[1 1 1]*.8,...\n\t 'MenuBar','none',...\n 'DefaultTextFontName',PF.helvetica,...\n 'DefaultTextFontSize',FS(10),...\n 'DefaultUicontrolFontName',PF.helvetica,...\n 'DefaultUicontrolFontSize',FS(10),...\n\t 'HandleVisibility','on',...\n\t 'Visible',visibility,...\n 'DeleteFcn','FieldMap(''Quit'');');\n\n%-Create phase map controls\n\n%-Frames and text\n\n uicontrol(PM,'Style','Frame','BackgroundColor',spm('Colour'),...\n 'Position',[10 270 490 240].*WS);\n uicontrol(PM,'Style','Text','String','Create field map in Hz',...\n\t 'Position',[100 480 300 020].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times,'FontAngle','Italic')\n uicontrol(PM,'Style','Text','String','Short TE',...\n\t 'Position',[25 452 60 20].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text','String','ms',...\n\t 'Position',[78 430 30 20].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text','String','Long TE',...\n\t 'Position',[25 392 60 20].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text','String','ms',...\n\t 'Position',[78 370 30 20].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text','String',{'Mask brain:'},...\n\t 'Position',[30 310 80 35].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text','String',{'Precalculated','field map:'},...\n\t 'Position',[30 275 80 35].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text','String',{'Field map value:'},...\n\t 'Position',[240 280 100 20].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text','String',{'Hz'},...\n\t 'Position',[403 280 20 20].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n\n\n%-Objects with Callbacks\n\n uicontrol(PM,'Style','radiobutton',...\n 'String','RI',...\n 'Position',[30 480 44 022].*WS,...\n\t 'ToolTipString','Select Real/Imaginary input images',...\n\t 'CallBack','FieldMap(''InputFormat'');',...\n 'UserData',1,...\n 'Tag','IFormat');\n uicontrol(PM,'Style','radiobutton',...\n 'String','PM',...\n 'Position',[76 480 44 022].*WS,...\n\t 'ToolTipString','Select phase/magnitude input images',...\n\t 'CallBack','FieldMap(''InputFormat'');',...\n 'UserData',2,...\n 'Tag','IFormat');\n uicontrol(PM,'Style','Edit',...\n 'Position',[30 430 50 024].*WS,...\n\t 'ToolTipString','Give shortest echo-time in ms',...\n\t 'CallBack','FieldMap(''EchoTime'');',...\n 'UserData',1,...\n 'Tag','ShortTime');\n uicontrol(PM,'Style','Edit',...\n 'Position',[30 370 50 024].*WS,...\n\t 'ToolTipString','Give longest echo-time in ms',...\n\t 'CallBack','FieldMap(''EchoTime'');',...\n 'UserData',2,...\n 'Tag','LongTime');\n\n % Here we set up appropriate gui\n\n FieldMap('IFormat_Gui');\n\n uicontrol(PM,'String','Calculate',...\n 'Position',[265 337 90 022].*WS,...\n 'Enable','Off',...\n\t 'ToolTipString','Go ahead and create unwrapped field map (in Hz)',...\n\t 'CallBack','FieldMap(''CreateFieldmap_Gui'');',...\n 'Tag','CreateFieldMap');\n uicontrol(PM,'String','Write',...\n 'Position',[370 337 90 022].*WS,...\n 'Enable','Off',...\n\t 'ToolTipString','Write Analyze image containing fininshed field map (in Hz)',...\n\t 'CallBack','FieldMap(''WriteFieldMap_Gui'');',...\n 'Tag','WriteFieldMap');\n uicontrol(PM,'String','Load',...\n 'Position',[125 280 90 022].*WS,...\n\t 'ToolTipString','Load Analyze image containing finished field map (in Hz)',...\n\t 'CallBack','FieldMap(''LoadFieldMap_Gui'');',...\n 'Tag','LoadFieldMap'); \n \n % Empty string written to Fieldmap value box\n uicontrol(PM,'Style','Text',...\n 'Position',[340 280 50 020].*WS,...\n 'HorizontalAlignment','left',...\n 'String','');\n\n%-Create voxel-displacement-map controls\n\n%-Frames and text\n\n uicontrol(PM,'Style','Frame','BackgroundColor',spm('Colour'),...\n 'Position',[10 10 490 250].*WS);\n uicontrol(PM,'Style','Text',...\n 'String','Create voxel displacement map (VDM) and unwarp EPI',...\n\t 'Position',[70 235 350 020].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times,'FontAngle','Italic')\n uicontrol(PM,'Style','Text',...\n 'String','EPI-based field map',...\n\t 'Position',[50 200 200 020].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text',...\n 'String','Polarity of phase-encode blips',...\n\t 'Position',[50 170 200 020].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text',...\n 'String','Apply Jacobian modulation',...\n\t 'Position',[50 140 200 020].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text',...\n 'String','Total EPI readout time',...\n\t 'Position',[50 110 200 020].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n uicontrol(PM,'Style','Text',...\n 'String','ms',...\n\t 'Position',[370 110 30 020].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times)\n\n%-Objects with Callbacks\n \n\n uicontrol(PM,'style','RadioButton',...\n 'String','Yes',...\n 'Position',[300 200 60 022].*WS,...\n\t 'ToolTipString','Field map is based on EPI data and needs inverting before use',...\n\t 'CallBack','FieldMap(''RadioButton'');',...\n 'Tag','EPI',...\n 'UserData',1);\n uicontrol(PM,'style','RadioButton',...\n 'String','No',...\n 'Position',[370 200 60 022].*WS,...\n\t 'ToolTipString','Phase-map is based on non-EPI (Flash) data and can be used directly',...\n\t 'CallBack','FieldMap(''RadioButton'');',...\n 'Tag','EPI',...\n 'UserData',2);\n\n uicontrol(PM,'style','RadioButton',...\n 'String','+ve',...\n 'Position',[370 170 60 022].*WS,...\n\t 'ToolTipString','K-space is traversed using positive phase-encode blips',...\n\t 'CallBack','FieldMap(''RadioButton'');',...\n 'Tag','BlipDir',...\n 'UserData',1);\n uicontrol(PM,'style','RadioButton',...\n 'String','-ve',...\n 'Position',[300 170 60 022].*WS,...\n\t 'ToolTipString','K-space is traversed using negative phase-encode blips',...\n\t 'CallBack','FieldMap(''RadioButton'');',...\n 'Tag','BlipDir',...\n 'UserData',2);\n uicontrol(PM,'style','RadioButton',...\n 'String','Yes',...\n 'Position',[300 140 60 022].*WS,...\n\t 'ToolTipString','Do Jacobian intensity modulation to compensate for compression/stretching',...\n\t 'CallBack','FieldMap(''RadioButton'');',...\n 'Tag','Jacobian',...\n 'UserData',1);\n uicontrol(PM,'style','RadioButton',...\n 'String','No',...\n 'Position',[370 140 60 022].*WS,...\n\t 'ToolTipString','Don''t do Jacobian intensity modulation to compensate for compression/stretching',...\n\t 'CallBack','FieldMap(''RadioButton'');',...\n 'Tag','Jacobian',...\n 'UserData',2);\n uicontrol(PM,'Style','Edit',...\n 'Position',[300 110 70 024].*WS,...\n\t 'ToolTipString','Give total time for readout of EPI echo train ms',...\n\t 'CallBack','FieldMap(''ReadOutTime'');',...\n 'Tag','ReadTime');\n\n uicontrol(PM,'String','Load EPI image',...\n 'Position',[30 70 120 022].*WS,...\n\t 'ToolTipString','Load sample modulus EPI Analyze image',...\n\t 'CallBack','FieldMap(''LoadEpi_Gui'');',...\n 'Tag','LoadEpi');\n uicontrol(PM,'String','Match VDM to EPI',...\n 'Position',[165 70 120 022].*WS,...\n\t 'ToolTipString','Match vdm to EPI (but only if you want to...)',...\n\t 'CallBack','FieldMap(''MatchVDM_gui'');',...\n 'Tag','MatchVDM');\n uicontrol(PM,'String','Write unwarped',...\n 'Position',[300 70 120 022].*WS,...\n\t 'ToolTipString','Write unwarped EPI Analyze image',...\n\t 'CallBack','FieldMap(''WriteUnwarped_Gui'');',...\n 'Tag','WriteUnwarped');\n uicontrol(PM,'String','Load structural',...\n 'Position',[30 30 120 022].*WS,...\n\t 'ToolTipString','Load structural image (but only if you want to...)',...\n\t 'CallBack','FieldMap(''LoadStructural_Gui'');',...\n 'Tag','LoadStructural');\n uicontrol(PM,'String','Match structural',...\n 'Position',[164 30 120 022].*WS,...\n\t 'ToolTipString','Match structural image to EPI (but only if you want to...)',...\n\t 'CallBack','FieldMap(''MatchStructural_Gui'');',...\n 'Tag','MatchStructural');\n uicontrol(PM,'String','Help',...\n 'Position',[320 30 80 022].*WS,...\n\t 'ToolTipString','Help',...\n\t 'CallBack','FieldMap(''Help_Gui'');',...\n\t 'ForegroundColor','g',...\n 'Tag','Help');\n uicontrol(PM,'String','Quit',...\n 'Position',[420 30 60 022].*WS,...\n 'Enable','On',...\n\t 'ToolTipString','Exit toolbox',...\n\t 'CallBack','FieldMap(''Quit'');',...\n 'ForegroundColor','r',...\n 'Tag','Quit');\n\n uicontrol(PM,'style','RadioButton',...\n 'String','Yes',...\n 'Position',[123 330 48 022].*WS,...\n\t 'ToolTipString','Mask brain using magnitude image before processing',...\n 'CallBack','FieldMap(''MaskBrain'');',...\n 'Tag','MaskBrain',...\n 'UserData',1);\n uicontrol(PM,'style','RadioButton',...\n 'String','No',...\n 'Position',[173 330 46 022].*WS,...\n\t 'ToolTipString','Do not mask brain using magnitude image before processing',...\n\t 'CallBack','FieldMap(''MaskBrain'');',...\n 'Tag','MaskBrain',...\n 'UserData',2);\n\n\n% Find list of default files and set up menu accordingly\n\n def_files = FieldMap('GetDefaultFiles');\n menu_items = FieldMap('DefFiles2MenuItems',def_files);\n if length(menu_items)==1\n uicontrol(PM,'String',menu_items{1},...\n\t\t 'Enable','Off',...\n\t\t 'ToolTipString','Site specific default files',...\n\t\t 'Position',[400 480 60 22].*WS);\n else\n\t uicontrol(PM,'Style','PopUp',...\n\t\t 'String',menu_items,...\n\t\t 'Enable','On',...\n\t\t 'ToolTipString','Site specific default files',...\n\t 'Position',[390 480 90 22].*WS,...\n\t\t 'callback','FieldMap(''DefaultFile_Gui'');',...\n\t 'UserData',def_files);\t\t \n end\n \n%-Apply defaults to buttons\n\n FieldMap('SynchroniseButtons');\n\n %\n % Disable necessary buttons and parameters until phase-map is finished.\n %\n FieldMap('Reset_Gui');\n \n%=======================================================================\n%\n% Make sure buttons reflect current parameter values\n%\n%=======================================================================\n\n case 'synchronisebuttons'\n\n % Set input format\n\n if ~isempty(IP.uflags.iformat)\n if strcmp(IP.uflags.iformat,'RI');\n h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',1);\n\t FieldMap('RadioOn',h);\n IP.uflags.iformat = 'RI';\n else\n h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',2);\n \t FieldMap('RadioOn',h);\n IP.uflags.iformat = 'PM';\n end\n else % Default to RI\n h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',1);\n \t FieldMap('RadioOn',h);\n IP.uflags.iformat = 'RI';\n end\n\n % Set brain masking defaults\n\n if ~isempty(IP.maskbrain)\n if IP.maskbrain == 1\n h = findobj(get(PM,'Children'),'Tag','MaskBrain','UserData',1);\n \t FieldMap('RadioOn',h);\n IP.maskbrain = 1;\n else\n h = findobj(get(PM,'Children'),'Tag','MaskBrain','UserData',2);\n \t FieldMap('RadioOn',h);\n IP.maskbrain = 0;\n end\n else % Default to no\n h = findobj(get(PM,'Children'),'Tag','MaskBrain','UserData',2);\n \t FieldMap('RadioOn',h);\n IP.maskbrain = 0;\n end\n \n % Set echo Times\n\n if ~isempty(IP.et{1})\n h = findobj(get(PM,'Children'),'Tag','ShortTime');\n set(h,'String',sprintf('%2.2f',IP.et{1}));\n end\n\n if ~isempty(IP.et{2})\n h = findobj(get(PM,'Children'),'Tag','LongTime');\n set(h,'String',sprintf('%2.2f',IP.et{2}));\n end\n\n\n % Set EPI field map\n\n if ~isempty(IP.epifm)\n if IP.epifm\n h = findobj(get(PM,'Children'),'Tag','EPI','UserData',1);\n\t FieldMap('RadioOn',h);\n IP.epifm = 1;\n else\n h = findobj(get(PM,'Children'),'Tag','EPI','UserData',2);\n\t FieldMap('RadioOn',h);\n IP.epifm = 0;\n end\n else % Default to yes\n h = findobj(get(PM,'Children'),'Tag','EPI','UserData',1);\n\t FieldMap('RadioOn',h);\n IP.epifm = 1;\n end\n\n % Set apply jacobian\n\n if ~isempty(IP.ajm)\n if IP.ajm\n h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',1);\n\t FieldMap('RadioOn',h);\n IP.ajm = 1;\n else\n h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',2);\n\t FieldMap('RadioOn',h);\n IP.ajm = 0;\n end\n else % Default to no\n h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',2);\n\t FieldMap('RadioOn',h);\n IP.ajm = 0;\n end\n \n % Set blip direction\n\n if ~isempty(IP.blipdir)\n if IP.blipdir == 1\n h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',1);\n \t FieldMap('RadioOn',h);\n IP.blipdir = 1;\n elseif IP.blipdir == -1\n h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',2);\n \t FieldMap('RadioOn',h);\n IP.blipdir = -1;\n else\n error('Invalid phase-encode direction');\n end\n else % Default to -1 = negative\n h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',1);\n \t FieldMap('RadioOn',h);\n IP.blipdir = -1;\n end\n\n % Set total readout time\n\n if ~isempty(IP.tert)\n h = findobj(get(PM,'Children'),'Tag','ReadTime');\n set(h,'String',sprintf('%2.2f',IP.tert));\n end\n\n%=======================================================================\n%\n% Input format was changed \n%\n%=======================================================================\n\n case 'inputformat'\n\n %\n % Enforce radio behaviour.\n %\n index = get(gcbo,'UserData');\n if index==1 \n partner = 2; \n IP.uflags.iformat = 'RI';\n else \n partner = 1; \n IP.uflags.iformat = 'PM';\n end\n\n h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',partner);\n maxv = get(gcbo,'Max');\n value = get(gcbo,'Value');\n\n if value == maxv\n set(h,'Value',get(h,'Min'));\n else\n set(h,'Value',get(h,'Max'));\n end \n \n FieldMap('IFormat_Gui');\n \n%=======================================================================\n%\n% A new default file has been chosen from the popup menu - gui version.\n%\n%=======================================================================\n\n case 'defaultfile_gui'\n m_file = get(gcbo,'UserData');\n m_file = m_file(get(gcbo,'Value'));\n m_file = m_file{1}(1:end-2);\n IP = FieldMap('SetParams',m_file);\n FieldMap('IFormat_Gui');\n FieldMap('SynchroniseButtons');\n \n%=======================================================================\n%\n% Load real or imaginary part of dual echo-time data - gui version.\n%\n%=======================================================================\n\n case 'loadfile_gui'\n\n FieldMap('Reset_Gui');\n % \n % File selection using gui\n %\n index = get(gcbo,'UserData');\n FieldMap('LoadFile',index);\n ypos = [445 420 385 360];\n uicontrol(PM,'Style','Text','String',spm_str_manip(IP.P{index}.fname,['l',num2str(50)]),...\n\t 'Position',[220 ypos(index) 260 20].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times,...\n 'FontSize',FS(8));\n FieldMap('Assert');\n\n%=======================================================================\n%\n% Load phase and magnitude images - gui version.\n%\n%=======================================================================\n\n case 'loadfilepm_gui'\n\n FieldMap('Reset_Gui');\n % \n % File selection using gui\n %\n index = get(gcbo,'UserData');\n FieldMap('LoadFilePM',index);\n ypos = [445 420 385 360];\n uicontrol(PM,'Style','Text','String',spm_str_manip(IP.P{index}.fname,['l',num2str(50)]),...\n\t 'Position',[220 ypos(index) 260 20].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times,...\n 'FontSize',FS(8));\n FieldMap('Assert');\n\n%=======================================================================\n%\n% Create unwrapped phase-map - gui version\n%\n%=======================================================================\n\n case 'createfieldmap_gui'\n\n %\n % Create fieldmap from complex images...\n %\n\n status=FieldMap('CreateFieldMap',IP);\n if ~isempty(status)\n\n FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);\n\n % Toggle relevant buttons\n FieldMap('ToggleGUI','Off','CreateFieldMap');\n FieldMap('ToggleGUI','On',str2mat('LoadFieldMap','WriteFieldMap'));\n %\n % Check that have correct parameters ready before allowing\n % an image to be loaded for unwarping and hence conversion of \n % fieldmap to voxel shift map.\n %\n if (FieldMap('GatherVDMData'))\n FieldMap('FM2VDM',IP);\n FieldMap('ToggleGUI','On',str2mat('LoadEpi','EPI',...\n 'BlipDir','Jacobian','ReadTime'));\n end\n end\n\n%=======================================================================\n%\n% Load already prepared fieldmap (in Hz).\n%\n%=======================================================================\n\n case 'loadfieldmap_gui'\n\n %\n % Reset all previously loaded field maps and images to unwarp\n %\n FieldMap('Reset_gui');\n %\n % Select a precalculated phase map\n %\n\n FieldMap('LoadFieldMap');\n\n uicontrol(PM,'Style','Text','String',spm_str_manip(IP.pP.fname,['l',num2str(50)]),...\n\t 'Position',[220 307 260 20].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'),...\n 'FontName',PF.times,...\n 'FontSize',FS(8));\n\n FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1); \n FieldMap('ToggleGUI','Off',str2mat('CreateFieldMap','WriteFieldMap',...\n 'MatchVDM','WriteUnwarped',...\n 'LoadStructural', 'MatchStructural'));\n \n % Check that have correct parameters ready before allowing\n % an image to be loaded for unwarping and hence conversion of \n % fieldmap to voxel shift map.\n %\n if (FieldMap('GatherVDMData'))\n FieldMap('FM2VDM',IP);\n FieldMap('ToggleGUI','On',str2mat('LoadEpi','EPI',...\n 'BlipDir','Jacobian','ReadTime'));\n end\n\n%=======================================================================\n%\n% Write out field map in Hz - using GUI\n%\n%=======================================================================\n\n case 'writefieldmap_gui'\n \n FieldMap('Write',IP.P{1},IP.fm.fpm,'fpm_',64,'Fitted phase map in Hz');\n \n%=======================================================================\n%\n% Load sample EPI image using gui, unwarp and display result\n%\n%=======================================================================\n\n case 'loadepi_gui'\n\n %\n % Select and display EPI image\n %\n\n FieldMap('LoadEPI');\n FieldMap('DisplayImage',IP.epiP,[.05 .5 .95 .2],2);\n\n % The fm2vdm parameters may have been changed so must calculate\n % the voxel shift map with current parameters.\n \n if (FieldMap('GatherVDMData'))\n FieldMap('FM2VDM',IP);\n FieldMap('UnwarpEPI',IP);\n FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);\n\n % Once EPI has been unwarped can enable unwarp checks and structural stuff\n FieldMap('ToggleGUI','On',str2mat('MatchVDM','WriteUnwarped','LoadStructural'));\n end\n\n %\n % Redisplay phasemap in case .mat file associated with \n % EPI image different from images that filadmap was\n % estimated from.\n %\n FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);\n \n%=======================================================================\n%\n% Coregister fieldmap magnitude image to EPI to unwarp using GUI \n%\n%=======================================================================\n\n case 'matchvdm_gui'\n\n if (FieldMap('GatherVDMData'))\n FieldMap('MatchVDM',IP);\n FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1)\n FieldMap('UnwarpEPI',IP);\n FieldMap('DisplayImage',IP.epiP,[.05 .5 .95 .2],2);\n FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);\n % Once EPI has been unwarped can enable unwarp checks\n FieldMap('ToggleGUI','On',str2mat('MatchVDM','WriteUnwarped','LoadStructural'));\n end\n\n%=======================================================================\n%\n% Load structural image\n%\n%=======================================================================\n\n case 'loadstructural_gui'\n\n FieldMap('LoadStructural');\n FieldMap('DisplayImage',IP.nwarp,[.05 0.0 .95 .2],4);\n %\n % Redisplay the other images to allow for recalculation\n % of size of display.\n %\n FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);\n FieldMap('DisplayImage',IP.epiP,[.05 .5 .95 .2],2);\n FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);\n \n FieldMap('ToggleGUI','On','MatchStructural');\n \n%=======================================================================\n%\n% Match structural image to unwarped EPI\n%\n%=======================================================================\n\n case 'matchstructural_gui'\n\n FieldMap('MatchStructural',IP);\n FieldMap('DisplayImage',IP.nwarp,[.05 0.0 .95 .2],4);\n\n%=======================================================================\n%\n% Write out unwarped EPI\n%\n%=======================================================================\n\n case 'writeunwarped_gui'\n \n unwarp_info=sprintf('Unwarped EPI:echo time difference=%2.2fms, EPI readout time=%2.2fms, Jacobian=%d',IP.uflags.etd, IP.tert,IP.ajm); \n IP.uepiP = FieldMap('Write',IP.epiP,IP.uepiP.dat,'u',IP.epiP.dt(1),unwarp_info);\n FieldMap('ToggleGUI','On', 'LoadStructural');\n FieldMap('ToggleGUI','Off', 'WriteUnwarped');\n\n%=======================================================================\n%\n% Help using spm_help\n%\n%=======================================================================\n\n case 'help_gui'\n\n FieldMap('help');\n\n%=======================================================================\n%\n% Quit Toolbox\n%\n%=======================================================================\n\n case 'quit'\n\n Fgraph=spm_figure('FindWin','Graphics');\n if ~isempty(Fgraph)\n\t if DGW\n delete(Fgraph);\n Fgraph=[];\n\t DGW = 0;\n\t else\n spm_figure('Clear','Graphics');\n end \n end\n PM=spm_figure('FindWin','FieldMap');\n if ~isempty(PM)\n delete(PM);\n PM=[];\n end\n\n%=======================================================================\n%\n% The following functions are GUI related functions that go on behind \n% the scenes.\n%=======================================================================\n%\n%=======================================================================\n%\n% Reset gui inputs when a new field map is to be calculated\n%\n%=======================================================================\n\n case 'reset_gui'\n\n % Clear any precalculated fieldmap name string\n uicontrol(PM,'Style','Text','String','',...\n\t 'Position',[230 307 260 20].*WS,...\n\t 'ForegroundColor','k','BackgroundColor',spm('Colour'));\n\n % Clear Fieldmap values\n uicontrol(PM,'Style','Text',...\n 'Position',[350 280 50 020].*WS,...\n 'HorizontalAlignment','left',...\n 'String','');\n\n % Disable input routes to make sure \n % a new fieldmap is calculated.\n %\n FieldMap('ToggleGUI','Off',str2mat('CreateFieldMap','WriteFieldMap',...\n 'LoadEpi','WriteUnwarped','MatchVDM',...\n 'LoadStructural','MatchStructural',...\n 'EPI','BlipDir',...\n 'Jacobian','ReadTime'));\n %\n % A new input image implies all processed data is void.\n %\n IP.fm = [];\n IP.vdm = [];\n IP.jim = [];\n IP.pP = [];\n IP.epiP = [];\n IP.uepiP = [];\n IP.vdmP = [];\n IP.fmagP = [];\n IP.wfmagP = [];\n ID = cell(4,1);\n\n spm_orthviews('Reset');\n spm_figure('Clear','Graphics');\n\n%=======================================================================\n%\n% Use gui for Real and Imaginary or Phase and Magnitude.\n%\n%=======================================================================\n\n case 'iformat_gui'\n\n FieldMap('Reset_Gui');\n\n % Load Real and Imaginary or Phase and Magnitude Buttons\n if IP.uflags.iformat=='PM'\n h=findobj('Tag','LoadRI');\n set(h,'Visible','Off');\n uicontrol(PM,'String','Load Phase',...\n 'Position',[125 450 90 022].*WS,...\n\t 'ToolTipString','Load Analyze image containing first phase image',...\n\t 'CallBack','FieldMap(''LoadFilePM_Gui'');',...\n 'UserData',1,...\n 'Tag','LoadPM');\n uicontrol(PM,'String','Load Mag.',...\n 'Position',[125 425 90 022].*WS,...\n\t 'ToolTipString','Load Analyze image containing first magnitude image',...\n\t 'CallBack','FieldMap(''LoadFilePM_Gui'');',...\n 'UserData',2,...\n 'Tag','LoadPM');\n uicontrol(PM,'String','Load Phase',...\n 'Position',[125 390 90 022].*WS,...\n\t 'ToolTipString','Load Analyze image containing second phase image',...\n\t 'CallBack','FieldMap(''LoadFilePM_Gui'');',...\n 'UserData',3,...\n 'Tag','LoadPM');\n uicontrol(PM,'String','Load Mag.',...\n 'Position',[125 365 90 022].*WS,...\n\t 'ToolTipString','Load Analyze image containing second magnitudeimage',...\n\t 'CallBack','FieldMap(''LoadFilePM_Gui'');',...\n 'UserData',4,...\n 'Tag','LoadPM');\n else\n\n % make the objects we don't want invisible\n h=findobj('Tag','LoadPM');\n set(h,'Visible','Off');\n\n uicontrol(PM,'String','Load Real',...\n 'Position',[125 450 90 022].*WS,...\n\t 'ToolTipString','Load Analyze image containing real part of short echo-time image',...\n\t 'CallBack','FieldMap(''LoadFile_Gui'');',...\n 'UserData',1,...\n 'Tag','LoadRI');\n uicontrol(PM,'String','Load Imag',...\n 'Position',[125 425 90 022].*WS,...\n\t 'ToolTipString','Load Analyze image containing imaginary part of short echo-time image',...\n\t 'CallBack','FieldMap(''LoadFile_Gui'');',...\n 'UserData',2,...\n 'Tag','LoadRI');\n uicontrol(PM,'String','Load Real',...\n 'Position',[125 390 90 022].*WS,...\n\t 'ToolTipString','Load Analyze image containing real part of long echo-time image',...\n\t 'CallBack','FieldMap(''LoadFile_Gui'');',...\n 'UserData',3,...\n 'Tag','LoadRI');\n uicontrol(PM,'String','Load Imag',...\n 'Position',[125 365 90 022].*WS,...\n\t 'ToolTipString','Load Analyze image containing imaginary part of long echo-time image',...\n\t 'CallBack','FieldMap(''LoadFile_Gui'');',...\n 'UserData',4,...\n 'Tag','LoadRI');\n end\n\n%=======================================================================\n%\n% Brain masking or not\n%\n%=======================================================================\n\n case 'maskbrain'\n\n FieldMap('Reset_Gui');\n %\n % Enforce radio behaviour.\n %\n index = get(gcbo,'UserData');\n if index==1 \n partner=2; \n IP.maskbrain=1;\n else \n partner=1; \n IP.maskbrain=0;\n end\n tag = get(gcbo,'Tag');\n value = get(gcbo,'Value');\n maxv = get(gcbo,'Max');\n h = findobj(get(PM,'Children'),'Tag',tag,'UserData',partner);\n if value == maxv\n set(h,'Value',get(h,'Min'));\n else\n set(h,'Value',get(h,'Max'));\n end \n\n FieldMap('Assert');\n\n%=======================================================================\n%\n% Echo time was changed or entered\n%\n%=======================================================================\n\n case 'echotime'\n\n FieldMap('Assert');\n\n%=======================================================================\n%\n% Check if inputs are correct for calculating new phase map\n%\n%=======================================================================\n\n case 'assert'\n\n if ~isempty(IP.pP) % If we're using precalculated fieldmap.\n go = 0;\n else\n go = 1;\n for i=1:2\n if isempty(IP.P{i}) go = 0; end\n end\n for i=3:4\n if (isempty(IP.P{i}) & IP.uflags.iformat=='RI') go = 0; end\n end \n h = findobj(get(PM,'Children'),'Tag','ShortTime');\n IP.et{1} = str2num(get(h,'String'));\n h = findobj(get(PM,'Children'),'Tag','LongTime');\n IP.et{2} = str2num(get(h,'String'));\n if isempty(IP.et{1}) | isempty(IP.et{2}) | IP.et{2} < IP.et{1}\n go = 0;\n end\n end\n if go\n FieldMap('ToggleGui','On','CreateFieldMap');\n else % Switch off fieldmap creation\n FieldMap('ToggleGui','Off','CreateFieldMap');\n end \n\n%=======================================================================\n%\n% Enable or disable specified buttons or parameters in GUI\n%\n%=======================================================================\n\n case 'togglegui'\n\n h = get(PM,'Children');\n tags=varargin{3};\n for n=1:size(varargin{3},1)\n set(findobj(h,'Tag',deblank(tags(n,:))),'Enable',varargin{2});\n end\n\n%=======================================================================\n%\n% A radiobutton was pressed.\n%\n%=======================================================================\n\n case 'radiobutton'\n\n %\n % Enforce radio behaviour.\n %\n index = get(gcbo,'UserData');\n if index==1 \n partner=2; \n else \n partner=1; \n end\n tag = get(gcbo,'Tag');\n value = get(gcbo,'Value');\n maxv = get(gcbo,'Max');\n h = findobj(get(PM,'Children'),'Tag',tag,'UserData',partner);\n if value == maxv\n set(h,'Value',get(h,'Min'));\n else\n set(h,'Value',get(h,'Max'));\n end \n\n % Update Hz to voxel displacement map if the input parameters are ok\n if (FieldMap('GatherVDMData'))\n\n FieldMap('FM2VDM',IP);\n %\n % Update unwarped EPI if one is loaded\n %\n if ~isempty(IP.epiP) \n IP.uepiP = FieldMap('UnwarpEPI',IP);\n FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);\n FieldMap('ToggleGUI','On',str2mat('WriteUnwarped')); \n end\n end\n\n%=======================================================================\n%\n% Enforce radio-button behaviour\n%\n%=======================================================================\n\n case 'radioon'\n my_gcbo = varargin{2};\n index = get(my_gcbo,'UserData');\n if index==1 \n partner=2; \n else \n partner=1; \n end\n set(my_gcbo,'Value',get(my_gcbo,'Max'));\n h = findobj(get(PM,'Children'),'Tag',get(my_gcbo,'Tag'),'UserData',partner);\n set(h,'Value',get(h,'Min')); \n \n%=======================================================================\n%\n% Total readout-time was changed or entered\n%\n%=======================================================================\n\n case 'readouttime'\n\n %\n % Update unwarped EPI\n %\n % This means the transformation phase-map to voxel displacement-map\n % has changed, which means the inversion will have to be redone,\n % which means (in the case of flash-based field map) coregistration\n % between field-map and sample EPI image should be redone. Phew!\n %\n \t\t\t\t\t\t\t \n if (FieldMap('GatherVDMData')) \n FieldMap('FM2VDM',IP);\n % Update unwarped EPI if one is loaded\n if ~isempty(IP.epiP) \n IP.uepiP = FieldMap('UnwarpEPI',IP);\n FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);\n FieldMap('ToggleGUI','On',str2mat('WriteUnwarped',...\n\t 'LoadStructural'));\n end\n FieldMap('ToggleGUI','On',str2mat('LoadEpi','EPI','BlipDir',...\n 'Jacobian','ReadTime')); \n else\n % If readtime is missing switch everything off...\n FieldMap('ToggleGUI','Off',str2mat('LoadEpi','EPI',...\n 'BlipDir','Jacobian',...\n\t 'WriteUnwarped','LoadStructural',...\n 'MatchStructural', 'MatchVDM'));\n end\n\n%=======================================================================\n%\n% Sample UIControls pertaining to information needed for transformation\n% phase-map -> voxel displacement-map\n%\n%=======================================================================\n\n case 'gathervdmdata'\n\n h = findobj(get(PM,'Children'),'Tag','EPI','UserData',1);\n v = get(h,{'Value','Max'});\n if v{1} == 1 \n IP.epifm = 1; \n else\n IP.epifm = 0; \n end\n h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',1);\n v = get(h,{'Value','Max'});\n if v{1} == 1 %% CHLOE: Changed \n IP.blipdir = 1; \n else\n IP.blipdir = -1; \n end\n h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',1);\n v = get(h,{'Value','Max'});\n if v{1} == 1 %% CHLOE: Changed \n IP.ajm = 1; \n else\n IP.ajm = 0; \n end\n h = findobj(get(PM,'Children'),'Tag','ReadTime');\n IP.tert = str2num(get(h,'String'));\n\n if isempty(IP.tert) | isempty(IP.fm) | isempty(IP.fm.fpm) \n varargout{1} = 0;\n FieldMap('ToggleGui','On','ReadTime');\n else\n varargout{1} = 1;\n end\n \n%=======================================================================\n%\n% Draw transversal and sagittal image.\n%\n%=======================================================================\n\n case 'redrawimages'\n global curpos;\n\n for i=1:length(ID)\n if ~isempty(ID{i}) & ~isempty(st.vols{i})\n set(st.vols{i}.ax{2}.ax,'Visible','Off'); % Disable event delivery in Coronal\n set(st.vols{i}.ax{2}.d,'Visible','Off'); % Make Coronal invisible\n set(st.vols{i}.ax{1}.ax,'Position',ID{i}.tra_pos); \n set(st.vols{i}.ax{1}.ax,'ButtonDownFcn',['FieldMap(''Orthviews'');']);\n set(get(st.vols{i}.ax{1}.ax,'YLabel'),'String',ID{i}.label); \n set(st.vols{i}.ax{3}.ax,'Position',ID{i}.sag_pos); \n set(st.vols{i}.ax{3}.ax,'ButtonDownFcn',['FieldMap(''Orthviews'');']);\n end\n end\n \n%=======================================================================\n%\n% Callback for orthviews\n%\n%=======================================================================\n\n case 'orthviews' \n \n if strcmp(get(gcf,'SelectionType'),'normal')\n spm_orthviews('Reposition');,...\n %spm_orthviews('set_pos2cm');,...\n elseif strcmp(get(gcf,'SelectionType'),'extend')\n spm_orthviews('Reposition');,...\n %spm_orthviews('set_pos2cm');,...\n spm_orthviews('context_menu','ts',1);\n end;\n curpos = spm_orthviews('pos',1); \n set(st.in, 'String',sprintf('%3.3f',spm_sample_vol(st.vols{1},curpos(1),curpos(2),curpos(3),st.hld)));\n\n%=======================================================================\n%\n% Display image.\n%\n%=======================================================================\n\n case 'displayimage'\n\n Fgraph=spm_figure('FindWin','Graphics');\n if isempty(Fgraph)\n st.fig=spm_figure('Create','Graphics','Graphics');\n\t DGW = 1;\n end\n\n if ~isempty(ID{varargin{4}})\n spm_orthviews('Delete',ID{varargin{4}}.h);\n ID{varargin{4}} = [];\n end\n\n h = spm_orthviews('Image',varargin{2},[.01 .01 .01 .01]);\n\n % Set bounding box to allow display of all images\n spm_orthviews('MaxBB'); \n \n % Put everything in space of original EPI image.\n if varargin{4} == 2\n\t %spm_orthviews('Space',h); % This was deleted for some reason\n end\n \n %\n % Get best possible positioning and scaling for\n % transversal and sagittal views.\n %\n tra_pos = get(st.vols{varargin{4}}.ax{1}.ax,'Position');\n sag_pos = get(st.vols{varargin{4}}.ax{3}.ax,'Position');\n field_pos = varargin{3};\n x_scale = field_pos(3) / (tra_pos(3) + sag_pos(3));\n height = max([tra_pos(4) sag_pos(4)]);\n y_scale = field_pos(4) / height;\n if x_scale > y_scale % Height limiting\n scale = y_scale;\n dx = (field_pos(3) - scale*(tra_pos(3) + sag_pos(3))) / 3;\n dy = 0;\n else % Width limiting\n scale = x_scale;\n dx = 0;\n dy = (field_pos(4) - scale*height) / 2;\n end\n tra_pos = [field_pos(1)+dx field_pos(2)+dy scale*tra_pos([3 4])];\n sag_pos = [field_pos(1)+tra_pos(3)+2*dx field_pos(2)+dy scale*sag_pos([3 4])];\n label = {'Fieldmap in Hz',...\n 'Warped EPI',...\n 'Unwarped EPI',...\n 'Structural'};\n ID{varargin{4}} = struct('tra_pos', tra_pos,...\n 'sag_pos', sag_pos,...\n 'h', h,...\n 'label', label{varargin{4}});\n FieldMap('RedrawImages');\n \n st.in = uicontrol(PM,'Style','Text',...\n 'Position',[340 280 50 020].*WS,...\n 'HorizontalAlignment','left',...\n 'String','');\n \n%=======================================================================\n%=======================================================================\n%\n% The functions below are called by the various gui buttons but are\n% not dependent on the gui to work. These functions can therefore also\n% be called from a script bypassing the gui and can return updated \n% variables.\n%\n%=======================================================================\n%=======================================================================\n%\n%=======================================================================\n%\n% Create and initialise parameters for FieldMap toolbox\n%\n%=======================================================================\n\n case 'initialise'\n \n %\n % Initialise parameters\n %\n ID = cell(4,1);\n IP.P = cell(1,4);\n IP.pP = [];\n IP.fmagP = [];\n IP.wfmagP = [];\n IP.epiP = [];\n IP.uepiP = [];\n IP.nwarp = [];\n IP.fm = [];\n IP.vdm = [];\n IP.et = cell(1,2);\n IP.epifm = [];\n IP.blipdir = [];\n IP.ajm = [];\n IP.tert = [];\n IP.vdmP = []; %% Check that this should be there %%\n IP.maskbrain = [];\n IP.uflags = struct('iformat','','method','','fwhm',[],'bmask',[],'pad',[],'etd',[],'ws',[]);\n IP.mflags = struct('template',[],'fwhm',[],'nerode',[],'ndilate',[],'thresh',[],'reg',[],'graphics',0);\n\n % Initially set brain mask to be empty \n IP.uflags.bmask = [];\n\n % Set parameter values according to defaults\n FieldMap('SetParams');\n \n varargout{1}= IP;\n\n%=======================================================================\n%\n% Sets parameters according to the defaults file that is being passed\n%\n%=======================================================================\n\n case 'setparams'\n if nargin == 1\n\t pm_defaults; % \"Default\" default file\n else \n\t eval(varargin{2}); % Scanner or sequence specific default file\n end\n\n % Define parameters for fieldmap creation\n IP.et{1} = pm_def.SHORT_ECHO_TIME;\n IP.et{2} = pm_def.LONG_ECHO_TIME;\n IP.maskbrain = pm_def.MASKBRAIN;\n\n % Set parameters for unwrapping\n IP.uflags.iformat = pm_def.INPUT_DATA_FORMAT;\n IP.uflags.method = pm_def.UNWRAPPING_METHOD;\n IP.uflags.fwhm = pm_def.FWHM;\n IP.uflags.pad = pm_def.PAD;\n IP.uflags.ws = pm_def.WS;\n IP.uflags.etd = pm_def.LONG_ECHO_TIME - pm_def.SHORT_ECHO_TIME; \n\n % Set parameters for brain masking\n IP.mflags.template = pm_def.MFLAGS.TEMPLATE;\n IP.mflags.fwhm = pm_def.MFLAGS.FWHM;\n IP.mflags.nerode = pm_def.MFLAGS.NERODE;\n IP.mflags.ndilate = pm_def.MFLAGS.NDILATE;\n IP.mflags.thresh = pm_def.MFLAGS.THRESH;\n IP.mflags.reg = pm_def.MFLAGS.REG;\n IP.mflags.graphics = pm_def.MFLAGS.GRAPHICS;\n\n % Set parameters for unwarping \n IP.ajm = pm_def.DO_JACOBIAN_MODULATION;\n IP.blipdir = pm_def.K_SPACE_TRAVERSAL_BLIP_DIR;\n IP.tert = pm_def.TOTAL_EPI_READOUT_TIME;\n IP.epifm = pm_def.EPI_BASED_FIELDMAPS;\n\n varargout{1}= IP;\n\n%=======================================================================\n%\n% Get a list of all the default files that are present\n%\n%=======================================================================\n\n case 'getdefaultfiles'\n fmdir = fullfile(spm('Dir'),'toolbox','FieldMap');\n defdir = dir(fullfile(fmdir,'pm_defaults*.m'));\n for i=1:length(defdir)\n\t if defdir(i).name(12) ~= '.' & defdir(i).name(12) ~= '_'\n\t error(sprintf('Error in default file spec: %s',defdir(i).name));\n\t end\n\t defnames{i} = defdir(i).name;\n end\n varargout{1} = defnames;\n\n%=======================================================================\n%\n% Get list of menuitems from list of default files\n%\n%=======================================================================\n\n case 'deffiles2menuitems'\n for i=1:length(varargin{2})\n\t if strcmp(varargin{2}{i},'pm_defaults.m');\n\t menit{i} = 'Default';\n\t else\n\t endindx = strfind(varargin{2}{i},'.m');\n\t menit{i} = varargin{2}{i}(13:(endindx-1));\n\t end\n end\n varargout{1} = menit;\n \n%=======================================================================\n%\n% Scale a phase map so that max = pi and min =-pi radians.\n%\n%=======================================================================\n\n case 'scale'\n\n F=varargin{2};\n V=spm_vol(F);\n vol=spm_read_vols(V);\n mn=min(vol(:));\n mx=max(vol(:));\n vol=-pi+(vol-mn)*2*pi/(mx-mn);\n varargout{1} = FieldMap('Write',V,vol,'sc',V.dt(1),V.descrip);\n\n%=======================================================================\n%\n% Load real or imaginary part of dual echo-time data - NO gui.\n%\n%=======================================================================\n\n case 'loadfile'\n\n index=varargin{2};\n prompt_string = {'Select short echo-time real',...\n 'Select short echo-time imaginary',...\n 'Select long echo-time real',...\n 'Select long echo-time imaginary'};\n %IP.P{index} = spm_vol(spm_get(1,'*.img',prompt_string{index}));\n % SPM\n IP.P{index} = spm_vol(spm_select(1,'image',prompt_string{index}));\n\n if isfield(IP,'pP') & ~isempty(IP.pP)\n\t IP.pP = [];\n end\n varargout{1} = IP.P{index};\n\n%=======================================================================\n%\n% Load phase or magnitude part of dual (possibly) echo-time data - NO gui.\n%\n%=======================================================================\n\n case 'loadfilepm'\n\n index=varargin{2};\n prompt_string = {'Select phase image',...\n 'Select magnitude image',...\n 'Select second phase image or press done',...\n 'Select magnitude image or press done'};\n if index<3\n %IP.P{index} = spm_vol(spm_get(1,'*.img',prompt_string{index}));\n % SPM5 Update\n IP.P{index} = spm_vol(spm_select(1,'image',prompt_string{index}));\n if index==1\n do=spm_input('Scale this to radians?',1,'b','Yes|No',[1,0]);\n Finter=spm_figure('FindWin','Interactive');\n close(Finter);\n if do==1\n tmp=FieldMap('Scale',IP.P{index}.fname);\n IP.P{index} = spm_vol(tmp.fname);\n end\n end\n else\n %IP.P{index} = spm_vol(spm_get([0 1],'*.img',prompt_string{index}));\n % SPM5 Update\n IP.P{index} = spm_vol(spm_select([0 1],'image',prompt_string{index}));\n if index==3 & ~isempty(IP.P{index})\n do=spm_input('Scale this to radians?',1,'b','Yes|No',[1,0]);\n Finter=spm_figure('FindWin','Interactive');\n close(Finter);\n if do==1\n tmp=FieldMap('Scale',IP.P{index}.fname);\n IP.P{index} = spm_vol(tmp.fname);\n end\n end\n end\n if isfield(IP,'pP') & ~isempty(IP.pP)\n\t IP.pP = [];\n end\n varargout{1} = IP.P{index};\n\n%=======================================================================\n%\n% Load already prepared fieldmap (in Hz) - no gui\n%\n%=======================================================================\n\n case 'loadfieldmap'\n\n %\n % Select field map\n %\n % 24/03/04 - Chloe change below to spm_get(1,'fpm_*.img')... \n % IP.pP = spm_vol(spm_get(1,'fpm_*.img','Select field map'));\n % SPM5 Update\n IP.pP = spm_vol(spm_select(1,'^fpm.*\\.img$','Select field map'));\n\n IP.fm.fpm = spm_read_vols(IP.pP);\n IP.fm.jac = pm_diff(IP.fm.fpm,2);\n if isfield(IP,'P') & ~isempty(IP.P{1})\n\t IP.P = cell(1,4);\n end\n varargout{1} = IP.fm;\n varargout{2} = IP.pP;\n\n%=======================================================================\n%\n% Create unwrapped phase-map - NO gui\n%\n%=======================================================================\n\n case 'createfieldmap'\n\n IP=varargin{2};\n\n % First check that images are in same space. \n\n if size([IP.P{1} IP.P{2} IP.P{3} IP.P{4}],2)==4\n ip_dim=cat(1,[IP.P{1}.dim' IP.P{2}.dim' IP.P{3}.dim' IP.P{4}.dim']');\n ip_mat=cat(2,[IP.P{1}.mat(:) IP.P{2}.mat(:) IP.P{3}.mat(:) IP.P{4}.mat(:)]');\n else\n ip_dim=cat(1,[IP.P{1}.dim' IP.P{2}.dim']');\n ip_mat=cat(2,[IP.P{1}.mat(:) IP.P{2}.mat(:)]');\n end\n\n if any(any(diff(ip_dim,1,1),1)&[1,1,1])\n errordlg({'Images don''t all have same dimensions'});\n drawnow;\n varargout{1}=[];\n elseif any(any(diff(ip_mat,1,1),1))\n\terrordlg({'Images don''t all have same orientation & voxel size'});\n drawnow;\n varargout{1}=[];\n else\n % Update flags for unwarping (in case TEs have been adjusted\n IP.uflags.etd = IP.et{2}-IP.et{1}; \n\n % Clear any brain mask \n IP.uflags.bmask = [];\n\n % SPM5 Update\n % If flag selected to mask brain and the field map is not based on EPI\n if IP.maskbrain==1 \n IP.fmagP = FieldMap('Magnitude',IP);\n IP.uflags.bmask = pm_brain_mask(IP.fmagP,IP.mflags);\n varargout{2} = IP.fmagP;\n end\n\n IP.fm = pm_make_fieldmap([IP.P{1} IP.P{2} IP.P{3} IP.P{4}],IP.uflags);\n varargout{1} = IP.fm;\n end\n\n%=======================================================================\n%\n% Convert field map to voxel displacement map and \n% do necessary inversions of displacement fields.\n%\n%=======================================================================\n\n case 'fm2vdm'\n\n IP=varargin{2};\n %\n % If we already have memory mapped image pointer to voxel\n % displacement map let's reuse it (so not to void possible\n % realignment). If field-map is non-EPI based the previous\n % realignment (based on different parameters) will be non-\n % optimal and we should advice user to redo it.\n %\n % If no pointer already exist we'll make one.\n %\n if isfield(IP,'vdmP') & ~isempty(IP.vdmP)\n\t msgbox({'Changing this parameter means that if previously',...\n 'you matched VDM to EPI, this result may no longer',...\n 'be optimal. In this case we recommend you redo the',...\n 'Match VDM to EPI.'},...\n\t\t 'Coregistration notice','warn','modal');\n else\n if ~isempty(IP.pP)\n IP.vdmP = struct('dim', IP.pP.dim(1:3),...\n 'dt',[4 spm_platform('bigend')],...\n 'mat', IP.pP.mat);\n IP.vdmP.fname=fullfile(spm_str_manip(IP.pP.fname, 'h'),['vdm5_' deblank(spm_str_manip(IP.pP.fname,'t'))]);\n else\n IP.vdmP = struct('dim', IP.P{1}.dim(1:3),...\n 'dt',[4 spm_platform('bigend')],...\n 'mat', IP.P{1}.mat);\n IP.vdmP.fname=fullfile(spm_str_manip(IP.P{1}.fname, 'h'),['vdm5_' deblank(spm_str_manip(IP.P{1}.fname,'t'))]);\n end\n end\n\n % Scale field map and jacobian by total EPI readout time\n IP.vdm.vdm = IP.blipdir*IP.tert*1e-3*IP.fm.fpm;\n IP.vdm.jac = IP.blipdir*IP.tert*1e-3*IP.fm.jac;\n\n % Chloe added this: 26/02/05\n % Put fieldmap parameters in descrip field of vdm\n\n vdm_info=sprintf('Voxel Displacement Map:echo time difference=%2.2fms, EPI readout time=%2.2fms',IP.uflags.etd, IP.tert); \n if IP.epifm ==1\n spm_progress_bar('Init',3,'Inverting displacement map','');\n spm_progress_bar('Set',1);\n % Invert voxel shift map and multiply by -1...\n IP.vdm.ivdm = pm_invert_phasemap(-1*IP.vdm.vdm);\n\t IP.vdm.ijac = pm_diff(IP.vdm.ivdm,2); \n spm_progress_bar('Set',2);\n spm_progress_bar('Clear');\n FieldMap('Write',IP.vdmP,IP.vdm.ivdm,'',IP.vdmP.dt(1),vdm_info);\n else\n FieldMap('Write',IP.vdmP,IP.vdm.vdm,'',IP.vdmP.dt(1),vdm_info);\n end\n varargout{1} = IP.vdm;\n varargout{2} = IP.vdmP;\n\n%=======================================================================\n%\n% Write out image\n%\n%=======================================================================\n\n case 'write'\n \n V=varargin{2};\n vol=varargin{3};\n name=varargin{4};\n\n % Write out image\n img=struct('dim', V.dim(1:3),...\n 'dt', [varargin{5} spm_platform('bigend')],...\n 'mat', V.mat);\n \n img.fname=fullfile(spm_str_manip(V.fname, 'h'),[name deblank(spm_str_manip(V.fname,'t'))]);\n img.descrip=varargin{6};\n img=spm_write_vol(img,vol);\n varargout{1}=img;\n\n%=======================================================================\n%\n% Create fieldmap (Hz) struct for use when displaying image.\n%\n%=======================================================================\n\n case 'makedp'\n\n if isfield(IP,'vdmP') & ~isempty(IP.vdmP);\n dP = struct('dim', IP.vdmP.dim,...\n 'dt',[64 spm_platform('bigend')],...\n 'pinfo', [1 0]',...\n 'mat', IP.vdmP.mat,...\n 'dat', reshape(IP.fm.fpm,IP.vdmP.dim),...\n 'fname', 'display_image');\n else\n if isfield(IP,'P') & ~isempty(IP.P{1})\n dP = struct('dim', IP.P{1}.dim,...\n 'dt',[64 spm_platform('bigend')],...\n 'pinfo', [1 0]',...\n 'mat', IP.P{1}.mat,...\n 'dat', reshape(IP.fm.fpm,IP.P{1}.dim),...\n 'fname', 'display_image');\n elseif isfield(IP,'pP') & ~isempty(IP.pP)\n dP = struct('dim', IP.pP.dim,...\n 'dt',[64 spm_platform('bigend')],...\n 'pinfo', [1 0]',...\n 'mat', IP.pP.mat,...\n 'dat', reshape(IP.fm.fpm,IP.pP.dim),...\n 'fname', 'display_image');\n end\n end\n varargout{1} = dP;\n\n%=======================================================================\n%\n% Load sample EPI image - NO gui\n%\n%=======================================================================\n\n case 'loadepi'\n\n %\n % Select EPI\n %\n %IP.epiP = spm_vol(spm_get(1,'*.img','Select sample EPI image'));\n % SPM5 Update\n IP.epiP = spm_vol(spm_select(1,'image','Select sample EPI image'));\n\n varargout{1} = IP.epiP;\n\n%=======================================================================\n%\n% Create unwarped epi - NO gui\n%\n%=======================================================================\n\n case 'unwarpepi'\n \n %\n % Update unwarped EPI\n %\n IP=varargin{2};\n IP.uepiP = struct('fname', 'Image in memory',...\n 'dim', IP.epiP.dim,...\n 'dt',[64 spm_platform('bigend')],...\n 'pinfo', IP.epiP.pinfo(1:2),...\n 'mat', IP.epiP.mat);\n\n % Need to sample EPI and voxel shift map in space of EPI...\n [x,y,z] = ndgrid(1:IP.epiP.dim(1),1:IP.epiP.dim(2),1:IP.epiP.dim(3));\n xyz = [x(:) y(:) z(:)];\n\n % Space of EPI is IP.epiP{1}.mat and space of \n % voxel shift map is IP.vdmP{1}.mat \n tM = inv(IP.epiP.mat\\IP.vdmP.mat);\n\n x2 = tM(1,1)*x + tM(1,2)*y + tM(1,3)*z + tM(1,4);\n y2 = tM(2,1)*x + tM(2,2)*y + tM(2,3)*z + tM(2,4);\n z2 = tM(3,1)*x + tM(3,2)*y + tM(3,3)*z + tM(3,4);\n xyz2 = [x2(:) y2(:) z2(:)];\n\n %\n % Make mask since it is only meaningful to calculate undistorted\n % image in areas where we have information about distortions.\n %\n msk = reshape(double(xyz2(:,1)>=1 & xyz2(:,1)<=IP.vdmP.dim(1) &...\n\t\t xyz2(:,2)>=1 & xyz2(:,2)<=IP.vdmP.dim(2) &...\n\t\t xyz2(:,3)>=1 & xyz2(:,3)<=IP.vdmP.dim(3)),IP.epiP.dim(1:3));\n\t \n % Read in voxel displacement map in correct space\n tvdm = reshape(spm_sample_vol(spm_vol(IP.vdmP.fname),xyz2(:,1),...\n xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));\n\n % Voxel shift map must be added to the y-coordinates. \n uepi = reshape(spm_sample_vol(IP.epiP,xyz(:,1),...\n xyz(:,2)+tvdm(:),xyz(:,3),1),IP.epiP.dim(1:3));% TEMP CHANGE\n \n % Sample Jacobian in correct space and apply if required \n if IP.ajm==1\n if IP.epifm==1 % If EPI, use inverted jacobian\n\n IP.jim = reshape(spm_sample_vol(IP.vdm.ijac,xyz2(:,1),...\n xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));\n else\n IP.jim = reshape(spm_sample_vol(IP.vdm.jac,xyz2(:,1),...\n xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));\n end \n uepi = uepi.*(1+IP.jim);\n end\n\n IP.uepiP.dat=uepi.*msk;\n varargout{1}=IP.uepiP;\n\n%=======================================================================\n%\n% Coregister fieldmap magnitude image to EPI to unwarp \n%\n%=======================================================================\n\n case 'matchvdm'\n \n IP=varargin{2};\n\n % \n % Need a fieldmap magnitude image\n %\n\n if isempty(IP.pP) & ~isempty(IP.P{1})\n\n IP.fmagP=struct('dim', IP.P{1}.dim,...\n\t 'dt',IP.P{1}.dt,...\n 'pinfo', IP.P{1}.pinfo,...\n 'mat', IP.P{1}.mat);\n IP.fmagP.fname=fullfile(spm_str_manip(IP.P{1}.fname, 'h'),['mag_' deblank(spm_str_manip(IP.P{1}.fname,'t'))]);\n\n \n % If using real and imaginary data, calculate using sqrt(i1.^2 + i2.^2).\n % If using phase and magnitude, use magnitude image.\n if IP.uflags.iformat=='RI' \n IP.fmagP = spm_imcalc(spm_vol([IP.P{1}.fname;IP.P{2}.fname]),IP.fmagP,'sqrt(i1.^2 + i2.^2)');\n else\n IP.fmagP = IP.P{2};\n end\n elseif ~isempty(IP.pP) & ~isempty(IP.fmagP)\n msg=sprintf('Using %s for matching\\n',IP.fmagP.fname);\n disp(msg);\n else\n %IP.fmagP = spm_vol(spm_get(1,'*.img','Select field map magnitude image'));\n % SPM5 Update\n IP.fmagP = spm_vol(spm_select(1,'image','Select field map magnitude image'));\n end\n\n % Now we have field map magnitude image, we want to coregister it to the \n % EPI to be unwarped. \n % If using an EPI field map:\n % 1) Coregister magnitude image to EPI.\n % 2) Apply resulting transformation matrix to voxel shift map\n % If using a non-EPI field map:\n % 1) Forward warp magnitude image\n % 2) Coregister warped magnitude image to EPI.\n % 3) Apply resulting transformation matrix to voxel shift map\n \n if IP.epifm==1\n [mi,M] = FieldMap('Coregister',IP.epiP,IP.fmagP);\n MM = IP.fmagP.mat;\n else\n % Need to sample magnitude image in space of EPI to be unwarped...\n [x,y,z] = ndgrid(1:IP.epiP.dim(1),1:IP.epiP.dim(2),1:IP.epiP.dim(3));\n xyz = [x(:) y(:) z(:)];\n\n % Space of EPI is IP.epiP{1}.mat and space of fmagP is IP.fmagP.mat \n tM = inv(IP.epiP.mat\\IP.fmagP.mat);\n x2 = tM(1,1)*x + tM(1,2)*y + tM(1,3)*z + tM(1,4);\n y2 = tM(2,1)*x + tM(2,2)*y + tM(2,3)*z + tM(2,4);\n z2 = tM(3,1)*x + tM(3,2)*y + tM(3,3)*z + tM(3,4);\n xyz2 = [x2(:) y2(:) z2(:)];\n wfmag = reshape(spm_sample_vol(IP.fmagP,xyz2(:,1),...\n xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3)); \n\n % Need to sample voxel shift map in space of EPI to be unwarped\n tvdm = reshape(spm_sample_vol(IP.vdm.vdm,xyz2(:,1),...\n xyz2(:,2),xyz2(:,3),0),IP.epiP.dim(1:3)); \n \n % Now apply warps to resampled forward warped magnitude image...\n wfmag = reshape(spm_sample_vol(wfmag,xyz(:,1),xyz(:,2)-tvdm(:),...\n xyz(:,3),1),IP.epiP.dim(1:3));\n \n % Write out forward warped magnitude image\n IP.wfmagP = struct('dim', IP.epiP.dim,...\n 'dt',[64 spm_platform('bigend')],...\n 'pinfo', IP.epiP.pinfo,...\n 'mat', IP.epiP.mat);\n IP.wfmagP = FieldMap('Write',IP.epiP,wfmag,'wfmag_',4,'Voxel shift map');\n\n % Now coregister warped magnitude field map to EPI\n [mi,M] = FieldMap('Coregister',IP.epiP,IP.wfmagP);\n\n % Update the .mat file of the forward warped mag image \n spm_get_space(deblank(IP.wfmagP.fname),M*IP.wfmagP.mat);\n\n % Get the original space of the fmap magnitude \n MM = IP.fmagP.mat;\n end\n\n % Update .mat file for voxel displacement map\n IP.vdmP.mat=M*MM; \n spm_get_space(deblank(IP.vdmP.fname),M*MM); \n\n varargout{1} = IP.vdmP; \n\n%=======================================================================\n%\n% Invert voxel displacement map\n%\n%=======================================================================\n\n case 'invert'\n\n vdm = pm_invert_phasemap(IP.vdm.vdm);\n varargout{1} = vdm; \n\n%=======================================================================\n%\n% Get fieldmap magnitude image\n%\n%=======================================================================\n\n case 'magnitude'\n\n IP=varargin{2};\n\n if isempty(IP.fmagP)\n % \n % Get fieldmap magnitude image\n %\n if isempty(IP.pP) & ~isempty(IP.P{1})\n\n IP.fmagP=struct('dim', IP.P{1}.dim,...\n 'dt', IP.P{1}.dt,...\t \n 'pinfo', IP.P{1}.pinfo,...\n 'mat', IP.P{1}.mat);\n IP.fmagP.fname=fullfile(spm_str_manip(IP.P{1}.fname, 'h'),['mag_' deblank(spm_str_manip(IP.P{1}.fname,'t'))]);\n \n % If using real and imaginary data, calculate using sqrt(i1.^2 + i2.^2).\n % If using phase and magnitude, use magnitude image.\n if IP.uflags.iformat=='RI' \n\n IP.fmagP = spm_imcalc(spm_vol([IP.P{1}.fname;IP.P{2}.fname]),IP.fmagP,'sqrt(i1.^2 + i2.^2)');\n else\n IP.fmagP = IP.P{2};\n end\n\n % else\n % IP.fmagP = spm_vol(spm_get(1,'*.img','Select field map magnitude image'));\n\n else\n do_f = ~isfield(IP, 'fmagP');\n if ~do_f, do_f = isempty(IP.fmagP); end\n if do_f\n IP.fmagP = spm_vol(spm_select(1,'image','Select field map magnitude image'));\n end\n\n end\n end \n varargout{1} = IP.fmagP;\n \n%=======================================================================\n%\n% Load structural image\n%\n%=======================================================================\n\ncase 'loadstructural'\n %IP.nwarp = spm_vol(spm_get(1,'*.img','Select structural image'));\n % SPM5 Update\n IP.nwarp = spm_vol(spm_select(1,'image','Select structural image'));\n\n varargout{1} = IP.nwarp;\n\n%=======================================================================\n%\n% Coregister structural image to unwarped EPI\n%\n%=======================================================================\n\n case 'matchstructural'\n \n IP = varargin{2};\n [mi,M] = FieldMap('Coregister',IP.uepiP,IP.nwarp);\n MM = IP.nwarp.mat;\n IP.nwarp.mat=M*MM;\n spm_get_space(deblank(IP.nwarp.fname),IP.nwarp.mat);\n varargout{1}=mi;\n\n%=======================================================================\n%\n% Coregister two images - NO gui\n%\n%=======================================================================\n\n case 'coregister'\n \n %\n % Coregisters image VF to image VG (use VF and VG like in SPM code)\n %\n VG = varargin{2};\n VF = varargin{3};\n\n % Define flags for coregistration...\n IP.cflags.cost_fun = defaults.coreg.estimate.cost_fun;\n IP.cflags.sep = defaults.coreg.estimate.sep;\n IP.cflags.tol = defaults.coreg.estimate.tol;\n IP.cflags.fwhm = defaults.coreg.estimate.fwhm; \n IP.cflags.graphics = 0;\n\n % Voxel sizes (mm)\n vxg = sqrt(sum(VG.mat(1:3,1:3).^2));\n vxf = sqrt(sum(VF.mat(1:3,1:3).^2));\n\n % Smoothnesses\n fwhmg = sqrt(max([1 1 1]*IP.cflags.sep(end)^2 - vxg.^2, [0 0 0]))./vxg;\n fwhmf = sqrt(max([1 1 1]*IP.cflags.sep(end)^2 - vxf.^2, [0 0 0]))./vxf;\n\n \n % Need to load data smoothed in unit8 format (as in spm_coreg_ui)\n% if isfield(VG,'dat')\n% VG=rmfield(VG,'dat');\n% end\n if ~isfield(VG,'uint8')\n VG.uint8 = loaduint8(VG);\n\t VG = smooth_uint8(VG,fwhmg); % Note side effects\n end\n\n % if isfield(VF,'dat')\n % VF=rmfield(VF,'dat');\n % end\n if ~isfield(VF,'uint8')\n VF.uint8 = loaduint8(VF);\n VF = smooth_uint8(VF,fwhmf); % Note side effects\n end\n\n x=spm_coreg(VG,VF,IP.cflags);\n M = inv(spm_matrix(x));\n MM = spm_get_space(deblank(VF.fname));\n\n varargout{1}=spm_coreg(x,VG,VF,2,IP.cflags.cost_fun,IP.cflags.fwhm);\n varargout{2}=M;\n\n%=======================================================================\n%\n% Use spm_help to display help for FieldMap toolbox\n%\n%=======================================================================\n\n case 'help'\n spm_help('FieldMap.man');\n return\nend\n\n%=======================================================================\n%\n% Smoothing functions required for spm_coreg\n%\n%=======================================================================\n\nfunction V = smooth_uint8(V,fwhm)\n\n% Convolve the volume in memory (fwhm in voxels).\nlim = ceil(2*fwhm);\ns = fwhm/sqrt(8*log(2));\nx = [-lim(1):lim(1)]; x = smoothing_kernel(fwhm(1),x); x = x/sum(x);\ny = [-lim(2):lim(2)]; y = smoothing_kernel(fwhm(2),y); y = y/sum(y);\nz = [-lim(3):lim(3)]; z = smoothing_kernel(fwhm(3),z); z = z/sum(z);\ni = (length(x) - 1)/2;\nj = (length(y) - 1)/2;\nk = (length(z) - 1)/2;\nspm_conv_vol(V.uint8,V.uint8,x,y,z,-[i j k]);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction krn = smoothing_kernel(fwhm,x)\n\n% Variance from FWHM\ns = (fwhm/sqrt(8*log(2)))^2+eps;\n\n% The simple way to do it. Not good for small FWHM\n% krn = (1/sqrt(2*pi*s))*exp(-(x.^2)/(2*s));\n\n% For smoothing images, one should really convolve a Gaussian\n% with a sinc function. For smoothing histograms, the\n% kernel should be a Gaussian convolved with the histogram\n% basis function used. This function returns a Gaussian\n% convolved with a triangular (1st degree B-spline) basis\n% function.\n\n% Gaussian convolved with 0th degree B-spline\n% int(exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= -0.5..0.5)\n% w1 = 1/sqrt(2*s);\n% krn = 0.5*(erf(w1*(x+0.5))-erf(w1*(x-0.5)));\n\n% Gaussian convolved with 1st degree B-spline\n% int((1-t)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= 0..1)\n% +int((t+1)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t=-1..0)\nw1 = 0.5*sqrt(2/s);\nw2 = -0.5/s;\nw3 = sqrt(s/2/pi);\nkrn = 0.5*(erf(w1*(x+1)).*(x+1) + erf(w1*(x-1)).*(x-1) - 2*erf(w1*x ).* x)...\n +w3*(exp(w2*(x+1).^2) + exp(w2*(x-1).^2) - 2*exp(w2*x.^2));\n\nkrn(krn<0) = 0;\nreturn;\n\n%=======================================================================\n%\n% Load data function required for spm_coreg\n%\n%=======================================================================\n\nfunction udat = loaduint8(V)\n% Load data from file indicated by V into an array of unsigned bytes.\nif size(V.pinfo,2)==1 & V.pinfo(1) == 2,\n\tmx = 255*V.pinfo(1) + V.pinfo(2);\n\tmn = V.pinfo(2);\nelse,\n\tspm_progress_bar('Init',V.dim(3),...\n\t\t['Computing max/min of ' spm_str_manip(V.fname,'t')],...\n\t\t'Planes complete');\n\tmx = -Inf; mn = Inf;\n\tfor p=1:V.dim(3),\n\t\timg = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n\t\tmx = max([max(img(:))+paccuracy(V,p) mx]);\n\t\tmn = min([min(img(:)) mn]);\n\t\tspm_progress_bar('Set',p);\n\tend;\nend;\nspm_progress_bar('Init',V.dim(3),...\n\t['Loading ' spm_str_manip(V.fname,'t')],...\n\t'Planes loaded');\n\nudat = uint8(0);\nudat(V.dim(1),V.dim(2),V.dim(3))=0;\nrand('state',100);\nfor p=1:V.dim(3),\n\timg = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n\tacc = paccuracy(V,p);\n\tif acc==0,\n\t\tudat(:,:,p) = uint8(round((img-mn)*(255/(mx-mn))));\n\telse,\n\t\t% Add random numbers before rounding to reduce aliasing artifact\n\t\tr = rand(size(img))*acc;\n\t\tudat(:,:,p) = uint8(round((img+r-mn)*(255/(mx-mn))));\n\tend;\n\tspm_progress_bar('Set',p);\nend;\nspm_progress_bar('Clear');\nreturn;\n\nfunction acc = paccuracy(V,p)\nif ~spm_type(V.dt(1),'intt'),\n\tacc = 0;\nelse,\n\tif size(V.pinfo,2)==1,\n\t\tacc = abs(V.pinfo(1,1));\n\telse,\n\t\tacc = abs(V.pinfo(1,p));\n\tend;\nend;\n%_______________________________________________________________________\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_FieldMap.m", "ext": ".m", "path": "spm5-master/toolbox/FieldMap/spm_config_FieldMap.m", "size": 21721, "source_encoding": "utf_8", "md5": "bbce33042158fb5cff2b9e4bc257f6ea", "text": "function job = spm_config_fieldmap\n% Configuration file for FieldMap jobs\n%_______________________________________________________________________\n% Copyright (C) 2006 Wellcome Department of Imaging Neuroscience\n\n% Chloe Hutton\n% $Id: spm_config_FieldMap.m 1754 2008-05-29 13:56:00Z chloe $\n%_______________________________________________________________________\nentry = inline(['struct(''type'',''entry'',''name'',name,'...\n '''tag'',tag,''strtype'',strtype,''num'',num)'],...\n 'name','tag','strtype','num');\n\nfiles = inline(['struct(''type'',''files'',''name'',name,'...\n '''tag'',tag,''filter'',fltr,''num'',num)'],...\n 'name','tag','fltr','num');\n\nmnu = inline(['struct(''type'',''menu'',''name'',name,'...\n '''tag'',tag,''labels'',{labels},''values'',{values})'],...\n 'name','tag','labels','values');\n\nbranch = inline(['struct(''type'',''branch'',''name'',name,'...\n '''tag'',tag,''val'',{val})'],...\n 'name','tag','val');\n\nrepeat = inline(['struct(''type'',''repeat'',''name'',name,''tag'',tag,'...\n '''values'',{values})'],'name','tag','values');\n \nchoice = inline(['struct(''type'',''choice'',''name'',name,''tag'',tag,'...\n '''values'',{values})'],'name','tag','values');\n%______________________________________________________________________\n\naddpath(fullfile(spm('dir'),'toolbox','FieldMap'));\n\n%------------------------------------------------------------------------\n% File selection for Precalculated field map data (in Hz)\nprecalcfieldmap.type = 'files';\nprecalcfieldmap.name = 'Precalculated field map';\nprecalcfieldmap.tag = 'precalcfieldmap';\nprecalcfieldmap.num = [1 1];\nprecalcfieldmap.filter = 'image';\nprecalcfieldmap.help = {['Select a precalculated field map. This should be a ',...\n'processed field map (ie phase unwrapped, masked if necessary and scaled to Hz), ',...\n'for example as generated by the FieldMap toolbox and stored as an fpm_* file.']};\n\n%------------------------------------------------------------------------\n% File selection for Phase/Magnitude field map data\n\nshortphase.type = 'files';\nshortphase.name = 'Short Echo Phase Image';\nshortphase.tag = 'shortphase';\nshortphase.num = [1 1];\nshortphase.filter = 'image';\nshortphase.help = {['Select short echo phase image']};\n\nshortmag.type = 'files';\nshortmag.name = 'Short Echo Magnitude Image';\nshortmag.tag = 'shortmag';\nshortmag.num = [1 1];\nshortmag.filter = 'image';\nshortmag.help = {['Select short echo magnitude image']};\n\nlongphase.type = 'files';\nlongphase.name = 'Long Echo Phase Image';\nlongphase.tag = 'longphase';\nlongphase.num = [1 1];\nlongphase.filter = 'image';\nlongphase.help = {['Select long echo phase image']};\n\nlongmag.type = 'files';\nlongmag.name = 'Long Echo Magnitude Image';\nlongmag.tag = 'longmag';\nlongmag.num = [1 1];\nlongmag.filter = 'image';\nlongmag.help = {['Select long echo magnitude image']};\n\n%------------------------------------------------------------------------\n% File selection for Presubtracted Magnitude/Phase field map data\npresubmag.type = 'files';\npresubmag.name = 'Magnitude Image';\npresubmag.tag = 'magnitude';\npresubmag.num = [1 1];\npresubmag.filter = 'image';\npresubmag.help = {['Select a single magnitude image']};\n\npresubphase.type = 'files';\npresubphase.name = 'Phase Image';\npresubphase.tag = 'phase';\npresubphase.num = [1 1];\npresubphase.filter = 'image';\npresubphase.help = {['Select a single phase image. This should be the result from the ',...\n'subtraction of two phase images (where the subtraction is usually done automatically by ',...\n'the scanner software). The phase image will be scaled between +/- PI.']};\n\n%------------------------------------------------------------------------\n% File selection for Real/Imaginary field map data\nshortreal.type = 'files';\nshortreal.name = 'Short Echo Real Image';\nshortreal.tag = 'shortreal';\nshortreal.num = [1 1];\nshortreal.filter = 'image';\nshortreal.help = {['Select short echo real image']};\n\nshortimag.type = 'files';\nshortimag.name = 'Short Echo Imaginary Image';\nshortimag.tag = 'shortimag';\nshortimag.num = [1 1];\nshortimag.filter = 'image';\nshortimag.help = {['Select short echo imaginary image']};\n\nlongreal.type = 'files';\nlongreal.name = 'Long Echo Real Image';\nlongreal.tag = 'longreal';\nlongreal.num = [1 1];\nlongreal.filter = 'image';\nlongreal.help = {['Select long echo real image']};\n\nlongimag.type = 'files';\nlongimag.name = 'Long Echo Imaginary Image';\nlongimag.tag = 'longimag';\nlongimag.num = [1 1];\nlongimag.filter = 'image';\nlongimag.help = {['Select long echo imaginary image']};\n\n%------------------------------------------------------------------------\n% Options for doing segmentation used to create brain mask\n\ntemplate_filename = fullfile(spm('Dir'),'templates','T1.nii'); \ntemplate.type = 'files';\ntemplate.name = 'Template image for brain masking';\ntemplate.tag = 'template';\ntemplate.num = [1 1];\ntemplate.filter = 'nii';\ntemplate.val = {template_filename};\ntemplate.help = {['Select template file for segmentation to create brain mask']};\n\nfwhm.type = 'entry';\nfwhm.name = 'FWHM';\nfwhm.tag = 'fwhm';\nfwhm.strtype = 'e';\nfwhm.num = [1 1];\nfwhm.val = {5};\nfwhm.help = {'FWHM of Gaussian filter for smoothing brain mask.'};\n\nnerode.type = 'entry';\nnerode.name = 'Number of erosions';\nnerode.tag = 'nerode';\nnerode.strtype = 'e';\nnerode.num = [1 1];\nnerode.val = {1};\nnerode.help = {'Number of erosions used to create brain mask.'};\n\nndilate.type = 'entry';\nndilate.name = 'Number of dilations';\nndilate.tag = 'ndilate';\nndilate.strtype = 'e';\nndilate.num = [1 1];\nndilate.val = {2};\nndilate.help = {'Number of dilations used to create brain mask.'};\n\nthresh.type = 'entry';\nthresh.name = 'Threshold';\nthresh.tag = 'thresh';\nthresh.strtype = 'e';\nthresh.num = [1 1];\nthresh.val = {0.5};\nthresh.help = {'Threshold used to create brain mask from segmented data.'};\n\nreg.type = 'entry';\nreg.name = 'Regularization';\nreg.tag = 'reg';\nreg.strtype = 'e';\nreg.num = [1 1];\nreg.val = {0.02};\nreg.help = {'Regularization value used in the segmentation. A larger value helps the segmentation to converge.'};\n\nmflags.type = 'branch';\nmflags.name = 'mflags';\nmflags.tag = 'mflags';\nmflags.val = {template,fwhm,nerode,ndilate,thresh,reg};\nmflags.help = {['Different options used for the segmentation and creation of the brain mask.']};\n\n%------------------------------------------------------------------------\n% Options for phase unwrapping and processing field map\nmethod.type = 'menu';\nmethod.name = 'Unwrapping method';\nmethod.tag = 'method';\nmethod.labels = {'Mark3D','Mark2D','Huttonish'};\nmethod.values = {'Mark3D' 'Mark2D' 'Huttonish'};\nmethod.val = {'Mark3D'};\nmethod.help = {'Select method for phase unwrapping'};\n\nfwhm.type = 'entry';\nfwhm.name = 'FWHM';\nfwhm.tag = 'fwhm';\nfwhm.strtype = 'e';\nfwhm.num = [1 1];\nfwhm.val = {10};\nfwhm.help = {'FWHM of Gaussian filter used to implement weighted smoothing of unwrapped maps.'};\n\npad.type = 'entry';\npad.name = 'pad';\npad.tag = 'pad';\npad.strtype = 'e';\npad.num = [1 1];\npad.val = {0};\npad.help = {'Size of padding kernel if required.'};\n\nws.type='menu';\nws.name = 'Weighted smoothing';\nws.tag = 'ws';\nws.labels = {'Weighted Smoothing','No weighted smoothing'};\nws.values = {1 0};\nws.val = {1};\nws.help = {'Select normal or weighted smoothing.'};\n\nuflags.type = 'branch';\nuflags.name = 'uflags';\nuflags.tag = 'uflags';\nuflags.val = {method,fwhm,pad,ws};\nuflags.help = {['Different options for phase unwrapping and field map processing']};\n\n%------------------------------------------------------------------------\n% Short and long echo times \net.type='entry';\net.name = 'Echo times [short TE long TE]';\net.tag = 'et';\net.strtype = 'e';\net.num = [1 2];\net.help = {'Enter the short and long echo times (in ms) of the data used to acquire the field map.'};\n\n%------------------------------------------------------------------------\n% Brain masking\nmaskbrain.type='menu';\nmaskbrain.name = 'Mask brain';\nmaskbrain.tag = 'maskbrain';\nmaskbrain.labels = {'Mask brain','No brain masking'};\nmaskbrain.values = {1 0};\nmaskbrain.help = {'Select masking or no masking of the brain. If masking is selected,',...\n'the magnitude image is used to generate a mask of the brain.'};\n\n%------------------------------------------------------------------------\n% Blip direction\nblipdir.type='menu';\nblipdir.name = 'Blip direction';\nblipdir.tag = 'blipdir';\nblipdir.labels = {'-1','1'};\nblipdir.values = {-1 1};\nblipdir.help = {['Enter the blip direction. This is the polarity of the phase-encode blips',...\n'describing the direction in which k-space is traversed along the y-axis',...\n'during EPI acquisition with respect to the coordinate system used in SPM.',...\n'In this coordinate system, the phase encode direction corresponds with the',...\n'y-direction and is defined as positive from the posterior to the anterior of the',...\n'head.']};\n\n%------------------------------------------------------------------------\n% Total EPI readout time\ntert.type='entry';\ntert.name = 'Total EPI readout time';\ntert.tag = 'tert';\ntert.strtype = 'e';\ntert.num = [1 1];\ntert.help = {'Enter the total EPI readout time (in ms). This is the time taken to',...\n'acquire all of the phase encode steps required to cover k-space (ie one image slice).',...\n'For example, if the EPI sequence has 64 phase encode steps, the total readout time is',...\n'the time taken to acquire 64 echoes, e.g.',...\n'total readout time = number of echoes × echo spacing.',...\n'This time does not include i) the duration of the excitation, ii) the delay between,'...\n'the excitation and the start of the acquisition or iii) time for fat saturation etc.'};\n\n%------------------------------------------------------------------------\n% EPI-based field map or not?\nepifm.type='menu';\nepifm.name = 'EPI-based field map?';\nepifm.tag = 'epifm';\nepifm.labels = {'non-EPI','EPI'};\nepifm.values = {0 1};\nepifm.help = {['Select non-EPI or EPI based field map. The field map data may be acquired using a non-EPI sequence (typically a',...\n'gradient echo sequence) or an EPI sequence. The processing will be slightly different',...\n'for the two cases. If using an EPI-based field map, the resulting Voxel Displacement',...\n'Map will be inverted since the field map was acquired in distorted space.']};\n\n%------------------------------------------------------------------------\n% Jacobian modulation\najm.type='menu';\najm.name = 'Jacobian modulation?';\najm.tag = 'ajm';\najm.labels = {'Do not use','Use'};\najm.values = {0 1};\najm.val = {0};\najm.help = {['Select whether or not to use Jacobian modulation. This will adjust',...\n'the intensities of voxels that have been stretched or compressed but in general is',...\n'not recommended for EPI distortion correction']};\n\n%------------------------------------------------------------------------\n% Defaults values used for field map creation\ndefaultsvals.type = 'branch';\ndefaultsvals.name = 'Defaults values';\ndefaultsvals.tag = 'defaultsval';\ndefaultsvals.val = {et,maskbrain,blipdir,tert,epifm,ajm,uflags,mflags};\ndefaultsvals.help = {['Defaults values']};\n\n%------------------------------------------------------------------------\n% Defaults parameter file used for field map creation\n[default_file_path, tmpname] = fileparts(mfilename('fullpath'));\ndefault_filename = sprintf('%s%s%s',default_file_path,filesep,'pm_defaults.m'); \ndefaultsfile.type = 'files';\ndefaultsfile.name = 'Defaults File';\ndefaultsfile.tag = 'defaultsfile';\ndefaultsfile.num = [1 1];\ndefaultsfile.filter = 'm';\ndefaultsfile.ufilter = '^pm_defaults.*\\.m$';\ndefaultsfile.val = {default_filename};\ndefaultsfile.dir = default_file_path;\ndefaultsfile.help = {[...\n'Select the ''pm_defaults*.m'' file containing the parameters for the field map data. ',...\n'Please make sure that the parameters defined in the defaults file are correct for ',...\n'your field map and EPI sequence. To create your own defaults file, either edit the '...\n'distributed version and/or save it with the name ''pm_defaults_yourname.m''.']};\n\n%------------------------------------------------------------------------\n% Choice for defaults input \ndefaults.type = 'choice';\ndefaults.name = 'FieldMap defaults';\ndefaults.tag = 'defaults';\ndefaults.values = {defaultsvals, defaultsfile};\ndefaults.help = {['FieldMap default values can be entered as a file or set of values.']};\n\n%-----------------------------------------------------------------------\n% Match anatomical image\nmatchanat.type = 'menu';\nmatchanat.name = 'Match anatomical image to EPI?';\nmatchanat.tag = 'matchanat';\nmatchanat.labels = {'match anat', 'none'};\nmatchanat.values = {1,0};\nmatchanat.val = {0};\nmatchanat.help = {[...\n'Match the anatomical image to the distortion corrected EPI. This can be done',...\n'to allow for visual inspection and comparison of the distortion corrected EPI.']};\n\n%------------------------------------------------------------------------\n% Select anatomical image for display and comparison\nanat.type = 'files';\nanat.name = 'Select anatomical image for comparison';\nanat.tag = 'anat';\nanat.filter = 'image';\nanat.num = [0 1];\nanat.val = {''};\nanat.help = {[...\n'Select an anatomical image for comparison with the distortion corrected EPI.']};\n\n%-----------------------------------------------------------------------\n% Write unwarped EPI image\nwriteunwarped.type = 'menu';\nwriteunwarped.name = 'Write unwarped EPI?';\nwriteunwarped.tag = 'writeunwarped';\nwriteunwarped.labels = {'write unwarped EPI', 'none'};\nwriteunwarped.values = {1,0};\nwriteunwarped.help = {[...\n'Write out distortion corrected EPI image. The image is saved with the prefix u.']};\n\n%-----------------------------------------------------------------------\n% Name \nsessname.type = 'entry';\nsessname.name = 'Name extension for session specific vdm files';\nsessname.tag = 'sessname';\nsessname.strtype = 's';\nsessname.num = [1 Inf];\nsessname.val = {'session'};\nsessname.help = {['This will be the name extension followed by an incremented',...\n'integer for session specific vdm files.']};\n\n%-----------------------------------------------------------------------\n% Match VDM file to EPI image\nmatchvdm.type = 'menu';\nmatchvdm.name = 'Match VDM to EPI?';\nmatchvdm.tag = 'matchvdm';\nmatchvdm.labels = {'match vdm', 'none'};\nmatchvdm.values = {1,0};\nmatchvdm.help = {[...\n'Match VDM file to EPI image. This option will coregister the field map data ',...\n'to the selected EPI before doing distortion correction.']};\n\n%------------------------------------------------------------------------\n% Select a single EPI to unwarp\nepi.type = 'files';\nepi.name = 'Select EPI to Unwarp';\nepi.tag = 'epi';\nepi.filter = 'image';\nepi.num = [0 1];\nepi.val = {''};\nepi.help = {[...\n'Select an image to distortion correct. The corrected image will be saved',...\n'with the prefix u. The original and the distortion corrected images can be',...\n'displayed for comparison.']};\n\n%------------------------------------------------------------------------\n% Other options that are not included in the defaults file\n% Define precalculated field map type of job\nsession.type = 'branch';\nsession.name = 'Session';\nsession.tag = 'session';\nsession.val = {epi};\nsession.help = {'Data for this session.'};\n\nepi_session.type = 'repeat';\nepi_session.name = 'EPI Sessions';\nepi_session.values = {session};\nepi_session.num = [1 Inf];\nepi_session.help = {[...\n'If a single VDM file will be used for multiple sessions, select the first EPI',...\n'in each session. A copy of the VDM file will be matched to the first EPI in each',...\n'session and save with a seprate name.']};\n\n%------------------------------------------------------------------------\n% If using precalculated field map and want to do a matching, need the\n% magnitude image in same space as precalculated field map\nmagfieldmap.type = 'files';\nmagfieldmap.name = 'Select magnitude image in same space as fieldmap';\nmagfieldmap.tag = 'magfieldmap';\nmagfieldmap.filter = 'image';\nmagfieldmap.num = [0 1];\nmagfieldmap.val = {''};\nmagfieldmap.help = {[...\n'Select magnitude image which is in the same space as the field map to do matching to EPI']};\n\n%------------------------------------------------------------------------\n% Define precalculated field map type of job\nsubj.type = 'branch';\nsubj.name = 'Subject';\nsubj.tag = 'subj';\nsubj.val = {precalcfieldmap,magfieldmap,defaults,epi_session,matchvdm,sessname,writeunwarped,anat,matchanat};\nsubj.help = {'Data for this subject or field map session.'};\n\ndata.type = 'repeat';\ndata.name = 'Data';\ndata.values = {subj};\ndata.num = [1 Inf];\ndata.help = {['Subjects or sessions for which individual field map data has been acquired.']};\n\nprecalcfieldmap.type = 'branch';\nprecalcfieldmap.name = 'Precalculated FieldMap (in Hz)';\nprecalcfieldmap.tag = 'precalcfieldmap';\nprecalcfieldmap.val = {data};\nprecalcfieldmap.prog = @fieldmap_precalcfieldmap;\nprecalcfieldmap.help = {[...\n'Calculate a voxel displacement map (VDM) from a precalculated field map. This option ',...\n'expects a processed field map (ie phase unwrapped, masked if necessary and scaled to Hz). ',...\n'Precalculated field maps can be generated by the FieldMap toolbox and stored as fpm_* files.']};\n\n%------------------------------------------------------------------------\n% Define phase/magnitude type of job, double phase and magnitude file\nsubj.type = 'branch';\nsubj.name = 'Subject';\nsubj.tag = 'subj';\nsubj.val = {shortphase,shortmag,longphase,longmag,defaults,epi_session,matchvdm,sessname,writeunwarped,anat,matchanat};\nsubj.help = {['Data for this subject or field map session.']};\n\ndata.type = 'repeat';\ndata.name = 'Data';\ndata.values = {subj};\ndata.num = [1 Inf];\ndata.help = {['Subjects or sessions for which individual field map data has been acquired.']};\n\nphasemag.type = 'branch';\nphasemag.name = 'Phase and Magnitude Data';\nphasemag.tag = 'phasemag';\nphasemag.val = {data};\nphasemag.prog = @fieldmap_phasemag;\nphasemag.help = {[...\n'Calculate a voxel displacement map (VDM) from double phase and magnitude field map data.'...\n'This option expects two phase and magnitude pairs of data of two different ',...\n'echo times.']};\n\n%------------------------------------------------------------------------\n% Define phase/magnitude type of job, presubtracted phase and single magnitude file\nsubj.type = 'branch';\nsubj.name = 'Subject';\nsubj.tag = 'subj';\nsubj.val = {presubphase,presubmag,defaults,epi_session,matchvdm,sessname,writeunwarped,anat,matchanat};\nsubj.help = {['Data for this subject or field map session.']};\n\ndata.type = 'repeat';\ndata.name = 'Data';\ndata.values = {subj};\ndata.num = [1 Inf];\ndata.help = {['Subjects or sessions for which individual field map data has been acquired.']};\n\npresubphasemag.type = 'branch';\npresubphasemag.name = 'Presubtracted Phase and Magnitude Data';\npresubphasemag.tag = 'presubphasemag';\npresubphasemag.val = {data};\npresubphasemag.prog = @fieldmap_presubphasemag;\npresubphasemag.help = {[...\n'Calculate a voxel displacement map (VDM) from presubtracted phase and magnitude field map data. ',...\n'This option expects a single magnitude image and a single phase image resulting from the ',...\n'subtraction of two phase images (where the subtraction is usually done automatically by ',...\n'the scanner software). The phase image will be scaled between +/- PI.']};\n\n%------------------------------------------------------------------------\n% Define real/imaginary type of job\nsubj.type = 'branch';\nsubj.name = 'Subject';\nsubj.tag = 'subj';\nsubj.val = {shortreal,shortimag,longreal,longimag,defaults,epi_session,matchvdm,sessname,writeunwarped,anat,matchanat};\nsubj.help = {['Data for this subject or field map session.']};\n\ndata.type = 'repeat';\ndata.name = 'Data';\ndata.values = {subj};\ndata.num = [1 Inf];\ndata.help = {['Subjects or sessions for which individual field map data has been acquired.']};\n\nrealimag.type = 'branch';\nrealimag.name = 'Real and Imaginary Data';\nrealimag.tag = 'realimag';\nrealimag.val = {data};\nrealimag.prog = @fieldmap_realimag;\nrealimag.help = {[...\n'Calculate a voxel displacement map (VDM) from real and imaginary field map data. ',...\n'This option expects two real and imaginary pairs of data of two different ',...\n'echo times.']};\n\n%------------------------------------------------------------------------\n% Define field map job\njob.type = 'choice';\njob.name = 'FieldMap';\njob.tag = 'fieldmap';\njob.values = {presubphasemag,realimag,phasemag,precalcfieldmap};\np1 = [...\n'The FieldMap toolbox generates unwrapped field maps which are converted to ',...\n'voxel displacement maps (VDM) that can be used to unwarp geometrically ',...\n'distorted EPI images. For references and an explantion of the theory behind the field map based ',...\n'unwarping, see FieldMap_principles.man. ',...\n'The resulting VDM files are saved with the prefix vdm and can be used in combination with Realign & Unwarp ',...\n'to calculate and correct for the combined effects of static and movement-related ',...\n'susceptibility induced distortions.'];\njob.help = {p1,''};\n\n%------------------------------------------------------------------------\nfunction fieldmap_presubphasemag(job)\nFieldMap_Run(job.subj);\n%------------------------------------------------------------------------\nfunction fieldmap_realimag(job)\nFieldMap_Run(job.subj);\n%------------------------------------------------------------------------\nfunction fieldmap_phasemag(job)\nFieldmap_Run(job.subj);\n%------------------------------------------------------------------------\nfunction fieldmap_precalcfieldmap(job)\nFieldMap_Run(job.subj);\n%------------------------------------------------------------------------\n\n \n\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_TBR_fieldmap.m", "ext": ".m", "path": "spm5-master/toolbox/FieldMap/spm_TBR_fieldmap.m", "size": 13503, "source_encoding": "utf_8", "md5": "89b1b6e02a00ef76ca59671d9b168743", "text": "function spm_TBR_fieldmap\n% Convert Raw Siemens DICOM files from fieldmap sequence into something \n% that SPM can use\n% FORMAT spm_TBR_fieldmap\n% Converted files are written to the current directory\n%_______________________________________________________________________\n% %W% %E%\n%17.10.2003: change of smooth parameter from 2 to 16 in trajrecon\n%10.12.2003: smooth parameter can be entered from dialog box\n%11.02.2004: update version for converting fieldmap data\nfprintf(1,'TBR 11.02.2004 Version for converting field map data \\n');\n\nspm_defaults;\nglobal hdr\n\nP = spm_get(Inf,'*','Select files');\n\n%SliceOrder = spm_input('Slice Order', 2, 'm',...\n% 'Ascending Slices|Descending Slices', str2mat('ascending','descending'));\nSliceOrder = 'ascending';\n\n% Select trajectory file\n[d,f,s] = fileparts(which(mfilename));\nt = load(spm_get(1,'traj_*_????-??-??_??-??.mat','Select trajectory',d));\n\n% Select smoothing parameter\nmyline1='Enter the smoothing parameter in the following dialog box';\nmyline2='The default value is 4.0 pixels';\nmyline3='Choose a lower value if ghosting occurs in the images';\nmyline4='Choose a higher value if there are line artefacts in the images';\nuiwait(msgbox({myline1,myline2,myline3,myline4},'Smoothing Info','modal'));\n\nmyprompt={'Enter the smoothing parameter (in pixels):'};\nmydef={'4.0'};\nmydlgTitle=['Smoothing parameter'];\nmylineNo=1;\nanswer=inputdlg(myprompt,mydlgTitle,mylineNo,mydef);\nmyzelle=answer(1);\nsmooth_par=str2num(myzelle{1});\n\nhdr = spm_dicom_headers(P);\n[raw,guff] = select_fid(hdr);\n\n% Find fieldmap data and extract it from the raw TBR data to be converted\n[raw,pm_raw] = select_series(raw,cat(2,'ralf_flash_fieldmap',' ','chloe_epi_tbr',' ','ralf_epi_fieldmap_ff','ralf_epi_fieldmap_ff_shim'));\n\n%spm_progress_bar('Init',length(hdr),['Writing Images'], 'Files written');\n%for i=1:length(raw),\n%\tconvert_fid(raw{i},t.M,SliceOrder,smooth_par);\n%\tspm_progress_bar('Set',i);\n%end;\n%spm_progress_bar('Clear');\n\nspm_progress_bar('Init',length(pm_raw),['Processing Fieldmap'], 'Files written');\nif ~isempty(pm_raw)\n % Process fieldmap data if acquired\n % Convert double echo fid\n convert_pm(pm_raw,t.M,SliceOrder,smooth_par);\nend\nspm_progress_bar('Clear');\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [fid,other] = select_fid(hdr)\nfid = {};\nother = {};\nfor i=1:length(hdr),\n\tif ~checkfields(hdr{i},'ImageType','StartOfCSAData') |...\n\t\t~strcmp(deblank(hdr{i}.ImageType),'ORIGINAL\\PRIMARY\\RAW'),\n\t\tother = {other{:},hdr{i}};\n\telse,\n\t\tfid = {fid{:},hdr{i}};\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction ok = checkfields(hdr,varargin)\nok = 1;\nfor i=1:(nargin-1),\n\tif ~isfield(hdr,varargin{i}),\n\t\tok = 0;\n\t\tbreak;\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction clean = strip_unwanted(dirty)\nmsk = find((dirty>='a'&dirty<='z') | (dirty>='A'&dirty<='Z') |...\n (dirty>='0'&dirty<='9') | dirty=='_');\nclean = dirty(msk);\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vol=trajrecon(meas,M,smooth_par)\n% Oliver Joseph's TBR reconstruction\n%17.10.2003: change of smooth parameter from 2 to 16\n%11.11.2003: smoothing parameter has become input argument\n\n% Regridded FT!!!!\n% fid ( LINES, POINTS, SLICES )!!!\n%-------------------------------------------------------------------\nf1d=zeros(64,size(meas,2),size(meas,3));\nfor line=1:size(meas,2)\n \tf1d(:,line,:)=M(:,:,line)*squeeze(meas(:,line,:));\nend;\n\n% Weighted phase reference smoothing\n%-------------------------------------------------------------------\nx = fftshift(-32:31)';\ny = exp(-(x.^2)*(smooth_par/64)^2);\ndd = f1d(:,65,:).*conj(f1d(:,66,:));\ndf = fft(dd,[],1);\ndf = df.*repmat(y,[1 1 size(meas,3)]);\ndff = ifft(df,[],1);\nd2 = exp(sqrt(-1)*angle(dff));\n\n% Slice Based Phase correction %\n%-------------------------------------------------------------------\nf1d(:,2:2:64,:) = f1d(:,2:2:64,:).*repmat(d2,[1,32,1]);\n\n% 2nd FT\n% Need loop to prevent odd-number-of-slices fftshift problem\n%-------------------------------------------------------------------\n% Chloe's changes 27/02/03 \n% Need an additional conj to extract correct phase direction \n% This doesn't effect the magnitude data\n%for slice=1:size(f1d,3),\n% \tvol(:,:,slice)=fftshift(fft(fftshift(conj(f1d(:,1:64,slice))),[],2));\n%end\n\nfor slice=1:size(f1d,3),\n vol(:,:,slice)=conj(fftshift(fft(fftshift(conj(f1d(:,1:64,slice))),[],2)));\nend\n\n% Don't calculate the magnitude here because we need complex data in case\n% image is field map data\n% vol = abs(vol);\nreturn;\n\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction convert_pm(hdr,M,SliceOrder,smooth_par)\n \n% Do the right thing with each type of field map\n\n[other_hdr, fmap_hdr] = select_series(hdr,cat(2,'ralf_epi_fieldmap_ff','ralf_flash_fieldmap','ralf_epi_fieldmap_ff_shim'));\n\nif ~isempty(fmap_hdr)\n % Sort fieldmap data into short/long echo pairs ready for conversion if require\n Fhdr=sort_fieldmap_data(fmap_hdr);\n nfmap=length(Fhdr)/2;\n TE={'short','long'}; \n % Processing each fieldmap requires converting two dicom files\n\n for i=1:2:length(Fhdr) % Process each fieldmap as pair of images\n\n % Need 4 cells to hold real and imaginary pair\n npm=1;\n V=cell(1,4);\n\n for j=1:2 % Process each pair of images\n index=(i-1)+j;\n hdr=Fhdr{index};\n\n % Sort out output filename\n %-------------------------------------------------------------------\n% fname = sprintf('f%s-%.4d.img', strip_unwanted(hdr.PatientID),hdr.SeriesNumber);\n fname = sprintf('f%s-%.4d-%.6d.img', strip_unwanted(hdr.PatientID),...\n\t\thdr.SeriesNumber, hdr.AcquisitionNumber);\n\n % Order of files for the field map routines is\n % short_real, short_imag, short_mag \n % long_real, long_imag, long_mag (are mags this really necessary?)\n\n TEname = sprintf('%s',TE{j});\n fname = [deblank(spm_str_manip(fname,'rt')) '-' deblank(TEname)];\n \n [V{npm},V{npm+1}] = complex2spm(hdr,M,SliceOrder,fname,smooth_par);\n npm=npm+2; \n end \n end\nend\n\nif ~isempty(other_hdr)\n for i=1:length(other_hdr) \n \n hdr=other_hdr{i};\n\n % Sort out output filename\n %-------------------------------------------------------------------\n% fname = sprintf('f%s-%.4d.img', strip_unwanted(hdr.PatientID),hdr.SeriesNumber);\n fname = sprintf('f%s-%.4d-%.6d.img', strip_unwanted(hdr.PatientID),...\n\t hdr.SeriesNumber, hdr.AcquisitionNumber);\n\n % Order of files for the field map \n TEname = sprintf('TE%s',num2str(hdr.EchoTime));\n fname = [deblank(spm_str_manip(fname,'rt')) '-' deblank(TEname)];\n complex2spm(hdr,M,SliceOrder,fname,smooth_par); \n end\nend\n\nreturn;\n\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction varargout = complex2spm(hdr,M,SliceOrder,fname,smooth_par)\n\npersistent SpacingBetweenSlices\n\n% Dimensions and data\n%-------------------------------------------------------------------\nif hdr.Columns*hdr.Rows*2 ~= hdr.SizeOfCSAData,\n warning(['Cant convert \"' fname '\".']);\n return;\nend;\n\nnphase = 66; % <- may change\ndim = [hdr.Columns/4 nphase hdr.Rows/nphase];\nfd = fopen(hdr.Filename,'r','ieee-le');\n\nif fd==-1,\n warning(['Cant open \"' hdr.Filename '\" to create \"' fname '\".']);\n return;\nend;\n\nfseek(fd,hdr.StartOfCSAData,-1);\ncdata = fread(fd,hdr.SizeOfCSAData/4,'float');\nfclose(fd);\ncdata = reshape(cdata(1:2:end)+sqrt(-1)*cdata(2:2:end),dim);\n\nif ~isempty(findstr('flash_fieldmap',hdr.SeriesDescription))\n volume = flashrecon(cdata);\nelse\n volume = trajrecon(cdata,M,smooth_par);\nend\ndim = [size(volume) spm_type('int16')];\n\n% Orientation information as for TBR above\n%-------------------------------------------------------------------\nanalyze_to_dicom = [diag([1 -1 1]) [0 (dim(2)+1) 0]'; 0 0 0 1]*[eye(4,3) [-1 -1 -1 1]'];\nif isfield(hdr,'SpacingBetweenSlices'),\n SpacingBetweenSlices = hdr.SpacingBetweenSlices;\nelse,\n if isempty(SpacingBetweenSlices),\n SpacingBetweenSlices = spm_input('Spacing Between Slices (mm)',1,'r','3.0',[1 1]);\n end;\nend;\n\nvox = [hdr.PixelSpacing SpacingBetweenSlices];\npos = hdr.ImagePositionPatient';\norient = reshape(hdr.ImageOrientationPatient,[3 2]);\norient(:,3) = null(orient');\nif det(orient)<0, orient(:,3) = -orient(:,3); end;\n\n% The image position vector is not correct. In dicom this vector points to\n% the upper left corner of the image. Perhaps it is unlucky that this is\n% calculated in the syngo software from the vector pointing to the center of\n% the slice (keep in mind: upper left slice) with the enlarged FoV.\n\ndicom_to_patient = [orient*diag(vox) pos ; 0 0 0 1];\ntruepos = dicom_to_patient *[([hdr.Columns hdr.Rows]-dim(1:2))/2 0 1]';\ndicom_to_patient = [orient*diag(vox) truepos(1:3) ; 0 0 0 1];\npatient_to_tal = diag([-1 -1 1 1]);\nmat = patient_to_tal*dicom_to_patient*analyze_to_dicom;\n\n% Re-arrange order of slices\nswitch SliceOrder,\n case {'descending'},\n order = 1:dim(3);\n case {'ascending'},\n order = dim(3):-1:1;\n otherwise,\n error('Unknown slice order');\n end;\n\nvolume(:,:,order) = volume;\nmat = mat*[eye(3) [0 0 -(order(1)-1)]'; 0 0 0 1];\n \n% Really need to have SliceNormalVector - but it doesn't exist.\n% Also need to do something else for interleaved volumes.\n%-------------------------------------------------------------------\n% SliceNormalVector = read_SliceNormalVector(hdr);\n% if det([reshape(hdr.ImageOrientationPatient,[3 2]) SliceNormalVector(:)])<0;\n% \tvolume = volume(:,:,end:-1:1);\n% \tmat = mat*[eye(3) [0 0 -(dim(3)-1)]'; 0 0 0 1];\n% end;\n\n% Possibly useful information\n%-------------------------------------------------------------------\ntim = datevec(hdr.AcquisitionTime/(24*60*60));\ndescrip = sprintf('%s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g TBR',...\n\t hdr.MRAcquisitionType,...\n\t deblank(hdr.ScanningSequence),...\n\t hdr.RepetitionTime,hdr.EchoTime,hdr.FlipAngle,...\n\t datestr(hdr.AcquisitionDate),tim(4),tim(5),tim(6));\n \n% Construct name and write out real part of complex data\nrealname=sprintf('%s','real');\nrealfname=[deblank(spm_str_manip(fname,'rt')) '-' deblank(realname) '.img'];\nV{1}=struct('fname',realfname,'dim',dim,'mat',mat,'descrip',descrip);\nV{1}=spm_write_vol(V{1},real(volume));\n \n% Construct name and write out imaginary part of complex data\nimagname=sprintf('%s','imag');\nimagfname=[deblank(spm_str_manip(fname,'rt')) '-' deblank(imagname) '.img'];\nV{2}=struct('fname',imagfname,'dim',dim,'mat',mat,'descrip',descrip);\nV{2}=spm_write_vol(V{2},imag(volume));\n \n% Construct name and write out magnitude of complex data\nmagfname=[deblank(spm_str_manip(fname,'rt')) '.img'];\nVi=struct('fname',magfname,'dim',dim,'mat',mat,'descrip',descrip);\nVi=spm_write_vol(Vi,abs(volume));\n \nvarargout{1}=V{1};\nvarargout{2}=V{2};\n\nreturn;\n\n%_______________________________________________________________________\nfunction F = sort_fieldmap_data(hdr)\n\n% Want to extract the structures in the correct order to \n% create a real and imaginary and a magnitude image for\n% two volumes (or more?).\n\nnfiles=length(hdr);\nif nfiles==1\n error('Need at least 2 dicom files for field map conversion');\n return\nend\n\nsessions=[];\nfor i=1:nfiles\n sessions(i)=hdr{i}.SeriesNumber;\nend;\n\n% Sort scans into sessions\nfnum=1;\nnfmap=1;\nwhile fnum<=nfiles\n nsess=find(sessions==sessions(fnum));\n for i=1:length(nsess)\n sesshdr{i}=hdr{nsess(i)};\n end\n % Split field maps up into pairs\n n=2:2:length(nsess);\n if ~isempty(n)\n% These lines are commented out so that only the last fieldmaps \n% images are written.\n%\n% for i=1:length(n)\n% F{nfmap}=sesshdr{n(i)-1};\n% F{nfmap+1}=sesshdr{n(i)};\n% nfmap=nfmap+2;\n% end\n F{nfmap}=sesshdr{n(end)-1};\n F{nfmap+1}=sesshdr{n(end)};\n nfmap=nfmap+2;\n end\n fnum=fnum+length(nsess);\nend\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [fid,sfid] = select_series(hdr,seriesname)\nfid = {};\nsfid = {};\nfor i=1:length(hdr),\n\tif findstr(deblank(hdr{i}.SeriesDescription),seriesname),\n\t\tsfid = {sfid{:},hdr{i}};\n\telse,\n\t\tfid = {fid{:},hdr{i}};\n\tend;\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vol=flashrecon(cdata)\n% Ralf Deichman's flash recon\n\n[ncol nphase nslc]=size(cdata);\ncdata=ifftshift(fft(fftshift(cdata),[],1));\n\n% Double conj to reverse y direction for consistency with TBR data\n% in y-direction, but without changing phase direction.\nvol=conj(ifftshift(fft(fftshift(conj(cdata(:,1:nphase-2,:))),[],2)));\nvol=vol(ncol/4+1:ncol*3/4,:,:);\ndim=size(vol);\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_config_dartel.m", "ext": ".m", "path": "spm5-master/toolbox/DARTEL/spm_config_dartel.m", "size": 37694, "source_encoding": "utf_8", "md5": "d594870b15cec5b2f71e483ac93c2bce", "text": "function job = spm_config_dartel\n% Configuration file for DARTEL jobs\n%_______________________________________________________________________\n% Copyright (C) 2007 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_config_dartel.m 1032 2007-12-20 14:45:55Z john $\n\nif spm_matlab_version_chk('7') < 0,\n job = struct('type','const',...\n 'name','Need MATLAB 7 onwards',...\n 'tag','old_matlab',...\n 'val',...\n {{['This toolbox needs MATLAB 7 or greater. '...\n 'More recent MATLAB functionality has been used by this toolbox.']}});\n return;\nend;\n\naddpath(fullfile(spm('dir'),'toolbox','DARTEL'));\n%_______________________________________________________________________\n\nentry = inline(['struct(''type'',''entry'',''name'',name,'...\n '''tag'',tag,''strtype'',strtype,''num'',num)'],...\n 'name','tag','strtype','num');\n\nfiles = inline(['struct(''type'',''files'',''name'',name,'...\n '''tag'',tag,''filter'',fltr,''num'',num)'],...\n 'name','tag','fltr','num');\n\nmnu = inline(['struct(''type'',''menu'',''name'',name,'...\n '''tag'',tag,''labels'',{labels},''values'',{values})'],...\n 'name','tag','labels','values');\n\nbranch = inline(['struct(''type'',''branch'',''name'',name,'...\n '''tag'',tag,''val'',{val})'],...\n 'name','tag','val');\n\nrepeat = inline(['struct(''type'',''repeat'',''name'',name,''tag'',tag,'...\n '''values'',{values})'],'name','tag','values');\n%_______________________________________________________________________\n\n\n\n\n% IMPORTING IMAGES FOR USE WITH DARTEL\n%------------------------------------------------------------------------\nmatname = files('Parameter Files','matnames','mat',[1 Inf]);\nmatname.ufilter = '.*seg_sn\\.mat$';\nmatname.help = {...\n['Select ''_sn.mat'' files containing the spatial transformation ',...\n 'and segmentation parameters. '...\n 'Rigidly aligned versions of the image that was segmented will '...\n 'be generated. '...\n 'The image files used by the segmentation may have moved. '...\n 'If they have, then (so the import can find them) ensure that they are '...\n 'either in the output directory, or the current working directory.']};\n%------------------------------------------------------------------------\nodir = files('Output Directory','odir','dir',[1 1]);\n%odir.val = {'.'};\nodir.help = {...\n'Select the directory where the resliced files should be written.'};\n%------------------------------------------------------------------------\nbb = entry('Bounding box','bb','e',[2 3]);\nbb.val = {ones(2,3)*NaN};\nbb.help = {[...\n'The bounding box (in mm) of the volume that is to be written ',...\n'(relative to the anterior commissure). '...\n'Non-finite values will be replaced by the bounding box of the tissue '...\n'probability maps used in the segmentation.']};\n%------------------------------------------------------------------------\nvox = entry('Voxel size','vox','e',[1 1]);\nvox.val = {1.5};\nvox.help = {...\n['The (isotropic) voxel sizes of the written images. '...\n 'A non-finite value will be replaced by the average voxel size of '...\n 'the tissue probability maps used by the segmentation.']};\n%------------------------------------------------------------------------\norig = mnu('Image option','image',...\n {'Original','Bias Corrected','Skull-Stripped','Bias Corrected and Skull-stripped','None'},...\n {1,3,5,7,0});\norig.val = {0};\norig.help = {...\n['A resliced version of the original image can be produced, which may have '...\n 'various procedures applied to it. All options will rescale the images so '...\n 'that the mean of the white matter intensity is set to one. '...\n 'The ``skull stripped'''' versions are the images simply scaled by the sum '...\n 'of the grey and white matter probabilities.']};\n%------------------------------------------------------------------------\ngrey = mnu('Grey Matter','GM',{'Yes','No'},{1,0});\ngrey.val = {1};\ngrey.help = {'Produce a resliced version of this tissue class?'};\n%------------------------------------------------------------------------\nwhite = mnu('White Matter','WM',{'Yes','No'},{1,0});\nwhite.val = {1};\nwhite.help = grey.help;\n%------------------------------------------------------------------------\ncsf = mnu('CSF','CSF',{'Yes','No'}, {1,0});\ncsf.val = {0};\ncsf.help = grey.help;\n%------------------------------------------------------------------------\ninitial = branch('Initial Import','initial',{matname,odir,bb,vox,orig,grey,white,csf});\ninitial.help = {[...\n'Images first need to be imported into a form that DARTEL can work with. '...\n'This involves taking the results of the segmentation (*_seg_sn.mat)/* \\cite{ashburner05} */, '...\n'in order to have rigidly aligned tissue class images. '...\n'Typically, there would be imported grey matter and white matter images, '...\n'but CSF images can also be included. '...\n'The subsequent DARTEL alignment will then attempt to nonlinearly register '...\n'these tissue class images together.']};\ninitial.prog = @spm_dartel_import;\ninitial.vfiles = @vfiles_initial_import;\n%------------------------------------------------------------------------\n\n\n\n\n% RUNNING DARTEL TO MATCH A COMMON MEAN TO THE INDIVIDUAL IMAGES\n%------------------------------------------------------------------------\niits = mnu('Inner Iterations','its',...\n {'1','2','3','4','5','6','7','8','9','10'},...\n {1,2,3,4,5,6,7,8,9,10});\niits.val = {3};\niits.help = {[...\n'The number of Gauss-Newton iterations to be done within this '...\n'outer iteration. After this, new average(s) are created, '...\n'which the individual images are warped to match.']};\n%------------------------------------------------------------------------\ntemplate = files('Template','template','nifti',[1 1]);\ntemplate.val = {};\ntemplate.help = {[...\n'Select template. Smoother templates should be used '...\n'for the early iterations. '...\n'Note that the template should be a 4D file, with the 4th dimension '...\n'equal to the number of sets of images.']};\n%------------------------------------------------------------------------\nrparam = entry('Reg params','rparam','e',[1 3]);\nrparam.val = {[0.1 0.01 0.001]};\nrparam.help = {...\n['For linear elasticity, the parameters are mu, lambda and id. ',...\n 'For membrane and bending energy, the parameters are lambda, unused and id.',...\n 'id is a term for penalising absolute displacements, '...\n 'and should therefore be small.'],...\n['Use more regularisation for the early iterations so that the deformations '...\n 'are smooth, and then use less for the later ones so that the details can '...\n 'be better matched.']};\n%------------------------------------------------------------------------\nK = mnu('Time Steps','K',{'1','2','4','8','16','32','64','128','256','512'},...\n {0,1,2,3,4,5,6,7,8,9});\nK.val = {6};\nK.help = {...\n['The number of time points used for solving the '...\n 'partial differential equations. A single time point would be '...\n 'equivalent to a small deformation model. '...\n 'Smaller values allow faster computations, but are less accurate in terms '...\n 'of inverse consistency and may result in the one-to-one mapping '...\n 'breaking down. Earlier iteration could use fewer time points, '...\n 'but later ones should use about 64 '...\n '(or fewer if the deformations are very smooth).']};\n%------------------------------------------------------------------------\nslam = mnu('Smoothing Parameter','slam',{'None','0.5','1','2','4','8','16','32'},...\n {0,0.5,1,2,4,8,16,32});\nslam.val = {1};\nslam.help = {...\n['A LogOdds parameterisation of the template is smoothed using a multi-grid '...\n 'scheme. The amount of smoothing is determined by this parameter.']};\n%------------------------------------------------------------------------\nlmreg = entry('LM Regularisation','lmreg','e',[1 1]);\nlmreg.val = {0.01};\nlmreg.help = {...\n['Levenberg-Marquardt regularisation. Larger values increase the '...\n 'the stability of the optimisation, but slow it down. A value of '...\n 'zero results in a Gauss-Newton strategy, but this is not recommended '...\n 'as it may result in instabilities in the FMG.']};\n%------------------------------------------------------------------------\ncycles = mnu('Cycles','cyc',{'1','2','3','4','5','6','7','8'},...\n {1,2,3,4,5,6,7,8});\ncycles.val = {3};\ncycles.help = {[...\n'Number of cycles used by the full multi-grid matrix solver. '...\n'More cycles result in higher accuracy, but slow down the algorithm. '...\n'See Numerical Recipes for more information on multi-grid methods.']};\n%------------------------------------------------------------------------\nits = mnu('Iterations','its',{'1','2','3','4','5','6','7','8'},...\n {1,2,3,4,5,6,7,8});\nits.val = {3};\nits.help = {[...\n'Number of relaxation iterations performed in each multi-grid cycle. '...\n'More iterations are needed if using ``bending energy'''' regularisation, '...\n'because the relaxation scheme only runs very slowly. '...\n'See the chapter on solving partial differential equations in '...\n'Numerical Recipes for more information about relaxation methods.']};\n%------------------------------------------------------------------------\nfmg = branch('Optimisation Settings','optim',{lmreg,cycles,its});\nfmg.help = {[...\n'Settings for the optimisation. If you are unsure about them, '...\n'then leave them at the default values. '...\n'Optimisation is by repeating a number of Levenberg-Marquardt '...\n'iterations, in which the equations are solved using a '...\n'full multi-grid (FMG) scheme. '...\n'FMG and Levenberg-Marquardt are both described in '...\n'Numerical Recipes (2nd edition).']};\n%------------------------------------------------------------------------\nparam = branch('Outer Iteration','param',{iits,rparam,K,slam});\nparam.help = {...\n['Different parameters can be specified for each '...\n 'outer iteration. '...\n 'Each of them warps the images to the template, and then regenerates '...\n 'the template from the average of the warped images. '...\n 'Multiple outer iterations should be used for more accurate results, '...\n 'beginning with a more coarse registration (more regularisation) '...\n 'then ending with the more detailed registration (less regularisation).']};\n%------------------------------------------------------------------------\nparams = repeat('Outer Iterations','param',{param});\nparams.help = {[...\n'The images are averaged, and each individual image is warped to '...\n'match this average. This is repeated a number of times.']};\nparams.num = [1 Inf];\n\nparam.val{1}.val{1} = 3; % iits\nparam.val{2}.val{1} = [4 2 1e-6]; % rparam\nparam.val{3}.val{1} = 0; % K\nparam.val{4}.val{1} = 16;\nparams.val{1} = param;\nparam.val{1}.val{1} = 3; % iits\nparam.val{2}.val{1} = [2 1 1e-6]; % rparam\nparam.val{3}.val{1} = 0; % K\nparam.val{4}.val{1} = 8;\nparams.val{2} = param;\nparam.val{1}.val{1} = 3; % iits\nparam.val{2}.val{1} = [1 0.5 1e-6]; % rparam\nparam.val{3}.val{1} = 1; % K\nparam.val{4}.val{1} = 4;\nparams.val{3} = param;\nparam.val{1}.val{1} = 3; % iits\nparam.val{2}.val{1} = [0.5 0.25 1e-6]; % rparam\nparam.val{3}.val{1} = 2; % K\nparam.val{4}.val{1} = 2;\nparams.val{4} = param;\nparam.val{1}.val{1} = 3; % iits\nparam.val{2}.val{1} = [0.25 0.125 1e-6]; % rparam\nparam.val{3}.val{1} = 4; % K\nparam.val{4}.val{1} = 1;\nparams.val{5} = param;\nparam.val{1}.val{1} = 3; % iits\nparam.val{2}.val{1} = [0.125 0.0625 1e-6]; % rparam\nparam.val{3}.val{1} = 6; % K\nparam.val{4}.val{1} = 0.5;\nparams.val{6} = param;\n\n%------------------------------------------------------------------------\ndata = files('Images','images','image',[1 Inf]);\ndata.ufilter = '^r.*';\ndata.help = {...\n['Select a set of imported images of the same type '...\n 'to be registered by minimising '...\n 'a measure of difference from the template.']};\n%------------------------------------------------------------------------\ndata = repeat('Images','images',{data});\ndata.num = [1 Inf];\ndata.help = {...\n['Select the images to be warped together. '...\n 'Multiple sets of images can be simultaneously registered. '...\n 'For example, the first set may be a bunch of grey matter images, '...\n 'and the second set may be the white matter images of the same subjects.']};\n%------------------------------------------------------------------------\ncode = mnu('Objective function','code',{'Sum of squares','Multinomial'},{0,2});\ncode.val = {2};\ncode.help = {...\n['The objective function of the registration is specified here. '...\n 'Multinomial is preferred for matching binary images to an average tissue probability map. '...\n 'Sums of squares is more appropriate for regular images.']};\n%------------------------------------------------------------------------\nform = mnu('Regularisation Form','rform',...\n {'Linear Elastic Energy','Membrane Energy','Bending Energy'},{0,1,2});\nform.val = {0};\nform.help = {[...\n'The registration is penalised by some ``energy'''' term. Here, the form '...\n'of this energy term is specified. '...\n'Three different forms of regularisation can currently be used.']};\n%------------------------------------------------------------------------\ntname = entry('Template basename','template','s',[1 Inf]);\ntname.val = {'Template'};\ntname.help = {[...\n'Enter the base for the template name. '...\n'Templates generated at each outer iteration of the '...\n'procedure will be basename_1.nii, basename_2.nii etc. If empty, then '...\n'no template will be saved. Similarly, the estimated flow-fields will '...\n'have the basename appended to them.']};\n%------------------------------------------------------------------------\nsettings = branch('Settings','settings',{tname,form,params,fmg});\nsettings.help = {[...\n'Various settings for the optimisation. '...\n'The default values should work reasonably well for aligning tissue '...\n'class images together.']};\n%------------------------------------------------------------------------\nwarp = branch('Run DARTEL (create Templates)','warp',{data,settings});\nwarp.prog = @spm_dartel_template;\nwarp.check = @check_runjob;\nwarp.vfiles = @vfiles_runjob;\nwarp.help = {[...\n'Run the DARTEL nonlinear image registration procedure. '...\n'This involves iteratively matching all the selected images to '...\n'a template generated from their own mean. '...\n'A series of Template*.nii files are generated, which become increasingly '...\n'crisp as the registration proceeds. '...\n'/* An example is shown in figure \\ref{Fig:averages}.'...\n'\\begin{figure} '...\n'\\begin{center} '...\n'\\epsfig{file=averages,width=140mm} '...\n'\\end{center} '...\n'\\caption{ '...\n'This figure shows the intensity averages of grey (left) and '...\n'white (right) matter images after different numbers of iterations. '...\n'The top row shows the average after initial rigid-body alignment. '...\n'The middle row shows the images after three iterations, '...\n'and the bottom row shows them after 18 iterations. '...\n'\\label{Fig:averages}} '...\n'\\end{figure}*/']};\n%------------------------------------------------------------------------\n\n\n\n\n% RUNNING DARTEL TO MATCH A PRE-EXISTING TEMPLATE TO THE INDIVIDUALS\n%------------------------------------------------------------------------\nparams1 = params;\nparams1.help = {[...\n'The images are warped to match a sequence of templates. '...\n'Early iterations should ideally use smoother templates '...\n'and more regularisation than later iterations.']};\nparams1.values{1}.val{4} = template;\nhlp = {[...\n'Different parameters and templates can be specified '...\n'for each outer iteration.']};\nhlp1={[...\n'The number of Gauss-Newton iterations to be done '...\n'within this outer iteration.']};\nparams1.values{1}.help = hlp;\nparams1.values{1}.val{1}.help = hlp1;\nfor i=1:numel(params1.val),\n params1.val{i}.val{4} = template;\n params1.val{i}.val{1}.help = hlp1;\n params1.val{i}.help = hlp;\nend\nsettings1 = branch('Settings','settings',{form,params1,fmg});\nsettings1.help = {[...\n'Various settings for the optimisation. '...\n'The default values should work reasonably well for aligning tissue '...\n'class images together.']};\n\nwarp1 = branch('Run DARTEL (existing Templates)','warp1',{data,settings1});\nwarp1.prog = @spm_dartel_warp;\nwarp1.check = @check_runjob;\nwarp1.vfiles = @vfiles_runjob1;\nwarp1.help = {[...\n'Run the DARTEL nonlinear image registration procedure to match '...\n'individual images to pre-existing template data. '...\n'Start out with smooth templates, and select crisp templates for '...\n'the later iterations.']};\n\n\n\n\n% WARPING IMAGES TO MATCH TEMPLATES\n%------------------------------------------------------------------------\nK = mnu('Time Steps','K',{'1','2','4','8','16','32','64','128','256','512'},...\n {0,1,2,3,4,5,6,7,8,9});\nK.val = {6};\nK.help = {...\n['The number of time points used for solving the '...\n 'partial differential equations. Note that Jacobian determinants are not '...\n 'very accurate for very small numbers of time steps (less than about 16).']};\n%------------------------------------------------------------------------\n%------------------------------------------------------------------------\nffields = files('Flow fields','flowfields','nifti',[1 Inf]);\nffields.ufilter = '^u_.*';\nffields.help = {...\n['The flow fields store the deformation information. '...\n 'The same fields can be used for both forward or backward deformations '...\n '(or even, in principle, half way or exaggerated deformations).']};\n%------------------------------------------------------------------------\ndata = files('Images','images','nifti',[1 Inf]);\ndata.help = {...\n['Select images to be warped. Note that there should be the same number '...\n 'of images as there are flow fields, such that each flow field '...\n 'warps one image.']};\n%------------------------------------------------------------------------\ndata = repeat('Images','images',{data});\ndata.num = [1 Inf];\ndata.help = {...\n['The flow field deformations can be applied to multiple images. '...\n 'At this point, you are choosing how many images each flow field '...\n 'should be applied to.']};\n%------------------------------------------------------------------------\ninterp.type = 'menu';\ninterp.name = 'Interpolation';\ninterp.tag = 'interp';\ninterp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-spline',...\n'3rd Degree B-Spline ','4th Degree B-Spline ','5th Degree B-Spline',...\n'6th Degree B-Spline','7th Degree B-Spline'};\ninterp.values = {0,1,2,3,4,5,6,7};\ninterp.val = {1};\ninterp.help = {...\n['The method by which the images are sampled when being written in a ',...\n'different space.'],...\n[' Nearest Neighbour: ',...\n' - Fastest, but not normally recommended.'],...\n[' Bilinear Interpolation: ',...\n' - OK for PET, or realigned fMRI.'],...\n[' B-spline Interpolation: ',...\n' - Better quality (but slower) interpolation/* \\cite{thevenaz00a}*/, especially ',...\n' with higher degree splines. Do not use B-splines when ',...\n' there is any region of NaN or Inf in the images. '],...\n};\n%------------------------------------------------------------------------\njactransf = mnu('Modulation','jactransf',...\n {'No modulation','Modulation','Sqrt Modulation'},...\n {0,1,0.5});\njactransf.val = {0};\njactransf.help = {...\n['This allows the spatially normalised images to be rescaled by the '...\n 'Jacobian determinants of the deformations. '...\n 'Note that the rescaling is only approximate for deformations generated '...\n 'using smaller numbers of time steps. '...\n 'The square-root modulation is for special applications, so can be '...\n 'ignored in most cases.']};\n%------------------------------------------------------------------------\nnrm = branch('Create Warped','crt_warped',{ffields,data,jactransf,K,interp});\nnrm.prog = @spm_dartel_norm;\nnrm.check = @check_norm;\nnrm.vfiles = @vfiles_norm;\nnrm.help = {...\n['This allows spatially normalised images to be generated. '...\n 'Note that voxel sizes and bounding boxes can not be adjusted, '...\n 'and that there may be strange effects due to the boundary conditions used '...\n 'by the warping. '...\n 'Also note that the warped images are not in Talairach or MNI space. '...\n 'The coordinate system is that of the average shape and size of the '...\n 'subjects to which DARTEL was applied. '...\n 'In order to have MNI-space normalised images, then the Deformations '...\n 'Utility can be used to compose the individual DARTEL warps, '...\n 'with a deformation field that matches (e.g.) the Template grey matter '...\n 'generated by DARTEL, with one of the grey matter volumes '...\n 'released with SPM.']};\n%------------------------------------------------------------------------\n\n\n\n\n% GENERATING JACOBIAN DETERMINANT FIELDS\n%------------------------------------------------------------------------\njac = branch('Jacobian determinants','jacdet',{ffields,K});\njac.help = {'Create Jacobian determinant fields from flowfields.'};\njac.prog = @spm_dartel_jacobian;\njac.vfiles = @vfiles_jacdet;\n\n\n\n% WARPING TEMPLATES TO MATCH IMAGES\n%------------------------------------------------------------------------\ndata = files('Images','images','nifti',[1 Inf]);\ndata.help = {...\n['Select the image(s) to be inverse normalised. '...\n 'These should be in alignment with the template image generated by the '...\n 'warping procedure.']};\n%------------------------------------------------------------------------\ninrm = branch('Create Inverse Warped','crt_iwarped',{ffields,data,K,interp});\ninrm.prog = @spm_dartel_invnorm;\ninrm.vfiles = @vfiles_invnorm;\ninrm.help = {...\n['Create inverse normalised versions of some image(s). '...\n 'The image that is inverse-normalised should be in alignment with the '...\n 'template (generated during the warping procedure). '...\n 'Note that the results have the same dimensions as the ``flow fields'''', '...\n 'but are mapped to the original images via the affine transformations '...\n 'in their headers.']};\n%------------------------------------------------------------------------\n\n\n\n% KERNEL UTILITIES FOR PATTERN RECOGNITION\n%------------------------------------------------------------------------\ntempl = files('Template','template','nifti',[0 1]);\ntempl.ufilter = '^Template.*';\ntempl.help = {[...\n 'Residual differences are computed between the '...\n 'warped images and template, and these are scaled by '...\n 'the square root of the Jacobian determinants '...\n '(such that the sum of squares is the same as would be '...\n 'computed from the difference between the warped template '...\n 'and individual images).']};\n%------------------------------------------------------------------------\ndata = files('Images','images','nifti',[1 Inf]);\ndata.ufilter = '^r.*c';\ndata.help = {'Select tissue class images (one per subject).'};\n\n%------------------------------------------------------------------------\ndata = repeat('Images','images',{data});\ndata.num = [1 Inf];\ndata.help = {...\n['Multiple sets of images are used here. '...\n 'For example, the first set may be a bunch of grey matter images, '...\n 'and the second set may be the white matter images of the '...\n 'same subjects. The number of sets of images must be the same '...\n 'as was used to generate the template.']};\n\nfwhm = mnu('Smoothing','fwhm',{'None',' 2mm',' 4mm',' 6mm',' 8mm','10mm','12mm','14mm','16mm'},{0,2,4,6,8,10,12,14,16});\nfwhm.val = {4};\nfwhm.help = {[...\n'The residuals can be smoothed with a Gaussian to reduce dimensionality. '...\n'More smoothing is recommended if there are fewer training images.']};\n\nflowfields = files('Flow fields','flowfields','nifti',[1 Inf]);\nflowfields.ufilter = '^u_.*';\nflowfields.help = {...\n 'Select the flow fields for each subject.'};\nres = branch('Generate Residuals','resids',{data,flowfields,templ,K,fwhm});\nres.help = {[...\n 'Generate residual images in a form suitable for computing a '...\n 'Fisher kernel. In principle, a Gaussian Process model can '...\n 'be used to determine the optimal (positive) linear combination '...\n 'of kernel matrices. The idea would be to combine the kernel '...\n 'from the residuals, with a kernel derived from the flow-fields. '...\n 'Such a combined kernel should then encode more relevant information '...\n 'than the individual kernels alone.']};\nres.prog = @spm_dartel_resids;\nres.check = @check_resids;\nres.vfiles = @vfiles_resids;\n%------------------------------------------------------------------------\nlam = entry('Reg param','rparam','e',[1 1]);\nlam.val = {0.1};\nlogodds = branch('Generate LogOdds','LogOdds',{data,flowfields,K,lam});\nlogodds.help = {'See Kilian Pohl''s recent work.'};\nlogodds.prog = @spm_dartel_logodds;\n\n%------------------------------------------------------------------------\ndata = files('Data','images','nifti',[1 Inf]);\ndata.help = {'Select images to generate dot-products from.'};\n\nmsk = files('Weighting image','weight','image',[0 1]);\nmsk.val = {''};\nmsk.help = {[...\n'The kernel can be generated so that some voxels contribute to '...\n'the similarity measures more than others. This is achieved by supplying '...\n'a weighting image, which each of the component images are multiplied '...\n'before the dot-products are computed. This image needs to have '...\n'the same dimensions as the component images, but orientation information '...\n'(encoded by matrices in the headers) is ignored. '...\n'If left empty, then all voxels are weighted equally.']};\n\nkname = entry('Dot-product Filename','dotprod','s',[1,Inf]);\nkname.help = {['Enter a filename for results (it will be prefixed by '...\n '``dp_'''' and saved in the current directory).']};\nreskern = branch('Kernel from Resids','reskern',{data,msk,kname});\nreskern.help = {['Generate a kernel matrix from residuals. '...\n 'In principle, this same function could be used for generating '...\n 'kernels from any image data (e.g. ``modulated'''' grey matter). '...\n 'If there is prior knowledge about some region providing more '...\n 'predictive information (e.g. the hippocampi for AD), '...\n 'then it is possible to weight the generation of the kernel '...\n 'accordingly. '...\n 'The matrix of dot-products is saved in a variable ``Phi'''', '...\n 'which can be loaded from the dp_*.mat file. '...\n 'The ``kernel trick'''' can be used to convert these dot-products '...\n 'into distance measures for e.g. radial basis-function approaches.']};\nreskern.prog = @spm_dartel_dotprods;\n%------------------------------------------------------------------------\nflowfields = files('Flow fields','flowfields','nifti',[1 Inf]);\nflowfields.ufilter = '^u_.*';\nflowfields.help = {'Select the flow fields for each subject.'};\nkname = entry('Dot-product Filename','dotprod','s',[1,Inf]);\nkname.help = {['Enter a filename for results (it will be prefixed by '...\n '``dp_'''' and saved in the current directory.']};\nrform = mnu('Regularisation Form','rform',...\n {'Linear Elastic Energy','Membrane Energy','Bending Energy'},{0,1,2});\nrform.val = {0};\nrform.help = {[...\n'The registration is penalised by some ``energy'''' term. Here, the '...\n'form of this energy term is specified. '...\n'Three different forms of regularisation can currently be used.']};\nrparam = entry('Reg params','rparam','e',[1 3]);\nrparam.val = {[0.125 0.0625 1e-6]};\nrparam.help = {...\n['For linear elasticity, the parameters are `mu'', `lambda'' and `id''. ',...\n 'For membrane and bending energy, '...\n 'the parameters are `lambda'', unused and `id''. ',...\n 'The term `id'' is for penalising absolute displacements, '...\n 'and should therefore be small.']};\nflokern = branch('Kernel from Flows' ,'flokern',{flowfields,rform,rparam,kname});\nflokern.help = {['Generate a kernel from flow fields. '...\n 'The dot-products are saved in a variable ``Phi'''' '...\n 'in the resulting dp_*.mat file.']};\nflokern.prog = @spm_dartel_kernel;\n%------------------------------------------------------------------------\nkernfun = repeat('Kernel Utilities','kernfun',{res,reskern,flokern});\nkernfun.help = {[...\n 'DARTEL can be used for generating Fisher kernels for '...\n 'various kernel pattern-recognition procedures. '...\n 'The idea is to use both the flow fields and residuals '...\n 'to generate two separate Fisher kernels (see the work of '...\n 'Jaakkola and Haussler for more information). '...\n 'Residual images need first to be generated in order to compute '...\n 'the latter kernel, prior to the dot-products being computed.'],[...\n 'The idea of applying pattern-recognition procedures is to obtain '...\n 'a multi-variate characterisation of the anatomical differences among '...\n 'groups of subjects. These characterisations can then be used to '...\n 'separate (eg) healthy individuals from particular patient populations. '...\n 'There is still a great deal of methodological work to be done, '...\n 'so the types of kernel that can be generated here are unlikely to '...\n 'be the definitive ways of proceeding. They are only just a few ideas '...\n 'that may be worth trying out. '...\n 'The idea is simply to attempt a vaguely principled way to '...\n 'combine generative models with discriminative models '...\n '(see the ``Pattern Recognition and Machine Learning'''' book by '...\n 'Chris Bishop for more ideas). Better ways (higher predictive accuracy) '...\n 'will eventually emerge.'],[...\n 'Various pattern recognition algorithms are available freely over the '...\n 'Internet. Possible approaches include Support-Vector Machines, '...\n 'Relevance-Vector machines and Gaussian Process Models. '...\n 'Gaussian Process Models probably give the most accurate probabilistic '...\n 'predictions, and allow kernels generated from different pieces of '...\n 'data to be most easily combined.']};\n\n\n\n\n\n% THE ENTRY POINT FOR DARTEL STUFF\n%------------------------------------------------------------------------\njob = repeat('DARTEL Tools','dartel',{initial,warp,warp1,nrm,jac,inrm,kernfun});\njob.help = {...\n['This toolbox is based around the ``A Fast Diffeomorphic Registration '...\n 'Algorithm'''' paper/* \\cite{ashburner07} */. '...\n 'The idea is to register images by computing a ``flow field'''', '...\n 'which can then be ``exponentiated'''' to generate both forward and '...\n 'backward deformations. '...\n 'Currently, the software only works with images that have isotropic '...\n 'voxels, identical dimensions and which are in approximate alignment '...\n 'with each other. '...\n 'One of the reasons for this is that the approach assumes circulant '...\n 'boundary conditions, which makes modelling global rotations impossible. '...\n 'Another reason why the images should be approximately aligned is because '...\n 'there are interactions among the transformations that are minimised by '...\n 'beginning with images that are already almost in register. '...\n 'This problem could be alleviated by a time varying flow field, '...\n 'but this is currently computationally impractical.'],...\n['Because of these limitations, images should first be imported. '...\n 'This involves taking the ``*_seg_sn.mat'''' files produced by the segmentation '...\n 'code of SPM5, and writing out rigidly transformed versions of '...\n 'the tissue class images, '...\n 'such that they are in as close alignment as possible with the tissue '...\n 'probability maps. '...\n 'Rigidly transformed original images can also be generated, '...\n 'with the option to have skull-stripped versions.'],...\n['The next step is the registration itself. This can involve matching '...\n 'single images together, or it can involve the simultaneous registration '...\n 'of e.g. GM with GM, WM with WM and 1-(GM+WM) with 1-(GM+WM) '...\n '(when needed, the 1-(GM+WM) class is generated implicitly, so there is '...\n 'no need to include this class yourself). '...\n 'This procedure begins by creating a mean of all the images, '...\n 'which is used as an initial template. '...\n 'Deformations from this template to each of the individual images '...\n 'are computed, and the template is then re-generated by applying '...\n 'the inverses of the deformations to the images and averaging. '... \n 'This procedure is repeated a number of times.'],...\n['Finally, warped versions of the images (or other images that are '...\n 'in alignment with them) can be generated. '],[],[...\n 'This toolbox is not yet seamlessly integrated into the SPM package. '...\n 'Eventually, the plan is to use many of the ideas here as the default '...\n 'strategy for spatial normalisation. The toolbox may change with future '...\n 'updates. There will also be a number of '...\n 'other (as yet unspecified) extensions, which may include '...\n 'a variable velocity version (related to LDDMM). '...\n 'Note that the Fast Diffeomorphism paper only describes a sum of squares '...\n 'objective function. '...\n 'The multinomial objective function is an extension, '...\n 'based on a more appropriate model for aligning binary data to a template.']};\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vf = vfiles_initial_import(job)\nopt = [job.GM, job.WM, job.CSF];\nodir = job.odir{1};\nmatnames = job.matnames;\n\nvf = {};\nfor i=1:numel(matnames),\n vf1 = {};\n [pth,nam,ext] = fileparts(matnames{i});\n nam = nam(1:(numel(nam)-7));\n if job.image,\n fname = fullfile(odir,['r',nam, '.nii' ',1']);\n vf1 = {fname};\n end\n for k1=1:numel(opt),\n if opt(k1),\n fname = fullfile(odir,['r','c', num2str(k1), nam, '.nii' ',1']);\n vf1 = {vf1{:},fname};\n end\n end\n vf = {vf{:},vf1{:}};\nend\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction chk = check_runjob(job)\nn1 = numel(job.images);\nn2 = numel(job.images{1});\nchk = '';\nfor i=1:n1,\n if numel(job.images{i}) ~= n2,\n chk = 'Incompatible number of images';\n break;\n end;\nend;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vf = vfiles_runjob(job)\nvf = {};\nn1 = numel(job.images);\nn2 = numel(job.images{1});\n[tdir,nam,ext] = fileparts(job.images{1}{1});\ntname = deblank(job.settings.template);\nif ~isempty(tname),\n for it=0:numel(job.settings.param),\n fname = fullfile(tdir,[tname '_' num2str(it) '.nii' ',1']);\n vf = {vf{:},fname};\n end\nend\nfor j=1:n2,\n [pth,nam,ext,num] = spm_fileparts(job.images{1}{j});\n if ~isempty(tname),\n fname = fullfile(pth,['u_' nam '_' tname '.nii' ',1']);\n else\n fname = fullfile(pth,['u_' nam '.nii' ',1']);\n end\n vf = {vf{:},fname};\nend;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vf = vfiles_runjob1(job)\nvf = {};\nn1 = numel(job.images);\nn2 = numel(job.images{1});\nfor j=1:n2,\n [pth,nam,ext,num] = spm_fileparts(job.images{1}{j});\n fname = fullfile(pth,['u_' nam '.nii' ',1']);\n vf = {vf{:},fname};\nend;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction chk = check_norm(job)\nchk = '';\nPU = job.flowfields;\nPI = job.images;\nn1 = numel(PU);\nfor i=1:numel(PI),\n if numel(PI{i}) ~= n1,\n chk = 'Incompatible number of images';\n break;\n end\nend\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vf = vfiles_norm(job)\nvf = {};\nPU = job.flowfields;\nPI = job.images;\njactransf = job.jactransf;\n\nfor i=1:numel(PU),\n for m=1:numel(PI),\n [pth,nam,ext,num] = spm_fileparts(PI{m}{i});\n if jactransf,\n fname = fullfile(pth,['mw' nam ext ',1']);\n else\n fname = fullfile(pth,['w' nam ext ',1']);\n end;\n vf = {vf{:},fname};\n end\nend\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vf = vfiles_invnorm(job)\nvf = {};\nPU = job.flowfields;\nPI = job.images;\nfor i=1:numel(PU),\n [pth1,nam1,ext1,num1] = spm_fileparts(PU{i});\n for m=1:numel(PI),\n [pth2,nam2,ext2,num2] = spm_fileparts(PI{m});\n fname = fullfile(pth1,['w' nam2 '_' nam1 ext2 ',1']);\n vf = {vf{:},fname};\n end\nend\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vf = vfiles_jacdet(job)\nvf = {};\nPU = job.flowfields;\nfor i=1:numel(PU),\n [pth,nam,ext] = fileparts(PU{i});\n fname = fullfile(pth,['jac_' nam(3:end) ext ',1']);\n vf = {vf{:},fname};\nend;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction chk = check_resids(job)\nchk = '';\nPU = job.flowfields;\nPI = job.images;\nn1 = numel(PU);\nfor i=1:numel(PI),\n if numel(PI{i}) ~= n1,\n chk = 'Incompatible number of images';\n break;\n end\nend\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction vf = vfiles_resids(job)\nvf = {};\nPI = job.images{1};\nfor i=1:numel(PI),\n [pth,nam,ext] = fileparts(PI{i});\n fname = fullfile(pwd,['resid_' nam '.nii',',1']);\n vf = {vf{:},fname};\nend\n%_______________________________________________________________________\n\n\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_dartel_logodds.m", "ext": ".m", "path": "spm5-master/toolbox/DARTEL/spm_dartel_logodds.m", "size": 4130, "source_encoding": "utf_8", "md5": "0ef776c3cdd4669c54e7331b35db163d", "text": "function spm_dartel_logodds(job)\n% Generate LogOdds files\n% FORMAT spm_dartel_logodds(job)\n% job.flowfields\n% job.images\n% job.K\n% job.rparam\n%\n% The aim is to obtain better pattern recognition through using\n% LogOdds. See Killian Pohl's work for more info.\n%_______________________________________________________________________\n% Copyright (C) 2007 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_dartel_logodds.m 964 2007-10-19 16:35:34Z john $\n\n\nPI = job.images;\nPU = job.flowfields;\nK = job.K;\nlam= job.rparam;\nn = numel(PI);\n\n\nspm_progress_bar('Init',numel(PI{1}),'Creating LogOdds');\n\nfor i=1:numel(PI{1}),\n\n % Derive deformations and Jacobian determinants from the\n % flow fields.\n NU = nifti(PU{i});\n [pth,nam,ext,num] = spm_fileparts(NU.dat.fname);\n fprintf('%s: def ',nam); drawnow;\n u = single(squeeze(NU.dat(:,:,:,1,:)));\n [y,dt] = dartel3('Exp',u,[K -1 1]);\n y1 = double(y(:,:,:,1));\n y2 = double(y(:,:,:,2));\n y3 = double(y(:,:,:,3));\n clear y\n dt = max(dt,single(0));\n\n f = zeros([NU.dat.dim(1:3),n+1],'single');\n \n [pth,nam,ext,num] = spm_fileparts(PI{1}{i});\n NI = nifti(fullfile(pth,[nam ext]));\n NO = NI;\n NO.dat.fname = fullfile('.',['logodds_' nam '.nii']);\n NO.dat.scl_slope = 1.0;\n NO.dat.scl_inter = 0.0;\n NO.dat.dtype = 'float32-le';\n NO.dat.dim = [NU.dat.dim(1:3) 1 n+1];\n NO.mat = NU.mat;\n NO.mat0 = NU.mat;\n NO.mat_intent = 'Aligned';\n NO.mat0_intent = 'Aligned';\n NO.descrip = 'LogOdds';\n create(NO);\n vx = sqrt(sum(NU.mat(1:3,1:3).^2));\n\n % Compute the warped tissue probabilities\n f(:,:,:,end) = 1; % Background\n for j=1:n,\n fprintf('%d ', j); drawnow;\n\n [pth,nam,ext,num] = spm_fileparts(PI{j}{i});\n NI = nifti(fullfile(pth,[nam ext]));\n if sum(sum((NI.mat - NU.mat ).^2)) < 0.0001 && ...\n sum(sum((NI.mat0 - NU.mat0).^2)) < 0.0001,\n ty1 = y1;\n ty2 = y2;\n ty3 = y3;\n else\n mat = NI.mat;\n if isfield(NI,'extras') && isfield(NI.extras,'mat'),\n mat1 = NI.extras.mat;\n if size(mat1,3) >= j && sum(sum(mat1(:,:,j).^2)) ~=0,\n mat = mat1;\n end;\n end;\n M = mat\\NU.mat0;\n ty1 = M(1,1)*y1 + M(1,2)*y2 + M(1,3)*y3 + M(1,4);\n ty2 = M(2,1)*y1 + M(2,2)*y2 + M(2,3)*y3 + M(2,4);\n ty3 = M(3,1)*y1 + M(3,2)*y2 + M(3,3)*y3 + M(3,4);\n end;\n spl_param = [3 3 3 1 1 1];\n cf = spm_bsplinc(NI.dat(:,:,:,1,1),spl_param);\n f(:,:,:,j) = spm_bsplins(cf,ty1,ty2,ty3,spl_param);\n f(:,:,:,end) = f(:,:,:,end) - f(:,:,:,j);\n clear cf ty1 ty2 ty3\n end;\n clear y1 y2 y3\n\n a = logodds(f,dt,lam,12,vx);\n a = softmax(a);\n fprintf('\\n');\n\n clear f dt\n for j=1:n+1,\n NO.dat(:,:,:,1,j) = log(a(:,:,:,j));\n end\n clear a\n spm_progress_bar('Set',i);\nend\nspm_progress_bar('Clear');\n\n\nfunction a = logodds(t,s,lam,its,vx)\nif nargin<5, vx = [1 1 1]; end;\nif nargin<4, its = 12; end;\nif nargin<3, lam = 1; end;\n\na = zeros(size(t),'single');\nd = size(t);\nW = zeros([d(1:3) round((d(4)*(d(4)+1))/2)],'single');\nfor i=1:its,\n sig = softmax(a);\n gr = sig - t;\n for k=1:d(4), gr(:,:,:,k) = gr(:,:,:,k).*s; end\n gr = gr + optimN('vel2mom',a,[2 vx lam 0 0]);\n jj = d(4)+1;\n for j1=1:d(4),\n W(:,:,:,j1) = sig(:,:,:,j1).*(1-sig(:,:,:,j1)).*s;\n for j2=1:j1-1,\n W(:,:,:,jj) = -sig(:,:,:,j1).*sig(:,:,:,j2).*s;\n jj = jj+1;\n end\n end\n a = a - optimN(W,gr,[2 vx lam 0 lam*1e-3 1 1]);\n %a = a - mean(a(:)); % unstable\n a = a - sum(sum(sum(sum(a))))/numel(a);\n fprintf('.');\n drawnow \nend;\nreturn;\n\nfunction sig = softmax(a)\nsig = zeros(size(a),'single');\nfor j=1:size(a,3),\n aj = double(squeeze(a(:,:,j,:)));\n aj = min(max(aj-mean(aj(:)),-700),700);\n sj = exp(aj);\n s = sum(sj,3);\n for i=1:size(a,4),\n sig(:,:,j,i) = single(sj(:,:,i)./s);\n end\nend;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_dartel_smooth.m", "ext": ".m", "path": "spm5-master/toolbox/DARTEL/spm_dartel_smooth.m", "size": 1765, "source_encoding": "utf_8", "md5": "3d5d4ff610b382c8068db96ecc345478", "text": "function [sig,a] = spm_dartel_smooth(t,lam,its,vx,a)\n% A function for smoothing tissue probability maps\n% FORMAT [sig,a_new] = spm_dartel_smooth(t,lam,its,vx,a_old)\n%________________________________________________________\n% (c) Wellcome Centre for NeuroImaging (2007)\n\n% John Ashburner\n% $Id: spm_dartel_smooth.m 3101 2009-05-08 11:17:29Z john $\n\nif nargin<5, a = zeros(size(t),'single'); end\nif nargin<4, vx = [1 1 1]; end;\nif nargin<3, its = 16; end;\nif nargin<2, lam = 1; end;\n\nd = size(t);\nW = zeros([d(1:3) round((d(4)*(d(4)+1))/2)],'single');\ns = max(sum(t,4),eps('single'));\nfor k=1:d(4),\n t(:,:,:,k) = max(min(t(:,:,:,k)./s,1-eps('single')),eps('single'));\nend\nfor i=1:its,\n %trnc= -log(eps('single'));\n %a = max(min(a,trnc),-trnc);\n sig = softmax(a);\n gr = sig - t;\n for k=1:d(4),\n gr(:,:,:,k) = gr(:,:,:,k).*s;\n end\n gr = gr + optimNn('vel2mom',a,[2 vx lam 0 1e-4]);\n jj = d(4)+1;\n reg = 2*sqrt(eps('single'))*d(4)^2;\n for j1=1:d(4),\n W(:,:,:,j1) = (sig(:,:,:,j1).*(1-sig(:,:,:,j1)) + reg).*s;\n for j2=(j1+1):d(4),\n W(:,:,:,jj) = -sig(:,:,:,j1).*sig(:,:,:,j2).*s;\n jj = jj+1;\n end\n end\n a = a - optimNn(W,gr,[2 vx lam 0 1e-4 1 1]);\n %a = a - mean(a(:)); % unstable\n %a = a - sum(sum(sum(sum(a))))/numel(a);\n fprintf(' %g,', sum(gr(:).^2)/numel(gr));\n drawnow \nend;\nfprintf('\\n');\nsig = softmax(a);\nreturn;\n\nfunction sig = softmax(a)\nsig = zeros(size(a),'single');\nfor j=1:size(a,3),\n aj = double(squeeze(a(:,:,j,:)));\n trunc = log(realmax*(1-eps));\n aj = min(max(aj-mean(aj(:)),-trunc),trunc);\n sj = exp(aj);\n s = sum(sj,3);\n for i=1:size(a,4),\n sig(:,:,j,i) = single(sj(:,:,i)./s);\n end\nend;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_dartel_import.m", "ext": ".m", "path": "spm5-master/toolbox/DARTEL/spm_dartel_import.m", "size": 10819, "source_encoding": "utf_8", "md5": "2c3aa19bc0c8d505f1fd8a9a17a00005", "text": "function spm_dartel_import(job)\n% Import subjects' data for use with DARTEL\n% FORMAT spm_dartel_import(job)\n% job.matnames - Names of *_seg_sn.mat files to use\n% job.odir - Output directory\n% job.bb - Bounding box\n% job.vox - Voxel sizes\n% job.GM/WM/CSF - Options fo different tissue classes\n% job.image - Options for resliced original image\n%\n% Rigidly aligned images are generated using info from the seg_sn.mat\n% files. These can be resliced GM, WM or CSF, but also various resliced\n% forms of the original image (skull-stripped, bias corrected etc).\n%____________________________________________________________________________\n% Copyright (C) 2007 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id: spm_dartel_import.m 1085 2008-01-11 15:09:48Z john $\n\nmatnames = job.matnames;\nfor i=1:numel(matnames),\n p(i) = load(matnames{i});\nend;\nif numel(p)>0,\n tmp = strvcat(p(1).VG.fname);\n p(1).VG = spm_vol(tmp);\n b0 = spm_load_priors(p(1).VG);\nend;\nodir = job.odir{1};\nbb = job.bb;\nvox = job.vox;\niopt = job.image;\nopt = [job.GM, job.WM, job.CSF];\nfor i=1:numel(p),\n preproc_apply(p(i),odir,b0,bb,vox,iopt,opt,matnames{i});\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction preproc_apply(p,odir,b0,bb,vx,iopt,opt,matname)\n[pth0,nam,ext,num] = spm_fileparts(matname);\n[pth ,nam,ext,num] = spm_fileparts(p.VF(1).fname);\nP = path_search([nam,ext],{pth,odir,pwd,pth0});\nif isempty(P),\n fprintf('Could not find \"%s\"\\n', [nam,ext]);\n return;\nend;\np.VF.fname = P;\nT = p.flags.Twarp;\nbsol = p.flags.Tbias;\nd2 = [size(T) 1];\nd = p.VF.dim(1:3);\n\n[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);\nx3 = 1:d(3);\nd3 = [size(bsol) 1];\nB1 = spm_dctmtx(d(1),d2(1));\nB2 = spm_dctmtx(d(2),d2(2));\nB3 = spm_dctmtx(d(3),d2(3));\nbB3 = spm_dctmtx(d(3),d3(3),x3);\nbB2 = spm_dctmtx(d(2),d3(2),x2(1,:)');\nbB1 = spm_dctmtx(d(1),d3(1),x1(:,1));\n\nmg = p.flags.mg;\nmn = p.flags.mn;\nvr = p.flags.vr;\nK = length(p.flags.mg);\nKb = length(p.flags.ngaus);\n\nlkp = []; for k=1:Kb, lkp = [lkp ones(1,p.flags.ngaus(k))*k]; end;\n\nspm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed');\nM = p.VG(1).mat\\p.flags.Affine*p.VF.mat;\n\nif iopt, idat = zeros(d(1:3),'single'); end;\ndat = {zeros(d(1:3),'uint8'),zeros(d(1:3),'uint8'),zeros(d(1:3),'uint8')};\n\nfor z=1:length(x3),\n\n % Bias corrected image\n f = spm_sample_vol(p.VF,x1,x2,o*x3(z),0);\n msk = (f==0) | ~isfinite(f);\n cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f;\n\n if iopt,\n if bitand(iopt,2),\n idat(:,:,z) = cr;\n else\n idat(:,:,z) = f;\n end;\n end;\n\n [t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M);\n q = zeros([d(1:2) Kb]);\n bg = ones(d(1:2));\n bt = zeros([d(1:2) Kb]);\n for k1=1:Kb,\n bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb);\n end;\n b = zeros([d(1:2) K]);\n for k=1:K,\n b(:,:,k) = bt(:,:,lkp(k))*mg(k);\n end;\n s = sum(b,3);\n for k=1:K,\n p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps);\n q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s;\n end;\n sq = sum(q,3)+eps;\n for k1=1:3,\n tmp = q(:,:,k1);\n tmp = tmp./sq;\n tmp(msk) = 0;\n dat{k1}(:,:,z) = uint8(round(255 * tmp));\n end;\n spm_progress_bar('set',z);\nend;\nspm_progress_bar('clear');\n\n%[dat{1},dat{2},dat{3}] = clean_gwc(dat{1},dat{2},dat{3}, 2); \nif iopt,\n if bitand(iopt,2),\n nwm = 0;\n swm = 0;\n for z=1:numel(x3),\n nwm = nwm + sum(sum(double(dat{2}(:,:,z))));\n swm = swm + sum(sum(double(dat{2}(:,:,z)).*idat(:,:,z)));\n end;\n idat = idat*(double(nwm)/double(swm));\n end;\n if bitand(iopt,4),\n for z=1:numel(x3),\n %msk = double(dat{1}(:,:,z)) ...\n % + double(dat{2}(:,:,z)) ...\n % + 0.5*double(dat{3}(:,:,z));\n %msk = msk<128;\n %tmp = idat(:,:,z);\n %tmp(msk) = 0;\n %idat(:,:,z) = tmp;\n wt = (double(dat{1}(:,:,z))+double(dat{2}(:,:,z)))/255;\n idat(:,:,z) = idat(:,:,z).*wt;\n end;\n end;\n for z=1:numel(x3),\n tmp = idat(:,:,z);\n tmp(~isfinite(double(tmp))) = 0;\n idat(:,:,z) = tmp;\n end;\nend;\n\n% Sort out bounding box etc\n[bb1,vx1] = bbvox_from_V(p.VG(1));\nbb(~isfinite(bb)) = bb1(~isfinite(bb));\nif ~isfinite(vx), vx = abs(prod(vx1))^(1/3); end;\nbb(1,:) = vx*ceil(bb(1,:)/vx);\nbb(2,:) = vx*floor(bb(2,:)/vx);\n\n% Figure out the mapping from the volumes to create to the original\nmm = [\n bb(1,1) bb(1,2) bb(1,3)\n bb(2,1) bb(1,2) bb(1,3)\n bb(1,1) bb(2,2) bb(1,3) \n bb(2,1) bb(2,2) bb(1,3)\n bb(1,1) bb(1,2) bb(2,3) \n bb(2,1) bb(1,2) bb(2,3) \n bb(1,1) bb(2,2) bb(2,3) \n bb(2,1) bb(2,2) bb(2,3)]';\n\nvx2 = inv(p.VG(1).mat)*[mm ; ones(1,8)];\n\nodim = abs(round((bb(2,:)-bb(1,:))/vx))+1;\n%dimstr = sprintf('%dx%dx%d',odim);\ndimstr = '';\n\nvx1 = [\n 1 1 1\n odim(1) 1 1\n 1 odim(2) 1\n odim(1) odim(2) 1\n 1 1 odim(3)\n odim(1) 1 odim(3)\n 1 odim(2) odim(3)\n odim(1) odim(2) odim(3)]';\nM = p.Affine*vx2/[vx1 ; ones(1,8)];\nmat0 = p.VF.mat*M;\nmat = [mm ; ones(1,8)]/[vx1 ; ones(1,8)];\n\nfwhm = max(vx./sqrt(sum(p.VF.mat(1:3,1:3).^2))-1,0.01);\n\nfor k1=1:numel(opt),\n if opt(k1),\n dat{k1} = decimate(dat{k1},fwhm);\n VT = struct('fname',fullfile(odir,['r',dimstr,'c', num2str(k1), nam, '.nii']),...\n 'dim', odim,...\n 'dt', [spm_type('uint8') spm_platform('bigend')],...\n 'pinfo',[1/255 0]',...\n 'mat',mat);\n VT = spm_create_vol(VT);\n\n Ni = nifti(VT.fname);\n Ni.mat0 = mat0;\n Ni.mat_intent = 'Aligned';\n Ni.mat0_intent = 'Aligned';\n create(Ni);\n\n for i=1:odim(3),\n tmp = spm_slice_vol(dat{k1},M*spm_matrix([0 0 i]),odim(1:2),1)/255;\n VT = spm_write_plane(VT,tmp,i);\n end;\n end;\nend;\n\nif iopt,\n %idat = decimate(idat,fwhm);\n VT = struct('fname',fullfile(odir,['r',dimstr,nam, '.nii']),...\n 'dim', odim,...\n 'dt', [spm_type('float32') spm_platform('bigend')],...\n 'pinfo',[1 0]',...\n 'mat',mat);\n VT.descrip = 'Resliced';\n if bitand(iopt,2), VT.descrip = [VT.descrip ', bias corrected']; end;\n if bitand(iopt,4), VT.descrip = [VT.descrip ', skull stripped']; end;\n \n VT = spm_create_vol(VT);\n\n Ni = nifti(VT.fname);\n Ni.mat0 = mat0;\n Ni.mat_intent = 'Aligned';\n Ni.mat0_intent = 'Aligned';\n create(Ni);\n\n for i=1:odim(3),\n tmp = spm_slice_vol(idat,M*spm_matrix([0 0 i]),odim(1:2),1);\n VT = spm_write_plane(VT,tmp,i);\n end;\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M)\nx1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1));\ny1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2));\nz1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3));\nx1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);\ny1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);\nz1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction t = transf(B1,B2,B3,T)\nd2 = [size(T) 1];\nt1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));\nt = B1*t1*B2';\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction dat = decimate(dat,fwhm)\n% Convolve the volume in memory (fwhm in voxels).\nlim = ceil(2*fwhm);\ns = fwhm/sqrt(8*log(2));\nx = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x);\ny = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y);\nz = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z);\ni = (length(x) - 1)/2;\nj = (length(y) - 1)/2;\nk = (length(z) - 1)/2;\nspm_conv_vol(dat,dat,x,y,z,-[i j k]);\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction [g,w,c] = clean_gwc(g,w,c, level)\nif nargin<4, level = 1; end;\n\nb = w;\nb(1) = w(1);\n\n% Build a 3x3x3 seperable smoothing kernel\n%-----------------------------------------------------------------------\nkx=[0.75 1 0.75];\nky=[0.75 1 0.75];\nkz=[0.75 1 0.75];\nsm=sum(kron(kron(kz,ky),kx))^(1/3);\nkx=kx/sm; ky=ky/sm; kz=kz/sm;\n\nth1 = 0.15;\nif level==2, th1 = 0.2; end;\n% Erosions and conditional dilations\n%-----------------------------------------------------------------------\nniter = 32;\nspm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');\nfor j=1:niter,\n if j>2, th=th1; else th=0.6; end; % Dilate after two its of erosion.\n for i=1:size(b,3),\n gp = double(g(:,:,i));\n wp = double(w(:,:,i));\n bp = double(b(:,:,i))/255;\n bp = (bp>th).*(wp+gp);\n b(:,:,i) = uint8(round(bp));\n end;\n spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);\n spm_progress_bar('Set',j);\nend;\nth = 0.05;\nfor i=1:size(b,3),\n gp = double(g(:,:,i))/255;\n wp = double(w(:,:,i))/255;\n cp = double(c(:,:,i))/255;\n bp = double(b(:,:,i))/255;\n bp = ((bp>th).*(wp+gp))>th;\n g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));\n w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));\n c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));\nend;\nspm_progress_bar('Clear');\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction pthnam = path_search(nam,pth)\npthnam = '';\nfor i=1:numel(pth),\n if exist(fullfile(pth{i},nam),'file'),\n pthnam = fullfile(pth{i},nam);\n return;\n end;\nend;\n%=======================================================================\n\n%=======================================================================\nfunction [bb,vx] = bbvox_from_V(V)\nvx = sqrt(sum(V(1).mat(1:3,1:3).^2));\nif det(V(1).mat(1:3,1:3))<0, vx(1) = -vx(1); end;\n\no = V(1).mat\\[0 0 0 1]';\no = o(1:3)';\nbb = [-vx.*(o-1) ; vx.*(V(1).dim(1:3)-o)];\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "spm_hdw.m", "ext": ".m", "path": "spm5-master/toolbox/HDW/spm_hdw.m", "size": 10918, "source_encoding": "utf_8", "md5": "264f8635ea0813aaa15de0175151b3cb", "text": "function spm_hdw(job)\n% Warp a pair of same subject images together\n%\n% Very little support can be provided for the warping routine, as it\n% involves optimising a very nonlinear objective function.\n% Also, don't ask what the best value for the regularisation is.\n%_______________________________________________________________________\n% Copyright (C) 2006 Wellcome Department of Imaging Neuroscience\n\n% John Ashburner\n% $Id$\n\nfor i=1:numel(job.data),\n run_warping(job.data(i).mov{1},job.data(i).ref{1},job.warp_opts,job.bias_opts);\nend;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction run_warping(PF,PG,warp_opts,bias_opts)\n\nVG = spm_vol(PG);\nVF = spm_vol(PF);\nreg = warp_opts.reg;\nnit = warp_opts.nits;\n\n% Load the image pair as 8 bit.\n%-----------------------------------------------------------------------\nbo = bias_opts;\n[VG.uint8,sf] = loaduint8(VG); % Template\nVF.uint8 = bias_correction(VF,VG,bo.nits,bo.fwhm,bo.reg,bo.lmreg,sf);\n\n% Try loading pre-existing deformation fields. Otherwise, create\n% deformation fields from uniform affine transformations.\n%-----------------------------------------------------------------------\n[pth,nme,ext,num] = spm_fileparts(VF.fname);\nofname = fullfile(pth,['y_' nme '.nii']);\nDef = cell(3,1);\nif exist(ofname)==2,\n P = [repmat(ofname,3,1), [',1,1';',1,2';',1,3']];\n VT = spm_vol(P);\n if any(abs(VT(1).mat\\VG.mat - eye(4))>0.00001),\n error('Incompatible affine transformation matrices.');\n end;\n Def{1} = spm_load_float(VT(1));\n Def{2} = spm_load_float(VT(2));\n Def{3} = spm_load_float(VT(3));\n spm_affdef(Def{:},inv(VF.mat));\nelse,\n fprintf('Generating uniform affine transformation field\\n');\n Def{1} = single(1:VG.dim(1))';\n Def{1} = Def{1}(:,ones(VG.dim(2),1),ones(VG.dim(3),1));\n Def{2} = single(1:VG.dim(2));\n Def{2} = Def{2}(ones(VG.dim(1),1),:,ones(VG.dim(3),1));\n Def{3} = reshape(single(1:VG.dim(3)),1,1,VG.dim(3));\n Def{3} = Def{3}(ones(VG.dim(1),1),ones(VG.dim(2),1),:);\n spm_affdef(Def{:},VF.mat\\VG.mat);\nend;\n\n% Voxel sizes\n%-----------------------------------------------------------------------\nvxg = sqrt(sum(VG.mat(1:3,1:3).^2))';if det(VG.mat(1:3,1:3))<0, vxg(1) = -vxg(1); end;\nvxf = sqrt(sum(VF.mat(1:3,1:3).^2))';if det(VF.mat(1:3,1:3))<0, vxf(1) = -vxf(1); end;\n\n% Do warping\n%-----------------------------------------------------------------------\nfprintf('Warping (iterations=%d regularisation=%g)\\n', nit, reg);\nspm_warp(VG.uint8,VF.uint8,Def{:},[vxg vxf],[nit,reg,1,0]);\n\n% Convert mapping from voxels to mm\n%-----------------------------------------------------------------------\nspm_affdef(Def{:},VF.mat);\n\n% Write the deformations\n%-----------------------------------------------------------------------\nsave_def(Def,VG.mat,ofname)\n\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction [udat,sf] = loaduint8(V)\n% Load data from file indicated by V into an array of unsigned bytes.\n\nspm_progress_bar('Init',V.dim(3),...\n ['Computing max/min of ' spm_str_manip(V.fname,'t')],...\n 'Planes complete');\nmx = -Inf;\nfor p=1:V.dim(3),\n img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n mx = max([max(img(:)) mx]);\n spm_progress_bar('Set',p);\nend;\nspm_progress_bar('Init',V.dim(3),...\n ['Loading ' spm_str_manip(V.fname,'t')],...\n 'Planes loaded');\nsf = 255/mx;\n\nudat = uint8(0);\nudat(V.dim(1),V.dim(2),V.dim(3))=0;\nfor p=1:V.dim(3),\n img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);\n udat(:,:,p) = round(max(min(img*sf,255),0));\n spm_progress_bar('Set',p);\nend;\nspm_progress_bar('Clear');\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction t = transf(B1,B2,B3,T)\nd2 = [size(T) 1];\nt1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));\nt = B1*t1*B2';\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction udat = bias_correction(VF,VG,nits,fwhm,reg1,reg2,sf)\n% This function is intended for doing bias correction prior\n% to high-dimensional intra-subject registration. Begin by\n% coregistering, then run the bias correction, and then do\n% the high-dimensional warping. A version of the first image\n% is returned out, that has the same bias as that of the second\n% image. This allows warping of the corrected first image, to\n% match the uncorrected second image.\n%\n% Ideally, it would all be combined into the same model, but\n% that would require quite a lot of extra work. I should really\n% sort out a good convergence criterion, and make it a proper\n% Levenberg-Marquardt optimisation.\n\nvx = sqrt(sum(VF.mat(1:3,1:3).^2));\nd = VF.dim(1:3);\nsd = vx(1)*VF.dim(1)/fwhm; d3(1) = ceil(sd*2); krn_x = exp(-(0:(d3(1)-1)).^2/sd.^2)/sqrt(vx(1));\nsd = vx(2)*VF.dim(2)/fwhm; d3(2) = ceil(sd*2); krn_y = exp(-(0:(d3(2)-1)).^2/sd.^2)/sqrt(vx(2));\nsd = vx(3)*VF.dim(3)/fwhm; d3(3) = ceil(sd*2); krn_z = exp(-(0:(d3(3)-1)).^2/sd.^2)/sqrt(vx(3));\nCbias = kron(krn_z,kron(krn_y,krn_x)).^(-2)*prod(d)*reg1;\nCbias = sparse(1:length(Cbias),1:length(Cbias),Cbias,length(Cbias),length(Cbias));\nB3bias = spm_dctmtx(d(3),d3(3));\nB2bias = spm_dctmtx(d(2),d3(2));\nB1bias = spm_dctmtx(d(1),d3(1));\nlmRb = speye(size(Cbias))*prod(d)*reg2;\nTbias = zeros(d3);\n\nll = Inf;\nspm_chi2_plot('Init','Bias Correction','- Log-likelihood','Iteration');\nfor subit=1:nits,\n\n % Compute objective function and its 1st and second derivatives\n Alpha = zeros(prod(d3),prod(d3)); % Second derivatives\n Beta = zeros(prod(d3),1); % First derivatives\n oll = ll;\n ll = 0.5*Tbias(:)'*Cbias*Tbias(:);\n\n for z=1:VF.dim(3),\n M1 = spm_matrix([0 0 z]);\n M2 = VG.mat\\VF.mat*M1;\n f1o = spm_slice_vol(VF,M1,VF.dim(1:2),0);\n f2o = spm_slice_vol(VG,M2,VF.dim(1:2),0);\n msk = (f1o==0) & (f2o==0);\n f1o(msk) = 0;\n f2o(msk) = 0;\n ro = transf(B1bias,B2bias,B3bias(z,:),Tbias);\n msk = abs(ro)>0.01; % false(d(1:2));\n\n % Use the form based on an integral for bias that is\n % far from uniform.\n f1 = f1o(msk);\n f2 = f2o(msk);\n r = ro(msk);\n e = exp(r);\n t1 = (f2.*e-f1);\n t2 = (f1./e-f2);\n ll = ll + 1/4*sum(sum((t1.^2-t2.^2)./r));\n wt1 = zeros(size(f1o));\n wt2 = zeros(size(f1o));\n wt1(msk) = (2*(t1.*f2.*e+t2.*f1./e)./r + (t2.^2-t1.^2)./r.^2)/4;\n wt2(msk) = ((f2.^2.*e.^2-f1.^2./e.^2+t1.*f2.*e-t2.*f1./e)./r/2 ...\n - (t1.*f2.*e+t2.*f1./e)./r.^2 + (t1.^2-t2.^2)./r.^3/2);\n\n % Use the simple symmetric form for bias close to uniform\n f1 = f1o(~msk);\n f2 = f2o(~msk);\n r = ro(~msk);\n e = exp(r);\n t1 = (f2.*e-f1);\n t2 = (f1./e-f2);\n ll = ll + (sum(t1.^2)+sum(t2.^2))/4;\n wt1(~msk) = (t1.*f2.*e-t2.*f1./e)/2;\n wt2(~msk) = ((f2.*e).^2+t1.*f2.*e + (f1./e).^2+t2.*f1./e)/2;\n\n b3 = B3bias(z,:)';\n Beta = Beta + kron(b3,spm_krutil(wt1,B1bias,B2bias,0));\n Alpha = Alpha + kron(b3*b3',spm_krutil(wt2,B1bias,B2bias,1));\n end;\n spm_chi2_plot('Set',ll/prod(d));\n\n\n if subit > 1 && ll>oll,\n % Hasn't improved, so go back to previous solution\n Tbias = oTbias;\n ll = oll;\n lmRb = lmRb*10;\n else\n % Accept new solution\n oTbias = Tbias;\n Tbias = Tbias(:);\n Tbias = Tbias - (Alpha + Cbias + lmRb)\\(Beta + Cbias*Tbias);\n Tbias = reshape(Tbias,d3);\n end;\nend;\n\nudat = uint8(0);\nudat(VF.dim(1),VF.dim(2),VF.dim(3)) = 0;\nfor z=1:VF.dim(3),\n M1 = spm_matrix([0 0 z]);\n f1 = spm_slice_vol(VF,M1,VF.dim(1:2),0);\n r = transf(B1bias,B2bias,B3bias(z,:),Tbias);\n f1 = f1./exp(r);\n udat(:,:,z) = round(max(min(f1*sf,255),0));\nend;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction save_def(Def,mat,fname)\n% Save a deformation field as an image\n\ndim = [size(Def{1},1) size(Def{1},2) size(Def{1},3) 1 3];\ndtype = 'FLOAT32-BE';\noff = 0;\nscale = 1;\ninter = 0;\ndat = file_array(fname,dim,dtype,off,scale,inter);\n\nN = nifti;\nN.dat = dat;\nN.mat = mat;\nN.mat0 = mat;\nN.mat_intent = 'Aligned';\nN.mat0_intent = 'Aligned';\nN.intent.code = 'VECTOR';\nN.intent.name = 'Mapping';\nN.descrip = 'Deformation field';\ncreate(N);\nN.dat(:,:,:,1,1) = Def{1};\nN.dat(:,:,:,1,2) = Def{2};\nN.dat(:,:,:,1,3) = Def{3};\n\n% Write Jacobian determinants\n[pth,nme,ext,num] = spm_fileparts(fname);\njfname = fullfile(pth,['j' nme '.nii'])\ndt = spm_def2det(Def{:},N.mat);\ndat = file_array(jfname,dim(1:3),dtype,off,scale,inter);\nN = nifti;\nN.dat = dat;\nN.mat = mat;\nN.mat0 = mat;\nN.mat_intent = 'Aligned';\nN.mat0_intent = 'Aligned';\nN.intent.code = 'NONE';\nN.intent.name = 'Det';\nN.descrip = 'Jacobian Determinant';\ncreate(N);\nN.dat(:,:,:) = dt;\nreturn;\n%_______________________________________________________________________\n\n%_______________________________________________________________________\nfunction theory\n% This function is never called. It simply contains my derivation of the\n% objective function and its first and second derivatives for the LM\n% optimisation. Note that this would simply be summed over all voxels.\n% An estimate of the variance should maybe have been included, but I'll\n% leave that for a future version.\n\n% These will be used to simplify expressions\nr = x1*p1+x2*p2;\ne = exp(r);\nt1 = (f2*e-f1)\nt2 = (f1/e-f2)\n\n% This is the actual objective function\nmaple int((exp(-(x1*p1+x2*p2)*(1-t))*f1-exp((x1*p1+x2*p2)*t)*f2)^2/2,t=0..1)\nf = 1/4*(t1^2-t2^2)/r\n\n% These are the first derivatives\nmaple diff(1/4*((f1-f2*exp(x1*p1+x2*p2))^2-(f2-f1/exp(x1*p1+x2*p2))^2)/(x1*p1+x2*p2),x1)\nd1 = p1*1/4*(2*(t1*f2*e+t2*f1/e)/r + (t2^2-t1^2)/r^2)\n\n% These are the second derivatives\nmaple diff(diff(1/4*((f1-f2*exp(x1*p1+x2*p2))^2-(f2-f1/exp(x1*p1+x2*p2))^2)/(x1*p1+x2*p2),x1),x2)\nd2 = p1*p2*(1/2*(f2^2*e^2-f1^2/e^2+t1*f2*e-t2*f1/e)/r - (t1*f2*e+t2*f1/e)/r^2 + 1/2*(t1^2-t2^2)/r^3)\n\n\n% However, the above formulation has problems in limiting case of zero bias,\n% so this objective function is used for these regions\nf = (t1^2+t2^2)/4\n\n% First derivs\nmaple diff((f1-exp(x1*p1+x2*p2)*f2)^2/4 + (f1/exp(x1*p1+x2*p2)-f2)^2/4,x1)\nd1 = (p1*t1*f2*e - p1*t2*f1/e)/2\n\n% Second derivatives\nmaple diff(diff((f1-exp(x1*p1+x2*p2)*f2)^2/4 + (f1/exp(x1*p1+x2*p2)-f2)^2/4,x1),x2)\nd2 = p1*p2*(f2^2*e^2+t1*f2*e + f1^2/e^2+t2*f1/e)/2\n\n\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "subsasgn.m", "ext": ".m", "path": "spm5-master/@file_array/subsasgn.m", "size": 4391, "source_encoding": "utf_8", "md5": "15f88c208f436610f7b87938c84835af", "text": "function obj = subsasgn(obj,subs,dat)\n% Overloaded subsasgn function for file_array objects.\n% _______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n%\n% $Id: subsasgn.m 945 2007-10-14 18:08:46Z volkmar $\n\n\nif isempty(subs)\n return;\nend;\nif ~strcmp(subs(1).type,'()'),\n if strcmp(subs(1).type,'.'),\n %error('Attempt to reference field of non-structure array.');\n if numel(struct(obj))~=1,\n error('Can only change the fields of simple file_array objects.');\n end;\n switch(subs(1).subs)\n case 'fname', obj = asgn(obj,@fname, subs(2:end),dat); %fname(obj,dat);\n case 'dtype', obj = asgn(obj,@dtype, subs(2:end),dat); %dtype(obj,dat);\n case 'offset', obj = asgn(obj,@offset, subs(2:end),dat); %offset(obj,dat);\n case 'dim', obj = asgn(obj,@dim, subs(2:end),dat); %obj = dim(obj,dat);\n case 'scl_slope', obj = asgn(obj,@scl_slope,subs(2:end),dat); %scl_slope(obj,dat);\n case 'scl_inter', obj = asgn(obj,@scl_inter,subs(2:end),dat); %scl_inter(obj,dat);\n otherwise, error(['Reference to non-existent field \"' subs.subs '\".']);\n end;\n return;\n end;\n if strcmp(subs(1).type,'{}'), error('Cell contents reference from a non-cell array object.'); end;\nend;\n\nif numel(subs)~=1, error('Expression too complicated');end;\ndm = size(obj);\nsobj = struct(obj);\n\nif length(subs.subs) < length(dm),\n l = length(subs.subs);\n dm = [dm(1:(l-1)) prod(dm(l:end))];\n if numel(sobj) ~= 1,\n error('Can only reshape simple file_array objects.');\n end;\n if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1,\n error('Can not reshape file_array objects with multiple slopes and intercepts.');\n end;\nend;\n\ndm = [dm ones(1,16)];\ndo = ones(1,16);\nargs = {};\nfor i=1:length(subs.subs),\n if ischar(subs.subs{i}),\n if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end;\n args{i} = int32(1:dm(i));\n else\n args{i} = int32(subs.subs{i});\n end;\n do(i) = length(args{i});\nend;\nif length(sobj)==1\n sobj.dim = dm;\n if numel(dat)~=1,\n subfun(sobj,double(dat),args{:});\n else\n dat1 = double(dat) + zeros(do);\n subfun(sobj,dat1,args{:});\n end;\nelse\n for j=1:length(sobj),\n ps = [sobj(j).pos ones(1,length(args))];\n dm = [sobj(j).dim ones(1,length(args))];\n siz = ones(1,16);\n for i=1:length(args),\n msk = args{i}>=ps(i) & args{i}<(ps(i)+dm(i));\n args2{i} = find(msk);\n args3{i} = int32(double(args{i}(msk))-ps(i)+1);\n siz(i) = numel(args2{i});\n end;\n if numel(dat)~=1,\n dat1 = double(subsref(dat,struct('type','()','subs',{args2})));\n else\n dat1 = double(dat) + zeros(siz);\n end;\n subfun(sobj(j),dat1,args3{:});\n end\nend\nreturn\n\nfunction sobj = subfun(sobj,dat,varargin)\nva = varargin;\n\ndt = datatypes;\nind = find(cat(1,dt.code)==sobj.dtype);\nif isempty(ind), error('Unknown datatype'); end;\nif dt(ind).isint, dat(~isfinite(dat)) = 0; end;\n\nif ~isempty(sobj.scl_inter),\n inter = sobj.scl_inter;\n if numel(inter)>1,\n inter = resize_scales(inter,sobj.dim,varargin);\n end;\n dat = double(dat) - inter;\nend;\n\nif ~isempty(sobj.scl_slope),\n slope = sobj.scl_slope;\n if numel(slope)>1,\n slope = resize_scales(slope,sobj.dim,varargin);\n dat = double(dat)./slope;\n else\n dat = double(dat)/slope;\n end;\nend;\n\nif dt(ind).isint, dat = round(dat); end;\n\n% Avoid warning messages in R14 SP3\nwrn = warning;\nwarning('off');\ndat = feval(dt(ind).conv,dat);\nwarning(wrn);\n\nnelem = dt(ind).nelem;\nif nelem==1,\n mat2file(sobj,dat,va{:});\nelseif nelem==2,\n sobj1 = sobj;\n sobj1.dim = [2 sobj.dim];\n sobj1.dtype = dt(find(strcmp(dt(ind).prec,{dt.prec}) & (cat(2,dt.nelem)==1))).code;\n dat = reshape(dat,[1 size(dat)]);\n dat = [real(dat) ; imag(dat)];\n mat2file(sobj1,dat,int32([1 2]),va{:});\nelse\n error('Inappropriate number of elements per voxel.');\nend;\nreturn\n\nfunction obj = asgn(obj,fun,subs,dat)\nif ~isempty(subs),\n tmp = feval(fun,obj);\n tmp = subsasgn(tmp,subs,dat);\n obj = feval(fun,obj,tmp);\nelse\n obj = feval(fun,obj,dat);\nend;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "subsref.m", "ext": ".m", "path": "spm5-master/@file_array/subsref.m", "size": 3491, "source_encoding": "utf_8", "md5": "ad5a748cb36c7c36dc4231cafb53cea8", "text": "function varargout=subsref(obj,subs)\n% SUBSREF Subscripted reference\n% An overloaded function...\n% _________________________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n%\n% $Id: subsref.m 315 2005-11-28 16:48:59Z john $\n\n\nif isempty(subs)\n return;\nend;\n\nif ~strcmp(subs(1).type,'()'),\n if strcmp(subs(1).type,'.'),\n %error('Attempt to reference field of non-structure array.');\n %if numel(struct(obj))~=1,\n % error('Can only access the fields of simple file_array objects.');\n %end;\n\n varargout = access_fields(obj,subs);\n return;\n end;\n if strcmp(subs.type,'{}'), error('Cell contents reference from a non-cell array object.'); end;\nend;\n\nif numel(subs)~=1, error('Expression too complicated');end;\n\ndim = [size(obj) ones(1,16)];\nnd = max(find(dim>1))-1;\nsobj = struct(obj);\n\nif length(subs.subs) < nd,\n l = length(subs.subs);\n dim = [dim(1:(l-1)) prod(dim(l:end))];\n if numel(sobj) ~= 1,\n error('Can only reshape simple file_array objects.');\n else\n if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1,\n error('Can not reshape file_array objects with multiple slopes and intercepts.');\n end;\n sobj.dim = dim;\n end;\nend;\n\ndo = ones(16,1);\nargs = {};\nfor i=1:length(subs.subs),\n if ischar(subs.subs{i}),\n if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end;\n args{i} = int32(1:dim(i));\n else\n args{i} = int32(subs.subs{i});\n end;\n do(i) = length(args{i});\nend;\n\nif length(sobj)==1,\n t = subfun(sobj,args{:});\nelse\n t = zeros(do');\n for j=1:length(sobj),\n ps = [sobj(j).pos ones(1,length(args))];\n dm = [sobj(j).dim ones(1,length(args))];\n for i=1:length(args),\n msk = find(args{i}>=ps(i) & args{i}<(ps(i)+dm(i)));\n args2{i} = msk;\n args3{i} = int32(double(args{i}(msk))-ps(i)+1);\n end;\n\n t = subsasgn(t,struct('type','()','subs',{args2}),subfun(sobj(j),args3{:}));\n end\nend\nvarargout = {t};\nreturn;\n\nfunction t = subfun(sobj,varargin)\n%sobj.dim = [sobj.dim ones(1,16)];\nt = file2mat(sobj,varargin{:});\nif ~isempty(sobj.scl_slope) || ~isempty(sobj.scl_inter)\n slope = 1;\n inter = 0;\n if ~isempty(sobj.scl_slope), slope = sobj.scl_slope; end;\n if ~isempty(sobj.scl_inter), inter = sobj.scl_inter; end;\n if numel(slope)>1,\n slope = resize_scales(slope,sobj.dim,varargin);\n t = double(t).*slope;\n else\n t = double(t)*slope;\n end;\n if numel(inter)>1,\n inter = resize_scales(inter,sobj.dim,varargin);\n end;\n t = t + inter;\nend;\nreturn;\n\nfunction c = access_fields(obj,subs)\n%error('Attempt to reference field of non-structure array.');\n%if numel(struct(obj))~=1,\n% error('Can only access the fields of simple file_array objects.');\n%end;\nc = {};\nsobj = struct(obj);\nfor i=1:numel(sobj),\n %obj = class(sobj(i),'file_array');\n obj = sobj(i);\n switch(subs(1).subs)\n case 'fname', t = fname(obj);\n case 'dtype', t = dtype(obj);\n case 'offset', t = offset(obj);\n case 'dim', t = dim(obj);\n case 'scl_slope', t = scl_slope(obj);\n case 'scl_inter', t = scl_inter(obj);\n otherwise, error(['Reference to non-existent field \"' subs(1).type '\".']);\n end;\n if numel(subs)>1,\n t = subsref(t,subs(2:end));\n end;\n c{i} = t;\nend;\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "disp.m", "ext": ".m", "path": "spm5-master/@file_array/disp.m", "size": 936, "source_encoding": "utf_8", "md5": "b554bdf3b9952d0af1a8bff9b3b2d79b", "text": "function disp(obj)\n% Display a file_array object\n% _______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n%\n% $Id: disp.m 253 2005-10-13 15:31:34Z guillaume $\n\n\nif numel(struct(obj))>1,\n fprintf(' %s object: ', class(obj));\n sz = size(obj);\n if length(sz)>4,\n fprintf('%d-D\\n',length(sz));\n else\n for i=1:(length(sz)-1),\n fprintf('%d-by-',sz(i));\n end;\n fprintf('%d\\n',sz(end));\n end;\nelse\n display(mystruct(obj))\nend;\nreturn;\n%=======================================================================\n\n%=======================================================================\nfunction t = mystruct(obj)\nfn = fieldnames(obj);\nfor i=1:length(fn)\n t.(fn{i}) = subsref(obj,struct('type','.','subs',fn{i}));\nend;\nreturn;\n%=======================================================================\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "offset.m", "ext": ".m", "path": "spm5-master/@file_array/private/offset.m", "size": 748, "source_encoding": "utf_8", "md5": "c89ae4584631eea52eb87b0dfd4fd7d3", "text": "function varargout = offset(varargin)\n% Format\n% For getting the value\n% dat = offset(obj)\n%\n% For setting the value\n% obj = offset(obj,dat)\n% _______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n%\n% $Id: offset.m 253 2005-10-13 15:31:34Z guillaume $\n\n\n\nif nargin==2,\n varargout{1} = asgn(varargin{:});\nelseif nargin==1,\n varargout{1} = ref(varargin{:});\nelse\n error('Wrong number of arguments.');\nend;\nreturn;\n\nfunction dat = ref(obj)\ndat = obj.offset;\nreturn;\n\nfunction obj = asgn(obj,dat)\nif isnumeric(dat) && numel(dat)==1 && dat>=0 && rem(dat,1)==0,\n obj.offset = double(dat);\nelse\n error('\"offset\" must be a positive integer.');\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "scl_slope.m", "ext": ".m", "path": "spm5-master/@file_array/private/scl_slope.m", "size": 734, "source_encoding": "utf_8", "md5": "73f54f5dbe19e718bd6b78dc882dc8af", "text": "function varargout = scl_slope(varargin)\n% Format\n% For getting the value\n% dat = scl_slope(obj)\n%\n% For setting the value\n% obj = scl_slope(obj,dat)\n% _______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n%\n% $Id: scl_slope.m 253 2005-10-13 15:31:34Z guillaume $\n\n\n\nif nargin==2,\n varargout{1} = asgn(varargin{:});\nelseif nargin==1,\n varargout{1} = ref(varargin{:});\nelse\n error('Wrong number of arguments.');\nend;\nreturn;\n\nfunction dat = ref(obj)\ndat = obj.scl_slope;\nreturn;\n\nfunction obj = asgn(obj,dat)\nif isnumeric(dat), % && numel(dat)<=1,\n obj.scl_slope = double(dat);\nelse\n error('\"scl_slope\" must be numeric.');\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "scl_inter.m", "ext": ".m", "path": "spm5-master/@file_array/private/scl_inter.m", "size": 735, "source_encoding": "utf_8", "md5": "def2da385023fb5bdc7cc3ce9fcd3395", "text": "function varargout = scl_inter(varargin)\n% Format\n% For getting the value\n% dat = scl_inter(obj)\n%\n% For setting the value\n% obj = scl_inter(obj,dat)\n% _______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n%\n% $Id: scl_inter.m 253 2005-10-13 15:31:34Z guillaume $\n\n\n\nif nargin==2,\n varargout{1} = asgn(varargin{:});\nelseif nargin==1,\n varargout{1} = ref(varargin{:});\nelse\n error('Wrong number of arguments.');\nend;\nreturn;\n\nfunction dat = ref(obj)\ndat = obj.scl_inter;\nreturn;\n\nfunction obj = asgn(obj,dat)\nif isnumeric(dat), % && numel(dat)<=1,\n obj.scl_inter = double(dat);\nelse\n error('\"scl_inter\" must be numeric.');\nend;\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "fname.m", "ext": ".m", "path": "spm5-master/@file_array/private/fname.m", "size": 698, "source_encoding": "utf_8", "md5": "c6216888cbebeb595fd5802255c31b22", "text": "function varargout = fname(varargin)\n% Format\n% For getting the value\n% dat = fname(obj)\n%\n% For setting the value\n% obj = fname(obj,dat)\n% _______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n%\n% $Id: fname.m 253 2005-10-13 15:31:34Z guillaume $\n\n\n\nif nargin==2,\n varargout{1} = asgn(varargin{:});\nelseif nargin==1,\n varargout{1} = ref(varargin{:});\nelse\n error('Wrong number of arguments.');\nend;\nreturn;\n\nfunction dat = ref(obj)\ndat = obj.fname;\nreturn;\n\nfunction obj = asgn(obj,dat)\nif ischar(dat)\n obj.fname = deblank(dat(:)');\nelse\n error('\"fname\" must be a character string.');\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "dim.m", "ext": ".m", "path": "spm5-master/@file_array/private/dim.m", "size": 810, "source_encoding": "utf_8", "md5": "93395c42c87fe17ad7dcc88a6062ebf8", "text": "function varargout = dim(varargin)\n% Format\n% For getting the value\n% dat = dim(obj)\n%\n% For setting the value\n% obj = dim(obj,dat)\n% _______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n%\n% $Id: dim.m 253 2005-10-13 15:31:34Z guillaume $\n\n\nif nargin==2,\n varargout{1} = asgn(varargin{:});\nelseif nargin==1,\n varargout{1} = ref(varargin{:});\nelse\n error('Wrong number of arguments.');\nend;\nreturn;\n\nfunction dat = ref(obj)\ndat = obj.dim;\nreturn;\n\nfunction obj = asgn(obj,dat)\nif isnumeric(dat) && all(dat>=0) && all(rem(dat,1)==0),\n dat = [double(dat(:)') 1 1];\n lim = max([2 find(dat~=1)]);\n dat = dat(1:lim);\n obj.dim = dat;\nelse\n error('\"dim\" must be a vector of positive integers.');\nend;\nreturn;\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "dtype.m", "ext": ".m", "path": "spm5-master/@file_array/private/dtype.m", "size": 2270, "source_encoding": "utf_8", "md5": "380230a467432825a6b68b343c50cbc2", "text": "function varargout = dtype(varargin)\n% Format\n% For getting the value\n% dat = dtype(obj)\n%\n% For setting the value\n% obj = dtype(obj,dat)\n% _______________________________________________________________________\n% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience\n\n%\n% $Id: dtype.m 466 2006-03-01 15:14:22Z john $\n\n\n\nif nargin==2,\n varargout{1} = asgn(varargin{:});\nelseif nargin==1,\n varargout{1} = ref(varargin{:});\nelse\n error('Wring number of arguments.');\nend;\nreturn;\n\nfunction t = ref(obj)\nd = datatypes;\nmch = find(cat(1,d.code)==obj.dtype);\nif isempty(mch), t = 'UNKNOWN'; else t = d(mch).label; end;\nif obj.be, t = [t '-BE']; else t = [t '-LE']; end;\nreturn;\n\nfunction obj = asgn(obj,dat)\nd = datatypes;\nif isnumeric(dat)\n if numel(dat)>=1,\n mch = find(cat(1,d.code)==dat(1));\n if isempty(mch) || mch==0,\n fprintf('Invalid datatype (%d).', dat(1));\n disp('First part of datatype should be of one of the following');\n disp(sortrows([num2str(cat(1,d.code)) ...\n repmat(' ',numel(d),2) strvcat(d.label)]));\n %error(['Invalid datatype (' num2str(dat(1)) ').']);\n return;\n end;\n obj.dtype = double(dat(1));\n end;\n if numel(dat)>=2,\n obj.be = double(dat(2)~=0);\n end;\n if numel(dat)>2,\n error('Too many elements in numeric datatype.');\n end;\nelseif ischar(dat),\n dat1 = lower(dat);\n sep = find(dat1=='-' | dat1=='/');\n sep = sep(sep~=1);\n if ~isempty(sep),\n c1 = dat1(1:(sep(1)-1));\n c2 = dat1((sep(1)+1):end);\n else\n c1 = dat1;\n c2 = '';\n end;\n mch = find(strcmpi(c1,lower({d.label})));\n if isempty(mch),\n disp('First part of datatype should be of one of the following');\n disp(sortrows([num2str(cat(1,d.code)) ...\n repmat(' ',numel(d),2) strvcat(d.label)]));\n %error(['Invalid datatype (' c1 ').']);\n return;\n else\n obj.dtype = double(d(mch(1)).code);\n end;\n if any(c2=='b'),\n if any(c2=='l'),\n error('Cannot be both big and little endian.');\n end;\n obj.be = 1;\n elseif any(c2=='l'),\n obj.be = 0;\n end;\nelse\n error('Invalid datatype.');\nend;\nreturn;\n\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "paint.m", "ext": ".m", "path": "spm5-master/@slover/paint.m", "size": 10059, "source_encoding": "utf_8", "md5": "b0890caeac7c122fe24ae8dc9ed9c742", "text": "function obj = paint(obj, params)\n% method to display slice overlay\n% FORMAT paint(obj, params)\n% \n% Inputs \n% obj - slice overlay object\n% params - optional structure containing extra display parameters\n% - refreshf - overrides refreshf in object\n% - clf - overrides clf in object \n% - userdata - if 0, does not add object to userdata field\n% (see below)\n%\n% Outputs\n% obj - which may have been filled with defaults\n% \n% paint attaches the object used for painting to the 'UserData' field of\n% the figure handle, unless instructed not to with 0 in userdata flag\n%\n% $Id: paint.m,v 1.2 2005/05/06 22:59:56 matthewbrett Exp $ \n\nfig_struct_fields = {'Position', 'Units'};\n\nif nargin < 2\n params = [];\nend\nparams = mars_struct('fillafromb', params, ...\n\t\t struct('refreshf', obj.refreshf,...\n\t\t\t 'clf', obj.clf, ...\n\t\t\t 'userdata', obj.userdata));\n\n% Fill any needed defaults\nobj = fill_defaults(obj); \n\n% check if object can be painted\nif isempty(obj.img)\n warning('No images, object cannot be painted')\n return\nend\n\n% get coordinates for plane\nX=1;Y=2;Z=3;\ndims = obj.slicedef;\nxmm = dims(X,1):dims(X,2):dims(X,3);\nymm = dims(Y,1):dims(Y,2):dims(Y,3);\nzmm = obj.slices;\n[y x] = meshgrid(ymm,xmm');\nvdims = [length(xmm),length(ymm),length(zmm)];\n\n% no of slices, and panels (an extra for colorbars)\nnslices = vdims(Z);\nminnpanels = nslices;\ncbars = 0;\nif ~isempty(obj.cbar)\n cbars = length(obj.cbar);\n minnpanels = minnpanels+cbars;\nend\n\n% Get figure data. The figure may be dead, in which case we may want to\n% revive it. If so, we set position etc as stored.\n% If written to, the axes may be specified already\ndead_f = ~ishandle(obj.figure);\nfigno = figure(obj.figure);\nif dead_f\n set(figno, obj.figure_struct);\nend\n\n% (re)initialize axes and stuff\n\n% check if the figure is set up correctly\nif ~params.refreshf\n axisd = flipud(findobj(obj.figure, 'Type','axes','Tag', 'slice overlay panel'));\n npanels = length(axisd);\n if npanels < vdims(Z)+cbars;\n params.refreshf = 1;\n end\nend\nif params.refreshf\n % clear figure, axis store\n if params.clf, clf; end\n axisd = [];\n\n % prevent print inversion problems\n set(figno,'InvertHardCopy','off');\n\n % put copy of object into UserData for callbacks\n if params.userdata\n set(figno, 'UserData', obj);\n end\n \n % calculate area of display in pixels\n parea = obj.area.position;\n if ~strcmp(obj.area.units, 'pixels')\n ubu = get(obj.figure, 'units');\n set(obj.figure, 'units','pixels');\n tmp = get(obj.figure, 'Position');\n ascf = tmp(3:4);\n if ~strcmp(obj.area.units, 'normalized')\n set(obj.figure, 'units',obj.area.units);\n tmp = get(obj.figure, 'Position');\n ascf = ascf ./ tmp(3:4);\n end\n set(figno, 'Units', ubu);\n parea = parea .* repmat(ascf, 1, 2);\n end\n asz = parea(3:4);\n \n % by default, make most parsimonious fit to figure\n yxratio = length(ymm)*dims(Y,2)/(length(xmm)*dims(X,2));\n if isempty(obj.xslices)\n % iteration needed to optimize, surprisingly. Thanks to Ian NS\n axlen(X,:)=asz(1):-1:1;\n axlen(Y,:)=yxratio*axlen(X,:);\n panels = floor(asz'*ones(1,size(axlen,2))./axlen);\n estnpanels = prod(panels);\n tmp = find(estnpanels >= minnpanels);\n if isempty(tmp)\n error('Whoops, cannot fit panels onto figure');\n end\n b = tmp(1); % best fitting scaling\n panels = panels(:,b);\n axlen = axlen(:, b);\n else\n % if xslices is specified, assume X is flush with X figure dimensions\n panels([X:Y],1) = [obj.xslices; 0];\n axlen([X:Y],1) = [asz(X)/panels(X); 0];\n end\n \n % Axis dimensions are in pixels. This prevents aspect ratio rescaling\n panels(Y) = ceil(minnpanels/panels(X));\n axlen(Y) = axlen(X)*yxratio;\n \n % centre (etc) panels in display area as required\n divs = [Inf 2 1];the_ds = [0;0];\n the_ds(X) = divs(strcmp(obj.area.halign, {'left','center','right'}));\n the_ds(Y) = divs(strcmp(obj.area.valign, {'bottom','middle','top'}));\n startc = parea(1:2)' + (asz'-(axlen.*panels))./the_ds;\n \n % make axes for panels\n r=0;c=1;\n npanels = prod(panels);\n lastempty = npanels-cbars;\n for i = 1:npanels\n % panel userdata\n if i<=nslices\n u.type = 'slice';\n u.no = zmm(i);\n elseif i > lastempty\n u.type = 'cbar';\n u.no = i - lastempty;\n else\n u.type = 'empty';\n u.no = i - nslices;\n end\n axpos = [r*axlen(X)+startc(X) (panels(Y)-c)*axlen(Y)+startc(Y) axlen'];\n axisd(i) = axes(...\n\t'Parent',figno,...\n\t'XTick',[],...\n\t'XTickLabel',[],...\n\t'YTick',[],...\n\t'YTickLabel',[],...\n\t'Box','on',...\n\t'XLim',[1 vdims(X)],...\n\t'YLim',[1 vdims(Y)],...\n\t'Units', 'pixels',...\n\t'Position',axpos,...\n\t'Tag','slice overlay panel',...\n\t'UserData',u);\n r = r+1;\n if r >= panels(X)\n r = 0;\n c = c+1;\n end\n end\nend\n\n% sort out labels\nif ischar(obj.labels)\n do_labels = ~strcmp(lower(obj.labels), 'none');\nelse\n do_labels = 1;\nend\nif do_labels\n labels = obj.labels;\n if iscell(labels.format)\n if length(labels.format)~=vdims(Z)\n error(...\n\t sprintf('Oh dear, expecting %d labels, but found %d',...\n\t\t vdims(Z), length(labels.contents)));\n end\n else\n % format string for mm from AC labelling\n fstr = labels.format;\n labels.format = cell(vdims(Z),1);\n acpt = obj.transform * [0 0 0 1]';\n for i = 1:vdims(Z)\n labels.format(i) = {sprintf(fstr,zmm(i)-acpt(Z))};\n end\n end\nend\n\n% split images into picture and contour\nitypes = {obj.img(:).type};\ntmp = strcmpi(itypes, 'contour');\ncontimgs = find(tmp);\npictimgs = find(~tmp);\n\n% modify picture image colormaps with any new colours\nnpimgs = length(pictimgs);\nlrn = zeros(npimgs,3);\ncmaps = cell(npimgs);\nfor i = 1:npimgs\n cmaps(i)={obj.img(pictimgs(i)).cmap};\n lrnv = {obj.img(pictimgs(i)).outofrange{:}, obj.img(pictimgs(i)).nancol};\n for j = 1:length(lrnv)\n if prod(size(lrnv{j}))==1\n lrn(i,j) = lrnv{j};\n else\n cmaps(i) = {[cmaps{i}; lrnv{j}(1:3)]};\n lrn(i,j) = size(cmaps{i},1);\n end\n end\nend\n\n% cycle through slices displaying images\nnvox = prod(vdims(1:2));\npandims = [vdims([2 1]) 3]; % NB XY transpose for display\n\nzimg = zeros(pandims);\nfor i = 1:nslices\n ixyzmm = [x(:)';y(:)';ones(1,nvox)*zmm(i);ones(1,nvox)];\n img = zimg;\n for j = 1:npimgs\n thisimg = obj.img(pictimgs(j));\n i1 = sf_slice2panel(thisimg, ixyzmm, obj.transform, vdims);\n % rescale to colormap\n [csdata badvals]= pr_scaletocmap(...\n\ti1,...\n\tthisimg.range(1),...\n\tthisimg.range(2),...\n\tthisimg.cmap,...\n\tlrn(j,:));\n % take indices from colormap to make true colour image\n iimg = reshape(cmaps{j}(csdata(:),:),pandims);\n tmp = repmat(logical(~badvals),[1 1 3]);\n if strcmpi(thisimg.type, 'truecolour') \n img(tmp) = img(tmp) + iimg(tmp)*thisimg.prop;\n else % split colormap effect\n img(tmp) = iimg(tmp)*thisimg.prop;\n end\n end\n % threshold out of range values\n img(img>1) = 1;\n \n image('Parent', axisd(i),...\n\t'ButtonDownFcn', obj.callback,...\n\t'CData',img);\n\n \n % do contour plot\n for j=1:length(contimgs)\n thisimg = obj.img(contimgs(j));\n i1 = sf_slice2panel(thisimg, ixyzmm, obj.transform, vdims);\n if any(any(isfinite(i1)))\n i1(i1max(thisimg.range))=max(thisimg.range);\n if mars_struct('isthere', thisimg, 'linespec')\n\tlinespec = thisimg.linespec;\n else\n\tlinespec = 'w-';\n end\n axes(axisd(i));\n set(axisd(i),'NextPlot','add');\n if mars_struct('isthere', thisimg, 'contours')\n\t[c h] = contour(i1, thisimg.contours, linespec);\n else\n\t[c h] = contour(i1, linespec);\n end\n if ~isempty(h)\n\tif ~mars_struct('isthere', thisimg, 'linespec') \n\t % need to reset colours\n\t % assumes contour value is in line UserData \n\t % as seemed to be the case \n\t convals = get(h, 'UserData');\n\t if ~iscell(convals),convals = {convals};end\n\t if ~isempty(convals)\n\t [csdata badvals] = pr_scaletocmap(...\n\t\tcat(1, convals{:}), ...\n\t\tthisimg.range(1),...\n\t\tthisimg.range(2),...\n\t\tthisimg.cmap,...\n\t\t[1 size(thisimg.cmap,1) 1]);\n\t colvals = thisimg.cmap(csdata(:),:)*thisimg.prop;\n\t set(h, {'Color'}, num2cell(colvals, 2));\n\t end\n\tend\n\tif mars_struct('isthere', thisimg, 'linewidth')\n\t set(h, 'LineWidth', thisimg.linewidth);\n\tend\n end\n end\n end \n\n if do_labels\n text('Parent',axisd(i),...\n\t 'Color', labels.colour,...\n\t 'FontUnits', 'normalized',...\n\t 'VerticalAlignment','bottom',...\n\t 'HorizontalAlignment','left',...\n\t 'Position', [1 1],...\n\t 'FontSize',labels.size,...\n\t 'ButtonDownFcn', obj.callback,...\n\t 'String', labels.format{i});\n end\nend\nfor i = (nslices+1):npanels\n set(axisd(i),'Color',[0 0 0]);\nend\n% add colorbar(s) \nfor i = 1:cbars\n axno = axisd(end-cbars+i);\n cbari = obj.img(obj.cbar(i));\n cml = size(cbari.cmap,1);\n p = get(axno, 'Position'); % position of last axis\n cw = p(3)*0.2;\n ch = p(4)*0.75;\n pc = p(3:4)/2;\n [axlims idxs] = sort(cbari.range);\n a=axes(...\n 'Parent',figno,...\n 'XTick',[],...\n 'XTickLabel',[],...\n 'Units', 'pixels',...\n 'YLim', axlims,... \n 'FontUnits', 'normalized',...\n 'FontSize', 0.075,...\n 'YColor',[1 1 1],...\n 'Tag', 'cbar',...\n 'Box', 'off',...\n 'Position',[p(1)+pc(1)-cw/2,p(2)+pc(2)-ch/2,cw,ch]...\n );\n ih = image('Parent', a,...\n\t'YData', axlims(idxs),... \n\t'CData', reshape(cbari.cmap,[cml,1,3]));\nend % colourbars\n\n% Get stuff for figure, in case it dies later\nobj.figure_struct = mars_struct('split', get(figno), fig_struct_fields);\n\nreturn\n\n% subfunctions\n% ------------\n\nfunction i1 = sf_slice2panel(img, xyzmm, transform, vdims)\n% to voxel space of image\nvixyz = inv(transform*img.vol.mat)*xyzmm;\n% raw data \nif mars_struct('isthere', img.vol, 'imgdata')\n V = img.vol.imgdata;\nelse\n V = img.vol;\nend\ni1 = spm_sample_vol(V,vixyz(1,:),vixyz(2,:),vixyz(3,:), ...\n\t\t [img.hold img.background]);\nif mars_struct('isthere', img, 'func')\n eval(img.func);\nend\n% transpose to reverse X and Y for figure\ni1 = reshape(i1, vdims(1:2))';\nreturn\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "pr_basic_ui.m", "ext": ".m", "path": "spm5-master/@slover/private/pr_basic_ui.m", "size": 3598, "source_encoding": "utf_8", "md5": "8626d5c4d641365e28e1cce491af5054", "text": "function obj = pr_basic_ui(imgs, dispf)\n% GUI to request parameters for slover routine\n% FORMAT obj = pr_basic_ui(imgs, dispf)\n%\n% GUI requests choices while accepting many defaults\n%\n% imgs - string or cell array of image names to display\n% (defaults to GUI select if no arguments passed)\n% dispf - optional flag: if set, displays overlay (default = 1)\n%\n% $Id: pr_basic_ui.m,v 1.1 2005/04/20 15:05:00 matthewbrett Exp $\n \nif nargin < 1\n imgs = '';\nend\nif isempty(imgs)\n imgs = spm_select(Inf, 'image', 'Image(s) to display');\nend\nif ischar(imgs)\n imgs = cellstr(imgs);\nend\nif nargin < 2\n dispf = 1;\nend\n \nspm_input('!SetNextPos', 1);\n\n% load images\nnimgs = size(imgs);\n\n% process names\nnchars = 20;\nimgns = spm_str_manip(imgs, ['rck' num2str(nchars)]);\n\n% Get new default object\nobj = slover;\n\n% identify image types\ncscale = [];\ndeftype = 1;\nobj.cbar = [];\nfor i = 1:nimgs\n obj.img(i).vol = spm_vol(imgs{i});\n options = {'Structural','Truecolour', ...\n\t 'Blobs','Negative blobs','Contours'};\n % if there are SPM results in the workspace, add this option\n [XYZ Z M] = pr_get_spm_results;\n if ~isempty(XYZ)\n options = {'Structural with SPM blobs', options{:}};\n end\n itype = spm_input(sprintf('Img %d: %s - image type?', i, imgns{i}), '+1', ...\n\t\t 'm', char(options),options, deftype);\n imgns(i) = {sprintf('Img %d (%s)',i,itype{1})};\n [mx mn] = slover('volmaxmin', obj.img(i).vol);\n if ~isempty(strmatch('Structural', itype))\n obj.img(i).type = 'truecolour';\n obj.img(i).cmap = gray;\n obj.img(i).range = [mn mx];\n deftype = 2;\n cscale = [cscale i];\n if strcmp(itype,'Structural with SPM blobs')\n obj = add_spm(obj);\n end\n else\n cprompt = ['Colormap: ' imgns{i}];\n switch itype{1}\n case 'Truecolour'\n obj.img(i).type = 'truecolour';\n dcmap = 'flow.lut';\n drange = [mn mx];\n cscale = [cscale i];\n obj.cbar = [obj.cbar i];\n case 'Blobs'\n obj.img(i).type = 'split';\n dcmap = 'hot';\n drange = [0 mx];\n obj.img(i).prop = 1;\n obj.cbar = [obj.cbar i];\n case 'Negative blobs'\n obj.img(i).type = 'split';\n dcmap = 'winter';\n drange = [0 mn];\n obj.img(i).prop = 1;\n obj.cbar = [obj.cbar i];\n case 'Contours'\n obj.img(i).type = 'contour';\n dcmap = 'white';\n drange = [mn mx];\n obj.img(i).prop = 1;\n end\n obj.img(i).cmap = sf_return_cmap(cprompt, dcmap);\n obj.img(i).range = spm_input('Img val range for colormap','+1', 'e', drange, 2);\n end\nend\nncmaps=length(cscale);\nif ncmaps == 1\n obj.img(cscale).prop = 1;\nelse\n remcol=1;\n for i = 1:ncmaps\n ino = cscale(i);\n obj.img(ino).prop = spm_input(sprintf('%s intensity',imgns{ino}),...\n\t\t\t\t '+1', 'e', ...\n\t\t\t\t remcol/(ncmaps-i+1),1);\n remcol = remcol - obj.img(ino).prop;\n end\nend\n \nobj.transform = deblank(spm_input('Image orientation', '+1', ['Axial|' ...\n\t\t ' Coronal|Sagittal'], strvcat('axial','coronal','sagittal'), ...\n\t\t 1));\n\n% use SPM figure window\nobj.figure = spm_figure('GetWin', 'Graphics'); \n\n% slices for display\nobj = fill_defaults(obj);\nslices = obj.slices;\nobj.slices = spm_input('Slices to display (mm)', '+1', 'e', ...\n\t\t sprintf('%0.0f:%0.0f:%0.0f',...\n\t\t\t slices(1),...\n\t\t\t mean(diff(slices)),...\n\t\t\t slices(end))...\n\t );\n\n% and do the display\nif dispf, obj = paint(obj); end\n\nreturn\n\n\n% Subfunctions \n% ------------\nfunction cmap = sf_return_cmap(prompt,defmapn)\ncmap = [];\nwhile isempty(cmap)\n [cmap w]= slover('getcmap', spm_input(prompt,'+1','s', defmapn));\n if isempty(cmap), disp(w);end\nend\nreturn\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "delete.m", "ext": ".m", "path": "spm5-master/@xmltree/delete.m", "size": 1062, "source_encoding": "utf_8", "md5": "3d4e3ea2ee3b6465070509309e6064c2", "text": "function tree = delete(tree,uid)\n% XMLTREE/DELETE Delete (delete a subtree given its UID)\n% \n% tree - XMLTree object\n% uid - array of UID's of subtrees to be deleted\n%_______________________________________________________________________\n%\n% Delete a subtree given its UID\n% The tree parameter must be in input AND in output\n%_______________________________________________________________________\n% @(#)delete.m Guillaume Flandin 02/04/08\n\nerror(nargchk(2,2,nargin));\n\nuid = uid(:);\nfor i=1:length(uid)\n\tif uid(i)==1\n\t\twarning('[XMLTree] Cannot delete root element.');\n\telse\n\t\tp = tree.tree{uid(i)}.parent;\n\t\ttree = sub_delete(tree,uid(i));\n\t\ttree.tree{p}.contents(find(tree.tree{p}.contents==uid(i))) = [];\n\tend\nend\n\n%=======================================================================\nfunction tree = sub_delete(tree,uid)\n\tif isfield(tree.tree{uid},'contents')\n\t\tfor i=1:length(tree.tree{uid}.contents)\n\t\t\ttree = sub_delete(tree,tree.tree{uid}.contents(i));\n\t\tend\n\tend\n\ttree.tree{uid} = struct('type','deleted');\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "save.m", "ext": ".m", "path": "spm5-master/@xmltree/save.m", "size": 4111, "source_encoding": "utf_8", "md5": "78be08cb954d03761753a9fe98f56f2c", "text": "function varargout = save(tree, filename)\n% XMLTREE/SAVE Save an XML tree in an XML file\n% FORMAT varargout = save(tree,filename)\n%\n% tree - XMLTree\n% filename - XML output filename\n% varargout - XML string\n%_______________________________________________________________________\n%\n% Convert an XML tree into a well-formed XML string and write it into\n% a file or return it as a string if no filename is provided.\n%_______________________________________________________________________\n% @(#)save.m Guillaume Flandin 01/07/11\n\nerror(nargchk(1,2,nargin));\n\nprolog = '\\n';\n\n%- Return the XML tree as a string\nif nargin == 1\n\tvarargout{1} = [sprintf(prolog) ...\n\t\tprint_subtree(tree,'',root(tree))];\n%- Output specified\nelse\n\t%- Filename provided\n\tif isstr(filename)\n\t\t[fid, msg] = fopen(filename,'w');\n\t\tif fid==-1, error(msg); end\n\t\tif isempty(tree.filename), tree.filename = filename; end\n\t%- File identifier provided\n\telseif isnumeric(filename) & prod(size(filename)) == 1\n\t\tfid = filename;\n\t\tprolog = ''; %- With this option, do not write any prolog\n\telse\n\t\terror('[XMLTree] Invalid argument.');\n\tend\n\tfprintf(fid,prolog);\n\tsave_subtree(tree,fid,root(tree));\n\tif isstr(filename), fclose(fid); end\n\tif nargout == 1\n\t\tvarargout{1} = print_subtree(tree,'',root(tree));\n\tend\nend\n\n%=======================================================================\nfunction xmlstr = print_subtree(tree,xmlstr,uid,order)\n\tif nargin < 4, order = 0; end\n\txmlstr = [xmlstr blanks(3*order)];\n\tswitch tree.tree{uid}.type\n\t\tcase 'element'\n\t\t\txmlstr = sprintf('%s<%s',xmlstr,tree.tree{uid}.name);\n\t\t\tfor i=1:length(tree.tree{uid}.attributes)\n\t\t\t\txmlstr = sprintf('%s %s=\"%s\"', xmlstr, ...\n\t\t\t\t\ttree.tree{uid}.attributes{i}.key,...\n\t\t\t\t\ttree.tree{uid}.attributes{i}.val);\n\t\t\tend\n\t\t\tif isempty(tree.tree{uid}.contents)\n\t\t\t\txmlstr = sprintf('%s/>\\n',xmlstr);\n\t\t\telse\n\t\t\t\txmlstr = sprintf('%s>\\n',xmlstr);\n\t\t\t\tfor i=1:length(tree.tree{uid}.contents)\n\t\t\t\t\txmlstr = print_subtree(tree,xmlstr, ...\n\t\t\t\t\t\ttree.tree{uid}.contents(i),order+1);\n \t\t\t\tend\n\t\t\t\txmlstr = [xmlstr blanks(3*order)];\n\t\t\t\txmlstr = sprintf('%s\\n',xmlstr,...\n\t\t\t\t\ttree.tree{uid}.name);\n\t\t\tend\n\t\tcase 'chardata'\n\t\t\txmlstr = sprintf('%s%s\\n',xmlstr, ...\n\t\t\t\tentity(tree.tree{uid}.value));\n\t\tcase 'cdata'\n\t\t\txmlstr = sprintf('%s\\n',xmlstr, ...\n\t\t\t\ttree.tree{uid}.value);\n\t\tcase 'pi'\n\t\t\txmlstr = sprintf('%s\\n',xmlstr, ...\n\t\t\t\ttree.tree{uid}.target, tree.tree{uid}.value);\n\t\tcase 'comment'\n\t\t\txmlstr = sprintf('%s\\n',xmlstr,...\n\t\t\t\ttree.tree{uid}.value);\n\t\totherwise\n\t\t\twarning(sprintf('Type %s unknown: not saved', ...\n\t\t\t\ttree.tree{uid}.type));\n\tend\n\n%=======================================================================\nfunction save_subtree(tree,fid,uid,order)\n\tif nargin < 4, order = 0; end\n\tfprintf(fid,blanks(3*order));\n\tswitch tree.tree{uid}.type\n\t\tcase 'element'\n\t\t\tfprintf(fid,'<%s',tree.tree{uid}.name);\n\t\t\tfor i=1:length(tree.tree{uid}.attributes)\n\t\t\t\tfprintf(fid,' %s=\"%s\"',...\n\t\t\t\ttree.tree{uid}.attributes{i}.key, ...\n\t\t\t\ttree.tree{uid}.attributes{i}.val);\n\t\t\tend\n\t\t\tif isempty(tree.tree{uid}.contents)\n\t\t\t\tfprintf(fid,'/>\\n');\n\t\t\telse\n\t\t\t\tfprintf(fid,'>\\n');\n\t\t\t\tfor i=1:length(tree.tree{uid}.contents)\n\t\t\t\t\tsave_subtree(tree,fid,...\n\t\t\t\t\t\ttree.tree{uid}.contents(i),order+1)\n \t\t\t\tend\n\t\t\t\tfprintf(fid,blanks(3*order));\n\t\t\t\tfprintf(fid,'\\n',tree.tree{uid}.name);\n\t\t\tend\n\t\tcase 'chardata'\n\t\t\tfprintf(fid,'%s\\n',entity(tree.tree{uid}.value));\n\t\tcase 'cdata'\n\t\t\t\tfprintf(fid,'\\n',tree.tree{uid}.value);\n\t\tcase 'pi'\n\t\t\tfprintf(fid,'\\n',tree.tree{uid}.target, ...\n\t\t\t\ttree.tree{uid}.value);\n\t\tcase 'comment'\n\t\t\tfprintf(fid,'\\n',tree.tree{uid}.value);\n\t\totherwise\n\t\t\twarning(sprintf('[XMLTree] Type %s unknown: not saved', ...\n\t\t\t\ttree.tree{uid}.type));\n\tend\n\n\n%=======================================================================\nfunction str = entity(str)\n\tstr = strrep(str,'&','&');\n\tstr = strrep(str,'<','<');\n\tstr = strrep(str,'>','>');\n\tstr = strrep(str,'\"','"');\n\tstr = strrep(str,'''',''');\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "branch.m", "ext": ".m", "path": "spm5-master/@xmltree/branch.m", "size": 1465, "source_encoding": "utf_8", "md5": "f9fcdbd88e225cdfc499733a2854dc93", "text": "function subtree = branch(tree,uid)\n% XMLTREE/BRANCH Branch Method\n% FORMAT uid = parent(tree,uid)\n% \n% tree - XMLTree object\n% uid - UID of the root element of the subtree\n% subtree - XMLTree object (a subtree from tree)\n%_______________________________________________________________________\n%\n% Return a subtree from a tree.\n%_______________________________________________________________________\n% @(#)branch.m Guillaume Flandin 02/04/17\n\nerror(nargchk(2,2,nargin));\n\nif uid > length(tree) | ...\n prod(size(uid))~=1 | ...\n ~strcmp(tree.tree{uid}.type,'element')\n\terror('[XMLTree] Invalid UID.');\nend\n\nsubtree = xmltree;\nsubtree = set(subtree,root(subtree),'name',tree.tree{uid}.name);\n\nchild = children(tree,uid);\n\nfor i=1:length(child)\n\tl = length(subtree);\n\tsubtree = sub_branch(tree,subtree,child(i),root(subtree));\n\tsubtree.tree{root(subtree)}.contents = [subtree.tree{root(subtree)}.contents l+1];\nend\n\n%=======================================================================\nfunction tree = sub_branch(t,tree,uid,p)\n\n\tl = length(tree);\n\ttree.tree{l+1} = t.tree{uid};\n\ttree.tree{l+1}.uid = l + 1;\n\ttree.tree{l+1}.parent = p;\n\ttree.tree{l+1}.contents = [];\n\tif isfield(t.tree{uid},'contents')\n\t\tcontents = get(t,uid,'contents');\n\t\tm = length(tree);\n\t\tfor i=1:length(contents)\n\t\t\ttree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1];\n\t\t\ttree = sub_branch(t,tree,contents(i),l+1);\n\t\t\tm = length(tree);\n\t\tend\n\tend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "flush.m", "ext": ".m", "path": "spm5-master/@xmltree/flush.m", "size": 1271, "source_encoding": "utf_8", "md5": "96e2fc9e3b1f4af1a63337f8aaf4e40f", "text": "function tree = flush(tree,uid)\n% XMLTREE/FLUSH Flush (Clear a subtree given its UID)\n% \n% tree - XMLTree object\n% uid - array of UID's of subtrees to be cleared\n% Default is root\n%_______________________________________________________________________\n%\n% Clear a subtree given its UID (remove all the leaves of the tree)\n% The tree parameter must be in input AND in output\n%_______________________________________________________________________\n% @(#)flush.m Guillaume Flandin 02/04/10\n\nerror(nargchk(1,2,nargin));\n\nif nargin == 1,\n\tuid = root(tree);\nend\n\nuid = uid(:);\nfor i=1:length(uid)\n\t tree = sub_flush(tree,uid(i));\nend\n\n%=======================================================================\nfunction tree = sub_flush(tree,uid)\n\tif isfield(tree.tree{uid},'contents')\n\t\t% contents is parsed in reverse order because each child is\n\t\t% deleted and the contents vector is then eventually reduced\n\t\tfor i=length(tree.tree{uid}.contents):-1:1\n\t\t\ttree = sub_flush(tree,tree.tree{uid}.contents(i));\n\t\tend\n\tend\n\tif strcmp(tree.tree{uid}.type,'chardata') |...\n\t\tstrcmp(tree.tree{uid}.type,'pi') |...\n\t\tstrcmp(tree.tree{uid}.type,'cdata') |...\n\t\tstrcmp(tree.tree{uid}.type,'comment')\n\t\ttree = delete(tree,uid);\n\tend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "copy.m", "ext": ".m", "path": "spm5-master/@xmltree/copy.m", "size": 1497, "source_encoding": "utf_8", "md5": "5afe1fb7338fdafff4202e08838794e1", "text": "function tree = copy(tree,subuid,uid)\n% XMLTREE/COPY Copy Method (copy a subtree in another branch)\n% FORMAT tree = copy(tree,subuid,uid)\n% \n% tree - XMLTree object\n% subuid - UID of the subtree to copy\n% uid - UID of the element where the subtree must be duplicated\n%_______________________________________________________________________\n%\n% Copy a subtree to another branch\n% The tree parameter must be in input AND in output\n%_______________________________________________________________________\n% @(#)copy.m Guillaume Flandin 02/04/08\n\nerror(nargchk(2,3,nargin));\nif nargin == 2\n\tuid = parent(tree,subuid);\nend\n\nl = length(tree);\ntree = sub_copy(tree,subuid,uid);\ntree.tree{uid}.contents = [tree.tree{uid}.contents l+1];\n\n% pour que la copie soit a cote de l'original et pas a la fin ?\n% contents = get(tree,parent,'contents');\n% i = find(contents==uid);\n% tree = set(tree,parent,'contents',[contents(1:i) l+1 contents(i+1:end)]);\n\n%=======================================================================\nfunction tree = sub_copy(tree,uid,p)\n\n\tl = length(tree);\n\ttree.tree{l+1} = tree.tree{uid};\n\ttree.tree{l+1}.uid = l+1;\n\ttree.tree{l+1}.parent = p;\n\ttree.tree{l+1}.contents = [];\n\tif isfield(tree.tree{uid},'contents')\n\t\tcontents = get(tree,uid,'contents');\n\t\tm = length(tree);\n\t\tfor i=1:length(contents)\n\t\t\ttree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1];\n\t\t\ttree = sub_copy(tree,contents(i),l+1);\n\t\t\tm = length(tree);\n\t\tend\n\tend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "convert.m", "ext": ".m", "path": "spm5-master/@xmltree/convert.m", "size": 3929, "source_encoding": "utf_8", "md5": "6247f0512cca7b09eccc0414b0e4d93d", "text": "function s = convert(tree,uid)\n% XMLTREE/CONVERT Converter an XML tree in a Matlab structure\n% \n% tree - XMLTree object\n% uid - uid of the root of the subtree, if provided.\n% Default is root\n% s - converted structure\n%_______________________________________________________________________\n%\n% Convert an xmltree into a Matlab structure, when possible.\n% When several identical tags are present, a cell array is used.\n% The root tag is not saved in the structure.\n% If provided, only the structure corresponding to the subtree defined\n% by the uid UID is returned.\n%_______________________________________________________________________\n% @(#)convert.m Guillaume Flandin 02/04/11\n\n% Exemple:\n% tree: field1field2field3\n% toto = convert(tree);\n% <=> toto = struct('titi',{{'field1', 'field3'}},'tutu','field2')\n\nerror(nargchk(1,2,nargin));\n\n% Get the root uid of the output structure\nif nargin == 1\n\t% Get the root uid of the XML tree\n\troot_uid = root(tree);\nelse\n\t% Uid provided by user\n\troot_uid = uid;\nend\n\n% Initialize the output structure\n% struct([]) should be used but this only works with Matlab 6\n% So we create a field that we delete at the end\n%s = struct(get(tree,root_uid,'name'),''); % struct([])\ns = struct('deletedummy','');\n\n%s = sub_convert(tree,s,root_uid,{get(tree,root_uid,'name')});\ns = sub_convert(tree,s,root_uid,{});\n\ns = rmfield(s,'deletedummy');\n\n%=======================================================================\nfunction s = sub_convert(tree,s,uid,arg)\n\ttype = get(tree,uid,'type');\n\tswitch type\n\t\tcase 'element'\n\t\t\tchild = children(tree,uid);\n\t\t\tl = {};\n\t\t\tll = {};\n\t\t\tfor i=1:length(child)\n\t\t\t\tif isfield(tree,child(i),'name')\n\t\t\t\t\tll = { ll{:}, get(tree,child(i),'name') };\n\t\t\t\tend\n\t\t\tend\n\t\t\tfor i=1:length(child)\n\t\t\t\tif isfield(tree,child(i),'name')\n\t\t\t\t\tname = get(tree,child(i),'name');\n\t\t\t\t\tnboccur = sum(ismember(l,name));\n\t\t\t\t\tnboccur2 = sum(ismember(ll,name));\n\t\t\t\t\tl = { l{:}, name };\n\t\t\t\t\tif nboccur | (nboccur2>1)\n\t\t\t\t\t\targ2 = { arg{:}, name, {nboccur+1} };\n\t\t\t\t\telse\n\t\t\t\t\t\targ2 = { arg{:}, name};\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\targ2 = arg;\n\t\t\t\tend\n\t\t\t\ts = sub_convert(tree,s,child(i),arg2);\n\t\t\tend\n\t\t\tif isempty(child)\n\t\t\t\ts = sub_setfield(s,arg{:},'');\n\t\t\tend\n\t\tcase 'chardata'\n\t\t\ts = sub_setfield(s,arg{:},get(tree,uid,'value'));\n\t\tcase 'cdata'\n\t\t\ts = sub_setfield(s,arg{:},get(tree,uid,'value'));\n\t\tcase 'pi'\n\t\t\t% Processing instructions are evaluated if possible\n\t\t\tapp = get(tree,uid,'target');\n\t\t\tswitch app\n\t\t\t\tcase {'matlab',''}\n\t\t\t\t\ts = sub_setfield(s,arg{:},eval(get(tree,uid,'value')));\n\t\t\t\tcase 'unix'\n\t\t\t\t\ts = sub_setfield(s,arg{:},unix(get(tree,uid,'value')));\n\t\t\t\tcase 'dos'\n\t\t\t\t\ts = sub_setfield(s,arg{:},dos(get(tree,uid,'value')));\n\t\t\t\tcase 'system'\n\t\t\t\t\ts = sub_setfield(s,arg{:},system(get(tree,uid,'value')));\n\t\t\t\totherwise\n\t\t\t\t\ttry,\n\t\t\t\t\t\ts = sub_setfield(s,arg{:},feval(app,get(tree,uid,'value')));\n\t\t\t\t\tcatch,\n\t\t\t\t\t\twarning('[Xmltree/convert] Unknown target application');\n\t\t\t\t\tend\n\t\t\tend\n\t\tcase 'comment'\n\t\t\t% Comments are forgotten\n\t\totherwise\n\t\t\twarning(sprintf('Type %s unknown : not saved',get(tree,uid,'type')));\n\tend\n\t\n%=======================================================================\nfunction s = sub_setfield(s,varargin)\n% Same as setfield but using '{}' rather than '()'\n%if (isempty(varargin) | length(varargin) < 2)\n% error('Not enough input arguments.');\n%end\n\nsubs = varargin(1:end-1);\nfor i = 1:length(varargin)-1\n if (isa(varargin{i}, 'cell'))\n types{i} = '{}';\n elseif isstr(varargin{i})\n types{i} = '.';\n subs{i} = varargin{i}; %strrep(varargin{i},' ',''); % deblank field name\n else\n error('Inputs must be either cell arrays or strings.');\n end\nend\n\n% Perform assignment\ntry\n s = builtin('subsasgn', s, struct('type',types,'subs',subs), varargin{end});\ncatch\n error(lasterr)\nend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "find.m", "ext": ".m", "path": "spm5-master/@xmltree/find.m", "size": 5146, "source_encoding": "utf_8", "md5": "1e2038bcaac9fe80c3213b6c35c7ee5d", "text": "function list = find(varargin)\n% XMLTREE/FIND Find elements in a tree with specified characteristics\n% FORMAT list = find(varargin)\n%\n% tree - XMLTree object\n% xpath - string path with specific grammar (XPath)\n% uid - lists of root uid's\n% parameter/value - pair of pattern\n% list - list of uid's of matched elements\n%\n% list = find(tree,xpath)\n% list = find(tree,parameter,value[,parameter,value])\n% list = find(tree,uid,parameter,value[,parameter,value])\n%\n% Grammar for addressing parts of an XML document: \n% XML Path Language XPath (http://www.w3.org/TR/xpath)\n% Example: /element1//element2[1]/element3[5]/element4\n%_______________________________________________________________________\n%\n% Find elements in an XML tree with specified characteristics or given\n% a path (using a subset of XPath language).\n%_______________________________________________________________________\n% @(#)find.m Guillaume Flandin 01/10/29\n\n% TODO:\n% - clean up subroutines\n% - find should only be documented using XPath (other use is internal)\n% - handle '*', 'last()' in [] and '@'\n% - if a key is invalid, should rather return [] than error ?\n\nif nargin==0\n\terror('[XMLTree] A tree must be provided');\nelseif nargin==1\n\tlist = 1:length(tree.tree);\n\treturn\nelseif mod(nargin,2)\n\tlist = sub_find_subtree1(varargin{1}.tree,root(tree),varargin{2:end});\nelseif isa(varargin{2},'double') & ...\n\t ndims(varargin{2}) == 2 & ...\n\t min(size(varargin{2})) == 1\n\tlist = unique(sub_find_subtree1(varargin{1}.tree,varargin{2:end}));\nelseif nargin==2 & ischar(varargin{2})\n\tlist = sub_pathfinder(varargin{:});\nelse\n error('[XMLTree] Arguments must be parameter/value pairs.');\nend\n\n%=======================================================================\nfunction list = sub_find_subtree1(varargin)\n\tlist = [];\n\tfor i=1:length(varargin{2})\n\t\tres = sub_find_subtree2(varargin{1},...\n\t\t\t\tvarargin{2}(i),varargin{3:end});\n\t\tlist = [list res];\n\tend\n\n%=======================================================================\nfunction list = sub_find_subtree2(varargin)\n\tuid = varargin{2};\n\tlist = [];\n\tif sub_comp_element(varargin{1}{uid},varargin{3:end})\n\t\tlist = [list varargin{1}{uid}.uid];\n\tend\n\tif isfield(varargin{1}{uid},'contents')\n\t\tlist = [list sub_find_subtree1(varargin{1},...\n\t\t varargin{1}{uid}.contents,varargin{3:end})];\n\tend\n\n%=======================================================================\nfunction match = sub_comp_element(varargin)\nmatch = 0;\ntry,\n\t% v = getfield(varargin{1}, varargin{2}); % slow...\n\tfor i=1:floor(nargin/2)\n\t\tv = subsref(varargin{1}, struct('type','.','subs',varargin{i+1})); \n\t\tif strcmp(v,varargin{i+2})\n\t\t\tmatch = 1;\n\t\tend\n\tend\ncatch,\nend\n\n% More powerful but much slower\n%match = 0;\n%for i=1:length(floor(nargin/2)) % bug: remove length !!!\n% if isfield(varargin{1},varargin{i+1})\n%\t if ischar(getfield(varargin{1},varargin{i+1})) & ischar(varargin{i+2})\n%\t if strcmp(getfield(varargin{1},varargin{i+1}),char(varargin{i+2}))\n%\t\t\tmatch = 1;\n%\t\t end\n%\t elseif isa(getfield(varargin{1},varargin{i+1}),'double') & ...\n%\t\t\tisa(varargin{i+2},'double')\n%\t\t if getfield(varargin{1},varargin{i+1}) == varargin{i+2}\n%\t\t\tmatch = 1;\n%\t\tend\n%\t else \n%\t\twarning('Cannot compare different objects');\n%\t end\n% end\n%end\n\n%=======================================================================\nfunction list = sub_pathfinder(tree,pth)\n\t%- Search for the delimiter '/' in the path\n\ti = findstr(pth,'/');\n\t%- Begin search by root\n\tlist = root(tree);\n\t%- Walk through the tree\n\tj = 1;\n\twhile j <= length(i)\n\t\t%- Look for recursion '//'\n\t\tif j length(list)+1\n\t\t\t\terror('[XMLTree] Bad key in the path.');\n\t\t\telseif val == length(list)+1\n\t\t\t\tlist = [];\n\t\t\t\treturn;\n\t\t\tend\n\t\t\tlist = list(val);\n\t\tend\n\t\tif isempty(list), return; end\n\t\tj = j + 1;\n\tend\n\t\n%=======================================================================\nfunction list = sub_findchild(tree,listt,elmt)\n\tlist = [];\n\tfor a=1:length(listt)\n\t\tfor b=1:length(tree.tree{listt(a)}.contents)\n\t\t\tif sub_comp_element(tree.tree{tree.tree{listt(a)}.contents(b)},'name',elmt)\n\t\t\t\tlist = [list tree.tree{tree.tree{listt(a)}.contents(b)}.uid];\n\t\t\tend\n\t\tend\n\tend\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "view.m", "ext": ".m", "path": "spm5-master/@xmltree/view.m", "size": 5879, "source_encoding": "utf_8", "md5": "b26972066a91937d42a5bb86239b92e4", "text": "function view(tree)\n% XMLTREE/VIEW View Method\n% FORMAT view(tree)\n% \n% tree - XMLTree object\n%_______________________________________________________________________\n%\n% Display an XML tree in a graphical interface\n%_______________________________________________________________________\n% @(#)view.m Guillaume Flandin 02/04/08\n\nerror(nargchk(1,1,nargin));\n\n%-Build the Graphical User Interface\n%-----------------------------------------------------------------------\nfigH = findobj('Tag','mlBatchFigure'); %this tag doesn't exist so a new \n% window is created ....\nif isempty(figH)\n\th = xmltree_build_ui;\n\tfigH = h.fig;\nelse\n set(figH,'Visible','on');\n % recover all the handles\n % h = struct(...);\nend\ndrawnow;\n\n%-New title for the main window\n%-----------------------------------------------------------------------\nset(figH,'Name',['XML TreeViewer:' getfilename(tree)]);\n\n\n%-Initialize batch listbox\n%-----------------------------------------------------------------------\ntree = set(tree,root(tree),'show',1);\nbuiltin('set',figH,'UserData',tree);\n\nview_ui('update',figH);\n\n%=======================================================================\nfunction handleStruct = xmltree_build_ui\n\n%- Create Figure\npixfactor = 72 / get(0,'screenpixelsperinch');\n%- Figure window size and position\noldRootUnits = get(0,'Units');\nset(0, 'Units', 'points');\nfigurePos = get(0,'DefaultFigurePosition');\nfigurePos(3:4) = [560 420];\nfigurePos = figurePos * pixfactor;\nrootScreenSize = get(0,'ScreenSize');\nif ((figurePos(1) < 1) ...\n\t | (figurePos(1)+figurePos(3) > rootScreenSize(3)))\n figurePos(1) = 30;\nend\nset(0, 'Units', oldRootUnits);\nif ((figurePos(2)+figurePos(4)+60 > rootScreenSize(4)) ...\n\t | (figurePos(2) < 1))\n figurePos(2) = rootScreenSize(4) - figurePos(4) - 60;\nend\n%- Create Figure Window\nhandleStruct.fig = figure(...\n\t'Name','XML TreeViewer', ...\n\t'Units', 'points', ...\n\t'NumberTitle','off', ...\n\t'Resize','on', ...\n\t'Color',[0.8 0.8 0.8],...\n\t'Position',figurePos, ...\n\t'MenuBar','none', ... \n\t'Tag', 'BatchFigure', ...\n\t'CloseRequestFcn','view_ui close');\n\n%- Build batch listbox\nbatchListPos = [20 55 160 345] * pixfactor;\nbatchString = ' ';\nhandleStruct.batchList = uicontrol( ...\n\t'Parent',handleStruct.fig, ...\n\t'Style', 'listbox', ...\n\t'HorizontalAlignment','left', ...\n\t'Units','points', ...\n\t'Visible','on',...\n\t'BackgroundColor', [1 1 1], ...\n\t'Max', 1, ...\n\t'Value', 1 , ...\n\t'Enable', 'on', ...\n\t'Position', batchListPos, ...\n\t'Callback', 'view_ui batchlist', ...\n\t'String', batchString, ...\n\t'Tag', 'BatchListbox');\n\n%- Build About listbox\naboutListPos = [200 220 340 180] * pixfactor;\naboutString = ' ';\nhandleStruct.aboutList = uicontrol( ...\n\t'Parent',handleStruct.fig, ...\n\t'Style', 'list', ...\n\t'HorizontalAlignment','left', ...\n\t'Units','points', ...\n\t'Visible','on',...\n\t'BackgroundColor', [0.8 0.8 0.8], ...\n\t'Min', 0, ...\n\t'Max', 2, ...\n\t'Value', [], ...\n\t'Enable', 'inactive', ...\n\t'Position', aboutListPos, ...\n\t'Callback', '', ...\n\t'String', aboutString, ...\n\t'Tag', 'AboutListbox');\n\n%- The Add button\naddBtnPos = [20 20 70 25] * pixfactor;\nhandleStruct.add = uicontrol( ...\n\t'Parent',handleStruct.fig, ...\n\t'Style', 'pushbutton', ...\n\t'Units', 'points', ...\n\t'Position', addBtnPos, ...\n\t'String', 'Add', ...\n 'Visible', 'on', ...\n 'Enable','on',...\n\t'Tag', 'Add', ...\n\t'Callback', 'view_ui add');\n\t%'TooltipString', 'Add batch', ...\n \n%- The modify button\nmodifyBtnPos = [95 20 70 25] * pixfactor;\nhandleStruct.modify = uicontrol( ...\n\t'Parent',handleStruct.fig, ...\n\t'Style', 'pushbutton', ...\n\t'Units', 'points', ...\n\t'Position', modifyBtnPos, ...\n\t'String', 'Modify', ...\n 'Visible', 'on', ...\n 'Enable','on',...\n\t'Tag', 'Modify', ...\n\t'Callback', 'view_ui modify');\n\t%'TooltipString', 'Modify batch', ...\n\n%- The Copy button\ncopyBtnPos = [170 20 70 25] * pixfactor;\nhandleStruct.copy = uicontrol( ...\n\t'Parent',handleStruct.fig, ...\n\t'Style', 'pushbutton', ...\n\t'Units', 'points', ...\n\t'Position', copyBtnPos, ...\n\t'String', 'Copy', ...\n 'Visible', 'on', ...\n 'Enable','on',...\n\t'Tag', 'Copy', ...\n\t'Callback', 'view_ui copy');\n\t%'TooltipString', 'Copy batch', ...\n\n%- The delete button\ndeleteBtnPos = [245 20 70 25] * pixfactor;\nhandleStruct.delete = uicontrol( ...\n\t'Parent',handleStruct.fig, ...\n\t'Style', 'pushbutton', ...\n\t'Units', 'points', ...\n\t'Position', deleteBtnPos, ...\n\t'String', 'Delete', ...\n 'Visible', 'on', ...\n 'Enable','on',...\n\t'Tag', 'Delete', ...\n\t'Callback', 'view_ui delete');\n\t%'TooltipString', 'Delete batch', ...\n\n%- The save button\nsaveBtnPos = [320 20 70 25] * pixfactor;\nhandleStruct.save = uicontrol( ...\n\t'Parent',handleStruct.fig, ...\n\t'Style', 'pushbutton', ...\n\t'Units', 'points', ...\n\t'Position', saveBtnPos, ...\n\t'String', 'Save', ...\n 'Visible', 'on', ...\n 'UserData',0,...\n\t'Tag', 'Save', ...\n\t'Callback', 'view_ui save');\n\t%'TooltipString', 'Save batch', ...\n\n%- The run button \nrunBtnPos = [395 20 70 25] * pixfactor;\nhandleStruct.run = uicontrol( ...\n\t'Parent',handleStruct.fig, ...\n\t'Style', 'pushbutton', ...\n\t'Units', 'points', ...\n\t'Position', runBtnPos, ...\n\t'String', 'Run', ...\n\t'Visible', 'on', ...\n\t'Enable', 'on', ...\n\t'Tag', 'Run', ...\n\t'Callback', 'view_ui run');\n\t%'TooltipString', 'Run batch', ...\n\n%- The close button\ncloseBtnPos = [470 20 70 25] * pixfactor;\nhandleStruct.close = uicontrol( ...\n\t'Parent',handleStruct.fig, ...\n\t'Style', 'pushbutton', ...\n\t'Units', 'points', ...\n\t'Position', closeBtnPos, ...\n\t'String', 'Close', ...\n\t'Visible', 'on', ...\n\t'Tag', 'Close', ...\n\t'Callback', 'view_ui close');\n\t%'TooltipString', 'Close window', ...\n\nhandleArray = [handleStruct.fig handleStruct.batchList handleStruct.aboutList handleStruct.add handleStruct.modify handleStruct.copy handleStruct.delete handleStruct.save handleStruct.run handleStruct.close];\n\nset(handleArray,'Units', 'normalized');\n"} +{"plateform": "github", "repo_name": "spm/spm5-master", "name": "xml_parser.m", "ext": ".m", "path": "spm5-master/@xmltree/private/xml_parser.m", "size": 14392, "source_encoding": "utf_8", "md5": "0380cbf01ef44fad90326b3fd342a11d", "text": "function tree = xml_parser(xmlstr)\n% XML (eXtensible Markup Language) Processor\n% FORMAT tree = xml_parser(xmlstr)\n%\n% xmlstr - XML string to parse\n% tree - tree structure corresponding to the XML file\n%_______________________________________________________________________\n%\n% xml_parser.m is an XML 1.0 (http://www.w3.org/TR/REC-xml) parser\n% written in Matlab. It aims to be fully conforming. It is currently not\n% a validating XML processor.\n%\n% A description of the tree structure provided in output is detailed in \n% the header of this m-file.\n%_______________________________________________________________________\n% @(#)xml_parser.m Guillaume Flandin 2002/04/04\n\n% XML Processor for MATLAB (The Mathworks, Inc.).\n% Copyright (C) 2002-2003 Guillaume Flandin \n%\n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.\n%-----------------------------------------------------------------------\n\n% Please feel free to email the author any comment/suggestion/bug report\n% to improve this XML processor in Matlab.\n% Email: \n% Check also the latest developments on the following webpage:\n% http://www.artefact.tk/software/matlab/xml/\n%-----------------------------------------------------------------------\n\n% The implementation of this XML parser is much inspired from a \n% Javascript parser available at http://www.jeremie.com/\n\n% A mex-file xml_findstr.c is also required, to encompass some\n% limitations of the built-in findstr Matlab function.\n% Compile it on your architecture using 'mex -O xml_findstr.c' command\n% if the compiled version for your system is not provided.\n% If this function behaves badly (crash or wrong results), comment the\n% line '#define __HACK_MXCHAR__' in xml_findstr.c and compile it again.\n%-----------------------------------------------------------------------\n\n% Structure of the output tree:\n% There are 5 types of nodes in an XML file: element, chardata, cdata,\n% pi and comment.\n% Each of them contains an UID (Unique Identifier): an integer between\n% 1 and the number of nodes of the XML file.\n%\n% element (a tag [contents] \n% |_ type: 'element'\n% |_ name: string\n% |_ attributes: cell array of struct 'key' and 'value' or []\n% |_ contents: double array of uid's or [] if empty\n% |_ parent: uid of the parent ([] if root)\n% |_ uid: double\n%\n% chardata (a character array)\n% |_ type: 'chardata'\n% |_ value: string\n% |_ parent: uid of the parent\n% |_ uid: double\n%\n% cdata (a litteral string )\n% |_ type: 'cdata'\n% |_ value: string\n% |_ parent: uid of the parent\n% |_ uid: double\n%\n% pi (a processing instruction )\n% |_ type: 'pi' \n% |_ target: string (may be empty)\n% |_ value: string\n% |_ parent: uid of the parent\n% |_ uid: double\n%\n% comment (a comment )\n% |_ type: 'comment'\n% |_ value: string\n% |_ parent: uid of the parent\n% |_ uid: double\n%\n%-----------------------------------------------------------------------\n\n% TODO/BUG/FEATURES:\n% - [compile] only a warning if TagStart is empty ?\n% - [attribution] should look for \" and ' rather than only \"\n% - [main] with normalize as a preprocessing, CDATA are modified\n% - [prolog] look for a DOCTYPE in the whole string even if it occurs\n% only in a far CDATA tag, bug even if the doctype is inside a comment\n% - [tag_element] erode should replace normalize here\n% - remove globals? uppercase globals rather persistent (clear mfile)?\n% - xml_findstr is indeed xml_strfind according to Mathworks vocabulary\n% - problem with entities: do we need to convert them here? (é)\n%-----------------------------------------------------------------------\n\n%- XML string to parse and number of tags read\nglobal xmlstring Xparse_count xtree;\n\n%- Check input arguments\nerror(nargchk(1,1,nargin));\nif isempty(xmlstr)\n\terror('[XML] Not enough parameters.')\nelseif ~isstr(xmlstr) | sum(size(xmlstr)>1)>1\n\terror('[XML] Input must be a string.')\nend\n\n%- Initialize number of tags (<=> uid)\nXparse_count = 0;\n\n%- Remove prolog and white space characters from the XML string\nxmlstring = normalize(prolog(xmlstr));\n\n%- Initialize the XML tree\nxtree = {};\ntree = fragment;\ntree.str = 1;\ntree.parent = 0;\n\n%- Parse the XML string\ntree = compile(tree);\n\n%- Return the XML tree\ntree = xtree;\n\n%- Remove global variables from the workspace\nclear global xmlstring Xparse_count xtree;\n\n%=======================================================================\n% SUBFUNCTIONS\n\n%-----------------------------------------------------------------------\nfunction frag = compile(frag)\n\tglobal xmlstring xtree Xparse_count;\n\t\n\twhile 1,\n\t\tif length(xmlstring)<=frag.str | ...\n\t\t (frag.str == length(xmlstring)-1 & strcmp(xmlstring(frag.str:end),' '))\n\t\t\treturn\n\t\tend\n\t\tTagStart = xml_findstr(xmlstring,'<',frag.str,1);\n\t\tif isempty(TagStart)\n\t\t\t%- Character data\n\t\t\terror(sprintf(['[XML] Unknown data at the end of the XML file.\\n' ...\n\t\t\t' Please send me your XML file at flandin@sophia.inria.fr']));\n\t\t\txtree{Xparse_count} = chardata;\n\t\t\txtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:end)));\n\t\t\txtree{Xparse_count}.parent = frag.parent;\n\t\t\txtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];\n\t\t\tfrag.str = '';\n\t\telseif TagStart > frag.str\n\t\t\tif strcmp(xmlstring(frag.str:TagStart-1),' ')\n\t\t\t\t%- A single white space before a tag (ignore)\n\t\t\t\tfrag.str = TagStart;\n\t\t\telse\n\t\t\t\t%- Character data\n\t\t\t\txtree{Xparse_count} = chardata;\n\t\t\t\txtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:TagStart-1)));\n\t\t\t\txtree{Xparse_count}.parent = frag.parent;\n\t\t\t\txtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];\n\t\t\t\tfrag.str = TagStart;\n\t\t\tend\n\t\telse \n\t\t\tif strcmp(xmlstring(frag.str+1),'?')\n\t\t\t\t%- Processing instruction\n\t\t\t\tfrag = tag_pi(frag);\n\t\t\telse\n\t\t\t\tif length(xmlstring)-frag.str>4 & strcmp(xmlstring(frag.str+1:frag.str+3),'!--')\n\t\t\t\t\t%- Comment\n\t\t\t\t\tfrag = tag_comment(frag);\n\t\t\t\telse\n\t\t\t\t\tif length(xmlstring)-frag.str>9 & strcmp(xmlstring(frag.str+1:frag.str+8),'![CDATA[')\n\t\t\t\t\t\t%- Litteral data\n\t\t\t\t\t\tfrag = tag_cdata(frag);\n\t\t\t\t\telse\n\t\t\t\t\t\t%- A tag element (empty (<.../>) or not)\n\t\t\t\t\t\tif ~isempty(frag.end)\n\t\t\t\t\t\t\tendmk = ['/' frag.end '>'];\n\t\t\t\t\t\telse \n\t\t\t\t\t\t\tendmk = '/>';\n\t\t\t\t\t\tend\n\t\t\t\t\t\tif strcmp(xmlstring(frag.str+1:frag.str+length(frag.end)+2),endmk) | ...\n\t\t\t\t\t\t\tstrcmp(strip(xmlstring(frag.str+1:frag.str+length(frag.end)+2)),endmk)\n\t\t\t\t\t\t\tfrag.str = frag.str + length(frag.end)+3;\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tfrag = tag_element(frag);\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n\n%-----------------------------------------------------------------------\nfunction frag = tag_element(frag)\n\tglobal xmlstring xtree Xparse_count;\n\tclose = xml_findstr(xmlstring,'>',frag.str,1);\n\tif isempty(close)\n\t\terror('[XML] Tag < opened but not closed.');\n\telse\n\t\tempty = strcmp(xmlstring(close-1:close),'/>');\n\t\tif empty\n\t\t\tclose = close - 1;\n\t\tend\n\t\tstarttag = normalize(xmlstring(frag.str+1:close-1));\n\t\tnextspace = xml_findstr(starttag,' ',1,1);\n\t\tattribs = '';\n\t\tif isempty(nextspace)\n\t\t\tname = starttag;\n\t\telse\n\t\t\tname = starttag(1:nextspace-1);\n\t\t\tattribs = starttag(nextspace+1:end);\n\t\tend\n\t\txtree{Xparse_count} = element;\n\t\txtree{Xparse_count}.name = strip(name);\n\t\tif frag.parent\n\t\t\txtree{Xparse_count}.parent = frag.parent;\n\t\t\txtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];\n\t\tend\n\t\tif length(attribs) > 0\n\t\t\txtree{Xparse_count}.attributes = attribution(attribs);\n\t\tend\n\t\tif ~empty\n\t\t\tcontents = fragment;\n\t\t\tcontents.str = close+1;\n\t\t\tcontents.end = name;\n\t\t\tcontents.parent = Xparse_count;\n\t\t\tcontents = compile(contents);\n\t\t\tfrag.str = contents.str;\n\t\telse\n\t\t\tfrag.str = close+2;\n\t\tend\n\tend\n\n%-----------------------------------------------------------------------\nfunction frag = tag_pi(frag)\n\tglobal xmlstring xtree Xparse_count;\n\tclose = xml_findstr(xmlstring,'?>',frag.str,1);\n\tif isempty(close)\n\t\twarning('[XML] Tag close | nextspace == frag.str+2\n\t\t\txtree{Xparse_count}.value = erode(xmlstring(frag.str+2:close-1));\n\t\telse\n\t\t\txtree{Xparse_count}.value = erode(xmlstring(nextspace+1:close-1));\n\t\t\txtree{Xparse_count}.target = erode(xmlstring(frag.str+2:nextspace));\n\t\tend\n\t\tif frag.parent\n\t\t\txtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];\n\t\t\txtree{Xparse_count}.parent = frag.parent;\n\t\tend\n\t\tfrag.str = close+2;\n\tend\n\n%-----------------------------------------------------------------------\nfunction frag = tag_comment(frag)\n\tglobal xmlstring xtree Xparse_count;\n\tclose = xml_findstr(xmlstring,'-->',frag.str,1);\n\tif isempty(close)\n\t\twarning('[XML] Tag ComputeSRSSD, BicubicReplacor-->SmoothnessPreservingFunction)\n%find a bug of missing a line idxstart = idxend+1;\nfunction PP9_TrainEdgePriors()\n Setting(1).Gau_sigma = 1.2;\n Setting(1).Zooming = 3;\n% Setting(2).Gau_sigma = 1.6;\n% Setting(2).Zooming = 4;\n Para.SaveFolder = 'EdgePriors';\n Para.TrainingImageFolder = fullfile('Examples','Upfrontal','Training'); %color images\n \n if ~exist(Para.SaveFolder,'dir')\n mkdir(Para.SaveFolder);\n end \n for i=1:length(Setting)\n Para.Zooming = Setting(i).Zooming;\n Para.Gau_sigma = Setting(i).Gau_sigma;\n Para.RawDataFileName = fullfile(Para.SaveFolder,sprintf('RawData_Sc%d_Si%0.1f.mat',Para.Zooming,Para.Gau_sigma));\n Para.StatisticsFileName = fullfile(Para.SaveFolder,sprintf('Statistics_Sc%d_Si%0.1f.mat',Para.Zooming,Para.Gau_sigma));\n %Extract features\n %ExtractOneSetting(Para); \n \n %ComputeStatisticsOneSetting(Para);\n DrawOneSetting(Para);\n end\nend\n\n%Extract features\nfunction ExtractOneSetting(Para)\n Zooming = Para.Zooming;\n TrainingImageFolder = Para.TrainingImageFolder;\n %FileList = dir(fullfile(TrainingImageFolder,'*.jpg'));\n FileList = dir(fullfile(TrainingImageFolder,'*.png'));\n ListLength = length(FileList);\n preallocatenumber = 120000; \n\n for i=1:ListLength\n fprintf('collecting statistics %d out of totoal %d files\\n',i,ListLength);\n fn_read = FileList(i).name;\n fn_short = fn_read(1:end-4);\n img_rgb = im2double(imread(fullfile(Para.TrainingImageFolder ,fn_read)));\n img_y_high = rgb2gray(img_rgb);\n [h w] = size(img_y_high);\n img_y_low = F19a_GenerateLRImage_GaussianKernel(img_y_high,Zooming,Para.Gau_sigma);\n\n MagOriginal = F15_ComputeSRSSD(img_y_high);\n if nnz(isnan(MagOriginal)) > 0\n keyboard\n end\n\n imgReconstruct = F27_SmoothnessPreserving(img_y_low,Para.Zooming,Para.Gau_sigma);\n %insert code, remove the fake edges\n\n MagReconstruct = F15_ComputeSRSSD(imgReconstruct);\n %find edge\n %the function has not fully implemented yet\n% EdgeCenter = NonMaximaSuppresion(MagReconstruct);\n EdgeCenter = edge(imgReconstruct,'canny',[0 0.01],0.05); %here is the problem, how to label non-maxinum depression\n DistMap = inf(h,w);\n UsedPixel = false(h,w);\n CenterCoor = zeros(h,w,2);\n [X Y] = meshgrid(1:7,1:7);\n SX = X -4;\n SY = Y -4;\n DistPatch = sqrt(SX.^2 + SY.^2);\n [r_set c_set] = find(EdgeCenter);\n SetLength = length(r_set);\n %create distmap\n for j=1:SetLength\n r = r_set(j);\n r1 = r-3;\n r2 = r+3;\n c = c_set(j);\n c1 = c-3;\n c2 = c+3;\n if r1>=1 && r2<=h && c1>=1 && c2<=w\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(7), c*ones(7));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %collect statistics data\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n Count = 0;\n samples = zeros(4,preallocatenumber); %ReconMag, Dist, OriginalMag, CenterMag\n for j=1:SetLength\n r = r_set(j);\n c = c_set(j);\n Count = Count + 1;\n samples(1,Count) = MagReconstruct(r,c); %T_p\n samples(2,Count) = DistMap(r,c); %d\n samples(3,Count) = MagOriginal(r,c); %S_p\n Center_r = CenterCoor(r,c,1);\n Center_c = CenterCoor(r,c,2);\n samples(4,Count) = MagReconstruct(Center_r,Center_c); %T_r\n end\n %save indivisual extracted feature\n samples = samples(:,1:Count);\n savename = sprintf('%s_samples.mat',fn_short);\n samplesavefolder = fullfile(Para.SaveFolder, 'Samples', sprintf('s%d',Para.Zooming));\n if ~exist(samplesavefolder,'dir')\n mkdir(samplesavefolder);\n end\n save(fullfile(samplesavefolder,savename),'samples');\n end\nend\n\nfunction ComputeStatisticsOneSetting(Para)\n%All samples are saved in EdgePriors\\Samples\\s3 or EdgePriors\\Samples\\s4\n%Combine all smaple files to compute statistics\n \n %load all samples\n samplesavefolder = fullfile(Para.SaveFolder, 'Samples', sprintf('s%d',Para.Zooming));\n filelist = dir(fullfile(samplesavefolder,'*_samples.mat'));\n listlength = length(filelist);\n inlist = zeros(listlength,1); %instance number list\n %compute the total sample number\n for i=1:listlength\n fn = filelist(i).name;\n ffn = fullfile(samplesavefolder, fn);\n info = whos('-file',ffn); \n for j=1:length(info)\n if strcmp(info(j).name , 'samples');\n inlist(i) = info(j).size(2);\n end\n end\n end\n intotal = sum(inlist); %maximun case\n\n %merge all files \n b = [0 1 sqrt(2) 2 sqrt(5) 2*sqrt(2) 3 sqrt(10) sqrt(13) sqrt(18)]; \n %the last one has to be sqrt(18) rather than 3*sqrt(2), otherwise \"matchedidx = samples(2,:) == dist\" fails due to precision\n DistLength = length(b);\n\n BinNumber = 100;\n BinMax = 0.5;\n BinMin = 0;\n BinInterval = (BinMax-BinMin)/BinNumber;\n BinCenter = BinMin+BinInterval/2:BinInterval:BinMax-BinInterval/2;\n Statistics(1:DistLength,1) = struct('EstimatedMag',zeros(BinNumber),'StdRecord',zeros(BinNumber),'dist',0); \n \n for distidx = 1:DistLength\n dist = b(distidx);\n %only extract the required data\n CollectedData = zeros(4,intotal);\n idxstart = 1;\n for i=1:listlength\n fprintf('read file idx %d, total %d, dist %0.1f\\n',i,listlength,dist);\n fn = filelist(i).name;\n ffn = fullfile(samplesavefolder, fn);\n loaddata = load(ffn,'samples');\n samples = loaddata.samples;\n matchedidx = samples(2,:) == dist;\n matchednumber = nnz(matchedidx);\n matcheddata = samples(:,matchedidx);\n idxend = idxstart + matchednumber -1;\n CollectedData(:,idxstart:idxend) = matcheddata;\n idxstart = idxend+1;\n end \n %remove extra data\n CollectedData = CollectedData(:,1:idxend);\n \n %compute statistics\n Statistics(distidx).dist = dist;\n MagReconstruct = CollectedData(1,:);\n MagOriginal = CollectedData(3,:);\n MagEdgeCenter = CollectedData(4,:); \n \n %put all samples into each cell\n %Now there is a problem. There are too few samples and too many cells.\n %Many cells are empty and statistics can not be computed\n SpSum = zeros(BinNumber);\n SpSqrSum = zeros(BinNumber);\n Count = zeros(BinNumber);\n for i=1:idxend\n if mod(i,1000) == 0\n fprintf('Process sample i %d, total %d\\n',i,idxend);\n end\n Tr = MagEdgeCenter(i);\n Tp = MagReconstruct(i);\n Sp = MagOriginal(i);\n %compute the index of bin\n TpBinIdx = Val2BinIdx(Tp); %first coordinate\n TrBinIdx = Val2BinIdx(Tr);\n SpSum(TpBinIdx,TrBinIdx) = SpSum(TpBinIdx,TrBinIdx) + Sp;\n SpSqrSum(TpBinIdx,TrBinIdx) = SpSqrSum(TpBinIdx,TrBinIdx) + Sp^2;\n Count(TpBinIdx,TrBinIdx) = Count(TpBinIdx,TrBinIdx) + 1;\n end\n Average = SpSum ./ Count;\n Std = sqrt(SpSqrSum./Count - Average.^2);\n %preserve the nan items\n Statistics(distidx).EstimatedMag = Average;\n Statistics(distidx).StdRecord = Std;\n end\n \n save(Para.StatisticsFileName,'Statistics','b','BinNumber','BinMax','BinMin','BinInterval','BinCenter','DistLength','dist');\nend\n\nfunction BinIdx = Val2BinIdx(val)\n %range 0~0.5, BinNumber 100\n %val 0 ~ 0.005 --> index 1\n %valu 0.005 ~ 0.01 --> index 2\n BinIdx = floor(val / 0.005) + 1;\n if BinIdx > 100\n BinIdx = 100;\n end\nend\n\nfunction DrawOneSetting(Para)\n load(Para.StatisticsFileName);\n for i=1:DistLength\n hFig = figure;\n %need to control here, if d=0, plot is a better choice than mesh\n if i==1\n MeanValue = zeros(1,BinNumber);\n StdValue = zeros(1,BinNumber);\n for j=1:BinNumber\n MeanValue(j) = Statistics(i).EstimatedMag(j,j);\n StdValue(j) = Statistics(i).StdRecord(j,j);\n end\n plot(BinCenter,MeanValue,'ro');\n hold on\n plot(BinCenter,MeanValue-StdValue,'bx');\n plot(BinCenter,MeanValue+StdValue,'bx');\n xlabel('$m_c$','interpreter','latex','FontSize',30);\n ylabel('$m_e$','interpreter','latex','FontSize',30);\n axis equal\n else\n mesh(BinCenter,BinCenter,Statistics(i).EstimatedMag);\n zlabel('$m_e$','interpreter','latex','FontSize',30);\n xlabel('$m_c$','interpreter','latex','FontSize',30,'Position',[0.2 -0.2 0]);\n ylabel('$m_p$','interpreter','latex','FontSize',30,'Position',[-0.1 0.3 0]);\n colorbar\n caxis([0 1.6]);\n zlim([0 1.6]);\n hAxes = gca;\n hAxesPosition = get(hAxes,'Position');\n set(hAxes,'Position',[hAxesPosition(1)+0.01 hAxesPosition(2) hAxesPosition(3) hAxesPosition(4)]);\n end\n% if dist == 0 || dist == 1\n% TitleString = sprintf('$d$ = %d',dist);\n% end\n% title(TitleString,'interpreter','latex');\n dist = b(i);\n SaveFileNameMain = sprintf('Statistics_Sc%d_Si%dp%d_dist%dp%d',...\n Para.Zooming,...\n floor(Para.Gau_sigma),floor(10*(eps+Para.Gau_sigma-floor(Para.Gau_sigma))),...\n floor(dist) ,floor(10*(eps+dist-floor(dist)))...\n );\n% SaveFileName = sprintf('Statistic_Sc%d_Si%dp%d',Para.Zooming,floor(Para.Gau_sigma),floor(10*(eps+Para.Gau_sigma-floor(Para.Gau_sigma))));\n FullSaveName = fullfile(Para.SaveFolder,[ SaveFileNameMain ,'.fig']);\n saveas(hFig,FullSaveName);\n FullSaveName = fullfile(Para.SaveFolder,[ SaveFileNameMain ,'.png']);\n saveas(hFig,FullSaveName); %how to control the png size?\n close(hFig);\n end\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F37d_GetTexturePatchMatch_PatchSizeAdjustable.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F37d_GetTexturePatchMatch_PatchSizeAdjustable.m", "size": 7696, "source_encoding": "utf_8", "md5": "1bcd3ae4af71a520d68c26d4e2bdaecf", "text": "%Chih-Yuan Yang\n%10/05/12\n%Use patchmatch to retrieve a texture background\nfunction [gradients_texture, img_texture, img_texture_backprojection] = ...\n F37d_GetTexturePatchMatch_PatchSizeAdjustable(img_y, ...\n hrexampleimages, lrexampleimages, patchsize)\n [h_lr, w_lr, exampleimagenumber] = size(lrexampleimages);\n [h_hr, w_hr, ~] = size(hrexampleimages);\n zooming = h_hr/h_lr;\n if zooming == 4\n Gau_sigma = 1.6;\n elseif zooming == 3\n Gau_sigma = 1.2;\n end\n \n cores = 2; % Use more cores for more speed\n\n if cores==1\n algo = 'cpu';\n else\n algo = 'cputiled';\n end\n nn_iters = 5;\n %A =F38_ExtractFeatureFromAnImage(img_y);\n A = repmat(img_y,[1 1 3]);\n testnumber = exampleimagenumber;\n xyandl2norm = zeros(h_lr,w_lr,3,testnumber,'int32');\n disp('patchmatching');\n parfor i=1:testnumber;\n %run patchmatch\n %fprintf('Patch match running image %d\\n',i);\n %B = F38_ExtractFeatureFromAnImage( lrexampleimages(:,:,i));\n B = repmat(lrexampleimages(:,:,i),[1 1 3]);\n xyandl2norm(:,:,:,i) = nnmex(A, B, algo, patchsize, nn_iters, [], [], [], [], cores); %the return in int32\n end\n l2norm = xyandl2norm(:,:,3,:);\n [~, ix] = sort(l2norm,4);\n \n %reconstruct the high-resolution image\n h_expected = h_lr * zooming;\n w_expected = w_lr * zooming;\n img_texture = zeros(h_expected,w_expected,'uint8');\n %most cases\n rpixelshift = 2;\n cpixelshift = 2;\n for rl = 2:h_lr - patchsize\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n for cl = 2:w_lr - patchsize\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n end\n end\n \n %left\n cl = 1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n for rl=2:h_lr-patchsize\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n end\n \n %right\n cl = w_lr - patchsize+1;\n ch = w_expected - 3*zooming+1;\n ch1 = w_expected;\n for rl=2:h_lr-patchsize\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n end\n \n %top\n rl = 1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n for cl=2:w_lr-patchsize\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+zooming-1;\n rhsource = (rlsource-1)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n end\n \n %bottom\n rl = h_lr-patchsize+1;\n rh = h_expected - 3*zooming+1;\n rh1 = h_expected;\n for cl=2:w_lr-patchsize\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n end\n \n %left-top corner\n rl=1;\n cl=1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n \n %right-top corner\n rl=1;\n cl=w_lr-patchsize+1;\n rh = (rl-1)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n\n %left-bottom corner\n rl=h_lr-patchsize+1;\n cl=1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1)*zooming+1;\n ch1 = ch+3*zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n \n %left-bottom corner\n rl=h_lr-patchsize+1;\n cl=w_lr-patchsize+1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n \n img_texture = im2double(img_texture);\n iternum = 1000;\n Tolf = 0.0001;\n breport = false;\n disp('backprojection for img_texture');\n img_texture_backprojection = F11d_BackProjection_GaussianKernel(img_y, img_texture, Gau_sigma, iternum,breport,Tolf);\n \n %extract the graident\n gradients_texture = F14_Img2Grad(img_texture_backprojection);\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F46_ConvertFilenameStringToFolderString_MultiPIE.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F46_ConvertFilenameStringToFolderString_MultiPIE.m", "size": 985, "source_encoding": "utf_8", "md5": "ea59d28b4a7699d9298682818c90d85e", "text": "%Chih-Yuan Yang\n%03/21/14\n%Convert a filename string to the folder strings of Multi-PIE dataset\nfunction folder_container = F46_ConvertFilenameStringToFolderString_MultiPIE( fn_file )\n str_identity = fn_file(1:3);\n str_session = fn_file(5:6);\n str_expression = fn_file(8:9);\n str_cameraposition = fn_file(11:13); %in filename, it is 051; in folder, it is 05_1\n str_illumination = fn_file(15:16); %this string is not used since images of all illumination are contained in the same folder\n %according to the data, to find the correct folder\n folder_session = sprintf('session%s',str_session);\n folder_multiview = fullfile('data',folder_session,'multiview');\n folder_identity = fullfile(folder_multiview,str_identity);\n folder_expression = fullfile(folder_identity,str_expression);\n folder_cameraposition = fullfile(folder_expression,[str_cameraposition(1:2) '_' str_cameraposition(3)]);\n folder_container = folder_cameraposition;\nend\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F16b_ACCV12TextureGradientNotIntensity.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F16b_ACCV12TextureGradientNotIntensity.m", "size": 47555, "source_encoding": "utf_8", "md5": "912ce9d2544a868a8174c7642d2f0747", "text": "%Chih-Yuan Yang\n%09/19/12\n%remove weightmap_texture to emphasize the edge\n%The results are worse than F16a\nfunction gradients_merge = F16b_ACCV12TextureGradientNotIntensity(img_y, zooming, Gau_sigma ,sfall,srecall,allHRexampleimages)\n if zooming == 4\n para.Gau_sigma = 1.6;\n elseif zooming == 3\n para.Gau_sigma = 1.2;\n end\n \n %change here, return gradient rather than intensity\n %[img_edge reliablemap_edge] = IF1_EdgePreserving(img_y,para,zooming,Gau_sigma);\n [gradients_edge weightmap_edge] = IF1a_EdgePreserving(img_y,para,zooming,Gau_sigma);\n \n \n [h_lr w_lr] = size(img_y);\n para.lh = h_lr;\n para.lw = w_lr;\n para.NumberOfHCandidate = 10;\n para.SimilarityFunctionSettingNumber = 1;\n %load all data set to save loading time\n [scanr scanra] = SearchExternalPatches(img_y,para,sfall,srecall);\n para.zooming = zooming;\n para.ps = 5;\n para.Gau_sigma = Gau_sigma;\n hrpatch = F8_ExtractAllHrPatches(img_y, para, scanr,allHRexampleimages);\n [scanr_self scanra_self] = F22_SearchForSelfSimilarPatchesL2Norm(img_y,para);\n para.ehrfKernelWidth = 1.0;\n para.bEnablemhrf = true;\n [img_texture weightmap_texture] = F11_FilterOutImproperHrPatches(img_y,hrpatch,para,scanr_self,scanra_self,scanr,scanra);\n %apply backprojection on img_texture only\n iternum = 10;\n breport = true;\n disp('backprojection for img_texture in ACCV12');\n img_texture_backproject = IF3_BackProjection(img_y, img_texture, Gau_sigma, iternum,breport);\n %extract the graident\n gradients_texture = Img2Grad(img_texture_backproject);\n weightmap_texture = 1- weightmap_edge;\n gradients_merge = gradients_texture .* repmat(weightmap_texture,[1,1,8]) + gradients_edge .* repmat(weightmap_edge,[1,1,8]);\n %debug, generate the intensity\n %img_initial = imresize(img_y,zooming);\n %bReport = true;\n %img_merge = GenerateIntensityFromGradient(img_y,img_initial,gradients_merge,para,zooming,Gau_sigma,bReport);\n %keyboard\n %nomi = img_texture_backproject.*weightmap_texture + img_edge .* weightmap_edge;\n %denomi = reliablemap_edge + weightmap_texture;\n %img_hr = nomi ./ denomi;\n %there are some 0 value of denomi around boundary\n %fill these pixels as img_edge\n %nanpixels = isnan(img_hr);\n %img_hr(nanpixels) = img_edge(nanpixels);\n %ensure there is no nan\n %if nnz(isnan(img_hr))\n % error('should not be here');\n %end\nend\nfunction [scanr scanra] = SearchExternalPatches(img_y,para,sfall,srecall)\n %how to search parallelly to speed up?\n ps = 5; %patch size\n [lh lw] = size(img_y);\n hrpatchnumber = 10;\n %featurefolder = para.featurefolder;\n sh = GetShGeneral(ps);\n scanr = zeros(6,hrpatchnumber,lh-ps+1,lw-ps+1); %scan results, mm, quan, ii, sr, sc, similairty\n smallvalue = -1;\n scanr(6,:,:,:) = smallvalue;\n scanra = zeros(lh-ps+1,lw-ps+1); %scan results active\n %scanrsimmax = smallvalue * ones(lh-ps+1,lw-ps+1); %del this line?\n quanarray = [1 2 4 8 16 32];\n B = [256 128 64 32 16 8];\n imlyi = im2uint8(img_y);\n for qidx=1:6\n quan = quanarray(qidx);\n b = B(qidx);\n \n cur_initial = floor(size(sfall{1},2)/2); %accelerate the loop by using an initial position\n for rl=1:lh-ps+1\n fprintf('look for lut rl:%d quan:%d\\n',rl,quan);\n for cl = 1:lw-ps+1\n patch = imlyi(rl:rl+ps-1,cl:cl+ps-1);\n fq = patch(sh);\n if qidx == 1\n fquan = fq;\n else\n fquan = fq - mod(fq,quan) + quan/2;\n end\n\n [iila mma] = LookForLookUpTable9_External(fquan,sfall{qidx},cur_initial,para); %index in lookuptable\n in = length(iila); %always return 20 instance\n for i=1:in\n ii = srecall{qidx}(1,iila(i)); \n sr = srecall{qidx}(2,iila(i));\n sc = srecall{qidx}(3,iila(i));\n %check whether the patch is in the scanr already\n bSamePatch = false;\n for j=1:scanra(rl,cl)\n if ii == scanr(3,j,rl,cl) && sr == scanr(4,j,rl,cl) && sc == scanr(5,j,rl,cl)\n bSamePatch = true;\n break\n end\n end\n\n if bSamePatch == false\n similarity = bmm2similarity(b,mma(i),para.SimilarityFunctionSettingNumber);\n if scanra(rl,cl) < hrpatchnumber\n ix = scanra(rl,cl) + 1;\n %to do: update scanr by similarity\n %need to double it, otherwise, the int6 will kill similarity\n scanr(:,ix,rl,cl) = cat(1,mma(i),quan,double(ii),double(sr),double(sc),similarity);\n scanra(rl,cl) = ix;\n else\n [minval ix] = min(scanr(6,:,rl,cl));\n if scanr(6,ix,rl,cl) < similarity\n %update\n scanr(:,ix,rl,cl) = cat(1,mma(i),quan,double(ii),double(sr),double(sc),similarity); \n end\n end\n end\n end\n end\n end\n end\nend\nfunction [iila mma] = LookForLookUpTable9_External(fq,lut,cur_initial,para)\n hrpatchnumber = para.NumberOfHCandidate; %default 10\n fl = length(fq); %feature length\n head = 1;\n tail = size(lut,2);\n lutsize = size(lut,2);\n if exist('cur_initial','var')\n if cur_initial > lutsize\n cur = lutsize;\n else\n cur = cur_initial;\n end\n else\n cur = round(lutsize/2);\n end\n cur_rec1 = cur;\n %initial comparison\n fqsmaller = -1;\n fqlarger = 1;\n fqsame = 0;\n cr = 0; %compare results\n mm = 0;\n mmiil = 0;\n %search for the largest mm\n while 1\n for c=1:fl\n if fq(c) < lut(c,cur)\n cr = fqsmaller;\n break\n elseif fq(c) > lut(c,cur)\n cr = fqlarger;\n break; %c moves to next\n else %equal\n cr = fqsame;\n if mm < c\n mm = c;\n mmiil = cur;\n end \n end\n end\n \n if cr == fqsmaller\n next = floor((cur + head)/2);\n tail = cur; %adjust the range of head and tail\n elseif cr == fqlarger;\n next = ceil((cur + tail)/2); %the round function has to be floor, because fq is larger than cur\n %otherwise the fully 255 patches will never match\n head = cur; %adjust the range of head and tail\n end\n \n if mm == 25 %it happens, the initial one match the fq, therefore, there is no next defined.\n break\n end\n if cur == next || cur_rec1 == next %the next might oscilate\n break;\n else\n cur_rec1 = cur;\n cur = next;\n end\n %fprintf('cur %d\\n',cur);\n end\n\n if mm == 0 \n iila = [];\n mma = [];\n return\n end\n %post-process to find the repeated partial vectors\n %search for previous\n idx = 1;\n iila = zeros(hrpatchnumber,1);\n mma = zeros(hrpatchnumber,1);\n iila(idx) = mmiil;\n mma(idx) = mm;\n bprecontinue = true;\n bproccontinue = true;\n \n presh = 0; %previous shift\n procsh = 0; %proceeding shift\n while 1\n presh = presh -1;\n iilpre = mmiil + presh;\n if iilpre <1\n bprecontinue = false;\n premm = 0;\n end\n procsh = procsh +1;\n iilproc = mmiil + procsh;\n if iilproc > lutsize\n bproccontinue = false;\n procmm = 0;\n end\n \n if bprecontinue \n diff = lut(:,iilpre) ~= fq;\n if nnz(diff) == 0\n premm = 25;\n else\n premm = find(diff,1,'first') -1;\n end\n end\n\n if bproccontinue\n diff = lut(:,iilproc) ~= fq;\n if nnz(diff) == 0\n procmm = 25;\n else\n procmm = find(diff,1,'first') -1;\n end\n end\n \n if premm == 0 && procmm == 0\n break\n end\n if premm > procmm\n %add pre item\n idx = idx + 1;\n iila(idx) = iilpre;\n mma(idx) = premm;\n %pause the proc\n bprecontinue = true;\n elseif premm < procmm\n %add proc item\n idx = idx + 1;\n iila(idx) = iilproc;\n mma(idx) = procmm;\n %pause the pre\n bproccontinue = true;\n else %premm == procmm\n %add both item\n idx = idx + 1;\n iila(idx) = iilpre;\n mma(idx) = premm;\n \n if idx == hrpatchnumber\n break\n end\n idx = idx + 1;\n iila(idx) = iilproc;\n mma(idx) = procmm; \n bproccontinue = true;\n bprecontinue = true;\n end\n if idx == hrpatchnumber\n break\n end\n end\n\n if idx < hrpatchnumber\n iila = iila(1:idx);\n mma = mma(1:idx);\n end\nend\nfunction s = bmm2similarity(b,mm,SimilarityFunctionSettingNumber)\n if SimilarityFunctionSettingNumber == 1\n if mm >= 9\n Smm = 0.9 + 0.1*(mm-9)/16;\n else\n Smm = 0.5 * mm/9;\n end\n\n Sb = 0.5+0.5*(log2(b)-3)/5;\n s = Sb * Smm;\n elseif SimilarityFunctionSettingNumber == 2\n Smm = mm/25;\n Sb = (log2(b)-2)/6;\n s = Sb * Smm;\n end\nend\nfunction hrpatch = F8_ExtractAllHrPatches(img_y, para, scanr,allHRexampleimages)\n disp('extracting HR patches');\n %how to search parallelly to speed up?\n psh = para.ps * para.zooming;\n ps = para.ps;\n lh = para.lh;\n lw = para.lw;\n s = para.zooming;\n hrpatchnumber = para.NumberOfHCandidate;\n hrpatch = zeros(psh,psh,lh-ps+1,lw-ps+1,hrpatchnumber);\n allimages = allHRexampleimages;\n \n %analyize which images need to be loaded\n alliiset = scanr(3,:,:,:);\n alliiset_uni = unique(alliiset(:)); %allmost all images are used, from 1 to 1500\n if alliiset_uni(1) ~= 0\n alliiset_uni_pure = alliiset_uni;\n else\n alliiset_uni_pure = alliiset_uni(2:end);\n end\n\n for i = 1:length(alliiset_uni_pure)\n ii = alliiset_uni_pure(i);\n\n exampleimage_hr = im2double(allimages(:,:,ii));\n\n exampleimage_lr = U3_GenerateLRImage_BlurSubSample(exampleimage_hr,para.zooming,para.Gau_sigma);\n match_4D = alliiset == ii;\n match_3D = reshape(match_4D,hrpatchnumber,lh-ps+1,lw-ps+1); %remove the first dimension\n [d1 d2 d3] = size(match_3D); %second dimention length\n [idxset posset] = find(match_3D);\n setin = length(idxset);\n for j = 1:setin\n idx = idxset(j);\n possum = posset(j);\n pos3 = floor( (possum-1)/d2) +1; %the relationship: possum = (pos3-1) * d2 + pos2, pos2 in (1,d2)\n pos2 = possum - (pos3-1)*d2;\n\n rl = pos2;\n cl = pos3;\n \n sr = scanr(4,idx,rl,cl);\n sc = scanr(5,idx,rl,cl);\n \n srh = (sr-1)*s+1;\n srh1 = srh + psh -1;\n sch = (sc-1)*s+1;\n sch1 = sch + psh-1;\n\n %to do: compensate the HR patch to match the LR query patch\n hrp = exampleimage_hr(srh:srh1,sch:sch1); %HR patch \n lrq = img_y(rl:rl+ps-1,cl:cl+ps-1); %LR query patch\n lrr = exampleimage_lr(sr:sr+ps-1,sc:sc+ps-1); %LR retrieved patch\n chrp = hrp + imresize(lrq - lrr,s,'bilinear'); %compensate HR patch\n hrpatch(:,:,rl,cl,idx) = chrp;\n \n bVisuallyCheck = false;\n if bVisuallyCheck\n if ~exist('hfig','var')\n hfig = figure;\n else\n figure(hfig);\n end\n subplot(1,4,1);\n imshow(hrp/255);\n title('hrp');\n subplot(1,4,2);\n imshow(lrr/255);\n title('lrr');\n subplot(1,4,3);\n imshow(lrq/255);\n title('lrq');\n subplot(1,4,4);\n imshow(chrp/255);\n title('chrp');\n keyboard\n end\n end \n end\nend\nfunction [img_texture Reliablemap] = F11_FilterOutImproperHrPatches(img_y,hrpatch,para,scanr_self,scanra_self,scanr,scanra)\n %filter out improper hr patches using similarity among lr patches\n %load the self-similar data\n s = para.zooming;\n lh = para.lh;\n lw = para.lw;\n ps = para.ps;\n psh = s * para.ps;\n patcharea = para.ps^2;\n\n\n SSnumberUpperbound = 10;\n \n %do I still need these variables?\n cqarray = zeros(32,1)/0;\n for qidx = 1:6\n quan = 2^(qidx-1);\n cqvalue = 0.9^(qidx-1);\n cqarray(quan) = cqvalue;\n end\n \n hh = lh * s;\n hw = lw * s;\n hrres_nomi = zeros(hh,hw);\n hrres_deno = zeros(hh,hw);\n maskmatrix = false(psh,psh,patcharea);\n Reliablemap = zeros(hh,hw);\n \n pshs = psh * psh; \n for i=1:patcharea\n [sh_notsued masklow maskhigh] = GetShGeneral(ps,i,true,s); %ps, mm, bhigh, s\n maskmatrix(:,:,i) = maskhigh;\n end\n mhr = zeros(5*s);\n r1 = 2*s+1;\n r2 = 3*s;\n c1 = 2*s+1;\n c2 = 3*s;\n mhr(r1:r2,c1:c2) = 1; %the central part\n sigma = para.ehrfKernelWidth;\n kernel = Sigma2Kernel(sigma);\n if para.bEnablemhrf\n mhrf = imfilter(mhr,kernel,'replicate');\n else\n mhrf = mhr;\n end\n\n noHmap = scanra == 0;\n noHmapToFill = noHmap;\n NHOOD = [0 1 0;\n 1 1 1;\n 0 1 0];\n se = strel('arbitrary',NHOOD);\n noHmapneighbor = and( imdilate(noHmap,se) ,~noHmap);\n %if the noHmapsever is 0, it is fine\n \n imb = imresize(img_y,s); %use it as the reference if no F is available\n \n rsa = [0 -1 0 1];\n csa = [1 0 -1 0];\n for rl= 1:lh-ps+1 %75\n fprintf('rl:%d total:%d\\n',rl,lh-ps+1);\n rh = (rl-1)*s+1;\n rh1 = rh+psh-1;\n for cl = 1:lw-ps+1 %128\n ch = (cl-1)*s+1;\n ch1 = ch+psh-1;\n \n %load candidates\n hin = para.NumberOfHCandidate;\n H = zeros(psh,psh,hin);\n HSim = zeros(hin,1);\n for j=1:hin\n H(:,:,j) = hrpatch(:,:,rl,cl,j); %H\n HSim(j) = scanr(6,j,rl,cl);\n end\n \n %compute the number of reference patches\n sspin = min(SSnumberUpperbound,scanra_self(rl,cl)); \n %self similar patch instance number\n F = zeros(ps,ps,sspin);\n FSimPure = zeros(1,sspin);\n rin = 0;\n for i=1:sspin\n sr = scanr_self(3,i,rl,cl);\n sc = scanr_self(4,i,rl,cl);\n %hr candidate number\n rin = rin + para.NumberOfHCandidate;\n F(:,:,i) = img_y(sr:sr+ps-1,sc:sc+ps-1);\n FSimPure(i) = scanr_self(5,i,rl,cl);\n end\n \n %load all of the two step patches\n R = zeros(psh,psh,rin);\n mms = zeros(rin,1);\n mmr = zeros(rin,1);\n qs = zeros(rin,1);\n qr = zeros(rin,1);\n FSimBaseR = zeros(rin,1); \n RSim = zeros(rin,1);\n idx = 0;\n if sspin > 0\n for i=1:sspin %sspin is the Fin\n sr = scanr_self(3,i,rl,cl);\n sc = scanr_self(4,i,rl,cl);\n %hr candidate number\n hrcanin = para.NumberOfHCandidate;\n for j=1:hrcanin\n idx = idx + 1;\n R(:,:,idx) = hrpatch(:,:,sr,sc,j);\n mms(idx) = scanr_self(1,i,rl,cl);\n qs(idx) = scanr_self(2,i,rl,cl);\n mmr(idx) = scanr(1,j,sr,sc);\n qr(idx) = scanr(2,j,sr,sc);\n FSimBaseR(idx) = FSimPure(i);\n RSim(idx) = scanr(6,j,sr,sc);\n end\n end\n else\n idx = 1;\n rin = 1; %use bicubic \n R(:,:,idx) = imb(rh:rh1,ch:ch1);\n FSimBaseR(idx) = 1;FSimPure(i);\n end\n\n %here is a question, how to define the similarity between H and R?\n %L2norm?\n hscore = zeros(hin,1);\n for i=1:hin\n theH = H(:,:,i);\n for j=1:rin\n theR = R(:,:,j);\n spf = FSimBaseR(j);\n %similarity between H and R\n diff = theH - theR;\n L2N = norm(diff(:));\n shr = exp(- L2N/pshs);\n hscore(i) = hscore(i) + shr*spf;\n end\n end\n [maxscore idx] = max(hscore);\n %take this as the example\n Reliablemap(rh:rh1,ch:ch1) = Reliablemap(rh:rh1,ch:ch1) + HSim(idx)*mhrf;\n \n if hin > 0 %some patches can't find H\n hrres_nomi(rh:rh1,ch:ch1) = hrres_nomi(rh:rh1,ch:ch1) + H(:,:,idx).*mhrf;\n hrres_deno(rh:rh1,ch:ch1) = hrres_deno(rh:rh1,ch:ch1) + mhrf; \n end\n %if any of its neighbor belongs to noHmap, copy additional region to hrres\n %if the pixel belongs to noHmapneighbor, then expand the copy regions\n if noHmapneighbor(rl,cl) == true\n mhrfspecial = zeros(5*s);\n mhrfspecial(r1:r2,c1:c2) = 1;\n for i=1:4\n rs = rsa(i);\n cs = csa(i);\n checkr = rl+rs;\n checkc = cl+cs;\n if checkr > 0 && checkr < lh-ps+1 && checkc >0 && checkc =1 && r2<=h && c1>=1 && c2<=w %discrad boundary?\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(11), c*ones(11));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %Convert dist to table index\n TableIndexMap = zeros(h,w);\n b = unique(DistPatch(:));\n for i=1:length(b)\n SetPixels = DistMap == b(i);\n TableIndexMap(SetPixels) = i;\n end\n\n \n %mapping (T_p, T_r, d) to S_p\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n UpdatedPixel = false(h,w);\n S = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n CurrentMagValue = T(r,c);\n BinIdx_Current = ceil(CurrentMagValue /0.005);\n %Zebra have super strong Mag\n if BinIdx_Current > 100\n BinIdx_Current = 100;\n end\n TableIndex = TableIndexMap(r,c);\n if TableIndex > para.DistanceUpperBound\n continue\n end\n CenterMagValue = T(r_Center,c_Center);\n %Low Mag Edge suppresion\n if CenterMagValue < para.LowMagSuppression\n continue\n end\n BinIdx_Center = ceil(CenterMagValue /0.005);\n if BinIdx_Center > 100\n BinIdx_Center = 100;\n end\n %consult the table\n if TableIndex == 1 %1 is the index of b(1) where dist = 0, enhance the contrast of pixel on edge \n S_p = para.ContrastEnhenceCoef * Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n else\n S_p = Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n end\n \n if isnan(S_p)\n else\n UpdatedPixel(r,c) = true;\n S(r,c) = S_p;\n end\n end\n\n %Record the RidgeMapMap, for computing te ProbOfMag\n %the Mag is the consulted Mag\n %here is the problem, when the S is very strong, the affect range of ProbMagOut exceeds 1 pixel\n RidgeMapMagValue = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n RidgeMapMagValue(r,c) = S(r_Center,c_Center);\n end \n \n S(~UpdatedPixel) = T(~UpdatedPixel);\n img_in = I_s;\n if min(Dissimilarity(:)) == 0\n d = Dissimilarity + 1e-6; %avoid 0 case; some images may have d(:,:,1) as 0\n else\n d = Dissimilarity;\n end\n ratio = d ./ repmat(d(:,:,1),[1,1,8]);\n %here is the problem, I need to amplify the gradient directionally \n Grad_in = Img2Grad(img_in);\n Product = Grad_in .* ratio;\n Sqr = Product.^2;\n Sum = sum(Sqr,3);\n Sqrt = sqrt(Sum); %the Sqrt might be 0, because Grad_in may be pure 0;\n r1 = S ./Sqrt;\n r1(isnan(r1)) = 0;\n\n Grad_exp = Grad_high_initial .*( ratio .*(repmat(r1,[1,1,8])));\n %consolidate inconsistatnt gradient\n NewGrad_exp = zeros(h,w,8);\n for k=1:4\n switch k\n case 1\n ShiftOp = [0 -1];\n case 2\n ShiftOp = [1 -1];\n case 3\n ShiftOp = [1 0];\n case 4\n ShiftOp = [1 1];\n end\n k2 =k+4;\n Grad1 = Grad_exp(:,:,k);\n Grad2 = Grad_exp(:,:,k2);\n Grad2Shift = circshift(Grad2,ShiftOp);\n Grad1Abs = abs(Grad1);\n Grad2AbsShift = abs(Grad2Shift);\n Grad1Larger = Grad1Abs > Grad2AbsShift;\n Grad2Larger = Grad2AbsShift > Grad1Abs;\n NewGrad1 = Grad1 .* Grad1Larger + (-Grad2Shift) .* Grad2Larger;\n NewGrad2Shift = Grad2Shift .* Grad2Larger + (-Grad1) .* Grad1Larger;\n NewGrad2 = circshift(NewGrad2Shift,-ShiftOp);\n NewGrad_exp(:,:,k) = NewGrad1;\n NewGrad_exp(:,:,k2) = NewGrad2;\n end\n %current problem is the over-enhanced gradient (NewMagExp too large)\n\n para.bReport = true;\n img_edge = GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,para,zooming,Gau_sigma);\n\n %compute the Map of edge weight\n lambda_m = 2;\n m0 = 0;\n ProbMagOut = lambda_m * RidgeMapMagValue + m0;\n\n lambda_d = 0.25;\n d0 = 0.25;\n ProbDistMap = exp(- (lambda_d * DistMap + d0) ); %this coef should be decied by zooming\n \n Product = ProbMagOut .* ProbDistMap;\n ProbOfEdge = min(Product,1); %the two terms are not sufficient, direction is not taken into considertion\nend\nfunction [gradients_edge weightmap_edge] = IF1a_EdgePreserving(img_y,para,zooming,Gau_sigma)\n para.LowMagSuppression = 0;\n para.DistanceUpperBound = 2.0;\n para.ContrastEnhenceCoef = 1.0;\n I_s = IF2_SmoothnessPreservingFunction(img_y,para,zooming);\n T = F15_ComputeSRSSD(I_s);\n Dissimilarity = EvaluateDissimilarity8(I_s);\n Grad_high_initial = Img2Grad(I_s);\n \n %SaveFolder = para.tuningfolder;\n \n [h w] = size(T);\n StatisticsFolder = fullfile('EdgePriors');\n LoadFileName = sprintf('Statistics_Sc%d_Si%0.1f.mat',zooming,Gau_sigma);\n LoadData = load(fullfile(StatisticsFolder,LoadFileName));\n Statistics = LoadData.Statistics;\n \n RidgeMap = edge(I_s,'canny',[0 0.01],0.05);\n\n %filter out small ridge and non-maximun ridges\n RidgeMap_filtered = RidgeMap;\n [r_set c_set] = find(RidgeMap);\n SetLength = length(r_set);\n for j=1:SetLength\n r = r_set(j);\n c = c_set(j);\n CenterMagValue = T(r,c);\n if CenterMagValue < para.LowMagSuppression\n RidgeMap_filtered(r,c) = false;\n end\n end\n \n\n [r_set c_set] = find(RidgeMap_filtered);\n SetLength = length(r_set);\n [X Y] = meshgrid(1:11,1:11);\n DistPatch = sqrt((X-6).^2 + (Y-6).^2);\n\n DistMap = inf(h,w); \n UsedPixel = false(h,w); \n CenterCoor = zeros(h,w,2); \n %Compute DistMap and CneterCoor\n [r_set c_set] = find(RidgeMap_filtered);\n for j=1:SetLength\n r = r_set(j);\n r1 = r-5;\n r2 = r+5;\n c = c_set(j);\n c1 = c-5;\n c2 = c+5;\n if r1>=1 && r2<=h && c1>=1 && c2<=w %discrad boundary?\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(11), c*ones(11));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %Convert dist to table index\n TableIndexMap = zeros(h,w);\n b = unique(DistPatch(:));\n for i=1:length(b)\n SetPixels = DistMap == b(i);\n TableIndexMap(SetPixels) = i;\n end\n\n \n %mapping (T_p, T_r, d) to S_p\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n UpdatedPixel = false(h,w);\n S = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n CurrentMagValue = T(r,c);\n BinIdx_Current = ceil(CurrentMagValue /0.005);\n %Zebra have super strong Mag\n if BinIdx_Current > 100\n BinIdx_Current = 100;\n end\n TableIndex = TableIndexMap(r,c);\n if TableIndex > para.DistanceUpperBound\n continue\n end\n CenterMagValue = T(r_Center,c_Center);\n %Low Mag Edge suppresion\n if CenterMagValue < para.LowMagSuppression\n continue\n end\n BinIdx_Center = ceil(CenterMagValue /0.005);\n if BinIdx_Center > 100\n BinIdx_Center = 100;\n end\n %consult the table\n if TableIndex == 1 %1 is the index of b(1) where dist = 0, enhance the contrast of pixel on edge \n S_p = para.ContrastEnhenceCoef * Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n else\n S_p = Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n end\n \n if isnan(S_p)\n else\n UpdatedPixel(r,c) = true;\n S(r,c) = S_p;\n end\n end\n\n %Record the RidgeMapMap, for computing te ProbOfMag\n %the Mag is the consulted Mag\n %here is the problem, when the S is very strong, the affect range of ProbMagOut exceeds 1 pixel\n RidgeMapMagValue = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n RidgeMapMagValue(r,c) = S(r_Center,c_Center);\n end \n \n S(~UpdatedPixel) = T(~UpdatedPixel);\n img_in = I_s;\n if min(Dissimilarity(:)) == 0\n d = Dissimilarity + 1e-6; %avoid 0 case; some images may have d(:,:,1) as 0\n else\n d = Dissimilarity;\n end\n ratio = d ./ repmat(d(:,:,1),[1,1,8]);\n %here is the problem, I need to amplify the gradient directionally \n Grad_in = Img2Grad(img_in);\n Product = Grad_in .* ratio;\n Sqr = Product.^2;\n Sum = sum(Sqr,3);\n Sqrt = sqrt(Sum); %the Sqrt might be 0, because Grad_in may be pure 0;\n r1 = S ./Sqrt;\n r1(isnan(r1)) = 0;\n\n Grad_exp = Grad_high_initial .*( ratio .*(repmat(r1,[1,1,8])));\n %consolidate inconsistatnt gradient\n NewGrad_exp = zeros(h,w,8);\n for k=1:4\n switch k\n case 1\n ShiftOp = [0 -1];\n case 2\n ShiftOp = [1 -1];\n case 3\n ShiftOp = [1 0];\n case 4\n ShiftOp = [1 1];\n end\n k2 =k+4;\n Grad1 = Grad_exp(:,:,k);\n Grad2 = Grad_exp(:,:,k2);\n Grad2Shift = circshift(Grad2,ShiftOp);\n Grad1Abs = abs(Grad1);\n Grad2AbsShift = abs(Grad2Shift);\n Grad1Larger = Grad1Abs > Grad2AbsShift;\n Grad2Larger = Grad2AbsShift > Grad1Abs;\n NewGrad1 = Grad1 .* Grad1Larger + (-Grad2Shift) .* Grad2Larger;\n NewGrad2Shift = Grad2Shift .* Grad2Larger + (-Grad1) .* Grad1Larger;\n NewGrad2 = circshift(NewGrad2Shift,-ShiftOp);\n NewGrad_exp(:,:,k) = NewGrad1;\n NewGrad_exp(:,:,k2) = NewGrad2;\n end\n %current problem is the over-enhanced gradient (NewMagExp too large)\n gradients_edge = NewGrad_exp;\n \n% para.bReport = true;\n% img_edge = GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,para,zooming,Gau_sigma);\n\n %compute the Map of edge weight\n lambda_m = 2;\n m0 = 0;\n ProbMagOut = lambda_m * RidgeMapMagValue + m0;\n\n lambda_d = 0.25;\n d0 = 0.25;\n ProbDistMap = exp(- (lambda_d * DistMap + d0) ); %this coef should be decied by zooming\n \n Product = ProbMagOut .* ProbDistMap;\n weightmap_edge = min(Product,1); %the two terms are not sufficient, direction is not taken into considertion\nend\nfunction img_out = IF2_SmoothnessPreservingFunction(img_y,para,zooming)\n img_bb = imresize(img_y,zooming);\n Kernel = Sigma2Kernel(para.Gau_sigma);\n\n %compute the similarity from low\n Coef = 10;\n PatchSize = 3;\n Sqrt_low = SimilarityEvaluation(img_y,PatchSize);\n Similarity_low = exp(-Sqrt_low*Coef);\n [h_high w_high] = size(img_bb);\n ExpectedSimilarity = zeros(h_high,w_high,16);\n %upsamplin the similarity\n for dir=1:16\n ExpectedSimilarity(:,:,dir) = imresize(Similarity_low(:,:,dir),zooming,'bilinear');\n end\n \n %refind the Grad_high by Similarity_high\n LoopNumber = 10;\n img = img_bb;\n for loop = 1:LoopNumber\n %refine gradient by ExpectedSimilarity\n ValueSum = zeros(h_high,w_high);\n WeightSum = sum(ExpectedSimilarity,3); %if thw weight sum is low, it is unsuitable to generate the grad by interpolation\n for dir = 1:16\n [MoveOp N] = GetMoveKernel16(dir);\n if N == 1\n MovedData = imfilter(img,MoveOp{1},'replicate');\n else %N ==2\n MovedData1 = imfilter(img,MoveOp{1},'replicate');\n MovedData2 = imfilter(img,MoveOp{2},'replicate');\n MovedData = (MovedData1 + MovedData2)/2;\n end\n Product = MovedData .* ExpectedSimilarity(:,:,dir);\n ValueSum = ValueSum + Product;\n end\n I = ValueSum ./ WeightSum;\n \n %intensity compensate\n Diff = imresize(imfilter(I,Kernel,'replicate'),1/zooming, 'nearest') - img_y;\n UpSampled = imresize(Diff,zooming,'bilinear');\n Grad0 = imfilter(UpSampled,Kernel,'replicate');\n Term_LowHigh_in = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n I_in = I; %make a copy, restore the value if all beta fails\n bDecrease = false;\n tau = 0.2;\n for line_search_loop=1:10\n %line search for the beta, fixed 1/32 is not a good choice\n I = I_in - tau * Grad0;\n Term_LowHigh_out = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n if Term_LowHigh_out < Term_LowHigh_in\n bDecrease = true;\n break;\n else\n tau = tau * 0.5;\n end\n end\n \n if bDecrease == true\n I_best = I;\n else\n break;\n end\n% fprintf('loop=%d, LowHihg_in=%0.1f, LowHigh_out=%0.1f,\\n',loop,Term_LowHigh_in,Term_LowHigh_out); \n \n% imwrite(I,fullfile(SaveFolder, [num2str(loop) '_GenIntenFromGrad.png']));\n img = I_best;\n end\n img_out = img;\n\nend\nfunction SqrtData = SimilarityEvaluation(Img_in,PatchSize)\n HalfPatchSize = (PatchSize-1)/2;\n [h w] = size(Img_in);\n SqrtData = zeros(h,w,16);\n \n f3x3 = ones(3);\n for i = 1:16\n [DiffOp N] = RetGradientKernel16(i);\n if N == 1\n Diff = imfilter(Img_in,DiffOp{1},'symmetric');\n else\n Diff1 = imfilter(Img_in,DiffOp{1},'symmetric');\n Diff2 = imfilter(Img_in,DiffOp{2},'symmetric');\n Diff = (Diff1+Diff2)/2;\n end\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Mean = Sum/9;\n SqrtData(:,:,i) = sqrt(Mean);\n end\nend\nfunction [DiffOp N] = RetGradientKernel16(dir)\n DiffOp = cell(2,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n DiffOp{1} = f{1};\n DiffOp{2} = [];\n case 2\n N = 2;\n DiffOp{1} = f{1};\n DiffOp{2} = f{2};\n case 3\n N = 1; \n DiffOp{1} = f{2};\n DiffOp{2} = [];\n case 4\n N = 2;\n DiffOp{1} = f{2};\n DiffOp{2} = f{3};\n case 5\n N = 1;\n DiffOp{1} = f{3};\n DiffOp{2} = [];\n case 6\n N = 2;\n DiffOp{1} = f{3};\n DiffOp{2} = f{4};\n case 7\n N = 1;\n DiffOp{1} = f{4};\n DiffOp{2} = [];\n case 8\n N = 2;\n DiffOp{1} = f{4};\n DiffOp{2} = f{5};\n case 9\n N = 1;\n DiffOp{1} = f{5};\n DiffOp{2} = [];\n case 10\n N = 2;\n DiffOp{1} = f{5};\n DiffOp{2} = f{6};\n case 11\n DiffOp{1} = f{6};\n DiffOp{2} = [];\n N = 1;\n case 12\n N = 2;\n DiffOp{1} = f{6};\n DiffOp{2} = f{7};\n case 13\n N = 1;\n DiffOp{1} = f{7};\n DiffOp{2} = [];\n case 14\n N = 2;\n DiffOp{1} = f{7};\n DiffOp{2} = f{8};\n case 15\n DiffOp{1} = f{8};\n DiffOp{2} = [];\n N = 1;\n case 16\n N = 2;\n DiffOp{1} = f{8};\n DiffOp{2} = f{1};\n end\nend\nfunction [Kernel N] = GetMoveKernel16(dir)\n Kernel = cell(2,1);\n f{1} = [0 0 0;\n 0 0 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 0 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 0 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 0 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 0 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 0 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 0 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 0 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n Kernel{1} = f{1};\n Kernel{2} = [];\n case 2\n N = 2;\n Kernel{1} = f{1};\n Kernel{2} = f{2};\n case 3\n N = 1; \n Kernel{1} = f{2};\n Kernel{2} = [];\n case 4\n N = 2;\n Kernel{1} = f{2};\n Kernel{2} = f{3};\n case 5\n N = 1;\n Kernel{1} = f{3};\n Kernel{2} = [];\n case 6\n N = 2;\n Kernel{1} = f{3};\n Kernel{2} = f{4};\n case 7\n N = 1;\n Kernel{1} = f{4};\n Kernel{2} = [];\n case 8\n N = 2;\n Kernel{1} = f{4};\n Kernel{2} = f{5};\n case 9\n N = 1;\n Kernel{1} = f{5};\n Kernel{2} = [];\n case 10\n N = 2;\n Kernel{1} = f{5};\n Kernel{2} = f{6};\n case 11\n Kernel{1} = f{6};\n Kernel{2} = [];\n N = 1;\n case 12\n N = 2;\n Kernel{1} = f{6};\n Kernel{2} = f{7};\n case 13\n N = 1;\n Kernel{1} = f{7};\n Kernel{2} = [];\n case 14\n N = 2;\n Kernel{1} = f{7};\n Kernel{2} = f{8};\n case 15\n Kernel{1} = f{8};\n Kernel{2} = [];\n N = 1;\n case 16\n N = 2;\n Kernel{1} = f{8};\n Kernel{2} = f{1};\n end\nend\nfunction f = ComputeFunctionValue_lowhigh(img,img_low,Gau_sigma)\n KernelSize = ceil(Gau_sigma) * 3 + 1;\n G = fspecial('gaussian',KernelSize,Gau_sigma);\n Conv = imfilter(img,G,'replicate');\n SubSample = imresize(Conv,size(img_low),'antialias',false);\n Diff = SubSample - img_low;\n Sqr = Diff.^2;\n f = sum(Sqr(:));\nend\nfunction Grad = Img2Grad(img)\n [h w] = size(img);\n Grad = zeros(h,w,8);\n DiffOp = RetGradientKernel();\n for i=1:8\n Grad(:,:,i) = imfilter(img,DiffOp{i},'replicate');\n end\nend\nfunction f = RetGradientKernel()\n f = cell(8,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\nend\nfunction Dissimilarity = EvaluateDissimilarity8(Img_in,PatchSize)\n if ~exist('PatchSize','var');\n PatchSize = 3;\n end\n [h w] = size(Img_in);\n Dissimilarity = zeros(h,w,8);\n \n f3x3 = ones(PatchSize)/(PatchSize^2);\n for i = 1:8\n DiffOp = RetGradientKernel8(i);\n Diff = imfilter(Img_in,DiffOp,'symmetric');\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Dissimilarity(:,:,i) = sqrt(Sum);\n end\nend\nfunction DiffOp = RetGradientKernel8(dir)\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n DiffOp = f{dir};\nend\nfunction img_out = GenerateIntensityFromGradient(img_y,img_initial,Grad_exp,para,zooming,Gau_sigma,bReport)\n if ~isfield(para,'LoopNumber')\n para.LoopNumber = 30;\n end\n if ~isfield(para,'beta0')\n beta0 = 1;\n else\n beta0 = para.beta0;\n end\n if ~isfield(para,'beta1')\n beta1 = 1;\n else\n beta1 = para.beta1;\n end\n \n Kernel = Sigma2Kernel(Gau_sigma);\n \n %compute gradient\n I = img_initial;\n I_best = I;\n for loop = 1:para.LoopNumber\n %refine image by patch similarity\n\n %refine image by low-high intensity\n Diff = imresize(imfilter(I,Kernel,'replicate'),1/zooming, 'nearest') - img_y;\n UpSampled = imresize(Diff,zooming,'bilinear');\n Grad0 = imfilter(UpSampled,Kernel,'replicate');\n \n %refine image by expected gradeint\n %Gradient decent\n %I = ModifyByGradient(I,Grad_exp);\n OptDir = Grad_exp - Img2Grad(I);\n Grad1 = sum(OptDir,3);\n Grad_all = beta0 * Grad0 + beta1 * Grad1;\n \n I_in = I; %make a copy, restore the value if all beta fails\n bDecrease = false;\n tau = 0.2;\n Term_Grad_in = ComputeFunctionValue_Grad(I,Grad_exp);\n Term_LowHigh_in = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n Term_all_in = Term_LowHigh_in * beta0 + Term_Grad_in * beta1;\n for line_search_loop=1:10\n %line search for the beta, fixed 1/32 is not a good choice\n I = I_in - tau * Grad_all;\n Term_Grad_out = ComputeFunctionValue_Grad(I,Grad_exp);\n Term_LowHigh_out = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n Term_all_out = Term_LowHigh_out * beta0 + Term_Grad_out * beta1;\n \n if Term_all_out < Term_all_in\n bDecrease = true;\n break;\n else\n tau = tau * 0.5;\n end\n end\n \n if bDecrease == true\n I_best = I;\n else\n break;\n end\n if bReport\n fprintf(['loop=%d, all_in=%0.1f, all_out=%0.1f, LowHihg_in=%0.1f, LowHigh_out=%0.1f, ' ...\n 'Grad_in=%0.1f, Grad_out=%0.1f\\n'],loop,Term_all_in,Term_all_out,Term_LowHigh_in,Term_LowHigh_out, ...\n Term_Grad_in,Term_Grad_out); \n end\n end\n img_out = I_best;\nend\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend\nfunction lrimg = U3_GenerateLRImage_BlurSubSample(hrimg,s,sigma)\n [h w d] = size(hrimg);\n htrim = h-mod(h,s);\n wtrim = w-mod(w,s);\n imtrim = hrimg(1:htrim,1:wtrim,1:d);\n \n %detect image type\n kernel = Sigma2Kernel(sigma);\n if d == 1\n blurimg = imfilter(imtrim,kernel,'replicate');\n elseif d == 3\n blurimg = zeros(htrim,wtrim,d);\n for i=1:3\n blurimg(:,:,i) = imfilter(imtrim(:,:,i),kernel,'replicate');\n end\n end\n lrimg = imresize(blurimg,1/s,'bilinear','antialias',false);\nend\nfunction img_bp = IF3_BackProjection(img_lr, img_hr, Gau_sigma, iternum,bReport)\n [h_hr] = size(img_hr,1);\n [h_lr] = size(img_lr,1);\n zooming = h_hr/h_lr;\n for i=1:iternum\n img_lr_gen = F19_GenerateLRImage_BlurSubSample(img_hr,zooming,Gau_sigma);\n diff_lr = img_lr - img_lr_gen;\n term_diff_lr_SSD = sum(sum(diff_lr.^2));\n diff_hr = imresize(diff_lr,zooming,'bilinear');\n img_hr = img_hr + diff_hr;\n img_lr_new = F19_GenerateLRImage_BlurSubSample(img_hr,zooming,Gau_sigma);\n diff_lr_new = img_lr - img_lr_new; \n term_diff_lr_SSD_afteronebackprojection = sum(sum(diff_lr_new.^2));\n if bReport\n fprintf('backproject iteration=%d, term_before=%0.1f, term_after=%0.1f\\n', ...\n i,term_diff_lr_SSD,term_diff_lr_SSD_afteronebackprojection); \n end \n end\n img_bp = img_hr;\n\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F35a_ComputeMask_Nose.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F35a_ComputeMask_Nose.m", "size": 2052, "source_encoding": "utf_8", "md5": "32e24280746b82dc016d413597ebf147", "text": "%Chih-Yuan Yang\n%07/20/14\n%F35a: I add new inputs to support the scaling factor of 3. I also replace F19a to F19c.\nfunction [mask_lr, mask_hr] = F35a_ComputeMask_Nose(landmarks_hr,scalingfactor,Gau_sigma)\n mask_hr = zeros(480,640);\n setrange = 28:36;\n checkpair = [28 32;\n 32 33;\n 33 34;\n 34 35;\n 35 36;\n 36 28;];\n for k=1:size(checkpair,1);\n i = checkpair(k,1);\n j = checkpair(k,2);\n %mark the pixel between i and j\n coor1 = landmarks_hr(i,:);\n coor2 = landmarks_hr(j,:);\n x1 = coor1(1);\n c1 = round(x1);\n y1 = coor1(2);\n r1 = round(y1);\n x2 = coor2(1);\n c2 = round(x2);\n y2 = coor2(2);\n r2 = round(y2);\n a = y2-y1;\n b = x1-x2;\n c = (x2-x1)*y1 - (y2-y1)*x1;\n sqra2b2 = sqrt(a^2+b^2);\n rmin = min(r1,r2);\n rmax = max(r1,r2);\n cmin = min(c1,c2);\n cmax = max(c1,c2);\n for rl=rmin:rmax\n for cl=cmin:cmax\n y_test = rl;\n x_test = cl;\n distance = abs(a*x_test+b*y_test +c)/sqra2b2;\n if distance <= sqrt(2)/2\n mask_hr(rl,cl) = 1;\n end\n end\n end\n end\n %fill the interior\n left_coor = min(landmarks_hr(setrange,1));\n right_coor = max(landmarks_hr(setrange,1));\n\n left_idx = round(left_coor);\n right_idx = round(right_coor);\n for cl = left_idx:right_idx\n rmin = find(mask_hr(:,cl),1,'first');\n rmax = find(mask_hr(:,cl),1,'last');\n if rmin ~= rmax\n mask_hr(rmin+1:rmax-1,cl) = 1;\n end\n end\n\n %dilate the get the surrounding region\n radius = 6;\n approximateN = 0;\n se = strel('disk',radius,approximateN);\n mask_hr = imdilate(mask_hr,se);\n\n %blur the boundary\n mask_hr = imfilter(mask_hr,fspecial('gaussian',11,1.6));\n \n mask_lr = F19c_GenerateLRImage_GaussianKernel(mask_hr,scalingfactor,Gau_sigma);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F21g_EdgePreserving_GaussianKernel.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F21g_EdgePreserving_GaussianKernel.m", "size": 10531, "source_encoding": "utf_8", "md5": "5bfbb1e8dfd8d31411776c204d8bd704", "text": "%Chih-Yuan Yang\n%10/27/12\n%F21b: Based on F21a, but change the square kernel to Gaussian, to see whether the square pattern disappear\n%F21c: remove the para argument\n%F21d: try to use large beta0 and small beta1 to see whether it can save the computational time\n%F21e: return gradient_expect to save time\n%F21f: change the function F27 to F27a used in this function\n%F21g: F21f is used by Test13 to generate the intermediate images for paper writing.\n%Those intermediate images are not required for most computing. Thus I create the F21g to remove\n%the intermediate outputs.\nfunction [gradient_expected, weightmap_edge] = F21g_EdgePreserving_GaussianKernel(img_y,zooming,Gau_sigma)\n LowMagSuppression = 0; %the three parameters should be adjusted later\n DistanceUpperBound = 2.0;\n ContrastEnhenceCoef = 1.0;\n I_s = F27b_SmoothnessPreserving(img_y,zooming,Gau_sigma);\n% folder_output = fullfile('Result','Test17_GenerateFigureForPAMI15');\n% imwrite(I_s,fullfile(folder_output,'H_s.png'));\n T = F15_ComputeSRSSD(I_s);\n% hfig = figure;\n% imagesc(T);\n% axis image off\n% caxis([0 0.7121]); \n% saveas(hfig, fullfile(folder_output,'mag.png'));\n% close(hfig);\n \n Dissimilarity = EvaluateDissimilarity8(I_s);\n Grad_high_initial = Img2Grad(I_s);\n \n [h w] = size(T);\n StatisticsFolder = fullfile('EdgePriors');\n LoadFileName = sprintf('Statistics_Sc%d_Si%0.1f.mat',zooming,Gau_sigma);\n LoadData = load(fullfile(StatisticsFolder,LoadFileName));\n Statistics = LoadData.Statistics;\n \n RidgeMap = edge(I_s,'canny',[0 0.01],0.05);\n \n %Draw the canny detected edges to the cropped region\n mag_plus_edge_whole_image = T;\n% mag_plus_edge_whole_image(RidgeMap) = 0.2111;\n% CropRegion = mag_plus_edge_whole_image(257+1:257+1+12-1,50+1:50+1+9-1);\n% hfig = figure;\n% imagesc(CropRegion);\n% axis image off\n% caxis([0 0.7121]);\n% saveas(hfig, fullfile(folder_output, 'mag_region.png'));\n% close(hfig);\n \n% RidgeMap_inverted = ~RidgeMap;\n% imwrite(RidgeMap_inverted,fullfile(folder_output,'Canny.png'));\n\n %filter out small ridge and non-maximun ridges\n RidgeMap_filtered = RidgeMap;\n [r_set c_set] = find(RidgeMap);\n SetLength = length(r_set);\n for j=1:SetLength\n r = r_set(j);\n c = c_set(j);\n CenterMagValue = T(r,c);\n if CenterMagValue < LowMagSuppression\n RidgeMap_filtered(r,c) = false;\n end\n end\n \n\n [r_set c_set] = find(RidgeMap_filtered);\n SetLength = length(r_set);\n [X Y] = meshgrid(1:11,1:11);\n DistPatch = sqrt((X-6).^2 + (Y-6).^2);\n\n DistMap = inf(h,w); \n UsedPixel = false(h,w); \n CenterCoor = zeros(h,w,2); \n %Compute DistMap and CneterCoor\n [r_set c_set] = find(RidgeMap_filtered);\n for j=1:SetLength\n r = r_set(j);\n r1 = r-5;\n r2 = r+5;\n c = c_set(j);\n c1 = c-5;\n c2 = c+5;\n if r1>=1 && r2<=h && c1>=1 && c2<=w %discrad boundary?\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(11), c*ones(11));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %Convert dist to table index\n TableIndexMap = zeros(h,w);\n b = unique(DistPatch(:));\n for i=1:length(b)\n SetPixels = DistMap == b(i);\n TableIndexMap(SetPixels) = i;\n end\n\n \n %mapping (T_p, T_r, d) to S_p\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n UpdatedPixel = false(h,w);\n S = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n CurrentMagValue = T(r,c);\n BinIdx_Current = ceil(CurrentMagValue /0.005);\n %Zebra have super strong Mag\n if BinIdx_Current > 100\n BinIdx_Current = 100;\n end\n TableIndex = TableIndexMap(r,c);\n if TableIndex > DistanceUpperBound\n continue\n end\n CenterMagValue = T(r_Center,c_Center);\n %Low Mag Edge suppresion\n if CenterMagValue < LowMagSuppression\n continue\n end\n BinIdx_Center = ceil(CenterMagValue /0.005);\n if BinIdx_Center > 100\n BinIdx_Center = 100;\n end\n %consult the table\n if TableIndex == 1 %1 is the index of b(1) where dist = 0, enhance the contrast of pixel on edge \n S_p = ContrastEnhenceCoef * Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n else\n S_p = Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n end\n \n if isnan(S_p)\n else\n UpdatedPixel(r,c) = true;\n S(r,c) = S_p;\n end\n end\n\n %Record the RidgeMapMap, for computing te ProbOfMag\n %the Mag is the consulted Mag\n %here is the problem, when the S is very strong, the affect range of ProbMagOut exceeds 1 pixel\n RidgeMapMagValue = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n RidgeMapMagValue(r,c) = S(r_Center,c_Center);\n end \n \n S(~UpdatedPixel) = T(~UpdatedPixel);\n img_in = I_s;\n if min(Dissimilarity(:)) == 0\n d = Dissimilarity + 1e-6; %avoid 0 case; some images may have d(:,:,1) as 0\n else\n d = Dissimilarity;\n end\n ratio = d ./ repmat(d(:,:,1),[1,1,8]);\n %here is the problem, I need to amplify the gradient directionally \n Grad_in = Img2Grad(img_in);\n Product = Grad_in .* ratio;\n Sqr = Product.^2;\n Sum = sum(Sqr,3);\n Sqrt = sqrt(Sum); %the Sqrt might be 0, because Grad_in may be pure 0;\n r1 = S ./Sqrt;\n r1(isnan(r1)) = 0;\n\n Grad_exp = Grad_high_initial .*( ratio .*(repmat(r1,[1,1,8])));\n %consolidate inconsistatnt gradient\n NewGrad_exp = zeros(h,w,8);\n for k=1:4\n switch k\n case 1\n ShiftOp = [0 -1];\n case 2\n ShiftOp = [1 -1];\n case 3\n ShiftOp = [1 0];\n case 4\n ShiftOp = [1 1];\n end\n k2 =k+4;\n Grad1 = Grad_exp(:,:,k);\n Grad2 = Grad_exp(:,:,k2);\n Grad2Shift = circshift(Grad2,ShiftOp);\n Grad1Abs = abs(Grad1);\n Grad2AbsShift = abs(Grad2Shift);\n Grad1Larger = Grad1Abs > Grad2AbsShift;\n Grad2Larger = Grad2AbsShift > Grad1Abs;\n NewGrad1 = Grad1 .* Grad1Larger + (-Grad2Shift) .* Grad2Larger;\n NewGrad2Shift = Grad2Shift .* Grad2Larger + (-Grad1) .* Grad1Larger;\n NewGrad2 = circshift(NewGrad2Shift,-ShiftOp);\n NewGrad_exp(:,:,k) = NewGrad1;\n NewGrad_exp(:,:,k2) = NewGrad2;\n end\n %current problem is the over-enhanced gradient (NewMagExp too large)\n gradient_expected = NewGrad_exp;\n \n lambda_m = 2;\n m0 = 0;\n ProbMagOut = lambda_m * RidgeMapMagValue + m0;\n\n lambda_d = 0.25;\n d0 = 0.25;\n ProbDistMap = exp(- (lambda_d * DistMap + d0) ); %this coef should be decied by zooming\n\n Product = ProbMagOut .* ProbDistMap;\n weightmap_edge = min(Product,1); %the two terms are not sufficient, direction is not taken into considertion\n \n% if 0\n% bReport = true;\n% updatenumber = 0;\n% loopnumber = 1000;\n% linesearchstepnumber = 10;\n% beta0 = 1;\n% beta1 = 0.5^8;\n% tolf = 0.001;\n% img_edge = F4e_GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,Gau_sigma,bReport,...\n% loopnumber,updatenumber,linesearchstepnumber,beta0,beta1,tolf);\n% imwrite(img_edge, fullfile(folder_output, 'img_edge.png'));\n% \n% Compute the new magitude of gradients\n% mog_new = sqrt(sum(NewGrad_exp.^2,3));\n% hfig = figure;\n% imagesc(mog_new);\n% axis image off\n% saveas(hfig, fullfile(folder_output,'mog_new.png'));\n% range = caxis;\n% disp(range);\n% img_edge = F4b_GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,Gau_sigma,bReport);\n% gradient_actual = Img2Grad(img_edge);\n% compute the Map of edge weight\n% end\nend\nfunction Grad = Img2Grad(img)\n [h w] = size(img);\n Grad = zeros(h,w,8);\n DiffOp = RetGradientKernel();\n for i=1:8\n Grad(:,:,i) = imfilter(img,DiffOp{i},'replicate');\n end\nend\nfunction f = RetGradientKernel()\n f = cell(8,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\nend\nfunction Dissimilarity = EvaluateDissimilarity8(Img_in,PatchSize)\n if ~exist('PatchSize','var');\n PatchSize = 3;\n end\n [h w] = size(Img_in);\n Dissimilarity = zeros(h,w,8);\n \n f3x3 = ones(PatchSize)/(PatchSize^2);\n for i = 1:8\n DiffOp = RetGradientKernel8(i);\n Diff = imfilter(Img_in,DiffOp,'symmetric');\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Dissimilarity(:,:,i) = sqrt(Sum);\n end\nend\nfunction DiffOp = RetGradientKernel8(dir)\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n DiffOp = f{dir};\nend\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F38_ExtractFeatureFromAnImage.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F38_ExtractFeatureFromAnImage.m", "size": 694, "source_encoding": "utf_8", "md5": "796ddd477c92cf9e25510468665edb6c", "text": "%Chih-Yuan Yang\n%10/05/12\n%Extract features from an image\nfunction FeatureMatrix = F38_ExtractFeatureFromAnImage(img)\n %Extract the feature of A\n [h_lr, w_lr] = size(img);\n img_ext = zeros(h_lr+4,w_lr+4);\n img_ext(3:end-2,3:end-2) = img;\n img_ext(1:2,:) = repmat(img_ext(3,:),[2,1]);\n img_ext(end-1:end,:) = repmat(img_ext(end-2,:),[2,1]);\n img_ext(:,1:2) = repmat(img_ext(:,3),[1,2]);\n img_ext(:,end-1:end) = repmat(img_ext(:,end-2),[1,2]);\n FeatureMatrix = zeros(h_lr,w_lr,25);\n for cl=1:w_lr\n cl1 = cl+4;\n for rl=1:h_lr\n rl1 = rl+4;\n FeatureMatrix(rl,cl,:) = reshape(img_ext(rl:rl1,cl:cl1),[1 1 25]);\n end\n end\n\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F6b_RetriveAreaGradientsByAlign_Optimization_UseMask.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F6b_RetriveAreaGradientsByAlign_Optimization_UseMask.m", "size": 2353, "source_encoding": "utf_8", "md5": "2c4433d1fefd4815dbe26347121ed43d", "text": "%Chih-Yuan Yang\n%10/02/12\n%Use mask\nfunction [retrievedhrimage retrievedlrimage retrievedidx] = F6b_RetriveAreaGradientsByAlign_Optimization_UseMask(testimage_lr, ...\n rawexampleimage, inputpoints, basepoints, mask_lr, zooming, Gau_sigma)\n %the rawexampleimage should be double\n if ~isa(rawexampleimage,'uint8')\n error('wrong class');\n end\n% region_hr = F30_ConvertLRRegionToHRRegion(component_lr, zooming);\n\n exampleimagenumber = size(rawexampleimage,3);\n %find the transform matrix by solving an optimization problem\n alignedexampleimage_hr = zeros(480,640,exampleimagenumber,'uint8'); %set as uint8 to reduce memory demand\n alignedexampleimage_lr = zeros(120,160,exampleimagenumber);\n parfor i=1:exampleimagenumber\n alignedexampleimage_hr(:,:,i) = F18_AlignExampleImageByLandmarkSet(rawexampleimage(:,:,i),inputpoints(:,:,i),basepoints);\n %F19 automatically convert uint8 input to double\n alignedexampleimage_lr(:,:,i) = F19a_GenerateLRImage_GaussianKernel(alignedexampleimage_hr(:,:,i),zooming,Gau_sigma);\n end\n\n %crop the region\n% mask_lr = component_lr.mask_lr;\n [r_set c_set] = find(mask_lr);\n top = min(r_set);\n bottom = max(r_set);\n left = min(c_set);\n right = max(c_set);\n area_test = im2double(testimage_lr(top:bottom,left:right));\n area_mask = mask_lr(top:bottom,left:right);\n area_test_aftermask = area_test .* area_mask;\n %extract feature from the eyerange, the features are the gradient of LR eye region\n feature_test = U16_ExtractFeatureFromArea(area_test_aftermask); %the unit is double\n\n %search for the thousand example images to find the most similar eyerange\n normvalue = zeros(exampleimagenumber,1);\n parfor j=1:exampleimagenumber\n examplearea_lr = alignedexampleimage_lr(top:bottom,left:right,j);\n examplearea_lr_aftermask = examplearea_lr .* area_mask;\n feature_example_lr = U16_ExtractFeatureFromArea(examplearea_lr_aftermask); %the unit is double\n normvalue(j) = norm(feature_test - feature_example_lr);\n end\n %find the small norm\n [sortnorm ix] = sort(normvalue);\n %some of them are very similar\n\n %only return the 1nn\n retrievedhrimage = alignedexampleimage_hr(:,:,ix(1)); \n retrievedlrimage = alignedexampleimage_lr(:,:,ix(1));\n retrievedidx = ix(1);\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U8_DrawMultiPieLandmark.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U8_DrawMultiPieLandmark.m", "size": 736, "source_encoding": "utf_8", "md5": "f326688c3c7fefa8d2729e0cda85f104", "text": "%Chih-Yuan Yang\n%10/26/12\n%This file looks wierd, maybe retired.\nfunction U8_DrawMultiPieLandmark()\n %load image\n imagefolder = fullfile('Examples','Aligned_Gray');\n fnlist = dir(fullfile(imagefolder,'*.png'));\n fileidx = 2;\n fn = fnlist(fileidx).name;\n img = imread(fullfile(imagefolder,fn));\n \n %load landmark\n fn_landmark = fullfile('Examples','SavedData','BasePoints.mat');\n loaddata = load(fn_landmark);\n landmark = loaddata.alignedlandmarks_image(:,:,fileidx);\n \n %show image\n imshow(img);\n axis on\n hold on\n \n %show landmark\n plot(landmark(:,1),landmark(:,2),'r.');\n \n %show text\n for i=1:68\n text(landmark(i,1),landmark(i,2), sprintf('%d',i));\n end\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F40g_GetTexturePatchMatch_Aligned.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F40g_GetTexturePatchMatch_Aligned.m", "size": 3784, "source_encoding": "utf_8", "md5": "5b86f2751275fcef64f35bc25f94da74", "text": "%Chih-Yuan Yang\n%02/1/15\n%Replace F19a by F19c on line 53.\n%\n%I want to know how Sifei add her code in this file to improve the output images?\n%Use patchmatch to retrieve a texture background\n% patchmatch for Lab 3 channels\n% using stv\n%F40g: The parfor is unstable on some certain linux machines. Sometimes a worker does not\n%response. The reaosn in unknown. I guess it is an OS bug.\n%To ensure the process not being interrupted, I reduce the parfor to for.\nfunction [gradients_texture, img_color] = F40g_GetTexturePatchMatch_Aligned(img_y, ...\n hrexampleimages, lrexampleimages, landmarks_test, rawexamplelandmarks)\n\n %parameter\n numberofHcandidate = 10;\n \n% img_y = TV(img_y,0.05, 20);\n \n %start\n [h_lr, w_lr, ~, ~] = size(lrexampleimages);\n [h_hr, w_hr, cn, exampleimagenumber] = size(hrexampleimages);\n zooming = h_hr/h_lr;\n if zooming == 4\n Gau_sigma = 1.6;\n elseif zooming == 3\n Gau_sigma = 1.2;\n end\n alignedexampleimage_hr = zeros(h_hr, w_hr, cn, exampleimagenumber,'uint8'); %set as uint8 to reduce memory demand\n alignedexampleimage_lr = zeros(h_lr, w_lr, cn, exampleimagenumber);\n disp('align images');\n set = 28:48; %eyes and nose\n basepoints = landmarks_test(set,:);\n inputpoints = rawexamplelandmarks(set,:,:);\n \n for k=1:exampleimagenumber\n alignedexampleimage_hr(:,:,:,k) = F18_AlignExampleImageByLandmarkSet(hrexampleimages(:,:,:,k),inputpoints(:,:,k),basepoints);\n %F19 automatically convert uint8 input to double\n %alignedexampleimage_lr(:,:,:,k) = F19a_GenerateLRImage_GaussianKernel(alignedexampleimage_hr(:,:,:,k),zooming,Gau_sigma);\n alignedexampleimage_lr(:,:,:,k) = F19c_GenerateLRImage_GaussianKernel(alignedexampleimage_hr(:,:,:,k),zooming,Gau_sigma);\n end\n \n cores = 2; % Use more cores for more speed\n\n if cores==1\n algo = 'cpu';\n else\n algo = 'cputiled';\n end\n patchsize_lr = 5;\n nn_iters = 5;\n\n% A = repmat(img_y,[1 1 3]);\n testnumber = exampleimagenumber;\n xyandl2norm = zeros(h_lr,w_lr,3,testnumber,'int32');\n disp('patchmatching');\n for i=1:testnumber;\n %run patchmatch\n B = reshape(alignedexampleimage_lr(:,:,:,i),[h_lr, w_lr, 3]);\n xyandl2norm(:,:,:,i) = nnmex(img_y, B, algo, patchsize_lr, nn_iters, [], [], [], [], cores); %the return totalpatchnumber int32\n end\n l2norm_double = double(xyandl2norm(:,:,3,:));\n [sortedl2norm, ix] = sort(l2norm_double,4);\n hrpatchextractdata = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate,3); %ii,r_lr_src,c_lr_src\n %here\n hrpatchsimilarity = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate);\n parameter_l2normtosimilarity = 625;\n for rl = 1:h_lr-patchsize_lr+1\n for cl = 1:w_lr-patchsize_lr+1\n for k=1:numberofHcandidate\n knnidx = ix(rl,cl,1,k);\n x = xyandl2norm(rl,cl,1,knnidx); %start from 0\n y = xyandl2norm(rl,cl,2,knnidx);\n clsource = x+1;\n rlsource = y+1;\n hrpatchextractdata(rl,cl,k,:) = reshape([knnidx rlsource clsource],[1 1 1 3]);\n hrpatchsimilarity(rl,cl,k) = exp(-sortedl2norm(rl,cl,1,knnidx)/parameter_l2normtosimilarity);\n end\n end\n end\n \n hrpatch = F40_ExtractAllHrPatches(patchsize_lr,zooming, hrpatchextractdata,alignedexampleimage_hr);\n img_texture = IF4s_BuildHRimagefromHRPatches(hrpatch,zooming);\n %extract the graident\n %The T1_ImprovePatchMatch is the code Sifei adds.\n img_texture(:,:,1) = T1_ImprovePatchMatch(img_texture(:,:,1),img_y(:,:,1));\n gradients_texture = F14_Img2Grad(img_texture(:,:,1));\n img_color = img_texture(:,:,2:3);\nend\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F20_GenerateConstraintMatrix.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F20_GenerateConstraintMatrix.m", "size": 1185, "source_encoding": "utf_8", "md5": "67cab96bf9cde799d86f4c30d479f15d", "text": "%Chih-Yuan Yang\n%09/19/12\n%Generate the constraint matrix\nfunction Aeq = F20_GenerateConstraintMatrix(h_hr,w_hr,Gau_sigma,zooming)\n %parse I_l = (I_h \\otimes G) \\downarrow to\n %v_h = Aeq * v_h\n HRpixelnumber = h_hr*w_hr;\n n = HRpixelnumber;\n LRpixelnumber = HRpixelnumber / zooming^2;\n m = LRpixelnumber;\n vectori = zeros(121*HRpixelnumber,1);\n vectorj = zeros(121*HRpixelnumber,1);\n vectors = zeros(121*HRpixelnumber,1);\n G = Sigma2Kernel(Gau_sigma);\n h_lr = h_hr/zooming;\n w_lr = w_hr/zooming;\n idx = 0;\n for k=1:m\n fprintf('k %d totoal %d\\n',k,m);\n for t=1:n\n idx = idx + 1;\n img_test(r,c) = 1;\n img_lr = F19_GenerateLRImage_BlurSubSample(img_test,zooming,Gau_sigma);\n AColumn = reshape(img_lr,[LRpixelnumber,1]);\n nonzeroset = find(AColumn);\n setsize = length(nonzeroset);\n for k=1:setsize\n Aeq(k,idx) = AColumn(k);\n end\n c_old = c;\n end\n r_old = r;\n end\n \n nzmax = 121*HRpixelnumber; %in fact, it should be slightly smaller\n Aeq = sparse(vectori,vectorj,vectors,m, n,nzmax);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F4d_GenerateIntensityFromGradient.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F4d_GenerateIntensityFromGradient.m", "size": 4732, "source_encoding": "utf_8", "md5": "fcba5aeef2abaa0fa377f3b94af16360", "text": "%Chih-Yuan Yang\n%10/02/12\n%F4b: change first gradient from F19 to F19a, which uses a precise Gaussian kernel\n%F4c: F4b is too slow, change the parameters\n%F4d: open all parameters because they matter\n%Gradually incrase the coef of high-low term to achieve the contrained optimization problem\n%07/20/14 This function should be replace by F4e\n%function img_out = F4d_GenerateIntensityFromGradient(img_y,img_initial,Grad_exp,Gau_sigma,bReport,...\n% loopnumber,totalupdatenumber,linesearchstepnumber,beta0,beta1,tolf)\n% if nargin <= 6\n% linesearchstepnumber = 4;\n% loopnumber = 4;\n% totalupdatenumber = 4;\n% end\n \n zooming = size(img_initial,1)/size(img_y,1);\n if zooming ~= floor(zooming)\n error('zooming should be an integer');\n end\n \n I = img_initial;\n I_best = I;\n term_intensity_check = zeros(linesearchstepnumber,1);\n term_gradient_check = zeros(linesearchstepnumber,1);\n [h w] = size(img_initial);\n for updatenumber = 0:totalupdatenumber\n %beta0 = beta0_initial;\n %beta1 = beta1_initial * 0.5^updatenumber;\n for loop = 1:loopnumber\n %refine image by low-high intensity\n img_lr_gen = F19a_GenerateLRImage_GaussianKernel(I,zooming,Gau_sigma);\n diff_lr = img_lr_gen - img_y;\n diff_hr = IF5_Upsample(diff_lr,zooming, Gau_sigma);\n Grad0 = diff_hr;\n\n %refine image by expected gradeint\n %Gradient decent\n OptDir = Grad_exp - F14_Img2Grad(I);\n Grad1 = sum(OptDir,3);\n Grad_all = beta0 * Grad0 + beta1 * Grad1;\n\n I_in = I; %make a copy, restore the value if all beta fails\n tau_initial = 1;\n term_gradient_in = ComputeFunctionValue_Grad(I,Grad_exp);\n term_intensity_in = F28_ComputeSquareSumLowHighDiff(I,img_y,Gau_sigma);\n term_all_in = term_intensity_in * beta0 + term_gradient_in * beta1;\n for line_search_step=1:linesearchstepnumber\n tau = tau_initial * 0.5^(line_search_step-1);\n I_check = I_in - tau * Grad_all;\n term_gradient_check(line_search_step) = ComputeFunctionValue_Grad(I_check,Grad_exp);\n term_intensity_check(line_search_step) = F28_ComputeSquareSumLowHighDiff(I_check,img_y,Gau_sigma);\n end\n \n term_all_check = term_intensity_check * beta0 + term_gradient_check * beta1;\n [sortvalue ix] = sort(term_all_check);\n if sortvalue(1) < term_all_in\n %update \n search_step_best = ix(1);\n tau_best = tau_initial * 0.5^(search_step_best-1);\n I_best = I_in - tau_best * Grad_all;\n I = I_best; %assign the image for next loop\n term_best = sortvalue(1);\n else\n break;\n end\n if bReport\n fprintf(['updatenumber=%d, loop=%d, all_in=%0.3f, all_out=%0.3f, Intensity_in=%0.3f, Intensity_out=%0.3f, ' ...\n 'Grad_in=%0.3f, Grad_out=%0.3f\\n'],updatenumber, loop,term_all_in,term_best,term_intensity_in,...\n term_intensity_check(ix(1)), term_gradient_in,term_gradient_check(ix(1))); \n end\n if term_best > term_all_in - tolf\n break\n end\n end\n end\n img_out = I_best;\nend\nfunction diff_hr = IF5_Upsample(diff_lr,zooming, Gau_sigma)\n [h w] = size(diff_lr);\n h_hr = h*zooming;\n w_hr = w*zooming;\n upsampled = zeros(h_hr,w_hr);\n if zooming == 3\n for rl = 1:h\n rh = (rl-1) * zooming + 2;\n for cl = 1:c\n ch = (cl-1) * zooming + 2;\n upsampled(rh,ch) = diff_lr(rl,cl);\n end\n end\n kernel = Sigma2Kernel(Gau_sigma);\n diff_hr = imfilter(upsampled,kernel,'replicate');\n elseif zooming == 4\n %compute the kernel by ourself, assuming the range is \n %control the kernel and the position of the diff\n kernelsize = ceil(Gau_sigma * 3)*2+2; %+2 this is the even number\n kernel = fspecial('gaussian',kernelsize,Gau_sigma);\n %subsample diff_lr to (3,3), because of the result of imfilter\n for rl = 1:h\n rh = (rl-1) * zooming + 3;\n for cl = 1:w\n ch = (cl-1) * zooming + 3;\n upsampled(rh,ch) = diff_lr(rl,cl);\n end\n end\n diff_hr = imfilter(upsampled, kernel,'replicate');\n else\n error('not processed');\n end\nend\n\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = F14_Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F19f_GenerateLRImage_IntegerSF.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F19f_GenerateLRImage_IntegerSF.m", "size": 1830, "source_encoding": "utf_8", "md5": "356ce4df12515a899936c1aab37368db", "text": "%Chih-Yuan Yang\n%09/28/12\n%Change the method of subsampling\n%F19f 03/20/14 update the function to accept integer scaling factors\nfunction img_lr = F19f_GenerateLRImage_IntegerSF(img_hr,sf,sigma)\n if isa(img_hr,'uint8')\n img_hr = im2double(img_hr);\n end\n [h_hr, w_hr, d] = size(img_hr);\n h_hr_trim = h_hr-mod(h_hr,sf);\n w_hr_trim = w_hr-mod(w_hr,sf);\n img_hr_trim = img_hr(1:h_hr_trim,1:w_hr_trim,1:d);\n h_lr = h_hr_trim/sf;\n w_lr = w_hr_trim/sf;\n \n %detect image type\n if mod(sf,2) == 1 %an odd number\n kernelsize = ceil(sigma*3)*2+1;\n kernel = fspecial('gaussian',kernelsize,sigma); %kernel is always a symmetric matrix\n img_blur = zeros(img_hr_trim,wtrim,d);\n for idx_d = 1:d\n img_blur(:,:,idx_d) = imfilter(img_hr_trim(:,:,idx_d),kernel,'replicate');\n end\n img_lr = imresize(img_blur,1/sf,'nearest');\n elseif mod(sf,2) == 0 %s is even\n sampleshift = sf/2;\n kernelsize = ceil(sigma*3)*2+2;\n kernel = fspecial('gaussian',kernelsize,sigma); %kernel is always a symmetric matrix\n img_blur = imfilter(img_hr_trim,kernel,'replicate');\n img_lr = zeros(h_lr,w_lr,d);\n for idx_d = 1:d\n for rl=1:h_lr\n r_hr_sample = (rl-1)*sf+sampleshift; %the shift is the key issue, because the effect of imfilter using a kernel\n %shapened in even number width is equivalent to a 0.5 pixel shift in the\n %original image\n for cl = 1:w_lr\n c_hr_sample = (cl-1)*sf+sampleshift;\n img_lr(rl,cl,idx_d) = img_blur(r_hr_sample,c_hr_sample,idx_d);\n end\n end\n end\n end \n \nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F6_RetriveAreaGradientsByAlign_Optimization.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F6_RetriveAreaGradientsByAlign_Optimization.m", "size": 2325, "source_encoding": "utf_8", "md5": "0208f2f45a168987c2d33991fa7059b8", "text": "%Chih-Yuan Yang\n%09/30/12\n%change rawexampleimage to uint8 to save memroy\nfunction gradientcandidate = F6_RetriveAreaGradientsByAlign_Optimization(testimage_lr, rawexampleimage, inputpoints, basepoints, region_lr, zooming, Gau_sigma)\n %the rawexampleimage should be double\n if ~isa(rawexampleimage,'uint8')\n error('wrong class');\n end\n region_hr = F30_ConvertLRRegionToHRRegion(region_lr, zooming);\n\n exampleimagenumber = size(rawexampleimage,3);\n %find the transform matrix by solving an optimization problem\n alignedexampleimage_hr = zeros(480,640,exampleimagenumber,'uint8'); %set as uint8 to reduce memory demand\n alignedexampleimage_lr = zeros(120,160,exampleimagenumber);\n parfor i=1:exampleimagenumber\n alignedexampleimage_hr(:,:,i) = F18_AlignExampleImageByLandmarkSet(rawexampleimage(:,:,i),inputpoints(:,:,i),basepoints);\n %F19 automatically convert uint8 input to double\n alignedexampleimage_lr(:,:,i) = F19a_GenerateLRImage_GaussianKernel(alignedexampleimage_hr(:,:,i),zooming,Gau_sigma);\n end\n\n %crop the region\n area_test = im2double(testimage_lr(region_lr.top_idx:region_lr.bottom_idx,region_lr.left_idx:region_lr.right_idx));\n %extract feature from the eyerange, the features are the gradient of LR eye region\n feature_test = U16_ExtractFeatureFromArea(area_test); %the unit is double\n\n %search for the thousand example images to find the most similar eyerange\n normvalue = zeros(exampleimagenumber,1);\n parfor j=1:exampleimagenumber\n examplearea_lr = alignedexampleimage_lr(region_lr.top_idx:region_lr.bottom_idx,region_lr.left_idx:region_lr.right_idx,j);\n feature_example_lr = U16_ExtractFeatureFromArea(examplearea_lr); %the unit is double\n normvalue(j) = norm(feature_test - feature_example_lr);\n end\n %find the small norm\n [sortnorm ix] = sort(normvalue);\n %some of them are very similar\n %mostsimilarindex = ix(1:20);\n\n gradientcandidate = zeros(region_hr.height,region_hr.width,8,1); %the 3rd dim is dx and dy\n %parfor j=1:20\n j=1;\n examplehrregion = alignedexampleimage_hr(region_hr.top_idx:region_hr.bottom_idx,region_hr.left_idx:region_hr.right_idx,ix(j));\n gradientcandidate(:,:,:,j) = F14_Img2Grad(im2double(examplehrregion));\n %end\n\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F23_SortFileListByNumber.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F23_SortFileListByNumber.m", "size": 990, "source_encoding": "utf_8", "md5": "93452adb03ef10957d88c1db09ecefa9", "text": "%Chih-Yuan Yang\n%09/21/12\n%the default dir() result is sorted by string, but Windows and MATLAB sort file name by number\n%make the \nfunction filelist_out = F23_SortFileListByNumber(filelist,appendix)\n listlength = length(filelist);\n filelist_out(1:listlength,1) = struct('name',[]);\n allnameasnumber = zeros(listlength,1);\n% extrecord = cell(listlength,1);\n% namerecord = cell(listlength,1);\n if ~exist('appendix','var');\n appendix = [];\n end\n for i=1:listlength\n fn_original = filelist(i).name;\n k = strfind(fn_original, appendix);\n fn_number = fn_original(1:k-1);\n allnameasnumber(i) = str2double(fn_number);\n% extrecord{i} = ext; %the ext includes dot.\n% namerecord{i} = fn_number;\n end\n %sort all the number\n [~, ix] = sort(allnameasnumber);\n \n %write it to filelist_out\n for i=1:listlength\n originalidx = ix(i);\n filelist_out(i).name = filelist(originalidx).name;\n end\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F18_AlignExampleImageByLandmarkSet.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F18_AlignExampleImageByLandmarkSet.m", "size": 1893, "source_encoding": "utf_8", "md5": "d9d9c52a4c78f4637dcb032e3b7c5ea4", "text": "%Chih-Yuan Yang\n%09/15/12\n%Change function name from U20 to F18\n%The different from U17: There are 20 points, solve an optimization problem to determine the trasnform matrix\nfunction alignedexampleimage = F18_AlignExampleImageByLandmarkSet(exampleimage,inputpoints,basepoints)\n %use shift and scaling only as the initial variables\n initial_shift = mean(basepoints(:,:)) - mean(inputpoints(:,1));\n initial_deltax = initial_shift(1);\n initial_deltay = initial_shift(2);\n initial_lambda = 1;\n initial_theta = 0;\n initial_variable = [initial_theta, initial_lambda, initial_deltax, initial_deltay];\n \n %solve the optimization problem\n options = optimset('Display','off','TolX',1e-4);\n [x fval]= fminsearch(@(x) OptProblem(x,inputpoints,basepoints), initial_variable, options);\n\n theta = x(1);\n lambda = x(2);\n deltax = x(3);\n deltay = x(4);\n transformmatrix = [lambda*cos(theta) -lambda*sin(theta) deltax;\n lambda*sin(theta) lambda*cos(theta) deltay];\n %take two points most apart to generate input points\n inputpoint1 = inputpoints(1,:)';\n setsize = size(inputpoints,1);\n dxdy = inputpoints - repmat(inputpoints(1,:),[setsize,1]);\n distsqr = sum(dxdy.^2,2);\n [sortresults ix] = sort(distsqr,'descend');\n farestpointidx = ix(1);\n inputpoint2 = inputpoints(farestpointidx,:)';\n inputpoints_2points = cat(1, inputpoint1',inputpoint2');\n basepoint1 = transformmatrix * cat(1,inputpoint1,1);\n basepoint2 = transformmatrix * cat(1,inputpoint2,1);\n basepoints_2points = cat(1, basepoint1', basepoint2');\n \n [h w d] = size(exampleimage);\n tform = cp2tform(inputpoints_2points, basepoints_2points,'nonreflective similarity');\n %generated the transform images\n XData = [1 w];\n YData = [1 h];\n alignedexampleimage = imtransform(exampleimage,tform,'XData',XData,'YData',YData);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F6c_RetriveImage_Mask_GlassAware.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F6c_RetriveImage_Mask_GlassAware.m", "size": 2404, "source_encoding": "utf_8", "md5": "e34dbf69cc41d28b122b89bcee79968c", "text": "%Chih-Yuan Yang\n%10/03/12\n%Use mask\nfunction [retrievedhrimage retrievedlrimage retrievedidx] = F6c_RetriveImage_Mask_GlassAware(testimage_lr, ...\n rawexampleimage, inputpoints, basepoints, mask_lr, zooming, Gau_sigma, glasslist, bglassavoid)\n %the rawexampleimage should be double\n if ~isa(rawexampleimage,'uint8')\n error('wrong class');\n end\n\n exampleimagenumber = size(rawexampleimage,3);\n %find the transform matrix by solving an optimization problem\n alignedexampleimage_hr = zeros(480,640,exampleimagenumber,'uint8'); %set as uint8 to reduce memory demand\n alignedexampleimage_lr = zeros(120,160,exampleimagenumber);\n parfor i=1:exampleimagenumber\n alignedexampleimage_hr(:,:,i) = F18_AlignExampleImageByLandmarkSet(rawexampleimage(:,:,i),inputpoints(:,:,i),basepoints);\n %F19 automatically convert uint8 input to double\n alignedexampleimage_lr(:,:,i) = F19a_GenerateLRImage_GaussianKernel(alignedexampleimage_hr(:,:,i),zooming,Gau_sigma);\n end\n\n [r_set c_set] = find(mask_lr);\n top = min(r_set);\n bottom = max(r_set);\n left = min(c_set);\n right = max(c_set);\n area_test = im2double(testimage_lr(top:bottom,left:right));\n area_mask = mask_lr(top:bottom,left:right);\n area_test_aftermask = area_test .* area_mask;\n %extract feature from the eyerange, the features are the gradient of LR eye region\n feature_test = F24_ExtractFeatureFromArea(area_test_aftermask); %the unit is double\n\n %search for the thousand example images to find the most similar eyerange\n normvalue = zeros(exampleimagenumber,1);\n parfor j=1:exampleimagenumber\n examplearea_lr = alignedexampleimage_lr(top:bottom,left:right,j);\n examplearea_lr_aftermask = examplearea_lr .* area_mask;\n feature_example_lr = F24_ExtractFeatureFromArea(examplearea_lr_aftermask); %the unit is double\n normvalue(j) = norm(feature_test - feature_example_lr);\n end\n %find the small norm\n [sortnorm ix] = sort(normvalue);\n %some of them are very similar\n\n %only return the 1nn\n if bglassavoid\n for k=1:exampleimagenumber\n if glasslist(ix(k)) == false\n break\n end\n end\n else\n k =1;\n end\n retrievedhrimage = alignedexampleimage_hr(:,:,ix(k)); \n retrievedlrimage = alignedexampleimage_lr(:,:,ix(k));\n retrievedidx = ix(k);\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F4b_GenerateIntensityFromGradJpeg.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F4b_GenerateIntensityFromGradJpeg.m", "size": 4914, "source_encoding": "utf_8", "md5": "4462f9d0490b3751c31e2d846b998083", "text": "%Chih-Yuan Yang\n%09/29/12\n%F4b: change first gradient from F19 to F19a, which uses a precise Gaussian kernel\n%Gradually incrase the coef of high-low term to achieve the contrained optimization problem\n% modify beta0_initial from 1 to 0.2\nfunction img_out = F4b_GenerateIntensityFromGradJpeg(img_y,img_initial,Grad_exp,Gau_sigma,bReport,quality)\n \n LoopNumber = 30;\n beta0_initial = 0.2; %beginning\n beta1_initial = 1;\n \n zooming = size(img_initial,1)/size(img_y,1);\n if zooming ~= floor(zooming)\n error('zooming should be an integer');\n end\n \n I = img_initial;\n linesearchstepnumber = 20;\n term_intensity_check = zeros(linesearchstepnumber,1);\n term_gradient_check = zeros(linesearchstepnumber,1);\n [h w] = size(img_initial);\n for updatenumber = 0:10\n beta0 = beta0_initial;\n beta1 = beta1_initial * 0.5^updatenumber;\n for loop = 1:LoopNumber\n %refine image by low-high intensity\n% img_lr_gen = F19a_GenerateLRImage_GaussianKernel(I,zooming,Gau_sigma);\n %This is Sifei's new code\n %I have a question about the function. For the JANUS inputs, how can Sifei know the quality index?\n %The logic is not sound.\n %I need to check her code for the JANUS input.\n img_lr_gen = F19b_GenerateLRImage_jpeg(I,zooming,Gau_sigma,quality);\n% img_lr_gen = img_lr_gen.image;\n diff_lr = img_lr_gen - img_y;\n %I am worry about this step. Is it correct to backproject the difference of JPEG images?\n diff_hr = IF5_Upsample(diff_lr,zooming, Gau_sigma);\n Grad0 = diff_hr;\n\n %refine image by expected gradeint\n %Gradient decent\n OptDir = Grad_exp - F14_Img2Grad(I);\n Grad1 = sum(OptDir,3);\n Grad_all = beta0 * Grad0 + beta1 * Grad1;\n\n I_in = I; %make a copy, restore the value if all beta fails\n tau_initial = 1;\n term_gradient_in = ComputeFunctionValue_Grad(I,Grad_exp);\n term_intensity_in = F28_ComputeSquareSumLowHighDiff(I,img_y,Gau_sigma);\n term_all_in = term_intensity_in * beta0 + term_gradient_in * beta1;\n for line_search_step=1:linesearchstepnumber %try to change here for speed up\n tau = tau_initial * 0.5^(line_search_step-1);\n I_check = I_in - tau * Grad_all;\n term_gradient_check(line_search_step) = ComputeFunctionValue_Grad(I_check,Grad_exp);\n term_intensity_check(line_search_step) = F28_ComputeSquareSumLowHighDiff(I_check,img_y,Gau_sigma);\n end\n \n term_all_check = term_intensity_check * beta0 + term_gradient_check * beta1;\n [sortvalue ix] = sort(term_all_check);\n if sortvalue(1) < term_all_in\n %update \n search_step_best = ix(1);\n tau_best = tau_initial * 0.5^(search_step_best-1);\n I_best = I_in - tau_best * Grad_all;\n I = I_best; %assign the image for next loop\n else\n break;\n end\n if bReport\n fprintf(['updatenumber=%d, loop=%d, all_in=%0.3f, all_out=%0.3f, Intensity_in=%0.3f, Intensity_out=%0.3f, ' ...\n 'Grad_in=%0.3f, Grad_out=%0.3f\\n'],updatenumber, loop,term_all_in,sortvalue(1),term_intensity_in,...\n term_intensity_check(ix(1)), term_gradient_in,term_gradient_check(ix(1))); \n end\n end\n end\n img_out = I_best;\nend\nfunction diff_hr = IF5_Upsample(diff_lr,zooming, Gau_sigma)\n [h w] = size(diff_lr);\n h_hr = h*zooming;\n w_hr = w*zooming;\n upsampled = zeros(h_hr,w_hr);\n if zooming == 3\n for rl = 1:h\n rh = (rl-1) * zooming + 2;\n for cl = 1:c\n ch = (cl-1) * zooming + 2;\n upsampled(rh,ch) = diff_lr(rl,cl);\n end\n end\n kernel = Sigma2Kernel(Gau_sigma);\n diff_hr = imfilter(upsampled,kernel,'replicate');\n elseif zooming == 4\n %compute the kernel by ourself, assuming the range is \n %control the kernel and the position of the diff\n kernelsize = ceil(Gau_sigma * 3)*2+2; %+2 this is the even number\n kernel = fspecial('gaussian',kernelsize,Gau_sigma);\n %subsample diff_lr to (3,3), because of the result of imfilter\n for rl = 1:h\n rh = (rl-1) * zooming + 3;\n for cl = 1:w\n ch = (cl-1) * zooming + 3;\n upsampled(rh,ch) = diff_lr(rl,cl);\n end\n end\n diff_hr = imfilter(upsampled, kernel,'replicate');\n else\n error('not processed');\n end\nend\n\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = F14_Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F30_ConvertLRRegionToHRRegion.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F30_ConvertLRRegionToHRRegion.m", "size": 511, "source_encoding": "utf_8", "md5": "db8198d99827980659f952b348395601", "text": "%Chih-Yuan Yang\n%09/29/12\n%Change name from U18 to F30\nfunction region_hr = F30_ConvertLRRegionToHRRegion(region_lr, zooming)\n region_hr.left_idx = (region_lr.left_idx-1) * zooming + 1;\n region_hr.top_idx = (region_lr.top_idx-1) * zooming + 1;\n region_hr.right_idx = region_lr.right_idx * zooming;\n region_hr.bottom_idx = region_lr.bottom_idx * zooming;\n region_hr.width = region_hr.right_idx - region_hr.left_idx + 1;\n region_hr.height = region_hr.bottom_idx - region_hr.top_idx + 1; \nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U5a_ReadGlassList.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U5a_ReadGlassList.m", "size": 307, "source_encoding": "utf_8", "md5": "99bdfffdcaf70473ea6d9875ebb03729", "text": "%Chih-Yuan Yang\n%2/20/15\n%U5: read list from a file and return it as an cell array\n%U5a: read glass list\nfunction [arr_label, arr_filename] = U5a_ReadGlassList( fn_list )\n fid = fopen(fn_list,'r');\n C = textscan(fid,'%05d %s %d\\n');\n fclose(fid);\n arr_filename = C{2};\n arr_label = C{3};\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U21b_DrawLandmarks_Points_ReturnHandle.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U21b_DrawLandmarks_Points_ReturnHandle.m", "size": 910, "source_encoding": "utf_8", "md5": "9b61a9bd6c2605b4d6b55de9c1a9ac98", "text": "%Chih-Yuan Yang\n%09/15/12\n%Sometimes the format of landmarks are coordinates rather than boxes\n%U21b 03/19/14 update the fucntion, the bdrawpose does not work\nfunction hfig = U21b_DrawLandmarks_Points_ReturnHandle(im, points, str_pose,bshownumbers,bdrawpose,bvisible)\n if bvisible\n hfig = figure;\n else\n hfig = figure('Visible','off');\n end\n imshow(im);\n hold on;\n axis image;\n axis off;\n\n setnumber = size(points,1);\n if bdrawpose\n tx = (min(points(:,1)) + max(points(:,1)))/2; %tx means half face width\n ty = min(points(:,2)) - tx; \n text(tx,ty, str_pose,'fontsize',18,'color','c');\n end\n for i=1:setnumber\n x = points(i,1);\n y = points(i,2);\n \n plot(x,y,'r.','markersize',9);\n if bshownumbers\n text(x,y, num2str(i), 'fontsize',9,'color','k');\n end\n end\n drawnow;\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F17_AlignExampleImageByLandmarkSet.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F17_AlignExampleImageByLandmarkSet.m", "size": 2024, "source_encoding": "utf_8", "md5": "70407314c6fb6afdfca2155287efb245", "text": "%Chih-Yuan Yang\n%09/15/12\n%return alignedpoints for paper writing\nfunction [alignedexampleimage alignedpoints]= F17_AlignExampleImageByLandmarkSet(exampleimage,inputpoints,basepoints)\n %inputpoints format: m x 2, m is the number of points\n %use shift and scaling only as the initial variables\n initial_shift = mean(basepoints(:,:)) - mean(inputpoints(:,1));\n initial_deltax = initial_shift(1);\n initial_deltay = initial_shift(2);\n initial_lambda = 1;\n initial_theta = 0;\n initial_variable = [initial_theta, initial_lambda, initial_deltax, initial_deltay];\n \n %solve the optimization problem\n options = optimset('Display','off','TolX',1e-4);\n [x fval]= fminsearch(@(x) OptProblem(x,inputpoints,basepoints), initial_variable, options);\n\n theta = x(1);\n lambda = x(2);\n deltax = x(3);\n deltay = x(4);\n transformmatrix = [lambda*cos(theta) -lambda*sin(theta) deltax;\n lambda*sin(theta) lambda*cos(theta) deltay];\n %take two points most apart to generate input points\n inputpoint1 = inputpoints(1,:)';\n setsize = size(inputpoints,1);\n dxdy = inputpoints - repmat(inputpoints(1,:),[setsize,1]);\n distsqr = sum(dxdy.^2,2);\n [sortresults ix] = sort(distsqr,'descend');\n farestpointidx = ix(1);\n inputpoint2 = inputpoints(farestpointidx,:)';\n inputpoints_2points = cat(1, inputpoint1',inputpoint2');\n basepoint1 = transformmatrix * cat(1,inputpoint1,1);\n basepoint2 = transformmatrix * cat(1,inputpoint2,1);\n basepoints_2points = cat(1, basepoint1', basepoint2');\n \n [h w d] = size(exampleimage);\n tform = cp2tform(inputpoints_2points, basepoints_2points,'nonreflective similarity');\n %generated the transform images\n XData = [1 w];\n YData = [1 h];\n alignedexampleimage = imtransform(exampleimage,tform,'XData',XData,'YData',YData);\n \n %compute the aligned points\n alignedpoints_tranlate = transformmatrix * cat(1,inputpoints',ones(1,setsize));\n alignedpoints = alignedpoints_tranlate';\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "OptProblem.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/OptProblem.m", "size": 483, "source_encoding": "utf_8", "md5": "bad41a87910a8d55c3f72a4067909992", "text": "%09/06/12\n%Chih-Yuan Yang\nfunction value = OptProblem(x,inputpoints,basepoints)\n theta = x(1);\n lambda = x(2);\n deltax = x(3);\n deltay = x(4);\n pointnumber = size(inputpoints,1);\n transformmatrix = [lambda*cos(theta) -lambda*sin(theta) deltax;\n lambda*sin(theta) lambda*cos(theta) deltay];\n newxy = transformmatrix * cat(1, inputpoints', ones(1,pointnumber));\n diff = basepoints - newxy';\n sqr = diff .^2;\n value = sum(sqr(:));\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F16a_ACCV12TextureGradientNotIntensity.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F16a_ACCV12TextureGradientNotIntensity.m", "size": 48117, "source_encoding": "utf_8", "md5": "fc71ab06a0f444e4b47f80161a3e11c3", "text": "%Chih-Yuan Yang\n%09/19/12\n%load sfall, srecall, allHRexampleimages before this function\nfunction gradients_merge = F16a_ACCV12TextureGradientNotIntensity(img_y, zooming, Gau_sigma ,sfall,srecall,allHRexampleimages)\n if zooming == 4\n para.Gau_sigma = 1.6;\n elseif zooming == 3\n para.Gau_sigma = 1.2;\n end\n \n %change here, return gradient rather than intensity\n %[img_edge reliablemap_edge] = IF1_EdgePreserving(img_y,para,zooming,Gau_sigma);\n [gradients_edge weightmap_edge] = IF1a_EdgePreserving(img_y,para,zooming,Gau_sigma);\n \n \n [h_lr w_lr] = size(img_y);\n para.lh = h_lr;\n para.lw = w_lr;\n para.NumberOfHCandidate = 10;\n para.SimilarityFunctionSettingNumber = 1;\n %load all data set to save loading time\n [scanr scanra] = SearchExternalPatches(img_y,para,sfall,srecall);\n para.zooming = zooming;\n para.ps = 5;\n para.Gau_sigma = Gau_sigma;\n hrpatch = F8_ExtractAllHrPatches(img_y, para, scanr,allHRexampleimages);\n [scanr_self scanra_self] = F22_SearchForSelfSimilarPatchesL2Norm(img_y,para);\n para.ehrfKernelWidth = 1.0;\n para.bEnablemhrf = true;\n [img_texture weightmap_texture] = F11_FilterOutImproperHrPatches(img_y,hrpatch,para,scanr_self,scanra_self,scanr,scanra);\n %apply backprojection on img_texture only\n iternum = 10;\n% img_texture_backproject = F11_BackProjection(img_y, img_texture, Gau_sigma, iternum);\n breport = true;\n disp('backprojection for img_texture in ACCV12');\n img_texture_backproject = IF3_BackProjection(img_y, img_texture, Gau_sigma, iternum,breport);\n \n %extract the graident\n gradients_texture = Img2Grad(img_texture_backproject);\n \n gradients_merge = gradients_texture .* repmat(weightmap_texture,[1,1,8]) + gradients_edge .* repmat(weightmap_edge,[1,1,8]);\n %debug, generate the intensity\n %img_initial = imresize(img_y,zooming);\n %bReport = true;\n %img_merge = GenerateIntensityFromGradient(img_y,img_initial,gradients_merge,para,zooming,Gau_sigma,bReport);\n %keyboard\n %nomi = img_texture_backproject.*weightmap_texture + img_edge .* weightmap_edge;\n %denomi = reliablemap_edge + weightmap_texture;\n %img_hr = nomi ./ denomi;\n %there are some 0 value of denomi around boundary\n %fill these pixels as img_edge\n %nanpixels = isnan(img_hr);\n %img_hr(nanpixels) = img_edge(nanpixels);\n %ensure there is no nan\n %if nnz(isnan(img_hr))\n % error('should not be here');\n %end\nend\nfunction [scanr scanra] = SearchExternalPatches(img_y,para,sfall,srecall)\n %how to search parallelly to speed up?\n ps = 5; %patch size\n [lh lw] = size(img_y);\n hrpatchnumber = 10;\n %featurefolder = para.featurefolder;\n sh = GetShGeneral(ps);\n scanr = zeros(6,hrpatchnumber,lh-ps+1,lw-ps+1); %scan results, mm, quan, ii, sr, sc, similairty\n smallvalue = -1;\n scanr(6,:,:,:) = smallvalue;\n scanra = zeros(lh-ps+1,lw-ps+1); %scan results active\n %scanrsimmax = smallvalue * ones(lh-ps+1,lw-ps+1); %del this line?\n quanarray = [1 2 4 8 16 32];\n B = [256 128 64 32 16 8];\n imlyi = im2uint8(img_y);\n for qidx=1:6\n quan = quanarray(qidx);\n b = B(qidx);\n \n cur_initial = floor(size(sfall{1},2)/2); %accelerate the loop by using an initial position\n for rl=1:lh-ps+1\n fprintf('look for lut rl:%d quan:%d\\n',rl,quan);\n for cl = 1:lw-ps+1\n patch = imlyi(rl:rl+ps-1,cl:cl+ps-1);\n fq = patch(sh);\n if qidx == 1\n fquan = fq;\n else\n fquan = fq - mod(fq,quan) + quan/2;\n end\n\n [iila mma] = LookForLookUpTable9_External(fquan,sfall{qidx},cur_initial,para); %index in lookuptable\n in = length(iila); %always return 20 instance\n for i=1:in\n ii = srecall{qidx}(1,iila(i)); \n sr = srecall{qidx}(2,iila(i));\n sc = srecall{qidx}(3,iila(i));\n %check whether the patch is in the scanr already\n bSamePatch = false;\n for j=1:scanra(rl,cl)\n if ii == scanr(3,j,rl,cl) && sr == scanr(4,j,rl,cl) && sc == scanr(5,j,rl,cl)\n bSamePatch = true;\n break\n end\n end\n\n if bSamePatch == false\n similarity = bmm2similarity(b,mma(i),para.SimilarityFunctionSettingNumber);\n if scanra(rl,cl) < hrpatchnumber\n ix = scanra(rl,cl) + 1;\n %to do: update scanr by similarity\n %need to double it, otherwise, the int6 will kill similarity\n scanr(:,ix,rl,cl) = cat(1,mma(i),quan,double(ii),double(sr),double(sc),similarity);\n scanra(rl,cl) = ix;\n else\n [minval ix] = min(scanr(6,:,rl,cl));\n if scanr(6,ix,rl,cl) < similarity\n %update\n scanr(:,ix,rl,cl) = cat(1,mma(i),quan,double(ii),double(sr),double(sc),similarity); \n end\n end\n end\n end\n end\n end\n end\nend\nfunction [iila mma] = LookForLookUpTable9_External(fq,lut,cur_initial,para)\n hrpatchnumber = para.NumberOfHCandidate; %default 10\n fl = length(fq); %feature length\n head = 1;\n tail = size(lut,2);\n lutsize = size(lut,2);\n if exist('cur_initial','var')\n if cur_initial > lutsize\n cur = lutsize;\n else\n cur = cur_initial;\n end\n else\n cur = round(lutsize/2);\n end\n cur_rec1 = cur;\n %initial comparison\n fqsmaller = -1;\n fqlarger = 1;\n fqsame = 0;\n cr = 0; %compare results\n mm = 0;\n mmiil = 0;\n %search for the largest mm\n while 1\n for c=1:fl\n if fq(c) < lut(c,cur)\n cr = fqsmaller;\n break\n elseif fq(c) > lut(c,cur)\n cr = fqlarger;\n break; %c moves to next\n else %equal\n cr = fqsame;\n if mm < c\n mm = c;\n mmiil = cur;\n end \n end\n end\n \n if cr == fqsmaller\n next = floor((cur + head)/2);\n tail = cur; %adjust the range of head and tail\n elseif cr == fqlarger;\n next = ceil((cur + tail)/2); %the round function has to be floor, because fq is larger than cur\n %otherwise the fully 255 patches will never match\n head = cur; %adjust the range of head and tail\n end\n \n if mm == 25 %it happens, the initial one match the fq, therefore, there is no next defined.\n break\n end\n if cur == next || cur_rec1 == next %the next might oscilate\n break;\n else\n cur_rec1 = cur;\n cur = next;\n end\n %fprintf('cur %d\\n',cur);\n end\n\n if mm == 0 \n iila = [];\n mma = [];\n return\n end\n %post-process to find the repeated partial vectors\n %search for previous\n idx = 1;\n iila = zeros(hrpatchnumber,1);\n mma = zeros(hrpatchnumber,1);\n iila(idx) = mmiil;\n mma(idx) = mm;\n bprecontinue = true;\n bproccontinue = true;\n \n presh = 0; %previous shift\n procsh = 0; %proceeding shift\n while 1\n presh = presh -1;\n iilpre = mmiil + presh;\n if iilpre <1\n bprecontinue = false;\n premm = 0;\n end\n procsh = procsh +1;\n iilproc = mmiil + procsh;\n if iilproc > lutsize\n bproccontinue = false;\n procmm = 0;\n end\n \n if bprecontinue \n diff = lut(:,iilpre) ~= fq;\n if nnz(diff) == 0\n premm = 25;\n else\n premm = find(diff,1,'first') -1;\n end\n end\n\n if bproccontinue\n diff = lut(:,iilproc) ~= fq;\n if nnz(diff) == 0\n procmm = 25;\n else\n procmm = find(diff,1,'first') -1;\n end\n end\n \n if premm == 0 && procmm == 0\n break\n end\n if premm > procmm\n %add pre item\n idx = idx + 1;\n iila(idx) = iilpre;\n mma(idx) = premm;\n %pause the proc\n bprecontinue = true;\n elseif premm < procmm\n %add proc item\n idx = idx + 1;\n iila(idx) = iilproc;\n mma(idx) = procmm;\n %pause the pre\n bproccontinue = true;\n else %premm == procmm\n %add both item\n idx = idx + 1;\n iila(idx) = iilpre;\n mma(idx) = premm;\n \n if idx == hrpatchnumber\n break\n end\n idx = idx + 1;\n iila(idx) = iilproc;\n mma(idx) = procmm; \n bproccontinue = true;\n bprecontinue = true;\n end\n if idx == hrpatchnumber\n break\n end\n end\n\n if idx < hrpatchnumber\n iila = iila(1:idx);\n mma = mma(1:idx);\n end\nend\nfunction s = bmm2similarity(b,mm,SimilarityFunctionSettingNumber)\n if SimilarityFunctionSettingNumber == 1\n if mm >= 9\n Smm = 0.9 + 0.1*(mm-9)/16;\n else\n Smm = 0.5 * mm/9;\n end\n\n Sb = 0.5+0.5*(log2(b)-3)/5;\n s = Sb * Smm;\n elseif SimilarityFunctionSettingNumber == 2\n Smm = mm/25;\n Sb = (log2(b)-2)/6;\n s = Sb * Smm;\n end\nend\nfunction hrpatch = F8_ExtractAllHrPatches(img_y, para, scanr,allHRexampleimages)\n disp('extracting HR patches');\n %how to search parallelly to speed up?\n psh = para.ps * para.zooming;\n ps = para.ps;\n lh = para.lh;\n lw = para.lw;\n s = para.zooming;\n hrpatchnumber = para.NumberOfHCandidate;\n hrpatch = zeros(psh,psh,lh-ps+1,lw-ps+1,hrpatchnumber);\n allimages = allHRexampleimages;\n \n %analyize which images need to be loaded\n alliiset = scanr(3,:,:,:);\n alliiset_uni = unique(alliiset(:)); %allmost all images are used, from 1 to 1500\n if alliiset_uni(1) ~= 0\n alliiset_uni_pure = alliiset_uni;\n else\n alliiset_uni_pure = alliiset_uni(2:end);\n end\n\n for i = 1:length(alliiset_uni_pure)\n ii = alliiset_uni_pure(i);\n\n exampleimage_hr = im2double(allimages(:,:,ii));\n\n exampleimage_lr = U3_GenerateLRImage_BlurSubSample(exampleimage_hr,para.zooming,para.Gau_sigma);\n match_4D = alliiset == ii;\n match_3D = reshape(match_4D,hrpatchnumber,lh-ps+1,lw-ps+1); %remove the first dimension\n [d1 d2 d3] = size(match_3D); %second dimention length\n [idxset posset] = find(match_3D);\n setin = length(idxset);\n for j = 1:setin\n idx = idxset(j);\n possum = posset(j);\n pos3 = floor( (possum-1)/d2) +1; %the relationship: possum = (pos3-1) * d2 + pos2, pos2 in (1,d2)\n pos2 = possum - (pos3-1)*d2;\n\n rl = pos2;\n cl = pos3;\n \n sr = scanr(4,idx,rl,cl);\n sc = scanr(5,idx,rl,cl);\n \n srh = (sr-1)*s+1;\n srh1 = srh + psh -1;\n sch = (sc-1)*s+1;\n sch1 = sch + psh-1;\n\n %to do: compensate the HR patch to match the LR query patch\n hrp = exampleimage_hr(srh:srh1,sch:sch1); %HR patch \n lrq = img_y(rl:rl+ps-1,cl:cl+ps-1); %LR query patch\n lrr = exampleimage_lr(sr:sr+ps-1,sc:sc+ps-1); %LR retrieved patch\n chrp = hrp + imresize(lrq - lrr,s,'bilinear'); %compensate HR patch\n hrpatch(:,:,rl,cl,idx) = chrp;\n \n bVisuallyCheck = false;\n if bVisuallyCheck\n if ~exist('hfig','var')\n hfig = figure;\n else\n figure(hfig);\n end\n subplot(1,4,1);\n imshow(hrp/255);\n title('hrp');\n subplot(1,4,2);\n imshow(lrr/255);\n title('lrr');\n subplot(1,4,3);\n imshow(lrq/255);\n title('lrq');\n subplot(1,4,4);\n imshow(chrp/255);\n title('chrp');\n keyboard\n end\n end \n end\nend\nfunction [img_texture Reliablemap] = F11_FilterOutImproperHrPatches(img_y,hrpatch,para,scanr_self,scanra_self,scanr,scanra)\n %filter out improper hr patches using similarity among lr patches\n %load the self-similar data\n s = para.zooming;\n lh = para.lh;\n lw = para.lw;\n ps = para.ps;\n psh = s * para.ps;\n patcharea = para.ps^2;\n\n\n SSnumberUpperbound = 10;\n \n %do I still need these variables?\n cqarray = zeros(32,1)/0;\n for qidx = 1:6\n quan = 2^(qidx-1);\n cqvalue = 0.9^(qidx-1);\n cqarray(quan) = cqvalue;\n end\n \n hh = lh * s;\n hw = lw * s;\n hrres_nomi = zeros(hh,hw);\n hrres_deno = zeros(hh,hw);\n maskmatrix = false(psh,psh,patcharea);\n Reliablemap = zeros(hh,hw);\n \n pshs = psh * psh; \n for i=1:patcharea\n [sh_notsued masklow maskhigh] = GetShGeneral(ps,i,true,s); %ps, mm, bhigh, s\n maskmatrix(:,:,i) = maskhigh;\n end\n mhr = zeros(5*s);\n r1 = 2*s+1;\n r2 = 3*s;\n c1 = 2*s+1;\n c2 = 3*s;\n mhr(r1:r2,c1:c2) = 1; %the central part\n sigma = para.ehrfKernelWidth;\n kernel = Sigma2Kernel(sigma);\n if para.bEnablemhrf\n mhrf = imfilter(mhr,kernel,'replicate');\n else\n mhrf = mhr;\n end\n\n noHmap = scanra == 0;\n noHmapToFill = noHmap;\n NHOOD = [0 1 0;\n 1 1 1;\n 0 1 0];\n se = strel('arbitrary',NHOOD);\n noHmapneighbor = and( imdilate(noHmap,se) ,~noHmap);\n %if the noHmapsever is 0, it is fine\n \n imb = imresize(img_y,s); %use it as the reference if no F is available\n \n rsa = [0 -1 0 1];\n csa = [1 0 -1 0];\n for rl= 1:lh-ps+1 %75\n fprintf('rl:%d total:%d\\n',rl,lh-ps+1);\n rh = (rl-1)*s+1;\n rh1 = rh+psh-1;\n for cl = 1:lw-ps+1 %128\n ch = (cl-1)*s+1;\n ch1 = ch+psh-1;\n \n %load candidates\n hin = para.NumberOfHCandidate;\n H = zeros(psh,psh,hin);\n HSim = zeros(hin,1);\n for j=1:hin\n H(:,:,j) = hrpatch(:,:,rl,cl,j); %H\n HSim(j) = scanr(6,j,rl,cl);\n end\n \n %compute the number of reference patches\n sspin = min(SSnumberUpperbound,scanra_self(rl,cl)); \n %self similar patch instance number\n F = zeros(ps,ps,sspin);\n FSimPure = zeros(1,sspin);\n rin = 0;\n for i=1:sspin\n sr = scanr_self(3,i,rl,cl);\n sc = scanr_self(4,i,rl,cl);\n %hr candidate number\n rin = rin + para.NumberOfHCandidate;\n F(:,:,i) = img_y(sr:sr+ps-1,sc:sc+ps-1);\n FSimPure(i) = scanr_self(5,i,rl,cl);\n end\n \n %load all of the two step patches\n R = zeros(psh,psh,rin);\n mms = zeros(rin,1);\n mmr = zeros(rin,1);\n qs = zeros(rin,1);\n qr = zeros(rin,1);\n FSimBaseR = zeros(rin,1); \n RSim = zeros(rin,1);\n idx = 0;\n if sspin > 0\n for i=1:sspin %sspin is the Fin\n sr = scanr_self(3,i,rl,cl);\n sc = scanr_self(4,i,rl,cl);\n %hr candidate number\n hrcanin = para.NumberOfHCandidate;\n for j=1:hrcanin\n idx = idx + 1;\n R(:,:,idx) = hrpatch(:,:,sr,sc,j);\n mms(idx) = scanr_self(1,i,rl,cl);\n qs(idx) = scanr_self(2,i,rl,cl);\n mmr(idx) = scanr(1,j,sr,sc);\n qr(idx) = scanr(2,j,sr,sc);\n FSimBaseR(idx) = FSimPure(i);\n RSim(idx) = scanr(6,j,sr,sc);\n end\n end\n else\n idx = 1;\n rin = 1; %use bicubic \n R(:,:,idx) = imb(rh:rh1,ch:ch1);\n FSimBaseR(idx) = 1;FSimPure(i);\n end\n\n %here is a question, how to define the similarity between H and R?\n %L2norm?\n hscore = zeros(hin,1);\n for i=1:hin\n theH = H(:,:,i);\n for j=1:rin\n theR = R(:,:,j);\n spf = FSimBaseR(j);\n %similarity between H and R\n diff = theH - theR;\n L2N = norm(diff(:));\n shr = exp(- L2N/pshs);\n hscore(i) = hscore(i) + shr*spf;\n end\n end\n [maxscore idx] = max(hscore);\n %take this as the example\n Reliablemap(rh:rh1,ch:ch1) = Reliablemap(rh:rh1,ch:ch1) + HSim(idx)*mhrf;\n \n if hin > 0 %some patches can't find H\n hrres_nomi(rh:rh1,ch:ch1) = hrres_nomi(rh:rh1,ch:ch1) + H(:,:,idx).*mhrf;\n hrres_deno(rh:rh1,ch:ch1) = hrres_deno(rh:rh1,ch:ch1) + mhrf; \n end\n %if any of its neighbor belongs to noHmap, copy additional region to hrres\n %if the pixel belongs to noHmapneighbor, then expand the copy regions\n if noHmapneighbor(rl,cl) == true\n mhrfspecial = zeros(5*s);\n mhrfspecial(r1:r2,c1:c2) = 1;\n for i=1:4\n rs = rsa(i);\n cs = csa(i);\n checkr = rl+rs;\n checkc = cl+cs;\n if checkr > 0 && checkr < lh-ps+1 && checkc >0 && checkc =1 && r2<=h && c1>=1 && c2<=w %discrad boundary?\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(11), c*ones(11));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %Convert dist to table index\n TableIndexMap = zeros(h,w);\n b = unique(DistPatch(:));\n for i=1:length(b)\n SetPixels = DistMap == b(i);\n TableIndexMap(SetPixels) = i;\n end\n\n \n %mapping (T_p, T_r, d) to S_p\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n UpdatedPixel = false(h,w);\n S = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n CurrentMagValue = T(r,c);\n BinIdx_Current = ceil(CurrentMagValue /0.005);\n %Zebra have super strong Mag\n if BinIdx_Current > 100\n BinIdx_Current = 100;\n end\n TableIndex = TableIndexMap(r,c);\n if TableIndex > para.DistanceUpperBound\n continue\n end\n CenterMagValue = T(r_Center,c_Center);\n %Low Mag Edge suppresion\n if CenterMagValue < para.LowMagSuppression\n continue\n end\n BinIdx_Center = ceil(CenterMagValue /0.005);\n if BinIdx_Center > 100\n BinIdx_Center = 100;\n end\n %consult the table\n if TableIndex == 1 %1 is the index of b(1) where dist = 0, enhance the contrast of pixel on edge \n S_p = para.ContrastEnhenceCoef * Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n else\n S_p = Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n end\n \n if isnan(S_p)\n else\n UpdatedPixel(r,c) = true;\n S(r,c) = S_p;\n end\n end\n\n %Record the RidgeMapMap, for computing te ProbOfMag\n %the Mag is the consulted Mag\n %here is the problem, when the S is very strong, the affect range of ProbMagOut exceeds 1 pixel\n RidgeMapMagValue = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n RidgeMapMagValue(r,c) = S(r_Center,c_Center);\n end \n \n S(~UpdatedPixel) = T(~UpdatedPixel);\n img_in = I_s;\n if min(Dissimilarity(:)) == 0\n d = Dissimilarity + 1e-6; %avoid 0 case; some images may have d(:,:,1) as 0\n else\n d = Dissimilarity;\n end\n ratio = d ./ repmat(d(:,:,1),[1,1,8]);\n %here is the problem, I need to amplify the gradient directionally \n Grad_in = Img2Grad(img_in);\n Product = Grad_in .* ratio;\n Sqr = Product.^2;\n Sum = sum(Sqr,3);\n Sqrt = sqrt(Sum); %the Sqrt might be 0, because Grad_in may be pure 0;\n r1 = S ./Sqrt;\n r1(isnan(r1)) = 0;\n\n Grad_exp = Grad_high_initial .*( ratio .*(repmat(r1,[1,1,8])));\n %consolidate inconsistatnt gradient\n NewGrad_exp = zeros(h,w,8);\n for k=1:4\n switch k\n case 1\n ShiftOp = [0 -1];\n case 2\n ShiftOp = [1 -1];\n case 3\n ShiftOp = [1 0];\n case 4\n ShiftOp = [1 1];\n end\n k2 =k+4;\n Grad1 = Grad_exp(:,:,k);\n Grad2 = Grad_exp(:,:,k2);\n Grad2Shift = circshift(Grad2,ShiftOp);\n Grad1Abs = abs(Grad1);\n Grad2AbsShift = abs(Grad2Shift);\n Grad1Larger = Grad1Abs > Grad2AbsShift;\n Grad2Larger = Grad2AbsShift > Grad1Abs;\n NewGrad1 = Grad1 .* Grad1Larger + (-Grad2Shift) .* Grad2Larger;\n NewGrad2Shift = Grad2Shift .* Grad2Larger + (-Grad1) .* Grad1Larger;\n NewGrad2 = circshift(NewGrad2Shift,-ShiftOp);\n NewGrad_exp(:,:,k) = NewGrad1;\n NewGrad_exp(:,:,k2) = NewGrad2;\n end\n %current problem is the over-enhanced gradient (NewMagExp too large)\n\n para.bReport = true;\n img_edge = GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,para,zooming,Gau_sigma);\n\n %compute the Map of edge weight\n lambda_m = 2;\n m0 = 0;\n ProbMagOut = lambda_m * RidgeMapMagValue + m0;\n\n lambda_d = 0.25;\n d0 = 0.25;\n ProbDistMap = exp(- (lambda_d * DistMap + d0) ); %this coef should be decied by zooming\n \n Product = ProbMagOut .* ProbDistMap;\n ProbOfEdge = min(Product,1); %the two terms are not sufficient, direction is not taken into considertion\nend\nfunction [gradients_edge weightmap_edge] = IF1a_EdgePreserving(img_y,para,zooming,Gau_sigma)\n para.LowMagSuppression = 0;\n para.DistanceUpperBound = 2.0;\n para.ContrastEnhenceCoef = 1.0;\n I_s = IF2_SmoothnessPreservingFunction(img_y,para,zooming);\n T = F15_ComputeSRSSD(I_s);\n Dissimilarity = EvaluateDissimilarity8(I_s);\n Grad_high_initial = Img2Grad(I_s);\n \n %SaveFolder = para.tuningfolder;\n \n [h w] = size(T);\n StatisticsFolder = fullfile('EdgePriors');\n LoadFileName = sprintf('Statistics_Sc%d_Si%0.1f.mat',zooming,Gau_sigma);\n LoadData = load(fullfile(StatisticsFolder,LoadFileName));\n Statistics = LoadData.Statistics;\n \n RidgeMap = edge(I_s,'canny',[0 0.01],0.05);\n\n %filter out small ridge and non-maximun ridges\n RidgeMap_filtered = RidgeMap;\n [r_set c_set] = find(RidgeMap);\n SetLength = length(r_set);\n for j=1:SetLength\n r = r_set(j);\n c = c_set(j);\n CenterMagValue = T(r,c);\n if CenterMagValue < para.LowMagSuppression\n RidgeMap_filtered(r,c) = false;\n end\n end\n \n\n [r_set c_set] = find(RidgeMap_filtered);\n SetLength = length(r_set);\n [X Y] = meshgrid(1:11,1:11);\n DistPatch = sqrt((X-6).^2 + (Y-6).^2);\n\n DistMap = inf(h,w); \n UsedPixel = false(h,w); \n CenterCoor = zeros(h,w,2); \n %Compute DistMap and CneterCoor\n [r_set c_set] = find(RidgeMap_filtered);\n for j=1:SetLength\n r = r_set(j);\n r1 = r-5;\n r2 = r+5;\n c = c_set(j);\n c1 = c-5;\n c2 = c+5;\n if r1>=1 && r2<=h && c1>=1 && c2<=w %discrad boundary?\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(11), c*ones(11));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %Convert dist to table index\n TableIndexMap = zeros(h,w);\n b = unique(DistPatch(:));\n for i=1:length(b)\n SetPixels = DistMap == b(i);\n TableIndexMap(SetPixels) = i;\n end\n\n \n %mapping (T_p, T_r, d) to S_p\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n UpdatedPixel = false(h,w);\n S = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n CurrentMagValue = T(r,c);\n BinIdx_Current = ceil(CurrentMagValue /0.005);\n %Zebra have super strong Mag\n if BinIdx_Current > 100\n BinIdx_Current = 100;\n end\n TableIndex = TableIndexMap(r,c);\n if TableIndex > para.DistanceUpperBound\n continue\n end\n CenterMagValue = T(r_Center,c_Center);\n %Low Mag Edge suppresion\n if CenterMagValue < para.LowMagSuppression\n continue\n end\n BinIdx_Center = ceil(CenterMagValue /0.005);\n if BinIdx_Center > 100\n BinIdx_Center = 100;\n end\n %consult the table\n if TableIndex == 1 %1 is the index of b(1) where dist = 0, enhance the contrast of pixel on edge \n S_p = para.ContrastEnhenceCoef * Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n else\n S_p = Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n end\n \n if isnan(S_p)\n else\n UpdatedPixel(r,c) = true;\n S(r,c) = S_p;\n end\n end\n\n %Record the RidgeMapMap, for computing te ProbOfMag\n %the Mag is the consulted Mag\n %here is the problem, when the S is very strong, the affect range of ProbMagOut exceeds 1 pixel\n RidgeMapMagValue = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n RidgeMapMagValue(r,c) = S(r_Center,c_Center);\n end \n \n S(~UpdatedPixel) = T(~UpdatedPixel);\n img_in = I_s;\n if min(Dissimilarity(:)) == 0\n d = Dissimilarity + 1e-6; %avoid 0 case; some images may have d(:,:,1) as 0\n else\n d = Dissimilarity;\n end\n ratio = d ./ repmat(d(:,:,1),[1,1,8]);\n %here is the problem, I need to amplify the gradient directionally \n Grad_in = Img2Grad(img_in);\n Product = Grad_in .* ratio;\n Sqr = Product.^2;\n Sum = sum(Sqr,3);\n Sqrt = sqrt(Sum); %the Sqrt might be 0, because Grad_in may be pure 0;\n r1 = S ./Sqrt;\n r1(isnan(r1)) = 0;\n\n Grad_exp = Grad_high_initial .*( ratio .*(repmat(r1,[1,1,8])));\n %consolidate inconsistatnt gradient\n NewGrad_exp = zeros(h,w,8);\n for k=1:4\n switch k\n case 1\n ShiftOp = [0 -1];\n case 2\n ShiftOp = [1 -1];\n case 3\n ShiftOp = [1 0];\n case 4\n ShiftOp = [1 1];\n end\n k2 =k+4;\n Grad1 = Grad_exp(:,:,k);\n Grad2 = Grad_exp(:,:,k2);\n Grad2Shift = circshift(Grad2,ShiftOp);\n Grad1Abs = abs(Grad1);\n Grad2AbsShift = abs(Grad2Shift);\n Grad1Larger = Grad1Abs > Grad2AbsShift;\n Grad2Larger = Grad2AbsShift > Grad1Abs;\n NewGrad1 = Grad1 .* Grad1Larger + (-Grad2Shift) .* Grad2Larger;\n NewGrad2Shift = Grad2Shift .* Grad2Larger + (-Grad1) .* Grad1Larger;\n NewGrad2 = circshift(NewGrad2Shift,-ShiftOp);\n NewGrad_exp(:,:,k) = NewGrad1;\n NewGrad_exp(:,:,k2) = NewGrad2;\n end\n %current problem is the over-enhanced gradient (NewMagExp too large)\n gradients_edge = NewGrad_exp;\n \n% para.bReport = true;\n% img_edge = GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,para,zooming,Gau_sigma);\n\n %compute the Map of edge weight\n lambda_m = 2;\n m0 = 0;\n ProbMagOut = lambda_m * RidgeMapMagValue + m0;\n\n lambda_d = 0.25;\n d0 = 0.25;\n ProbDistMap = exp(- (lambda_d * DistMap + d0) ); %this coef should be decied by zooming\n \n Product = ProbMagOut .* ProbDistMap;\n weightmap_edge = min(Product,1); %the two terms are not sufficient, direction is not taken into considertion\nend\nfunction img_out = IF2_SmoothnessPreservingFunction(img_y,para,zooming)\n img_bb = imresize(img_y,zooming);\n Kernel = Sigma2Kernel(para.Gau_sigma);\n\n %compute the similarity from low\n Coef = 10;\n PatchSize = 3;\n Sqrt_low = SimilarityEvaluation(img_y,PatchSize);\n Similarity_low = exp(-Sqrt_low*Coef);\n [h_high w_high] = size(img_bb);\n ExpectedSimilarity = zeros(h_high,w_high,16);\n %upsamplin the similarity\n for dir=1:16\n ExpectedSimilarity(:,:,dir) = imresize(Similarity_low(:,:,dir),zooming,'bilinear');\n end\n \n %refind the Grad_high by Similarity_high\n LoopNumber = 10;\n img = img_bb;\n for loop = 1:LoopNumber\n %refine gradient by ExpectedSimilarity\n ValueSum = zeros(h_high,w_high);\n WeightSum = sum(ExpectedSimilarity,3); %if thw weight sum is low, it is unsuitable to generate the grad by interpolation\n for dir = 1:16\n [MoveOp N] = GetMoveKernel16(dir);\n if N == 1\n MovedData = imfilter(img,MoveOp{1},'replicate');\n else %N ==2\n MovedData1 = imfilter(img,MoveOp{1},'replicate');\n MovedData2 = imfilter(img,MoveOp{2},'replicate');\n MovedData = (MovedData1 + MovedData2)/2;\n end\n Product = MovedData .* ExpectedSimilarity(:,:,dir);\n ValueSum = ValueSum + Product;\n end\n I = ValueSum ./ WeightSum;\n \n %intensity compensate\n Diff = imresize(imfilter(I,Kernel,'replicate'),1/zooming, 'nearest') - img_y;\n UpSampled = imresize(Diff,zooming,'bilinear');\n Grad0 = imfilter(UpSampled,Kernel,'replicate');\n Term_LowHigh_in = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n I_in = I; %make a copy, restore the value if all beta fails\n bDecrease = false;\n tau = 0.2;\n for line_search_loop=1:10\n %line search for the beta, fixed 1/32 is not a good choice\n I = I_in - tau * Grad0;\n Term_LowHigh_out = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n if Term_LowHigh_out < Term_LowHigh_in\n bDecrease = true;\n break;\n else\n tau = tau * 0.5;\n end\n end\n \n if bDecrease == true\n I_best = I;\n else\n break;\n end\n% fprintf('loop=%d, LowHihg_in=%0.1f, LowHigh_out=%0.1f,\\n',loop,Term_LowHigh_in,Term_LowHigh_out); \n \n% imwrite(I,fullfile(SaveFolder, [num2str(loop) '_GenIntenFromGrad.png']));\n img = I_best;\n end\n img_out = img;\n\nend\nfunction SqrtData = SimilarityEvaluation(Img_in,PatchSize)\n HalfPatchSize = (PatchSize-1)/2;\n [h w] = size(Img_in);\n SqrtData = zeros(h,w,16);\n \n f3x3 = ones(3);\n for i = 1:16\n [DiffOp N] = RetGradientKernel16(i);\n if N == 1\n Diff = imfilter(Img_in,DiffOp{1},'symmetric');\n else\n Diff1 = imfilter(Img_in,DiffOp{1},'symmetric');\n Diff2 = imfilter(Img_in,DiffOp{2},'symmetric');\n Diff = (Diff1+Diff2)/2;\n end\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Mean = Sum/9;\n SqrtData(:,:,i) = sqrt(Mean);\n end\nend\nfunction [DiffOp N] = RetGradientKernel16(dir)\n DiffOp = cell(2,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n DiffOp{1} = f{1};\n DiffOp{2} = [];\n case 2\n N = 2;\n DiffOp{1} = f{1};\n DiffOp{2} = f{2};\n case 3\n N = 1; \n DiffOp{1} = f{2};\n DiffOp{2} = [];\n case 4\n N = 2;\n DiffOp{1} = f{2};\n DiffOp{2} = f{3};\n case 5\n N = 1;\n DiffOp{1} = f{3};\n DiffOp{2} = [];\n case 6\n N = 2;\n DiffOp{1} = f{3};\n DiffOp{2} = f{4};\n case 7\n N = 1;\n DiffOp{1} = f{4};\n DiffOp{2} = [];\n case 8\n N = 2;\n DiffOp{1} = f{4};\n DiffOp{2} = f{5};\n case 9\n N = 1;\n DiffOp{1} = f{5};\n DiffOp{2} = [];\n case 10\n N = 2;\n DiffOp{1} = f{5};\n DiffOp{2} = f{6};\n case 11\n DiffOp{1} = f{6};\n DiffOp{2} = [];\n N = 1;\n case 12\n N = 2;\n DiffOp{1} = f{6};\n DiffOp{2} = f{7};\n case 13\n N = 1;\n DiffOp{1} = f{7};\n DiffOp{2} = [];\n case 14\n N = 2;\n DiffOp{1} = f{7};\n DiffOp{2} = f{8};\n case 15\n DiffOp{1} = f{8};\n DiffOp{2} = [];\n N = 1;\n case 16\n N = 2;\n DiffOp{1} = f{8};\n DiffOp{2} = f{1};\n end\nend\nfunction [Kernel N] = GetMoveKernel16(dir)\n Kernel = cell(2,1);\n f{1} = [0 0 0;\n 0 0 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 0 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 0 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 0 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 0 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 0 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 0 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 0 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n Kernel{1} = f{1};\n Kernel{2} = [];\n case 2\n N = 2;\n Kernel{1} = f{1};\n Kernel{2} = f{2};\n case 3\n N = 1; \n Kernel{1} = f{2};\n Kernel{2} = [];\n case 4\n N = 2;\n Kernel{1} = f{2};\n Kernel{2} = f{3};\n case 5\n N = 1;\n Kernel{1} = f{3};\n Kernel{2} = [];\n case 6\n N = 2;\n Kernel{1} = f{3};\n Kernel{2} = f{4};\n case 7\n N = 1;\n Kernel{1} = f{4};\n Kernel{2} = [];\n case 8\n N = 2;\n Kernel{1} = f{4};\n Kernel{2} = f{5};\n case 9\n N = 1;\n Kernel{1} = f{5};\n Kernel{2} = [];\n case 10\n N = 2;\n Kernel{1} = f{5};\n Kernel{2} = f{6};\n case 11\n Kernel{1} = f{6};\n Kernel{2} = [];\n N = 1;\n case 12\n N = 2;\n Kernel{1} = f{6};\n Kernel{2} = f{7};\n case 13\n N = 1;\n Kernel{1} = f{7};\n Kernel{2} = [];\n case 14\n N = 2;\n Kernel{1} = f{7};\n Kernel{2} = f{8};\n case 15\n Kernel{1} = f{8};\n Kernel{2} = [];\n N = 1;\n case 16\n N = 2;\n Kernel{1} = f{8};\n Kernel{2} = f{1};\n end\nend\nfunction f = ComputeFunctionValue_lowhigh(img,img_low,Gau_sigma)\n KernelSize = ceil(Gau_sigma) * 3 + 1;\n G = fspecial('gaussian',KernelSize,Gau_sigma);\n Conv = imfilter(img,G,'replicate');\n SubSample = imresize(Conv,size(img_low),'antialias',false);\n Diff = SubSample - img_low;\n Sqr = Diff.^2;\n f = sum(Sqr(:));\nend\nfunction Grad = Img2Grad(img)\n [h w] = size(img);\n Grad = zeros(h,w,8);\n DiffOp = RetGradientKernel();\n for i=1:8\n Grad(:,:,i) = imfilter(img,DiffOp{i},'replicate');\n end\nend\nfunction f = RetGradientKernel()\n f = cell(8,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\nend\nfunction Dissimilarity = EvaluateDissimilarity8(Img_in,PatchSize)\n if ~exist('PatchSize','var');\n PatchSize = 3;\n end\n [h w] = size(Img_in);\n Dissimilarity = zeros(h,w,8);\n \n f3x3 = ones(PatchSize)/(PatchSize^2);\n for i = 1:8\n DiffOp = RetGradientKernel8(i);\n Diff = imfilter(Img_in,DiffOp,'symmetric');\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Dissimilarity(:,:,i) = sqrt(Sum);\n end\nend\nfunction DiffOp = RetGradientKernel8(dir)\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n DiffOp = f{dir};\nend\nfunction img_out = GenerateIntensityFromGradient(img_y,img_initial,Grad_exp,para,zooming,Gau_sigma,bReport)\n if ~isfield(para,'LoopNumber')\n para.LoopNumber = 30;\n end\n if ~isfield(para,'beta0')\n beta0 = 1;\n else\n beta0 = para.beta0;\n end\n if ~isfield(para,'beta1')\n beta1 = 1;\n else\n beta1 = para.beta1;\n end\n \n Kernel = Sigma2Kernel(Gau_sigma);\n \n %compute gradient\n I = img_initial;\n I_best = I;\n for loop = 1:para.LoopNumber\n %refine image by patch similarity\n\n %refine image by low-high intensity\n Diff = imresize(imfilter(I,Kernel,'replicate'),1/zooming, 'nearest') - img_y;\n UpSampled = imresize(Diff,zooming,'bilinear');\n Grad0 = imfilter(UpSampled,Kernel,'replicate');\n \n %refine image by expected gradeint\n %Gradient decent\n %I = ModifyByGradient(I,Grad_exp);\n OptDir = Grad_exp - Img2Grad(I);\n Grad1 = sum(OptDir,3);\n Grad_all = beta0 * Grad0 + beta1 * Grad1;\n \n I_in = I; %make a copy, restore the value if all beta fails\n bDecrease = false;\n tau = 0.2;\n Term_Grad_in = ComputeFunctionValue_Grad(I,Grad_exp);\n Term_LowHigh_in = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n Term_all_in = Term_LowHigh_in * beta0 + Term_Grad_in * beta1;\n for line_search_loop=1:10\n %line search for the beta, fixed 1/32 is not a good choice\n I = I_in - tau * Grad_all;\n Term_Grad_out = ComputeFunctionValue_Grad(I,Grad_exp);\n Term_LowHigh_out = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n Term_all_out = Term_LowHigh_out * beta0 + Term_Grad_out * beta1;\n \n if Term_all_out < Term_all_in\n bDecrease = true;\n break;\n else\n tau = tau * 0.5;\n end\n end\n \n if bDecrease == true\n I_best = I;\n else\n break;\n end\n if bReport\n fprintf(['loop=%d, all_in=%0.1f, all_out=%0.1f, LowHihg_in=%0.1f, LowHigh_out=%0.1f, ' ...\n 'Grad_in=%0.1f, Grad_out=%0.1f\\n'],loop,Term_all_in,Term_all_out,Term_LowHigh_in,Term_LowHigh_out, ...\n Term_Grad_in,Term_Grad_out); \n end\n end\n img_out = I_best;\nend\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend\nfunction lrimg = U3_GenerateLRImage_BlurSubSample(hrimg,s,sigma)\n [h w d] = size(hrimg);\n htrim = h-mod(h,s);\n wtrim = w-mod(w,s);\n imtrim = hrimg(1:htrim,1:wtrim,1:d);\n \n %detect image type\n kernel = Sigma2Kernel(sigma);\n if d == 1\n blurimg = imfilter(imtrim,kernel,'replicate');\n elseif d == 3\n blurimg = zeros(htrim,wtrim,d);\n for i=1:3\n blurimg(:,:,i) = imfilter(imtrim(:,:,i),kernel,'replicate');\n end\n end\n lrimg = imresize(blurimg,1/s,'bilinear','antialias',false);\nend\nfunction img_bp = F11_BackProjection(img_lr, img_hr, Gau_sigma, iternum)\n [h_hr] = size(img_hr,1);\n [h_lr] = size(img_lr,1);\n zooming = h_hr/h_lr;\n for i=1:iternum\n img_lr_gen = U3_GenerateLRImage_BlurSubSample(img_hr,zooming,Gau_sigma);\n diff_lr = img_lr - img_lr_gen;\n diff_hr = imresize(diff_lr,zooming,'bilinear');\n img_hr = img_hr + diff_hr;\n end\n img_bp = img_hr;\nend\nfunction img_bp = IF3_BackProjection(img_lr, img_hr, Gau_sigma, iternum,bReport)\n [h_hr] = size(img_hr,1);\n [h_lr] = size(img_lr,1);\n zooming = h_hr/h_lr;\n for i=1:iternum\n img_lr_gen = F19_GenerateLRImage_BlurSubSample(img_hr,zooming,Gau_sigma);\n diff_lr = img_lr - img_lr_gen;\n term_diff_lr_SSD = sum(sum(diff_lr.^2));\n \n %here is the problem. How to guide this step? Assume the relative intensity unchange?\n diff_hr = imresize(diff_lr,zooming,'bilinear');\n img_hr = img_hr + diff_hr;\n img_lr_new = F19_GenerateLRImage_BlurSubSample(img_hr,zooming,Gau_sigma);\n diff_lr_new = img_lr - img_lr_new; \n term_diff_lr_SSD_afteronebackprojection = sum(sum(diff_lr_new.^2));\n if bReport\n fprintf('backproject iteration=%d, term_before=%0.1f, term_after=%0.1f\\n', ...\n i,term_diff_lr_SSD,term_diff_lr_SSD_afteronebackprojection); \n end \n end\n img_bp = img_hr;\nend\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U9_DrawMultiPieLandmarkVisualCheck.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U9_DrawMultiPieLandmarkVisualCheck.m", "size": 504, "source_encoding": "utf_8", "md5": "3f1349d55d7d68600170460c93193816", "text": "%Chih-Yuan Yang\n%10/01/12\nfunction hfig = U9_DrawMultiPieLandmarkVisualCheck(image,landmark,bshowtext)\n %show image\n hfig = figure;\n imshow(image);\n axis off image\n hold on\n \n %show landmark\n plot(landmark(:,1),landmark(:,2),'w.','MarkerSize',30); %why the color changes after hfig returns?\n \n %show text\n if bshowtext\n setsize = size(landmark,1);\n for i=1:setsize;\n text(landmark(i,1),landmark(i,2), sprintf('%d',i));\n end\n end\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F11e_BackProjection_GaussianKernel.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F11e_BackProjection_GaussianKernel.m", "size": 1422, "source_encoding": "utf_8", "md5": "91c09fc297bd57f1030101b30351e20b", "text": "%Chih-Yuan Yang\n%07/20/14 \n%F11c: controlled by iternum\n%F11d: controled by TolF\n%F11e: I replace the IF5 internal function by F26 since they are identical. \n% I update the code to support the scaling factor of 3. I replace the F19a\n% by F19c since F19c is simpler and does not require F20.\nfunction img_bp = F11e_BackProjection_GaussianKernel(img_lr, img_hr, Gau_sigma, iternum,bReport,TolF)\n [h_hr] = size(img_hr,1);\n [h_lr] = size(img_lr,1);\n zooming = h_hr/h_lr;\n for i=1:iternum\n img_lr_gen = F19c_GenerateLRImage_GaussianKernel(img_hr,zooming,Gau_sigma);\n diff_lr = img_lr - img_lr_gen;\n RMSE_diff_lr = sqrt(mean2(diff_lr.^2));\n diff_hr = F26_UpsampleAndBlur(diff_lr,zooming, Gau_sigma);\n %diff_hr = imresize(diff_lr,zooming,'bilinear');\n img_hr = img_hr + diff_hr;\n img_lr_new = F19c_GenerateLRImage_GaussianKernel(img_hr,zooming,Gau_sigma);\n diff_lr_new = img_lr - img_lr_new; \n RMSE_diff_lr_afteronebackprojection = sqrt(mean2(diff_lr_new.^2));\n if bReport\n fprintf('backproject iteration=%d, RMSE_before=%0.6f, RMSE_after=%0.6f\\n', ...\n i,RMSE_diff_lr,RMSE_diff_lr_afteronebackprojection); \n end\n if RMSE_diff_lr_afteronebackprojection < TolF\n disp('RMSE_diff_lr_afteronebackprojection < TolF');\n break;\n end\n end\n img_bp = img_hr;\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F15_ComputeSRSSD.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F15_ComputeSRSSD.m", "size": 236, "source_encoding": "utf_8", "md5": "3532526636455f6cc3acccf05b85199d", "text": "%03/17/12\nfunction SRSSD = F15_ComputeSRSSD(GradOrImg)\n if size(GradOrImg,3) == 8\n Grad = GradOrImg;\n else\n Grad = F14_Img2Grad(GradOrImg);\n end\n Sqr = Grad .^2;\n Sum = sum(Sqr,3);\n SRSSD = sqrt(Sum);\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U5_ReadFileNameList.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U5_ReadFileNameList.m", "size": 249, "source_encoding": "utf_8", "md5": "6cc6e817fc7e4d5c331e663041ff41fc", "text": "%Chih-Yuan Yang\n%03/07/13\n%U5: read list from a file and return it as an cell array\nfunction filenamelist = U5_ReadFileNameList( fn_list )\n fid = fopen(fn_list,'r');\n C = textscan(fid,'%d %s\\n');\n fclose(fid);\n filenamelist = C{2};\nend\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "IF4s_BuildHRimagefromHRPatches.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/IF4s_BuildHRimagefromHRPatches.m", "size": 4401, "source_encoding": "utf_8", "md5": "07e053559d7bc259285d722b784bfab0", "text": "% Build color image\nfunction img_texture = IF4s_BuildHRimagefromHRPatches(hrpatch,zooming)\n %reconstruct the high-resolution image\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr/zooming;\n h_lr = size(hrpatch,4) + patchsize_lr - 1;\n w_lr = size(hrpatch,5) + patchsize_lr - 1;\n h_expected = h_lr * zooming;\n w_expected = w_lr * zooming;\n img_texture = zeros(h_expected,w_expected,3);\n %most cases\n rpixelshift = 2; %this should be modified according to patchsize_lr\n cpixelshift = 2;\n for rl = 2:h_lr - patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n for cl = 2:w_lr - patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,:,rl,cl);\n img_texture(rh:rh1,ch:ch1,:) = usedhrpatch(9:12,9:12,:);\n end\n end\n \n %left\n cl = 1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1,:) = usedhrpatch(rhsource:rh1source,chsource:ch1source,:);\n end\n \n %right\n cl = w_lr - patchsize_lr+1;\n ch = w_expected - 3*zooming+1;\n ch1 = w_expected;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1,:) = usedhrpatch(rhsource:rh1source,chsource:ch1source,:);\n end\n \n %top\n rl = 1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1,:) = usedhrpatch(rhsource:rh1source,chsource:ch1source,:);\n end\n \n %bottom\n rl = h_lr-patchsize_lr+1;\n rh = h_expected - 3*zooming+1;\n rh1 = h_expected;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1,:) = usedhrpatch(rhsource:rh1source,chsource:ch1source,:);\n end\n \n %left-top corner\n rl=1;\n cl=1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1,:) = usedhrpatch(rhsource:rh1source,chsource:ch1source,:);\n \n %right-top corner\n rl=1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1,:) = usedhrpatch(rhsource:rh1source,chsource:ch1source,:);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1,:) = usedhrpatch(rhsource:rh1source,chsource:ch1source,:);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1,:) = usedhrpatch(rhsource:rh1source,chsource:ch1source,:);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F11a_AdaptiveBackProjection.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F11a_AdaptiveBackProjection.m", "size": 7250, "source_encoding": "utf_8", "md5": "404edc2e654e7c70e60151b263ca5528", "text": "%09/28/12\n%Chih-Yuan Yang\n%The adaptive kernelmap has to be passed from the caller, or generated by img_lr\nfunction img_bp = F11a_AdaptiveBackProjection(img_lr, img_hr, Gau_sigma, iternum,bReport,kernelmap)\n [h_hr] = size(img_hr,1);\n [h_lr] = size(img_lr,1);\n zooming = h_hr/h_lr;\n \n if nargin < 6\n %generate the kernelmap\n %compute the similarity from low\n coef = 10;\n sqrt_low = IF1_SimilarityEvaluation(img_lr);\n similarity_low = exp(-sqrt_low*coef);\n %model the directional Gaussian kernel\n [h w] = size(similarity_low);\n options = optimset('Display','iter','TolFun',0.001,'TolX',0.1);\n initial_sigmax = 1;\n initial_sigmay = 1;\n initial_theta = 0;\n initial_variable = [initial_sigmax, initial_sigmay, initial_theta];\n \n kernel = zeros(8); %the number depends on te zooming\n kernelmap = zeros(8,8,h,w);\n for rl=1:h\n for cl=1:w\n %solve the optimization problem for each position\n zvalue16points = similarity_low(rl,cl,:);\n [x fval]= fminsearch(@(x) IF3_OptProblem(x,zvalue16points), initial_variable, options);\n sigma_x = x(1);\n sigma_y = x(2);\n theta = x(3);\n \n a = cos(theta)^2/2/sigma_x^2 + sin(theta)^2/2/sigma_y^2;\n b = -sin(2*theta)/4/sigma_x^2 + sin(2*theta)/4/sigma_y^2 ;\n c = sin(theta)^2/2/sigma_x^2 + cos(theta)^2/2/sigma_y^2;\n \n %create the kernel map by parameter a b c\n for s = 1:12\n yi = s-6.5;\n for t = 1:12\n xi = t-6.5;\n kernel(s,t) = exp(-(a*xi^2 + 2*b*xi*yi + c*yi^2));\n end\n end\n sumvalue = sum(kernel(:));\n kernel_normal = kernel / sumvalue;\n kernelmap(:,:,rl,cl) = kernel_normal;\n end\n end\n end\n for i=1:iternum\n img_lr_gen = F19_GenerateLRImage_BlurSubSample(img_hr,zooming,Gau_sigma);\n diff_lr = img_lr - img_lr_gen;\n term_diff_lr_SSD = sum(sum(diff_lr.^2));\n %here, change the kernel pixel by pixel\n diff_hr = Upsample(diff_lr,zooming, kernelmap);\n% diff_hr = imresize(diff_lr,zooming,'bilinear');\n img_hr = img_hr + diff_hr;\n img_lr_new = F19_GenerateLRImage_BlurSubSample(img_hr,zooming,Gau_sigma);\n diff_lr_new = img_lr - img_lr_new; \n term_diff_lr_SSD_afteronebackprojection = sum(sum(diff_lr_new.^2));\n if bReport\n fprintf('backproject iteration=%d, term_before=%0.1f, term_after=%0.1f\\n', ...\n i,term_diff_lr_SSD,term_diff_lr_SSD_afteronebackprojection); \n end \n end\n img_bp = img_hr;\nend\n%model kernelmap as Gaussian?\nfunction diff_hr = Upsample(diff_lr,zooming, kernelmap)\n [h w] = size(diff_lr);\n for r=1:h\n for c=1:w\n \n end\n end\nend\nfunction SqrtData = IF1_SimilarityEvaluation(Img_in)\n [h w] = size(Img_in);\n SqrtData = zeros(h,w,16);\n \n f3x3 = ones(3);\n for i = 1:16\n [DiffOp N] = IF2_RetGradientKernel16(i); %this may be better if there are 32 samples\n if N == 1\n Diff = imfilter(Img_in,DiffOp{1},'symmetric');\n else\n Diff1 = imfilter(Img_in,DiffOp{1},'symmetric');\n Diff2 = imfilter(Img_in,DiffOp{2},'symmetric');\n Diff = (Diff1+Diff2)/2;\n end\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Mean = Sum/9;\n SqrtData(:,:,i) = sqrt(Mean);\n end\nend\nfunction [DiffOp N] = IF2_RetGradientKernel16(dir)\n DiffOp = cell(2,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n DiffOp{1} = f{1};\n DiffOp{2} = [];\n case 2\n N = 2;\n DiffOp{1} = f{1};\n DiffOp{2} = f{2};\n case 3\n N = 1; \n DiffOp{1} = f{2};\n DiffOp{2} = [];\n case 4\n N = 2;\n DiffOp{1} = f{2};\n DiffOp{2} = f{3};\n case 5\n N = 1;\n DiffOp{1} = f{3};\n DiffOp{2} = [];\n case 6\n N = 2;\n DiffOp{1} = f{3};\n DiffOp{2} = f{4};\n case 7\n N = 1;\n DiffOp{1} = f{4};\n DiffOp{2} = [];\n case 8\n N = 2;\n DiffOp{1} = f{4};\n DiffOp{2} = f{5};\n case 9\n N = 1;\n DiffOp{1} = f{5};\n DiffOp{2} = [];\n case 10\n N = 2;\n DiffOp{1} = f{5};\n DiffOp{2} = f{6};\n case 11\n DiffOp{1} = f{6};\n DiffOp{2} = [];\n N = 1;\n case 12\n N = 2;\n DiffOp{1} = f{6};\n DiffOp{2} = f{7};\n case 13\n N = 1;\n DiffOp{1} = f{7};\n DiffOp{2} = [];\n case 14\n N = 2;\n DiffOp{1} = f{7};\n DiffOp{2} = f{8};\n case 15\n DiffOp{1} = f{8};\n DiffOp{2} = [];\n N = 1;\n case 16\n N = 2;\n DiffOp{1} = f{8};\n DiffOp{2} = f{1};\n end\nend\nfunction value = IF3_OptProblem(x,zvalue16points)\n sigma_x = x(1);\n sigma_y = x(2);\n theta = x(3);\n a = cos(theta)^2/2/sigma_x^2 + sin(theta)^2/2/sigma_y^2;\n b = -sin(2*theta)/4/sigma_x^2 + sin(2*theta)/4/sigma_y^2 ;\n c = sin(theta)^2/2/sigma_x^2 + cos(theta)^2/2/sigma_y^2;\n \n value = 0;\n for i=1:16\n [xi yi] = IF4_GetXiYi(i);\n diff = zvalue16points(i) - exp(- (a*xi^2 + 2*b*xi*yi + c*yi^2));\n value = value + diff^2;\n end\nend\nfunction [xi yi] = IF4_GetXiYi(i)\n switch i\n case 1\n xi = 1;\n yi = 0;\n case 2\n xi = 1;\n yi = -0.5;\n case 3\n xi = 1;\n yi = -1;\n case 4\n xi = 0.5;\n yi = -1;\n case 5\n xi = 0;\n yi = -1;\n case 6\n xi = -0.5;\n yi = -1;\n case 7\n xi = -1;\n yi = -1;\n case 8\n xi = -1;\n yi = -0.5;\n case 9\n xi = -1;\n yi = 0;\n case 10\n xi = -1;\n yi = 0.5;\n case 11\n xi = -1;\n yi = 1;\n case 12\n xi = -0.5;\n yi = 1;\n case 13\n xi = 0;\n yi = 1;\n case 14\n xi = 0.5;\n yi = 1;\n case 15\n xi = 1;\n yi = 1;\n case 16\n xi = 1;\n yi = 0.5;\n end\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F14c_Img2Grad_fast_suppressboundary.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F14c_Img2Grad_fast_suppressboundary.m", "size": 2487, "source_encoding": "utf_8", "md5": "dfc73eaa1e6c8da2acc4a7384ee4802a", "text": "%Chih-Yuan Yang\n%03/05/13\n%add class control\n%F14b: improve the speed, the boudnary is inaccurate\n%F14c: resolve the boundary problem\nfunction grad = F14c_Img2Grad_fast_suppressboundary(img)\n [h, w] = size(img);\n grad = zeros(h,w,8);\n rsup = cell(2,1);\n csup = cell(2,1);\n for i=1:8\n switch i\n case 1 %right\n rs = 0;\n cs = 1;\n rsup{1} = 'all';\n csup{1} = w;\n supnumber = 1;\n case 2 %top right\n rs = -1;\n cs = 1;\n rsup{1} = 'all';\n csup{1} = w;\n rsup{2} = 1;\n csup{2} = 'all';\n supnumber = 2;\n case 3 %top\n rs = -1;\n cs = 0;\n rsup{1} = 1;\n csup{1} = 'all';\n supnumber = 1;\n case 4 %top left\n rs = -1;\n cs = -1;\n rsup{1} = 1;\n csup{1} = 'all';\n rsup{2} = 'all';\n csup{2} = 1;\n supnumber = 2;\n case 5 %left\n rs = 0;\n cs = -1;\n rsup{1} = 'all';\n csup{1} = 1;\n supnumber = 1;\n case 6 %left bottom\n rs = 1;\n cs = -1;\n rsup{1} = 'all';\n csup{1} = 1;\n rsup{2} = h;\n csup{2} = 'all';\n supnumber = 2;\n case 7 %bottom\n rs = 1;\n cs = 0;\n rsup{1} = h;\n csup{1} = 'all';\n supnumber = 1;\n case 8 %bottom right\n rs = 1;\n cs = 1;\n rsup{1} = h;\n csup{1} = 'all';\n rsup{2} = 'all';\n csup{2} = w;\n supnumber = 2;\n end\n grad(:,:,i) = circshift(img,[-rs,-cs]) - img ; %correct\n %suppress the boundary\n for supidx = 1:supnumber\n if ischar(rsup{supidx}) && strcmp(rsup{supidx},'all')\n c = csup{supidx};\n grad(:,c,i) = 0;\n end\n if ischar(csup{supidx}) && strcmp(csup{supidx},'all')\n r = rsup{supidx};\n grad(r,:,i) = 0;\n end \n end\n end\nend\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F16d_ACCV12TextureGradientNotIntensity.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F16d_ACCV12TextureGradientNotIntensity.m", "size": 21023, "source_encoding": "utf_8", "md5": "d5f8b5f2fa7dd109fd9f1bad6a31d0ce", "text": "%Chih-Yuan Yang\n%10/04/12\n%16d: only run patch selection because the edge part has been separated\nfunction [gradients_texture img_texture img_texture_backproject] = F16d_ACCV12TextureGradientNotIntensity(img_y, zooming, Gau_sigma ,sfall,srecall,allHRexampleimages,allLRexampleimages)\n if zooming == 4\n para.Gau_sigma = 1.6;\n elseif zooming == 3\n para.Gau_sigma = 1.2;\n end\n \n [h_lr w_lr] = size(img_y);\n para.lh = h_lr;\n para.lw = w_lr;\n para.NumberOfHCandidate = 10;\n para.SimilarityFunctionSettingNumber = 1;\n %load all data set to save loading time\n [scanr scanra] = SearchExternalPatches(img_y,para,sfall,srecall);\n para.zooming = zooming;\n para.ps = 5;\n para.Gau_sigma = Gau_sigma;\n hrpatch = F8_ExtractAllHrPatches(img_y, para, scanr,allHRexampleimages,allLRexampleimages);\n [scanr_self scanra_self] = F22_SearchForSelfSimilarPatchesL2Norm(img_y,para);\n para.ehrfKernelWidth = 1.0;\n para.bEnablemhrf = true;\n [img_texture weightmap_texture] = F11_FilterOutImproperHrPatches(img_y,hrpatch,para,scanr_self,scanra_self,scanr,scanra);\n %apply backprojection on img_texture only\n iternum = 100;\n breport = true;\n disp('backprojection for img_texture in ACCV12');\n img_texture_backproject = F11c_BackProjection_GaussianKernel(img_y, img_texture, Gau_sigma, iternum,breport);\n \n %extract the graident\n gradients_texture = Img2Grad(img_texture_backproject);\n \nend\nfunction [scanr scanra] = SearchExternalPatches(img_y,para,sfall,srecall)\n %how to search parallelly to speed up?\n ps = 5; %patch size\n [lh lw] = size(img_y);\n hrpatchnumber = 10;\n %featurefolder = para.featurefolder;\n sh = GetShGeneral(ps);\n scanr = zeros(6,hrpatchnumber,lh-ps+1,lw-ps+1); %scan results, mm, quan, ii, sr, sc, similairty\n smallvalue = -1;\n scanr(6,:,:,:) = smallvalue;\n scanra = zeros(lh-ps+1,lw-ps+1); %scan results active\n %scanrsimmax = smallvalue * ones(lh-ps+1,lw-ps+1); %del this line?\n quanarray = [1 2 4 8 16 32];\n B = [256 128 64 32 16 8];\n imlyi = im2uint8(img_y);\n for qidx=1:6\n quan = quanarray(qidx);\n b = B(qidx);\n \n cur_initial = floor(size(sfall{1},2)/2); %accelerate the loop by using an initial position\n for rl=1:lh-ps+1\n fprintf('look for lut rl:%d quan:%d\\n',rl,quan);\n for cl = 1:lw-ps+1\n patch = imlyi(rl:rl+ps-1,cl:cl+ps-1);\n fq = patch(sh);\n if qidx == 1\n fquan = fq;\n else\n fquan = fq - mod(fq,quan) + quan/2;\n end\n\n [iila mma] = LookForLookUpTable9_External(fquan,sfall{qidx},cur_initial,para); %index in lookuptable\n in = length(iila); %always return 20 instance\n for i=1:in\n ii = srecall{qidx}(1,iila(i)); \n sr = srecall{qidx}(2,iila(i));\n sc = srecall{qidx}(3,iila(i));\n %check whether the patch is in the scanr already\n bSamePatch = false;\n for j=1:scanra(rl,cl)\n if ii == scanr(3,j,rl,cl) && sr == scanr(4,j,rl,cl) && sc == scanr(5,j,rl,cl)\n bSamePatch = true;\n break\n end\n end\n\n if bSamePatch == false\n similarity = bmm2similarity(b,mma(i),para.SimilarityFunctionSettingNumber);\n if scanra(rl,cl) < hrpatchnumber\n ix = scanra(rl,cl) + 1;\n %to do: update scanr by similarity\n %need to double it, otherwise, the int6 will kill similarity\n scanr(:,ix,rl,cl) = cat(1,mma(i),quan,double(ii),double(sr),double(sc),similarity);\n scanra(rl,cl) = ix;\n else\n [minval ix] = min(scanr(6,:,rl,cl));\n if scanr(6,ix,rl,cl) < similarity\n %update\n scanr(:,ix,rl,cl) = cat(1,mma(i),quan,double(ii),double(sr),double(sc),similarity); \n end\n end\n end\n end\n end\n end\n end\nend\nfunction [iila mma] = LookForLookUpTable9_External(fq,lut,cur_initial,para)\n hrpatchnumber = para.NumberOfHCandidate; %default 10\n fl = length(fq); %feature length\n head = 1;\n tail = size(lut,2);\n lutsize = size(lut,2);\n if exist('cur_initial','var')\n if cur_initial > lutsize\n cur = lutsize;\n else\n cur = cur_initial;\n end\n else\n cur = round(lutsize/2);\n end\n cur_rec1 = cur;\n %initial comparison\n fqsmaller = -1;\n fqlarger = 1;\n fqsame = 0;\n cr = 0; %compare results\n mm = 0;\n mmiil = 0;\n %search for the largest mm\n while 1\n for c=1:fl\n if fq(c) < lut(c,cur)\n cr = fqsmaller;\n break\n elseif fq(c) > lut(c,cur)\n cr = fqlarger;\n break; %c moves to next\n else %equal\n cr = fqsame;\n if mm < c\n mm = c;\n mmiil = cur;\n end \n end\n end\n \n if cr == fqsmaller\n next = floor((cur + head)/2);\n tail = cur; %adjust the range of head and tail\n elseif cr == fqlarger;\n next = ceil((cur + tail)/2); %the round function has to be floor, because fq is larger than cur\n %otherwise the fully 255 patches will never match\n head = cur; %adjust the range of head and tail\n end\n \n if mm == 25 %it happens, the initial one match the fq, therefore, there is no next defined.\n break\n end\n if cur == next || cur_rec1 == next %the next might oscilate\n break;\n else\n cur_rec1 = cur;\n cur = next;\n end\n %fprintf('cur %d\\n',cur);\n end\n\n if mm == 0 \n iila = [];\n mma = [];\n return\n end\n %post-process to find the repeated partial vectors\n %search for previous\n idx = 1;\n iila = zeros(hrpatchnumber,1);\n mma = zeros(hrpatchnumber,1);\n iila(idx) = mmiil;\n mma(idx) = mm;\n bprecontinue = true;\n bproccontinue = true;\n \n presh = 0; %previous shift\n procsh = 0; %proceeding shift\n while 1\n presh = presh -1;\n iilpre = mmiil + presh;\n if iilpre <1\n bprecontinue = false;\n premm = 0;\n end\n procsh = procsh +1;\n iilproc = mmiil + procsh;\n if iilproc > lutsize\n bproccontinue = false;\n procmm = 0;\n end\n \n if bprecontinue \n diff = lut(:,iilpre) ~= fq;\n if nnz(diff) == 0\n premm = 25;\n else\n premm = find(diff,1,'first') -1;\n end\n end\n\n if bproccontinue\n diff = lut(:,iilproc) ~= fq;\n if nnz(diff) == 0\n procmm = 25;\n else\n procmm = find(diff,1,'first') -1;\n end\n end\n \n if premm == 0 && procmm == 0\n break\n end\n if premm > procmm\n %add pre item\n idx = idx + 1;\n iila(idx) = iilpre;\n mma(idx) = premm;\n %pause the proc\n bprecontinue = true;\n elseif premm < procmm\n %add proc item\n idx = idx + 1;\n iila(idx) = iilproc;\n mma(idx) = procmm;\n %pause the pre\n bproccontinue = true;\n else %premm == procmm\n %add both item\n idx = idx + 1;\n iila(idx) = iilpre;\n mma(idx) = premm;\n \n if idx == hrpatchnumber\n break\n end\n idx = idx + 1;\n iila(idx) = iilproc;\n mma(idx) = procmm; \n bproccontinue = true;\n bprecontinue = true;\n end\n if idx == hrpatchnumber\n break\n end\n end\n\n if idx < hrpatchnumber\n iila = iila(1:idx);\n mma = mma(1:idx);\n end\nend\nfunction s = bmm2similarity(b,mm,SimilarityFunctionSettingNumber)\n if SimilarityFunctionSettingNumber == 1\n if mm >= 9\n Smm = 0.9 + 0.1*(mm-9)/16;\n else\n Smm = 0.5 * mm/9;\n end\n\n Sb = 0.5+0.5*(log2(b)-3)/5;\n s = Sb * Smm;\n elseif SimilarityFunctionSettingNumber == 2\n Smm = mm/25;\n Sb = (log2(b)-2)/6;\n s = Sb * Smm;\n end\nend\nfunction hrpatch = F8_ExtractAllHrPatches(img_y, para, scanr,allHRexampleimages,allLRexampleimages)\n disp('extracting HR patches');\n %how to search parallelly to speed up?\n psh = para.ps * para.zooming;\n ps = para.ps;\n lh = para.lh;\n lw = para.lw;\n s = para.zooming;\n hrpatchnumber = para.NumberOfHCandidate;\n hrpatch = zeros(psh,psh,lh-ps+1,lw-ps+1,hrpatchnumber);\n allimages = allHRexampleimages;\n \n %analyize which images need to be loaded\n alliiset = scanr(3,:,:,:);\n alliiset_uni = unique(alliiset(:)); %allmost all images are used, from 1 to 1500\n if alliiset_uni(1) ~= 0\n alliiset_uni_pure = alliiset_uni;\n else\n alliiset_uni_pure = alliiset_uni(2:end);\n end\n\n for i = 1:length(alliiset_uni_pure)\n ii = alliiset_uni_pure(i);\n fprintf('extracting image %d\\n',ii);\n exampleimage_hr = im2double(allimages(:,:,ii));\n exampleimage_lr = allLRexampleimages(:,:,ii);\n %exampleimage_lr = U3_GenerateLRImage_BlurSubSample(exampleimage_hr,para.zooming,para.Gau_sigma);\n match_4D = alliiset == ii;\n match_3D = reshape(match_4D,hrpatchnumber,lh-ps+1,lw-ps+1); %remove the first dimension\n [d1 d2 d3] = size(match_3D); %second dimention length\n [idxset posset] = find(match_3D);\n setin = length(idxset);\n for j = 1:setin\n idx = idxset(j);\n possum = posset(j);\n pos3 = floor( (possum-1)/d2) +1; %the relationship: possum = (pos3-1) * d2 + pos2, pos2 in (1,d2)\n pos2 = possum - (pos3-1)*d2;\n\n rl = pos2;\n cl = pos3;\n \n sr = scanr(4,idx,rl,cl);\n sc = scanr(5,idx,rl,cl);\n \n srh = (sr-1)*s+1;\n srh1 = srh + psh -1;\n sch = (sc-1)*s+1;\n sch1 = sch + psh-1;\n\n %to do: compensate the HR patch to match the LR query patch\n hrp = exampleimage_hr(srh:srh1,sch:sch1); %HR patch \n lrq = img_y(rl:rl+ps-1,cl:cl+ps-1); %LR query patch\n lrr = exampleimage_lr(sr:sr+ps-1,sc:sc+ps-1); %LR retrieved patch\n chrp = hrp + imresize(lrq - lrr,s,'bilinear'); %compensate HR patch\n hrpatch(:,:,rl,cl,idx) = chrp;\n \n bVisuallyCheck = false;\n if bVisuallyCheck\n if ~exist('hfig','var')\n hfig = figure;\n else\n figure(hfig);\n end\n subplot(1,4,1);\n imshow(hrp/255);\n title('hrp');\n subplot(1,4,2);\n imshow(lrr/255);\n title('lrr');\n subplot(1,4,3);\n imshow(lrq/255);\n title('lrq');\n subplot(1,4,4);\n imshow(chrp/255);\n title('chrp');\n keyboard\n end\n end \n end\nend\nfunction [img_texture Reliablemap] = F11_FilterOutImproperHrPatches(img_y,hrpatch,para,scanr_self,scanra_self,scanr,scanra)\n %filter out improper hr patches using similarity among lr patches\n %load the self-similar data\n s = para.zooming;\n lh = para.lh;\n lw = para.lw;\n ps = para.ps;\n psh = s * para.ps;\n patcharea = para.ps^2;\n\n\n SSnumberUpperbound = 10;\n \n %do I still need these variables?\n cqarray = zeros(32,1)/0;\n for qidx = 1:6\n quan = 2^(qidx-1);\n cqvalue = 0.9^(qidx-1);\n cqarray(quan) = cqvalue;\n end\n \n hh = lh * s;\n hw = lw * s;\n hrres_nomi = zeros(hh,hw);\n hrres_deno = zeros(hh,hw);\n maskmatrix = false(psh,psh,patcharea);\n Reliablemap = zeros(hh,hw);\n \n pshs = psh * psh; \n for i=1:patcharea\n [sh_notsued masklow maskhigh] = GetShGeneral(ps,i,true,s); %ps, mm, bhigh, s\n maskmatrix(:,:,i) = maskhigh;\n end\n mhr = zeros(5*s);\n r1 = 2*s+1;\n r2 = 3*s;\n c1 = 2*s+1;\n c2 = 3*s;\n mhr(r1:r2,c1:c2) = 1; %the central part\n sigma = para.ehrfKernelWidth;\n kernel = F20_Sigma2Kernel(sigma);\n if para.bEnablemhrf\n mhrf = imfilter(mhr,kernel,'replicate');\n else\n mhrf = mhr;\n end\n\n noHmap = scanra == 0;\n noHmapToFill = noHmap;\n NHOOD = [0 1 0;\n 1 1 1;\n 0 1 0];\n se = strel('arbitrary',NHOOD);\n noHmapneighbor = and( imdilate(noHmap,se) ,~noHmap);\n %if the noHmapsever is 0, it is fine\n \n imb = imresize(img_y,s); %use it as the reference if no F is available\n \n rsa = [0 -1 0 1];\n csa = [1 0 -1 0];\n for rl= 1:lh-ps+1 %75\n fprintf('rl:%d total:%d\\n',rl,lh-ps+1);\n rh = (rl-1)*s+1;\n rh1 = rh+psh-1;\n for cl = 1:lw-ps+1 %128\n ch = (cl-1)*s+1;\n ch1 = ch+psh-1;\n \n %load candidates\n hin = para.NumberOfHCandidate;\n H = zeros(psh,psh,hin);\n HSim = zeros(hin,1);\n for j=1:hin\n H(:,:,j) = hrpatch(:,:,rl,cl,j); %H\n HSim(j) = scanr(6,j,rl,cl);\n end\n \n %compute the number of reference patches\n sspin = min(SSnumberUpperbound,scanra_self(rl,cl)); \n %self similar patch instance number\n F = zeros(ps,ps,sspin);\n FSimPure = zeros(1,sspin);\n rin = 0;\n for i=1:sspin\n sr = scanr_self(3,i,rl,cl);\n sc = scanr_self(4,i,rl,cl);\n %hr candidate number\n rin = rin + para.NumberOfHCandidate;\n F(:,:,i) = img_y(sr:sr+ps-1,sc:sc+ps-1);\n FSimPure(i) = scanr_self(5,i,rl,cl);\n end\n \n %load all of the two step patches\n R = zeros(psh,psh,rin);\n mms = zeros(rin,1);\n mmr = zeros(rin,1);\n qs = zeros(rin,1);\n qr = zeros(rin,1);\n FSimBaseR = zeros(rin,1); \n RSim = zeros(rin,1);\n idx = 0;\n if sspin > 0\n for i=1:sspin %sspin is the Fin\n sr = scanr_self(3,i,rl,cl);\n sc = scanr_self(4,i,rl,cl);\n %hr candidate number\n hrcanin = para.NumberOfHCandidate;\n for j=1:hrcanin\n idx = idx + 1;\n R(:,:,idx) = hrpatch(:,:,sr,sc,j);\n mms(idx) = scanr_self(1,i,rl,cl);\n qs(idx) = scanr_self(2,i,rl,cl);\n mmr(idx) = scanr(1,j,sr,sc);\n qr(idx) = scanr(2,j,sr,sc);\n FSimBaseR(idx) = FSimPure(i);\n RSim(idx) = scanr(6,j,sr,sc);\n end\n end\n else\n idx = 1;\n rin = 1; %use bicubic \n R(:,:,idx) = imb(rh:rh1,ch:ch1);\n FSimBaseR(idx) = 1;FSimPure(i);\n end\n\n %here is a question, how to define the similarity between H and R?\n %L2norm?\n hscore = zeros(hin,1);\n for i=1:hin\n theH = H(:,:,i);\n for j=1:rin\n theR = R(:,:,j);\n spf = FSimBaseR(j);\n %similarity between H and R\n diff = theH - theR;\n L2N = norm(diff(:));\n shr = exp(- L2N/pshs);\n hscore(i) = hscore(i) + shr*spf;\n end\n end\n [maxscore idx] = max(hscore);\n %take this as the example\n Reliablemap(rh:rh1,ch:ch1) = Reliablemap(rh:rh1,ch:ch1) + HSim(idx)*mhrf;\n \n if hin > 0 %some patches can't find H\n hrres_nomi(rh:rh1,ch:ch1) = hrres_nomi(rh:rh1,ch:ch1) + H(:,:,idx).*mhrf;\n hrres_deno(rh:rh1,ch:ch1) = hrres_deno(rh:rh1,ch:ch1) + mhrf; \n end\n %if any of its neighbor belongs to noHmap, copy additional region to hrres\n %if the pixel belongs to noHmapneighbor, then expand the copy regions\n if noHmapneighbor(rl,cl) == true\n mhrfspecial = zeros(5*s);\n mhrfspecial(r1:r2,c1:c2) = 1;\n for i=1:4\n rs = rsa(i);\n cs = csa(i);\n checkr = rl+rs;\n checkc = cl+cs;\n if checkr > 0 && checkr < lh-ps+1 && checkc >0 && checkc c,r $retrived results\n %dimension: w,h,2,nnk\n for l = 1:nnk\n colMap = retres(:,:,1,l);\n rowMap = retres(:,:,2,l);\n br_boundary_to_ignore = width -1;\n %GetAnnError_GrayLevel_C1 is a funciton in CHS lab. It can compute very fast\n normcurr(:,:,l) = GetAnnError_GrayLevel_C1(A,B,uint16(rowMap),uint16(colMap),uint16(0),uint16(br_boundary_to_ignore), uint16(width));\n end\n \n %update scanr\n normcurrmin = min(normcurr,[],3);\n checkmap = normcurrmin(1:eh,1:ew) < scanr(:,:,recin,1); %the last one has the largest norm\n [rset cset] = find(checkmap);\n setin = length(rset);\n for j=1:setin\n rl = rset(j);\n cl = cset(j);\n [normcurrsort ixcurr] = sort(normcurr(rl,cl,:));\n for i=1:nnk\n %update the smaller norm\n compidx = recin-i+1;\n if normcurrsort(i) < scanr(rl,cl,compidx,1)\n %update\n oriidx = ixcurr(i);\n scanr(rl,cl,compidx,1) = normcurrsort(i);\n scanr(rl,cl,compidx,2) = ii;\n scanr(rl,cl,compidx,3) = retres(rl,cl,2,oriidx); %rowmap\n scanr(rl,cl,compidx,4) = retres(rl,cl,1,oriidx); %colmap\n else\n break\n end\n end\n \n %sort again the updated data\n [normnewsort ixnew] = sort(scanr(rl,cl,:,1));\n tempdata = scanr(rl,cl,:,:);\n for i=1:recin\n if ixnew(i) ~= i\n scanr(rl,cl,i,:) = tempdata(1,1,ixnew(i),:);\n end\n end\n end\n end\n sn = sprintf('%s_csh_scanr_%d_%d.mat',para.SaveName,iistart,iiend);\n save(fullfile(para.tuningfolder,sn),'scanr');\n \n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F4c_GenerateIntensityFromGradient.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F4c_GenerateIntensityFromGradient.m", "size": 4531, "source_encoding": "utf_8", "md5": "8f1bc8f4bba3afae27185acf447e8f30", "text": "%Chih-Yuan Yang\n%09/29/12\n%F4b: change first gradient from F19 to F19a, which uses a precise Gaussian kernel\n%F4c: F4b is too slow, change the parameters\n%Gradually incrase the coef of high-low term to achieve the contrained optimization problem\nfunction img_out = F4c_GenerateIntensityFromGradient(img_y,img_initial,Grad_exp,Gau_sigma,bReport,loopnumber,totalupdatenumber,linesearchstepnumber)\n if nargin <= 6\n linesearchstepnumber = 4;\n loopnumber = 4;\n totalupdatenumber = 4;\n end\n beta0_initial = 1; %beginning\n beta1_initial = 1;\n \n zooming = size(img_initial,1)/size(img_y,1);\n if zooming ~= floor(zooming)\n error('zooming should be an integer');\n end\n \n I = img_initial;\n \n term_intensity_check = zeros(linesearchstepnumber,1);\n term_gradient_check = zeros(linesearchstepnumber,1);\n [h w] = size(img_initial);\n for updatenumber = 0:totalupdatenumber\n beta0 = beta0_initial;\n beta1 = beta1_initial * 0.5^updatenumber;\n for loop = 1:loopnumber\n %refine image by low-high intensity\n img_lr_gen = F19a_GenerateLRImage_GaussianKernel(I,zooming,Gau_sigma);\n diff_lr = img_lr_gen - img_y;\n diff_hr = IF5_Upsample(diff_lr,zooming, Gau_sigma);\n Grad0 = diff_hr;\n\n %refine image by expected gradeint\n %Gradient decent\n OptDir = Grad_exp - F14_Img2Grad(I);\n Grad1 = sum(OptDir,3);\n Grad_all = beta0 * Grad0 + beta1 * Grad1;\n\n I_in = I; %make a copy, restore the value if all beta fails\n tau_initial = 1;\n term_gradient_in = ComputeFunctionValue_Grad(I,Grad_exp);\n term_intensity_in = F28_ComputeSquareSumLowHighDiff(I,img_y,Gau_sigma);\n term_all_in = term_intensity_in * beta0 + term_gradient_in * beta1;\n for line_search_step=1:linesearchstepnumber\n tau = tau_initial * 0.5^(line_search_step-1);\n I_check = I_in - tau * Grad_all;\n term_gradient_check(line_search_step) = ComputeFunctionValue_Grad(I_check,Grad_exp);\n term_intensity_check(line_search_step) = F28_ComputeSquareSumLowHighDiff(I_check,img_y,Gau_sigma);\n end\n \n term_all_check = term_intensity_check * beta0 + term_gradient_check * beta1;\n [sortvalue ix] = sort(term_all_check);\n if sortvalue(1) < term_all_in\n %update \n search_step_best = ix(1);\n tau_best = tau_initial * 0.5^(search_step_best-1);\n I_best = I_in - tau_best * Grad_all;\n I = I_best; %assign the image for next loop\n else\n break;\n end\n if bReport\n fprintf(['updatenumber=%d, loop=%d, all_in=%0.3f, all_out=%0.3f, Intensity_in=%0.3f, Intensity_out=%0.3f, ' ...\n 'Grad_in=%0.3f, Grad_out=%0.3f\\n'],updatenumber, loop,term_all_in,sortvalue(1),term_intensity_in,...\n term_intensity_check(ix(1)), term_gradient_in,term_gradient_check(ix(1))); \n end\n end\n end\n img_out = I_best;\nend\nfunction diff_hr = IF5_Upsample(diff_lr,zooming, Gau_sigma)\n [h w] = size(diff_lr);\n h_hr = h*zooming;\n w_hr = w*zooming;\n upsampled = zeros(h_hr,w_hr);\n if zooming == 3\n for rl = 1:h\n rh = (rl-1) * zooming + 2;\n for cl = 1:c\n ch = (cl-1) * zooming + 2;\n upsampled(rh,ch) = diff_lr(rl,cl);\n end\n end\n kernel = Sigma2Kernel(Gau_sigma);\n diff_hr = imfilter(upsampled,kernel,'replicate');\n elseif zooming == 4\n %compute the kernel by ourself, assuming the range is \n %control the kernel and the position of the diff\n kernelsize = ceil(Gau_sigma * 3)*2+2; %+2 this is the even number\n kernel = fspecial('gaussian',kernelsize,Gau_sigma);\n %subsample diff_lr to (3,3), because of the result of imfilter\n for rl = 1:h\n rh = (rl-1) * zooming + 3;\n for cl = 1:w\n ch = (cl-1) * zooming + 3;\n upsampled(rh,ch) = diff_lr(rl,cl);\n end\n end\n diff_hr = imfilter(upsampled, kernel,'replicate');\n else\n error('not processed');\n end\nend\n\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = F14_Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F16_ACCV12UpamplingBackProjectionOnTextureOnly.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F16_ACCV12UpamplingBackProjectionOnTextureOnly.m", "size": 43630, "source_encoding": "utf_8", "md5": "35bce9ddf165ff8accb3378a116dace3", "text": "%Chih-Yuan Yang\n%09/18/12\n%load sfall, srecall, allHRexampleimages before this function\nfunction img_hr = F16_ACCV12UpamplingBackProjectionOnTextureOnly(img_y, zooming, Gau_sigma ,sfall,srecall,allHRexampleimages)\n if zooming == 4\n para.Gau_sigma = 1.6;\n elseif zooming == 3\n para.Gau_sigma = 1.2;\n end\n \n [img_edge reliablemap_edge] = F1_EdgePreserving(img_y,para,zooming,Gau_sigma);\n [h_lr w_lr] = size(img_y);\n para.lh = h_lr;\n para.lw = w_lr;\n para.NumberOfHCandidate = 10;\n para.SimilarityFunctionSettingNumber = 1;\n %load all data set to save loading time\n [scanr scanra] = SearchExternalPatches(img_y,para,sfall,srecall);\n para.zooming = zooming;\n para.ps = 5;\n para.Gau_sigma = Gau_sigma;\n hrpatch = F8_ExtractAllHrPatches(img_y, para, scanr,allHRexampleimages);\n [scanr_self scanra_self] = F22_SearchForSelfSimilarPatchesL2Norm(img_y,para);\n para.ehrfKernelWidth = 1.0;\n para.bEnablemhrf = true;\n [img_texture reliablemap_texture] = F11_FilterOutImproperHrPatches(img_y,hrpatch,para,scanr_self,scanra_self,scanr,scanra);\n %apply backprojection on img_texture only\n iternum = 10;\n img_texture_backproject = F11_BackProjection(img_y, img_texture, Gau_sigma, iternum);\n \n nomi = img_texture_backproject.*reliablemap_texture + img_edge .* reliablemap_edge;\n denomi = reliablemap_edge + reliablemap_texture;\n img_hr = nomi ./ denomi;\n %there are some 0 value of denomi around boundary\n %fill these pixels as img_edge\n nanpixels = isnan(img_hr);\n img_hr(nanpixels) = img_edge(nanpixels);\n %ensure there is no nan\n if nnz(isnan(img_hr))\n error('should not be here');\n end\nend\nfunction [scanr scanra] = SearchExternalPatches(img_y,para,sfall,srecall)\n %how to search parallelly to speed up?\n ps = 5; %patch size\n [lh lw] = size(img_y);\n hrpatchnumber = 10;\n %featurefolder = para.featurefolder;\n sh = GetShGeneral(ps);\n scanr = zeros(6,hrpatchnumber,lh-ps+1,lw-ps+1); %scan results, mm, quan, ii, sr, sc, similairty\n smallvalue = -1;\n scanr(6,:,:,:) = smallvalue;\n scanra = zeros(lh-ps+1,lw-ps+1); %scan results active\n %scanrsimmax = smallvalue * ones(lh-ps+1,lw-ps+1); %del this line?\n quanarray = [1 2 4 8 16 32];\n B = [256 128 64 32 16 8];\n imlyi = im2uint8(img_y);\n for qidx=1:6\n quan = quanarray(qidx);\n b = B(qidx);\n \n cur_initial = floor(size(sfall{1},2)/2); %accelerate the loop by using an initial position\n for rl=1:lh-ps+1\n fprintf('look for lut rl:%d quan:%d\\n',rl,quan);\n for cl = 1:lw-ps+1\n patch = imlyi(rl:rl+ps-1,cl:cl+ps-1);\n fq = patch(sh);\n if qidx == 1\n fquan = fq;\n else\n fquan = fq - mod(fq,quan) + quan/2;\n end\n\n [iila mma] = LookForLookUpTable9_External(fquan,sfall{qidx},cur_initial,para); %index in lookuptable\n in = length(iila); %always return 20 instance\n for i=1:in\n ii = srecall{qidx}(1,iila(i)); \n sr = srecall{qidx}(2,iila(i));\n sc = srecall{qidx}(3,iila(i));\n %check whether the patch is in the scanr already\n bSamePatch = false;\n for j=1:scanra(rl,cl)\n if ii == scanr(3,j,rl,cl) && sr == scanr(4,j,rl,cl) && sc == scanr(5,j,rl,cl)\n bSamePatch = true;\n break\n end\n end\n\n if bSamePatch == false\n similarity = bmm2similarity(b,mma(i),para.SimilarityFunctionSettingNumber);\n if scanra(rl,cl) < hrpatchnumber\n ix = scanra(rl,cl) + 1;\n %to do: update scanr by similarity\n %need to double it, otherwise, the int6 will kill similarity\n scanr(:,ix,rl,cl) = cat(1,mma(i),quan,double(ii),double(sr),double(sc),similarity);\n scanra(rl,cl) = ix;\n else\n [minval ix] = min(scanr(6,:,rl,cl));\n if scanr(6,ix,rl,cl) < similarity\n %update\n scanr(:,ix,rl,cl) = cat(1,mma(i),quan,double(ii),double(sr),double(sc),similarity); \n end\n end\n end\n end\n end\n end\n end\nend\nfunction [iila mma] = LookForLookUpTable9_External(fq,lut,cur_initial,para)\n hrpatchnumber = para.NumberOfHCandidate; %default 10\n fl = length(fq); %feature length\n head = 1;\n tail = size(lut,2);\n lutsize = size(lut,2);\n if exist('cur_initial','var')\n if cur_initial > lutsize\n cur = lutsize;\n else\n cur = cur_initial;\n end\n else\n cur = round(lutsize/2);\n end\n cur_rec1 = cur;\n %initial comparison\n fqsmaller = -1;\n fqlarger = 1;\n fqsame = 0;\n cr = 0; %compare results\n mm = 0;\n mmiil = 0;\n %search for the largest mm\n while 1\n for c=1:fl\n if fq(c) < lut(c,cur)\n cr = fqsmaller;\n break\n elseif fq(c) > lut(c,cur)\n cr = fqlarger;\n break; %c moves to next\n else %equal\n cr = fqsame;\n if mm < c\n mm = c;\n mmiil = cur;\n end \n end\n end\n \n if cr == fqsmaller\n next = floor((cur + head)/2);\n tail = cur; %adjust the range of head and tail\n elseif cr == fqlarger;\n next = ceil((cur + tail)/2); %the round function has to be floor, because fq is larger than cur\n %otherwise the fully 255 patches will never match\n head = cur; %adjust the range of head and tail\n end\n \n if mm == 25 %it happens, the initial one match the fq, therefore, there is no next defined.\n break\n end\n if cur == next || cur_rec1 == next %the next might oscilate\n break;\n else\n cur_rec1 = cur;\n cur = next;\n end\n %fprintf('cur %d\\n',cur);\n end\n\n if mm == 0 \n iila = [];\n mma = [];\n return\n end\n %post-process to find the repeated partial vectors\n %search for previous\n idx = 1;\n iila = zeros(hrpatchnumber,1);\n mma = zeros(hrpatchnumber,1);\n iila(idx) = mmiil;\n mma(idx) = mm;\n bprecontinue = true;\n bproccontinue = true;\n \n presh = 0; %previous shift\n procsh = 0; %proceeding shift\n while 1\n presh = presh -1;\n iilpre = mmiil + presh;\n if iilpre <1\n bprecontinue = false;\n premm = 0;\n end\n procsh = procsh +1;\n iilproc = mmiil + procsh;\n if iilproc > lutsize\n bproccontinue = false;\n procmm = 0;\n end\n \n if bprecontinue \n diff = lut(:,iilpre) ~= fq;\n if nnz(diff) == 0\n premm = 25;\n else\n premm = find(diff,1,'first') -1;\n end\n end\n\n if bproccontinue\n diff = lut(:,iilproc) ~= fq;\n if nnz(diff) == 0\n procmm = 25;\n else\n procmm = find(diff,1,'first') -1;\n end\n end\n \n if premm == 0 && procmm == 0\n break\n end\n if premm > procmm\n %add pre item\n idx = idx + 1;\n iila(idx) = iilpre;\n mma(idx) = premm;\n %pause the proc\n bprecontinue = true;\n elseif premm < procmm\n %add proc item\n idx = idx + 1;\n iila(idx) = iilproc;\n mma(idx) = procmm;\n %pause the pre\n bproccontinue = true;\n else %premm == procmm\n %add both item\n idx = idx + 1;\n iila(idx) = iilpre;\n mma(idx) = premm;\n \n if idx == hrpatchnumber\n break\n end\n idx = idx + 1;\n iila(idx) = iilproc;\n mma(idx) = procmm; \n bproccontinue = true;\n bprecontinue = true;\n end\n if idx == hrpatchnumber\n break\n end\n end\n\n if idx < hrpatchnumber\n iila = iila(1:idx);\n mma = mma(1:idx);\n end\nend\nfunction s = bmm2similarity(b,mm,SimilarityFunctionSettingNumber)\n if SimilarityFunctionSettingNumber == 1\n if mm >= 9\n Smm = 0.9 + 0.1*(mm-9)/16;\n else\n Smm = 0.5 * mm/9;\n end\n\n Sb = 0.5+0.5*(log2(b)-3)/5;\n s = Sb * Smm;\n elseif SimilarityFunctionSettingNumber == 2\n Smm = mm/25;\n Sb = (log2(b)-2)/6;\n s = Sb * Smm;\n end\nend\nfunction hrpatch = F8_ExtractAllHrPatches(img_y, para, scanr,allHRexampleimages)\n disp('extracting HR patches');\n %how to search parallelly to speed up?\n psh = para.ps * para.zooming;\n ps = para.ps;\n lh = para.lh;\n lw = para.lw;\n s = para.zooming;\n hrpatchnumber = para.NumberOfHCandidate;\n hrpatch = zeros(psh,psh,lh-ps+1,lw-ps+1,hrpatchnumber);\n allimages = allHRexampleimages;\n \n %analyize which images need to be loaded\n alliiset = scanr(3,:,:,:);\n alliiset_uni = unique(alliiset(:)); %allmost all images are used, from 1 to 1500\n if alliiset_uni(1) ~= 0\n alliiset_uni_pure = alliiset_uni;\n else\n alliiset_uni_pure = alliiset_uni(2:end);\n end\n\n for i = 1:length(alliiset_uni_pure)\n ii = alliiset_uni_pure(i);\n\n exampleimage_hr = im2double(allimages(:,:,ii));\n\n exampleimage_lr = U3_GenerateLRImage_BlurSubSample(exampleimage_hr,para.zooming,para.Gau_sigma);\n match_4D = alliiset == ii;\n match_3D = reshape(match_4D,hrpatchnumber,lh-ps+1,lw-ps+1); %remove the first dimension\n [d1 d2 d3] = size(match_3D); %second dimention length\n [idxset posset] = find(match_3D);\n setin = length(idxset);\n for j = 1:setin\n idx = idxset(j);\n possum = posset(j);\n pos3 = floor( (possum-1)/d2) +1; %the relationship: possum = (pos3-1) * d2 + pos2, pos2 in (1,d2)\n pos2 = possum - (pos3-1)*d2;\n\n rl = pos2;\n cl = pos3;\n \n sr = scanr(4,idx,rl,cl);\n sc = scanr(5,idx,rl,cl);\n \n srh = (sr-1)*s+1;\n srh1 = srh + psh -1;\n sch = (sc-1)*s+1;\n sch1 = sch + psh-1;\n\n %to do: compensate the HR patch to match the LR query patch\n hrp = exampleimage_hr(srh:srh1,sch:sch1); %HR patch \n lrq = img_y(rl:rl+ps-1,cl:cl+ps-1); %LR query patch\n lrr = exampleimage_lr(sr:sr+ps-1,sc:sc+ps-1); %LR retrieved patch\n chrp = hrp + imresize(lrq - lrr,s,'bilinear'); %compensate HR patch\n hrpatch(:,:,rl,cl,idx) = chrp;\n \n bVisuallyCheck = false;\n if bVisuallyCheck\n if ~exist('hfig','var')\n hfig = figure;\n else\n figure(hfig);\n end\n subplot(1,4,1);\n imshow(hrp/255);\n title('hrp');\n subplot(1,4,2);\n imshow(lrr/255);\n title('lrr');\n subplot(1,4,3);\n imshow(lrq/255);\n title('lrq');\n subplot(1,4,4);\n imshow(chrp/255);\n title('chrp');\n keyboard\n end\n end \n end\nend\nfunction [img_texture Reliablemap] = F11_FilterOutImproperHrPatches(img_y,hrpatch,para,scanr_self,scanra_self,scanr,scanra)\n %filter out improper hr patches using similarity among lr patches\n %load the self-similar data\n s = para.zooming;\n lh = para.lh;\n lw = para.lw;\n ps = para.ps;\n psh = s * para.ps;\n patcharea = para.ps^2;\n\n\n SSnumberUpperbound = 10;\n \n %do I still need these variables?\n cqarray = zeros(32,1)/0;\n for qidx = 1:6\n quan = 2^(qidx-1);\n cqvalue = 0.9^(qidx-1);\n cqarray(quan) = cqvalue;\n end\n \n hh = lh * s;\n hw = lw * s;\n hrres_nomi = zeros(hh,hw);\n hrres_deno = zeros(hh,hw);\n maskmatrix = false(psh,psh,patcharea);\n Reliablemap = zeros(hh,hw);\n \n pshs = psh * psh; \n for i=1:patcharea\n [sh_notsued masklow maskhigh] = GetShGeneral(ps,i,true,s); %ps, mm, bhigh, s\n maskmatrix(:,:,i) = maskhigh;\n end\n mhr = zeros(5*s);\n r1 = 2*s+1;\n r2 = 3*s;\n c1 = 2*s+1;\n c2 = 3*s;\n mhr(r1:r2,c1:c2) = 1; %the central part\n sigma = para.ehrfKernelWidth;\n kernel = Sigma2Kernel(sigma);\n if para.bEnablemhrf\n mhrf = imfilter(mhr,kernel,'replicate');\n else\n mhrf = mhr;\n end\n\n noHmap = scanra == 0;\n noHmapToFill = noHmap;\n NHOOD = [0 1 0;\n 1 1 1;\n 0 1 0];\n se = strel('arbitrary',NHOOD);\n noHmapneighbor = and( imdilate(noHmap,se) ,~noHmap);\n %if the noHmapsever is 0, it is fine\n \n imb = imresize(img_y,s); %use it as the reference if no F is available\n \n rsa = [0 -1 0 1];\n csa = [1 0 -1 0];\n for rl= 1:lh-ps+1 %75\n fprintf('rl:%d total:%d\\n',rl,lh-ps+1);\n rh = (rl-1)*s+1;\n rh1 = rh+psh-1;\n for cl = 1:lw-ps+1 %128\n ch = (cl-1)*s+1;\n ch1 = ch+psh-1;\n \n %load candidates\n hin = para.NumberOfHCandidate;\n H = zeros(psh,psh,hin);\n HSim = zeros(hin,1);\n for j=1:hin\n H(:,:,j) = hrpatch(:,:,rl,cl,j); %H\n HSim(j) = scanr(6,j,rl,cl);\n end\n \n %compute the number of reference patches\n sspin = min(SSnumberUpperbound,scanra_self(rl,cl)); \n %self similar patch instance number\n F = zeros(ps,ps,sspin);\n FSimPure = zeros(1,sspin);\n rin = 0;\n for i=1:sspin\n sr = scanr_self(3,i,rl,cl);\n sc = scanr_self(4,i,rl,cl);\n %hr candidate number\n rin = rin + para.NumberOfHCandidate;\n F(:,:,i) = img_y(sr:sr+ps-1,sc:sc+ps-1);\n FSimPure(i) = scanr_self(5,i,rl,cl);\n end\n \n %load all of the two step patches\n R = zeros(psh,psh,rin);\n mms = zeros(rin,1);\n mmr = zeros(rin,1);\n qs = zeros(rin,1);\n qr = zeros(rin,1);\n FSimBaseR = zeros(rin,1); \n RSim = zeros(rin,1);\n idx = 0;\n if sspin > 0\n for i=1:sspin %sspin is the Fin\n sr = scanr_self(3,i,rl,cl);\n sc = scanr_self(4,i,rl,cl);\n %hr candidate number\n hrcanin = para.NumberOfHCandidate;\n for j=1:hrcanin\n idx = idx + 1;\n R(:,:,idx) = hrpatch(:,:,sr,sc,j);\n mms(idx) = scanr_self(1,i,rl,cl);\n qs(idx) = scanr_self(2,i,rl,cl);\n mmr(idx) = scanr(1,j,sr,sc);\n qr(idx) = scanr(2,j,sr,sc);\n FSimBaseR(idx) = FSimPure(i);\n RSim(idx) = scanr(6,j,sr,sc);\n end\n end\n else\n idx = 1;\n rin = 1; %use bicubic \n R(:,:,idx) = imb(rh:rh1,ch:ch1);\n FSimBaseR(idx) = 1;FSimPure(i);\n end\n\n %here is a question, how to define the similarity between H and R?\n %L2norm?\n hscore = zeros(hin,1);\n for i=1:hin\n theH = H(:,:,i);\n for j=1:rin\n theR = R(:,:,j);\n spf = FSimBaseR(j);\n %similarity between H and R\n diff = theH - theR;\n L2N = norm(diff(:));\n shr = exp(- L2N/pshs);\n hscore(i) = hscore(i) + shr*spf;\n end\n end\n [maxscore idx] = max(hscore);\n %take this as the example\n Reliablemap(rh:rh1,ch:ch1) = Reliablemap(rh:rh1,ch:ch1) + HSim(idx)*mhrf;\n \n if hin > 0 %some patches can't find H\n hrres_nomi(rh:rh1,ch:ch1) = hrres_nomi(rh:rh1,ch:ch1) + H(:,:,idx).*mhrf;\n hrres_deno(rh:rh1,ch:ch1) = hrres_deno(rh:rh1,ch:ch1) + mhrf; \n end\n %if any of its neighbor belongs to noHmap, copy additional region to hrres\n %if the pixel belongs to noHmapneighbor, then expand the copy regions\n if noHmapneighbor(rl,cl) == true\n mhrfspecial = zeros(5*s);\n mhrfspecial(r1:r2,c1:c2) = 1;\n for i=1:4\n rs = rsa(i);\n cs = csa(i);\n checkr = rl+rs;\n checkc = cl+cs;\n if checkr > 0 && checkr < lh-ps+1 && checkc >0 && checkc =1 && r2<=h && c1>=1 && c2<=w %discrad boundary?\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(11), c*ones(11));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %Convert dist to table index\n TableIndexMap = zeros(h,w);\n b = unique(DistPatch(:));\n for i=1:length(b)\n SetPixels = DistMap == b(i);\n TableIndexMap(SetPixels) = i;\n end\n\n \n %mapping (T_p, T_r, d) to S_p\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n UpdatedPixel = false(h,w);\n S = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n CurrentMagValue = T(r,c);\n BinIdx_Current = ceil(CurrentMagValue /0.005);\n %Zebra have super strong Mag\n if BinIdx_Current > 100\n BinIdx_Current = 100;\n end\n TableIndex = TableIndexMap(r,c);\n if TableIndex > para.DistanceUpperBound\n continue\n end\n CenterMagValue = T(r_Center,c_Center);\n %Low Mag Edge suppresion\n if CenterMagValue < para.LowMagSuppression\n continue\n end\n BinIdx_Center = ceil(CenterMagValue /0.005);\n if BinIdx_Center > 100\n BinIdx_Center = 100;\n end\n %consult the table\n if TableIndex == 1 %1 is the index of b(1) where dist = 0, enhance the contrast of pixel on edge \n S_p = para.ContrastEnhenceCoef * Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n else\n S_p = Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n end\n \n if isnan(S_p)\n else\n UpdatedPixel(r,c) = true;\n S(r,c) = S_p;\n end\n end\n\n %Record the RidgeMapMap, for computing te ProbOfMag\n %the Mag is the consulted Mag\n %here is the problem, when the S is very strong, the affect range of ProbMagOut exceeds 1 pixel\n RidgeMapMagValue = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n RidgeMapMagValue(r,c) = S(r_Center,c_Center);\n end \n \n S(~UpdatedPixel) = T(~UpdatedPixel);\n img_in = I_s;\n if min(Dissimilarity(:)) == 0\n d = Dissimilarity + 1e-6; %avoid 0 case; some images may have d(:,:,1) as 0\n else\n d = Dissimilarity;\n end\n ratio = d ./ repmat(d(:,:,1),[1,1,8]);\n %here is the problem, I need to amplify the gradient directionally \n Grad_in = Img2Grad(img_in);\n Product = Grad_in .* ratio;\n Sqr = Product.^2;\n Sum = sum(Sqr,3);\n Sqrt = sqrt(Sum); %the Sqrt might be 0, because Grad_in may be pure 0;\n r1 = S ./Sqrt;\n r1(isnan(r1)) = 0;\n\n Grad_exp = Grad_high_initial .*( ratio .*(repmat(r1,[1,1,8])));\n %consolidate inconsistatnt gradient\n NewGrad_exp = zeros(h,w,8);\n for k=1:4\n switch k\n case 1\n ShiftOp = [0 -1];\n case 2\n ShiftOp = [1 -1];\n case 3\n ShiftOp = [1 0];\n case 4\n ShiftOp = [1 1];\n end\n k2 =k+4;\n Grad1 = Grad_exp(:,:,k);\n Grad2 = Grad_exp(:,:,k2);\n Grad2Shift = circshift(Grad2,ShiftOp);\n Grad1Abs = abs(Grad1);\n Grad2AbsShift = abs(Grad2Shift);\n Grad1Larger = Grad1Abs > Grad2AbsShift;\n Grad2Larger = Grad2AbsShift > Grad1Abs;\n NewGrad1 = Grad1 .* Grad1Larger + (-Grad2Shift) .* Grad2Larger;\n NewGrad2Shift = Grad2Shift .* Grad2Larger + (-Grad1) .* Grad1Larger;\n NewGrad2 = circshift(NewGrad2Shift,-ShiftOp);\n NewGrad_exp(:,:,k) = NewGrad1;\n NewGrad_exp(:,:,k2) = NewGrad2;\n end\n %current problem is the over-enhanced gradient (NewMagExp too large)\n\n para.bReport = true;\n img_edge = GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,para,zooming,Gau_sigma);\n\n %compute the Map of edge weight\n lambda_m = 2;\n m0 = 0;\n ProbMagOut = lambda_m * RidgeMapMagValue + m0;\n\n lambda_d = 0.25;\n d0 = 0.25;\n ProbDistMap = exp(- (lambda_d * DistMap + d0) ); %this coef should be decied by zooming\n \n Product = ProbMagOut .* ProbDistMap;\n ProbOfEdge = min(Product,1); %the two terms are not sufficient, direction is not taken into considertion\n\n para.bDumpInformation = false;\n if para.bDumpInformation\n scc(ProbOfEdge);\n title('Edge Weight Map');\n hfig = gcf;\n fn = sprintf('%s_%s_%d_%d_EdgeWeightMap.png',para.SaveName,para.Legend,para.setting,para.tuning);\n saveas(hfig,fullfile(para.tuningfolder,fn));\n close(hfig)\n \n scc(ProbMagOut,[0 1]); \n hFig = gcf;\n title('$b_1 s_r + b_0$, sharpness term','interpreter','latex');\n axis off\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_Weight_SharpnessTerm.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_Weight_SharpnessTerm.fig']));\n close(hFig);\n \n scc(ProbDistMap,[0 1]); \n hFig = gcf;\n title('$e^{a_1 d+a_0}$, distance term','interpreter','latex');\n axis off\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_Weight_DistanceTerm.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_Weight_DistanceTerm.fig']));\n close(hFig);\n\n\n scc(ProbOfEdge,[0 1]); \n hFig = gcf;\n title(''); %remove title, make it blank\n axis off\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_W_e.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_W_e.fig']));\n close(hFig);\n\n scc(RidgeMap,'g');\n hFig = gcf;\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_R_WithFrame.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_R_WithFrame.fig']));\n close(hFig);\n\n RidgeMap_filtered_inverted = 1-RidgeMap_filtered;\n scc(RidgeMap_filtered_inverted,'g');\n colorbar off\n hFig = gcf;\n title('$R$','interpreter','latex');\n saveas(hFig,fullfile(SaveFolder,[para.SaveName 'RidgeMap_WithFrame.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName 'RidgeMap_WithFrame.fig']));\n close(hFig);\n imwrite(1-RidgeMap_filtered,fullfile(para.tuningfolder,[para.SaveName '_R.png']));\n\n MaxS = max(S(:));\n scc(T,[0 MaxS]);\n hFig = gcf;\n %title('$M^*$, Mangnitude of gradient of $I^*$','interpreter','latex');\n title('');\n axis off\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_T.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_T.fig']));\n close(hFig);\n \n scc(S,[0 MaxS]); \n %title('$M''$, Predicted mangnitude of gradient','interpreter','latex');\n title('');\n hFig = gcf;\n axis off\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_S.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_S.fig']));\n close(hFig);\n\n imwrite(I_s,fullfile(SaveFolder, [para.SaveName '_I_s.png']));\n MagOut = F15_ComputeSRSSD(img_edge);\n scc(MagOut,[0 0.9]); \n hFig = gcf;\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_I_e_WithFrame.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_I_e_WithFrame.fig']));\n close(hFig);\n\n imwrite(img_edge,fullfile(SaveFolder, [para.SaveName '_I_e.png']));\n% scc(img_edge, 'g',[0 1]); \n% hFig = gcf;\n% saveas(hFig,fullfile(SaveFolder,'img_edge.fig'));\n% imwrite(img_edge,fullfile(SaveFolder,'img_edge.png'));\n% close(hFig);\n end\nend\nfunction img_out = SmoothnessPreservingFunction(img_y,para,zooming)\n img_bb = imresize(img_y,zooming);\n Kernel = Sigma2Kernel(para.Gau_sigma);\n\n %compute the similarity from low\n Coef = 10;\n PatchSize = 3;\n Sqrt_low = SimilarityEvaluation(img_y,PatchSize);\n Similarity_low = exp(-Sqrt_low*Coef);\n [h_high w_high] = size(img_bb);\n ExpectedSimilarity = zeros(h_high,w_high,16);\n %upsamplin the similarity\n for dir=1:16\n ExpectedSimilarity(:,:,dir) = imresize(Similarity_low(:,:,dir),zooming,'bilinear');\n end\n \n %refind the Grad_high by Similarity_high\n LoopNumber = 10;\n img = img_bb;\n for loop = 1:LoopNumber\n %refine gradient by ExpectedSimilarity\n ValueSum = zeros(h_high,w_high);\n WeightSum = sum(ExpectedSimilarity,3); %if thw weight sum is low, it is unsuitable to generate the grad by interpolation\n for dir = 1:16\n [MoveOp N] = GetMoveKernel16(dir);\n if N == 1\n MovedData = imfilter(img,MoveOp{1},'replicate');\n else %N ==2\n MovedData1 = imfilter(img,MoveOp{1},'replicate');\n MovedData2 = imfilter(img,MoveOp{2},'replicate');\n MovedData = (MovedData1 + MovedData2)/2;\n end\n Product = MovedData .* ExpectedSimilarity(:,:,dir);\n ValueSum = ValueSum + Product;\n end\n I = ValueSum ./ WeightSum;\n \n %intensity compensate\n Diff = imresize(imfilter(I,Kernel,'replicate'),1/zooming, 'nearest') - img_y;\n UpSampled = imresize(Diff,zooming,'bilinear');\n Grad0 = imfilter(UpSampled,Kernel,'replicate');\n Term_LowHigh_in = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n I_in = I; %make a copy, restore the value if all beta fails\n bDecrease = false;\n tau = 0.2;\n for line_search_loop=1:10\n %line search for the beta, fixed 1/32 is not a good choice\n I = I_in - tau * Grad0;\n Term_LowHigh_out = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n if Term_LowHigh_out < Term_LowHigh_in\n bDecrease = true;\n break;\n else\n tau = tau * 0.5;\n end\n end\n \n if bDecrease == true\n I_best = I;\n else\n break;\n end\n% fprintf('loop=%d, LowHihg_in=%0.1f, LowHigh_out=%0.1f,\\n',loop,Term_LowHigh_in,Term_LowHigh_out); \n \n% imwrite(I,fullfile(SaveFolder, [num2str(loop) '_GenIntenFromGrad.png']));\n img = I_best;\n end\n img_out = img;\n\nend\nfunction SqrtData = SimilarityEvaluation(Img_in,PatchSize)\n HalfPatchSize = (PatchSize-1)/2;\n [h w] = size(Img_in);\n SqrtData = zeros(h,w,16);\n \n f3x3 = ones(3);\n for i = 1:16\n [DiffOp N] = RetGradientKernel16(i);\n if N == 1\n Diff = imfilter(Img_in,DiffOp{1},'symmetric');\n else\n Diff1 = imfilter(Img_in,DiffOp{1},'symmetric');\n Diff2 = imfilter(Img_in,DiffOp{2},'symmetric');\n Diff = (Diff1+Diff2)/2;\n end\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Mean = Sum/9;\n SqrtData(:,:,i) = sqrt(Mean);\n end\nend\nfunction [DiffOp N] = RetGradientKernel16(dir)\n DiffOp = cell(2,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n DiffOp{1} = f{1};\n DiffOp{2} = [];\n case 2\n N = 2;\n DiffOp{1} = f{1};\n DiffOp{2} = f{2};\n case 3\n N = 1; \n DiffOp{1} = f{2};\n DiffOp{2} = [];\n case 4\n N = 2;\n DiffOp{1} = f{2};\n DiffOp{2} = f{3};\n case 5\n N = 1;\n DiffOp{1} = f{3};\n DiffOp{2} = [];\n case 6\n N = 2;\n DiffOp{1} = f{3};\n DiffOp{2} = f{4};\n case 7\n N = 1;\n DiffOp{1} = f{4};\n DiffOp{2} = [];\n case 8\n N = 2;\n DiffOp{1} = f{4};\n DiffOp{2} = f{5};\n case 9\n N = 1;\n DiffOp{1} = f{5};\n DiffOp{2} = [];\n case 10\n N = 2;\n DiffOp{1} = f{5};\n DiffOp{2} = f{6};\n case 11\n DiffOp{1} = f{6};\n DiffOp{2} = [];\n N = 1;\n case 12\n N = 2;\n DiffOp{1} = f{6};\n DiffOp{2} = f{7};\n case 13\n N = 1;\n DiffOp{1} = f{7};\n DiffOp{2} = [];\n case 14\n N = 2;\n DiffOp{1} = f{7};\n DiffOp{2} = f{8};\n case 15\n DiffOp{1} = f{8};\n DiffOp{2} = [];\n N = 1;\n case 16\n N = 2;\n DiffOp{1} = f{8};\n DiffOp{2} = f{1};\n end\nend\nfunction [Kernel N] = GetMoveKernel16(dir)\n Kernel = cell(2,1);\n f{1} = [0 0 0;\n 0 0 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 0 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 0 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 0 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 0 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 0 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 0 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 0 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n Kernel{1} = f{1};\n Kernel{2} = [];\n case 2\n N = 2;\n Kernel{1} = f{1};\n Kernel{2} = f{2};\n case 3\n N = 1; \n Kernel{1} = f{2};\n Kernel{2} = [];\n case 4\n N = 2;\n Kernel{1} = f{2};\n Kernel{2} = f{3};\n case 5\n N = 1;\n Kernel{1} = f{3};\n Kernel{2} = [];\n case 6\n N = 2;\n Kernel{1} = f{3};\n Kernel{2} = f{4};\n case 7\n N = 1;\n Kernel{1} = f{4};\n Kernel{2} = [];\n case 8\n N = 2;\n Kernel{1} = f{4};\n Kernel{2} = f{5};\n case 9\n N = 1;\n Kernel{1} = f{5};\n Kernel{2} = [];\n case 10\n N = 2;\n Kernel{1} = f{5};\n Kernel{2} = f{6};\n case 11\n Kernel{1} = f{6};\n Kernel{2} = [];\n N = 1;\n case 12\n N = 2;\n Kernel{1} = f{6};\n Kernel{2} = f{7};\n case 13\n N = 1;\n Kernel{1} = f{7};\n Kernel{2} = [];\n case 14\n N = 2;\n Kernel{1} = f{7};\n Kernel{2} = f{8};\n case 15\n Kernel{1} = f{8};\n Kernel{2} = [];\n N = 1;\n case 16\n N = 2;\n Kernel{1} = f{8};\n Kernel{2} = f{1};\n end\nend\nfunction f = ComputeFunctionValue_lowhigh(img,img_low,Gau_sigma)\n KernelSize = ceil(Gau_sigma) * 3 + 1;\n G = fspecial('gaussian',KernelSize,Gau_sigma);\n Conv = imfilter(img,G,'replicate');\n SubSample = imresize(Conv,size(img_low),'antialias',false);\n Diff = SubSample - img_low;\n Sqr = Diff.^2;\n f = sum(Sqr(:));\nend\nfunction Grad = Img2Grad(img)\n [h w] = size(img);\n Grad = zeros(h,w,8);\n DiffOp = RetGradientKernel();\n for i=1:8\n Grad(:,:,i) = imfilter(img,DiffOp{i},'replicate');\n end\nend\nfunction f = RetGradientKernel()\n f = cell(8,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\nend\nfunction Dissimilarity = EvaluateDissimilarity8(Img_in,PatchSize)\n if ~exist('PatchSize','var');\n PatchSize = 3;\n end\n [h w] = size(Img_in);\n Dissimilarity = zeros(h,w,8);\n \n f3x3 = ones(PatchSize)/(PatchSize^2);\n for i = 1:8\n DiffOp = RetGradientKernel8(i);\n Diff = imfilter(Img_in,DiffOp,'symmetric');\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Dissimilarity(:,:,i) = sqrt(Sum);\n end\nend\nfunction DiffOp = RetGradientKernel8(dir)\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n DiffOp = f{dir};\nend\nfunction img_out = GenerateIntensityFromGradient(img_y,img_initial,Grad_exp,para,zooming,Gau_sigma)\n if ~isfield(para,'bReport')\n para.bReport = false;\n end\n if ~isfield(para,'LoopNumber')\n para.LoopNumber = 30;\n end\n if ~isfield(para,'beta0')\n beta0 = 1;\n else\n beta0 = para.beta0;\n end\n if ~isfield(para,'beta1')\n beta1 = 1;\n else\n beta1 = para.beta1;\n end\n% TempFolder = para.tuningfolder;\n% zooming = para.zooming;\n \n \n %create dir\n% if isfield(para,'tuning')\n% SaveFolder = para.tuningfolder;\n% else\n% SaveFolder = fullfile(TempFolder,'OptimizationProgress');\n% end\n% if ~exist(SaveFolder,'dir')\n% mkdir( SaveFolder );\n% end\n \n Kernel = Sigma2Kernel(Gau_sigma);\n \n %compute gradient\n I = img_initial;\n I_best = I;\n for loop = 1:para.LoopNumber\n %refine image by patch similarity\n\n %refine image by low-high intensity\n Diff = imresize(imfilter(I,Kernel,'replicate'),1/zooming, 'nearest') - img_y;\n UpSampled = imresize(Diff,zooming,'bilinear');\n Grad0 = imfilter(UpSampled,Kernel,'replicate');\n \n %refine image by expected gradeint\n %Gradient decent\n %I = ModifyByGradient(I,Grad_exp);\n OptDir = Grad_exp - Img2Grad(I);\n Grad1 = sum(OptDir,3);\n Grad_all = beta0 * Grad0 + beta1 * Grad1;\n \n I_in = I; %make a copy, restore the value if all beta fails\n bDecrease = false;\n tau = 0.2;\n Term_Grad_in = ComputeFunctionValue_Grad(I,Grad_exp);\n Term_LowHigh_in = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n Term_all_in = Term_LowHigh_in * beta0 + Term_Grad_in * beta1;\n for line_search_loop=1:10\n %line search for the beta, fixed 1/32 is not a good choice\n I = I_in - tau * Grad_all;\n Term_Grad_out = ComputeFunctionValue_Grad(I,Grad_exp);\n Term_LowHigh_out = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n Term_all_out = Term_LowHigh_out * beta0 + Term_Grad_out * beta1;\n \n if Term_all_out < Term_all_in\n bDecrease = true;\n break;\n else\n tau = tau * 0.5;\n end\n end\n \n if bDecrease == true\n I_best = I;\n else\n break;\n end\n if para.bReport\n fprintf(['loop=%d, all_in=%0.1f, all_out=%0.1f, LowHihg_in=%0.1f, LowHigh_out=%0.1f, ' ...\n 'Grad_in=%0.1f, Grad_out=%0.1f\\n'],loop,Term_all_in,Term_all_out,Term_LowHigh_in,Term_LowHigh_out, ...\n Term_Grad_in,Term_Grad_out); \n end\n \n% imwrite(I,fullfile(SaveFolder, [num2str(loop) '_GenIntenFromGrad.png']));\n end\n img_out = I_best;\nend\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend\nfunction lrimg = U3_GenerateLRImage_BlurSubSample(hrimg,s,sigma)\n [h w d] = size(hrimg);\n htrim = h-mod(h,s);\n wtrim = w-mod(w,s);\n imtrim = hrimg(1:htrim,1:wtrim,1:d);\n \n %detect image type\n kernel = Sigma2Kernel(sigma);\n if d == 1\n blurimg = imfilter(imtrim,kernel,'replicate');\n elseif d == 3\n blurimg = zeros(htrim,wtrim,d);\n for i=1:3\n blurimg(:,:,i) = imfilter(imtrim(:,:,i),kernel,'replicate');\n end\n end\n lrimg = imresize(blurimg,1/s,'bilinear','antialias',false);\nend\nfunction img_bp = F11_BackProjection(img_lr, img_hr, Gau_sigma, iternum)\n [h_hr] = size(img_hr,1);\n [h_lr] = size(img_lr,1);\n zooming = h_hr/h_lr;\n for i=1:iternum\n img_lr_gen = U3_GenerateLRImage_BlurSubSample(img_hr,zooming,Gau_sigma);\n diff_lr = img_lr - img_lr_gen;\n diff_hr = imresize(diff_lr,zooming,'bilinear');\n img_hr = img_hr + diff_hr;\n end\n img_bp = img_hr;\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F37f_GetTexturePatchMatch_Aligned.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F37f_GetTexturePatchMatch_Aligned.m", "size": 13388, "source_encoding": "utf_8", "md5": "9f5b9bae31553af0503055933b6977aa", "text": "%Chih-Yuan Yang\n%10/07/12\n%Use patchmatch to retrieve a texture background\nfunction [gradients_texture, img_texture, img_texture_backprojection] = F37f_GetTexturePatchMatch_Aligned(img_y, ...\n hrexampleimages, lrexampleimages, landmarks_test, rawexamplelandmarks)\n\n %parameter\n numberofHcandidate = 10;\n \n %start\n [h_lr, w_lr, exampleimagenumber] = size(lrexampleimages);\n [h_hr, w_hr, ~] = size(hrexampleimages);\n zooming = floor(h_hr/h_lr);\n if zooming == 4\n Gau_sigma = 1.6;\n elseif zooming == 3\n Gau_sigma = 1.2;\n end\n alignedexampleimage_hr = zeros(h_hr,w_hr,exampleimagenumber,'uint8'); %set as uint8 to reduce memory demand\n alignedexampleimage_lr = zeros(h_lr,w_lr,exampleimagenumber);\n disp('align images');\n set = 28:48; %eyes and nose\n basepoints = landmarks_test(set,:);\n inputpoints = rawexamplelandmarks(set,:,:);\n \n parfor k=1:exampleimagenumber\n alignedexampleimage_hr(:,:,k) = F18_AlignExampleImageByLandmarkSet(hrexampleimages(:,:,k),inputpoints(:,:,k),basepoints);\n %F19 automatically convert uint8 input to double\n alignedexampleimage_lr(:,:,k) = F19a_GenerateLRImage_GaussianKernel(alignedexampleimage_hr(:,:,k),zooming,Gau_sigma);\n end\n \n cores = 2; % Use more cores for more speed\n\n if cores==1\n algo = 'cpu';\n else\n algo = 'cputiled';\n end\n patchsize_lr = 5;\n nn_iters = 5;\n\n A = repmat(img_y,[1 1 3]);\n testnumber = exampleimagenumber;\n xyandl2norm = zeros(h_lr,w_lr,3,testnumber,'int32');\n disp('patchmatching');\n parfor i=1:testnumber;\n %run patchmatch\n B = repmat(alignedexampleimage_lr(:,:,i),[1 1 3]);\n xyandl2norm(:,:,:,i) = nnmex(A, B, algo, patchsize_lr, nn_iters, [], [], [], [], cores); %the return totalpatchnumber int32\n end\n l2norm_double = double(xyandl2norm(:,:,3,:));\n [sortedl2norm, ix] = sort(l2norm_double,4);\n hrpatchextractdata = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate,3); %ii,r_lr_src,c_lr_src\n %here\n hrpatchsimilarity = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate);\n parameter_l2normtosimilarity = 625;\n for rl = 1:h_lr-patchsize_lr+1\n for cl = 1:w_lr-patchsize_lr+1\n for k=1:numberofHcandidate\n knnidx = ix(rl,cl,1,k);\n x = xyandl2norm(rl,cl,1,knnidx); %start from 0\n y = xyandl2norm(rl,cl,2,knnidx);\n clsource = x+1;\n rlsource = y+1;\n hrpatchextractdata(rl,cl,k,:) = reshape([knnidx rlsource clsource],[1 1 1 3]);\n hrpatchsimilarity(rl,cl,k) = exp(-sortedl2norm(rl,cl,1,knnidx)/parameter_l2normtosimilarity);\n end\n end\n end\n \n hrpatch = F39_ExtractAllHrPatches(patchsize_lr,zooming, hrpatchextractdata,alignedexampleimage_hr);\n hrpatch = F40_CompensateHRpatches(hrpatch, img_y, zooming, hrpatchextractdata,alignedexampleimage_lr);\n\n %mostsimilarinputpatchrecord = IF2_SearchForSelfSimilarPatchesL2Norm(img_y,patchsize_lr);\n \n %hrpatch_filtered = IF3_SimilarityFilter(hrpatch,hrpatchsimilarity,mostsimilarinputpatchrecord);\n \n %img_texture = IF4_BuildHRimagefromHRPatches(hrpatch_filtered,zooming);\n img_texture = IF4_BuildHRimagefromHRPatches(hrpatch,zooming);\n iternum = 1000;\n Tolf = 0.0001;\n breport = false;\n disp('backprojection for img_texture');\n img_texture_backprojection = F11d_BackProjection_GaussianKernel(img_y, img_texture, Gau_sigma, iternum,breport,Tolf);\n \n %extract the graident\n gradients_texture = F14_Img2Grad(img_texture_backprojection);\nend\nfunction scanresult = IF2_SearchForSelfSimilarPatchesL2Norm(img_y,patchsize_lr)\n %out:\n %scanresult: 3 x numberofFcandidate x (h_lr-patchsize+1) x (w_lr-patchsize+1)\n patcharea = patchsize_lr^2;\n [lh lw] = size(img_y);\n %Find self similar patches\n numberofFcandidate = 10;\n scanresult = zeros(3,numberofFcandidate,lh-patchsize_lr+1,lw-patchsize_lr+1); %scan results: r,c, similarity\n totalpatchnumber = (lh-patchsize_lr+1)*(lw-patchsize_lr+1);\n featurematrix = zeros(patcharea,totalpatchnumber);\n rec = zeros(2,totalpatchnumber);\n idx = 0;\n for rl=1:lh-patchsize_lr+1\n rl1 = rl+patchsize_lr-1;\n for cl=1:lw-patchsize_lr+1\n cl1 = cl+patchsize_lr-1;\n idx = idx + 1;\n rec(:,idx) = [rl;cl];\n featurematrix(:,idx) = reshape(img_y(rl:rl1,cl:cl1),patcharea,1);\n end\n end\n \n %search\n idx = 0;\n for rl=1:lh-patchsize_lr+1\n for cl=1:lw-patchsize_lr+1\n idx = idx + 1;\n fprintf('idx %d totalpatchnumber %d\\n',idx,totalpatchnumber);\n queryfeature = featurematrix(:,idx);\n diff = featurematrix - repmat(queryfeature,1,totalpatchnumber);\n sqr = sum(diff.^2);\n [ssqr ix] = sort(sqr);\n saveidx = 0;\n for j=1:numberofFcandidate+1 %add one to prevent find itself\n indexinsort = ix(j);\n sr = rec(1,indexinsort);\n sc = rec(2,indexinsort);\n %explanation: it is possible that there are 11 lr patches with the same appearance\n %and the input one is sorted at item indexed more than 11 so that sr and cl are insufficient\n %to prevenet the problem\n if sr ~= rl || sc ~= cl\n saveidx = saveidx + 1;\n if saveidx <= numberofFcandidate\n l2norm = sqrt(ssqr(j));\n similarity = exp(-l2norm/25);\n scanresult(1:3,saveidx,rl,cl) = [sr;sc;similarity];\n end\n end\n end\n end\n end\nend\nfunction hrpatch_filtered = IF3_SimilarityFilter(hrpatch,hrpatchsimilarity,mostsimilarinputpatches)\n %totalpatchnumber\n %hrpatch: patchsize_hr x patchsize_hr x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate\n %hrpatchsimilarity: (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate\n %mostsimilarinputpatches: 3 x numberofFcandidate x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1)\n %out\n %hrpatch_filtered: patchsize_hr x patchsize_hr x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1)\n zooming = 4;\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr /zooming;\n h_lr = size(hrpatch,3) + patchsize_lr -1;\n w_lr = size(hrpatch,4) + patchsize_lr -1;\n numberofHcandidate = size(hrpatch,5);\n numberofFcandidate = size(mostsimilarinputpatches,2);\n \n %allocate for out\n hrpatch_filtered = zeros(patchsize_hr,patchsize_hr,h_lr-patchsize_lr+1,w_lr-patchsize_lr+1);\n \n for rl= 1:h_lr-patchsize_lr+1\n fprintf('rl:%d total:%d\\n',rl,h_lr-patchsize_lr+1);\n for cl = 1:w_lr-patchsize_lr+1\n %load candidates\n H = zeros(patchsize_hr,patchsize_hr,numberofHcandidate);\n similarityHtolrpatch = zeros(numberofHcandidate,1);\n for j=1:numberofHcandidate\n H(:,:,j) = hrpatch(:,:,rl,cl,j); %H\n similarityHtolrpatch(j) = hrpatchsimilarity(rl,cl,j);\n end\n \n %self similar patch instance number\n similarityFtolrpatch = reshape( mostsimilarinputpatches(3,:,rl,cl) , [numberofFcandidate , 1]);\n \n %load all of the two step patches\n R = zeros(patchsize_hr,patchsize_hr,numberofFcandidate,numberofHcandidate);\n RSimbasedonF = zeros(numberofFcandidate,numberofHcandidate);\n for i=1:numberofFcandidate\n sr = mostsimilarinputpatches(1,i,rl,cl);\n sc = mostsimilarinputpatches(2,i,rl,cl);\n %hr candidate number\n for j=1:numberofHcandidate\n R(:,:,i,j) = hrpatch(:,:,sr,sc,j);\n RSimbasedonF(i,j) = hrpatchsimilarity(sr,sc,j);\n end\n end\n \n %here is a question, how to define the similarity between H and R?\n %L2norm?\n hscore = zeros(numberofHcandidate,1);\n for i=1:numberofHcandidate\n theH = H(:,:,i);\n for j=1:numberofFcandidate\n for k=1:numberofHcandidate\n theR = R(:,:,j,k);\n similarityRbasedonF = RSimbasedonF(j,k);\n %similarity between H and R\n diff = theH - theR;\n L2N = norm(diff(:));\n similarityRtoH = exp(- L2N/25); %the 25 is a parameter, need to be tuned totalpatchnumber the future\n hscore(i) = hscore(i) + similarityHtolrpatch(i) * similarityRbasedonF * similarityRtoH * similarityFtolrpatch(j);\n end\n end\n end\n [~, idx] = max(hscore);\n hrpatch_filtered(:,:,rl,cl) = hrpatch(:,:,rl,cl,idx(1));\n end\n end\nend\nfunction img_texture = IF4_BuildHRimagefromHRPatches(hrpatch,zooming)\n %reconstruct the high-resolution image\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr/zooming;\n h_lr = size(hrpatch,3) + patchsize_lr - 1;\n w_lr = size(hrpatch,4) + patchsize_lr - 1;\n h_expected = h_lr * zooming;\n w_expected = w_lr * zooming;\n img_texture = zeros(h_expected,w_expected);\n %most cases\n rpixelshift = 2; %this should be modified according to patchsize_lr\n cpixelshift = 2;\n for rl = 2:h_lr - patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n for cl = 2:w_lr - patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(9:12,9:12);\n end\n end\n \n %left\n cl = 1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %right\n cl = w_lr - patchsize_lr+1;\n ch = w_expected - 3*zooming+1;\n ch1 = w_expected;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %top\n rl = 1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %bottom\n rl = h_lr-patchsize_lr+1;\n rh = h_expected - 3*zooming+1;\n rh1 = h_expected;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %left-top corner\n rl=1;\n cl=1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %right-top corner\n rl=1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F40_CompensateHRpatches.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F40_CompensateHRpatches.m", "size": 1341, "source_encoding": "utf_8", "md5": "ece1f9e17377677e192ae02b610fb56a", "text": "%Chih-Yuan Yang\n%10/07/12\nfunction hrpatch_compensate = F40_CompensateHRpatches(hrpatch, img_y, zooming, hrpatchextractdata,lrexampleimages)\n %in:\n %hrpatchextractdata: (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate x 3 %ii,r_lr_src,c_lr_src\n\n hrpatch_compensate = zeros(size(hrpatch));\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr / zooming;\n [h_lr_active w_lr_active numberofHcandidate ~] = size(hrpatchextractdata);\n for rl = 1:h_lr_active\n rl1 = rl + patchsize_lr -1;\n for cl = 1:w_lr_active\n cl1 = cl + patchsize_lr -1;\n patch_lr = img_y(rl:rl1,cl:cl1);\n for k=1:numberofHcandidate\n patch_hr = hrpatch(:,:,rl,cl,k);\n ii = hrpatchextractdata(rl,cl,k,1);\n sr = hrpatchextractdata(rl,cl,k,2);\n sc = hrpatchextractdata(rl,cl,k,3);\n sr1 = sr+patchsize_lr-1;\n sc1 = sc+patchsize_lr-1;\n patch_lr_found = lrexampleimages(sr:sr1,sc:sc1,ii);\n diff_lr = patch_lr - patch_lr_found;\n diff_hr = imresize(diff_lr,zooming,'bilinear'); \n patch_hr_compensated = patch_hr + diff_hr;\n hrpatch_compensate(:,:,rl,cl,k) = patch_hr_compensated;\n end\n end\n end\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F18a_AlignExampleImageByTwoPoints.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F18a_AlignExampleImageByTwoPoints.m", "size": 459, "source_encoding": "utf_8", "md5": "5bdf68475e0ffcc19064b4878111e604", "text": "%Chih-Yuan Yang\n%09/15/12\n%Change from F18 to F18, two points only, no optimization\nfunction alignedexampleimage = F18a_AlignExampleImageByTwoPoints(exampleimage,inputpoints,basepoints)\n [h w d] = size(exampleimage);\n tform = cp2tform(inputpoints, basepoints,'nonreflective similarity');\n %generated the transform images\n XData = [1 w];\n YData = [1 h];\n alignedexampleimage = imtransform(exampleimage,tform,'XData',XData,'YData',YData);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U21a_DrawLandmarks_Points_ReturnHandle.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U21a_DrawLandmarks_Points_ReturnHandle.m", "size": 933, "source_encoding": "utf_8", "md5": "c9419254c3dd43155fec87373fe5e03a", "text": "%Chih-Yuan Yang\n%09/15/12\n%Sometimes the format of landmarks are coordinates rather than boxes\n%03/19/14 update the fucntion, the bdrawpose does not work\nfunction hfig = U21a_DrawLandmarks_Points_ReturnHandle(im, points, posemap,bshownumbers,bdrawpose,bvisible)\n if bvisible\n hfig = figure;\n else\n hfig = figure('Visible','off');\n end\n imshow(im);\n hold on;\n axis image;\n axis off;\n\n setnumber = size(points,1);\n if bdrawpose\n tx = (min(points(:,1)) + max(points(:,1)))/2; %tx means half face width\n ty = min(points(:,2)) - tx; \n text(tx,ty, num2str(posemap(b.c)),'fontsize',18,'color','c');\n end\n for i=1:setnumber\n x = points(i,1);\n y = points(i,2);\n \n plot(x,y,'r.','markersize',9);\n if bshownumbers\n text((x1+x2)/2,(y1+y2)/2, num2str(i), 'fontsize',9,'color','k');\n end\n end\n drawnow;\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F18b_AlignExampleImageByLandmarkSet.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F18b_AlignExampleImageByLandmarkSet.m", "size": 2230, "source_encoding": "utf_8", "md5": "b636615d164ee40bc5b4be7afc6a6730", "text": "%Chih-Yuan Yang\n%06/12/13\n%F18: only return the aligned image\n%F18a: AlignExampleImagesByTwoPoints, this must be an old function.\n%F18b: from F18, return the aligned landmarks\nfunction [alignedexampleimage, landmarks_aligned] = F18b_AlignExampleImageByLandmarkSet(exampleimage,inputpoints,basepoints)\n %use shift and scaling only as the initial variables\n initial_shift = mean(basepoints(:,:)) - mean(inputpoints(:,1));\n initial_deltax = initial_shift(1);\n initial_deltay = initial_shift(2);\n initial_lambda = 1;\n initial_theta = 0;\n initial_variable = [initial_theta, initial_lambda, initial_deltax, initial_deltay];\n \n %solve the optimization problem\n options = optimset('Display','off','TolX',1e-4);\n [x, fval]= fminsearch(@(x) OptProblem(x,inputpoints,basepoints), initial_variable, options);\n\n theta = x(1);\n lambda = x(2);\n deltax = x(3);\n deltay = x(4);\n transformmatrix = [lambda*cos(theta) -lambda*sin(theta) deltax;\n lambda*sin(theta) lambda*cos(theta) deltay];\n landmarks_input_rowvector = inputpoints;\n landmarks_input_colvector = landmarks_input_rowvector';\n num_landmarks = size(landmarks_input_colvector,2);\n landmarks_input_plus1 = cat(1,landmarks_input_colvector,ones(1,num_landmarks));\n landmarks_aligned = transformmatrix * landmarks_input_plus1;\n %take two points most apart to generate input points\n inputpoint1 = inputpoints(1,:)';\n setsize = size(inputpoints,1);\n dxdy = inputpoints - repmat(inputpoints(1,:),[setsize,1]);\n distsqr = sum(dxdy.^2,2);\n [sortresults, ix] = sort(distsqr,'descend');\n farestpointidx = ix(1);\n inputpoint2 = inputpoints(farestpointidx,:)';\n inputpoints_2points = cat(1, inputpoint1',inputpoint2');\n basepoint1 = transformmatrix * cat(1,inputpoint1,1);\n basepoint2 = transformmatrix * cat(1,inputpoint2,1);\n basepoints_2points = cat(1, basepoint1', basepoint2');\n \n [h, w, d] = size(exampleimage);\n tform = cp2tform(inputpoints_2points, basepoints_2points,'nonreflective similarity');\n %generated the transform images\n XData = [1 w];\n YData = [1 h];\n alignedexampleimage = imtransform(exampleimage,tform,'XData',XData,'YData',YData);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "T1_Facesmoother.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/T1_Facesmoother.m", "size": 2384, "source_encoding": "utf_8", "md5": "9169e2fd4a51a23c10447e4562d7a510", "text": "function img = T1_Facesmoother(img)\n% for super-resolution results smmother\ndimg = T2_MultiDoG(img);\nedge_bw = edge(rgb2gray(img),'canny',[0.01,0.12]);\nimg = T1_EdgeSmoothing(img, dimg, edge_bw);\nend\n\n% EDGESOMMTHIMG.m produce the edages by preserveing the edge-data in\n% ref_im, and generates new pixels of other regions from dst_im.\n% In face denoising it helps preserving the edge area. \n% In face beautification, it helps manipulating the mask's boundaries.\n% Input:\n% ref_im: original image or image layer;\n% dst_im: processed image or image layer\n% edge_bw: binary image of edge map;\n% Output:\n% rut_im: combined result image\n% Sifei Liu, 05/30/2013\n\nfunction rut_im = T1_EdgeSmoothing(ref_im, dst_im, edge_bw)\n%% parameters configuration\nw_im = double(edge_bw);\n% thr = 10;\n[r,c,n] = size(ref_im);\nthr = floor(min(r,c)/40);\nw_im(1:thr,:) = 1; w_im(end-thr:end,:) = 1;\nw_im(:,1:thr) = 1; w_im(:,end-thr:end) = 1;\n%% find the nearest edge point\n[er,ec] = find(edge_bw == 1);\ne_len = length(er);\nmat = T1_RangeMat(thr);\nfor m = 1:e_len\n if and(and(er(m)>thr+1,er(m)thr+1,ec(m)= 50\n hl = fspecial('gaussian',[3,3],sqrt(2));\n l1=2;l2=3;l3=5;\nelse\n hl = fspecial('gaussian',[2,2],sqrt(2));\n l1=1;l2=5;l3 = l2;\nend\nhh = fspecial('gaussian',[l,l],sqrt(l/2));\n\nif length(size(I)) == 3\n [L,a,b] = RGB2Lab(I);\n maxL = max(max(L));minL = min(min(L));\n L = Normalize(L,maxL,minL);\nelse\n maxL = max(max(I));minL = min(min(I));\n L = Normalize(I,maxL,minL);\nend\n\nDI = cell(1,layer+1);\nDI{1,1} = L;\nda = imfilter(a,hh);\ndb = imfilter(b,hh);\n\nfor m = 1:layer\n DI{1,m+1} = imfilter(DI{1,m},hl);\nend\nDh = imfilter(L,hh);\n\n% RL = DI{1,1}-(DI{1,l1}-DI{1,l2})-(DI{1,l3}-Dh);\nRL = DI{1,1}-(DI{1,3}-Dh);\n\nRI = ReNormalize(RL, maxL,minL);\n\nif length(size(I)) == 3\n RI = Lab2RGB(RI,da,db);\nend\nclose all\n% imshow(RI);\nend\n\nfunction I = Normalize(I,MAX,MIN)\nI = (I - MIN)/(MAX-MIN);\nend\n\nfunction I = ReNormalize(I, MAX, MIN)\nI = I * (MAX-MIN) + MIN;\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U23_PrepareResultFolder.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U23_PrepareResultFolder.m", "size": 1104, "source_encoding": "utf_8", "md5": "85619b24913ae5e317fd6fc41deeea7b", "text": "%Chih-Yuan Yang\n%09/15/12\n%simplify main function\nfunction para = U23_PrepareResultFolder(resultfolder,para)\n settingfolder = fullfile(resultfolder,sprintf('%s%d',para.SaveName,para.setting));\n tuningfolder = fullfile(settingfolder, sprintf('Tuning%d',para.tuning));\n para.resultfolder = resultfolder;\n para.settingfolder = settingfolder;\n para.tuningfolder = tuningfolder;\n \n U22_makeifnotexist(tuningfolder);\n if ~isempty(para.settingnote)\n fid = fopen(fullfile(settingfolder, 'SettingNote.txt'),'w');\n fprintf(fid,'%s',para.settingnote);\n fclose(fid);\n end\n \n if ~isempty(para.tuningnote)\n fid = fopen(fullfile(para.tuningfolder ,'TunningNote.txt'),'w');\n fprintf(fid,'%s',para.tuningnote);\n fclose(fid);\n end\n \n %copy parameter setting\n if ispc\n cmd = ['copy ' para.MainFileName '.m ' fullfile(para.tuningfolder, [para.MainFileName '_backup.m '])];\n elseif isunix\n cmd = ['cp ' para.MainFileName '.m ' fullfile(para.tuningfolder, [para.MainFileName '_backup.m '])];\n end\n dos(cmd);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F37e_GetTexturePatchMatch_PatchCompensate_SimilarityFilter.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F37e_GetTexturePatchMatch_PatchCompensate_SimilarityFilter.m", "size": 12898, "source_encoding": "utf_8", "md5": "7e0e3d9bfb628f725e1490725478cf54", "text": "%Chih-Yuan Yang\n%10/07/12\n%Use patchmatch to retrieve a texture background\nfunction [gradients_texture img_texture img_texture_backprojection] = ...\n F37e_GetTexturePatchMatch_PatchCompensate_SimilarityFilter(img_y, ...\n hrexampleimages, lrexampleimages)\n\n %parameter\n numberofHcandidate = 10;\n \n %start\n [h_lr, w_lr, exampleimagenumber] = size(lrexampleimages);\n [h_hr, w_hr, ~] = size(hrexampleimages);\n zooming = h_hr/h_lr;\n if zooming == 4\n Gau_sigma = 1.6;\n elseif zooming == 3\n Gau_sigma = 1.2;\n end\n \n cores = 2; % Use more cores for more speed\n\n if cores==1\n algo = 'cpu';\n else\n algo = 'cputiled';\n end\n patchsize_lr = 5;\n nn_iters = 5;\n %A =F38_ExtractFeatureFromAnImage(img_y);\n A = repmat(img_y,[1 1 3]);\n testnumber = exampleimagenumber;\n xyandl2norm = zeros(h_lr,w_lr,3,testnumber,'int32');\n %question: how to control the random seed in PatchMatch? in the nn.cpp, but it looks fixed because srand2() is never called\n %However, since the numberofHcandiate are different in Test34 (as 10) and Test35 (as 1), the retrieved patches are different\n disp('patchmatching');\n parfor i=1:testnumber;\n %run patchmatch\n B = repmat(lrexampleimages(:,:,i),[1 1 3]);\n xyandl2norm(:,:,:,i) = nnmex(A, B, algo, patchsize_lr, nn_iters, [], [], [], [], cores); %the return totalpatchnumber int32\n end\n l2norm_double = double(xyandl2norm(:,:,3,:));\n [sortedl2norm, ix] = sort(l2norm_double,4);\n hrpatchextractdata = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate,3); %ii,r_lr_src,c_lr_src\n %here\n hrpatchsimilarity = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate);\n parameter_l2normtosimilarity = 625;\n for rl = 1:h_lr-patchsize_lr+1\n for cl = 1:w_lr-patchsize_lr+1\n for k=1:numberofHcandidate\n knnidx = ix(rl,cl,1,k);\n x = xyandl2norm(rl,cl,1,knnidx); %start from 0\n y = xyandl2norm(rl,cl,2,knnidx);\n clsource = x+1;\n rlsource = y+1;\n hrpatchextractdata(rl,cl,k,:) = reshape([knnidx rlsource clsource],[1 1 1 3]);\n hrpatchsimilarity(rl,cl,k) = exp(-sortedl2norm(rl,cl,1,knnidx)/parameter_l2normtosimilarity);\n end\n end\n end\n \n hrpatch = F39_ExtractAllHrPatches(patchsize_lr,zooming, hrpatchextractdata,hrexampleimages);\n hrpatch = F40_CompensateHRpatches(hrpatch, img_y, zooming, hrpatchextractdata,lrexampleimages);\n\n mostsimilarinputpatchrecord = IF2_SearchForSelfSimilarPatchesL2Norm(img_y,patchsize_lr);\n \n hrpatch_filtered = IF3_SimilarityFilter(hrpatch,hrpatchsimilarity,mostsimilarinputpatchrecord);\n \n img_texture = IF4_BuildHRimagefromHRPatches(hrpatch_filtered,zooming);\n iternum = 1000;\n Tolf = 0.0001;\n breport = false;\n disp('backprojection for img_texture');\n img_texture_backprojection = F11d_BackProjection_GaussianKernel(img_y, img_texture, Gau_sigma, iternum,breport,Tolf);\n \n %extract the graident\n gradients_texture = F14_Img2Grad(img_texture_backprojection);\nend\nfunction scanresult = IF2_SearchForSelfSimilarPatchesL2Norm(img_y,patchsize_lr)\n %out:\n %scanresult: 3 x numberofFcandidate x (h_lr-patchsize+1) x (w_lr-patchsize+1)\n patcharea = patchsize_lr^2;\n [lh lw] = size(img_y);\n %Find self similar patches\n numberofFcandidate = 10;\n scanresult = zeros(3,numberofFcandidate,lh-patchsize_lr+1,lw-patchsize_lr+1); %scan results: r,c, similarity\n totalpatchnumber = (lh-patchsize_lr+1)*(lw-patchsize_lr+1);\n featurematrix = zeros(patcharea,totalpatchnumber);\n rec = zeros(2,totalpatchnumber);\n idx = 0;\n for rl=1:lh-patchsize_lr+1\n rl1 = rl+patchsize_lr-1;\n for cl=1:lw-patchsize_lr+1\n cl1 = cl+patchsize_lr-1;\n idx = idx + 1;\n rec(:,idx) = [rl;cl];\n featurematrix(:,idx) = reshape(img_y(rl:rl1,cl:cl1),patcharea,1);\n end\n end\n \n %search\n idx = 0;\n for rl=1:lh-patchsize_lr+1\n for cl=1:lw-patchsize_lr+1\n idx = idx + 1;\n fprintf('idx %d totalpatchnumber %d\\n',idx,totalpatchnumber);\n queryfeature = featurematrix(:,idx);\n diff = featurematrix - repmat(queryfeature,1,totalpatchnumber);\n sqr = sum(diff.^2);\n [ssqr ix] = sort(sqr);\n saveidx = 0;\n for j=1:numberofFcandidate+1 %add one to prevent find itself\n indexinsort = ix(j);\n sr = rec(1,indexinsort);\n sc = rec(2,indexinsort);\n %explanation: it is possible that there are 11 lr patches with the same appearance\n %and the input one is sorted at item indexed more than 11 so that sr and cl are insufficient\n %to prevenet the problem\n if sr ~= rl || sc ~= cl\n saveidx = saveidx + 1;\n if saveidx <= numberofFcandidate\n l2norm = sqrt(ssqr(j));\n similarity = exp(-l2norm/25);\n scanresult(1:3,saveidx,rl,cl) = [sr;sc;similarity];\n end\n end\n end\n end\n end\nend\nfunction hrpatch_filtered = IF3_SimilarityFilter(hrpatch,hrpatchsimilarity,mostsimilarinputpatches)\n %totalpatchnumber\n %hrpatch: patchsize_hr x patchsize_hr x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate\n %hrpatchsimilarity: (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate\n %mostsimilarinputpatches: 3 x numberofFcandidate x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1)\n %out\n %hrpatch_filtered: patchsize_hr x patchsize_hr x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1)\n zooming = 4;\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr /zooming;\n h_lr = size(hrpatch,3) + patchsize_lr -1;\n w_lr = size(hrpatch,4) + patchsize_lr -1;\n numberofHcandidate = size(hrpatch,5);\n numberofFcandidate = size(mostsimilarinputpatches,2);\n \n %allocate for out\n hrpatch_filtered = zeros(patchsize_hr,patchsize_hr,h_lr-patchsize_lr+1,w_lr-patchsize_lr+1);\n \n for rl= 1:h_lr-patchsize_lr+1\n fprintf('rl:%d total:%d\\n',rl,h_lr-patchsize_lr+1);\n for cl = 1:w_lr-patchsize_lr+1\n %load candidates\n H = zeros(patchsize_hr,patchsize_hr,numberofHcandidate);\n similarityHtolrpatch = zeros(numberofHcandidate,1);\n for j=1:numberofHcandidate\n H(:,:,j) = hrpatch(:,:,rl,cl,j); %H\n similarityHtolrpatch(j) = hrpatchsimilarity(rl,cl,j);\n end\n \n %self similar patch instance number\n similarityFtolrpatch = reshape( mostsimilarinputpatches(3,:,rl,cl) , [numberofFcandidate , 1]);\n \n %load all of the two step patches\n R = zeros(patchsize_hr,patchsize_hr,numberofFcandidate,numberofHcandidate);\n RSimbasedonF = zeros(numberofFcandidate,numberofHcandidate);\n for i=1:numberofFcandidate\n sr = mostsimilarinputpatches(1,i,rl,cl);\n sc = mostsimilarinputpatches(2,i,rl,cl);\n %hr candidate number\n for j=1:numberofHcandidate\n R(:,:,i,j) = hrpatch(:,:,sr,sc,j);\n RSimbasedonF(i,j) = hrpatchsimilarity(sr,sc,j);\n end\n end\n \n %here is a question, how to define the similarity between H and R?\n %L2norm?\n hscore = zeros(numberofHcandidate,1);\n for i=1:numberofHcandidate\n theH = H(:,:,i);\n for j=1:numberofFcandidate\n for k=1:numberofHcandidate\n theR = R(:,:,j,k);\n similarityRbasedonF = RSimbasedonF(j,k);\n %similarity between H and R\n diff = theH - theR;\n L2N = norm(diff(:));\n similarityRtoH = exp(- L2N/25); %the 25 is a parameter, need to be tuned totalpatchnumber the future\n hscore(i) = hscore(i) + similarityHtolrpatch(i) * similarityRbasedonF * similarityRtoH * similarityFtolrpatch(j);\n end\n end\n end\n [~, idx] = max(hscore);\n hrpatch_filtered(:,:,rl,cl) = hrpatch(:,:,rl,cl,idx(1));\n end\n end\nend\nfunction img_texture = IF4_BuildHRimagefromHRPatches(hrpatch,zooming)\n %reconstruct the high-resolution image\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr/zooming;\n h_lr = size(hrpatch,3) + patchsize_lr - 1;\n w_lr = size(hrpatch,4) + patchsize_lr - 1;\n h_expected = h_lr * zooming;\n w_expected = w_lr * zooming;\n img_texture = zeros(h_expected,w_expected);\n %most cases\n rpixelshift = 2; %this should be modified according to patchsize_lr\n cpixelshift = 2;\n for rl = 2:h_lr - patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n for cl = 2:w_lr - patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(9:12,9:12);\n end\n end\n \n %left\n cl = 1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %right\n cl = w_lr - patchsize_lr+1;\n ch = w_expected - 3*zooming+1;\n ch1 = w_expected;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %top\n rl = 1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %bottom\n rl = h_lr-patchsize_lr+1;\n rh = h_expected - 3*zooming+1;\n rh1 = h_expected;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %left-top corner\n rl=1;\n cl=1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %right-top corner\n rl=1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U24_sc.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U24_sc.m", "size": 1764, "source_encoding": "utf_8", "md5": "fed7b2eda56837174f633232855bd7f8", "text": "%Chih-Yuan Yang\n%10/11/12\n%Usage\n%U24_sc(img,[0 1]);\nfunction hfig = U24_sc(varargin)\n bSetColormapGray = false;\n for j=1:nargin\n if isa(varargin{j},'char')\n ControlString = varargin{j};\n StringLength = length(ControlString);\n for i=1:StringLength\n switch ControlString(i)\n case 'c'\n close all\n case 'g'\n bSetColormapGray = true;\n otherwise\n end\n end\n end\n \n [h w] = size(varargin{j});\n if h == 1 && w == 2 && ~isa(varargin{j},'char')\n caxis_min_high = varargin{j};\n end\n end\n \n for i=1:nargin\n if ~isa(varargin{i},'char')\n [h w] = size(varargin{i});\n if ~(h==1 && w==2)\n layer = size(varargin{i},3);\n for j=1:layer\n hfig = figure;\n imagesc(varargin{i}(:,:,j));\n colorbar\n axis image\n axis on\n if layer == 1\n string = inputname(i);\n else\n string = sprintf('%s %d',inputname(i), j);\n end\n TitleString = regexprep(string,'\\_','\\\\_');\n title(TitleString);\n set(hfig,'Name',string,'NumberTitle','off');\n \n if bSetColormapGray\n colormap gray\n end\n if exist('caxis_min_high','var')\n caxis(caxis_min_high);\n end\n end\n end\n end\n end\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F6f_RetriveImage_DrawFlowChart.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F6f_RetriveImage_DrawFlowChart.m", "size": 2688, "source_encoding": "utf_8", "md5": "4062d227dc2025015b7a09ca66eddc0d", "text": "%Chih-Yuan Yang\n%2/2/15\n%F6d: return the alinged images to draw the flowchart. I update the function F19a to F19c.\n%F6f: The parallel command parfor is unstall on Linux. Thus I change it back to normal for loop.\nfunction [retrievedhrimage, retrievedlrimage, retrievedidx, alignedexampleimage_hr, alignedexampleimage_lr] = ...\n F6f_RetriveImage_DrawFlowChart(testimage_lr, ...\n rawexampleimage, inputpoints, basepoints, mask_lr, zooming, Gau_sigma, glasslist, bglassavoid)\n %the rawexampleimage should be double\n if ~isa(rawexampleimage,'uint8')\n error('wrong class');\n end\n\n [h_hr, w_hr, exampleimagenumber] = size(rawexampleimage);\n [h_lr, w_lr] = size(testimage_lr);\n %find the transform matrix by solving an optimization problem\n alignedexampleimage_hr = zeros(h_hr,w_hr,exampleimagenumber,'uint8'); %set as uint8 to reduce memory demand\n alignedexampleimage_lr = zeros(h_lr,w_lr,exampleimagenumber);\n for i=1:exampleimagenumber\n alignedexampleimage_hr(:,:,i) = F18b_AlignExampleImageByLandmarkSet(rawexampleimage(:,:,i),inputpoints(:,:,i),basepoints);\n %F19 automatically convert uint8 input to double\n alignedexampleimage_lr(:,:,i) = F19c_GenerateLRImage_GaussianKernel(alignedexampleimage_hr(:,:,i),zooming,Gau_sigma);\n end\n\n [r_set, c_set] = find(mask_lr);\n top = min(r_set);\n bottom = max(r_set);\n left = min(c_set);\n right = max(c_set);\n area_test = im2double(testimage_lr(top:bottom,left:right));\n area_mask = mask_lr(top:bottom,left:right);\n area_test_aftermask = area_test .* area_mask;\n %extract feature from the eyerange, the features are the gradient of LR eye region\n feature_test = F24_ExtractFeatureFromArea(area_test_aftermask); %the unit is double\n\n %search for the thousand example images to find the most similar eyerange\n normvalue = zeros(exampleimagenumber,1);\n for j=1:exampleimagenumber\n examplearea_lr = alignedexampleimage_lr(top:bottom,left:right,j);\n examplearea_lr_aftermask = examplearea_lr .* area_mask;\n feature_example_lr = F24_ExtractFeatureFromArea(examplearea_lr_aftermask); %the unit is double\n normvalue(j) = norm(feature_test - feature_example_lr);\n end\n %find the small norm\n [sortnorm ix] = sort(normvalue);\n %some of them are very similar\n\n %only return the 1nn\n if bglassavoid\n for k=1:exampleimagenumber\n if glasslist(ix(k)) == false\n break\n end\n end\n else\n k =1;\n end\n retrievedhrimage = alignedexampleimage_hr(:,:,ix(k)); \n retrievedlrimage = alignedexampleimage_lr(:,:,ix(k));\n retrievedidx = ix(k);\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U26_DrawMask.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U26_DrawMask.m", "size": 971, "source_encoding": "utf_8", "md5": "b784d543172316f3d30cd8a78746ed36", "text": "%Chih-Yuan Yang\n%10/10/12\nfunction U26_DrawMask(img, componentrecord, bsave, fn_save)\n if nargin < 3\n bsave = false;\n end\n codefolder = fileparts(pwd);\n addpath(fullfile(codefolder,'Lib','YIQConverter'));\n [h w] = size(img);\n img = repmat(img,[1 1 3]); %prepare for color\n img_yiq = RGB2YIQ(img);\n img_y = img_yiq(:,:,1);\n img_iq = img_yiq(:,:,2:3);\n \n color{1} = [1 0 0]; %red\n color{2} = [1 1 0]; %yellow\n color{3} = [0 1 0]; %green\n color{4} = [0 0 1]; %blue\n \n for k=1:4\n rgb_color = reshape(color{k},[1 1 3]);\n yiq_color = RGB2YIQ(rgb_color);\n iq_color = yiq_color(2:3);\n mask = componentrecord(k).mask_lr;\n img_iq = img_iq + repmat(iq_color, [h w 1]) .* repmat(mask, [1 1 2]);\n end\n \n img_yiq = cat(3,img_y,img_iq);\n img_rgb = YIQ2RGB(img_yiq);\n \n if bsave\n imwrite(img_rgb,fn_save);\n else\n figure\n imshow(img_rgb);\n end\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U25a_ReadSemaphoreFile.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U25a_ReadSemaphoreFile.m", "size": 321, "source_encoding": "utf_8", "md5": "b1430f2eb5cfb5ee4f131ef486b3272f", "text": "%Chih-Yuan Yang\n%08/28/13\n%To parallel run Glasner's algorithm\n%Just read, do not change the semaphore file\nfunction [arr_filename, arr_label] = U25a_ReadSemaphoreFile(fn_symphony)\n fid = fopen(fn_symphony,'r+');\n C = textscan(fid,'%05d %s %d\\n');\n arr_filename = C{2};\n arr_label = C{3};\n fclose(fid);\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F29_AddPixelIdxFromCoor.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F29_AddPixelIdxFromCoor.m", "size": 360, "source_encoding": "utf_8", "md5": "df5423a57f2287ff5eee471e2b6ce3ed", "text": "%Chih-Yuan Yang\n%10/01/12\n%Correct error, the mapping from coordinate to index is round rather than floor or ceil\nfunction region = F29_AddPixelIdxFromCoor(region)\n region.left_idx = round(region.left_coor);\n region.top_idx = round(region.top_coor);\n region.right_idx = round(region.right_coor);\n region.bottom_idx = round(region.bottom_coor);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F27b_SmoothnessPreserving.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F27b_SmoothnessPreserving.m", "size": 7564, "source_encoding": "utf_8", "md5": "9a939481df544fadc2c13f24d293c052", "text": "%Chih-Yuan Yang\n%1/3/15\n%Seperate this function from F21, because this function is required in training phase\n%F27a: save similarity_lr and similarity_hr to draw figures required for the paper\n%F27b: Now I run the code on a Linux machine through SSH. There is no GUI so that I\n%would like to disable all image rendering.\nfunction img_out = F27b_SmoothnessPreserving(img_y,zooming,Gau_sigma)\n img_bb = imresize(img_y,zooming);\n\n %compute the similarity from low\n Coef = 10;\n Sqrt_low = IF1_SimilarityEvaluation(img_y); %I may need more directions, 16 may be too small\n Similarity_low = exp(-Sqrt_low*Coef);\n [h_high, w_high] = size(img_bb);\n ExpectedSimilarity = zeros(h_high,w_high,16);\n %upsamplin the similarity\n for dir=1:16\n ExpectedSimilarity(:,:,dir) = imresize(Similarity_low(:,:,dir),zooming,'bilinear');\n end\n\n %refind the Grad_high by Similarity_high\n LoopNumber = 10;\n img = img_bb;\n for loop = 1:LoopNumber\n %refine gradient by ExpectedSimilarity\n ValueSum = zeros(h_high,w_high);\n WeightSum = sum(ExpectedSimilarity,3); %if thw weight sum is low, it is unsuitable to generate the grad by interpolation\n for dir = 1:16\n [MoveOp, N] = IF3_GetMoveKernel16(dir);\n if N == 1\n MovedData = imfilter(img,MoveOp{1},'replicate');\n else %N ==2\n MovedData1 = imfilter(img,MoveOp{1},'replicate');\n MovedData2 = imfilter(img,MoveOp{2},'replicate');\n MovedData = (MovedData1 + MovedData2)/2;\n end\n Product = MovedData .* ExpectedSimilarity(:,:,dir);\n ValueSum = ValueSum + Product;\n end\n I = ValueSum ./ WeightSum;\n \n %intensity compensate\n diff_lr = F19c_GenerateLRImage_GaussianKernel(I,zooming,Gau_sigma) - img_y;\n diff_hr = F26_UpsampleAndBlur(diff_lr,zooming,Gau_sigma);\n Grad0 = diff_hr;\n Term_LowHigh_in = F28_ComputeSquareSumLowHighDiff(I,img_y,Gau_sigma);\n I_in = I; %make a copy, restore the value if all beta fails\n bDecrease = false;\n %should I use the strict constraint?\n tau = 0.2;\n for line_search_loop=1:10\n %line search for the beta, fixed 1/32 is not a good choice\n I = I_in - tau * Grad0;\n Term_LowHigh_out = F28_ComputeSquareSumLowHighDiff(I,img_y,Gau_sigma);\n if Term_LowHigh_out < Term_LowHigh_in\n bDecrease = true;\n break;\n else\n tau = tau * 0.5;\n end\n end\n \n if bDecrease == true\n I_best = I;\n else\n break;\n end\n img = I_best;\n end\n img_out = img;\nend\nfunction SqrtData = IF1_SimilarityEvaluation(Img_in)\n [h, w] = size(Img_in);\n SqrtData = zeros(h,w,16);\n \n f3x3 = ones(3);\n for i = 1:16\n [DiffOp, N] = IF2_RetGradientKernel16(i);\n if N == 1\n Diff = imfilter(Img_in,DiffOp{1},'symmetric');\n else\n Diff1 = imfilter(Img_in,DiffOp{1},'symmetric');\n Diff2 = imfilter(Img_in,DiffOp{2},'symmetric');\n Diff = (Diff1+Diff2)/2;\n end\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Mean = Sum/9;\n SqrtData(:,:,i) = sqrt(Mean);\n end\nend\nfunction [DiffOp, N] = IF2_RetGradientKernel16(dir)\n DiffOp = cell(2,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n DiffOp{1} = f{1};\n DiffOp{2} = [];\n case 2\n N = 2;\n DiffOp{1} = f{1};\n DiffOp{2} = f{2};\n case 3\n N = 1; \n DiffOp{1} = f{2};\n DiffOp{2} = [];\n case 4\n N = 2;\n DiffOp{1} = f{2};\n DiffOp{2} = f{3};\n case 5\n N = 1;\n DiffOp{1} = f{3};\n DiffOp{2} = [];\n case 6\n N = 2;\n DiffOp{1} = f{3};\n DiffOp{2} = f{4};\n case 7\n N = 1;\n DiffOp{1} = f{4};\n DiffOp{2} = [];\n case 8\n N = 2;\n DiffOp{1} = f{4};\n DiffOp{2} = f{5};\n case 9\n N = 1;\n DiffOp{1} = f{5};\n DiffOp{2} = [];\n case 10\n N = 2;\n DiffOp{1} = f{5};\n DiffOp{2} = f{6};\n case 11\n DiffOp{1} = f{6};\n DiffOp{2} = [];\n N = 1;\n case 12\n N = 2;\n DiffOp{1} = f{6};\n DiffOp{2} = f{7};\n case 13\n N = 1;\n DiffOp{1} = f{7};\n DiffOp{2} = [];\n case 14\n N = 2;\n DiffOp{1} = f{7};\n DiffOp{2} = f{8};\n case 15\n DiffOp{1} = f{8};\n DiffOp{2} = [];\n N = 1;\n case 16\n N = 2;\n DiffOp{1} = f{8};\n DiffOp{2} = f{1};\n end\nend\nfunction [Kernel, N] = IF3_GetMoveKernel16(dir)\n Kernel = cell(2,1);\n f{1} = [0 0 0;\n 0 0 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 0 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 0 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 0 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 0 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 0 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 0 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 0 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n Kernel{1} = f{1};\n Kernel{2} = [];\n case 2\n N = 2;\n Kernel{1} = f{1};\n Kernel{2} = f{2};\n case 3\n N = 1; \n Kernel{1} = f{2};\n Kernel{2} = [];\n case 4\n N = 2;\n Kernel{1} = f{2};\n Kernel{2} = f{3};\n case 5\n N = 1;\n Kernel{1} = f{3};\n Kernel{2} = [];\n case 6\n N = 2;\n Kernel{1} = f{3};\n Kernel{2} = f{4};\n case 7\n N = 1;\n Kernel{1} = f{4};\n Kernel{2} = [];\n case 8\n N = 2;\n Kernel{1} = f{4};\n Kernel{2} = f{5};\n case 9\n N = 1;\n Kernel{1} = f{5};\n Kernel{2} = [];\n case 10\n N = 2;\n Kernel{1} = f{5};\n Kernel{2} = f{6};\n case 11\n Kernel{1} = f{6};\n Kernel{2} = [];\n N = 1;\n case 12\n N = 2;\n Kernel{1} = f{6};\n Kernel{2} = f{7};\n case 13\n N = 1;\n Kernel{1} = f{7};\n Kernel{2} = [];\n case 14\n N = 2;\n Kernel{1} = f{7};\n Kernel{2} = f{8};\n case 15\n Kernel{1} = f{8};\n Kernel{2} = [];\n N = 1;\n case 16\n N = 2;\n Kernel{1} = f{8};\n Kernel{2} = f{1};\n end\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F7_ComputePSNR_SSIM_DIIVINE.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F7_ComputePSNR_SSIM_DIIVINE.m", "size": 1163, "source_encoding": "utf_8", "md5": "5eee7e53e792342dbae52c1943352c21", "text": "%09/12/12\n%Chih-Yuan Yang, EECS, UC Merced\n%Compute PSNR, SSIM, DIVINE\n%If you encounter a MATLAB error: Undefined function 'buildSFpyr' for input arguments of type 'double'.\n%You need to install libraries which are dependencies of DIIVINE\n%Steerable Pyramid Toolbox, Download from: http://www.cns.nyu.edu/~eero/steerpyr/\n% action ==>compile mex in MEX subfolder, copy the pointOp.mexw64 to matlabPyrTools folder\n% ==>addpath('matlabPyrTools')\n%LibSVM package for MATLAB, Download from: http://www.csie.ntu.edu.tw/~cjlin/libsvm/\n\nfunction [PSNR, SSIM, DIIVINE] = F7_ComputePSNR_SSIM_DIIVINE(img_gt, img_input, bComputeDIIVINE)\n %check the type\n if isa(img_gt,'double')\n img_gt = im2uint8(img_gt);\n img_input = im2uint8(img_input);\n end\n \n if size(img_gt,3) > 1\n img_gt = rgb2gray(img_gt);\n end\n if size(img_input,3) > 1\n img_input = rgb2gray(img_input);\n end\n PSNR = measerr(img_gt, img_input);\n SSIM = ssim( img_gt, img_input);\n\n DIIVINE = 0;\n if ~exist('bComputeDIIVINE','var')\n bComputeDIIVINE = false;\n end\n if bComputeDIIVINE\n DIIVINE = divine(img_input);\n end\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U23a_PrepareResultFolder.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U23a_PrepareResultFolder.m", "size": 1137, "source_encoding": "utf_8", "md5": "3560d9fcfec329fa70657e0caeabb913", "text": "%Chih-Yuan Yang\n%09/25/12\n%from U23 to U23a, change the name of setting folder\nfunction para = U23a_PrepareResultFolder(resultfolder,para)\n settingfolder = fullfile(resultfolder,sprintf('%s%d',para.settingname, para.setting));\n tuningfolder = fullfile(settingfolder, sprintf('Tuning%d',para.tuning));\n para.resultfolder = resultfolder;\n para.settingfolder = settingfolder;\n para.tuningfolder = tuningfolder;\n \n U22_makeifnotexist(tuningfolder);\n if ~isempty(para.settingnote)\n fid = fopen(fullfile(settingfolder, 'SettingNote.txt'),'w');\n fprintf(fid,'%s',para.settingnote);\n fclose(fid);\n end\n \n if ~isempty(para.tuningnote)\n fid = fopen(fullfile(para.tuningfolder ,'TuningNote.txt'),'w');\n fprintf(fid,'%s',para.tuningnote);\n fclose(fid);\n end\n \n %copy parameter setting\n if ispc\n cmd = ['copy ' para.mainfilename '.m ' fullfile(para.tuningfolder, [para.mainfilename '_backup.m '])];\n elseif isunix\n cmd = ['cp ' para.mainfilename '.m ' fullfile(para.tuningfolder, [para.mainfilename '_backup.m '])];\n end\n dos(cmd);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F37b_GetTexturePatchMatch_PatchCompensate.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F37b_GetTexturePatchMatch_PatchCompensate.m", "size": 12865, "source_encoding": "utf_8", "md5": "849b03c185bdc637acc0f2492918d37b", "text": "%Chih-Yuan Yang\n%10/07/12\n%Use patchmatch to retrieve a texture background\nfunction [gradients_texture img_texture img_texture_backprojection] = F37b_GetTexturePatchMatch_PatchCompensate(img_y, ...\n hrexampleimages, lrexampleimages)\n\n %parameter\n numberofHcandidate = 1;\n \n %start\n [h_lr, w_lr, exampleimagenumber] = size(lrexampleimages);\n [h_hr, w_hr, ~] = size(hrexampleimages);\n zooming = h_hr/h_lr;\n if zooming == 4\n Gau_sigma = 1.6;\n elseif zooming == 3\n Gau_sigma = 1.2;\n end\n \n cores = 2; % Use more cores for more speed\n\n if cores==1\n algo = 'cpu';\n else\n algo = 'cputiled';\n end\n patchsize_lr = 5;\n nn_iters = 5;\n %A =F38_ExtractFeatureFromAnImage(img_y);\n A = repmat(img_y,[1 1 3]);\n testnumber = exampleimagenumber;\n xyandl2norm = zeros(h_lr,w_lr,3,testnumber,'int32');\n %question: how to control the random seed in PatchMatch? in the nn.cpp, but it looks fixed because srand2() is never called\n %However, since the numberofHcandiate are different in Test34 (as 10) and Test35 (as 1), the retrieved patches are different\n disp('patchmatching');\n parfor i=1:testnumber;\n %run patchmatch\n B = repmat(lrexampleimages(:,:,i),[1 1 3]);\n xyandl2norm(:,:,:,i) = nnmex(A, B, algo, patchsize_lr, nn_iters, [], [], [], [], cores); %the return totalpatchnumber int32\n end\n l2norm_double = double(xyandl2norm(:,:,3,:));\n [sortedl2norm, ix] = sort(l2norm_double,4);\n hrpatchextractdata = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate,3); %ii,r_lr_src,c_lr_src\n %here\n hrpatchsimilarity = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate);\n parameter_l2normtosimilarity = 625;\n for rl = 1:h_lr-patchsize_lr+1\n for cl = 1:w_lr-patchsize_lr+1\n for k=1:numberofHcandidate\n knnidx = ix(rl,cl,1,k);\n x = xyandl2norm(rl,cl,1,knnidx); %start from 0\n y = xyandl2norm(rl,cl,2,knnidx);\n clsource = x+1;\n rlsource = y+1;\n hrpatchextractdata(rl,cl,k,:) = reshape([knnidx rlsource clsource],[1 1 1 3]);\n hrpatchsimilarity(rl,cl,k) = exp(-sortedl2norm(rl,cl,1,knnidx)/parameter_l2normtosimilarity);\n end\n end\n end\n \n hrpatch = F39_ExtractAllHrPatches(patchsize_lr,zooming, hrpatchextractdata,hrexampleimages);\n hrpatch = F40_CompensateHRpatches(hrpatch, img_y, zooming, hrpatchextractdata,lrexampleimages);\n\n% mostsimilarinputpatchrecord = IF2_SearchForSelfSimilarPatchesL2Norm(img_y,patchsize_lr);\n \n% hrpatch_filtered = IF3_SimilarityFilter(hrpatch,hrpatchsimilarity,mostsimilarinputpatchrecord);\n \n img_texture = IF4_BuildHRimagefromHRPatches(hrpatch,zooming);\n iternum = 1000;\n Tolf = 0.0001;\n breport = false;\n disp('backprojection for img_texture');\n img_texture_backprojection = F11d_BackProjection_GaussianKernel(img_y, img_texture, Gau_sigma, iternum,breport,Tolf);\n \n %extract the graident\n gradients_texture = F14_Img2Grad(img_texture_backprojection);\nend\nfunction scanresult = IF2_SearchForSelfSimilarPatchesL2Norm(img_y,patchsize_lr)\n %out:\n %scanresult: 3 x numberofFcandidate x (h_lr-patchsize+1) x (w_lr-patchsize+1)\n patcharea = patchsize_lr^2;\n [lh lw] = size(img_y);\n %Find self similar patches\n numberofFcandidate = 10;\n scanresult = zeros(3,numberofFcandidate,lh-patchsize_lr+1,lw-patchsize_lr+1); %scan results: r,c, similarity\n totalpatchnumber = (lh-patchsize_lr+1)*(lw-patchsize_lr+1);\n featurematrix = zeros(patcharea,totalpatchnumber);\n rec = zeros(2,totalpatchnumber);\n idx = 0;\n for rl=1:lh-patchsize_lr+1\n rl1 = rl+patchsize_lr-1;\n for cl=1:lw-patchsize_lr+1\n cl1 = cl+patchsize_lr-1;\n idx = idx + 1;\n rec(:,idx) = [rl;cl];\n featurematrix(:,idx) = reshape(img_y(rl:rl1,cl:cl1),patcharea,1);\n end\n end\n \n %search\n idx = 0;\n for rl=1:lh-patchsize_lr+1\n for cl=1:lw-patchsize_lr+1\n idx = idx + 1;\n fprintf('idx %d totalpatchnumber %d\\n',idx,totalpatchnumber);\n queryfeature = featurematrix(:,idx);\n diff = featurematrix - repmat(queryfeature,1,totalpatchnumber);\n sqr = sum(diff.^2);\n [ssqr ix] = sort(sqr);\n saveidx = 0;\n for j=1:numberofFcandidate+1 %add one to prevent find itself\n indexinsort = ix(j);\n sr = rec(1,indexinsort);\n sc = rec(2,indexinsort);\n %explanation: it is possible that there are 11 lr patches with the same appearance\n %and the input one is sorted at item indexed more than 11 so that sr and cl are insufficient\n %to prevenet the problem\n if sr ~= rl || sc ~= cl\n saveidx = saveidx + 1;\n if saveidx <= numberofFcandidate\n l2norm = sqrt(ssqr(j));\n similarity = exp(-l2norm/25);\n scanresult(1:3,saveidx,rl,cl) = [sr;sc;similarity];\n end\n end\n end\n end\n end\nend\nfunction hrpatch_filtered = IF3_SimilarityFilter(hrpatch,hrpatchsimilarity,mostsimilarinputpatches)\n %totalpatchnumber\n %hrpatch: patchsize_hr x patchsize_hr x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate\n %hrpatchsimilarity: (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate\n %mostsimilarinputpatches: 3 x numberofFcandidate x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1)\n %out\n %hrpatch_filtered: patchsize_hr x patchsize_hr x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1)\n zooming = 4;\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr /zooming;\n h_lr = size(hrpatch,3) + patchsize_lr -1;\n w_lr = size(hrpatch,4) + patchsize_lr -1;\n numberofHcandidate = size(hrpatch,5);\n numberofFcandidate = size(mostsimilarinputpatches,2);\n \n %allocate for out\n hrpatch_filtered = zeros(patchsize_hr,patchsize_hr,h_lr-patchsize_lr+1,w_lr-patchsize_lr+1);\n \n for rl= 1:h_lr-patchsize_lr+1\n fprintf('rl:%d total:%d\\n',rl,h_lr-patchsize_lr+1);\n for cl = 1:w_lr-patchsize_lr+1\n %load candidates\n H = zeros(patchsize_hr,patchsize_hr,numberofHcandidate);\n similarityHtolrpatch = zeros(numberofHcandidate,1);\n for j=1:numberofHcandidate\n H(:,:,j) = hrpatch(:,:,rl,cl,j); %H\n similarityHtolrpatch(j) = hrpatchsimilarity(rl,cl,j);\n end\n \n %self similar patch instance number\n similarityFtolrpatch = reshape( mostsimilarinputpatches(3,:,rl,cl) , [numberofFcandidate , 1]);\n \n %load all of the two step patches\n R = zeros(patchsize_hr,patchsize_hr,numberofFcandidate,numberofHcandidate);\n RSimbasedonF = zeros(numberofFcandidate,numberofHcandidate);\n for i=1:numberofFcandidate\n sr = mostsimilarinputpatches(1,i,rl,cl);\n sc = mostsimilarinputpatches(2,i,rl,cl);\n %hr candidate number\n for j=1:numberofHcandidate\n R(:,:,i,j) = hrpatch(:,:,sr,sc,j);\n RSimbasedonF(i,j) = hrpatchsimilarity(sr,sc,j);\n end\n end\n \n %here is a question, how to define the similarity between H and R?\n %L2norm?\n hscore = zeros(numberofHcandidate,1);\n for i=1:numberofHcandidate\n theH = H(:,:,i);\n for j=1:numberofFcandidate\n for k=1:numberofHcandidate\n theR = R(:,:,j,k);\n similarityRbasedonF = RSimbasedonF(j,k);\n %similarity between H and R\n diff = theH - theR;\n L2N = norm(diff(:));\n similarityRtoH = exp(- L2N/25); %the 25 is a parameter, need to be tuned totalpatchnumber the future\n hscore(i) = hscore(i) + similarityHtolrpatch(i) * similarityRbasedonF * similarityRtoH * similarityFtolrpatch(j);\n end\n end\n end\n [~, idx] = max(hscore);\n hrpatch_filtered(:,:,rl,cl) = hrpatch(:,:,rl,cl,idx(1));\n end\n end\nend\nfunction img_texture = IF4_BuildHRimagefromHRPatches(hrpatch,zooming)\n %reconstruct the high-resolution image\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr/zooming;\n h_lr = size(hrpatch,3) + patchsize_lr - 1;\n w_lr = size(hrpatch,4) + patchsize_lr - 1;\n h_expected = h_lr * zooming;\n w_expected = w_lr * zooming;\n img_texture = zeros(h_expected,w_expected);\n %most cases\n rpixelshift = 2; %this should be modified according to patchsize_lr\n cpixelshift = 2;\n for rl = 2:h_lr - patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n for cl = 2:w_lr - patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(9:12,9:12);\n end\n end\n \n %left\n cl = 1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %right\n cl = w_lr - patchsize_lr+1;\n ch = w_expected - 3*zooming+1;\n ch1 = w_expected;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %top\n rl = 1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %bottom\n rl = h_lr-patchsize_lr+1;\n rh = h_expected - 3*zooming+1;\n rh1 = h_expected;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %left-top corner\n rl=1;\n cl=1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %right-top corner\n rl=1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U12_AlignExampleImageByTestEyes.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U12_AlignExampleImageByTestEyes.m", "size": 797, "source_encoding": "utf_8", "md5": "0c2c35f5e7ac99a7309df8637e349a4c", "text": "%Chih-Yuan Yang\n%08/31/12\nfunction [alignedexampleimage alignedlandmarks] = U12_AlignExampleImageByTestEyes(exampleimage,landmarks,eyecenter,testeyecenter)\n [h w exampleimagenumber] = size(exampleimage);\n alignedexampleimage = zeros(h, w, exampleimagenumber,'uint8');\n alignedlandmarks = zeros(68,2,exampleimagenumber);\n parfor i=1:exampleimagenumber\n %show the message if not matlatpool\n %if mod(i,100) == 0\n % fprintf('aligning images and landmarks i=%d\\n',i);\n %end\n [alignedimage_this alignedlandmark_this] = U10_ConvertImageAndLandmarksByTwoPoints(exampleimage(:,:,i),landmarks(:,:,i),eyecenter(:,:,i),testeyecenter);\n alignedexampleimage(:,:,i) = alignedimage_this;\n alignedlandmarks(:,:,i) = alignedlandmark_this;\n end\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F21c_EdgePreserving_GaussianKernel.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F21c_EdgePreserving_GaussianKernel.m", "size": 8595, "source_encoding": "utf_8", "md5": "31c45f6b14eb21121a14bd50f78e5d4b", "text": "%Chih-Yuan Yang\n%09/29/12\n%F21b: Based on F21a, but change the square kernel to Gaussian, to see whether the square pattern disappear\n%F21c: remove the para argument\nfunction [gradient_expected gradient_actual weightmap_edge img_edge] = F21c_EdgePreserving_GaussianKernel(img_y,zooming,Gau_sigma)\n LowMagSuppression = 0; %the three parameters should be adjusted later\n DistanceUpperBound = 2.0;\n ContrastEnhenceCoef = 1.0;\n I_s = F27_SmoothnessPreserving(img_y,zooming,Gau_sigma);\n T = F15_ComputeSRSSD(I_s);\n Dissimilarity = EvaluateDissimilarity8(I_s);\n Grad_high_initial = Img2Grad(I_s);\n \n [h w] = size(T);\n StatisticsFolder = fullfile('EdgePriors');\n LoadFileName = sprintf('Statistics_Sc%d_Si%0.1f.mat',zooming,Gau_sigma);\n LoadData = load(fullfile(StatisticsFolder,LoadFileName));\n Statistics = LoadData.Statistics;\n \n RidgeMap = edge(I_s,'canny',[0 0.01],0.05);\n\n %filter out small ridge and non-maximun ridges\n RidgeMap_filtered = RidgeMap;\n [r_set c_set] = find(RidgeMap);\n SetLength = length(r_set);\n for j=1:SetLength\n r = r_set(j);\n c = c_set(j);\n CenterMagValue = T(r,c);\n if CenterMagValue < LowMagSuppression\n RidgeMap_filtered(r,c) = false;\n end\n end\n \n\n [r_set c_set] = find(RidgeMap_filtered);\n SetLength = length(r_set);\n [X Y] = meshgrid(1:11,1:11);\n DistPatch = sqrt((X-6).^2 + (Y-6).^2);\n\n DistMap = inf(h,w); \n UsedPixel = false(h,w); \n CenterCoor = zeros(h,w,2); \n %Compute DistMap and CneterCoor\n [r_set c_set] = find(RidgeMap_filtered);\n for j=1:SetLength\n r = r_set(j);\n r1 = r-5;\n r2 = r+5;\n c = c_set(j);\n c1 = c-5;\n c2 = c+5;\n if r1>=1 && r2<=h && c1>=1 && c2<=w %discrad boundary?\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(11), c*ones(11));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %Convert dist to table index\n TableIndexMap = zeros(h,w);\n b = unique(DistPatch(:));\n for i=1:length(b)\n SetPixels = DistMap == b(i);\n TableIndexMap(SetPixels) = i;\n end\n\n \n %mapping (T_p, T_r, d) to S_p\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n UpdatedPixel = false(h,w);\n S = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n CurrentMagValue = T(r,c);\n BinIdx_Current = ceil(CurrentMagValue /0.005);\n %Zebra have super strong Mag\n if BinIdx_Current > 100\n BinIdx_Current = 100;\n end\n TableIndex = TableIndexMap(r,c);\n if TableIndex > DistanceUpperBound\n continue\n end\n CenterMagValue = T(r_Center,c_Center);\n %Low Mag Edge suppresion\n if CenterMagValue < LowMagSuppression\n continue\n end\n BinIdx_Center = ceil(CenterMagValue /0.005);\n if BinIdx_Center > 100\n BinIdx_Center = 100;\n end\n %consult the table\n if TableIndex == 1 %1 is the index of b(1) where dist = 0, enhance the contrast of pixel on edge \n S_p = ContrastEnhenceCoef * Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n else\n S_p = Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n end\n \n if isnan(S_p)\n else\n UpdatedPixel(r,c) = true;\n S(r,c) = S_p;\n end\n end\n\n %Record the RidgeMapMap, for computing te ProbOfMag\n %the Mag is the consulted Mag\n %here is the problem, when the S is very strong, the affect range of ProbMagOut exceeds 1 pixel\n RidgeMapMagValue = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n RidgeMapMagValue(r,c) = S(r_Center,c_Center);\n end \n \n S(~UpdatedPixel) = T(~UpdatedPixel);\n img_in = I_s;\n if min(Dissimilarity(:)) == 0\n d = Dissimilarity + 1e-6; %avoid 0 case; some images may have d(:,:,1) as 0\n else\n d = Dissimilarity;\n end\n ratio = d ./ repmat(d(:,:,1),[1,1,8]);\n %here is the problem, I need to amplify the gradient directionally \n Grad_in = Img2Grad(img_in);\n Product = Grad_in .* ratio;\n Sqr = Product.^2;\n Sum = sum(Sqr,3);\n Sqrt = sqrt(Sum); %the Sqrt might be 0, because Grad_in may be pure 0;\n r1 = S ./Sqrt;\n r1(isnan(r1)) = 0;\n\n Grad_exp = Grad_high_initial .*( ratio .*(repmat(r1,[1,1,8])));\n %consolidate inconsistatnt gradient\n NewGrad_exp = zeros(h,w,8);\n for k=1:4\n switch k\n case 1\n ShiftOp = [0 -1];\n case 2\n ShiftOp = [1 -1];\n case 3\n ShiftOp = [1 0];\n case 4\n ShiftOp = [1 1];\n end\n k2 =k+4;\n Grad1 = Grad_exp(:,:,k);\n Grad2 = Grad_exp(:,:,k2);\n Grad2Shift = circshift(Grad2,ShiftOp);\n Grad1Abs = abs(Grad1);\n Grad2AbsShift = abs(Grad2Shift);\n Grad1Larger = Grad1Abs > Grad2AbsShift;\n Grad2Larger = Grad2AbsShift > Grad1Abs;\n NewGrad1 = Grad1 .* Grad1Larger + (-Grad2Shift) .* Grad2Larger;\n NewGrad2Shift = Grad2Shift .* Grad2Larger + (-Grad1) .* Grad1Larger;\n NewGrad2 = circshift(NewGrad2Shift,-ShiftOp);\n NewGrad_exp(:,:,k) = NewGrad1;\n NewGrad_exp(:,:,k2) = NewGrad2;\n end\n %current problem is the over-enhanced gradient (NewMagExp too large)\n gradient_expected = NewGrad_exp;\n \n bReport = true;\n img_edge = F4b_GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,Gau_sigma,bReport);\n gradient_actual = Img2Grad(img_edge);\n %compute the Map of edge weight\n lambda_m = 2;\n m0 = 0;\n ProbMagOut = lambda_m * RidgeMapMagValue + m0;\n\n lambda_d = 0.25;\n d0 = 0.25;\n ProbDistMap = exp(- (lambda_d * DistMap + d0) ); %this coef should be decied by zooming\n \n Product = ProbMagOut .* ProbDistMap;\n weightmap_edge = min(Product,1); %the two terms are not sufficient, direction is not taken into considertion\nend\nfunction Grad = Img2Grad(img)\n [h w] = size(img);\n Grad = zeros(h,w,8);\n DiffOp = RetGradientKernel();\n for i=1:8\n Grad(:,:,i) = imfilter(img,DiffOp{i},'replicate');\n end\nend\nfunction f = RetGradientKernel()\n f = cell(8,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\nend\nfunction Dissimilarity = EvaluateDissimilarity8(Img_in,PatchSize)\n if ~exist('PatchSize','var');\n PatchSize = 3;\n end\n [h w] = size(Img_in);\n Dissimilarity = zeros(h,w,8);\n \n f3x3 = ones(PatchSize)/(PatchSize^2);\n for i = 1:8\n DiffOp = RetGradientKernel8(i);\n Diff = imfilter(Img_in,DiffOp,'symmetric');\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Dissimilarity(:,:,i) = sqrt(Sum);\n end\nend\nfunction DiffOp = RetGradientKernel8(dir)\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n DiffOp = f{dir};\nend\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F2_ReturnLandmarks.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F2_ReturnLandmarks.m", "size": 1429, "source_encoding": "utf_8", "md5": "7bfe348598b5785b1ac920493bfaef49", "text": "%09/29/12\n%Chih-Yuan Yang\n%This file has to be executed on Linux\nfunction [bs posemap]= F2_ReturnLandmarks(im, modelname)\n\n % load and visualize model\n % Pre-trained model with 146 parts. Works best for faces larger than 80*80\n %load face_p146_small.mat\n\n % % Pre-trained model with 99 parts. Works best for faces larger than 150*150\n % load face_p99.mat\n\n % % Pre-trained model with 1050 parts. Give best performance on localization, but very slow\n % load multipie_independent.mat\n \n switch modelname\n case 'p146'\n load face_p146_small.mat\n case 'p99'\n load face_p99.mat\n case 'mi'\n load multipie_independent.mat\n otherwise\n error('no such a model');\n end\n\n % 5 levels for each octave\n model.interval = 5;\n % set up the threshold\n model.thresh = min(-0.65, model.thresh);\n\n % define the mapping from view-specific mixture id to viewpoint\n if length(model.components)==13 \n posemap = 90:-15:-90;\n elseif length(model.components)==18\n posemap = [90:-15:15 0 0 0 0 0 0 -15:-15:-90];\n else\n error('Can not recognize this model');\n end\n\n bs = detect(im, model, model.thresh); %this function only can be executed on Linux\n bs = clipboxes(im, bs); %this function removes the boxes exceeding the boundary\n bs = nms_face(bs,0.3); %non-maximum suppression\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F32a_ComputeMask_Mouth.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F32a_ComputeMask_Mouth.m", "size": 2375, "source_encoding": "utf_8", "md5": "272accc010ebb93eccf1bac4f6d2eb9f", "text": "%Chih-Yuan Yang\n%07/20/14\n%Blur the mask_hr to prevent discontinue boundary\n%F32a: I add new inputs to support the scaling factor of 3. I also replace F19a to F19c.\nfunction [mask_lr, mask_hr] = F32a_ComputeMask_Mouth(landmarks_hr, scalingfactor, Gau_sigma)\n %poits 49:68 are mouth\n \n mask_hr = zeros(480,640);\n setrange = 49:68;\n checkpair = [49 50;\n 50 51;\n 51 52;\n 52 53;\n 53 54;\n 54 55;\n 55 56;\n 56 57;\n 57 58;\n 58 59;\n 59 60;\n 60 49];\n for k=1:size(checkpair,1);\n i = checkpair(k,1);\n j = checkpair(k,2);\n %mark the pixel between i and j\n coor1 = landmarks_hr(i,:);\n coor2 = landmarks_hr(j,:);\n x1 = coor1(1);\n c1 = round(x1);\n y1 = coor1(2);\n r1 = round(y1);\n x2 = coor2(1);\n c2 = round(x2);\n y2 = coor2(2);\n r2 = round(y2);\n a = y2-y1;\n b = x1-x2;\n c = (x2-x1)*y1 - (y2-y1)*x1;\n sqra2b2 = sqrt(a^2+b^2);\n rmin = min(r1,r2);\n rmax = max(r1,r2);\n cmin = min(c1,c2);\n cmax = max(c1,c2);\n for rl=rmin:rmax\n for cl=cmin:cmax\n y_test = rl;\n x_test = cl;\n distance = abs(a*x_test+b*y_test +c)/sqra2b2;\n if distance <= sqrt(2)/2\n mask_hr(rl,cl) = 1;\n end\n end\n end\n end\n %fill the interior\n left_coor = min(landmarks_hr(setrange,1));\n right_coor = max(landmarks_hr(setrange,1));\n\n left_idx = round(left_coor);\n right_idx = round(right_coor);\n for cl = left_idx:right_idx\n rmin = find(mask_hr(:,cl),1,'first');\n rmax = find(mask_hr(:,cl),1,'last');\n if rmin ~= rmax\n mask_hr(rmin+1:rmax-1,cl) = 1;\n end\n end\n \n %blur the boundary\n mask_hr = imfilter(mask_hr,fspecial('gaussian',11,1.6));\n \n %do not dilate, otherwise the beard will be copied and generate wrong patterns\n %dilate the get the surrounding region\n% radius = 6;\n% approximateN = 0;\n% se = strel('disk',radius,approximateN);\n% mask_hr = imdilate(mask_hr,se);\n \n mask_lr = F19c_GenerateLRImage_GaussianKernel(mask_hr,scalingfactor,Gau_sigma);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F37_GetTexturePatchMatch.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F37_GetTexturePatchMatch.m", "size": 7673, "source_encoding": "utf_8", "md5": "14c2ead333bda6b48e4e390a7728a074", "text": "%Chih-Yuan Yang\n%10/05/12\n%Use patchmatch to retrieve a texture background\nfunction [gradients_texture img_texture img_texture_backprojection] = F37_GetTexturePatchMatch(img_y, ...\n hrexampleimages, lrexampleimages)\n [h_lr, w_lr, exampleimagenumber] = size(lrexampleimages);\n [h_hr, w_hr, ~] = size(hrexampleimages);\n zooming = h_hr/h_lr;\n if zooming == 4\n Gau_sigma = 1.6;\n elseif zooming == 3\n Gau_sigma = 1.2;\n end\n \n cores = 4; % Use more cores for more speed\n\n if cores==1\n algo = 'cpu';\n else\n algo = 'cputiled';\n end\n patchsize = 5;\n nn_iters = 5;\n %A =F38_ExtractFeatureFromAnImage(img_y);\n A = repmat(img_y,[1 1 3]);\n testnumber = exampleimagenumber;\n xyandl2norm = zeros(h_lr,w_lr,3,testnumber,'int32');\n disp('patchmatching');\n parfor i=1:testnumber;\n %run patchmatch\n %fprintf('Patch match running image %d\\n',i);\n %B = F38_ExtractFeatureFromAnImage( lrexampleimages(:,:,i));\n B = repmat(lrexampleimages(:,:,i),[1 1 3]);\n xyandl2norm(:,:,:,i) = nnmex(A, B, algo, patchsize, nn_iters, [], [], [], [], cores); %the return in int32\n end\n l2norm = xyandl2norm(:,:,3,:);\n [~, ix] = sort(l2norm,4);\n \n %reconstruct the high-resolution image\n h_expected = h_lr * zooming;\n w_expected = w_lr * zooming;\n img_texture = zeros(h_expected,w_expected,'uint8');\n %most cases\n rpixelshift = 2;\n cpixelshift = 2;\n for rl = 2:h_lr - patchsize\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n for cl = 2:w_lr - patchsize\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n end\n end\n \n %left\n cl = 1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n for rl=2:h_lr-patchsize\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n end\n \n %right\n cl = w_lr - patchsize+1;\n ch = w_expected - 3*zooming+1;\n ch1 = w_expected;\n for rl=2:h_lr-patchsize\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n end\n \n %top\n rl = 1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n for cl=2:w_lr-patchsize\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+zooming-1;\n rhsource = (rlsource-1)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n end\n \n %bottom\n rl = h_lr-patchsize+1;\n rh = h_expected - 3*zooming+1;\n rh1 = h_expected;\n for cl=2:w_lr-patchsize\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n end\n \n %left-top corner\n rl=1;\n cl=1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n \n %right-top corner\n rl=1;\n cl=w_lr-patchsize+1;\n rh = (rl-1)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n\n %left-bottom corner\n rl=h_lr-patchsize+1;\n cl=1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1)*zooming+1;\n ch1 = ch+3*zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n \n %left-bottom corner\n rl=h_lr-patchsize+1;\n cl=w_lr-patchsize+1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n onennidx = ix(rl,cl,1,1);\n x = xyandl2norm(rl,cl,1,onennidx); %start from 0\n y = xyandl2norm(rl,cl,2,onennidx);\n clsource = x+1;\n rlsource = y+1;\n chsource = (clsource-1+cpixelshift)*zooming+1;\n ch1source = chsource+3*zooming-1;\n rhsource = (rlsource-1+rpixelshift)*zooming+1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = hrexampleimages(rhsource:rh1source,chsource:ch1source,onennidx);\n \n img_texture = im2double(img_texture);\n iternum = 1000;\n Tolf = 0.0001;\n breport = false;\n disp('backprojection for img_texture');\n img_texture_backprojection = F11d_BackProjection_GaussianKernel(img_y, img_texture, Gau_sigma, iternum,breport,Tolf);\n \n %extract the graident\n gradients_texture = F14_Img2Grad(img_texture_backprojection);\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F21d_EdgePreserving_GaussianKernel.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F21d_EdgePreserving_GaussianKernel.m", "size": 8988, "source_encoding": "utf_8", "md5": "36518bf567ca2194183e56d5dd021413", "text": "%Chih-Yuan Yang\n%10/02/12\n%F21b: Based on F21a, but change the square kernel to Gaussian, to see whether the square pattern disappear\n%F21c: remove the para argument\n%F21d: try to use large beta0 and small beta1 to see whether it can save the computational time\nfunction [gradient_expected gradient_actual weightmap_edge img_edge] = F21d_EdgePreserving_GaussianKernel(img_y,zooming,Gau_sigma)\n LowMagSuppression = 0; %the three parameters should be adjusted later\n DistanceUpperBound = 2.0;\n ContrastEnhenceCoef = 1.0;\n I_s = F27_SmoothnessPreserving(img_y,zooming,Gau_sigma);\n T = F15_ComputeSRSSD(I_s);\n Dissimilarity = EvaluateDissimilarity8(I_s);\n Grad_high_initial = Img2Grad(I_s);\n \n [h w] = size(T);\n StatisticsFolder = fullfile('EdgePriors');\n LoadFileName = sprintf('Statistics_Sc%d_Si%0.1f.mat',zooming,Gau_sigma);\n LoadData = load(fullfile(StatisticsFolder,LoadFileName));\n Statistics = LoadData.Statistics;\n \n RidgeMap = edge(I_s,'canny',[0 0.01],0.05);\n\n %filter out small ridge and non-maximun ridges\n RidgeMap_filtered = RidgeMap;\n [r_set c_set] = find(RidgeMap);\n SetLength = length(r_set);\n for j=1:SetLength\n r = r_set(j);\n c = c_set(j);\n CenterMagValue = T(r,c);\n if CenterMagValue < LowMagSuppression\n RidgeMap_filtered(r,c) = false;\n end\n end\n \n\n [r_set c_set] = find(RidgeMap_filtered);\n SetLength = length(r_set);\n [X Y] = meshgrid(1:11,1:11);\n DistPatch = sqrt((X-6).^2 + (Y-6).^2);\n\n DistMap = inf(h,w); \n UsedPixel = false(h,w); \n CenterCoor = zeros(h,w,2); \n %Compute DistMap and CneterCoor\n [r_set c_set] = find(RidgeMap_filtered);\n for j=1:SetLength\n r = r_set(j);\n r1 = r-5;\n r2 = r+5;\n c = c_set(j);\n c1 = c-5;\n c2 = c+5;\n if r1>=1 && r2<=h && c1>=1 && c2<=w %discrad boundary?\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(11), c*ones(11));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %Convert dist to table index\n TableIndexMap = zeros(h,w);\n b = unique(DistPatch(:));\n for i=1:length(b)\n SetPixels = DistMap == b(i);\n TableIndexMap(SetPixels) = i;\n end\n\n \n %mapping (T_p, T_r, d) to S_p\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n UpdatedPixel = false(h,w);\n S = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n CurrentMagValue = T(r,c);\n BinIdx_Current = ceil(CurrentMagValue /0.005);\n %Zebra have super strong Mag\n if BinIdx_Current > 100\n BinIdx_Current = 100;\n end\n TableIndex = TableIndexMap(r,c);\n if TableIndex > DistanceUpperBound\n continue\n end\n CenterMagValue = T(r_Center,c_Center);\n %Low Mag Edge suppresion\n if CenterMagValue < LowMagSuppression\n continue\n end\n BinIdx_Center = ceil(CenterMagValue /0.005);\n if BinIdx_Center > 100\n BinIdx_Center = 100;\n end\n %consult the table\n if TableIndex == 1 %1 is the index of b(1) where dist = 0, enhance the contrast of pixel on edge \n S_p = ContrastEnhenceCoef * Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n else\n S_p = Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n end\n \n if isnan(S_p)\n else\n UpdatedPixel(r,c) = true;\n S(r,c) = S_p;\n end\n end\n\n %Record the RidgeMapMap, for computing te ProbOfMag\n %the Mag is the consulted Mag\n %here is the problem, when the S is very strong, the affect range of ProbMagOut exceeds 1 pixel\n RidgeMapMagValue = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n RidgeMapMagValue(r,c) = S(r_Center,c_Center);\n end \n \n S(~UpdatedPixel) = T(~UpdatedPixel);\n img_in = I_s;\n if min(Dissimilarity(:)) == 0\n d = Dissimilarity + 1e-6; %avoid 0 case; some images may have d(:,:,1) as 0\n else\n d = Dissimilarity;\n end\n ratio = d ./ repmat(d(:,:,1),[1,1,8]);\n %here is the problem, I need to amplify the gradient directionally \n Grad_in = Img2Grad(img_in);\n Product = Grad_in .* ratio;\n Sqr = Product.^2;\n Sum = sum(Sqr,3);\n Sqrt = sqrt(Sum); %the Sqrt might be 0, because Grad_in may be pure 0;\n r1 = S ./Sqrt;\n r1(isnan(r1)) = 0;\n\n Grad_exp = Grad_high_initial .*( ratio .*(repmat(r1,[1,1,8])));\n %consolidate inconsistatnt gradient\n NewGrad_exp = zeros(h,w,8);\n for k=1:4\n switch k\n case 1\n ShiftOp = [0 -1];\n case 2\n ShiftOp = [1 -1];\n case 3\n ShiftOp = [1 0];\n case 4\n ShiftOp = [1 1];\n end\n k2 =k+4;\n Grad1 = Grad_exp(:,:,k);\n Grad2 = Grad_exp(:,:,k2);\n Grad2Shift = circshift(Grad2,ShiftOp);\n Grad1Abs = abs(Grad1);\n Grad2AbsShift = abs(Grad2Shift);\n Grad1Larger = Grad1Abs > Grad2AbsShift;\n Grad2Larger = Grad2AbsShift > Grad1Abs;\n NewGrad1 = Grad1 .* Grad1Larger + (-Grad2Shift) .* Grad2Larger;\n NewGrad2Shift = Grad2Shift .* Grad2Larger + (-Grad1) .* Grad1Larger;\n NewGrad2 = circshift(NewGrad2Shift,-ShiftOp);\n NewGrad_exp(:,:,k) = NewGrad1;\n NewGrad_exp(:,:,k2) = NewGrad2;\n end\n %current problem is the over-enhanced gradient (NewMagExp too large)\n gradient_expected = NewGrad_exp;\n \n bReport = true;\n updatenumber = 0;\n loopnumber = 1000;\n linesearchstepnumber = 10;\n beta0 = 1;\n beta1 = 0.5^8;\n tolf = 0.001;\n img_edge = F4d_GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,Gau_sigma,bReport,...\n loopnumber,updatenumber,linesearchstepnumber,beta0,beta1,tolf);\n %img_edge = F4b_GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,Gau_sigma,bReport);\n gradient_actual = Img2Grad(img_edge);\n %compute the Map of edge weight\n lambda_m = 2;\n m0 = 0;\n ProbMagOut = lambda_m * RidgeMapMagValue + m0;\n\n lambda_d = 0.25;\n d0 = 0.25;\n ProbDistMap = exp(- (lambda_d * DistMap + d0) ); %this coef should be decied by zooming\n \n Product = ProbMagOut .* ProbDistMap;\n weightmap_edge = min(Product,1); %the two terms are not sufficient, direction is not taken into considertion\nend\nfunction Grad = Img2Grad(img)\n [h w] = size(img);\n Grad = zeros(h,w,8);\n DiffOp = RetGradientKernel();\n for i=1:8\n Grad(:,:,i) = imfilter(img,DiffOp{i},'replicate');\n end\nend\nfunction f = RetGradientKernel()\n f = cell(8,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\nend\nfunction Dissimilarity = EvaluateDissimilarity8(Img_in,PatchSize)\n if ~exist('PatchSize','var');\n PatchSize = 3;\n end\n [h w] = size(Img_in);\n Dissimilarity = zeros(h,w,8);\n \n f3x3 = ones(PatchSize)/(PatchSize^2);\n for i = 1:8\n DiffOp = RetGradientKernel8(i);\n Diff = imfilter(Img_in,DiffOp,'symmetric');\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Dissimilarity(:,:,i) = sqrt(Sum);\n end\nend\nfunction DiffOp = RetGradientKernel8(dir)\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n DiffOp = f{dir};\nend\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U5d_ReadFileNameList_Index_Comment.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U5d_ReadFileNameList_Index_Comment.m", "size": 2170, "source_encoding": "utf_8", "md5": "363e2331409333cc628abb5f9e597ed0", "text": "%Chih-Yuan Yang\n%09/01/13\n%U5: read list from a file and return it as an cell array\n%U5c: add more comment controls, the comment sign % may occur at the end of a line\n%U5d: suppose the list contains index\nfunction filenamelist = U5d_ReadFileNameList_Index_Comment( fn_list )\n fid = fopen(fn_list,'r');\n %skip the heading comment lines started with %\n tline = fgetl(fid);\n idx_fn = 0;\n filenamelist = cell(1);\n str_tab = sprintf('\\t');\n while ischar(tline)\n %if it is empty line or starts with %, do nothing\n if isempty(tline) || tline(1) == '%' \n %do nothing\n else\n %if a % is found, neglect the characters after the first space or %\n k_space = strfind(tline,' ');\n k_percentsign = strfind(tline,'%');\n k_tab = strfind(tline,str_tab); %how to find a tab?\n %initialize the str_fn as emtpy\n str_fn = [];\n if isempty(k_percentsign) && isempty(k_tab)\n idx_fn = idx_fn + 1;\n A = sscanf(tline,'%d %s');\n num_char_fn = length(A) - 1; %A(1) is the %d, type double\n for idx_char = 1:num_char_fn\n str_fn(idx_char) = sprintf('%c',A(1+idx_char));\n end\n filenamelist{idx_fn,1} = str_fn;\n else\n k = length(tline);\n if ~isempty(k_space)\n k = min(k,k_space(2));\n end\n if ~isempty(k_tab)\n k = min(k,k_tab(1));\n end\n if ~isempty(k_percentsign)\n k = min(k,k_percentsign(1));\n end\n idx_fn = idx_fn + 1;\n A = sscanf(tline(1:k-1),'%d %s');\n num_char_index = length(sprintf('%d',A(1)));\n num_char_fn = length(A) - num_char_index;\n for idx_char = 1:num_char_fn\n str_fn(idx_char) = sprintf('%c',A(num_char_index+idx_char));\n end\n filenamelist{idx_fn,1} = str_fn;\n end\n end\n tline = fgetl(fid);\n end\n fclose(fid);\nend\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F11_BackProjection.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F11_BackProjection.m", "size": 934, "source_encoding": "utf_8", "md5": "4b0bbea072111144272dbf5b81271106", "text": "%09/19/12\n%Chih-Yuan Yang\n%add report\nfunction img_bp = F11_BackProjection(img_lr, img_hr, Gau_sigma, iternum,bReport)\n [h_hr] = size(img_hr,1);\n [h_lr] = size(img_lr,1);\n zooming = h_hr/h_lr;\n for i=1:iternum\n img_lr_gen = F19_GenerateLRImage_BlurSubSample(img_hr,zooming,Gau_sigma);\n diff_lr = img_lr - img_lr_gen;\n term_diff_lr_SSD = sum(sum(diff_lr.^2));\n diff_hr = imresize(diff_lr,zooming,'bilinear');\n img_hr = img_hr + diff_hr;\n img_lr_new = F19_GenerateLRImage_BlurSubSample(img_hr,zooming,Gau_sigma);\n diff_lr_new = img_lr - img_lr_new; \n term_diff_lr_SSD_afteronebackprojection = sum(sum(diff_lr_new.^2));\n if bReport\n fprintf('backproject iteration=%d, term_before=%0.1f, term_after=%0.1f\\n', ...\n i,term_diff_lr_SSD,term_diff_lr_SSD_afteronebackprojection); \n end \n end\n img_bp = img_hr;\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U27d_CreateSemaphoreFile_IndexOnly_Exclude.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U27d_CreateSemaphoreFile_IndexOnly_Exclude.m", "size": 321, "source_encoding": "utf_8", "md5": "afcd97c7aca96d193bf7d1e1e1f51dab", "text": "%Chih-Yuan Yang\n%4/1/13\n%\nfunction U27d_CreateSemaphoreFile_IndexOnly_Exclude(fn_create,iiend,set_value0)\n fid = fopen(fn_create,'w+');\n for i=1:iiend\n if nnz(set_value0 == i)\n fprintf(fid,'%05d 0\\n',i);\n else\n fprintf(fid,'%05d 1\\n',i);\n end\n end\n fclose(fid);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F14_Img2Grad.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F14_Img2Grad.m", "size": 805, "source_encoding": "utf_8", "md5": "782f46fa3e2d8440290ca95abe60cc43", "text": "%Chih-Yuan Yang\n%10/02/12\n%add class control\nfunction Grad = F14_Img2Grad(img)\n if ~isa(img,'double')\n img = im2double(img);\n warning('input type is not double.');\n end\n [h w] = size(img);\n Grad = zeros(h,w,8);\n DiffOp = IF1_RetGradientKernel();\n for i=1:8\n Grad(:,:,i) = imfilter(img,DiffOp{i},'replicate');\n end\nend\n\nfunction f = IF1_RetGradientKernel()\n f = cell(8,1);\n f{1} = [0 -1 1];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [ 1;\n -1;\n 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [1 -1 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [ 0;\n -1;\n 1];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U27f_CreateSemaphoreFile_FromFilenamelist_SetArray.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U27f_CreateSemaphoreFile_FromFilenamelist_SetArray.m", "size": 300, "source_encoding": "utf_8", "md5": "d02e9667b2345eca5608aafa983837c6", "text": "%Chih-Yuan Yang\n%4/3/12\n%To parallel run \nfunction U27f_CreateSemaphoreFile_FromFilenamelist_SetArray(fn_create,arr_filename, arr_value)\n fid = fopen(fn_create,'w+');\n for i=1:length(arr_filename)\n fprintf(fid,'%05d %s %d\\n',i,arr_filename{i},arr_value(i));\n end\n fclose(fid);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "T1_ImprovePatchMatch.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/T1_ImprovePatchMatch.m", "size": 1264, "source_encoding": "utf_8", "md5": "6d50fdf1fcee30d1a653f63f9c78c8f0", "text": "%Chih-Yuan Yang\n%04/25/16\n%Sifei calls the TVD_dpreserve_mm three times, to regularize images along x, y, and x axis by TV norm.\n%Does the paper and the original released code also work in this way consequently for x, y, and then x?\nfunction img_texture = T1_ImprovePatchMatch(img_texture,img_y)\n %Grad_o is a set of refined gradient maps in LR\n Grad_o = T1_Img2Grad_Blockcompensate(img_y);\n y = img_texture;\n [h,w] = size(y);\n %z is the gradient map of +x direction\n z = imresize(Grad_o(:,:,1), 4, 'bilinear');\n\n %This is Sifei's L1L2norm-regualized gradients\n x = TVD_dpreserve_mm(y(:), z(1:end-1)', 0.036, 0.5, 50);\n x = reshape(x,[h,w])';\n %here z changes to the gradient map of +y direction\n z = imresize(Grad_o(:,:,7), 4, 'bilinear');\n x = TVD_dpreserve_mm(x(:), z(1:end-1)', 0.036, 0.8, 50);\n\n x = reshape(x,[w,h])';\n \n %Here z goes back to the gradient map of +x direction to smooth the gradients along x-axis again.\n %The new parameters are smaller than the ones of the first x-axis smoothing. I guess that Sifei does\n %not to want over-blur the images.\n z = imresize(Grad_o(:,:,1), 4, 'bilinear');\n x = TVD_dpreserve_mm(x(:), z(1:end-1)', 0.01, 0.5, 50);\n img_texture = reshape(x,[h,w]);\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F8_RetriveAreaGradientsByAlign_Optimization_PatchCompare.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F8_RetriveAreaGradientsByAlign_Optimization_PatchCompare.m", "size": 2368, "source_encoding": "utf_8", "md5": "221a92eeab3f073b39ce5d43f33b465e", "text": "%Chih-Yuan Yang\n%09/11/12\n%Solve the hair and background problem\n%This idea does not work\nfunction gradientcandidate = F8_RetriveAreaGradientsByAlign_Optimization_PatchCompare(testimage_lr, rawexampleimage, inputpoints, basepoints, region_lr, zooming, Gau_sigma)\n region_hr = U18_ConvertLRRegionToHRRegion(region_lr, zooming);\n exampleimagenumber = size(rawexampleimage,3);\n %find the transform matrix by solving an optimization problem\n parfor i=1:exampleimagenumber\n alignedexampleimage_hr(:,:,i) = U20_AlignExampleImageByLandmarkSet(rawexampleimage(:,:,i),inputpoints(:,:,i),basepoints);\n alignedexampleimage_lr(:,:,i) = U3_GenerateLRImage_BlurSubSample(im2double(alignedexampleimage_hr(:,:,i)),zooming,Gau_sigma);\n end\n\n %Patch to patch searching to reconstruct the back ground and hair, take how much NN? try 5\n patchsize_lr = 5;\n %use feature as intensity\n [h_hr w_hr] = size(alignedexampleimage_hr(:,:,1));\n [h_lr w_lr] = size(alignedexampleimage_lr(:,:,1));\n %how much overlap? try 1\n overlap_lr = 1;\n stepforward_lr = patchsize_lr - overlap_lr;\n r_last = h_lr-patchsize_lr+1;\n rlist = 1:stepforward_lr:r_last;\n if rlist(end) ~= r_last\n rlist = [rlist r_last];\n end\n c_last = w_lr-patchsize_lr+1;\n clist = 1:stepforward_lr:c_last;\n if clist(end) ~= c_last\n clist = [clist c_last];\n end\n \n samplenumber = length(clist)*length(rlist);\n for r = rlist\n for c = clist\n \n end\n end\n normvalue = zeros(exampleimagenumber,1);\n parfor j=1:exampleimagenumber\n examplearea_lr = alignedexampleimage_lr(region_lr.top_idx:region_lr.bottom_idx,region_lr.left_idx:region_lr.right_idx,j);\n feature_example_lr = U16_ExtractFeatureFromArea(examplearea_lr); %the unit is double\n normvalue(j) = norm(feature_test - feature_example_lr);\n end\n %find the small norm\n [sortnorm ix] = sort(normvalue);\n %some of them are very similar\n %mostsimilarindex = ix(1:20);\n\n gradientcandidate = zeros(region_hr.height,region_hr.width,8,20); %the 3rd dim is dx and dy\n parfor j=1:20\n examplehrregion = alignedexampleimage_hr(region_hr.top_idx:region_hr.bottom_idx,region_hr.left_idx:region_hr.right_idx,ix(j));\n gradientcandidate(:,:,:,j) = Img2Grad(im2double(examplehrregion));\n end\n\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U20_ReturnHandleDrawLandmarks.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U20_ReturnHandleDrawLandmarks.m", "size": 1015, "source_encoding": "utf_8", "md5": "feb1dfaf1aeb76f0c572dba0f91c468d", "text": "%09/14/12\n%Chih-Yuan Yang\n%Return the handle\nfunction hfig = U23_ReturnHandleDrawLandmarks(im, boxes, posemap,bshownumbers,bdrawpose,bVisible)\n\n if bVisible\n hfig = figure;\n else\n hfig = figure('Visible','off');\n end\n imshow(im);\n hold on;\n axis image;\n axis off;\n\n for b = boxes,\n partsize = b.xy(1,3)-b.xy(1,1)+1;\n tx = (min(b.xy(:,1)) + max(b.xy(:,3)))/2;\n ty = min(b.xy(:,2)) - partsize/2;\n if bdrawpose\n text(tx,ty, num2str(posemap(b.c)),'fontsize',18,'color','c');\n end\n for i = size(b.xy,1):-1:1;\n x1 = b.xy(i,1);\n y1 = b.xy(i,2);\n x2 = b.xy(i,3);\n y2 = b.xy(i,4);\n %line([x1 x1 x2 x2 x1]', [y1 y2 y2 y1 y1]', 'color', 'b', 'linewidth', 1);\n\n plot((x1+x2)/2,(y1+y2)/2,'r.','markersize',9);\n if bshownumbers\n text((x1+x2)/2,(y1+y2)/2, num2str(i), 'fontsize',9,'color','k');\n end\n end\n end\n drawnow;\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F42_ConvertImageCoorToCartesianCoor.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F42_ConvertImageCoorToCartesianCoor.m", "size": 570, "source_encoding": "utf_8", "md5": "dfd1f5972aeb86cbc8334d60cde570ef", "text": "%Chih-Yun Yang\n%10/23/12\n%Called by PP2_GenerateAlignImageAndAlignedLandmarks\nfunction pts_cartisian = F42_ConvertImageCoorToCartesianCoor(pts_image, imagesize)\n h = imagesize(1);\n w = imagesize(2); %not used\n [pointperimage, dimperpts, imagenumber] = size(pts_image);\n pts_cartisian = zeros(pointperimage, dimperpts, imagenumber);\n for ii = 1:imagenumber\n for ptsidx =1:pointperimage\n pts_cartisian(ptsidx,1,ii) = pts_image(ptsidx,1,ii);\n pts_cartisian(ptsidx,2,ii) = h - pts_image(ptsidx,2,ii);\n end\n end\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F11d_BackProjection_GaussianKernel.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F11d_BackProjection_GaussianKernel.m", "size": 2514, "source_encoding": "utf_8", "md5": "77f0ae684573082cd6e59065b67a6e02", "text": "%Chih-Yuan Yang\n%07/20/14 I update the code to support the scaling factor of 3.\n%F11c: controlled by iternum\n%F11d: controled by TolF\n%This file should be replace by F11e\n%function img_bp = F11d_BackProjection_GaussianKernel(img_lr, img_hr, Gau_sigma, iternum,bReport,TolF)\n [h_hr] = size(img_hr,1);\n [h_lr] = size(img_lr,1);\n zooming = h_hr/h_lr;\n for i=1:iternum\n img_lr_gen = F19a_GenerateLRImage_GaussianKernel(img_hr,zooming,Gau_sigma);\n diff_lr = img_lr - img_lr_gen;\n RMSE_diff_lr = sqrt(mean2(diff_lr.^2));\n diff_hr = IF5_Upsample(diff_lr,zooming, Gau_sigma);\n %diff_hr = imresize(diff_lr,zooming,'bilinear');\n img_hr = img_hr + diff_hr;\n img_lr_new = F19a_GenerateLRImage_GaussianKernel(img_hr,zooming,Gau_sigma);\n diff_lr_new = img_lr - img_lr_new; \n RMSE_diff_lr_afteronebackprojection = sqrt(mean2(diff_lr_new.^2));\n if bReport\n fprintf('backproject iteration=%d, RMSE_before=%0.6f, RMSE_after=%0.6f\\n', ...\n i,RMSE_diff_lr,RMSE_diff_lr_afteronebackprojection); \n end\n if RMSE_diff_lr_afteronebackprojection < TolF\n disp('RMSE_diff_lr_afteronebackprojection < TolF');\n break;\n end\n end\n img_bp = img_hr;\nend\nfunction diff_hr = IF5_Upsample(diff_lr,zooming, Gau_sigma)\n [h w] = size(diff_lr);\n h_hr = h*zooming;\n w_hr = w*zooming;\n upsampled = zeros(h_hr,w_hr);\n if zooming == 3\n for rl = 1:h\n rh = (rl-1) * zooming + 2;\n for cl = 1:w\n ch = (cl-1) * zooming + 2;\n upsampled(rh,ch) = diff_lr(rl,cl);\n end\n end\n kernelsize = ceil(Gau_sigma * 3)*2+1;\n kernel = fspecial('gaussian',kernelsize,Gau_sigma);\n diff_hr = imfilter(upsampled,kernel,'replicate');\n elseif zooming == 4\n %compute the kernel by ourself, assuming the range is \n %control the kernel and the position of the diff\n kernelsize = ceil(Gau_sigma * 3)*2+2; %+2 this is the even number\n kernel = fspecial('gaussian',kernelsize,Gau_sigma);\n %subsample diff_lr to (3,3), because of the result of imfilter\n for rl = 1:h\n rh = (rl-1) * zooming + 3;\n for cl = 1:w\n ch = (cl-1) * zooming + 3;\n upsampled(rh,ch) = diff_lr(rl,cl);\n end\n end\n diff_hr = imfilter(upsampled, kernel,'replicate');\n else\n error('not supported');\n end\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F12_ACCV12Preprocess_LoadingData.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F12_ACCV12Preprocess_LoadingData.m", "size": 906, "source_encoding": "utf_8", "md5": "6c1821196672d0e9d784f00f25d71390", "text": "%Chih-Yuan Yang\n%09/19/12\n%hint: for patch work, loading all data into memory can save time.\nfunction [sfall srecall] = F12_ACCV12Preprocess_LoadingData(zooming,featurefilename,recordfilename)\n if zooming == 4\n featurefolder = fullfile('TexturePatchDataset','Feature','s4');\n elseif zooming == 3\n featurefolder = fullfile('TexturePatchDataset','Feature','s3');\n end\n \n sfall = cell(6,1);\n srecall = cell(6,1);\n quanarray = [1 2 4 8 16 32];\n for qidx=1:6\n quan = quanarray(qidx);\n loadfilename = sprintf('%s%d.mat',featurefilename,quan);\n loaddata = load(fullfile(featurefolder,loadfilename));\n sfall{qidx} = loaddata.sf;\n loadfilename = sprintf('%s%d.mat',recordfilename,quan);\n loaddata = load(fullfile(featurefolder,loadfilename));\n srecall{qidx} = loaddata.srec;\n fprintf('.');\n end\n fprintf('\\n');\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U27e_CreateSemaphoreFile_FromFilenamelist_ExcludeSet.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U27e_CreateSemaphoreFile_FromFilenamelist_ExcludeSet.m", "size": 419, "source_encoding": "utf_8", "md5": "7a0ceb3028a632f982a4637bb8fadf24", "text": "%Chih-Yuan Yang\n%4/3/12\n%To parallel run \nfunction U27e_CreateSymphonyFile_FromFilenamelist_ExcludeSet(fn_create,filenamelist, set_value0)\n fid = fopen(fn_create,'w+');\n for i=1:length(filenamelist)\n if nnz(set_value0 == i)\n fprintf(fid,'%05d %s 0\\n',i,filenamelist{i});\n else \n fprintf(fid,'%05d %s 1\\n',i,filenamelist{i});\n end\n end\n fclose(fid);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F43_ConvertCartesianCoorToImageCoor.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F43_ConvertCartesianCoorToImageCoor.m", "size": 519, "source_encoding": "utf_8", "md5": "695a55806208b4ae78261a7b13223eb9", "text": "%Chih-Yuan Yang\n%10/29/12\n\nfunction pts_image = F43_ConvertCartesianCoorToImageCoor(pts_cartisian, imagesize)\n h = imagesize(1);\n w = imagesize(2); %not used\n [pointperimage, dimperpts, imagenumber] = size(pts_cartisian);\n pts_image = zeros(pointperimage, dimperpts, imagenumber);\n for ii = 1:imagenumber\n for ptsidx =1:pointperimage\n pts_image(ptsidx,1,ii) = pts_cartisian(ptsidx,1,ii);\n pts_image(ptsidx,2,ii) = h - pts_cartisian(ptsidx,2,ii);\n end\n end\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U27_CreateSemaphoreFile_TwoColumn.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U27_CreateSemaphoreFile_TwoColumn.m", "size": 257, "source_encoding": "utf_8", "md5": "1ea771b33752980e41f3531484e57e53", "text": "%Chih-Yuan Yang\n%09/29/12\n%for parallel execution\nfunction U27_CreateSemaphoreFile_TwoColumn(fn_create,iiend,filenamelist)\n fid = fopen(fn_create,'w+');\n for i=1:iiend\n fprintf(fid,'%05d %s 0\\n',i,filenamelist{i});\n end\n fclose(fid);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F28_ComputeSquareSumLowHighDiff.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F28_ComputeSquareSumLowHighDiff.m", "size": 393, "source_encoding": "utf_8", "md5": "73640adb8e524325e9992ea6ea807837", "text": "%Chih-Yuan Yang\n%07/20/14\n%I replace F19a to F19c to support the scaling factor of 3. In addition, F19c is simpler.\nfunction f = F28_ComputeSquareSumLowHighDiff(img,img_low,Gau_sigma)\n zooming = size(img,1)/size(img_low,1);\n img_lr_generated = F19c_GenerateLRImage_GaussianKernel(img,zooming,Gau_sigma);\n diff = img_low - img_lr_generated;\n Sqr = diff.^2;\n f = sum(Sqr(:));\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F9_ACCV12Upampling.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F9_ACCV12Upampling.m", "size": 42896, "source_encoding": "utf_8", "md5": "b224bc49f05d72474523f5a65d022076", "text": "%Chih-Yuan Yang\n%09/12/12\n%To solve the hair and background problem\n%hint: for patch work, loading all data into memory can save time.\nfunction img_hr = F9_ACCV12Upampling(img_y, zooming, Gau_sigma ,sfall,srecall)\n if zooming == 4\n para.Gau_sigma = 1.6;\n featurefilename = 'sf_1_1264_qf';\n recordfilename = 'srec_1_1264_qf';\n featurefolder = fullfile('TexturePatchDataset','Feature','s4');\n elseif zooming == 3\n para.Gau_sigma = 1.2;\n featurefilename = 'sf_1_1264_qf';\n recordfilename = 'srec_1_1264_qf';\n featurefolder = fullfile('TexturePatchDataset','Feature','s3');\n end\n \n [img_edge reliablemap_edge] = F1_EdgePreserving(img_y,para,zooming,Gau_sigma);\n %esn = 1;\n [h_lr w_lr] = size(img_y);\n para.lh = h_lr;\n para.lw = w_lr;\n para.NumberOfHCandidate = 10;\n para.SimilarityFunctionSettingNumber = 1;\n %load all data set to save loading time\n [scanr scanra] = SearchExternalPatches(img_y,para,sfall,srecall);\n para.zooming = zooming;\n para.ps = 5;\n para.Gau_sigma = Gau_sigma;\n hrpatch = F8_ExtractAllHrPatches(img_y, para, scanr);\n [scanr_self scanra_self] = F22_SearchForSelfSimilarPatchesL2Norm(img_y,para);\n para.ehrfKernelWidth = 1.0;\n para.bEnablemhrf = true;\n [img_texture reliablemap_texture] = F11_FilterOutImproperHrPatches(img_y,hrpatch,para,scanr_self,scanra_self,scanr,scanra);\n nomi = img_texture.*reliablemap_texture + img_edge .* reliablemap_edge;\n denomi = reliablemap_edge + reliablemap_texture;\n img_hr = nomi ./ denomi;\n %there are some 0 value of denomi around boundary\n %fill these pixels as img_edge\n nanpixels = isnan(img_hr);\n img_hr(nanpixels) = img_edge(nanpixels);\n %ensure there is no nan\n if nnz(isnan(img_hr))\n error('should not be here');\n end\nend\nfunction [scanr scanra] = SearchExternalPatches(img_y,para,sfall,srecall)\n %how to search parallelly to speed up?\n ps = 5; %patch size\n [lh lw] = size(img_y);\n hrpatchnumber = 10;\n %featurefolder = para.featurefolder;\n sh = GetShGeneral(ps);\n scanr = zeros(6,hrpatchnumber,lh-ps+1,lw-ps+1); %scan results, mm, quan, ii, sr, sc, similairty\n smallvalue = -1;\n scanr(6,:,:,:) = smallvalue;\n scanra = zeros(lh-ps+1,lw-ps+1); %scan results active\n %scanrsimmax = smallvalue * ones(lh-ps+1,lw-ps+1); %del this line?\n quanarray = [1 2 4 8 16 32];\n B = [256 128 64 32 16 8];\n imlyi = im2uint8(img_y);\n for qidx=1:6\n quan = quanarray(qidx);\n b = B(qidx);\n \n cur_initial = floor(size(sfall{1},2)/2); %accelerate the loop by using an initial position\n for rl=1:lh-ps+1\n fprintf('look for lut rl:%d quan:%d\\n',rl,quan);\n for cl = 1:lw-ps+1\n patch = imlyi(rl:rl+ps-1,cl:cl+ps-1);\n fq = patch(sh);\n if qidx == 1\n fquan = fq;\n else\n fquan = fq - mod(fq,quan) + quan/2;\n end\n\n [iila mma] = LookForLookUpTable9_External(fquan,sfall{qidx},cur_initial,para); %index in lookuptable\n in = length(iila); %always return 20 instance\n for i=1:in\n ii = srecall{qidx}(1,iila(i)); \n sr = srecall{qidx}(2,iila(i));\n sc = srecall{qidx}(3,iila(i));\n %check whether the patch is in the scanr already\n bSamePatch = false;\n for j=1:scanra(rl,cl)\n if ii == scanr(3,j,rl,cl) && sr == scanr(4,j,rl,cl) && sc == scanr(5,j,rl,cl)\n bSamePatch = true;\n break\n end\n end\n\n if bSamePatch == false\n similarity = bmm2similarity(b,mma(i),para.SimilarityFunctionSettingNumber);\n if scanra(rl,cl) < hrpatchnumber\n ix = scanra(rl,cl) + 1;\n %to do: update scanr by similarity\n %need to double it, otherwise, the int6 will kill similarity\n scanr(:,ix,rl,cl) = cat(1,mma(i),quan,double(ii),double(sr),double(sc),similarity);\n scanra(rl,cl) = ix;\n else\n [minval ix] = min(scanr(6,:,rl,cl));\n if scanr(6,ix,rl,cl) < similarity\n %update\n scanr(:,ix,rl,cl) = cat(1,mma(i),quan,double(ii),double(sr),double(sc),similarity); \n end\n end\n end\n end\n end\n end\n end\nend\nfunction [iila mma] = LookForLookUpTable9_External(fq,lut,cur_initial,para)\n hrpatchnumber = para.NumberOfHCandidate; %default 10\n fl = length(fq); %feature length\n head = 1;\n tail = size(lut,2);\n lutsize = size(lut,2);\n if exist('cur_initial','var')\n if cur_initial > lutsize\n cur = lutsize;\n else\n cur = cur_initial;\n end\n else\n cur = round(lutsize/2);\n end\n cur_rec1 = cur;\n %initial comparison\n fqsmaller = -1;\n fqlarger = 1;\n fqsame = 0;\n cr = 0; %compare results\n mm = 0;\n mmiil = 0;\n %search for the largest mm\n while 1\n for c=1:fl\n if fq(c) < lut(c,cur)\n cr = fqsmaller;\n break\n elseif fq(c) > lut(c,cur)\n cr = fqlarger;\n break; %c moves to next\n else %equal\n cr = fqsame;\n if mm < c\n mm = c;\n mmiil = cur;\n end \n end\n end\n \n if cr == fqsmaller\n next = floor((cur + head)/2);\n tail = cur; %adjust the range of head and tail\n elseif cr == fqlarger;\n next = ceil((cur + tail)/2); %the round function has to be floor, because fq is larger than cur\n %otherwise the fully 255 patches will never match\n head = cur; %adjust the range of head and tail\n end\n \n if mm == 25 %it happens, the initial one match the fq, therefore, there is no next defined.\n break\n end\n if cur == next || cur_rec1 == next %the next might oscilate\n break;\n else\n cur_rec1 = cur;\n cur = next;\n end\n %fprintf('cur %d\\n',cur);\n end\n\n if mm == 0 \n iila = [];\n mma = [];\n return\n end\n %post-process to find the repeated partial vectors\n %search for previous\n idx = 1;\n iila = zeros(hrpatchnumber,1);\n mma = zeros(hrpatchnumber,1);\n iila(idx) = mmiil;\n mma(idx) = mm;\n bprecontinue = true;\n bproccontinue = true;\n \n presh = 0; %previous shift\n procsh = 0; %proceeding shift\n while 1\n presh = presh -1;\n iilpre = mmiil + presh;\n if iilpre <1\n bprecontinue = false;\n premm = 0;\n end\n procsh = procsh +1;\n iilproc = mmiil + procsh;\n if iilproc > lutsize\n bproccontinue = false;\n procmm = 0;\n end\n \n if bprecontinue \n diff = lut(:,iilpre) ~= fq;\n if nnz(diff) == 0\n premm = 25;\n else\n premm = find(diff,1,'first') -1;\n end\n end\n\n if bproccontinue\n diff = lut(:,iilproc) ~= fq;\n if nnz(diff) == 0\n procmm = 25;\n else\n procmm = find(diff,1,'first') -1;\n end\n end\n \n if premm == 0 && procmm == 0\n break\n end\n if premm > procmm\n %add pre item\n idx = idx + 1;\n iila(idx) = iilpre;\n mma(idx) = premm;\n %pause the proc\n bprecontinue = true;\n elseif premm < procmm\n %add proc item\n idx = idx + 1;\n iila(idx) = iilproc;\n mma(idx) = procmm;\n %pause the pre\n bproccontinue = true;\n else %premm == procmm\n %add both item\n idx = idx + 1;\n iila(idx) = iilpre;\n mma(idx) = premm;\n \n if idx == hrpatchnumber\n break\n end\n idx = idx + 1;\n iila(idx) = iilproc;\n mma(idx) = procmm; \n bproccontinue = true;\n bprecontinue = true;\n end\n if idx == hrpatchnumber\n break\n end\n end\n\n if idx < hrpatchnumber\n iila = iila(1:idx);\n mma = mma(1:idx);\n end\nend\nfunction s = bmm2similarity(b,mm,SimilarityFunctionSettingNumber)\n if SimilarityFunctionSettingNumber == 1\n if mm >= 9\n Smm = 0.9 + 0.1*(mm-9)/16;\n else\n Smm = 0.5 * mm/9;\n end\n\n Sb = 0.5+0.5*(log2(b)-3)/5;\n s = Sb * Smm;\n elseif SimilarityFunctionSettingNumber == 2\n Smm = mm/25;\n Sb = (log2(b)-2)/6;\n s = Sb * Smm;\n end\nend\nfunction hrpatch = F8_ExtractAllHrPatches(img_y, para, scanr)\n %how to search parallelly to speed up?\n psh = para.ps * para.zooming;\n ps = para.ps;\n lh = para.lh;\n lw = para.lw;\n s = para.zooming;\n hrpatchnumber = para.NumberOfHCandidate;\n hrpatch = zeros(psh,psh,lh-ps+1,lw-ps+1,hrpatchnumber);\n ihfolder = fullfile('TexturePatchDataset','HRGray');\n %read all images\n loaddata = load(fullfile(ihfolder,'AllImages_1_1264.mat'));\n allimages = loaddata.allimages;\n clear loaddata\n \n %analyize which images need to be loaded\n alliiset = scanr(3,:,:,:);\n alliiset_uni = unique(alliiset(:)); %allmost all images are used, from 1 to 1500\n if alliiset_uni(1) ~= 0\n alliiset_uni_pure = alliiset_uni;\n else\n alliiset_uni_pure = alliiset_uni(2:end);\n end\n\n for i = 1:length(alliiset_uni_pure)\n ii = alliiset_uni_pure(i);\n\n exampleimage_hr = im2double(allimages(:,:,ii));\n\n exampleimage_lr = GenerateLRImage_BlurSubSample(exampleimage_hr,para.zooming,para.Gau_sigma);\n match_4D = alliiset == ii;\n match_3D = reshape(match_4D,hrpatchnumber,lh-ps+1,lw-ps+1); %remove the first dimension\n [d1 d2 d3] = size(match_3D); %second dimention length\n [idxset posset] = find(match_3D);\n setin = length(idxset);\n for j = 1:setin\n idx = idxset(j);\n possum = posset(j);\n pos3 = floor( (possum-1)/d2) +1; %the relationship: possum = (pos3-1) * d2 + pos2, pos2 in (1,d2)\n pos2 = possum - (pos3-1)*d2;\n\n rl = pos2;\n cl = pos3;\n \n sr = scanr(4,idx,rl,cl);\n sc = scanr(5,idx,rl,cl);\n \n srh = (sr-1)*s+1;\n srh1 = srh + psh -1;\n sch = (sc-1)*s+1;\n sch1 = sch + psh-1;\n\n %to do: compensate the HR patch to match the LR query patch\n hrp = exampleimage_hr(srh:srh1,sch:sch1); %HR patch \n lrq = img_y(rl:rl+ps-1,cl:cl+ps-1); %LR query patch\n lrr = exampleimage_lr(sr:sr+ps-1,sc:sc+ps-1); %LR retrieved patch\n chrp = hrp + imresize(lrq - lrr,s,'bilinear'); %compensate HR patch\n hrpatch(:,:,rl,cl,idx) = chrp;\n \n bVisuallyCheck = false;\n if bVisuallyCheck\n if ~exist('hfig','var')\n hfig = figure;\n else\n figure(hfig);\n end\n subplot(1,4,1);\n imshow(hrp/255);\n title('hrp');\n subplot(1,4,2);\n imshow(lrr/255);\n title('lrr');\n subplot(1,4,3);\n imshow(lrq/255);\n title('lrq');\n subplot(1,4,4);\n imshow(chrp/255);\n title('chrp');\n keyboard\n end\n end \n end\nend\nfunction [img_texture Reliablemap] = F11_FilterOutImproperHrPatches(img_y,hrpatch,para,scanr_self,scanra_self,scanr,scanra)\n %filter out improper hr patches using similarity among lr patches\n %load the self-similar data\n s = para.zooming;\n lh = para.lh;\n lw = para.lw;\n ps = para.ps;\n psh = s * para.ps;\n patcharea = para.ps^2;\n\n\n SSnumberUpperbound = 10;\n \n %do I still need these variables?\n cqarray = zeros(32,1)/0;\n for qidx = 1:6\n quan = 2^(qidx-1);\n cqvalue = 0.9^(qidx-1);\n cqarray(quan) = cqvalue;\n end\n \n hh = lh * s;\n hw = lw * s;\n hrres_nomi = zeros(hh,hw);\n hrres_deno = zeros(hh,hw);\n maskmatrix = false(psh,psh,patcharea);\n Reliablemap = zeros(hh,hw);\n \n pshs = psh * psh; \n for i=1:patcharea\n [sh_notsued masklow maskhigh] = GetShGeneral(ps,i,true,s); %ps, mm, bhigh, s\n maskmatrix(:,:,i) = maskhigh;\n end\n mhr = zeros(5*s);\n r1 = 2*s+1;\n r2 = 3*s;\n c1 = 2*s+1;\n c2 = 3*s;\n mhr(r1:r2,c1:c2) = 1; %the central part\n sigma = para.ehrfKernelWidth;\n kernel = Sigma2Kernel(sigma);\n if para.bEnablemhrf\n mhrf = imfilter(mhr,kernel,'replicate');\n else\n mhrf = mhr;\n end\n\n noHmap = scanra == 0;\n noHmapToFill = noHmap;\n NHOOD = [0 1 0;\n 1 1 1;\n 0 1 0];\n se = strel('arbitrary',NHOOD);\n noHmapneighbor = and( imdilate(noHmap,se) ,~noHmap);\n %if the noHmapsever is 0, it is fine\n \n imb = imresize(img_y,s); %use it as the reference if no F is available\n \n rsa = [0 -1 0 1];\n csa = [1 0 -1 0];\n for rl= 1:lh-ps+1 %75\n fprintf('rl:%d total:%d\\n',rl,lh-ps+1);\n rh = (rl-1)*s+1;\n rh1 = rh+psh-1;\n for cl = 1:lw-ps+1 %128\n ch = (cl-1)*s+1;\n ch1 = ch+psh-1;\n \n %load candidates\n hin = para.NumberOfHCandidate;\n H = zeros(psh,psh,hin);\n HSim = zeros(hin,1);\n for j=1:hin\n H(:,:,j) = hrpatch(:,:,rl,cl,j); %H\n HSim(j) = scanr(6,j,rl,cl);\n end\n \n %compute the number of reference patches\n sspin = min(SSnumberUpperbound,scanra_self(rl,cl)); \n %self similar patch instance number\n F = zeros(ps,ps,sspin);\n FSimPure = zeros(1,sspin);\n rin = 0;\n for i=1:sspin\n sr = scanr_self(3,i,rl,cl);\n sc = scanr_self(4,i,rl,cl);\n %hr candidate number\n rin = rin + para.NumberOfHCandidate;\n F(:,:,i) = img_y(sr:sr+ps-1,sc:sc+ps-1);\n FSimPure(i) = scanr_self(5,i,rl,cl);\n end\n \n %load all of the two step patches\n R = zeros(psh,psh,rin);\n mms = zeros(rin,1);\n mmr = zeros(rin,1);\n qs = zeros(rin,1);\n qr = zeros(rin,1);\n FSimBaseR = zeros(rin,1); \n RSim = zeros(rin,1);\n idx = 0;\n if sspin > 0\n for i=1:sspin %sspin is the Fin\n sr = scanr_self(3,i,rl,cl);\n sc = scanr_self(4,i,rl,cl);\n %hr candidate number\n hrcanin = para.NumberOfHCandidate;\n for j=1:hrcanin\n idx = idx + 1;\n R(:,:,idx) = hrpatch(:,:,sr,sc,j);\n mms(idx) = scanr_self(1,i,rl,cl);\n qs(idx) = scanr_self(2,i,rl,cl);\n mmr(idx) = scanr(1,j,sr,sc);\n qr(idx) = scanr(2,j,sr,sc);\n FSimBaseR(idx) = FSimPure(i);\n RSim(idx) = scanr(6,j,sr,sc);\n end\n end\n else\n idx = 1;\n rin = 1; %use bicubic \n R(:,:,idx) = imb(rh:rh1,ch:ch1);\n FSimBaseR(idx) = 1;FSimPure(i);\n end\n\n %here is a question, how to define the similarity between H and R?\n %L2norm?\n hscore = zeros(hin,1);\n for i=1:hin\n theH = H(:,:,i);\n for j=1:rin\n theR = R(:,:,j);\n spf = FSimBaseR(j);\n %similarity between H and R\n diff = theH - theR;\n L2N = norm(diff(:));\n shr = exp(- L2N/pshs);\n hscore(i) = hscore(i) + shr*spf;\n end\n end\n [maxscore idx] = max(hscore);\n %take this as the example\n Reliablemap(rh:rh1,ch:ch1) = Reliablemap(rh:rh1,ch:ch1) + HSim(idx)*mhrf;\n \n if hin > 0 %some patches can't find H\n hrres_nomi(rh:rh1,ch:ch1) = hrres_nomi(rh:rh1,ch:ch1) + H(:,:,idx).*mhrf;\n hrres_deno(rh:rh1,ch:ch1) = hrres_deno(rh:rh1,ch:ch1) + mhrf; \n end\n %if any of its neighbor belongs to noHmap, copy additional region to hrres\n %if the pixel belongs to noHmapneighbor, then expand the copy regions\n if noHmapneighbor(rl,cl) == true\n mhrfspecial = zeros(5*s);\n mhrfspecial(r1:r2,c1:c2) = 1;\n for i=1:4\n rs = rsa(i);\n cs = csa(i);\n checkr = rl+rs;\n checkc = cl+cs;\n if checkr > 0 && checkr < lh-ps+1 && checkc >0 && checkc =1 && r2<=h && c1>=1 && c2<=w %discrad boundary?\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(11), c*ones(11));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %Convert dist to table index\n TableIndexMap = zeros(h,w);\n b = unique(DistPatch(:));\n for i=1:length(b)\n SetPixels = DistMap == b(i);\n TableIndexMap(SetPixels) = i;\n end\n\n \n %mapping (T_p, T_r, d) to S_p\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n UpdatedPixel = false(h,w);\n S = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n CurrentMagValue = T(r,c);\n BinIdx_Current = ceil(CurrentMagValue /0.005);\n %Zebra have super strong Mag\n if BinIdx_Current > 100\n BinIdx_Current = 100;\n end\n TableIndex = TableIndexMap(r,c);\n if TableIndex > para.DistanceUpperBound\n continue\n end\n CenterMagValue = T(r_Center,c_Center);\n %Low Mag Edge suppresion\n if CenterMagValue < para.LowMagSuppression\n continue\n end\n BinIdx_Center = ceil(CenterMagValue /0.005);\n if BinIdx_Center > 100\n BinIdx_Center = 100;\n end\n %consult the table\n if TableIndex == 1 %1 is the index of b(1) where dist = 0, enhance the contrast of pixel on edge \n S_p = para.ContrastEnhenceCoef * Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n else\n S_p = Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n end\n \n if isnan(S_p)\n else\n UpdatedPixel(r,c) = true;\n S(r,c) = S_p;\n end\n end\n\n %Record the RidgeMapMap, for computing te ProbOfMag\n %the Mag is the consulted Mag\n %here is the problem, when the S is very strong, the affect range of ProbMagOut exceeds 1 pixel\n RidgeMapMagValue = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n RidgeMapMagValue(r,c) = S(r_Center,c_Center);\n end \n \n S(~UpdatedPixel) = T(~UpdatedPixel);\n img_in = I_s;\n if min(Dissimilarity(:)) == 0\n d = Dissimilarity + 1e-6; %avoid 0 case; some images may have d(:,:,1) as 0\n else\n d = Dissimilarity;\n end\n ratio = d ./ repmat(d(:,:,1),[1,1,8]);\n %here is the problem, I need to amplify the gradient directionally \n Grad_in = Img2Grad(img_in);\n Product = Grad_in .* ratio;\n Sqr = Product.^2;\n Sum = sum(Sqr,3);\n Sqrt = sqrt(Sum); %the Sqrt might be 0, because Grad_in may be pure 0;\n r1 = S ./Sqrt;\n r1(isnan(r1)) = 0;\n\n Grad_exp = Grad_high_initial .*( ratio .*(repmat(r1,[1,1,8])));\n %consolidate inconsistatnt gradient\n NewGrad_exp = zeros(h,w,8);\n for k=1:4\n switch k\n case 1\n ShiftOp = [0 -1];\n case 2\n ShiftOp = [1 -1];\n case 3\n ShiftOp = [1 0];\n case 4\n ShiftOp = [1 1];\n end\n k2 =k+4;\n Grad1 = Grad_exp(:,:,k);\n Grad2 = Grad_exp(:,:,k2);\n Grad2Shift = circshift(Grad2,ShiftOp);\n Grad1Abs = abs(Grad1);\n Grad2AbsShift = abs(Grad2Shift);\n Grad1Larger = Grad1Abs > Grad2AbsShift;\n Grad2Larger = Grad2AbsShift > Grad1Abs;\n NewGrad1 = Grad1 .* Grad1Larger + (-Grad2Shift) .* Grad2Larger;\n NewGrad2Shift = Grad2Shift .* Grad2Larger + (-Grad1) .* Grad1Larger;\n NewGrad2 = circshift(NewGrad2Shift,-ShiftOp);\n NewGrad_exp(:,:,k) = NewGrad1;\n NewGrad_exp(:,:,k2) = NewGrad2;\n end\n %current problem is the over-enhanced gradient (NewMagExp too large)\n\n para.bReport = true;\n img_edge = GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,para,zooming,Gau_sigma);\n\n %compute the Map of edge weight\n lambda_m = 2;\n m0 = 0;\n ProbMagOut = lambda_m * RidgeMapMagValue + m0;\n\n lambda_d = 0.25;\n d0 = 0.25;\n ProbDistMap = exp(- (lambda_d * DistMap + d0) ); %this coef should be decied by zooming\n \n Product = ProbMagOut .* ProbDistMap;\n ProbOfEdge = min(Product,1); %the two terms are not sufficient, direction is not taken into considertion\n\n para.bDumpInformation = false;\n if para.bDumpInformation\n scc(ProbOfEdge);\n title('Edge Weight Map');\n hfig = gcf;\n fn = sprintf('%s_%s_%d_%d_EdgeWeightMap.png',para.SaveName,para.Legend,para.setting,para.tuning);\n saveas(hfig,fullfile(para.tuningfolder,fn));\n close(hfig)\n \n scc(ProbMagOut,[0 1]); \n hFig = gcf;\n title('$b_1 s_r + b_0$, sharpness term','interpreter','latex');\n axis off\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_Weight_SharpnessTerm.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_Weight_SharpnessTerm.fig']));\n close(hFig);\n \n scc(ProbDistMap,[0 1]); \n hFig = gcf;\n title('$e^{a_1 d+a_0}$, distance term','interpreter','latex');\n axis off\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_Weight_DistanceTerm.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_Weight_DistanceTerm.fig']));\n close(hFig);\n\n\n scc(ProbOfEdge,[0 1]); \n hFig = gcf;\n title(''); %remove title, make it blank\n axis off\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_W_e.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_W_e.fig']));\n close(hFig);\n\n scc(RidgeMap,'g');\n hFig = gcf;\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_R_WithFrame.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_R_WithFrame.fig']));\n close(hFig);\n\n RidgeMap_filtered_inverted = 1-RidgeMap_filtered;\n scc(RidgeMap_filtered_inverted,'g');\n colorbar off\n hFig = gcf;\n title('$R$','interpreter','latex');\n saveas(hFig,fullfile(SaveFolder,[para.SaveName 'RidgeMap_WithFrame.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName 'RidgeMap_WithFrame.fig']));\n close(hFig);\n imwrite(1-RidgeMap_filtered,fullfile(para.tuningfolder,[para.SaveName '_R.png']));\n\n MaxS = max(S(:));\n scc(T,[0 MaxS]);\n hFig = gcf;\n %title('$M^*$, Mangnitude of gradient of $I^*$','interpreter','latex');\n title('');\n axis off\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_T.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_T.fig']));\n close(hFig);\n \n scc(S,[0 MaxS]); \n %title('$M''$, Predicted mangnitude of gradient','interpreter','latex');\n title('');\n hFig = gcf;\n axis off\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_S.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_S.fig']));\n close(hFig);\n\n imwrite(I_s,fullfile(SaveFolder, [para.SaveName '_I_s.png']));\n MagOut = ComputeSRSSD(img_edge);\n scc(MagOut,[0 0.9]); \n hFig = gcf;\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_I_e_WithFrame.png']));\n saveas(hFig,fullfile(SaveFolder,[para.SaveName '_I_e_WithFrame.fig']));\n close(hFig);\n\n imwrite(img_edge,fullfile(SaveFolder, [para.SaveName '_I_e.png']));\n% scc(img_edge, 'g',[0 1]); \n% hFig = gcf;\n% saveas(hFig,fullfile(SaveFolder,'img_edge.fig'));\n% imwrite(img_edge,fullfile(SaveFolder,'img_edge.png'));\n% close(hFig);\n end\nend\nfunction img_out = SmoothnessPreservingFunction(img_y,para,zooming)\n img_bb = imresize(img_y,zooming);\n Kernel = Sigma2Kernel(para.Gau_sigma);\n\n %compute the similarity from low\n Coef = 10;\n PatchSize = 3;\n Sqrt_low = SimilarityEvaluation(img_y,PatchSize);\n Similarity_low = exp(-Sqrt_low*Coef);\n [h_high w_high] = size(img_bb);\n ExpectedSimilarity = zeros(h_high,w_high,16);\n %upsamplin the similarity\n for dir=1:16\n ExpectedSimilarity(:,:,dir) = imresize(Similarity_low(:,:,dir),zooming,'bilinear');\n end\n \n %refind the Grad_high by Similarity_high\n LoopNumber = 10;\n img = img_bb;\n for loop = 1:LoopNumber\n %refine gradient by ExpectedSimilarity\n ValueSum = zeros(h_high,w_high);\n WeightSum = sum(ExpectedSimilarity,3); %if thw weight sum is low, it is unsuitable to generate the grad by interpolation\n for dir = 1:16\n [MoveOp N] = GetMoveKernel16(dir);\n if N == 1\n MovedData = imfilter(img,MoveOp{1},'replicate');\n else %N ==2\n MovedData1 = imfilter(img,MoveOp{1},'replicate');\n MovedData2 = imfilter(img,MoveOp{2},'replicate');\n MovedData = (MovedData1 + MovedData2)/2;\n end\n Product = MovedData .* ExpectedSimilarity(:,:,dir);\n ValueSum = ValueSum + Product;\n end\n I = ValueSum ./ WeightSum;\n \n %intensity compensate\n Diff = imresize(imfilter(I,Kernel,'replicate'),1/zooming, 'nearest') - img_y;\n UpSampled = imresize(Diff,zooming,'bilinear');\n Grad0 = imfilter(UpSampled,Kernel,'replicate');\n Term_LowHigh_in = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n I_in = I; %make a copy, restore the value if all beta fails\n bDecrease = false;\n tau = 0.2;\n for line_search_loop=1:10\n %line search for the beta, fixed 1/32 is not a good choice\n I = I_in - tau * Grad0;\n Term_LowHigh_out = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n if Term_LowHigh_out < Term_LowHigh_in\n bDecrease = true;\n break;\n else\n tau = tau * 0.5;\n end\n end\n \n if bDecrease == true\n I_best = I;\n else\n break;\n end\n% fprintf('loop=%d, LowHihg_in=%0.1f, LowHigh_out=%0.1f,\\n',loop,Term_LowHigh_in,Term_LowHigh_out); \n \n% imwrite(I,fullfile(SaveFolder, [num2str(loop) '_GenIntenFromGrad.png']));\n img = I_best;\n end\n img_out = img;\n\nend\nfunction SqrtData = SimilarityEvaluation(Img_in,PatchSize)\n HalfPatchSize = (PatchSize-1)/2;\n [h w] = size(Img_in);\n SqrtData = zeros(h,w,16);\n \n f3x3 = ones(3);\n for i = 1:16\n [DiffOp N] = RetGradientKernel16(i);\n if N == 1\n Diff = imfilter(Img_in,DiffOp{1},'symmetric');\n else\n Diff1 = imfilter(Img_in,DiffOp{1},'symmetric');\n Diff2 = imfilter(Img_in,DiffOp{2},'symmetric');\n Diff = (Diff1+Diff2)/2;\n end\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Mean = Sum/9;\n SqrtData(:,:,i) = sqrt(Mean);\n end\nend\nfunction [DiffOp N] = RetGradientKernel16(dir)\n DiffOp = cell(2,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n DiffOp{1} = f{1};\n DiffOp{2} = [];\n case 2\n N = 2;\n DiffOp{1} = f{1};\n DiffOp{2} = f{2};\n case 3\n N = 1; \n DiffOp{1} = f{2};\n DiffOp{2} = [];\n case 4\n N = 2;\n DiffOp{1} = f{2};\n DiffOp{2} = f{3};\n case 5\n N = 1;\n DiffOp{1} = f{3};\n DiffOp{2} = [];\n case 6\n N = 2;\n DiffOp{1} = f{3};\n DiffOp{2} = f{4};\n case 7\n N = 1;\n DiffOp{1} = f{4};\n DiffOp{2} = [];\n case 8\n N = 2;\n DiffOp{1} = f{4};\n DiffOp{2} = f{5};\n case 9\n N = 1;\n DiffOp{1} = f{5};\n DiffOp{2} = [];\n case 10\n N = 2;\n DiffOp{1} = f{5};\n DiffOp{2} = f{6};\n case 11\n DiffOp{1} = f{6};\n DiffOp{2} = [];\n N = 1;\n case 12\n N = 2;\n DiffOp{1} = f{6};\n DiffOp{2} = f{7};\n case 13\n N = 1;\n DiffOp{1} = f{7};\n DiffOp{2} = [];\n case 14\n N = 2;\n DiffOp{1} = f{7};\n DiffOp{2} = f{8};\n case 15\n DiffOp{1} = f{8};\n DiffOp{2} = [];\n N = 1;\n case 16\n N = 2;\n DiffOp{1} = f{8};\n DiffOp{2} = f{1};\n end\nend\nfunction [Kernel N] = GetMoveKernel16(dir)\n Kernel = cell(2,1);\n f{1} = [0 0 0;\n 0 0 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 0 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 0 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 0 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 0 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 0 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 0 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 0 0;\n 0 0 1];\n switch dir\n case 1\n N = 1;\n Kernel{1} = f{1};\n Kernel{2} = [];\n case 2\n N = 2;\n Kernel{1} = f{1};\n Kernel{2} = f{2};\n case 3\n N = 1; \n Kernel{1} = f{2};\n Kernel{2} = [];\n case 4\n N = 2;\n Kernel{1} = f{2};\n Kernel{2} = f{3};\n case 5\n N = 1;\n Kernel{1} = f{3};\n Kernel{2} = [];\n case 6\n N = 2;\n Kernel{1} = f{3};\n Kernel{2} = f{4};\n case 7\n N = 1;\n Kernel{1} = f{4};\n Kernel{2} = [];\n case 8\n N = 2;\n Kernel{1} = f{4};\n Kernel{2} = f{5};\n case 9\n N = 1;\n Kernel{1} = f{5};\n Kernel{2} = [];\n case 10\n N = 2;\n Kernel{1} = f{5};\n Kernel{2} = f{6};\n case 11\n Kernel{1} = f{6};\n Kernel{2} = [];\n N = 1;\n case 12\n N = 2;\n Kernel{1} = f{6};\n Kernel{2} = f{7};\n case 13\n N = 1;\n Kernel{1} = f{7};\n Kernel{2} = [];\n case 14\n N = 2;\n Kernel{1} = f{7};\n Kernel{2} = f{8};\n case 15\n Kernel{1} = f{8};\n Kernel{2} = [];\n N = 1;\n case 16\n N = 2;\n Kernel{1} = f{8};\n Kernel{2} = f{1};\n end\nend\nfunction f = ComputeFunctionValue_lowhigh(img,img_low,Gau_sigma)\n KernelSize = ceil(Gau_sigma) * 3 + 1;\n G = fspecial('gaussian',KernelSize,Gau_sigma);\n Conv = imfilter(img,G,'replicate');\n SubSample = imresize(Conv,size(img_low),'antialias',false);\n Diff = SubSample - img_low;\n Sqr = Diff.^2;\n f = sum(Sqr(:));\nend\nfunction Grad = Img2Grad(img)\n [h w] = size(img);\n Grad = zeros(h,w,8);\n DiffOp = RetGradientKernel();\n for i=1:8\n Grad(:,:,i) = imfilter(img,DiffOp{i},'replicate');\n end\nend\nfunction f = RetGradientKernel()\n f = cell(8,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\nend\nfunction Dissimilarity = EvaluateDissimilarity8(Img_in,PatchSize)\n if ~exist('PatchSize','var');\n PatchSize = 3;\n end\n [h w] = size(Img_in);\n Dissimilarity = zeros(h,w,8);\n \n f3x3 = ones(PatchSize)/(PatchSize^2);\n for i = 1:8\n DiffOp = RetGradientKernel8(i);\n Diff = imfilter(Img_in,DiffOp,'symmetric');\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Dissimilarity(:,:,i) = sqrt(Sum);\n end\nend\nfunction DiffOp = RetGradientKernel8(dir)\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n DiffOp = f{dir};\nend\nfunction img_out = GenerateIntensityFromGradient(img_y,img_initial,Grad_exp,para,zooming,Gau_sigma)\n if ~isfield(para,'bReport')\n para.bReport = false;\n end\n if ~isfield(para,'LoopNumber')\n para.LoopNumber = 30;\n end\n if ~isfield(para,'beta0')\n beta0 = 1;\n else\n beta0 = para.beta0;\n end\n if ~isfield(para,'beta1')\n beta1 = 1;\n else\n beta1 = para.beta1;\n end\n% TempFolder = para.tuningfolder;\n% zooming = para.zooming;\n \n \n %create dir\n% if isfield(para,'tuning')\n% SaveFolder = para.tuningfolder;\n% else\n% SaveFolder = fullfile(TempFolder,'OptimizationProgress');\n% end\n% if ~exist(SaveFolder,'dir')\n% mkdir( SaveFolder );\n% end\n \n Kernel = Sigma2Kernel(Gau_sigma);\n \n %compute gradient\n I = img_initial;\n I_best = I;\n for loop = 1:para.LoopNumber\n %refine image by patch similarity\n\n %refine image by low-high intensity\n Diff = imresize(imfilter(I,Kernel,'replicate'),1/zooming, 'nearest') - img_y;\n UpSampled = imresize(Diff,zooming,'bilinear');\n Grad0 = imfilter(UpSampled,Kernel,'replicate');\n \n %refine image by expected gradeint\n %Gradient decent\n %I = ModifyByGradient(I,Grad_exp);\n OptDir = Grad_exp - Img2Grad(I);\n Grad1 = sum(OptDir,3);\n Grad_all = beta0 * Grad0 + beta1 * Grad1;\n \n I_in = I; %make a copy, restore the value if all beta fails\n bDecrease = false;\n tau = 0.2;\n Term_Grad_in = ComputeFunctionValue_Grad(I,Grad_exp);\n Term_LowHigh_in = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n Term_all_in = Term_LowHigh_in * beta0 + Term_Grad_in * beta1;\n for line_search_loop=1:10\n %line search for the beta, fixed 1/32 is not a good choice\n I = I_in - tau * Grad_all;\n Term_Grad_out = ComputeFunctionValue_Grad(I,Grad_exp);\n Term_LowHigh_out = ComputeFunctionValue_lowhigh(I,img_y,para.Gau_sigma);\n Term_all_out = Term_LowHigh_out * beta0 + Term_Grad_out * beta1;\n \n if Term_all_out < Term_all_in\n bDecrease = true;\n break;\n else\n tau = tau * 0.5;\n end\n end\n \n if bDecrease == true\n I_best = I;\n else\n break;\n end\n if para.bReport\n fprintf(['loop=%d, all_in=%0.1f, all_out=%0.1f, LowHihg_in=%0.1f, LowHigh_out=%0.1f, ' ...\n 'Grad_in=%0.1f, Grad_out=%0.1f\\n'],loop,Term_all_in,Term_all_out,Term_LowHigh_in,Term_LowHigh_out, ...\n Term_Grad_in,Term_Grad_out); \n end\n \n% imwrite(I,fullfile(SaveFolder, [num2str(loop) '_GenIntenFromGrad.png']));\n end\n img_out = I_best;\nend\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U2_ReturnTheLargestToDoNumber.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U2_ReturnTheLargestToDoNumber.m", "size": 707, "source_encoding": "utf_8", "md5": "f1e7aae84f58dba2883b935de28df52c", "text": "%Chih-Yuan Yang\n%09/29/12\n%To parallel run Glasner's algorithm\n%Change name from U25 to U2\nfunction fileidx = U2_ReturnTheLargestToDoNumber(fn_symphony,iistart)\n fileidx = -1; %default, if \n\n fid = fopen(fn_symphony,'r+');\n C = textscan(fid,'%05d %s %d\\n');\n iiend = length(C{1,3});\n bwriteback = false;\n for i=iistart:iiend\n if C{1,3}(i) == 0\n fileidx = i;\n C{1,3}(i) = 1;\n bwriteback = true;\n break;\n end\n end\n if bwriteback\n fseek(fid,0,'bof'); %move to beginning\n for i=1:iiend\n fprintf(fid,'%05d %s %d\\n',C{1,1}(i),C{1,2}{i},C{1,3}(i));\n end \n end\n fclose(fid);\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F19c_GenerateLRImage_GaussianKernel.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F19c_GenerateLRImage_GaussianKernel.m", "size": 1852, "source_encoding": "utf_8", "md5": "867da30d81dc53d3a29ad3042d25141d", "text": "%Chih-Yuan Yang\n%03/15/13\n%Change the method of subsampling\n%F19b, add the mode of scaling as 2\n%F19c, add the mode of scaling as 8\nfunction lrimg = F19c_GenerateLRImage_GaussianKernel(hrimg,s,sigma)\n if isa(hrimg,'uint8')\n hrimg = im2double(hrimg);\n end\n [h, w, d] = size(hrimg);\n htrim = h-mod(h,s);\n wtrim = w-mod(w,s);\n imtrim = hrimg(1:htrim,1:wtrim,1:d);\n h_lr = htrim/s;\n w_lr = wtrim/s;\n \n %detect image type\n if mod(s,2) == 1 \n kernelsize = ceil(sigma * 3)*2+1; %the kernel size is odd\n kernel = fspecial('gaussian',kernelsize,sigma);\n if d == 1\n blurimg = imfilter(imtrim,kernel,'replicate');\n elseif d == 3\n blurimg = zeros(htrim,wtrim,d);\n for i=1:3\n blurimg(:,:,i) = imfilter(imtrim(:,:,i),kernel,'replicate');\n end\n end\n lrimg = imresize(blurimg,1/s,'nearest');\n elseif mod(s,2) == 0 %s is even\n sampleshift = s/2;\n kernelsize = ceil(sigma*3)*2+2; %the kernel size is even\n kernel = fspecial('gaussian',kernelsize,sigma); %kernel is always a symmetric matrix\n blurimg = imfilter(imtrim,kernel,'replicate');\n lrimg = zeros(h_lr,w_lr,d);\n for didx = 1:d\n for rl=1:h_lr\n r_hr_sample = (rl-1)*s+sampleshift; %the shift is the key issue, because the effect of imfilter using a kernel\n %shapened in even number width is equivalent to a 0.5 pixel shift in the\n %original image\n for cl = 1:w_lr\n c_hr_sample = (cl-1)*s+sampleshift;\n lrimg(rl,cl,didx) = blurimg(r_hr_sample,c_hr_sample,didx);\n end\n end\n end\n end \nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F37g_GetTexturePatchMatch_Aligned.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F37g_GetTexturePatchMatch_Aligned.m", "size": 13512, "source_encoding": "utf_8", "md5": "daf2019f43ec02e60280f1cc83622ce9", "text": "%Chih-Yuan Yang\n%09/08/13\n%Use patchmatch to retrieve a texture background\n%F37g: There is parallel optimization toolbox problem so that I have to\n%temporarily change the code where all parfor has to be removed.\nfunction [gradients_texture, img_texture, img_texture_backprojection] = F37g_GetTexturePatchMatch_Aligned(img_y, ...\n hrexampleimages, lrexampleimages, landmarks_test, rawexamplelandmarks)\n\n %parameter\n numberofHcandidate = 10;\n \n %start\n [h_lr, w_lr, exampleimagenumber] = size(lrexampleimages);\n [h_hr, w_hr, ~] = size(hrexampleimages);\n zooming = h_hr/h_lr;\n if zooming == 4\n Gau_sigma = 1.6;\n elseif zooming == 3\n Gau_sigma = 1.2;\n end\n alignedexampleimage_hr = zeros(h_hr,w_hr,exampleimagenumber,'uint8'); %set as uint8 to reduce memory demand\n alignedexampleimage_lr = zeros(h_lr,w_lr,exampleimagenumber);\n disp('align images');\n set = 28:48; %eyes and nose\n basepoints = landmarks_test(set,:);\n inputpoints = rawexamplelandmarks(set,:,:);\n \n for k=1:exampleimagenumber\n alignedexampleimage_hr(:,:,k) = F18_AlignExampleImageByLandmarkSet(hrexampleimages(:,:,k),inputpoints(:,:,k),basepoints);\n %F19 automatically convert uint8 input to double\n alignedexampleimage_lr(:,:,k) = F19a_GenerateLRImage_GaussianKernel(alignedexampleimage_hr(:,:,k),zooming,Gau_sigma);\n end\n \n cores = 2; % Use more cores for more speed\n\n if cores==1\n algo = 'cpu';\n else\n algo = 'cputiled';\n end\n patchsize_lr = 5;\n nn_iters = 5;\n\n A = repmat(img_y,[1 1 3]);\n testnumber = exampleimagenumber;\n xyandl2norm = zeros(h_lr,w_lr,3,testnumber,'int32');\n disp('patchmatching');\n for i=1:testnumber;\n %run patchmatch\n B = repmat(alignedexampleimage_lr(:,:,i),[1 1 3]);\n xyandl2norm(:,:,:,i) = nnmex(A, B, algo, patchsize_lr, nn_iters, [], [], [], [], cores); %the return totalpatchnumber int32\n end\n l2norm_double = double(xyandl2norm(:,:,3,:));\n [sortedl2norm, ix] = sort(l2norm_double,4);\n hrpatchextractdata = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate,3); %ii,r_lr_src,c_lr_src\n %here\n hrpatchsimilarity = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate);\n parameter_l2normtosimilarity = 625;\n for rl = 1:h_lr-patchsize_lr+1\n for cl = 1:w_lr-patchsize_lr+1\n for k=1:numberofHcandidate\n knnidx = ix(rl,cl,1,k);\n x = xyandl2norm(rl,cl,1,knnidx); %start from 0\n y = xyandl2norm(rl,cl,2,knnidx);\n clsource = x+1;\n rlsource = y+1;\n hrpatchextractdata(rl,cl,k,:) = reshape([knnidx rlsource clsource],[1 1 1 3]);\n hrpatchsimilarity(rl,cl,k) = exp(-sortedl2norm(rl,cl,1,knnidx)/parameter_l2normtosimilarity);\n end\n end\n end\n \n hrpatch = F39_ExtractAllHrPatches(patchsize_lr,zooming, hrpatchextractdata,alignedexampleimage_hr);\n hrpatch = F40_CompensateHRpatches(hrpatch, img_y, zooming, hrpatchextractdata,alignedexampleimage_lr);\n\n %mostsimilarinputpatchrecord = IF2_SearchForSelfSimilarPatchesL2Norm(img_y,patchsize_lr);\n \n %hrpatch_filtered = IF3_SimilarityFilter(hrpatch,hrpatchsimilarity,mostsimilarinputpatchrecord);\n \n %img_texture = IF4_BuildHRimagefromHRPatches(hrpatch_filtered,zooming);\n img_texture = IF4_BuildHRimagefromHRPatches(hrpatch,zooming);\n iternum = 1000;\n Tolf = 0.0001;\n breport = false;\n disp('backprojection for img_texture');\n img_texture_backprojection = F11d_BackProjection_GaussianKernel(img_y, img_texture, Gau_sigma, iternum,breport,Tolf);\n \n %extract the graident\n gradients_texture = F14_Img2Grad(img_texture_backprojection);\nend\nfunction scanresult = IF2_SearchForSelfSimilarPatchesL2Norm(img_y,patchsize_lr)\n %out:\n %scanresult: 3 x numberofFcandidate x (h_lr-patchsize+1) x (w_lr-patchsize+1)\n patcharea = patchsize_lr^2;\n [lh lw] = size(img_y);\n %Find self similar patches\n numberofFcandidate = 10;\n scanresult = zeros(3,numberofFcandidate,lh-patchsize_lr+1,lw-patchsize_lr+1); %scan results: r,c, similarity\n totalpatchnumber = (lh-patchsize_lr+1)*(lw-patchsize_lr+1);\n featurematrix = zeros(patcharea,totalpatchnumber);\n rec = zeros(2,totalpatchnumber);\n idx = 0;\n for rl=1:lh-patchsize_lr+1\n rl1 = rl+patchsize_lr-1;\n for cl=1:lw-patchsize_lr+1\n cl1 = cl+patchsize_lr-1;\n idx = idx + 1;\n rec(:,idx) = [rl;cl];\n featurematrix(:,idx) = reshape(img_y(rl:rl1,cl:cl1),patcharea,1);\n end\n end\n \n %search\n idx = 0;\n for rl=1:lh-patchsize_lr+1\n for cl=1:lw-patchsize_lr+1\n idx = idx + 1;\n fprintf('idx %d totalpatchnumber %d\\n',idx,totalpatchnumber);\n queryfeature = featurematrix(:,idx);\n diff = featurematrix - repmat(queryfeature,1,totalpatchnumber);\n sqr = sum(diff.^2);\n [ssqr ix] = sort(sqr);\n saveidx = 0;\n for j=1:numberofFcandidate+1 %add one to prevent find itself\n indexinsort = ix(j);\n sr = rec(1,indexinsort);\n sc = rec(2,indexinsort);\n %explanation: it is possible that there are 11 lr patches with the same appearance\n %and the input one is sorted at item indexed more than 11 so that sr and cl are insufficient\n %to prevenet the problem\n if sr ~= rl || sc ~= cl\n saveidx = saveidx + 1;\n if saveidx <= numberofFcandidate\n l2norm = sqrt(ssqr(j));\n similarity = exp(-l2norm/25);\n scanresult(1:3,saveidx,rl,cl) = [sr;sc;similarity];\n end\n end\n end\n end\n end\nend\nfunction hrpatch_filtered = IF3_SimilarityFilter(hrpatch,hrpatchsimilarity,mostsimilarinputpatches)\n %totalpatchnumber\n %hrpatch: patchsize_hr x patchsize_hr x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate\n %hrpatchsimilarity: (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate\n %mostsimilarinputpatches: 3 x numberofFcandidate x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1)\n %out\n %hrpatch_filtered: patchsize_hr x patchsize_hr x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1)\n zooming = 4;\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr /zooming;\n h_lr = size(hrpatch,3) + patchsize_lr -1;\n w_lr = size(hrpatch,4) + patchsize_lr -1;\n numberofHcandidate = size(hrpatch,5);\n numberofFcandidate = size(mostsimilarinputpatches,2);\n \n %allocate for out\n hrpatch_filtered = zeros(patchsize_hr,patchsize_hr,h_lr-patchsize_lr+1,w_lr-patchsize_lr+1);\n \n for rl= 1:h_lr-patchsize_lr+1\n fprintf('rl:%d total:%d\\n',rl,h_lr-patchsize_lr+1);\n for cl = 1:w_lr-patchsize_lr+1\n %load candidates\n H = zeros(patchsize_hr,patchsize_hr,numberofHcandidate);\n similarityHtolrpatch = zeros(numberofHcandidate,1);\n for j=1:numberofHcandidate\n H(:,:,j) = hrpatch(:,:,rl,cl,j); %H\n similarityHtolrpatch(j) = hrpatchsimilarity(rl,cl,j);\n end\n \n %self similar patch instance number\n similarityFtolrpatch = reshape( mostsimilarinputpatches(3,:,rl,cl) , [numberofFcandidate , 1]);\n \n %load all of the two step patches\n R = zeros(patchsize_hr,patchsize_hr,numberofFcandidate,numberofHcandidate);\n RSimbasedonF = zeros(numberofFcandidate,numberofHcandidate);\n for i=1:numberofFcandidate\n sr = mostsimilarinputpatches(1,i,rl,cl);\n sc = mostsimilarinputpatches(2,i,rl,cl);\n %hr candidate number\n for j=1:numberofHcandidate\n R(:,:,i,j) = hrpatch(:,:,sr,sc,j);\n RSimbasedonF(i,j) = hrpatchsimilarity(sr,sc,j);\n end\n end\n \n %here is a question, how to define the similarity between H and R?\n %L2norm?\n hscore = zeros(numberofHcandidate,1);\n for i=1:numberofHcandidate\n theH = H(:,:,i);\n for j=1:numberofFcandidate\n for k=1:numberofHcandidate\n theR = R(:,:,j,k);\n similarityRbasedonF = RSimbasedonF(j,k);\n %similarity between H and R\n diff = theH - theR;\n L2N = norm(diff(:));\n similarityRtoH = exp(- L2N/25); %the 25 is a parameter, need to be tuned totalpatchnumber the future\n hscore(i) = hscore(i) + similarityHtolrpatch(i) * similarityRbasedonF * similarityRtoH * similarityFtolrpatch(j);\n end\n end\n end\n [~, idx] = max(hscore);\n hrpatch_filtered(:,:,rl,cl) = hrpatch(:,:,rl,cl,idx(1));\n end\n end\nend\nfunction img_texture = IF4_BuildHRimagefromHRPatches(hrpatch,zooming)\n %reconstruct the high-resolution image\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr/zooming;\n h_lr = size(hrpatch,3) + patchsize_lr - 1;\n w_lr = size(hrpatch,4) + patchsize_lr - 1;\n h_expected = h_lr * zooming;\n w_expected = w_lr * zooming;\n img_texture = zeros(h_expected,w_expected);\n %most cases\n rpixelshift = 2; %this should be modified according to patchsize_lr\n cpixelshift = 2;\n for rl = 2:h_lr - patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n for cl = 2:w_lr - patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(9:12,9:12);\n end\n end\n \n %left\n cl = 1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %right\n cl = w_lr - patchsize_lr+1;\n ch = w_expected - 3*zooming+1;\n ch1 = w_expected;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %top\n rl = 1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %bottom\n rl = h_lr-patchsize_lr+1;\n rh = h_expected - 3*zooming+1;\n rh1 = h_expected;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %left-top corner\n rl=1;\n cl=1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %right-top corner\n rl=1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "U11_ExtractEyeRangeFeature.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/U11_ExtractEyeRangeFeature.m", "size": 529, "source_encoding": "utf_8", "md5": "8b0d1120b08d30f10d422b87054bd2bf", "text": "%Chih-Yuan Yang\n%08/31/12\nfunction eyerangefeature = U11_ExtractEyeRangeFeature(eyerange)\n [h w] = size(eyerange);\n %the feature: gradient\n %check type, int8 can not compute feature\n if isa(eyerange,'double')\n eyerange_double = eyerange;\n else\n eyerange_double = double(eyerange);\n end\n dx = eyerange_double(:,2:end) - eyerange_double(:,1:end-1);\n dy = eyerange_double(2:end,:) - eyerange_double(1:end-1,:);\n eyerangefeature = cat(1,reshape(dx,[h*(w-1) 1]), reshape(dy,[(h-1)*w 1]));\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F41_ComputePatchSimilarity.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F41_ComputePatchSimilarity.m", "size": 483, "source_encoding": "utf_8", "md5": "9a56cadc176880ec786d047551d619eb", "text": "%Chih-Yuan Yang\n%10/12/12\n%For nnmex() in terms of discriptor mode\nfunction l2norm = F41_ComputePatchSimilarity(A,B,xy)\n [h w d] = size(A);\n retrieveddescriptor = zeros(h,w,d);\n for r=1:h\n for c=1:w\n x = xy(r,c,1);\n y = xy(r,c,2);\n r_source = y+1;\n c_source = x+1;\n retrieveddescriptor(r,c,:) = B(r_source,c_source,:);\n end\n end\n diff = A-retrieveddescriptor;\n l2norm = sqrt(sum(diff.^2,3));\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "T1_Img2Grad.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/T1_Img2Grad.m", "size": 743, "source_encoding": "utf_8", "md5": "dfeb710d5ccd6e72fc1185c0d2ad270b", "text": "function Grad = T1_Img2Grad(img)\n [h w] = size(img);\n Grad = zeros(h,w,8);\n DiffOp = RetGradientKernel();\n for i=1:8\n Grad(:,:,i) = imfilter(img,DiffOp{i},'replicate');\n end\nend\nfunction f = RetGradientKernel()\n f = cell(8,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F37a_GetTexturePatchMatchSimilarityFilter.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F37a_GetTexturePatchMatchSimilarityFilter.m", "size": 15700, "source_encoding": "utf_8", "md5": "a3d7b006dc2ed233234aae66f7da2cbe", "text": "%Chih-Yuan Yang\n%10/05/12\n%Use patchmatch to retrieve a texture background\nfunction [gradients_texture img_texture img_texture_backprojection] = F37a_GetTexturePatchMatchSimilarityFilter(img_y, ...\n hrexampleimages, lrexampleimages)\n\n %parameter\n numberofHcandidate = 10;\n \n %start\n [h_lr, w_lr, exampleimagenumber] = size(lrexampleimages);\n [h_hr, w_hr, ~] = size(hrexampleimages);\n zooming = h_hr/h_lr;\n if zooming == 4\n Gau_sigma = 1.6;\n elseif zooming == 3\n Gau_sigma = 1.2;\n end\n \n cores = 2; % Use more cores for more speed\n\n if cores==1\n algo = 'cpu';\n else\n algo = 'cputiled';\n end\n patchsize_lr = 5;\n nn_iters = 5;\n %A =F38_ExtractFeatureFromAnImage(img_y);\n A = repmat(img_y,[1 1 3]);\n testnumber = exampleimagenumber;\n xyandl2norm = zeros(h_lr,w_lr,3,testnumber,'int32');\n disp('patchmatching');\n parfor i=1:testnumber;\n %run patchmatch\n B = repmat(lrexampleimages(:,:,i),[1 1 3]);\n xyandl2norm(:,:,:,i) = nnmex(A, B, algo, patchsize_lr, nn_iters, [], [], [], [], cores); %the return totalpatchnumber int32\n end\n l2norm_double = double(xyandl2norm(:,:,3,:));\n [sortedl2norm, ix] = sort(l2norm_double,4);\n hrpatchextractdata = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate,3); %ii,r_lr_src,c_lr_src\n %here\n hrpatchsimilarity = zeros(h_lr-patchsize_lr+1,w_lr-patchsize_lr+1,numberofHcandidate);\n parameter_l2normtosimilarity = 625;\n for rl = 1:h_lr-patchsize_lr+1\n for cl = 1:w_lr-patchsize_lr+1\n for k=1:numberofHcandidate\n knnidx = ix(rl,cl,1,k);\n x = xyandl2norm(rl,cl,1,knnidx); %start from 0\n y = xyandl2norm(rl,cl,2,knnidx);\n clsource = x+1;\n rlsource = y+1;\n hrpatchextractdata(rl,cl,k,:) = reshape([knnidx rlsource clsource],[1 1 1 3]);\n hrpatchsimilarity(rl,cl,k) = exp(-sortedl2norm(rl,cl,1,knnidx)/parameter_l2normtosimilarity);\n end\n end\n end\n \n hrpatch = IF1_ExtractAllHrPatches(img_y, patchsize_lr,zooming, hrpatchextractdata,hrexampleimages,lrexampleimages);\n\n mostsimilarinputpatchrecord = IF2_SearchForSelfSimilarPatchesL2Norm(img_y,patchsize_lr);\n \n hrpatch_filtered = IF3_SimilarityFilter(hrpatch,hrpatchsimilarity,mostsimilarinputpatchrecord);\n \n img_texture = IF4_BuildHRimagefromHRPatches(hrpatch_filtered,zooming);\n iternum = 1000;\n Tolf = 0.0001;\n breport = false;\n disp('backprojection for img_texture');\n img_texture_backprojection = F11d_BackProjection_GaussianKernel(img_y, img_texture, Gau_sigma, iternum,breport,Tolf);\n \n %extract the graident\n gradients_texture = F14_Img2Grad(img_texture_backprojection);\nend\nfunction scanresult = IF2_SearchForSelfSimilarPatchesL2Norm(img_y,patchsize_lr)\n %out:\n %scanresult: 3 x numberofFcandidate x (h_lr-patchsize+1) x (w_lr-patchsize+1)\n patcharea = patchsize_lr^2;\n [lh lw] = size(img_y);\n %Find self similar patches\n numberofFcandidate = 10;\n scanresult = zeros(3,numberofFcandidate,lh-patchsize_lr+1,lw-patchsize_lr+1); %scan results: r,c, similarity\n totalpatchnumber = (lh-patchsize_lr+1)*(lw-patchsize_lr+1);\n featurematrix = zeros(patcharea,totalpatchnumber);\n rec = zeros(2,totalpatchnumber);\n idx = 0;\n for rl=1:lh-patchsize_lr+1\n rl1 = rl+patchsize_lr-1;\n for cl=1:lw-patchsize_lr+1\n cl1 = cl+patchsize_lr-1;\n idx = idx + 1;\n rec(:,idx) = [rl;cl];\n featurematrix(:,idx) = reshape(img_y(rl:rl1,cl:cl1),patcharea,1);\n end\n end\n \n %search\n idx = 0;\n for rl=1:lh-patchsize_lr+1\n for cl=1:lw-patchsize_lr+1\n idx = idx + 1;\n fprintf('idx %d totalpatchnumber %d\\n',idx,totalpatchnumber);\n queryfeature = featurematrix(:,idx);\n diff = featurematrix - repmat(queryfeature,1,totalpatchnumber);\n sqr = sum(diff.^2);\n [ssqr ix] = sort(sqr);\n saveidx = 0;\n for j=1:numberofFcandidate+1 %add one to prevent find itself\n indexinsort = ix(j);\n sr = rec(1,indexinsort);\n sc = rec(2,indexinsort);\n %explanation: it is possible that there are 11 lr patches with the same appearance\n %and the input one is sorted at item indexed more than 11 so that sr and cl are insufficient\n %to prevenet the problem\n if sr ~= rl || sc ~= cl\n saveidx = saveidx + 1;\n if saveidx <= numberofFcandidate\n l2norm = sqrt(ssqr(j));\n similarity = exp(-l2norm/25);\n scanresult(1:3,saveidx,rl,cl) = [sr;sc;similarity];\n end\n end\n end\n end\n end\nend\nfunction hrpatch_filtered = IF3_SimilarityFilter(hrpatch,hrpatchsimilarity,mostsimilarinputpatches)\n %totalpatchnumber\n %hrpatch: patchsize_hr x patchsize_hr x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate\n %hrpatchsimilarity: (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate\n %mostsimilarinputpatches: 3 x numberofFcandidate x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1)\n %out\n %hrpatch_filtered: patchsize_hr x patchsize_hr x (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1)\n zooming = 4;\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr /zooming;\n h_lr = size(hrpatch,3) + patchsize_lr -1;\n w_lr = size(hrpatch,4) + patchsize_lr -1;\n numberofHcandidate = size(hrpatch,5);\n numberofFcandidate = size(mostsimilarinputpatches,2);\n \n %allocate for out\n hrpatch_filtered = zeros(patchsize_hr,patchsize_hr,h_lr-patchsize_lr+1,w_lr-patchsize_lr+1);\n \n for rl= 1:h_lr-patchsize_lr+1\n fprintf('rl:%d total:%d\\n',rl,h_lr-patchsize_lr+1);\n for cl = 1:w_lr-patchsize_lr+1\n %load candidates\n H = zeros(patchsize_hr,patchsize_hr,numberofHcandidate);\n similarityHtolrpatch = zeros(numberofHcandidate,1);\n for j=1:numberofHcandidate\n H(:,:,j) = hrpatch(:,:,rl,cl,j); %H\n similarityHtolrpatch(j) = hrpatchsimilarity(rl,cl,j);\n end\n \n %self similar patch instance number\n similarityFtolrpatch = reshape( mostsimilarinputpatches(3,:,rl,cl) , [numberofFcandidate , 1]);\n \n %load all of the two step patches\n R = zeros(patchsize_hr,patchsize_hr,numberofFcandidate,numberofHcandidate);\n RSimbasedonF = zeros(numberofFcandidate,numberofHcandidate);\n for i=1:numberofFcandidate\n sr = mostsimilarinputpatches(1,i,rl,cl);\n sc = mostsimilarinputpatches(2,i,rl,cl);\n %hr candidate number\n for j=1:numberofHcandidate\n R(:,:,i,j) = hrpatch(:,:,sr,sc,j);\n RSimbasedonF(i,j) = hrpatchsimilarity(sr,sc,j);\n end\n end\n \n %here is a question, how to define the similarity between H and R?\n %L2norm?\n hscore = zeros(numberofHcandidate,1);\n for i=1:numberofHcandidate\n theH = H(:,:,i);\n for j=1:numberofFcandidate\n for k=1:numberofHcandidate\n theR = R(:,:,j,k);\n similarityRbasedonF = RSimbasedonF(j,k);\n %similarity between H and R\n diff = theH - theR;\n L2N = norm(diff(:));\n similarityRtoH = exp(- L2N/25); %the 25 is a parameter, need to be tuned totalpatchnumber the future\n hscore(i) = hscore(i) + similarityHtolrpatch(i) * similarityRbasedonF * similarityRtoH * similarityFtolrpatch(j);\n end\n end\n end\n [~, idx] = max(hscore);\n hrpatch_filtered(:,:,rl,cl) = hrpatch(:,:,rl,cl,idx(1));\n end\n end\nend\nfunction hrpatch = IF1_ExtractAllHrPatches(img_y, patchsize_lr,zooming,hrpatchextractdata,allHRexampleimages,allLRexampleimages)\n %question: if the hrpatch does not need compensate, the input paramters img_y and allLRexampleimages can be ignore\n %in:\n %hrpatchextractdata: (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate * 3\n %the last 3 dim: ii, r_lr_src, c_lr_src\n disp('extracting HR patches');\n patchsize_hr = patchsize_lr * zooming;\n [h_lr_active, w_lr_active, numberofHcandidate, ~] = size(hrpatchextractdata);\n hrpatch = zeros(patchsize_hr,patchsize_hr,h_lr_active,w_lr_active,numberofHcandidate);\n \n %analyize which images need to be loaded\n alliiset = hrpatchextractdata(:,:,:,1);\n alliiset_uni = unique(alliiset(:));\n\n for i = 1:length(alliiset_uni)\n ii = alliiset_uni(i);\n fprintf('extracting image %d\\n',ii);\n exampleimage_hr = im2double(allHRexampleimages(:,:,ii));\n exampleimage_lr = allLRexampleimages(:,:,ii);\n match_4D = alliiset == ii;\n match_3D = reshape(match_4D,h_lr_active,w_lr_active,numberofHcandidate); %remove the last dimension\n [rlset clandkset] = find(match_3D);\n setsize = length(rlset);\n for j = 1:setsize\n rl = rlset(j);\n clandklinearindex = clandkset(j);\n %the relationship clandklindearidx = x_lr_active * (k-1) + cl\n k = floor( (clandklinearindex-1)/w_lr_active) +1; %the relationship: possum = (pos3-1) * d2 + pos2, pos2 totalpatchnumber (1,d2)\n cl = clandklinearindex - (k-1)*w_lr_active;\n\n sr = hrpatchextractdata(rl,cl,k,2);\n sc = hrpatchextractdata(rl,cl,k,3);\n \n srh = (sr-1)*zooming+1;\n srh1 = srh + patchsize_hr -1;\n sch = (sc-1)*zooming+1;\n sch1 = sch + patchsize_hr-1;\n\n %compensate the HR patch to match the LR query patch\n hrp = exampleimage_hr(srh:srh1,sch:sch1); %HR patch \n %lrq = img_y(rl:rl+patchsize_lr-1,cl:cl+patchsize_lr-1); %LR query patch\n %lrr = exampleimage_lr(sr:sr+patchsize_lr-1,sc:sc+patchsize_lr-1); %LR retrieved patch\n %the imresize make the process very slow\n %chrp = hrp + imresize(lrq - lrr,zooming,'bilinear'); %compensate HR patch\n %hrpatch(:,:,rl,cl,k) = chrp;\n hrpatch(:,:,rl,cl,k) = hrp;\n \n if 0\n bVisuallyCheck = false;\n if bVisuallyCheck\n if ~exist('hfig','var')\n hfig = figure;\n else\n figure(hfig);\n end\n subplot(1,4,1);\n imshow(hrp/255);\n title('hrp');\n subplot(1,4,2);\n imshow(lrr/255);\n title('lrr');\n subplot(1,4,3);\n imshow(lrq/255);\n title('lrq');\n subplot(1,4,4);\n imshow(chrp/255);\n title('chrp');\n keyboard\n end\n end\n end \n end\nend\nfunction img_texture = IF4_BuildHRimagefromHRPatches(hrpatch,zooming)\n %reconstruct the high-resolution image\n patchsize_hr = size(hrpatch,1);\n patchsize_lr = patchsize_hr/zooming;\n h_lr = size(hrpatch,3) + patchsize_lr - 1;\n w_lr = size(hrpatch,4) + patchsize_lr - 1;\n h_expected = h_lr * zooming;\n w_expected = w_lr * zooming;\n img_texture = zeros(h_expected,w_expected);\n %most cases\n rpixelshift = 2; %this should be modified according to patchsize_lr\n cpixelshift = 2;\n for rl = 2:h_lr - patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n for cl = 2:w_lr - patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(9:12,9:12);\n end\n end\n \n %left\n cl = 1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %right\n cl = w_lr - patchsize_lr+1;\n ch = w_expected - 3*zooming+1;\n ch1 = w_expected;\n for rl=2:h_lr-patchsize_lr\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %top\n rl = 1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %bottom\n rl = h_lr-patchsize_lr+1;\n rh = h_expected - 3*zooming+1;\n rh1 = h_expected;\n for cl=2:w_lr-patchsize_lr\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n end\n \n %left-top corner\n rl=1;\n cl=1;\n rh = 1;\n rh1 = rh+3*zooming-1;\n ch = 1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %right-top corner\n rl=1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 1;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 1;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\n \n %left-bottom corner\n rl=h_lr-patchsize_lr+1;\n cl=w_lr-patchsize_lr+1;\n rh = (rl-1+rpixelshift)*zooming+1;\n rh1 = rh+3*zooming-1;\n ch = (cl-1+cpixelshift)*zooming+1;\n ch1 = ch+3*zooming-1;\n usedhrpatch = hrpatch(:,:,rl,cl);\n chsource = 9;\n ch1source = chsource+3*zooming-1;\n rhsource = 9;\n rh1source = rhsource+3*zooming-1;\n img_texture(rh:rh1,ch:ch1) = usedhrpatch(rhsource:rh1source,chsource:ch1source);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F39_ExtractAllHrPatches.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F39_ExtractAllHrPatches.m", "size": 2478, "source_encoding": "utf_8", "md5": "2b17a373baa50a6548520ff944833a50", "text": "%Chih-Yuan Yang\n%10/07/12\n%Sepearte internal function as external\nfunction hrpatch = F39_ExtractAllHrPatches(patchsize_lr,zooming,hrpatchextractdata,allHRexampleimages)\n %question: if the hrpatch does not need compensate, the input paramters img_y and allLRexampleimages can be ignore\n %in:\n %hrpatchextractdata: (h_lr-patchsize_lr+1) x (w_lr-patchsize_lr+1) x numberofHcandidate * 3\n %the last 3 dim: ii, r_lr_src, c_lr_src\n disp('extracting HR patches');\n patchsize_hr = patchsize_lr * zooming;\n [h_lr_active, w_lr_active, numberofHcandidate, ~] = size(hrpatchextractdata);\n hrpatch = zeros(patchsize_hr,patchsize_hr,h_lr_active,w_lr_active,numberofHcandidate);\n \n %analyize which images need to be loaded\n alliiset = hrpatchextractdata(:,:,:,1);\n alliiset_uni = unique(alliiset(:));\n\n for i = 1:length(alliiset_uni)\n ii = alliiset_uni(i);\n fprintf('extracting image %d in function F39\\n',ii);\n exampleimage_hr = im2double(allHRexampleimages(:,:,ii));\n match_4D = alliiset == ii;\n match_3D = reshape(match_4D,h_lr_active,w_lr_active,numberofHcandidate); %remove the last dimension\n [rlset clandkset] = find(match_3D);\n setsize = length(rlset);\n for j = 1:setsize\n rl = rlset(j);\n clandklinearindex = clandkset(j);\n %the relationship clandklindearidx = x_lr_active * (k-1) + cl\n k = floor( (clandklinearindex-1)/w_lr_active) +1; %the relationship: possum = (pos3-1) * d2 + pos2, pos2 totalpatchnumber (1,d2)\n cl = clandklinearindex - (k-1)*w_lr_active;\n\n sr = hrpatchextractdata(rl,cl,k,2);\n sc = hrpatchextractdata(rl,cl,k,3);\n \n srh = (sr-1)*zooming+1;\n srh1 = srh + patchsize_hr -1;\n sch = (sc-1)*zooming+1;\n sch1 = sch + patchsize_hr-1;\n\n %compensate the HR patch to match the LR query patch\n hrp = exampleimage_hr(srh:srh1,sch:sch1); %HR patch \n %lrq = img_y(rl:rl+patchsize_lr-1,cl:cl+patchsize_lr-1); %LR query patch\n %lrr = exampleimage_lr(sr:sr+patchsize_lr-1,sc:sc+patchsize_lr-1); %LR retrieved patch\n %the imresize make the process very slow\n %chrp = hrp + imresize(lrq - lrr,zooming,'bilinear'); %compensate HR patch\n %hrpatch(:,:,rl,cl,k) = chrp;\n hrpatch(:,:,rl,cl,k) = hrp;\n end \n end\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F20_Sigma2Kernel.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F20_Sigma2Kernel.m", "size": 174, "source_encoding": "utf_8", "md5": "5dd9a9e790fe6562963dad18ce1f632d", "text": "%Chih-Yuan Yang\n%09/20/12\nfunction Kernel = F20_Sigma2Kernel(Gau_sigma)\n KernelSize = ceil(Gau_sigma * 3)*2+1;\n Kernel = fspecial('gaussian',KernelSize,Gau_sigma);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F6e_RetriveImage_DrawFlowChart.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F6e_RetriveImage_DrawFlowChart.m", "size": 2799, "source_encoding": "utf_8", "md5": "90151785621128e11aefa5cdc589c2fe", "text": "%Chih-Yuan Yang\n%6/12/13\n%F6d: return the alinged images to draw the flowchart\n%F6e: return the aligned landmarks so that I can draw the new figure for PAMI\nfunction [retrievedhrimage, retrievedlrimage, retrievedidx, alignedexampleimage_hr, alignedexampleimage_lr, ...\n alignedlandmarks] = ...\n F6e_RetriveImage_DrawFlowChart(testimage_lr, ...\n rawexampleimage, inputpoints, basepoints, mask_lr, zooming, Gau_sigma, glasslist, bglassavoid)\n %the rawexampleimage should be double\n if ~isa(rawexampleimage,'uint8')\n error('wrong class');\n end\n\n [h_hr, w_hr, exampleimagenumber] = size(rawexampleimage);\n [h_lr, w_lr] = size(testimage_lr);\n %find the transform matrix by solving an optimization problem\n alignedexampleimage_hr = zeros(h_hr,w_hr,exampleimagenumber,'uint8'); %set as uint8 to reduce memory demand\n alignedexampleimage_lr = zeros(h_lr,w_lr,exampleimagenumber);\n arr_alignedlandmarks = cell(exampleimagenumber,1);\n parfor i=1:exampleimagenumber\n [alignedexampleimage_hr(:,:,i) , arr_alignedlandmarks{i}]= F18b_AlignExampleImageByLandmarkSet(rawexampleimage(:,:,i),inputpoints(:,:,i),basepoints);\n %F19 automatically convert uint8 input to double\n alignedexampleimage_lr(:,:,i) = F19a_GenerateLRImage_GaussianKernel(alignedexampleimage_hr(:,:,i),zooming,Gau_sigma);\n end\n\n [r_set, c_set] = find(mask_lr);\n top = min(r_set);\n bottom = max(r_set);\n left = min(c_set);\n right = max(c_set);\n area_test = im2double(testimage_lr(top:bottom,left:right));\n area_mask = mask_lr(top:bottom,left:right);\n area_test_aftermask = area_test .* area_mask;\n %extract feature from the eyerange, the features are the gradient of LR eye region\n feature_test = F24_ExtractFeatureFromArea(area_test_aftermask); %the unit is double\n\n %search for the thousand example images to find the most similar eyerange\n normvalue = zeros(exampleimagenumber,1);\n parfor j=1:exampleimagenumber\n examplearea_lr = alignedexampleimage_lr(top:bottom,left:right,j);\n examplearea_lr_aftermask = examplearea_lr .* area_mask;\n feature_example_lr = F24_ExtractFeatureFromArea(examplearea_lr_aftermask); %the unit is double\n normvalue(j) = norm(feature_test - feature_example_lr);\n end\n %find the small norm\n [sortnorm, ix] = sort(normvalue);\n %some of them are very similar\n\n %only return the 1nn\n if bglassavoid\n for k=1:exampleimagenumber\n if glasslist(ix(k)) == false\n break\n end\n end\n else\n k =1;\n end\n retrievedhrimage = alignedexampleimage_hr(:,:,ix(k)); \n retrievedlrimage = alignedexampleimage_lr(:,:,ix(k));\n alignedlandmarks = arr_alignedlandmarks{ix(k)};\n retrievedidx = ix(k);\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F21f_EdgePreserving_GaussianKernel.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ours2/F21f_EdgePreserving_GaussianKernel.m", "size": 10261, "source_encoding": "utf_8", "md5": "c49afa98a0822dec5155f604e7daf9f1", "text": "%Chih-Yuan Yang\n%10/27/12\n%F21b: Based on F21a, but change the square kernel to Gaussian, to see whether the square pattern disappear\n%F21c: remove the para argument\n%F21d: try to use large beta0 and small beta1 to see whether it can save the computational time\n%F21e: return gradient_expect to save time\n%F21f: change the function F27 to F27a used in this function\nfunction [gradient_expected, weightmap_edge] = F21f_EdgePreserving_GaussianKernel(img_y,zooming,Gau_sigma)\n LowMagSuppression = 0; %the three parameters should be adjusted later\n DistanceUpperBound = 2.0;\n ContrastEnhenceCoef = 1.0;\n I_s = F27a_SmoothnessPreserving(img_y,zooming,Gau_sigma);\n folder_output = fullfile('Result','Test17_GenerateFigureForPAMI15');\n imwrite(I_s,fullfile(folder_output,'H_s.png'));\n T = F15_ComputeSRSSD(I_s);\n hfig = figure;\n imagesc(T);\n axis image off\n caxis([0 0.7121]); \n saveas(hfig, fullfile(folder_output,'mag.png'));\n close(hfig);\n \n Dissimilarity = EvaluateDissimilarity8(I_s);\n Grad_high_initial = Img2Grad(I_s);\n \n [h w] = size(T);\n StatisticsFolder = fullfile('EdgePriors');\n LoadFileName = sprintf('Statistics_Sc%d_Si%0.1f.mat',zooming,Gau_sigma);\n LoadData = load(fullfile(StatisticsFolder,LoadFileName));\n Statistics = LoadData.Statistics;\n \n RidgeMap = edge(I_s,'canny',[0 0.01],0.05);\n \n %Draw the canny detected edges to the cropped region\n mag_plus_edge_whole_image = T;\n% mag_plus_edge_whole_image(RidgeMap) = 0.2111;\n CropRegion = mag_plus_edge_whole_image(257+1:257+1+12-1,50+1:50+1+9-1);\n hfig = figure;\n imagesc(CropRegion);\n axis image off\n caxis([0 0.7121]);\n saveas(hfig, fullfile(folder_output, 'mag_region.png'));\n close(hfig);\n \n RidgeMap_inverted = ~RidgeMap;\n imwrite(RidgeMap_inverted,fullfile(folder_output,'Canny.png'));\n\n %filter out small ridge and non-maximun ridges\n RidgeMap_filtered = RidgeMap;\n [r_set c_set] = find(RidgeMap);\n SetLength = length(r_set);\n for j=1:SetLength\n r = r_set(j);\n c = c_set(j);\n CenterMagValue = T(r,c);\n if CenterMagValue < LowMagSuppression\n RidgeMap_filtered(r,c) = false;\n end\n end\n \n\n [r_set c_set] = find(RidgeMap_filtered);\n SetLength = length(r_set);\n [X Y] = meshgrid(1:11,1:11);\n DistPatch = sqrt((X-6).^2 + (Y-6).^2);\n\n DistMap = inf(h,w); \n UsedPixel = false(h,w); \n CenterCoor = zeros(h,w,2); \n %Compute DistMap and CneterCoor\n [r_set c_set] = find(RidgeMap_filtered);\n for j=1:SetLength\n r = r_set(j);\n r1 = r-5;\n r2 = r+5;\n c = c_set(j);\n c1 = c-5;\n c2 = c+5;\n if r1>=1 && r2<=h && c1>=1 && c2<=w %discrad boundary?\n MapPatch = DistMap(r1:r2,c1:c2);\n MinPatch = min(MapPatch, DistPatch);\n DistMap(r1:r2,c1:c2) = MinPatch;\n UsedPixel(r1:r2,c1:c2) = true;\n ChangedPixels = MinPatch < MapPatch;\n OriginalCenterCoorPatch = CenterCoor(r1:r2,c1:c2,:);\n NewCoor = cat(3,r*ones(11), c*ones(11));\n NewCenterCoorPatch = OriginalCenterCoorPatch .* repmat(1-ChangedPixels,[1,1,2]) + NewCoor .* repmat(ChangedPixels,[1,1,2]);\n CenterCoor(r1:r2,c1:c2,:) = NewCenterCoorPatch;\n end\n end\n\n %Convert dist to table index\n TableIndexMap = zeros(h,w);\n b = unique(DistPatch(:));\n for i=1:length(b)\n SetPixels = DistMap == b(i);\n TableIndexMap(SetPixels) = i;\n end\n\n \n %mapping (T_p, T_r, d) to S_p\n [r_set c_set] = find(UsedPixel);\n SetLength = length(r_set);\n UpdatedPixel = false(h,w);\n S = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n CurrentMagValue = T(r,c);\n BinIdx_Current = ceil(CurrentMagValue /0.005);\n %Zebra have super strong Mag\n if BinIdx_Current > 100\n BinIdx_Current = 100;\n end\n TableIndex = TableIndexMap(r,c);\n if TableIndex > DistanceUpperBound\n continue\n end\n CenterMagValue = T(r_Center,c_Center);\n %Low Mag Edge suppresion\n if CenterMagValue < LowMagSuppression\n continue\n end\n BinIdx_Center = ceil(CenterMagValue /0.005);\n if BinIdx_Center > 100\n BinIdx_Center = 100;\n end\n %consult the table\n if TableIndex == 1 %1 is the index of b(1) where dist = 0, enhance the contrast of pixel on edge \n S_p = ContrastEnhenceCoef * Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n else\n S_p = Statistics(TableIndex).EstimatedMag(BinIdx_Current,BinIdx_Center);\n end\n \n if isnan(S_p)\n else\n UpdatedPixel(r,c) = true;\n S(r,c) = S_p;\n end\n end\n\n %Record the RidgeMapMap, for computing te ProbOfMag\n %the Mag is the consulted Mag\n %here is the problem, when the S is very strong, the affect range of ProbMagOut exceeds 1 pixel\n RidgeMapMagValue = zeros(h,w);\n for i=1:SetLength\n r = r_set(i);\n c = c_set(i);\n r_Center = CenterCoor(r,c,1);\n c_Center = CenterCoor(r,c,2);\n RidgeMapMagValue(r,c) = S(r_Center,c_Center);\n end \n \n S(~UpdatedPixel) = T(~UpdatedPixel);\n img_in = I_s;\n if min(Dissimilarity(:)) == 0\n d = Dissimilarity + 1e-6; %avoid 0 case; some images may have d(:,:,1) as 0\n else\n d = Dissimilarity;\n end\n ratio = d ./ repmat(d(:,:,1),[1,1,8]);\n %here is the problem, I need to amplify the gradient directionally \n Grad_in = Img2Grad(img_in);\n Product = Grad_in .* ratio;\n Sqr = Product.^2;\n Sum = sum(Sqr,3);\n Sqrt = sqrt(Sum); %the Sqrt might be 0, because Grad_in may be pure 0;\n r1 = S ./Sqrt;\n r1(isnan(r1)) = 0;\n\n Grad_exp = Grad_high_initial .*( ratio .*(repmat(r1,[1,1,8])));\n %consolidate inconsistatnt gradient\n NewGrad_exp = zeros(h,w,8);\n for k=1:4\n switch k\n case 1\n ShiftOp = [0 -1];\n case 2\n ShiftOp = [1 -1];\n case 3\n ShiftOp = [1 0];\n case 4\n ShiftOp = [1 1];\n end\n k2 =k+4;\n Grad1 = Grad_exp(:,:,k);\n Grad2 = Grad_exp(:,:,k2);\n Grad2Shift = circshift(Grad2,ShiftOp);\n Grad1Abs = abs(Grad1);\n Grad2AbsShift = abs(Grad2Shift);\n Grad1Larger = Grad1Abs > Grad2AbsShift;\n Grad2Larger = Grad2AbsShift > Grad1Abs;\n NewGrad1 = Grad1 .* Grad1Larger + (-Grad2Shift) .* Grad2Larger;\n NewGrad2Shift = Grad2Shift .* Grad2Larger + (-Grad1) .* Grad1Larger;\n NewGrad2 = circshift(NewGrad2Shift,-ShiftOp);\n NewGrad_exp(:,:,k) = NewGrad1;\n NewGrad_exp(:,:,k2) = NewGrad2;\n end\n %current problem is the over-enhanced gradient (NewMagExp too large)\n gradient_expected = NewGrad_exp;\n \n lambda_m = 2;\n m0 = 0;\n ProbMagOut = lambda_m * RidgeMapMagValue + m0;\n\n lambda_d = 0.25;\n d0 = 0.25;\n ProbDistMap = exp(- (lambda_d * DistMap + d0) ); %this coef should be decied by zooming\n\n Product = ProbMagOut .* ProbDistMap;\n weightmap_edge = min(Product,1); %the two terms are not sufficient, direction is not taken into considertion\n \n if 1\n bReport = true;\n updatenumber = 0;\n loopnumber = 1000;\n linesearchstepnumber = 10;\n beta0 = 1;\n beta1 = 0.5^8;\n tolf = 0.001;\n img_edge = F4e_GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,Gau_sigma,bReport,...\n loopnumber,updatenumber,linesearchstepnumber,beta0,beta1,tolf);\n imwrite(img_edge, fullfile(folder_output, 'img_edge.png'));\n \n %Compute the new magitude of gradients\n mog_new = sqrt(sum(NewGrad_exp.^2,3));\n hfig = figure;\n imagesc(mog_new);\n axis image off\n saveas(hfig, fullfile(folder_output,'mog_new.png'));\n range = caxis;\n disp(range);\n %img_edge = F4b_GenerateIntensityFromGradient(img_y,img_in,NewGrad_exp,Gau_sigma,bReport);\n %gradient_actual = Img2Grad(img_edge);\n %compute the Map of edge weight\n end\nend\nfunction Grad = Img2Grad(img)\n [h w] = size(img);\n Grad = zeros(h,w,8);\n DiffOp = RetGradientKernel();\n for i=1:8\n Grad(:,:,i) = imfilter(img,DiffOp{i},'replicate');\n end\nend\nfunction f = RetGradientKernel()\n f = cell(8,1);\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\nend\nfunction Dissimilarity = EvaluateDissimilarity8(Img_in,PatchSize)\n if ~exist('PatchSize','var');\n PatchSize = 3;\n end\n [h w] = size(Img_in);\n Dissimilarity = zeros(h,w,8);\n \n f3x3 = ones(PatchSize)/(PatchSize^2);\n for i = 1:8\n DiffOp = RetGradientKernel8(i);\n Diff = imfilter(Img_in,DiffOp,'symmetric');\n Sqr = Diff.^2;\n Sum = imfilter(Sqr,f3x3,'replicate');\n Dissimilarity(:,:,i) = sqrt(Sum);\n end\nend\nfunction DiffOp = RetGradientKernel8(dir)\n f{1} = [0 0 0;\n 0 -1 1;\n 0 0 0];\n f{2} = [0 0 1;\n 0 -1 0;\n 0 0 0];\n f{3} = [0 1 0;\n 0 -1 0;\n 0 0 0];\n f{4} = [1 0 0;\n 0 -1 0;\n 0 0 0];\n f{5} = [0 0 0;\n 1 -1 0;\n 0 0 0];\n f{6} = [0 0 0;\n 0 -1 0;\n 1 0 0];\n f{7} = [0 0 0;\n 0 -1 0;\n 0 1 0];\n f{8} = [0 0 0;\n 0 -1 0;\n 0 0 1];\n DiffOp = f{dir};\nend\nfunction f = ComputeFunctionValue_Grad(img, Grad_exp)\n Grad = Img2Grad(img);\n Diff = Grad - Grad_exp;\n Sqrt = Diff .^2;\n f = sqrt(sum(Sqrt(:)));\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "im2patches.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Ma10/im2patches.m", "size": 1616, "source_encoding": "utf_8", "md5": "cc1828fb7cc7e88a54b135f8bd1c17a6", "text": "% function to convert an image into patches according to a possible mask\n% note that for now im has to be a grayscale image\nfunction [patches,max_x,max_y] = im2patches(im,patchSize,intervalSize)\n\nif exist('boundarySize','var')~=1\n boundarySize = ceil(patchSize/2);\nend\n% if boundarySize < patchSize\n% error('The boundary size must be equal to or greater than the patch size!');\n% end\n\n% the grid of a patch\n[p_xx,p_yy]=meshgrid(-patchSize/2:patchSize/2-1,-patchSize/2:patchSize/2-1);\nnDim = numel(p_xx);\n\n[height,width]=size(im);\n\n[grid_xx,grid_yy]=meshgrid(boundarySize+1:intervalSize:width-boundarySize+1,boundarySize+1:intervalSize:height-boundarySize+1);\n% [ind_xx,ind_yy]=meshgrid(1:size(grid_xx,2),1:size(grid_xx,1));\nif nargin > 1\n max_x = size(grid_xx,2);\n max_y = size(grid_xx,1);\nend\ngrid_xx = grid_xx(:); grid_yy = grid_yy(:);\n% ind_xx = ind_xx(:); ind_yy = ind_yy(:);\n\n% if exist('mask','var')==1\n% if ~isempty(mask)\n% index = mask(sub2ind([height,width],grid_yy(:),grid_xx(:)))>0.5;\n% grid_xx = grid_xx(index);\n% grid_yy = grid_yy(index);\n% end\n% end\n\nnPatches = numel(grid_xx);\nPatches = struct('x',{},'y',{},'vec',{[]});\nxx = repmat(p_xx(:)',[nPatches,1]) + repmat(grid_xx(:),[1,nDim]);\nyy = repmat(p_yy(:)',[nPatches,1]) + repmat(grid_yy(:),[1,nDim]);\nindex = sub2ind([height,width],yy(:),xx(:));\n\npatches = reshape(im(index),[nPatches,nDim]);\n% for ii = 1:nPatches\n% Patches(ii).x = grid_xx(ii);\n% Patches(ii).y = grid_yy(ii);\n% % Patches(ii).indx = ind_xx(ii);\n% % Patches(ii).indy = ind_yy(ii);\n% Patches(ii).vec = patches(ii,:);\n% end\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F1a_rnd_smp_dictionary.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/F1a_rnd_smp_dictionary.m", "size": 1202, "source_encoding": "utf_8", "md5": "efe29029302db06579a4ca72784e60a1", "text": "%Chih-Yuan Yang\n%10/29/12\n%F1: Change the original file to load '*.png'\n%F1a: according to the ICIP paper of Jianchao, the Xl and Xh are both high-resolution patch\nfunction [Xh, Xl] = F1a_rnd_smp_dictionary(folder_exampleimages, folder_reconstructedimages, patch_size, num_patch)\n\nfpath = fullfile(folder_reconstructedimages, '*.png');\nfilelist = dir(fpath);\nXh = [];\nXl = [];\n\nfilenumber = length(filelist);\n\nnums = zeros(1, filenumber);\n\nfor num = 1:length(filelist),\n img_reconstructed = imread(fullfile(folder_reconstructedimages, filelist(num).name));\n nums(num) = prod(size(img_reconstructed));\nend;\n\nnums = floor(nums*num_patch/sum(nums));\n\nfor ii = 1:filenumber,\n \n patch_num = nums(ii);\n fn_load_recon = filelist(ii).name;\n fn_short = fn_load_recon(1:end-10);\n fn_original = [fn_short '.png'];\n img_reconstructed = im2double(imread(fullfile(folder_reconstructedimages, fn_load_recon)));\n img_original = rgb2gray(im2double(imread(fullfile(folder_exampleimages, fn_original))));\n \n [H, L] = F5_sample_patches(img_reconstructed, img_original, patch_size, patch_num);\n \n Xh = [Xh, H];\n Xl = [Xl, L];\n \n fprintf('Sampled...%d\\n', size(Xh, 2));\nend;\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F2_coupled_dic_train.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/F2_coupled_dic_train.m", "size": 1084, "source_encoding": "utf_8", "md5": "142a3e5792ad61dc4db24ef3a0d90175", "text": "%Chih-Yuan Yang\n%10/19/12\n%reduce the iteration number to reduce the computation time\n%this function needs to be further improved, to pass the temp folder of dictionary to F3_sparse_coding\n%and remove the hard-coded folder in F3_sparse_coding\nfunction [Dh, Dl] = F2_coupled_dic_train(Xh, Xl, codebook_size, lambda, iterationnumber)\n\naddpath('Sparse coding/sc2');\n\nhDim = size(Xh, 1);\nlDim = size(Xl, 1);\n\n% joint learning of the dictionary\nX = [1/sqrt(hDim)*Xh; 1/sqrt(lDim)*Xl];\nif size(X,2) > 80000\n X = X(:, 1:80000);\nend\nXnorm = sqrt(sum(X.^2, 1));\n\nclear Xh Xl;\n\nX = X(:, Xnorm > 1e-5);\nX = X./repmat(sqrt(sum(X.^2, 1)), hDim+lDim, 1);\n\nidx = randperm(size(X, 2));\nBinit = X(:, idx(1:codebook_size));\n %why is this lambda/2?\nfn_save_temp = 'Dictionary_temp';\n[D] = F3_sparse_coding(X, codebook_size, lambda/2, 'L1', [], iterationnumber, 5000, fn_save_temp, [], Binit);\n\nDh = D(1:hDim, :);\nDl = D(hDim+1:end, :);\n\n% normalize the dictionary\nDh = Dh./repmat(sqrt(sum(Dh.^2, 1)), hDim, 1);\nDl = Dl./repmat(sqrt(sum(Dl.^2, 1)), lDim, 1);\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "rnd_smp_dictionary.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/rnd_smp_dictionary.m", "size": 2852, "source_encoding": "utf_8", "md5": "212d5ad367742fb65a07fe925569d9ec", "text": "function [Xh, Xl] = rnd_smp_dictionary(tr_dir, patch_size, zooming, num_patch)\n\nfpath = fullfile(tr_dir, '*.bmp');\nimg_dir = dir(fpath);\nXh = [];\nXl = [];\n\nimg_num = length(img_dir);\n\nnums = zeros(1, img_num);\n\nfor num = 1:length(img_dir),\n im = imread(fullfile(tr_dir, img_dir(num).name));\n nums(num) = prod(size(im));\nend;\n\nnums = floor(nums*num_patch/sum(nums));\n\nfor ii = 1:img_num,\n \n patch_num = nums(ii);\n im = imread(fullfile(tr_dir, img_dir(ii).name));\n \n [H, L] = sample_patches(im, patch_size, zooming, patch_num);\n \n Xh = [Xh, H];\n Xl = [Xl, L];\n \n fprintf('Sampled...%d\\n', size(Xh, 2));\nend;\n\nfunction [HP, LP] = sample_patches(im, patch_size, zooming, patch_num)\n\nlz = 2;\n\nif size(im, 3) == 3,\n hIm = rgb2gray(im);\nelse\n hIm = im;\nend;\n\nif rem(size(hIm,1),zooming)\n nrow = floor(size(hIm,1)/zooming)*zooming;\n hIm = hIm(1:nrow,:);\nend;\nif rem(size(hIm,2),zooming)\n ncol = floor(size(hIm,2)/zooming)*zooming;\n hIm = hIm(:,1:ncol);\nend;\n\nlIm = imresize(hIm,1/zooming);\n[nrow, ncol] = size(lIm);\n\nx = randperm(nrow-patch_size-lz-1);\ny = randperm(ncol-patch_size-lz-1);\n[X,Y] = meshgrid(x,y);\n\nxrow = X(:);\nycol = Y(:);\n\nxrow = xrow(1:patch_num);\nycol = ycol(1:patch_num);\n\n% zoom the original image\nlIm = imresize(lIm, lz,'bicubic');\nhIm = double(hIm);\nlIm = double(lIm);\n\nH = zeros(zooming^2*patch_size^2,patch_num);\nL = zeros(lz^2*4*patch_size^2,patch_num);\n \n% compute the first and second order gradients\nhf1 = [-1,0,1];\nvf1 = [-1,0,1]';\n \nlImG11 = conv2(lIm,hf1,'same');\nlImG12 = conv2(lIm,vf1,'same');\n \nhf2 = [1,0,-2,0,1];\nvf2 = [1,0,-2,0,1]';\n \nlImG21 = conv2(lIm,hf2,'same');\nlImG22 = conv2(lIm,vf2,'same');\n\ncount = 1;\nfor pnum = 1:patch_num,\n \n hrow = (xrow(pnum)-1)*zooming + 1;\n hcol = (ycol(pnum)-1)*zooming + 1;\n Hpatch = hIm(hrow:hrow+zooming*patch_size-1,hcol:hcol+zooming*patch_size-1);\n \n lrow = (xrow(pnum)-1)*lz + 1;\n lcol = (ycol(pnum)-1)*lz + 1;\n \n% fprintf('(%d, %d), %d, [%d, %d]\\n', lrow, lcol, lz*patch_size,\n% size(lImG11));\n Lpatch1 = lImG11(lrow:lrow+lz*patch_size-1,lcol:lcol+lz*patch_size-1);\n Lpatch2 = lImG12(lrow:lrow+lz*patch_size-1,lcol:lcol+lz*patch_size-1);\n Lpatch3 = lImG21(lrow:lrow+lz*patch_size-1,lcol:lcol+lz*patch_size-1);\n Lpatch4 = lImG22(lrow:lrow+lz*patch_size-1,lcol:lcol+lz*patch_size-1);\n \n Lpatch = [Lpatch1(:),Lpatch2(:),Lpatch3(:),Lpatch4(:)];\n Lpatch = Lpatch(:);\n \n HP(:,count) = Hpatch(:)-mean(Hpatch(:));\n LP(:,count) = Lpatch;\n \n count = count + 1;\n \n Hpatch = Hpatch';\n Lpatch1 = Lpatch1';\n Lpatch2 = Lpatch2';\n Lpatch3 = Lpatch3';\n Lpatch4 = Lpatch4';\n Lpatch = [Lpatch1(:),Lpatch2(:),Lpatch3(:),Lpatch4(:)];\n \n HP(:,count) = Hpatch(:)-mean(Hpatch(:));\n LP(:,count) = Lpatch(:);\n count = count + 1;\n \nend;\n\n\n \n "} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F3_L1SR.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/F3_L1SR.m", "size": 4861, "source_encoding": "utf_8", "md5": "f698e5b227c276d06019af58f299e8b5", "text": "%Chih-Yuan yang\n%10/24/12\n%remove a bug where the upsampled image size in not always 3x, but should be controlled by zooming\n%remove a bug where the boundary can not be well filled in Jianchao's original code\n%note: the format of the first argument lIm is double but the range is 0~255\nfunction [hIm, ww] = F3_L1SR(lIm, zooming, patch_size, overlap, Dh, Dl, lambda, regres)\n% Use sparse representation as the prior for image super-resolution\n% Usage\n% [hIm] = L1SR(lIm, zooming, patch_size, overlap, Dh, Dl, lambda)\n% \n% Inputs\n% -lIm: low resolution input image, single channel, e.g.\n% illuminance\n% -zooming: zooming factor, e.g. 3\n% -patch_size: patch size for the low resolution image\n% -overlap: overlap among patches, e.g. 1\n% -Dh: dictionary for the high resolution patches\n% -Dl: dictionary for the low resolution patches\n% -regres: 'L1' use the sparse representation directly to high\n% resolution dictionary;\n% 'L2' use the supports found by sparse representation\n% and apply least square regression coefficients to high\n% resolution dictionary.\n% Ouputs\n% -hIm: the recovered image, single channel\n%\n% Written by Jianchao Yang @ IFP UIUC\n% April, 2009\n% Webpage: http://www.ifp.illinois.edu/~jyang29/\n% For any questions, please email me by jyang29@uiuc.edu\n%\n% Reference\n% Jianchao Yang, John Wright, Thomas Huang and Yi Ma. Image superresolution\n% as sparse representation of raw image patches. IEEE Computer Society\n% Conference on Computer Vision and Pattern Recognition (CVPR), 2008. \n%\n\n[lhg, lwd] = size(lIm);\nhhg = lhg*zooming;\nhwd = lwd*zooming;\n\nmIm = imresize(lIm, 2,'bicubic');\n[mhg, mwd] = size(mIm);\nhpatch_size = patch_size*zooming;\nmpatch_size = patch_size*2;\n\n% extract gradient feature from lIm\nhf1 = [-1,0,1];\nvf1 = [-1,0,1]';\nhf2 = [1,0,-2,0,1];\nvf2 = [1,0,-2,0,1]';\n\nlImG11 = conv2(mIm,hf1,'same');\nlImG12 = conv2(mIm,vf1,'same');\nlImG21 = conv2(mIm,hf2,'same');\nlImG22 = conv2(mIm,vf2,'same');\n\nlImfea(:,:,1) = lImG11;\nlImfea(:,:,2) = lImG12;\nlImfea(:,:,3) = lImG21;\nlImfea(:,:,4) = lImG22;\n\nlgridx = 2:patch_size-overlap:lwd-patch_size;\nlgridx = [lgridx, lwd-patch_size];\nlgridy = 2:patch_size-overlap:lhg-patch_size;\nlgridy = [lgridy, lhg-patch_size];\n\nmgridx = (lgridx - 1)*2 + 1;\nmgridy = (lgridy - 1)*2 + 1;\n\n% using linear programming to find sparse solution\nbhIm = imresize(lIm, zooming, 'bicubic');\nhIm = zeros([hhg, hwd]);\nnrml_mat = zeros([hhg, hwd]);\n\nhgridx = (lgridx-1)*zooming + 1;\nhgridy = (lgridy-1)*zooming + 1;\n\ndisp('Processing the patches sequentially...');\ncount = 0;\n\n% loop to recover each patch\nfor xx = 1:length(mgridx),\n for yy = 1:length(mgridy),\n \n mcolx = mgridx(xx);\n mrowy = mgridy(yy);\n \n count = count + 1;\n if ~mod(count, 100),\n fprintf('.\\n');\n else\n fprintf('.');\n end;\n \n mpatch = mIm(mrowy:mrowy+mpatch_size-1, mcolx:mcolx+mpatch_size-1);\n mmean = mean(mpatch(:));\n \n mpatchfea = lImfea(mrowy:mrowy+mpatch_size-1, mcolx:mcolx+mpatch_size-1, :);\n mpatchfea = mpatchfea(:);\n \n mnorm = sqrt(sum(mpatchfea.^2));\n \n if mnorm > 1,\n y = mpatchfea./mnorm;\n else\n y = mpatchfea;\n end;\n w = SolveLasso(Dl, y, size(Dl, 2), 'nnlasso', [], lambda); \n% w = feature_sign(Dl, y, lambda);\n \n if isempty(w),\n w = zeros(size(Dl, 2), 1);\n end;\n switch regres,\n case 'L1'\n if mnorm > 1,\n hpatch = Dh*w*mnorm;\n else\n hpatch = Dh*w;\n end;\n case 'L2'\n idx = find(w);\n lsups = Dl(:, idx);\n hsups = Dh(:, idx);\n w = inv(lsups'*lsups)*lsups'*mpatchfea;\n hpatch = hsups*w;\n otherwise\n error('Unknown fitting!');\n end;\n \n hpatch = reshape(hpatch, [hpatch_size, hpatch_size]);\n hpatch = hpatch + mmean;\n \n hcolx = hgridx(xx);\n hrowy = hgridy(yy);\n \n hIm(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1)...\n = hIm(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1) + hpatch;\n nrml_mat(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1)...\n = nrml_mat(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1) + 1;\n end;\nend;\n\nfprintf('done!\\n');\n\n% fill the empty\nhIm(1:zooming, :) = bhIm(1:zooming, :);\nhIm(:, 1:zooming) = bhIm(:, 1:zooming);\n\nhIm(end-zooming+1:end, :) = bhIm(end-zooming+1:end, :);\nhIm(:, end-zooming+1:end) = bhIm(:, end-zooming+1:end);\n\nnrml_mat(nrml_mat < 1) = 1;\nhIm = hIm./nrml_mat;\n\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F3a_L1SR.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/F3a_L1SR.m", "size": 7950, "source_encoding": "utf_8", "md5": "c517a83c8a2019640fb35dc497f554b6", "text": "%Chih-Yuan yang\n%10/24/12\n%remove a bug where the upsampled image size in not always 3x, but should be controlled by zooming\n%remove a bug where the boundary can not be well filled in Jianchao's original code\n%note: the format of the first argument lIm is double but the range is 0~255\n%F3a: dymanically change the dictionary so that the overlapped region can be taken into consideration\nfunction [img_hr, ww] = F3a_L1SR(lIm, zooming, patch_size, overlap, Dh, Dl, lambda, regres)\n% Use sparse representation as the prior for image super-resolution\n% Usage\n% [img_hr] = L1SR(lIm, zooming, patch_size, overlap, Dh, Dl, lambda)\n% \n% Inputs\n% -lIm: low resolution input image, single channel, e.g.\n% illuminance\n% -zooming: zooming factor, e.g. 3\n% -patch_size: patch size for the low resolution image\n% -overlap: overlap among patches, e.g. 1\n% -Dh: dictionary for the high resolution patches\n% -Dl: dictionary for the low resolution patches\n% -regres: 'L1' use the sparse representation directly to high\n% resolution dictionary;\n% 'L2' use the supports found by sparse representation\n% and apply least square regression coefficients to high\n% resolution dictionary.\n% Ouputs\n% -img_hr: the recovered image, single channel\n%\n% Written by Jianchao Yang @ IFP UIUC\n% April, 2009\n% Webpage: http://www.ifp.illinois.edu/~jyang29/\n% For any questions, please email me by jyang29@uiuc.edu\n%\n% Reference\n% Jianchao Yang, John Wright, Thomas Huang and Yi Ma. Image superresolution\n% as sparse representation of raw image patches. IEEE Computer Society\n% Conference on Computer Vision and Pattern Recognition (CVPR), 2008. \n%\n\n[lhg, lwd] = size(lIm);\nhhg = lhg*zooming;\nhwd = lwd*zooming;\n\nmIm = imresize(lIm, 2,'bicubic');\n[mhg, mwd] = size(mIm);\npatchsize_hr = patch_size*zooming;\npatcharea_hr = patchsize_hr^2;\nmpatch_size = patch_size*2;\n\n% extract gradient feature from lIm\nhf1 = [-1,0,1];\nvf1 = [-1,0,1]';\nhf2 = [1,0,-2,0,1];\nvf2 = [1,0,-2,0,1]';\n\nlImG11 = conv2(mIm,hf1,'same');\nlImG12 = conv2(mIm,vf1,'same');\nlImG21 = conv2(mIm,hf2,'same');\nlImG22 = conv2(mIm,vf2,'same');\n\nlImfea(:,:,1) = lImG11;\nlImfea(:,:,2) = lImG12;\nlImfea(:,:,3) = lImG21;\nlImfea(:,:,4) = lImG22;\n\n%it is very wierd why the index start from 2, change it to one\nlgridx = 1:patch_size-overlap:lwd-patch_size+1;\nif lgridx(end) ~= lwd-patch_size+1\n lgridx = [lgridx, lwd-patch_size+1]; %fill the last one\nend\nlgridy = 1:patch_size-overlap:lhg-patch_size+1;\nif lgridy(end) ~= lhg-patch_size+1\n lgridy = [lgridy, lhg-patch_size+1];\nend\n\n%the index of extract features from middle resolution\nmgridx = (lgridx - 1)*2 + 1; %the horizonal sample coordinate of the x2 interpolated image\nmgridy = (lgridy - 1)*2 + 1; %the vertical\n\n% using linear programming to find sparse solution\nbimg_hr = imresize(lIm, zooming, 'bicubic');\nimg_hr = zeros([hhg, hwd]);\n%nrml_mat = zeros([hhg, hwd]);\nh_hr = hhg;\nw_hr = hwd;\nfilledmap = false(h_hr,w_hr);\nreconfeature = zeros(h_hr,w_hr);\nnrml_mat = zeros(h_hr,w_hr);\n\nhgridx = (lgridx-1)*zooming + 1; %the destination in HR\nhgridy = (lgridy-1)*zooming + 1;\n\ndisp('Processing the patches sequentially...');\ncount = 0;\n\n% loop to recover each patch\nfor cidx = 1:length(mgridx) %cidx is the index of array, not the coordinate\n for ridx = 1:length(mgridy)\n \n %the index in LR is disregarded because it is irrelevant to feature extraction\n c_mr = mgridx(cidx); %cidx is the coordinate of the index in middle resolution\n r_mr = mgridy(ridx);\n \n c_hr = hgridx(cidx);\n r_hr = hgridy(ridx);\n \n count = count + 1;\n if ~mod(count, 100),\n fprintf('.\\n');\n else\n fprintf('.');\n end;\n \n %mpatch_size: the patchsize * 2\n mpatch = mIm(r_mr:r_mr+mpatch_size-1, c_mr:c_mr+mpatch_size-1); %mIm: the middle image, \n mmean = mean(mpatch(:));\n \n %here, the feature changes, not only the gradient, but also the filled HR intensity, too,\n mpatchfea = lImfea(r_mr:r_mr+mpatch_size-1, c_mr:c_mr+mpatch_size-1, :);\n mpatchfea = mpatchfea(:);\n \n %consider the overlapped region\n processregion_hr = zeros(h_hr,w_hr);\n processregion_hr(r_hr:r_hr+patchsize_hr-1,c_hr:c_hr+patchsize_hr-1) = 1;\n overlapregion_hr = filledmap .* processregion_hr;\n overlapregion_inpatch = overlapregion_hr(r_hr:r_hr+patchsize_hr-1,c_hr:c_hr+patchsize_hr-1);\n overlapregion_hr_logical = logical(overlapregion_hr);\n %extract the intensity of filled hr\n if nnz(overlapregion_hr) == 0\n overlapreconfeature = [];\n Dh_partial = [];\n else\n overlapreconfeature = reconfeature(overlapregion_hr_logical); %reshape already\n usedpixels = reshape(overlapregion_inpatch,[patcharea_hr,1]);\n Dh_partial = Dh(logical(usedpixels),:);\n end\n \n %create the new y, new Dl, and new Dh, assuming beta is 1, the same as described in paper\n y_concatenated = cat(1,mpatchfea,overlapreconfeature);\n D_concatenated = cat(1,Dl,Dh_partial);\n thenorm = sqrt(sum(y_concatenated.^2));\n if thenorm > 1,\n y_input = y_concatenated./thenorm;\n else\n y_input = y_concatenated;\n end;\n w = SolveLasso(D_concatenated, y_input, size(D_concatenated, 2), 'nnlasso', [], lambda);\n\n if isempty(w),\n w = zeros(size(Dl, 2), 1);\n end;\n\n if thenorm > 1,\n reconfeature_hr_concatenated = Dh*w*thenorm;\n else\n reconfeature_hr_concatenated = Dh*w; %this is the reconstructed\n end\n reconfeature_hr = reconfeature_hr_concatenated(1:patcharea_hr);\n \n %mnorm = sqrt(sum(mpatchfea.^2));\n \n %the extracted feature, which is also dynamically change\n %if mnorm > 1,\n % y = mpatchfea./mnorm;\n %else\n % y = mpatchfea;\n %end;\n %here, the Dl and the corresponding Dh will be dymanically change\n %w = SolveLasso(Dl, y, size(Dl, 2), 'nnlasso', [], lambda); \n% w = feature_sign(Dl, y, lambda);\n \n %if isempty(w),\n %\n %w = zeros(size(Dl, 2), 1);\n %end;\n %switch regres,\n % case 'L1'\n % if mnorm > 1,\n % reconfeature_hr = Dh*w*mnorm;\n % else\n % reconfeature_hr = Dh*w; %this is the reconstructed\n % end;\n % case 'L2'\n % idx = find(w);\n % lsups = Dl(:, idx);\n % hsups = Dh(:, idx);\n % w = inv(lsups'*lsups)*lsups'*mpatchfea;\n % reconfeature_hr = hsups*w;\n % otherwise\n % error('Unknown fitting!');\n %end;\n \n patchdiff_hr = reshape(reconfeature_hr, [patchsize_hr, patchsize_hr]);\n reconfeature(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1) = patchdiff_hr;\n reconintensity_hr = patchdiff_hr + mmean;\n \n img_hr(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1)...\n = img_hr(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1) + reconintensity_hr;\n nrml_mat(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1)...\n = nrml_mat(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1) + 1;\n filledmap(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1) = 1;\n \n end\nend\n\nfprintf('done!\\n');\n\n% fill the empty\n%img_hr(1:zooming, :) = bimg_hr(1:zooming, :);\n%img_hr(:, 1:zooming) = bimg_hr(:, 1:zooming);\n\n%img_hr(end-zooming+1:end, :) = bimg_hr(end-zooming+1:end, :);\n%img_hr(:, end-zooming+1:end) = bimg_hr(:, end-zooming+1:end);\n\nnrml_mat(nrml_mat < 1) = 1;\nimg_hr = img_hr./nrml_mat;\n\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F4_OptimizationTerm.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/F4_OptimizationTerm.m", "size": 857, "source_encoding": "utf_8", "md5": "15d8711641b99d84c55235c45fb90590", "text": "%Chih-Yuan Yang\n%10/29/12\n%solve the optimization problem\nfunction termvalue = F4_OptimizationTerm(c, basisW,img_y,sigma)\n [h_lr, w_lr] = size(img_y);\n vector_hr = basisW * c;\n zooming = round(sqrt(size(vector_hr,1)/(h_lr* w_lr)));\n h_hr = h_lr * zooming;\n w_hr = w_lr * zooming;\n img_hr = reshape(vector_hr,[h_hr,w_hr]);\n img_downsample = F19a_GenerateLRImage_GaussianKernel(img_hr,zooming,sigma);\n diff = img_downsample - img_y;\n term1 = sum(sum(diff.^2));\n %what is the high pass filter? the difference of two Gaussian function?\n kernel1 = fspecial('gaussian',11,1.6);\n kernel2 = fspecial('gaussian',11,1.2);\n img_Gau1 = imfilter(img_hr,kernel1,'replicate');\n img_Gau2 = imfilter(img_hr,kernel2,'replicate');\n diff = img_Gau1 - img_Gau2;\n term2 = sqrt(sum(sum(diff.^2)));\n termvalue = term1 + term2;\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F3b_L1SR.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/F3b_L1SR.m", "size": 7366, "source_encoding": "utf_8", "md5": "1e041e1c5630403bb833d728f9d3828b", "text": "%Chih-Yuan yang\n%10/24/12\n%remove a bug where the upsampled image size in not always 3x, but should be controlled by zooming\n%remove a bug where the boundary can not be well filled in Jianchao's original code\n%note: the format of the first argument lIm is double but the range is 0~255\n%F3a: dymanically change the dictionary so that the overlapped region can be taken into consideration\n%F3b: Jianchao does not mention how to handle the overlap, the average look \nfunction [img_hr, ww] = F3b_L1SR(lIm, zooming, patch_size, overlap, Dh, Dl, lambda, regres)\n% Use sparse representation as the prior for image super-resolution\n% Usage\n% [img_hr] = L1SR(lIm, zooming, patch_size, overlap, Dh, Dl, lambda)\n% \n% Inputs\n% -lIm: low resolution input image, single channel, e.g.\n% illuminance\n% -zooming: zooming factor, e.g. 3\n% -patch_size: patch size for the low resolution image\n% -overlap: overlap among patches, e.g. 1\n% -Dh: dictionary for the high resolution patches\n% -Dl: dictionary for the low resolution patches\n% -regres: 'L1' use the sparse representation directly to high\n% resolution dictionary;\n% 'L2' use the supports found by sparse representation\n% and apply least square regression coefficients to high\n% resolution dictionary.\n% Ouputs\n% -img_hr: the recovered image, single channel\n%\n% Written by Jianchao Yang @ IFP UIUC\n% April, 2009\n% Webpage: http://www.ifp.illinois.edu/~jyang29/\n% For any questions, please email me by jyang29@uiuc.edu\n%\n% Reference\n% Jianchao Yang, John Wright, Thomas Huang and Yi Ma. Image superresolution\n% as sparse representation of raw image patches. IEEE Computer Society\n% Conference on Computer Vision and Pattern Recognition (CVPR), 2008. \n%\n\n[lhg, lwd] = size(lIm);\nhhg = lhg*zooming;\nhwd = lwd*zooming;\n\nmIm = imresize(lIm, 2,'bicubic');\n[mhg, mwd] = size(mIm);\npatchsize_hr = patch_size*zooming;\npatcharea_hr = patchsize_hr^2;\nmpatch_size = patch_size*2;\n\n% extract gradient feature from lIm\nhf1 = [-1,0,1];\nvf1 = [-1,0,1]';\nhf2 = [1,0,-2,0,1];\nvf2 = [1,0,-2,0,1]';\n\nlImG11 = conv2(mIm,hf1,'same');\nlImG12 = conv2(mIm,vf1,'same');\nlImG21 = conv2(mIm,hf2,'same');\nlImG22 = conv2(mIm,vf2,'same');\n\nlImfea(:,:,1) = lImG11;\nlImfea(:,:,2) = lImG12;\nlImfea(:,:,3) = lImG21;\nlImfea(:,:,4) = lImG22;\n\n%it is very wierd why the index start from 2, change it to one\nlgridx = 1:patch_size-overlap:lwd-patch_size+1;\nif lgridx(end) ~= lwd-patch_size+1\n lgridx = [lgridx, lwd-patch_size+1]; %fill the last one\nend\nlgridy = 1:patch_size-overlap:lhg-patch_size+1;\nif lgridy(end) ~= lhg-patch_size+1\n lgridy = [lgridy, lhg-patch_size+1];\nend\n\n%the index of extract features from middle resolution\nmgridx = (lgridx - 1)*2 + 1; %the horizonal sample coordinate of the x2 interpolated image\nmgridy = (lgridy - 1)*2 + 1; %the vertical\n\n% using linear programming to find sparse solution\nbimg_hr = imresize(lIm, zooming, 'bicubic');\nimg_hr = zeros([hhg, hwd]);\n%nrml_mat = zeros([hhg, hwd]);\nh_hr = hhg;\nw_hr = hwd;\nfilledmap = false(h_hr,w_hr);\nreconfeature = zeros(h_hr,w_hr);\nnrml_mat = zeros(h_hr,w_hr);\n\nhgridx = (lgridx-1)*zooming + 1; %the destination in HR\nhgridy = (lgridy-1)*zooming + 1;\n\ndisp('Processing the patches sequentially...');\ncount = 0;\n\n% loop to recover each patch\nfor cidx = 1:length(mgridx) %cidx is the index of array, not the coordinate\n for ridx = 1:length(mgridy)\n \n %the index in LR is disregarded because it is irrelevant to feature extraction\n c_mr = mgridx(cidx); %cidx is the coordinate of the index in middle resolution\n r_mr = mgridy(ridx);\n \n c_hr = hgridx(cidx);\n r_hr = hgridy(ridx);\n \n count = count + 1;\n if ~mod(count, 100),\n fprintf('.\\n');\n else\n fprintf('.');\n end;\n \n %mpatch_size: the patchsize * 2\n mpatch = mIm(r_mr:r_mr+mpatch_size-1, c_mr:c_mr+mpatch_size-1); %mIm: the middle image, \n mmean = mean(mpatch(:));\n \n %here, the feature changes, not only the gradient, but also the filled HR intensity, too,\n mpatchfea = lImfea(r_mr:r_mr+mpatch_size-1, c_mr:c_mr+mpatch_size-1, :);\n mpatchfea = mpatchfea(:);\n \n %consider the overlapped region\n processregion_image = false(h_hr,w_hr);\n processregion_image(r_hr:r_hr+patchsize_hr-1,c_hr:c_hr+patchsize_hr-1) = true;\n overlapregion_image = filledmap & processregion_image;\n nonoverlapregion_image = processregion_image & ~overlapregion_image;\n overlapregion_patch = overlapregion_image(r_hr:r_hr+patchsize_hr-1,c_hr:c_hr+patchsize_hr-1);\n overlapregion_itensity = img_hr(r_hr:r_hr+patchsize_hr-1,c_hr:c_hr+patchsize_hr-1);\n expectedfeature_patch = overlapregion_itensity - mmean;\n expectedfeature_overlap_linearize = expectedfeature_patch(overlapregion_patch);\n nonoverlapregion_patch = true(patchsize_hr) & ~overlapregion_patch;\n %extract the intensity of filled hr\n if nnz(overlapregion_image) == 0\n overlapreconfeature = [];\n Dh_partial = [];\n else\n overlapreconfeature = expectedfeature_overlap_linearize;\n usedpixels = reshape(overlapregion_patch,[patcharea_hr,1]);\n Dh_partial = Dh(usedpixels,:);\n end\n \n %create the new y, new Dl, and new Dh, assuming beta is 1, the same as described in paper\n y_concatenated = cat(1,mpatchfea,overlapreconfeature);\n Dl_concatenated = cat(1,Dl,Dh_partial);\n Dh_concatenated = cat(1,Dh,Dh_partial);\n %norm_y = sqrt(sum(mpatchfea.^2));\n norm_concatenated = sqrt(sum(y_concatenated.^2));\n if norm_concatenated > 1,\n y_input = y_concatenated./norm_concatenated;\n else\n y_input = y_concatenated;\n end;\n w = SolveLasso(Dl_concatenated, y_input, size(Dl_concatenated, 2), 'lasso', [], lambda);\n\n if isempty(w),\n w = zeros(size(Dl, 2), 1);\n end;\n\n if norm_concatenated > 1,\n reconfeature_hr_concatenated = Dh_concatenated*w*norm_concatenated;\n else\n reconfeature_hr_concatenated = Dh*w; %this is the reconstructed\n end\n reconfeature_hr = reconfeature_hr_concatenated(1:patcharea_hr);\n \n patchdiff_hr = reshape(reconfeature_hr, [patchsize_hr, patchsize_hr]);\n reconfeature(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1) = patchdiff_hr;\n reconintensity_hr = patchdiff_hr + mmean;\n \n %try not overlap\n %img_hr(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1)...\n % = img_hr(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1) + reconintensity_hr;\n img_hr(nonoverlapregion_image) = reconintensity_hr(nonoverlapregion_patch);\n nrml_mat(nonoverlapregion_image) = nrml_mat(nonoverlapregion_image) + 1;\n %nrml_mat(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1)...\n % = nrml_mat(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1) + 1;\n filledmap(r_hr:r_hr+patchsize_hr-1, c_hr:c_hr+patchsize_hr-1) = 1;\n \n end\nend\n\nfprintf('done!\\n');\n\nnrml_mat(nrml_mat < 1) = 1;\nimg_hr = img_hr./nrml_mat;\n\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F5_sample_patches.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/F5_sample_patches.m", "size": 1400, "source_encoding": "utf_8", "md5": "4eb7f1f373a3a48d367c73424626b0bb", "text": "%Chih-Yuan Yang\n%10/29/12\n%Export this function form F1a_rnd_smp_dictionary\nfunction [HP, LP] = F5_sample_patches(img_reconstructed, img_original, patchsize, patch_num)\n\n[nrow, ncol] = size(img_reconstructed);\n\nx = randperm(nrow-patchsize+1);\ny = randperm(ncol-patchsize+1);\n[X,Y] = meshgrid(x,y);\n\nxrow = X(:);\nycol = Y(:);\n\nxrow = xrow(1:patch_num);\nycol = ycol(1:patch_num);\n\n% compute the first and second order gradients\nhf1 = [-1,0,1];\nvf1 = [-1,0,1]';\n \ngrad1 = conv2(img_reconstructed,hf1,'same');\ngrad2 = conv2(img_reconstructed,vf1,'same');\n \nhf2 = [1,0,-2,0,1];\nvf2 = [1,0,-2,0,1]';\n \ngrad3 = conv2(img_reconstructed,hf2,'same');\ngrad4 = conv2(img_reconstructed,vf2,'same');\n\nfeaturelength_hr = patchsize^2;\nfeaturelength_lr = 4*patchsize^2;\nHP = zeros(featurelength_hr,patch_num);\nLP = zeros(featurelength_lr,patch_num);\nfor idx = 1:patch_num,\n \n hrow = xrow(idx);\n hcol = ycol(idx);\n Hpatch = img_original(hrow:hrow+patchsize-1,hcol:hcol+patchsize-1);\n \n Lpatch1 = grad1(hrow:hrow+patchsize-1,hcol:hcol+patchsize-1);\n Lpatch2 = grad2(hrow:hrow+patchsize-1,hcol:hcol+patchsize-1);\n Lpatch3 = grad3(hrow:hrow+patchsize-1,hcol:hcol+patchsize-1);\n Lpatch4 = grad4(hrow:hrow+patchsize-1,hcol:hcol+patchsize-1);\n \n Lpatch = [Lpatch1(:);Lpatch2(:);Lpatch3(:);Lpatch4(:)];\n \n HP(:,idx) = Hpatch(:)-mean(Hpatch(:));\n LP(:,idx) = Lpatch;\nend\n\n\n \n "} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F1_rnd_smp_dictionary.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/F1_rnd_smp_dictionary.m", "size": 2927, "source_encoding": "utf_8", "md5": "eb2f78ed0c406dcc46fb5cc253b0b1ef", "text": "%Chih-Yuan Yang\n%10/17/12\n%F1: Change the original file to load '*.png'\nfunction [Xh, Xl] = F1_rnd_smp_dictionary(tr_dir, patch_size, zooming, num_patch)\n\nfpath = fullfile(tr_dir, '*.png');\nimg_dir = dir(fpath);\nXh = [];\nXl = [];\n\nimg_num = length(img_dir);\n\nnums = zeros(1, img_num);\n\nfor num = 1:length(img_dir),\n im = imread(fullfile(tr_dir, img_dir(num).name));\n nums(num) = prod(size(im));\nend;\n\nnums = floor(nums*num_patch/sum(nums));\n\nfor ii = 1:img_num,\n \n patch_num = nums(ii);\n im = imread(fullfile(tr_dir, img_dir(ii).name));\n \n [H, L] = sample_patches(im, patch_size, zooming, patch_num);\n \n Xh = [Xh, H];\n Xl = [Xl, L];\n \n fprintf('Sampled...%d\\n', size(Xh, 2));\nend;\n\nfunction [HP, LP] = sample_patches(im, patch_size, zooming, patch_num)\n\nlz = 2;\n\nif size(im, 3) == 3,\n hIm = rgb2gray(im);\nelse\n hIm = im;\nend;\n\nif rem(size(hIm,1),zooming)\n nrow = floor(size(hIm,1)/zooming)*zooming;\n hIm = hIm(1:nrow,:);\nend;\nif rem(size(hIm,2),zooming)\n ncol = floor(size(hIm,2)/zooming)*zooming;\n hIm = hIm(:,1:ncol);\nend;\n\nlIm = imresize(hIm,1/zooming);\n[nrow, ncol] = size(lIm);\n\nx = randperm(nrow-patch_size-lz-1);\ny = randperm(ncol-patch_size-lz-1);\n[X,Y] = meshgrid(x,y);\n\nxrow = X(:);\nycol = Y(:);\n\nxrow = xrow(1:patch_num);\nycol = ycol(1:patch_num);\n\n% zoom the original image\nlIm = imresize(lIm, lz,'bicubic');\nhIm = double(hIm);\nlIm = double(lIm);\n\nH = zeros(zooming^2*patch_size^2,patch_num);\nL = zeros(lz^2*4*patch_size^2,patch_num);\n \n% compute the first and second order gradients\nhf1 = [-1,0,1];\nvf1 = [-1,0,1]';\n \nlImG11 = conv2(lIm,hf1,'same');\nlImG12 = conv2(lIm,vf1,'same');\n \nhf2 = [1,0,-2,0,1];\nvf2 = [1,0,-2,0,1]';\n \nlImG21 = conv2(lIm,hf2,'same');\nlImG22 = conv2(lIm,vf2,'same');\n\ncount = 1;\nfor pnum = 1:patch_num,\n \n hrow = (xrow(pnum)-1)*zooming + 1;\n hcol = (ycol(pnum)-1)*zooming + 1;\n Hpatch = hIm(hrow:hrow+zooming*patch_size-1,hcol:hcol+zooming*patch_size-1);\n \n lrow = (xrow(pnum)-1)*lz + 1;\n lcol = (ycol(pnum)-1)*lz + 1;\n \n% fprintf('(%d, %d), %d, [%d, %d]\\n', lrow, lcol, lz*patch_size,\n% size(lImG11));\n Lpatch1 = lImG11(lrow:lrow+lz*patch_size-1,lcol:lcol+lz*patch_size-1);\n Lpatch2 = lImG12(lrow:lrow+lz*patch_size-1,lcol:lcol+lz*patch_size-1);\n Lpatch3 = lImG21(lrow:lrow+lz*patch_size-1,lcol:lcol+lz*patch_size-1);\n Lpatch4 = lImG22(lrow:lrow+lz*patch_size-1,lcol:lcol+lz*patch_size-1);\n \n Lpatch = [Lpatch1(:),Lpatch2(:),Lpatch3(:),Lpatch4(:)];\n Lpatch = Lpatch(:);\n \n HP(:,count) = Hpatch(:)-mean(Hpatch(:));\n LP(:,count) = Lpatch;\n \n count = count + 1;\n \n Hpatch = Hpatch';\n Lpatch1 = Lpatch1';\n Lpatch2 = Lpatch2';\n Lpatch3 = Lpatch3';\n Lpatch4 = Lpatch4';\n Lpatch = [Lpatch1(:),Lpatch2(:),Lpatch3(:),Lpatch4(:)];\n \n HP(:,count) = Hpatch(:)-mean(Hpatch(:));\n LP(:,count) = Lpatch(:);\n count = count + 1;\n \nend;\n\n\n \n "} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "L1SR.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/L1SR.m", "size": 4642, "source_encoding": "utf_8", "md5": "6a6cc4d000b3a0e623ebe08066cce5ad", "text": "%Chih-Yuan yang\n%10/22/12\n%remove a bug where the upsampled image size in not always 3x, but should be controlled by zooming\nfunction [hIm, ww] = L1SR(lIm, zooming, patch_size, overlap, Dh, Dl, lambda, regres)\n% Use sparse representation as the prior for image super-resolution\n% Usage\n% [hIm] = L1SR(lIm, zooming, patch_size, overlap, Dh, Dl, lambda)\n% \n% Inputs\n% -lIm: low resolution input image, single channel, e.g.\n% illuminance\n% -zooming: zooming factor, e.g. 3\n% -patch_size: patch size for the low resolution image\n% -overlap: overlap among patches, e.g. 1\n% -Dh: dictionary for the high resolution patches\n% -Dl: dictionary for the low resolution patches\n% -regres: 'L1' use the sparse representation directly to high\n% resolution dictionary;\n% 'L2' use the supports found by sparse representation\n% and apply least square regression coefficients to high\n% resolution dictionary.\n% Ouputs\n% -hIm: the recovered image, single channel\n%\n% Written by Jianchao Yang @ IFP UIUC\n% April, 2009\n% Webpage: http://www.ifp.illinois.edu/~jyang29/\n% For any questions, please email me by jyang29@uiuc.edu\n%\n% Reference\n% Jianchao Yang, John Wright, Thomas Huang and Yi Ma. Image superresolution\n% as sparse representation of raw image patches. IEEE Computer Society\n% Conference on Computer Vision and Pattern Recognition (CVPR), 2008. \n%\n\n[lhg, lwd] = size(lIm);\nhhg = lhg*zooming;\nhwd = lwd*zooming;\n\nmIm = imresize(lIm, 2,'bicubic');\n[mhg, mwd] = size(mIm);\nhpatch_size = patch_size*zooming;\nmpatch_size = patch_size*2;\n\n% extract gradient feature from lIm\nhf1 = [-1,0,1];\nvf1 = [-1,0,1]';\nhf2 = [1,0,-2,0,1];\nvf2 = [1,0,-2,0,1]';\n\nlImG11 = conv2(mIm,hf1,'same');\nlImG12 = conv2(mIm,vf1,'same');\nlImG21 = conv2(mIm,hf2,'same');\nlImG22 = conv2(mIm,vf2,'same');\n\nlImfea(:,:,1) = lImG11;\nlImfea(:,:,2) = lImG12;\nlImfea(:,:,3) = lImG21;\nlImfea(:,:,4) = lImG22;\n\nlgridx = 2:patch_size-overlap:lwd-patch_size;\nlgridx = [lgridx, lwd-patch_size];\nlgridy = 2:patch_size-overlap:lhg-patch_size;\nlgridy = [lgridy, lhg-patch_size];\n\nmgridx = (lgridx - 1)*2 + 1;\nmgridy = (lgridy - 1)*2 + 1;\n\n% using linear programming to find sparse solution\nbhIm = imresize(lIm, zooming, 'bicubic');\nhIm = zeros([hhg, hwd]);\nnrml_mat = zeros([hhg, hwd]);\n\nhgridx = (lgridx-1)*zooming + 1;\nhgridy = (lgridy-1)*zooming + 1;\n\ndisp('Processing the patches sequentially...');\ncount = 0;\n\n% loop to recover each patch\nfor xx = 1:length(mgridx),\n for yy = 1:length(mgridy),\n \n mcolx = mgridx(xx);\n mrowy = mgridy(yy);\n \n count = count + 1;\n if ~mod(count, 100),\n fprintf('.\\n');\n else\n fprintf('.');\n end;\n \n mpatch = mIm(mrowy:mrowy+mpatch_size-1, mcolx:mcolx+mpatch_size-1);\n mmean = mean(mpatch(:));\n \n mpatchfea = lImfea(mrowy:mrowy+mpatch_size-1, mcolx:mcolx+mpatch_size-1, :);\n mpatchfea = mpatchfea(:);\n \n mnorm = sqrt(sum(mpatchfea.^2));\n \n if mnorm > 1,\n y = mpatchfea./mnorm;\n else\n y = mpatchfea;\n end;\n \n w = SolveLasso(Dl, y, size(Dl, 2), 'nnlasso', [], lambda);\n% w = feature_sign(Dl, y, lambda);\n \n if isempty(w),\n w = zeros(size(Dl, 2), 1);\n end;\n switch regres,\n case 'L1'\n if mnorm > 1,\n hpatch = Dh*w*mnorm;\n else\n hpatch = Dh*w;\n end;\n case 'L2'\n idx = find(w);\n lsups = Dl(:, idx);\n hsups = Dh(:, idx);\n w = inv(lsups'*lsups)*lsups'*mpatchfea;\n hpatch = hsups*w;\n otherwise\n error('Unknown fitting!');\n end;\n \n hpatch = reshape(hpatch, [hpatch_size, hpatch_size]);\n hpatch = hpatch + mmean;\n \n hcolx = hgridx(xx);\n hrowy = hgridy(yy);\n \n hIm(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1)...\n = hIm(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1) + hpatch;\n nrml_mat(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1)...\n = nrml_mat(hrowy:hrowy+hpatch_size-1, hcolx:hcolx+hpatch_size-1) + 1;\n end;\nend;\n\nfprintf('done!\\n');\n\n% fill the empty\nhIm(1:3, :) = bhIm(1:3, :);\nhIm(:, 1:3) = bhIm(:, 1:3);\n\nhIm(end-2:end, :) = bhIm(end-2:end, :);\nhIm(:, end-2:end) = bhIm(:, end-2:end);\n\nnrml_mat(nrml_mat < 1) = 1;\nhIm = hIm./nrml_mat;\n\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F3c_L1SR_HRHR_Dictionary.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Jianchao08/F3c_L1SR_HRHR_Dictionary.m", "size": 5822, "source_encoding": "utf_8", "md5": "a24f9782d6dab41b0c2b7d6e052d10cd", "text": "%Chih-Yuan yang\n%10/24/12\n%remove a bug where the upsampled image size in not always 3x, but should be controlled by zooming\n%remove a bug where the boundary can not be well filled in Jianchao's original code\n%note: the format of the first argument img_recon is double but the range is 0~255\n%F3a: dymanically change the dictionary so that the overlapped region can be taken into consideration\n%F3b: Jianchao does not mention how to handle the overlap, the average look \n%F3c: The new dictioanry maps HR patch to HR patch, so the code in the file changes, too.\nfunction img_hr = F3c_L1SR_HRHR_Dictionary(img_recon, patchsize, overlap, Dh, Dl, lambda, regres)\n% Use sparse representation as the prior for image super-resolution\n% Usage\n% [img_hr] = L1SR(img_recon, zooming, patchsize, overlap, Dh, Dl, lambda)\n% \n% Inputs\n% -img_recon: low resolution input image, single channel, e.g.\n% illuminance\n% -zooming: zooming factor, e.g. 3\n% -patchsize: patch size for the low resolution image\n% -overlap: overlap among patches, e.g. 1\n% -Dh: dictionary for the high resolution patches\n% -Dl: dictionary for the low resolution patches\n% -regres: 'L1' use the sparse representation directly to high\n% resolution dictionary;\n% 'L2' use the supports found by sparse representation\n% and apply least square regression coefficients to high\n% resolution dictionary.\n% Ouputs\n% -img_hr: the recovered image, single channel\n%\n% Written by Jianchao Yang @ IFP UIUC\n% April, 2009\n% Webpage: http://www.ifp.illinois.edu/~jyang29/\n% For any questions, please email me by jyang29@uiuc.edu\n%\n% Reference\n% Jianchao Yang, John Wright, Thomas Huang and Yi Ma. Image superresolution\n% as sparse representation of raw image patches. IEEE Computer Society\n% Conference on Computer Vision and Pattern Recognition (CVPR), 2008. \n%\npatcharea = patchsize^2;\n[h_hr, w_hr] = size(img_recon);\n\nhf1 = [-1,0,1];\nvf1 = [-1,0,1]';\nhf2 = [1,0,-2,0,1];\nvf2 = [1,0,-2,0,1]';\n\ngrad1 = imfilter(img_recon,hf1,'conv','same','replicate');\ngrad2 = imfilter(img_recon,vf1,'conv','same','replicate');\ngrad3 = imfilter(img_recon,hf2,'conv','same','replicate');\ngrad4 = imfilter(img_recon,vf2,'conv','same','replicate');\n\ngradall(:,:,1) = grad1;\ngradall(:,:,2) = grad2;\ngradall(:,:,3) = grad3;\ngradall(:,:,4) = grad4;\n\ngridx = 1:patchsize-overlap:w_hr-patchsize+1;\nif gridx(end) ~= w_hr-patchsize+1\n gridx = [gridx, w_hr-patchsize+1]; %fill the last one\nend\ngridy = 1:patchsize-overlap:h_hr-patchsize+1;\nif gridy(end) ~= h_hr-patchsize+1\n gridy = [gridy, h_hr-patchsize+1];\nend\n\nimg_hr = zeros([h_hr, w_hr]);\nfilledmap = false(h_hr,w_hr);\nreconfeature = zeros(h_hr,w_hr);\n\n%the boundary \nfor cidx = 1:length(gridx) %cidx is the index of array, not the coordinate\n sprintf('cidx = %d out of %d\\n',cidx, length(gridx));\n for ridx = 1:length(gridy)\n \n c = gridx(cidx);\n c1 = c + patchsize-1;\n r = gridy(ridx);\n r1 = r+ patchsize-1;\n \n %mpatch_size: the patchsize * 2\n patch_intensity = img_recon(r:r1, c:c1); %mIm: the middle image, \n patch_intensity_mean = mean2(patch_intensity);\n \n %here, the feature changes, not only the gradient, but also the filled HR intensity, too,\n patch_feature = gradall(r:r1, c:c1, :);\n vector_feature = patch_feature(:);\n \n %consider the overlapped region\n processregion_image = false(h_hr,w_hr);\n processregion_image(r:r1,c:c1) = true;\n overlapregion_image = filledmap & processregion_image;\n nonoverlapregion_image = processregion_image & ~overlapregion_image;\n overlapregion_patch = overlapregion_image(r:r1,c:c1);\n overlapregion_itensity = img_hr(r:r1,c:c1);\n expectedfeature_patch = overlapregion_itensity - patch_intensity_mean;\n expectedfeature_overlap_linearize = expectedfeature_patch(overlapregion_patch);\n nonoverlapregion_patch = true(patchsize) & ~overlapregion_patch;\n %extract the intensity of filled hr\n if nnz(overlapregion_image) == 0\n overlapreconfeature = [];\n Dh_partial = [];\n else\n overlapreconfeature = expectedfeature_overlap_linearize;\n usedpixels = reshape(overlapregion_patch,[patcharea,1]);\n Dh_partial = Dh(usedpixels,:);\n end\n \n %create the new y, new Dl, and new Dh, assuming beta is 1, the same as described in paper\n y_concatenated = cat(1,vector_feature,overlapreconfeature);\n Dl_concatenated = cat(1,Dl,Dh_partial);\n Dh_concatenated = cat(1,Dh,Dh_partial);\n %norm_y = sqrt(sum(mpatchfea.^2));\n norm_concatenated = sqrt(sum(y_concatenated.^2));\n if norm_concatenated > 1,\n y_input = y_concatenated./norm_concatenated;\n else\n y_input = y_concatenated;\n end;\n w = SolveLasso(Dl_concatenated, y_input, size(Dl_concatenated, 2), 'lasso', [], lambda);\n\n if isempty(w),\n w = zeros(size(Dl, 2), 1);\n end\n\n if norm_concatenated > 1,\n reconfeature_hr_concatenated = Dh_concatenated*w*norm_concatenated;\n else\n reconfeature_hr_concatenated = Dh*w; %this is the reconstructed\n end\n reconfeature_hr = reconfeature_hr_concatenated(1:patcharea);\n \n patchdiff_hr = reshape(reconfeature_hr, [patchsize, patchsize]);\n reconfeature(r:r1, c:c1) = patchdiff_hr;\n reconintensity_hr = patchdiff_hr + patch_intensity_mean;\n \n img_hr(nonoverlapregion_image) = reconintensity_hr(nonoverlapregion_patch);\n filledmap(r:r1, c:c1) = 1;\n end\nend\n\nfprintf('done!\\n');\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "immaxproduct.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Liu07IJCV/immaxproduct.m", "size": 4991, "source_encoding": "utf_8", "md5": "63134b108b43613ee53f95414d8be926", "text": "% max-product belief propagation on image lattice (2D matrix)\n% This implementation contains no product. The compatibility function\n% should be changed to exp{-E} where E is energy or error. Here E is the\n% input. Output is the MAP estimation of the graph\n% \n% This implementation is based on W.T. Freeman et al's IJCV paper\n% http://www.merl.com/reports/docs/TR2000-05.pdf\n%\n% Input arguments:\n% CO: [nstates x height x width] -- energy function phi, connecting to\n% the observation\n% CM_h: [nstates x nstates x height x (width-1)]--compatibility function \n% psi, connectiing horizontal neighbors. Each matrix is\n% [index of left x index of right]\n% CM_v: [nstates x nstates x (height-1) x width]--compatibility function\n% psi, connectiing vertical neighbors. Each matrix is\n% [index of top x index of bottom]\n% nIerations: scalar-- the number of iterations in BP. The default value\n% is max(height,width)/2\n% alpha: scalar-- It's better to smooth the message update in each\n% iteration. Weight alpha is used to weight the new\n% messages, and (1-alpha) is to weight the old ones.\n%\n% Output arguments:\n% IDX [height x width]-- Bayesian MAP estimation of the graph, each\n% element is an integer between 1 and nstates\n%\n% Ce Liu\n% CSAIL,MIT, celiu@mit.edu\n% Feb, 2006\n\nfunction [IDX,En]=immaxproduct(CO,CM_h,CM_v,nIterations,alpha)\n% get the dimension of the \n[nstates,height,width]=size(CO);\n\n% sanity check for the dimensions\nif size(CM_h)~=[nstates nstates height width-1] \n error('The dimension of CM_h is incorrect!');\nend\nif size(CM_v)~=[nstates nstates height-1 width]\n error('The dimension of CM_v is incorrect!');\nend\n\n% default values for nIerations and alpha\nif exist('nIterations','var')~=1\n nIterations=round(max(height,width)/2);\nend\nif exist('alpha','var')~=1\n alpha=0.6;\nend\n\n% compatibility function psi has to be permuted for bottom to top and right\n% to left. \nCMtb=reshape(CM_v,nstates,nstates*(height-1)*width);\nCMbt=reshape(permute(CM_v,[2,1,3,4]),nstates,nstates*(height-1)*width);\nCMlr=reshape(CM_h,nstates,nstates*height*(width-1));\nCMrl=reshape(permute(CM_h,[2,1,3,4]),nstates,nstates*height*(width-1));\n\n% initialize messages\n% Mtb: top to bottom\n% Mbt: bottom to top\n% Mlr: left to right\n% Mrl: right to left\nMtb=zeros(nstates,(height-1),width);\nMbt=Mtb;\nMlr=zeros(nstates,height,width-1);\nMrl=Mlr;\n\n[foo,IDX]=min(CO,[],1);\nEn(1)=imgraphen(IDX,CO,CM_h,CM_v);\n\n\nfor i=1:nIterations\n % update message from top to bottom\n Mtb1=zeros(nstates,height-1,width);\n Mtb1(:,2:end,:)=Mtb1(:,2:end,:)+Mtb(:,1:end-1,:);\n Mtb1(:,:,1:end-1)=Mtb1(:,:,1:width-1)+Mrl(:,1:end-1,:);\n Mtb1(:,:,2:end)=Mtb1(:,:,2:end)+Mlr(:,1:end-1,:);\n Mtb1=Mtb1+CO(:,1:end-1,:);\n Mtb1=kron(reshape(Mtb1,nstates,(height-1)*width),ones(1,nstates))+CMtb;\n Mtb1=reshape(min(Mtb1,[],1),[nstates,height-1,width]);\n \n % update message from bottom to top\n Mbt1=zeros(nstates,height-1,width);\n Mbt1(:,1:end-1,:)=Mbt1(:,1:end-1,:)+Mbt(:,2:end,:);\n Mbt1(:,:,1:end-1)=Mbt1(:,:,1:end-1)+Mrl(:,2:end,:);\n Mbt1(:,:,2:end)=Mbt1(:,:,2:end)+Mlr(:,2:end,:);\n Mbt1=Mbt1+CO(:,2:end,:);\n Mbt1=kron(reshape(Mbt1,nstates,(height-1)*width),ones(1,nstates))+CMbt;\n Mbt1=reshape(min(Mbt1,[],1),[nstates,height-1,width]);\n \n % update message from left to right\n Mlr1=zeros(nstates,height,width-1);\n Mlr1(:,:,2:end)=Mlr1(:,:,2:end)+Mlr(:,:,1:end-1);\n Mlr1(:,1:end-1,:)=Mlr1(:,1:end-1,:)+Mbt(:,:,1:end-1);\n Mlr1(:,2:end,:)=Mlr1(:,2:end,:)+Mtb(:,:,1:end-1);\n Mlr1=Mlr1+CO(:,:,1:end-1);\n Mlr1=kron(reshape(Mlr1,nstates,height*(width-1)),ones(1,nstates))+CMlr;\n Mlr1=reshape(min(Mlr1,[],1),[nstates,height,width-1]);\n \n % update message from right to left\n Mrl1=zeros(nstates,height,width-1);\n Mrl1(:,:,1:end-1)=Mrl1(:,:,1:end-1)+Mrl(:,:,2:end);\n Mrl1(:,1:end-1,:)=Mrl1(:,1:end-1,:)+Mbt(:,:,2:end);\n Mrl1(:,2:end,:)=Mrl1(:,2:end,:)+Mtb(:,:,2:end);\n Mrl1=Mrl1+CO(:,:,2:end);\n Mrl1=kron(reshape(Mrl1,nstates,height*(width-1)),ones(1,nstates))+CMrl;\n Mrl1=reshape(min(Mrl1,[],1),[nstates,height,width-1]);\n \n % reassign message\n Mtb=Mtb1*alpha+Mtb*(1-alpha);\n Mbt=Mbt1*alpha+Mbt*(1-alpha);\n Mlr=Mlr1*alpha+Mlr*(1-alpha);\n Mrl=Mrl1*alpha+Mrl*(1-alpha);\n \n % Bayesian MAP inference\n M=zeros(nstates,height,width);\n M(:,2:end,:)=M(:,2:end,:)+Mtb;\n M(:,1:end-1,:)=M(:,1:end-1,:)+Mbt;\n M(:,:,2:end)=M(:,:,2:end)+Mlr;\n M(:,:,1:end-1)=M(:,:,1:end-1)+Mrl;\n M=M+CO;\n [foo,IDX]=min(M,[],1);\n En(i+1)=imgraphen(IDX,CO,CM_h,CM_v);\nend\n\n%figure;plot(En);\n\n% step 2. Bayesian MAP inference\nM=zeros(nstates,height,width);\nM(:,2:end,:)=M(:,2:end,:)+Mtb;\nM(:,1:end-1,:)=M(:,1:end-1,:)+Mbt;\nM(:,:,2:end)=M(:,:,2:end)+Mlr;\nM(:,:,1:end-1)=M(:,:,1:end-1)+Mrl;\nM=M+CO;\n[foo,IDX]=min(M,[],1);\nIDX=squeeze(IDX);\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "Sigma2Kernel.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Liu07IJCV/Sigma2Kernel.m", "size": 154, "source_encoding": "utf_8", "md5": "139abf654633c4b0fd0c1146ade54f2c", "text": "%10/23/11\nfunction Kernel = Sigma2Kernel(Gau_sigma)\n KernelSize = ceil(Gau_sigma * 3)*2+1;\n Kernel = fspecial('gaussian',KernelSize,Gau_sigma);\nend\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F2_FindSimilarPatch_CSH.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Liu07IJCV/F2_FindSimilarPatch_CSH.m", "size": 3398, "source_encoding": "utf_8", "md5": "b326c59409096453749c6affa18ca294", "text": "%Chih-Yuan Yang, EECS, UC Merced\n%Last Modified: 08/23/12\n%Find similar patches form many images using CSH\n%Question: I do not need to use all patches cropped from the query image.\n%Only parts are required. How to handle it?\n%However, do not consider it now.\n%And what I need are the coordinate and norm, not the patch. How to do it?\n\nfunction F2_FindSimilarPatch_CSH(queryimage,middlebandimage)\n addpath('Utility');\n addpath(genpath(fullfile('Lib','CSH_code_v2')));\n\n %set randseed\n seed = RandStream('mcg16807','Seed',0); \n RandStream.setGlobalStream(seed) \n\n im8 = imread( para.SourceFile);\n im8y = rgb2gray(im8);\n %find the CSH nn\n \n width = ps; %should I use 4 or 8? Problem: CSH does not support patch size as 6\n iteration = 5;\n nnk = 20;\n [lh lw d] = size(im8);\n recin = 20;\n normcurr = zeros(lh,lw,nnk);\n A = im8y;\n ps = width;\n eh = lh-ps+1;\n ew = lw-ps+1; %effective w\n scanr = zeros(eh,ew,recin,4); %scan results, norm, ii, sr, sc\n bigvalue = 255*width*width;\n scanr(:,:,:,1) = bigvalue;\n iistart = para.iistart;\n iiend = para.iiend;\n \n for ii=iistart:iiend\n %if ii == 2\n % keyboard\n %end\n fn = sprintf('%05d.png',ii);\n fprintf('csh fn: %s\\n',fn);\n ime = imread(fullfile(DatasetFolder,fn)); %the channel number is 1\n B = ime;\n idxhead = (ii-1)*nnk+1;\n idxend = idxhead + nnk-1;\n retres = CSH_nn(A,B,width,iteration,nnk); %x,y <==> c,r $retrived results\n %dimension: w,h,2,nnk\n for l = 1:nnk\n colMap = retres(:,:,1,l);\n rowMap = retres(:,:,2,l);\n br_boundary_to_ignore = width -1;\n %GetAnnError_GrayLevel_C1 is a funciton in CHS lab. It can compute very fast\n normcurr(:,:,l) = GetAnnError_GrayLevel_C1(A,B,uint16(rowMap),uint16(colMap),uint16(0),uint16(br_boundary_to_ignore), uint16(width));\n end\n \n %update scanr\n normcurrmin = min(normcurr,[],3);\n checkmap = normcurrmin(1:eh,1:ew) < scanr(:,:,recin,1); %the last one has the largest norm\n [rset cset] = find(checkmap);\n setin = length(rset);\n for j=1:setin\n rl = rset(j);\n cl = cset(j);\n [normcurrsort ixcurr] = sort(normcurr(rl,cl,:));\n for i=1:nnk\n %update the smaller norm\n compidx = recin-i+1;\n if normcurrsort(i) < scanr(rl,cl,compidx,1)\n %update\n oriidx = ixcurr(i);\n scanr(rl,cl,compidx,1) = normcurrsort(i);\n scanr(rl,cl,compidx,2) = ii;\n scanr(rl,cl,compidx,3) = retres(rl,cl,2,oriidx); %rowmap\n scanr(rl,cl,compidx,4) = retres(rl,cl,1,oriidx); %colmap\n else\n break\n end\n end\n \n %sort again the updated data\n [normnewsort ixnew] = sort(scanr(rl,cl,:,1));\n tempdata = scanr(rl,cl,:,:);\n for i=1:recin\n if ixnew(i) ~= i\n scanr(rl,cl,i,:) = tempdata(1,1,ixnew(i),:);\n end\n end\n end\n end\n sn = sprintf('%s_csh_scanr_%d_%d.mat',para.SaveName,iistart,iiend);\n save(fullfile(para.tuningfolder,sn),'scanr');\nend\n\n"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "imgraphen.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Liu07IJCV/imgraphen.m", "size": 505, "source_encoding": "utf_8", "md5": "fcf09b9d17018fce6c5fefc7e27f85ce", "text": "% function to compute energy of the graph defiend on image lattice\nfunction E=imgraphen(IDX,CO,CM_h,CM_v)\nif length(size(IDX))==2\n [nh,nw]=size(IDX);\n IDX=reshape(IDX,[1 nh nw]);\nend\nE=CO(IDX);\nE=sum(E(:));\nIDX=squeeze(IDX);\n[nh,nw]=size(IDX);\nfor i=1:nh\n for j=1:nw\n % horizontal energy\n p=IDX(i,j);\n if j 1) = 1;\n imgbb(imgbb < 0) = 0;\n img_out_yiq = imgbb;\n img_out_yiq(:,:,2:3) = para.IQLayer_upsampled;\n img_out_rgb = YIQ2RGB(img_out_yiq);\n fn = sprintf('%s_bbcolor.png',para.SaveName);\n imwrite(img_out_rgb, fullfile(para.tuningfolder, fn));\n\n img_out_yiq = imgnn;\n img_out_yiq(:,:,2:3) = para.IQLayer_upsampled;\n img_out_rgb = YIQ2RGB(img_out_yiq);\n fn = sprintf('%s_nncolor.png',para.SaveName);\n imwrite(img_out_rgb, fullfile(para.tuningfolder, fn));\nend"} +{"plateform": "github", "repo_name": "Liusifei/Face-Hallucination-master", "name": "F15_ComputePSNR_RMSE_SSIM_DIIVINE.m", "ext": ".m", "path": "Face-Hallucination-master/Code/Liu07IJCV/F15_ComputePSNR_RMSE_SSIM_DIIVINE.m", "size": 1065, "source_encoding": "utf_8", "md5": "b4057938b919964cf07810f9cf5fca3d", "text": "%08/09/12\n%Chih-Yuan Yang, EECS, UC Merced\n%Compute PSNR, SSIM, DIVINE\n%If you encounter a MATLAB error: Undefined function 'buildSFpyr' for input arguments of type 'double'.\n%You need to install libraries which are dependencies of DIIVINE\n%Steerable Pyramid Toolbox, Download from: http://www.cns.nyu.edu/~eero/steerpyr/\n% action ==>compile mex in MEX subfolder, copy the pointOp.mexw64 to matlabPyrTools folder\n% ==>addpath('matlabPyrTools')\n%LibSVM package for MATLAB, Download from: http://www.csie.ntu.edu.tw/~cjlin/libsvm/\n\nfunction [PSNR SSIM DIIVINE] = F15_ComputePSNR_RMSE_SSIM_DIIVINE(img_test, img_gt, para)\n %in the future, change the pathes of lib by para\n addpath(fullfile('Lib','SSIM'))\n addpath(genpath(fullfile('Lib','matlabPyrTools')));\n addpath(genpath(fullfile('Lib','libsvm-3.12')));\n addpath(fullfile('Lib','DIIVINE')) %DIIVINE\n\n img_test255 = img_test * 255;\n img_gt255 = img_gt * 255;\n PSNR = measerr(img_gt255, img_test255);\n SSIM = ssim( img_gt255, img_test255);\n DIIVINE = divine(img_test255);\nend"} +{"plateform": "github", "repo_name": "tanvir002700/Coursera-Introduction-to-Programming-with-MATLAB-master", "name": "roman2.m", "ext": ".m", "path": "Coursera-Introduction-to-Programming-with-MATLAB-master/Lab08/roman2.m", "size": 1861, "source_encoding": "utf_8", "md5": "a5646f76cbee04af3dd08f0530e14808", "text": "function A = roman2 (R)\n% This function initially assumes the supplied input is valid. If it is not valid,\n% the result, when converted back to Roman, will differ from the original input.\n Roman = 'IVXLC';\n Arabic = {1 5 10 50 100};\n LastValue = 0; % V is value, LastValue is last V\n A = uint16(0);\n for k = length(R):-1:1 % scan backward from last character\n P = strfind(Roman,R(k)); % search list of valid Roman characters\n if isempty(P) % if invalid\n V = 0; % value is zero\n else % else\n V = Arabic{P}; % value is Arabic equivalent\n end\n if V=400 || ~strcmp(R,A2R(A)) % if out of range or result does\n A = uint16(0); % not generate original string\n end % send back zero\nend\n\n% convert Arabic to Roman\nfunction R = A2R (A)\n% Remove subtraction by including secondary moduli.\n Roman = {'I' 'IV' 'V' 'IX' 'X' 'XL' 'L' 'XC' 'C'};\n Arabic = {1 4 5 9 10 40 50 90 100};\n R = ''; k = 9;\n while k>0 % remove larger moduli first\n if A>=Arabic{k} % if value is at least current modulus\n A = A-Arabic{k}; % remove modulus from value\n R = [R Roman{k}]; % append Roman character\n else % else\n k = k-1; % consider next smaller modulus\n end\n end\nend"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "mvnpdfbench.m", "ext": ".m", "path": "libDirectional-master/examples/mvnpdfbench.m", "size": 2336, "source_encoding": "utf_8", "md5": "aaba49ec24c7c9856decfeeb2472618e", "text": "% This function performs a benchmark of the mvnpdf and the mvnpdffast\r\n% functions.\r\n\r\nfunction mvnpdfbench\r\n figure(1)\r\n benchmark();\r\n figure(2)\r\n benchmarkSingle();\r\n\r\n %bench(1) ;\r\n %benchSingle(1);\r\nend\r\n\r\nfunction benchmark\r\n dims = 1:20;\r\n evals = 1000000;\r\n repeats = 10;\r\n t1 = zeros(1,repeats);\r\n t2 = zeros(1,repeats);\r\n times = zeros(2, length(dims));\r\n for i = dims\r\n for j=1:repeats\r\n [t1(j), t2(j)]= bench(i, evals);\r\n end\r\n times (1,i) = median(t1);\r\n times (2,i) = median(t2);\r\n end\r\n benchPlot(dims, times, sprintf('time for %i evaluations with one call', evals))\r\nend\r\n\r\nfunction benchmarkSingle\r\n dims = 1:20;\r\n evals = 1000;\r\n repeats = 10;\r\n t1 = zeros(1,repeats);\r\n t2 = zeros(1,repeats); \r\n times = zeros(2, length(dims));\r\n for i = dims\r\n for j=1:repeats\r\n [t1(j), t2(j)]= benchSingle(i, evals);\r\n end\r\n times (1,i) = median(t1);\r\n times (2,i) = median(t2);\r\n end\r\n benchPlot(dims, times, sprintf('time for %i evaluations with individual calls', evals))\r\nend\r\n\r\nfunction benchPlot(dims, times, titletext)\r\n subplot(2,1,1);\r\n plot(dims, times(1,:));\r\n hold on\r\n plot(dims, times(2,:));\r\n hold off\r\n legend('mvnpdf', 'mvnpdffast', 'location', 'northwest')\r\n xlabel('dimension');\r\n ylabel('time (s)');\r\n title(titletext);\r\n \r\n subplot(2,1,2);\r\n plot(dims, times(1,:)./times(2,:));\r\n hold on\r\n plot(dims, times(1,:)./times(1,:), 'b--');\r\n hold off\r\n xlabel('dimension'); \r\n ylabel('speedup');\r\nend\r\n\r\nfunction [t1, t2]= bench(n, evals)\r\n % n-D\r\n rng default\r\n mu = rand(1,n);\r\n C = rand(n,n);\r\n C=C*C';\r\n x = rand(evals,n);\r\n\r\n tic\r\n r = mvnpdf(x, mu, C); %#ok\r\n t1 = toc;\r\n tic\r\n r = mvnpdffast(x, mu, C); %#ok\r\n t2 = toc;\r\n fprintf('%fs\\n%fs\\n', t1, t2);\r\nend\r\n\r\nfunction [t1, t2]= benchSingle(n,evals)\r\n % n-D\r\n rng default\r\n mu = rand(1,n);\r\n C = rand(n,n);\r\n C=C*C';\r\n x = rand(evals,n);\r\n\r\n tic\r\n for i=1:length(x)\r\n r = mvnpdf(x, mu, C); %#ok\r\n end\r\n t1 = toc;\r\n tic\r\n for i=1:length(x)\r\n r = mvnpdffast(x, mu, C); %#ok\r\n end\r\n t2 = toc;\r\n fprintf('%fs\\n%fs\\n', t1, t2);\r\nend"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "stochasticSampling.m", "ext": ".m", "path": "libDirectional-master/examples/stochasticSampling.m", "size": 2375, "source_encoding": "utf_8", "md5": "b95cc1ebeba799e1541c14fff85a6289", "text": "% This example evaluates stochastic sampling of circular densities.\r\n%\r\n% Three different sampling methods are compared, a native sample for the\r\n% respective density, a generic Metropolis-Hastings sampler, and a sampler\r\n% based on inverting the cumulative distribution function.\r\n\r\nfunction stochasticSampling\r\n %dist = WNDistribution(3, 1.5);\r\n dist = VMDistribution(3, 1.5);\r\n %dist = WCDistribution(3, 1.5);\r\n \r\n nSamples = 1000;\r\n \r\n samples = dist.sample(nSamples);\r\n figure(1);\r\n compare(samples, dist, 'Native Sampling');\r\n\r\n figure(2);\r\n samples = dist.sampleMetropolisHastings(nSamples);\r\n compare(samples, dist, 'Metropolis-Hastings Sampling');\r\n\r\n figure(3);\r\n samples = dist.sampleCdf(nSamples);\r\n compare(samples, dist, 'Sampling Based on Inversion of CDF');\r\nend\r\n\r\nfunction compare(samples, distribution, titlestr)\r\n n = size(samples,2);\r\n steps = 50;\r\n s = zeros(1,steps);\r\n firstMomentError = zeros(1,steps);\r\n kuiper = zeros(1,steps);\r\n for i=1:steps\r\n s(i) = floor(i/steps*n);\r\n wd = WDDistribution(samples(:,1:s(i)));\r\n firstMomentError(i) = abs(wd.trigonometricMoment(1) - distribution.trigonometricMoment(1));\r\n kuiper(i) = wd.kuiperTest(distribution);\r\n end\r\n [hAx,~,~] = plotyy(s, firstMomentError, s, kuiper);\r\n xlabel('samples')\r\n ylabel(hAx(1),'first moment error') % left y-axis\r\n ylabel(hAx(2),'kuiper test') % right y-axis\r\n title(titlestr);\r\n\r\n wd = WDDistribution(samples);\r\n firstMomentErrorTotal = abs(wd.trigonometricMoment(1) - distribution.trigonometricMoment(1));\r\n kuiperTotal = wd.kuiperTest(distribution);\r\n \r\n fprintf('[%s] first moment error: %f\\n', titlestr, firstMomentErrorTotal);\r\n fprintf('[%s] kuiper test: %f\\n', titlestr, kuiperTotal);\r\n \r\n %llRatioWN = calculateLikelihoodRatio(samples, distribution, distribution.toWN())\r\n %llRatioVM = calculateLikelihoodRatio(samples, distribution, distribution.toVM())\r\n %llRatioWC = calculateLikelihoodRatio(samples, distribution, distribution.toWC())\r\n %llRatioUniform = calculateLikelihoodRatio(samples, distribution, CircularUniformDistribution)\r\nend\r\n\r\nfunction lr = calculateLikelihoodRatio(samples, distribution1, distribution2)\r\n lr = exp(sum(distribution1.logLikelihood(samples)) - sum(distribution2.logLikelihood(samples)));\r\nend"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "quaternionMultiplication.m", "ext": ".m", "path": "libDirectional-master/lib/util/quaternionMultiplication.m", "size": 725, "source_encoding": "utf_8", "md5": "5f8f9db745a1a49bf998e78a0db4f783", "text": "% Calculates product of quaternions q and w\r\n% Parameters:\r\n% q (4 x 1 column vector)\r\n% first quaternion\r\n% w (4 x 1 column vector)\r\n% second quaternion\r\n% Returns:\r\n% r (4 x 1 column vector)\r\n% product q*w\r\nfunction r = quaternionMultiplication(q, w) \r\n assert(all(size(q) == [4 1]));\r\n assert(all(size(w) == [4 1]));\r\n \r\n % Formula based on cross product\r\n % Hart, J. C.; Francis, G. K. & Kauffman, L. H. \r\n % Visualizing Quaternion Rotation ACM Transactions on Graphics, \r\n % ACM, 1994, 13, 256-276\r\n \r\n q0 = q(1,:);\r\n w0 = w(1,:);\r\n qvec = q(2:4,:);\r\n wvec = w(2:4,:);\r\n r = [q0 .* w0 - dot(qvec, wvec); q0 .* wvec + w0 .* qvec + cross(qvec, wvec)];\r\nend"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "besselratioInverse.m", "ext": ".m", "path": "libDirectional-master/lib/util/besselratioInverse.m", "size": 3540, "source_encoding": "utf_8", "md5": "3bfa2d63da38bd6f3e6a84460c69a82c", "text": "function kappa = besselratioInverse(v, x, type)\r\n % The inverse of the Ratio I_{v+1}(x)/I_v(x) is computed, where\r\n % I_v(x) is the Bessel-I function of order v evaluated at x.\r\n %\r\n % Parameters:\r\n % v (scalar)\r\n % order\r\n % x (scalar)\r\n % where to evaluate\r\n % type (string)\r\n % can be used to choose between several algorithms\r\n arguments\r\n v (1,1) double\r\n x (1,1) double\r\n type char = 'sraamos'\r\n end\r\n \r\n if x == 0\r\n kappa = 0;\r\n return\r\n end\r\n \r\n if strcmp(type,'sraamos')\r\n assert (v==0);\r\n kappa = besselInverseSraAmos(x);\r\n elseif strcmp(type,'fisher')\r\n assert(v==0);\r\n kappa = besselInverseFisher(x);\r\n elseif strcmp(type,'amosfsolve')\r\n kappa = besselInverseAmosFsolve(v,x);\r\n elseif strcmp(type,'matlabfsolve')\r\n kappa = besselInverseMatlabFsolve(v,x);\r\n elseif strcmp(type,'sra')\r\n kappa = besselInverseSra(v,x);\r\n end\r\nend\r\n\r\nfunction kappa = besselInverseFisher(x)\r\n % Approximation by Fisher for v=0\r\n %\r\n % Fisher, N. I. Statistical Analysis of Circular Data \r\n % Cambridge University Press, 1995, eq (3.47)\r\n %\r\n % recommended if speed is more important than accuracy\r\n kappa = (x<0.53).*(2*x+x.^3+5*x.^5/6) + (x>=0.53).*(x<0.85).*(-0.4+1.39*x+0.43./(1-x)) + (x>=0.85)./(x.^3-4*x.^2+3*x);\r\nend\r\n\r\nfunction kappa = besselInverseAmosFsolve(v,x)\r\n % Use fsolve to calculate the inverse, use the approxmation by Amos for\r\n % the ratio of bessel functions, only works well until approx. kappa=1000\r\n f = @(t) besselratio(v,t) - x;\r\n start = 1;\r\n kappa = fsolve(f, start, optimset('Display', 'off', 'TolFun', 1e-40));\r\nend\r\n\r\nfunction kappa = besselInverseMatlabFsolve(v,x)\r\n % Use fsolve to calculate the inverse, use the Matlab for the ratio of\r\n % bessel functions, only works well until approx. kappa=1000\r\n f = @(t) besseli(v+1,t,1)/besseli(v,t,1) - x;\r\n start = 1;\r\n kappa = fsolve(f, start, optimset('Display', 'off', 'TolFun', 1e-40));\r\nend\r\n\r\nfunction kappa = besselInverseSra(v,x)\r\n % Sra, S. \r\n % A Short Note on Parameter Approximation for von Mises--Fisher Distributions: And a Fast Implementation of Is (x) \r\n % Computational Statistics, Springer-Verlag, 2012, 27, 177-190\r\n d=2*v+2;\r\n % approximation by Banaerjee et al.\r\n kappa = x*(d-x^2)/(1-x^2);\r\n\r\n % newton approximation by Sra 2012\r\n % relies on matlab bessel functions\r\n % Attention: Sra defines A_d differently than we usually do!\r\n Ad = @(kappa) besseli(d/2, kappa, 1)/besseli(d/2-1, kappa, 1);\r\n newtonStep = @(kappa) kappa - (Ad(kappa)-x)/(1- Ad(kappa)^2 - (d-1)/kappa*Ad(kappa));\r\n for i=2:25\r\n kappaNew = newtonStep(kappa);\r\n if kappaNew == kappa\r\n break\r\n end\r\n kappa = kappaNew;\r\n end\r\nend\r\n\r\nfunction kappa = besselInverseSraAmos(x)\r\n % Combination of the methods by Sra and Amos\r\n % recommended for good if high accuracy is desired, also works for\r\n % large kappa\r\n \r\n % approximation by Banaerjee et al.\r\n kappa = x*(2-x^2)/(1-x^2);\r\n\r\n % newton approximation by Sra 2012\r\n Ad = @(kappa) besselratio(0,kappa); %use approximation by Amos to allow large values of kappa\r\n newtonStep = @(kappa) kappa - (Ad(kappa)-x)/(1- Ad(kappa)^2 - 1/kappa*Ad(kappa));\r\n for i=2:25\r\n kappaNew = newtonStep(kappa);\r\n if kappaNew == kappa\r\n break\r\n end\r\n kappa = kappaNew;\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "generateSymbolic.m", "ext": ".m", "path": "libDirectional-master/lib/util/generateSymbolic.m", "size": 1215, "source_encoding": "utf_8", "md5": "af1b6b5f9689ff00d9cbe748f7c983d5", "text": "function generateSymbolic(D)\n % Requires the symbolic toolbox, if you need to generate further files.\n % Files are already generated for d = 2:6.\n \n name = 'cBinghamNorm';\n filename = mFilePath(D, name);\n if exist(filename, 'file') == 0\n [c, X] = cBinghamNormSymbolic(D);\n mFileExport(c, X, name);\n end\n \n name = 'cBinghamGradLogNorm';\n filename = mFilePath(D, name);\n if exist(filename, 'file') == 0\n grad_log_c = cBinghamGradLogNormSymbolic(c, X);\n mFileExport(grad_log_c, X, name);\n end\n \n name = 'cBinghamGradNormDividedByNorm';\n filename = mFilePath(D, name);\n if exist(filename, 'file') == 0\n grad_c_divided_by_c = cBinghamGradNormDividedByNormSymbolic(c, X);\n mFileExport(grad_c_divided_by_c, X, name);\n end\nend\n\nfunction filename = mFilePath(D, name)\n thisFilePath = mfilename('fullpath');\n filename = sprintf('%s%d.m', name, D);\n filename = fullfile(fileparts(thisFilePath), ['autogenerated/' filename]);\nend\n\nfunction mFileExport(expression, variables, name)\n D = numel(variables);\n filename = mFilePath(D, name);\n matlabFunction(expression, 'file', filename, 'vars', {variables});\nend\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "sphMeanShift.m", "ext": ".m", "path": "libDirectional-master/lib/util/sphMeanShift.m", "size": 659, "source_encoding": "utf_8", "md5": "958ccbbe80ce6728e0237139b4c65685", "text": "function x_mean = sphMeanShift(x, w)\n% @author Kailai Li kailai.li@kit.edu\n% @date 2018\nx_mean = x(:, 1);\nwhile 1\n x(:, x_mean'*x < 0) = -x(:, x_mean'*x < 0);\n x_t = sphLog(x_mean, x);\n x_mean_t = sum(x_t.*w, 2);\n if norm(x_mean_t) < 1E-6\n break\n end\n x_mean = sphExp(x_mean, x_mean_t);\nend\nend\n\nfunction x_t = sphLog(x_center, x)\n% spherical logarithm map\n%\ndot_prod = x_center' * x;\nalpha = acos(dot_prod);\nx_t = (x - dot_prod .* x_center) ./ sinc(alpha/pi);\nend\n\nfunction x = sphExp(x_center, x_t)\n% spherical exponential map\n%\nnorm_t = vecnorm(x_t); % sqrt(sum(x_t.^2,1));\nx = cos(norm_t) .* x_center + x_t .* sinc(norm_t/pi);\nend"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "cubesubdivision.m", "ext": ".m", "path": "libDirectional-master/lib/util/cubesubdivision.m", "size": 2048, "source_encoding": "utf_8", "md5": "5fb465876f34031556a8763f0ea61709", "text": "% Gerhard Kurz, Florian Pfaff, Uwe D. Hanebeck,\r\n% Discretization of SO(3) Using Recursive Tesseract Subdivision\r\n% Proceedings of the 2017 IEEE International Conference on Multisensor Fusion and Integration for Intelligent Systems (MFI 2017)\r\n% Daegu, Korea, November 2017.\r\n\r\nfunction result = cubesubdivision(n, normalize)\r\n if nargin < 2\r\n normalize = true;\r\n end\r\n \r\n %number of points is 6*4^n+2\r\n quads = generateCube();\r\n\r\n while length(unique(cell2mat(quads),'rows')) < n\r\n newQuads = cell(4*length(quads),1);\r\n for i=1:length(quads)\r\n newQuads(4*i-3:4*i,1) = subdividequad(quads{i});\r\n end\r\n quads = newQuads;\r\n end\r\n \r\n result = unique(cell2mat(quads),'rows');\r\n\r\n if normalize \r\n result = result./repmat(sqrt(sum(result.^2,2)), 1, 3);\r\n end\r\nend\r\n\r\nfunction quads = generateCube()\r\n quad2d = (dec2bin(0:3)-'0')*2-1;\r\n \r\n quads = cell(6,1);\r\n for i=1:3\r\n %insert column with +1 or -1 at location i\r\n quads{2*i-1} = [quad2d(:,1:i-1), ones(4,1), quad2d(:,i:end)];\r\n quads{2*i} = [quad2d(:,1:i-1), -ones(4,1), quad2d(:,i:end)];\r\n end\r\nend\r\n\r\nfunction quads = subdividequad(quad)\r\n %divides given cube into 8 cubes\r\n assert(all(size(quad) == [4 3]));\r\n center = mean(quad);\r\n quads = cell(4,1);\r\n for i=1:4 %create 4 new quads\r\n p = quad(i,:); \r\n %create cube with corners p and center \r\n newCube = generateQuad(p,center);\r\n quads {i} = newCube;\r\n end\r\nend\r\n\r\nfunction newQuads = generateQuad(a,b)\r\n %generate axis aligned cube with opposite corners a and b\r\n x = zeros(8,3); %corner candidates\r\n %try all combinations of min/max in each dimension\r\n %todo optimize performance\r\n for i=1:8\r\n for j=1:3\r\n if bitget(i,j) == 1\r\n x(i,j) = min(a(j),b(j));\r\n else\r\n x(i,j) = max(a(j),b(j));\r\n end\r\n end\r\n end\r\n %throw away duplicates\r\n newQuads = unique(x,'rows');\r\nend"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "angularError.m", "ext": ".m", "path": "libDirectional-master/lib/util/angularError.m", "size": 317, "source_encoding": "utf_8", "md5": "2e98c005845e7d6a1d6fa3de25e778ea", "text": "%% Calculates the angular error between alpha and beta\r\nfunction e = angularError(alpha, beta)\r\n arguments\r\n alpha double {mustBeNonempty}\r\n beta double {mustBeNonempty}\r\n end\r\n alpha = mod(alpha,2*pi);\r\n beta = mod(beta,2*pi);\r\n diff = abs(alpha-beta);\r\n e = min(diff,2*pi-diff);\r\nend"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "complexMultiplication.m", "ext": ".m", "path": "libDirectional-master/lib/util/complexMultiplication.m", "size": 457, "source_encoding": "utf_8", "md5": "8061eca5ea8d1f05e0742757e60cd78d", "text": "% Calculates product of complex numbers q and w\r\n% Parameters:\r\n% q (2 x 1 column vector)\r\n% first complex number\r\n% w (2 x 1 column vector)\r\n% second complex number\r\n% Returns:\r\n% r (2 x 1 column vector)\r\n% product q*w\r\n\r\nfunction r = complexMultiplication(q, w)\r\n assert(all(size(q) == [2,1]));\r\n assert(all(size(w) == [2,1]));\r\n \r\n r = [q(1,:) .* w(1,:) - q(2,:) .* w(2,:); q(1,:) .* w(2,:) + q(2,:) .* w(1,:)];\r\nend\r\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "tesseractsubdivision.m", "ext": ".m", "path": "libDirectional-master/lib/util/tesseractsubdivision.m", "size": 2141, "source_encoding": "utf_8", "md5": "06207da5af3e03c28de06cff44f5f135", "text": "% Gerhard Kurz, Florian Pfaff, Uwe D. Hanebeck,\r\n% Discretization of SO(3) Using Recursive Tesseract Subdivision\r\n% Proceedings of the 2017 IEEE International Conference on Multisensor Fusion and Integration for Intelligent Systems (MFI 2017)\r\n% Daegu, Korea, November 2017.\r\n\r\nfunction result = tesseractsubdivision(n, normalize)\r\n if nargin < 2\r\n normalize = true;\r\n end\r\n \r\n %numer of points is f(2^m) where m=0,1, ... and f(n)=(n+1).^4-(n-1).^4\r\n %f is https://oeis.org/A008511\r\n cubes = generateTesseract();\r\n\r\n while length(unique(cell2mat(cubes),'rows')) < n\r\n newCubes = cell(8*length(cubes),1);\r\n for i=1:length(cubes)\r\n newCubes(8*i-7:8*i,1) = subdividecube(cubes{i});\r\n end\r\n cubes = newCubes;\r\n end\r\n \r\n result = unique(cell2mat(cubes),'rows');\r\n \r\n if normalize\r\n result = result./repmat(sqrt(sum(result.^2,2)), 1, 4);\r\n end\r\nend\r\n\r\nfunction cubes = generateTesseract()\r\n cube3d = (dec2bin(0:7)-'0')*2-1;\r\n \r\n cubes = cell(8,1);\r\n for i=1:4\r\n %insert column with +1 or -1 at location i\r\n cubes{2*i-1} = [cube3d(:,1:i-1), ones(8,1), cube3d(:,i:end)];\r\n cubes{2*i} = [cube3d(:,1:i-1), -ones(8,1), cube3d(:,i:end)];\r\n end\r\nend\r\n\r\nfunction cubes = subdividecube(cube)\r\n %divides given cube into 8 cubes\r\n assert(all(size(cube) == [8 4]));\r\n center = mean(cube);\r\n cubes = cell(8,1);\r\n for i=1:8 %create 8 new cubes\r\n p = cube(i,:); \r\n %create cube with corners p and center \r\n newCube = generateCube(p,center);\r\n cubes {i} = newCube;\r\n end\r\nend\r\n\r\nfunction newCube = generateCube(a,b)\r\n %generate axis aligned cube with opposite corners a and b\r\n x = zeros(16,4); %corner candidates\r\n %try all combinations of min/max in each dimension\r\n %todo optimize performance\r\n for i=1:16\r\n for j=1:4\r\n if bitget(i,j) == 1\r\n x(i,j) = min(a(j),b(j));\r\n else\r\n x(i,j) = max(a(j),b(j));\r\n end\r\n end\r\n end\r\n %throw away duplicates\r\n newCube = unique(x,'rows');\r\nend"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "BinghamDistribution.m", "ext": ".m", "path": "libDirectional-master/lib/distributions/Hypersphere/BinghamDistribution.m", "size": 44212, "source_encoding": "utf_8", "md5": "c8bf69cc58a27838875cc22e978de144", "text": "% The Bingham Distribution.\r\n% This class represents a d-dimensional Bingham distribution.\r\n%\r\n% Notation:\r\n% In this class, d represents the dimension of the distribution.\r\n% Currently, there is no support for uniform Bingham distributions.\r\n%\r\n% see\r\n% C. Bingham, \"An antipodally symmetric distribution on the sphere\",\r\n% The Annals of Statistics, vol. 2, no. 6, pp. 1201-1225, Nov. 1974.\r\n\r\nclassdef BinghamDistribution < AbstractHypersphericalDistribution\r\n \r\n properties\r\n Z (:,1) double {mustBeNonpositive} % Concentrations as a vector\r\n M (:,:) double % Rotation matrix\r\n F (1,1) double % Normalization constant\r\n dF (1,:) double % Partial derivates of F\r\n end\r\n \r\n properties (Constant)\r\n S2 = AbstractHypersphericalDistribution.computeUnitSphereSurface(2) % Circle length\r\n end\r\n \r\n methods\r\n function B = BinghamDistribution(Z_, M_)\r\n % Constructs a Bingham distribution object.\r\n % Parameters:\r\n % Z_ (d x 1 column vector)\r\n % concentration parameters (have to be increasing, and last\r\n % entry has to be zero)\r\n % M_ (d x d matrix)\r\n % orthogonal matrix that describes rotation\r\n % Returns:\r\n % B (BinghamDistribution)\r\n % an object representing the constructed distribution\r\n arguments\r\n Z_ (:,1) double\r\n M_ (:,:) double\r\n end\r\n B.dim = size(M_,1);\r\n \r\n % Check Dimensions\r\n assert(size(M_,2) == B.dim, 'M is not square');\r\n assert(size(Z_,1) == B.dim, 'Z has wrong number of rows');\r\n assert(size(Z_,2) == 1, 'Z needs to be column vector');\r\n \r\n % Enforce last entry of Z to be zero\r\n assert(Z_(B.dim, 1) == 0, 'last entry of Z needs to be zero');\r\n \r\n % Enforce z1<=z2<=...<=z(d-1)<=0=z(d)\r\n assert(all(Z_(1:end-1) <= Z_(2:end)), 'values in Z have to be ascending');\r\n \r\n %enforce that M is orthogonal\r\n epsilon = 0.001;\r\n assert (max(max(M_*M_' - eye(B.dim,B.dim))) < epsilon, 'M is not orthogonal');\r\n \r\n B.Z = Z_;\r\n B.M = M_;\r\n B.F = BinghamDistribution.computeF(B.Z);\r\n B.dF = BinghamDistribution.computeDF(B.Z);\r\n end\r\n \r\n function p = pdf(this, xa)\r\n % Evaluates pdf at each column of xa\r\n % Parameters:\r\n % xa (d x n matrix)\r\n % each column represents one of the n points in R^d that the\r\n % pdf is evaluated at; can be just a (d x 1) vector as well\r\n % Returns:\r\n % p (1 x n row vector)\r\n % values of the pdf at each column of xa\r\n arguments\r\n this (1,1) BinghamDistribution\r\n xa (:,:) double\r\n end\r\n assert(size(xa,1) == this.dim);\r\n \r\n C = this.M * diag(this.Z) * this.M';\r\n p = 1/this.F * exp(sum(xa.*(C*xa)));\r\n end\r\n \r\n function meanDirection(~)\r\n error('Due to their symmetry, the mean direction is undefined for Bingham distributions.');\r\n end\r\n \r\n function B = multiply(this, B2)\r\n % Computes the product of two Bingham pdfs\r\n % This method makes use of the fact that the Bingham distribution\r\n % is closed under Bayesian inference. Thus, the product of two\r\n % Bingham pdfs is itself the pdf of a Bingham distribution. This\r\n % method computes the parameters of the resulting distribution.\r\n %\r\n % Parameters:\r\n % B2 (BinghamDistribution)\r\n % second Bingham Distribution\r\n % Returns:\r\n % B (BinghamDistribution)\r\n % Bingham distribution representing this*B2 (after\r\n % renormalization)\r\n arguments\r\n this (1,1) BinghamDistribution\r\n B2 (1,1) BinghamDistribution\r\n end\r\n assert(isa(B2, 'BinghamDistribution'));\r\n if this.dim == B2.dim\r\n C = this.M * diag(this.Z) * this.M' + B2.M * diag(B2.Z) * B2.M'; % new exponent\r\n \r\n C = 0.5*(C+C'); % Ensure symmetry of C, asymmetry may arise as a consequence of a numerical instability earlier.\r\n \r\n [V,D] = eig(C); % Eigenvalue decomposition\r\n [D, order] = sort(diag(D),'ascend'); % sort eigenvalues\r\n V = V(:,order);\r\n Z_ = D;\r\n Z_ = Z_-Z_(end); % last entry should be zero\r\n M_ = V;\r\n B = BinghamDistribution(Z_,M_);\r\n else\r\n error('dimensions do not match');\r\n end\r\n end\r\n \r\n function B = compose(this, B2)\r\n % Compose two Bingham distributions\r\n % Using Moment Matching based approximation, we compose two Bingham\r\n % distributions. The mode of the new distribution should be the\r\n % quaternion multiplication of the original modes; the uncertainty\r\n % should be larger than before\r\n %\r\n % Parameters:\r\n % B2 (BinghamDistribution)\r\n % second Bingham Distribution\r\n % Returns:\r\n % B (BinghamDistribution)\r\n % Bingham distribution representing the convolution\r\n arguments\r\n this (1,1) BinghamDistribution\r\n B2 (1,1) BinghamDistribution\r\n end\r\n B1=this;\r\n B1S = B1.moment();\r\n B2S = B2.moment();\r\n if this.dim==2 && B2.dim==2\r\n % for complex numbers\r\n % derived from complex multiplication\r\n % Gerhard Kurz, Igor Gilitschenski, Simon Julier, Uwe D. Hanebeck,\r\n % Recursive Bingham Filter for Directional Estimation Involving 180 Degree Symmetry\r\n % Journal of Advances in Information Fusion, 9(2):90 - 105, December 2014.\r\n a11 = B1S(1,1);\r\n a12 = B1S(1,2);\r\n a22 = B1S(2,2);\r\n b11 = B2S(1,1);\r\n b12 = B2S(1,2);\r\n b22 = B2S(2,2);\r\n \r\n S(1,1) = a11*b11 - 2*a12*b12 + a22*b22;\r\n S(1,2) = a11*b12 - a22*b12 - a12*b22 + a12*b11;\r\n S(2,1) = S(1,2);\r\n S(2,2) = a11*b22 + 2*a12*b12 + a22*b11;\r\n \r\n B = BinghamDistribution.fitToMoment(S);\r\n elseif this.dim==4 && B2.dim==4\r\n % adapted from Glover's C code in libBingham, see also\r\n % Glover, J. & Kaelbling, L. P.\r\n % Tracking 3-D Rotations with the Quaternion Bingham Filter\r\n % MIT, 2013\r\n \r\n a11 = B1S(1,1);\r\n a12 = B1S(1,2);\r\n a13 = B1S(1,3);\r\n a14 = B1S(1,4);\r\n a22 = B1S(2,2);\r\n a23 = B1S(2,3);\r\n a24 = B1S(2,4);\r\n a33 = B1S(3,3);\r\n a34 = B1S(3,4);\r\n a44 = B1S(4,4);\r\n \r\n b11 = B2S(1,1);\r\n b12 = B2S(1,2);\r\n b13 = B2S(1,3);\r\n b14 = B2S(1,4);\r\n b22 = B2S(2,2);\r\n b23 = B2S(2,3);\r\n b24 = B2S(2,4);\r\n b33 = B2S(3,3);\r\n b34 = B2S(3,4);\r\n b44 = B2S(4,4);\r\n \r\n %can be derived from quaternion multiplication\r\n S(1,1) = a11*b11 - 2*a12*b12 - 2*a13*b13 - 2*a14*b14 + a22*b22 + 2*a23*b23 + 2*a24*b24 + a33*b33 + 2*a34*b34 + a44*b44;\r\n S(1,2) = a11*b12 + a12*b11 + a13*b14 - a14*b13 - a12*b22 - a22*b12 - a13*b23 - a23*b13 - a14*b24 - a24*b14 - a23*b24 + a24*b23 - a33*b34 + a34*b33 - a34*b44 + a44*b34;\r\n S(2,1) = S(1,2);\r\n S(1,3) = a11*b13 + a13*b11 - a12*b14 + a14*b12 - a12*b23 - a23*b12 - a13*b33 + a22*b24 - a24*b22 - a33*b13 - a14*b34 - a34*b14 + a23*b34 - a34*b23 + a24*b44 - a44*b24;\r\n S(3,1) = S(1,3);\r\n S(1,4) = a11*b14 + a12*b13 - a13*b12 + a14*b11 - a12*b24 - a24*b12 - a22*b23 + a23*b22 - a13*b34 - a34*b13 - a23*b33 + a33*b23 - a14*b44 - a24*b34 + a34*b24 - a44*b14;\r\n S(4,1) = S(1,4);\r\n S(2,2) = 2*a12*b12 + a11*b22 + a22*b11 + 2*a13*b24 - 2*a14*b23 + 2*a23*b14 - 2*a24*b13 - 2*a34*b34 + a33*b44 + a44*b33;\r\n S(2,3) = a12*b13 + a13*b12 + a11*b23 + a23*b11 - a12*b24 + a14*b22 - a22*b14 + a24*b12 + a13*b34 - a14*b33 + a33*b14 - a34*b13 + a24*b34 + a34*b24 - a23*b44 - a44*b23;\r\n S(3,2) = S(2,3);\r\n S(2,4) = a12*b14 + a14*b12 + a11*b24 + a12*b23 - a13*b22 + a22*b13 - a23*b12 + a24*b11 - a14*b34 + a34*b14 + a13*b44 + a23*b34 - a24*b33 - a33*b24 + a34*b23 - a44*b13;\r\n S(4,2) = S(2,4);\r\n S(3,3) = 2*a13*b13 + 2*a14*b23 - 2*a23*b14 + a11*b33 + a33*b11 - 2*a12*b34 + 2*a34*b12 - 2*a24*b24 + a22*b44 + a44*b22;\r\n S(3,4) = a13*b14 + a14*b13 - a13*b23 + a23*b13 + a14*b24 - a24*b14 + a11*b34 + a12*b33 - a33*b12 + a34*b11 + a23*b24 + a24*b23 - a12*b44 - a22*b34 - a34*b22 + a44*b12;\r\n S(4,3) = S(3,4);\r\n S(4,4) = 2*a14*b14 - 2*a13*b24 + 2*a24*b13 + 2*a12*b34 - 2*a23*b23 - 2*a34*b12 + a11*b44 + a22*b33 + a33*b22 + a44*b11;\r\n \r\n B = BinghamDistribution.fitToMoment(S);\r\n else\r\n error('unsupported dimension');\r\n end\r\n end\r\n \r\n function s = sample(this, n)\r\n % Stocahastic sampling\r\n % Fall back to Kent's method by default\r\n %\r\n % Parameters:\r\n % n (scalar)\r\n % number of samples\r\n % Returns:\r\n % s (dim x n)\r\n % one sample per column\r\n arguments\r\n this (1,1) BinghamDistribution\r\n n (1,1) {mustBeInteger, mustBePositive}\r\n end\r\n s = sampleKent(this, n);\r\n end\r\n \r\n function s = sampleKent(this, n)\r\n % Generate samples from Bingham distribution using rejection\r\n % sampling based on a angular central Gaussian\r\n %\r\n % Kent, J. T.; Ganeiber, A. M. & Mardia, K. V.\r\n % A New Method to Simulate the Bingham and Related Distributions in Directional Data Analysis with Applications\r\n % arXiv preprint arXiv:1310.8110, 2013\r\n arguments\r\n this (1,1) BinghamDistribution\r\n n (1,1) {mustBeInteger, mustBePositive}\r\n end\r\n s = zeros(this.dim, n);\r\n i = 1;\r\n A = - this.M * diag(this.Z) * this.M'; % Kent uses a minus sign here!\r\n q = this.dim;\r\n \r\n % compute b\r\n bfun = @(b) sum(1./(b-2*this.Z)) - 1; % use a minus sign before 2*this.z because Kent's matrix is negative\r\n b = fsolve(bfun, 1, optimset('display', 'none'));\r\n Omega = eye(this.dim) + 2*A/b;\r\n %efficiency = 1/(exp(-(q-b)/2) * (q/b)^(q/2))\r\n %Mb = 1/this.F * exp(-(q-b)/2) * (q/b)^(q/2) * det(Omega)^(-1/2);\r\n Mbstar = exp(-(q-b)/2) * (q/b)^(q/2);\r\n nReject = 0;\r\n fbingstar = @(x) exp(-x' * A * x);\r\n facgstar = @(x) (x' * Omega * x)^(-q/2);\r\n while(i<=n)\r\n % draw x from angular central Gaussian\r\n y = mvnrnd(zeros(this.dim,1), inv(Omega))';\r\n x = y/norm(y);\r\n % check rejection\r\n W = rand(1);\r\n if W < fbingstar(x) /(Mbstar * facgstar(x))\r\n s(:,i) = x;\r\n i = i + 1;\r\n else\r\n nReject = nReject + 1;\r\n end\r\n end\r\n %nReject\r\n end\r\n \r\n function X = sampleGlover(this, n)\r\n % Generate samples from Bingham distribution\r\n % based on Glover's implementation in libBingham\r\n % uses Metropolis-Hastings\r\n % see http://en.wikipedia.org/wiki/Metropolis-Hastings_algorithm\r\n %\r\n % The implementation has a bug because it just repeats the\r\n % previos sample if a sample is rejected.\r\n %\r\n % Parameters:\r\n % n (scalar)\r\n % number of samples to generate\r\n % Returns:\r\n % X (dimx n matrix)\r\n % generated samples (one sample per column)\r\n arguments\r\n this (1,1) BinghamDistribution\r\n n (1,1) {mustBeInteger, mustBePositive}\r\n end\r\n burnin = 5;\r\n samplerate = 10;\r\n \r\n x = this.mode();\r\n z = sqrt(-1./(this.Z - 1));\r\n \r\n target = this.pdf(x); % target\r\n proposal = acgpdf_pcs(x', z, this.M); % proposal\r\n \r\n X2 = (randn(n*samplerate+burnin,this.dim).*repmat(z',[n*samplerate+burnin,1]))*this.M'; % sample Gaussian\r\n X2 = X2 ./ repmat(sqrt(sum(X2.^2,2)), [1 this.dim]); % normalize\r\n \r\n Target2 = this.pdf(X2');\r\n Proposal2 = acgpdf_pcs(X2, z, this.M);\r\n \r\n nAccepts = 0;\r\n X = zeros(size(X2));\r\n for i=1:n*samplerate+burnin\r\n a = Target2(i) / target * proposal / Proposal2(i);\r\n if a > rand()\r\n x = X2(i,:);\r\n proposal = Proposal2(i);\r\n target = Target2(i);\r\n nAccepts = nAccepts + 1;\r\n end\r\n X(i,:) = x;\r\n end\r\n \r\n %accept_rate = num_accepts / (n*sample_rate + burn_in)\r\n \r\n X = X(burnin+1:samplerate:end,:)';\r\n end\r\n \r\n function m = mode(this)\r\n % Calculate the mode of a Bingham distribution\r\n % Returns:\r\n % m (column vector)\r\n % mode of the distribution (note that -m is the mode as well)\r\n arguments\r\n this (1,1) BinghamDistribution\r\n end\r\n m = this.M(:,end); %last column of M\r\n end\r\n \r\n function S = moment(this)\r\n arguments\r\n this (1,1) BinghamDistribution\r\n end\r\n % Calculate scatter/covariance matrix of Bingham distribution\r\n % Returns:\r\n % S (d x d matrix)\r\n % scatter/covariance matrix in R^d\r\n D = diag(this.dF/this.F);\r\n % the sum of the diagonal of D is always 1, however this may\r\n % not be the case because dF and F are calculated using\r\n % approximations\r\n D = D / sum(diag(D));\r\n S = this.M * D * this.M';\r\n S = (S+S')/2; % enforce symmetry\r\n end\r\n \r\n function [samples, weights] = sampleDeterministic(this, lambda)\r\n % Computes deterministic samples of a Bingham distribution.\r\n % The computed samples represent the current Bingham distribution.\r\n % They are choosen in a deterministic way, which is a circular\r\n % adaption of the UKF.\r\n %\r\n % see\r\n % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck,\r\n % Unscented Orientation Estimation Based on the Bingham Distribution\r\n % IEEE Transactions on Automatic Control, January 2016.\r\n %\r\n % Important: The paper discusses samples from both modes of the\r\n % Bingham. This code only samples from one mode. If desired, the samples\r\n % from the other mode can be obtained by mirroring:\r\n % [s,w] = bd.sampleDeterministic\r\n % s2 = [s, -s]\r\n % w2 = [w, w]/2\r\n %\r\n % Parameters:\r\n % lambda (scalar or string)\r\n % weighting parameter in [0,1] or the string 'uniform' (only\r\n % in 2D)\r\n % Returns:\r\n % samples (d x ... matrix)\r\n % generated samples (one sample per column)\r\n % weights (1 x ... vector)\r\n % weight > 0 for each sample (weights sum to one)\r\n arguments\r\n this (1,1) BinghamDistribution\r\n lambda = []\r\n end\r\n if isempty(lambda) % default value for lambda\r\n if this.dim == 2\r\n lambda = 'uniform';\r\n else\r\n lambda = 0.5;\r\n end\r\n end\r\n if strcmp(lambda,'uniform') && this.dim == 2\r\n % uniform weights can only be guaranteed for d=2\r\n B = BinghamDistribution(this.Z, eye(2,2));\r\n S = B.moment();\r\n alpha = asin(sqrt(S(1,1)*3/2));\r\n samples = [ 0, 1;\r\n sin(alpha), cos(alpha);\r\n -sin(alpha), cos(alpha)];\r\n samples = this.M*samples';\r\n weights = [1/3, 1/3, 1/3];\r\n else\r\n assert (lambda>=0 && lambda <=1);\r\n B = BinghamDistribution(this.Z, eye(this.dim,this.dim));\r\n S = B.moment();\r\n samples = zeros(2*this.dim-1,this.dim);\r\n weights = zeros(1, 2*this.dim-1);\r\n p = zeros(1, this.dim-1);\r\n alpha = zeros(1, this.dim-1);\r\n samples(1,end) = 1; %sample at mode\r\n for i=1:this.dim-1\r\n p(i) = S(i,i) + (1-lambda)*(S(end,end)/(this.dim-1));\r\n alpha(i) = asin(sqrt(S(i,i)/p(i)));\r\n samples(2*i,end) = cos(alpha(i));\r\n samples(2*i+1,end) = cos(alpha(i));\r\n samples(2*i,i) = sin(alpha(i));\r\n samples(2*i+1,i) = -sin(alpha(i));\r\n weights(1,2*i) = p(i)/2;\r\n weights(1,2*i+1) = p(i)/2;\r\n end\r\n weights(1) = 1-sum(weights(2:end)); % = lambda*S(4,4)\r\n samples = this.M*samples';\r\n end\r\n end\r\n \r\n function [samples, weights] = sampleOptimalQuantization(this, N)\r\n % Computes optimal quantization of the\r\n % Bingham distribution using 2*N samples.\r\n %\r\n % Parameters:\r\n % N(scalar)\r\n % number of samples on half circle\r\n % Returns:\r\n % samples (1 x 2N)\r\n % 2N samples on the circle, parameterized as [0,2pi)\r\n % weights (1 x 2N)\r\n % weight for each sample\r\n %\r\n % Igor Gilitschenski, Gerhard Kurz, Uwe D. Hanebeck, Roland Siegwart,\r\n % Optimal Quantization of Circular Distributions\r\n % Proceedings of the 19th International Conference on Information Fusion (Fusion 2016), Heidelberg, Germany, July 2016.\r\n arguments\r\n this (1,1) BinghamDistribution\r\n N (1,1) {mustBeInteger, mustBePositive}\r\n end\r\n assert(this.dim == 2, 'sampleOptimalQuantization only implemented for 2d Bingham');\r\n \r\n mu = atan2(this.M(2,2), this.M(1,2));\r\n kappa = (this.Z(2)-this.Z(1))/2;\r\n \r\n [samples, weights] = VMDistribution(0, kappa).sampleOptimalQuantization(N);\r\n samples = [samples/2 (samples/2+pi)];\r\n samples = mod(samples+mu,2*pi);\r\n \r\n weights = [weights weights]/2;\r\n end\r\n \r\n function [s,w] = sampleWeighted(this, n)\r\n % Weighted sample generator.\r\n % Generates uniform (w.r.t. the Haar Measure) random samples on\r\n % the unit sphere and assigns each sample a weight based on the\r\n % pdf.\r\n %\r\n % Parameters:\r\n % n (scalar)\r\n % number of samples\r\n %\r\n % Returns:\r\n % samples (d x n matrix)\r\n % generated samples (one sample per column)\r\n % weights (1 x n vector)\r\n arguments\r\n this (1,1) BinghamDistribution\r\n n (1,1) {mustBeInteger, mustBePositive}\r\n end\r\n s = mvnrnd(zeros(1,this.dim), eye(this.dim), n)';\r\n s = s./repmat(sqrt(sum(s.^2,1)),this.dim, 1);\r\n \r\n w = this.pdf(s);\r\n w = w/sum(w); % normalize weights\r\n end\r\n \r\n function alpha = bounds(this, p)\r\n % Calculates the confidence interval for a given confidence p\r\n % Only works for d=2 so far.\r\n % Parameters:\r\n % p (scalar)\r\n % confidence to achieve, 00)\r\n assert(p<1)\r\n f = @(phi) this.pdf([cos(phi); sin(phi)]);\r\n mB = this.mode();\r\n mBangle = atan2(mB(2), mB(1));\r\n g = @(alpha) integral(f,mBangle,mBangle+alpha, 'AbsTol', 0.01) - p/2;\r\n alpha = fsolve(g, 0.1, optimset('display', 'none'));\r\n else\r\n error('unsupported dimension');\r\n end\r\n end\r\n \r\n function P = gaussianCovariance(this, angle)\r\n % Calculates the covariance to obtain a comparable Gaussian.\r\n % Attention: this does not compute the covariance of the entire\r\n % Bingham but only on the half sphere!\r\n %\r\n % Returns:\r\n % P (1 x 1 matrix for d=2, if angle = true (angle represenation)\r\n % d x d matrix for d>=2, if angle = false (vector\r\n % representation)\r\n arguments\r\n this (1,1) BinghamDistribution\r\n angle = false\r\n end\r\n if angle\r\n assert(this.dim==2)\r\n m = this.mode();\r\n mAngle = atan2(m(2),m(1));\r\n \r\n % sample-based solution:\r\n % samples = this.sample(1000);\r\n % sampleAngles = atan2(samples(:,2), samples(:,1));\r\n % sampleAngles = mod(sampleAngles + pi/2 + mAngle, pi);\r\n % P = cov(sampleAngles);\r\n \r\n % numerical-integration-based solution\r\n P = 2*integral(@(phi) this.pdf([cos(mAngle+phi);sin(mAngle+phi)]).*phi.^2, -pi/2, +pi/2);\r\n else\r\n if this.dim==2\r\n % numerical-integration-based solution:\r\n m = this.mode();\r\n mAngle = atan2(m(2),m(1));\r\n fx = @(phi) 2*this.pdf([cos(phi);sin(phi)]).*(cos(phi)-m(1)).^2;\r\n fxy = @(phi) 2*this.pdf([cos(phi);sin(phi)]).*(cos(phi)-m(1)).*(sin(phi)-m(2));\r\n fy = @(phi) 2*this.pdf([cos(phi);sin(phi)]).*(sin(phi)-m(2)).^2;\r\n P(1,1) = integral(fx, mAngle-pi/2, mAngle+pi/2);\r\n P(1,2) = integral(fxy, mAngle-pi/2, mAngle+pi/2);\r\n P(2,1) = P(1,2);\r\n P(2,2) = integral(fy, mAngle-pi/2, mAngle+pi/2);\r\n else\r\n count = 1000;\r\n samples = this.sample(count);\r\n for i=1:count\r\n if samples(:,i)'*this.mode()<0 %scalar product\r\n samples(:,i)=-samples(:,i);\r\n end\r\n end\r\n %P = cov(samples);\r\n % do not use cov, because the mean of the Gaussian will\r\n % be at the mode of the Bingham, not at the mean of the\r\n % samples\r\n samples = samples - repmat(this.mode(), 1, count);\r\n P = samples*samples'/count;\r\n end\r\n end\r\n end\r\n end\r\n \r\n methods (Static)\r\n function F = computeF(Z, mode)\r\n % Compute normalization constant\r\n % Parameters:\r\n % Z (d x d matrix)\r\n % concentration matrix\r\n % mode (string, optional)\r\n % choses the algorithm to compute the normalization constant\r\n % Returns:\r\n % F (scalar)\r\n % the calculated normalization constant\r\n assert(size(Z,2) == 1);\r\n dim = length(Z);\r\n \r\n if nargin<2\r\n mode = 'default';\r\n end\r\n \r\n if dim == 2\r\n if strcmp(mode, 'default') || strcmp(mode, 'bessel')\r\n % Gerhard Kurz, Igor Gilitschenski, Simon Julier, Uwe D. Hanebeck,\r\n % Recursive Bingham Filter for Directional Estimation Involving 180 Degree Symmetry\r\n % Journal of Advances in Information Fusion, 9(2):90 - 105, December 2014.\r\n F = exp(Z(2))* BinghamDistribution.S2 * besseli(0,(Z(1)-Z(2))/2) * exp((Z(1)-Z(2))/2);\r\n elseif strcmp(mode, 'hypergeom')\r\n % Gerhard Kurz, Igor Gilitschenski, Simon J. Julier, Uwe D. Hanebeck,\r\n % Recursive Estimation of Orientation Based on the Bingham Distribution\r\n % Proceedings of the 16th International Conference on Information Fusion (Fusion 2013), Istanbul, Turkey, July 2013.\r\n F = exp(Z(2))* BinghamDistribution.S2 * double(hypergeom(0.5,1, vpa(Z(1)-Z(2))));\r\n elseif strcmp(mode, 'mhg')\r\n % Koev, P. & Edelman, A.\r\n % The Efficient Evaluation of the Hypergeometric Function of a Matrix Argument\r\n % Mathematics of Computation., 2006, 75, 833-846\r\n F = BinghamDistribution.S2 * mhg(100, 2, 0.5, dim/2, Z);\r\n elseif strcmp(mode, 'saddlepoint')\r\n % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck,\r\n % Efficient Bingham Filtering based on Saddlepoint Approximations\r\n % Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014.\r\n F = numericalSaddlepointWithDerivatives(sort(-Z)+1)*exp(1);\r\n F = F(3);\r\n elseif strcmp(mode, 'glover')\r\n % https://code.google.com/p/bingham/\r\n % and\r\n %\r\n % Glover, J. & Kaelbling, L. P.\r\n % Tracking 3-D Rotations with the Quaternion Bingham Filter\r\n % MIT, 2013\r\n % http://dspace.mit.edu/handle/1721.1/78248\r\n \r\n F = glover(Z);\r\n else\r\n error('unsupported mode');\r\n end\r\n else\r\n if strcmp(mode, 'default') || strcmp(mode, 'saddlepoint')\r\n % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck,\r\n % Efficient Bingham Filtering based on Saddlepoint Approximations\r\n % Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014.\r\n F = numericalSaddlepointWithDerivatives(sort(-Z)+1)*exp(1);\r\n F = F(3);\r\n elseif strcmp(mode, 'mhg')\r\n % Koev, P. & Edelman, A.\r\n % The Efficient Evaluation of the Hypergeometric Function of a Matrix Argument\r\n % Mathematics of Computation., 2006, 75, 833-846\r\n F = AbstractHypersphericalDistribution.computeUnitSphereSurface(dim) * mhg(100, 2, 0.5, dim/2, Z);\r\n elseif strcmp(mode, 'wood') && dim == 4\r\n % ANDREW T.A. WOOD\r\n % ESTIMATION OF THE CONCENTRATION PARAMETERS\r\n % OF THE FISHER MATRIX DISTRIBUTION ON SO(3)\r\n % AND THE BINGHAM DISTRIBUTION ON Sq, q>= 2\r\n % Austral. J. Statist., S5(1), 1993, 69-79\r\n J = @(Z,u) besseli(0, 0.5 .* abs(Z(1)-Z(2)) .* u) .* besseli(0, 0.5 .* abs(Z(3)-Z(4)) .* (1-u));\r\n ifun = @(u) J(Z,u).*exp(0.5 .* (Z(1)+Z(2)).* u + 0.5.*(Z(3)+Z(4)).*(1-u));\r\n F = 2*pi^2*integral(ifun,0,1);\r\n elseif strcmp(mode, 'glover') && dim <= 4\r\n % https://code.google.com/p/bingham/\r\n % and\r\n %\r\n % Glover, J. & Kaelbling, L. P.\r\n % Tracking 3-D Rotations with the Quaternion Bingham Filter\r\n % MIT, 2013\r\n % http://dspace.mit.edu/handle/1721.1/78248\r\n \r\n if any(abs(Z(1:end-1))<1e-8)\r\n warning('Glover''s method currently does not work for Z with more than one zero entry.');\r\n end\r\n \r\n F = glover(Z);\r\n else\r\n error('unsupported mode');\r\n end\r\n end\r\n end\r\n \r\n %todo: add glover?\r\n \r\n function dF = computeDF(Z, mode)\r\n % Partial derivatives of normalization constant\r\n % Parameters:\r\n % Z (d x d matrix)\r\n % concentration matrix\r\n % Returns:\r\n % dF (scalar)\r\n % the calculated derivative of the normalization constant\r\n assert(size(Z,2) == 1);\r\n \r\n dim = size(Z,1);\r\n dF = zeros(1,dim);\r\n \r\n if nargin<2\r\n mode = 'default';\r\n end\r\n \r\n if dim==2\r\n if strcmp(mode, 'default') || strcmp(mode, 'bessel')\r\n % Gerhard Kurz, Igor Gilitschenski, Simon Julier, Uwe D. Hanebeck,\r\n % Recursive Bingham Filter for Directional Estimation Involving 180 Degree Symmetry\r\n % Journal of Advances in Information Fusion, 9(2):90 - 105, December 2014.\r\n b1 = besseli(1,(Z(1)-Z(2))/2);\r\n b0 = besseli(0,(Z(1)-Z(2))/2);\r\n dF(1) = BinghamDistribution.S2/2 * (b1 + b0)* exp((Z(1)+Z(2))/2);\r\n dF(2) = BinghamDistribution.S2/2 * (-b1 + b0 )* exp((Z(1)+Z(2))/2);\r\n elseif strcmp(mode, 'hypergeom')\r\n % Gerhard Kurz, Igor Gilitschenski, Simon J. Julier, Uwe D. Hanebeck,\r\n % Recursive Estimation of Orientation Based on the Bingham Distribution\r\n % Proceedings of the 16th International Conference on Information Fusion (Fusion 2013), Istanbul, Turkey, July 2013.\r\n h = double(hypergeom(1.5,2,vpa(Z(1)-Z(2))));\r\n dF(1) = BinghamDistribution.S2 * exp(Z(2)) * 0.5 * h;\r\n dF(2) = BinghamDistribution.S2 * exp(Z(2)) * (double(hypergeom(0.5,1, vpa(Z(1)-Z(2)))) - 0.5*h);\r\n elseif strcmp(mode, 'saddlepoint')\r\n % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck,\r\n % Efficient Bingham Filtering based on Saddlepoint Approximations\r\n % Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014.\r\n for i=1:dim\r\n ModZ = Z([1:i i i:dim]);\r\n T = numericalSaddlepointWithDerivatives(sort(-ModZ)+1)*exp(1)/(2*pi);\r\n dF(i) = T(3);\r\n end\r\n elseif strncmp(mode, 'finitedifferences', 17)\r\n % Approximation by finite Differences\r\n % use mode='finitedifferences-method', where method\r\n % is a method for calculating the normalizaton\r\n % constant\r\n for i=1:dim\r\n epsilon=0.001;\r\n dZ = [zeros(i-1,1); epsilon; zeros(dim-i,1)];\r\n F1 = BinghamDistribution.computeF(Z + dZ, mode(19:end));\r\n F2 = BinghamDistribution.computeF(Z - dZ, mode(19:end));\r\n dF(i) = (F1-F2)/(2*epsilon);\r\n end\r\n else\r\n error('unsupported mode');\r\n end\r\n else\r\n if strcmp(mode, 'default') || strcmp(mode, 'saddlepoint')\r\n % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck,\r\n % Efficient Bingham Filtering based on Saddlepoint Approximations\r\n % Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014.\r\n for i=1:dim\r\n ModZ = Z([1:i i i:dim]);\r\n T = numericalSaddlepointWithDerivatives(sort(-ModZ)+1)*exp(1)/(2*pi);\r\n dF(i) = T(3);\r\n end\r\n elseif strncmp(mode, 'finitedifferences', 17)\r\n for i=1:dim\r\n % Approximation by finite differences\r\n % use mode='finitedifferences-method', where method\r\n % is a method for calculating the normalizaton\r\n % constant\r\n epsilon=0.001;\r\n dZ = [zeros(i-1,1); epsilon; zeros(dim-i,1)];\r\n F1 = BinghamDistribution.computeF(Z + dZ, mode(19:end));\r\n F2 = BinghamDistribution.computeF(Z - dZ, mode(19:end));\r\n dF(i) = (F1-F2)/(2*epsilon);\r\n end\r\n else\r\n error('unsupported mode');\r\n end\r\n end\r\n end\r\n \r\n function B = fit(samples, weights, options)\r\n % Fits Bingham parameters to a set of samples\r\n % Parameters:\r\n % samples (d x n matrix)\r\n % matrix that contains one sample per column\r\n % weights (1 x n row vector)\r\n % weight for each sample\r\n % options (struct)\r\n % parameter to select the MLE algorithm\r\n % Returns:\r\n % B (BinghamDistribution)\r\n % the MLE estimate for a Bingham distribution given the\r\n % samples\r\n n = size(samples,2);\r\n if nargin<2\r\n C = samples*samples'/n;\r\n else\r\n assert(abs(sum(weights)-1) < 1E-10, 'weights must sum to 1'); %check normalization\r\n assert(size(weights,1)==1, 'weights needs to be a row vector');\r\n assert(size(weights,2)==n, 'number of weights and samples needs to match');\r\n C = samples.*weights*samples';\r\n end\r\n \r\n C = (C+C')/2; % ensure symmetry\r\n \r\n if nargin<3\r\n B = BinghamDistribution.fitToMoment(C);\r\n else\r\n B = BinghamDistribution.fitToMoment(C, options);\r\n end\r\n end\r\n \r\n function B = fitToMoment(S, options)\r\n % Finds a Bingham distribution with a given second moment\r\n %\r\n % Parameters:\r\n %\tS (d x d matrix)\r\n % matrix representing second moment.\r\n % options (struct)\r\n % parameters to configure the MLE algorithm\r\n % Returns:\r\n % B (BinghamDistribution)\r\n % the MLE estimate for a Bingham distribution given the\r\n % scatter matrix S\r\n \r\n assert(all(all(S == S')), 'S must be symmetric');\r\n if nargin < 2\r\n options.algorithm = 'default';\r\n end\r\n \r\n assert(isfield(options,'algorithm'), ...\r\n 'Options need to contain an algorithm field');\r\n \r\n if strcmp(options.algorithm, 'default') || strcmp(options.algorithm, 'fsolve')\r\n % Gerhard Kurz, Igor Gilitschenski, Simon Julier, Uwe D. Hanebeck,\r\n % Recursive Bingham Filter for Directional Estimation Involving 180 Degree Symmetry\r\n % Journal of Advances in Information Fusion, 9(2):90 - 105, December 2014.\r\n [eigenvectors,omega] = eig(S);\r\n [omega, order] = sort(diag(omega),'ascend'); % sort eigenvalues\r\n M_ = eigenvectors(:,order); % swap columns to match the sorted eigenvalues\r\n omega = omega / sum(omega); % ensure that entries sum to one\r\n Z_ = BinghamDistribution.mleFsolve(omega, options);\r\n \r\n % This reordering shouldn't be necessary. However, it can\r\n % become necessary as a consequence of numerical errors when\r\n % fitting to moment matrices with almost equal eigenvalues.\r\n [Z_, order] = sort(Z_,'ascend'); %sort eigenvalues\r\n M_ = M_(:,order);\r\n Z_=Z_-Z_(size(Z_,1)); %subtract last entry to ensure that last entry is zero\r\n B = BinghamDistribution(Z_,M_);\r\n elseif strcmp(options.algorithm, 'fminunc')\r\n [eigenvectors,omega] = eig(S);\r\n [omega, order] = sort(diag(omega),'ascend'); % sort eigenvalues\r\n M_ = eigenvectors(:,order); % swap columns to match the sorted eigenvalues\r\n omega = omega / sum(omega); % ensure that entries sum to one\r\n Z_ = BinghamDistribution.mleFminunc(omega, options);\r\n \r\n % This reordering shouldn't be necessary. However, it can\r\n % become necessary as a consequence of numerical errors when\r\n % fitting to moment matrices with almost equal eigenvalues.\r\n [Z_, order] = sort(Z_,'ascend'); %sort eigenvalues\r\n M_ = M_(:,order);\r\n Z_=Z_-Z_(size(Z_,1)); %subtract last entry to ensure that last entry is zero\r\n B = BinghamDistribution(Z_,M_);\r\n elseif strcmp(options.algorithm, 'gaussnewton')\r\n % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck,\r\n % Efficient Bingham Filtering based on Saddlepoint Approximations\r\n % Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014.\r\n [eigenvectors,omega] = eig(S);\r\n [omega, order] = sort(diag(omega),'ascend'); %sort eigenvalues\r\n M_ = eigenvectors(:,order); %swap columns to match the sorted eigenvalues\r\n omega = omega / sum(omega); % ensure that entries sum to one\r\n Z_ = numericalBinghamMLE(omega);\r\n \r\n % This reordering shouldn't be necessary. However, it can\r\n % become necessary as a consequence of numerical errors when\r\n % fitting to moment matrices with almost equal eigenvalues.\r\n [Z_, order] = sort(Z_,'ascend'); %sort eigenvalues\r\n M_ = M_(:,order);\r\n Z_=Z_-Z_(size(Z_,1)); %subtract last entry to ensure that last entry is zero\r\n B = BinghamDistribution(Z_,M_);\r\n else\r\n error('Unsupported estimation algorithm');\r\n end\r\n end\r\n \r\n function Z = mleFsolve (omega, options)\r\n % Calculate maximum likelihood estimate of Z.\r\n % Considers only the first three values of omega.\r\n %\r\n % Parameters:\r\n % omega (d x 1 column vector)\r\n % eigenvalues of the scatter matrix\r\n % Returns:\r\n % Z (d x 1 column vector)\r\n \r\n if nargin < 2 || ~isfield(options, 'Fmethod')\r\n options.Fmethod = 'default';\r\n end\r\n \r\n if nargin < 2 || ~isfield(options, 'dFmethod')\r\n options.dFmethod = 'default';\r\n end\r\n \r\n function r = mleGoalFun(z, rhs)\r\n % objective function of MLE.\r\n d = size(z,1)+1;\r\n \r\n %if d == 2\r\n a = BinghamDistribution.computeF([z;0], options.Fmethod);\r\n b = BinghamDistribution.computeDF([z;0], options.dFmethod);\r\n %else\r\n % [a,b] = numericalSaddlepointWithDerivatives([-z; 0]);\r\n % a = a(3);\r\n % b = b(3,:);\r\n %end\r\n \r\n r = zeros(d-1,1);\r\n for i=1:(d-1)\r\n r(i) = b(i)/a - rhs(i);\r\n end\r\n end\r\n \r\n dim = size(omega,1);\r\n \r\n f = @(z) mleGoalFun(z, omega);\r\n Z = fsolve(f, -ones(dim-1,1), optimset('display', 'off', 'algorithm', 'levenberg-marquardt'));\r\n Z = [Z; 0];\r\n end\r\n \r\n function Z = mleFminunc (omega, options)\r\n % Calculate maximum likelihood estimate of Z.\r\n % Considers all four values of omega.\r\n %\r\n % Parameters:\r\n % omega (d x 1 column vector)\r\n % eigenvalues of the scatter matrix\r\n % Returns:\r\n % Z (d x 1 column vector)\r\n \r\n if nargin < 2 || ~isfield(options, 'Fmethod')\r\n options.Fmethod = 'default';\r\n end\r\n \r\n if nargin < 2 || ~isfield(options, 'dFmethod')\r\n options.dFmethod = 'default';\r\n end\r\n \r\n function r = mleGoalFun(z, rhs)\r\n % objective function of MLE.\r\n d = size(z,1)+1;\r\n \r\n %if d == 2\r\n a = BinghamDistribution.computeF([z;0], options.Fmethod);\r\n b = BinghamDistribution.computeDF([z;0], options.dFmethod);\r\n %else\r\n % [a,b] = numericalSaddlepointWithDerivatives([-z; 0]);\r\n % a = a(3);\r\n % b = b(3,:);\r\n %end\r\n \r\n r = zeros(d,1);\r\n for i=1:d\r\n r(i) = b(i)/a - rhs(i);\r\n end\r\n r=norm(r);\r\n end\r\n \r\n dim = size(omega,1);\r\n \r\n f = @(z) mleGoalFun(z, omega);\r\n Z = fminunc(f, -ones(dim-1,1), optimoptions('fminunc','algorithm','quasi-newton', 'display', 'off'));\r\n Z = [Z; 0];\r\n end\r\n end\r\nend\r\n\r\nfunction P = acgpdf_pcs(X,z,M) %taken from libBingham\r\n %P = acgpdf_pcs(X,z,;) -- z and M are the sqrt(eigenvalues) and\r\n %eigenvectors of the covariance matrix; x's are in the rows of X\r\n\r\n S_inv = M*diag(1./(z.^2))*M';\r\n\r\n d = size(X,2);\r\n P = repmat(1 / (prod(z) * BinghamDistribution.computeUnitSphereSurface(d)), [size(X,1),1]);\r\n md = sum((X*S_inv).*X, 2); % mahalanobis distance\r\n P = P .* md.^(-d/2);\r\nend\r\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "circVMcdf.m", "ext": ".m", "path": "libDirectional-master/lib/external/circVMcdf.m", "size": 2511, "source_encoding": "utf_8", "md5": "02fe9e452bc8b1c42bd0b222292d3062", "text": "function res = circVMcdf(T,VK)\r\n%circVMcdf cumulative Von-Mises distribution VM(0,k)\r\n% res = circVMcdf(T,VK)\r\n% T - angles at which to compute CDF\r\n% VK - kappa value for distribution\r\n%\r\n% Directly converted from Fortran code published in\r\n%\r\n% Algorithm 518: Incomplete Bessel Function I0.\r\n% The Von Mises Distribution [S14]\r\n% ACM Transactions on Mathematical Software (TOMS)\r\n% Volume 3 , Issue 3 (September 1977)\r\n% Pages: 279 - 284\r\n% Author: Geoffrey W. Hill\r\n%\r\n% (A BibTeX citation is in a comment at the end of this file)\r\n%\r\n% By Shai Revzen, Berkeley 2006\r\n% Modified by Gerhard Kurz, KIT 2015\r\n\r\n\r\n % 8 digit accuracy\r\n % CK = 10.5;\r\n % 12 digit accuracy\r\n CK = 50;\r\n\r\n if length(VK) ~= 1\r\n error('circ:mustBeScalar','kurtosis must be a scalar')\r\n end\r\n %T = T-mu;\r\n Z = VK;\r\n U = mod(T+pi,2*pi);\r\n Y = U-pi;\r\n if Z>CK\r\n res = largeVK(Y, Z);\r\n elseif Z<=0\r\n res = (U*0.5)/pi;\r\n else\r\n V = smallVK(Y, Z);\r\n res = (U*0.5+V)/pi;\r\n end\r\n res(res<0)=0;\r\n res(res>1)=1;\r\nend\r\n\r\nfunction V = smallVK( Y, Z )\r\n % 8 digit accuracy\r\n %A1 = 12; A2 = 0.8; A3 = 8.0; A4 = 1.0; \r\n % 12 digit accuracy \r\n A1 = 28; A2 = 0.5; A3 = 100.0; A4 = 5.0; \r\n \r\n IP = Z*A2 - A3/(Z+A4) + A1;\r\n P = round(IP);\r\n S = sin(Y);\r\n C = cos(Y);\r\n Y = P*Y;\r\n SN = sin(Y);\r\n CN = cos(Y);\r\n R = 0.0;\r\n V = 0.0;\r\n Z = 2.0/Z;\r\n for N=2:round(IP)\r\n P = P - 1.0;\r\n Y = SN;\r\n SN = SN.*C - CN.*S;\r\n CN = CN.*C + Y.*S;\r\n R = 1.0./(P*Z+R);\r\n V = (SN./P+V)*R;\r\n end\r\nend\r\n\r\nfunction res = largeVK( Y, Z )\r\n % 8 digit accuracy\r\n % C1 = 56;\r\n % 12 digit accuracy\r\n C1 = 50.1;\r\n\r\n C = 24.0 * Z;\r\n V = C - C1;\r\n R=sqrt((54.0/(347.0/V+26.0-C)-6.0+C)/12.0);\r\n Z=sin(Y*0.5)*R;\r\n S=Z.*Z*2.0;\r\n V = V - S + 3.0;\r\n Y = (C-S-S-16.0)/3.0;\r\n Y = ((S+1.75)*S+83.5)/V - Y;\r\n res=erf(Z-S/(Y.*Y).*Z)*0.5+0.5;\r\nend\r\n\r\n% BibTeX:\r\n% @article{355753,\r\n% author = {Geoffrey W. Hill},\r\n% title = {Algorithm 518: Incomplete Bessel Function I0.\r\n% The Von Mises Distribution [S14]},\r\n% journal = {ACM Trans. Math. Softw.},\r\n% volume = {3},\r\n% number = {3},\r\n% year = {1977},\r\n% issn = {0098-3500},\r\n% pages = {279--284},\r\n% doi = {http://doi.acm.org/10.1145/355744.355753},\r\n% publisher = {ACM Press},\r\n% address = {New York, NY, USA},\r\n% }"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "wigner3jm.m", "ext": ".m", "path": "libDirectional-master/lib/external/slepian_alpha/wigner3jm.m", "size": 13476, "source_encoding": "utf_8", "md5": "a051e6ecc6ac2a6461d55afb9277a876", "text": "function [w3j,j]=wigner3jm(L,l2,l3,m1,m2,m3)\n% [w3j,j]=WIGNER3JM(L,l2,l3,m1,m2,m3)\n%\n% Calculates Wigner 3j symbols by recursion, for all values of j<=L\n% allowed in the expression (L l2 l3)\n% (m1 m2 m3)\n% There is no truncation at any bandwidth - they are all returned\n% Note the selection rules:\n% jmin = max(|l2-l3|, |m1|)\n% jmax = l2 + l3\n% m1 + m2 + m3 = 0. \n%\n% INPUT:\n%\n% L Maximum degree, bandwidth [default: that what's allowed]\n% l2,l3 Other degrees in the symbol above, don't have to be integers\n% m1,m2,m3 Orders in the symbol above, don't have to be integers, and\n% note that the defaults here are not zero!\n%\n% OUTPUT:\n%\n% w3j The Wigner3j function\n% j The first degrees from 0 to L\n% With normalization check\n%\n% EXAMPLES:\n% \n% wigner3jm('demo1') % Should return nothing if it all works\n% wigner3jm('demo2') % Reproduces Table I of Schulten and Gordon\n%\n% See also: WIGNER0J, GUSEINOV, THREEJ, ZEROJ\n%\n% Last modified by fjsimons-at-alum.mit.edu, 06/15/2010\n% Last modified by Florian Pfaff for libDirectional, 11/04/2016\n\n% Note, if you truncate, like here, at the degree L, you're actually\n% doing too much work; you could improve this.\n\n% After Fortran (could you tell?) by Mark Wieczorek, who further notes:\n% Returned values have a relative error less than ~1.d-8 when l2 and l3 are\n% less than 103 (see below). In practice, this routine is probably usable up\n% to 165. This routine is based upon the stable non-linear recurrence\n% relations of Luscombe and Luban (1998) for the \"non classical\" regions near\n% jmin and jmax. For the classical region, the standard three term recursion\n% relationship is used (Schulten and Gordon 1975). Note that this three term\n% recursion can be unstable and can also lead to overflows. Thus the values\n% are rescaled by a factor \"scalef\" whenever the absolute value of the 3j\n% coefficient becomes greater than unity. Also, the direction of the iteration\n% starts from low values of j to high values, but when abs(w3j(j+2)/w3j(j)) is\n% less than one, the iteration will restart from high to low values. More\n% efficient algorithms might be found for specific cases (for instance, when\n% all m's are zero).\n\n% Verification: \n\n% The results have been verified against this routine run in quadruple\n% precision. For 1.e7 acceptable random values of l2, l3, m2, and m3 between\n% -200 and 200, the relative error was calculated only for those 3j\n% coefficients that had an absolute value greater than 1.d-17 (values smaller\n% than this are for all practical purposed zero, and can be heavily affected\n% by machine roundoff errors or underflow). 853 combinations of parameters\n% were found to have relative errors greater than 1.d-8. Here I list the\n% minimum value of max(l2,l3) for different ranges of error, as well as the\n% number of times this occured 1.d-7 < error <=1.d-8 = 103 # = 483 1.d-6 <\n% error <= 1.d-7 = 116 # = 240 1.d-5 < error <= 1.d-6 = 165 # = 93 1.d-4 <\n% error <= 1.d-5 = 167 # = 36\n\n% Many times (maybe always), the large relative errors occur when the 3j\n% coefficient changes sign and is close to zero. (I.e., adjacent values are\n% about 10.e7 times greater in magnitude.) Thus, if one does not need to know\n% highly accurate values of the 3j coefficients when they are almost zero\n% (i.e., ~1.d-10) then this routine is probably usable up to about 160.\n\n% These results have also been verified for parameter values less than 100\n% using a code based on the algorithm of de Blanc (1987), which was originally\n% coded by Olav van Genabeek, and modified by M. Fang (note that this code was\n% run in quadruple precision, and only calculates one coefficient for each\n% call. I also have no idea if this code was verified.) Maximum relative\n% errors in this case were less than 1.d-8 for a large number of values\n% (again, only 3j coefficients greater than 1.d-17 were considered here). The\n% biggest improvement that could be made in this routine is to determine when\n% one should stop iterating in the forward direction, and start iterating from\n% high to low values.\n\nif ~ischar(L)\n switch nargin\n case 0\n l2=6;l3=5;\n L=l2+l3;\n m1=3;m2=2;m3=-5;\n case 1\n l2=6;l3=5;\n m1=3;m2=2;m3=-5;\n case 2\n l3=5;\n m1=3;m2=2;m3=-5; \n case 3\n m1=3;m2=2;m3=-5; \n case 4\n m2=2;m3=-5;\n case 5\n m3=-5; \n end\n flag1=0;\n flag2=0;\n\n % Didn't realize this factor was wrong until 10/02/2006\n % But - Luscombe and Luban imply that the three-term recursion in the\n % classical, oscillatory region rarely suffers from the overflows - all\n % should be probably well\n scalef=1000;\n\n jmin=max(abs(l2-l3),abs(m1));\n jmax=l2+l3;\n jnum=jmax-jmin+1;\n\n % Initialize\n w3j=zeros(1,jnum);\n if abs(m2)>l2 || abs(m3)>l3\n w3j=zeros(L+1,1)';\n j=0:L; return\n elseif m1+m2+m3~=0 \n w3j=zeros(L+1,1)';\n j=0:L; return\n elseif jmax0) || ...\n\t (w3j>0 && (-1)^(l2-l3+m2+m3)<0)\n w3j=-w3j;\n end\n [w3j,j]=output(jmin,l2,l3,L,w3j); return\n end\n\n % Calculate lower non-classical values for [jmin, jn]. If the second\n % term can not be calculated because the recursion relationsips give\n % rise to a 1/0, then set flag1 to 1. If all m's are zero, then this\n % is not a problem as all odd terms must be zero.\n\n \n [rs,wu,wl]=deal(0);\n\n warning off\n rs(1)=-x(jmin,l2,l3,m1)/y(jmin,l2,l3,m1,m2,m3);\n warning on\n\n if m1==0 && m2==0 && m3==0\n wl(1)=1;\n wl(2)=0;\n jn=jmin+1;\n elseif y(jmin,l2,l3,m1,m2,m3)==0\n if x(jmin,l2,l3,m1)==0\n flag1=1;\n jn=jmin;\n else\n wl(1)=1;\n wl(2)=0;\n jn=jmin+1;\n end\n elseif rs(1)<=0\n wl(1)=1;\n wl(2)=-y(jmin,l2,l3,m1,m2,m3)/x(jmin,l2,l3,m1);\n jn=jmin+1;\n else\n jn=jmax;\n for j=jmin+1:jmax-1\n denom=y(j,l2,l3,m1,m2,m3)+z(j,l2,l3,m1)*rs(j-jmin);\n warning off\n rs(j-jmin+1)=-x(j,l2,l3,m1)/denom;\n warning on\n if (rs(j-jmin+1)>1 || rs(j-jmin+1) <= 0 || denom==0) \n\tjn=j-1;\n\tbreak\n end\n end\n \n wl(jn-jmin+1)=1;\n \n for k=1:jn-jmin\n wl(jn-k-jmin+1)=wl(jn-k-jmin+2)*rs(jn-k-jmin+1);\n end\n if (jn==jmin) \t\t\t\t\t\n wl(2)=-y(jmin,l2,l3,m1,m2,m3)/x(jmin,l2,l3,m1);\n jn=jmin+1;\n end\n end\n\n if jn==jmax\n w3j(1:jnum)=wl(1:jnum);\n w3j=normw3j(w3j,jmin,jmax,jnum);\n w3j=fixsign(w3j,jnum,l2,l3,m2,m3);\n [w3j,j]=output(jmin,l2,l3,L,w3j); return\n end\n\n % Calculate upper non-classical values for [jp, jmax].\n % If the second last term can not be calculated because the\n % recursion relations give a 1/0, then set flag2 to 1. \n\n warning off\n rs(jnum)=-z(jmax,l2,l3,m1)/y(jmax,l2,l3,m1,m2,m3);\n warning on\n\n if m1==0 && m2==0 && m3==0\n wu(jnum)=1;\n wu(jmax-jmin)=0;\n jp=jmax-1;\n elseif y(jmax,l2,l3,m1,m2,m3)==0\n if z(jmax,l2,l3,m1)==0\n flag2=1;\n jp=jmax;\n else\n wu(jnum)=1;\n wu(jmax-jmin)=-y(jmax,l2,l3,m1,m2,m3)/z(jmax,l2,l3,m1);\n jp=jmax-1;\n end\n elseif rs(jnum)<=0 \n wu(jnum)=1;\n wu(jmax-jmin)=-y(jmax,l2,l3,m1,m2,m3)/z(jmax,l2,l3,m1);\n jp=jmax-1;\n else\n jp=jmin;\n for j=jmax-1:-1:jn\n % This appears to be Luscombe and Luban's Eq. (2)\n denom=y(j,l2,l3,m1,m2,m3)+x(j,l2,l3,m1)*rs(j-jmin+2);\n warning off\n rs(j-jmin+1)=-z(j,l2,l3,m1)/denom;\n warning on\n if (rs(j-jmin+1)>1 || rs(j-jmin+1) <= 0 || denom==0)\n\tjp=j+1;\n\tbreak\n end\n end\t\n wu(jp-jmin+1)=1;\n for k=1:jmax-jp\n wu(jp+k-jmin+1)=wu(jp+k-jmin)*rs(jp+k-jmin+1);\n end\n \n if jp==jmax\n wu(jmax-jmin)=-y(jmax,l2,l3,m1,m2,m3)/z(jmax,l2,l3,m1);\n jp=jmax-1;\n end\n end\n\n % Calculate classical terms for [jn+1, jp-1] using standard three term\n % rercusion relationship. Start from both jn and jp and stop at the\n % midpoint. If flag1 is set, then perform the recursion solely from\n % high to low values. If flag2 is set, then perform the recursion\n % solely from low to high.\n\n if flag1==0\n % I think Fortran rounds like this\n jmid=round((jn+jp)/2);\n \n for j=jn:jmid-1\n wl(j-jmin+2)=-(z(j,l2,l3,m1)*wl(j-jmin)+...\n\t\t\t y(j,l2,l3,m1,m2,m3)* ...\n\t\t\t wl(j-jmin+1))/x(j,l2,l3,m1); \n if abs(wl(j-jmin+2))>1\n\twl(1:j-jmin+2)=...\n\t wl(1:j-jmin+2)/scalef;\n end\n \n if abs(wl(j-jmin+2)/wl(j-jmin))<1 && ...\n\t wl(j-jmin+2)~=0 \n\tjmid=j+1;\t\t\t\t\n\tbreak\n end\n end\n wnmid=wl(jmid-jmin+1);\n\n warning off\n if abs(wnmid/wl(jmid-jmin))<1e-6 && wl(jmid-jmin)~=0\n wnmid=wl(jmid-jmin);\n jmid=jmid-1;\n end\n warning on\n \n for j=jp:-1:jmid+1\n wu(j-jmin)=-(x(j,l2,l3,m1)*wu(j-jmin+2)+...\n\t\t\t y(j,l2,l3,m1,m2,m3)* ...\n\t\t\t wu(j-jmin+1))/z(j,l2,l3,m1); \n if abs(wu(j-jmin))>1\n\twu(j-jmin:jnum)=...\n\t wu(j-jmin:jnum)/scalef;\n end\n end\n\n wpmid=wu(jmid-jmin+1);\n \n if jmid==jmax\n w3j(1:jnum)=wl(1:jnum);\n elseif jmid==jmin\n w3j(1:jnum)=wu(1:jnum);\n else\n w3j(1:jmid-jmin+1)=wl(1:jmid-jmin+1)*wpmid/wnmid; \n w3j(jmid-jmin+2:jnum)=...\n\t wu(jmid-jmin+2:jnum);\n end\n \n elseif flag1==1 && flag2==0\n for j=jp:-1:jmin+1\n wu(j-jmin)=-(x(j,l2,l3,m1)*wu(j-jmin+2)+...\n\t\t\t y(j,l2,l3,m1,m2,m3)* ...\n\t\t\t wu(j-jmin+1))/z(j,l2,l3,m1); \n if abs(wu(j-jmin))>1\n\twu(j-jmin:jnum)=...\n\t wu(j-jmin:jnum)/scalef;\n end\n end\n \n w3j(1:jnum)=wu(1:jnum);\n \n elseif flag2==1 && flag1==0\n \n for j=jn:jp-1\n wl(j-jmin+2)=-(z(j,l2,l3,m1)*wl(j-jmin)+...\n\t\t\t y(j,l2,l3,m1,m2,m3)* ...\n\t\t\t wl(j-jmin+1))/x(j,l2,l3,m1); \n if abs(wl(j-jmin+2))>1\n\twl(1:j-jmin+2)=...\n\t wl(1:j-jmin+2)/scalef;\n end\n end\n \n w3j(1:jnum)=wl(1:jnum);\n \n elseif flag1==1 && flag2==1\n error('Can not calculate function for input values')\n end\n\n w3j=normw3j(w3j,jmin,jmax,jnum);\n w3j=fixsign(w3j,jnum,l2,l3,m2,m3);\n\n % Output: give output in all degrees from zero to the bandwidth\n if L<=l2+l3\n % Truncate\n w3j=[repmat(0,1,jmin) w3j(1:L-jmin+1)];\n else\n % Append\n w3j=[repmat(0,1,jmin) w3j repmat(0,1,L-l2-l3)];\n end\n j=0:L;\n\n % Perform normalization check\n if L==l2+l3\n norma=sum((2*[0:L]+1).*w3j.^2);\n difer(norma-1,[],[],NaN)\n end\n\nelseif strcmp(L,'demo1')\n difer(wigner3jm(20,10,10,0,0,0)-wigner0j(20,10,10))\n difer(wigner3jm(400,200,200,0,0,0)-wigner0j(400,200,200))\n difer(wigner3jm(40,10,13,0,0,0)-wigner0j(40,10,13))\n difer(indeks(wigner3jm(8,6,5,3,2,-5),'end')-sqrt(42/4199))\n difer(indeks(wigner3jm(8,6,5,3,2,-5),'end-1')-35*sqrt(2/138567))\n difer(indeks(wigner3jm(8,6,5,3,2,-5),'end-2')-7*sqrt(1/2431))\n difer(indeks(wigner3jm(8,6,5,3,2,-5),'end-3')-sqrt(35/2431))\n difer(indeks(wigner3jm(8,6,5,3,2,-5),'end-4')-sqrt(5/858))\n difer(indeks(wigner3jm(3,2,2,1,0,-1),'end')--sqrt(1/35))\n difer(indeks(wigner3jm(0,1,1,0,1,-1),'end')-sqrt(1/3))\n difer(indeks(wigner3jm(1,1,1,0,1,-1),'end')-sqrt(1/6))\n difer(indeks(wigner3jm(2,1,1,0,1,-1),'end')-sqrt(1/30))\n difer(indeks(wigner3jm(3,2,3,-2,0,2),'end')-0)\n difer(indeks(wigner3jm(6,2,4,-4,1,3),'end')-4*sqrt(1/429))\n difer(indeks(wigner3jm(0,1,1,0,0,0),'end')--sqrt(1/3))\n difer(indeks(wigner3jm(2,1,1,0,0,0),'end')-sqrt(2/15))\n difer(indeks(wigner3jm(3,2,3,3,0,-3),'end')-(1/2)*sqrt(5/21))\n difer(indeks(wigner3jm(2,2,3,-2,0,2),'end')--sqrt(1/14))\n difer(indeks(wigner3jm(8,6,5,3,2,-5),'end-5')-sqrt(1/1001))\n difer(indeks(wigner3jm(20,15,9,-3,2,1),'end')+(311/2)*sqrt(115/1231496049))\n difer(indeks(wigner3jm(10,10,12,9,3,-12),'end')--(1/15)*sqrt(4199/9889))\nelseif strcmp(L,'demo2')\n [w,L]=wigner3jm([],9/2,7/2,1,-7/2,5/2);\n disp(sprintf('------------------------------'))\n disp(sprintf('L1 Values of 3j coefficients'))\n disp(sprintf('------------------------------'))\n disp(sprintf('%2.2i %23.16i\\n',[L(2:9)' w(2:9)']'))\n disp(sprintf('------------------------------'))\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [o,p]=output(jmin,l2,l3,L,w3j)\n% Output: give output in all degrees from zero to the bandwidth\n% Perform normalization check before possible completion or truncation\nnorma=sum((2*[jmin:l2+l3]+1).*w3j.^2);\ndifer(norma-1,[],[],NaN)\nif L<=l2+l3\n % Truncate...\n o=[repmat(0,1,jmin) w3j(1:L-jmin+1)];\nelse\n % Append\n o=[repmat(0,1,jmin) w3j repmat(0,1,L-l2-l3)];\nend\np=0:L;\n\n% The following functions are straight from Table I of Luscombe and Luban \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction o=x(j,l2,l3,m1)\t\no=j*a(j+1,l2,l3,m1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction o=y(j,l2,l3,m1,m2,m3)\n% This is the Y-function in Table 1 of Luscombe and Luban\no=-(2*j+1)*(m1*(l2*(l2+1)-l3*(l3+1))-(m3-m2)*j*(j+1));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction o=z(j,l2,l3,m1)\no=(j+1)*a(j,l2,l3,m1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction o=a(j,l2,l3,m1)\no=sqrt((j^2-(l2-l3)^2)*((l2+l3+1)^2-j^2)*(j^2-m1^2));\n\t\t\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction o=normw3j(w3j,jmin,jmax,jnum)\nnormo=0;\nfor j=jmin:jmax\n normo=normo+(2*j+1)*w3j(j-jmin+1)^2;\nend\no(1:jnum)=w3j(1:jnum)/sqrt(normo);\n\t\t\t\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction o=fixsign(w3j,jnum,l2,l3,m2,m3)\nif ((w3j(jnum)<0 & (-1)^(l2-l3+m2+m3)>0) |...\n (w3j(jnum)>0 & (-1)^(l2-l3+m2+m3)<0)) \n o(1:jnum)=-w3j(1:jnum);\nelse\n o(1:jnum)=w3j(1:jnum);\nend\n\t\t\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "xyz2plm.m", "ext": ".m", "path": "libDirectional-master/lib/external/slepian_alpha/xyz2plm.m", "size": 10265, "source_encoding": "utf_8", "md5": "c12b5c4b341a7d4cdc70443ff4bfd698", "text": "function [lmcosi,dw]=xyz2plm(fthph,L,method,lat,lon,cnd)\n% [lmcosi,dw]=XYZ2PLM(fthph,L,method,lat,lon,cnd)\n%\n% Forward real spherical harmonic transform in the 4pi normalized basis.\n%\n% Converts a spatially gridded field into spherical harmonics.\n% For complete and regular spatial samplings [0 360 -90 90].\n% If regularly spaced and complete, do not specify lat,lon.\n% If not regularly spaced, fthph, lat and lon are column vectors.\n%\n% INPUT:\n%\n% fthph Real-valued function whose transform we seek: \n% [1] MxN matrix of values corresponding to a regular grid\n% defined by lat,lon as described below, OR\n% [2] an MNx1 vector of values corrsponding to a set of\n% latitude and longitude values given by lat,lon as below\n% L Maximum degree of the expansion (Nyquist checked)\n% method 'im' By inversion (fast, accurate, preferred),\n% uses FFT on equally spaced longitudes, ok to\n% specify latitudes only as long as nat>=(L+1),\n% note: works with the orthogonality of the\n% cosine/sine of the longitude instead of with\n% the orthogonality of the Legendre polynomials. \n% 'gl' By Gauss-Legendre integration (fast, inaccurate)\n% note: resampling to GL integration points,\n% uses FFT on equally spaced longitudes\n% 'simpson' By Simpson integation (fast, inaccurate),\n% note: requires equidistant latitude spacing,\n% uses FFT on equally spaced longitudes\n% 'irr' By inversion (irregular samplings)\n% 'fib' By Riemann sum on a Fibonacci grid (not done yet)\n% lat Latitude range for the grid or set of function values: \n% [1] if unspecified, we assume [90 -90] and a regular grid\n% [2] 1x2 vector [maximumlatitude minimumlatitude] in degrees\n% [3] an MNx1 vector of values with the explicit latitudes\n% lon Longitude range for the grid or set of function values: \n% [1] if unspecified, we assume [0 360] and a regular grid\n% [2] 1x2 vector [maximumlatitude minimumlatitude] in degrees\n% [3] an MNx1 vector of values with the explicit longitudes\n% cnd Eigenvalue tolerance in the irregular case\n%\n% OUTPUT:\n%\n% lmcosi Matrix listing l,m,cosine and sine coefficients\n% dw Eigenvalue spectrum in the irregular case\n%\n% Note that the MEAN of the input data deviates from C(1), as sampled\n% fields lose the orthogonality. The inversion approaches should recover\n% the exact value of C(1), the true mean of the data, not the sample\n% mean.\n%\n% lmcosi=xyz2plm(ones(randi(100),randi(100))); lmcosi(1,3) is close to one\n%\n% See also PLM2XYZ, PLM2SPEC, PLOTPLM, etc.\n%\n% Previously modified by fjsimons-at-alum.mit.edu, 09/04/2014\n% Last modified by Florian Pfaff for libDirectional, 21/10/2019\narguments \n fthph (:,:) double\n L (1,1) {mustBeInteger} = -1 % Will be overwritten if -1\n method char = 'im'\n lat double = zeros(0,1)\n lon double = zeros(0,1)\n cnd (1,1) double = 1e-6\nend\npersistent legendreCell\nt0=clock;\nif nargin<3 && numel(fthph)>1 % If lat and lon are not given and is only single elementary, enforce matrix\n assert(size(fthph,1)>1 && size(fthph,2)>1);\nelse\n assert(numel(lat)==numel(fthph) && numel(lon)==numel(fthph) || (numel(lat)*numel(lon))==numel(fthph));\nend\n\ndw=[];\n% If no grid is specified, assumes equal spacing and complete grid\nif isempty(lat) && isempty(lon)\n % Test if data is 2D, and periodic over longitude\n fthph=reduntest(fthph);\n polestest(fthph)\n % Make a complete grid\n nlon=size(fthph,2);\n nlat=size(fthph,1);\n % Nyquist wavelength\n Lnyq=min([ceil((nlon-1)/2) nlat-1]);\n % Colatitude and its increment\n theta=linspace(0,pi,nlat);\n canUseSaved=true; % Equally spaced\n % Calculate latitude/longitude sampling interval; no wrap-around left\n dtheta=pi/(nlat-1);\n dphi=2*pi/nlon;\n switch method \n % Even without lat/lon can still choose the full inversion method\n % without Fourier transformation\n case 'irr'\n [LON,LAT]=meshgrid(linspace(0,2*pi*(1-1/nlon),nlon),...\n\t\t\tlinspace(pi/2,-pi/2,nlat));\n lat=LAT(:); lon=LON(:); fthph=fthph(:);\n theta=pi/2-lat;\n clear LON LAT\n end\nelseif isempty(lon)\n % If only latitudes are specified; make equal spacing longitude grid\n % Latitudes can be unequally spaced for 'im', 'irr' and 'gl'.\n canUseSaved=false;\n fthph=reduntest(fthph);\n theta=(90-lat)*pi/180;\n dtheta=(lat(1)-lat(2))*pi/180;\n nlat=length(lat);\n nlon=size(fthph,2);\n dphi=2*pi/nlon;\n Lnyq=min([ceil((nlon-1)/2) ceil(pi/dtheta)]);\nelse\n canUseSaved=false;\n % Irregularly sampled data\n fthph=fthph(:);\n theta=(90-lat)*pi/180;\n lat=lat(:)*pi/180;\n lon=lon(:)*pi/180;\n nlon=length(lon);\n nlat=length(lat);\n % Nyquist wavelength\n adi=[abs(diff(sort(lon))) ; abs(diff(sort(lat)))];\n Lnyq=ceil(pi/min(adi(~~adi)));\n method='irr';\nend\n\n% Decide on the Nyquist frequency\nif L==-1\n L=Lnyq;\nend\n% Never use Libbrecht algorithm... found out it wasn't that good\nlibb=false;\n%disp(sprintf('Lnyq= %i ; expansion out to degree L= %i',Lnyq,L))\n\nif L>Lnyq || nlat<(L+1)\n warning('XYZ2PLM: Function undersampled. Aliasing will occur.')\nend\n\n% Make cosine and sine matrices\n[m,l,mz]=addmon(L);\nlmcosi=[l m zeros(length(l),2)];\n\n% Define evaluation points\nswitch method\n case 'gl'\n % Highest degree of integrand will always be 2*L\n [w,x]=gausslegendrecof(2*L,[],[-1 1]);\n % Function interpolated at Gauss-Legendre latitudes; 2D no help\n fthph=interp1(theta,fthph,acos(x),'spline');\n case {'irr','simpson','im'}\n % Where else to evaluate the Legendre polynomials\n x=cos(theta);\n otherwise\n error('Specify valid method')\nend\n\nif canUseSaved && size(legendreCell,1)>L && size(legendreCell,2)>length(x) && ~isempty(legendreCell{L+1,length(x)+1}) \n Plm=legendreCell{L+1,length(x)+1};\nelse\n mfn=mfilename('fullpath');\n fnpl=fullfile(mfn(1:end-8),'LEGENDRE',sprintf('LSSM-%i-%i.mat',L,length(x))); % Expect in folder of xyz2plm\n \n if exist(fnpl,'file')==2 && canUseSaved\n load(fnpl,'Plm')\n else \n % Evaluate Legendre polynomials at selected points\n Plm=NaN(length(x),addmup(L));\n if L>200\n h=waitbar(0,'Evaluating all Legendre polynomials');\n end\n in1=0;\n in2=1;\n for l=0:L\n if ~libb\n Plm(:,in1+1:in2)=(legendre(l,x(:)','sch')*sqrt(2*l+1))';\n else\n Plm(:,in1+1:in2)=(libbrecht(l,x(:)','sch')*sqrt(2*l+1))';\n end\n in1=in2;\n in2=in1+l+2;\n if L>200\n waitbar((l+1)/(L+1),h)\n end\n end\n if L>200\n delete(h)\n end\n if canUseSaved\n save(fnpl,'Plm')\n end\n end\n if canUseSaved\n legendreCell{L+1,length(x)+1}=Plm;\n disp('Keeping legendre polynomials in memory, call ''clear xyz2plm'' to free memory.');\n end\nend\n\nswitch method\n case {'irr'}\n Plm=[Plm.*cos(lon(:)*m(:)') Plm.*sin(lon(:)*m(:)')];\n % Add these into the sensitivity matrix\n [C,merr,mcov,chi2,L2err,rnk,dw]=datafit(Plm,fthph);\n lmcosi(:,3)=C(1:end/2);\n lmcosi(:,4)=C(end/2+1:end);\n case {'im','gl','simpson'}\n % Perhaps demean the data for Fourier transform\n dem=false;\n if dem\n meanm=mean(fthph,2); %#ok\n fthph=fthph-repmat(meanm,1,nlon);\n end\n \n % Calculate integration over phi by the fast Fourier\n % transform. Integration of real input field with respect to the second\n % dimension of r, at wavenumber m, thus at constant latitude. You get\n % as many wavenumbers m as there are longitudes; only use to L. With\n % Matlab's FFT, need to multiply by sampling interval. \n gfft=dphi*fft(fthph,nlon,2);\n\n if dem\n % Add the azimuthal mean back in there\n gfft(:,1)=2*pi*meanm; %#ok\n end\n\n % Note these things are only half unique - the maximum m is nlon/2\n % But no Nyquist theory exists for the Legendre transform...\n a=real(gfft);\n b=-imag(gfft);\n in1=0;\n in2=1;\n otherwise\n error('Specify valid method')\nend\n\nswitch method\n case 'im'\n % Loop over the orders. This speeds it up versus 'irr'\n for ord=0:L\n a(:,1)=a(:,1)/2;\n b(:,1)=b(:,1)/2;\n Pm=Plm(:,mz(ord+1:end)+ord)*pi;\n [lmcosi(mz(ord+1:end)+ord,3)]=datafit(Pm,a(:,ord+1));\n [lmcosi(mz(ord+1:end)+ord,4)]=datafit(Pm,b(:,ord+1));\n end\n case 'simpson'\n % Loop over the degrees. Could go up to l=nlon if you want\n for l=0:L\n % Integrate over theta using Simpson's rule\n clm=simpson(theta,...\n\t\trepmat(sin(theta(:)),1,l+1).*a(:,1:l+1).*Plm(:,in1+1:in2));\n slm=simpson(theta,...\n\t\trepmat(sin(theta(:)),1,l+1).*b(:,1:l+1).*Plm(:,in1+1: ...\n\t\t\t\t\t\t in2));\n in1=in2;\n in2=in1+l+2;\n % And stick it in a matrix [l m Ccos Csin]\n lmcosi(addmup(l-1)+1:addmup(l),3)=clm(:)/4/pi;\n lmcosi(addmup(l-1)+1:addmup(l),4)=slm(:)/4/pi;\n end\n case 'gl'\n % Loop over the degrees. Could go up to l=nlon if you want\n for l=0:L\n % Integrate over theta using Gauss-Legendre integration\n clm=sum(a(:,1:l+1).*(diag(w)*Plm(:,in1+1:in2)));\n slm=sum(b(:,1:l+1).*(diag(w)*Plm(:,in1+1:in2)));\n in1=in2;\n in2=in1+l+2;\n % And stick it in a matrix [l m Ccos Csin]\n lmcosi(addmup(l-1)+1:addmup(l),3)=clm(:)/4/pi;\n lmcosi(addmup(l-1)+1:addmup(l),4)=slm(:)/4/pi;\n end \nend\n\n% Get rid of machine precision error\nlmcosi(abs(lmcosi(:,3))= size(grd,2)*eps*10\n fprintf('Data violate wrap-around by %8.4e\\n',...\n\t\t sum(abs(grd(:,1)-grd(:,end))));\nend\ngrd=grd(:,1:end-1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction polestest(grd)\n% Tests if poles (-90,90) are identical over longitudes \nvar1=var(grd(1,:));\nvar2=var(grd(end,:));\nif var1>eps*10 || var2>eps*10\n fprintf('Poles violated by %8.4e and %8.4e\\n',var1,var2);\nend\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "project_s3_partition.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/project_s3_partition.m", "size": 7962, "source_encoding": "utf_8", "md5": "1a63325e3e5e2ea8d502ba34b4e06f3c", "text": "function [movie_frame] = project_s3_partition(N,varargin)\n%PROJECT_S3_PARTITION Use projection to illustrate an EQ partition of S^3\n%\n%Syntax\n% [movie_frame] = project_s3_partition(N,options);\n%\n%Description\n% PROJECT_S3_PARTITION(N) uses projection to illustrate the partition of\n% the unit sphere S^3 into N regions.\n%\n% MOVIE_FRAME = PROJECT_S3_PARTITION(N) sets MOVIE_FRAME to be an array of\n% movie frames for use with MOVIE. The movie frames will contain the region by\n% region build-up of the illustration.\n%\n% PROJECT_S3_PARTITION(N,'offset','extra') uses experimental extra offsets.\n% For more detail on partition options, see HELP PARTITION_OPTIONS.\n%\n% PROJECT_S3_PARTITION(N,options) also recognizes a number of illustration\n% options, which are specified as name, value pairs.\n% Any number of pairs can be used, in any order.\n%\n% The following illustration options are used.\n%\n% PROJECT_S3_PARTITION(N,'fontsize',size)\n% Font size used in titles (numeric, default 18).\n%\n% PROJECT_S3_PARTITION(N,'title','long')\n% PROJECT_S3_PARTITION(N,'title','short')\n% Use long or short titles (default 'long').\n%\n% PROJECT_S3_PARTITION(N,'proj','stereo')\n% PROJECT_S3_PARTITION(N,'proj','eqarea')\n% Use stereographic or equal area projection (default 'stereo').\n%\n% PROJECT_S3_PARTITION(N,'points','show')\n% PROJECT_S3_PARTITION(N,'points','hide')\n% Show or hide center points (default 'show').\n%\n% PROJECT_S3_PARTITION(N,'surf','show')\n% PROJECT_S3_PARTITION(N,'surf','hide')\n% Show or hide surfaces of regions (default 'show').\n%\n% For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS.\n%\n%Examples\n% > project_s3_partition(10)\n% > frames=project_s3_partition(9,'offset','extra','proj','eqarea')\n% frames =\n% 1x18 struct array with fields:\n% cdata\n% colormap\n% > project_s3_partition(99,'proj','eqarea','points','hide')\n%\n%See also\n% MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, PROJECT_S2_PARTITION\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Function changed name from s2x to polar2cart\n% Function changed name from x2s2 to cart2polar2\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-13 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\npdefault.extra_offset = false;\n\npopt = partition_options(pdefault, varargin{:});\n\ngdefault.fontsize = 18;\ngdefault.stereo = true;\ngdefault.long_title = true;\ngdefault.show_points = true;\ngdefault.show_surfaces = true;\n\ngopt = illustration_options(gdefault, varargin{:});\n\ndim = 3;\n\n[X,Y,Z] = sphere(90);\nif gopt.stereo\n r = 0;\nelse\n r = (area_of_sphere(dim)/volume_of_ball(dim)).^(1/dim);\nend\n\nhold off\n\nif gopt.show_surfaces\n surf(r*X,r*Y,r*Z,zeros(size(Z)),...\n 'FaceAlpha',1/20,'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\nelse\n plot3(0,0,0,'w.')\nend\naxis equal;hold on\ncamlight right\ncolormap jet\ngrid off\naxis off\n\nif gopt.long_title\n if gopt.stereo\n s = 'Stereographic';\n else\n s = 'Equal volume';\n end\n if gopt.show_points\n pointstr = ', showing the center point of each region';\n else\n pointstr = '';\n end\n\n title(sprintf(...\n '\\n%s projection of recursive zonal equal area partition of {S^3} \\n into %d regions%s.',...\n s,N,pointstr),'FontSize',gopt.fontsize);\nelse\n title(sprintf('\\nEQ(3,%d)',N),'FontSize',gopt.fontsize);\nend\n\naxis equal\ngrid off\naxis off\n\npause(0);\nif nargout > 0\n movie_frame(1) = getframe(gcf);\nend\n\nif gopt.stereo && (N == 1)\n return;\nend\n\nif popt.extra_offset\n [R,dim_1_rot] = eq_regions(dim,N,popt.extra_offset);\nelse\n R = eq_regions(dim,N);\nend\n\nfor i = N:-1:2\n if popt.extra_offset\n project_s3_region(R(:,:,i),N,gopt.stereo,gopt.show_surfaces,dim_1_rot{i});\n else\n project_s3_region(R(:,:,i),N,gopt.stereo,gopt.show_surfaces);\n end\n pause(0);\n if nargout > 0\n movie_frame(N-i+2) = getframe(gcf);\n end\nend\n\nif gopt.show_points\n project_s3_eq_point_set(N,popt.extra_offset,gopt.stereo);\n if nargout > 0\n for k=1:min(N,40)\n movie_frame(N+k) = getframe(gcf);\n end\n end\nend\n\nhold off\n%\n% end function\n\nfunction project_s3_region(region, N, stereo, show_surfaces, rot_matrix)\n%PROJECT_S3_REGION Use projection to illustrate an EQ region of S^3\n%Syntax\n% project_s3_region(region, stereo, show_surfaces, rot_matrix);\n%\n%Notes\n% The region is given as a 3 x 2 matrix in spherical polar coordinates\n%\n% The default is to use stereographic projection\n% If the optional second argument, stereo is false,\n% then use a equal area projection.\n\nif nargin < 3\n stereo = true;\nend\nif stereo\n projection = 'x2stereo';\nelse\n projection = 'x2eqarea';\nend\nif nargin < 4\n show_surfaces = true;\nend\n\noffset_regions = (nargin >= 5);\n\ntol = eps*2^5;\n\ndim = size(region,1);\nt = region(:,1);\nb = region(:,2);\n\nif abs(b(1)) < tol\n b(1) = 2*pi;\nend\npseudo = 0;\nif abs(t(1)) < tol && abs(b(1)-2*pi) < tol\n pseudo = 1;\nend\nn = 33;\ndelta = 1/(n-1);\nh = 0:delta:1;\n[h1, h2] = meshgrid(h,h);\nt_to_b = zeros(dim,n,n);\nb_to_t = t_to_b;\nr = N^(-1/3)/32;\nfor k = 1:dim\n if ~pseudo || k < 3\n L = 1:dim;\n j(L) = mod(k+L,dim)+1;\n t_to_b(j(1),:,:) = t(j(1))+(b(j(1))-t(j(1)))*h1;\n t_to_b(j(2),:,:) = t(j(2))+(b(j(2))-t(j(2)))*h2;\n t_to_b(j(3),:,:) = t(j(3))*ones(n,n);\n t_to_b_v = reshape(t_to_b,dim,n*n);\n if offset_regions\n t_to_b_x = polar2cart([cart2polar2(rot_matrix*polar2cart(t_to_b_v(1:dim-1,:)));t_to_b_v(dim,:)]);\n else\n t_to_b_x = polar2cart(t_to_b_v);\n end\n s = reshape(feval(projection,t_to_b_x),dim,n,n);\n degenerate = (norm(s(:,1,1)-s(:,1,2)) < tol);\n if ~degenerate && (~pseudo || k > 1)\n [X,Y,Z] = fatcurve(squeeze(s(:,1,:)),r);\n surface(X,Y,Z,zeros(size(Z)),...\n 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n axis equal; hold on\n end\n if show_surfaces\n surf(squeeze(s(1,:,:)),squeeze(s(2,:,:)),squeeze(s(3,:,:)),t(3)*ones(n,n),...\n 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n end\n axis equal; hold on\n camlight right\n b_to_t(j(1),:,:) = b(j(1))-(b(j(1))-t(j(1)))*h1;\n b_to_t(j(2),:,:) = b(j(2))-(b(j(2))-t(j(2)))*h2;\n b_to_t(j(3),:,:) = b(j(3))*ones(n,n);\n b_to_t_v = reshape(b_to_t,dim,n*n);\n if offset_regions\n b_to_t_x = polar2cart([cart2polar2(rot_matrix*polar2cart(b_to_t_v(1:dim-1,:)));b_to_t_v(dim,:)]);\n else\n b_to_t_x = polar2cart(b_to_t_v);\n end\n s = reshape(feval(projection,b_to_t_x),dim,n,n);\n degenerate = (norm(s(:,1,1)-s(:,1,2)) < tol);\n if ~degenerate && (~pseudo || (k > 1 && abs(b(2)-pi) > tol))\n [X,Y,Z] = fatcurve(squeeze(s(:,1,:)),r);\n surface(X,Y,Z,zeros(size(Z)),...\n 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n end\n if show_surfaces && k < 2\n surf(squeeze(s(1,:,:)),squeeze(s(2,:,:)),squeeze(s(3,:,:)),t(3)*ones(n,n),...\n 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n camlight right\n end\n end\nend\ncolormap jet\ngrid off\naxis off\n%\n% end function\n\nfunction project_s3_eq_point_set(N,extra_offset,stereo)\n%PROJECT_S3_EQ_POINT_SET Use projection to illustrate an EQ point set of S^3\n%\n%Syntax\n% project_s3_eq_point_set(N,min_energy,stereo);\n\nif nargin < 2\n extra_offset = true;\nend\nif nargin < 3\n stereo = true;\nend\nif stereo\n projection = 'stereo';\nelse\n projection = 'eqarea';\nend\n\nx = eq_point_set(3,N,extra_offset);\nproject_point_set(x,'title','hide','proj',projection);\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "project_s3_partition_symm.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/project_s3_partition_symm.m", "size": 8491, "source_encoding": "utf_8", "md5": "2a42994a8120fb1cf8dff550211ed31a", "text": "function [movie_frame] = project_s3_partition_symm(N,showOnlyHalf,varargin)\n%PROJECT_S3_PARTITION Use projection to illustrate an EQ partition of S^3\n%\n%Syntax\n% [movie_frame] = project_s3_partition(N,options);\n%\n%Description\n% PROJECT_S3_PARTITION(N) uses projection to illustrate the partition of\n% the unit sphere S^3 into N regions.\n%\n% MOVIE_FRAME = PROJECT_S3_PARTITION(N) sets MOVIE_FRAME to be an array of\n% movie frames for use with MOVIE. The movie frames will contain the region by\n% region build-up of the illustration.\n%\n% PROJECT_S3_PARTITION(N,'offset','extra') uses experimental extra offsets.\n% For more detail on partition options, see HELP PARTITION_OPTIONS.\n%\n% PROJECT_S3_PARTITION(N,options) also recognizes a number of illustration\n% options, which are specified as name, value pairs.\n% Any number of pairs can be used, in any order.\n%\n% The following illustration options are used.\n%\n% PROJECT_S3_PARTITION(N,'fontsize',size)\n% Font size used in titles (numeric, default 18).\n%\n% PROJECT_S3_PARTITION(N,'title','long')\n% PROJECT_S3_PARTITION(N,'title','short')\n% Use long or short titles (default 'long').\n%\n% PROJECT_S3_PARTITION(N,'proj','stereo')\n% PROJECT_S3_PARTITION(N,'proj','eqarea')\n% Use stereographic or equal area projection (default 'stereo').\n%\n% PROJECT_S3_PARTITION(N,'points','show')\n% PROJECT_S3_PARTITION(N,'points','hide')\n% Show or hide center points (default 'show').\n%\n% PROJECT_S3_PARTITION(N,'surf','show')\n% PROJECT_S3_PARTITION(N,'surf','hide')\n% Show or hide surfaces of regions (default 'show').\n%\n% For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS.\n%\n%Examples\n% > project_s3_partition(10)\n% > frames=project_s3_partition(9,'offset','extra','proj','eqarea')\n% frames =\n% 1x18 struct array with fields:\n% cdata\n% colormap\n% > project_s3_partition(99,'proj','eqarea','points','hide')\n%\n%See also\n% MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, PROJECT_S2_PARTITION\n\n% Adapted version by Florian Pfaff for libDirectional 2020-03-07\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Function changed name from s2x to polar2cart\n% Function changed name from x2s2 to cart2polar2\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-13 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\nassert(mod(N,2)==0);\nif nargin==1\n showOnlyHalf=false;\nend\nif showOnlyHalf\n N=N/2;\nend\n\npdefault.extra_offset = false;\n\npopt = partition_options(pdefault, varargin{:});\n\ngdefault.fontsize = 18;\ngdefault.stereo = true;\ngdefault.long_title = true;\ngdefault.show_points = true;\ngdefault.show_surfaces = true;\n\ngopt = illustration_options(gdefault, varargin{:});\n\ndim = 3;\n\n[X,Y,Z] = sphere(90);\nif gopt.stereo\n r = 0;\nelse\n r = (area_of_sphere(dim)/volume_of_ball(dim)).^(1/dim);\nend\n\nhold off\n\nif gopt.show_surfaces\n surf(r*X,r*Y,r*Z,zeros(size(Z)),...\n 'FaceAlpha',1/20,'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\nelse\n plot3(0,0,0,'w.')\nend\naxis equal;hold on\ncamlight right\ncolormap jet\ngrid off\naxis off\n\nif gopt.long_title\n if gopt.stereo\n s = 'Stereographic';\n else\n s = 'Equal volume';\n end\n if gopt.show_points\n pointstr = ', showing the center point of each region';\n else\n pointstr = '';\n end\n\n title(sprintf(...\n '\\n%s projection of recursive zonal equal area partition of {S^3} \\n into %d regions%s.',...\n s,N,pointstr),'FontSize',gopt.fontsize);\nelse\n title(sprintf('\\nEQ(3,%d)',N),'FontSize',gopt.fontsize);\nend\n\naxis equal\ngrid off\naxis off\n\npause(0);\nif nargout > 0\n movie_frame(1) = getframe(gcf);\nend\n\nif gopt.stereo && (N == 1)\n return;\nend\n\nif popt.extra_offset\n error('Unsupported');\nelse\n if showOnlyHalf\n R = eq_regions_symm(dim,2*N,true,popt.extra_offset);\n else\n R = eq_regions_symm(dim,N,false,popt.extra_offset);\n end\nend\n\nfor i = N:-1:2\n if popt.extra_offset\n project_s3_region(R(:,:,i),N,gopt.stereo,gopt.show_surfaces,dim_1_rot{i});\n else\n project_s3_region(R(:,:,i),N,gopt.stereo,gopt.show_surfaces);\n end\n pause(0);\n% title('');\n% set(gcf,'color',[1,1,1]);\n% export_fig('-nocrop',sprintf('pres%03d.png',N-i))\n if nargout > 0\n movie_frame(N-i+2) = getframe(gcf);\n end\nend\n\nif gopt.show_points\n project_s3_eq_point_set(N,showOnlyHalf,popt.extra_offset,gopt.stereo);\n if nargout > 0\n for k=1:min(N,40)\n movie_frame(N+k) = getframe(gcf);\n end\n end\nend\n\nhold off\n%\n% end function\n\nfunction project_s3_region(region, N, stereo, show_surfaces, rot_matrix)\n%PROJECT_S3_REGION Use projection to illustrate an EQ region of S^3\n%Syntax\n% project_s3_region(region, stereo, show_surfaces, rot_matrix);\n%\n%Notes\n% The region is given as a 3 x 2 matrix in spherical polar coordinates\n%\n% The default is to use stereographic projection\n% If the optional second argument, stereo is false,\n% then use a equal area projection.\n\nif nargin < 3\n stereo = true;\nend\nif stereo\n projection = 'x2stereo';\nelse\n projection = 'x2eqarea';\nend\nif nargin < 4\n show_surfaces = true;\nend\n\noffset_regions = (nargin >= 5);\n\ntol = eps*2^5;\n\ndim = size(region,1);\nt = region(:,1);\nb = region(:,2);\n\nif abs(b(1)) < tol\n b(1) = 2*pi;\nend\npseudo = 0;\nif abs(t(1)) < tol && abs(b(1)-2*pi) < tol\n pseudo = 1;\nend\nn = 33;\ndelta = 1/(n-1);\nh = 0:delta:1;\n[h1, h2] = meshgrid(h,h);\nt_to_b = zeros(dim,n,n);\nb_to_t = t_to_b;\nr = N^(-1/3)/32;\nfor k = 1:dim\n if ~pseudo || k < 3\n L = 1:dim;\n j(L) = mod(k+L,dim)+1;\n t_to_b(j(1),:,:) = t(j(1))+(b(j(1))-t(j(1)))*h1;\n t_to_b(j(2),:,:) = t(j(2))+(b(j(2))-t(j(2)))*h2;\n t_to_b(j(3),:,:) = t(j(3))*ones(n,n);\n t_to_b_v = reshape(t_to_b,dim,n*n);\n if offset_regions\n t_to_b_x = polar2cart([cart2polar2(rot_matrix*polar2cart(t_to_b_v(1:dim-1,:)));t_to_b_v(dim,:)]);\n else\n t_to_b_x = polar2cart(t_to_b_v);\n end\n s = reshape(feval(projection,t_to_b_x),dim,n,n);\n degenerate = (norm(s(:,1,1)-s(:,1,2)) < tol);\n if ~degenerate && (~pseudo || k > 1)\n [X,Y,Z] = fatcurve(squeeze(s(:,1,:)),r);\n surface(X,Y,Z,zeros(size(Z)),...\n 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n axis equal; hold on\n end\n if show_surfaces\n surf(squeeze(s(1,:,:)),squeeze(s(2,:,:)),squeeze(s(3,:,:)),t(3)*ones(n,n),...\n 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n end\n axis equal; hold on\n camlight right\n b_to_t(j(1),:,:) = b(j(1))-(b(j(1))-t(j(1)))*h1;\n b_to_t(j(2),:,:) = b(j(2))-(b(j(2))-t(j(2)))*h2;\n b_to_t(j(3),:,:) = b(j(3))*ones(n,n);\n b_to_t_v = reshape(b_to_t,dim,n*n);\n if offset_regions\n b_to_t_x = polar2cart([cart2polar2(rot_matrix*polar2cart(b_to_t_v(1:dim-1,:)));b_to_t_v(dim,:)]);\n else\n b_to_t_x = polar2cart(b_to_t_v);\n end\n s = reshape(feval(projection,b_to_t_x),dim,n,n);\n degenerate = (norm(s(:,1,1)-s(:,1,2)) < tol);\n if ~degenerate && (~pseudo || (k > 1 && abs(b(2)-pi) > tol))\n [X,Y,Z] = fatcurve(squeeze(s(:,1,:)),r);\n surface(X,Y,Z,zeros(size(Z)),...\n 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n end\n if show_surfaces && k < 2\n surf(squeeze(s(1,:,:)),squeeze(s(2,:,:)),squeeze(s(3,:,:)),t(3)*ones(n,n),...\n 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n camlight right\n end\n end\nend\ncolormap jet\ngrid off\naxis off\n%\n% end function\n\nfunction project_s3_eq_point_set(N,showOnlyHalf,extra_offset,stereo)\n%PROJECT_S3_EQ_POINT_SET Use projection to illustrate an EQ point set of S^3\n%\n%Syntax\n% project_s3_eq_point_set(N,showOnlyHalf,min_energy,stereo);\n\nif nargin < 2\n extra_offset = true;\nend\nif nargin < 3\n stereo = true;\nend\nif stereo\n projection = 'stereo';\nelse\n projection = 'eqarea';\nend\n\nif showOnlyHalf\n x = eq_point_set_symm(3,2*N,true,'plane',extra_offset);\nelse\n x = eq_point_set_symm(3,N,false,'plane',extra_offset);\nend\nproject_point_set(x,'title','hide','proj',projection);\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "show_s2_partition.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/show_s2_partition.m", "size": 4545, "source_encoding": "utf_8", "md5": "82695a64c69f1c5c3889d51e8bbc426d", "text": "function [movie_frame] = show_s2_partition(N,varargin)\n%SHOW_S2_PARTITION 3D illustration of an EQ partition of S^2\n%\n%Syntax\n% [movie_frame] = show_s2_partition(N,options);\n%\n%Description\n% SHOW_S2_PARTITION(N) uses a 3d plot to illustrate the partition of\n% the unit sphere S^2 into N regions.\n%\n% MOVIE_FRAME = SHOW_S2_PARTITION(N) sets MOVIE_FRAME to be an array of\n% movie frames for use with MOVIE. The movie frames will contain the region by\n% region build-up of the illustration.\n%\n% SHOW_S2_PARTITION(N,'offset','extra') uses experimental extra offsets.\n% For more detail on partition options, see HELP PARTITION_OPTIONS.\n%\n% SHOW_S2_PARTITION(N,options) also recognizes a number of illustration\n% options, which are specified as name, value pairs.\n% Any number of pairs can be used, in any order.\n%\n% The following illustration options are used.\n%\n% SHOW_S2_PARTITION(N,'fontsize',size)\n% Font size used in titles (numeric, default 16).\n%\n% SHOW_S2_PARTITION(N,'title','show')\n% SHOW_S2_PARTITION(N,'title','hide')\n% Show or hide title (default 'show').\n%\n% SHOW_S2_PARTITION(N,'points','show')\n% SHOW_S2_PARTITION(N,'points','hide')\n% Show or hide center points (default 'show').\n%\n% SHOW_S2_PARTITION(N,'sphere','show')\n% SHOW_S2_PARTITION(N,'sphere','hide')\n% Show or hide the unit sphere S^2 (default 'show').\n%\n% For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS.\n%\n%Examples\n% > show_s2_partition(10)\n% > frames=show_s2_partition(9,'offset','extra')\n% frames =\n% 1x10 struct array with fields:\n% cdata\n% colormap\n% > show_s2_partition(99,'points','hide')\n%\n%See also\n% MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, PROJECT_S2_PARTITION\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Function changed name from s2x to polar2cart\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-13 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\npdefault.extra_offset = false;\npopt = partition_options(pdefault, varargin{:});\n\ngdefault.fontsize = 16;\ngdefault.show_title = true;\ngdefault.show_points = true;\ngdefault.show_sphere = true;\ngopt = illustration_options(gdefault, varargin{:});\n\ndim = 2;\n\nsurf_jet;\n\nif gopt.show_title\n if gopt.show_points\n pointstr = ', showing the center point of each region';\n else\n pointstr = '';\n end\n titlestr = sprintf(...\n '\\nRecursive zonal equal area partition of {S^2} \\n into %d regions%s.',...\n N,pointstr);\n title(titlestr,'FontWeight','bold','FontUnits','normalized',...\n 'FontSize',gopt.fontsize/512);\nend\n\nframe_no = 1;\nif nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\nend\n\nif gopt.show_sphere\n show_s2_sphere;\n hold on\n if nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\n end\nend\n\nR = eq_regions(dim,N,popt.extra_offset);\ntop_colat = 0;\nfor i = N:-1:2\n if top_colat ~= R(2,1,i)\n top_colat = R(2,1,i);\n pause(0);\n end\n show_s2_region(R(:,:,i),N);\n if nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\n end\nend\n\nif gopt.show_points\n x = eq_point_set(dim,N,popt.extra_offset);\n show_r3_point_set(x,'sphere','hide','title','hide');\n hold on\n if nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\n end\nend\n\nhold off\n%\n% end function\n\nfunction show_s2_region(region,N)\n%SHOW_S2_REGION Illustrate a region of S^2\n%\n%Syntax\n% show_s2_region(region,N);\n%\n%Description\n% SHOW_S2_REGION(REGION,N) uses 3D surface plots to illustrate a region of S^2.\n% The region is given as a 2 x 2 matrix in spherical polar coordinates\n\ntol = eps*2^5;\n\ndim = size(region,1);\nt = region(:,1);\nb = region(:,2);\n\nif abs(b(1)) < tol\n b(1) = 2*pi;\nend\npseudo = 0;\nif abs(t(1)) < tol && abs(b(1)-2*pi) < tol\n pseudo = 1;\nend\nn = 21;\ndelta = 1/(n-1);\nh = 0:delta:1;\nt_to_b = zeros(dim,n);\nb_to_t = t_to_b;\nr = sqrt(1/N)/12;\nfor k = 1:dim\n if ~pseudo || k < 2\n L = 1:dim;\n j(L) = mod(k+L,dim)+1;\n t_to_b(j(1),:) = t(j(1))+(b(j(1))-t(j(1)))*h;\n t_to_b(j(2),:) = t(j(2))*ones(1,n);\n t_to_b_x = polar2cart(t_to_b);\n [X,Y,Z] = fatcurve(t_to_b_x,r);\n surface(X,Y,Z,-ones(size(Z)),...\n 'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n axis equal\n hold on\n end\nend\ngrid off\naxis off\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "illustration_options.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/illustration_options.m", "size": 6138, "source_encoding": "utf_8", "md5": "1834482cf5939c4cf12940d3c0151dbb", "text": "function gopt = illustration_options(gdefault, varargin)\n%ILLUSTRATION_OPTIONS Options for illustrations of EQ partitions\n%\n%Syntax\n% gopt = illustration_options(gdefault,options);\n%\n%Description\n% GOPT = ILLUSTRATION_OPTIONS(GDEFAULT,options) collects illustration options,\n% specified as name, value pairs, and places these into the structure GOPT.\n% The structure GDEFAULT is used to define default option values.\n%\n% The structures gdefault and gopt may contain the following fields:\n% fontsize: numeric\n% long_title: boolean\n% stereo: boolean\n% show_points: boolean\n% show_sphere: boolean\n% show_surfaces: boolean\n%\n% The following illustration options are available.\n%\n% 'fontsize': Font size used in titles.\n% number Assigns number to field gopt.fontsize.\n%\n% 'title': Length of titles.\n% 'long': Long titles.\n% Sets gopt.show_title to true.\n% Sets gopt.long_title to true.\n% 'short': Short titles.\n% Sets gopt.show_title to true.\n% Sets gopt.long_title to false.\n% 'none': No titles.\n% Sets gopt.show_title to false.\n% Sets gopt.long_title to false.\n% 'show': Show default titles.\n% Sets gopt.show_title to true.\n% 'hide': Same as 'none'.\n%\n% 'proj': Projection from the sphere to the plane R^2 or the space R^3.\n% 'stereo': Stereographic projection from the sphere to the whole space.\n% Sets gopt.stereo to true.\n% 'eqarea': Equal area projection from the sphere to the disk or ball.\n% Sets gopt.stereo to false.\n%\n% 'points': Show or hide center points of regions.\n% 'show': Show center points of regions.\n% Sets gopt.show_points to true.\n% 'hide': Hide center points of regions.\n% Sets gopt.show_points to false.\n%\n% 'sphere': Show or hide the sphere S^2.\n% 'show': Show sphere.\n% Sets gopt.show_sphere to true.\n% 'hide': Hide sphere.\n% Sets gopt.show_sphere to false.\n%\n% 'surf': Show or hide surfaces of regions of a partition of S^3.\n% 'show': Show surfaces of regions.\n% Sets gopt.show_surfaces to true.\n% 'hide': Hide surfaces of regions.\n% Sets gopt.show_surfaces to false.\n%\n%Examples\n% > gdefault.fontsize=14;\n% > gopt=illustration_options(gdefault,'proj','stereo')\n% gopt =\n% fontsize: 14\n% stereo: 1\n%\n% > gopt=illustration_options(gdefault,'proj','stereo','fontsize',12)\n% gopt =\n% fontsize: 12\n% stereo: 1\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\ngopt = gdefault;\nnargs = length(varargin);\nnopts = floor(nargs/2);\nopt_args = {varargin{1:2:2*nopts-1}};\nfor k=1:nopts\n if ~ischar([opt_args{k}])\n fprintf('Option names must be character strings\\n');\n option_error(varargin{:});\n end\nend\nopt_vals = {varargin{2:2:2*nopts}};\n\noption_name = 'fontsize';\npos = strmatch(option_name,opt_args,'exact');\nif ~isempty(pos)\n if (length(pos) == 1)\n gopt.fontsize = opt_vals{pos};\n else\n duplicate_error(option_name,varargin{:});\n end\nend\n\noption_name = 'title';\npos = strmatch(option_name,opt_args,'exact');\nif ~isempty(pos)\n if (length(pos) == 1)\n value = opt_vals{pos};\n else\n duplicate_error(option_name,varargin{:});\n end\n switch value\n case 'long'\n gopt.show_title = true;\n gopt.long_title = true;\n case 'short'\n gopt.show_title = true;\n gopt.long_title = false;\n case 'none'\n gopt.show_title = false;\n gopt.long_title = false;\n case 'hide'\n gopt.show_title = false;\n case 'hide'\n gopt.show_title = false;\n gopt.long_title = false;\n case 'show'\n gopt.show_title = true;\n otherwise\n value_error(value,varargin{:});\n end\nend\n\noption_name = 'proj';\npos = strmatch(option_name,opt_args);\nif ~isempty(pos)\n if (length(pos) == 1)\n value = opt_vals{pos};\n else\n duplicate_error(option_name,varargin{:});\n end\n switch value\n case 'stereo'\n gopt.stereo = true;\n case 'eqarea'\n gopt.stereo = false;\n otherwise\n value_error(value,varargin{:});\n end\nend\n\noption_name = 'points';\npos = strmatch(option_name,opt_args,'exact');\nif ~isempty(pos)\n if (length(pos) == 1)\n value = opt_vals{pos};\n else\n duplicate_error(option_name,varargin{:});\n end\n switch value\n case 'show'\n gopt.show_points = true;\n case 'hide'\n gopt.show_points = false;\n otherwise\n value_error(value,varargin{:});\n end\nend\n\noption_name = 'surf';\npos = strmatch(option_name,opt_args);\nif ~isempty(pos)\n if (length(pos) == 1)\n value = opt_vals{pos};\n else\n duplicate_error(option_name,varargin{:});\n end\n switch value\n case 'show'\n gopt.show_surfaces = true;\n case 'hide'\n gopt.show_surfaces = false;\n otherwise\n value_error(value,varargin{:});\n end\nend\n\noption_name = 'sphere';\npos = strmatch(option_name,opt_args);\nif ~isempty(pos)\n if (length(pos) == 1)\n value = opt_vals{pos};\n else\n duplicate_error(option_name,varargin{:});\n end\n switch value\n case 'show'\n gopt.show_sphere = true;\n case 'hide'\n gopt.show_sphere = false;\n otherwise\n value_error(value,varargin{:});\n end\nend\n%\n% end function\n\nfunction duplicate_error(option_name,varargin)\nfprintf('Duplicate option %s\\n',option_name); \noption_error(varargin{:});\n%\n% end function\n\nfunction value_error(value,varargin) \nfprintf('Invalid option value ');\ndisp(value);\noption_error(varargin{:});\n%\n% end function\n\nfunction option_error(varargin)\nfprintf('Error in options:\\n');\ndisp(varargin);\nerror('Please check \"help illustration_options\" for options');\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "project_s2_partition.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/project_s2_partition.m", "size": 5591, "source_encoding": "utf_8", "md5": "da4b16d4d4515eaa89b78c51d43e6b44", "text": "function [movie_frame] = project_s2_partition(N,varargin)\n%PROJECT_S2_PARTITION Use projection to illustrate an EQ partition of S^2\n%\n%Syntax\n% [movie_frame] = project_s2_partition(N,options);\n%\n%Description\n% PROJECT_S2_PARTITION(N) uses projection to illustrate the partition of\n% the unit sphere S^2 into N regions.\n%\n% MOVIE_FRAME = PROJECT_S2_PARTITION(N) sets MOVIE_FRAME to be an array of\n% movie frames for use with MOVIE. The movie frames will contain the region by\n% region build-up of the illustration.\n%\n% PROJECT_S2_PARTITION(N,'offset','extra') uses experimental extra offsets.\n% For more detail on partition options, see HELP PARTITION_OPTIONS.\n%\n% PROJECT_S2_PARTITION(N,options) also recognizes a number of illustration\n% options, which are specified as name, value pairs.\n% Any number of pairs can be used, in any order.\n%\n% The following illustration options are used.\n%\n% PROJECT_S2_PARTITION(N,'fontsize',size)\n% Font size used in titles (numeric, default 16).\n%\n% PROJECT_S2_PARTITION(N,'title','long')\n% PROJECT_S2_PARTITION(N,'title','short')\n% Use long or short titles (default 'long').\n%\n% PROJECT_S2_PARTITION(N,'proj','stereo')\n% PROJECT_S2_PARTITION(N,'proj','eqarea')\n% Use stereographic or equal area projection (default 'stereo').\n%\n% PROJECT_S2_PARTITION(N,'points','show')\n% PROJECT_S2_PARTITION(N,'points','hide')\n% Show or hide center points (default 'show').\n%\n% For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS.\n%\n%Examples\n% > project_s2_partition(10)\n% > frames=project_s2_partition(9,'offset','extra','proj','eqarea')\n% frames =\n% 1x10 struct array with fields:\n% cdata\n% colormap\n% > project_s2_partition(99,'proj','eqarea','points','hide')\n%\n%See also\n% MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, SHOW_S2_PARTITION,\n% PROJECT_S3_PARTITION\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Function changed name from s2x to polar2cart\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-13 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\npdefault.extra_offset = false;\n\npopt = partition_options(pdefault, varargin{:});\n\ngdefault.fontsize = 16;\ngdefault.stereo = true;\ngdefault.show_title = true;\ngdefault.long_title = true;\ngdefault.show_points = true;\n\ngopt = illustration_options(gdefault, varargin{:});\n\ndim = 2;\n\nPhi = 2*pi*(0:1/40:1);\nX = cos(Phi);\nY = sin(Phi);\nif gopt.stereo\n r = 0;\nelse\n r = (area_of_sphere(dim)/volume_of_ball(dim)).^(1/dim);\nend\nplot(r*X,r*Y,'k')\naxis equal;hold on\ncolormap jet\ngrid off\naxis off\n\nif gopt.show_title\n if gopt.long_title\n if gopt.stereo\n s = 'Stereographic';\n else\n s = 'Equal area';\n end\n if gopt.show_points\n pointstr = ', showing the center point of each region';\n else\n pointstr = '';\n end\n\n titlestr = sprintf(...\n '%s projection of recursive zonal equal area partition of {S^2}\\ninto %d regions%s.',...\n s,N,pointstr);\n else\n titlestr = sprintf('EQ(2,%d)',N);\n end\n title(titlestr, ...\n 'FontWeight','bold','FontUnits','normalized','FontSize',gopt.fontsize/512);\nend\n\nif nargout > 0\n movie_frame(1) = getframe(gcf);\nend\n\nR = eq_regions(dim,N,popt.extra_offset);\nfor i = N:-1:2\n project_s2_region(R(:,:,i),gopt.stereo);\n if nargout > 0\n movie_frame(N-i+2) = getframe(gcf);\n end\nend\n\nif gopt.show_points\n project_s2_eq_point_set(N,popt.extra_offset,gopt.stereo);\n if nargout > 0\n movie_frame(N+1) = getframe(gcf);\n end\nend\n\nhold off\n%\n% end function\n\nfunction project_s2_region(region, stereo)\n%PROJECT_S2_REGION Use projection to illustrate an EQ region of S^2\n%\n%Syntax\n% project_s2_region(region, stereo);\n%\n%Notes\n% The region is given as a 2 x 2 matrix in spherical polar coordinates\n%\n% The default is to use stereographic projection\n% If the optional second argument, stereo is false,\n% then use a equal area projection.\n\nif nargin < 2\n stereo = true;\nend\nif stereo\n projection = 'x2stereo';\nelse\n projection = 'x2eqarea';\nend\n\ntol = eps*2^5;\n\ndim = size(region,1);\nt = region(:,1);\nb = region(:,2);\n\nif abs(b(1)) < tol\n b(1) = 2*pi;\nend\npseudo = 0;\nif abs(t(1)) < tol && abs(b(1)-2*pi) < tol\n pseudo = 1;\nend\nn = 21;\ndelta = 1/(n-1);\nh = 0:delta:1;\nt_to_b = zeros(dim,n);\nb_to_t = t_to_b;\nfor k = 1:dim\n if ~pseudo || k < 2\n L = 1:dim;\n j(L) = mod(k+L,dim)+1;\n t_to_b(j(1),:) = t(j(1))+(b(j(1))-t(j(1)))*h;\n t_to_b(j(2),:) = t(j(2))*ones(1,n);\n t_to_b_x = polar2cart(t_to_b);\n s = feval(projection,t_to_b_x);\n plot(s(1,:),s(2,:),'k');\n axis equal; hold on\n if pseudo\n axis equal; hold on\n b_to_t(j(1),:,:) = b(j(1))-(b(j(1))-t(j(1)))*h;\n b_to_t(j(2),:,:) = b(j(2))*ones(1,n);\n b_to_t_x = polar2cart(b_to_t);\n s = feval(projection,b_to_t_x);\n plot(s(1,:),s(2,:),'k');\n end\n end\nend\ngrid off\naxis off\n%\n% end function\n\nfunction project_s2_eq_point_set(N,extra_offset,stereo)\n%PROJECT_S2_EQ_POINT_SET Use projection to illustrate an EQ point set of S^2\n%\n%Syntax\n% project_s2_eq_point_set(N,extra_offset,stereo);\n\nif nargin < 2\n extra_offset = true;\nend\nif nargin < 3\n stereo = true;\nend\nif stereo\n projection = 'stereo';\nelse\n projection = 'eqarea';\nend\n\nx = eq_point_set(2,N,extra_offset);\nproject_point_set(x,'title','hide','proj',projection);\nhold on\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "show_s2_partition_symm.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/show_s2_partition_symm.m", "size": 5246, "source_encoding": "utf_8", "md5": "127934bf827e86dae624f46407897ce4", "text": "function [movie_frame] = show_s2_partition_symm(N,showOnlyHalf,symmetryType,varargin)\n%SHOW_S2_PARTITION 3D illustration of an EQ partition of S^2\n%\n%Syntax\n% [movie_frame] = show_s2_partition(N,options);\n%\n%Description\n% SHOW_S2_PARTITION(N) uses a 3d plot to illustrate the partition of\n% the unit sphere S^2 into N regions.\n%\n% MOVIE_FRAME = SHOW_S2_PARTITION(N) sets MOVIE_FRAME to be an array of\n% movie frames for use with MOVIE. The movie frames will contain the region by\n% region build-up of the illustration.\n%\n% SHOW_S2_PARTITION(N,'offset','extra') uses experimental extra offsets.\n% For more detail on partition options, see HELP PARTITION_OPTIONS.\n%\n% SHOW_S2_PARTITION(N,options) also recognizes a number of illustration\n% options, which are specified as name, value pairs.\n% Any number of pairs can be used, in any order.\n%\n% The following illustration options are used.\n%\n% SHOW_S2_PARTITION(N,'fontsize',size)\n% Font size used in titles (numeric, default 16).\n%\n% SHOW_S2_PARTITION(N,'title','show')\n% SHOW_S2_PARTITION(N,'title','hide')\n% Show or hide title (default 'show').\n%\n% SHOW_S2_PARTITION(N,'points','show')\n% SHOW_S2_PARTITION(N,'points','hide')\n% Show or hide center points (default 'show').\n%\n% SHOW_S2_PARTITION(N,'sphere','show')\n% SHOW_S2_PARTITION(N,'sphere','hide')\n% Show or hide the unit sphere S^2 (default 'show').\n%\n% For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS.\n%\n%Examples\n% > show_s2_partition(10)\n% > frames=show_s2_partition(9,'offset','extra')\n% frames =\n% 1x10 struct array with fields:\n% cdata\n% colormap\n% > show_s2_partition(99,'points','hide')\n%\n%See also\n% MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, PROJECT_S2_PARTITION\n\n% Adapted version by Florian Pfaff (pfaff@kit.edu) for libDirectional\n% 2020-03-28\n%\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Function changed name from s2x to polar2cart\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-13 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\narguments\n N (1,1) double {mustBeInteger}\n showOnlyHalf (1,1) logical = false\n symmetryType char = 'mirror'\nend\narguments (Repeating)\n varargin\nend\nassert(mod(N,2)==0);\nif nargin==1\n showOnlyHalf=false;\nend\nif showOnlyHalf\n N=N/2;\nend\n\npdefault.extra_offset = false;\npopt = partition_options(pdefault, varargin{:});\n\ngdefault.fontsize = 16;\ngdefault.show_title = true;\ngdefault.show_points = true;\ngdefault.show_sphere = true;\ngopt = illustration_options(gdefault, varargin{:});\n\ndim = 2;\n\nsurf_jet;\n\nif gopt.show_title\n if gopt.show_points\n pointstr = ', showing the center point of each region';\n else\n pointstr = '';\n end\n titlestr = sprintf(...\n '\\nRecursive zonal equal area partition of {S^2} \\n into %d regions%s.',...\n N,pointstr);\n title(titlestr,'FontWeight','bold','FontUnits','normalized',...\n 'FontSize',gopt.fontsize/512);\nend\n\nframe_no = 1;\nif nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\nend\n\nif gopt.show_sphere\n if showOnlyHalf\n show_s2_hemisphere\n else\n show_s2_sphere;\n end\n hold on\n if nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\n end\nend\n\nif showOnlyHalf\n R = eq_regions_symm(dim,2*N,true,symmetryType,popt.extra_offset);\nelse\n R = eq_regions_symm(dim,N,false,symmetryType,popt.extra_offset);\nend\ntop_colat = 0;\nfor i = N:-1:2\n if top_colat ~= R(2,1,i)\n top_colat = R(2,1,i);\n pause(0);\n end\n show_s2_region(R(:,:,i),N);\n if nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\n end\nend\n\nif gopt.show_points\n if showOnlyHalf\n x = eq_point_set_symm(dim,2*N,true,symmetryType,popt.extra_offset);\n else\n x = eq_point_set_symm(dim,N,false,symmetryType,popt.extra_offset);\n end\n show_r3_point_set(x,'sphere','hide','title','hide');\n hold on\n if nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\n end\nend\n\nhold off\n%\n% end function\n\nfunction show_s2_region(region,N)\n%SHOW_S2_REGION Illustrate a region of S^2\n%\n%Syntax\n% show_s2_region(region,N);\n%\n%Description\n% SHOW_S2_REGION(REGION,N) uses 3D surface plots to illustrate a region of S^2.\n% The region is given as a 2 x 2 matrix in spherical polar coordinates\n\ntol = eps*2^5;\n\ndim = size(region,1);\nt = region(:,1);\nb = region(:,2);\n\nif abs(b(1)) < tol\n b(1) = 2*pi;\nend\npseudo = 0;\nif abs(t(1)) < tol && abs(b(1)-2*pi) < tol\n pseudo = 1;\nend\nn = 21;\ndelta = 1/(n-1);\nh = 0:delta:1;\nt_to_b = zeros(dim,n);\nb_to_t = t_to_b;\nr = sqrt(1/N)/12;\nfor k = 1:dim\n if ~pseudo || k < 2\n L = 1:dim;\n j(L) = mod(k+L,dim)+1;\n t_to_b(j(1),:) = t(j(1))+(b(j(1))-t(j(1)))*h;\n t_to_b(j(2),:) = t(j(2))*ones(1,n);\n t_to_b_x = polar2cart(t_to_b);\n [X,Y,Z] = fatcurve(t_to_b_x,r);\n surface(X,Y,Z,-ones(size(Z)),...\n 'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n axis equal\n hold on\n end\nend\ngrid off\naxis off\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "calc_energy_coeff.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_point_set_props/calc_energy_coeff.m", "size": 4435, "source_encoding": "utf_8", "md5": "2d3fad0cecbe7e98770c8fb861b465f9", "text": "function coeff = calc_energy_coeff(dim,N,s,energy)\n%CALC_ENERGY_COEFF Coefficient of second term in expansion of energy\n%\n%Syntax\n% coeff = calc_energy_coeff(d,N,s,energy);\n%\n%Description\n% COEFF = CALC_ENERGY_COEFF(dim,N,s,ENERGY) sets COEFF to be the coefficient of\n% the second term of an expansion of ENERGY with the same form as the expansion \n% of E(dim,N,s), the minimum r^(-s) energy of a set of N points on S^dim.\n%\n% Specifically, for s not equal to 0, COEFF is the solution to\n%\n% ENERGY == (SPHERE_INT_ENERGY(dim,s)/2) N^2 + COEFF N^(1+s/dim),\n%\n% and for s == 0 (the logarithmic potential), COEFF is the solution to\n%\n% ENERGY == (SPHERE_INT_ENERGY(dim,0)/2) N^2 + COEFF N LOG(N).\n%\n% The argument dim must be a positive integer.\n% The argument N must be a positive integer or an array of positive integers. \n% The argument ENERGY must an array of real numbers of the same array size as N.\n% The result COEFF will be an array of the same size as N.\n%\n%Notes\n% 1) The energy expansion is not valid for N == 1, and in particular,\n%\n% EQ_ENERGY_COEFF(dim,N,0,energy) := 0.\n%\n% 2) For s > 0, [KuiS98 (1.6) p524] has\n%\n% E(dim,N,s) == (SPHERE_INT_ENERGY(dim,s)/2) N^2 + COEFF N^(1+s/dim) + ...\n% \n% where SPHERE_INT_ENERGY(dim,s) is the energy integral of the r^(-s) potential\n% on S^dim.\n%\n% The case s == 0 (logarithmic potential) can be split into subcases.\n% For s == 0 and dim == 1, E(1,N,0) is obtained by equally spaced points on S^1,\n% and the formula for the log potential for N equally spaced points on a circle\n% gives\n%\n% E(1,N,0) == (-1/2) N LOG(N) exactly.\n%\n% For s == 0 and dim == 2, [SafK97 (4) p7] has\n%\n% E(2,N,0) == (SPHERE_INT_ENERGY(2,0)/2) N^2 + COEFF N LOG(N) + o(N LOG(N)).\n%\n% In general, for s == 0,\n%\n% E(dim,N,0) == (SPHERE_INT_ENERGY(dim,0)/2) N^2 + COEFF N LOG(N) + ... \n%\n% with sphere_int_energy(1,0) == 0.\n%\n% CALC_ENERGY_COEFF just uses this general formula for s == 0, so for s == 0 and\n% dim == 1, the coefficient returned is actually the coefficient of the first\n% non-zero term.\n%\n%Examples\n% > N=2:6\n% N =\n% 2 3 4 5 6\n% \n% > energy=eq_energy_dist(2,N,0)\n% energy =\n% -0.6931 -1.3863 -2.7726 -4.4205 -6.2383\n% \n% > calc_energy_coeff(2,N,0,energy)\n% ans =\n% -0.2213 -0.1569 -0.2213 -0.2493 -0.2569\n%\n%See also\n% EQ_ENERGY_DIST, EQ_ENERGY_COEFF\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\n%\n% Compute the energy coefficient: subtract the first term in the expansion of\n% the minimum energy and divide by the power of N in the second term.\n%\nif s > 0\n %\n % The first term in the expansion of the minimum energy.\n % Ref: [KuiS98 (1.6) p524]\n %\n first_term = (sphere_int_energy(dim,s)/2) * N.^2;\n coeff = (energy-first_term) ./ (N.^(1+s/dim));\nelse\n %\n % Flatten N into a row vector.\n %\n shape = size(N);\n n_partitions = prod(shape);\n N = reshape(N,1,n_partitions);\n %\n % Refs for s==0, dim == 2: \n % [SafK97 (4) p. 7] [Zho95 (5.6) p. 68, 3.11 - corrected) p. 42]\n %\n first_term = (sphere_int_energy(dim,s)/2) * N.^2;\n %\n % Avoid division by zero.\n %\n coeff = zeros(size(N));\n neq1 = (N ~= 1);\n coeff(neq1) = (energy(neq1)-first_term(neq1)) ./ (N(neq1) .* log(N(neq1)));\n %\n % Reshape output to same array size as original N.\n %\n coeff = reshape(coeff,shape);\n %\nend\n%\n% end function\n\nfunction energy = sphere_int_energy(dim,s)\n%SPHERE_INT_ENERGY Energy integral of r^(-s) potential\n%\n%Syntax\n% energy = sphere_int_energy(d,s);\n%\n%Description\n% ENERGY = SPHERE_INT_ENERGY(dim,s) sets ENERGY to be the energy integral \n% on S^dim of the r^(-s) potential, defined using normalized Lebesgue measure.\n%\n% Ref for s > 0: [KuiS98 (1.6) p524]\n% Ref for s == 0 and dim == 2: SafK97 (4) p. 7] \n% For s == 0 and dim >= 2, integral was obtained using Maple:\n% energy = (1/2)*(omega(dim)/omega(dim+1)* ...\n% int(-log(2*sin(theta/2)*(sin(theta))^(dim-1),theta=0..Pi),\n% where omega(dim+1) == area_of_sphere(dim).\n\nif s ~= 0\n energy = (gamma((dim+1)/2)*gamma(dim-s)/(gamma((dim-s+1)/2)*gamma(dim-s/2)));\nelseif dim ~= 1\n energy = (psi(dim)-psi(dim/2)-log(4))/2;\nelse\n energy = 0; \nend\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "point_set_energy_dist.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_point_set_props/point_set_energy_dist.m", "size": 2278, "source_encoding": "utf_8", "md5": "8d415c577d853255ac6e39d54d3c7e04", "text": "function [energy,min_dist] = point_set_energy_dist(points,s)\n%POINT_SET_ENERGY_DIST Energy and minimum distance of a point set\n%\n%Syntax\n% [energy,min_dist] = point_set_energy_dist(points,s);\n%\n%Description\n% [ENERGY,MIN_DIST] = POINT_SET_ENERGY_DIST(POINTS,s) sets ENERGY to be the\n% energy of the r^(-s) potential on the point set POINTS, and sets MIN_DIST \n% to be the minimum Euclidean distance between points of POINTS.\n%\n% POINTS must be an array of real numbers of size (M by N), where M and N\n% are positive integers, with each of the N columns representing a point of\n% R^M in Cartesian coordinates.\n% The result MIN_DIST is optional.\n%\n% [ENERGY,MIN_DIST] = POINT_SET_ENERGY_DIST(POINTS) uses the default value of\n% dim-1 for s.\n%\n%Notes\n% The value of ENERGY for a single point is 0.\n% Since this function is usually meant to be used for points on a unit sphere,\n% the value of MIN_DIST for a single point is defined to be 2.\n%\n%Examples\n% > x\n% x =\n% 0 0 0.0000 0\n% 0 0 0 0\n% 0 1.0000 -1.0000 0.0000\n% 1.0000 0.0000 0.0000 -1.0000\n%\n% > [e,d]=point_set_energy_dist(x)\n% e =\n% 2.5000\n% d =\n% 1.4142\n%\n%See also\n% EUCLIDEAN_DIST, EQ_ENERGY_DIST, POINT_SET_MIN_DIST\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-22 $\n% Documentation files renamed\n% Fix nasty but obvious bug by using separate variables dist and min_dist\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\ndim = size(points,1)-1;\n%\n% The default value of s is dim-1.\n%\nif nargin < 2\n s = dim-1;\nend\nenergy = 0;\nif nargout > 1\n min_dist = 2;\nend\nn_points = size(points,2);\nfor i = 1:(n_points-1)\n j = (i+1):n_points;\n dist = euclidean_dist(points(:,i)*ones(1,n_points-i),points(:,j));\n energy = energy + sum(potential(s,dist));\n if nargout > 1\n min_dist = min(min_dist,min(dist));\n end\nend\n%\n% end function\n\nfunction pot = potential(s,r)\n%POTENTIAL r^(-s) potential at Euclidean radius r.\n%\n%Syntax\n% pot = potential(s,r);\n\nswitch s\n case 0\n pot = -log(r);\n otherwise\n pot = r.^(-s);\nend\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "partition_options.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_partitions/partition_options.m", "size": 3298, "source_encoding": "utf_8", "md5": "66003a1c85613d062acb28376dd1550c", "text": "function popt = partition_options(pdefault, varargin)\n%PARTITION_OPTIONS Options for EQ partition\n%\n%Syntax\n% popt = partition_options(pdefault,options);\n%\n%Description\n% POPT = PARTITION_OPTIONS(PDEFAULT,options) collects partition options,\n% specified as name, value pairs, and places these into the structure POPT.\n% The structure PDEFAULT is used to define default option values.\n%\n% The structures pdefault and popt may contain the following fields:\n% extra_offset: boolean\n%\n% The following partition options are available.\n%\n% 'offset': Control extra rotation offsets for S^2 and S^3 regions.\n% 'extra': Use extra rotation offsets for S^2 and S^3 regions, to try\n% to minimize energy.\n% Sets opt.extra_offset to true.\n% 'normal': Do not use extra offsets\n% Sets opt.extra_offset to false.\n%\n% Some shortcuts are also provided.\n% POPT = PARTITION_OPTIONS(pdefault) just sets POPT to PDEFAULT.\n%\n% The following are equivalent to PARTITION_OPTIONS(PDEFAULT,'offset','extra'):\n% PARTITION_OPTIONS(PDEFAULT,true)\n% PARTITION_OPTIONS(PDEFAULT,'extra')\n%\n% The following are equivalent to PARTITION_OPTIONS(PDEFAULT,'offset','normal'):\n% PARTITION_OPTIONS(PDEFAULT,false)\n% PARTITION_OPTIONS(PDEFAULT,'normal')\n%\n%Examples\n% > pdefault.extra_offset=false;\n% > popt=partition_options(pdefault,'offset','extra')\n% popt =\n% extra_offset: 1\n%\n% > popt=partition_options(pdefault,false)\n% popt =\n% extra_offset: 0\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\npopt = pdefault;\nnargs = length(varargin);\n\nif nargs == 1\n %\n % Short circuit: single argument is value of extra_offset\n %\n value = varargin{1};\n switch value\n case true\n popt.extra_offset = true;\n case false\n popt.extra_offset = false;\n case 'extra'\n popt.extra_offset = true;\n case 'normal'\n popt.extra_offset = false;\n otherwise\n value_error(value,varargin{:});\n end\n return;\nend\n\nnopts = floor(nargs/2);\nopt_args = {varargin{1:2:2*nopts-1}};\nfor k=1:nopts\n if ~ischar([opt_args{k}])\n fprintf('Option names must be character strings\\n');\n option_error(varargin{:});\n end\nend \nopt_vals = {varargin{2:2:2*nopts}};\n\noption_name = 'offset';\npos = strmatch(option_name,opt_args,'exact');\nif ~isempty(pos)\n if (length(pos) == 1)\n value = opt_vals{pos};\n else\n duplicate_error(option_name,varargin{:});\n end\n switch value\n case 'extra'\n popt.extra_offset = true;\n case 'normal'\n popt.extra_offset = false;\n otherwise\n value_error(value,varargin{:});\n end\nend\n\nfunction duplicate_error(option_name,varargin)\nfprintf('Duplicate option %s\\n',option_name);\noption_error(varargin{:});\n%\n% end function\n\nfunction value_error(value,varargin)\nfprintf('Invalid option value ');\ndisp(value);\noption_error(varargin{:});\n%\n% end function\n\nfunction option_error(varargin)\nfprintf('Error in options:\\n');\ndisp(varargin);\nerror('Please check \"help partition_options\" for options');\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "illustrate_eq_algorithm.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_partitions/illustrate_eq_algorithm.m", "size": 10506, "source_encoding": "utf_8", "md5": "d513f0f352186d48897941b08abbdeed", "text": "function illustrate_eq_algorithm(dim,N,varargin)\n%ILLUSTRATE_EQ_ALGORITHM Illustrate the EQ partition algorithm\n%\n%Syntax\n% illustrate_eq_algorithm(dim,N,options);\n%\n%Description\n% ILLUSTRATE_EQ_ALGORITHM(dim,N) illustrates the recursive zonal equal area\n% sphere partitioning algorithm, which partitions S^dim (the unit sphere in \n% dim+1 dimensional space) into N regions of equal area and small diameter.\n%\n% The illustration consists of four subplots:\n% 1. Steps 1 and 2\n% 2. Steps 3 to 5\n% 3. Steps 6 and 7\n% 4. Lower dimensional partitions (if dim == 2 or dim == 3)\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'offset','extra') uses experimental extra\n% offsets for S^2 and S^3. If dim > 3, extra offsets are not used.\n% For more detail on partition options, see HELP PARTITION_OPTIONS.\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,options) also recognizes a number of\n% illustration options, which are specified as name, value pairs.\n% Any number of pairs can be used, in any order.\n%\n% The following illustration options are used.\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'fontsize',size)\n% Font size used in titles (numeric, default 16).\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'title','long')\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'title','short')\n% Use long or short titles (default 'short').\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'proj','stereo')\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'proj','eqarea')\n% Use stereographic or equal area projection (default 'stereo').\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'points','show')\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'points','hide')\n% Show or hide center points (default 'show').\n%\n% See examples below.\n% For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS.\n%\n%Notes\n% The step numbers refer to the following steps of the the recursive zonal\n% equal area sphere partitioning algorithm, which partition the sphere into \n% zones.\n%\n% 1. Determine the colatitudes of the North and South polar caps.\n% 2. Determine an ideal collar angle.\n% 3. Use the angle between the North and South polar caps and the ideal collar\n% angle to determine an ideal number of collars.\n% 4. Use a rounding procedure to determine the actual number of collars,\n% given the ideal number of collars.\n% 5. Create a list containing the ideal number of regions in each collar.\n% 6. Use a rounding procedure to create a list containing the actual number of\n% regions in each collar, given the list containing the ideal number of\n% regions.\n% 7. Create a list containing the colatitude of the top of each zone,\n% given the list containing the actual number of regions in each collar,\n% and the colatitudes of the polar caps.\n%\n%Examples\n% > illustrate_eq_algorithm(3,99)\n% > illustrate_eq_algorithm(3,99,'offset','extra','proj','eqarea')\n% > illustrate_eq_algorithm(3,99,'proj','eqarea','points','hide')\n%\n%See also\n% PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, SUBPLOT\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-13 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\npdefault.extra_offset = false;\n\npopt = partition_options(pdefault, varargin{:});\n\ngdefault.fontsize = 16;\ngdefault.show_title = true;\ngdefault.long_title = false;\ngdefault.stereo = false;\ngdefault.show_points = true;\n\ngopt = illustration_options(gdefault, varargin{:});\nopt_args = option_arguments(popt,gopt);\n\nsubplot(2,2,1);axis off\nillustrate_steps_1_2(dim,N,opt_args);\n\nsubplot(2,2,2);axis off\nillustrate_steps_3_5(dim,N,opt_args);\n\nsubplot(2,2,3);axis off\nillustrate_steps_6_7(dim,N,opt_args);\n\nsubplot(2,2,4);axis off\ncla\n\ngopt.fontsize = 32;\nswitch dim\ncase 2\n opt_args = option_arguments(popt,gopt);\n project_s2_partition(N,opt_args{:});\ncase 3\n opt_args = option_arguments(popt,gopt);\n [s,m] = eq_caps(dim,N);\n max_collar = min(4,size(m,2)-2);\n for k = 1:max_collar\n subn = 9+2*k-mod(k-1,2);\n subplot(4,4,subn);axis off\n project_s2_partition(m(1+k),opt_args{:});\n end\nend\n%\n% end function\n\nfunction illustrate_steps_1_2(dim,N,varargin)\n% Illustrate steps 1 and 2 of the EQ partition of S^dim into N regions;\n%\n% illustrate_steps_1_2(dim,N,options);\n\ngdefault.fontsize = 14;\ngdefault.show_title = true;\ngdefault.long_title = false;\n\ngopt = illustration_options(gdefault, varargin{:});\nh = [0:1/90:1];\n% Plot a circle to represent dth coordinate of S^d\nPhi = h*2*pi;\nplot(sin(Phi),cos(Phi),'k','LineWidth',1)\naxis equal;axis off;hold on\n\nc_polar = polar_colat(dim,N);\n\nk = [-1:1/20:1];\nj = ones(size(k));\n\n% Plot the bounding parallels of the polar caps\nplot(sin(c_polar)*k, cos(c_polar)*j,'r','LineWidth',2)\nplot(sin(c_polar)*k,-cos(c_polar)*j,'r','LineWidth',2)\n\n% Plot the North-South axis\nplot(zeros(size(j)),k,'b','LineWidth',1)\n% Plot the polar angle\nplot(sin(c_polar)*h,cos(c_polar)*h,'b','LineWidth',2)\n\ntext(0.05,2/3,'\\theta_c','Fontsize',gopt.fontsize);\n\n% Plot the ideal collar angle\nDelta_I = ideal_collar_angle(dim,N);\ntheta = c_polar + Delta_I;\nplot(sin(theta)*h,cos(theta)*h,'b','LineWidth',2)\n\nmid = c_polar + Delta_I/2;\ntext(sin(mid)*2/3,cos(mid)*2/3,'\\Delta_I','Fontsize',gopt.fontsize);\n\n% Plot an arc to indicate angles\ntheta = h*(c_polar + Delta_I);\nplot(sin(theta)/5,cos(theta)/5,'b','LineWidth',1)\n\ntext(-0.9,-0.1,sprintf('V(\\\\theta_c) = V_R \\n = \\\\sigma(S^{%d})/%d',dim,N),...\n 'Fontsize',gopt.fontsize);\n\ncaption_angle = min(mid + 2*Delta_I,pi-c_polar);\ntext(sin(caption_angle)/3,cos(caption_angle)/3,sprintf('\\\\Delta_I = V_R^{1/%d}',dim),...\n 'Fontsize',gopt.fontsize);\n\nif gopt.show_title\n title_str = sprintf('EQ(%d,%d) Steps 1 to 2\\n',dim,N);\n title(title_str,'Fontsize',gopt.fontsize);\nend\n\nhold off\n%\n% end function\n\nfunction illustrate_steps_3_5(dim,N,varargin)\n% Illustrate steps 3 to 5 of the EQ partition of S^dim into N regions;\n%\n% illustrate_steps_3_5(dim,N,options);\n\ngdefault.fontsize = 14;\ngdefault.show_title = true;\ngdefault.long_title = false;\n\ngopt = illustration_options(gdefault, varargin{:});\n\nh = [0:1/90:1];\nPhi = h*2*pi;\nplot(sin(Phi),cos(Phi),'k','LineWidth',1)\naxis equal;axis off;hold on\n\nc_polar = polar_colat(dim,N);\nn_collars = num_collars(N,c_polar,ideal_collar_angle(dim,N));\nr_regions = ideal_region_list(dim,N,c_polar,n_collars);\ns_cap = cap_colats(dim,N,c_polar,r_regions);\n\nk = [-1:1/20:1];\nj = ones(size(k));\nplot(sin(c_polar)*k, cos(c_polar)*j,'r','LineWidth',2);\n\nplot(zeros(size(j)),k,'b','LineWidth',1)\n\nfor collar_n = 0:n_collars\n zone_n = 1+collar_n;\n theta = s_cap(zone_n);\n plot(sin(theta)*h,cos(theta)*h,'b','LineWidth',2);\n theta_str = sprintf('\\\\theta_{F,%d}',zone_n);\n text(sin(theta)*1.1,cos(theta)*1.1,theta_str,'Fontsize',gopt.fontsize);\n if collar_n ~= 0\n plot(sin(theta)*k, cos(theta)*j,'r','LineWidth',2);\n theta_p = s_cap(collar_n);\n arc = theta_p + (theta-theta_p)*h;\n plot(sin(arc)/5,cos(arc)/5,'b','LineWidth',1);\n mid = (theta_p + theta)/2;\n text(sin(mid)/2,cos(mid)/2,'\\Delta_F','Fontsize',gopt.fontsize);\n y_str = sprintf('y_{%d} = %3.1f...',collar_n,r_regions(zone_n));\n text(-sin(mid)+1/20,cos(mid)+(mid-pi)/30,y_str,'Fontsize',gopt.fontsize);\n end\nend\nif gopt.show_title\n title_str = sprintf('EQ(%d,%d) Steps 3 to 5\\n',dim,N);\n title(title_str,'Fontsize',gopt.fontsize);\nend\nhold off\n%\n% end function\n\nfunction illustrate_steps_6_7(dim,N,varargin)\n% Illustrate steps 6 to 7 of the EQ partition of S^dim into N regions;\n%\n% illustrate_steps_6_7(dim,N,options);\n\ngdefault.fontsize = 14;\ngdefault.show_title = true;\ngdefault.long_title = false;\n\ngopt = illustration_options(gdefault, varargin{:});\n\nh = [0:1/90:1];\nPhi = h*2*pi;\nplot(sin(Phi),cos(Phi),'k','LineWidth',1)\naxis equal;axis off;hold on\n\nc_polar = polar_colat(dim,N);\nn_collars = num_collars(N,c_polar,ideal_collar_angle(dim,N));\nr_regions = ideal_region_list(dim,N,c_polar,n_collars);\nn_regions = round_to_naturals(N,r_regions);\ns_cap = cap_colats(dim,N,c_polar,n_regions);\n\nk = [-1:1/20:1];\nj = ones(size(k));\nplot(sin(c_polar)*k, cos(c_polar)*j,'r','LineWidth',2);\n\nplot(zeros(size(j)),k,'b','LineWidth',1)\n\nfor collar_n = 0:n_collars\n zone_n = 1+collar_n;\n theta = s_cap(zone_n);\n plot(sin(theta)*h,cos(theta)*h,'b','LineWidth',2);\n theta_str = sprintf('\\\\theta_{%d}',zone_n);\n text(sin(theta)*1.1,cos(theta)*1.1,theta_str,'Fontsize',gopt.fontsize);\n if collar_n ~= 0\n plot(sin(theta)*k, cos(theta)*j,'r','LineWidth',2);\n theta_p = s_cap(collar_n);\n arc = theta_p + (theta-theta_p)*h;\n plot(sin(arc)/5,cos(arc)/5,'b','LineWidth',1);\n mid = (theta_p + theta)/2;\n Delta_str = sprintf('\\\\Delta_{%i}',collar_n);\n text(sin(mid)/2,cos(mid)/2,Delta_str,'Fontsize',gopt.fontsize);\n m_str = sprintf('m_{%d} =%3.0f',collar_n,n_regions(zone_n));\n text(-sin(mid)+1/20,cos(mid)+(mid-pi)/30,m_str,'Fontsize',gopt.fontsize);\n end\nend\nif gopt.show_title\n title_str = sprintf('EQ(%d,%d) Steps 6 to 7\\n',dim,N);\n title(title_str,'Fontsize',gopt.fontsize);\nend\nhold off\n%\n% end function\n\nfunction arg = option_arguments(popt,gopt)\n\nk = 1;\nif isfield(popt,'extra_offset')\n arg{k} = 'offset';\n if popt.extra_offset\n arg{k+1} = 'extra';\n else\n arg{k+1} = 'normal';\n end\n k = k+2;\nend\n\nif isfield(gopt,'fontsize')\n arg{k} = 'fontsize';\n arg{k+1} = gopt.fontsize;\n k = k+2;\nend\n\nif isfield(gopt,'stereo')\n arg{k} = 'proj';\n if gopt.stereo\n arg{k+1} = 'stereo';\n else\n arg{k+1} = 'eqarea';\n end\n k = k+2;\nend \n\nif isfield(gopt,'show_title')\n arg{k} = 'title';\n if gopt.show_title\n if isfield(gopt,'long_title')\n if gopt.long_title\n arg{k+1} = 'long';\n else\n arg{k+1} = 'short';\n end\n else\n arg{k+1} = 'show';\n end\n else\n arg{k+1} = 'none';\n end\n k = k+2;\nelseif isfield(gopt,'long_title')\n arg{k} = 'title';\n if gopt.long_title\n arg{k+1} = 'long';\n else\n arg{k+1} = 'short';\n end\n k = k+2;\nend\n\n\nif isfield(gopt,'show_points')\n arg{k} = 'points';\n if gopt.show_points\n arg{k+1} = 'show';\n else\n arg{k+1} = 'hide';\n end\n k = k+2;\nend\n\nif isfield(gopt,'show_surfaces')\n arg{k} = 'surf';\n if gopt.show_surfaces\n arg{k+1} = 'show';\n else\n arg{k+1} = 'hide';\n end\n k = k+2;\nend \n\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "expand_region_for_diam.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_region_props/private/expand_region_for_diam.m", "size": 1159, "source_encoding": "utf_8", "md5": "7e9858ac0283f7c2396c3d6727ead0b7", "text": "function expanded_region = expand_region_for_diam(region)\n%EXPAND_REGION_FOR_DIAM The set of 2^d vertices of a region\n%\n% Expand a region from the 2 vertex definition to the set of 2^dim vertices\n% of the pseudo-region of a region, so that the Euclidean diameter of a region \n% is approximated by the diameter of this set.\n%\n% expanded_region = expand_region_for_diam(region);\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\ndim = size(region,1);\nif dim > 1\n s_top = region(dim,1);\n s_bot = region(dim,2);\n region_1 = expand_region_for_diam(region(1:dim-1,:));\n expanded_region = [append(region_1, s_top), append(region_1, s_bot)];\nelse\n expanded_region = pseudo_region_for_diam(region);\nend\n%\n% end function\n\nfunction result = append(matrix,value)\n% Append a coordinate value to each column of a matrix.\n%\n% result = append(matrix,value);\n\nresult = [matrix; ones(1,size(matrix,2))*value];\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "max_vertex_diam_of_regions.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_region_props/private/max_vertex_diam_of_regions.m", "size": 1945, "source_encoding": "utf_8", "md5": "06d6d3f18a8b458a382632d6c252e136", "text": "function vertex_diam = max_vertex_diam_of_regions(regions)\n%MAX_VERTEX_DIAM_OF_REGIONS The max vertex diameter in a cell array of regions\n%\n% vertex_diam = max_vertex_diam_of_regions(regions);\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Function changed name from s2x to polar2cart\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\ndim = size(regions,1);\nif dim == 1\n vertex_diam = vertex_diam_region(regions(:,:,1));\nelse\n colatitude = -inf*ones(dim-1,1);\n vertex_diam = 0;\n N = size(regions,3);\n for region_n = 1:N\n top = regions(:,1,region_n);\n if norm(top(2:dim)-colatitude) ~= 0\n colatitude = top(2:dim);\n vertex_diam = max(vertex_diam,vertex_diam_region(regions(:,:,region_n)));\n end\n end\nend\n%\n% end function\n\nfunction diam = vertex_diam_region(region)\n% Calculate the Euclidean diameter of the set of 2^dim vertices\n% of the pseudo-region of a region.\n%\n% diam = vertex_diam_region(region);\n\nexpanded_region = expand_region_for_diam(region);\ndim = size(expanded_region,1);\nfull = size(expanded_region,2);\nhalf = floor(full/2);\ntop = expanded_region(:,1);\nbot = expanded_region(:,full);\ndiam = 0;\nif sin(top(dim)) > sin(bot(dim))\n for point_n_1 = 1:2:half\n for point_n_2 = point_n_1+1:2:full\n x1 = polar2cart(expanded_region(:,point_n_1));\n x2 = polar2cart(expanded_region(:,point_n_2));\n diam = max(diam,euclidean_dist(x1,x2));\n end\n end\nelse\n for point_n_1 = full:-2:half+1\n for point_n_2 = point_n_1-1:-2:1\n x1 = polar2cart(expanded_region(:,point_n_1));\n x2 = polar2cart(expanded_region(:,point_n_2));\n diam = max(diam,euclidean_dist(x1,x2));\n end\n end\nend\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "max_diam_bound_of_regions.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_region_props/private/max_diam_bound_of_regions.m", "size": 1775, "source_encoding": "utf_8", "md5": "40cdd90073575c36f53cfb9196f84187", "text": "function diam_bound = max_diam_bound_of_regions(regions)\n%MAX_DIAM_BOUND_OF_REGIONS The maximum diameter bound in an array of regions\n%\n% diam_bound = max_diam_bound_of_regions(regions);\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Function s2e changed name to sph2euc_dist\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\ndim = size(regions,1);\nif dim == 1\n diam_bound = diam_bound_region(regions(:,:,1));\nelse\n colatitude = -inf*ones(dim-1,1);\n diam_bound = 0;\n N = size(regions,3);\n for region_n = 1:N\n top = regions(:,1,region_n);\n if norm(top(2:dim)-colatitude) ~= 0\n colatitude = top(2:dim);\n diam_bound = max(diam_bound,diam_bound_region(regions(:,:,region_n)));\n end\n end\nend\n%\n% end function\n\nfunction diam_bound = diam_bound_region(region)\n% Calculate the per-region bound on the Euclidean diameter of a region.\n%\n% diam_bound = diam_bound_region(region)\n\ntol = eps*2^5;\npseudo_region = pseudo_region_for_diam(region);\ndim = size(pseudo_region,1);\ntop = pseudo_region(:,1);\nbot = pseudo_region(:,2);\ndiam_bound = 0;\ns = bot(dim)-top(dim);\ne = sph2euc_dist(s);\nif dim == 1\n diam_bound = e;\nelse\n max_sin = max(sin(top(dim)),sin(bot(dim)));\n if (top(dim) <= pi/2) && (bot(dim) >= pi/2)\n max_sin = 1;\n end\n if (abs(top(dim)) < tol) || (abs(pi-bot(dim)) < tol)\n diam_bound = 2*max_sin;\n else\n region_1 = [top(1:dim-1),bot(1:dim-1)];\n diam_bound_1 = max_sin*diam_bound_region(region_1);\n diam_bound = min(2,sqrt(e^2+diam_bound_1^2));\n end\nend\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "eq_area_error.m", "ext": ".m", "path": "libDirectional-master/lib/external/eq_sphere_partitions/eq_test/eq_area_error.m", "size": 3108, "source_encoding": "utf_8", "md5": "167106e355712248825d71c9393c02b0", "text": "function [total_error, max_error] = eq_area_error(dim,N)\n%EQ_AREA_ERROR Total area error and max area error per region of an EQ partition\n%\n%Syntax\n% [total_error, max_error] = eq_area_error(dim,N)\n%\n%Description\n% [TOTAL_ERROR, MAX_ERROR] = EQ_AREA_ERROR(dim,N) does the following:\n% 1) uses the recursive zonal equal area sphere partitioning algorithm to \n% partition the unit sphere S^dim into N regions,\n% 2) sets TOTAL_ERROR to be the absolute difference between the total area of\n% all regions of the partition, and the area of S^dim, and\n% 3) sets MAX_ERROR to be the maximum absolute difference between the area of \n% any region of the partition, and the ideal area of a region as given by\n% AREA_OF_IDEAL_REGION(dim,N), which is 1/N times the area of S^dim.\n%\n% The argument dim must be a positive integer.\n% The argument N must be a positive integer or an array of positive integers. \n% The results TOTAL_ERROR and MAX_ERROR will be arrays of the same size as N.\n%\n%Examples\n% > [total_error, max_error] = eq_area_error(2,10)\n% total_error =\n% 1.7764e-15\n% \n% max_error =\n% 4.4409e-16\n% \n% > [total_error, max_error] = eq_area_error(3,1:6)\n% total_error =\n% 1.0e-12 *\n% 0.0036 0.0036 0.1847 0.0142 0.0142 0.2132\n% \n% max_error =\n% 1.0e-12 *\n% 0.0036 0.0018 0.1954 0.0284 0.0440 0.0777\n%\n%See also\n% EQ_REGIONS, AREA_OF_SPHERE, AREA_OF_IDEAL_REGION\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\n%\n% Check number of arguments\n%\nnarginchk(2,2);\nnargoutchk(2,2);\n\n%\n% Flatten N into a row vector.\n%\nshape = size(N);\nn_partitions = prod(shape);\nN = reshape(N,1,n_partitions);\n\ntotal_error = zeros(size(N));\nmax_error = zeros(size(N));\nsphere_area = area_of_sphere(dim);\n\nfor partition_n = 1:n_partitions\n n = N(partition_n);\n regions = eq_regions(dim,n);\n ideal_area = area_of_ideal_region(dim,n);\n total_area = 0;\n for region_n = 1:size(regions,3)\n area = area_of_region(regions(:,:,region_n));\n total_area = total_area + area;\n region_error = abs(area - ideal_area);\n if region_error > max_error(partition_n)\n max_error(partition_n) = region_error;\n end\n end\n total_error(partition_n) = abs(sphere_area - total_area);\nend\n%\n% Reshape output to same array size as original N.\n%\ntotal_error = reshape(total_error,shape);\nmax_error = reshape(max_error,shape);\n%\n% end function\n\nfunction area = area_of_region(region)\n%AREA_OF_REGION Area of given region\n%\n% area = area_of_region(region);\n\ndim = size(region,1);\ns_top = region(dim,1);\ns_bot = region(dim,2);\nif dim > 1\n area = area_of_collar(dim, s_top, s_bot)*area_of_region(region(1:dim-1,:))/area_of_sphere(dim-1);\nelse\n if s_bot == 0\n s_bot = 2*pi;\n end\n if s_top == s_bot\n s_bot = s_top + 2*pi;\n end\n area = s_bot - s_top;\nend\n%\n% end function\n"} +{"plateform": "github", "repo_name": "libDirectional/libDirectional-master", "name": "DiscreteHypersphericalFilter.m", "ext": ".m", "path": "libDirectional-master/lib/filters/DiscreteHypersphericalFilter.m", "size": 21276, "source_encoding": "utf_8", "md5": "8956277005138d99e8f538738913764f", "text": "classdef DiscreteHypersphericalFilter < AbstractHypersphericalFilter\n % A discrete filter on the hypersphere \n \n properties\n d\n w\n DT\n end\n \n methods\n function this = DiscreteHypersphericalFilter(nParticles, dim, method) \n % Constructor\n %\n % Parameters:\n % nParticles (integer > 0)\n % number of particles to use\n if nargin < 3\n method = 'equalarea';\n end \n this.d = DiscreteHypersphericalFilter.computeDiscretization(nParticles, dim, method);\n nParticles = size(this.d,2); %the actual number of particles may be different from the requested number of particles\n this.w = ones(1,nParticles)/nParticles;\n %this.DT = delaunayTriangulation(this.d') ;\n this.DT = convhulln(this.d');\n end\n \n function setState(this, distribution)\n % Sets the current system state\n %\n % Parameters:\n % distribution (AbstractHypersphericalDistribution)\n % new state\n assert(isa(distribution, 'AbstractHypersphericalDistribution'));\n this.w = distribution.pdf(this.d);\n this.w = this.w/sum(this.w);\n end\n \n function d = dim(this)\n d = size(this.d,1);\n end\n \n function predictNonlinear(this, f, noiseDistribution)\n % where w(k) is noise given by noiseDistribution.\n % Predicts assuming a nonlinear system model, i.e.,\n % f(x(k+1)|x_k) = VMF(x(k+1) ; mu = f(x_k), kappa_k^w)\n % where w is noise given by sysNoise.\n %\n % Parameters:\n % f (function handle)\n % function from S^(dim-1) to S^(dim-1)\n % noiseDistribution (VMFDistribution)\n % distribution of noise\n assert(isa (noiseDistribution, 'VMFDistribution')); %todo generalize to Watson etc.\n assert(isa(f,'function_handle'));\n \n %apply f\n nParticles = length(this.d);\n w_ = zeros(size(this.w)); % set all weights to zero\n for i=1:nParticles\n newLocation = f(this.d(:,i)); \n noiseDistribution.mu = newLocation;\n w_ = w_ + this.w(i)*noiseDistribution.pdf(this.d);\n end\n \n this.w = w_;\n end\n \n function predictNonlinearNonAdditive(this, f, noiseSamples, noiseWeights, mode) \n % Predicts assuming a nonlinear system model, i.e.,\n % x(k+1) = f(x(k), w(k))\n % where w(k) is non-additive noise given by samples and weights.\n %\n % Parameters:\n % f (function handle)\n % function from S^(dim-1) x W to S^(dim-1) (W is the space\n % containing the noise samples)\n % noiseSamples (d2 x n matrix)\n % n samples of the noise as d2-dimensional vectors\n % noiseWeights (1 x n vector)\n % weight of each sample\n \n % (samples, weights) are discrete approximation of noise\n assert(size(noiseWeights,1) == 1, 'weights most be row vector')\n assert(size(noiseSamples,2) == size(noiseWeights,2), 'samples and weights must match in size');\n assert(isa(f,'function_handle'));\n \n noiseWeights = noiseWeights/sum(noiseWeights); % ensure normalization\n \n if nargin <= 4\n mode = 'nn';\n end\n\n % apply f\n nParticles = length(this.d);\n oldWeights = this.w;\n this.w = zeros(size(this.w)); % set all weights to zero\n for i=1:nParticles\n for j=1:length(noiseSamples)\n newLocation = f(this.d(:,i),noiseSamples(:,j));\n newWeight = oldWeights(i)*noiseWeights(j);\n if strcmp(mode, 'nn')\n %simple nearest neighbor assignment for now\n idx = knnsearch(this.d', newLocation');\n this.w(idx) = this.w(idx) + newWeight;\n elseif strcmp(mode, 'delaunay')\n %todo: only works in 3D so far?\n if this.dim == 3\n %find triangle\n [t,u,v] = this.findTriangle(newLocation);\n %interpolate in triangle\n this.w(t(1)) = this.w(t(1)) + (1-u-v)*newWeight;\n this.w(t(2)) = this.w(t(2)) + u*newWeight;\n this.w(t(3)) = this.w(t(3)) + v*newWeight;\n else\n error('not supported')\n end\n elseif strcmp(mode, 'knn')\n k=3;\n [idx,D] = knnsearch(this.d', newLocation', 'K', k);\n %todo test, verify that weights sum to 1\n %todo this can lead to negative weights!\n for l=1:k \n this.w(idx(l)) = this.w(idx(l)) + (sum(D)-(k-1)*D(l))/sum(D)*newWeight;\n end\n else\n error('unsupported mode');\n end\n end\n end \n end\n \n function [triangle, u, v] = findTriangle(this, x)\n [int, ~, u, v] = TriangleRayIntersection([0,0,0], x, this.d(:,this.DT(:,1)), this.d(:,this.DT(:,2)), this.d(:,this.DT(:,3)));\n index = find(int,1);\n assert(~isempty(index)); %if this fails, no triangle was found due to numerical inaccuracy - how to handle that?\n triangle = this.DT(index,:);\n u = u(index);\n v = v(index);\n end\n \n function updateNonlinear(this, likelihood, z) \n % Updates assuming nonlinear measurement model given by a\n % likelihood function likelihood(z,x) = f(z|x), where z is the\n % measurement. The function can be created using the\n % LikelihoodFactory.\n % \n % Parameters:\n % likelihood (function handle)\n % function from Z x [0,2pi) to [0, infinity), where Z is\n % the measurement space containing z\n % z (arbitrary)\n % measurement\n \n assert(isa(likelihood,'function_handle'));\n \n % You can either use a likelihood depending on z and x\n % and specify the measurement as z or use a likelihood that\n % depends only on x and omit z.\n if nargin==2\n this.w = this.w .* likelihood(this.d);\n else\n this.w = this.w .* likelihood(z, this.d);\n end\n end\n \n function [d,w] = getEstimate(this)\n % Return current estimate \n %\n % Returns:\n d = this.d;\n w = this.w;\n end\n \n function plotEstimate(this)\n switch this.dim\n case 2\n scatter3(this.d(1,:), this.d(2,:), this.w)\n case 3\n scatter3(this.d(1,:), this.d(2,:), this.d(3,:), length(this.w)*10*this.w)\n otherwise\n error('not implemented')\n end\n end\n \n function m = getEstimateMean(this)\n m = sum(this.d.*repmat(this.w, this.dim, 1),2);\n m = m/norm(m);\n end\n end\n \n methods (Static)\n function d = computeDiscretization(nParticles, dim, method)\n function r = goalFun (d)\n d = d./repmat(sqrt(sum(d.^2)),size(d,1),1);\n [~, dist] = knnsearch(d',d', 'K', 2);\n r = -sum((dist(:,2)));\n end \n \n if strcmp(method, 'random')\n d = rand(dim, nParticles)-0.5;\n d = d./repmat(sqrt(sum(d.^2)),dim,1);\n elseif strcmp(method, 'stratified')\n assert(dim == 3);\n d = RandSampleSphere(nParticles, 'stratified')';\n elseif strcmp(method, 'optimize')\n if dim == 2\n % use simple closed form solution in 2D\n phi = linspace(0,2*pi,nParticles + 1);\n phi = phi(1:end-1);\n d = [cos(phi);sin(phi)];\n else\n [pathstr,~,~] = fileparts(mfilename('fullpath'));\n filename = sprintf('%s/../util/autogenerated/optimize-%i-%i.mat', pathstr, nParticles, dim);\n if exist(filename, 'file')\n load (filename);\n else\n %initialize with random values\n %d = rand(dim, nParticles)-0.5;\n %d = d./repmat(sqrt(sum(d.^2)),dim,1);\n %initialize with equal area solution\n d = eq_point_set(dim-1, nParticles);\n %todo improve solution quality and performance\n d = fminunc(@goalFun, d, optimoptions('fminunc', 'display', 'iter', 'MaxFunEvals', 1E6));\n d = d./repmat(sqrt(sum(d.^2)),dim,1);\n save(filename, 'd');\n end\n end\n elseif strcmp(method, 'platonic')\n assert(dim == 3);\n %todo generate next larger polyhedron instead of insisting\n %on number of particles\n switch nParticles\n case 4\n d = DiscreteHypersphericalFilter.tetrahedron();\n case 6\n d = DiscreteHypersphericalFilter.octahedron();\n case 8\n d = DiscreteHypersphericalFilter.hexahedron();\n case 12\n d = DiscreteHypersphericalFilter.icosahedron();\n case 20\n d = DiscreteHypersphericalFilter.dodecahedron();\n otherwise\n error('unsupported number of particles');\n end\n elseif strcmp(method, 'spiral')\n assert(dim == 3);\n d = SpiralSampleSphere(nParticles)';\n elseif strcmp(method, 'reisz')\n assert(dim == 3);\n if nParticles<14 \n nParticles = 14;\n end\n d = ParticleSampleSphere('N', nParticles)';\n elseif strcmp(method, 'cubesubdivision')\n %number of points: 6*4.^n+2\n assert(dim == 3);\n c = QuadCubeMesh();\n while size(c.vertices, 1) < nParticles\n % subdivide untile we have at least nParticles\n c = SubdivideSphericalMesh(c,1);\n end\n d = c.vertices';\n elseif strcmp(method, 'pentakissubdivision')\n %number of points 30*4.^n+2\n assert(dim == 3);\n c = DodecahedronMesh();\n while size(c.Points, 1) < nParticles\n % subdivide untile we have at least nParticles\n c = SubdivideSphericalMesh(c,1);\n end\n d = c.Points'; \n elseif strcmp(method, 'rhombicsubdivision')\n %number of points 12*4.^n+2\n assert(dim == 3);\n c = QuadRhombDodecMesh();\n while size(c.vertices, 1) < nParticles\n % subdivide untile we have at least nParticles\n c = SubdivideSphericalMesh(c,1);\n end\n d = c.vertices'; \n elseif strcmp(method, 'icosahedronsubdivision')\n %number of points: 10*4.^n+2\n %https://oeis.org/A122973\n assert(dim == 3);\n c = IcosahedronMesh();\n while size(c.Points, 1) < nParticles\n % subdivide untile we have at least nParticles\n c = SubdivideSphericalMesh(c,1);\n end\n d = c.Points'; \n elseif strcmp(method, 'equalarea')\n d = eq_point_set(dim-1, nParticles);\n elseif strcmp(method, 'gridsphere')\n assert(dim == 3);\n [lat,lon] = GridSphere(nParticles);\n lat = lat/180*pi;\n lon = lon/180*pi;\n\n x = cos(lat) .* cos(lon);\n y = cos(lat) .* sin(lon);\n z = sin(lat);\n d = [x'; y'; z'];\n elseif strcmp(method, 'schaefer')\n assert(dim == 4);\n %will return 2*8^n points for n=1,2,3,...\n d = tessellate_S3(nParticles);\n elseif strcmp(method, 'regular4polytope')\n assert(dim == 4);\n %todo implement remaining 4 polytopes?\n if nParticles <=24\n d = DiscreteHypersphericalFilter.generate24cell();\n elseif nParticles <=120\n d = DiscreteHypersphericalFilter.generate600cell();\n elseif nParticles<=600\n d = DiscreteHypersphericalFilter.generate120cell();\n else\n d = DiscreteHypersphericalFilter.generate120cell();\n %todo warning/error?\n end\n elseif strcmp(method, 'tesseractsubdivision')\n assert(dim == 4);\n d = tesseractsubdivision(nParticles)';\n else\n error('unsupported method')\n end\n end\n \n function d = tetrahedron()\n % see https://en.wikipedia.org/wiki/Tetrahedron#Formulas_for_a_regular_tetrahedron\n d = [1 0 -1/sqrt(2);\n -1 0 -1/sqrt(2);\n 0 1 1/sqrt(2);\n 0 -1 1/sqrt(2)]';\n d = d./repmat(sqrt(sum(d.^2)),size(d,1),1); \n end\n \n function d = hexahedron()\n % see https://en.wikipedia.org/wiki/Cube#Cartesian_coordinates\n d = [1 1 1;\n 1 1 -1;\n 1 -1 1;\n 1 -1 -1;\n -1 1 1;\n -1 1 -1;\n -1 -1 1;\n -1 -1 -1]'/sqrt(3); \n end\n \n function d = octahedron()\n % see https://en.wikipedia.org/wiki/Octahedron#Cartesian_coordinates\n d = [1 0 0 ;\n 0 1 0;\n 0 0 1]';\n d = [d -d];\n end\n \n function d = dodecahedron()\n % see https://en.wikipedia.org/wiki/Dodecahedron#Cartesian_coordinates\n h = (sqrt(5)-1)/2; % inverse golden ratio\n a = 1+h;\n b = 1-h^2;\n d = [1 1 1;\n 1 1 -1;\n 1 -1 1;\n 1 -1 -1;\n -1 1 1;\n -1 1 -1;\n -1 -1 1;\n -1 -1 -1;\n 0 a b;\n 0 a -b;\n 0 -a b;\n 0 -a -b;\n a, b, 0;\n a, -b, 0;\n -a, b, 0;\n -a, -b, 0;\n b, 0, a;\n b, 0, -a;\n -b, 0, a;\n -b, 0, -a;\n ]'; \n d = d./repmat(sqrt(sum(d.^2)),size(d,1),1);\n end\n \n function d = icosahedron()\n % see https://en.wikipedia.org/wiki/Regular_icosahedron#Cartesian_coordinates\n phi = (1+sqrt(5))/2; % golden ratio\n d = [0 1 phi;\n 1 phi 0;\n phi 0 1;\n 0 -1 phi;\n -1 phi 0;\n phi 0 -1]';\n d = [d -d];\n d = d./repmat(sqrt(sum(d.^2)),size(d,1),1);\n end\n \n function d = generate600cell()\n % Generates 600 cell in 4D\n % see https://en.wikipedia.org/wiki/600-cell\n % The 600 cell has 120 vertices!\n phi = (1+sqrt(5))/2; % golden ratio\n signs3 = 2*(dec2bin(0:7)-'0')-1;\n p = evenperms(4);\n \n %16 vertices on [+-0.5, +-0.5, +-0.5, +-0.5]\n d1 = dec2bin(0:2^4-1)-'0'-0.5;\n %8 vertices on permutations of [0 0 0 +-1]\n d2 = dec2bin(2.^(0:3))-'0';\n d3 = -d2;\n %96 vertices on even permutations of 0.5 [+-phi, +-1, +-1/phi,0]\n d4 = zeros(96,4);\n index = 1;\n for j=1:size(p,1) %iterate over permutations\n for i=1:size(signs3,1) %iterate over 8 different combinations of signs\n currentPoint = 0.5* [ [phi , 1 , 1/phi].*signs3(i,:), 0];\n d4(index,:) = currentPoint(p(j,:));\n index = index + 1;\n end\n end\n d = [d1; d2; d3; d4]';\n d = d./repmat(sqrt(sum(d.^2)),size(d,1),1);\n end\n \n function d = generate120cell()\n % Generates 120 cell in 4D\n % see https://en.wikipedia.org/wiki/120-cell\n % and http://mathworld.wolfram.com/120-Cell.html\n % The 120 cell has 600 vertices!\n phi = (1+sqrt(5))/2; % golden ratio\n signs3 = 2*(dec2bin(0:7)-'0')-1;\n signs4 = 2*(dec2bin(0:15)-'0')-1;\n p = evenperms(4);\n shiftRight = [0 1 0 0; 0 0 1 0; 0 0 0 1; 1 0 0 0];\n \n % permutations of [0, 0, +-2, +-2]\n %d1 = [zeros(4,2) (dec2bin(0:3)-'0')*4-2];\n d1 = [perms([0 0 -2 -2]); perms([0 0 -2 2]); perms([0 0 2 2])];\n d1 = unique(d1,'rows');\n \n % permutations of [+-1, +-1, +-1,, +-sqrt(5)]\n d2 = signs4.*repmat([1 1 1 sqrt(5)], 16, 1);\n d2 = [d2; d2*shiftRight; d2*shiftRight^2; d2*shiftRight^3];\n \n % permutations of [+- phi^(-2), +-phi, +-phi, +-phi]\n d3 = signs4.*repmat([phi^(-2), phi, phi, phi], 16, 1);\n d3 = [d3; d3*shiftRight; d3*shiftRight^2; d3*shiftRight^3];\n \n % permutations of [+- phi^(-1), +- phi^(-1), +-phi^(-1), +-phi^2]\n d4 = signs4.*repmat([phi^(-1), phi^(-1), phi^(-1), phi^2], 16, 1);\n d4 = [d4; d4*shiftRight; d4*shiftRight^2; d4*shiftRight^3];\n \n %even permutations of [0, +-phi^(-2), +-1, +-phi^2]\n d5 = zeros(96,4);\n index = 1;\n for j=1:size(p,1) %iterate over permutations\n for i=1:size(signs3,1) %iterate over 8 different combinations of signs\n currentPoint = [0, [phi^(-2) , 1 , phi^2].*signs3(i,:)];\n d5(index,:) = currentPoint(p(j,:));\n index = index + 1;\n end\n end \n \n %even permutations of [0, +-phi^(-1), +-phi, +-sqrt(5)]\n d6 = zeros(96,4);\n index = 1;\n for j=1:size(p,1) %iterate over permutations\n for i=1:size(signs3,1) %iterate over 8 different combinations of signs\n currentPoint = [0, [phi^(-1) , phi , sqrt(5)].*signs3(i,:)];\n d6(index,:) = currentPoint(p(j,:));\n index = index + 1;\n end\n end \n \n %even permutations of [+-phi^(-1), +-1, +-phi, +-2]\n d7 = zeros(192,4);\n index = 1;\n for j=1:size(p,1) %iterate over permutations\n for i=1:size(signs4,1) %iterate over 16 different combinations of signs\n currentPoint = [phi^(-1), 1, phi, 2].*signs4(i,:);\n d7(index,:) = currentPoint(p(j,:));\n index = index + 1;\n end\n end \n \n d = [d1; d2; d3; d4; d5; d6; d7]';\n d = d./repmat(sqrt(sum(d.^2)),size(d,1),1);\n end\n \n function d = generate24cell()\n % Generates 24 cell in 4D\n % see https://en.wikipedia.org/wiki/24-cell\n % The 24 cell has 24 vertices!\n signs4 = 2*(dec2bin(0:15)-'0')-1;\n shiftRight = [0 1 0 0; 0 0 1 0; 0 0 0 1; 1 0 0 0];\n \n %permutations of [+-1, 0, 0, 0]\n d1 = [1 0 0 0; -1 0 0 0];\n d1 = [d1; d1*shiftRight; d1*shiftRight^2; d1*shiftRight^3];\n \n %[+-0.5,+-0.5,+-0.5,+-0.5]\n d2 = signs4 * 0.5;\n \n d = [d1; d2;]';\n d = d./repmat(sqrt(sum(d.^2)),size(d,1),1);\n end\n end\n \nend\n\nfunction p = evenperms(n)\n %returns even permutations of 1,..,n\n p = perms(1:n);\n M = eye(n,n);\n e = false(1,size(p,1));\n for j=1:size(p,1) %iterate over permutations\n currentPerm = p(j,:);\n if det(M(currentPerm,:))==1 %check if permutation is even\n e(j)=1;\n end\n end\n p = p(e,:);\nend\n"} +{"plateform": "github", "repo_name": "jmportilla/stanford_dl_ex-master", "name": "WolfeLineSearch.m", "ext": ".m", "path": "stanford_dl_ex-master/common/minFunc_2012/minFunc/WolfeLineSearch.m", "size": 10590, "source_encoding": "utf_8", "md5": "f962bc5ae0a1e9f80202a9aaab106dab", "text": "function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(...\n x,t,d,f,g,gtd,c1,c2,LS_interp,LS_multi,maxLS,progTol,debug,doPlot,saveHessianComp,funObj,varargin)\n%\n% Bracketing Line Search to Satisfy Wolfe Conditions\n%\n% Inputs:\n% x: starting location\n% t: initial step size\n% d: descent direction\n% f: function value at starting location\n% g: gradient at starting location\n% gtd: directional derivative at starting location\n% c1: sufficient decrease parameter\n% c2: curvature parameter\n% debug: display debugging information\n% LS_interp: type of interpolation\n% maxLS: maximum number of iterations\n% progTol: minimum allowable step length\n% doPlot: do a graphical display of interpolation\n% funObj: objective function\n% varargin: parameters of objective function\n%\n% Outputs:\n% t: step length\n% f_new: function value at x+t*d\n% g_new: gradient value at x+t*d\n% funEvals: number function evaluations performed by line search\n% H: Hessian at initial guess (only computed if requested\n\n% Evaluate the Objective and Gradient at the Initial Step\nif nargout == 5\n [f_new,g_new,H] = funObj(x + t*d,varargin{:});\nelse\n [f_new,g_new] = funObj(x+t*d,varargin{:});\nend\nfunEvals = 1;\ngtd_new = g_new'*d;\n\n% Bracket an Interval containing a point satisfying the\n% Wolfe criteria\n\nLSiter = 0;\nt_prev = 0;\nf_prev = f;\ng_prev = g;\ngtd_prev = gtd;\nnrmD = max(abs(d));\ndone = 0;\n\nwhile LSiter < maxLS\n\n %% Bracketing Phase\n if ~isLegal(f_new) || ~isLegal(g_new)\n if debug\n fprintf('Extrapolated into illegal region, switching to Armijo line-search\\n');\n end\n t = (t + t_prev)/2;\n % Do Armijo\n if nargout == 5\n [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(...\n x,t,d,f,f,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,...\n funObj,varargin{:});\n else\n [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(...\n x,t,d,f,f,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,...\n funObj,varargin{:});\n end\n funEvals = funEvals + armijoFunEvals;\n return;\n end\n\n\n if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev)\n bracket = [t_prev t];\n bracketFval = [f_prev f_new];\n bracketGval = [g_prev g_new];\n break;\n elseif abs(gtd_new) <= -c2*gtd\n bracket = t;\n bracketFval = f_new;\n bracketGval = g_new;\n done = 1;\n break;\n elseif gtd_new >= 0\n bracket = [t_prev t];\n bracketFval = [f_prev f_new];\n bracketGval = [g_prev g_new];\n break;\n end\n temp = t_prev;\n t_prev = t;\n minStep = t + 0.01*(t-temp);\n maxStep = t*10;\n if LS_interp <= 1\n if debug\n fprintf('Extending Braket\\n');\n end\n t = maxStep;\n elseif LS_interp == 2\n if debug\n fprintf('Cubic Extrapolation\\n');\n end\n t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep);\n elseif LS_interp == 3\n t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot);\n end\n \n f_prev = f_new;\n g_prev = g_new;\n gtd_prev = gtd_new;\n if ~saveHessianComp && nargout == 5\n [f_new,g_new,H] = funObj(x + t*d,varargin{:});\n else\n [f_new,g_new] = funObj(x + t*d,varargin{:});\n end\n funEvals = funEvals + 1;\n gtd_new = g_new'*d;\n LSiter = LSiter+1;\nend\n\nif LSiter == maxLS\n bracket = [0 t];\n bracketFval = [f f_new];\n bracketGval = [g g_new];\nend\n\n%% Zoom Phase\n\n% We now either have a point satisfying the criteria, or a bracket\n% surrounding a point satisfying the criteria\n% Refine the bracket until we find a point satisfying the criteria\ninsufProgress = 0;\nTpos = 2;\nLOposRemoved = 0;\nwhile ~done && LSiter < maxLS\n\n % Find High and Low Points in bracket\n [f_LO LOpos] = min(bracketFval);\n HIpos = -LOpos + 3;\n\n % Compute new trial value\n if LS_interp <= 1 || ~isLegal(bracketFval) || ~isLegal(bracketGval)\n if debug\n fprintf('Bisecting\\n');\n end\n t = mean(bracket);\n elseif LS_interp == 2\n if debug\n fprintf('Grad-Cubic Interpolation\\n');\n end\n t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d\n bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot);\n else\n % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n nonTpos = -Tpos+3;\n if LOposRemoved == 0\n oldLOval = bracket(nonTpos);\n oldLOFval = bracketFval(nonTpos);\n oldLOGval = bracketGval(:,nonTpos);\n end\n t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\n end\n\n\n % Test that we are making sufficient progress\n if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1\n if debug\n fprintf('Interpolation close to boundary');\n end\n if insufProgress || t>=max(bracket) || t <= min(bracket)\n if debug\n fprintf(', Evaluating at 0.1 away from boundary\\n');\n end\n if abs(t-max(bracket)) < abs(t-min(bracket))\n t = max(bracket)-0.1*(max(bracket)-min(bracket));\n else\n t = min(bracket)+0.1*(max(bracket)-min(bracket));\n end\n insufProgress = 0;\n else\n if debug\n fprintf('\\n');\n end\n insufProgress = 1;\n end\n else\n insufProgress = 0;\n end\n\n % Evaluate new point\n if ~saveHessianComp && nargout == 5\n [f_new,g_new,H] = funObj(x + t*d,varargin{:});\n else\n [f_new,g_new] = funObj(x + t*d,varargin{:});\n end\n funEvals = funEvals + 1;\n gtd_new = g_new'*d;\n LSiter = LSiter+1;\n\n\tarmijo = f_new < f + c1*t*gtd;\n if ~armijo || f_new >= f_LO\n % Armijo condition not satisfied or not lower than lowest\n % point\n bracket(HIpos) = t;\n bracketFval(HIpos) = f_new;\n bracketGval(:,HIpos) = g_new;\n Tpos = HIpos;\n else\n if abs(gtd_new) <= - c2*gtd\n % Wolfe conditions satisfied\n done = 1;\n elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0\n % Old HI becomes new LO\n bracket(HIpos) = bracket(LOpos);\n bracketFval(HIpos) = bracketFval(LOpos);\n bracketGval(:,HIpos) = bracketGval(:,LOpos);\n if LS_interp == 3\n if debug\n fprintf('LO Pos is being removed!\\n');\n end\n LOposRemoved = 1;\n oldLOval = bracket(LOpos);\n oldLOFval = bracketFval(LOpos);\n oldLOGval = bracketGval(:,LOpos);\n end\n end\n % New point becomes new LO\n bracket(LOpos) = t;\n bracketFval(LOpos) = f_new;\n bracketGval(:,LOpos) = g_new;\n Tpos = LOpos;\n\tend\n\n if ~done && abs(bracket(1)-bracket(2))*nrmD < progTol\n if debug\n fprintf('Line-search bracket has been reduced below progTol\\n');\n end\n break;\n end\n\nend\n\n%%\nif LSiter == maxLS\n if debug\n fprintf('Line Search Exceeded Maximum Line Search Iterations\\n');\n end\nend\n\n[f_LO LOpos] = min(bracketFval);\nt = bracket(LOpos);\nf_new = bracketFval(LOpos);\ng_new = bracketGval(:,LOpos);\n\n\n\n% Evaluate Hessian at new point\nif nargout == 5 && funEvals > 1 && saveHessianComp\n [f_new,g_new,H] = funObj(x + t*d,varargin{:});\n funEvals = funEvals + 1;\nend\n\nend\n\n\n%%\nfunction [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot);\nalpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep);\nalpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep);\nif alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1)\n if debug\n fprintf('Cubic Extrapolation\\n');\n end\n t = alpha_c;\nelse\n if debug\n fprintf('Secant Extrapolation\\n');\n end\n t = alpha_s;\nend\nend\n\n%%\nfunction [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot);\n\n% Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nnonTpos = -Tpos+3;\n\ngtdT = bracketGval(:,Tpos)'*d;\ngtdNonT = bracketGval(:,nonTpos)'*d;\noldLOgtd = oldLOGval'*d;\nif bracketFval(Tpos) > oldLOFval\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\n alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd\n bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot);\n if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval)\n if debug\n fprintf('Cubic Interpolation\\n');\n end\n t = alpha_c;\n else\n if debug\n fprintf('Mixed Quad/Cubic Interpolation\\n');\n end\n t = (alpha_q + alpha_c)/2;\n end\nelseif gtdT'*oldLOgtd < 0\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\n alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd\n bracket(Tpos) sqrt(-1) gtdT],doPlot);\n if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos))\n if debug\n fprintf('Cubic Interpolation\\n');\n end\n t = alpha_c;\n else\n if debug\n fprintf('Quad Interpolation\\n');\n end\n t = alpha_s;\n end\nelseif abs(gtdT) <= abs(oldLOgtd)\n alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd\n bracket(Tpos) bracketFval(Tpos) gtdT],...\n doPlot,min(bracket),max(bracket));\n alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd\n bracket(Tpos) bracketFval(Tpos) gtdT],...\n doPlot,min(bracket),max(bracket));\n if alpha_c > min(bracket) && alpha_c < max(bracket)\n if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos))\n if debug\n fprintf('Bounded Cubic Extrapolation\\n');\n end\n t = alpha_c;\n else\n if debug\n fprintf('Bounded Secant Extrapolation\\n');\n end\n t = alpha_s;\n end\n else\n if debug\n fprintf('Bounded Secant Extrapolation\\n');\n end\n t = alpha_s;\n end\n\n if bracket(Tpos) > oldLOval\n t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\n else\n t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t);\n end\nelse\n t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT\n bracket(Tpos) bracketFval(Tpos) gtdT],doPlot);\nend\nend"} +{"plateform": "github", "repo_name": "jmportilla/stanford_dl_ex-master", "name": "minFunc_processInputOptions.m", "ext": ".m", "path": "stanford_dl_ex-master/common/minFunc_2012/minFunc/minFunc_processInputOptions.m", "size": 4103, "source_encoding": "utf_8", "md5": "8822581c3541eabe5ce7c7927a57c9ab", "text": "\r\nfunction [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,optTol,progTol,method,...\r\n corrections,c1,c2,LS_init,cgSolve,qnUpdate,cgUpdate,initialHessType,...\r\n HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...\r\n Damped,HvFunc,bbType,cycle,...\r\n HessianIter,outputFcn,useMex,useNegCurv,precFunc,...\r\n LS_type,LS_interp,LS_multi,DerivativeCheck] = ...\r\n minFunc_processInputOptions(o)\r\n\r\n% Constants\r\nSD = 0;\r\nCSD = 1;\r\nBB = 2;\r\nCG = 3;\r\nPCG = 4;\r\nLBFGS = 5;\r\nQNEWTON = 6;\r\nNEWTON0 = 7;\r\nNEWTON = 8;\r\nTENSOR = 9;\r\n\r\nverbose = 1;\r\nverboseI= 1;\r\ndebug = 0;\r\ndoPlot = 0;\r\nmethod = LBFGS;\r\ncgSolve = 0;\r\n\r\no = toUpper(o);\r\n\r\nif isfield(o,'DISPLAY')\r\n switch(upper(o.DISPLAY))\r\n case 0\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FINAL'\r\n verboseI = 0;\r\n case 'OFF'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'NONE'\r\n verbose = 0;\r\n verboseI = 0;\r\n case 'FULL'\r\n debug = 1;\r\n case 'EXCESSIVE'\r\n debug = 1;\r\n doPlot = 1;\r\n end\r\nend\r\n\r\nDerivativeCheck = 0;\r\nif isfield(o,'DERIVATIVECHECK')\r\n switch(upper(o.DERIVATIVECHECK))\r\n case 1\r\n DerivativeCheck = 1;\r\n case 'ON'\r\n DerivativeCheck = 1;\r\n end\r\nend\r\n\r\nLS_init = 0;\r\nLS_type = 1;\r\nLS_interp = 2;\r\nLS_multi = 0;\r\nFref = 1;\r\nDamped = 0;\r\nHessianIter = 1;\r\nc2 = 0.9;\r\nif isfield(o,'METHOD')\r\n m = upper(o.METHOD);\r\n switch(m)\r\n case 'TENSOR'\r\n method = TENSOR;\r\n case 'NEWTON'\r\n method = NEWTON;\r\n case 'MNEWTON'\r\n method = NEWTON;\r\n HessianIter = 5;\r\n case 'PNEWTON0'\r\n method = NEWTON0;\r\n cgSolve = 1;\r\n case 'NEWTON0'\r\n method = NEWTON0;\r\n case 'QNEWTON'\r\n method = QNEWTON;\r\n Damped = 1;\r\n case 'LBFGS'\r\n method = LBFGS;\r\n case 'BB'\r\n method = BB;\r\n LS_type = 0;\r\n Fref = 20;\r\n case 'PCG'\r\n method = PCG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'SCG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 4;\r\n case 'CG'\r\n method = CG;\r\n c2 = 0.2;\r\n LS_init = 2;\r\n case 'CSD'\r\n method = CSD;\r\n c2 = 0.2;\r\n Fref = 10;\r\n LS_init = 2;\r\n case 'SD'\r\n method = SD;\r\n LS_init = 2;\r\n end\r\nend\r\n\r\nmaxFunEvals = getOpt(o,'MAXFUNEVALS',1000);\r\nmaxIter = getOpt(o,'MAXITER',500);\r\noptTol = getOpt(o,'OPTTOL',1e-5);\r\nprogTol = getOpt(o,'PROGTOL',1e-9);\r\ncorrections = getOpt(o,'CORRECTIONS',100);\r\ncorrections = getOpt(o,'CORR',corrections);\r\nc1 = getOpt(o,'C1',1e-4);\r\nc2 = getOpt(o,'C2',c2);\r\nLS_init = getOpt(o,'LS_INIT',LS_init);\r\ncgSolve = getOpt(o,'CGSOLVE',cgSolve);\r\nqnUpdate = getOpt(o,'QNUPDATE',3);\r\ncgUpdate = getOpt(o,'CGUPDATE',2);\r\ninitialHessType = getOpt(o,'INITIALHESSTYPE',1);\r\nHessianModify = getOpt(o,'HESSIANMODIFY',0);\r\nFref = getOpt(o,'FREF',Fref);\r\nuseComplex = getOpt(o,'USECOMPLEX',0);\r\nnumDiff = getOpt(o,'NUMDIFF',0);\r\nLS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1);\r\nDamped = getOpt(o,'DAMPED',Damped);\r\nHvFunc = getOpt(o,'HVFUNC',[]);\r\nbbType = getOpt(o,'BBTYPE',0);\r\ncycle = getOpt(o,'CYCLE',3);\r\nHessianIter = getOpt(o,'HESSIANITER',HessianIter);\r\noutputFcn = getOpt(o,'OUTPUTFCN',[]);\r\nuseMex = getOpt(o,'USEMEX',1);\r\nuseNegCurv = getOpt(o,'USENEGCURV',1);\r\nprecFunc = getOpt(o,'PRECFUNC',[]);\r\nLS_type = getOpt(o,'LS_type',LS_type);\r\nLS_interp = getOpt(o,'LS_interp',LS_interp);\r\nLS_multi = getOpt(o,'LS_multi',LS_multi);\r\nend\r\n\r\nfunction [v] = getOpt(options,opt,default)\r\nif isfield(options,opt)\r\n if ~isempty(getfield(options,opt))\r\n v = getfield(options,opt);\r\n else\r\n v = default;\r\n end\r\nelse\r\n v = default;\r\nend\r\nend\r\n\r\nfunction [o] = toUpper(o)\r\nif ~isempty(o)\r\n fn = fieldnames(o);\r\n for i = 1:length(fn)\r\n o = setfield(o,upper(fn{i}),getfield(o,fn{i}));\r\n end\r\nend\r\nend"} +{"plateform": "github", "repo_name": "jmportilla/stanford_dl_ex-master", "name": "removeDC.m", "ext": ".m", "path": "stanford_dl_ex-master/rica/removeDC.m", "size": 420, "source_encoding": "utf_8", "md5": "98f8564a2e7aaf2a188d142a08be2c14", "text": "% Removes DC component from image patches\n% Data given as a matrix where each patch is one column vectors\n% That is, the patches are vectorized.\n\nfunction [Y,meanX]=removeDC(X, dim);\n\n% Subtract local mean gray-scale value from each patch in X to give output Y\nif nargin == 1\n dim = 1;\nend\n\nmeanX = mean(X,dim);\n\nif dim==1\n Y = X-meanX(ones(size(X,1),1),:);\nelse\n Y = X-meanX(:,ones(size(X,2),1));\nend\n\nreturn;\n"} +{"plateform": "github", "repo_name": "jmportilla/stanford_dl_ex-master", "name": "softICACost.m", "ext": ".m", "path": "stanford_dl_ex-master/rica/softICACost.m", "size": 388, "source_encoding": "utf_8", "md5": "d9004e62d6d16c20a74f4b05339c197c", "text": "%% Your job is to implement the RICA cost and gradient\nfunction [cost,grad] = softICACost(theta, x, params)\n\n% unpack weight matrix\nW = reshape(theta, params.numFeatures, params.n);\n\n% project weights to norm ball (prevents degenerate bases)\nWold = W;\nW = l2rowscaled(W, 1);\n\n%%% YOUR CODE HERE %%%\n\n% unproject gradient for minFunc\ngrad = l2rowscaledg(Wold, W, Wgrad, 1);\ngrad = grad(:);"} +{"plateform": "github", "repo_name": "jmportilla/stanford_dl_ex-master", "name": "bsxfunwrap.m", "ext": ".m", "path": "stanford_dl_ex-master/rica/bsxfunwrap.m", "size": 1030, "source_encoding": "utf_8", "md5": "9db0f61375c03b342b2005b39d596726", "text": "\nfunction c = bsxfunwrap(func, a, b)\n\nglobal usegpu;\n\nif usegpu\n if size(a,1) > 1 && size(b,1) == 1\n assert(size(a,2) == size(b,2), 'bsxfunwrap singleton dimensions dont agree');\n c = func(a, repmat(b, size(a,1), 1));\n elseif size(a,2) > 1 && size(b,2) == 1\n assert(size(a,1) == size(b,1), 'bsxfunwrap singleton dimensions dont agree');\n c = func(a, repmat(b, 1, size(a,2)));\n elseif size(b,1) > 1 && size(a,1) == 1\n assert(size(b,2) == size(a,2), 'bsxfunwrap singleton dimensions dont agree');\n c = func(repmat(a, size(b, 1), 1), b);\n elseif size(b,2) > 1 && size(a,2) == 1\n assert(size(b,1) == size(a,1), 'bsxfunwrap singleton dimensions dont agree');\n c = func(repmat(a, 1, size(b, 2)), b);\n else\n assert(size(a,1) == size(b,1), 'no bsxfun to do, bsxfunwrap dimensions dont agree');\n assert(size(a,2) == size(b,2), 'no bsxfun to do, bsxfunwrap dimensions dont agree');\n c = func(a, b);\n end\nelse\n c = bsxfun(func, a, b);\nend\n\nend"} +{"plateform": "github", "repo_name": "ABCDlab/surfstat-helper-master", "name": "saveTable.m", "ext": ".m", "path": "surfstat-helper-master/+abcd/saveTable.m", "size": 3659, "source_encoding": "utf_8", "md5": "af8e02e2a64a016617202555de96a114", "text": "function saveTable( table, file, varargin )\n\n% A flexible table writer to save tabular data to a file. Accepts data in\n% several formats, and can handle mixed text and numeric data.\n%\n% Usage: saveTable( table, file [, optionName, optionvalue ...]);\n%\n% table The input table data. Can be:\n% - A structure array where each field contains one column.\n% Column names are taken from the field names.\n% - A cell array where the first row contains the field names,\n% and the following rows contain the data values.\n%\n% file The output file. Can be:\n% - A file name\n% - The fid of an already-open file\n%\n% OPTIONS\n%\n% 'colDelim' Default is tab ('\\t')\n%\n% 'rowDelim' Default is newline ('\\n')\n%\n% 'strict' Require all table rows to have equal number of columns. Default is false.\n%\n\np = inputParser;\np.addParamValue('colDelim', sprintf('\\t'), @ischar);\np.addParamValue('rowDelim', sprintf('\\n'), @ischar);\np.addParamValue('strict', false, @islogical);\np.parse(varargin{:});\n\noutputTable = {};\nif (isa(table, 'struct'))\n outputTable = cellTableFromStructTable(table, p.Results);\nend\n\nif isnumeric(file)\n fid = file;\nelseif ischar(file)\n fid = fopen(file, 'w');\nelse\n error('File must be a filename or fid');\nend\n\nif fid < 0\n error('Error opening outout file');\nend\n\nwriteCellTableToOpenFile(outputTable, fid, p.Results);\n\nif fid > 2 % if fid is not STDOUT/STDIN/STDERR\n fclose(fid);\nend\n\nend\n\n\n%% Private functions . . .\n\nfunction writeCellTableToOpenFile(table, fid, p)\n for r = 1:size(table,1)\n for c = 1:size(table,2)\n if c>1, fprintf(fid, p.colDelim); end\n if isnumeric(table{r,c})\n fprintf(fid, '%s', num2str(table{r,c}));\n elseif ischar(table{r,c})\n fprintf(fid, '%s', table{r,c});\n else\n error('Unrecognized value type in output table, row=%d, col=%s, type=%s', r, c, class(table{r,c}));\n end\n end\n fprintf(fid, p.rowDelim);\n end\nend\n\nfunction cellTable = cellTableFromStructTable(structTable, p)\n f = fieldnames(structTable);\n maxRows = 0;\n allColsEqualLength = true;\n for i = 1:length(f)\n prevMaxRows = maxRows;\n if (ischar(structTable.(f{i})))\n maxRows = max(maxRows, size(structTable.(f{i}),1));\n elseif (isvector(structTable.(f{i})) || isempty(structTable.(f{i})))\n maxRows = max(maxRows, length(structTable.(f{i})));\n else\n error(['Received a structure array table, but a column is not a column vector! Field = ' f{i}]);\n end\n if (prevMaxRows ~= 0 && prevMaxRows ~= maxRows)\n allColsEqualLength = false;\n end\n end\n\n if ~allColsEqualLength\n if p.strict\n error('Not all columns have an equal number of values!');\n else\n warning('Not all columns have an equal number of values!');\n end\n end\n\n cellTable = cell(maxRows+1, length(f));\n cellTable(1,:) = f(:)';\n\n for i = 1:length(f)\n if (ischar(structTable.(f{i})))\n cellTable(2:1+size(structTable.(f{i}),1), i) = cellstr(structTable.(f{i}))';\n elseif (iscellstr(structTable.(f{i})))\n cellTable(2:1+size(structTable.(f{i}),1), i) = structTable.(f{i})(:)';\n elseif ((isvector(structTable.(f{i})) || isempty(structTable.(f{i}))) && isnumeric(structTable.(f{i})))\n cellTable(2:1+length(structTable.(f{i})), i) = num2cell(structTable.(f{i})(:))';\n else\n error(['Unrecognized column type, field = ' f{i}]);\n end\n end\nend\n\n"} +{"plateform": "github", "repo_name": "ABCDlab/surfstat-helper-master", "name": "attributeStore.m", "ext": ".m", "path": "surfstat-helper-master/+abcd/@attributeStore/attributeStore.m", "size": 5414, "source_encoding": "utf_8", "md5": "c03158b2f6dfbc0d89eef9815363aa6e", "text": "classdef attributeStore < handle\n % AttributeStore is a class to store name-value attributes.\n % The contents of the store can be rendered to a string in a flexible\n % format using the asString method.\n\n properties\n Attribs = struct();\n end\n\n properties (Hidden)\n StringOptions = [];\n end\n\n methods\n function obj = attributeStore(varargin)\n % Create an AttributeStore object\n if (nargin == 1)\n arg = varargin{1};\n if (isa(arg, class(obj)))\n % pass through\n obj = arg;\n elseif (isa(arg, 'struct'))\n f = fieldnames(arg);\n for i=1:numel(f)\n name = f{1};\n obj.set(name, arg.(name));\n end\n end\n elseif (nargin > 1)\n obj.set(varargin{:});\n end\n end\n\n function value = value(AS, name)\n % Get value of attribute\n if (~isfield(AS.Attribs, name))\n value = [];\n else\n value = AS.Attribs.(name);\n end\n end\n\n function set(AS, varargin)\n % Set value of attribute\n for i=1:2:numel(varargin)\n name = varargin{i};\n value = varargin{i+1};\n assert(any(strcmp(class(value),{'char' 'single' 'double' 'logical'})));\n AS.Attribs.(name) = value;\n end\n end\n\n function append(AS, name, value, delimiter)\n if (nargin < 4), delimiter = ','; end\n origValue = AS.value(name);\n if (isempty(origValue)), delimiter = ''; origValue = ''; end\n if (~isa(origValue, 'char'))\n error('The append method requires the existing value to be a string or empty');\n end\n AS.set(name, [origValue delimiter value]);\n end\n\n function clear(AS, name)\n if (nargin < 2)\n AS.Attribs = struct();\n else\n if (isfield(AS.Attribs, name))\n AS.Attribs = rmfield(AS.Attribs, name);\n end\n end\n end\n\n function setStringOptions(AS, varargin)\n AS.StringOptions = parseStringOptions(varargin{:});\n end\n\n function p = stringOptions(AS, varargin)\n if (~isempty(varargin))\n p = parseStringOptions(varargin{:});\n elseif (~isempty(AS.StringOptions))\n p = AS.StringOptions;\n else\n p = parseStringOptions();\n end\n\n if (isempty(p))\n error('This AttributeStore does not have any stringOptions set yet');\n end\n end\n\n function attributeString = asString(AS, varargin)\n % asString([optionName, optionValue...])\n %\n % itemDelim: delimiter between attributes (default ', ')\n % before: string preceding each attribute including the first one (default '')\n % after: string following each attribute including the last one (default '')\n % attributeNames: attribute names are only included if this is true (default true)\n % attributeDelim: delimiter between attribute name and value (default '=')\n p = AS.stringOptions(varargin{:});\n\n attributeString = '';\n n = 0;\n f = fieldnames(AS.Attribs);\n for i = 1:numel(f)\n name = f{i};\n value = AS.Attribs.(name);\n valueString = '';\n if (isnumeric(value))\n valueString = num2str(value);\n elseif (islogical(value))\n valueString = 'false';\n if (value)\n valueString = 'true';\n end\n elseif (ischar(value))\n valueString = value;\n else\n error('Unknown type for attribute %s', name);\n end\n\n itemDelim = '';\n nameString = '';\n attributeDelim = '';\n if (p.Results.attributeNames)\n nameString = name;\n attributeDelim = p.Results.attributeDelim;\n end\n if (i > 1), itemDelim = p.Results.itemDelim; end\n attributeString = [ ...\n attributeString ...\n itemDelim ...\n p.Results.before ...\n nameString ...\n attributeDelim ...\n valueString ...\n p.Results.after ...\n ];\n end\n end\n end\nend\n\nfunction options = parseStringOptions(varargin)\n p = inputParser();\n p.addParamValue('itemDelim', ', ', @ischar);\n p.addParamValue('before', '', @ischar);\n p.addParamValue('after', '', @ischar);\n % p.addParamValue('wrap', {}, @iscellstr);\n p.addParamValue('attributeNames', true, @islogical);\n p.addParamValue('attributeDelim', '=', @ischar);\n p.parse(varargin{:});\n\n% if (numel(p.Results.wrap) >= 2)\n% p.Results.before = p.Results.wrap{1};\n% p.Results.after = p.Results.wrap{2};\n% end\n options = p;\nend"} +{"plateform": "github", "repo_name": "sensestage/swonder-master", "name": "waves.m", "ext": ".m", "path": "swonder-master/twonder_old/waves.m", "size": 2924, "source_encoding": "utf_8", "md5": "46497ec3089228a79e83175a1313032d", "text": "\n\nglobal rresox=200\nglobal rresoy=200\n\nfunction mat=calc_circ( center_x, center_y, resox, resoy )\n\tmab=ones( resox, resoy );\n\tfor x=1:resox\n\t\tfor y=1:resoy\n\t\t\tmab( x, y ) = sqrt( (x - center_x)^2 + (y - center_y)^2 );\n\t\tendfor\n\tendfor\n\tmat=mab;\nendfunction\n\nfunction bool = fexists( name )\n\tf = fopen( name, \"rb\" );\n\tif( f != -1 )\n\t\tfclose( f );\n\t\tbool = 1;\n\telse \n\t\tbool=0;\n\tendif\nendfunction\n\nfunction mat = load_precalc_circle()\n\tif( fexists( \"circle.bin\" ) )\n\t\tx = load \"circle.bin\";\n\t\tmat = x.mat;\n\telse\n\t\tmat = calc_circ( 400,400,800,800 );\n\t\tsave -binary \"circle.bin\" mat;\n\tendif\nendfunction\n\nfunction mat=get_circ( center_x, center_y )\n\tmab=ones( 200, 200 );\n\tfor x=1:200\n\t\tfor y=1:200\n\t\t\tmab( x, y ) = sqrt( (x - center_x)^2 + (y - center_y)^2 );\n\t\tendfor\n\tendfor\n\tmat=mab;\nendfunction\n\nfunction mat=get_precalc_circ( center_x, center_y, precalc_circ )\n\tmat = precalc_circ( 400-center_x:599-center_x, 400-center_y:599-center_y );\n#\tmat = precalc_circ( 401-center_x:600-center_x, 401-center_y:600-center_y );\n#\tmat = precalc_circ( 399-center_x:598-center_x, 399-center_y:598-center_y );\nendfunction\n\nfunction mat=get_wave( center_x, center_y, phi, omega, precalc )\n\tm = get_precalc_circ( center_x, center_y, precalc );\n\tmat = (0.1*m+1).^-1 .* sin( 2*pi*omega*m + phi*omega*2*pi );\nendfunction\n\ncolormap( gray(256) );\n\n\n#precalculated_circle = calc_circ( 200,200,400,400 );\nprecalculated_circle = load_precalc_circle();\n\npic = zeros( 200, 200 );\npic2 = zeros( 200, 200 );\nspkmap = zeros( 200, 200 );\n\n\nspk = zeros( 24*4,2 );\nspkn = zeros( 24*4,2 );\nweights = ones( 24*4 );\n\nfor i=1:24\n\tspk(i,1) = 30;\n\tspk(i,2) = 30 + 5 * i;\n\tspkn(i,1) = 1;\n\tspkn(i,2) = 0;\nendfor\n\t\nfor i=1:24\n\tspk(i+24,1) = 30 + 5 * i;\n\tspk(i+24,2) = 30;\n\tspkn(i+24,1) = 0;\n\tspkn(i+24,2) = 1;\nendfor\n\t\n##weights( 1 ) = 0.75;\n##weights( 25 ) = 0.75;\n\nfunction res = theint( l, r )\n\t res = ( log( abs( sqrt( l^2 + r^2 ) + l )) * r^2 + l * sqrt( l^2+r^2 ) ) / 2;\nendfunction\n\nomeg = 0.25;\n\nfor i=1:48\n\trvec = spk(i,:) - [50, 10];\n\twrongrlen = sqrt( sumsq( rvec ) )\n\tnormproject = dot( rvec, spkn(i,:) )\n\tif( normproject < 0 )\n\t\twrongrlen = - wrongrlen\n\tendif\n\n\tcosphi = normproject / wrongrlen;\n\n\trr = dot(rvec, spkn(i,:));\n\tl = dot(rvec, rot90( spkn(i,:) ) );\n\tl0 = l - 2.5;\n\tl1 = l + 2.5;\n\n\trlen = (theint( l1, rr ) - theint( l0,rr )) / 5\n\tif( normproject < 0 )\n\t\trlen = - rlen\n\tendif\n\t#rlen = wrongrlen;\n\t#cosphi = dot( rvec, spkn(i,:) ) / rlen;\n\n\tpic = pic + weights(i) /rlen * cosphi * get_wave( spk(i,1), spk(i,2), rlen, omeg, precalculated_circle );\n\t#pic2 = pic2 + weights(i) /wrongrlen * cosphi * get_wave( spk(i,1), spk(i,2), wrongrlen, 0.1, precalculated_circle );\n\tspkmap( spk(i,1), spk(i,2) ) =1.0;\nendfor\n\n\n#pic2 = get_wave( 50, 10, 0, omeg, precalculated_circle );\n#pic2 = pic-pic2;\n\n\npic = pic .- min(min(pic));\npic = pic ./ max(max(pic));\n\n\npic2 = pic2 .- min(min(pic2));\npic2 = pic2 ./ max(max(pic2));\n\nimshow( pic2, pic, spkmap );\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_single_port_ram_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_single_port_ram_init.m", "size": 19918, "source_encoding": "utf_8", "md5": "09e8b58ab26d2a4b7d02d66ebfbf8fc3", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_single_port_ram_init(blk, varargin)\n log_group = 'bus_single_port_ram_init_debug';\n\n clog('entering bus_single_port_ram_init', {'trace', log_group});\n \n defaults = { ...\n 'n_bits', 36, 'bin_pts', 0, ...\n 'init_vector', zeros(8192,1), ...\n 'max_fanout', 1, 'mem_type', 'Distributed memory', ...\n 'bram_optimization', 'Speed', ... %'Speed', 'Area' \n 'async', 'off', 'misc', 'off', ...\n 'bram_latency', 1, 'fan_latency', 0, ...\n 'addr_register', 'on', 'addr_implementation', 'behavioral', ...\n 'din_register', 'on', 'din_implementation', 'behavioral', ...\n 'we_register', 'on', 'we_implementation', 'behavioral', ...\n 'en_register', 'on', 'en_implementation', 'behavioral', ...\n }; \n \n check_mask_type(blk, 'bus_single_port_ram');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 80;\n ypos = 50; yinc = 20;\n\n port_w = 30; port_d = 14;\n rep_w = 50; rep_d = 30;\n bus_expand_w = 60; bus_expand_d = 10;\n bus_create_w = 60; bus_create_d = 10;\n bram_w = 50; bram_d = 40;\n del_w = 30; del_d = 20;\n\n maxy = 2^13; %Simulink limit\n\n n_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\n bin_pts = get_var('bin_pts', 'defaults', defaults, varargin{:});\n init_vector = get_var('init_vector', 'defaults', defaults, varargin{:});\n bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\n mem_type = get_var('mem_type', 'defaults', defaults, varargin{:});\n bram_optimization = get_var('bram_optimization', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n async = get_var('async', 'defaults', defaults, varargin{:});\n max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:});\n fan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:});\n addr_register = get_var('addr_register', 'defaults', defaults, varargin{:});\n addr_implementation = get_var('addr_implementation', 'defaults', defaults, varargin{:});\n din_register = get_var('din_register', 'defaults', defaults, varargin{:});\n din_implementation = get_var('din_implementation', 'defaults', defaults, varargin{:});\n we_register = get_var('we_register', 'defaults', defaults, varargin{:});\n we_implementation = get_var('we_implementation', 'defaults', defaults, varargin{:});\n en_register = get_var('en_register', 'defaults', defaults, varargin{:});\n en_implementation = get_var('en_implementation', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state, do nothing \n if (n_bits(1) == 0),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_single_port_ram_init', {'trace', log_group});\n return;\n end\n\n [riv, civ] = size(init_vector);\n [rnb, cnb] = size(n_bits);\n [rbp, cbp] = size(bin_pts);\n\n if (cnb ~= 1 && cbp ~= 1) && ((civ ~= cnb) || (civ ~= cbp)),\n clog('The number of columns in initialisation vector must match the number of values in binary point and number of bits parameter specifications', {'error', log_group});\n error('The number of columns in initialisation vector must match the number of values in binary point and number of bits parameter specifications');\n end\n\n %%%%%%%%%%%%%%%\n % input ports %\n %%%%%%%%%%%%%%%\n\n %The calculations below anticipate how BRAMs are to be configured by the Xilinx tools\n %(as detailed in UG190), explicitly generates these, and attempts to control fanout into\n %these\n \n %if optimizing for Area, do the best we can minimising fanout while still using whole BRAMs\n %fanout for very deep BRAMs will be large\n %TODO this should depend on FPGA architecture, assuming V5 or V6\n if strcmp(bram_optimization, 'Area'), \n if (riv >= 2^11), max_word_size = 9;\n elseif (riv >= 2^10), max_word_size = 18;\n else, max_word_size = 36;\n end\n %if optimising for Speed, keep splitting word size even if wasting BRAM resources\n else, \n if (riv >= 2^14), max_word_size = 1;\n elseif (riv >= 2^13), max_word_size = 2;\n elseif (riv >= 2^12), max_word_size = 4;\n elseif (riv >= 2^11), max_word_size = 9;\n elseif (riv >= 2^10), max_word_size = 18;\n else, max_word_size = 36;\n end\n end\n \n ctiv = 0;\n\n while (ctiv == 0) || ((ctiv * bram_d) > maxy),\n\n %if we are going to go beyond Xilinx bounds, double the word width\n if (ctiv * bram_d) > maxy,\n clog(['doubling word size from ', num2str(max_word_size), ' to make space'], log_group);\n if (max_word_size == 1), max_word_size = 2;\n elseif (max_word_size == 2), max_word_size = 4;\n elseif (max_word_size == 4), max_word_size = 9;\n elseif (max_word_size == 9), max_word_size = 18;\n else, max_word_size = 36;\n end %if\n end %if\n \n % translate initialisation matrix based on architecture \n [translated_init_vecs, result] = doubles2unsigned(init_vector, n_bits, bin_pts, max_word_size);\n if result ~= 0,\n clog('error translating initialisation matrix', {'error', log_group});\n error('error translating initialisation matrix');\n end %if\n \n [rtiv, ctiv] = size(translated_init_vecs);\n end %while\n\n clog([num2str(ctiv), ' brams required'], log_group);\n\n replication = ceil(ctiv/max_fanout);\n clog(['replication factor of ', num2str(replication), ' required'], log_group);\n\n if (cnb == 1),\n n_bits = repmat(n_bits, 1, civ);\n bin_pts = repmat(bin_pts, 1, civ);\n end %if\n\n ypos_tmp = ypos;\n \n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'addr', 'built-in/inport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n reuse_block(blk, 'din', 'built-in/inport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*ctiv/2;\n \n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'we', 'built-in/inport', ...\n 'Port', '3', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n\n port_index = 4;\n % asynchronous A port\n if strcmp(async, 'on'),\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'en', 'built-in/inport', ...\n 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n port_index = port_index + 1;\n end\n\n %misc port\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/inport', ...\n 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n end\n\n xpos = xpos + xinc + port_w/2; \n\n %%%%%%%%%%%%%%%%%%%%\n % replicate inputs %\n %%%%%%%%%%%%%%%%%%%%\n\n xpos = xpos + rep_w/2;\n\n ypos_tmp = ypos; %reset ypos\n\n % replicate addr\n if strcmp(addr_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n reuse_block(blk, 'rep_addr', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ...\n 'implementation', addr_implementation, ... \n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'addr/1', 'rep_addr/1');\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n\n % delay din\n if strcmp(din_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n if strcmp(din_implementation, 'core'), reg_retiming = 'off';\n else, reg_retiming = 'on';\n end\n\n reuse_block(blk, 'ddin', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(latency), 'reg_retiming', reg_retiming, ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, ['din/1'], 'ddin/1');\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n\n % replicate we\n if strcmp(we_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n reuse_block(blk, 'rep_we', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... \n 'implementation', we_implementation, ... \n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'we/1', 'rep_we/1'); \n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n\n if strcmp(async, 'on'),\n if strcmp(en_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n % replicate en\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n reuse_block(blk, 'rep_en', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... \n 'implementation', en_implementation, ... \n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'en/1', 'rep_en/1'); \n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n end\n\n xpos = xpos + xinc + rep_w/2;\n \n %%%%%%%%%%%%%%%%\n % debus inputs %\n %%%%%%%%%%%%%%%%\n \n xpos = xpos + bus_expand_w/2;\n \n % debus addra\n ypos_tmp = ypos + bus_expand_d*ctiv/2;\n reuse_block(blk, 'debus_addr', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ...\n 'outputWidth', mat2str(repmat(ceil(log2(rtiv)), 1, replication)), ...\n 'outputBinaryPt', mat2str(zeros(1, replication)), ...\n 'outputArithmeticType', mat2str(zeros(1,replication)), 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'rep_addr/1', 'debus_addr/1');\n \n % debus din\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n total_bits = sum(n_bits);\n extra = mod(total_bits, max_word_size);\n main = repmat(max_word_size, 1, floor(total_bits/max_word_size));\n outputWidth = [main];\n if (extra ~= 0), \n outputWidth = [extra, outputWidth]; \n end\n\n reuse_block(blk, 'debus_din', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', mat2str(outputWidth), 'outputBinaryPt', mat2str(zeros(1, ctiv)), ...\n 'outputArithmeticType', mat2str(zeros(1,ctiv)), 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'ddin/1', 'debus_din/1');\n\n % debus we\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n reuse_block(blk, 'debus_we', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ...\n 'outputWidth', mat2str(ones(1, replication)), ...\n 'outputBinaryPt', mat2str(zeros(1, replication)), ...\n 'outputArithmeticType', mat2str(repmat(2,1,replication)), 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'rep_we/1', 'debus_we/1');\n\n if strcmp(async, 'on'),\n % debus ena \n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n reuse_block(blk, 'debus_en', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ...\n 'outputWidth', mat2str(ones(1, replication)), 'outputBinaryPt', mat2str(zeros(1, replication)), ...\n 'outputArithmeticType', mat2str(repmat(2,1,replication)), ...\n 'show_format', 'on', 'outputToWorkspace', 'off', 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'rep_en/1', 'debus_en/1');\n end \n \n if strcmp(misc, 'on'),\n % delay misc\n ypos_tmp = ypos_tmp + del_d/2;\n reuse_block(blk, 'dmisc0', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(fan_latency), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n ypos_tmp = ypos_tmp + del_d/2 + yinc;\n add_line(blk, 'misci/1', 'dmisc0/1');\n end\n\n xpos = xpos + xinc + bus_expand_w/2;\n\n %%%%%%%%%%%%%%\n % bram layer %\n %%%%%%%%%%%%%%\n \n ypos_tmp = ypos;\n xpos = xpos + xinc + bram_w/2;\n\n for bram_index = 1:ctiv,\n\n % bram self\n\n % because the string version of the initVector could be too long (Matlab has upper limits on the length of strings), \n % we save the values in the UserData parameter of the ram block (available on all Simulink blocks it seems)\n % and then reference that value from the mask\n % (It seems that when copying Xilinx blocks this parameter is not preserved and the block must be redrawn to \n % get the values back)\n\n initVector = translated_init_vecs(:, bram_index)';\n UserData = struct('initVector', double(initVector));\n\n ypos_tmp = ypos_tmp + bram_d/2; \n bram_name = ['bram', num2str(bram_index-1)];\n clog(['adding ', bram_name], log_group);\n reuse_block(blk, bram_name, 'xbsIndex_r4/Single Port RAM', ...\n 'UserData', UserData, 'UserDataPersistent', 'on', ...\n 'depth', num2str(rtiv), 'write_mode', 'Read Before Write', 'en', async, 'optimize', bram_optimization, ...\n 'distributed_mem', mem_type, 'latency', num2str(bram_latency), ...\n 'Position', [xpos-bram_w/2 ypos_tmp-bram_d/2 xpos+bram_w/2 ypos_tmp+bram_d/2]);\n clog(['done adding ', bram_name], 'bus_single_port_ram_init_desperate_debug');\n clog(['setting initVector of ', bram_name], 'bus_single_port_ram_init_desperate_debug');\n set_param([blk, '/', bram_name], 'initVector', 'getfield(get_param(gcb, ''UserData''), ''initVector'')');\n clog(['done setting initVector of ', bram_name], 'bus_single_port_ram_init_desperate_debug');\n\n ypos_tmp = ypos_tmp + yinc + bram_d/2; \n \n % bram connections to replication and debus blocks\n rep_index = mod(bram_index-1, replication) + 1; %replicated index to use\n add_line(blk, ['debus_addr/', num2str(rep_index)], [bram_name, '/1']);\n add_line(blk, ['debus_din/', num2str(bram_index)], [bram_name, '/2']);\n add_line(blk, ['debus_we/', num2str(rep_index)], [bram_name, '/3']);\n\n if strcmp(async, 'on'), \n add_line(blk, ['debus_en/', num2str(rep_index)], [bram_name, '/4']);\n end %if \n\n end %for \n\n % delay for enables and misc\n\n if strcmp(async, 'on'),\n ypos_tmp = ypos_tmp + del_d/2;\n reuse_block(blk, 'den', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(bram_latency), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n ypos_tmp = ypos_tmp + yinc + del_d/2;\n add_line(blk, ['debus_en/',num2str(replication)], 'den/1');\n end;\n \n if strcmp(misc, 'on'),\n ypos_tmp = ypos_tmp + del_d/2;\n reuse_block(blk, 'dmisc1', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(bram_latency), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n ypos_tmp = ypos_tmp + yinc + del_d/2;\n add_line(blk, 'dmisc0/1', 'dmisc1/1');\n end %if\n \n xpos = xpos + xinc + bram_w/2;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%\n % recombine bram outputs %\n %%%%%%%%%%%%%%%%%%%%%%%%%%\n\n xpos = xpos + bus_create_w/2;\n ypos_tmp = ypos; \n \n ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; \n reuse_block(blk, 'din_bussify', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(ctiv), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-bus_create_d*ctiv/2 xpos+bus_create_w/2 ypos_tmp+bus_create_d*ctiv/2]);\n ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; \n \n for index = 1:ctiv,\n add_line(blk, ['bram',num2str(index-1),'/1'], ['din_bussify', '/', num2str(index)]); \n end %for\n\n xpos = xpos + xinc + bus_create_w/2;\n\n %%%%%%%%%%%%%%%%\n % output ports %\n %%%%%%%%%%%%%%%%\n\n xpos = xpos + port_w/2;\n ypos_tmp = ypos; \n \n ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; \n reuse_block(blk, 'dout', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; \n add_line(blk, 'din_bussify/1', 'dout/1');\n\n port_index = 2;\n if strcmp(async, 'on'),\n ypos_tmp = ypos_tmp + port_d/2;\n reuse_block(blk, 'dvalid', 'built-in/outport', ...\n 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + port_d/2; \n port_index = port_index + 1;\n add_line(blk, 'den/1', 'dvalid/1');\n end\n \n if strcmp(misc, 'on'),\n ypos_tmp = ypos_tmp + port_d/2;\n reuse_block(blk, 'misco', 'built-in/outport', ...\n 'Port', num2str(port_index), ... \n 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + port_d/2;\n\n add_line(blk, 'dmisc1/1', 'misco/1');\n end\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_single_port_ram_init', {'trace', log_group});\n\nend %function bus_single_port_ram_init\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "rcmult_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/rcmult_init.m", "size": 4200, "source_encoding": "utf_8", "md5": "48239288509e086f6d81eb521a80beec", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% MeerKAT Radio Telescope Project %\n% www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (meerKAT) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction rcmult_init(blk, varargin)\n\n defaults = {};\n check_mask_type(blk, 'rcmult');\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n latency = get_var('latency','defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state in library\n if latency == 0,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); \n return; \n end\n\n reuse_block(blk, 'd', 'built-in/Inport');\n set_param([blk,'/d'], ...\n 'Port', '1', ...\n 'Position', '[15 33 45 47]');\n\n reuse_block(blk, 'sin', 'built-in/Inport');\n set_param([blk,'/sin'], ...\n 'Port', '2', ...\n 'Position', '[75 138 105 152]');\n\n reuse_block(blk, 'cos', 'built-in/Inport');\n set_param([blk,'/cos'], ...\n 'Port', '3', ...\n 'Position', '[75 58 105 72]');\n\n reuse_block(blk, 'Mult0', 'xbsIndex_r4/Mult');\n set_param([blk,'/Mult0'], ...\n 'n_bits', '8', ...\n 'bin_pt', '2', ...\n 'latency', 'latency', ...\n 'use_rpm', 'off', ...\n 'placement_style', 'Rectangular shape', ...\n 'Position', '[160 27 210 78]');\n\n reuse_block(blk, 'Mult1', 'xbsIndex_r4/Mult');\n set_param([blk,'/Mult1'], ...\n 'n_bits', '8', ...\n 'bin_pt', '2', ...\n 'latency', 'latency', ...\n 'use_rpm', 'off', ...\n 'placement_style', 'Rectangular shape', ...\n 'Position', '[160 107 210 158]');\n\n reuse_block(blk, 'real', 'built-in/Outport');\n set_param([blk,'/real'], ...\n 'Port', '1', ...\n 'Position', '[235 48 265 62]');\n\n reuse_block(blk, 'imag', 'built-in/Outport');\n set_param([blk,'/imag'], ...\n 'Port', '2', ...\n 'Position', '[235 128 265 142]');\n\n add_line(blk,'cos/1','Mult0/2', 'autorouting', 'on');\n add_line(blk,'sin/1','Mult1/2', 'autorouting', 'on');\n add_line(blk,'d/1','Mult1/1', 'autorouting', 'on');\n add_line(blk,'d/1','Mult0/1', 'autorouting', 'on');\n add_line(blk,'Mult0/1','real/1', 'autorouting', 'on');\n add_line(blk,'Mult1/1','imag/1', 'autorouting', 'on');\n\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:});\nend % rcmult_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "cosin_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/cosin_init.m", "size": 29664, "source_encoding": "utf_8", "md5": "78c309b6249d7f1414582677b0b52625", "text": "% Generate cos/sin\n%\n% cosin_init(blk, varargin)\n%\n% blk = The block to be configured.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Karoo Array Telesope %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%TODO logic for where conditions don't allow optimization \n\nfunction cosin_init(blk,varargin)\n\n clog('entering cosin_init',{'trace', 'cosin_init_debug'});\n check_mask_type(blk, 'cosin');\n\n % Set default vararg values.\n % reg_retiming is not an actual parameter of this block, but it is included\n % in defaults so that same_state will return false for blocks drawn prior to\n % adding reg_retiming='on' to some of the underlying Delay blocks.\n defaults = { ...\n 'output0', 'cos', ... \n 'output1', '-sin', ... \n 'indep_theta', 'off', ...\n 'phase', 0, ...\n 'fraction', 3, ... \n 'store', 3, ... \n 'table_bits', 5, ... \n 'n_bits', 18, ... \n 'bin_pt', 17, ... \n 'bram_latency', 2, ...\n 'add_latency', 1, ... \n 'mux_latency', 1, ... \n 'neg_latency', 1, ... \n 'conv_latency', 1, ...\n 'pack', 'off', ...\n 'bram', 'BRAM', ... %'BRAM' or 'distributed RAM'\n 'misc', 'off', ...\n 'reg_retiming', 'on', ...\n };\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n output0 = get_var('output0', 'defaults', defaults, varargin{:});\n output1 = get_var('output1', 'defaults', defaults, varargin{:});\n indep_theta = get_var('indep_theta', 'defaults', defaults, varargin{:});\n phase = get_var('phase', 'defaults', defaults, varargin{:});\n fraction = get_var('fraction', 'defaults', defaults, varargin{:});\n store = get_var('store', 'defaults', defaults, varargin{:});\n table_bits = get_var('table_bits', 'defaults', defaults, varargin{:});\n n_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\n bin_pt = get_var('bin_pt', 'defaults', defaults, varargin{:});\n bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\n add_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\n mux_latency = get_var('mux_latency', 'defaults', defaults, varargin{:});\n neg_latency = get_var('neg_latency', 'defaults', defaults, varargin{:});\n conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\n pack = get_var('pack', 'defaults', defaults, varargin{:});\n bram = get_var('bram', 'defaults', defaults, varargin{:}); \n misc = get_var('misc', 'defaults', defaults, varargin{:}); \n \n delete_lines(blk);\n\n %default case for storage in the library\n if table_bits == 0,\n clean_blocks(blk);\n set_param(blk, 'AttributesFormatString', '');\n save_state(blk, 'defaults', defaults, varargin{:});\n clog('exiting cosin_init',{'trace', 'cosin_init_debug'});\n return;\n end %if\n\n %%%%%%%%%%%%%%%\n % input ports %\n %%%%%%%%%%%%%%%\n port_n=1;\n\n reuse_block(blk, 'theta', 'built-in/Inport', 'Port', int2str(port_n), 'Position', [10 88 40 102]);\n\n reuse_block(blk, 'assert', 'xbsIndex_r4/Assert', ...\n 'assert_type', 'on', ...\n 'type_source', 'Explicitly', ...\n 'arith_type', 'Unsigned', ...\n 'n_bits', num2str(table_bits), 'bin_pt', '0', ...\n 'Position', [70 85 115 105]);\n add_line(blk, 'theta/1', 'assert/1');\n port_n =port_n +1;\n\n if strcmp(indep_theta, 'on'),\n reuse_block(blk, 'theta2', 'built-in/Inport', 'Port', int2str(port_n), 'Position', [10 188 40 202]);\n\n reuse_block(blk, 'assert2', 'xbsIndex_r4/Assert', ...\n 'assert_type', 'on', ...\n 'type_source', 'Explicitly', ...\n 'arith_type', 'Unsigned', ...\n 'n_bits', num2str(table_bits), 'bin_pt', '0', ...\n 'Position', [70 185 115 205]);\n add_line(blk, 'theta2/1', 'assert2/1');\n port_n =port_n +1;\n end\n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/Inport', 'Port', int2str(port_n), 'Position', [10 238 40 252]);\n else\n reuse_block(blk, 'misci', 'xbsIndex_r4/Constant', ...\n 'const', '0', 'n_bits', '1', 'arith_type', 'Unsigned', ...\n 'bin_pt', '0', 'explicit_period', 'on', 'period', '1', ...\n 'Position', [10 238 40 252]);\n port_n =port_n +1;\n end\n\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % address manipulation logic %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %make sure not storing more than outputting and not storing too few points\n if (store < fraction) || (fraction <= 2 && store > 2), \n clog(['need 1/',num2str(fraction),' cycle but want to store 1/',num2str(store),', forcing 1/',num2str(fraction)],{'warning','cosin_init_debug'});\n warning(['need 1/',num2str(fraction),' cycle but want to store 1/',num2str(store),', forcing 1/',num2str(fraction)]);\n store = fraction; \n end\n\n full_cycle_bits = table_bits + fraction;\n\n %need full_cycle_bits to be at least 3 so can cut 2 above and 1 low in add_convert\n if (full_cycle_bits < 3),\n if ~(store == fraction && strcmp(pack,'on')),\n clog('forcing all values storage for small number of points',{'trace', 'cosin_init_debug'});\n warning('forcing all value storage for small number of points');\n end\n store = fraction; pack = 'on';\n end\n \n if (fraction > 2),\n if ~(store == fraction && strcmp(pack,'on')),\n clog('forcing full storage for output cycle fraction less than a quarter',{'trace', 'cosin_init_debug'});\n warning('forcing full storage for output cycle fraction less than a quarter');\n end\n store = fraction; pack = 'on';\n end\n\n %force separate, complete storage if we have an initial phase offset\n if phase ~= 0, \n if ~(store == fraction && strcmp(pack,'on')),\n clog('forcing full storage for non zero initial phase',{'trace', 'cosin_init_debug'});\n warning('forcing full storage for non zero initial phase');\n end\n store = fraction; pack = 'on';\n end %if phase\n\n %determine optimal lookup functions if not packed\n if strcmp(pack, 'on'),\n lookup0 = output0; lookup1 = output1; %not sharing values so store as specified\n else,\n if store == 0 || store == 1, \n lookup0 = 'cos'; lookup1 = 'cos'; \n elseif store == 2,\n lookup0 = 'sin'; lookup1 = 'sin'; %minimise amplitude error for last sample with sin\n end %if store\n end %if strcmp(pack) \n\n %lookup size depends on fraction of cycle stored\n lookup_bits = full_cycle_bits - store;\n\n address_bits = table_bits;\n draw_basic_partial_cycle(blk, full_cycle_bits, address_bits, lookup_bits, output0, output1, lookup0, lookup1);\n\n add_line(blk,'misci/1','add_convert1/2');\n\n if strcmp(indep_theta, 'on'),\n add_line(blk,'assert2/1','add_convert1/1');\n else,\n add_line(blk,'assert/1','add_convert1/1');\n end\n\n %%%%%%%%%%%%%\n % ROM setup %\n %%%%%%%%%%%%%\n \n %misc delay\n reuse_block(blk, 'Delay', 'xbsIndex_r4/Delay', ...\n 'latency', 'bram_latency', ...\n 'reg_retiming', 'on', ...\n 'Position', [450 336 480 354]);\n add_line(blk,'add_convert1/3', 'Delay/1');\n\n %determine memory implementation\n if strcmp(bram, 'BRAM'),\n distributed_mem = 'Block RAM';\n elseif strcmp(bram, 'distributed RAM'),\n distributed_mem = 'Distributed memory';\n else,\n %TODO\n end\n\n vec_len = 2^lookup_bits;\n \n initVector = [lookup0,'((',num2str(phase),'*(2*pi))+(2*pi)/(2^',num2str(full_cycle_bits),')*(0:(2^',num2str(lookup_bits),')-1))'];\n\n %pack two outputs into the same word from ROM\n if strcmp(pack, 'on'),\n \n %lookup ROM\n reuse_block(blk, 'ROM', 'xbsIndex_r4/ROM', ...\n 'depth', ['2^(',num2str(lookup_bits),')'], ...\n 'latency', 'bram_latency', ...\n 'arith_type', 'Unsigned', ...\n 'n_bits', 'n_bits*2', ...\n 'bin_pt', '0', ...\n 'optimize', 'Speed', ...\n 'distributed_mem', distributed_mem, ...\n 'Position', [435 150 490 300]);\n\n add_line(blk,'add_convert0/2', 'ROM/1');\n reuse_block(blk, 'Terminator4', 'built-in/Terminator', 'Position', [285 220 305 240]);\n add_line(blk,'add_convert1/2', 'Terminator4/1');\n\n %calculate values to be stored in ROM\n real_vals = gen_vals(output0, phase, full_cycle_bits, vec_len, n_bits, bin_pt);\n\n imag_vals = gen_vals(output1, phase, full_cycle_bits, vec_len, n_bits, bin_pt);\n \n vals = doubles2unsigned([real_vals',imag_vals'], n_bits, bin_pt, n_bits*2);\n\n set_param([blk,'/ROM'], 'initVector', mat2str(vals'));\n\n %extract real and imaginary parts of vector\n reuse_block(blk, 'c_to_ri', 'casper_library_misc/c_to_ri', ...\n 'n_bits', 'n_bits', 'bin_pt', 'bin_pt', ...\n 'Position', [510 204 550 246]);\n\n add_line(blk,'ROM/1','c_to_ri/1');\n\n elseif strcmp(pack, 'off'),\n\n %lookup table\n reuse_block(blk, 'lookup', 'xbsIndex_r4/Dual Port RAM', ...\n 'initVector', initVector, ...\n 'depth', sprintf('2^(%s)',num2str(lookup_bits)), ...\n 'latency', 'bram_latency', ...\n 'distributed_mem', distributed_mem, ...\n 'Position', [435 137 490 298]);\n \n add_line(blk,'add_convert0/2','lookup/1');\n add_line(blk,'add_convert1/2','lookup/4');\n\n %constant inputs to lookup table \n reuse_block(blk, 'Constant', 'xbsIndex_r4/Constant', ...\n 'const', '0', ...\n 'n_bits', 'n_bits', ...\n 'bin_pt', 'bin_pt', ...\n 'Position', [380 170 400 190]);\n add_line(blk,'Constant/1','lookup/2');\n\n reuse_block(blk, 'Constant2', 'xbsIndex_r4/Constant', ...\n 'const', '0', ...\n 'arith_type', 'Boolean', ...\n 'n_bits', 'n_bits', ...\n 'bin_pt', 'bin_pt', ...\n 'Position', [380 195 400 215]);\n add_line(blk,'Constant2/1','lookup/3');\n\n %add constants if using BRAM (ports don't exist when using distributed RAM)\n if strcmp(bram, 'BRAM')\n reuse_block(blk, 'Constant1', 'xbsIndex_r4/Constant', ...\n 'const', '0', ...\n 'n_bits', 'n_bits', ...\n 'bin_pt', 'bin_pt', ...\n 'Position', [380 245 400 265]);\n add_line(blk,'Constant1/1','lookup/5');\n\n reuse_block(blk, 'Constant3', 'xbsIndex_r4/Constant', ...\n 'const', '0', ...\n 'arith_type', 'Boolean', ...\n 'n_bits', 'n_bits', ...\n 'bin_pt', 'bin_pt', ...\n 'Position', [380 270 400 290]);\n add_line(blk,'Constant3/1','lookup/6');\n end %if strcmp(bram)\n\n else,\n %TODO\n end %if strcmp(pack)\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % delays for negate outputs from address manipulation block % \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n reuse_block(blk, 'Delay8', 'xbsIndex_r4/Delay', ...\n 'latency', 'bram_latency', ...\n 'reg_retiming', 'on', ...\n 'Position', [450 116 480 134]);\n add_line(blk,'add_convert1/1','Delay8/1');\n reuse_block(blk, 'Delay10', 'xbsIndex_r4/Delay', ...\n 'latency', 'bram_latency', ...\n 'reg_retiming', 'on', ...\n 'Position', [450 81 480 99]);\n add_line(blk,'add_convert0/1','Delay10/1');\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % data manipulation before output %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n if strcmp(pack, 'on'),\n src0 = 'c_to_ri/1'; src1 = 'c_to_ri/2';\n else,\n src0 = 'lookup/1'; src1 = 'lookup/2';\n end\n\n %data\n reuse_block(blk, 'Constant5', 'xbsIndex_r4/Constant', ...\n 'const', '0', ...\n 'arith_type', 'Unsigned', ...\n 'n_bits', '1', ...\n 'bin_pt', '0', ...\n 'explicit_period', 'on', ...\n 'Position', [770 122 785 138]);\n\n reuse_block(blk, 'invert0', 'built-in/SubSystem');\n invert_gen([blk,'/invert0']);\n set_param([blk,'/invert0'], ...\n 'Position', [800 80 850 142]);\n add_line(blk,'Delay10/1','invert0/1');\n add_line(blk,'Constant5/1','invert0/3');\n add_line(blk, src0, 'invert0/2');\n\n reuse_block(blk, 'invert1', 'built-in/SubSystem');\n invert_gen([blk,'/invert1']);\n set_param([blk,'/invert1'], ...\n 'Position', [800 160 850 222]);\n add_line(blk,'Delay8/1','invert1/1');\n add_line(blk,src1, 'invert1/2');\n\n reuse_block(blk, 'Terminator1', 'built-in/Terminator', ...\n 'Position', [880 115 900 135]);\n add_line(blk,'invert0/2','Terminator1/1');\n\n %misc\n add_line(blk,'Delay/1','invert1/3');\n \n %%%%%%%%%%%%%%%% \n % output ports %\n %%%%%%%%%%%%%%%% \n\n \nif strcmp(output0,output1),\n reuse_block(blk, strcat(output0,'0'), 'built-in/Outport', ...\n 'Port', '1', ...\n 'Position', [875 88 905 102]);\n\n reuse_block(blk, strcat(output1,'1'), 'built-in/Outport', ...\n 'Port', '2', ...\n 'Position', [875 168 905 182]);\n\n add_line(blk,'invert0/1',[strcat(output0,'0'),'/1']);\n add_line(blk,'invert1/1',[strcat(output1,'1'),'/1']);\n\nelse,\n reuse_block(blk, output0, 'built-in/Outport', ...\n 'Port', '1', ...\n 'Position', [875 88 905 102]);\n\n reuse_block(blk, output1, 'built-in/Outport', ...\n 'Port', '2', ...\n 'Position', [875 168 905 182]);\n add_line(blk,'invert0/1',[output0,'/1']);\n add_line(blk,'invert1/1',[output1,'/1']);\nend\n\n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misco', 'built-in/Outport', ...\n 'Port', '3', ...\n 'Position', [875 198 905 212]);\n else,\n reuse_block(blk, 'misco', 'built-in/Terminator', 'Position', [875 198 905 212]);\n end\n add_line(blk,'invert1/2','misco/1');\n\n\n %%%%%%%%%%%%%%%%%%%%% \n % final cleaning up %\n %%%%%%%%%%%%%%%%%%%%% \n\n clean_blocks(blk);\n\n fmtstr = sprintf('');\n set_param(blk, 'AttributesFormatString', fmtstr);\n %ensure that parameters we have forced reflect in mask parameters (ensure this matches varargin\n %passed by block so that hash in same_state can be compared)\n args = { ...\n 'output0', output0, 'output1', output1, 'phase', phase, 'fraction', fraction, ...\n 'table_bits', table_bits, 'n_bits', n_bits, 'bin_pt', bin_pt, 'bram_latency', bram_latency, ...\n 'add_latency', add_latency, 'mux_latency', mux_latency, 'neg_latency', neg_latency, ...\n 'conv_latency', conv_latency, 'store', store, 'pack', pack, 'bram', bram, 'misc', misc};\n save_state(blk, 'defaults', defaults, args{:});\n clog('exiting cosin_init',{'trace', 'cosin_init_debug'});\n\nend %cosin_init\n\nfunction draw_basic_partial_cycle(blk, full_cycle_bits, address_bits, lookup_bits, output0, output1, lookup_function0, lookup_function1)\n\n clog(sprintf('full_cycle_bits = %d, address_bits = %d, lookup_bits = %d', full_cycle_bits, address_bits, lookup_bits), {'draw_basic_partial_cycle_debug', 'cosin_init_debug'});\n \n if full_cycle_bits < 3,\n clog('parameters not sensible so returning', {'draw_basic_partial_cycle_debug', 'cosin_init_debug'});\n return;\n end\n\n reuse_block(blk, 'Constant4', 'xbsIndex_r4/Constant', ...\n 'const', '0', ...\n 'arith_type', 'Unsigned', ...\n 'n_bits', '1', ...\n 'bin_pt', '0', ...\n 'explicit_period', 'on', ...\n 'Position', [150 115 175 135]);\n \n clog(['adding ',[blk,'/add_convert0']], {'cosin_init_debug', 'draw_basic_partial_cycle_debug'});\n reuse_block(blk, 'add_convert0', 'built-in/SubSystem', 'Position', [195 80 265 140]);\n add_convert_init([blk,'/add_convert0'], full_cycle_bits, address_bits, lookup_bits, lookup_function0, output0);\n\n reuse_block(blk, 'Terminator', 'built-in/Terminator');\n set_param([blk,'/Terminator'], 'Position', [285 120 305 140]);\n\n add_line(blk,'assert/1','add_convert0/1');\n add_line(blk,'Constant4/1','add_convert0/2');\n add_line(blk,'add_convert0/3','Terminator/1');\n \n clog(['adding ',[blk,'/add_convert1']], {'cosin_init_debug', 'draw_basic_partial_cycle_debug'});\n reuse_block(blk, 'add_convert1', 'built-in/SubSystem', 'Position', [195 200 265 260]);\n add_convert_init([blk,'/add_convert1'], full_cycle_bits, address_bits, lookup_bits, lookup_function1, output1);\n \n\n\nend %draw_basic_partial_cycle\n\nfunction add_convert_init(blk, full_cycle_bits, address_bits, lookup_bits, lookup_function, output)\n\n clog(sprintf('full_cycle_bits = %d, address_bits = %d, lookup_bits = %d. lookup_function = %s, output = %s', full_cycle_bits, address_bits, lookup_bits, lookup_function, output), {'add_convert_init_debug', 'cosin_init_debug'});\n\n pad_bits = full_cycle_bits - address_bits; %need to pad address bits in to get to full cycle \n\n diff_bits = full_cycle_bits - lookup_bits; %what fraction of a cycle are we storing \n\n %reference using cos as lookup\n names = {'cos', '-sin', '-cos', 'sin'};\n \n %find how far lookup function is from our reference\n base = find(strcmp(lookup_function,names));\n\n %now find how far the required output is from our reference\n offset = find(strcmp(output,names));\n \n %find how many quadrants to shift address by to get to lookup function\n direction_offset = mod(offset - base,4);\n\n if (diff_bits == 2) && (strcmp(lookup_function, 'cos') || strcmp(lookup_function, '-cos')),\n negate_offset = mod(direction_offset + 1,4);\n else\n negate_offset = direction_offset;\n end \n\n clog(sprintf('direction offset = %d, diff_bits = %d', direction_offset, diff_bits), {'add_convert_init_debug', 'cosin_init_debug'});\n\n reuse_block(blk, 'theta', 'built-in/Inport', 'Port', '1', 'Position', [20 213 50 227]);\n\n if pad_bits ~= 0,\n reuse_block(blk, 'pad', 'xbsIndex_r4/Constant', 'const', '0', ...\n 'arith_type', 'Unsigned', 'n_bits', num2str(pad_bits), ...\n 'bin_pt', '0', 'Position', [65 185 85 205]);\n\n reuse_block(blk, 'fluff', 'xbsIndex_r4/Concat', ...\n 'num_inputs', '2', 'Position', [105 180 130 235]);\n add_line(blk, 'theta/1', 'fluff/2'); \n add_line(blk, 'pad/1', 'fluff/1'); \n end\n \n reuse_block(blk, 'add', 'built-in/Outport', 'Port', '2', 'Position', [840 203 870 217]);\n\n reuse_block(blk, 'new_add', 'xbsIndex_r4/Slice', ...\n 'nbits', num2str(lookup_bits), ...\n 'mode', 'Lower Bit Location + Width', ...\n 'Position', [380 242 410 268]);\n\n %%%%%%%%%%%%%%%%%%%%%%%\n % address translation %\n %%%%%%%%%%%%%%%%%%%%%%%\n\n if ~(direction_offset == 0 && diff_bits == 0),\n\n reuse_block(blk, 'quadrant', 'xbsIndex_r4/Slice', 'nbits', '2', 'Position', [150 172 180 198]);\n if pad_bits == 0, add_line(blk,'theta/1','quadrant/1');\n else add_line(blk, 'fluff/1', 'quadrant/1');\n end\n\n reuse_block(blk, 'direction_offset', 'xbsIndex_r4/Constant', ...\n 'const', num2str(direction_offset), ...\n 'arith_type', 'Unsigned', ...\n 'n_bits', '2', ...\n 'bin_pt', '0', ...\n 'Position', [55 150 75 170]);\n\n reuse_block(blk, 'AddSub5', 'xbsIndex_r4/AddSub', ...\n 'latency', '0', ...\n 'precision', 'User Defined', ...\n 'n_bits', '2', ...\n 'bin_pt', '0', ...\n 'use_behavioral_HDL', 'on', ...\n 'Position', [240 148 285 197]);\n add_line(blk,'direction_offset/1','AddSub5/1');\n add_line(blk,'quadrant/1','AddSub5/2');\n\n reuse_block(blk, 'lookup', 'xbsIndex_r4/Slice', 'nbits', num2str(full_cycle_bits-2), 'mode', 'Lower Bit Location + Width', ...\n 'Position', [150 252 180 278]);\n if pad_bits == 0, add_line(blk,'theta/1','lookup/1');\n else add_line(blk, 'fluff/1', 'lookup/1');\n end\n\n reuse_block(blk, 'Concat', 'xbsIndex_r4/Concat', 'num_inputs', '2', 'Position', [320 233 345 277]);\n add_line(blk,'lookup/1','Concat/2');\n add_line(blk,'AddSub5/1','Concat/1');\n\n add_line(blk,'Concat/1','new_add/1');\n else, \n if diff_bits == 0, add_line(blk,'theta/1','new_add/1');\n else add_line(blk, 'fluff/1', 'new_add/1');\n end\n end %if diff_bits == 0\n\n reuse_block(blk, 'Delay14', 'xbsIndex_r4/Delay', ...\n 'reg_retiming', 'on', 'latency', 'add_latency', 'Position', [540 201 570 219]); \n add_line(blk,'new_add/1','Delay14/1');\n\n reuse_block(blk, 'Convert2', 'xbsIndex_r4/Convert', ...\n 'arith_type', 'Unsigned', ...\n 'n_bits', num2str(lookup_bits), ...\n 'bin_pt', '0', ...\n 'overflow', 'Saturate', ...\n 'latency', 'conv_latency', ...\n 'pipeline', 'on', ...\n 'Position', [785 201 810 219]);\n add_line(blk,'Convert2/1','add/1');\n\n %%%%%%%%%%%%%\n % backwards %\n %%%%%%%%%%%%%\n \n %only need backwards translation for quarter cycle operation\n if (diff_bits == 2),\n\n reuse_block(blk, 'backwards', 'xbsIndex_r4/Slice', ...\n 'boolean_output', 'on', ...\n 'mode', 'Lower Bit Location + Width', ...\n 'bit0', '0', ...\n 'Position', [380 166 410 184]);\n\n reuse_block(blk, 'Constant4', 'xbsIndex_r4/Constant', ...\n 'const', num2str(2^lookup_bits), ...\n 'arith_type', 'Unsigned', ...\n 'n_bits', num2str(lookup_bits+1), ...\n 'bin_pt', '0', ...\n 'Position', [450 220 475 240]);\n\n reuse_block(blk, 'AddSub', 'xbsIndex_r4/AddSub', ...\n 'mode', 'Subtraction', ...\n 'latency', 'add_latency', ...\n 'precision', 'User Defined', ...\n 'n_bits', num2str(lookup_bits+1), ...\n 'bin_pt', '0', ...\n 'pipelined', 'on', ...\n 'Position', [530 217 575 268]);\n\n reuse_block(blk, 'Mux', 'xbsIndex_r4/Mux', 'latency', 'mux_latency', 'Position', [675 156 700 264]);\n\n reuse_block(blk, 'Delay13', 'xbsIndex_r4/Delay', ...\n 'latency', 'add_latency', ...\n 'reg_retiming', 'on', ...\n 'Position', [540 166 570 184]);\n\n add_line(blk,'AddSub5/1','backwards/1');\n add_line(blk,'backwards/1','Delay13/1');\n add_line(blk,'new_add/1','AddSub/2');\n add_line(blk,'Constant4/1','AddSub/1');\n add_line(blk,'Delay13/1','Mux/1');\n add_line(blk,'Delay14/1','Mux/2');\n add_line(blk,'AddSub/1','Mux/3');\n add_line(blk,'Mux/1','Convert2/1');\n\n else,\n %no backwards translation so just delay and put new address through\n reuse_block(blk, 'Delay13', 'xbsIndex_r4/Delay', ...\n 'reg_retiming', 'on', 'latency', 'mux_latency', 'Position', [675 201 705 219]);\n add_line(blk,'Delay14/1','Delay13/1');\n add_line(blk,'Delay13/1','Convert2/1');\n \n end %backwards translation\n\n %%%%%%%%%%%%%%%%%%%%%%\n % invert logic chain %\n %%%%%%%%%%%%%%%%%%%%%% \n \n reuse_block(blk, 'negate', 'built-in/Outport', 'Port', '1', 'Position', [835 98 865 112]);\n\n %need inversion if not got full cycle \n if (diff_bits ~= 0), \n \n reuse_block(blk, 'invert', 'xbsIndex_r4/Slice', ...\n 'boolean_output', 'on', ...\n 'Position', [380 96 410 114]);\n\n %if different sized offset\n if (negate_offset ~= direction_offset), \n reuse_block(blk, 'negate_offset', 'xbsIndex_r4/Constant', ...\n 'const', num2str(negate_offset), ...\n 'arith_type', 'Unsigned', ...\n 'n_bits', '2', ...\n 'bin_pt', '0', ...\n 'Position', [55 80 75 100]);\n\n reuse_block(blk, 'AddSub1', 'xbsIndex_r4/AddSub', ...\n 'latency', '0', ...\n 'precision', 'User Defined', ...\n 'n_bits', '2', ...\n 'bin_pt', '0', ...\n 'pipelined', 'on', ...\n 'Position', [240 78 285 127]);\n \n add_line(blk,'negate_offset/1','AddSub1/1');\n add_line(blk,'quadrant/1','AddSub1/2');\n add_line(blk,'AddSub1/1','invert/1');\n else,\n add_line(blk,'AddSub5/1','invert/1');\n end\n \n reuse_block(blk, 'Delay2', 'xbsIndex_r4/Delay', ...\n 'latency', 'add_latency+mux_latency+conv_latency', ...\n 'reg_retiming', 'on', ...\n 'Position', [675 96 705 114]);\n add_line(blk,'invert/1','Delay2/1');\n add_line(blk,'Delay2/1','negate/1');\n\n else, %otherwise no inversion required\n clog('no inversion required', {'add_convert_init_debug', 'cosin_init_debug'});\n reuse_block(blk, 'invert', 'xbsIndex_r4/Constant', ...\n 'const', '0', ...\n 'arith_type', 'Boolean', ...\n 'explicit_period', 'on', ...\n 'period', '1', ...\n 'Position', [675 96 705 114]);\n add_line(blk, 'invert/1', 'negate/1'); \n end\n\n %%%%%%%%%%%%%%\n % misc chain %\n %%%%%%%%%%%%%%\n \n reuse_block(blk, 'misci', 'built-in/Inport', ...\n 'Port', '2', ...\n 'Position', sprintf('[20 303 50 317]'));\n\n reuse_block(blk, 'Delay1', 'xbsIndex_r4/Delay', ...\n 'latency', 'mux_latency+add_latency+conv_latency', ...\n 'reg_retiming', 'on', ...\n 'Position', [540 301 570 319]);\n add_line(blk,'misci/1','Delay1/1');\n\n reuse_block(blk, 'misco', 'built-in/Outport', ...\n 'Port', '3', ...\n 'Position', [835 303 865 317]);\n add_line(blk,'Delay1/1','misco/1');\n\nend % add_convert_init\n\nfunction[vals] = gen_vals(func, phase, table_bits, subset, n_bits, bin_pt),\n %calculate init vector\n if strcmp(func, 'sin'),\n vals = sin((phase*(2*pi))+[0:subset-1]*pi*2/(2^table_bits));\n elseif strcmp(func, 'cos'),\n vals = cos((phase*(2*pi))+[0:subset-1]*pi*2/(2^table_bits));\n elseif strcmp(func, '-sin'),\n vals = -sin((phase*(2*pi))+[0:subset-1]*pi*2/(2^table_bits));\n elseif strcmp(func, '-cos'),\n vals = -cos((phase*(2*pi))+[0:subset-1]*pi*2/(2^table_bits));\n end %if strcmp(func)\n% vals = fi(vals, true, n_bits, bin_pt); %saturates at max so no overflow\n% vals = fi(vals, false, n_bits, bin_pt, 'OverflowMode', 'wrap'); %wraps negative component so can get back when positive\n\nend %gen_vals\n\nfunction invert_gen(blk)\n\n\tinvert_mask(blk);\n\tinvert_init(blk);\nend % invert_gen\n\nfunction invert_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', 'on', ...\n\t\t'MaskSelfModifiable', 'off', ...\n\t\t'MaskPromptString', 'bit width|binary point|negate latency|mux latency', ...\n\t\t'MaskStyleString', 'edit,edit,edit,edit', ...\n\t\t'MaskCallbackString', '|||', ...\n\t\t'MaskEnableString', 'on,on,on,on', ...\n\t\t'MaskVisibilityString', 'on,on,on,on', ...\n\t\t'MaskToolTipString', 'on,on,on,on', ...\n\t\t'MaskVariables', 'n_bits=@1;bin_pt=@2;neg_latency=@3;mux_latency=@4;', ...\n\t\t'MaskValueString', 'n_bits|bin_pt|neg_latency|mux_latency', ...\n\t\t'BackgroundColor', 'white');\n\nend % invert_mask\n\nfunction invert_init(blk)\n\n\treuse_block(blk, 'negate', 'built-in/Inport', ...\n\t\t'Port', '1', ...\n\t\t'Position', [15 43 45 57]);\n\n\treuse_block(blk, 'in', 'built-in/Inport', ...\n\t\t'Port', '2', ...\n\t\t'Position', [15 83 45 97]);\n\n\treuse_block(blk, 'misci', 'built-in/Inport', ...\n\t\t'Port', '3', ...\n\t\t'Position', [15 193 45 207]);\n\n\treuse_block(blk, 'Delay21', 'xbsIndex_r4/Delay', ...\n\t\t'latency', 'neg_latency', ...\n 'reg_retiming', 'on', ...\n\t\t'Position', [110 41 140 59]);\n\n\treuse_block(blk, 'Delay20', 'xbsIndex_r4/Delay', ...\n\t\t'latency', 'neg_latency', ...\n 'reg_retiming', 'on', ...\n\t\t'Position', [110 81 140 99]);\n\n\treuse_block(blk, 'Negate', 'xbsIndex_r4/Negate', ...\n\t\t'precision', 'User Defined', ...\n\t\t'arith_type', 'Signed (2''s comp)', ...\n\t\t'n_bits', 'n_bits', ...\n\t\t'bin_pt', 'bin_pt', ...\n\t\t'latency', 'neg_latency', ...\n 'overflow', 'Saturate', ...\n\t\t'Position', [100 119 155 141]);\n\n\treuse_block(blk, 'mux', 'xbsIndex_r4/Mux', ...\n\t\t'latency', 'mux_latency', ...\n\t\t'Position', [215 26 250 154]);\n\n\treuse_block(blk, 'Delay1', 'xbsIndex_r4/Delay', ...\n\t\t'latency', 'mux_latency+neg_latency', ...\n 'reg_retiming', 'on', ...\n\t\t'Position', [215 191 245 209]);\n\n\treuse_block(blk, 'out', 'built-in/Outport', ...\n\t\t'Port', '1', ...\n\t\t'Position', [300 83 330 97]);\n\n\treuse_block(blk, 'misco', 'built-in/Outport', ...\n\t\t'Port', '2', ...\n\t\t'Position', [300 193 330 207]);\n\n\tadd_line(blk,'misci/1','Delay1/1');\n\tadd_line(blk,'negate/1','Delay21/1');\n\tadd_line(blk,'in/1','Negate/1');\n\tadd_line(blk,'in/1','Delay20/1');\n\tadd_line(blk,'Delay21/1','mux/1');\n\tadd_line(blk,'Delay20/1','mux/2');\n\tadd_line(blk,'Negate/1','mux/3');\n\tadd_line(blk,'mux/1','out/1');\n\tadd_line(blk,'Delay1/1','misco/1');\nend % invert_init\n\n\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fir_dbl_tap_async_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fir_dbl_tap_async_init.m", "size": 9146, "source_encoding": "utf_8", "md5": "6ca1f7ee8663db5bce186dca292e24ce", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% MeerKAT Radio Telescope Project %\n% www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (meerKAT) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction fir_dbl_tap_async_init(blk)\n clog('entering fir_dbl_tap_async_init', 'trace');\n varargin = make_varargin(blk);\n defaults = {};\n check_mask_type(blk, 'fir_tap_async');\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n clog('fir_dbl_tap_async_init post same_state', 'trace');\n munge_block(blk, varargin{:});\n\n% factor = get_var('factor','defaults', defaults, varargin{:});\n% add_latency = get_var('latency','defaults', defaults, varargin{:});\n% mult_latency = get_var('latency','defaults', defaults, varargin{:});\n coeff_bit_width = get_var('coeff_bit_width','defaults', defaults, varargin{:});\n% coeff_bin_pt = get_var('coeff_bin_pt','defaults', defaults, varargin{:});\n async_ops = strcmp('on', get_var('async','defaults', defaults, varargin{:}));\n double_blk = strcmp('on', get_var('dbl','defaults', defaults, varargin{:}));\n\n if ~double_blk,\n error('This script should only be called on a doubled-up tap block.');\n end\n\n delete_lines(blk);\n\n %default state in library\n if coeff_bit_width == 0,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); \n return; \n end\n\n reuse_block(blk, 'a', 'built-in/Inport');\n set_param([blk,'/a'], ...\n 'Port', '1', ...\n 'Position', '[25 33 55 47]');\n reuse_block(blk, 'b', 'built-in/Inport');\n set_param([blk,'/b'], ...\n 'Port', '2', ...\n 'Position', '[25 123 55 137]');\n reuse_block(blk, 'c', 'built-in/Inport');\n set_param([blk,'/c'], ...\n 'Port', '3', ...\n 'Position', '[25 213 55 227]');\n reuse_block(blk, 'd', 'built-in/Inport');\n set_param([blk,'/d'], ...\n 'Port', '4', ...\n 'Position', '[25 303 55 317]');\n if async_ops,\n reuse_block(blk, 'dv_in', 'built-in/Inport', 'Port', '5', ...\n 'Position', '[205 0 235 14]');\n end\n \nreuse_block(blk, 'Register0', 'xbsIndex_r4/Register');\nset_param([blk,'/Register0'], ...\n'Position', '[315 16 360 64]');\n\nreuse_block(blk, 'Register1', 'xbsIndex_r4/Register');\nset_param([blk,'/Register1'], ...\n'Position', '[315 106 360 154]');\n\nreuse_block(blk, 'Register2', 'xbsIndex_r4/Register');\nset_param([blk,'/Register2'], ...\n'Position', '[315 196 360 244]');\n\nreuse_block(blk, 'Register3', 'xbsIndex_r4/Register');\nset_param([blk,'/Register3'], ...\n'Position', '[315 286 360 334]');\n\n if async_ops,\n set_param([blk, '/Register0'], 'en', 'on');\n set_param([blk, '/Register1'], 'en', 'on');\n set_param([blk, '/Register2'], 'en', 'on');\n set_param([blk, '/Register3'], 'en', 'on');\n else\n set_param([blk, '/Register0'], 'en', 'off');\n set_param([blk, '/Register1'], 'en', 'off');\n set_param([blk, '/Register2'], 'en', 'off');\n set_param([blk, '/Register3'], 'en', 'off');\n end\n\n reuse_block(blk, 'coefficient', 'xbsIndex_r4/Constant');\n set_param([blk,'/coefficient'], ...\n 'const', 'factor', ...\n 'n_bits', 'coeff_bit_width', ...\n 'bin_pt', 'coeff_bin_pt', ...\n 'explicit_period', 'on', ...\n 'Position', '[165 354 285 386]');\n \n reuse_block(blk, 'AddSub0', 'xbsIndex_r4/AddSub');\n set_param([blk,'/AddSub0'], ...\n 'latency', 'add_latency', ...\n 'arith_type', 'Signed (2''s comp)', ...\n 'n_bits', '18', ...\n 'bin_pt', '16', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'on', ...\n 'Position', '[180 412 230 463]');\n\n reuse_block(blk, 'Mult0', 'xbsIndex_r4/Mult');\n set_param([blk,'/Mult0'], ...\n 'n_bits', '18', ...\n 'bin_pt', '17', ...\n 'latency', 'mult_latency', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'off', ...\n 'placement_style', 'Rectangular shape', ...\n 'Position', '[315 402 365 453]');\n\n reuse_block(blk, 'AddSub1', 'xbsIndex_r4/AddSub');\n set_param([blk,'/AddSub1'], ...\n 'latency', 'add_latency', ...\n 'arith_type', 'Signed (2''s comp)', ...\n 'n_bits', '18', ...\n 'bin_pt', '16', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'on', ...\n 'Position', '[180 497 230 548]');\n\n reuse_block(blk, 'Mult1', 'xbsIndex_r4/Mult');\n set_param([blk,'/Mult1'], ...\n 'n_bits', '18', ...\n 'bin_pt', '17', ...\n 'latency', 'mult_latency', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'off', ...\n 'placement_style', 'Rectangular shape', ...\n 'Position', '[315 487 365 538]');\n\n reuse_block(blk, 'a_out', 'built-in/Outport');\n set_param([blk,'/a_out'], ...\n 'Port', '1', ...\n 'Position', '[390 33 420 47]');\n\n reuse_block(blk, 'b_out', 'built-in/Outport');\n set_param([blk,'/b_out'], ...\n 'Port', '2', ...\n 'Position', '[390 123 420 137]');\n\n reuse_block(blk, 'c_out', 'built-in/Outport');\n set_param([blk,'/c_out'], ...\n 'Port', '3', ...\n 'Position', '[390 213 420 227]');\n\n reuse_block(blk, 'd_out', 'built-in/Outport');\n set_param([blk,'/d_out'], ...\n 'Port', '4', ...\n 'Position', '[390 303 420 317]');\n\n reuse_block(blk, 'real', 'built-in/Outport');\n set_param([blk,'/real'], ...\n 'Port', '5', ...\n 'Position', '[390 423 420 437]');\n\n reuse_block(blk, 'imag', 'built-in/Outport');\n set_param([blk,'/imag'], ...\n 'Port', '6', ...\n 'Position', '[390 508 420 522]');\n\n if async_ops,\n add_line(blk, 'dv_in/1', 'Register0/2', 'autorouting', 'on');\n add_line(blk, 'dv_in/1', 'Register1/2', 'autorouting', 'on');\n add_line(blk, 'dv_in/1', 'Register2/2', 'autorouting', 'on');\n add_line(blk, 'dv_in/1', 'Register3/2', 'autorouting', 'on');\n end\n add_line(blk,'d/1','AddSub1/2', 'autorouting', 'on');\n add_line(blk,'d/1','Register3/1', 'autorouting', 'on');\n add_line(blk,'c/1','AddSub0/2', 'autorouting', 'on');\n add_line(blk,'c/1','Register2/1', 'autorouting', 'on');\n add_line(blk,'b/1','AddSub1/1', 'autorouting', 'on');\n add_line(blk,'b/1','Register1/1', 'autorouting', 'on');\n add_line(blk,'a/1','AddSub0/1', 'autorouting', 'on');\n add_line(blk,'a/1','Register0/1', 'autorouting', 'on');\n add_line(blk,'Register0/1','a_out/1', 'autorouting', 'on');\n add_line(blk,'Register1/1','b_out/1', 'autorouting', 'on');\n add_line(blk,'Register2/1','c_out/1', 'autorouting', 'on');\n add_line(blk,'coefficient/1','Mult0/1', 'autorouting', 'on');\n add_line(blk,'coefficient/1','Mult1/1', 'autorouting', 'on');\n add_line(blk,'Register3/1','d_out/1', 'autorouting', 'on');\n add_line(blk,'AddSub0/1','Mult0/2', 'autorouting', 'on');\n add_line(blk,'Mult0/1','real/1', 'autorouting', 'on');\n add_line(blk,'AddSub1/1','Mult1/2', 'autorouting', 'on');\n add_line(blk,'Mult1/1','imag/1', 'autorouting', 'on');\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:});\n clog('exiting fir_dbl_tap_async_init', 'trace');\n\nend % fir_dbl_tap_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "polynomial_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/polynomial_init.m", "size": 9746, "source_encoding": "utf_8", "md5": "1e1f6739e96ec953e2b202317ce5f63a", "text": "% Polynomial.\r\n%\r\n% polynomial_init(blk, varargin)\r\n%\r\n% blk = The block to be configured.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% n_polys = number of polynomials to implement\r\n% degree = polynomial degree\r\n% mult_latency = multiplier latency \r\n% bits_out = number of bits in output\r\n% bin_pt_out = binary point position of output\r\n% conv_latency = latency of convert/cast block\r\n% quantization = rounding/quantisation strategy \r\n% overflow = overflow strategy\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% MeerKAT Radio Telescope Project %\r\n% Copyright (C) 2011 Andrew Martens %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction polynomial_init(blk,varargin)\r\n\r\nclog('entering polynomial_init', 'trace');\r\ncheck_mask_type(blk, 'polynomial');\r\n\r\ndefaults = {'n_polys', 1, 'degree', 3, 'mult_latency', 2, ...\r\n 'bits_out', 18, 'bin_pt_out', 17, 'conv_latency', 2, ...\r\n 'quantization', 'Truncate', 'overflow', 'Wrap', ...\r\n 'bits_in', 8, 'bin_pt_in', 0};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('polynomial_init: post same_state', 'trace');\r\nmunge_block(blk, varargin{:});\r\ndelete_lines(blk);\r\n\r\nn_polys = get_var('n_polys', 'defaults', defaults, varargin{:});\r\ndegree = get_var('degree', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nbits_out = get_var('bits_out', 'defaults', defaults, varargin{:});\r\nbin_pt_out = get_var('bin_pt_out', 'defaults', defaults, varargin{:});\r\nconv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\noverflow = get_var('overflow', 'defaults', defaults, varargin{:});\r\nbits_in = get_var('bits_in', 'defaults', defaults, varargin{:});\r\nbin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:});\r\n\r\nxinc = 50+25*degree; %adder names become larger with higher degree\r\nyinc = 100;\r\n\r\n% Take care of misc \r\nreuse_block(blk, 'misc', 'built-in/inport', 'Port', '1', 'Position', [xinc-10 yinc-8 xinc+10 yinc+8]);\r\nreuse_block(blk, 'misc_out', 'built-in/outport', 'Port', '1' , ...\r\n 'Position', [((degree+3+1)*xinc)-10 yinc-8 ((degree+3+1)*xinc)+10 yinc+8]);\r\nif n_polys > 0, \r\n reuse_block(blk, 'misc_delay', 'xbsIndex_r4/Delay', ...\r\n 'latency', 'mult_latency*(degree+1)+conv_latency', ...\r\n 'Position', [(2*xinc)-15 yinc-10 ((degree+3)*xinc)+15 yinc+10]);\r\n add_line(blk, 'misc/1', 'misc_delay/1');\r\n add_line(blk, 'misc_delay/1', 'misc_out/1');\r\nelse\r\n add_line(blk, 'misc/1', 'misc_out/1');\r\nend\r\n\r\n%set up x delay and mult chain\r\nreuse_block(blk, 'x', 'built-in/inport', 'Port', '2', 'Position', [xinc/2-10 2*yinc-8 xinc/2+10 2*yinc+8]);\r\n\r\nprev_del_blk = 'x';\r\nif n_polys > 0, %don't bother if number of polynomials less than 1\r\n\r\n %x must be signed for MACs to be synthesised\r\n reuse_block(blk, 'convx', 'xbsIndex_r4/Convert', ...\r\n 'arith_type', 'Signed', ...\r\n 'latency', '0', 'quantization', 'Truncate', 'overflow', 'Wrap', ...\r\n 'n_bits', 'bits_in+1', 'bin_pt', 'bin_pt_in', ...\r\n 'Position', [xinc-15 2*yinc-8 xinc+15 2*yinc+8]);\r\n add_line(blk, 'x/1', 'convx/1');\r\n \r\n prev_mult_blk = 'convx';\r\n prev_del_blk = 'convx';\r\n for n = 2:degree,\r\n\r\n %delay block\r\n if n < degree,\r\n cur_del_blk = ['x_d',num2str(n-2)];\r\n latency = 'mult_latency';\r\n xend = n*xinc+15;\r\n reuse_block(blk, cur_del_blk, 'xbsIndex_r4/Delay', 'latency', latency, ...\r\n 'Position', [n*xinc-15 2*yinc-10 xend 2*yinc+10]);\r\n add_line(blk, [prev_del_blk,'/1'], [cur_del_blk,'/1']);\r\n prev_del_blk = cur_del_blk;\r\n end\r\n\r\n %mult block\r\n cur_mult_blk = ['x^',num2str(n)];\r\n reuse_block(blk, cur_mult_blk, 'xbsIndex_r4/Mult', 'latency', 'mult_latency', ...\r\n 'precision', 'Full', 'use_behavioral_HDL', 'on', ...\r\n 'Position', [n*xinc-15 3*yinc-15 n*xinc+15 3*yinc+15]);\r\n add_line(blk, [prev_del_blk,'/1'],[cur_mult_blk,'/1']);\r\n add_line(blk, [prev_mult_blk,'/1'],[cur_mult_blk,'/2']);\r\n prev_mult_blk = cur_mult_blk;\r\n \r\n end\r\nend\r\n\r\nif n_polys > 0,\r\n %last delay block\r\n cur_del_blk = ['x_d',num2str(max(0,degree-2))];\r\n latency = [num2str(min(degree+1,3)),'*mult_latency+conv_latency'];\r\n xend = (degree+3)*xinc+15;\r\n reuse_block(blk, cur_del_blk, 'xbsIndex_r4/Delay', 'latency', latency, ...\r\n 'Position', [max(degree,2)*xinc-15 2*yinc-10 xend 2*yinc+10]);\r\n add_line(blk, [prev_del_blk,'/1'], [cur_del_blk,'/1']);\r\n prev_del_blk = cur_del_blk;\r\nend\r\n\r\nreuse_block(blk, 'x_out', 'built-in/outport', 'Port', '2', ...\r\n 'Position', [((degree+3+1)*xinc)-10 2*yinc-8 ((degree+3+1)*xinc)+10 2*yinc+8]);\r\nadd_line(blk, [prev_del_blk,'/1'], 'x_out/1');\r\n\r\n%set up polynomial mult chain for each input\r\nyoff=5;\r\npoff=3;\r\nxoff=1;\r\nfor poly = 0:n_polys-1,\r\n src_mult_blk = 'convx';\r\n base = sprintf('%c',('a'+poly)); %a, b, c etc \r\n \r\n y_offset = yoff+(poly*(degree+1));\r\n p_offset = poff+(poly*(degree+1));\r\n port_name = [base,'0'];\r\n %a/b/c...0 input ports\r\n reuse_block(blk, port_name, 'built-in/inport', 'Port', ['',num2str(p_offset),''], ...\r\n 'Position', [(xoff*xinc)-10 (y_offset*yinc)-8 (xoff*xinc)+10 (y_offset*yinc)+8]);\r\n reuse_block(blk, [port_name,'_del'], 'xbsIndex_r4/Delay', 'latency', 'mult_latency', ...\r\n 'Position', [((xoff+1)*xinc)-15 (y_offset*yinc)-10 ((xoff+1)*xinc)+15 (y_offset*yinc)+10]);\r\n add_line(blk, [port_name,'/1'], [port_name,'_del/1']);\r\n \r\n add_name = port_name; %adder names starting with coefficient 0\r\n prev_adder = [port_name,'_del']; %input to first adder is delay\r\n for n = 1:degree,\r\n\r\n mult_name = [base,num2str(n),src_mult_blk];\r\n \r\n %adder\r\n add_name = [add_name,'+',mult_name]; %recursively build adder names\r\n reuse_block(blk, add_name, 'xbsIndex_r4/AddSub', 'latency', 'mult_latency', ...\r\n 'use_behavioral_HDL', 'on', 'pipelined', 'on', ...\r\n 'Position', [((xoff+n+1)*xinc)-20 (y_offset*yinc)-20 (xoff+n+1)*xinc+20 (y_offset*yinc)+20]);\r\n add_line(blk, [prev_adder,'/1'], [add_name,'/1']);\r\n prev_adder = add_name;\r\n\r\n %coefficient input port\r\n port_name = [base, num2str(n)];\r\n coeff_port = p_offset+n; \r\n reuse_block(blk, port_name, 'built-in/inport', 'Port', ['',num2str(coeff_port),''], ...\r\n 'Position', [xoff*xinc-10 ((y_offset+n)*yinc)-8 xoff*xinc+10 ((y_offset+n)*yinc)+8]);\r\n\r\n if n > 1,\r\n del_blk = [port_name,'_del'];\r\n %coefficient delay \r\n reuse_block(blk, del_blk, 'xbsIndex_r4/Delay', 'latency', ['mult_latency*',num2str(n-1)], ...\r\n 'Position', [((xoff+1)*xinc)-15 ((y_offset+n)*yinc)-10 ((xoff+n-1)*xinc)+15 ((y_offset+n)*yinc)+10]);\r\n add_line(blk, [port_name,'/1'], [del_blk,'/1']);\r\n else\r\n del_blk = port_name; \r\n end \r\n\r\n %polynomial multiplier\r\n reuse_block(blk, mult_name, 'xbsIndex_r4/Mult', 'latency', 'mult_latency', ...\r\n 'precision', 'Full', 'use_behavioral_HDL', 'on', ...\r\n 'Position', [(xoff+n)*xinc-15 ((y_offset+n)*yinc)-15 (xoff+n)*xinc+15 ((y_offset+n)*yinc)+15]);\r\n \r\n add_line(blk, [src_mult_blk,'/1'], [mult_name,'/1']);\r\n add_line(blk, [del_blk,'/1'], [mult_name,'/2']);\r\n src_mult_blk = ['x^',num2str(n+1)]; \r\n add_line(blk, [mult_name,'/1'], [add_name,'/2']);\r\n\r\n end \r\n\r\n %convert block\r\n conv_name = ['conv_',base,'(x)'];\r\n reuse_block(blk, conv_name, 'xbsIndex_r4/Convert', ...\r\n 'n_bits', 'bits_out', 'bin_pt', 'bin_pt_out', 'pipeline', 'on', ...\r\n 'latency', 'conv_latency', 'quantization', quantization, 'overflow', overflow, ...\r\n 'Position', [((degree+3)*xinc)-20 ((yoff+poly*(degree+1))*yinc)-20 ((degree+3)*xinc)+20 ((yoff+poly*(degree+1))*yinc)+20]);\r\n add_line(blk, [prev_adder,'/1'], [conv_name,'/1']);\r\n\r\n %output port\r\n reuse_block(blk, [base,'(x)'], 'built-in/outport', 'Port', ['',num2str(3+poly),''], ...\r\n 'Position', [((degree+3+1)*xinc)-10 ((yoff+poly*(degree+1))*yinc)-8 ((degree+3+1)*xinc)+10 ((yoff+poly*(degree+1))*yinc)+8]);\r\n add_line(blk, [conv_name,'/1'], [base,'(x)/1']);\r\n \r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\r\n\r\nclog('exiting polynomial_init', 'trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_add_tree_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_add_tree_init.m", "size": 7371, "source_encoding": "utf_8", "md5": "1e2bd3a590b6dc5ab6214b61484f1e1d", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction pfb_add_tree_init(blk, varargin)\n% Initialize and configure the Polyphase Filter Bank final summing tree.\n%\n% pfb_add_tree_init(blk, varargin)\n%\n% blk = The block to configure.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% TotalTaps = Total number of taps in the PFB\n% BitWidthIn = Input Bitwidth\n% BitWidthOut = Output Bitwidth\n% CoeffBitWidth = Bitwidth of Coefficients.\n% add_latency = Latency through each adder.\n% quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round\n% (unbiased: Even Values)'\n\n% Declare any default values for arguments you might like.\ndefaults = {};\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\ncheck_mask_type(blk, 'pfb_add_tree');\nmunge_block(blk, varargin{:});\n\nTotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:});\nBitWidthIn = get_var('BitWidthIn', 'defaults', defaults, varargin{:});\nBitWidthOut = get_var('BitWidthOut', 'defaults', defaults, varargin{:});\nCoeffBitWidth = get_var('CoeffBitWidth', 'defaults', defaults, varargin{:});\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\n\ndelete_lines(blk);\n\n% Add ports\nreuse_block(blk, 'din', 'built-in/inport', 'Position', [15 123 45 137], 'Port', '1');\nreuse_block(blk, 'sync', 'built-in/inport', 'Position', [15 28 45 42], 'Port', '2');\nreuse_block(blk, 'dout', 'built-in/outport', 'Position', [600 25*TotalTaps+100 630 25*TotalTaps+115], 'Port', '1');\nreuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [600 28 630 42], 'Port', '2');\n\n% Add Static Blocks\nreuse_block(blk, 'adder_tree1', 'casper_library_misc/adder_tree', ...\n 'n_inputs', num2str(TotalTaps), 'latency', num2str(add_latency), ...\n 'Position', [200 114 350 50*TotalTaps+114]);\nreuse_block(blk, 'adder_tree2', 'casper_library_misc/adder_tree', ...\n 'n_inputs', num2str(TotalTaps), 'latency', num2str(add_latency), ...\n 'Position', [200 164+50*TotalTaps 350 164+100*TotalTaps]);\nreuse_block(blk, 'convert1', 'xbsIndex_r4/Convert', ...\n 'arith_type', 'Signed (2''s comp)', 'n_bits', num2str(BitWidthOut), ...\n 'bin_pt', num2str(BitWidthOut-1), 'quantization', quantization, ...\n 'overflow', 'Saturate', 'latency', num2str(add_latency), 'pipeline', 'on',...\n 'Position', [500 25*TotalTaps+114 530 25*TotalTaps+128]);\nreuse_block(blk, 'convert2', 'xbsIndex_r4/Convert', ...\n 'arith_type', 'Signed (2''s comp)', 'n_bits', num2str(BitWidthOut), ...\n 'bin_pt', num2str(BitWidthOut-1), 'quantization', quantization, ...\n 'overflow', 'Saturate', 'latency', num2str(add_latency), ...\n 'Position', [500 158+25*TotalTaps 530 172+25*TotalTaps]);\n\n % Delay to compensate for latency of convert blocks\nreuse_block(blk, 'delay1', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(add_latency), ...\n 'Position', [400 50+25*TotalTaps 430 80+25*TotalTaps]);\n\n % Scale Blocks are required before casting to n_(n-1) format\n % Input to adder tree seemes to be n_(n-2) format\n % each level in the adder tree requires one more shift\n % so with just two taps, there is one level in the adder tree\n % so we would have, eg, 17_14 format, so we need to shift by 2 to get\n % 17_16 which can be converted to 18_17 without overflow.\n % There are nextpow2(TotalTaps) levels in the adder tree.\nscale_factor = 1 + nextpow2(TotalTaps);\nreuse_block(blk, 'scale1', 'xbsIndex_r4/Scale', ...\n 'scale_factor', num2str(-scale_factor), ...\n 'Position', [400 25*TotalTaps+114 430 25*TotalTaps+128]);\nreuse_block(blk, 'scale2', 'xbsIndex_r4/Scale', ...\n 'scale_factor', num2str(-scale_factor), ...\n 'Position', [400 158+25*TotalTaps 430 172+25*TotalTaps]);\n\n% Add lines\n%add_line(blk, 'adder_tree1/2', 'convert1/1');\n%add_line(blk, 'adder_tree2/2', 'convert2/1');\nadd_line(blk, 'adder_tree1/2', 'scale1/1');\nadd_line(blk, 'scale1/1', 'convert1/1');\nadd_line(blk, 'adder_tree2/2', 'scale2/1');\nadd_line(blk, 'scale2/1', 'convert2/1');\nreuse_block(blk, 'ri_to_c', 'casper_library_misc/ri_to_c', ...\n 'Position', [550 114+25*TotalTaps 580 144+25*TotalTaps]);\nadd_line(blk, 'convert1/1', 'ri_to_c/1');\nadd_line(blk, 'convert2/1', 'ri_to_c/2');\nadd_line(blk, 'ri_to_c/1', 'dout/1');\nadd_line(blk, 'sync/1', 'adder_tree1/1');\nadd_line(blk, 'sync/1', 'adder_tree2/1');\n%add_line(blk, 'adder_tree1/1', 'sync_out/1');\nadd_line(blk, 'adder_tree1/1', 'delay1/1');\nadd_line(blk, 'delay1/1', 'sync_out/1');\n\nfor p=0:TotalTaps-1,\n for q=1:2,\n slice_name = ['Slice', num2str(p),'_',num2str(q)];\n reuse_block(blk, slice_name, 'xbsIndex_r4/Slice', ...\n 'mode', 'Upper Bit Location + Width', 'nbits', num2str(CoeffBitWidth + BitWidthIn), ...\n 'base0', 'MSB of Input', 'base1', 'MSB of Input', ...\n 'bit1', num2str(-(2*p+q-1)*(CoeffBitWidth + BitWidthIn)), 'Position', [70 50*p+25*q+116 115 50*p+25*q+128]);\n add_line(blk, 'din/1', [slice_name, '/1']);\n reint_name = ['Reint',num2str(p),'_',num2str(q)];\n reuse_block(blk, reint_name, 'xbsIndex_r4/Reinterpret', ...\n 'force_arith_type', 'on', 'arith_type', 'Signed (2''s comp)', ...\n 'force_bin_pt', 'on', 'bin_pt', num2str(CoeffBitWidth + BitWidthIn - 2), ...\n 'Position', [130 50*p+25*q+116 160 50*p+25*q+128]);\n add_line(blk, [slice_name, '/1'], [reint_name, '/1']);\n add_line(blk, [reint_name, '/1'], ['adder_tree',num2str(q),'/',num2str(p+2)]);\n end\nend\n\nclean_blocks(blk);\n\nfmtstr = sprintf('taps=%d, add_latency=%d', TotalTaps, add_latency);\nset_param(blk, 'AttributesFormatString', fmtstr);\nsave_state(blk, 'defaults', defaults, varargin{:});\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fft_biplex_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fft_biplex_init.m", "size": 12957, "source_encoding": "utf_8", "md5": "ce01d00a2963f3ab6f7167d1f5912412", "text": "% Initialize and configure an fft_biplex block.\r\n%\r\n% fft_biplex_init(blk, varargin)\r\n%\r\n% blk = the block to configure\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames:\r\n% n_inputs = Number of simultaneous inputs\r\n% FFTSize = Size of the FFT (2^FFTSize points).\r\n% input_bit_width = Bit width of input and output data.\r\n% bin_pt_in = Binary point position of input data.\r\n% coeff_bit_width = Bit width of coefficients.\r\n% add_latency = The latency of adders in the system.\r\n% mult_latency = The latency of multipliers in the system.\r\n% bram_latency = The latency of BRAM in the system. \r\n% conv_latency = The latency of convert operations in the system. \r\n% quantization = Quantization strategy.\r\n% overflow = Overflow strategy.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://casper.berkeley.edu %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% SKA Africa %\r\n% www.kat.ac.za %\r\n% Copyright (C) 2013 Andrew Martens %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction fft_biplex_init(blk, varargin)\r\nclog('entering fft_biplex_init','trace');\r\n\r\n% If we are in a library, do nothing\r\nif is_library_block(blk)\r\n clog('exiting fft_biplex_init (library block)','trace');\r\n return\r\nend\r\n\r\n% If FFTSize is passed as 0, do nothing\r\nif get_var('FFTSize', varargin{:}) == 0\r\n clog('exiting fft_biplex_init (FFTSize==0)','trace');\r\n return\r\nend\r\n\r\n% If n_inputs is passed as 0, do nothing\r\nif get_var('n_inputs', varargin{:}) == 0\r\n clog('exiting fft_biplex_init (n_inputs==0)','trace');\r\n return\r\nend\r\n\r\n% Make sure block is not too old for current init script\r\ntry\r\n get_param(blk, 'n_streams');\r\ncatch\r\n errmsg = sprintf(['Block %s is too old for current init script.\\n', ...\r\n 'Please run \"update_casper_block(%s)\".\\n'], ...\r\n blk, blk);\r\n % We are not initializing the block because it is too old. Make sure the\r\n % user knows this by using a modal error dialog. Using a modal error\r\n % dialog is a drastic step, but the situation really needs user attention.\r\n errordlg(errmsg, 'FFT Block Too Old', 'modal');\r\n try\r\n ex = MException('casper:blockTooOldError', errmsg);\r\n throw(ex);\r\n catch ex\r\n clog('throwing from fft_biplex_init', 'trace');\r\n % We really want to dump this exception, even if its a duplicate of the\r\n % previously dumped exception, so reset dump_exception before dumping.\r\n dump_exception([]);\r\n dump_and_rethrow(ex);\r\n end\r\nend\r\n\r\n% Set default vararg values.\r\ndefaults = { ...\r\n 'n_streams', 1, ...\r\n 'n_inputs', 1, ...\r\n 'FFTSize', 2, ...\r\n 'input_bit_width', 18, ...\r\n 'bin_pt_in', 17, ...\r\n 'coeff_bit_width', 18, ...\r\n 'async', 'off', ...\r\n 'add_latency', 1, ...\r\n 'mult_latency', 2, ...\r\n 'bram_latency', 2, ...\r\n 'conv_latency', 1, ...\r\n 'quantization', 'Round (unbiased: +/- Inf)', ...\r\n 'overflow', 'Saturate', ...\r\n 'delays_bit_limit', 8, ...\r\n 'coeffs_bit_limit', 8, ...\r\n 'coeff_sharing', 'on', ...\r\n 'coeff_decimation', 'on', ...\r\n 'max_fanout', 4, ...\r\n 'mult_spec', 2, ...\r\n 'bitgrowth', 'off', ...\r\n 'max_bits', 18, ...\r\n 'hardcode_shifts', 'off', ...\r\n 'shift_schedule', [1 1], ...\r\n 'dsp48_adders', 'off', ...\r\n};\r\n\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('fft_biplex_init post same_state', {'trace', 'fft_biplex_init_debug'});\r\ncheck_mask_type(blk, 'fft_biplex');\r\nmunge_block(blk, varargin{:});\r\n\r\n% Retrieve values from mask fields.\r\nn_streams = get_var('n_streams', 'defaults', defaults, varargin{:});\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\nFFTSize = get_var('FFTSize', 'defaults', defaults, varargin{:});\r\ninput_bit_width = get_var('input_bit_width', 'defaults', defaults, varargin{:});\r\nbin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:});\r\ncoeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\r\nasync = get_var('async', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\nconv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\noverflow = get_var('overflow', 'defaults', defaults, varargin{:});\r\ndelays_bit_limit = get_var('delays_bit_limit', 'defaults', defaults, varargin{:});\r\ncoeffs_bit_limit = get_var('coeffs_bit_limit', 'defaults', defaults, varargin{:});\r\ncoeff_sharing = get_var('coeff_sharing', 'defaults', defaults, varargin{:});\r\ncoeff_decimation = get_var('coeff_decimation', 'defaults', defaults, varargin{:});\r\nmax_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:});\r\nmult_spec = get_var('mult_spec', 'defaults', defaults, varargin{:});\r\nbitgrowth = get_var('bitgrowth', 'defaults', defaults, varargin{:});\r\nmax_bits = get_var('max_bits', 'defaults', defaults, varargin{:});\r\nhardcode_shifts = get_var('hardcode_shifts', 'defaults', defaults, varargin{:});\r\nshift_schedule = get_var('shift_schedule', 'defaults', defaults, varargin{:});\r\ndsp48_adders = get_var('dsp48_adders', 'defaults', defaults, varargin{:});\r\n\r\n% bin_pt_in == -1 is a special case for backwards compatibility\r\nif bin_pt_in == -1\r\n bin_pt_in = input_bit_width - 1;\r\n set_mask_params(blk, 'bin_pt_in', num2str(bin_pt_in));\r\nend\r\n\r\nytick = 60;\r\n\r\ndelete_lines(blk);\r\n\r\n% check the per-stage multiplier specification\r\n[temp, mult_spec] = multiplier_specification(mult_spec, FFTSize, blk);\r\nclear temp;\r\n\r\n%\r\n% prepare bus creators\r\n%\r\n\r\nreuse_block(blk, 'even_bussify', 'casper_library_flow_control/bus_create', ...\r\n 'inputNum', num2str(n_inputs*n_streams), 'Position', [150 74 210 116+(((n_streams*n_inputs)-1)*ytick)]); \r\n\r\nreuse_block(blk, 'odd_bussify', 'casper_library_flow_control/bus_create', ...\r\n 'inputNum', num2str(n_inputs*n_streams), 'Position', [150 74+((n_streams*n_inputs)*ytick) 210 116+((((n_streams*n_inputs)*2)-1)*ytick)]); \r\n\r\n%\r\n% prepare bus splitters\r\n%\r\n\r\nif strcmp(bitgrowth,'on'), n_bits_out = min(input_bit_width+FFTSize, max_bits);\r\nelse n_bits_out = input_bit_width;\r\nend\r\n\r\nfor index = 0:1,\r\n reuse_block(blk, ['pol',num2str(index),'_debus'], 'casper_library_flow_control/bus_expand', ...\r\n 'mode', 'divisions of equal size', 'outputNum', num2str(n_inputs*n_streams), ...\r\n 'outputWidth', num2str(n_bits_out*2), 'outputBinaryPt', '0', 'outputArithmeticType', '0', ...\r\n 'Position', [490 49+((n_streams*n_inputs)*index)*ytick 580 81+(((n_streams*n_inputs)*(index+1))-1)*ytick]);\r\nend %for\r\n\r\n%input ports\r\nreuse_block(blk, 'sync', 'built-in/inport', 'Position', [15 13 45 27], 'Port', '1');\r\nreuse_block(blk, 'shift', 'built-in/inport', 'Position', [15 43 45 57], 'Port', '2');\r\nreuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [635 25 665 39], 'Port', '1');\r\nreuse_block(blk, 'of', 'built-in/outport', 'Position', [400 150 430 164], 'Port', num2str(1+((n_streams*n_inputs)*2)+1));\r\n\r\nif strcmp(async, 'on'),\r\n reuse_block(blk, 'en', 'built-in/inport', ...\r\n 'Position', [180 73+(((n_streams*n_inputs*2)+1)*ytick) 210 87+(((n_streams*n_inputs*2)+1)*ytick)], 'Port', num2str(2+(n_streams*n_inputs*2)+1));\r\n reuse_block(blk, 'dvalid', 'built-in/outport', ...\r\n 'Position', [490 73+(((n_streams*n_inputs*2)+1)*ytick) 520 87+(((n_streams*n_inputs*2)+1)*ytick)], 'Port', num2str(1+(n_streams*n_inputs*2)+1+1));\r\nend\r\n\r\n%data inputs, outputs, connections to bus creation and expansion blocks\r\nmult = 2;\r\nfor s = 0:n_streams-1,\r\n base = s*(n_inputs*mult);\r\n for n = 0:(n_inputs*mult)-1,\r\n in = ['pol',num2str(s),num2str(n),'_in'];\r\n reuse_block(blk, in, 'built-in/inport', ...\r\n 'Position', [15 73+((base+n)*ytick) 45 87+((base+n)*ytick)], ...\r\n 'Port', num2str(3+base+n));\r\n\r\n out = ['pol',num2str(s),num2str(n),'_out'];\r\n reuse_block(blk, out, 'built-in/outport', ...\r\n 'Position', [635 53+((base+n)*ytick) 665 67+((base+n)*ytick)], ...\r\n 'Port', num2str(2+base+n));\r\n\r\n %connect inputs to bus creators\r\n if mod(n,mult) == 0, bussify_target = 'even';\r\n else bussify_target = 'odd';\r\n end\r\n add_line(blk, [in,'/1'], [bussify_target, '_bussify/', num2str(floor((base+n)/mult)+1)]);\r\n\r\n %connect debus outputs to output\r\n add_line(blk, ['pol', num2str(mod((base+n),mult)), '_debus/', num2str(floor((base+n)/mult)+1)], [out,'/1']); \r\n end %for n\r\nend %for s\r\n\r\nreuse_block(blk, 'biplex_core', 'casper_library_ffts/biplex_core', ...\r\n 'n_inputs', num2str(n_streams*n_inputs), ...\r\n 'FFTSize', num2str(FFTSize), ...\r\n 'input_bit_width', num2str(input_bit_width), ...\r\n 'bin_pt_in', num2str(bin_pt_in), ...\r\n 'coeff_bit_width', num2str(coeff_bit_width), ...\r\n 'async', async, ...\r\n 'add_latency', num2str(add_latency), ...\r\n 'mult_latency', num2str(mult_latency), ...\r\n 'bram_latency', num2str(bram_latency), ...\r\n 'conv_latency', num2str(conv_latency), ...\r\n 'quantization', quantization, ...\r\n 'overflow', overflow, ...\r\n 'delays_bit_limit', num2str(delays_bit_limit), ...\r\n 'coeffs_bit_limit', num2str(coeffs_bit_limit), ...\r\n 'coeff_sharing', coeff_sharing, ...\r\n 'coeff_decimation', coeff_decimation, ...\r\n 'max_fanout', num2str(max_fanout), ...\r\n 'mult_spec', mat2str(mult_spec), ...\r\n 'bitgrowth', bitgrowth, ...\r\n 'max_bits', num2str(max_bits), ...\r\n 'hardcode_shifts', hardcode_shifts, ...\r\n 'shift_schedule', mat2str(shift_schedule), ...\r\n 'dsp48_adders', dsp48_adders, ...\r\n 'Position', [250 30 335 125]);\r\n\r\nadd_line(blk, 'sync/1', 'biplex_core/1');\r\nadd_line(blk, 'shift/1', 'biplex_core/2');\r\nadd_line(blk, 'even_bussify/1', 'biplex_core/3');\r\nadd_line(blk, 'odd_bussify/1', 'biplex_core/4');\r\n\r\nreuse_block(blk, 'biplex_cplx_unscrambler', 'casper_library_ffts_internal/biplex_cplx_unscrambler', ...\r\n 'FFTSize', num2str(FFTSize), ...\r\n 'bram_latency', num2str(bram_latency), ...\r\n 'coeffs_bit_limit', num2str(coeffs_bit_limit), ...\r\n 'async', async, ...\r\n 'Position', [380 30 455 120]) \r\n\r\nadd_line(blk, ['biplex_core/1'], ['biplex_cplx_unscrambler/3']);\r\nadd_line(blk, ['biplex_core/2'], ['biplex_cplx_unscrambler/1']);\r\nadd_line(blk, ['biplex_core/3'], ['biplex_cplx_unscrambler/2']);\r\n\r\nadd_line(blk, 'biplex_core/4', 'of/1');\r\n\r\n%output ports\r\n\r\nif strcmp(async, 'on'),\r\n add_line(blk, 'en/1', 'biplex_core/5');\r\n add_line(blk, 'biplex_core/5', 'biplex_cplx_unscrambler/4');\r\n add_line(blk, 'biplex_cplx_unscrambler/4', 'dvalid/1');\r\nend\r\n\r\nadd_line(blk, 'biplex_cplx_unscrambler/3', 'sync_out/1');\r\nadd_line(blk, 'biplex_cplx_unscrambler/1', 'pol0_debus/1');\r\nadd_line(blk, 'biplex_cplx_unscrambler/2', 'pol1_debus/1');\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('%d stages',FFTSize);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\nclog('exiting fft_biplex_init', {'trace', 'fft_biplex_init_debug'});\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "update_casper_library_links.m", "ext": ".m", "path": "mlib_devel-master/casper_library/update_casper_library_links.m", "size": 5038, "source_encoding": "utf_8", "md5": "27eb7a850735a99442bca74c2fc283e2", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://casper.berkeley.edu/ %\n% Copyright (C) 2013 David MacMahon %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction update_casper_library_links(varargin)\n\n % Regexp for blacklisted blocks (e.g. script generated or xBlock based\n % blocks)\n persistent blacklist_re;\n if ~iscell(blacklist_re)\n blacklist_re = { ...\n '^casper_library_bus$', ...\n '^casper_library_multipliers/complex_conj/' ...\n };\n end\n\n if nargin == 0\n % No arguments given, use all open or loaded CASPER library block diagrams\n sys = find_system( ...\n 'RegExp', 'on', ...\n 'Type', 'block_diagram', ...\n 'Name', '(casper|xps)_library');\n elseif nargin == 1\n % Handle single cell array arguments\n sys = varargin{1};\n else\n sys = varargin;\n end\n\n if ~iscell(sys)\n sys = {sys};\n end\n\n linked_blks = {};\n for k=1:length(sys)\n % Ignore this block if it has been blacklisted\n if any(cell2mat(regexp(sys{k}, blacklist_re)))\n continue;\n end\n\n % If this block has been linked\n if strcmp(get_param(sys{k}, 'Type'), 'block') ...\n && ~strcmp(get_param(sys{k}, 'StaticLinkStatus'), 'none')\n % Use ^ and $ anchors to blacklist this specific block\n % (so we don't see it again)\n blacklist_re{end+1} = sprintf('^%s$', sys{k});\n % If this block is linked, blacklist sub-blocks and ignore this one\n if ~strcmp(get_param(sys{k}, 'StaticLinkStatus'), 'none')\n blacklist_re{end+1} = sprintf('^%s/', sys{k});\n end\n continue;\n end\n\n % Make sure sys{k}'s block diagram is loaded\n bd = regexprep(sys{k}, '/.*', '');\n if ~bdIsLoaded(bd)\n fprintf(2, 'loading library %s\\n', bd);\n load_system(bd);\n end\n\n % Find blocks that have inactive link to a CASPER block\n inactive_links = find_system(sys{k}, 'FollowLinks', 'off', ...\n 'LookUnderMasks','all', 'RegExp', 'on', ...\n 'StaticLinkStatus', 'inactive', ...\n 'AncenstorBlock','(casper|xps)_library');\n\n % Find blocks that have resolved link to a CASPER block\n resolved_links = find_system(sys{k}, 'FollowLinks', 'off', ...\n 'LookUnderMasks','all', 'RegExp', 'on', ...\n 'StaticLinkStatus', 'resolved', ...\n 'ReferenceBlock','(casper|xps)_library');\n\n % Concatentate the two lists onto linked_blks\n linked_blks = [linked_blks; resolved_links; inactive_links];\n end\n\n % Sort linked_blks and remove duplicates\n linked_blks = unique(sort(linked_blks));\n\n % For each linked block, find its source block\n for k=1:length(linked_blks)\n % Skip if blacklisted\n if any(cell2mat(regexp(linked_blks{k}, blacklist_re)))\n continue;\n else\n % Make sure we skip this block if we see it again\n blacklist_re{end+1} = sprintf('^%s$', linked_blks{k});\n end\n\n link_status = get_param(linked_blks{k}, 'StaticLinkStatus');\n if strcmp(link_status, 'inactive'),\n source = get_param(linked_blks{k}, 'AncestorBlock');\n elseif strcmp(link_status, 'resolved'),\n source = get_param(linked_blks{k}, 'ReferenceBlock'); \n else\n % Should \"never\" happen\n continue;\n end\n\n % Make sure any links in the source block have been updated\n update_casper_library_links(source);\n\n % Make sure linked block's block diagram is unlocked\n set_param(bdroot(linked_blks{k}), 'Lock', 'off');\n\n % Update linked block\n fprintf(1, 'updating %s (linked to %s)\\n', linked_blks{k}, source);\n update_casper_block(linked_blks{k});\n end\n\nend % function\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "compute_order.m", "ext": ".m", "path": "mlib_devel-master/casper_library/compute_order.m", "size": 380, "source_encoding": "utf_8", "md5": "6fa81a3a2aa0a58dde94ccd697afb31e", "text": "% Computes the cyclic order of a permutation\r\nfunction rv = compute_order(map)\r\norder = 1;\r\nfor i=1:length(map),\r\n j = -1;\r\n cur_order = 1;\r\n while j+1 ~= i,\r\n if j < 0,\r\n j = map(i);\r\n else,\r\n j = map(j+1);\r\n cur_order = cur_order + 1;\r\n end\r\n end\r\n order = lcm(order, cur_order);\r\nend\r\n \r\nrv = order;\r\n "} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "save_state.m", "ext": ".m", "path": "mlib_devel-master/casper_library/save_state.m", "size": 2502, "source_encoding": "utf_8", "md5": "a9966a2e72bf3417935963e7a092139d", "text": "% Saves blk's new state and parameters.\n%\n% save_state(blk,varargin)\n%\n% blk = The block to check\n% varargin = The things to compare.\n%\n% The block's UserData 'state' parameter is updated with the contents of the hash of\n% varargin, and the parameters saved in the 'parameters' struct.\n% the block's UserDataPersistent parameter is set to 'on'.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction save_state(blk,varargin)\n\n%check varargin contains even number of variables\nif( mod(length(varargin),2) ~= 0 ) disp('save_state.m: Non-even parameter list'); return; end;\n\t\nstruct.state = hashcell(varargin);\nstruct.parameters = [];\n% Construct struct of parameter values\nfor j = 1:length(varargin)/2,\n\tstruct.parameters = setfield( struct.parameters, varargin{j*2-1}, varargin{j*2} );\nend\n\nset_param(blk,'UserData',struct);\nset_param(blk,'UserDataPersistent','on');\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "twiddle_general_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/twiddle_general_init.m", "size": 11555, "source_encoding": "utf_8", "md5": "28b657eb3a8f35ee083eb58d841f0efe", "text": "% twiddle_general_init(blk, varargin)\r\n%\r\n% blk = The block to configure\r\n% varargin = {'varname', 'value, ...} pairs\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Karoo Array Telesope %\r\n% http://www.kat.ac.za %\r\n% Copyright (C) 2013 Andrew Martens %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction twiddle_general_init(blk, varargin)\r\nclog('entering twiddle_general_init','trace');\r\n\r\ndefaults = { ...\r\n 'n_inputs', 1, ...\r\n 'FFTSize', 2, ...\r\n 'async', 'off', ...\r\n 'Coeffs', [0 1], ...\r\n 'StepPeriod', 0, ...\r\n 'input_bit_width', 18, ...\r\n 'bin_pt_in', 17, ...\r\n 'coeff_bit_width', 18, ...\r\n 'add_latency', 1, ...\r\n 'mult_latency', 2, ...\r\n 'conv_latency', 1, ...\r\n 'bram_latency', 2, ...\r\n 'coeffs_bit_limit', 9, ...\r\n 'coeff_sharing', 'on', ...\r\n 'coeff_decimation', 'on', ...\r\n 'coeff_generation', 'on', ...\r\n 'cal_bits', 1, ...\r\n 'n_bits_rotation', 25, ...\r\n 'max_fanout', 4, ...\r\n 'use_hdl', 'off', ...\r\n 'use_embedded', 'off', ...\r\n 'quantization', 'Round (unbiased: +/- Inf)', ...\r\n 'overflow', 'Wrap'};\r\n\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('twiddle_general_init post same_state', 'trace');\r\ncheck_mask_type(blk, 'twiddle_general');\r\nmunge_block(blk, varargin{:});\r\n\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\nFFTSize = get_var('FFTSize', 'defaults', defaults, varargin{:});\r\nCoeffs = get_var('Coeffs', 'defaults', defaults, varargin{:});\r\nStepPeriod = get_var('StepPeriod', 'defaults', defaults, varargin{:});\r\ninput_bit_width = get_var('input_bit_width', 'defaults', defaults, varargin{:});\r\nbin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:});\r\ncoeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nconv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\ncoeffs_bit_limit = get_var('coeffs_bit_limit', 'defaults', defaults, varargin{:});\r\ncoeff_sharing = get_var('coeff_sharing', 'defaults', defaults, varargin{:});\r\ncoeff_decimation = get_var('coeff_decimation', 'defaults', defaults, varargin{:});\r\ncoeff_generation = get_var('coeff_generation', 'defaults', defaults, varargin{:});\r\ncal_bits = get_var('cal_bits', 'defaults', defaults, varargin{:});\r\nn_bits_rotation = get_var('n_bits_rotation', 'defaults', defaults, varargin{:});\r\nmax_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:});\r\nuse_hdl = get_var('use_hdl', 'defaults', defaults, varargin{:});\r\nuse_embedded = get_var('use_embedded', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\noverflow = get_var('overflow', 'defaults', defaults, varargin{:});\r\nasync = get_var('async', 'defaults', defaults, varargin{:});\r\n\r\ndelete_lines(blk);\r\n\r\n%default case, leave clean block with nothing for storage in the libraries \r\nif n_inputs == 0 || FFTSize == 0, \r\n clean_blocks(blk);\r\n set_param(blk, 'AttributesFormatString', '');\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting twiddle_general_init', 'trace');\r\n return;\r\nend\r\n\r\n%sync signal path\r\nreuse_block(blk, 'sync_in', 'built-in/Inport', 'Port', '3', 'Position', [10 108 40 122]);\r\nreuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '3', 'Position', [750 233 780 247]);\r\n\r\n%a signal path\r\nreuse_block(blk, 'ai', 'built-in/Inport', 'Port', '1', 'Position', [10 273 40 287]);\r\nreuse_block(blk, 'ao', 'built-in/Outport', 'Port', '1', 'Position', [750 283 780 297]);\r\n\r\n%b signal path\r\nreuse_block(blk, 'bi', 'built-in/Inport', 'Port', '2', 'Position', [10 213 40 227]);\r\n\r\nif strcmp(async, 'on'), inputNum = 4;\r\nelse, inputNum = 3;\r\nend\r\n\r\nreuse_block(blk, 'bwo', 'built-in/Outport', 'Port', '2', 'Position', [750 133 780 147]);\r\n\r\n%data valid for asynchronous operation\r\nif strcmp(async, 'on'),\r\n reuse_block(blk, 'en', 'built-in/Inport', 'Port', '4', 'Position', [10 183 40 197]);\r\n reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', '4', 'Position', [750 333 780 347]);\r\nend\r\n\r\nreuse_block(blk, 'bus_create', 'casper_library_flow_control/bus_create', ...\r\n 'inputNum', num2str(inputNum), 'Position', [145 204 200 326]);\r\nadd_line(blk, 'bi/1', 'bus_create/1');\r\nadd_line(blk, 'sync_in/1', 'bus_create/2');\r\nadd_line(blk, 'ai/1', 'bus_create/3');\r\n\r\n% Coefficient generator\r\nreuse_block(blk, 'coeff_gen', 'casper_library_ffts_twiddle_coeff_gen/coeff_gen', ...\r\n 'FFTSize', 'FFTSize', 'Coeffs', mat2str(Coeffs), ...\r\n 'coeff_bit_width', 'coeff_bit_width', 'StepPeriod', 'StepPeriod', ...\r\n 'async', async, 'misc', 'on', ...\r\n 'bram_latency', 'bram_latency', 'mult_latency', 'mult_latency', ...\r\n 'add_latency', 'add_latency', 'conv_latency', 'conv_latency', ...\r\n 'coeffs_bit_limit', 'coeffs_bit_limit', 'coeff_sharing', coeff_sharing, ...\r\n 'coeff_decimation', coeff_decimation, 'coeff_generation', coeff_generation, ...\r\n 'cal_bits', 'cal_bits', 'n_bits_rotation', 'n_bits_rotation', ... \r\n 'quantization', quantization, 'Position', [225 78 285 302]);\r\nadd_line(blk, 'sync_in/1', 'coeff_gen/1');\r\n\r\nif strcmp(async, 'on'), \r\n add_line(blk, 'en/1', 'bus_create/4'); \r\n add_line(blk, 'en/1', 'coeff_gen/2'); \r\n add_line(blk, 'bus_create/1', 'coeff_gen/3'); \r\n \r\n reuse_block(blk, 'Terminator', 'built-in/Terminator', 'Position', [305 180 325 200]);\r\n add_line(blk, 'coeff_gen/2', 'Terminator/1'); \r\n outputWidth = '[n_inputs*input_bit_width*2, 2+(n_inputs*input_bit_width*2)]'; %for bus_expand\r\nelse, \r\n add_line(blk, 'bus_create/1', 'coeff_gen/2'); \r\n outputWidth = '[n_inputs*input_bit_width*2, 1+(n_inputs*input_bit_width*2)]'; %for bus_expand\r\nend\r\n\r\n%bus expand pre multipliers\r\nreuse_block(blk, 'bus_expand', 'casper_library_flow_control/bus_expand', ...\r\n 'mode', 'divisions of arbitrary size', 'outputNum', '2', ...\r\n 'outputWidth', outputWidth, 'outputBinaryPt', '[0 0]', ...\r\n 'outputArithmeticType', '[0 0]', 'Position', [345 164 395 366]);\r\n\r\nif strcmp(async,'on'), add_line(blk, 'coeff_gen/3', 'bus_expand/1');\r\nelse add_line(blk, 'coeff_gen/2', 'bus_expand/1');\r\nend\r\n\r\nif strcmp(use_hdl,'off') & strcmp(use_embedded,'on')\r\n multiplier_implementation = 'embedded multiplier core';\r\nelseif strcmp(use_hdl,'off') & strcmp(use_embedded,'off')\r\n multiplier_implementation = 'standard core';\r\nelse\r\n multiplier_implementation = 'behavioral HDL';\r\nend\r\n\r\n%multipliers\r\nreuse_block(blk, 'bus_mult', 'casper_library_bus/bus_mult', ...\r\n 'n_bits_a', 'coeff_bit_width', ...\r\n 'bin_pt_a', 'coeff_bit_width-1', 'type_a', '1', 'cmplx_a', 'on', ...\r\n 'n_bits_b', mat2str(repmat(input_bit_width, 1, n_inputs)), ...\r\n 'bin_pt_b', 'bin_pt_in', 'type_b', '1', 'cmplx_b', 'on', ...\r\n 'n_bits_out', 'input_bit_width+coeff_bit_width+1', ...\r\n 'bin_pt_out', '(bin_pt_in+coeff_bit_width-1)', 'type_out', '1', ...\r\n 'quantization', '0', 'overflow', '0', ...\r\n 'multiplier_implementation', multiplier_implementation,...\r\n 'mult_latency', 'mult_latency', 'add_latency', 'add_latency', 'conv_latency', '0', ...\r\n 'max_fanout', 'max_fanout', 'fan_latency', num2str(ceil(log2(n_inputs))+1), ...\r\n 'misc', 'on', ...\r\n 'Position', [430 66 485 364]);\r\n\tadd_line(blk,'coeff_gen/1','bus_mult/1');\r\n\tadd_line(blk,'bus_expand/2','bus_mult/3');\r\n\tadd_line(blk,'bus_expand/1','bus_mult/2');\r\n\r\n%convert\r\nif strcmp(quantization, 'Truncate'), quant = '0';\r\nelseif strcmp(quantization, 'Round (unbiased: +/- Inf)'), quant = '1';\r\nelseif strcmp(quantization, 'Round (unbiased: Even Values)'), quant = '2';\r\nelse %TODO \r\nend\r\n\r\nif strcmp(overflow, 'Wrap'), of = '0';\r\nelseif strcmp(overflow, 'Saturate'), of = '1';\r\nelseif strcmp(overflow, 'Flag as error'), of = '2';\r\nelse %TODO\r\nend\r\n\r\nreuse_block(blk, 'bus_convert', 'casper_library_bus/bus_convert', ...\r\n 'n_bits_in', 'repmat(input_bit_width+coeff_bit_width+1, 1, n_inputs)', ...\r\n 'bin_pt_in', '(bin_pt_in+coeff_bit_width-1)', 'cmplx', 'on', ...\r\n 'n_bits_out', 'input_bit_width+1', 'bin_pt_out', 'bin_pt_in', ...\r\n 'quantization', quant, 'overflow', of, ...\r\n 'latency', 'conv_latency', 'of', 'off', 'misc', 'on', ...\r\n 'Position', [515 64 570 366]);\r\nadd_line(blk, 'bus_mult/1', 'bus_convert/1'); \r\nadd_line(blk, 'bus_mult/2', 'bus_convert/2'); \r\nadd_line(blk, 'bus_convert/1', 'bwo/1');\r\n\r\noutputWidth = [1 n_inputs*(input_bit_width*2)]; %cut sync out\r\noutputBinaryPt = [0 0]; \r\noutputArithmeticType = [2 0];\r\n\r\n%cut dvalid out again\r\nif strcmp(async, 'on'),\r\n outputWidth = [outputWidth, 1];\r\n outputBinaryPt = [outputBinaryPt, 0];\r\n outputArithmeticType = [outputArithmeticType, 2];\r\nend\r\n\r\nreuse_block(blk, 'bus_expand1', 'casper_library_flow_control/bus_expand', ...\r\n 'mode', 'divisions of arbitrary size', ...\r\n 'outputNum', num2str(inputNum-1), ...\r\n 'outputWidth', mat2str(outputWidth) , ...\r\n 'outputBinaryPt', mat2str(outputBinaryPt) , ...\r\n 'outputArithmeticType', mat2str(outputArithmeticType), ...\r\n 'Position', [600 212 650 363]);\r\n\r\nadd_line(blk,'bus_convert/2','bus_expand1/1');\r\n\r\nadd_line(blk,'bus_expand1/1','sync_out/1');\r\nadd_line(blk,'bus_expand1/2','ao/1');\r\n\r\nif strcmp(async, 'on'), add_line(blk,'bus_expand1/3','dvalid/1'); end\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('data=(%d,%d)\\ncoeffs=(%d,%d)\\n(%s,%s)', ...\r\n input_bit_width, bin_pt_in, coeff_bit_width, coeff_bit_width-1, quantization, overflow);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\nclog('exiting twiddle_general_init', 'trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "same_state.m", "ext": ".m", "path": "mlib_devel-master/casper_library/same_state.m", "size": 4645, "source_encoding": "utf_8", "md5": "418e3d4fb1b5e950970b0b1c7a7c592b", "text": "% Determines if a block's state matches the arguments.\n%\n% blk = The block to check\n% varargin = A cell array of things to compare.\n%\n% The compares the block's UserData parameter with the contents of\n% varargin. If they match, this function returns true. If they do not\n% match, this function returns false.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction match = same_state(blk,varargin)\n\n% Many mask initialization function call same_state early on to see whether the\n% block's state has changed since the last time it was initialized. Because\n% same_state is called so early in the initialization process, it is a good\n% place to check for illegitmately empty parameter values. Some empty\n% parameter values are legitimate, but an empty parameter value can also be\n% indicative of an exception that was silently ignored by the mask when\n% evaluating parameter strings. same_state now checks for empty parameter\n% values and thoroughly validates those that come from \"evaulated\" fields in\n% the mask.\n\n% Loop through all name/value pairs\nfor j = 1:length(varargin)/2\n param_value = varargin{2*j};\n % If this parameter value is empty\n if isempty(param_value)\n param_name = varargin{j*2-1};\n clog(sprintf('Checking empty value for parameter ''%s''...', param_name), ...\n 'same_state_debug');\n % If it is an evaluated parameter\n mask_vars = get_param(blk, 'MaskVariables');\n pattern = sprintf('(^|;)%s=@', param_name);\n if regexp(mask_vars, pattern)\n clog('...it is an evaluated parameter', 'same_state_debug');\n % Get its string value\n param_str = get_param(blk, param_name);\n % If its string value is not empty\n if ~isempty(param_str)\n clog(sprintf('...trying to evaluate its non-empty string: \"%s\"', ...\n param_str), 'same_state_debug');...\n try\n eval_val = eval_param(blk, param_name);\n clog('...its non-empty string eval''d OK', 'same_state_debug');\n % Raise exception if we did not also get an empty result\n if ~isempty(eval_val)\n link = sprintf('%s', ...\n blk, blk);\n ex = MException('casper:emptyMaskParamError', ...\n 'Parameter %s of %s is empty in same_state!', param_name, link);\n throw(ex);\n end\n catch ex\n % We really want to see this exception, even if its a duplicate of the\n % previous exception, so reset dump_exception before calling\n % dump_and_rethrow.\n dump_exception([]);\n dump_and_rethrow(ex);\n end % try/catch\n end % if non-empty param string\n end % if evaluated\n clog(sprintf('Empty value for parameter ''%s'' is OK.', param_name), ...\n 'same_state_debug');\n end % if empty\nend % name/value pair loop\n\n% Determine whether the state has changed\ntry\n match = getfield( get_param(blk,'UserData'), 'state') == hashcell(varargin);\ncatch\n match = 0;\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "coeff_gen_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/coeff_gen_init.m", "size": 28562, "source_encoding": "utf_8", "md5": "85557fc93abc4baed77457647b63dcb1", "text": "% coeff_gen_init(blk, varargin)\r\n%\r\n% blk = The block to configure\r\n% varargin = {'varname', 'value, ...} pairs\r\n%\r\n%\r\n%\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% SKA Africa %\r\n% http://www.kat.ac.za %\r\n% Copyright (C) 2009, 2013 Andrew Martens %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction coeff_gen_init(blk, varargin)\r\n \r\n clog('entering coeff_gen_init.m',{'trace', 'coeff_gen_init_debug'});\r\n FFTSize = 6;\r\n\r\n % Set default vararg values.\r\n % reg_retiming is not an actual parameter of this block, but it is included\r\n % in defaults so that same_state will return false for blocks drawn prior to\r\n % adding reg_retiming='on' to some of the underlying Delay blocks.\r\n defaults = { ...\r\n 'FFTSize', FFTSize, ...\r\n 'Coeffs', 4, ...%bit_rev([0:2^(FFTSize-1)-1],FFTSize-1), ...\r\n 'coeff_bit_width', 18, ...\r\n 'StepPeriod', 0, ...\r\n 'async', 'off', ...\r\n 'misc', 'off', ...\r\n 'bram_latency', 2, ...\r\n 'mult_latency', 2, ...\r\n 'add_latency', 1, ...\r\n 'conv_latency', 2, ...\r\n 'coeffs_bit_limit', 8, ...\r\n 'coeff_sharing', 'on', ...\r\n 'coeff_decimation', 'on', ...\r\n 'coeff_generation', 'on', ...\r\n 'cal_bits', 1, ...\r\n 'n_bits_rotation', 25, ...\r\n 'quantization', 'Round (unbiased: Even Values)', ...\r\n 'reg_retiming', 'on', ...\r\n };\r\n\r\n check_mask_type(blk, 'coeff_gen');\r\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\n clog('coeff_gen_init post same_state',{'trace', 'coeff_gen_init_debug'});\r\n munge_block(blk, varargin{:});\r\n\r\n FFTSize = get_var('FFTSize', 'defaults', defaults, varargin{:});\r\n Coeffs = get_var('Coeffs', 'defaults', defaults, varargin{:});\r\n coeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\r\n StepPeriod = get_var('StepPeriod', 'defaults', defaults, varargin{:});\r\n async = get_var('async', 'defaults', defaults, varargin{:});\r\n misc = get_var('misc', 'defaults', defaults, varargin{:});\r\n bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\n mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\n add_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\n conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\r\n coeffs_bit_limit = get_var('coeffs_bit_limit', 'defaults', defaults, varargin{:});\r\n coeff_sharing = get_var('coeff_sharing', 'defaults', defaults, varargin{:});\r\n coeff_decimation = get_var('coeff_decimation', 'defaults', defaults, varargin{:});\r\n coeff_generation = get_var('coeff_generation', 'defaults', defaults, varargin{:});\r\n cal_bits = get_var('cal_bits', 'defaults', defaults, varargin{:});\r\n n_bits_rotation = get_var('n_bits_rotation', 'defaults', defaults, varargin{:});\r\n quantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\n\r\n decimation_limit_bits = 6; %do not allow decimation below this many coefficients\r\n\r\n delete_lines(blk);\r\n\r\n %default case for library storage, do nothing\r\n if FFTSize == 0,\r\n clean_blocks(blk);\r\n set_param(blk, 'AttributesFormatString', '');\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting coeff_gen_init',{'coeff_gen_init_debug','trace'});\r\n return;\r\n end\r\n\r\n %%%%%%%%%\r\n % ports %\r\n %%%%%%%%%\r\n\r\n reuse_block(blk, 'rst', 'built-in/inport', 'Port', '1', 'Position', [25 48 55 62]);\r\n\r\n reuse_block(blk, 'ri_to_c', 'casper_library_misc/ri_to_c', 'Position', [395 54 435 96]);\r\n reuse_block(blk, 'w', 'built-in/outport', 'Port', '1', 'Position', [490 68 520 82]);\r\n add_line(blk, 'ri_to_c/1', 'w/1');\r\n\r\n port_offset = 1;\r\n if strcmp(async, 'on'),\r\n reuse_block(blk, 'en', 'built-in/inport', 'Port', '2', 'Position', [25 198 55 212]);\r\n reuse_block(blk, 'dvalid', 'built-in/outport', 'Port', '2', 'Position', [490 198 520 212]);\r\n\r\n port_offset = 2; \r\n end %if async\r\n\r\n if strcmp(misc, 'on'),\r\n reuse_block(blk, 'misci', 'built-in/inport', 'Port', num2str(port_offset+1), 'Position', [25 248 55 262]);\r\n reuse_block(blk, 'misco', 'built-in/outport', 'Port', num2str(port_offset+1), 'Position', [490 248 520 262]);\r\n end\r\n\r\n % Compute the complex, bit-reversed values of the twiddle factors\r\n br_indices = bit_rev(Coeffs, FFTSize-1);\r\n br_indices = -2*pi*1j*br_indices/2^FFTSize;\r\n ActualCoeffs = exp(br_indices);\r\n\r\n %static coefficients\r\n if length(ActualCoeffs) == 1,\r\n %terminator\r\n reuse_block(blk, 'Terminator', 'built-in/Terminator', 'Position', [75 45 95 65]);\r\n add_line(blk, 'rst/1', 'Terminator/1');\r\n\r\n %constant blocks\r\n real_coeff = round(real(ActualCoeffs(1)) * 2^(coeff_bit_width-2)) / 2^(coeff_bit_width-2);\r\n imag_coeff = round(imag(ActualCoeffs(1)) * 2^(coeff_bit_width-2)) / 2^(coeff_bit_width-2);\r\n reuse_block(blk, 'real', 'xbsIndex_r4/Constant', ...\r\n 'arith_type', 'Signed (2''s comp)', ...\r\n 'const', num2str(real_coeff), 'n_bits', num2str(coeff_bit_width), ...\r\n 'explicit_period', 'on', 'period', '1', ...\r\n 'bin_pt', num2str(coeff_bit_width-1), 'Position', [190 43 335 67]); \r\n add_line(blk, 'real/1', 'ri_to_c/1');\r\n reuse_block(blk, 'imaginary', 'xbsIndex_r4/Constant', ...\r\n 'arith_type', 'Signed (2''s comp)', ...\r\n 'const', num2str(imag_coeff), 'n_bits', num2str(coeff_bit_width), ...\r\n 'explicit_period', 'on', 'period', '1', ...\r\n 'bin_pt', num2str(coeff_bit_width-1), 'Position', [190 83 335 107]); \r\n add_line(blk, 'imaginary/1', 'ri_to_c/2');\r\n \r\n if strcmp(misc, 'on'), add_line(blk, 'misci/1', 'misco/1'); end\r\n if strcmp(async, 'on'), add_line(blk, 'en/1', 'dvalid/1'); end\r\n\r\n else,\r\n vlen = length(ActualCoeffs);\r\n\r\n % Get FPGA part from System Generator block\r\n fpga = 'xc5v';\r\n try\r\n xsg_blk = find_system(bdroot(blk), 'SearchDepth', 2, ...\r\n 'MaskType','Xilinx System Generator Block');\r\n fpga = get_param(xsg_blk{1},'part');\r\n catch,\r\n clog('Could not find FPGA part name - is there a System Generator block in this model? Defaulting FPGA to Virtex5.', {'coeff_gen_init_debug'});\r\n warning('coeff_gen_init: Could not find FPGA part name - is there a System Generator block in this model? Defaulting FPGA to Virtex5.');\r\n end %try/catch\r\n\r\n %parameters to decide optimisation parameters\r\n switch fpga(1:4)\r\n case 'xc6v'\r\n port_width = 36; %upper limit\r\n bram_capacity = 2^9*36;\r\n otherwise % including 'xc5v'\r\n port_width = 36; %upper limit\r\n bram_capacity = 2^9*36;\r\n end %switch\r\n\r\n %could we pack the whole word to output from one port\r\n if (coeff_bit_width * 2) <= port_width, can_pack = 1;\r\n else, can_pack = 0;\r\n end\r\n\r\n %work out fraction of BRAM for all coefficients\r\n coeffs_volume = length(Coeffs) * 2 * coeff_bit_width;\r\n n_brams = coeffs_volume/bram_capacity;\r\n \r\n clog(['Coeffs = ',mat2str(Coeffs)], 'coeff_gen_init_desperate_debug');\r\n % check to see if we can generate by bit reversing a counter\r\n inorder = 1;\r\n for i = 2:length(Coeffs)-2,\r\n if ~((Coeffs(i+1)-Coeffs(i)) == (Coeffs(i)-Coeffs(i-1))), inorder = 0; break; \r\n end \r\n end %for\r\n\r\n %if not in order, check if we can generate by undoing bit reversal\r\n if inorder == 0,\r\n clog(['bit_rev(Coeffs,FFTSize-1) = ',mat2str(bit_rev(Coeffs,FFTSize-1))], 'coeff_gen_init_desperate_debug');\r\n bit_reversed = 1;\r\n for i = 2:length(Coeffs)-2, \r\n if ~((bit_rev(Coeffs(i+1), FFTSize-1) - bit_rev(Coeffs(i), FFTSize-1)) == (bit_rev(Coeffs(i), FFTSize-1) - bit_rev(Coeffs(i-1), FFTSize-1))), bit_reversed = 0; break; \r\n end \r\n end %for\r\n else\r\n bit_reversed = 0;\r\n end %if\r\n\r\n %determine fraction of cycle phase offset and increment\r\n if inorder == 0, \r\n phase_offset = bit_rev(Coeffs(1), FFTSize-1); phase_step = bit_rev(Coeffs(2), FFTSize-1) - bit_rev(Coeffs(1), FFTSize-1);\r\n else, \r\n phase_offset = Coeffs(1); phase_step = Coeffs(2) - Coeffs(1);\r\n end\r\n phase_offset_fraction = phase_offset/(2^(FFTSize-StepPeriod));\r\n phase_multiple = phase_offset/length(Coeffs);\r\n \r\n %what fraction of the cycle is required\r\n if inorder == 0, \r\n top = bit_rev(Coeffs(length(Coeffs)), FFTSize-1);\r\n bottom = bit_rev(Coeffs(1), FFTSize-1);\r\n else\r\n top = Coeffs(length(Coeffs));\r\n bottom = Coeffs(1);\r\n end\r\n\r\n multiple = (2^(FFTSize-StepPeriod))/((top+phase_step)-bottom);\r\n multiple_bits = log2(multiple);\r\n step_bits = multiple_bits+log2(length(Coeffs));\r\n\r\n clog(['Need ',num2str(n_brams),' BRAM/s for all coefficients'], 'coeff_gen_init_debug');\r\n clog(['Can pack into same port : ',num2str(can_pack)], 'coeff_gen_init_debug');\r\n clog(['In order : ',num2str(inorder)],'coeff_gen_init_debug');\r\n clog(['Bit reversed : ',num2str(bit_reversed)],'coeff_gen_init_debug');\r\n clog(['Fraction of cycle to output : 1/2^',num2str(multiple_bits)],'coeff_gen_init_debug');\r\n clog(['Step size : 1/2^',num2str(step_bits)],'coeff_gen_init_debug');\r\n clog(['Phase offset : ',num2str(phase_offset),' = ',num2str(phase_multiple),' * output cycle fraction'],'coeff_gen_init_debug');\r\n\r\n %\r\n % sanity checks\r\n %if small number of points, don't generate even if we want to \r\n if strcmp(coeff_generation, 'on') && (bit_reversed == 1) && (log2(vlen) <= ceil(log2(mult_latency+add_latency+conv_latency+1)) + cal_bits),\r\n clog(['Forcing lookup of coefficients for small number of values relative to latencies'], {'coeff_gen_init_debug'});\r\n warning(['Forcing lookup of coefficients for small number of values relative to latencies']);\r\n coeff_generation = 'off';\r\n end\r\n\r\n %if in order, then must have phase offset of 0\r\n if inorder == 1 && phase_offset ~= 0,\r\n clog(['In order coefficients not starting at 0 not handled'], {'error', 'coeff_gen_init_debug'});\r\n error(['In order coefficients not starting at 0 not handled']);\r\n return;\r\n end\r\n\r\n %initial phase must be an exact multiple of the number of coefficients\r\n if floor(phase_multiple) ~= phase_multiple,\r\n clog(['initial phase offset must be an exact multiple of the number of coefficients'], {'error', 'coeff_gen_init_debug'});\r\n error(['initial phase offset must be an exact multiple of the number of coefficients']);\r\n return;\r\n end\r\n\r\n %if we don't have a power of two fraction of a cycle then we have a problem\r\n if multiple_bits ~= floor(log2(multiple)), \r\n clog(['The FFT size must be a power-of-two-multiple of the number of coefficients '], {'error', 'coeff_gen_init_debug'});\r\n error(['The FFT size must be a power-of-two-multiple of the number of coefficients ']);\r\n return;\r\n end\r\n\r\n %coefficients must be in order or bit reversed\r\n if (inorder == 0) && (bit_reversed == 0),\r\n clog(['we don''t know how to generate coefficients that are not in order nor bit reversed'], {'error','coeff_gen_init_debug'});\r\n error(['we don''t know how to generate coefficients that are not in order nor bit reversed']);\r\n return;\r\n end\r\n\r\n %If the coefficients to be generated are in order then we can generate them by \r\n %bit reversing the output of a counter and performing a lookup on these values\r\n %\r\n %If the coefficients are bit reversed then we can generate them by taking the output of a \r\n %counter and getting the lookup directly. We can also generate the values as the next\r\n %value is just the current value rotated by a particular angle.\r\n %\r\n %An initial coefficient not being 0 can be compensated for by starting the counter with a \r\n %non-zero offset. Similarly for final value\r\n %\r\n %When generating coefficients by phase rotation with a StepPeriod ~= 2^0, we must use a\r\n %counter and control using the en port on the oscillator\r\n\r\n %if not allowed to generate or coeffs in order (bit reversed when being looked up) then store in lookup and use counter\r\n if (inorder == 1) || strcmp(coeff_generation, 'off'),\r\n \r\n table_bits = log2(length(Coeffs)); \r\n\r\n %\r\n % work out optimal output functions depending on phase offset\r\n output_ref = {'cos', '-sin', '-cos', 'sin'}; \r\n output_ref_index = floor(phase_offset_fraction/(1/4));\r\n output0 = output_ref{output_ref_index+1};\r\n output1 = output_ref{mod(output_ref_index+1,4)+1};\r\n\r\n %\r\n % adjust initial phase to use new reference point\r\n phase_offset = phase_offset_fraction - output_ref_index*(1/4); \r\n \r\n %can coefficients be derived from each other and themselves\r\n if (phase_offset == 0) && (multiple_bits <= 2), derivable = 1;\r\n else, derivable = 0;\r\n end\r\n\r\n %n_brams = coeffs_volume/bram_capacity\r\n\r\n %\r\n % determine whether to derive coefficients from each other or pack both\r\n \r\n % share coefficients if can be derived from each other and allowed\r\n % NOTE: we may decide to pack later as well if using single BRAM and can pack into output ports\r\n if (derivable == 1) && strcmp(coeff_sharing, 'on'), \r\n pack = 'off';\r\n coeffs_volume = coeffs_volume/2;\r\n else, \r\n pack = 'on';\r\n end\r\n\r\n %n_brams = coeffs_volume/bram_capacity\r\n\r\n %\r\n % calculate what fraction of cycle we are going to store\r\n \r\n % if can be derived and allowed to decimate and above limit where allowed to decimate\r\n % NOTE: we may decide to decimate by less later if we can fit a larger portion into a BRAM\r\n if (derivable == 1) && strcmp(coeff_decimation, 'on') && (table_bits > decimation_limit_bits), \r\n store = 2; %decimate to the max\r\n coeffs_volume = coeffs_volume/(2^(store-multiple_bits));\r\n n_brams = coeffs_volume/bram_capacity;\r\n else, \r\n store = multiple_bits; %do not decimate\r\n end\r\n\r\n %\r\n % determine if we need to store coefficients in BRAM\r\n \r\n if coeffs_volume > 2^coeffs_bit_limit, coeffs_bram = 'on';\r\n else, coeffs_bram = 'off';\r\n end\r\n\r\n %\r\n % relook at fraction stored if using BRAM\r\n % store a larger fraction of coefficients if not wasting BRAMs\r\n % will reduce error as well as logic (large adder) to make address go backwards\r\n if strcmp(coeffs_bram, 'on') && (derivable == 1) && strcmp(coeff_decimation, 'on') && (n_brams < 1),\r\n if n_brams <= 1/4, new_store = multiple_bits; %store up to a full cycle\r\n elseif n_brams <= 1/2, new_store = max(1,multiple_bits); %store up to half a cycle\r\n else new_store = 2; %store a quarter of a cycle\r\n end\r\n\r\n coeffs_volume = coeffs_volume * 2^(store-new_store); \r\n n_brams = n_brams * 2^(store-new_store);\r\n store = new_store;\r\n end \r\n\r\n %\r\n % relook at packing if using BRAM\r\n % if we can output both from a single port and occupy less than a BRAM with both\r\n % i.e if we store both sets and can output through same port, then reduce address logic\r\n if strcmp(pack, 'off') && strcmp(coeffs_bram, 'on') && ((can_pack == 1) && (n_brams <= 1/2)), \r\n pack = 'on';\r\n coeffs_volume = coeffs_volume * 2;\r\n n_brams = n_brams*2;\r\n end\r\n\r\n if strcmp(coeffs_bram, 'on'), bram = 'BRAM';\r\n else bram = 'distributed RAM';\r\n end\r\n\r\n if strcmp(misc, 'on') || strcmp(async, 'on'), cosin_misc = 'on';\r\n else, cosin_misc = 'off';\r\n end\r\n\r\n clog(['adding cosin block to ',blk], 'coeff_gen_init_debug');\r\n clog(['output0 = ',output0], 'coeff_gen_init_debug');\r\n clog(['output1 = ',output1], 'coeff_gen_init_debug');\r\n clog(['initial phase offset ',num2str(phase_offset)], 'coeff_gen_init_debug');\r\n clog(['outputting 2^',num2str(table_bits),' points across 1/2^',num2str(multiple_bits),' of a cycle'], 'coeff_gen_init_debug');\r\n clog(['storing 1/2^',num2str(store),' of a cycle in ',num2str(n_brams),' ',bram,'/s'], 'coeff_gen_init_debug');\r\n if strcmp(pack, 'on') clog(['packing coefficients'], 'coeff_gen_init_debug'); \r\n end\r\n if strcmp(pack, 'off') clog(['not packing coefficients'], 'coeff_gen_init_debug'); \r\n end\r\n\r\n reuse_block(blk, 'Counter', 'xbsIndex_r4/Counter', ...\r\n 'cnt_type', 'Free Running', 'start_count', '0', 'cnt_by_val', '1', ...\r\n 'arith_type', 'Unsigned', 'n_bits', num2str(log2(vlen)+StepPeriod), ...\r\n 'use_behavioral_HDL', 'on', 'bin_pt', '0', 'rst', 'on', 'en', async, ...\r\n 'Position', [75 29 125 81]);\r\n add_line(blk, 'rst/1', 'Counter/1');\r\n\r\n if strcmp(async, 'on'), add_line(blk, 'en/1', 'Counter/2');\r\n end\r\n\r\n reuse_block(blk, 'Slice', 'xbsIndex_r4/Slice', ...\r\n 'nbits', num2str(log2(vlen)), ...\r\n 'mode', 'Upper Bit Location + Width', ...\r\n 'bit1', '0', 'base1', 'MSB of Input', ...\r\n 'Position', [145 41 190 69]);\r\n add_line(blk, 'Counter/1', 'Slice/1');\r\n\r\n if (strcmp(async, 'on') && strcmp(misc, 'on')),\r\n reuse_block(blk, 'Concat', 'xbsIndex_r4/Concat', 'num_inputs', '2', 'Position', [90 182 115 278]);\r\n \r\n add_line(blk, 'en/1', 'Concat/1');\r\n add_line(blk, 'misci/1', 'Concat/2');\r\n end\r\n \r\n if inorder == 1, \r\n %bit reverse block\r\n reuse_block(blk, 'bit_reverse', 'casper_library_misc/bit_reverse', ...\r\n 'n_bits', num2str(log2(vlen)), ...\r\n 'Position', [205 44 260 66]);\r\n add_line(blk, 'Slice/1', 'bit_reverse/1');\r\n end\r\n\r\n %cosin block\r\n reuse_block(blk, 'cosin', 'casper_library_downconverter/cosin', ...\r\n 'output0', output0, 'output1', output1, ...\r\n 'phase', num2str(phase_offset), ...\r\n 'fraction', num2str(multiple_bits), ...\r\n 'table_bits', num2str(table_bits), ...\r\n 'n_bits', num2str(coeff_bit_width), 'bin_pt', num2str(coeff_bit_width-1), ...\r\n 'bram_latency', num2str(bram_latency), 'add_latency', '1', ...\r\n 'mux_latency', '2', 'neg_latency', '1', 'conv_latency', '2', ...\r\n 'store', num2str(store), 'pack', pack, 'bram', bram, 'misc', cosin_misc, ...\r\n 'Position', [280 23 345 147]);\r\n\r\n if inorder == 1, add_line(blk, 'bit_reverse/1', 'cosin/1');\r\n else, add_line(blk, 'Slice/1', 'cosin/1');\r\n end\r\n\r\n add_line(blk, 'cosin/1', 'ri_to_c/1');\r\n add_line(blk, 'cosin/2', 'ri_to_c/2');\r\n\r\n if strcmp(async, 'on') && strcmp(misc, 'on'), \r\n add_line(blk, 'Concat/1', 'cosin/2');\r\n\r\n %separate data valid from misco\r\n reuse_block(blk, 'Slice1', 'xbsIndex_r4/Slice', ...\r\n 'nbits', '1', ...\r\n 'mode', 'Upper Bit Location + Width', ...\r\n 'bit1', '0', 'base1', 'MSB of Input', ...\r\n 'Position', [395 191 440 219]);\r\n add_line(blk, 'cosin/3', 'Slice1/1');\r\n add_line(blk, 'Slice1/1', 'dvalid/1');\r\n\r\n reuse_block(blk, 'Slice2', 'xbsIndex_r4/Slice', ...\r\n 'mode', 'Two Bit Locations', ...\r\n 'bit1', '-1', 'base1', 'MSB of Input', ...\r\n 'bit0', '0', 'base0', 'LSB of Input', ...\r\n 'Position', [395 241 440 269]);\r\n add_line(blk, 'cosin/3', 'Slice2/1');\r\n add_line(blk, 'Slice2/1', 'misco/1');\r\n\r\n elseif strcmp(async, 'on') && strcmp(misc, 'off'),\r\n add_line(blk, 'en/1', 'cosin/2');\r\n add_line(blk, 'cosin/3', 'dvalid/1');\r\n elseif strcmp(async, 'off') && strcmp(misc, 'on'),\r\n add_line(blk, 'misci/1', 'cosin/2');\r\n add_line(blk, 'cosin/3', 'misco/1');\r\n end \r\n \r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \r\n % if coefficient indices are bit_reversed (values in order) and allowed to generate %\r\n % then generate using feedback oscillator using multipliers %\r\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n elseif ((bit_reversed == 1) && strcmp(coeff_generation,'on')),\r\n \r\n %concat enable and misc inputs \r\n if (strcmp(async, 'on') && strcmp(misc, 'on')),\r\n reuse_block(blk, 'Concat', 'xbsIndex_r4/Concat', 'num_inputs', '2', 'Position', [90 182 115 278]);\r\n \r\n add_line(blk, 'en/1', 'Concat/1');\r\n add_line(blk, 'misci/1', 'Concat/2');\r\n end\r\n\r\n %derived from feedback_osc_init\r\n pipeline_delay_bits = ceil(log2(mult_latency+add_latency+conv_latency+1)); \r\n \r\n coeffs_volume = (2^(pipeline_delay_bits+cal_bits)) * coeff_bit_width * 2;\r\n if coeffs_volume > 2^coeffs_bit_limit, coeffs_bram = 'on'; \r\n else, coeffs_bram = 'off';\r\n end\r\n \r\n clog(['pipeline required based on latencies = ',num2str(2^pipeline_delay_bits)],'coeff_gen_init_desperate_debug');\r\n clog(['calibration points = ',num2str(2^cal_bits)],'coeff_gen_init_desperate_debug');\r\n clog(['total coeffs volume = ',num2str(coeffs_volume),' bits'],'coeff_gen_init_desperate_debug');\r\n clog(['coeffs limit = ',num2str(2^coeffs_bit_limit),' bits'],'coeff_gen_init_desperate_debug');\r\n\r\n if strcmp(coeffs_bram, 'on'), bram = 'Block RAM';\r\n else bram = 'Distributed memory';\r\n end\r\n\r\n %if we have to use a Block RAM, then increase the number of calibration points to the maximum supported\r\n %TODO\r\n\r\n phase_step_bits = step_bits;\r\n phase_steps_bits = log2(length(Coeffs));\r\n\r\n clog(['adding feedback oscillator block to ',blk], 'coeff_gen_init_debug');\r\n clog(['initial phase is ',num2str(phase_offset_fraction),' * 2*pi stored in ',bram], 'coeff_gen_init_debug');\r\n clog(['outputting 2^',num2str(phase_steps_bits),' steps of size 1/2^',num2str(phase_step_bits),' of a cycle'], 'coeff_gen_init_debug');\r\n\r\n %feedback oscillator\r\n reuse_block(blk, 'feedback_osc', 'casper_library_downconverter/feedback_osc', ...\r\n 'n_bits', 'coeff_bit_width', ... \r\n 'n_bits_rotation', 'n_bits_rotation', ... \r\n 'phase_initial', num2str(phase_offset_fraction), ...\r\n 'phase_step_bits', num2str(phase_step_bits), ...\r\n 'phase_steps_bits', num2str(phase_steps_bits), ...\r\n 'ref_values_bits', num2str(cal_bits), ...\r\n 'bram_latency', num2str(bram_latency), ...\r\n 'mult_latency', num2str(mult_latency), ... \r\n 'add_latency', num2str(add_latency), ... \r\n 'conv_latency', num2str(conv_latency), ... \r\n 'bram', bram, ...\r\n 'quantization', quantization, ... \r\n 'Position', [280 23 345 147]);\r\n\r\n %generate counter to slow enable if required\r\n if StepPeriod ~= 0,\r\n reuse_block(blk, 'counter', 'xbsIndex_r4/Counter', ...\r\n 'cnt_type', 'Free Running', 'start_count', '0', 'cnt_by_val', '1', ...\r\n 'arith_type', 'Unsigned', 'n_bits', num2str(StepPeriod), ...\r\n 'implentation', 'Fabric', 'use_behavioral_HDL', 'off', ...\r\n 'bin_pt', '0', 'rst', 'on', 'en', async, 'Position', [80 45 120 85]);\r\n add_line(blk, 'rst/1', 'counter/1');\r\n\r\n if strcmp(async, 'on'), add_line(blk, 'en/1', 'counter/2');\r\n end\r\n\r\n reuse_block(blk, 'relational', 'xbsIndex_r4/Relational', ...\r\n 'mode', 'a=b', 'latency', '0', 'Position', [225 56 255 134]);\r\n add_line(blk, 'relational/1', 'feedback_osc/2');\r\n\r\n if strcmp(async, 'on'),\r\n reuse_block(blk, 'concat1', 'xbsIndex_r4/Concat', ...\r\n 'num_inputs', '2', 'Position', [155 55 185 90]);\r\n add_line(blk, 'counter/1', 'concat1/1');\r\n add_line(blk, 'en/1', 'concat1/2');\r\n add_line(blk, 'concat1/1', 'relational/1');\r\n len = 'StepPeriod+1';\r\n else\r\n add_line(blk, 'counter/1','relational/1');\r\n len = 'StepPeriod'; \r\n end\r\n reuse_block(blk, 'constant', 'xbsIndex_r4/Constant', ...\r\n 'const', ['(2^(',len,'))-1'], 'arith_type', 'Unsigned', ...\r\n 'n_bits', len, 'bin_pt', '0', ...\r\n 'Position', [145 102 200 128]);\r\n add_line(blk, 'constant/1', 'relational/2');\r\n\r\n else, \r\n if strcmp(async, 'off'), %if StepPeriod 0 but no enable, then create constant to enable always\r\n reuse_block(blk, 'en', 'xbsIndex_r4/Constant', ...\r\n 'arith_type', 'Boolean', 'const', '1', 'explicit_period', 'on', 'period', '1', ...\r\n 'Position', [205 44 260 66]);\r\n end \r\n\r\n add_line(blk, 'en/1', 'feedback_osc/2'); \r\n end %if StepPeriod ~= 0\r\n\r\n add_line(blk, 'rst/1', 'feedback_osc/1', 'autorouting', 'on'); \r\n\r\n reuse_block(blk, 't0', 'built-in/Terminator', 'Position', [370 25 390 45]);\r\n add_line(blk, 'feedback_osc/1', 't0/1');\r\n reuse_block(blk, 't1', 'built-in/Terminator', 'Position', [370 100 390 120]);\r\n add_line(blk, 'feedback_osc/4', 't1/1');\r\n\r\n add_line(blk, 'feedback_osc/2', 'ri_to_c/1');\r\n add_line(blk, 'feedback_osc/3', 'ri_to_c/2');\r\n\r\n if strcmp(async, 'on') && strcmp(misc, 'on'), \r\n add_line(blk, 'Concat/1', 'feedback_osc/3');\r\n\r\n %separate data valid from misco\r\n reuse_block(blk, 'Slice1', 'xbsIndex_r4/Slice', ...\r\n 'nbits', '1', ...\r\n 'mode', 'Upper Bit Location + Width', ...\r\n 'bit1', '0', 'base1', 'MSB of Input', ...\r\n 'Position', [395 191 440 219]);\r\n add_line(blk, 'feedback_osc/5', 'Slice1/1');\r\n add_line(blk, 'Slice1/1', 'dvalid/1');\r\n\r\n reuse_block(blk, 'Slice2', 'xbsIndex_r4/Slice', ...\r\n 'mode', 'Two Bit Locations', ...\r\n 'bit1', '-1', 'base1', 'MSB of Input', ...\r\n 'bit0', '0', 'base0', 'LSB of Input', ...\r\n 'Position', [395 241 440 269]);\r\n add_line(blk, 'feedback_osc/5', 'Slice2/1');\r\n add_line(blk, 'Slice2/1', 'misco/1');\r\n\r\n elseif strcmp(async, 'on') && strcmp(misc, 'off'),\r\n add_line(blk, 'en/1', 'feedback_osc/3');\r\n add_line(blk, 'feedback_osc/5', 'dvalid/1');\r\n elseif strcmp(async, 'off') && strcmp(misc, 'on'),\r\n add_line(blk, 'misci/1', 'feedback_osc/3');\r\n add_line(blk, 'feedback_osc/5', 'misco/1');\r\n else\r\n add_line(blk, 'rst/1', 'feedback_osc/3', 'autorouting', 'on');\r\n reuse_block(blk, 't2', 'built-in/Terminator', 'Position', [370 125 390 145]);\r\n add_line(blk, 'feedback_osc/5', 't2/1');\r\n end \r\n\r\n else,\r\n error('Bad news, this state should not be reached'); \r\n %TODO\r\n end %if inorder\r\n end %if length(ActualCoeffs)\r\n\r\n clean_blocks(blk);\r\n\r\n fmtstr = sprintf('%d @ (%d,%d)', length(ActualCoeffs), coeff_bit_width, coeff_bit_width-1);\r\n set_param(blk, 'AttributesFormatString', fmtstr);\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting coeff_gen_init',{'trace', 'coeff_gen_init_debug'});\r\n\r\nend %coeff_gen_init\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bitsnap_callback.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bitsnap_callback.m", "size": 3198, "source_encoding": "utf_8", "md5": "680d04a1deb9d1c412fee10711f367bb", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Meerkat radio telescope project %\n% www.kat.ac.za %\n% Copyright (C) Andrew Martens 2011 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bitsnap_callback()\n\nclog('entering bitsnap_callback', 'trace');\nblk = gcb;\ncheck_mask_type(blk, 'bitsnap');\n\nmask_names = get_param(blk, 'MaskNames');\nmask_enables = get_param(blk, 'MaskEnables');\nmask_visibilities = get_param(blk, 'MaskVisibilities');\n\nstorage = get_param(blk, 'snap_storage');\nif strcmp(storage, 'bram'),\n mask_visibilities{ismember(mask_names, 'snap_dram_dimm')} = 'off';\n mask_visibilities{ismember(mask_names, 'snap_dram_clock')} = 'off';\n mask_enables{ismember(mask_names, 'snap_data_width')} = 'on';\nelseif strcmp(storage, 'dram'),\n mask_visibilities{ismember(mask_names, 'snap_dram_dimm')} = 'on';\n mask_visibilities{ismember(mask_names, 'snap_dram_clock')} = 'on';\n set_param(blk, 'snap_data_width', '64');\n mask_enables{ismember(mask_names, 'snap_data_width')} = 'off';\nend\n\nif strcmp(get_param(blk,'snap_value'), 'on'),\n mask_enables{ismember(mask_names, 'extra_names')} = 'on';\n mask_enables{ismember(mask_names, 'extra_widths')} = 'on';\n mask_enables{ismember(mask_names, 'extra_bps')} = 'on';\n mask_enables{ismember(mask_names, 'extra_types')} = 'on';\nelse\n mask_enables{ismember(mask_names, 'extra_names')} = 'off';\n mask_enables{ismember(mask_names, 'extra_widths')} = 'off';\n mask_enables{ismember(mask_names, 'extra_bps')} = 'off';\n mask_enables{ismember(mask_names, 'extra_types')} = 'off';\nend\n\nset_param(gcb, 'MaskEnables', mask_enables);\nset_param(gcb, 'MaskVisibilities', mask_visibilities);\n\nclog('exiting bitsnap_callback', 'trace');\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fir_col_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fir_col_init.m", "size": 7197, "source_encoding": "utf_8", "md5": "fb82de9a6c3f4e202a20478cef68e0fc", "text": "% fir_col_init(blk, varargin)\r\n%\r\n% blk = The block to initialize.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% n_inputs = The number of parallel input samples.\r\n% coeff = The FIR coefficients, top-to-bottom.\r\n% add_latency = The latency of adders.\r\n% mult_latency = The latency of multipliers.\r\n% coeff_bit_width = The number of bits used for coefficients\r\n% coeff_bin_pt = The number of fractional bits in the coefficients\r\n% first_stage_hdl = Whether to implement the first stage in adder trees\r\n% as behavioral HDL so that adders are absorbed into DSP slices used for\r\n% multipliers where this is possible.\r\n% adder_imp = adder implementation (Fabric, behavioral HDL, DSP48)\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction fir_col_init(blk,varargin)\r\n\r\nclog('entering fir_col_init', 'trace');\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {'n_inputs', 1, 'coeff', 0.1, 'add_latency', 2, 'mult_latency', 3, ...\r\n 'coeff_bit_width', 25, 'coeff_bin_pt', 24, ...\r\n 'first_stage_hdl', 'off', 'adder_imp', 'Fabric'};\r\n\r\ncheck_mask_type(blk, 'fir_col');\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('fir_col_init post same_state', 'trace');\r\nmunge_block(blk, varargin{:});\r\nn_inputs = get_var('n_inputs','defaults', defaults, varargin{:});\r\ncoeff = get_var('coeff','defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency','defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency','defaults', defaults, varargin{:});\r\ncoeff_bit_width = get_var('coeff_bit_width','defaults', defaults, varargin{:});\r\ncoeff_bin_pt = get_var('coeff_bin_pt','defaults', defaults, varargin{:});\r\nfirst_stage_hdl = get_var('first_stage_hdl','defaults', defaults, varargin{:});\r\nadder_imp = get_var('adder_imp','defaults', defaults, varargin{:});\r\n\r\ndelete_lines(blk);\r\n\r\n%default library state\r\nif n_inputs == 0,\r\n clean_blocks(blk);\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting fir_col_init', 'trace');\r\n return;\r\nend\r\n\r\nif length(coeff) ~= n_inputs,\r\n clog('number of coefficients must be the same as the number of inputs', {'fir_col_init_debug', 'error'});\r\n error('number of coefficients must be the same as the number of inputs');\r\nend\r\n\r\nfor i=1:n_inputs,\r\n reuse_block(blk, ['real',num2str(i)], 'built-in/inport', 'Position', [30 i*80 60 15+80*i]);\r\n reuse_block(blk, ['imag',num2str(i)], 'built-in/inport', 'Position', [30 i*80+30 60 45+80*i]);\r\n reuse_block(blk, ['fir_tap',num2str(i)], 'casper_library_downconverter/fir_tap', ...\r\n 'Position', [180 i*160-70 230 50+160*i], 'latency', num2str(mult_latency), ...\r\n 'factor',num2str(coeff(i)), 'coeff_bit_width', num2str(coeff_bit_width), ...\r\n\t'coeff_bin_pt', num2str(coeff_bin_pt));\r\n reuse_block(blk, ['real_out',num2str(i)], 'built-in/outport', 'Position', [350 i*80 380 15+80*i], 'Port', num2str(2*i-1));\r\n reuse_block(blk, ['imag_out',num2str(i)], 'built-in/outport', 'Position', [350 i*80+30 380 45+80*i], 'Port', num2str(2*i));\r\nend\r\n\r\nreuse_block(blk, 'real_sum', 'built-in/outport', 'Position', [600 10+20*n_inputs 630 30+20*n_inputs], 'Port', num2str(2*n_inputs+1));\r\nreuse_block(blk, 'imag_sum', 'built-in/outport', 'Position', [600 110+20*n_inputs 630 130+20*n_inputs], 'Port', num2str(2*n_inputs+2));\r\n\r\nif n_inputs > 1,\r\n reuse_block(blk, 'adder_tree1', 'casper_library_misc/adder_tree', ...\r\n 'Position', [500 100 550 100+20*n_inputs], 'n_inputs', num2str(n_inputs),...\r\n 'latency', num2str(add_latency), 'first_stage_hdl', first_stage_hdl, 'adder_imp', adder_imp);\r\n reuse_block(blk, 'adder_tree2', 'casper_library_misc/adder_tree', ...\r\n 'Position', [500 200+20*n_inputs 550 200+20*n_inputs+20*n_inputs], 'n_inputs', num2str(n_inputs),...\r\n 'latency', num2str(add_latency), 'first_stage_hdl', first_stage_hdl, 'adder_imp', adder_imp);\r\n reuse_block(blk, 'c1', 'xbsIndex_r4/Constant', ...\r\n 'explicit_period', 'on', 'Position', [450 100 480 110]);\r\n reuse_block(blk, 'c2', 'xbsIndex_r4/Constant', ...\r\n 'explicit_period', 'on', 'Position', [450 200+20*n_inputs 480 210+20*n_inputs]);\r\n reuse_block(blk, 'term1','built-in/Terminator', 'Position', [600 100 615 115]);\t\r\n add_line(blk, 'adder_tree1/1', 'term1/1');\r\n reuse_block(blk, 'term2','built-in/Terminator', 'Position', [600 200+20*n_inputs 615 215+20*n_inputs]);\t\r\n add_line(blk, 'adder_tree2/1', 'term2/1');\r\n\r\n add_line(blk, 'c1/1', 'adder_tree1/1');\r\n add_line(blk, 'c2/1', 'adder_tree2/1');\r\n add_line(blk,'adder_tree1/2','real_sum/1');\r\n add_line(blk,'adder_tree2/2','imag_sum/1');\r\nend\r\n\r\nfor i=1:n_inputs,\r\n add_line(blk,['real',num2str(i),'/1'],['fir_tap',num2str(i),'/1']);\r\n add_line(blk,['imag',num2str(i),'/1'],['fir_tap',num2str(i),'/2']);\r\n add_line(blk,['fir_tap',num2str(i),'/1'],['real_out',num2str(i),'/1']);\r\n add_line(blk,['fir_tap',num2str(i),'/2'],['imag_out',num2str(i),'/1']);\r\n if n_inputs > 1\r\n add_line(blk,['fir_tap',num2str(i),'/3'],['adder_tree1/',num2str(i+1)]);\r\n add_line(blk,['fir_tap',num2str(i),'/4'],['adder_tree2/',num2str(i+1)]);\r\n else\r\n add_line(blk,['fir_tap',num2str(i),'/3'],['real_sum/1']);\r\n add_line(blk,['fir_tap',num2str(i),'/4'],['imag_sum/1']);\r\n end\r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\nclog('exiting fir_col_init', 'trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "simple_bram_vacc_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/simple_bram_vacc_init.m", "size": 2999, "source_encoding": "utf_8", "md5": "8f8e87fb49dd1595118ad9a02258af3e", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://casper.berkeley.edu %\n% Copyright (C)2010 Billy Mallard %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction simple_bram_vacc_init(blk, varargin)\n% Initialize and configure a simple_bram_vacc block.\n%\n% simple_bram_vacc_init(blk, varargin)\n%\n% blk = The block to configure.\n% varargin = {'varname', 'value', ...} pairs.\n%\n% Valid varnames for this block are:\n% vec_len = \n% arith_type = \n% n_bits = \n% bin_pt = \n\n% Declare any default values for arguments you might like.\ndefaults = {};\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\ncheck_mask_type(blk, 'simple_bram_vacc');\nmunge_block(blk, varargin{:});\n\nvec_len = get_var('vec_len', 'defaults', defaults, varargin{:});\narith_type = get_var('arith_type', 'defaults', defaults, varargin{:});\nn_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\nbin_pt = get_var('bin_pt', 'defaults', defaults, varargin{:});\n\n% Validate input fields.\n\nif vec_len < 6\n\terrordlg('simple_bram_vacc: Invalid vector length. Must be greater than 5.')\nend\n\nif n_bits < 1\n\terrordlg('simple_bram_vacc: Invalid bit width. Must be greater than 0.')\nend\n\nif bin_pt > n_bits\n\terrordlg('simple_bram_vacc: Invalid binary point. Cannot be greater than the bit width.')\nend\n\n% Adjust sub-block parameters.\n\nset_param([blk, '/Constant'], 'arith_type', arith_type)\nset_param([blk, '/Adder'], 'arith_type', arith_type)\n\nsave_state(blk, 'defaults', defaults, varargin{:});\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "cross_multiplier_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/cross_multiplier_init.m", "size": 11071, "source_encoding": "utf_8", "md5": "0bdb1cd084e68bc458335523ffe226de", "text": "% cross_multiplier_init(blk, varargin)\r\n%\r\n% Used in refactor block \r\n%\r\n% blk = The block to configure\r\n% varargin = {'varname', 'value, ...} pairs\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Karoo Array Telesope %\r\n% http://www.kat.ac.za %\r\n% Copyright (C) 2009 Andrew Martens %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction refactor_storage_init(blk, varargin)\r\n\r\ndefaults = {};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'cross_multiplier');\r\nmunge_block(blk, varargin{:});\r\ndelete_lines(blk);\r\n\r\nstreams = get_var('streams', 'defaults', defaults, varargin{:});\r\naggregation = get_var('aggregation', 'defaults', defaults, varargin{:});\r\nbit_width_in = get_var('bit_width_in', 'defaults', defaults, varargin{:});\r\nbinary_point_in = get_var('binary_point_in', 'defaults', defaults, varargin{:});\r\nbit_width_out = get_var('bit_width_out', 'defaults', defaults, varargin{:});\r\nbinary_point_out = get_var('binary_point_out', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\noverflow = get_var('overflow', 'defaults', defaults, varargin{:});\r\nquantisation = get_var('quantisation', 'defaults', defaults, varargin{:});\r\nconv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\r\n\r\n%delay infrastructure\r\nreuse_block(blk, 'sync_in', 'built-in/inport', ...\r\n 'Port', '1', 'Position', [30 30 60 45]);\r\nreuse_block(blk, 'sync_delay', 'xbsIndex_r4/Delay', ...\r\n 'latency', 'mult_latency+add_latency+1+conv_latency', ...\r\n 'Position', [410 25 460 50]) \r\nadd_line(blk, 'sync_in/1', 'sync_delay/1');\r\nreuse_block(blk, 'sync_out', 'built-in/outport', ...\r\n 'Port', '1', 'Position', [950 30 980 45]);\r\nadd_line(blk, 'sync_delay/1', 'sync_out/1');\r\n\r\noffset = 0;\r\ntick=120;\r\nfor input = 0:streams-1,\r\n %number of multipliers to be used\r\n %mults = (2*(input+1)-1)*aggregation\r\n mults = (streams - input)*aggregation; \r\n\r\n reuse_block(blk, ['din',num2str(input)], 'built-in/inport', ...\r\n 'Port', [num2str(input+2)], 'Position', [30 100+(offset+mults)*tick 60 115+(offset+mults)*tick]);\r\n\r\n % set up uncram block for each stream\r\n reuse_block(blk, ['unpack',num2str(input)], 'casper_library_flow_control/bus_expand', ...\r\n 'mode', 'divisions of equal size', ...\r\n 'outputNum', 'aggregation', ...\r\n 'outputWidth', 'bit_width_in*2', ... \r\n 'outputBinaryPt', '0', 'outputArithmeticType', '0', ...\r\n 'Position', [120 100+(offset+mults)*tick 170 100+(offset+mults+aggregation)*tick]);\r\n add_line(blk, ['din',num2str(input),'/1'],['unpack',num2str(input),'/1']);\r\n\r\n %go through each aggregated stream\r\n for substream = 0:aggregation-1,\r\n\r\n %combine real from imaginary parts\r\n sub_name = ['c_to_ri', num2str(input), '_', num2str(substream)];\r\n reuse_block(blk, sub_name, 'casper_library_misc/c_to_ri', ...\r\n 'n_bits', 'bit_width_in', 'bin_pt', 'binary_point_in', ...\r\n 'Position', [200 100+(offset+mults+substream)*tick 250 150+(offset+mults+substream)*tick]);\r\n add_line(blk, ['unpack',num2str(input),'/',num2str(substream+1)], [sub_name,'/1']);\r\n end\r\nend\r\n\r\noffset = 0;\r\ntick=120;\r\nfor input = 0:streams-1,\r\n mults = (streams - input)*aggregation; \r\n %go through multipliers \r\n for mult = 0:(mults/aggregation)-1,\r\n \r\n %pick inputs to multipliers, generating mults based on matrix as follows\r\n % | A B C D\r\n %------------------\r\n %A* | AA* BA* CA* DA*\r\n %B* | AB* BB* CB* DB*\r\n %C* | AC* BC* CC* DC*\r\n %D* | AD* BD* CD* DD*\r\n \r\n %x_in = min(mult,input)\r\n x_in = input\r\n %y_in = min(input,mults/aggregation-mult-1)\r\n y_in = input+mult;\r\n \r\n %to recombine streams\r\n pack_name = ['pack', num2str(input), '_', num2str(mult)];\r\n reuse_block(blk, pack_name, 'casper_library_flow_control/bus_create', ...\r\n 'inputNum', 'aggregation', ...\r\n 'Position', [800 100+(offset+(mult*aggregation))*tick 850 130+(offset+(mult*aggregation))*tick]);\r\n \r\n for substream = 0:aggregation-1,\r\n\r\n %set up multiplier\r\n mult_name = ['cmult', num2str(input), '_', num2str(mult), '_', num2str(substream)]; \r\n reuse_block(blk, mult_name, 'casper_library_multipliers/cmult_4bit_hdl*', ...\r\n 'mult_latency', 'mult_latency', 'add_latency', 'add_latency', ...\r\n 'Position', [550 100+(offset+(mult*aggregation)+substream)*tick 600 195+(offset+(mult*aggregation)+substream)*tick]);\r\n\r\n %set up delays to remove fanout from c_to_ri blocks\r\n delay_name = ['delay', num2str(input), '_', num2str(mult), '_', num2str(substream), '_0'];\r\n reuse_block(blk, delay_name, 'xbsIndex_r4/Delay', ...\r\n 'latency', '1', ...\r\n 'Position', [450 100+(offset+(mult*aggregation)+substream)*tick 480 100+(offset+(mult*aggregation)+substream)*tick+15]); \r\n add_line(blk, ['c_to_ri', num2str(x_in), '_', num2str(substream), '/1'], [delay_name,'/1']);\r\n add_line(blk, [delay_name,'/1'], [mult_name,'/1']);\r\n\r\n delay_name = ['delay', num2str(input), '_', num2str(mult), '_', num2str(substream), '_1'];\r\n reuse_block(blk, delay_name, 'xbsIndex_r4/Delay', ...\r\n 'latency', '1', ...\r\n 'Position', [450 100+(offset+(mult*aggregation)+substream)*tick+30 480 100+(offset+(mult*aggregation)+substream)*tick+45]); \r\n add_line(blk, ['c_to_ri', num2str(x_in), '_', num2str(substream), '/2'], [delay_name,'/1']);\r\n add_line(blk, [delay_name,'/1'], [mult_name,'/2']);\r\n \r\n delay_name = ['delay', num2str(input), '_', num2str(mult), '_', num2str(substream), '_2'];\r\n reuse_block(blk, delay_name, 'xbsIndex_r4/Delay', ...\r\n 'latency', '1', ...\r\n 'Position', [450 100+(offset+(mult*aggregation)+substream)*tick+60 480 100+(offset+(mult*aggregation)+substream)*tick+75]); \r\n add_line(blk, ['c_to_ri', num2str(y_in), '_', num2str(substream), '/1'], [delay_name,'/1']);\r\n add_line(blk, [delay_name,'/1'], [mult_name,'/3']);\r\n\r\n delay_name = ['delay', num2str(input), '_', num2str(mult), '_', num2str(substream), '_3'];\r\n reuse_block(blk, delay_name, 'xbsIndex_r4/Delay', ...\r\n 'latency', '1', ...\r\n 'Position', [450 100+(offset+(mult*aggregation)+substream)*tick+90 480 100+(offset+(mult*aggregation)+substream)*tick+105]); \r\n add_line(blk, ['c_to_ri', num2str(y_in), '_', num2str(substream), '/2'], [delay_name,'/1']);\r\n add_line(blk, [delay_name,'/1'], [mult_name,'/4']);\r\n\r\n %TODO finish overflow detection\r\n %convert data to output precision\r\n cvrt_name = ['cvrt', num2str(input), '_', num2str(mult), '_', num2str(substream)];\r\n reuse_block(blk, [cvrt_name, '_real'], 'casper_library_misc/convert_of', ...\r\n\t \t'bit_width_i', tostring(bit_width_in*2+1), 'binary_point_i', tostring(binary_point_in*2), ...\r\n\t \t'bit_width_o', tostring(bit_width_out), 'binary_point_o', tostring(binary_point_out), ...\r\n\t\t'overflow', tostring(overflow), 'quantization', tostring(quantisation), 'latency', tostring(conv_latency), ...\r\n 'Position', [625 100+(offset+(mult*aggregation)+substream)*tick 675 130+(offset+(mult*aggregation)+substream)*tick]);\r\n reuse_block(blk, [cvrt_name, '_imag'], 'casper_library_misc/convert_of', ...\r\n\t \t'bit_width_i', tostring(bit_width_in*2+1), 'binary_point_i', tostring(binary_point_in*2), ...\r\n\t \t'bit_width_o', tostring(bit_width_out), 'binary_point_o', tostring(binary_point_out), ...\r\n\t\t'overflow', tostring(overflow), 'quantization', tostring(quantisation), 'latency', tostring(conv_latency), ... \r\n 'Position', [625 150+(offset+(mult*aggregation)+substream)*tick 675 180+(offset+(mult*aggregation)+substream)*tick]);\r\n \r\n\t add_line(blk, [mult_name,'/1'], [cvrt_name,'_real/1']);\r\n add_line(blk, [mult_name,'/2'], [cvrt_name,'_imag/1']);\r\n\r\n %join results into complex output\r\n ri2c_name = ['ri_to_c', num2str(input), '_', num2str(mult), '_', num2str(substream)];\r\n reuse_block(blk, ri2c_name, 'casper_library_misc/ri_to_c', ...\r\n 'Position', [725 100+(offset+(mult*aggregation)+substream)*tick 775 130+(offset+(mult*aggregation)+substream)*tick]);\r\n\r\n add_line(blk, [cvrt_name,'_real/1'], [ri2c_name,'/1']);\r\n add_line(blk, [cvrt_name,'_imag/1'], [ri2c_name,'/2']);\r\n \r\n add_line(blk, [ri2c_name,'/1'], [pack_name,'/',num2str(substream+1)]);\r\n \r\n end\r\n \r\n %create output port\r\n out_name = ['din', num2str(x_in), '_x_din', num2str(y_in), '*']; \r\n reuse_block(blk, out_name, 'built-in/outport', 'Port', num2str((offset/aggregation)+mult+2), ...\r\n 'Position', [950 100+(offset+(mult*aggregation))*tick 980 115+(offset+(mult*aggregation))*tick])\r\n add_line(blk, [pack_name,'/1'], [out_name,'/1']);\r\n\r\n end\r\n\r\n offset = offset+mults;\r\n\r\nend\r\n\r\nclean_blocks(blk);\r\n\r\n%fmtstr = sprintf('%d:1 %d bit',input_streams, bit_width);\r\n%set_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_expand_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_expand_init.m", "size": 10705, "source_encoding": "utf_8", "md5": "bb8856be5d72c2cfa78289755e0824bb", "text": "% Create a 'bus' of similar signals\n%\n% bus_expand_init(blk, varargin)\n%\n% blk = The block to be configured.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% outputNum = Number of outputs to split bus into\n% outputWidth = Total bit width of each output\n% outputBinaryPt = Binary point of each output\n% outputArithmeticType = Numerical type of each output\n% outputToWorkspace = Optionally output each output to the Workspace\n% variablePrefix =\n% outputToModeAsWell =\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Meerkat radio telescope project %\n% www.kat.ac.za %\n% Copyright (C) Paul Prozesky 2011 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Sometimes it's nice to 'combine' a bunch of similar signals into one\n% 'bus' using the bus_create or Xilinx concat blocks. But to split them up\n% again is a pain in the butt. So this block just provides an easy way of\n% doing that.\n\nfunction bus_expand_init(blk, varargin)\n\nclog('entering bus_expand_init','trace');\n\ncheck_mask_type(blk, 'bus_expand');\nmunge_block(blk, varargin{:});\n\ndefaults = {'mode', 'divisions of equal size', 'outputNum', 2, 'outputWidth', 8, ...\n 'outputBinaryPt', 7, 'outputArithmeticType', 1, ...\n 'outputToWorkspace', 'off', 'variablePrefix', 'out', ...\n 'outputToModelAsWell', 'off'};\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\n\n% check the params\nmode = get_var('mode', 'defaults', defaults, varargin{:});\noutputNum = get_var('outputNum', 'defaults', defaults, varargin{:});\noutputWidth = get_var('outputWidth', 'defaults', defaults, varargin{:});\noutputBinaryPt = get_var('outputBinaryPt', 'defaults', defaults, varargin{:});\noutputArithmeticType = get_var('outputArithmeticType', 'defaults', defaults, varargin{:});\noutputToWorkspace = get_var('outputToWorkspace', 'defaults', defaults, varargin{:});\nvariablePrefix = get_var('variablePrefix', 'defaults', defaults, varargin{:});\noutputToModelAsWell = get_var('outputToModelAsWell', 'defaults', defaults, varargin{:});\nshow_format = get_var('show_format', 'defaults', defaults, varargin{:});\n\nif (strcmp(mode, 'divisions of arbitrary size') == 1),\n if (((length(outputWidth) ~= length(outputBinaryPt)) && (length(outputBinaryPt) ~= 1)) || ...\n ((length(outputWidth) ~= length(outputArithmeticType)) && (length(outputArithmeticType) ~= 1))),\n error('Division width, binary point and arithmetic type vectors must be the same length when using arbitrary divisions');\n end\n if length(outputArithmeticType) == 1,\n outputArithmeticType = ones(1, length(outputWidth)) * outputArithmeticType;\n end\n if length(outputBinaryPt) == 1,\n outputBinaryPt = ones(1, length(outputWidth)) * outputBinaryPt;\n end\nend\n\nif strcmp(mode, 'divisions of arbitrary size'),\n outputNum = length(outputWidth);\nelse\n if ((outputNum <= 0) || isnan(outputNum) || (~isnumeric(outputNum))),\n error('Need one or more outputs!');\n end\nend\n\nif strcmp(mode, 'divisions of equal size'),\n vals = 1;\nelse\n vals = outputNum;\nend\nfor div = 1:vals,\n if ((outputWidth(div) <= 0) || isnan(outputWidth(div)) || (~isnumeric(outputWidth(div)))),\n error('Need non-zero output width!');\n end\n if ((outputBinaryPt(div) > outputWidth(div)) || isnan(outputBinaryPt(div)) || (~isnumeric(outputBinaryPt(div)))),\n error('Binary point > output width makes no sense!');\n end\n if ( ...\n ((outputArithmeticType(div) ~= 9) && ...\n (outputArithmeticType(div) ~= 2) && ...\n (outputArithmeticType(div) ~= 1) && ...\n (outputArithmeticType(div) ~= 0)) || ...\n isnan(outputArithmeticType(div)) || ...\n (~isnumeric(outputArithmeticType(div))) ...\n ),\n error('Arithmetic type must be one of 0,1,2,9!');\n end\n if (outputArithmeticType(div) == 2 && (outputWidth(div) ~= 1 || outputBinaryPt(div) ~= 0)),\n error('Division width must be 1 and binary point 0 for Boolean Arithmetic type');\n end\n\nend\n\nif strcmp(outputToWorkspace,'on') == 1,\n if (~isvarname(variablePrefix)),\n error('That is not a valid variable name!'); end;\nend\n\nmunge_block(blk, varargin{:});\n\n% delete all the lines\ndelete_lines(blk);\n\n% add the inputs, outputs and gateway out blocks, drawing lines between them\nxSize = 100; ySize = 20; xStart = 100; yPos = 100;\n\n% one input for the bus\nreuse_block(blk, 'bus_in', 'built-in/inport', 'Position', [xStart, yPos, xStart + (xSize/2), yPos + ySize]);\n\nacc_bits = 0;\nconfig_string = '';\nportnum = 1;\n\n% draw the output chains\nfor p = 1 : outputNum,\n if strcmp(mode, 'divisions of equal size'),\n index = 1;\n else\n index = p;\n end\n\n boolean = 'off';\n discard = false;\n width = outputWidth(index);\n bin_pt = outputBinaryPt(index);\n switch outputArithmeticType(index),\n case 1\n arithmeticType = 'Signed (2''s comp)';\n config_string = [config_string, sprintf('f%i.%i,', width, bin_pt)];\n case 2\n boolean = 'on';\n config_string = [config_string, 'b,'];\n case 9\n discard = true;\n config_string = [config_string, 'X,'];\n otherwise\n arithmeticType = 'Unsigned';\n config_string = [config_string, sprintf('uf%i.%i,', width, bin_pt)];\n end\n\n if discard == false,\n xPos = xStart + (xSize * 2);\n blockNum = outputNum + 1 - p;\n % the slice block\n sliceName = sprintf('slice%i', blockNum);\n\n reuse_block(blk, sliceName, 'xbsIndex_r4/Slice', ...\n 'Position', [xPos, yPos, xPos + (xSize/2), yPos + ySize], ...\n 'boolean_output', boolean, 'nbits', num2str(width), ...\n 'bit1', num2str(-1 * acc_bits));\n xPos = xPos + (xSize * 2);\n add_line(blk, ['bus_in', '/1'], [sliceName, '/1']);\n\n if outputArithmeticType(index) ~= 2,\n % the reinterpret block if not boolean\n reinterpretName = sprintf('reinterpret%i', blockNum);\n reuse_block(blk, reinterpretName, 'xbsIndex_r4/Reinterpret', ...\n 'Position', [xPos, yPos, xPos + (xSize/2), yPos + ySize], ...\n 'force_arith_type', 'on', 'arith_type', arithmeticType, ...\n 'force_bin_pt', 'on', 'bin_pt', num2str(bin_pt));\n add_line(blk, [sliceName, '/1'], [reinterpretName, '/1']);\n end\n xPos = xPos + (xSize * 2);\n\n % to workspace?\n if strcmp(outputToWorkspace,'on') == 1,\n % the gateway out block\n gatewayOutName = sprintf('gatewayOut%i', blockNum);\n reuse_block(blk, gatewayOutName, 'xbsIndex_r4/Gateway Out', ...\n 'Position', [xPos, yPos, xPos + (xSize/2), yPos + ySize], 'hdl_port', 'no');\n xPos = xPos + (xSize * 2);\n % the to-workspace block\n toWorkspaceName = sprintf('toWorkspace%i', blockNum);\n toWorkspaceVariableName = sprintf('%s_%i', variablePrefix, blockNum);\n reuse_block(blk, toWorkspaceName, 'built-in/To Workspace', ...\n 'Position', [xPos, yPos, xPos + (xSize * 2), yPos + ySize], ...\n 'VariableName', toWorkspaceVariableName, 'MaxDataPoints', 'inf',...\n 'Decimation', '1','SampleTime', '-1','SaveFormat', 'Structure With Time', 'FixptAsFi', 'yes');\n if outputArithmeticType(index) ~= 2, % not boolean\n add_line(blk, [reinterpretName, '/1'], [gatewayOutName, '/1']);\n else\n add_line(blk, [sliceName, '/1'], [gatewayOutName, '/1']);\n end\n add_line(blk, [gatewayOutName, '/1'], [toWorkspaceName, '/1'], 'autorouting', 'on');\n yPos = yPos + (ySize * 2);\n end\n if ((strcmp(outputToWorkspace,'on') == 1) && (strcmp(outputToModelAsWell,'on') == 1)) || (strcmp(outputToWorkspace,'off') == 1),\n % the output block\n outName = sprintf('out%i', blockNum);\n if (blockNum == 1),\n outName = sprintf('lsb_%s', outName);\n end\n if (blockNum == outputNum),\n outName = sprintf('msb_%s', outName);\n end\n reuse_block(blk, outName, 'built-in/outport', 'Position', [xPos, yPos, xPos + (xSize/2), yPos + ySize], 'Port', num2str(portnum));\n if outputArithmeticType(index) ~= 2, % not boolean\n add_line(blk, [reinterpretName, '/1'], [outName, '/1']);\n else\n add_line(blk, [sliceName, '/1'], [outName, '/1']);\n end\n yPos = yPos + (ySize * 2);\n end\n portnum = portnum + 1;\n end % /discard\n acc_bits = acc_bits + width;\nend\n\n% remove unconnected blocks\nclean_blocks(blk);\n\n% update format string so we know what's going on with this block\nif strcmp(show_format, 'on')\n displayString = sprintf('%d outputs: %s', outputNum, config_string);\nelse\n displayString = sprintf('%d outputs', outputNum);\nend\nif strcmp(outputToWorkspace,'on') == 1,\n displayString = sprintf('%s, %s_?', displayString, variablePrefix);\nend\nset_param(blk, 'AttributesFormatString', displayString);\n\nsave_state(blk, 'defaults', defaults, varargin{:}); % save and back-populate mask parameter values\n\nclog('exiting bus_expand_init','trace');\n\n% end\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_dual_port_ram_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_dual_port_ram_init.m", "size": 29653, "source_encoding": "utf_8", "md5": "c6478aedce086e963916fa3618e5d4eb", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_dual_port_ram_init(blk, varargin)\n log_group = 'bus_dual_port_ram_init_debug';\n\n clog('entering bus_dual_port_ram_init', {'trace', log_group});\n \n defaults = { ...\n 'n_bits', repmat(10, 1, 64), 'bin_pts', repmat(0, 1, 64), ...\n 'init_vector', repmat(zeros(8192, 1), 1, 64), ...\n 'max_fanout', 3, 'mem_type', 'Distributed memory', ...\n 'bram_optimization', 'Speed', ... %'Speed' 'Area' \n 'async_a', 'off', 'async_b', 'off', 'misc', 'on', ...\n 'bram_latency', 1, 'fan_latency', 1, ...\n 'addra_register', 'on', 'addra_implementation', 'behavioral', ...\n 'dina_register', 'on', 'dina_implementation', 'behavioral', ...\n 'wea_register', 'on', 'wea_implementation', 'behavioral', ...\n 'ena_register', 'on', 'ena_implementation', 'behavioral', ...\n 'addrb_register', 'on', 'addrb_implementation', 'behavioral', ...\n 'dinb_register', 'on', 'dinb_implementation', 'behavioral', ...\n 'web_register', 'on', 'web_implementation', 'behavioral', ...\n 'enb_register', 'on', 'enb_implementation', 'behavioral', ...\n }; \n \n check_mask_type(blk, 'bus_dual_port_ram');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 80;\n ypos = 50; yinc = 20;\n\n port_w = 30; port_d = 14;\n rep_w = 50; rep_d = 30;\n bus_expand_w = 50; bus_expand_d = 10;\n bus_create_w = 50; bus_create_d = 10;\n bram_w = 50; bram_d = 50;\n del_w = 30; del_d = 20;\n\n maxy = 2^15; %Simulink limit\n\n n_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\n bin_pts = get_var('bin_pts', 'defaults', defaults, varargin{:});\n init_vector = get_var('init_vector', 'defaults', defaults, varargin{:});\n bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\n mem_type = get_var('mem_type', 'defaults', defaults, varargin{:});\n bram_optimization = get_var('bram_optimization', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n async_a = get_var('async_a', 'defaults', defaults, varargin{:});\n async_b = get_var('async_b', 'defaults', defaults, varargin{:});\n max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:});\n fan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:});\n addra_register = get_var('addra_register', 'defaults', defaults, varargin{:});\n addra_implementation = get_var('addra_implementation', 'defaults', defaults, varargin{:});\n dina_register = get_var('dina_register', 'defaults', defaults, varargin{:});\n dina_implementation = get_var('dina_implementation', 'defaults', defaults, varargin{:});\n wea_register = get_var('wea_register', 'defaults', defaults, varargin{:});\n wea_implementation = get_var('wea_implementation', 'defaults', defaults, varargin{:});\n ena_register = get_var('ena_register', 'defaults', defaults, varargin{:});\n ena_implementation = get_var('ena_implementation', 'defaults', defaults, varargin{:});\n addrb_register = get_var('addrb_register', 'defaults', defaults, varargin{:});\n addrb_implementation = get_var('addrb_implementation', 'defaults', defaults, varargin{:});\n dinb_register = get_var('dinb_register', 'defaults', defaults, varargin{:});\n dinb_implementation = get_var('dinb_implementation', 'defaults', defaults, varargin{:});\n web_register = get_var('web_register', 'defaults', defaults, varargin{:});\n web_implementation = get_var('web_implementation', 'defaults', defaults, varargin{:});\n enb_register = get_var('enb_register', 'defaults', defaults, varargin{:});\n enb_implementation = get_var('enb_implementation', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state, do nothing \n if (n_bits(1) == 0),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_dual_port_ram_init', {'trace', log_group});\n return;\n end\n\n [riv, civ] = size(init_vector);\n [rnb, cnb] = size(n_bits);\n [rbp, cbp] = size(bin_pts);\n\n if (cnb ~= 1 && cbp ~= 1) && ((civ ~= cnb) || (civ ~= cbp)),\n clog('The number of columns in initialisation vector must match the number of values in binary point and number of bits parameter specifications', {'error', log_group});\n error('The number of columns in initialisation vector must match the number of values in binary point and number of bits parameter specifications');\n end\n\n %%%%%%%%%%%%%%%\n % input ports %\n %%%%%%%%%%%%%%%\n\n %The calculations below anticipate how BRAMs are to be configured by the Xilinx tools\n %(as detailed in UG190), explicitly generates these, and attempts to control fanout into\n %these\n \n %if optimizing for Area, do the best we can minimising fanout while still using whole BRAMs\n %fanout for very deep BRAMs will be large\n %TODO this should depend on FPGA architecture\n if strcmp(bram_optimization, 'Area'), \n if (riv >= 2^12), max_word_size = 9;\n elseif (riv >= 2^11), max_word_size = 18;\n else, max_word_size = 36;\n end\n %if optimising for Speed, keep splitting word size even if wasting BRAM resources\n else, \n if (riv >= 2^15), max_word_size = 1;\n elseif (riv >= 2^14), max_word_size = 2;\n elseif (riv >= 2^13), max_word_size = 4;\n elseif (riv >= 2^12), max_word_size = 9;\n elseif (riv >= 2^11), max_word_size = 18;\n else, max_word_size = 36;\n end\n end\n \n ctiv = 0;\n\n while (ctiv == 0) || ((ctiv * bram_d) > maxy),\n\n %if we are going to go beyond Xilinx bounds, double the word width\n if (ctiv * bram_d) > maxy,\n clog(['doubling word size from ', num2str(max_word_size), ' to make space'], log_group);\n if (max_word_size == 1), max_word_size = 2;\n elseif (max_word_size == 2), max_word_size = 4;\n elseif (max_word_size == 4), max_word_size = 9;\n elseif (max_word_size == 9), max_word_size = 18;\n else, max_word_size = 36;\n end %if\n end %if\n \n % translate initialisation matrix based on architecture \n [translated_init_vecs, result] = doubles2unsigned(init_vector, n_bits, bin_pts, max_word_size);\n if result ~= 0,\n clog('error translating initialisation matrix', {'error', log_group});\n error('error translating initialisation matrix');\n end\n\n [rtiv, ctiv] = size(translated_init_vecs);\n end %while\n\n clog([num2str(ctiv), ' brams required'], log_group);\n\n replication = ceil(ctiv/max_fanout);\n clog(['replication factor of ', num2str(replication), ' required'], log_group);\n\n if (cnb == 1),\n n_bits = repmat(n_bits, 1, civ);\n bin_pts = repmat(bin_pts, 1, civ);\n end\n\n ypos_tmp = ypos;\n \n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'addra', 'built-in/inport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n reuse_block(blk, 'dina', 'built-in/inport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*ctiv/2;\n \n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'wea', 'built-in/inport', ...\n 'Port', '3', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'addrb', 'built-in/inport', ...\n 'Port', '4', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n\n port_index = 5;\n %if we are using Block RAM, then need ports for dinb and web\n if strcmp(mem_type, 'Block RAM'),\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n reuse_block(blk, 'dinb', 'built-in/inport', ...\n 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*ctiv/2;\n port_index = port_index + 1; \n\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'web', 'built-in/inport', ...\n 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n port_index = port_index + 1; \n end\n\n % asynchronous A port\n if strcmp(async_a, 'on'),\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'ena', 'built-in/inport', ...\n 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n port_index = port_index + 1;\n end\n\n % asynchronous B port\n if strcmp(async_b, 'on'),\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'enb', 'built-in/inport', ...\n 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n port_index = port_index + 1;\n end\n \n %misc port\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/inport', ...\n 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n end\n\n xpos = xpos + xinc + port_w/2; \n\n %%%%%%%%%%%%%%%%%%%%\n % replicate inputs %\n %%%%%%%%%%%%%%%%%%%%\n\n xpos = xpos + rep_w/2;\n\n ypos_tmp = ypos; %reset ypos\n\n % replicate addra\n if strcmp(addra_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'rep_addra', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... \n 'implementation', addra_implementation, ...\n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'addra/1', 'rep_addra/1');\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n\n % delay dina\n if strcmp(dina_implementation, 'core'), reg_retiming = 'off';\n else, reg_retiming = 'on';\n end\n \n if strcmp(dina_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n reuse_block(blk, 'ddina', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(latency), 'reg_retiming', reg_retiming, ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, ['dina/1'], 'ddina/1');\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n\n % replicate wea\n if strcmp(wea_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'rep_wea', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... \n 'implementation', wea_implementation, ...\n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'wea/1', 'rep_wea/1'); \n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n\n % replicate addrb\n if strcmp(addrb_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'rep_addrb', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... \n 'implementation', addrb_implementation, ...\n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'addrb/1', 'rep_addrb/1'); \n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n\n if strcmp(mem_type, 'Block RAM'),\n % delay dinb\n if strcmp(dinb_implementation, 'core'), reg_retiming = 'off';\n else, reg_retiming = 'on';\n end\n\n if strcmp(dinb_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2;\n reuse_block(blk, 'ddinb', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(latency), 'reg_retiming', reg_retiming, ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, ['dinb/1'], 'ddinb/1');\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n \n % replicate web\n if strcmp(web_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'rep_web', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... \n 'implementation', web_implementation, ...\n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'web/1', 'rep_web/1'); \n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n end %if\n\n if strcmp(async_a, 'on'),\n % replicate ena\n if strcmp(ena_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'rep_ena', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... \n 'implementation', ena_implementation, ...\n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'ena/1', 'rep_ena/1'); \n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n end\n\n if strcmp(async_b, 'on'),\n % replicate enb\n if strcmp(enb_register, 'on'), latency = fan_latency;\n else, latency = 0;\n end\n ypos_tmp = ypos_tmp + bus_expand_d*replication/2;\n reuse_block(blk, 'rep_enb', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... \n 'implementation', enb_implementation, ...\n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'enb/1', 'rep_enb/1'); \n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n end \n\n xpos = xpos + xinc + rep_w/2;\n \n %%%%%%%%%%%%%%%%\n % debus inputs %\n %%%%%%%%%%%%%%%%\n \n xpos = xpos + bus_expand_w/2;\n \n % debus addra\n ypos_tmp = ypos + bus_expand_d*ctiv/2 + yinc;\n reuse_block(blk, 'debus_addra', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ...\n 'outputWidth', mat2str(repmat(ceil(log2(rtiv)), 1, replication)), ...\n 'outputBinaryPt', mat2str(zeros(1, replication)), ...\n 'outputArithmeticType', mat2str(zeros(1,replication)), 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2;\n add_line(blk, 'rep_addra/1', 'debus_addra/1');\n \n % debus dina\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n total_bits = sum(n_bits);\n extra = mod(total_bits, max_word_size);\n main = repmat(max_word_size, 1, floor(total_bits/max_word_size));\n outputWidth = [main];\n if (extra ~= 0), \n outputWidth = [extra, outputWidth]; \n end\n\n reuse_block(blk, 'debus_dina', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', mat2str(outputWidth), 'outputBinaryPt', mat2str(zeros(1, ctiv)), ...\n 'outputArithmeticType', mat2str(zeros(1,ctiv)), 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'ddina/1', 'debus_dina/1');\n\n % debus wea\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n reuse_block(blk, 'debus_wea', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ...\n 'outputWidth', mat2str(ones(1, replication)), ...\n 'outputBinaryPt', mat2str(zeros(1, replication)), ...\n 'outputArithmeticType', mat2str(repmat(2,1,replication)), 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'rep_wea/1', 'debus_wea/1');\n\n % debus addrb\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n reuse_block(blk, 'debus_addrb', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ...\n 'outputWidth', mat2str(repmat(ceil(log2(rtiv)), 1, replication)), ...\n 'outputBinaryPt', mat2str(zeros(1, replication)), ...\n 'outputArithmeticType', mat2str(zeros(1,replication)), 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'rep_addrb/1', 'debus_addrb/1');\n\n if strcmp(mem_type, 'Block RAM'),\n % debus dinb\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n reuse_block(blk, 'debus_dinb', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', mat2str(outputWidth), 'outputBinaryPt', mat2str(zeros(1, ctiv)), ...\n 'outputArithmeticType', mat2str(zeros(1,ctiv)), 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'ddinb/1', 'debus_dinb/1');\n\n % debus web\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n reuse_block(blk, 'debus_web', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ...\n 'outputWidth', mat2str(ones(1, replication)), 'outputBinaryPt', mat2str(zeros(1, replication)), ...\n 'outputArithmeticType', mat2str(repmat(2,1,replication)), ...\n 'show_format', 'on', 'outputToWorkspace', 'off', 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'rep_web/1', 'debus_web/1');\n end %if\n\n if strcmp(async_a, 'on'),\n % debus ena \n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n reuse_block(blk, 'debus_ena', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ...\n 'outputWidth', mat2str(ones(1, replication)), 'outputBinaryPt', mat2str(zeros(1, replication)), ...\n 'outputArithmeticType', mat2str(repmat(2,1,replication)), ...\n 'show_format', 'on', 'outputToWorkspace', 'off', 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'rep_ena/1', 'debus_ena/1');\n end \n \n if strcmp(async_b, 'on'),\n % debus enb \n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n reuse_block(blk, 'debus_enb', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ...\n 'outputWidth', mat2str(ones(1, replication)), 'outputBinaryPt', mat2str(zeros(1, replication)), ...\n 'outputArithmeticType', mat2str(repmat(2,1,replication)), ...\n 'show_format', 'on', 'outputToWorkspace', 'off', 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]);\n ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc;\n add_line(blk, 'rep_enb/1', 'debus_enb/1');\n end \n\n if strcmp(misc, 'on'),\n % delay misc\n ypos_tmp = ypos_tmp + del_d/2;\n reuse_block(blk, 'dmisc0', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(fan_latency), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n ypos_tmp = ypos_tmp + yinc + del_d/2;\n add_line(blk, 'misci/1', 'dmisc0/1');\n end\n\n xpos = xpos + xinc + bus_expand_w/2;\n\n %%%%%%%%%%%%%%\n % bram layer %\n %%%%%%%%%%%%%%\n \n ypos_tmp = ypos;\n xpos = xpos + xinc + bram_w/2;\n\n for bram_index = 1:ctiv,\n\n % bram self\n\n % because the string version of the initVector could be too long (Matlab has upper limits on the length of strings), \n % we save the values in the UserData parameter of the dual port ram block (available on all Simulink blocks it seems)\n % and then reference that value from the mask\n\n initVector = translated_init_vecs(:, bram_index)';\n UserData = struct('initVector', double(initVector));\n\n if strcmp(bram_optimization, 'Speed'), optimize = 'Speed';\n else, optimize = 'Area';\n end\n\n ypos_tmp = ypos_tmp + bram_d/2; \n bram_name = ['bram', num2str(bram_index-1)];\n reuse_block(blk, bram_name, 'xbsIndex_r4/Dual Port RAM', ...\n 'UserData', UserData, 'UserDataPersistent', 'on', ...\n 'depth', num2str(rtiv), 'initVector', ['zeros( 1, ',num2str(rtiv),')'], ...\n 'write_mode_A', 'Read Before Write', 'write_mode_B', 'Read Before Write', ...\n 'en_a', async_a, 'en_b', async_b, 'optimize', optimize, ...\n 'distributed_mem', mem_type, 'latency', num2str(bram_latency), ...\n 'Position', [xpos-bram_w/2 ypos_tmp-bram_d/2 xpos+bram_w/2 ypos_tmp+bram_d/2]);\n ypos_tmp = ypos_tmp + yinc + bram_d/2; \n \n set_param([blk,'/',bram_name], 'initVector', 'getfield(get_param(gcb, ''UserData''), ''initVector'')');\n\n % bram connections to replication and debus blocks\n rep_index = mod(bram_index-1, replication) + 1; %replicated index to use\n add_line(blk, ['debus_addra/', num2str(rep_index)], [bram_name, '/1']);\n add_line(blk, ['debus_dina/', num2str(bram_index)], [bram_name, '/2']);\n add_line(blk, ['debus_wea/', num2str(rep_index)], [bram_name, '/3']);\n add_line(blk, ['debus_addrb/', num2str(rep_index)], [bram_name, '/4']);\n\n port_index = 4;\n if strcmp(mem_type, 'Block RAM'),\n add_line(blk, ['debus_dinb/', num2str(bram_index)], [bram_name, '/5']);\n add_line(blk, ['debus_web/', num2str(rep_index)], [bram_name, '/6']);\n port_index = 6;\n end %if\n \n if strcmp(async_a, 'on'), \n port_index = port_index+1;\n add_line(blk, ['debus_ena/', num2str(rep_index)], [bram_name, '/', num2str(port_index)]);\n end %if \n\n if strcmp(async_b, 'on'), \n port_index = port_index+1;\n add_line(blk, ['debus_enb/', num2str(rep_index)], [bram_name, '/', num2str(port_index)]);\n end %if \n end %for \n\n % delay for enables and misc\n\n if strcmp(async_a, 'on'),\n ypos_tmp = ypos_tmp + del_d/2;\n reuse_block(blk, 'dena', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(bram_latency), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n ypos_tmp = ypos_tmp + yinc + del_d/2;\n add_line(blk, ['debus_ena/',num2str(replication)], 'dena/1');\n end;\n \n if strcmp(async_b, 'on'),\n ypos_tmp = ypos_tmp + del_d/2;\n reuse_block(blk, 'denb', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(bram_latency), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n ypos_tmp = ypos_tmp + yinc + del_d/2;\n add_line(blk, ['debus_enb/1'], 'denb/1');\n end %if\n\n if strcmp(misc, 'on'),\n ypos_tmp = ypos_tmp + del_d/2;\n reuse_block(blk, 'dmisc1', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(bram_latency), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n ypos_tmp = ypos_tmp + yinc + del_d/2;\n add_line(blk, 'dmisc0/1', 'dmisc1/1');\n end %if\n \n xpos = xpos + xinc + bram_w/2;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%\n % recombine bram outputs %\n %%%%%%%%%%%%%%%%%%%%%%%%%%\n\n xpos = xpos + bus_create_w/2;\n ypos_tmp = ypos; \n \n ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; \n reuse_block(blk, 'A_bussify', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(ctiv), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-bus_create_d*ctiv/2 xpos+bus_create_w/2 ypos_tmp+bus_create_d*ctiv/2]);\n ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; \n \n ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; \n reuse_block(blk, 'B_bussify', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(ctiv), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-bus_create_d*ctiv/2 xpos+bus_create_w/2 ypos_tmp+bus_create_d*ctiv/2]);\n ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; \n \n for index = 1:ctiv,\n add_line(blk, ['bram',num2str(index-1),'/1'], ['A_bussify', '/', num2str(index)]); \n add_line(blk, ['bram',num2str(index-1),'/2'], ['B_bussify', '/', num2str(index)]); \n end %for\n\n xpos = xpos + xinc + bus_create_w/2;\n\n %%%%%%%%%%%%%%%%\n % output ports %\n %%%%%%%%%%%%%%%%\n\n xpos = xpos + port_w/2;\n ypos_tmp = ypos; \n \n ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; \n reuse_block(blk, 'A', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; \n add_line(blk, 'A_bussify/1', 'A/1');\n\n ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; \n reuse_block(blk, 'B', 'built-in/outport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; \n add_line(blk, 'B_bussify/1', 'B/1');\n \n port_index = 3;\n if strcmp(async_a, 'on'),\n ypos_tmp = ypos_tmp + port_d/2;\n reuse_block(blk, 'dvalida', 'built-in/outport', ...\n 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + port_d/2; \n port_index = port_index + 1;\n add_line(blk, 'dena/1', 'dvalida/1');\n end\n \n if strcmp(async_b, 'on'),\n ypos_tmp = ypos_tmp + port_d/2;\n reuse_block(blk, 'dvalidb', 'built-in/outport', ...\n 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + port_d/2; \n port_index = port_index + 1;\n add_line(blk, 'denb/1', 'dvalidb/1');\n end\n\n if strcmp(misc, 'on'),\n ypos_tmp = ypos_tmp + port_d/2;\n reuse_block(blk, 'misco', 'built-in/outport', ...\n 'Port', num2str(port_index), ... \n 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + port_d/2;\n\n add_line(blk, 'dmisc1/1', 'misco/1');\n end\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_dual_port_ram_init', {'trace', log_group});\n\nend %function bus_dual_port_ram_init\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "mirror_spectrum_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/mirror_spectrum_init.m", "size": 8383, "source_encoding": "utf_8", "md5": "e4141a1bad1ef5d40637641fadd247c5", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKASA %\n% www.kat.ac.za %\n% Copyright (C) Andrew Martens 2013 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction mirror_spectrum_init(blk, varargin)\n\n clog('entering mirror_spectrum_init', {'trace', 'mirror_spectrum_init_debug'});\n\n % Set default vararg values.\n % reg_retiming is not an actual parameter of this block, but it is included\n % in defaults so that same_state will return false for blocks drawn prior to\n % adding reg_retiming='on' to some of the underlying Delay blocks.\n defaults = { ...\n 'n_inputs', 1, ...\n 'FFTSize', 8, ...\n 'input_bitwidth', 18, ...\n 'bin_pt_in', 'input_bitwidth-1', ...\n 'bram_latency', 2, ...\n 'negate_latency', 1, ...\n 'negate_mode', 'Logic', ...\n 'async', 'off', ...\n 'reg_retiming', 'on', ...\n };\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n check_mask_type(blk, 'mirror_spectrum');\n munge_block(blk, varargin{:});\n\n % Retrieve values from mask fields.\n n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\n FFTSize = get_var('FFTSize', 'defaults', defaults, varargin{:});\n input_bitwidth = get_var('input_bitwidth', 'defaults', defaults, varargin{:});\n bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:});\n bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\n negate_latency = get_var('negate_latency', 'defaults', defaults, varargin{:});\n negate_mode = get_var('negate_mode', 'defaults', defaults, varargin{:});\n async = get_var('async', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default setup for library\n if n_inputs == 0 | FFTSize == 0,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:});\n clog('exiting mirror_spectrum_init',{'trace','mirror_spectrum_init_debug'});\n return;\n end\n\n %\n % sync and counter\n %\n\n reuse_block(blk, 'sync', 'built-in/Inport', 'Port', '1', 'Position', [10 42 40 58]);\n\n reuse_block(blk, 'sync_delay0', 'xbsIndex_r4/Delay', ...\n 'latency', '1 + bram_latency + negate_latency - ceil(log2(n_inputs))', 'reg_retiming', 'on', ...\n 'Position', [105 39 140 61]);\n add_line(blk, 'sync/1', 'sync_delay0/1');\n\n reuse_block(blk, 'counter', 'xbsIndex_r4/Counter', ...\n 'cnt_type', 'Free Running', 'operation', 'Up', 'start_count', '0', 'cnt_by_val', '1', ...\n 'arith_type', 'Unsigned', 'n_bits', 'FFTSize', 'bin_pt', '0', ...\n 'rst', 'on', 'en', async, ...\n 'use_behavioral_HDL', 'off', 'implementation', 'Fabric', ...\n 'Position', [185 156 245 189]);\n add_line(blk, 'sync_delay0/1', 'counter/1');\n\n reuse_block(blk, 'constant', 'xbsIndex_r4/Constant', ...\n 'const', num2str(2^(FFTSize-1)), ...\n 'arith_type', 'Unsigned', 'n_bits', num2str(FFTSize), 'bin_pt', '0', ...\n 'explicit_period', 'on', 'period', '1', ...\n 'Position', [185 207 245 233]);\n\n reuse_block(blk, 'relational', 'xbsIndex_r4/Relational', 'latency', '0', 'mode', 'a>b', 'Position', [300 154 340 241]);\n add_line(blk, 'counter/1', 'relational/1');\n add_line(blk, 'constant/1', 'relational/2');\n\n reuse_block(blk, 'sync_delay1', 'xbsIndex_r4/Delay', ...\n 'reg_retiming', 'on', 'latency', '1 + ceil(log2(n_inputs))', ...\n 'Position', [375 39 495 61]);\n add_line(blk, 'sync_delay0/1', 'sync_delay1/1');\n\n reuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '1', 'Position', [550 42 580 58]);\n add_line(blk, 'sync_delay1/1', 'sync_out/1');\n\n %\n % data\n %\n\n for index = 0:3,\n reuse_block(blk, ['din',num2str(index)], 'built-in/Inport', ...\n 'Port', num2str((index+1)*2), 'Position', [10 310+(125*index) 40 325+(125*index)]);\n\n reuse_block(blk, ['delay',num2str(index)], 'xbsIndex_r4/Delay', ...\n 'latency', '1 + bram_latency + negate_latency', 'reg_retiming', 'on', ...\n 'Position', [105 307+(125*index) 140 329+(125*index)]);\n add_line(blk, ['din',num2str(index),'/1'], ['delay',num2str(index),'/1']);\n \n reuse_block(blk, ['reo_in',num2str(index)], 'built-in/Inport', ...\n 'Port', num2str((index+1)*2+1), 'Position', [10 345+(125*index) 40 361+(125*index)]);\n \n %from original script (commit 8ea553 and earlier)\n if strcmp(negate_mode, 'dsp48e'), cc_latency = 3;\n else, cc_latency = negate_latency;\n end\n reuse_block(blk, ['complex_conj',num2str(index)], 'casper_library_misc/complex_conj', ...\n 'n_inputs', num2str(n_inputs), 'n_bits', num2str(input_bitwidth), ...\n 'bin_pt', num2str(bin_pt_in), 'latency', num2str(cc_latency), 'overflow', 'Wrap', ... %TODO Wrap really?\n 'Position', [105 343+(125*index) 140 363+(125*index)]);\n add_line(blk, ['reo_in',num2str(index),'/1'], ['complex_conj',num2str(index),'/1']);\n\n reuse_block(blk, ['sel_replicate',num2str(index)], 'casper_library_bus/bus_replicate', ...\n 'replication', 'n_inputs', 'latency', 'ceil(log2(n_inputs))', 'misc', 'off', 'implementation', 'core', ...\n 'Position', [375 274+(125*index) 415 296+(125*index)]);\n add_line(blk, 'relational/1', ['sel_replicate',num2str(index),'/1']);\n\n reuse_block(blk, ['dmux',num2str(index)], 'casper_library_bus/bus_mux', ...\n 'n_inputs', '2', 'n_bits', mat2str(repmat(input_bitwidth, 1, n_inputs)), 'mux_latency', '1', ...\n 'cmplx', 'on', 'misc', 'off', ...\n 'Position', [460 268+(125*index) 495 372+(125*index)]);\n add_line(blk, ['sel_replicate',num2str(index),'/1'], ['dmux',num2str(index),'/1']);\n add_line(blk, ['delay',num2str(index),'/1'], ['dmux',num2str(index),'/2']);\n add_line(blk, ['complex_conj',num2str(index),'/1'], ['dmux',num2str(index),'/3']);\n\n reuse_block(blk, ['dout',num2str(index)], 'built-in/Outport', ...\n 'Port', num2str(index+2), 'Position', [550 312+(125*index) 580 325+(125*index)]);\n add_line(blk, ['dmux',num2str(index),'/1'], ['dout',num2str(index),'/1']);\n end\n\n if strcmp(async, 'on'),\n reuse_block(blk, 'en', 'built-in/Inport', 'Port', '10', 'Position', [10 87 40 103]);\n\n reuse_block(blk, 'en_delay0', 'xbsIndex_r4/Delay', ...\n 'latency', '1 + bram_latency + negate_latency - ceil(log2(n_inputs))', 'reg_retiming', 'on', ...\n 'Position', [105 84 140 106]);\n add_line(blk, 'en/1', 'en_delay0/1');\n add_line(blk, 'en_delay0/1', 'counter/2');\n\n reuse_block(blk, 'en_delay1', 'xbsIndex_r4/Delay', ...\n 'latency', '1 + ceil(log2(n_inputs))', 'reg_retiming', 'on', ...\n 'Position', [375 84 495 106]);\n add_line(blk, 'en_delay0/1', 'en_delay1/1');\n \n reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', '6', 'Position', [550 87 580 103]);\n add_line(blk, 'en_delay1/1', 'dvalid/1'); \n end\n\n % Delete all unconnected blocks.\n clean_blocks(blk);\n\n % Save block state to stop repeated init script runs.\n save_state(blk, 'defaults', defaults, varargin{:});\nend % mirror_spectrum_init\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_fir_coeff_gen_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_fir_coeff_gen_init.m", "size": 15990, "source_encoding": "utf_8", "md5": "1de8ce4de68d6d055f4914665ca8e8a1", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (andrew@ska.ac.za) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction pfb_fir_coeff_gen_init(blk, varargin)\n log_group = 'pfb_fir_coeff_gen_init_debug';\n clog('entering pfb_fir_coeff_gen_init', {'trace', log_group});\n\n defaults = { ...\n 'n_inputs', 2, ...\n 'pfb_size', 5, ...\n 'n_taps', 4, ...\n 'n_bits_coeff', 18, ...\n 'WindowType', 'hamming', ...\n 'fwidth', 1, ...\n 'async', 'on', ...\n 'bram_latency', 2, ...\n 'fan_latency', 2, ...\n 'add_latency', 1, ...\n 'max_fanout', 1, ...\n 'bram_optimization', 'Area', ...\n };\n \n check_mask_type(blk, 'pfb_fir_coeff_gen');\n\n yinc = 40;\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\n pfb_size = get_var('pfb_size', 'defaults', defaults, varargin{:});\n n_taps = get_var('n_taps', 'defaults', defaults, varargin{:});\n n_bits_coeff = get_var('n_bits_coeff', 'defaults', defaults, varargin{:});\n WindowType = get_var('WindowType', 'defaults', defaults, varargin{:});\n fwidth = get_var('fwidth', 'defaults', defaults, varargin{:});\n async = get_var('async', 'defaults', defaults, varargin{:});\n bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\n fan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:});\n add_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\n max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:});\n bram_optimization = get_var('bram_optimization', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default empty block for storage in library\n if n_taps == 0,\n clean_blocks(blk);\n set_param(blk, 'AttributesFormatString', '');\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting pfb_fir_coeff_gen_init', {'trace', log_group});\n return;\n end\n\n %check parameters\n if n_taps < 4,\n clog('need at least 4 taps', {'error', log_group});\n error('need at least 4 taps');\n return;\n end\n \n if mod(n_taps, 2) ~= 0,\n clog('Number of taps must be an even number', {'error', log_group});\n error('Number of taps must be an even number');\n return;\n end\n \n %get hardware platform from XSG block\n try\n xsg_blk = find_system(bdroot, 'SearchDepth', 1,'FollowLinks','on','LookUnderMasks','all','Tag','xps:xsg');\n hw_sys = xps_get_hw_plat(get_param(xsg_blk{1},'hw_sys'));\n catch,\n clog('Could not find hardware platform - is there an XSG block in this model? Defaulting platform to ROACH.', {log_group});\n warning('pfb_fir_coeff_gen_init: Could not find hardware platform - is there an XSG block in this model? Defaulting platform to ROACH.');\n hw_sys = 'ROACH';\n end %try/catch\n\n %parameters to decide optimisation parameters\n switch hw_sys\n case 'ROACH'\n port_width = 36; %upper limit\n case 'ROACH2'\n port_width = 36; %upper limit\n end %switch\n\n yoff = 226;\n\n %%%%%%%%%%%%%%%%%\n % sync pipeline %\n %%%%%%%%%%%%%%%%%\n\n reuse_block(blk, 'sync', 'built-in/Inport', 'Port', '1', 'Position', [15 23 45 37]);\n reuse_block(blk, 'sync_delay', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'latency', num2str(fan_latency+bram_latency), 'Position', [255 22 515 38]);\n add_line(blk,'sync/1', 'sync_delay/1');\n reuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '1', 'Position', [1060 23 1090 37]);\n add_line(blk,'sync_delay/1', 'sync_out/1');\n \n %%%%%%%%%%%%%%%%\n % din pipeline %\n %%%%%%%%%%%%%%%%\n\n reuse_block(blk, 'din', 'built-in/Inport', 'Port', '2', 'Position', [15 68 45 82]);\n reuse_block(blk, 'din_delay', 'xbsIndex_r4/Delay', 'reg_retiming', 'on',...\n 'latency', num2str(fan_latency+bram_latency), 'Position', [255 67 515 83]);\n add_line(blk, 'din/1', 'din_delay/1');\n reuse_block(blk, 'dout', 'built-in/Outport', 'Port', '2', 'Position', [1060 68 1090 82]);\n add_line(blk,'din_delay/1', 'dout/1');\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%\n % coefficient generation %\n %%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % address generation\n reuse_block(blk, 'counter', 'xbsIndex_r4/Counter', ...\n 'cnt_type', 'Free Running', 'operation', 'Up', 'start_count', '0', 'cnt_by_val', '1', ...\n 'n_bits', num2str(pfb_size-n_inputs), 'arith_type', 'Unsigned', 'bin_pt', '0', ...\n 'rst', 'on', 'en', async, ...\n 'Position', [95 211 145 264]);\n add_line(blk, 'sync/1', 'counter/1'); \n\n %we invert the address to get address for the other half of the taps\n reuse_block(blk, 'inverter', 'xbsIndex_r4/Inverter', ...\n 'latency', '0', 'Position', [170 303 220 357]);\n add_line(blk, 'counter/1', 'inverter/1'); \n \n % ROM generation\n outputs_required = 2^n_inputs*(n_taps/2); \n \n % constants\n reuse_block(blk, 'rom_din', 'xbsIndex_r4/Constant', ...\n 'const', '0', 'arith_type', 'Unsigned', ...\n 'n_bits', num2str(outputs_required*n_bits_coeff), 'bin_pt', '0', ...\n 'explicit_period', 'on', 'period', '1', ...\n 'Position', [255 262 275 278]);\n reuse_block(blk, 'rom_we', 'xbsIndex_r4/Constant', ...\n 'const', '0', 'arith_type', 'Boolean', ...\n 'explicit_period', 'on', 'period', '1', ...\n 'Position', [255 292 275 308]);\n\n % rom\n init_vector = '';\n for tap_index = 1:(n_taps/2), \n for input_index = 0:(2^n_inputs)-1,\n vec = ['pfb_coeff_gen_calc(', num2str(pfb_size), ', ', num2str(n_taps), ', ''', WindowType, ''', ', num2str(n_inputs), ', ', num2str(input_index), ', ', num2str(fwidth), ', ', num2str(tap_index), ', false)'''];\n if(tap_index == 1 && input_index == 0), init_vector = vec; \n else, init_vector = [init_vector, ', ', vec];\n end\n end %for input_index\n end %for tap_index\n\n reuse_block(blk, 'rom', 'casper_library_bus/bus_dual_port_ram', ...\n 'n_bits', mat2str(repmat(n_bits_coeff, 1, outputs_required)), ...\n 'bin_pts', mat2str(repmat(n_bits_coeff-1, 1, outputs_required)), ...\n 'init_vector', ['[', init_vector, ']'], ...\n 'max_fanout', num2str(max_fanout), ...\n 'mem_type', 'Block RAM', 'bram_optimization', bram_optimization, ...\n 'async_a', 'off', 'async_b', 'off', 'misc', 'off', ...\n 'bram_latency', num2str(bram_latency), ...\n 'fan_latency', num2str(fan_latency), ...\n 'addra_register', 'on', 'addra_implementation', 'core', ...\n 'dina_register', 'off', 'dina_implementation', 'behavioral', ...\n 'wea_register', 'off', 'wea_implementation', 'behavioral', ...\n 'addrb_register', 'on', 'addra_implementation', 'core', ...\n 'dinb_register', 'off', 'dinb_implementation', 'behavioral', ...\n 'web_register', 'off', 'web_implementation', 'behavioral', ...\n 'Position', [330 226 385 404]);\n add_line(blk, 'counter/1', 'rom/1');\n add_line(blk, 'inverter/1', 'rom/4');\n add_line(blk, 'rom_din/1', 'rom/2');\n add_line(blk, 'rom_din/1', 'rom/5');\n add_line(blk, 'rom_we/1', 'rom/3');\n add_line(blk, 'rom_we/1', 'rom/6');\n\n % logic for second half of taps \n % Coefficients are not quite symmetrical, they are off by one, and do not overlap by one\n % e.g with T taps and fft size of N: tap T-1, sample 0 is not the same as tap 0, sample N-1\n % instead it is unique and not included in the coefficients for Tap 0\n\n reuse_block(blk, 'zero', 'xbsIndex_r4/Constant', ...\n 'const', '0', 'arith_type', 'Unsigned', ...\n 'n_bits', num2str(pfb_size-n_inputs), 'bin_pt', '0', ...\n 'explicit_period', 'on', 'period', '1', ...\n 'Position', [210 122 230 138]);\n \n reuse_block(blk, 'first', 'xbsIndex_r4/Relational' , ...\n 'latency', '1', 'mode', 'a=b', 'Position', [295 114 325 176]);\n add_line(blk, 'counter/1', 'first/2');\n add_line(blk, 'zero/1', 'first/1');\n \n reuse_block(blk, 'dfirst', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'latency', num2str(bram_latency+fan_latency-1-1), 'Position', [455 136 515 154] );\n add_line(blk, 'first/1', 'dfirst/1');\n\n % get the first value of the second half of the taps\n vector = pfb_coeff_gen_calc(pfb_size, n_taps, WindowType, n_inputs, 0, fwidth, n_taps/2+1, false);\n val = doubles2unsigned(vector(1), n_bits_coeff, n_bits_coeff-1, n_bits_coeff); \n\n init = val(1);\n reuse_block(blk, 'register', 'xbsIndex_r4/Register', ...\n 'init', num2str(init), 'rst', 'on', 'en', async, ...\n 'Position', [675 yoff+(outputs_required*yinc) 720 yoff+((outputs_required+1)*yinc)]);\n add_line(blk, 'dfirst/1', 'register/2');\n\n % reorder output of port B \n order = zeros(1, n_taps/2 * 2^n_inputs);\n for tap_index = 0:n_taps/2-1,\n for input_index = 0:2^n_inputs-1,\n offset = ((n_taps/2)-tap_index-1) * (2^n_inputs);\n if input_index == 0, index = offset;\n else, index = offset + (2^n_inputs - input_index);\n end\n \n order(tap_index*(2^n_inputs) + input_index + 1) = index;\n end %for\n end %for\n\n reuse_block(blk, 'munge', 'casper_library_flow_control/munge', ...\n 'divisions', num2str(outputs_required), ...\n 'div_size', mat2str(repmat(n_bits_coeff, 1, outputs_required)), ...\n 'order', mat2str(order), 'arith_type_out', 'Unsigned', 'bin_pt_out', '0', ... \n 'Position', [435 377 475 403] );\n add_line(blk, 'rom/2', 'munge/1');\n \n % coefficient extraction\n reuse_block(blk, 'a_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(outputs_required), ...\n 'outputWidth', num2str(n_bits_coeff), 'outputBinaryPt', '0', 'outputArithmeticType', '0', ...\n 'Position', [740 yoff 790 yoff+(outputs_required*yinc)]);\n add_line(blk, 'rom/1', 'a_expand/1');\n \n reuse_block(blk, 'b_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(outputs_required), ...\n 'outputWidth', num2str(n_bits_coeff), 'outputBinaryPt', '0', 'outputArithmeticType', '0', ...\n 'Position', [515 yoff+(outputs_required*yinc) 565 yoff+(outputs_required*yinc*2)]);\n add_line(blk, 'munge/1', 'b_expand/1');\n add_line(blk, 'b_expand/1', 'register/1');\n\n reuse_block(blk, 'coeffs', 'built-in/Outport', 'Port', '3', ...\n 'Position', [1060 yoff+outputs_required*yinc-7 1090 yoff+outputs_required*yinc+7]);\n\n % concat a and b busses together\n reuse_block(blk, 'concat', 'xbsIndex_r4/Concat', ...\n 'num_inputs', num2str(outputs_required*2), ...\n 'Position', [1005 yoff 1035 yoff+(outputs_required*2*yinc)]); \n add_line(blk, 'concat/1', 'coeffs/1');\n\n % delays for each output\n for d_index = 0:outputs_required*2-1,\n d_name = ['d',num2str(d_index)];\n\n latency = (floor((outputs_required*2-d_index-1)/(2^n_inputs)))*add_latency;\n \n if d_index >= outputs_required,\n if mod(d_index, 2^n_inputs) == 0, \n if mod(d_index, (n_taps/2)*2^n_inputs) ~= 0, \n latency = latency + 1;\n end\n end\n end\n \n %force delay block with 0 latency to have no enable port\n if latency > 0, en = async;\n else, en = 'off';\n end\n\n reuse_block(blk, d_name, 'casper_library_delays/delay_srl', ...\n 'async', en, 'DelayLen', num2str(latency), ...\n 'Position', [875 yoff+d_index*yinc 930 yoff+d_index*yinc+18]);\n add_line(blk, [d_name,'/1'], ['concat/',num2str(d_index+1)]); \n\n % join bus expansion blocks to delay\n if ((d_index/outputs_required) < 1), \n src_blk = 'a_expand';\n else,\n if (mod(d_index, outputs_required) == 0), src_blk = 'register';\n else, src_blk = 'b_expand';\n end\n end %if\n \n src_port = mod(d_index, outputs_required) + 1;\n add_line(blk, [src_blk, '/', num2str(src_port)], [d_name, '/1']);\n\n end %for \n \n % asynchronous pipeline\n if strcmp(async, 'on'),\n yoff = 226;\n\n reuse_block(blk, 'en', 'built-in/Inport', 'Port', '3', ...\n 'Position', [15 243 45 257]);\n add_line(blk, 'en/1', 'counter/2'); \n \n reuse_block(blk, 'den0', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'latency', num2str(bram_latency), ...\n 'Position', [255 yoff+(outputs_required*2+2)*yinc 280 yoff+(outputs_required*2+2)*yinc+18]);\n add_line(blk, 'en/1', 'den0/1');\n \n reuse_block(blk, 'den1', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'latency', num2str(fan_latency), ...\n 'Position', [540 yoff+(outputs_required*2+2)*yinc 565 yoff+(outputs_required*2+2)*yinc+18]);\n add_line(blk, 'den0/1', 'den1/1');\n add_line(blk, 'den1/1', 'register/3');\n\n outputNum = outputs_required*2-(2^n_inputs-1);\n reuse_block(blk, 'en_replicate', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(outputNum), 'latency', num2str(fan_latency+bram_latency), 'misc', 'off', ...\n 'Position', [245 yoff+(outputs_required*2+4)*yinc 295 yoff+(outputs_required*2+4)*yinc+30]);\n add_line(blk, 'en/1', 'en_replicate/1');\n\n reuse_block(blk, 'en_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(outputNum), ...\n 'outputWidth', '1', 'outputBinaryPt', '0', 'outputArithmeticType', '2', ...\n 'Position', [740 yoff+(outputs_required*2+4)*yinc 790 yoff+(outputs_required*3+4)*yinc]);\n add_line(blk, 'en_replicate/1', 'en_expand/1');\n\n for d_index = 0:outputs_required*2-1,\n \n latency = (floor((outputs_required*2-d_index-1)/(2^n_inputs)))*add_latency;\n \n if d_index >= outputs_required,\n if mod(d_index, 2^n_inputs) == 0, \n if mod(d_index, (n_taps/2)*2^n_inputs) ~= 0, latency = latency + 1;\n end\n end\n end\n \n if(latency > 0), \n d_name = ['d',num2str(d_index)];\n add_line(blk, ['en_expand/',num2str(d_index+1)], [d_name,'/2']);\n end\n end %for\n \n reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', '4', ...\n 'Position', [1060 yoff+(outputs_required*2+2)*yinc+2 1090 yoff+(outputs_required*2+2)*yinc+16]);\n add_line(blk, 'den1/1', 'dvalid/1');\n\n end %if async\n\n clean_blocks(blk);\n set_param(blk, 'AttributesFormatString', '');\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting pfb_fir_coeff_gen_init', {'trace', log_group});\n\nend %pfb_fir_coeff_gen_init\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "delay_wideband_prog_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/delay_wideband_prog_init.m", "size": 10869, "source_encoding": "utf_8", "md5": "a754c63e13487297b707da15284afa1f", "text": "% Initialize and configure the delay wideband programmable block .\n% By Jason + Mekhala, mods by Andrew\n%\n% delay_wideband_prog_init(blk, varargin)\n%\n% blk = The block to configure.\n% varargin = {'varname', 'value', ...} pairs\n% \n% Declare any default values for arguments you might like.\n\nfunction delay_wideband_prog_init(blk, varargin)\n\nlog_group = 'delay_wideband_prog_init_debug';\n\nclog('entering delay_wideband_prog_init', {log_group, 'trace'}); \ndefaults = { ...\n 'max_delay', 1024, ...\n 'n_inputs_bits', 2, ...\n 'bram_latency', 2, ...\n 'bram_type', 'Dual Port', ...\n 'async', 'off'};\n \n% if parameter is changed then only it will redraw otherwise will exit\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\n\n% Checks whether the block selected is correct with this called function.\ncheck_mask_type(blk, 'delay_wideband_prog');\n \n%Sets the variable to the sub-blocks (scripted ones), also checks whether\n%to update or prevent from any update\nmunge_block(blk, varargin{:});\n \n% sets the variable needed\nmax_delay = get_var('max_delay', 'defaults', defaults, varargin{:});\nn_inputs_bits = get_var('n_inputs_bits', 'defaults', defaults, varargin{:});\nram_bits = ceil(log2(max_delay/(2^n_inputs_bits)));\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\nbram_type = get_var('bram_type', 'defaults', defaults,varargin{:});\nasync = get_var('async', 'defaults', defaults,varargin{:});\n\nif strcmp(async, 'on') && strcmp(bram_type, 'Single Port'),\n clog('Delays must be implemented in dual port memories when in asynchronous mode', {log_group, 'error'}); \n error('Delays must be implemented in dual port memories when in asynchronous mode in the delay_wideband_prog block'); \nend\n \n% Begin redrawing\ndelete_lines(blk);\n\nif (max_delay == 0),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); \n clog('exiting delay_wideband_prog_init', {log_group, 'trace'});\n return;\nend\n\n% delay sync to compensate for delays\n% through BRAMs as well as for delay offset added\n% when using single port RAMs\nif strcmp(bram_type, 'Single Port'),\n latency = bram_latency + 2;\n sync_latency = latency + (bram_latency+1)*2^n_inputs_bits;\nelse\n latency = bram_latency + 1;\n sync_latency = latency;\nend\n\n% sync\nreuse_block(blk, 'sync', 'built-in/Inport', 'Port', '1', 'Position', [15 218 45 232]) ;\n\nif strcmp(async, 'on'),\n % en\n y = 230 + (2^n_inputs_bits)*70;\n reuse_block(blk, 'en', 'built-in/Inport', 'Port', num2str(1 + 2^n_inputs_bits), ...\n 'Position',[15 y+28 45 y+42]);\n reuse_block(blk, 'en_delay0', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'Position', [565 y+21 605 y+49], 'latency', '0');\n add_line(blk, 'en/1', 'en_delay0/1');\n reuse_block(blk, 'en_delay1', 'xbsIndex_r4/Delay', ...\n 'Position', [705 y+21 745 y+49], 'latency', num2str(sync_latency), 'reg_retiming', 'on');\n add_line(blk, 'en_delay0/1', 'en_delay1/1');\n reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', num2str(1 + 2^n_inputs_bits), ...\n 'Position', [975 y+28 1005 y+42]);\nend\n\nreuse_block(blk, 'sync_delay', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'Position', [705 211 745 239], 'latency', num2str(sync_latency));\n\nreuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '1', 'Position', [975 158 1005 172]);\nadd_line(blk, 'sync/1', 'sync_delay/1');\n\n% register delay value\nreuse_block(blk, 'delay', 'built-in/Inport', 'Port', '2', 'Position', [15 273 45 287]) ;\nreuse_block(blk, 'ld_delay', 'built-in/Inport', 'Port', '3', 'Position', [15 303 45 317]) ;\n\nreuse_block(blk, 'delay_reg', 'xbsIndex_r4/Register', 'Position',[105 266 160 324], 'en', 'on');\n\nadd_line(blk, 'delay/1', 'delay_reg/1', 'autorouting', 'on');\n\nadd_line(blk, 'ld_delay/1', 'delay_reg/2', 'autorouting', 'on');\n\n%cut address for BRAM from delay\nreuse_block(blk, 'bram_rd_addrs', 'xbsIndex_r4/Slice', ...\n 'Position', [420 282 450 308], ...\n 'mode', 'Lower Bit Location + Width', ...\n 'nbits', num2str(ram_bits), ...\n 'bit0', num2str(n_inputs_bits), ...\n 'base0', 'LSB of Input');\n \nif strcmp(bram_type, 'Single Port'),\n\n % When using single-port BRAMs, a delay offset must added due to limitations in the delay_bram_prog\n\n reuse_block(blk, 'delay_offset', 'xbsIndex_r4/Constant', ...\n 'Position', [230 333 255 357], ...\n 'const', num2str((bram_latency+1)*2^n_inputs_bits), ... \n 'arith_type', 'Unsigned', ...\n 'n_bits', num2str(ceil(log2(max_delay))), ...\n 'bin_pt', '0', ...\n 'explicit_period', 'on', ...\n 'period', '1');\n \n reuse_block(blk, 'delay_adder', 'xbsIndex_r4/AddSub', ...\n 'Position', [310 266 345 319], ...\n 'latency', '1', 'mode', 'Addition');\n add_line(blk, 'delay_offset/1', 'delay_adder/2', 'autorouting', 'on');\n add_line(blk, 'delay_adder/1', 'bram_rd_addrs/1', 'autorouting', 'on');\n\n % This offset must be removed from the max possible delay value (and we force the value to clip at\n % this lower value) to prevent wrapping when this offset is added\n \n reuse_block(blk, 'max_delay', 'xbsIndex_r4/Constant',...\n 'Position', [115 230 145 250],...\n 'const', num2str((2^ram_bits * 2^n_inputs_bits)-((bram_latency+1)*2^n_inputs_bits) - 1),...\n 'arith_type', 'Unsigned',...\n 'n_bits', num2str(ceil(log2(max_delay))),...\n 'bin_pt', '0',...\n 'explicit_period', 'on',...\n 'period', '1');\n\n reuse_block(blk, 'max_delay_chk', 'xbsIndex_r4/Relational', ...\n 'latency', '1', 'Position', [185 234 225 276], 'mode', 'a<=b');\n add_line(blk, 'delay_reg/1', 'max_delay_chk/1', 'autorouting', 'on');\n add_line(blk, 'max_delay/1', 'max_delay_chk/2', 'autorouting', 'on');\n \n reuse_block (blk,'mux_delay','xbsIndex_r4/Mux', 'Position', [250 245 275 315], 'inputs', '2');\n add_line(blk, 'mux_delay/1', 'delay_adder/1', 'autorouting', 'on');\n add_line(blk, 'max_delay_chk/1', 'mux_delay/1', 'autorouting', 'on');\n add_line(blk, 'max_delay/1', 'mux_delay/2', 'autorouting', 'on');\n\n add_line(blk, 'delay_reg/1', 'mux_delay/3', 'autorouting', 'on');\nelse\n add_line(blk, 'delay_reg/1', 'bram_rd_addrs/1', 'autorouting', 'on');\nend\n\nif n_inputs_bits > 0, \n reuse_block(blk, 'barrel_switcher', 'casper_library_reorder/barrel_switcher', ...\n 'async', async, 'n_inputs', num2str(n_inputs_bits), ...\n 'Position', [825 127 910 127+(62*(2+2^n_inputs_bits))]);\n add_line(blk, 'sync_delay/1', 'barrel_switcher/2');\n add_line(blk, 'barrel_switcher/1', 'sync_out/1');\n\n if strcmp(async, 'on'),\n add_line(blk, 'en_delay1/1', ['barrel_switcher/', num2str(3 + 2^n_inputs_bits)]);\n add_line(blk, ['barrel_switcher/', num2str(2 + 2^n_inputs_bits)], 'dvalid/1');\n end\n\n %slice out amount of rotation in barrel shifter from delay value\n reuse_block(blk, 'shift_sel', 'xbsIndex_r4/Slice', ...\n 'mode', 'Lower Bit Location + Width', ...\n 'nbits', num2str(n_inputs_bits), ...\n 'bit0', '0', 'base0', 'LSB of Input', ...\n 'Position', [190 153 220 177]);\n \n if strcmp(bram_type, 'Single Port')\n add_line(blk, 'delay_adder/1', 'shift_sel/1', 'autorouting', 'on');\n else\n add_line(blk, 'delay_reg/1', 'shift_sel/1');\n end\n\n %delay shift value to match delay latency through delay brams\n reuse_block(blk, 'delay_sel', 'xbsIndex_r4/Delay', 'latency', num2str(latency), ...\n 'reg_retiming', 'on', 'Position', [705 152 745 178]);\n add_line(blk, 'shift_sel/1', 'delay_sel/1');\n add_line(blk, 'delay_sel/1', 'barrel_switcher/1');\n\n y = 230;\n for n=0:((2^n_inputs_bits)-1),\n name = ['data_out', num2str(n)];\n reuse_block(blk, name, 'built-in/Outport', 'Port', num2str(n+2), 'Position', [975 y+3 1005 y+17]); \n add_line(blk, ['barrel_switcher/', num2str((2^n_inputs_bits)-n+1)], [name,'/1']); \n y=y+70;\n end\n\n y = 260;\n for n=0:(2^n_inputs_bits)-1,\n in_name = ['data_in', num2str(n)];\n reuse_block(blk, in_name, 'built-in/Inport', 'Port', num2str(n+4), 'Position', [570 y+8 600 y+22]) ; \n\n % delay brams\n if strcmp(bram_type, 'Single Port'),\n delay_name = ['delay_sp', num2str(n)];\n reuse_block(blk, delay_name, 'casper_library_delays/delay_bram_prog', ...\n 'Position', [705 y+5 745 y+45], ...\n 'MaxDelay', num2str(ram_bits), ...\n 'bram_latency', num2str(bram_latency));\n else\n delay_name = ['delay_dp', num2str(n)];\n reuse_block(blk, delay_name, 'casper_library_delays/delay_bram_prog_dp', ...\n 'Position',[705 y+5 745 y+45], ...\n 'ram_bits', num2str(ram_bits), 'async', async, ...\n 'bram_latency', num2str(bram_latency));\n end\n add_line(blk, [in_name, '/1'], [delay_name, '/1']); \n add_line(blk, [delay_name, '/1'], ['barrel_switcher/', num2str((2^n_inputs_bits)-n+2)]); \n\n if strcmp(async, 'on'), add_line(blk, 'en_delay0/1', [delay_name, '/3']); \n end\n \n if n > 0, \n name = ['Constant', num2str(n)];\n reuse_block(blk, name, 'xbsIndex_r4/Constant',...\n 'Position', [295 y+41 310 y+59],...\n 'const', num2str(2^n_inputs_bits-1-n),...\n 'arith_type', 'Unsigned',...\n 'n_bits', num2str(n_inputs_bits),...\n 'bin_pt', '0',...\n 'explicit_period', 'on',...\n 'period', '1' ); \n \n name = ['Relational', num2str(n)];\n reuse_block(blk, name, 'xbsIndex_r4/Relational', ...\n 'Position', [335 y+35 380 y+55], ...\n 'latency', '0', 'mode', 'a>b');\n add_line(blk, 'shift_sel/1', ['Relational', num2str(n),'/1']);\n add_line(blk, ['Constant', num2str(n),'/1'], ['Relational', num2str(n), '/2']);\n \n name = ['Convert', num2str(n)];\n reuse_block(blk, name, 'xbsIndex_r4/Convert', ...\n 'Position', [420 y+35 450 y+55], ...\n 'arith_type', 'Unsigned', 'n_bits', '1', 'bin_pt', '0') ; \n add_line(blk, ['Relational', num2str(n), '/1'], ['Convert', num2str(n), '/1']);\n\n add_name = ['AddSub', num2str(n)];\n reuse_block(blk, add_name, 'xbsIndex_r4/AddSub', ...\n 'Position', [515 y+17 550 y+53], ...\n 'mode', 'Addition', 'arith_type', 'Unsigned', ...\n 'n_bits', num2str(ram_bits), ...\n 'bin_pt', '0', 'quantization', 'Truncate', ...\n 'overflow', 'Wrap', 'latency', '0');\n add_line(blk, 'bram_rd_addrs/1', [add_name, '/1']);\n add_line(blk, ['Convert', num2str(n), '/1'], [add_name, '/2']);\n add_line(blk, [add_name, '/1'], [delay_name, '/2']);\n else,\n add_line(blk, 'bram_rd_addrs/1', [delay_name, '/2']);\n end %if\n\n y=y+60;\n end %for \nelse,\n if strcmp(bram_type, 'Single Port'), add_line(blk, 'delay_sp/1', 'data_out0/1');\n else, add_line(blk, 'delay_dp/1', 'data_out0/1');\n end\n add_line(blk, 'sync_delay/1', 'sync_out/1');\n \n if strcmp(async, 'on'), add_line(blk, 'en_delay/1', 'dvalid/1');\n end\nend\n\nclean_blocks(blk);\n \nsave_state(blk, 'defaults', defaults, varargin{:});\nclog('exiting delay_wideband_prog_init', {log_group, 'trace'}); \n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fir_dbl_tap_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fir_dbl_tap_init.m", "size": 7747, "source_encoding": "utf_8", "md5": "b5c58515b786a94c758a38b09fd6d81f", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% MeerKAT Radio Telescope Project %\n% www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (meerKAT) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction fir_dbl_tap_init(blk, varargin)\n\n defaults = {};\n check_mask_type(blk, 'fir_dbl_tap');\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n factor = get_var('factor','defaults', defaults, varargin{:});\n add_latency = get_var('latency','defaults', defaults, varargin{:});\n mult_latency = get_var('latency','defaults', defaults, varargin{:});\n coeff_bit_width = get_var('coeff_bit_width','defaults', defaults, varargin{:});\n coeff_bin_pt = get_var('coeff_bin_pt','defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state in library\n if coeff_bit_width == 0,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); \n return; \n end\n\n reuse_block(blk, 'a', 'built-in/Inport');\n set_param([blk,'/a'], ...\n 'Port', '1', ...\n 'Position', '[25 33 55 47]');\n\n reuse_block(blk, 'b', 'built-in/Inport');\n set_param([blk,'/b'], ...\n 'Port', '2', ...\n 'Position', '[25 123 55 137]');\n\n reuse_block(blk, 'c', 'built-in/Inport');\n set_param([blk,'/c'], ...\n 'Port', '3', ...\n 'Position', '[25 213 55 227]');\n\n reuse_block(blk, 'd', 'built-in/Inport');\n set_param([blk,'/d'], ...\n 'Port', '4', ...\n 'Position', '[25 303 55 317]');\n\n reuse_block(blk, 'Register0', 'xbsIndex_r4/Register');\n set_param([blk,'/Register0'], ...\n 'Position', '[315 16 360 64]');\n\n reuse_block(blk, 'Register1', 'xbsIndex_r4/Register');\n set_param([blk,'/Register1'], ...\n 'Position', '[315 106 360 154]');\n\n reuse_block(blk, 'Register2', 'xbsIndex_r4/Register');\n set_param([blk,'/Register2'], ...\n 'Position', '[315 196 360 244]');\n\n reuse_block(blk, 'coefficient', 'xbsIndex_r4/Constant');\n set_param([blk,'/coefficient'], ...\n 'const', 'factor', ...\n 'n_bits', 'coeff_bit_width', ...\n 'bin_pt', 'coeff_bin_pt', ...\n 'explicit_period', 'on', ...\n 'Position', '[165 354 285 386]');\n\n reuse_block(blk, 'Register3', 'xbsIndex_r4/Register');\n set_param([blk,'/Register3'], ...\n 'Position', '[315 286 360 334]');\n\n reuse_block(blk, 'AddSub0', 'xbsIndex_r4/AddSub');\n set_param([blk,'/AddSub0'], ...\n 'latency', 'add_latency', ...\n 'arith_type', 'Signed (2''s comp)', ...\n 'n_bits', '18', ...\n 'bin_pt', '16', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'on', ...\n 'Position', '[180 412 230 463]');\n\n reuse_block(blk, 'Mult0', 'xbsIndex_r4/Mult');\n set_param([blk,'/Mult0'], ...\n 'n_bits', '18', ...\n 'bin_pt', '17', ...\n 'latency', 'mult_latency', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'off', ...\n 'placement_style', 'Rectangular shape', ...\n 'Position', '[315 402 365 453]');\n\n reuse_block(blk, 'AddSub1', 'xbsIndex_r4/AddSub');\n set_param([blk,'/AddSub1'], ...\n 'latency', 'add_latency', ...\n 'arith_type', 'Signed (2''s comp)', ...\n 'n_bits', '18', ...\n 'bin_pt', '16', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'on', ...\n 'Position', '[180 497 230 548]');\n\n reuse_block(blk, 'Mult1', 'xbsIndex_r4/Mult');\n set_param([blk,'/Mult1'], ...\n 'n_bits', '18', ...\n 'bin_pt', '17', ...\n 'latency', 'mult_latency', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'off', ...\n 'placement_style', 'Rectangular shape', ...\n 'Position', '[315 487 365 538]');\n\n reuse_block(blk, 'a_out', 'built-in/Outport');\n set_param([blk,'/a_out'], ...\n 'Port', '1', ...\n 'Position', '[390 33 420 47]');\n\n reuse_block(blk, 'b_out', 'built-in/Outport');\n set_param([blk,'/b_out'], ...\n 'Port', '2', ...\n 'Position', '[390 123 420 137]');\n\n reuse_block(blk, 'c_out', 'built-in/Outport');\n set_param([blk,'/c_out'], ...\n 'Port', '3', ...\n 'Position', '[390 213 420 227]');\n\n reuse_block(blk, 'd_out', 'built-in/Outport');\n set_param([blk,'/d_out'], ...\n 'Port', '4', ...\n 'Position', '[390 303 420 317]');\n\n reuse_block(blk, 'real', 'built-in/Outport');\n set_param([blk,'/real'], ...\n 'Port', '5', ...\n 'Position', '[390 423 420 437]');\n\n reuse_block(blk, 'imag', 'built-in/Outport');\n set_param([blk,'/imag'], ...\n 'Port', '6', ...\n 'Position', '[390 508 420 522]');\n\n add_line(blk,'d/1','AddSub1/2', 'autorouting', 'on');\n add_line(blk,'d/1','Register3/1', 'autorouting', 'on');\n add_line(blk,'c/1','AddSub0/2', 'autorouting', 'on');\n add_line(blk,'c/1','Register2/1', 'autorouting', 'on');\n add_line(blk,'b/1','AddSub1/1', 'autorouting', 'on');\n add_line(blk,'b/1','Register1/1', 'autorouting', 'on');\n add_line(blk,'a/1','AddSub0/1', 'autorouting', 'on');\n add_line(blk,'a/1','Register0/1', 'autorouting', 'on');\n add_line(blk,'Register0/1','a_out/1', 'autorouting', 'on');\n add_line(blk,'Register1/1','b_out/1', 'autorouting', 'on');\n add_line(blk,'Register2/1','c_out/1', 'autorouting', 'on');\n add_line(blk,'coefficient/1','Mult0/1', 'autorouting', 'on');\n add_line(blk,'coefficient/1','Mult1/1', 'autorouting', 'on');\n add_line(blk,'Register3/1','d_out/1', 'autorouting', 'on');\n add_line(blk,'AddSub0/1','Mult0/2', 'autorouting', 'on');\n add_line(blk,'Mult0/1','real/1', 'autorouting', 'on');\n add_line(blk,'AddSub1/1','Mult1/2', 'autorouting', 'on');\n add_line(blk,'Mult1/1','imag/1', 'autorouting', 'on');\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:});\n\nend % fir_dbl_tap_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get_param_state.m", "ext": ".m", "path": "mlib_devel-master/casper_library/get_param_state.m", "size": 1994, "source_encoding": "utf_8", "md5": "77eacf7f9e7eed2d656b20cdfe419cf9", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://casper.berkeley.edu %\n% Copyright (C) 2010 William Mallard %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [ param_state ] = get_param_state(cursys, param_name)\n% Check if a mask parameter is enabled or disabled.\n\n mask_names = get_param(cursys, 'MaskNames');\n param_index = ismember(mask_names, param_name);\n\n mask_enables = get_param(cursys, 'MaskEnables');\n param_state = mask_enables{param_index};\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get_var.m", "ext": ".m", "path": "mlib_devel-master/casper_library/get_var.m", "size": 2305, "source_encoding": "utf_8", "md5": "435a2de952a1862c45f78c3bd3f88368", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006-2007 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction value = get_var(varname, varargin)\r\n% Find the value of varname in varargin. If varname is not found, looks\r\n% for 'defaults' and tries to find varname in there. If any of this fails,\r\n% return Nan.\r\n%\r\n% value = get_var(varname, varargin)\r\n%\r\n% varname = the variable name to retrieve (as a string).\r\n% varargin = {'varname', value, ...} pairs\r\n\r\ni = find(strcmp(varname,varargin));\r\nif i >= 1,\r\n value = varargin{i+1};\r\nelse\r\n i = find(strcmp('defaults',varargin));\r\n if i >= 1,\r\n value = get_var(varname,varargin{i+1}{:});\r\n else\r\n value = nan;\r\n end\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "tostring.m", "ext": ".m", "path": "mlib_devel-master/casper_library/tostring.m", "size": 1006, "source_encoding": "utf_8", "md5": "b3d643714b38a14e0d24db55ab592352", "text": "%Designed to convert things into strings for populating mask text boxes.\r\n%Works with 1D arrays (lists) and strings or single values.\r\n% YMMV with multidimensional arrays or matrices.\r\n\r\n\r\nfunction string = tostring( something, precision )\r\n\r\nprec = 32;\r\nif nargin > 1,\r\n if precision > 50,\r\n\tdisp(['tostring: maximum precision when converting to string is 50 digits,',precision,' provided']);\r\n\tclog(['tostring: maximum precision when converting to string is 50 digits,',precision,' provided'], 'error');\r\n end\r\n prec = precision;\r\nend\r\n \r\nif isa(something, 'char'), \r\n string = something;\r\n return;\r\nend\r\nif isa(something, 'numeric'), \r\n if length(something)>1,\r\n string = ['[',num2str(something,prec),']'];\r\n return;\r\n else,\r\n string = num2str(something,prec);\r\n return;\r\n end\r\nend\r\n\r\ndisp(['tostring: Data passed (', something, ') not numeric nor string']);\r\nclog(['tostring: Data passed (', something, ') not numeric nor string'],'error')\r\n \r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "reorder_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/reorder_init.m", "size": 22713, "source_encoding": "utf_8", "md5": "2eec3baa33bc583d333266b32d5c9e1f", "text": "% Initialize and configure the reorder block.\r\n%\r\n% reorder_init(blk, varargin)\r\n%\r\n% blk = The block to be initialize.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% map = The desired output order.\r\n% map_latency = The latency of the map block.\r\n% bram_latency = The latency of buffer BRAM blocks.\r\n% n_inputs = The number of parallel inputs to be reordered.\r\n% double_buffer = Whether to use two buffers to reorder data (instead of\r\n% doing it in-place).\r\n% bram_map = Whether to use BlockRAM for address mapping (instead of\r\n% distributed RAM.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% Meerkat Radio Telescope Project %\r\n% http://www.kat.ac.za %\r\n% Copyright (C) 2011, 2013 Andrew Martens %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction reorder_init(blk, varargin)\r\n\r\nlog_group = 'reorder_init_debug';\r\n\r\nclog('entering reorder_init', {log_group, 'trace'});\r\n% Declare any default values for arguments you might like.\r\ndefaults = { ...\r\n 'map', [0 7 1 3 2 5 6 4], ...\r\n 'n_bits', 0, ...\r\n 'map_latency', 2, ...\r\n 'bram_latency', 1, ...\r\n 'fanout_latency', 0, ...\r\n 'n_inputs', 1, ...\r\n 'double_buffer', 0, ...\r\n 'bram_map', 'on'};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\n\r\ncheck_mask_type(blk, 'reorder');\r\nmunge_block(blk, varargin{:});\r\n\r\nmap = get_var('map', 'defaults', defaults, varargin{:});\r\nn_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\r\nmap_latency = get_var('map_latency', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\nfanout_latency = get_var('fanout_latency', 'defaults', defaults, varargin{:});\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\ndouble_buffer = get_var('double_buffer', 'defaults', defaults, varargin{:});\r\nbram_map = get_var('bram_map', 'defaults', defaults, varargin{:});\r\nmux_latency = 1;\r\n\r\nyinc = 20;\r\n\r\ndelete_lines(blk);\r\nif isempty(map),\r\n clean_blocks(blk);\r\n set_param(blk, 'AttributesFormatString', '');\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting reorder_init', {log_group, 'trace'});\r\n return;\r\nend %if\r\n\r\nmap_length = length(map);\r\nmap_bits = ceil(log2(map_length));\r\nif double_buffer == 1, order = 2;\r\nelse, order = compute_order(map);\r\nend\r\norder_bits = ceil(log2(order));\r\n\r\nif (strcmp('on',bram_map)), map_memory_type = 'Block RAM';\r\nelse, map_memory_type = 'Distributed memory';\r\nend\r\n\r\n% if we are using BRAM for mapping then we need to optimise for Speed, otherwise want to optimise Space as\r\n% distributed RAM inherently fast\r\nif strcmp(bram_map, 'on'), optimize = 'Speed';\r\nelse, optimize = 'Area';\r\nend\r\n\r\nif (double_buffer < 0 || double_buffer > 1) ,\r\n clog('Double Buffer must be 0 or 1', {log_group, 'error'});\r\n error('Double Buffer must be 0 or 1');\r\nend\r\n\r\n% Non-power-of-two maps could be supported by adding a counter an a\r\n% comparitor, rather than grouping the map and address count into one\r\n% counter.\r\nif 2^map_bits ~= map_length,\r\n clog('Reorder currently only supports maps which are 2^? long.', {log_group, 'error'})\r\n error('Reorder currently only supports maps which are 2^? long.')\r\nend\r\n\r\n% make fanout as low as possible (2)\r\nrep_latency = log2(n_inputs);\r\n\r\n% en stuff\r\n% delays on way into buffer depend on double buffering \r\nif double_buffer == 0, \r\n if order == 2, pre_delay = map_latency + mux_latency; \r\n else, pre_delay = 1 + mux_latency + map_latency;\r\n end\r\nelse, pre_delay = map_latency;\r\nend\r\n\r\nreuse_block(blk, 'en', 'built-in/inport', 'Position', [25 43 55 57], 'Port', '2');\r\nreuse_block(blk, 'delay_we0', 'xbsIndex_r4/Delay', ...\r\n 'reg_retiming', 'off', 'latency', num2str(pre_delay+rep_latency), 'Position', [305 40 345 60]);\r\nadd_line(blk, 'en/1', 'delay_we0/1');\r\nreuse_block(blk, 'delay_we1', 'xbsIndex_r4/Delay', ...\r\n 'reg_retiming', 'off', 'latency', num2str(pre_delay+rep_latency), 'Position', [305 80 345 100]);\r\nadd_line(blk, 'en/1', 'delay_we1/1');\r\nreuse_block(blk, 'delay_we2', 'xbsIndex_r4/Delay', ...\r\n 'reg_retiming', 'off', 'latency', num2str(pre_delay), 'Position', [305 120 345 140]);\r\nadd_line(blk, 'en/1', 'delay_we2/1');\r\nreuse_block(blk, 'delay_valid', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\r\n 'Position', [860 80 900 100], 'latency', num2str(bram_latency+(double_buffer*2)+fanout_latency));\r\nadd_line(blk, 'delay_we1/1', 'delay_valid/1');\r\nreuse_block(blk, 'valid', 'built-in/outport', 'Position', [965 82 995 98], 'Port', '2');\r\nadd_line(blk, 'delay_valid/1', 'valid/1');\r\n\r\nreuse_block(blk, 'we_replicate', 'casper_library_bus/bus_replicate', ...\r\n 'latency', num2str(rep_latency), 'replication', num2str(n_inputs), 'misc', 'off', ...\r\n 'Position', [490 119 530 141]);\r\nadd_line(blk, 'delay_we2/1', 'we_replicate/1');\r\n\r\nreuse_block(blk, 'we_expand', 'casper_library_flow_control/bus_expand', ...\r\n 'mode', 'divisions of equal size', 'outputNum', num2str(n_inputs), ...\r\n 'outputWidth', '1', 'outputBinaryPt', '0', 'outputArithmeticType', '2', ...\r\n 'Position', [585 119 635 119+(yinc*n_inputs)]);\r\nadd_line(blk, 'we_replicate/1', 'we_expand/1');\r\n\r\n% sync stuff\r\n% delay value here is time into BRAM + time for one vector + time out of BRAM\r\nreuse_block(blk, 'sync', 'built-in/inport', 'Position', [25 3 55 17], 'Port', '1');\r\nreuse_block(blk, 'pre_sync_delay', 'xbsIndex_r4/Delay', ...\r\n 'reg_retiming', 'off', 'Position', [305 0 345 20], 'latency', num2str(pre_delay+rep_latency));\r\nadd_line(blk, 'sync/1', 'pre_sync_delay/1');\r\nreuse_block(blk, 'or', 'xbsIndex_r4/Logical', ...\r\n 'logical_function', 'OR', 'Position', [375 19 400 46]);\r\nadd_line(blk, 'delay_we0/1', 'or/2');\r\nadd_line(blk, 'pre_sync_delay/1', 'or/1');\r\nreuse_block(blk, 'sync_delay_en', 'casper_library_delays/sync_delay_en', ...\r\n 'Position', [530 5 690 25], 'DelayLen', num2str(map_length));\r\nadd_line(blk, 'or/1', 'sync_delay_en/2');\r\nadd_line(blk, 'pre_sync_delay/1', 'sync_delay_en/1');\r\nreuse_block(blk, 'post_sync_delay', 'xbsIndex_r4/Delay', ...\r\n 'reg_retiming', 'on', 'Position', [860 5 900 25], 'latency', num2str(bram_latency+(double_buffer*2)+fanout_latency));\r\nadd_line(blk, 'sync_delay_en/1', 'post_sync_delay/1');\r\nreuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [965 7 995 23], 'Port', '1');\r\nadd_line(blk, 'post_sync_delay/1', 'sync_out/1');\r\n\r\nbase = 160 + (n_inputs-1)*yinc;\r\n\r\n%Ports\r\nfor cnt=1:n_inputs,\r\n % Ports\r\n reuse_block(blk, ['din', num2str(cnt-1)], 'built-in/inport', ...\r\n 'Position', [680 base+80*(cnt-1)+43 710 base+80*(cnt-1)+57], 'Port', num2str(2+cnt));\r\n reuse_block(blk, ['delay_din', num2str(cnt-1)], 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\r\n 'Position', [760 base+80*(cnt-1)+40 800 base+80*(cnt-1)+60], 'latency', num2str(pre_delay+rep_latency));\r\n add_line(blk, ['din', num2str(cnt-1),'/1'], ['delay_din', num2str(cnt-1),'/1']);\r\n reuse_block(blk, ['dout', num2str(cnt-1)], 'built-in/outport', ...\r\n 'Position', [965 base+80*(cnt-1)+43 995 base+80*(cnt-1)+57], 'Port', num2str(2+cnt));\r\nend %for\r\n\r\nif order ~= 1,\r\n if order == 2,\r\n reuse_block(blk, 'Counter', 'xbsIndex_r4/Counter', ...\r\n 'Position', [95 base 145 base+55], 'n_bits', num2str(map_bits + order_bits), 'cnt_type', 'Free Running', ...\r\n 'use_behavioral_HDL', 'off', 'implementation', 'Fabric', 'arith_type', 'Unsigned', ...\r\n 'en', 'on', 'rst', 'on');\r\n add_line(blk, 'sync/1', 'Counter/1');\r\n add_line(blk, 'en/1', 'Counter/2');\r\n\r\n reuse_block(blk, 'Slice2', 'xbsIndex_r4/Slice', ...\r\n 'Position', [170 base+35 200 base+55], 'mode', 'Lower Bit Location + Width', ...\r\n 'nbits', num2str(map_bits));\r\n add_line(blk, 'Counter/1', 'Slice2/1');\r\n\r\n if double_buffer == 0, latency = (order-1)*map_latency;\r\n else, latency = (order-1)*map_latency + rep_latency;\r\n end \r\n reuse_block(blk, 'delay_sel', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\r\n 'Position', [305 base 345 base+20], 'latency', num2str(latency));\r\n reuse_block(blk, 'delay_d0', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\r\n 'Position', [305 base+35 345 base+55], 'latency', num2str(latency));\r\n add_line(blk, 'Slice2/1', 'delay_d0/1');\r\n\r\n end %if order == 2\r\n\r\n reuse_block(blk, 'addr_replicate', 'casper_library_bus/bus_replicate', ...\r\n 'latency', num2str(rep_latency), 'replication', num2str(n_inputs), 'misc', 'off', ...\r\n 'Position', [490 base 530 base+22]);\r\n\r\n reuse_block(blk, 'addr_expand', 'casper_library_flow_control/bus_expand', ...\r\n 'mode', 'divisions of equal size', 'outputNum', num2str(n_inputs), ...\r\n 'outputWidth', num2str(map_bits), 'outputBinaryPt', '0', 'outputArithmeticType', '0', ...\r\n 'Position', [585 base 635 base+(yinc*n_inputs)]);\r\n add_line(blk, 'addr_replicate/1', 'addr_expand/1');\r\nend %if order\r\n\r\n% Special case for reorder of order 1 (just delay)\r\nif order == 1,\r\n for cnt=1:n_inputs,\r\n % Delays\r\n reuse_block(blk, ['delay_din_bram', num2str(cnt-1)], 'casper_library_delays/delay_bram_en_plus', ...\r\n 'DelayLen', 'length(map)', 'bram_latency', 'bram_latency+fanout_latency', ...\r\n 'Position', [850 base+80*(cnt-1)+40 915 base+80*(cnt-1)+60]);\r\n\r\n % Wires\r\n add_line(blk, ['delay_din', num2str(cnt-1),'/1'], ['delay_din_bram', num2str(cnt-1),'/1']);\r\n add_line(blk, ['delay_din_bram', num2str(cnt-1),'/1'], ['dout', num2str(cnt-1),'/1']);\r\n add_line(blk, ['we_expand/',num2str(cnt)], ['delay_din_bram', num2str(cnt-1),'/2']);\r\n end %for\r\n% Case for order != 1, single-buffered\r\nelseif double_buffer == 0,\r\n\r\n % Add Dynamic Blocks and wires\r\n for cnt=1:n_inputs,\r\n % BRAMS\r\n bram_name = ['buf', num2str(cnt-1)];\r\n % if we dont specify a valid bit width, use generic BRAMs\r\n if n_bits == 0,\r\n reuse_block(blk, bram_name, 'xbsIndex_r4/Single Port RAM', ...\r\n 'depth', num2str(2^map_bits), 'optimize', 'Speed', ...\r\n 'write_mode', 'Read Before Write', 'latency', num2str(bram_latency+fanout_latency), ...\r\n 'Position', [845 base+80*(cnt-1)-17+40 910 base+80*(cnt-1)+77]);\r\n else, %otherwise use brams that help reduce fanout\r\n m = floor(n_bits/64);\r\n n_bits_in = ['[repmat(64, 1, ', num2str(m),')]'];\r\n\r\n if m ~= (n_bits/64), \r\n n = m+1;\r\n n_bits_in = ['[', n_bits_in, ', ', num2str(n_bits - (m*64)),']'];\r\n else,\r\n n = m;\r\n end\r\n bin_pts = ['[zeros(1, ', num2str(n),')]'];\r\n init_vector = ['[zeros(', num2str(2^map_bits), ',', num2str(n), ')]'];\r\n\r\n reuse_block(blk, bram_name, 'casper_library_bus/bus_single_port_ram', ...\r\n 'n_bits', n_bits_in, 'bin_pts', bin_pts, 'init_vector', init_vector, ...\r\n 'max_fanout', '1', 'mem_type', 'Block RAM', 'bram_optimization', 'Speed', ...\r\n 'async', 'off', 'misc', 'off', ...\r\n 'bram_latency', num2str(bram_latency), 'fan_latency', num2str(fanout_latency), ...\r\n 'addr_register', 'on', 'addr_implementation', 'core', ...\r\n 'din_register', 'on', 'din_implementation', 'behavioral', ...\r\n 'we_register', 'on', 'we_implementation', 'core', ...\r\n 'en_register', 'off', 'en_implementation', 'behavioral', ...\r\n 'Position', [845 base+80*(cnt-1)-17+40 910 base+80*(cnt-1)+77]);\r\n end\r\n add_line(blk, ['we_expand/',num2str(cnt)], [bram_name,'/3']);\r\n add_line(blk, ['addr_expand/',num2str(cnt)], [bram_name,'/1']);\r\n add_line(blk, ['delay_din',num2str(cnt-1),'/1'], [bram_name,'/2']);\r\n add_line(blk, [bram_name,'/1'], ['dout',num2str(cnt-1),'/1']);\r\n end\r\n\r\n %special case for order of 2 \r\n if order == 2,\r\n reuse_block(blk, 'Slice1', 'xbsIndex_r4/Slice', ...\r\n 'Position', [170 base 200 base+20], 'mode', 'Upper Bit Location + Width', ...\r\n 'nbits', num2str(order_bits));\r\n add_line(blk, 'Counter/1', 'Slice1/1');\r\n add_line(blk, 'Slice1/1', 'delay_sel/1');\r\n\r\n reuse_block(blk, 'Mux', 'xbsIndex_r4/Mux', ...\r\n 'Position', [415 base 440 base+10+20*order], 'inputs', num2str(order), 'latency', num2str(mux_latency));\r\n add_line(blk, 'delay_sel/1', 'Mux/1');\r\n add_line(blk, 'delay_d0/1', 'Mux/2');\r\n add_line(blk, 'Mux/1', 'addr_replicate/1');\r\n\r\n % Add Maps\r\n for cnt=1:order-1,\r\n mapname = ['map', num2str(cnt)];\r\n\r\n reuse_block(blk, mapname, 'xbsIndex_r4/ROM', ...\r\n 'depth', num2str(map_length), 'initVector', 'map', 'latency', num2str(map_latency), ...\r\n 'arith_type', 'Unsigned', 'n_bits', num2str(map_bits), 'bin_pt', '0', 'optimize', optimize, ...\r\n 'distributed_mem', map_memory_type, 'Position', [230 base+50*cnt+35 270 base+50*cnt+55]);\r\n reuse_block(blk, ['delay_',mapname], 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\r\n 'Position', [305 base+50*cnt+35 345 base+50*cnt+55], 'latency', [num2str((order-(cnt+1))*map_latency)]);\r\n end\r\n\r\n for cnt=1:order-1,\r\n mapname = ['map',num2str(cnt)];\r\n prevmapname = ['map',num2str(cnt-1)];\r\n if cnt == 1,\r\n add_line(blk, 'Slice2/1', 'map1/1');\r\n else,\r\n add_line(blk, [prevmapname,'/1'], [mapname,'/1'], 'autorouting', 'on');\r\n end\r\n add_line(blk, [mapname,'/1'], ['delay_',mapname,'/1']);\r\n add_line(blk, ['delay_',mapname,'/1'], ['Mux/',num2str(cnt+2)]);\r\n end %for\r\n\r\n % for order greater than 2, we use a more optimal bram configuration\r\n else,\r\n reuse_block(blk, 'Counter', 'xbsIndex_r4/Counter', ...\r\n 'n_bits', num2str(map_bits), 'cnt_type', 'Free Running', ...\r\n 'use_behavioral_HDL', 'off', 'implementation', 'Fabric', 'arith_type', 'Unsigned', 'en', 'on', 'rst', 'on', ...\r\n 'Position', [80 base+300 120 base+340]);\r\n add_line(blk, 'sync/1', 'Counter/1');\r\n add_line(blk, 'en/1', 'Counter/2');\r\n \r\n % logic to cater for resyncing\r\n reuse_block(blk, 'dsync', 'xbsIndex_r4/Delay', 'reg_retiming', 'off', 'latency', '1', 'Position', [85 base+50 115 base+70]);\r\n add_line(blk, 'sync/1', 'dsync/1');\r\n \r\n reuse_block(blk, 'msb', 'xbsIndex_r4/Slice', 'boolean_output', 'on', ...\r\n 'Position', [135 base+65 160 base+85], 'mode', 'Upper Bit Location + Width', 'nbits', '1');\r\n add_line(blk, 'Counter/1', 'msb/1');\r\n \r\n reuse_block(blk, 'edge_detect', 'casper_library_misc/edge_detect', ...\r\n 'edge', 'Falling', 'polarity', 'Active High', 'Position', [185 base+65 230 base+85]);\r\n add_line(blk, 'msb/1', 'edge_detect/1');\r\n \r\n reuse_block(blk, 'map_src', 'xbsIndex_r4/Register', ...\r\n 'en', 'on', 'rst', 'on', 'Position', [265 base+40 305 base+80]);\r\n add_line(blk, 'edge_detect/1', 'map_src/1');\r\n add_line(blk, 'dsync/1', 'map_src/2');\r\n add_line(blk, 'edge_detect/1', 'map_src/3');\r\n \r\n reuse_block(blk, 'dmap_src', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', 'latency', num2str(map_latency), ...\r\n 'Position', [330 base+50 370 base+70]);\r\n add_line(blk, 'map_src/1', 'dmap_src/1');\r\n\r\n reuse_block(blk, 'map_mux', 'xbsIndex_r4/Mux', 'latency', num2str(mux_latency), 'inputs', '2', ...\r\n 'Position', [440 base+176 470 base+264]);\r\n add_line(blk, 'dmap_src/1', 'map_mux/1');\r\n add_line(blk, 'map_mux/1', 'addr_replicate/1');\r\n\r\n % lookup of current map \r\n reuse_block(blk, 'daddr0', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', 'latency', '1', 'Position', [265 base+310 300 base+330]);\r\n add_line(blk, 'Counter/1', 'daddr0/1');\r\n \r\n % memory holding current map \r\n reuse_block(blk, 'current_map', 'casper_library_bus/bus_dual_port_ram', ...\r\n 'n_bits', num2str(map_bits), ...\r\n 'bin_pts', '0', ...\r\n 'init_vector', ['[0:',num2str((2^map_bits)-1),']'''], ...\r\n 'max_fanout', '1', ...\r\n 'mem_type', map_memory_type, 'bram_optimization', 'Speed', ...\r\n 'async_a', 'off', 'async_b', 'off', 'misc', 'off', ...\r\n 'bram_latency', num2str(map_latency), ...\r\n 'fan_latency', num2str(1 + map_latency + 1), ...\r\n 'addra_register', 'on', 'addra_implementation', 'core', ...\r\n 'dina_register', 'off', 'dina_implementation', 'behavioral', ...\r\n 'wea_register', 'on', 'wea_implementation', 'core', ...\r\n 'addrb_register', 'off', 'addra_implementation', 'behavioral', ...\r\n 'dinb_register', 'off', 'dinb_implementation', 'behavioral', ...\r\n 'web_register', 'off', 'web_implementation', 'behavioral', ...\r\n 'Position', [320 base+150 380 base+280]);\r\n \r\n add_line(blk, 'daddr0/1', 'current_map/4');\r\n add_line(blk, 'current_map/2', 'map_mux/3');\r\n \r\n reuse_block(blk, 'term', 'built-in/Terminator', 'Position', [395 base+175 415 base+195]);\r\n add_line(blk, 'current_map/1', 'term/1');\r\n\r\n if strcmp(bram_map, 'on'),\r\n reuse_block(blk, 'blank', 'xbsIndex_r4/Constant', ...\r\n 'const', '0', 'arith_type', 'Unsigned', 'n_bits', num2str(map_bits), 'bin_pt', '0', ...\r\n 'explicit_period', 'on', 'period', '1', 'Position', [240 base+237 255 base+253]);\r\n add_line(blk, 'blank/1', 'current_map/5'); \r\n \r\n reuse_block(blk, 'never', 'xbsIndex_r4/Constant', ...\r\n 'const', '0', 'arith_type', 'Boolean', 'explicit_period', 'on', 'period', '1', ...\r\n 'Position', [265 base+257 280 base+273]);\r\n add_line(blk, 'never/1', 'current_map/6'); \r\n end\r\n \r\n reuse_block(blk, 'den', 'xbsIndex_r4/Delay', 'reg_retiming', 'off', ...\r\n 'latency', num2str(1 + map_latency), ...\r\n 'Position', [265 base+400 385 base+420]);\r\n add_line(blk, 'en/1', 'den/1');\r\n add_line(blk, 'den/1', 'current_map/3', 'autorouting', 'on'); \r\n \r\n reuse_block(blk, 'daddr1', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\r\n 'latency', num2str(map_latency), ...\r\n 'Position', [320 base+310 380 base+330]);\r\n add_line(blk, 'daddr0/1', 'daddr1/1');\r\n add_line(blk, 'daddr1/1', 'map_mux/2');\r\n add_line(blk, 'daddr1/1', 'current_map/1', 'autorouting', 'on');\r\n\r\n % memory holding change to current map\r\n reuse_block(blk, 'map_mod', 'xbsIndex_r4/ROM', ...\r\n 'depth', num2str(map_length), 'initVector', 'map', 'latency', num2str(map_latency), ...\r\n 'arith_type', 'Unsigned', 'n_bits', num2str(map_bits), 'bin_pt', '0', 'optimize', optimize, ...\r\n 'distributed_mem', map_memory_type, 'Position', [520 base+194 570 base+246]);\r\n add_line(blk, 'map_mux/1', 'map_mod/1');\r\n\r\n reuse_block(blk, 'dnew_map', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\r\n 'latency', '1', 'Position', [620 base+210 645 base+230]);\r\n add_line(blk, 'map_mod/1', 'dnew_map/1');\r\n add_line(blk, 'dnew_map/1', 'current_map/2', 'autorouting', 'on');\r\n\r\n end %if order == 2\r\n\r\n% case for order > 1, double-buffered\r\nelse, %TODO fanout for signals into wr_addr and rw_mode for many inputs not handled\r\n reuse_block(blk, 'Slice1', 'xbsIndex_r4/Slice', ...\r\n 'Position', [170 base 200 base+20], 'mode', 'Upper Bit Location + Width', ...\r\n 'nbits', '1');\r\n add_line(blk, 'Counter/1', 'Slice1/1');\r\n add_line(blk, 'Slice1/1', 'delay_sel/1');\r\n\r\n % Add Dynamic Blocks\r\n for cnt=1:n_inputs,\r\n % BRAMS\r\n reuse_block(blk, ['dbl_buffer',num2str(cnt-1)], 'casper_library_reorder/dbl_buffer', ...\r\n 'Position', [845 base+80*(cnt-1)-17+40 910 base+80*(cnt-1)+77], 'depth', num2str(2^map_bits), ...\r\n 'latency', num2str(bram_latency+fanout_latency));\r\n end\r\n\r\n % Add Maps\r\n mapname = 'map1';\r\n reuse_block(blk, mapname, 'xbsIndex_r4/ROM', ...\r\n 'depth', num2str(map_length), 'initVector', 'map', 'latency', num2str(map_latency), ...\r\n 'arith_type', 'Unsigned', 'n_bits', num2str(map_bits), 'bin_pt', '0', ...\r\n 'distributed_mem', map_memory_type, 'Position', [230 base+15+70 270 base+35+70]);\r\n add_line(blk, 'Slice2/1', 'map1/1');\r\n add_line(blk, 'map1/1', 'addr_replicate/1');\r\n\r\n % Add dynamic wires\r\n for cnt=1:n_inputs\r\n bram_name = ['dbl_buffer',num2str(cnt-1)];\r\n add_line(blk, 'delay_d0/1', [bram_name,'/2']);\r\n add_line(blk, ['addr_expand/',num2str(cnt)], [bram_name,'/3']);\r\n add_line(blk, ['we_expand/',num2str(cnt)], [bram_name,'/5']);\r\n add_line(blk, 'delay_sel/1', [bram_name,'/1']);\r\n add_line(blk, ['delay_din',num2str(cnt-1),'/1'], [bram_name,'/4']);\r\n add_line(blk, [bram_name,'/1'], ['dout',num2str(cnt-1),'/1']);\r\n end\r\nend\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('order=%d', order);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\nclog('exiting reorder_init', {log_group, 'trace'});\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_expand_callback.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_expand_callback.m", "size": 2941, "source_encoding": "utf_8", "md5": "a9578b135a2cf3ba7b12b59590d8ad04", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Meerkat radio telescope project %\n% www.kat.ac.za %\n% Copyright (C) Andrew Martens 2011 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_expand_callback()\n\nclog('entering bus_expand_callback', 'trace');\n\nblk = gcb;\n\ncheck_mask_type(blk, 'bus_expand');\n\noutputToWorkspace = get_param(blk, 'outputToWorkspace');\nmode = get_param(blk, 'mode');\noutputWidth = str2double(get_param(blk, 'outputWidth'));\n\nmask_names = get_param(blk, 'MaskNames');\nmask_enables = get_param(blk, 'MaskEnables');\n\nif strcmp(mode, 'divisions of arbitrary size'),\n en = 'off';\n set_param(blk, 'outputNum', num2str(length(outputWidth)));\nelse\n en = 'on';\nend\n\nmask_enables{ismember(mask_names, 'outputNum')} = en;\nmask_enables{ismember(mask_names, 'variablePrefix')} = outputToWorkspace;\nmask_enables{ismember(mask_names, 'outputToModelAsWell')} = outputToWorkspace;\nset_param(gcb, 'MaskEnables', mask_enables);\n\ntemp = get_param(blk, 'MaskPrompts');\nif strcmp(en, 'off'),\n temp(3) = {'Output width [msb ... lsb]:'};\n temp(4) = {'Output binary point position [msb ... lsb]:'};\n temp(5) = {'Output arithmetic type (ufix=0, fix=1, bool=2) [msb ... lsb]:'};\nelse\n temp(3) = {'Output width:'};\n temp(4) = {'Output binary point position:'};\n temp(5) = {'Output arithmetic type (ufix=0, fix=1, bool=2):'};\nend\nset_param(blk, 'MaskPrompts', temp);\n \nclog('exiting bus_expand_callback', 'trace');\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "update_casper_blocks.m", "ext": ".m", "path": "mlib_devel-master/casper_library/update_casper_blocks.m", "size": 5609, "source_encoding": "utf_8", "md5": "c520d2a32e492de75f7aec5808065f24", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2013 David MacMahon\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% This function updates casper_library and xps_library blocks in sys using the\n% most recent library versions. Mask parameters are copied over whenever\n% possible. If sys is a block diagram and is not a library, its solver\n% parameters are updated using xlConfigureSolver.\n%\n% varargin is for experts only! It can be used to specify extra options to\n% find_system.\nfunction update_casper_blocks(sys, varargin)\n\n % Clear last dumped exception to ensure that all exceptions are shown.\n dump_exception([]);\n\n % For now, we require that sys is either an unlinked subsytem or a\n % block_diagram\n type = get_param(sys,'Type');\n if strcmpi(type, 'block')\n % Make sure it is subsystem that is not linked to a library\n block_type = get_param(sys,'BlockType');\n if ~strcmpi(block_type, 'SubSystem')\n error('Block %s is not a SubSystem', sys);\n end\n link_status = get_param(sys,'LinkStatus');\n if ~strcmpi(link_status, 'none')\n error('SubSystem block %s appears to be linked to a library', sys);\n end\n elseif strcmpi(type, 'block_diagram')\n % If it is not a library\n if strcmpi(get_param(sys, 'LibraryType'), 'None')\n fprintf('configuring solver for block diagram %s...\\n', sys);\n xlConfigureSolver(sys);\n end\n else\n error('%s is not a block diagram or a block', sys);\n end\n \n % First, deal with the special cases of blocks whose names\n % have changed. These can cause broken library links which\n % will prevent the rest of this script finding these blocks.\n special_blocks = {'xps_library/XSG core config', ...\n 'xps_library/software register', ...\n 'xps_library/Software BRAM', ...\n 'xps_library/Software FIFO', ...\n };\n \n for n = 1:length(special_blocks)\n blks = find_system(sys, 'LookUnderMasks', 'all', ...\n 'SourceBlock', special_blocks{n});\n for m = 1:length(blks)\n set_param(blks{m}, 'SourceBlock', ...\n casper_library_forwarding_table(special_blocks{n}));\n end\n end\n \n fprintf('searching for CASPER blocks to update in %s...', sys);\n\n ref_blks = find_system(sys, ...\n 'RegExp', 'on', ...\n 'LookUnderMasks', 'all', ...\n 'FollowLinks', 'off', ...\n varargin{:}, ...\n 'ReferenceBlock', '(casper|xps)_library');\n\n %fprintf('found %d blocks with ReferenceBlock\\n', length(ref_blks));\n %for k = 1:length(ref_blks)\n % fprintf(' %3d %s\\n', k, ref_blks{k});\n %end\n \n anc_blks = find_system(sys, ...\n 'RegExp', 'on', ...\n 'LookUnderMasks', 'all', ...\n 'FollowLinks', 'off', ...\n varargin{:}, ...\n 'AncestorBlock', '(casper|xps)_library');\n\n %fprintf('found %d blocks with AncestorBlock\\n', length(anc_blks));\n %for k = 1:length(anc_blks)\n % fprintf(' %3d %s\\n', k, anc_blks{k});\n %end\n\n % Concatenate the lists of blocks then sort. Sorting the list optimizes the\n % culling process that follows.\n blks = sort([ref_blks; anc_blks]);\n\n % Even though we say \"FollowLinks=off\", find_system will still search through\n % block's with disabled links. To make sure we don't update blocks inside\n % subsystems with disabled links, we need to cull the list of blocks. For\n % each block found, we remove any blocks that start with \"block_name/\".\n keepers = ones(size(blks));\n for k = 1:length(blks)\n % If this block has not yet been culled, cull its sub-blocks. (If it has\n % already been culled, then its sub-blocks have also been culled already.)\n if keepers(k)\n pattern = ['^', blks{k}, '/'];\n keepers(find(cellfun('length', regexp(blks, pattern)))) = 0;\n end\n end\n blks = blks(find(keepers));\n\n fprintf('found %d\\n', length(blks));\n\n for k = 1:length(blks)\n fprintf('updating block %s...\\n', blks{k});\n update_casper_block(blks{k});\n end\n\n % Don't show done message for zero blocks\n if length(blks) > 0\n fprintf('done updating %d blocks in %s\\n', length(blks), sys);\n end\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "reuse_block.m", "ext": ".m", "path": "mlib_devel-master/casper_library/reuse_block.m", "size": 6803, "source_encoding": "utf_8", "md5": "f620e6db62266a70cf21654582ac4a59", "text": "% Instantiate a block named 'name' from library template 'refblk', \r\n% if no such block already exists. Otherwise, just configure that\r\n% block with any parameter, value pairs provided in varargin.\r\n% If refblk is has an '_init' function, this may still need to be\r\n% called after this function is called.\r\n%\r\n% reuse_block(blk, name, refblk, varargin)\r\n%\r\n% blk = the overarching system\r\n% name = the name of the block to instantiate\r\n% refblk = the library block to instantiate\r\n% varargin = {'varname', 'value', ...} pairs\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% MeerKAT Radio Telescope Project %\r\n% www.kat.ac.za %\r\n% Copyright (C) 2013 Andrew Martens (meerKAT) %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction reuse_block(blk, name, refblk, varargin)\r\n\r\n% Wrap whole function in try/catch\r\ntry\r\n\r\n existing_blks = find_system(blk, ...\r\n 'lookUnderMasks', 'all', 'FollowLinks','on', ...\r\n 'SearchDepth', 1, 'Name', name);\r\n\r\n % Just add block straight away if does not yet exist\r\n if isempty(existing_blks)\r\n add_block(refblk, [blk,'/',name], 'Name', name, varargin{:});\r\n % Done!\r\n return\r\n end\r\n\r\n % If find_system returned more than one block (should \"never\" happen, but\r\n % sometimes it does!)\r\n if length(existing_blks) > 1\r\n % Get their handles to see whether they are really the same block\r\n handles = cell(size(existing_blks));\r\n for k = 1:length(existing_blks)\r\n handles{k} = num2str(get_param(existing_blks{k}, 'Handle'));\r\n end\r\n\r\n % If more than one handle (should \"really never\" happen...)\r\n if length(unique(handles)) > 1\r\n error('casper:MultipleBlocksForName', ...\r\n 'More than one block in \"%s\" has name \"%s\"', blk, name);\r\n end\r\n end\r\n\r\n % A block with that name does exist, so re-use it\r\n existing_blk = existing_blks{1};\r\n \r\n %check Link status\r\n link_status = get_param(existing_blk, 'StaticLinkStatus');\r\n \r\n %inactive link (link disabled but not broken) so get AncestorBlock\r\n if strcmp(link_status, 'inactive'),\r\n source = get_param(existing_blk, 'AncestorBlock');\r\n\r\n %resolved link (link in place) so get ReferenceBlock\r\n elseif strcmp(link_status, 'resolved'),\r\n source = get_param(existing_blk, 'ReferenceBlock'); \r\n \r\n %no link (broken link, never existed, or built-in) so get block type \r\n elseif strcmp(link_status, 'none'),\r\n block_type = get_param(existing_blk, 'BlockType');\r\n\r\n %if weird (subsystem or s-function not from library) \r\n if strcmp(block_type, 'SubSystem') || strcmp(block_type, 'S-Function'),\r\n clog([name,': built-in/',block_type,' so forcing replacement'], 'reuse_block_debug');\r\n source = '';\r\n else\r\n %assuming built-in\r\n source = strcat('built-in/',block_type);\r\n end\r\n \r\n %implicit library block\r\n elseif strcmp(link_status, 'implicit'),\r\n \r\n anc_block = get_param(existing_blk, 'AncestorBlock');\r\n %we have a block in the library derived from another block\r\n if ~isempty(anc_block),\r\n source = anc_block;\r\n %we have a block without a source or built-in\r\n else,\r\n block_type = get_param(existing_blk, 'BlockType');\r\n\r\n %if weird (subsystem or s-function not from library) \r\n if strcmp(block_type, 'SubSystem') || strcmp(block_type, 'S-Function'),\r\n clog([name,': built-in/',block_type,' so forcing replacement'], 'reuse_block_debug');\r\n source = '';\r\n else,\r\n %assuming built-in\r\n source = strcat('built-in/',block_type);\r\n end\r\n end %if ~isempty\r\n else,\r\n clog([name,' not a library block and not built-in so force replace'], 'reuse_block_debug');\r\n source = '';\r\n end\r\n\r\n % If source is a cell, take its first element so we can log it\r\n if iscell(source)\r\n % TODO Warn if length(source) > 1?\r\n source = source{1};\r\n end\r\n\r\n % Change newlines in source to spaces\r\n source = strrep(source, char(10), ' ');\r\n \r\n % Do case-insensitive string comparison\r\n if strcmpi(source, refblk),\r\n msg = sprintf('%s is already a \"%s\" so just setting parameters', name, source);\r\n clog(msg, {'reuse_block_debug', 'reuse_block_reuse'});\r\n if ~isempty(varargin),\r\n set_param([blk,'/',name], varargin{:});\r\n end\r\n else,\r\n if evalin('base','exist(''casper_force_reuse_block'')') ...\r\n && evalin('base','casper_force_reuse_block')\r\n msg = sprintf('%s is a \"%s\" and want \"%s\" but reuse is being forced', name, source, refblk);\r\n % Log as reuse_block_replace even though reuse is being forced\r\n clog(msg, {'reuse_block_debug', 'reuse_block_replace'});\r\n set_param([blk,'/',name], varargin{:});\r\n else\r\n msg = sprintf('%s is a \"%s\" but want \"%s\" so replacing', name, source, refblk);\r\n clog(msg, {'reuse_block_debug', 'reuse_block_replace'});\r\n delete_block([blk,'/',name]);\r\n add_block(refblk, [blk,'/',name], 'Name', name, varargin{:});\r\n end\r\n end\r\ncatch ex\r\n dump_and_rethrow(ex)\r\nend % try/catch\r\nend % function\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_register_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_register_init.m", "size": 8416, "source_encoding": "utf_8", "md5": "56479e2951c05003310a5480efa71460", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_register_init(blk, varargin)\n log_group = 'bus_register_init_debug';\n\n clog('entering bus_register_init', {log_group, 'trace'});\n defaults = { ...\n 'n_bits', [8], ...\n 'reset', 'on', ...\n 'cmplx', 'on', ...\n 'enable', 'on', ...\n 'misc', 'on'};\n \n check_mask_type(blk, 'bus_register');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 80;\n ypos = 50; yinc = 50;\n\n port_w = 30; port_d = 14;\n bus_expand_w = 50;\n bus_compress_w = 50;\n reg_w = 50; reg_d = 60;\n del_w = 30; del_d = 20;\n\n reset = get_var('reset', 'defaults', defaults, varargin{:});\n enable = get_var('enable', 'defaults', defaults, varargin{:});\n cmplx = get_var('cmplx', 'defaults', defaults, varargin{:});\n n_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n len = length(n_bits);\n\n delete_lines(blk);\n\n %default state, do nothing \n if isempty(n_bits),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_register_init', {log_group, 'trace'});\n return;\n end\n\n if strcmp(cmplx,'on'), n_bits = 2*n_bits; end\n\n %input ports\n port_no = 1;\n ypos_tmp = ypos + reg_d*len/2;\n reuse_block(blk, 'din', 'built-in/inport', ...\n 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + reg_d*len;\n port_no = port_no + 1;\n\n if strcmp(reset, 'on'),\n reuse_block(blk, 'rst', 'built-in/inport', ...\n 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + reg_d*len;\n port_no = port_no + 1;\n end\n\n if strcmp(enable, 'on'),\n reuse_block(blk, 'en', 'built-in/inport', ...\n 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + reg_d*len;\n port_no = port_no + 1;\n end\n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/inport', ...\n 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n end\n\n xpos = xpos + xinc + port_w/2; \n ypos_tmp = ypos + reg_d*len/2; %reset ypos\n\n %data bus expand\n reuse_block(blk, 'din_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', ['[',num2str(n_bits),']'], ...\n 'outputBinaryPt', ['[',num2str(zeros(1, length(n_bits))),']'], ...\n 'outputArithmeticType', ['[',num2str(zeros(1, length(n_bits))),']'], ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-reg_d*len/2 xpos+bus_expand_w/2 ypos_tmp+reg_d*len/2]);\n add_line(blk, 'din/1', 'din_expand/1');\n ypos_tmp = ypos_tmp + reg_d*len + yinc;\n\n %reset bus expand\n if strcmp(reset, 'on'),\n reuse_block(blk, 'rst_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', ...\n 'outputNum', num2str(length(n_bits)), ...\n 'outputWidth', '1', 'outputBinaryPt', '0', ...\n 'outputArithmeticType', '2', 'show_format', 'on', ...\n 'outputToWorkspace', 'off', 'variablePrefix', '', ...\n 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-reg_d*len/2 xpos+bus_expand_w/2 ypos_tmp+reg_d*len/2]);\n add_line(blk, 'rst/1', 'rst_expand/1');\n ypos_tmp = ypos_tmp + reg_d*len + yinc;\n end\n\n %enable bus expand\n if strcmp(enable, 'on'),\n reuse_block(blk, 'en_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', ...\n 'outputNum', num2str(length(n_bits)), ...\n 'outputWidth', '1', 'outputBinaryPt', '0', ...\n 'outputArithmeticType', '2', 'show_format', 'on', ...\n 'outputToWorkspace', 'off', 'variablePrefix', '', ...\n 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-reg_d*len/2 xpos+bus_expand_w/2 ypos_tmp+reg_d*len/2]);\n add_line(blk, 'en/1', 'en_expand/1');\n end\n\n xpos = xpos + xinc + bus_expand_w/2;\n\n %register layer\n ypos_tmp = ypos; %reset ypos \n\n for index = 1:len,\n reg_name = ['reg',num2str(index)];\n %data\n reuse_block(blk, reg_name, 'xbsIndex_r4/Register', ...\n 'rst', reset, 'en', enable, ...\n 'Position', [xpos-reg_w/2 ypos_tmp xpos+reg_w/2 ypos_tmp+reg_d-20]);\n ypos_tmp = ypos_tmp + reg_d;\n\n add_line(blk, ['din_expand/',num2str(index)], [reg_name,'/1']);\n port_index = 2;\n if strcmp(reset, 'on'), add_line(blk, ['rst_expand/',num2str(index)], [reg_name,'/',num2str(port_index)]); \n port_index=port_index+1;\n end\n if strcmp(enable, 'on'), add_line(blk, ['en_expand/',num2str(index)], [reg_name,'/',num2str(port_index)]); end\n end\n \n if strcmp(misc, 'on'),\n reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ...\n 'latency', '1', 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)-del_d/2+(port_no-1)*yinc xpos+del_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+(port_no-1)*yinc+del_d/2]);\n add_line(blk, 'misci/1', 'dmisc/1');\n ypos_tmp = ypos_tmp + reg_d;\n end\n \n %create bus again\n ypos_tmp = ypos + reg_d*len/2;\n xpos = xpos + xinc + bus_expand_w/2;\n\n reuse_block(blk, 'dout_compress', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(len), ...\n 'Position', [xpos-bus_compress_w/2 ypos_tmp-reg_d*len/2 xpos+bus_compress_w/2 ypos_tmp+reg_d*len/2]);\n \n for index = 1:len,\n add_line(blk, ['reg',num2str(index),'/1'], ['dout_compress/',num2str(index)]);\n end\n\n %output port/s\n ypos_tmp = ypos + reg_d*len/2;\n xpos = xpos + xinc + bus_compress_w/2;\n reuse_block(blk, 'dout', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, ['dout_compress/1'], ['dout/1']);\n ypos_tmp = ypos_tmp + yinc + port_d/2; \n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misco', 'built-in/outport', ...\n 'Port', '2', ... \n 'Position', [xpos-port_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+((port_no-1)*yinc)-port_d/2 xpos+port_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+((port_no-1)*yinc)+port_d/2]);\n\n add_line(blk, 'dmisc/1', 'misco/1');\n end\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_register_init', {log_group, 'trace'});\n\nend %function bus_register_init\n\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "dsp48e_bram_vacc_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/dsp48e_bram_vacc_init.m", "size": 3432, "source_encoding": "utf_8", "md5": "b71af83720863c419ea3b9fa21ccfbd4", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://casper.berkeley.edu %\n% Copyright (C) 2010 William Mallard %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction dsp48e_bram_vacc_init (blk, varargin)\n% Initialize and configure a simple_bram_vacc block.\n%\n% dsp48e_bram_vacc_init(blk, varargin)\n%\n% blk = The block to configure.\n% varargin = {'varname', 'value', ...} pairs.\n%\n% Valid varnames:\n% * vec_len\n% * arith_type\n% * bin_pt_in\n% * n_bits_out\n\n% Set default vararg values.\ndefaults = { ...\n 'vec_len', 8, ...\n 'arith_type', 'Unsigned', ...\n 'bin_pt_in', 0, ...\n 'n_bits_out', 32, ...\n};\n\n% Skip init script if mask state has not changed.\nif same_state(blk, 'defaults', defaults, varargin{:}),\n return\nend\n\n% Verify that this is the right mask for the block.\ncheck_mask_type(blk, 'dsp48e_bram_vacc');\n\n% Disable link if state changes from default.\nmunge_block(blk, varargin{:});\n\n% Retrieve input fields.\nvec_len = get_var('vec_len', 'defaults', defaults, varargin{:});\narith_type = get_var('arith_type', 'defaults', defaults, varargin{:});\nbin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:});\nn_bits_out = get_var('n_bits_out', 'defaults', defaults, varargin{:});\n\n% Validate input fields.\n\nif (vec_len < 6),\n errordlg([blk, ': Vector length must be greater than 5.']);\n return\nend\n\nif (bin_pt_in < 0),\n errordlg([blk, ': Binary point must be non-negative.']);\n return\nend\n\nif (bin_pt_in > n_bits_out),\n errordlg([blk, ': Input binary point cannot exceed output bit width.']);\n return\nend\n\nif (n_bits_out < 1),\n errordlg([blk, ': Bit width must be greater than 0.']);\n return\nend\n\nif (n_bits_out > 32),\n errordlg([blk, ': Bit width cannot exceed 32.']);\n return\nend\n\n% Update sub-block parameters.\n\nset_param([blk, '/Reinterpret'], 'arith_type', arith_type)\n\n% Save block state to stop repeated init script runs.\nsave_state(blk, 'defaults', defaults, varargin{:});\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_mux_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_mux_init.m", "size": 8977, "source_encoding": "utf_8", "md5": "e6b13766a778f08c129db349ec3c5276", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (andrew@ska.ac.za) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_mux_init(blk, varargin)\n log_group = 'bus_mux_init_debug';\n\n clog('entering bus_mux_init', {log_group, 'trace'});\n defaults = {\n 'n_inputs', 1, ...\n 'n_bits', [8 7 3 4], ...\n 'mux_latency', 0, ...\n 'cmplx', 'off', ...\n 'misc', 'off'};\n \n check_mask_type(blk, 'bus_mux');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 150;\n ypos = 50; yinc = 60;\n\n port_w = 30; port_d = 14;\n muxi_d = 30;\n bus_expand_w = 60;\n bus_create_w = 60;\n mux_w = 50;\n del_w = 30; del_d = 20;\n\n n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\n n_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\n mux_latency = get_var('mux_latency', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n cmplx = get_var('cmplx', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state, do nothing \n if n_inputs == 0,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_mux_init', {log_group, 'trace'});\n return;\n end\n \n len = length(n_bits);\n if strcmp(cmplx, 'on'), n_bits = 2*n_bits; end\n\n % the mux depth depends on\n % whether splitting one input, or many\n if n_inputs == 1, depth = muxi_d*len;\n else, depth = muxi_d*n_inputs;\n end\n\n % if doing one, number muxes == 1, otherwise == number of elements\n if n_inputs == 1, n_muxes = 1;\n else, n_muxes = len;\n end\n\n %%%%%%%%%%%%%%%%%%%%\n % input port layer %\n %%%%%%%%%%%%%%%%%%%%\n\n xpos = xpos + port_w/2;\n ypos_tmp = ypos + (n_muxes*muxi_d)/2; \n\n reuse_block(blk, 'sel', 'built-in/inport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n \n % for the data ports, if only one input then are to mux between separate components of the same\n % bus, otherwise are to mux between components of separate busses\n ypos_tmp = ypos_tmp + (n_muxes*muxi_d)/2 + yinc;\n\n for n = 0:n_inputs-1, \n ypos_tmp = ypos_tmp + depth/2;\n reuse_block(blk, ['d',num2str(n)], 'built-in/inport', ...\n 'Port', num2str(n+2), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + depth/2 + yinc;\n end %for\n\n if strcmp(misc, 'on'),\n ypos_tmp = ypos + (yinc + (n_muxes*muxi_d)) + max(n_muxes, n_inputs)*(depth + yinc) + del_d/2;\n reuse_block(blk, 'misci', 'built-in/inport', ...\n 'Port', num2str(n_inputs+2), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n end\n\n xpos = xpos + xinc + port_w/2; \n\n %%%%%%%%%%%%%%%%%%%%%%%%%\n % data bus expand layer %\n %%%%%%%%%%%%%%%%%%%%%%%%%\n\n if n_inputs == 1, inputs = len;\n else, inputs = n_inputs;\n end\n\n xpos = xpos + bus_expand_w/2; \n ypos_tmp = ypos + (n_muxes*muxi_d)/2;\n\n % one bus_expand for sel input\n reuse_block(blk, 'sel_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', ...\n 'outputNum', num2str(n_muxes), ...\n 'outputWidth', num2str(ceil(log2(inputs))), 'outputBinaryPt', '0', 'outputArithmeticType', '0', ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-(n_muxes*muxi_d)/2 xpos+bus_expand_w/2 ypos_tmp+(n_muxes*muxi_d)/2]);\n add_line(blk, 'sel/1', 'sel_expand/1');\n\n ypos_tmp = ypos_tmp + (n_muxes*muxi_d)/2 + yinc;\n\n % one bus_expand block for each input\n for n = 0:n_inputs-1,\n ypos_tmp = ypos_tmp + depth/2;\n reuse_block(blk, ['expand', num2str(n)], 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', mat2str(n_bits), ...\n 'outputBinaryPt', ['[',num2str(zeros(1, length(n_bits))),']'], ...\n 'outputArithmeticType', ['[',num2str(zeros(1, length(n_bits))),']'], ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-depth/2 xpos+bus_expand_w/2 ypos_tmp+depth/2]);\n add_line(blk, ['d', num2str(n), '/1'], ['expand', num2str(n), '/1']);\n ypos_tmp = ypos_tmp + depth/2 + yinc;\n end %for\n\n xpos = xpos + xinc + bus_expand_w/2;\n\n %%%%%%%%%%%%%\n % mux layer %\n %%%%%%%%%%%%%\n\n xpos = xpos + mux_w/2;\n ypos_tmp = ypos + (n_muxes*muxi_d) + yinc;\n\n for n = 0:n_muxes-1,\n ypos_tmp = ypos_tmp + depth/2;\n \n reuse_block(blk, ['mux', num2str(n)], 'xbsIndex_r4/Mux', ...\n 'inputs', num2str(inputs), 'latency', num2str(mux_latency), ...\n 'Position', [xpos-mux_w/2 ypos_tmp-depth/2 xpos+mux_w/2 ypos_tmp+depth/2]);\n \n add_line(blk, ['sel_expand/', num2str(n+1)], ['mux', num2str(n), '/1']);\n\n % take all mux inputs from single input\n if n_inputs == 1, \n for index = 1:len, add_line(blk, ['expand0/',num2str(index)], ['mux0/',num2str(index+1)]);\n end %for\n %or take a mux input from each input\n else, \n for in_index = 0:n_inputs-1, \n add_line(blk, ['expand', num2str(in_index), '/', num2str(n+1)], ['mux',num2str(n), '/', num2str(in_index+2)])\n end\n end %if\n ypos_tmp = ypos_tmp + depth/2 + yinc;\n end %for n_muxes\n \n if strcmp(misc, 'on'),\n ypos_tmp = ypos + (yinc + (n_muxes*muxi_d)) + max(n_muxes, n_inputs)*(depth + yinc) + del_d/2;\n reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(mux_latency), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, 'misci/1', 'dmisc/1');\n ypos_tmp = ypos_tmp + del_d/2 + yinc;\n end\n\n xpos = xpos + mux_w/2 + xinc;\n\n %%%%%%%%%%%%%%%%%%%%%%%\n % bus creation layer %\n %%%%%%%%%%%%%%%%%%%%%%%\n\n xpos = xpos + bus_create_w/2;\n ypos_tmp = ypos + (n_muxes*muxi_d)/2;\n \n reuse_block(blk, 'd_bussify', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(n_muxes), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-(n_muxes*muxi_d)/2 xpos+bus_create_w/2 ypos_tmp+(n_muxes*muxi_d)/2]);\n\n for n = 0:n_muxes-1,\n add_line(blk, ['mux', num2str(n), '/1'], ['d_bussify/', num2str(n+1)])\n end %for\n \n xpos = xpos + xinc + bus_create_w/2;\n\n %%%%%%%%%%%%%%%%%%%%%\n % output port layer %\n %%%%%%%%%%%%%%%%%%%%%\n\n xpos = xpos + port_w/2;\n ypos_tmp = ypos + (n_muxes*muxi_d)/2;\n\n reuse_block(blk, 'out', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, 'd_bussify/1', 'out/1');\n ypos_tmp = ypos + (n_muxes*muxi_d)/2 + yinc;\n\n if strcmp(misc, 'on'),\n ypos_tmp = ypos + (yinc + (n_muxes*muxi_d)) + max(n_muxes, n_inputs)*(depth + yinc) + del_d/2;\n reuse_block(blk, 'misco', 'built-in/outport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n\n add_line(blk, 'dmisc/1', 'misco/1');\n end\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_mux_init', {log_group, 'trace'});\n\nend %function bus_mux_init\n\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set_mask_params.m", "ext": ".m", "path": "mlib_devel-master/casper_library/set_mask_params.m", "size": 3193, "source_encoding": "utf_8", "md5": "a43b90f45d40808d05842252739bc372", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2013 David MacMahon\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Function for setting one or more mask parameters. This updates the\n% block's MaskValues parameter. Unlike using set_param, this does NOT trigger\n% the mask init script and can be used to set mask parameters from within a\n% mask init script (e.g. to replace a placeholder value with a calculated\n% value). Note that param_names and param_values must both be strings OR both\n% be cell arrays of equal length.\n%\n% Typical usage:\n%\n% % Passing strings (sets latency=1 in mask)\n% set_mask_params(gcb, 'latency', '1');\n%\n% % Passing cells (sets latency=1 and n_inputs=4 in mask)\n% set_mask_params(gcb, {'latency', 'n_inputs'}, {'1', '4'})\n\nfunction params = set_mask_params(blk, param_names, param_values)\n \n % Make sure we are working with cells\n if ~iscell(param_names)\n param_names = {param_names};\n end\n\n if ~iscell(param_values)\n param_values = {param_values};\n end\n\n % Make sure lengths agree\n if length(param_names) ~= length(param_values)\n error('param_names and param_values must have same length');\n end\n\n % Get mask names and values\n mask_names = get_param(blk, 'MaskNames');\n mask_values = get_param(blk, 'MaskValues');\n\n % For each parameter being set\n for param_idx = 1:length(param_names)\n % Find its index in the mask\n mask_idx = find(strcmp(mask_names, param_names{param_idx}));\n if mask_idx\n % If found, update mask_values with new value\n mask_values{mask_idx} = param_values{param_idx};\n end\n end\n\n % Store updated mask_values\n set_param(blk, 'MaskValues', mask_values);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_convert_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_convert_init.m", "size": 12096, "source_encoding": "utf_8", "md5": "6efe30a309718fd9745a244c78282c49", "text": "\nfunction bus_convert_init(blk, varargin)\n\n clog('entering bus_convert_init', 'trace');\n \n % Set default vararg values.\n % reg_retiming is not an actual parameter of this block, but it is included\n % in defaults so that same_state will return false for blocks drawn prior to\n % adding reg_retiming='on' to some of the underlying Delay blocks.\n defaults = { ...\n 'n_bits_in', [8 8 8], ...\n 'bin_pt_in', 8, ...\n 'type_in', 1, ...\n 'cmplx', 'off', ...\n 'n_bits_out', 8, ...\n 'bin_pt_out', 4, ...\n 'type_out', 1, ...\n 'overflow', 1, ...\n 'quantization', 1, ...\n 'misc', 'on', ...\n 'latency', 2, ...\n 'of', 'on', ...\n 'reg_retiming', 'on', ...\n }; \n \n check_mask_type(blk, 'bus_convert');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 80;\n ypos = 50; yinc = 50;\n\n port_w = 30; port_d = 14;\n bus_expand_w = 50;\n bus_create_w = 50;\n convert_w = 50; convert_d = 60;\n del_w = 30; del_d = 20;\n\n n_bits_in = get_var('n_bits_in', 'defaults', defaults, varargin{:});\n bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:});\n type_in = get_var('type_in', 'defaults', defaults, varargin{:});\n cmplx = get_var('cmplx', 'defaults', defaults, varargin{:});\n n_bits_out = get_var('n_bits_out', 'defaults', defaults, varargin{:});\n bin_pt_out = get_var('bin_pt_out', 'defaults', defaults, varargin{:});\n type_out = get_var('type_out', 'defaults', defaults, varargin{:});\n overflow = get_var('overflow', 'defaults', defaults, varargin{:});\n quantization = get_var('quantization', 'defaults', defaults, varargin{:});\n latency = get_var('latency', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n of = get_var('of', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n \n %default state, do nothing \n if isempty(n_bits_in),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_convert_init','trace');\n return;\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % check input lists for consistency %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n lenbi = length(n_bits_in); lenpi = length(bin_pt_in); lenti = length(type_in);\n i = [lenbi, lenpi, lenti]; \n unique_i = unique(i);\n compi = unique_i(length(unique_i));\n\n lenbo = length(n_bits_out); lenpo = length(bin_pt_out); lento = length(type_out); \n lenq = length(quantization); leno = length(overflow);\n o = [lenbo, lenpo, lento, lenq, leno];\n unique_o = unique(o);\n compo = unique_o(length(unique_o));\n\n too_many_i = length(unique_i) > 2;\n conflict_i = (length(unique_i) == 2) && (unique_i(1) ~= 1);\n if too_many_i | conflict_i,\n error('conflicting component number for input bus');\n clog('conflicting component number for input bus', 'error');\n end\n\n too_many_o = length(unique_o) > 2;\n conflict_o = (length(unique_o) == 2) && (unique_o(1) ~= 1);\n if too_many_o | conflict_o,\n error('conflicting component number for output bus');\n clog('conflicting component number for output bus', 'error');\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % autocomplete input lists where necessary %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n comp = compi;\n\n %replicate items if needed for a input\n n_bits_in = repmat(n_bits_in, 1, compi/lenbi); \n bin_pt_in = repmat(bin_pt_in, 1, compi/lenpi); \n type_in = repmat(type_in, 1, compi/lenti); \n\n %if complex we need to double down on some of these\n if strcmp(cmplx, 'on'),\n compi = compi*2;\n n_bits_in = reshape([n_bits_in; n_bits_in], 1, compi); \n bin_pt_in = reshape([bin_pt_in; bin_pt_in], 1, compi); \n type_in = reshape([type_in; type_in], 1, compi); \n end\n \n %replicate items if needed for output\n compo = comp;\n n_bits_out = repmat(n_bits_out, 1, comp/lenbo);\n bin_pt_out = repmat(bin_pt_out, 1, comp/lenpo);\n type_out = repmat(type_out, 1, comp/lento);\n overflow = repmat(overflow, 1, comp/leno);\n quantization = repmat(quantization, 1, comp/lenq);\n \n if strcmp(cmplx, 'on'),\n compo = comp*2;\n n_bits_out = reshape([n_bits_out; n_bits_out], 1, compo); \n bin_pt_out = reshape([bin_pt_out; bin_pt_out], 1, compo); \n type_out = reshape([type_out; type_out], 1, compo); \n overflow = reshape([overflow; overflow], 1, compo); \n quantization= reshape([quantization; quantization], 1, compo); \n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % at this point all input, output lists should match %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n clog(['n_bits_in = ',mat2str(n_bits_in)],'bus_convert_init_debug');\n clog(['n_bits_out = ',mat2str(n_bits_out)],'bus_convert_init_debug');\n clog(['bin_pt_out = ',mat2str(bin_pt_out)],'bus_convert_init_debug');\n clog(['type_out = ',mat2str(type_out)],'bus_convert_init_debug');\n clog(['overflow = ',mat2str(overflow)],'bus_convert_init_debug');\n clog(['quantization = ',mat2str(quantization)],'bus_convert_init_debug');\n clog(['compi = ',num2str(compi), ' compo = ', num2str(compo)],'bus_convert_init_debug');\n\n %%%%%%%%%%%%%%%\n % input ports %\n %%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + convert_d*compi/2;\n reuse_block(blk, 'din', 'built-in/inport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + convert_d*compi/2;\n \n %space for of_bussify\n if strcmp(of, 'on'), ypos_tmp = ypos_tmp + yinc + convert_d*compi; end\n \n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/inport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n end\n xpos = xpos + xinc + port_w/2; \n\n %%%%%%%%%%%%%%\n % bus expand %\n %%%%%%%%%%%%%%\n \n ypos_tmp = ypos + convert_d*compi/2; %reset ypos\n\n outputWidth = mat2str(n_bits_in);\n outputBinaryPt = mat2str(bin_pt_in);\n outputArithmeticType = mat2str(type_in);\n\n reuse_block(blk, 'debus', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', outputWidth, ...\n 'outputBinaryPt', outputBinaryPt, ...\n 'outputArithmeticType', outputArithmeticType, ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-convert_d*compi/2 xpos+bus_expand_w/2 ypos_tmp+convert_d*compi/2]);\n add_line(blk, 'din/1', 'debus/1');\n ypos_tmp = ypos_tmp + convert_d*(compi/2) + yinc;\n xpos = xpos + xinc + bus_expand_w/2;\n\n %%%%%%%%%%%%%%%%%\n % convert layer %\n %%%%%%%%%%%%%%%%%\n\n ypos_tmp = ypos; %reset ypos \n\n for index = 1:compo,\n switch type_out(index),\n case 0,\n arith_type = 'Unsigned';\n case 1,\n arith_type = 'Signed';\n otherwise,\n clog(['unknown arithmetic type ',num2str(arith_type)], 'error');\n error(['bus_convert_init: unknown arithmetic type ',num2str(arith_type)]);\n end\n switch quantization(index),\n case 0,\n quant = 'Truncate';\n case 1,\n quant = 'Round (unbiased: +/- Inf)';\n case 2,\n quant = 'Round (unbiased: Even Values)';\n end \n switch overflow(index),\n case 0,\n oflow = 'Wrap';\n case 1,\n oflow = 'Saturate';\n case 2,\n oflow = 'Flag as error';\n end \n bits_in = n_bits_in(index); pt_in = bin_pt_in(index);\n bits_out = n_bits_out(index); pt_out = bin_pt_out(index);\n\n clog(['output ',num2str(index), ...\n ': (', num2str(bits_in), ' ', num2str(pt_in),') => ', ... \n '(', num2str(bits_out), ' ', num2str(pt_out),') ', ... \n arith_type,' ',quant,' ', oflow], ...\n 'bus_convert_init_debug'); \n\n conv_name = ['conv',num2str(index)];\n\n position = [xpos-convert_w/2 ypos_tmp xpos+convert_w/2 ypos_tmp+convert_d-20];\n\n %casper convert blocks don't support increasing binary points\n if strcmp(of, 'on'),\n reuse_block(blk, conv_name, 'casper_library_misc/convert_of', ...\n 'bit_width_i', num2str(bits_in), 'binary_point_i', num2str(pt_in), ... \n 'bit_width_o', num2str(bits_out), 'binary_point_o', num2str(pt_out), ... \n 'latency', num2str(latency), 'overflow', oflow, 'quantization', quant, ...\n 'Position', position);\n else,\n %CASPER converts can't increase binary points so use generic Xilinx\n if pt_out > pt_in,\n reuse_block(blk, conv_name, 'xbsIndex_r4/Convert', ...\n 'arith_type', 'Signed (2''s comp)', ...\n 'n_bits', num2str(bits_out), 'bin_pt', num2str(pt_out), 'latency', num2str(latency), ...\n 'overflow', oflow, 'quantization', quant, 'pipeline', 'on', ...\n 'Position', position);\n else,\n reuse_block(blk, conv_name, 'casper_library_misc/convert', ...\n 'bin_pt_in', num2str(pt_in), ...\n 'n_bits_out', num2str(bits_out), 'bin_pt_out', num2str(pt_out), ...\n 'overflow', oflow, 'quantization', quant, 'latency', num2str(latency), ... \n 'Position', position);\n end\n end\n\n ypos_tmp = ypos_tmp + convert_d;\n\n add_line(blk, ['debus/',num2str(index)], [conv_name,'/1']);\n end\n \n ypos_tmp = ypos + yinc + convert_d*compi;\n\n %space for of_bussify\n if strcmp(of, 'on'), ypos_tmp = ypos_tmp + yinc + convert_d*compi; end\n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ...\n 'latency', 'latency', 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, 'misci/1', 'dmisc/1');\n ypos_tmp = ypos_tmp + convert_d;\n end\n \n %%%%%%%%%%%%%%%%%%%%\n % create bus again %\n %%%%%%%%%%%%%%%%%%%%\n \n ypos_tmp = ypos + convert_d*compo/2;\n xpos = xpos + xinc + bus_expand_w/2;\n\n reuse_block(blk, 'bussify', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(compo), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-convert_d*compo/2 xpos+bus_create_w/2 ypos_tmp+convert_d*compo/2]);\n \n for index = 1:compo,\n add_line(blk, ['conv',num2str(index),'/1'], ['bussify/',num2str(index)]);\n end\n\n if strcmp(of, 'on'),\n ypos_tmp = ypos_tmp + yinc + compo*convert_d;\n reuse_block(blk, 'of_bussify', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(compo), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-convert_d*compo/2 xpos+bus_create_w/2 ypos_tmp+convert_d*compo/2]);\n \n for index = 1:compo,\n add_line(blk, ['conv',num2str(index),'/2'], ['of_bussify/',num2str(index)]);\n end\n end\n\n %%%%%%%%%%%%%%%%%\n % output port/s %\n %%%%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + convert_d*compo/2;\n xpos = xpos + xinc + bus_create_w/2;\n reuse_block(blk, 'dout', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, ['bussify/1'], ['dout/1']);\n \n ypos_tmp = ypos_tmp + yinc + convert_d*compo/2;\n \n port_no = 1;\n if strcmp(of, 'on'), \n ypos_tmp = ypos_tmp + convert_d*compo/2;\n reuse_block(blk, 'overflow', 'built-in/outport', ...\n 'Port', num2str(port_no+1), ... \n 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n\n add_line(blk, 'of_bussify/1', 'overflow/1');\n ypos_tmp = ypos_tmp + yinc + convert_d*compo/2;\n port_no = port_no + 1;\n end\n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misco', 'built-in/outport', ...\n 'Port', num2str(port_no + 1), ... \n 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n\n add_line(blk, 'dmisc/1', 'misco/1');\n end\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_convert_init','trace');\n\nend %function bus_convert_init\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_delay_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_delay_init.m", "size": 7548, "source_encoding": "utf_8", "md5": "504af36d730100c74211cf950122986b", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_delay_init(blk, varargin)\n log_group = 'bus_delay_init_debug';\n\n clog('entering bus_delay_init', {log_group, 'trace'});\n defaults = { ...\n 'n_bits', [8 8], ...\n 'cmplx', 'off', ...\n 'enable', 'on', ...\n 'latency', 1, ...\n 'misc', 'off', ...\n 'reg_retiming', 'on'};\n \n check_mask_type(blk, 'bus_delay');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 80;\n ypos = 50; yinc = 50;\n\n port_w = 30; port_d = 14;\n bus_expand_w = 50;\n bus_compress_w = 50;\n reg_w = 50; reg_d = 60;\n del_w = 30; del_d = 20;\n\n enable = get_var('enable', 'defaults', defaults, varargin{:});\n cmplx = get_var('cmplx', 'defaults', defaults, varargin{:});\n n_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n latency = get_var('latency', 'defaults', defaults, varargin{:});\n reg_retiming = get_var('reg_retiming', 'defaults', defaults, varargin{:});\n len = length(n_bits);\n\n delete_lines(blk);\n\n %default state, do nothing \n if latency == -1,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_delay_init', {log_group, 'trace'});\n return;\n end\n\n if strcmp(cmplx,'on'), n_bits = 2*n_bits; end\n\n %input ports\n port_no = 1;\n ypos_tmp = ypos + reg_d*len/2;\n reuse_block(blk, 'din', 'built-in/inport', ...\n 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + reg_d*len;\n port_no = port_no + 1;\n\n if strcmp(enable, 'on'),\n reuse_block(blk, 'en', 'built-in/inport', ...\n 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + reg_d*len;\n port_no = port_no + 1;\n end\n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/inport', ...\n 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n end\n\n xpos = xpos + xinc + port_w/2; \n ypos_tmp = ypos + reg_d*len/2; %reset ypos\n\n %data bus expand\n reuse_block(blk, 'din_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', ['[',num2str(n_bits),']'], ...\n 'outputBinaryPt', ['[',num2str(zeros(1, length(n_bits))),']'], ...\n 'outputArithmeticType', ['[',num2str(zeros(1, length(n_bits))),']'], ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-reg_d*len/2 xpos+bus_expand_w/2 ypos_tmp+reg_d*len/2]);\n add_line(blk, 'din/1', 'din_expand/1');\n ypos_tmp = ypos_tmp + reg_d*len + yinc;\n\n %enable bus expand\n if strcmp(enable, 'on'),\n reuse_block(blk, 'en_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', ...\n 'outputNum', num2str(length(n_bits)), ...\n 'outputWidth', '1', 'outputBinaryPt', '0', ...\n 'outputArithmeticType', '2', 'show_format', 'on', ...\n 'outputToWorkspace', 'off', 'variablePrefix', '', ...\n 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-reg_d*len/2 xpos+bus_expand_w/2 ypos_tmp+reg_d*len/2]);\n add_line(blk, 'en/1', 'en_expand/1');\n end\n\n xpos = xpos + xinc + bus_expand_w/2;\n\n %delay layer\n ypos_tmp = ypos; %reset ypos \n\n for index = 1:len,\n delay_name = ['del',num2str(index)];\n %data\n reuse_block(blk, delay_name, 'xbsIndex_r4/Delay', ...\n 'en', enable, 'reg_retiming', reg_retiming, 'latency', num2str(latency), ...\n 'Position', [xpos-reg_w/2 ypos_tmp xpos+reg_w/2 ypos_tmp+reg_d-20]);\n ypos_tmp = ypos_tmp + reg_d;\n\n add_line(blk, ['din_expand/',num2str(index)], [delay_name,'/1']);\n port_index = 2;\n if strcmp(enable, 'on'), add_line(blk, ['en_expand/', num2str(index)], [delay_name, '/', num2str(port_index)]); end\n end\n \n if strcmp(misc, 'on'),\n reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(latency), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)-del_d/2+(port_no-1)*yinc xpos+del_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+(port_no-1)*yinc+del_d/2]);\n add_line(blk, 'misci/1', 'dmisc/1');\n ypos_tmp = ypos_tmp + reg_d;\n end\n \n %create bus again\n ypos_tmp = ypos + reg_d*len/2;\n xpos = xpos + xinc + bus_expand_w/2;\n\n reuse_block(blk, 'dout_compress', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(len), ...\n 'Position', [xpos-bus_compress_w/2 ypos_tmp-reg_d*len/2 xpos+bus_compress_w/2 ypos_tmp+reg_d*len/2]);\n \n for index = 1:len,\n add_line(blk, ['del',num2str(index),'/1'], ['dout_compress/',num2str(index)]);\n end\n\n %output port/s\n ypos_tmp = ypos + reg_d*len/2;\n xpos = xpos + xinc + bus_compress_w/2;\n reuse_block(blk, 'dout', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, ['dout_compress/1'], ['dout/1']);\n ypos_tmp = ypos_tmp + yinc + port_d/2; \n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misco', 'built-in/outport', ...\n 'Port', '2', ... \n 'Position', [xpos-port_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+((port_no-1)*yinc)-port_d/2 xpos+port_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+((port_no-1)*yinc)+port_d/2]);\n\n add_line(blk, 'dmisc/1', 'misco/1');\n end\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_delay_init', {log_group, 'trace'});\n\nend %function bus_delay_init\n\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "convert_of_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/convert_of_init.m", "size": 7714, "source_encoding": "utf_8", "md5": "9521c93dea6662366ea24665b32c1297", "text": "% Bit width conversion in 2's complement data with indication of\r\n% over/underflow\r\n%\r\n% convert_of_init(blk, varargin)\r\n% \r\n% blk = The block to initialise\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n%\r\n% bit_width_i = Total bit width of input data\r\n% binary_point_i = Number of fractional bits in input data\r\n% bit_width_o = Total bit width of output data\r\n% binary_point_o = Number of fractional bits in output data\r\n% quantization = Quantization strategy during conversion\r\n% overflow = Overflow strategy during conversion\r\n% latency = Latency during conversion process\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2008 Andrew Martens %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction convert_of_init(blk,varargin)\r\n\r\ndefaults = { ...\r\n 'bit_width_i', 0, ...\r\n 'binary_point_i', 2, ...\r\n 'quantization', 'Truncate', ...\r\n 'overflow', 'Wrap', ...\r\n 'bit_width_o', 8, ...\r\n 'binary_point_o', 7, ...\r\n 'latency',2, ...\r\n};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'convert_of');\r\nmunge_block(blk, varargin{:});\r\n\r\nbit_width_i = get_var('bit_width_i', 'defaults', defaults, varargin{:});\r\n%data_type_i = get_var('data_type_i', 'defaults', defaults, varargin{:});\r\nbinary_point_i = get_var('binary_point_i', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\noverflow = get_var('overflow', 'defaults', defaults, varargin{:});\r\nbit_width_o = get_var('bit_width_o', 'defaults', defaults, varargin{:});\r\n%data_type_o = get_var('data_type_o', 'defaults', defaults, varargin{:});\r\nbinary_point_o = get_var('binary_point_o', 'defaults', defaults, varargin{:});\r\nlatency = get_var('latency', 'defaults', defaults, varargin{:});\r\n\r\ndelete_lines(blk);\r\n\r\nif bit_width_i == 0 | bit_width_o == 0,\r\n clean_blocks(blk);\r\n set_param(blk, 'AttributesFormatString', '');\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n return;\r\nend\r\n\r\n%input and output ports\r\nreuse_block(blk, 'din', 'built-in/inport', 'Port', '1', 'Position', [50 108 80 122]);\r\nreuse_block(blk, 'dout', 'built-in/outport', 'Port', '1', 'Position', [415 108 445 122]);\r\nreuse_block(blk, 'of', 'built-in/outport', 'Port', '2', 'Position', [415 188 445 202]);\r\n\r\n%draw convert block\r\n\r\n% First delete the convert block that exists so that it can be changed from a\r\n% Xilnix convert block to a CASPER convert block.\r\n%\r\n% It would probably be better to simply change the convert_of block in\r\n% casper_library_misc.mdl to use CASPER converts explicitly, but changing\r\n% the .mdl file is riskier in that it could lead to merges that tend not to\r\n% be pleasant.\r\nconv_blk = find_system(blk, ...\r\n\t'LookUnderMasks','all', 'FollowLinks','on', ...\r\n\t'SearchDepth',1, 'Name','convert');\r\nif ~isempty(conv_blk)\r\n\tdelete_block(conv_blk{1});\r\nend\r\n\r\n%if within the capabilities of CASPER convert\r\nif binary_point_i >= binary_point_o,\r\n reuse_block(blk, 'convert', 'casper_library_misc/convert', ...\r\n 'bin_pt_in', 'binary_point_i', ...\r\n 'n_bits_out', 'bit_width_o', ...\r\n 'bin_pt_out', 'binary_point_o', ...\r\n 'quantization', quantization, ...\r\n 'overflow', overflow, ...\r\n 'latency', 'latency', ...\r\n 'Position', [275 100 320 130]);\r\nelse, %use Xilinx convert\r\n reuse_block(blk, 'convert', 'xbsIndex_r4/Convert', ...\r\n 'arith_type', 'Signed (2''s comp)', ...\r\n 'n_bits', 'bit_width_o', ...\r\n 'bin_pt', 'binary_point_o', ...\r\n 'quantization', quantization, ...\r\n 'overflow', overflow, ...\r\n 'latency', 'latency', ...\r\n 'pipeline', 'on', ...\r\n 'Position', [275 100 320 130]);\r\nend\r\n\r\n%join input port to convert to output port\r\nadd_line(blk, 'din/1', 'convert/1'); \r\nadd_line(blk, 'convert/1', 'dout/1');\r\n\r\n%only care about bits above binary point\r\nwb_lost = max((bit_width_i - binary_point_i) - (bit_width_o - binary_point_o),0);\r\n\r\n%for case where no overflow issues\r\nif wb_lost == 0,\r\n\treuse_block(blk, 'never', 'xbsIndex_r4/Constant', ...\r\n\t\t'arith_type', 'Boolean', 'const','0', ...\r\n 'explicit_period', 'on', 'period', '1', ...\r\n\t\t'Position', [315 182 370 208]);\r\n\tadd_line(blk, 'never/1','of/1');\r\nelse\r\n\t%draw 'and' blocks \\\r\n\t%2's complement numbers have overflow if most sig bits to be discarded\r\n\t%are different (i.e not all 1's or all 0's)\r\n\treuse_block(blk, 'all_0s', 'xbsIndex_r4/Logical', ...\r\n\t\t'precision','Full', ...\r\n\t\t'inputs', num2str(wb_lost+1), ...\r\n\t\t'latency', 'latency', ...\r\n\t\t'logical_function', 'NAND', ...\r\n\t\t'Position', [275 185 320 185+(wb_lost+1)*20] );\r\n\r\n\treuse_block(blk, 'all_1s', 'xbsIndex_r4/Logical', ...\r\n\t\t'precision','Full', ...\r\n\t\t'inputs', num2str(wb_lost+1), ...\r\n\t\t'latency', 'latency', ...\r\n\t\t'logical_function', 'NAND', ...\r\n\t\t'Position', [275 185+(wb_lost+2)*20 320 185+(wb_lost+2)*20+(wb_lost+1)*20] );\r\n\t\r\n %draw slice blocks and inversion blocks\r\n\tfor i = 1:(wb_lost+1),\r\n\t\treuse_block(blk, ['slice',num2str(i)], 'xbsIndex_r4/Slice', ...\r\n\t\t'boolean_output','on', 'mode', 'Upper Bit Location + Width', ...\r\n\t\t'bit1', num2str(-1*(i-1)), 'base1', 'MSB of Input', ...\r\n\t\t'Position', [140 134+i*50 175 156+i*50]);\r\n\t\t\r\n add_line(blk, 'din/1', ['slice',num2str(i),'/1']);\r\n\t\tadd_line(blk, ['slice',num2str(i),'/1'], ['all_1s','/',num2str(i)]);\r\n\r\n\t\treuse_block(blk, ['invert',num2str(i)], 'xbsIndex_r4/Inverter', ...\r\n\t\t'Position', [200 134+i*50 235 156+i*50]);\r\n \r\n add_line(blk, ['slice',num2str(i),'/1'], ['invert',num2str(i),'/1']);\r\n add_line(blk, ['invert',num2str(i),'/1'], ['all_0s','/',num2str(i)]);\r\n\r\n\tend\r\n\r\n\treuse_block(blk, 'and', 'xbsIndex_r4/Logical', ...\r\n\t\t'precision','Full', ...\r\n\t\t'inputs', '2', ...\r\n\t\t'latency', '0', ...\r\n\t\t'logical_function', 'AND', ...\r\n\t\t'Position', [350 185 390 220] );\r\n\r\n\tadd_line(blk, 'all_0s/1', 'and/1'); \r\n\tadd_line(blk, 'all_1s/1', 'and/2');\r\n\r\n add_line(blk, 'and/1', 'of/1'); \r\nend\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('[%d,%d]->[%d,%d]', bit_width_i, binary_point_i, bit_width_o, binary_point_o);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "twiddle_general_4mult_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/twiddle_general_4mult_init.m", "size": 14577, "source_encoding": "utf_8", "md5": "a0dc57fd861b1c01fb32e2a389e2c90a", "text": "% twiddle_general_4mult_init(blk, varargin)\r\n%\r\n% blk = The block to configure\r\n% varargin = {'varname', 'value, ...} pairs\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Karoo Array Telesope %\r\n% http://www.kat.ac.za %\r\n% Copyright (C) 2009 Andrew Martens %\r\n% %\r\n% Radio Astronomy Lab %\r\n% University of California, Berkeley %\r\n% http://ral.berkeley.edu/ %\r\n% Copyright (C) 2010 David MacMahon %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction twiddle_general_4mult_init(blk, varargin)\r\nclog('entering twiddle_general_4mult_init','trace');\r\n\r\ndefaults = {'Coeffs', [0, j], 'StepPeriod', 0, 'input_bit_width', 18, ...\r\n 'coeff_bit_width', 18,'add_latency', 1, 'mult_latency', 2, ...\r\n 'conv_latency', 1, 'bram_latency', 2, 'arch', 'Virtex5', ...\r\n 'coeffs_bram', 'off', 'use_hdl', 'off', 'use_embedded', 'off', ...\r\n 'quantization', 'Round (unbiased: +/- Inf)', 'overflow', 'Wrap'};\r\n\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('twiddle_general_4mult_init post same_state', 'trace');\r\ncheck_mask_type(blk, 'twiddle_general_4mult');\r\nmunge_block(blk, varargin{:});\r\n\r\nCoeffs = get_var('Coeffs', 'defaults', defaults, varargin{:});\r\nStepPeriod = get_var('StepPeriod', 'defaults', defaults, varargin{:});\r\ninput_bit_width = get_var('input_bit_width', 'defaults', defaults, varargin{:});\r\ncoeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nconv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\narch = get_var('arch', 'defaults', defaults, varargin{:});\r\ncoeffs_bram = get_var('coeffs_bram', 'defaults', defaults, varargin{:});\r\nuse_hdl = get_var('use_hdl', 'defaults', defaults, varargin{:});\r\nuse_embedded = get_var('use_embedded', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\noverflow = get_var('overflow', 'defaults', defaults, varargin{:});\r\n\r\nclog(flatstrcell(varargin),'twiddle_general_4mult_init_debug');\r\n\r\nif( strcmp(arch,'Virtex2Pro') ),\r\nelseif( strcmp(arch,'Virtex5') ),\r\nelse,\r\n clog(['twiddle_general_4mult_init: unknown target architecture ',arch],'error');\r\n error(['twiddle_general_4mult_init: Unknown target architecture ',arch]);\r\n return\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\n%default case, leave clean block with nothing for storage in the libraries \r\nif isempty(Coeffs)\r\n clean_blocks(blk);\r\n set_param(blk, 'AttributesFormatString', '');\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting twiddle_general_4mult_init', 'trace');\r\n return;\r\nend\r\n\r\n%a input signal path\r\nreuse_block(blk, 'a', 'built-in/inport', 'Port', '1', 'Position',[225 28 255 42]);\r\nreuse_block(blk, 'delay0', 'xbsIndex_r4/Delay', ...\r\n 'latency','mult_latency + add_latency + bram_latency + conv_latency', ...\r\n 'Position', [275 15 315 55]);\r\nadd_line(blk, 'a/1', 'delay0/1');\r\nreuse_block(blk, 'c_to_ri1', 'casper_library_misc/c_to_ri', ...\r\n 'n_bits', 'input_bit_width', 'bin_pt', 'input_bit_width-1', ...\r\n 'Position', [340 14 380 56]);\r\nadd_line(blk,'delay0/1','c_to_ri1/1');\r\nreuse_block(blk, 'a_re', 'built-in/outport', 'Port', '1', 'Position', [405 13 435 27]);\r\nreuse_block(blk, 'a_im', 'built-in/outport', 'Port', '2', 'Position', [405 43 435 57]);\r\nadd_line(blk, 'c_to_ri1/1', 'a_re/1');\r\nadd_line(blk, 'c_to_ri1/2', 'a_im/1');\r\n\r\n%sync input signal path\r\nreuse_block(blk, 'sync', 'built-in/inport', 'Port', '3', 'Position',[40 393 70 407]);\r\nreuse_block(blk, 'delay2', 'xbsIndex_r4/Delay', ...\r\n 'latency','mult_latency + add_latency + bram_latency + conv_latency', ...\r\n 'Position', [280 380 320 420]);\r\nadd_line(blk, 'sync/1', 'delay2/1');\r\nreuse_block(blk, 'sync_out', 'built-in/outport', 'Port', '5', 'Position', [340 393 370 407]);\r\nadd_line(blk, 'delay2/1', 'sync_out/1');\r\n\r\n%coefficient generator\r\nreuse_block(blk, 'coeff_gen', 'casper_library_ffts_twiddle_coeff_gen/coeff_gen', ...\r\n 'Coeffs', tostring(Coeffs), ...\r\n 'StepPeriod', tostring(StepPeriod), 'coeff_bit_width', 'coeff_bit_width', ...\r\n 'bram_latency', 'bram_latency', 'coeffs_bram', coeffs_bram, ...\r\n 'Position', [105 249 150 291]);\r\nadd_line(blk, 'sync/1', 'coeff_gen/1');\r\n\r\nreuse_block(blk, 'c_to_ri2', 'casper_library_misc/c_to_ri', ...\r\n 'n_bits', 'coeff_bit_width', 'bin_pt', 'coeff_bit_width-2', ...\r\n 'Position', [180 249 220 291]);\r\nadd_line(blk, 'coeff_gen/1', 'c_to_ri2/1');\r\n\r\n%b input signal path\r\nreuse_block(blk, 'b', 'built-in/inport', 'Port', '2', 'Position',[35 148 65 162]);\r\nreuse_block(blk, 'delay1', 'xbsIndex_r4/Delay', 'latency', 'bram_latency', ...\r\n 'reg_retiming', 'on', 'Position', [105 135 145 175]);\r\nadd_line(blk, 'b/1', 'delay1/1');\r\nreuse_block(blk, 'c_to_ri3', 'casper_library_misc/c_to_ri', ...\r\n 'n_bits', 'input_bit_width', 'bin_pt', 'input_bit_width-1', ...\r\n 'Position', [185 134 225 176]);\r\nadd_line(blk, 'delay1/1', 'c_to_ri3/1');\r\n\r\n%Mult\r\nreuse_block(blk, 'mult', 'xbsIndex_r4/Mult', ...\r\n 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ...\r\n 'latency', 'mult_latency', ...\r\n 'Position', [275 128 320 172]);\r\nadd_line(blk, 'c_to_ri3/1', 'mult/1');\r\nadd_line(blk, 'c_to_ri2/1', 'mult/2');\r\n\r\n%Mult1\r\nreuse_block(blk, 'mult1', 'xbsIndex_r4/Mult', ...\r\n 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ...\r\n 'latency', 'mult_latency', ...\r\n 'Position', [275 188 320 232]);\r\nadd_line(blk, 'c_to_ri3/2', 'mult1/1');\r\nadd_line(blk, 'c_to_ri2/1', 'mult1/2');\r\n\r\n%Mult2\r\nreuse_block(blk, 'mult2', 'xbsIndex_r4/Mult', ...\r\n 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ...\r\n 'latency', 'mult_latency', ...\r\n 'Position', [275 248 320 292]);\r\nadd_line(blk, 'c_to_ri3/2', 'mult2/1');\r\nadd_line(blk, 'c_to_ri2/2', 'mult2/2');\r\n\r\n%Mult3\r\nreuse_block(blk, 'mult3', 'xbsIndex_r4/Mult', ...\r\n 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ...\r\n 'latency', 'mult_latency', ...\r\n 'Position', [275 308 320 352]);\r\nadd_line(blk, 'c_to_ri3/1', 'mult3/1');\r\nadd_line(blk, 'c_to_ri2/2', 'mult3/2');\r\n\r\n%adders\r\nreuse_block(blk, 'AddSub', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ...\r\n 'mode', 'Subtraction','use_behavioral_HDL', 'on', ...\r\n 'Position', [410 138 455 182]);\r\nreuse_block(blk, 'AddSub1', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ...\r\n 'mode', 'Addition','use_behavioral_HDL', 'on', ...\r\n 'Position', [410 298 455 342]);\r\n\r\n%output ports\r\nreuse_block(blk, 'bw_re', 'built-in/outport', 'Port', '3', 'Position', [670 153 710 167]);\r\nreuse_block(blk, 'bw_im', 'built-in/outport', 'Port', '4', 'Position', [670 313 710 327]);\r\n\r\n% First delete any convert blocks that exist so that different architectures\r\n% can use different convert blocks. For Virtex2Pro, use CASPER convert blocks.\r\n% For Virtex5 blocks, use Xilinx convert blocks (for \"historical\"\r\n% compatibility; recommend changing V5 to use CASPER convert blocks, too).\r\n% Deleting beforehand is needed so that reuse_block for V2P will not try to\r\n% configure Xilinx convert blocks (left over from code for V5) as CASPER\r\n% convert blocks and vice versa.\r\n%\r\n% It would probably be better to simply change the block in\r\n% casper_library_ffts_twiddle.mdl to use CASPER converts always regardless of\r\n% architecture (e.g. V5 vs V2P), but changing the .mdl file is riskier in that\r\n% it could lead to merges that tend not to be pleasant.\r\nfor k=0:3\r\n conv_name = sprintf('convert%d', k);\r\n conv_blk = find_system(blk, ...\r\n 'LookUnderMasks','all', 'FollowLinks','on', ...\r\n 'SearchDepth',1, 'Name',conv_name);\r\n if ~isempty(conv_blk)\r\n delete_block(conv_blk{1});\r\n end\r\nend\r\n\r\n%architecture specific logic\r\nif( strcmp(arch,'Virtex2Pro') ),\r\n\r\n %add convert blocks to reduce logic in adders\r\n\r\n % Multiplication by a complex twiddle factor is nothing more than a\r\n % rotation in the complex plane. The bit width of the input value being\r\n % twiddled can grow no more than one non-fractional bit. The input value\r\n % does not gain more precision by being twiddled so therefore it need not\r\n % grow any fractional bits.\r\n %\r\n % Since the growth by one non-fractional bit provides sufficient dynamic\r\n % range for the twiddle operation, any \"overflow\" can (and should!) be\r\n % ignored (i.e. set to \"Wrap\"; *not* set to \"Saturate\").\r\n\r\n reuse_block(blk, 'convert0', 'casper_library_misc/convert', ...\r\n 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-2)', ...\r\n 'n_bits_out', 'input_bit_width+1', ...\r\n 'bin_pt_out', 'input_bit_width-1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', 'Wrap', ...\r\n 'Position', [340 135 380 165]);\r\n add_line(blk, 'mult/1', 'convert0/1');\r\n\r\n reuse_block(blk, 'convert1', 'casper_library_misc/convert', ...\r\n 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-2)', ...\r\n 'n_bits_out', 'input_bit_width+1', ...\r\n 'bin_pt_out', 'input_bit_width-1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', 'Wrap', ...\r\n 'Position', [340 195 380 225]);\r\n add_line(blk, 'mult1/1', 'convert1/1');\r\n\r\n reuse_block(blk, 'convert2', 'casper_library_misc/convert', ...\r\n 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-2)', ...\r\n 'n_bits_out', 'input_bit_width+1', ...\r\n 'bin_pt_out', 'input_bit_width-1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', 'Wrap', ...\r\n 'Position', [340 255 380 285]);\r\n add_line(blk, 'mult2/1', 'convert2/1');\r\n\r\n reuse_block(blk, 'convert3', 'casper_library_misc/convert', ...\r\n 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-2)', ...\r\n 'n_bits_out', 'input_bit_width+1', ...\r\n 'bin_pt_out', 'input_bit_width-1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', 'Wrap', ...\r\n 'Position', [340 315 380 345]);\r\n add_line(blk, 'mult3/1', 'convert3/1');\r\n\r\n %join convert blocks to adders\r\n add_line(blk, 'convert0/1', 'AddSub/1');\r\n add_line(blk, 'convert2/1', 'AddSub/2');\r\n add_line(blk, 'convert1/1', 'AddSub1/1');\r\n add_line(blk, 'convert3/1', 'AddSub1/2');\r\n\r\n %join adders to ouputs\r\n add_line(blk, 'AddSub/1', 'bw_re/1');\r\n add_line(blk, 'AddSub1/1', 'bw_im/1');\r\n\r\n % Set output precision on adder outputs\r\n set_param([blk,'/AddSub'], ...\r\n 'precision', 'User Defined', ...\r\n 'arith_type', 'Signed (2''s comp)', ...\r\n 'n_bits', 'input_bit_width+1', ...\r\n 'bin_pt', 'input_bit_width-1', ...\r\n 'quantization', 'Truncate', ...\r\n 'overflow', 'Wrap');\r\n\r\n set_param([blk,'/AddSub1'], ...\r\n 'precision', 'User Defined', ...\r\n 'arith_type', 'Signed (2''s comp)', ...\r\n 'n_bits', 'input_bit_width+1', ...\r\n 'bin_pt', 'input_bit_width-1', ...\r\n 'quantization', 'Truncate', ...\r\n 'overflow', 'Wrap');\r\n\r\nelseif( strcmp(arch,'Virtex5') )\r\n %add convert blocks to after adders to ensure adders absorbed into multipliers\r\n add_line(blk, 'mult/1', 'AddSub/1');\r\n add_line(blk, 'mult1/1', 'AddSub1/1');\r\n add_line(blk, 'mult2/1', 'AddSub/2');\r\n add_line(blk, 'mult3/1', 'AddSub1/2');\r\n\r\n reuse_block(blk, 'convert0', 'xbsIndex_r4/Convert', ...\r\n 'pipeline', 'on', ...\r\n 'n_bits', 'input_bit_width+4', ...\r\n 'bin_pt', 'input_bit_width+1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', tostring(overflow), ...\r\n 'Position', [485 145 525 175]);\r\n add_line(blk, 'AddSub/1', 'convert0/1');\r\n add_line(blk, 'convert0/1', 'bw_re/1');\r\n\r\n reuse_block(blk, 'convert1', 'xbsIndex_r4/Convert', ...\r\n 'pipeline', 'on', ...\r\n 'n_bits', 'input_bit_width+4', ...\r\n 'bin_pt', 'input_bit_width+1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', tostring(overflow), ...\r\n 'Position', [485 305 525 335]);\r\n add_line(blk, 'AddSub1/1', 'convert1/1');\r\n add_line(blk, 'convert1/1', 'bw_im/1');\r\n\r\nelse\r\n return;\r\nend\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('data=(%d,%d)\\ncoeffs=(%d,%d)\\n%s\\n(%s,%s)', ...\r\n input_bit_width, input_bit_width-1, coeff_bit_width, coeff_bit_width-2, arch, quantization, overflow);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\nclog('exiting twiddle_general_4mult_init', 'trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set_param_state.m", "ext": ".m", "path": "mlib_devel-master/casper_library/set_param_state.m", "size": 2025, "source_encoding": "utf_8", "md5": "4cabaa5ab4266c8cda5e954f884f6822", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://casper.berkeley.edu %\n% Copyright (C) 2010 William Mallard %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction set_param_state(cursys, param_name, param_state)\n% Enable or disable a mask parameter.\n\n mask_names = get_param(cursys, 'MaskNames');\n param_index = ismember(mask_names, param_name);\n\n mask_enables = get_param(cursys, 'MaskEnables');\n mask_enables{param_index} = param_state;\n set_param(cursys, 'MaskEnables', mask_enables);\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "sincos_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/sincos_init.m", "size": 5943, "source_encoding": "utf_8", "md5": "f46b84e172872452da8ca5c34a2a10e6", "text": "% Generate sine/cos.\r\n%\r\n% sincos_init(blk, varargin)\r\n%\r\n% blk = The block to be configured.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction sincos_init(blk,varargin)\r\n\r\ncheck_mask_type(blk, 'sincos');\r\n\r\ndefaults = {};\r\n%if same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nmunge_block(blk, varargin{:});\r\nfunc = get_var('func', 'defaults', defaults, varargin{:});\r\nneg_sin = get_var('neg_sin', 'defaults', defaults, varargin{:});\r\nneg_cos = get_var('neg_cos', 'defaults', defaults, varargin{:});\r\nbit_width = get_var('bit_width', 'defaults', defaults, varargin{:});\r\nsymmetric = get_var('symmetric', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\ndepth_bits = get_var('depth_bits', 'defaults', defaults, varargin{:});\r\nhandle_sync = get_var('handle_sync', 'defaults', defaults, varargin{:});\r\n\r\ndelete_lines(blk);\r\n\r\n%default case for storage in library\r\nif depth_bits == 0,\r\n % When finished drawing blocks and lines, remove all unused blocks.\r\n clean_blocks(blk);\r\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\r\n return;\r\nend\r\n\r\nbase = 0;\r\n%handle the sync\r\nif strcmp(handle_sync, 'on'),\r\n reuse_block(blk, 'sync_in', 'built-in/inport', 'Port', '1', 'Position', [80 70 110 90]);\r\n reuse_block(blk, 'delay', 'xbsIndex_r4/Delay', ...\r\n 'latency', 'bram_latency', ... \r\n 'Position', [190 70 230 90]);\r\n\r\n add_line(blk, 'sync_in/1', 'delay/1');\r\n reuse_block(blk, 'sync_out', 'built-in/outport', 'Port', '1', 'Position', [500 70 530 90]);\r\n add_line(blk, 'delay/1', 'sync_out/1');\r\n base = 1;\r\nend\r\n\r\n%input and output ports\r\nreuse_block(blk, 'theta', 'built-in/inport', 'Port', num2str(base+1), 'Position', [80 130 110 150]);\r\n\r\n%draw first lookup\r\nif( strcmp(func, 'sine and cosine') || strcmp(func, 'sine') ),\r\n if strcmp(neg_sin, 'on') , sin_name = '-sine'; else sin_name = 'sine'; end\r\n reuse_block(blk, sin_name, 'built-in/outport', 'Port', num2str(base+1), 'Position', [500 130 530 150]);\r\nend\r\nif( strcmp(func, 'sine and cosine') || strcmp(func, 'cosine')),\r\n if strcmp(neg_cos, 'on') , cos_name = '-cos'; else cos_name = 'cos'; end\r\n if strcmp(func, 'sine and cosine') pos = '3'; end\r\n reuse_block(blk, cos_name, 'built-in/outport', 'Port', num2str(base+2), 'Position', [500 190 530 210]);\r\nend\r\n\r\n%lookup for sine/cos\r\ns = '';\r\nif( strcmp(func, 'sine') || strcmp(func, 'sine and cosine') ),\r\n if strcmp(neg_sin, 'on') , s = '-'; end \r\n init_vec = sprintf('%ssin(2*pi*(0:(%s))/(%s))',s,'2^depth_bits-1','2^depth_bits'); \r\nelse \r\n if( strcmp(neg_cos, 'on') ), s = '-'; end\r\n init_vec = sprintf('%scos(2*pi*(0:(%s))/(%s))',s,'2^depth_bits-1','2^depth_bits'); \r\nend\r\n\r\nbin_pt = 'bit_width-1';\r\nif(strcmp(symmetric, 'on')), bin_pt = 'bit_width-2'; end\r\nreuse_block(blk, 'rom0', 'xbsIndex_r4/ROM', ...\r\n 'depth', '2^depth_bits', 'initVector', init_vec, ...\r\n 'latency', 'bram_latency', 'n_bits', 'bit_width', ...\r\n 'bin_pt', bin_pt, ...\r\n 'Position', [180 120 240 160]);\r\n\r\nadd_line(blk, 'theta/1', 'rom0/1'); \r\n\r\nif strcmp(func, 'sine and cosine') || strcmp(func, 'sine'), dest = sin_name;\r\nelse dest = cos_name;\r\nend\r\n\r\nadd_line(blk, 'rom0/1', [dest,'/1']);\r\n\r\n%have 2 outputs\r\nif strcmp(func, 'sine and cosine'),\r\n s = '';\r\n if( strcmp(neg_cos, 'on') ), s = '-'; end\r\n init_vec = sprintf('%scos(2*pi*(0:(%s))/(%s))',s,'2^depth_bits-1','2^depth_bits'); \r\n\r\n reuse_block(blk, 'rom1', 'xbsIndex_r4/ROM', ...\r\n 'depth', '2^depth_bits', 'initVector', init_vec, ...\r\n 'latency', 'bram_latency', 'n_bits', 'bit_width', ...\r\n 'bin_pt', bin_pt, ...\r\n 'Position', [180 180 240 220]);\r\n \r\n add_line(blk, 'theta/1', 'rom1/1'); \r\n dest = cos_name;\r\n add_line(blk, 'rom1/1', [dest,'/1']);\r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\n% Set attribute format string (block annotation)\r\nannotation=sprintf('');\r\nset_param(blk,'AttributesFormatString',annotation);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "last_tap_real_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/last_tap_real_init.m", "size": 2685, "source_encoding": "utf_8", "md5": "8ea0bf0847220ce597822a7e4e587225", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction last_tap_real_init(blk, varargin)\r\n% Initialize and configure the last tap of the Polyphase Filter Bank.\r\n%\r\n% last_tap_real_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% TotalTaps = Total number of taps in the PFB\r\n% BitWidthIn = Input Bitwidth\r\n% CoeffBitWidth = Bitwidth of Coefficients.\r\n% mult_latency = Latency through each multiplier\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'last_tap_real');\r\nmunge_block(blk, varargin{:});\r\n\r\nuse_hdl = get_var('use_hdl','defaults', defaults, varargin{:});\r\nuse_embedded = get_var('use_embedded','defaults', defaults, varargin{:});\r\n\r\nset_param([blk,'/Mult'],'use_embedded',use_embedded);\r\nset_param([blk,'/Mult'],'use_behavioral_HDL',use_hdl);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bit_reverse_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bit_reverse_init.m", "size": 3419, "source_encoding": "utf_8", "md5": "7a63f92cfb4aa1dfddd8dd479d06b938", "text": "% Initialize and populate a bit_reverse block.\r\n%\r\n% bit_reverse_init(blk, varargin)\r\n%\r\n% blk = The block to initialize.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% n_bits = The number of input bits to reverse\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction bit_reverse_init(blk,varargin)\r\n\r\ncheck_mask_type(blk, 'bit_reverse');\r\nif same_state(blk, varargin{:}), return, end\r\nmunge_block(blk, varargin{:});\r\nn_bits = get_var('n_bits',varargin{:});\r\n\r\n% When dynamically drawing blocks, first delete all lines in a system.\r\ndelete_lines(blk);\r\n\r\n% Draw blocks and lines, using 'reuse_block' to efficiently instantiate blocks.\r\nif n_bits <= 1,\r\n add_line(blk,'in/1','out/1');\r\nelse\r\n % Always propagate variables by value (num2str)\r\n reuse_block(blk, 'concat', 'xbsIndex_r4/Concat', ...\r\n 'Position',[450 100 500 100+n_bits*20],'num_inputs',num2str(n_bits));\r\n for i=n_bits-1:-1:0,\r\n bitname=['bit' num2str(i)];\r\n reuse_block(blk, bitname, 'xbsIndex_r4/Slice', ...\r\n 'Position',[100 100+i*40 140 120+i*40], ...\r\n 'mode','Lower Bit Location + Width', ...\r\n 'nbits', '1', 'bit0', num2str(i));\r\n add_line(blk,'in/1',[bitname,'/1'],'autorouting','on');\r\n add_line(blk,[bitname,'/1'],['concat/',num2str(i+1)],'autorouting','on');\r\n end\r\n add_line(blk,'concat/1','out/1','autorouting','on');\r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\n% Set attribute format string (block annotation)\r\nannotation=sprintf('%d bits',n_bits);\r\nset_param(blk,'AttributesFormatString',annotation);\r\n\r\nsave_state(blk,varargin{:}); % Save and back-populate mask parameter values\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "backpopulate_mask.m", "ext": ".m", "path": "mlib_devel-master/casper_library/backpopulate_mask.m", "size": 3100, "source_encoding": "utf_8", "md5": "8a41f770a26ae171fd8c088d0458ff61", "text": "% Rewrites mask parameters as strings if short enough, otherwise call to extract.\n%\n% backpopulate_mask( blk, varargin )\n%\n% blk - The block whose mask will be modified\n% varargin - {'var', 'value', ...} pairs\n%\n% Cycles through the list of mask parameter variable names. Appends a new cell\n% with the variable value (extracted from varargin) as a string to a cell array if\n% value short enough, otherwise a call to its value in 'UserData'. Overwrites the\n% 'MaskValues' parameter with this new cell array. Essentially converts any pointers\n% or references to strings in the mask.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons, %\n% Copyright (C) 2008 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nfunction backpopulate_mask(blk,varargin)\n\ntry\n % Match mask names to {variables, values} in varargin\n masknames = get_param(blk, 'MaskNames');\n mv = {};\n for i=1:length(masknames),\n\n varname = masknames{i};\n value = get_var(varname, varargin{:});\n\n if isnan(value),\n \terror(['No value specified for ',varname]);\n end\n\n %if parameter too large\n if( length(tostring(value)) > 100 ),\n \tmv{i} = ['getfield( getfield( get_param( gcb,''UserData'' ), ''parameters''),''',varname,''')'];\n else\n \tmv{i} = tostring(value);\n end\n\n end\n \n %Back populate mask parameter values\n set_param(blk,'MaskValues',mv); % This call echos blk name if mv contains a matrix ???\ncatch ex\n dump_and_rethrow(ex);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fft_callback_dsp48_adders.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fft_callback_dsp48_adders.m", "size": 2151, "source_encoding": "utf_8", "md5": "a28df53b3efb26e11cfa3e0158f78560", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://casper.berkeley.edu %\n% Copyright (C) 2010 William Mallard %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction fft_callback_dsp48_adders(cursys)\n% Dialog callback for dsp48_adders parameter in all fft blocks.\n\n % if dsp48_adders is set,\n % force add_latency to 2\n % and disable the field.\n % otherwise, enable it.\n\n dsp48_adders = get_param(cursys, 'dsp48_adders');\n if strcmp(dsp48_adders, 'on'),\n set_param(cursys, 'add_latency', '2');\n set_param_state(cursys, 'add_latency', 'off');\n else\n set_param_state(cursys, 'add_latency', 'on');\n end\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_replicate_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_replicate_init.m", "size": 6992, "source_encoding": "utf_8", "md5": "e36f7955f116f0ce1ce005d256e92bfb", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (andrew@ska.ac.za) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_replicate_init(blk, varargin)\n log_group = 'bus_replicate_init_debug';\n \n clog('entering bus_replicate_init', {log_group, 'trace'});\n defaults = { ...\n 'replication', 8, 'latency', 4, 'misc', 'on', ...\n 'implementation', 'core'}; %'core' 'behavioral'\n \n check_mask_type(blk, 'bus_replicate');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 100;\n ypos = 50; yinc = 50;\n\n port_w = 30; port_d = 14;\n del_w = 30; del_d = 20;\n bus_create_w = 50;\n\n replication = get_var('replication', 'defaults', defaults, varargin{:});\n latency = get_var('latency', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n implementation = get_var('implementation', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state, do nothing \n if replication == 0 || isempty(replication),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_replicate_init', {log_group, 'trace'});\n return;\n end\n\n %%%%%%%%%%%%%%% \n % input ports %\n %%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + (yinc*replication)/2; \n reuse_block(blk, 'in', 'built-in/inport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + (replication*yinc)/2;\n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/inport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n end\n xpos = xpos + xinc; \n\n %%%%%%%%%%%%%%%%%%%%%%%%%%% \n % delay layer if required %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n if strcmp(implementation, 'behavioral'), reg_retiming_global = 'on';\n else, reg_retiming_global = 'off';\n end \n\n xpos_tmp = xpos;\n rps = replication^(1/latency);\n if latency > 0,\n prev_rep_required = 1;\n\n for stage_index = 0:latency-1, \n ypos_tmp = ypos;\n \n if (stage_index == 0), rep = floor(rps);\n else, rep = ceil(rps);\n end\n\n %force the final stage to have the full amount of replication\n if stage_index == latency-1, rep_required = replication;\n else, rep_required = min(prev_rep_required * rep, replication);\n end\n\n clog([num2str(rep_required), ' replication required for stage ',num2str(stage_index)], log_group);\n\n for rep_index = 0:rep_required-1,\n dname = ['din', num2str(stage_index), '_', num2str(rep_index)];\n % implement with behavioral HDL if we have reached the replication amount required\n % before the final delay stage to potentially save resources\n if (rep_required == replication) && (stage_index ~= latency-1), reg_retiming = 'on';\n else, reg_retiming = reg_retiming_global;\n end\n reuse_block(blk, dname, 'xbsIndex_r4/Delay', ...\n 'reg_retiming', reg_retiming, 'latency', '1', ...\n 'Position', [xpos_tmp-del_w/2 ypos_tmp-del_d/2 xpos_tmp+del_w/2 ypos_tmp+del_d/2]);\n\n if stage_index == 0, add_line(blk, 'in/1', [dname,'/1']); \n else, add_line(blk, ['din', num2str(stage_index-1), '_', num2str(mod(rep_index, prev_rep_required)), '/1'], [dname, '/1']); \n end\n\n ypos_tmp = ypos_tmp + yinc;\n end %for\n\n prev_rep_required = rep_required;\n xpos_tmp = xpos_tmp + xinc;\n end %for stage_index \n\n ypos_tmp = ypos + (replication+1)*yinc;\n if strcmp(misc, 'on'), \n reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ...\n 'reg_retiming', 'on', 'latency', num2str(latency), ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, 'misci/1', 'dmisc/1'); \n end %if strcmp\n\n xpos = xpos + latency*xinc;\n end %if latency > 0\n\n %%%%%%%%%%%%%%\n % create bus %\n %%%%%%%%%%%%%%\n\n ypos_tmp = ypos;\n reuse_block(blk, 'bussify', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(replication), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp xpos+bus_create_w/2 ypos_tmp+replication*yinc]);\n \n for index = 1:replication,\n if latency > 0, \n dsrc = ['din', num2str(latency-1), '_', num2str(index-1),'/1'];\n msrc = ['dmisc/1'];\n else, \n dsrc = 'in/1';\n msrc = 'misci/1';\n end\n\n add_line(blk, dsrc, ['bussify/',num2str(index)]);\n end\n\n %%%%%%%%%%%%%%%%% \n % output port/s %\n %%%%%%%%%%%%%%%%%\n \n ypos_tmp = ypos + replication*yinc/2;\n xpos = xpos + xinc + bus_create_w/2;\n reuse_block(blk, 'out', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, ['bussify/1'], ['out/1']);\n ypos_tmp = ypos_tmp + yinc + replication*yinc/2; \n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misco', 'built-in/outport', ...\n 'Port', '2', ... \n 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n\n add_line(blk, msrc, 'misco/1');\n end\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_replicate_init','trace');\n\nend %function bus_replicate_init\n\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "casper_library_downconverter_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/casper_library_downconverter_init.m", "size": 36385, "source_encoding": "utf_8", "md5": "e4cd6212025975a22f85b003fed1b78d", "text": "function casper_library_downconverter_init()\n\n\twarning off Simulink:Engine:MdlFileShadowing;\n\tclose_system('casper_library_downconverter', 0);\n\tmdl = new_system('casper_library_downconverter', 'Library');\n\tblk = get(mdl,'Name');\n\twarning on Simulink:Engine:MdlFileShadowing;\n\n\tadd_block('built-in/SubSystem', [blk,'/mixer']);\n\tmixer_gen([blk,'/mixer']);\n\tset_param([blk,'/mixer'], ...\n\t\t'freq_div', sprintf('2'), ...\n\t\t'freq', sprintf('2'), ...\n\t\t'nstreams', sprintf('0'), ...\n\t\t'n_bits', sprintf('4'), ...\n\t\t'bram_latency', sprintf('2'), ...\n\t\t'mult_latency', sprintf('4'), ...\n\t\t'Position', sprintf('[15 30 80 120]'), ...\n\t\t'Tag', sprintf('casper:mixer'));\n\n\tadd_block('built-in/SubSystem', [blk,'/sincos']);\n\tsincos_gen([blk,'/sincos']);\n\tset_param([blk,'/sincos'], ...\n\t\t'func', sprintf('sine and cosine'), ...\n\t\t'neg_sin', sprintf('off'), ...\n\t\t'neg_cos', sprintf('off'), ...\n\t\t'symmetric', sprintf('on'), ...\n\t\t'handle_sync', sprintf('off'), ...\n\t\t'depth_bits', sprintf('0'), ...\n\t\t'bit_width', sprintf('16'), ...\n\t\t'bram_latency', sprintf('2'), ...\n\t\t'Position', sprintf('[102 26 157 64]'), ...\n\t\t'Tag', sprintf('casper:sincos'));\n\n\tadd_block('built-in/SubSystem', [blk,'/feedback_osc']);\n\tfeedback_osc_gen([blk,'/feedback_osc']);\n\tset_param([blk,'/feedback_osc'], ...\n\t\t'n_bits', sprintf('0'), ...\n\t\t'n_bits_rotation', sprintf('25'), ...\n\t\t'phase_initial', sprintf('0'), ...\n\t\t'phase_step_bits', sprintf('8'), ...\n\t\t'phase_steps_bits', sprintf('8'), ...\n\t\t'ref_values_bits', sprintf('1'), ...\n\t\t'bram_latency', sprintf('2'), ...\n\t\t'mult_latency', sprintf('2'), ...\n\t\t'add_latency', sprintf('1'), ...\n\t\t'conv_latency', sprintf('2'), ...\n\t\t'bram', sprintf('Distributed memory'), ...\n\t\t'quantization', sprintf('Round (unbiased: Even Values)'), ...\n\t\t'Position', sprintf('[105 101 145 139]'), ...\n\t\t'Tag', sprintf('casper:feedback_osc'));\n\n\tadd_block('built-in/SubSystem', [blk,'/cosin']);\n\tcosin_gen([blk,'/cosin']);\n\tset_param([blk,'/cosin'], ...\n\t\t'output0', sprintf('sin'), ...\n\t\t'output1', sprintf('cos'), ...\n\t\t'indep_theta', sprintf('off'), ...\n\t\t'phase', sprintf('0'), ...\n\t\t'fraction', sprintf('0'), ...\n\t\t'store', sprintf('0'), ...\n\t\t'table_bits', sprintf('0'), ...\n\t\t'n_bits', sprintf('18'), ...\n\t\t'bin_pt', sprintf('17'), ...\n\t\t'bram_latency', sprintf('1'), ...\n\t\t'add_latency', sprintf('1'), ...\n\t\t'mux_latency', sprintf('1'), ...\n\t\t'neg_latency', sprintf('1'), ...\n\t\t'conv_latency', sprintf('1'), ...\n\t\t'pack', sprintf('off'), ...\n\t\t'bram', sprintf('BRAM'), ...\n\t\t'misc', sprintf('off'), ...\n\t\t'Position', sprintf('[175 26 230 64]'), ...\n\t\t'Tag', sprintf('casper:cosin'));\n\n\tadd_block('built-in/SubSystem', [blk,'/dec_fir']);\n\tdec_fir_gen([blk,'/dec_fir']);\n\tset_param([blk,'/dec_fir'], ...\n\t\t'n_inputs', sprintf('0'), ...\n\t\t'coeff', sprintf('0.10000000000000000555111512312578'), ...\n\t\t'n_bits', sprintf('8'), ...\n\t\t'n_bits_bp', sprintf('7'), ...\n\t\t'quantization', sprintf('Round (unbiased: +/- Inf)'), ...\n\t\t'add_latency', sprintf('1'), ...\n\t\t'mult_latency', sprintf('2'), ...\n\t\t'conv_latency', sprintf('2'), ...\n\t\t'coeff_bit_width', sprintf('25'), ...\n\t\t'coeff_bin_pt', sprintf('24'), ...\n\t\t'absorb_adders', sprintf('on'), ...\n\t\t'adder_imp', sprintf('DSP48'), ...\n\t\t'lshift', sprintf('1'), ...\n\t\t'Position', sprintf('[15 215 80 308]'), ...\n\t\t'Tag', sprintf('casper:dec_fir'));\n\n\tadd_block('built-in/SubSystem', [blk,'/lo_osc']);\n\tlo_osc_gen([blk,'/lo_osc']);\n\tset_param([blk,'/lo_osc'], ...\n\t\t'n_bits', sprintf('0'), ...\n\t\t'counter_step', sprintf('3'), ...\n\t\t'counter_start', sprintf('4'), ...\n\t\t'counter_width', sprintf('4'), ...\n\t\t'latency', sprintf('2'), ...\n\t\t'Position', sprintf('[248 26 288 81]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/fir_tap']);\n\tfir_tap_gen([blk,'/fir_tap']);\n\tset_param([blk,'/fir_tap'], ...\n\t\t'factor', sprintf('1'), ...\n\t\t'latency', sprintf('2'), ...\n\t\t'coeff_bit_width', sprintf('0'), ...\n\t\t'coeff_bin_pt', sprintf('24'), ...\n\t\t'Position', sprintf('[100 215 150 282]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/fir_dbl_tap']);\n\tfir_dbl_tap_gen([blk,'/fir_dbl_tap']);\n\tset_param([blk,'/fir_dbl_tap'], ...\n\t\t'factor', sprintf('0.073384000000000004781952611665474'), ...\n\t\t'add_latency', sprintf('1'), ...\n\t\t'mult_latency', sprintf('2'), ...\n\t\t'coeff_bit_width', sprintf('0'), ...\n\t\t'coeff_bin_pt', sprintf('17'), ...\n\t\t'Position', sprintf('[172 215 222 282]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/lo_const']);\n\tlo_const_gen([blk,'/lo_const']);\n\tset_param([blk,'/lo_const'], ...\n\t\t'n_bits', sprintf('0'), ...\n\t\t'phase', sprintf('0'), ...\n\t\t'Position', sprintf('[306 26 346 81]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/fir_dbl_col']);\n\tfir_dbl_col_gen([blk,'/fir_dbl_col']);\n\tset_param([blk,'/fir_dbl_col'], ...\n\t\t'n_inputs', sprintf('0'), ...\n\t\t'coeff', sprintf('0.10000000000000000555111512312578'), ...\n\t\t'add_latency', sprintf('2'), ...\n\t\t'mult_latency', sprintf('3'), ...\n\t\t'coeff_bit_width', sprintf('25'), ...\n\t\t'coeff_bin_pt', sprintf('24'), ...\n\t\t'first_stage_hdl', sprintf('off'), ...\n\t\t'adder_imp', sprintf('Fabric'), ...\n\t\t'Position', sprintf('[244 215 279 330]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/dds']);\n\tdds_gen([blk,'/dds']);\n\tset_param([blk,'/dds'], ...\n\t\t'freq_div', sprintf('4'), ...\n\t\t'freq', sprintf('1'), ...\n\t\t'num_lo', sprintf('0'), ...\n\t\t'n_bits', sprintf('8'), ...\n\t\t'latency', sprintf('2'), ...\n\t\t'Position', sprintf('[364 25 404 80]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/fir_col']);\n\tfir_col_gen([blk,'/fir_col']);\n\tset_param([blk,'/fir_col'], ...\n\t\t'n_inputs', sprintf('0'), ...\n\t\t'coeff', sprintf('0.10000000000000000555111512312578'), ...\n\t\t'add_latency', sprintf('2'), ...\n\t\t'mult_latency', sprintf('3'), ...\n\t\t'coeff_bit_width', sprintf('25'), ...\n\t\t'coeff_bin_pt', sprintf('24'), ...\n\t\t'first_stage_hdl', sprintf('off'), ...\n\t\t'adder_imp', sprintf('Fabric'), ...\n\t\t'Position', sprintf('[301 215 336 330]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/rcmult']);\n\trcmult_gen([blk,'/rcmult']);\n\tset_param([blk,'/rcmult'], ...\n\t\t'latency', sprintf('0'), ...\n\t\t'Position', sprintf('[422 26 462 81]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/dec_fir_async']);\n\tdec_fir_async_gen([blk,'/dec_fir_async']);\n\tset_param([blk,'/dec_fir_async'], ...\n\t\t'n_inputs', sprintf('0'), ...\n\t\t'coeff', sprintf('0.10000000000000000555111512312578'), ...\n\t\t'output_width', sprintf('8'), ...\n\t\t'output_bp', sprintf('7'), ...\n\t\t'quantization', sprintf('Round (unbiased: +/- Inf)'), ...\n\t\t'add_latency', sprintf('1'), ...\n\t\t'mult_latency', sprintf('2'), ...\n\t\t'conv_latency', sprintf('2'), ...\n\t\t'coeff_bit_width', sprintf('25'), ...\n\t\t'coeff_bin_pt', sprintf('24'), ...\n\t\t'lshift', sprintf('1'), ...\n\t\t'absorb_adders', sprintf('on'), ...\n\t\t'adder_imp', sprintf('DSP48'), ...\n\t\t'async', sprintf('off'), ...\n\t\t'bus_input', sprintf('off'), ...\n\t\t'input_width', sprintf('0'), ...\n\t\t'input_bp', sprintf('0'), ...\n\t\t'input_type', sprintf('Signed'), ...\n\t\t'Position', sprintf('[15 405 80 498]'), ...\n\t\t'Tag', sprintf('casper:dec_fir_async'));\n\n\tadd_block('built-in/SubSystem', [blk,'/fir_tap_async']);\n\tfir_tap_async_gen([blk,'/fir_tap_async']);\n\tset_param([blk,'/fir_tap_async'], ...\n\t\t'factor', sprintf('1'), ...\n\t\t'add_latency', sprintf('1'), ...\n\t\t'mult_latency', sprintf('2'), ...\n\t\t'coeff_bit_width', sprintf('0'), ...\n\t\t'coeff_bin_pt', sprintf('24'), ...\n\t\t'async', sprintf('off'), ...\n\t\t'dbl', sprintf('off'), ...\n\t\t'Position', sprintf('[125 404 175 476]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/fir_col_async']);\n\tfir_col_async_gen([blk,'/fir_col_async']);\n\tset_param([blk,'/fir_col_async'], ...\n\t\t'n_inputs', sprintf('0'), ...\n\t\t'coeff', sprintf('0.10000000000000000555111512312578'), ...\n\t\t'add_latency', sprintf('2'), ...\n\t\t'mult_latency', sprintf('3'), ...\n\t\t'coeff_bit_width', sprintf('25'), ...\n\t\t'coeff_bin_pt', sprintf('24'), ...\n\t\t'first_stage_hdl', sprintf('off'), ...\n\t\t'adder_imp', sprintf('Fabric'), ...\n\t\t'async', sprintf('off'), ...\n\t\t'bus_input', sprintf('off'), ...\n\t\t'input_width', sprintf('16'), ...\n\t\t'input_bp', sprintf('0'), ...\n\t\t'input_type', sprintf('Signed'), ...\n\t\t'dbl', sprintf('off'), ...\n\t\t'Position', sprintf('[226 405 261 520]'), ...\n\t\t'Tag', sprintf(''));\n\n\tset_param(blk, ...\n\t\t'Name', sprintf('casper_library_downconverter'), ...\n\t\t'LibraryType', sprintf('BlockLibrary'), ...\n\t\t'Lock', sprintf('off'), ...\n\t\t'PreSaveFcn', sprintf('mdl2m(gcs);'), ...\n\t\t'SolverName', sprintf('ode45'), ...\n\t\t'SolverMode', sprintf('SingleTasking'), ...\n\t\t'StartTime', sprintf('0.0'), ...\n\t\t'StopTime', sprintf('10.0'));\n\tfilename = save_system(mdl,[getenv('MLIB_DEVEL_PATH'), '/casper_library/', 'casper_library_downconverter']);\n\tif iscell(filename), filename = filename{1}; end;\n\tfileattrib(filename, '+w');\nend % casper_library_downconverter_init\n\nfunction mixer_gen(blk)\n\n\tmixer_mask(blk);\n\tmixer_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('mixer_init(gcb, ...\\n ''freq_div'', freq_div, ...\\n ''freq'', freq, ...\\n ''nstreams'', nstreams, ...\\n ''n_bits'', n_bits, ...\\n ''bram_latency'', bram_latency, ...\\n ''mult_latency'', mult_latency);\\n'));\n\nend % mixer_gen\n\nfunction mixer_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('mixer'), ...\n\t\t'MaskDescription', sprintf('Digitally mixes an input signal (which can be several samples in parallel) with an LO of the indicated frequency (which is some fraction of the native FPGA clock rate).'), ...\n\t\t'MaskPromptString', sprintf('Frequency Divisions (M)|Mixing Frequency (? / M*2pi)|Number of Parallel Streams|Bit Width|BRAM Latency|Mult Latency'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit'), ...\n\t\t'MaskCallbackString', sprintf('|||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('freq_div=@1;freq=@2;nstreams=@3;n_bits=@4;bram_latency=@5;mult_latency=@6;'), ...\n\t\t'MaskValueString', sprintf('2|2|0|4|2|4'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ...\n\t\t'Tag', sprintf('casper:mixer'));\n\nend % mixer_mask\n\nfunction mixer_init(blk)\n\nend % mixer_init\n\nfunction sincos_gen(blk)\n\n\tsincos_mask(blk);\n\tsincos_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('sincos_init(gcb, ...\\n ''func'', func, ...\\n ''neg_sin'', neg_sin, ...\\n ''neg_cos'', neg_cos, ...\\n ''symmetric'', symmetric, ...\\n ''handle_sync'', handle_sync, ...\\n ''depth_bits'', depth_bits, ...\\n ''bit_width'', bit_width, ...\\n ''bram_latency'', bram_latency);'));\n\nend % sincos_gen\n\nfunction sincos_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('sincos'), ...\n\t\t'MaskPromptString', sprintf('Function|Negative sine|Negative cosine|Symmetric output|Handle sync|Lookup table depth (2^?)|Output bit width|BRAM latency'), ...\n\t\t'MaskStyleString', sprintf('popup(cosine|sine|sine and cosine),checkbox,checkbox,checkbox,checkbox,edit,edit,edit'), ...\n\t\t'MaskCallbackString', sprintf('|||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('func=&1;neg_sin=&2;neg_cos=&3;symmetric=&4;handle_sync=&5;depth_bits=@6;bit_width=@7;bram_latency=@8;'), ...\n\t\t'MaskValueString', sprintf('sine and cosine|off|off|on|off|0|16|2'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ...\n\t\t'Tag', sprintf('casper:sincos'));\n\nend % sincos_mask\n\nfunction sincos_init(blk)\n\nend % sincos_init\n\nfunction feedback_osc_gen(blk)\n\n\tfeedback_osc_mask(blk);\n\tfeedback_osc_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('feedback_osc_init(gcb, ...\\n ''n_bits'', n_bits, ... \\n ''n_bits_rotation'', n_bits_rotation, ... \\n ''phase_initial'', phase_initial, ...\\n ''phase_step_bits'', phase_step_bits, ...\\n ''phase_steps_bits'', phase_steps_bits, ...\\n ''ref_values_bits'', ref_values_bits, ...\\n ''bram_latency'', bram_latency, ...\\n ''mult_latency'', mult_latency, ...\\n ''add_latency'', add_latency, ...\\n ''conv_latency'', conv_latency, ...\\n ''bram'', bram, ...\\n ''quantization'', quantization);\\n'));\n\nend % feedback_osc_gen\n\nfunction feedback_osc_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('feedback_osc'), ...\n\t\t'MaskDescription', sprintf('A complex exponential generated using an initial vector, complex multiplication\\nto rotate it, and feedback. A lookup table of reference vectors is used\\nto periodically remove accumulated error.'), ...\n\t\t'MaskPromptString', sprintf('output bit resolution|rotation vector bit resolution |initial phase ?*(2*pi)|phase step size (2*pi)/2^?|number phase steps 2^?|number calibration locations (2^?)|BRAM latency|multiplier latency|adder latency|convert latency|BRAM implementation|quantization strategy'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,edit,edit,edit,edit,popup(Distributed memory|Block RAM),popup(Truncate|Round (unbiased: +/- Inf)|Round (unbiased: Even Values))'), ...\n\t\t'MaskTabNameString', sprintf('basic,basic,basic,basic,basic,basic,latency,latency,latency,latency,implementation,implementation'), ...\n\t\t'MaskCallbackString', sprintf('|||||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits=@1;n_bits_rotation=@2;phase_initial=@3;phase_step_bits=@4;phase_steps_bits=@5;ref_values_bits=@6;bram_latency=@7;mult_latency=@8;add_latency=@9;conv_latency=@10;bram=&11;quantization=&12;'), ...\n\t\t'MaskValueString', sprintf('0|25|0|8|8|1|2|2|1|2|Distributed memory|Round (unbiased: Even Values)'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ...\n\t\t'Tag', sprintf('casper:feedback_osc'));\n\nend % feedback_osc_mask\n\nfunction feedback_osc_init(blk)\n\nend % feedback_osc_init\n\nfunction cosin_gen(blk)\n\n\tcosin_mask(blk);\n\tcosin_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('cosin_init(gcb, ...\\n ''output0'', output0, ... \\n ''output1'', output1, ...\\n ''indep_theta'', indep_theta, ...\\n ''phase'', phase, ...\\n ''fraction'', fraction, ...\\n ''table_bits'', table_bits, ... \\n ''n_bits'', n_bits, ... \\n ''bin_pt'', bin_pt, ... \\n ''bram_latency'', bram_latency, ...\\n ''add_latency'', add_latency, ...\\n ''mux_latency'', mux_latency, ...\\n ''neg_latency'', neg_latency, ...\\n ''conv_latency'', conv_latency, ...\\n ''store'', store, ...\\n ''pack'', pack, ...\\n ''bram'', bram, ...\\n ''misc'', misc);\\n'));\n\nend % cosin_gen\n\nfunction cosin_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('cosin'), ...\n\t\t'MaskPromptString', sprintf('first output function|second output function|Independent theta values|initial phase offset (?*(2*pi))|fraction of cycle period to output (1/2^?)|fraction of cycle period to store (1/2^?)|samples in cycle period fraction to output (2^?)|bit width|binary point|bram latency|large adder latency|mux latency|negate latency|convert latency|pack lookup values in same output word|BRAM implementation|Miscellaneous port'), ...\n\t\t'MaskStyleString', sprintf('popup(sin|cos|-sin|-cos),popup(none|sin|cos|-sin|-cos),checkbox,edit,edit,edit,edit,edit,edit,edit,edit,edit,edit,edit,checkbox,popup(distributed RAM|BRAM),checkbox'), ...\n\t\t'MaskTabNameString', sprintf('basic,basic,basic,basic,basic,implementation,basic,basic,basic,latency,latency,latency,latency,latency,implementation,implementation,implementation'), ...\n\t\t'MaskCallbackString', sprintf('||||||||||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('output0=&1;output1=&2;indep_theta=&3;phase=@4;fraction=@5;store=@6;table_bits=@7;n_bits=@8;bin_pt=@9;bram_latency=@10;add_latency=@11;mux_latency=@12;neg_latency=@13;conv_latency=@14;pack=&15;bram=&16;misc=&17;'), ...\n\t\t'MaskValueString', sprintf('sin|cos|off|0|0|0|0|18|17|1|1|1|1|1|off|BRAM|off'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ...\n\t\t'MaskDisplay', sprintf('if ~(table_bits == 0),\\n color(''black'');port_label(''output'',1,output0);\\n color(''black'');port_label(''output'',2,output1);\\n color(''black'');disp([''z^{-'',num2str(add_latency+mux_latency+conv_latency+bram_latency+neg_latency+mux_latency),''}''],''texmode'',''on'');color(''black'');port_label(''input'',1,''theta'');\\n if strcmp(misc, ''on''),\\n color(''black'');port_label(''input'',2,''misci'');\\n color(''black'');port_label(''output'',3,''misco'');\\n end\\nend'), ...\n\t\t'Tag', sprintf('casper:cosin'));\n\nend % cosin_mask\n\nfunction cosin_init(blk)\n\nend % cosin_init\n\nfunction dec_fir_gen(blk)\n\n\tdec_fir_mask(blk);\n\tdec_fir_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('dec_fir_init(gcb, ...\\n ''n_inputs'', n_inputs, ...\\n ''coeff'', coeff, ...\\n ''n_bits'', n_bits, ...\\n ''n_bits_bp'', n_bits_bp, ...\\n ''quantization'', quantization, ...\\n ''add_latency'', add_latency, ...\\n ''mult_latency'', mult_latency, ...\\n ''conv_latency'', conv_latency, ...\\n ''coeff_bit_width'', coeff_bit_width, ...\\n ''coeff_bin_pt'', coeff_bin_pt, ...\\n ''absorb_adders'', absorb_adders, ...\\n ''adder_imp'', adder_imp, ...\\n ''lshift'', lshift);'));\n\nend % dec_fir_gen\n\nfunction dec_fir_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('dec_fir'), ...\n\t\t'MaskDescription', sprintf('FIR filter which can handle multiple time samples in parallel and decimates down to 1 time sample. If coefficients are symmetric, will automatically fold before multiplying.'), ...\n\t\t'MaskPromptString', sprintf('Number of Parallel Streams|Coefficients|Bit Width Out|Bin Pt Out|Quantization Behavior|Add Latency|Mult Latency|Convert latency|Coefficient bit width|Coefficient binary point|Absorb adders into DSP slices|Adder implementation|Post adder-tree shift'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,popup(Truncate|Round (unbiased: +/- Inf)|Round (unbiased: Even Values)),edit,edit,edit,edit,edit,checkbox,popup(Behavioral|Fabric|DSP48),edit'), ...\n\t\t'MaskCallbackString', sprintf('||||||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_inputs=@1;coeff=@2;n_bits=@3;n_bits_bp=@4;quantization=&5;add_latency=@6;mult_latency=@7;conv_latency=@8;coeff_bit_width=@9;coeff_bin_pt=@10;absorb_adders=&11;adder_imp=&12;lshift=@13;'), ...\n\t\t'MaskValueString', sprintf('0|0.10000000000000000555111512312578|8|7|Round (unbiased: +/- Inf)|1|2|2|25|24|on|DSP48|1'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ...\n\t\t'Tag', sprintf('casper:dec_fir'));\n\nend % dec_fir_mask\n\nfunction dec_fir_init(blk)\n\nend % dec_fir_init\n\nfunction lo_osc_gen(blk)\n\n\tlo_osc_mask(blk);\n\tlo_osc_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('lo_osc_init(gcb, ...\\n ''n_bits'', n_bits, ...\\n ''counter_step'', counter_step, ...\\n ''counter_start'', counter_start, ...\\n ''counter_width'', counter_width, ...\\n ''latency'', latency);'));\n\nend % lo_osc_gen\n\nfunction lo_osc_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('lo_osc'), ...\n\t\t'MaskDescription', sprintf('Generates -sin and cos data using a look-up \\ntable. '), ...\n\t\t'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Lo_osc'''')'')'), ...\n\t\t'MaskPromptString', sprintf('Output Bitwidth|counter step|counter start value|Counter Bitwidth|Lookup latency'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit'), ...\n\t\t'MaskCallbackString', sprintf('||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits=@1;counter_step=@2;counter_start=@3;counter_width=@4;latency=@5;'), ...\n\t\t'MaskValueString', sprintf('0|3|4|4|2'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]'));\n\nend % lo_osc_mask\n\nfunction lo_osc_init(blk)\n\nend % lo_osc_init\n\nfunction fir_tap_gen(blk)\n\n\tfir_tap_mask(blk);\n\tfir_tap_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('fir_tap_init(gcb, ...\\n ''factor'', factor, ...\\n ''latency'', latency, ...\\n ''coeff_bit_width'', coeff_bit_width, ...\\n ''coeff_bin_pt'', coeff_bin_pt);'));\n\nend % fir_tap_gen\n\nfunction fir_tap_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('fir_tap'), ...\n\t\t'MaskDescription', sprintf('Multiplies input data with factor specified.'), ...\n\t\t'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_tap'''')'')'), ...\n\t\t'MaskPromptString', sprintf('Factor|Mult latency|Coefficient bit width|Coefficient binary point'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit'), ...\n\t\t'MaskCallbackString', sprintf('|||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('factor=@1;latency=@2;coeff_bit_width=@3;coeff_bin_pt=@4;'), ...\n\t\t'MaskValueString', sprintf('1|2|0|24'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]'));\n\nend % fir_tap_mask\n\nfunction fir_tap_init(blk)\n\nend % fir_tap_init\n\nfunction fir_dbl_tap_gen(blk)\n\n\tfir_dbl_tap_mask(blk);\n\tfir_dbl_tap_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('fir_dbl_tap_init(gcb, ...\\n ''factor'', factor, ...\\n ''add_latency'', add_latency, ...\\n ''mult_latency'', mult_latency, ...\\n ''coeff_bit_width'', coeff_bit_width, ...\\n ''coeff_bin_pt'', coeff_bin_pt);'));\n\nend % fir_dbl_tap_gen\n\nfunction fir_dbl_tap_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('fir_dbl_tap'), ...\n\t\t'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_dbl_tap'''')'')'), ...\n\t\t'MaskPromptString', sprintf('factor|Add latency|Mult latency|Coefficient bit width|Coefficient binary point '), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit'), ...\n\t\t'MaskCallbackString', sprintf('||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('factor=@1;add_latency=@2;mult_latency=@3;coeff_bit_width=@4;coeff_bin_pt=@5;'), ...\n\t\t'MaskValueString', sprintf('0.073384000000000004781952611665474|1|2|0|17'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]'));\n\nend % fir_dbl_tap_mask\n\nfunction fir_dbl_tap_init(blk)\n\nend % fir_dbl_tap_init\n\nfunction lo_const_gen(blk)\n\n\tlo_const_mask(blk);\n\tlo_const_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('lo_const_init(gcb, ...\\n ''n_bits'', n_bits, ...\\n ''phase'', phase);'));\n\nend % lo_const_gen\n\nfunction lo_const_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('lo_const'), ...\n\t\t'MaskDescription', sprintf('Generates a complex constant associated with the \\nphase supplied as a parameter.'), ...\n\t\t'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Lo_const'''')'')'), ...\n\t\t'MaskPromptString', sprintf('Output Bitwidth|Phase (0 to 2*pi)'), ...\n\t\t'MaskStyleString', sprintf('edit,edit'), ...\n\t\t'MaskCallbackString', sprintf('|'), ...\n\t\t'MaskEnableString', sprintf('on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits=@1;phase=@2;'), ...\n\t\t'MaskValueString', sprintf('0|0'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]'));\n\nend % lo_const_mask\n\nfunction lo_const_init(blk)\n\nend % lo_const_init\n\nfunction fir_dbl_col_gen(blk)\n\n\tfir_dbl_col_mask(blk);\n\tfir_dbl_col_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('fir_dbl_col_init(gcb, ...\\n ''n_inputs'', n_inputs, ...\\n ''coeff'', coeff, ...\\n ''mult_latency'', mult_latency, ...\\n ''add_latency'', add_latency, ...\\n ''coeff_bit_width'', coeff_bit_width, ...\\n ''coeff_bin_pt'', coeff_bin_pt, ...\\n ''first_stage_hdl'', first_stage_hdl, ...\\n ''adder_imp'', adder_imp);'));\n\nend % fir_dbl_col_gen\n\nfunction fir_dbl_col_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('fir_dbl_col'), ...\n\t\t'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_dbl_col'''')'')'), ...\n\t\t'MaskPromptString', sprintf('Inputs|Coefficients|Add latency|Mult Latency|Coefficient bit width|Coefficient binary point|Implement first stage of adder trees on output as behavioural HDL|Adder implementation'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,checkbox,popup(Behavioral|Fabric|DSP48)'), ...\n\t\t'MaskCallbackString', sprintf('|||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_inputs=@1;coeff=@2;add_latency=@3;mult_latency=@4;coeff_bit_width=@5;coeff_bin_pt=@6;first_stage_hdl=&7;adder_imp=&8;'), ...\n\t\t'MaskValueString', sprintf('0|0.10000000000000000555111512312578|2|3|25|24|off|Fabric'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]'));\n\nend % fir_dbl_col_mask\n\nfunction fir_dbl_col_init(blk)\n\nend % fir_dbl_col_init\n\nfunction dds_gen(blk)\n\n\tdds_mask(blk);\n\tdds_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('dds_init(gcb, ...\\n ''freq_div'', freq_div, ...\\n ''freq'', freq, ...\\n ''num_lo'', num_lo, ...\\n ''n_bits'', n_bits, ...\\n ''latency'', latency);'));\n\nend % dds_gen\n\nfunction dds_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('dds'), ...\n\t\t'MaskDescription', sprintf('Generates P channels of sin and cos data for mixing\\nwith input data in a DDC. To generate frequency \\nN/M(Fc x P) (where Fc is the clock rate) \\nM = \"Frequency Divisions\", N = \"Frequency\",\\nParallel LOs = P'), ...\n\t\t'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Dds'''')'')'), ...\n\t\t'MaskPromptString', sprintf('Frequency divisions (M)|Frequency (? / M*2pi)|Parallel LOs|Bit Width|Latency'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit'), ...\n\t\t'MaskCallbackString', sprintf('||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('freq_div=@1;freq=@2;num_lo=@3;n_bits=@4;latency=@5;'), ...\n\t\t'MaskValueString', sprintf('4|1|0|8|2'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]'));\n\nend % dds_mask\n\nfunction dds_init(blk)\n\nend % dds_init\n\nfunction fir_col_gen(blk)\n\n\tfir_col_mask(blk);\n\tfir_col_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('fir_col_init(gcb, ...\\n ''n_inputs'', n_inputs,...\\n ''coeff'', coeff, ...\\n ''mult_latency'', mult_latency, ...\\n ''add_latency'', add_latency, ...\\n ''coeff_bit_width'', coeff_bit_width, ...\\n ''coeff_bin_pt'', coeff_bin_pt, ...\\n ''first_stage_hdl'', first_stage_hdl, ...\\n ''adder_imp'', adder_imp);'));\n\nend % fir_col_gen\n\nfunction fir_col_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('fir_col'), ...\n\t\t'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_col'''')'')'), ...\n\t\t'MaskPromptString', sprintf('Inputs|Coefficients|Add latency|Mult Latency|Coefficient bit width|Coefficient binary point|Implement first stage of adder trees on output as behavioural HDL|Adder implementation'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,checkbox,popup(Behavioral|Fabric|DSP48)'), ...\n\t\t'MaskCallbackString', sprintf('|||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_inputs=@1;coeff=@2;add_latency=@3;mult_latency=@4;coeff_bit_width=@5;coeff_bin_pt=@6;first_stage_hdl=&7;adder_imp=&8;'), ...\n\t\t'MaskValueString', sprintf('0|0.10000000000000000555111512312578|2|3|25|24|off|Fabric'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]'));\n\nend % fir_col_mask\n\nfunction fir_col_init(blk)\n\nend % fir_col_init\n\nfunction rcmult_gen(blk)\n\n\trcmult_mask(blk);\n\trcmult_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('rcmult_init(gcb, ...\\n ''latency'', latency);'));\n\nend % rcmult_gen\n\nfunction rcmult_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('rcmult'), ...\n\t\t'MaskDescription', sprintf('Multiplies input data with cos and sin inputs and\\noutputs results on real and imag ports \\nrespectively. '), ...\n\t\t'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Rcmult'''')'')'), ...\n\t\t'MaskPromptString', sprintf('Multiplier latency'), ...\n\t\t'MaskStyleString', sprintf('edit'), ...\n\t\t'MaskEnableString', sprintf('on'), ...\n\t\t'MaskVisibilityString', sprintf('on'), ...\n\t\t'MaskToolTipString', sprintf('on'), ...\n\t\t'MaskVariables', sprintf('latency=@1;'), ...\n\t\t'MaskValueString', sprintf('0'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]'));\n\nend % rcmult_mask\n\nfunction rcmult_init(blk)\n\nend % rcmult_init\n\nfunction dec_fir_async_gen(blk)\n\n\tdec_fir_async_mask(blk);\n\tdec_fir_async_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('dec_fir_async_init(gcb);'));\n\nend % dec_fir_async_gen\n\nfunction dec_fir_async_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('dec_fir_async'), ...\n\t\t'MaskDescription', sprintf('FIR filter which can handle multiple time samples in parallel and decimates down to 1 time sample. If coefficients are symmetric, will automatically fold before multiplying.'), ...\n\t\t'MaskPromptString', sprintf('Number of Parallel Streams|Coefficients|Output bitwidth|Output binary point|Quantization Behavior|Add Latency|Mult Latency|Convert latency|Coefficient bitwidth|Coefficient binary point|Post adder-tree shift|Absorb adders into DSP slices|Adder implementation|Asynchronous ops|Bus input|Input bitwidth|Input binary point|Input datatype'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,popup(Truncate|Round (unbiased: +/- Inf)|Round (unbiased: Even Values)),edit,edit,edit,edit,edit,edit,checkbox,popup(Behavioral|Fabric|DSP48),checkbox,checkbox,edit,edit,popup(Signed|Unsigned)'), ...\n\t\t'MaskCallbackString', sprintf('||||||||||||||onoff = get_param(gcb, ''bus_input'');\\nset_param_state(gcb, ''input_width'', onoff)\\nset_param_state(gcb, ''input_bp'', onoff)\\nset_param_state(gcb, ''input_type'', onoff)|||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,off,off,off'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_inputs=@1;coeff=@2;output_width=@3;output_bp=@4;quantization=&5;add_latency=@6;mult_latency=@7;conv_latency=@8;coeff_bit_width=@9;coeff_bin_pt=@10;lshift=@11;absorb_adders=&12;adder_imp=&13;async=&14;bus_input=&15;input_width=@16;input_bp=@17;input_type=&18;'), ...\n\t\t'MaskValueString', sprintf('0|0.10000000000000000555111512312578|8|7|Round (unbiased: +/- Inf)|1|2|2|25|24|1|on|DSP48|off|off|0|0|Signed'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ...\n\t\t'Tag', sprintf('casper:dec_fir_async'));\n\nend % dec_fir_async_mask\n\nfunction dec_fir_async_init(blk)\n\nend % dec_fir_async_init\n\nfunction fir_tap_async_gen(blk)\n\n\tfir_tap_async_mask(blk);\n\tfir_tap_async_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('fir_tap_async_init(gcb);'));\n\nend % fir_tap_async_gen\n\nfunction fir_tap_async_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('fir_tap_async'), ...\n\t\t'MaskDescription', sprintf('Multiplies input data with factor specified.'), ...\n\t\t'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_tap'''')'')'), ...\n\t\t'MaskPromptString', sprintf('Factor|Add latency|Mult latency|Coefficient bit width|Coefficient binary point|Asynchronous ops|Double tap'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit,checkbox,checkbox'), ...\n\t\t'MaskCallbackString', sprintf('||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('factor=@1;add_latency=@2;mult_latency=@3;coeff_bit_width=@4;coeff_bin_pt=@5;async=&6;dbl=&7;'), ...\n\t\t'MaskValueString', sprintf('1|1|2|0|24|off|off'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]'));\n\nend % fir_tap_async_mask\n\nfunction fir_tap_async_init(blk)\n\nend % fir_tap_async_init\n\nfunction fir_col_async_gen(blk)\n\n\tfir_col_async_mask(blk);\n\tfir_col_async_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('fir_col_async_init(gcb);'));\n\nend % fir_col_async_gen\n\nfunction fir_col_async_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('fir_col_async'), ...\n\t\t'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_col'''')'')'), ...\n\t\t'MaskPromptString', sprintf('Inputs|Coefficients|Add latency|Mult Latency|Coefficient bit width|Coefficient binary point|Implement first stage of adder trees on output as behavioural HDL|Adder implementation|Asynchronous ops|Bus input|Input bitwidth|Input binary point|Input datatype|Double col'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,checkbox,popup(Behavioral|Fabric|DSP48),checkbox,checkbox,edit,edit,popup(Signed|Unsigned),checkbox'), ...\n\t\t'MaskCallbackString', sprintf('|||||||||onoff = get_param(gcb, ''bus_input'');\\nset_param_state(gcb, ''input_width'', onoff)\\nset_param_state(gcb, ''input_bp'', onoff)\\nset_param_state(gcb, ''input_type'', onoff)||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,off,off,off,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_inputs=@1;coeff=@2;add_latency=@3;mult_latency=@4;coeff_bit_width=@5;coeff_bin_pt=@6;first_stage_hdl=&7;adder_imp=&8;async=&9;bus_input=&10;input_width=@11;input_bp=@12;input_type=&13;dbl=&14;'), ...\n\t\t'MaskValueString', sprintf('0|0.10000000000000000555111512312578|2|3|25|24|off|Fabric|off|off|16|0|Signed|off'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]'));\n\nend % fir_col_async_mask\n\nfunction fir_col_async_init(blk)\n\nend % fir_col_async_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "last_tap_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/last_tap_init.m", "size": 3201, "source_encoding": "utf_8", "md5": "b4a61bac8f0d784d5db5bf82b9eb1e81", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction last_tap_init(blk, varargin)\r\n% Initialize and configure the last tap of the Polyphase Filter Bank.\r\n%\r\n% last_tap_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% TotalTaps = Total number of taps in the PFB\r\n% BitWidthIn = Input Bitwidth\r\n% BitWidthOut = Output Bitwidth\r\n% CoeffBitWidth = Bitwidth of Coefficients.\r\n% add_latency = Latency through each adder.\r\n% mult_latency = Latency through each multiplier\r\n% quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round\r\n% (unbiased: Even Values)'\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'last_tap');\r\nmunge_block(blk, varargin{:});\r\n\r\npropagate_vars([blk,'/pfb_add_tree'], 'defaults', defaults, varargin{:});\r\n\r\nuse_hdl = get_var('use_hdl','defaults', defaults, varargin{:});\r\nuse_embedded = get_var('use_embedded','defaults', defaults, varargin{:});\r\n\r\nset_param([blk,'/Mult'],'use_embedded',use_embedded);\r\nset_param([blk,'/Mult'],'use_behavioral_HDL',use_hdl);\r\nset_param([blk,'/Mult1'],'use_embedded',use_embedded);\r\nset_param([blk,'/Mult1'],'use_behavioral_HDL',use_hdl)\r\n\r\n\r\nTotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:});\r\n\r\nfmtstr = sprintf('taps=%d', TotalTaps);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "barrel_switcher_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/barrel_switcher_init.m", "size": 7183, "source_encoding": "utf_8", "md5": "1bc6d7d6ad595f2b3ef0271a4dd0a5e4", "text": "% Initialize and configure the barrel switcher.\r\n%\r\n% barrel_switcher_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% n_inputs = Number of inputs\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction barrel_switcher_init(blk, varargin)\r\n\r\n clog('entering barrel_switcher_init', {'trace', 'barrel_switcher_init_debug'});\r\n\r\n % Declare any default values for arguments you might like.\r\n % reg_retiming is not an actual parameter of this block, but it is included\r\n % in defaults so that same_state will return false for blocks drawn prior to\r\n % adding reg_retiming='on' to some of the underlying Delay blocks.\r\n defaults = { ...\r\n 'n_inputs', 1, ...\r\n 'async', 'off', ...\r\n 'reg_retiming', 'on', ...\r\n };\r\n\r\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\n check_mask_type(blk, 'barrel_switcher')\r\n munge_block(blk, varargin{:})\r\n\r\n n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\n async = get_var('async', 'defaults', defaults, varargin{:});\r\n\r\n delete_lines(blk);\r\n\r\n %default case for library storage\r\n if n_inputs == 0,\r\n clean_blocks(blk);\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting barrel_switcher_init', {'trace', 'barrel_switcher_init_debug'});\r\n return;\r\n end\r\n\r\n reuse_block(blk, 'sel', 'built-in/inport', 'Position', [15 23 45 37], 'Port', '1');\r\n\r\n %\r\n % sync data path\r\n %\r\n\r\n reuse_block(blk, 'sync_in', 'built-in/inport',...\r\n 'Position', [15 (2^n_inputs+1)*80+95 45 109+80*(2^n_inputs+1)], 'Port', '2');\r\n reuse_block(blk, 'sync_out', 'built-in/outport',...\r\n 'Position', [135 (2^n_inputs+1)*80+95 165 109+80*(2^n_inputs+1)], 'Port', '1');\r\n reuse_block(blk, 'Delay_sync', 'xbsIndex_r4/Delay', ...\r\n 'reg_retiming', 'on', 'latency', num2str(n_inputs), ...\r\n 'Position', [75 (2^n_inputs+1)*80+95 105 109+80*(2^n_inputs+1)]);\r\n add_line(blk, 'sync_in/1', 'Delay_sync/1');\r\n add_line(blk, 'Delay_sync/1', 'sync_out/1');\r\n\r\n %\r\n % muxes\r\n %\r\n\r\n for i=1:2^n_inputs,\r\n reuse_block(blk, ['In',num2str(i)], 'built-in/inport', 'Position', [15 i*80+95 45 109+80*i]);\r\n reuse_block(blk, ['Out',num2str(i)], 'built-in/outport', 'Position', [15+150*(n_inputs+1) 95+i*80 45+150*(n_inputs+1) 109+80*i]);\r\n for j=1:n_inputs,\r\n reuse_block(blk, ['Mux', num2str(10*i + j)], 'xbsIndex_r4/Mux', ...\r\n 'latency', '1', 'Position', [15+150*j, 67+80*i, 40+150*j, 133+80*i]);\r\n end\r\n end\r\n for j=1:(n_inputs-1),\r\n reuse_block(blk, ['Delay', num2str(j)], 'xbsIndex_r4/Delay', ...\r\n 'reg_retiming', 'on', 'Position', [15+150*j 15 45+150*j 45]);\r\n end\r\n for j=1:n_inputs,\r\n reuse_block(blk, ['Slice', num2str(j)], 'xbsIndex_r4/Slice', ...\r\n 'Position', [85+150*(j-1) 91 130+150*(j-1) 119], 'bit1', ['-', num2str(j-1)]);\r\n end\r\n add_line(blk, 'sel/1', 'Slice1/1');\r\n if n_inputs > 1, add_line(blk, 'sel/1', 'Delay1/1');\r\n end\r\n for j=1:(n_inputs-2),\r\n delayname = ['Delay', num2str(j)];\r\n nextdelay = ['Delay', num2str(j+1)];\r\n add_line(blk, [delayname, '/1'], [nextdelay, '/1']);\r\n end\r\n for j=1:(n_inputs-1),\r\n slicename = ['Slice', num2str(j+1)];\r\n delayname = ['Delay', num2str(j)];\r\n add_line(blk, [delayname, '/1'], [slicename, '/1']);\r\n end\r\n for j=1:n_inputs,\r\n slicename = ['Slice', num2str(j)];\r\n for i=1:2^n_inputs\r\n muxname = ['Mux', num2str(10*i + j)];\r\n add_line(blk, [slicename, '/1'], [muxname, '/1']);\r\n end\r\n end\r\n for i=1:2^n_inputs,\r\n iport = ['In', num2str(i)];\r\n oport = ['Out', num2str(i)];\r\n firstmux = ['Mux', num2str(10*i + 1)];\r\n if i > 2^n_inputs / 2\r\n swmux = ['Mux', num2str(10*(i-2^n_inputs/2) + 1)];\r\n else\r\n swmux = ['Mux', num2str(10*(i-2^n_inputs/2 + 2^n_inputs) + 1)];\r\n end\r\n lastmux = ['Mux', num2str(10*i + n_inputs)];\r\n add_line(blk, [iport, '/1'], [firstmux, '/2']);\r\n add_line(blk, [iport, '/1'], [swmux, '/3']);\r\n add_line(blk, [lastmux, '/1'], [oport, '/1']);\r\n end\r\n for i=1:2^n_inputs,\r\n for j=1:(n_inputs-1)\r\n muxname = ['Mux', num2str(10*i + j)];\r\n nextmuxname = ['Mux', num2str(10*i + j+1)];\r\n add_line(blk, [muxname, '/1'], [nextmuxname, '/2']);\r\n if i > 2^n_inputs / (2^(j+1))\r\n swmux = ['Mux', num2str(10*(i-2^n_inputs/(2^(j+1))) + j+1)];\r\n else\r\n swmux = ['Mux', num2str(10*(i-2^n_inputs/(2^(j+1)) + 2^n_inputs) + j+1)];\r\n end\r\n add_line(blk, [muxname, '/1'], [swmux, '/3']);\r\n end\r\n end\r\n\r\n %\r\n % data valid\r\n %\r\n\r\n if strcmp(async, 'on'),\r\n reuse_block(blk, 'en', 'built-in/inport',...\r\n 'Position', [15 (2^n_inputs+2)*80+95 45 109+80*(2^n_inputs+2)], 'Port', num2str(2^n_inputs+3));\r\n reuse_block(blk, 'dvalid', 'built-in/outport',...\r\n 'Position', [135 (2^n_inputs+2)*80+95 165 109+80*(2^n_inputs+2)], 'Port', num2str(2^n_inputs+2));\r\n reuse_block(blk, 'den', 'xbsIndex_r4/Delay', ...\r\n 'reg_retiming', 'on', 'latency', num2str(n_inputs), ...\r\n 'Position', [75 (2^n_inputs+2)*80+95 105 109+80*(2^n_inputs+2)]);\r\n add_line(blk, 'en/1', 'den/1');\r\n add_line(blk, 'den/1', 'dvalid/1');\r\n end\r\n\r\n clean_blocks(blk);\r\n\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n \r\n clog('exiting barrel_switcher_init', {'trace', 'barrel_switcher_init_debug'});\r\n\r\nend %function\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "rcs_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/rcs_init.m", "size": 12031, "source_encoding": "utf_8", "md5": "c057a49a7b8e6b434c3314e6d96c3705", "text": "% Embed revision control info into gateware\n%\n% rcs_init(blk, varargin)\n%\n% blk = The block to be configured.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% app_src = Revision source for application (git, svn, timestamp)\n% lib_src = Revision source for libraries (git, svn, timestamp)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2010 Andrew Martens (meerKAT) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction rcs_init(blk, varargin),\n\n clog('entering rcs_init', 'trace');\n\n check_mask_type(blk, 'rcs');\n munge_block(blk, varargin);\n\n\n defaults = { 'app_src', 'timestamp', 'lib_src', 'timestamp'};\n app_src = get_var('app_src', 'defaults', defaults, varargin{:});\n lib_src = get_var('lib_src', 'defaults', defaults, varargin{:});\n\n system_os = determine_os();\n\n % application info\n\n path = which(gcs);\n indices = regexp(path,['/']);\n if isempty(indices),\n disp('rcs_init: Model must be saved to get revision info for it, using current time as revision');\n app_src = 'timestamp';\n else, \n app_dir = path(1:indices(length(indices)));\n app_file = path(indices(length(indices))+1:length(path));\n end\n\n app_revision = 0;\n app_dirty = 1;\n if strcmp(app_src, 'svn') == 1 || strcmp(app_src, 'git') == 1,\n [app_result, app_revision, app_dirty] = get_revision_info(system_os, app_src, app_dir, app_file);\n if app_result ~= 0,\n disp('rcs_init: Failed to get revision info for application from specified source, will use timestamp');\n app_src = 'timestamp';\n end\n end\n\n app_timestamp = 0;\n if isempty(indices),\n [app_timestamp_result, app_timestamp] = get_current_time();\n else,\n [app_timestamp_result, app_timestamp] = get_timestamp(system_os, path);\n end\n if app_timestamp_result ~= 0,\n disp('rcs_init: Failed to get timestamp info for design. No revision info possible!');\n end\n\n %set up application registers\n result = set_registers(blk, 'app', app_src, app_timestamp, app_revision, app_dirty);\n if result ~= 0,\n disp('rcs_init: Failed to set application registers');\n end \n\n % libraries info\n path = getenv('MLIB_DEVEL_PATH'); %the new path to the CASPER libraries\n if isempty(path),\n path = getenv('MLIB_ROOT'); %the older path to CASPER libraries\n end\n if isempty(path), %neither paths give us anything\n disp('rcs_init: MLIB_DEVEL_PATH or MLIB_ROOT must be defined in your system, using current time as revision');\n lib_src = 'timestamp';\n end\n \n lib_dir = path;\n\n lib_revision = 0;\n lib_dirty = 1;\n if strcmp(lib_src, 'svn') == 1 || strcmp(lib_src, 'git') == 1,\n [lib_result, lib_revision, lib_dirty] = get_revision_info(system_os, lib_src, lib_dir, '');\n if lib_result ~= 0,\n disp('rcs_init: Failed to get revision info for libraries from specified source, will use current time as timestamp');\n lib_src = 'timestamp';\n else\n\n end\n end\n\n lib_timestamp = 0;\n [lib_timestamp_result, lib_timestamp] = get_current_time();\n if lib_timestamp_result ~= 0,\n disp('rcs_init: Failed to get timestamp for libraries. No revision info possible!');\n end\n\n %set up application registers\n result = set_registers(blk, 'lib', lib_src, lib_timestamp, lib_revision, lib_dirty);\n if result ~= 0,\n disp('rcs_init: Failed to set library registers');\n end \n\n clog('exiting rcs_init', 'trace');\n\nend\n\nfunction [result] = set_registers(blk, section, info_type, timestamp, revision, dirty)\n\n result = 1;\n\n if strcmp(info_type, 'git'), \n clog(sprintf('%s revision :%x dirty :%d', section, revision, dirty),'rcs_init_debug'); \n elseif strcmp(info_type, 'svn'), \n clog(sprintf('%s revision :%d dirty :%d', section, revision, dirty),'rcs_init_debug'); \n end\n clog(sprintf('%s timestamp :%s', section, num2str(timestamp,10)),'rcs_init_debug'); \n\n % set up mux and revision type\n if strcmp(info_type, 'timestamp'),\n const = 1;\n type = 0;\n elseif strcmp(info_type, 'git'),\n type = 0;\n const = 0;\n elseif strcmp(info_type, 'svn'),\n const = 0;\n type = 1;\n end\n set_param([blk, '/', section, '_type'], 'const', num2str(const));\n \n % timestamp\n % blank out most sig bit so fits in 31 bits, valid till \n set_param([blk, '/', section, '_timestamp'], 'const', num2str(bitset(uint32(timestamp),32,0))); \n\n % revision info\n set_param([blk, '/', section, '_rcs_type'], 'const', num2str(type));\n if strcmp(info_type, 'git'),\n rev = sprintf('hex2dec(''%x'')',revision);\n else\n rev = num2str(revision);\n end\n \n set_param([blk, '/', section, '_revision'], 'const', rev);\n set_param([blk, '/', section, '_dirty'], 'const', num2str(dirty));\n \n result = 0;\nend\n\n% returns current time in number of seconds since epoch\nfunction [result, timestamp] = get_current_time()\n timestamp = round(etime(clock, [1970 1 1 0 0 0]));\n result = 0;\nend\n\nfunction [result, timestamp] = get_timestamp(system_os, path)\n result = 1;\n if strcmp(system_os,'windows') == 1,\n %TODO windows timestamp\n disp('rcs_init: can''t do timestamp in Windoze yet');\n clog('rcs_init: can''t do timestamp in Windoze yet','error');\n\n elseif strcmp(system_os, 'linux'),\n % take last modification time as timestamp\n % in seconds since epoch\n [s, r] = system(['ls -l --time-style=+%s ',path]);\n if s == 0,\n info = regexp(r,'\\s+','split');\n timestamp = str2num(info{6}); \n \n if isnumeric(timestamp),\n result = 0;\n end\n else\n disp('rcs_init: failure using ''ls -l ',path,''' in Linux');\n clog('rcs_init: failure using ''ls -l ',path,''' in Linux','error');\n end \n else\n disp(['rcs_init: unknown os ',system_os]);\n clog(['rcs_init: unknown os ',system_os],'error');\n end\n\n return;\nend\n\nfunction [system_os] = determine_os()\n %following os detection logic lifted from gen_xps_files, thanks Dave G\n [s,w] = system('uname -a');\n\n system_os = 'linux';\n if s ~= 0\n system_os = 'windows';\n elseif ~isempty(regexp(w,'Linux'))\n system_os = 'linux';\n end\n\n clog([system_os,' system detected'],'rcs_init_debug');\nend\n\nfunction [result, revision, dirty] = get_revision_info(system_os, rev_sys, dir, file),\n\n result = 1; %tough crowd\n revision = 0;\n dirty = 1;\n\n if strcmp(rev_sys, 'git') == 1 ,\n if strcmp(system_os,'windows') == 1,\n %TODO git in windows\n disp('rcs_init: can''t handle git in Windows yet');\n clog('rcs_init: can''t handle git in Windows yet','error');\n elseif strcmp(system_os,'linux') == 1,\n \n %get latest commit\n [s, r] = system(['cd ',dir,'; git log -n 1 --abbrev-commit ',file,'| grep commit']);\n if s == 0,\n % get first commit from log\n indices=regexp(r,[' ']);\n if length(indices) ~= 0,\n revision = uint32(0);\n % convert text to 28 bit value\n for n = 0:6,\n revision = bitor(revision, bitshift(uint32(hex2dec(r(indices(1)+n+1))), (6-n)*4)); \n end \n result = 0;\n end\n\n % determine if dirty. If file, must not appear, if whole repository, must be clean\n if isempty(file), search = 'grep \"nothing to commit (working directory clean)\"';\n else, search = ['grep ',file,' | grep modified'];\n end\n dirty = 1;\n [s, r] = system(['cd ',dir,'; git status |', search]);\n clog(['cd ',dir,'; git status | ', search], 'rcs_init_debug');\n clog([num2str(s),' : ',r], 'rcs_init_debug');\n % failed to find modified string\n if ~isempty(file) && s == 1 && isempty(r), \n dirty = 0;\n % git succeeded and found nothing to commit\n elseif isempty(file) && s == 0,\n dirty = 0;\n end \n else\n disp(['rcs_init: failure using ''cd ',dir,'; git log -n 1 --abbrev-commit ',file,' | grep commit'' in Linux']);\n clog(['rcs_init: failure using ''cd ',dir,'; git log -n 1 --abbrev-commit ',file,' | grep commit'' in Linux'], 'error');\n end \n\n else\n disp(['rcs_init: unrecognised os ',system_os]);\n end\n elseif strcmp(rev_sys, 'svn') == 1,\n if strcmp(system_os,'windows') == 1,\n % tortoiseSVN\n [usr_r,usr_rev] = system(sprintf('%s %s\\%s', 'SubWCRev.exe', dir, file));\n\n if (usr_r == 0) %success\n if (~isempty(regexp(usr_rev,'Local modifications'))) % we have local mods\n dirty = 1;\n else\n dirty = 0;\n end\n\n temp=regexp(usr_rev,'Updated to revision (?\\d+)','tokens');\n if (~isempty(temp))\n revision = str2num(temp{1}{1});\n else \n temp=regexp(usr_rev,'Last committed at revision (?\\d+)','tokens');\n if (~isempty(temp))\n revision = str2num(temp{1}{1});\n end\n end \n clog(['tortioseSVN revision :',num2str(revision),' dirty: ',num2str(dirty)],'rcs_init_debug'); \n result = 0;\n else\n disp(['rcs_init: failure using ''SubWCRev.exe ',dir,'\\',file,''' in Windoze']);\n clog(['rcs_init: failure using ''SubWCRev.exe ',dir,'\\',file,''' in Windoze'],'rcs_init_debug');\n end\n elseif strcmp(system_os, 'linux'), % svn in linux\n \n %revision number\n [usr_r,usr_rev] = system(sprintf('%s %s%s', 'svn info', dir, file));\n if (usr_r == 0)\n temp=regexp(usr_rev,'Revision: (?\\d+)','tokens');\n if (~isempty(temp))\n revision = str2num(temp{1}{1});\n end\n \n %modified status\n [usr_r,usr_rev] = system(sprintf('%s %s%s', 'svn status 2>/dev/null | grep ''^[AMD]'' | wc -l', dir, file));\n if (usr_r == 0)\n if (str2num(usr_rev) > 0)\n dirty = 1;\n else\n dirty = 0;\n end\n else\n disp(['rcs_init: failure using ''svn status ',dir,file,''' in Linux']);\n clog(['rcs_init: failure using ''svn status ',dir,file,''' in Linux'],'error');\n end\n if isnumeric(revision), \n result = 0;\n end\n else\n disp(sprintf('rcs_init: failure using ''svn info ''%s%s'' in Linux\\nError msg: ''%s''', dir, file, usr_rev));\n clog(sprintf('rcs_init: failure using ''svn info ''%s%s'' in Linux\\nError msg: ''%s''', dir, file ,usr_rev), 'error');\n end\n else\n disp(['rcs_init: unrecognised os ',system_os]);\n end \n\n else \n disp(['rcs_init: unrecognised revision system ', rev_sys]);\n clog(['rcs_init: unrecognised revision system ', rev_sys], 'error');\n end %revision system\n\n return; \nend\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "delay_bram_prog_dp_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/delay_bram_prog_dp_init.m", "size": 4950, "source_encoding": "utf_8", "md5": "eeab252737022d3657e6b9ada95a8180", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction delay_bram_prog_dp_init(blk, varargin)\n\n log_group = 'delay_bram_prog_dp_init_debug';\n\n clog('entering delay_bram_prog_dp_init', {log_group, 'trace'});\n \n defaults = { ...\n 'ram_bits', 10, ...\n 'bram_latency', 2, ...\n 'async', 'off'}; \n \n check_mask_type(blk, 'delay_bram_prog_dp');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n ram_bits = get_var('ram_bits', 'defaults', defaults, varargin{:});\n bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\n async = get_var('async', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n if (ram_bits == 0),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); \n clog('exiting delay_bram_prog_dp_init', {log_group, 'trace'});\n return;\n end\n \n reuse_block(blk, 'din', 'built-in/Inport', 'Port', '1', 'Position', [235 43 265 57]);\n reuse_block(blk, 'delay', 'built-in/Inport', 'Port', '2', 'Position', [115 83 145 97]);\n if strcmp(async, 'on'),\n reuse_block(blk, 'en', 'built-in/Inport', 'Port', '3', 'Position', [15 28 45 42]);\n end\n\n reuse_block(blk, 'wr_addr', 'xbsIndex_r4/Counter', ...\n 'n_bits', 'ram_bits', 'use_behavioral_HDL', 'on', 'use_rpm', 'on', ...\n 'en', async, 'Position', [75 18 110 52]);\n if strcmp(async, 'on'), \n add_line(blk, 'en/1', 'wr_addr/1');\n end\n\n reuse_block(blk, 'AddSub', 'xbsIndex_r4/AddSub', ...\n 'mode', 'Subtraction', 'latency', '1', ...\n 'precision', 'User Defined', 'n_bits', 'ram_bits', 'bin_pt', '0', ...\n 'use_behavioral_HDL', 'on', 'use_rpm', 'on', ...\n 'Position', [175 52 225 103]);\n add_line(blk, 'delay/1', 'AddSub/2');\n add_line(blk, 'wr_addr/1', 'AddSub/1');\n\n reuse_block(blk, 'Constant2', 'xbsIndex_r4/Constant', ...\n 'arith_type', 'Boolean', 'n_bits', '1', 'bin_pt', '0', ...\n 'explicit_period', 'on', 'Position', [285 56 300 74]);\n\n reuse_block(blk, 'Constant4', 'xbsIndex_r4/Constant', ...\n 'const', '0', 'arith_type', 'Boolean', 'n_bits', '1', 'bin_pt', '0', ...\n 'explicit_period', 'on', 'Position', [285 102 300 118]);\n\n reuse_block(blk, 'Dual Port RAM', 'xbsIndex_r4/Dual Port RAM', ...\n 'depth', '2^ram_bits', 'initVector', '0', ...\n 'latency', 'bram_latency', 'write_mode_B', 'Read Before Write', ...\n 'optimize', 'Area', 'Position', [315 26 385 119]);\n add_line(blk, 'din/1', 'Dual Port RAM/2');\n add_line(blk, 'din/1', 'Dual Port RAM/5');\n add_line(blk, 'wr_addr/1', 'Dual Port RAM/1');\n add_line(blk, 'AddSub/1', 'Dual Port RAM/4');\n add_line(blk, 'Constant2/1', 'Dual Port RAM/3');\n add_line(blk, 'Constant4/1', 'Dual Port RAM/6');\n\n reuse_block(blk, 'Terminator', 'built-in/Terminator', 'Position', [420 40 440 60]);\n add_line(blk,'Dual Port RAM/1', 'Terminator/1');\n\n reuse_block(blk, 'dout', 'built-in/Outport', 'Port', '1', 'Position', [415 88 445 102]);\n add_line(blk, 'Dual Port RAM/2', 'dout/1');\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting delay_bram_prog_dp_init', {log_group, 'trace'});\nend % delay_bram_prog_dp_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "cmult_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/cmult_init.m", "size": 15367, "source_encoding": "utf_8", "md5": "ebc6efcdec67117f0f322f39cf8b1e56", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction cmult_init(blk, varargin)\n% Configure a cmult block.\n%\n% cmult_init(blk, n_bits_b, bin_pt_b, n_bits_w, bin_pt_w, ...\n% n_bits_bw, bin_pt_bw, quantization, overflow, ...\n% mult_latency, add_latency)\n%\n% blk = Block to configure\n% n_bits_X = Number of bits for port X.\n% Assumed equal for both components.\n% bin_pt_X = Binary Point for port X.\n% Assumed equal for both components.\n% quantization = Quantization mode\n% 1 = 'Truncate'\n% 2 = 'Round (unbiased: +/- Inf)'\n% 3 = 'Round (unbiased: Even Values)'\n% overflow - Overflow mode\n% 1 = 'Wrap'\n% 2 = 'Saturate'\n% mult_latency = Latency to use for the underlying real multipliers.\n% add_latency = Latency to use for the underlying real adders.\n% conjugated = Whether or not to conjugate the 'a' input.\n\n % Set default vararg values.\n % reg_retiming is not an actual parameter of this block, but it is included\n % in defaults so that same_state will return false for blocks drawn prior to\n % adding reg_retiming='on' to some of the underlying Delay blocks.\n defaults = { ...\n 'n_bits_a', 18, ...\n 'bin_pt_a', 17, ...\n 'n_bits_b', 18, ...\n 'bin_pt_b', 17, ...\n 'n_bits_ab', 37, ...\n 'bin_pt_ab', 14, ...\n 'quantization', 'Truncate', ...\n 'overflow', 'Wrap', ...\n 'mult_latency', 3, ...\n 'add_latency', 1, ...\n 'conv_latency', 1, ...\n 'in_latency', 0, ...\n 'conjugated', 'off', ...\n 'async', 'off', ...\n 'pipelined_enable', 'on', ...\n 'multiplier_implementation', 'behavioral HDL', ...\n 'reg_retiming', 'on', ...\n };\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n\n munge_block(blk,varargin);\n\n n_bits_a = get_var('n_bits_a','defaults',defaults,varargin{:});\n n_bits_b = get_var('n_bits_b','defaults',defaults,varargin{:});\n n_bits_ab = get_var('n_bits_ab','defaults',defaults,varargin{:});\n bin_pt_a = get_var('bin_pt_a','defaults',defaults,varargin{:});\n bin_pt_b = get_var('bin_pt_b','defaults',defaults,varargin{:});\n bin_pt_ab = get_var('bin_pt_ab','defaults',defaults,varargin{:});\n quantization = get_var('quantization','defaults',defaults,varargin{:});\n overflow = get_var('overflow','defaults',defaults,varargin{:});\n mult_latency = get_var('mult_latency','defaults',defaults,varargin{:});\n add_latency = get_var('add_latency','defaults',defaults,varargin{:});\n conv_latency = get_var('conv_latency','defaults',defaults,varargin{:});\n in_latency = get_var('in_latency','defaults',defaults,varargin{:});\n conjugated = get_var('conjugated','defaults',defaults,varargin{:});\n async = get_var('async','defaults',defaults,varargin{:});\n pipelined_enable = get_var('pipelined_enable','defaults',defaults,varargin{:});\n multiplier_implementation = get_var('multiplier_implementation','defaults',defaults,varargin{:});\n\n delete_lines(blk);\n\n if n_bits_a == 0 || n_bits_b == 0,\n clean_blocks(blk);\n set_param(blk,'AttributesFormatString','');\n save_state(blk, 'defaults', defaults, varargin{:});\n return;\n end\n\n if (n_bits_a < bin_pt_a),\n errordlg('Number of bits for a input must be greater than binary point position.'); return; end\n if (n_bits_b < bin_pt_b),\n errordlg('Number of bits for b input must be greater than binary point position.'); return; end\n if (n_bits_ab < bin_pt_ab),\n errordlg('Number of bits for ab input must be greater than binary point position.'); return; end\n\n %ports\n\n reuse_block(blk, 'a', 'built-in/Inport', 'Port', '1', 'Position', [5 148 35 162]);\n reuse_block(blk, 'b', 'built-in/Inport', 'Port', '2', 'Position', [5 333 35 347]);\n \n if strcmp(async, 'on'),\n reuse_block(blk, 'en', 'built-in/Inport', 'Port', '3', 'Position', [5 478 35 492]);\n end \n \n %replication layer\n \n if strcmp(async, 'off') || strcmp(pipelined_enable, 'on'), latency = in_latency;\n else, latency = 0;\n end\n \n reuse_block(blk, 'a_replicate', 'casper_library_bus/bus_replicate', ...\n 'replication', '2', 'latency', num2str(latency), 'misc', 'off', ...\n 'Position', [90 143 125 167]);\n add_line(blk, 'a/1', 'a_replicate/1'); \n \n reuse_block(blk, 'b_replicate', 'casper_library_bus/bus_replicate', ...\n 'replication', '2', 'latency', num2str(latency), 'misc', 'off', ...\n 'Position', [90 328 125 352]);\n add_line(blk, 'b/1', 'b_replicate/1'); \n\n if strcmp(async, 'on'),\n reuse_block(blk, 'en_replicate0', 'casper_library_bus/bus_replicate', ...\n 'replication', '5', 'latency', num2str(latency), 'misc', 'off', ...\n 'Position', [90 473 125 497]);\n add_line(blk, 'en/1', 'en_replicate0/1'); \n\n reuse_block(blk, 'en_expand0', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', '5', ...\n 'outputWidth', mat2str(ones(1, 5)), 'outputBinaryPt', mat2str(zeros(1, 5)), ...\n 'outputArithmeticType', mat2str(2*ones(1, 5)), ...\n 'Position', [180 436 230 534]);\n add_line(blk, 'en_replicate0/1', 'en_expand0/1'); \n end \n\n %bus_expand layer\n \n reuse_block(blk, 'a_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', '4', ...\n 'outputWidth', mat2str(repmat(n_bits_a, 1, 4)), ...\n 'outputBinaryPt', mat2str(repmat(bin_pt_a, 1, 4)), ...\n 'outputArithmeticType', mat2str(ones(1,4)), ...\n 'Position', [180 106 230 199]);\n add_line(blk, 'a_replicate/1', 'a_expand/1'); \n \n reuse_block(blk, 'b_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', '4', ...\n 'outputWidth', mat2str(repmat(n_bits_b, 1, 4)), ...\n 'outputBinaryPt', mat2str(repmat(bin_pt_b, 1, 4)), ...\n 'outputArithmeticType', mat2str(ones(1,4)), ...\n 'Position', [180 291 230 384]);\n add_line(blk, 'b_replicate/1', 'b_expand/1'); \n \n %multipliers\n\n if strcmp(multiplier_implementation, 'behavioral HDL'),\n use_behavioral_HDL = 'on';\n use_embedded = 'off';\n else\n use_behavioral_HDL = 'off';\n if strcmp(multiplier_implementation, 'embedded multiplier core'),\n use_embedded = 'on';\n elseif strcmp(multiplier_implementation, 'standard core'),\n use_embedded = 'off';\n else,\n end\n end\n\n reuse_block(blk, 'rere', 'xbsIndex_r4/Mult', ...\n 'use_behavioral_HDL', use_behavioral_HDL, 'use_embedded', use_embedded, ...\n 'en', async, 'latency', num2str(mult_latency), 'precision', 'Full', ...\n 'Position', [290 102 340 153]);\n add_line(blk, 'a_expand/1', 'rere/1');\n add_line(blk, 'b_expand/1', 'rere/2');\n\n reuse_block(blk, 'imim', 'xbsIndex_r4/Mult', ...\n 'use_behavioral_HDL', use_behavioral_HDL, 'use_embedded', use_embedded, ...\n 'en', async, 'latency', num2str(mult_latency), 'precision', 'Full', ...\n 'Position', [290 172 340 223]);\n add_line(blk, 'a_expand/2', 'imim/1');\n add_line(blk, 'b_expand/2', 'imim/2');\n\n reuse_block(blk, 'imre', 'xbsIndex_r4/Mult', ...\n 'use_behavioral_HDL', use_behavioral_HDL, 'use_embedded', use_embedded, ...\n 'en', async, 'latency', num2str(mult_latency), 'precision', 'Full', ...\n 'Position', [290 267 340 318]);\n add_line(blk, 'a_expand/4', 'imre/1');\n add_line(blk, 'b_expand/3', 'imre/2');\n\n reuse_block(blk, 'reim', 'xbsIndex_r4/Mult', ...\n 'use_behavioral_HDL', use_behavioral_HDL, 'use_embedded', use_embedded, ...\n 'en', async, 'latency', num2str(mult_latency), 'precision', 'Full', ...\n 'Position', [290 337 340 388]);\n add_line(blk, 'a_expand/3', 'reim/1');\n add_line(blk, 'b_expand/4', 'reim/2');\n\n if strcmp(async, 'on'),\n add_line(blk, 'en_expand0/1', 'rere/3');\n add_line(blk, 'en_expand0/2', 'imim/3');\n add_line(blk, 'en_expand0/3', 'imre/3');\n add_line(blk, 'en_expand0/4', 'reim/3');\n\n if strcmp(pipelined_enable, 'on'), latency = mult_latency;\n else, latency = 0;\n end\n\n reuse_block(blk, 'en_replicate1', 'casper_library_bus/bus_replicate', ...\n 'replication', '3', 'latency', num2str(latency), 'misc', 'off', ...\n 'Position', [295 523 330 547]);\n add_line(blk, 'en_expand0/5', 'en_replicate1/1');\n\n reuse_block(blk, 'en_expand1', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', '3', ...\n 'outputWidth', mat2str(ones(1, 3)), 'outputBinaryPt', mat2str(zeros(1, 3)), ...\n 'outputArithmeticType', mat2str(2*ones(1, 3)), ...\n 'Position', [355 499 405 571]);\n add_line(blk, 'en_replicate1/1', 'en_expand1/1'); \n end\n\n %add/subs\n reuse_block(blk, 'addsub_re', 'xbsIndex_r4/AddSub', ...\n 'en', async, 'use_behavioral_HDL', 'on', 'pipelined', 'on', ...\n 'latency', num2str(add_latency), 'use_rpm', 'on', 'precision', 'Full', ...\n 'Position', [445 94 495 236]);\n add_line(blk, 'rere/1', 'addsub_re/1');\n add_line(blk, 'imim/1', 'addsub_re/2');\n\n reuse_block(blk, 'addsub_im', 'xbsIndex_r4/AddSub', ...\n 'en', async, 'use_behavioral_HDL', 'on', 'pipelined', 'on', ...\n 'latency', num2str(add_latency), 'use_rpm', 'on', 'precision', 'Full', ...\n 'Position', [445 259 495 401]);\n add_line(blk, 'imre/1', 'addsub_im/1');\n add_line(blk, 'reim/1', 'addsub_im/2');\n\n % Set conjugation mode.\n if strcmp(conjugated, 'on'),\n set_param([blk, '/addsub_re'], 'mode', 'Addition');\n set_param([blk, '/addsub_im'], 'mode', 'Subtraction');\n else,\n set_param([blk, '/addsub_re'], 'mode', 'Subtraction');\n set_param([blk, '/addsub_im'], 'mode', 'Addition');\n end\n \n if strcmp(async, 'on'),\n add_line(blk, 'en_expand1/1', 'addsub_re/3');\n add_line(blk, 'en_expand1/2', 'addsub_im/3');\n\n if strcmp(pipelined_enable, 'on'), \n latency = add_latency;\n replication = 3;\n else, \n latency = 0;\n replication = 2;\n end\n\n reuse_block(blk, 'en_replicate2', 'casper_library_bus/bus_replicate', ...\n 'replication', '3', 'latency', num2str(latency), 'misc', 'off', ...\n 'Position', [450 548 485 572]);\n add_line(blk, 'en_expand1/3', 'en_replicate2/1');\n\n reuse_block(blk, 'en_expand2', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ...\n 'outputWidth', mat2str(ones(1, replication)), 'outputBinaryPt', mat2str(zeros(1, replication)), ...\n 'outputArithmeticType', mat2str(2*ones(1, replication)), ...\n 'Position', [515 524 565 596]);\n add_line(blk, 'en_replicate2/1', 'en_expand2/1'); \n end\n \n%code below taken from original cmult_init script but unsure of what is supposed to happen \n% % If overflow mode is \"wrap\", do the wrap for free in the multipliers\n% % and post-multiply adders to save bits.\n% wrapables={'rere', 'imim', 'imre', 'reim', 'addsub_re', 'addsub_im'};\n% if overflow == 1,\n% bin_pt_wrap=bin_pt_b+bin_pt_a;\n% n_bits_wrap=(n_bits_ab-bin_pt_ab)+bin_pt_wrap;\n\n% for name=wrapables\n% set_param([blk,'/',name{1}], ...\n% 'precision', 'User Defined', ...\n% 'arith_type', 'Signed (2''s comp)', ...\n% 'n_bits', num2str(n_bits_wrap), ...\n% 'bin_pt', num2str(bin_pt_wrap), ...\n% 'quantization', 'Truncate', ...\n% 'overflow', 'Wrap');\n% end\n% else\n% for name=wrapables\n% set_param([blk, '/', name{1}], 'precision', 'Full');\n% end\n% end\n\n %convert\n reuse_block(blk, 'convert_re', 'xbsIndex_r4/Convert', ...\n 'en', async, 'n_bits', num2str(n_bits_ab), 'bin_pt', num2str(bin_pt_ab), ...\n 'quantization', quantization, 'overflow', overflow, 'pipeline', 'on', ...\n 'latency', num2str(conv_latency), 'Position', [595 152 640 183]);\n add_line(blk, 'addsub_re/1', 'convert_re/1');\n\n reuse_block(blk, 'convert_im', 'xbsIndex_r4/Convert', ...\n 'en', async, 'n_bits', num2str(n_bits_ab), 'bin_pt', num2str(bin_pt_ab), ...\n 'quantization', quantization, 'overflow', overflow, 'pipeline', 'on', ...\n 'latency', num2str(conv_latency), 'Position', [595 317 640 348]);\n add_line(blk,'addsub_im/1','convert_im/1');\n\n if strcmp(async, 'on'),\n add_line(blk, 'en_expand2/1', 'convert_re/2');\n add_line(blk, 'en_expand2/2', 'convert_im/2');\n \n if strcmp(pipelined_enable, 'on'), \n reuse_block(blk, 'den', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(latency), 'reg_retiming', 'on', ...\n 'Position', [600 574 635 596]);\n add_line(blk, 'en_expand2/3', 'den/1');\n latency = conv_latency;\n else, \n latency = mult_latency + add_latency + conv_latency;\n end\n end\n\n %output ports\n\n reuse_block(blk, 'ri_to_c', 'casper_library_misc/ri_to_c', ...\n 'Position', [660 229 700 271]);\n add_line(blk,'convert_re/1','ri_to_c/1');\n add_line(blk,'convert_im/1','ri_to_c/2');\n\n reuse_block(blk, 'ab', 'built-in/Outport', ...\n 'Port', '1', ...\n 'Position', [745 243 775 257]);\n add_line(blk,'ri_to_c/1','ab/1');\n\n if strcmp(async, 'on') && strcmp(pipelined_enable, 'on'),\n reuse_block(blk, 'dvalid', 'built-in/Outport', ...\n 'Port', '2', ...\n 'Position', [745 438 775 452]);\n add_line(blk, 'den/1', 'dvalid/1');\n end\n\n clean_blocks(blk);\n\n % Set attribute format string (block annotation)\n annotation=sprintf('%d_%d * %d_%d ==> %d_%d\\n%s, %s\\nLatency=%d', ...\n n_bits_a,bin_pt_a,n_bits_b,bin_pt_b,n_bits_ab,bin_pt_ab,quantization,overflow,latency);\n set_param(blk,'AttributesFormatString',annotation);\n\n % Save and back-populate mask parameter values\n save_state(blk, 'defaults', defaults, varargin{:});\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "propagate_vars.m", "ext": ".m", "path": "mlib_devel-master/casper_library/propagate_vars.m", "size": 2403, "source_encoding": "utf_8", "md5": "554d3ff7095f1958d659d4526bdb56b6", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006-2007 Terry Filiba, David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction propagate_vars(blk, varargin)\r\n% Propagates values from varargin to parameters in blk of the same name. \r\n% If varname is not found, looks for 'defaults' and tries to find varname \r\n% in there. \r\n%\r\n% value = get_var(varname, varargin)\r\n%\r\n% blk = the block to propagate to.\r\n% varargin = {'varname', value, ...} pairs\r\n\r\nparams = fieldnames(get_param(blk, 'DialogParameters'));\r\n% loop through the block parameters\r\nfor i=1:length(params),\r\n % find that parameter in the current block or defaults\r\n found = get_var(params{i},varargin{:}); \r\n % if parameter of the same name is found, copy\r\n if ~isnan(found),\r\n \tset_param(blk, params{i}, tostring(found));\r\n end\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "twiddle_general_3mult_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/twiddle_general_3mult_init.m", "size": 15210, "source_encoding": "utf_8", "md5": "1274f1b5c8cdef1a8d3ad7f931f58f27", "text": "% twiddle_general_3mult_init(blk, varargin)\r\n%\r\n% blk = The block to configure\r\n% varargin = {'varname', 'value, ...} pairs\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Karoo Array Telesope %\r\n% http://www.kat.ac.za %\r\n% Copyright (C) 2009 Andrew Martens %\r\n% %\r\n% Radio Astronomy Lab %\r\n% University of California, Berkeley %\r\n% http://ral.berkeley.edu/ %\r\n% Copyright (C) 2010 David MacMahon %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction twiddle_general_3mult_init(blk, varargin)\r\n\r\nclog('entering twiddle_general_3mult_init', 'trace');\r\ndefaults = {'Coeffs', [0, j], 'StepPeriod', 0, 'input_bit_width', 18, ...\r\n 'coeff_bit_width', 18,'add_latency', 1, 'mult_latency', 2, ...\r\n 'conv_latency', 1, 'bram_latency', 2, 'arch', 'Virtex5', ...\r\n 'coeffs_bram', 'off', 'use_hdl', 'off', 'use_embedded', 'off', ...\r\n 'quantization', 'Round (unbiased: +/- Inf)', 'overflow', 'Wrap'};\r\n\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('twiddle_general_3mult_init post same_state','trace');\r\ncheck_mask_type(blk, 'twiddle_general_3mult');\r\nmunge_block(blk, varargin{:});\r\n\r\nCoeffs = get_var('Coeffs', 'defaults', defaults, varargin{:});\r\nStepPeriod = get_var('StepPeriod', 'defaults', defaults, varargin{:});\r\ninput_bit_width = get_var('input_bit_width', 'defaults', defaults, varargin{:});\r\ncoeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\nconv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\r\narch = get_var('arch', 'defaults', defaults, varargin{:});\r\ncoeffs_bram = get_var('coeffs_bram', 'defaults', defaults, varargin{:});\r\nuse_hdl = get_var('use_hdl', 'defaults', defaults, varargin{:});\r\nuse_embedded = get_var('use_embedded', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\noverflow = get_var('overflow', 'defaults', defaults, varargin{:});\r\n\r\nclog(flatstrcell(varargin),'twiddle_general_3mult_init_debug');\r\n\r\nif( strcmp(arch,'Virtex2Pro') ),\r\nelseif( strcmp(arch,'Virtex5') ),\r\nelse,\r\n clog(['twiddle_general_3mult_init: unknown target architecture ',arch],'error');\r\n error('twiddle_general_3mult_init.m: Unknown target architecture');\r\n return;\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\n%default case, leave clean block with nothing for storage in the libraries \r\nif isempty(Coeffs)\r\n clean_blocks(blk);\r\n set_param(blk, 'AttributesFormatString', '');\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting twiddle_general_3mult_init', 'trace');\r\n return;\r\nend\r\n\r\n%a input signal path\r\nreuse_block(blk, 'a', 'built-in/inport', 'Port', '1', 'Position',[225 28 255 42]);\r\nreuse_block(blk, 'delay0', 'xbsIndex_r4/Delay', ...\r\n 'latency','mult_latency + 2*add_latency + bram_latency + conv_latency', ...\r\n 'Position', [275 15 315 55]);\r\nadd_line(blk, 'a/1', 'delay0/1');\r\nreuse_block(blk, 'c_to_ri1', 'casper_library_misc/c_to_ri', ...\r\n 'n_bits', num2str(input_bit_width), 'bin_pt', num2str(input_bit_width-1), ...\r\n 'Position', [340 14 380 56]);\r\nadd_line(blk,'delay0/1','c_to_ri1/1');\r\nreuse_block(blk, 'a_re', 'built-in/outport', 'Port', '1', 'Position', [405 13 435 27]);\r\nreuse_block(blk, 'a_im', 'built-in/outport', 'Port', '2', 'Position', [405 43 435 57]);\r\nadd_line(blk, 'c_to_ri1/1', 'a_re/1');\r\nadd_line(blk, 'c_to_ri1/2', 'a_im/1');\r\n\r\n%sync input signal path\r\nreuse_block(blk, 'sync', 'built-in/inport', 'Port', '3', 'Position',[40 463 70 477]);\r\nreuse_block(blk, 'delay2', 'xbsIndex_r4/Delay', ...\r\n 'latency','mult_latency + 2*add_latency + bram_latency + conv_latency', ...\r\n 'Position', [280 450 320 490]);\r\nadd_line(blk, 'sync/1', 'delay2/1');\r\nreuse_block(blk, 'sync_out', 'built-in/outport', 'Port', '5', 'Position', [340 463 370 477]);\r\nadd_line(blk, 'delay2/1', 'sync_out/1');\r\n\r\n%coefficient generator\r\nreuse_block(blk, 'coeff_gen', 'casper_library_ffts_twiddle_coeff_gen/coeff_gen', ...\r\n 'Coeffs', tostring(Coeffs), ...\r\n 'StepPeriod', tostring(StepPeriod), 'coeff_bit_width', num2str(coeff_bit_width-1), ...\r\n 'bram_latency', 'bram_latency', 'coeffs_bram', coeffs_bram, ...\r\n 'Position', [100 319 145 361]);\r\nadd_line(blk, 'sync/1', 'coeff_gen/1');\r\n\r\nreuse_block(blk, 'c_to_ri2', 'casper_library_misc/c_to_ri', ...\r\n 'n_bits', num2str(coeff_bit_width-1), 'bin_pt', num2str(coeff_bit_width-3), ...\r\n 'Position', [180 319 220 361]);\r\nadd_line(blk, 'coeff_gen/1', 'c_to_ri2/1');\r\nreuse_block(blk, 'AddSub2', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ...\r\n 'use_behavioral_HDL', 'on', ...\r\n 'mode', 'Addition', 'Position', [255 318 300 362]);\r\nadd_line(blk, 'c_to_ri2/1', 'AddSub2/1');\r\nadd_line(blk, 'c_to_ri2/2', 'AddSub2/2');\r\nreuse_block(blk, 'AddSub3', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ...\r\n 'use_behavioral_HDL', 'on', ...\r\n 'mode', 'Subtraction', 'Position', [255 388 300 432]);\r\nadd_line(blk, 'c_to_ri2/2', 'AddSub3/1');\r\nadd_line(blk, 'c_to_ri2/1', 'AddSub3/2');\r\nreuse_block(blk, 'delay5', 'xbsIndex_r4/Delay', 'latency', 'add_latency', ...\r\n 'reg_retiming', 'on', ...\r\n 'Position', [260 255 300 295]);\r\nadd_line(blk, 'c_to_ri2/1', 'delay5/1');\r\n\r\n%b input signal path\r\nreuse_block(blk, 'b', 'built-in/inport', 'Port', '2', 'Position',[50 98 80 112]);\r\nreuse_block(blk, 'delay1', 'xbsIndex_r4/Delay', 'latency', 'bram_latency', ...\r\n 'Position', [105 85 145 125]);\r\nadd_line(blk, 'b/1', 'delay1/1');\r\nreuse_block(blk, 'c_to_ri3', 'casper_library_misc/c_to_ri', ...\r\n 'n_bits', 'input_bit_width', 'bin_pt', 'input_bit_width-1', ...\r\n 'Position', [175 84 215 126]);\r\nadd_line(blk,'delay1/1', 'c_to_ri3/1');\r\nreuse_block(blk, 'AddSub1', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ...\r\n 'use_behavioral_HDL', 'on', ...\r\n 'mode', 'Addition', 'Position', [255 83 300 127]);\r\nadd_line(blk,'c_to_ri3/1', 'AddSub1/1');\r\nadd_line(blk,'c_to_ri3/2', 'AddSub1/2');\r\nreuse_block(blk, 'delay3', 'xbsIndex_r4/Delay', 'latency', 'add_latency', ...\r\n 'reg_retiming', 'on', ...\r\n 'Position', [260 145 300 185]);\r\nadd_line(blk, 'c_to_ri3/1','delay3/1');\r\nreuse_block(blk, 'delay4', 'xbsIndex_r4/Delay', 'latency', 'add_latency', ...\r\n 'reg_retiming', 'on', ...\r\n 'Position', [260 200 300 240]);\r\nadd_line(blk, 'c_to_ri3/2','delay4/1');\r\n\r\n%mult0\r\nreuse_block(blk, 'mult0', 'xbsIndex_r4/Mult', ...\r\n 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ...\r\n 'latency', 'mult_latency', ...\r\n 'Position', [380 93 425 137]);\r\nadd_line(blk, 'AddSub1/1', 'mult0/1');\r\nadd_line(blk, 'delay5/1', 'mult0/2');\r\n\r\n%mult1\r\nreuse_block(blk, 'mult1', 'xbsIndex_r4/Mult', ...\r\n 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ...\r\n 'latency', 'mult_latency', ...\r\n 'Position', [380 308 425 352]);\r\nadd_line(blk, 'delay4/1', 'mult1/1');\r\nadd_line(blk, 'AddSub2/1', 'mult1/2');\r\n\r\n%mult2\r\nreuse_block(blk, 'mult2', 'xbsIndex_r4/Mult', ...\r\n 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ...\r\n 'latency', 'mult_latency', ...\r\n 'Position', [380 378 425 422]);\r\nadd_line(blk, 'delay3/1', 'mult2/1');\r\nadd_line(blk, 'AddSub3/1', 'mult2/2');\r\n\r\n%post mult adders\r\nreuse_block(blk, 'AddSub', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ...\r\n 'use_behavioral_HDL', 'on', ...\r\n 'mode', 'Subtraction', 'Position', [525 103 570 147]);\r\nreuse_block(blk, 'AddSub4', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ...\r\n 'use_behavioral_HDL', 'on', ...\r\n 'mode', 'Addition', 'Position', [525 303 570 347]);\r\n\r\nreuse_block(blk, 'bw_re', 'built-in/outport', 'Port', '3', 'Position', [740 118 780 132]);\r\nreuse_block(blk, 'bw_im', 'built-in/outport', 'Port', '4', 'Position', [740 318 780 332]);\r\n\r\n% First delete any convert blocks that exist so that different architectures\r\n% can use different convert blocks. For Virtex2Pro, use CASPER convert blocks.\r\n% For Virtex5 blocks, use Xilinx convert blocks (for \"historical\"\r\n% compatibility; recommend changing V5 to use CASPER convert blocks, too).\r\n% Deleting beforehand is needed so that reuse_block for V2P will not try to\r\n% configure Xilinx convert blocks (left over from code for V5) as CASPER\r\n% convert blocks and vice versa.\r\n%\r\n% It would probably be better to simply change the block in\r\n% casper_library_ffts_twiddle.mdl to use CASPER converts always regardless of\r\n% architecture (e.g. V5 vs V2P), but changing the .mdl file is riskier in that\r\n% it could lead to merges that tend not to be pleasant.\r\nfor k=2:4\r\n conv_name = sprintf('convert%d', k);\r\n conv_blk = find_system(blk, ...\r\n 'LookUnderMasks','all', 'FollowLinks','on', ...\r\n 'SearchDepth',1, 'Name',conv_name);\r\n if ~isempty(conv_blk)\r\n delete_block(conv_blk{1});\r\n end\r\nend\r\n\r\n%architecture specific logic\r\nif( strcmp(arch,'Virtex2Pro') ),\r\n\r\n %add convert blocks to reduce logic in adders\r\n\r\n % Multiplication by a complex twiddle factor is nothing more than a\r\n % rotation in the complex plane. The bit width of the input value being\r\n % twiddled can grow no more than one non-fractional bit. The input value\r\n % does not gain more precision by being twiddled so therefore it need not\r\n % grow any fractional bits.\r\n %\r\n % Since the growth by one non-fractional bit provides sufficient dynamic\r\n % range for the twiddle operation, any \"overflow\" can (and should!) be\r\n % ignored (i.e. set to \"Wrap\"; *not* set to \"Saturate\").\r\n\r\n reuse_block(blk, 'convert2', 'casper_library_misc/convert', ...\r\n 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-3)', ...\r\n 'n_bits_out', 'input_bit_width+1', ...\r\n 'bin_pt_out', 'input_bit_width-1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', 'Wrap', ...\r\n 'Position', [445 100 485 130]);\r\n add_line(blk, 'mult0/1', 'convert2/1');\r\n\r\n reuse_block(blk, 'convert3', 'casper_library_misc/convert', ...\r\n 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-3)', ...\r\n 'n_bits_out', 'input_bit_width+1', ...\r\n 'bin_pt_out', 'input_bit_width-1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', 'Wrap', ...\r\n 'Position', [445 315 485 345]);\r\n add_line(blk, 'mult1/1', 'convert3/1');\r\n\r\n reuse_block(blk, 'convert4', 'casper_library_misc/convert', ...\r\n 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-3)', ...\r\n 'n_bits_out', 'input_bit_width+1', ...\r\n 'bin_pt_out', 'input_bit_width-1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', 'Wrap', ...\r\n 'Position', [445 385 485 415]);\r\n add_line(blk, 'mult2/1', 'convert4/1');\r\n\r\n %join convert blocks to adders\r\n add_line(blk, 'convert2/1', 'AddSub/1');\r\n add_line(blk, 'convert3/1', 'AddSub/2');\r\n add_line(blk, 'convert2/1', 'AddSub4/1');\r\n add_line(blk, 'convert4/1', 'AddSub4/2');\r\n\r\n %join adders to ouputs\r\n add_line(blk, 'AddSub/1', 'bw_re/1');\r\n add_line(blk, 'AddSub4/1', 'bw_im/1');\r\n\r\n % Set output precision on adder outputs\r\n set_param([blk,'/AddSub'], ...\r\n 'precision', 'User Defined', ...\r\n 'arith_type', 'Signed (2''s comp)', ...\r\n 'n_bits', 'input_bit_width+1', ...\r\n 'bin_pt', 'input_bit_width-1', ...\r\n 'quantization', 'Truncate', ...\r\n 'overflow', 'Wrap');\r\n\r\n set_param([blk,'/AddSub4'], ...\r\n 'precision', 'User Defined', ...\r\n 'arith_type', 'Signed (2''s comp)', ...\r\n 'n_bits', 'input_bit_width+1', ...\r\n 'bin_pt', 'input_bit_width-1', ...\r\n 'quantization', 'Truncate', ...\r\n 'overflow', 'Wrap');\r\n\r\nelseif( strcmp(arch,'Virtex5') )\r\n %add convert blocks to after adders to ensure adders absorbed into multipliers\r\n add_line(blk, 'mult0/1', 'AddSub/1');\r\n add_line(blk, 'mult1/1', 'AddSub/2');\r\n add_line(blk, 'mult0/1', 'AddSub4/1');\r\n add_line(blk, 'mult2/1', 'AddSub4/2');\r\n\r\n reuse_block(blk, 'convert2', 'xbsIndex_r4/Convert', ...\r\n 'pipeline', 'on', ...\r\n 'n_bits', 'input_bit_width+5', ...\r\n 'bin_pt', 'input_bit_width+1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', tostring(overflow), ...\r\n 'Position', [600 105 650 140]);\r\n add_line(blk, 'AddSub/1', 'convert2/1');\r\n add_line(blk, 'convert2/1', 'bw_re/1');\r\n\r\n reuse_block(blk, 'convert3', 'xbsIndex_r4/Convert', ...\r\n 'pipeline', 'on', ...\r\n 'n_bits', 'input_bit_width+5', ...\r\n 'bin_pt', 'input_bit_width+1', ...\r\n 'latency', 'conv_latency', 'quantization', tostring(quantization), ...\r\n 'overflow', tostring(overflow), ...\r\n 'Position', [600 305 650 340]);\r\n add_line(blk, 'AddSub4/1', 'convert3/1');\r\n add_line(blk, 'convert3/1', 'bw_im/1');\r\n\r\nelse\r\n return;\r\nend\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('data=(%d,%d)\\ncoeffs=(%d,%d)\\n%s\\n(%s,%s)', ...\r\n input_bit_width, input_bit_width-1, coeff_bit_width-1, coeff_bit_width-3, arch, quantization, overflow);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\nclog('exiting twiddle_general_3mult_init','trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "first_tap_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/first_tap_init.m", "size": 3182, "source_encoding": "utf_8", "md5": "50e9b43589ff76f954942548c2469f51", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction first_tap_init(blk, varargin)\r\n% Initialize and configure the first tap of the Polyphase Filter Bank.\r\n%\r\n% first_tap_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% PFBSize = The size of the PFB\r\n% CoeffBitWidth = Bitwidth of Coefficients.\r\n% TotalTaps = Total number of taps in the PFB\r\n% BitWidthIn = Input Bitwidth\r\n% WindowType = The type of windowing function to use.\r\n% mult_latency = Latency through each multiplier\r\n% bram_latency = Latency through each BRAM.\r\n% n_inputs = The number of parallel inputs\r\n% fwidth = Scaling of the width of each PFB channel\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'first_tap');\r\nmunge_block(blk, varargin{:});\r\n\r\nTotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:});\r\nuse_hdl = get_var('use_hdl','defaults', defaults, varargin{:});\r\nuse_embedded = get_var('use_embedded','defaults', defaults, varargin{:});\r\n\r\nset_param([blk,'/Mult'],'use_embedded', use_embedded);\r\nset_param([blk,'/Mult'],'use_behavioral_HDL', use_hdl);\r\nset_param([blk,'/Mult1'],'use_embedded', use_embedded);\r\nset_param([blk,'/Mult1'],'use_behavioral_HDL', use_hdl)\r\n\r\nfmtstr = sprintf('taps=%d', TotalTaps);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "butterfly_direct_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/butterfly_direct_init.m", "size": 22175, "source_encoding": "utf_8", "md5": "4874f5db36e43f539e5f319cc57d131b", "text": "% Initialize and configure a butterfly_direct block.\n%\n% butterfly_direct_init(blk, varargin)\n%\n% blk = the block to configure\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames:\n% * biplex = Make biplex.\n% * FFTSize = Size of the FFT (2^FFTSize points).\n% * Coeffs = Coefficients for twiddle blocks.\n% * StepPeriod = Coefficient step period.\n% * coeffs_bram = Store coefficients in BRAM.\n% * coeff_bit_width = Bitwdith of coefficients.\n% * input_bit_width = Bitwidth of input data.\n% * bin_pt_in = Binary point position of input data.\n% * bitgrowth = Option to grow non-fractional bits by so don't have to shift.\n% * downshift = Explicitly downshift output data if shifting.\n% * bram_latency = Latency of BRAM blocks.\n% * add_latency = Latency of adders blocks.\n% * mult_latency = Latency of multiplier blocks.\n% * conv_latency = Latency of cast blocks.\n% * quantization = Quantization behavior.\n% * overflow = Overflow behavior.\n% * use_hdl = Use behavioral HDL for multipliers.\n% * use_embedded = Use embedded multipliers.\n% * hardcode_shifts = If not using bit growth, option to hardcode downshift setting.\n% * dsp48_adders = Use DSP48-based adders.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://casper.berkeley.edu %\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\n% Copyright (C) 2010 William Mallard, David MacMahon %\n% %\n% SKASA radio telescope project %\n% www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction butterfly_direct_init(blk, varargin)\n\n clog('entering butterfly_direct_init', {'trace', 'butterfly_direct_init_debug'});\n\n % Set default vararg values.\n defaults = { ...\n 'n_inputs', 1, ...\n 'biplex', 'on', ...\n 'FFTSize', 6, ...\n 'Coeffs', bit_rev([0:2^5-1],5), ...\n 'StepPeriod', 1, ...\n 'coeff_bit_width', 18, ...\n 'input_bit_width', 18, ...\n 'bin_pt_in', 17, ...\n 'bitgrowth', 'off', ...\n 'downshift', 'off', ...\n 'async', 'off', ...\n 'add_latency', 1, ...\n 'mult_latency', 2, ...\n 'bram_latency', 2, ...\n 'conv_latency', 1, ...\n 'quantization', 'Truncate', ...\n 'overflow', 'Wrap', ...\n 'coeffs_bit_limit', 8, ...\n 'coeff_sharing', 'on', ...\n 'coeff_decimation', 'on', ...\n 'coeff_generation', 'on', ...\n 'cal_bits', 1, ...\n 'n_bits_rotation', 25, ...\n 'max_fanout', 4, ...\n 'use_hdl', 'off', ...\n 'use_embedded', 'off', ...\n 'hardcode_shifts', 'off', ...\n 'dsp48_adders', 'off', ...\n };\n\n % Skip init script if mask state has not changed.\n if same_state(blk, 'defaults', defaults, varargin{:}), return; end\n\n clog('butterfly_direct_init post same_state', {'trace', 'butterfly_direct_init_debug'});\n\n % Verify that this is the right mask for the block.\n check_mask_type(blk, 'butterfly_direct');\n\n % Disable link if state changes from default.\n munge_block(blk, varargin{:});\n\n % Retrieve values from mask fields.\n n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\n biplex = get_var('biplex', 'defaults', defaults, varargin{:});\n FFTSize = get_var('FFTSize', 'defaults', defaults, varargin{:});\n Coeffs = get_var('Coeffs', 'defaults', defaults, varargin{:});\n StepPeriod = get_var('StepPeriod', 'defaults', defaults, varargin{:});\n coeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\n input_bit_width = get_var('input_bit_width', 'defaults', defaults, varargin{:});\n bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:});\n bitgrowth = get_var('bitgrowth', 'defaults', defaults, varargin{:});\n downshift = get_var('downshift', 'defaults', defaults, varargin{:});\n async = get_var('async', 'defaults', defaults, varargin{:});\n bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\n add_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\n mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\n conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\n quantization = get_var('quantization', 'defaults', defaults, varargin{:});\n overflow = get_var('overflow', 'defaults', defaults, varargin{:});\n coeffs_bit_limit = get_var('coeffs_bit_limit', 'defaults', defaults, varargin{:});\n coeff_sharing = get_var('coeff_sharing', 'defaults', defaults, varargin{:});\n coeff_decimation = get_var('coeff_decimation', 'defaults', defaults, varargin{:});\n coeff_generation = get_var('coeff_generation', 'defaults', defaults, varargin{:});\n cal_bits = get_var('cal_bits', 'defaults', defaults, varargin{:});\n n_bits_rotation = get_var('n_bits_rotation', 'defaults', defaults, varargin{:});\n max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:});\n use_hdl = get_var('use_hdl', 'defaults', defaults, varargin{:});\n use_embedded = get_var('use_embedded', 'defaults', defaults, varargin{:});\n hardcode_shifts = get_var('hardcode_shifts', 'defaults', defaults, varargin{:});\n dsp48_adders = get_var('dsp48_adders', 'defaults', defaults, varargin{:});\n\n %default case for library storage, delete everything\n if n_inputs == 0 | FFTSize == 0,\n delete_lines(blk);\n clean_blocks(blk);\n set_param(blk, 'AttributesFormatString', '');\n save_state(blk, 'defaults', defaults, varargin{:});\n clog('exiting butterfly_direct_init', 'trace');\n return;\n end\n\n % bin_pt_in == -1 is a special case for backwards compatibility\n if bin_pt_in == -1\n bin_pt_in = input_bit_width - 1;\n set_mask_params(blk, 'bin_pt_in', num2str(bin_pt_in));\n end\n\n use_dsp48_mults = strcmp(use_embedded, 'on');\n use_dsp48_adders = strcmp(dsp48_adders, 'on');\n\n % Validate input fields.\n\n if strcmp(bitgrowth, 'on') || strcmp(hardcode_shifts, 'on'), mux_latency = 0;\n else mux_latency = 2;\n end\n\n %TODO\n if use_dsp48_adders,\n set_param(blk, 'add_latency', '2');\n add_latency = 2;\n end\n\n % Optimize twiddle for coeff = 0, 1, or alternating 0-1\n if length(Coeffs) == 1,\n if Coeffs(1) == 0,\n %if used in biplex core and first stage\n if(strcmp(biplex, 'on')),\n twiddle_type = 'twiddle_pass_through';\n else, %otherwise do same but make sure have correct delay\n twiddle_type = 'twiddle_coeff_0';\n end\n elseif Coeffs(1) == 1,\n twiddle_type = 'twiddle_coeff_1';\n else\n twiddle_type = 'twiddle_general';\n end\n elseif length(Coeffs)==2 && Coeffs(1)==0 && Coeffs(2)==1 && StepPeriod==FFTSize-2,\n twiddle_type = 'twiddle_stage_2';\n else\n twiddle_type = 'twiddle_general';\n end\n\n clog([twiddle_type, ' for twiddle'], 'butterfly_direct_init_debug');\n clog(['Coeffs = ', mat2str(Coeffs)], 'butterfly_direct_init_debug');\n\n % Compute bit widths into addsub and convert blocks.\n bw = input_bit_width + 3;\n bd = bin_pt_in+1;\n if strcmp(twiddle_type, 'twiddle_stage_2') ...\n || strcmp(twiddle_type, 'twiddle_coeff_0') ...\n || strcmp(twiddle_type, 'twiddle_coeff_1') ...\n || strcmp(twiddle_type, 'twiddle_pass_through'),\n bw = input_bit_width + 2;\n bd = bin_pt_in+1;\n end\n\n addsub_b_bitwidth = bw - 2;\n addsub_b_binpoint = bd - 1;\n\n n_bits_addsub_out = addsub_b_bitwidth+1;\n bin_pt_addsub_out = addsub_b_binpoint;\n\n if strcmp(bitgrowth, 'off') \n if strcmp(hardcode_shifts, 'on'),\n if strcmp(downshift, 'on'),\n convert_in_bitwidth = n_bits_addsub_out; \n convert_in_binpoint = bin_pt_addsub_out+1;\n else\n convert_in_bitwidth = n_bits_addsub_out;\n convert_in_binpoint = bin_pt_addsub_out;\n end\n else\n convert_in_bitwidth = n_bits_addsub_out+1;\n convert_in_binpoint = bin_pt_addsub_out+1;\n end\n else\n convert_in_bitwidth = n_bits_addsub_out;\n convert_in_binpoint = bin_pt_addsub_out;\n end \n\n %%%%%%%%%%%%%%%%%%\n % Start drawing! %\n %%%%%%%%%%%%%%%%%%\n\n % Delete all lines.\n delete_lines(blk);\n\n %\n % Add inputs and outputs.\n %\n\n reuse_block(blk, 'a', 'built-in/Inport', 'Port', '1', 'Position', [45 63 75 77]);\n reuse_block(blk, 'b', 'built-in/Inport', 'Port', '2', 'Position', [45 123 75 137]);\n reuse_block(blk, 'sync_in', 'built-in/Inport', 'Port', '3', 'Position', [45 183 75 197]);\n reuse_block(blk, 'shift', 'built-in/Inport', 'Port', '4', 'Position', [380 63 410 77]);\n if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/Inport', 'Port', '5','Position', [45 243 75 257]);\n end\n \n reuse_block(blk, 'a+bw', 'built-in/Outport', 'Port', '1', 'Position', [880 58 910 72]);\n reuse_block(blk, 'a-bw', 'built-in/Outport', 'Port', '2', 'Position', [880 88 910 102]);\n reuse_block(blk, 'of', 'built-in/Outport', 'Port', '3', 'Position', [880 143 910 157]);\n reuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '4', 'Position', [880 183 910 197]);\n if strcmp(async, 'on'),\n reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', '5', 'Position', [880 243 910 257]);\n end\n\n %\n % Add twiddle block.\n %\n\n params = {'n_inputs', num2str(n_inputs), 'async', async};\n\n if ~strcmp(twiddle_type, 'twiddle_pass_through'),\n params = { params{:}, ... \n 'add_latency', num2str(add_latency), ...\n 'mult_latency', num2str(mult_latency), ...\n 'bram_latency', num2str(bram_latency), ...\n 'conv_latency', num2str(conv_latency)};\n end\n \n if strcmp(twiddle_type, 'twiddle_coeff_1'),\n params = { params{:}, ...\n 'input_bit_width', num2str(input_bit_width), ...\n 'bin_pt_in', num2str(bin_pt_in)};\n elseif strcmp(twiddle_type, 'twiddle_stage_2'), \n params = { params{:}, ...\n 'FFTSize', num2str(FFTSize), ...\n 'input_bit_width', num2str(input_bit_width), ...\n 'bin_pt_in', num2str(bin_pt_in)};\n elseif strcmp(twiddle_type, 'twiddle_general'), \n params = { params{:}, ...\n 'FFTSize', num2str(FFTSize), ...\n 'Coeffs', mat2str(Coeffs), ...\n 'StepPeriod', num2str(StepPeriod), ...\n 'coeff_bit_width', num2str(coeff_bit_width), ...\n 'input_bit_width', num2str(input_bit_width), ...\n 'bin_pt_in', num2str(bin_pt_in), ...\n 'coeffs_bit_limit', num2str(coeffs_bit_limit), ...\n 'coeff_sharing', coeff_sharing, ...\n 'coeff_decimation', coeff_decimation, ...\n 'coeff_generation', coeff_generation, ...\n 'cal_bits', num2str(cal_bits), ...\n 'n_bits_rotation', num2str(n_bits_rotation), ...\n 'max_fanout', num2str(max_fanout), ...\n 'use_hdl', use_hdl, ...\n 'use_embedded', use_embedded, ...\n 'quantization', quantization, ...\n 'overflow', overflow}; \n end\n reuse_block(blk, 'twiddle', ['casper_library_ffts_twiddle/', twiddle_type], ...\n params{:}, 'Position', [120 37 205 283]);\n add_line(blk, 'a/1', 'twiddle/1');\n add_line(blk, 'b/1', 'twiddle/2');\n add_line(blk, 'sync_in/1', 'twiddle/3');\n\n %\n % Add complex add/sub blocks.\n %\n \n if strcmp(dsp48_adders, 'on'), add_implementation = 'DSP48 core';\n else add_implementation = 'behavioral HDL';\n end\n\n reuse_block(blk, 'bus_add', 'casper_library_bus/bus_addsub', ...\n 'opmode', '0', 'latency', num2str(add_latency), ...\n 'n_bits_a', mat2str(repmat(input_bit_width, 1, n_inputs)), ...\n 'bin_pt_a', mat2str(bin_pt_in), ...\n 'misc', 'off', ...\n 'n_bits_b', mat2str(repmat(addsub_b_bitwidth, 1, n_inputs)), ...\n 'bin_pt_b', num2str(addsub_b_binpoint), ...\n 'n_bits_out', num2str(addsub_b_bitwidth+1), ...\n 'bin_pt_out', num2str(addsub_b_binpoint), ...\n 'add_implementation', add_implementation, ...\n 'Position', [270 64 310 91]);\n add_line(blk, 'twiddle/1', 'bus_add/1');\n add_line(blk, 'twiddle/2', 'bus_add/2');\n\n reuse_block(blk, 'bus_sub', 'casper_library_bus/bus_addsub', ...\n 'opmode', '1', 'latency', num2str(add_latency), ...\n 'n_bits_a', mat2str(repmat(input_bit_width, 1, n_inputs)), ...\n 'bin_pt_a', mat2str(bin_pt_in), ...\n 'misc', 'off', ...\n 'n_bits_b', mat2str(repmat(addsub_b_bitwidth, 1, n_inputs)), ...\n 'bin_pt_b', num2str(addsub_b_binpoint), ...\n 'n_bits_out', num2str(addsub_b_bitwidth+1), ...\n 'bin_pt_out', num2str(addsub_b_binpoint), ...\n 'add_implementation', add_implementation, ...\n 'Position', [270 109 310 136]);\n add_line(blk, 'twiddle/1', 'bus_sub/1');\n add_line(blk, 'twiddle/2', 'bus_sub/2');\n\n reuse_block(blk, 'Concat', 'xbsIndex_r4/Concat', ...\n 'num_inputs', '2', ...\n 'Position', [340 59 370 146]);\n add_line(blk, 'bus_add/1', 'Concat/1');\n add_line(blk, 'bus_sub/1', 'Concat/2');\n \n %\n % Convert\n %\n if strcmp(quantization, 'Truncate'), quant = '0';\n elseif strcmp(quantization, 'Round (unbiased: +/- Inf)'), quant = '1';\n elseif strcmp(quantization, 'Round (unbiased: Even Values)'), quant = '2';\n else %TODO\n end\n \n if strcmp(overflow, 'Wrap'), of = '0';\n elseif strcmp(overflow, 'Saturate'), of = '1';\n elseif strcmp(overflow, 'Flag as error'), of = '2';\n else %TODO\n end\n\n if strcmp(bitgrowth, 'on'),\n n_bits_out = input_bit_width+1;\n else\n n_bits_out = input_bit_width;\n end\n\n reuse_block(blk, 'bus_convert', 'casper_library_bus/bus_convert', ...\n 'n_bits_in', mat2str(repmat(convert_in_bitwidth, 1, n_inputs*2)), ...\n 'bin_pt_in', mat2str(repmat(convert_in_binpoint, 1, n_inputs*2)), ...\n 'cmplx', 'on', ...\n 'n_bits_out', num2str(n_bits_out), ...\n 'bin_pt_out', num2str(bin_pt_in), ...\n 'quantization', quant, 'overflow', of, ...\n 'misc', 'off', 'of', 'on', 'latency', 'conv_latency', ...\n 'Position', [635 86 690 119]);\n\n %\n % Add scale \n %\n\n fan_latency = max(1, ceil(log2((n_inputs*2*2)/max_fanout)));\n\n if strcmp(bitgrowth, 'off') && strcmp(hardcode_shifts, 'off'),\n reuse_block(blk, 'shift_replicate', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(n_inputs*2*2), 'latency', num2str(fan_latency), 'misc', 'off', 'Position', [455 59 485 81]);\n\n add_line(blk, 'shift/1', 'shift_replicate/1');\n \n %required to add padding to match bit width of other stream (from bus_scale)\n reuse_block(blk, 'bus_norm0', 'casper_library_bus/bus_convert', ...\n 'n_bits_in', mat2str(repmat(addsub_b_bitwidth+1, 1, n_inputs*2)), ...\n 'bin_pt_in', mat2str(repmat(addsub_b_binpoint, 1, n_inputs*2)), ...\n 'cmplx', 'on', ...\n 'n_bits_out', num2str(addsub_b_bitwidth+2), ...\n 'bin_pt_out', num2str(addsub_b_binpoint+1), ...\n 'quantization', '0', 'overflow', '0', ...\n 'misc', 'off', 'of', 'off', 'latency', '0', ...\n 'Position', [500 92 545 118]);\n add_line(blk, 'Concat/1', 'bus_norm0/1'); \n\n reuse_block(blk, 'bus_scale', 'casper_library_bus/bus_scale', ...\n 'n_bits_in', mat2str(repmat(addsub_b_bitwidth+1, 1, n_inputs*2)), ...\n 'bin_pt_in', num2str(addsub_b_binpoint), ...\n 'cmplx', 'on', ...\n 'scale_factor', '-1', ...\n 'misc', 'off', ...\n 'Position', [405 127 450 153]);\n add_line(blk, 'Concat/1', 'bus_scale/1'); \n \n %scaling causes binary point to be moved up by one place \n reuse_block(blk, 'bus_norm1', 'casper_library_bus/bus_convert', ...\n 'n_bits_in', mat2str(repmat(addsub_b_bitwidth+1, 1, n_inputs*2)), ...\n 'bin_pt_in', mat2str(repmat(addsub_b_binpoint+1, 1, n_inputs*2)), ...\n 'cmplx', 'on', ...\n 'n_bits_out', num2str(addsub_b_bitwidth+2), ...\n 'bin_pt_out', num2str(addsub_b_binpoint+1), ...\n 'quantization', '0', 'overflow', '0', ...\n 'misc', 'off', 'of', 'off', 'latency', '0', ...\n 'Position', [500 127 545 153]);\n add_line(blk, 'bus_scale/1', 'bus_norm1/1'); \n\n reuse_block(blk, 'mux', 'casper_library_bus/bus_mux', ...\n 'n_inputs', '2', 'n_bits', mat2str(repmat(convert_in_bitwidth, 1, n_inputs*2*2)), ...\n 'cmplx', 'off', 'misc', 'off', 'mux_latency', num2str(mux_latency), ...\n 'Position', [580 53 610 157]);\n add_line(blk, 'shift_replicate/1', 'mux/1');\n add_line(blk, 'bus_norm0/1', 'mux/2');\n add_line(blk, 'bus_norm1/1', 'mux/3');\n add_line(blk, 'mux/1', 'bus_convert/1');\n \n else\n reuse_block(blk, 'Terminator', 'built-in/terminator', 'Position', [430 59 460 81], 'ShowName', 'off');\n add_line(blk, 'shift/1', 'Terminator/1');\n\n %if we are not growing bits and need to downshift\n if strcmp(bitgrowth, 'off') && strcmp(downshift, 'on'),\n reuse_block(blk, 'bus_scale', 'casper_library_bus/bus_scale', ...\n 'n_bits_in', mat2str(repmat(addsub_b_bitwidth+1, 1, n_inputs*2)), ... \n 'bin_pt_in', num2str(addsub_b_binpoint), ...\n 'cmplx', 'on', ...\n 'scale_factor', '-1', ...\n 'misc', 'off', ...\n 'Position', [405 127 450 153]);\n add_line(blk, 'Concat/1', 'bus_scale/1');\n add_line(blk, 'bus_scale/1', 'bus_convert/1'); \n else\n add_line(blk, 'Concat/1', 'bus_convert/1');\n end\n end %if hardcode_shifts\n\n %\n % bus_expand \n %\n\n reuse_block(blk, 'bus_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', ...\n 'outputNum', '2', 'outputWidth', mat2str(repmat(n_inputs*n_bits_out*2,1,2)), ...\n 'outputBinaryPt', '[0,0]', 'outputArithmeticType', '[0,0]', ... \n 'Position', [715 51 765 109]);\n add_line(blk, 'bus_convert/1', 'bus_expand/1');\n add_line(blk, 'bus_expand/1', 'a+bw/1');\n add_line(blk, 'bus_expand/2', 'a-bw/1');\n\n %\n % overflow detection for different input streams\n %\n \n %need to move a and b input streams next to each other for each input \n reuse_block(blk, 'munge', 'casper_library_flow_control/munge', ...\n 'divisions', num2str(n_inputs * 2), ...\n 'div_size', mat2str(repmat(2, 1, n_inputs*2)), ...\n 'order', mat2str(reshape([[0:n_inputs-1];[n_inputs:n_inputs*2-1]],1,n_inputs*2)), ...\n 'arith_type_out', 'Unsigned', 'bin_pt_out', '0', ...\n 'Position', [720 147 760 173]);\n add_line(blk, 'bus_convert/2', 'munge/1');\n \n reuse_block(blk, 'constant', 'xbsIndex_r4/Constant', ...\n 'const', '0', 'arith_type', 'Unsigned', 'n_bits', '4', 'bin_pt', '0', ...\n 'explicit_period', 'on', 'period', '1', 'Position', [775 127 790 143]);\n\n reuse_block(blk, 'bus_relational', 'casper_library_bus/bus_relational', ...\n 'n_bits_a', '4', 'bin_pt_a', '0', 'type_a', '0', ...\n 'n_bits_b', mat2str(repmat(4, 1, n_inputs)), 'bin_pt_b', '0', 'type_b', '0', ...\n 'mode', 'a!=b', 'misc', 'off', 'en', 'off', 'latency', '0', ...\n 'Position', [820 123 850 172]);\n add_line(blk, 'constant/1', 'bus_relational/1');\n add_line(blk, 'munge/1', 'bus_relational/2');\n add_line(blk, 'bus_relational/1', 'of/1');\n\n %\n % sync delay.\n %\n\n reuse_block(blk, 'delay0', 'xbsIndex_r4/Delay');\n set_param([blk,'/delay0'], ...\n 'latency', ['add_latency+',num2str(mux_latency),'+conv_latency'], ...\n 'reg_retiming', 'on', ...\n 'Position', [580 179 610 201]);\n add_line(blk, 'twiddle/3', 'delay0/1'); \n add_line(blk, 'delay0/1', 'sync_out/1'); \n\n %\n % dvalid delay.\n %\n\n if strcmp(async, 'on'),\n add_line(blk, 'en/1', 'twiddle/4');\n reuse_block(blk, 'delay1', 'xbsIndex_r4/Delay', ...\n 'latency', ['add_latency+',num2str(mux_latency),'+conv_latency'], ...\n 'reg_retiming', 'on', ...\n 'Position', [580 239 610 261]);\n add_line(blk, 'twiddle/4', 'delay1/1'); \n add_line(blk, 'delay1/1', 'dvalid/1'); \n end\n\n % Delete all unconnected blocks.\n clean_blocks(blk);\n\n %%%%%%%%%%%%%%%%%%%\n % Finish drawing! %\n %%%%%%%%%%%%%%%%%%%\n\n % Set attribute format string (block annotation).\n fmtstr = sprintf('%s', twiddle_type);\n set_param(blk, 'AttributesFormatString', fmtstr);\n\n % Save block state to stop repeated init script runs.\n save_state(blk, 'defaults', defaults, varargin{:});\n\n clog('exiting butterfly_direct_init', {'trace', 'butterfly_direct_init_debug'});\n\nend %function\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "casper_library_bus_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/casper_library_bus_init.m", "size": 44036, "source_encoding": "utf_8", "md5": "6051a65f926951968b15924edc2de8b5", "text": "function casper_library_bus_init()\n\n\twarning off Simulink:Engine:MdlFileShadowing;\n\tclose_system('casper_library_bus', 0);\n\tmdl = new_system('casper_library_bus', 'Library');\n\tblk = get(mdl,'Name');\n\twarning on Simulink:Engine:MdlFileShadowing;\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_addsub']);\n\tbus_addsub_gen([blk,'/bus_addsub']);\n\tset_param([blk,'/bus_addsub'], ...\n\t\t'opmode', sprintf('0'), ...\n\t\t'n_bits_a', sprintf('0'), ...\n\t\t'bin_pt_a', sprintf('3'), ...\n\t\t'type_a', sprintf('1'), ...\n\t\t'n_bits_b', sprintf('4'), ...\n\t\t'bin_pt_b', sprintf('3'), ...\n\t\t'type_b', sprintf('1'), ...\n\t\t'cmplx', sprintf('on'), ...\n\t\t'misc', sprintf('on'), ...\n\t\t'async', sprintf('off'), ...\n\t\t'n_bits_out', sprintf('8'), ...\n\t\t'bin_pt_out', sprintf('3'), ...\n\t\t'type_out', sprintf('1'), ...\n\t\t'quantization', sprintf('0'), ...\n\t\t'overflow', sprintf('1'), ...\n\t\t'add_implementation', sprintf('fabric core'), ...\n\t\t'latency', sprintf('1'), ...\n\t\t'Position', sprintf('[20 17 95 93]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_register']);\n\tbus_register_gen([blk,'/bus_register']);\n\tset_param([blk,'/bus_register'], ...\n\t\t'reset', sprintf('on'), ...\n\t\t'enable', sprintf('on'), ...\n\t\t'cmplx', sprintf('on'), ...\n\t\t'n_bits', sprintf('[]'), ...\n\t\t'misc', sprintf('on'), ...\n\t\t'Position', sprintf('[120 17 195 93]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_mux']);\n\tbus_mux_gen([blk,'/bus_mux']);\n\tset_param([blk,'/bus_mux'], ...\n\t\t'n_inputs', sprintf('0'), ...\n\t\t'n_bits', sprintf('8'), ...\n\t\t'mux_latency', sprintf('0'), ...\n\t\t'cmplx', sprintf('off'), ...\n\t\t'misc', sprintf('off'), ...\n\t\t'Position', sprintf('[20 129 95 211]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_mult']);\n\tbus_mult_gen([blk,'/bus_mult']);\n\tset_param([blk,'/bus_mult'], ...\n\t\t'n_bits_a', sprintf('0'), ...\n\t\t'bin_pt_a', sprintf('4'), ...\n\t\t'type_a', sprintf('1'), ...\n\t\t'cmplx_a', sprintf('on'), ...\n\t\t'n_bits_b', sprintf('4'), ...\n\t\t'bin_pt_b', sprintf('3'), ...\n\t\t'type_b', sprintf('1'), ...\n\t\t'cmplx_b', sprintf('on'), ...\n\t\t'n_bits_out', sprintf('12'), ...\n\t\t'bin_pt_out', sprintf('7'), ...\n\t\t'type_out', sprintf('1'), ...\n\t\t'quantization', sprintf('0'), ...\n\t\t'overflow', sprintf('0'), ...\n\t\t'mult_latency', sprintf('3'), ...\n\t\t'add_latency', sprintf('1'), ...\n\t\t'conv_latency', sprintf('1'), ...\n\t\t'max_fanout', sprintf('2'), ...\n\t\t'fan_latency', sprintf('0'), ...\n\t\t'multiplier_implementation', sprintf('behavioral HDL'), ...\n\t\t'misc', sprintf('on'), ...\n\t\t'Position', sprintf('[120 132 195 208]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_replicate']);\n\tbus_replicate_gen([blk,'/bus_replicate']);\n\tset_param([blk,'/bus_replicate'], ...\n\t\t'replication', sprintf('0'), ...\n\t\t'latency', sprintf('0'), ...\n\t\t'misc', sprintf('on'), ...\n\t\t'implementation', sprintf('core'), ...\n\t\t'Position', sprintf('[220 17 295 93]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_logical']);\n\tbus_logical_gen([blk,'/bus_logical']);\n\tset_param([blk,'/bus_logical'], ...\n\t\t'logical_function', sprintf('AND'), ...\n\t\t'align_bp', sprintf('on'), ...\n\t\t'latency', sprintf('1'), ...\n\t\t'n_bits_a', sprintf('[]'), ...\n\t\t'bin_pt_a', sprintf('3'), ...\n\t\t'type_a', sprintf('1'), ...\n\t\t'n_bits_b', sprintf('4'), ...\n\t\t'bin_pt_b', sprintf('3'), ...\n\t\t'type_b', sprintf('1'), ...\n\t\t'cmplx', sprintf('on'), ...\n\t\t'en', sprintf('on'), ...\n\t\t'misc', sprintf('on'), ...\n\t\t'n_bits_out', sprintf('8'), ...\n\t\t'bin_pt_out', sprintf('3'), ...\n\t\t'type_out', sprintf('1'), ...\n\t\t'Position', sprintf('[20 252 95 328]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_convert']);\n\tbus_convert_gen([blk,'/bus_convert']);\n\tset_param([blk,'/bus_convert'], ...\n\t\t'n_bits_in', sprintf('[]'), ...\n\t\t'bin_pt_in', sprintf('8'), ...\n\t\t'cmplx', sprintf('off'), ...\n\t\t'n_bits_out', sprintf('8'), ...\n\t\t'bin_pt_out', sprintf('4'), ...\n\t\t'quantization', sprintf('1'), ...\n\t\t'overflow', sprintf('1'), ...\n\t\t'latency', sprintf('2'), ...\n\t\t'of', sprintf('on'), ...\n\t\t'misc', sprintf('on'), ...\n\t\t'Position', sprintf('[220 132 295 208]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_negate']);\n\tbus_negate_gen([blk,'/bus_negate']);\n\tset_param([blk,'/bus_negate'], ...\n\t\t'n_bits_in', sprintf('0'), ...\n\t\t'bin_pt_in', sprintf('8'), ...\n\t\t'cmplx', sprintf('off'), ...\n\t\t'overflow', sprintf('1'), ...\n\t\t'latency', sprintf('2'), ...\n\t\t'misc', sprintf('off'), ...\n\t\t'Position', sprintf('[120 252 195 328]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_accumulator']);\n\tbus_accumulator_gen([blk,'/bus_accumulator']);\n\tset_param([blk,'/bus_accumulator'], ...\n\t\t'reset', sprintf('on'), ...\n\t\t'enable', sprintf('on'), ...\n\t\t'n_bits_in', sprintf('[]'), ...\n\t\t'bin_pt_in', sprintf('3'), ...\n\t\t'type_in', sprintf('1'), ...\n\t\t'cmplx', sprintf('on'), ...\n\t\t'n_bits_out', sprintf('16'), ...\n\t\t'overflow', sprintf('1'), ...\n\t\t'misc', sprintf('on'), ...\n\t\t'Position', sprintf('[320 17 395 93]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_relational']);\n\tbus_relational_gen([blk,'/bus_relational']);\n\tset_param([blk,'/bus_relational'], ...\n\t\t'n_bits_a', sprintf('0'), ...\n\t\t'bin_pt_a', sprintf('0'), ...\n\t\t'type_a', sprintf('1'), ...\n\t\t'n_bits_b', sprintf('8'), ...\n\t\t'bin_pt_b', sprintf('0'), ...\n\t\t'type_b', sprintf('1'), ...\n\t\t'en', sprintf('off'), ...\n\t\t'misc', sprintf('off'), ...\n\t\t'mode', sprintf('a=b'), ...\n\t\t'latency', sprintf('1'), ...\n\t\t'Position', sprintf('[220 252 295 328]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_scale']);\n\tbus_scale_gen([blk,'/bus_scale']);\n\tset_param([blk,'/bus_scale'], ...\n\t\t'n_bits_in', sprintf('[]'), ...\n\t\t'bin_pt_in', sprintf('8'), ...\n\t\t'type_in', sprintf('1'), ...\n\t\t'cmplx', sprintf('off'), ...\n\t\t'scale_factor', sprintf('2'), ...\n\t\t'misc', sprintf('on'), ...\n\t\t'Position', sprintf('[320 132 395 208]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_single_port_ram']);\n\tbus_single_port_ram_gen([blk,'/bus_single_port_ram']);\n\tset_param([blk,'/bus_single_port_ram'], ...\n\t\t'n_bits', sprintf('0'), ...\n\t\t'bin_pts', sprintf('17'), ...\n\t\t'init_vector', sprintf('[[-2:1/(2^10):2-(1/(2^10))]'']'), ...\n\t\t'max_fanout', sprintf('4'), ...\n\t\t'mem_type', sprintf('Block RAM'), ...\n\t\t'bram_optimization', sprintf('Speed'), ...\n\t\t'async', sprintf('off'), ...\n\t\t'misc', sprintf('off'), ...\n\t\t'bram_latency', sprintf('2'), ...\n\t\t'fan_latency', sprintf('1'), ...\n\t\t'addr_register', sprintf('on'), ...\n\t\t'addr_implementation', sprintf('core'), ...\n\t\t'din_register', sprintf('on'), ...\n\t\t'din_implementation', sprintf('core'), ...\n\t\t'we_register', sprintf('on'), ...\n\t\t'we_implementation', sprintf('core'), ...\n\t\t'en_register', sprintf('on'), ...\n\t\t'en_implementation', sprintf('core'), ...\n\t\t'Position', sprintf('[20 372 95 448]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_maddsub']);\n\tbus_maddsub_gen([blk,'/bus_maddsub']);\n\tset_param([blk,'/bus_maddsub'], ...\n\t\t'n_bits_a', sprintf('0'), ...\n\t\t'bin_pt_a', sprintf('7'), ...\n\t\t'type_a', sprintf('1'), ...\n\t\t'cmplx_a', sprintf('on'), ...\n\t\t'n_bits_b', sprintf('[18 18]'), ...\n\t\t'bin_pt_b', sprintf('17'), ...\n\t\t'type_b', sprintf('1'), ...\n\t\t'mult_latency', sprintf('3'), ...\n\t\t'multiplier_implementation', sprintf('behavioral HDL'), ...\n\t\t'replication_ab', sprintf('on'), ...\n\t\t'opmode', sprintf('Addition'), ...\n\t\t'n_bits_c', sprintf('[4 4 4 4]'), ...\n\t\t'bin_pt_c', sprintf('3'), ...\n\t\t'type_c', sprintf('0'), ...\n\t\t'add_implementation', sprintf('behavioral HDL'), ...\n\t\t'add_latency', sprintf('1'), ...\n\t\t'async_add', sprintf('on'), ...\n\t\t'align_c', sprintf('off'), ...\n\t\t'replication_c', sprintf('off'), ...\n\t\t'n_bits_out', sprintf('26'), ...\n\t\t'bin_pt_out', sprintf('24'), ...\n\t\t'type_out', sprintf('1'), ...\n\t\t'quantization', sprintf('0'), ...\n\t\t'overflow', sprintf('0'), ...\n\t\t'max_fanout', sprintf('2'), ...\n\t\t'Position', sprintf('[120 372 195 448]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_dual_port_ram']);\n\tbus_dual_port_ram_gen([blk,'/bus_dual_port_ram']);\n\tset_param([blk,'/bus_dual_port_ram'], ...\n\t\t'n_bits', sprintf('0'), ...\n\t\t'bin_pts', sprintf('17'), ...\n\t\t'init_vector', sprintf('[[-2:1/(2^10):2-(1/(2^10))]'']'), ...\n\t\t'max_fanout', sprintf('4'), ...\n\t\t'mem_type', sprintf('Block RAM'), ...\n\t\t'bram_optimization', sprintf('Area'), ...\n\t\t'async_a', sprintf('off'), ...\n\t\t'async_b', sprintf('off'), ...\n\t\t'misc', sprintf('off'), ...\n\t\t'bram_latency', sprintf('2'), ...\n\t\t'fan_latency', sprintf('1'), ...\n\t\t'addra_register', sprintf('off'), ...\n\t\t'addra_implementation', sprintf('core'), ...\n\t\t'dina_register', sprintf('off'), ...\n\t\t'dina_implementation', sprintf('core'), ...\n\t\t'wea_register', sprintf('off'), ...\n\t\t'wea_implementation', sprintf('core'), ...\n\t\t'ena_register', sprintf('off'), ...\n\t\t'ena_implementation', sprintf('core'), ...\n\t\t'addrb_register', sprintf('off'), ...\n\t\t'addrb_implementation', sprintf('core'), ...\n\t\t'dinb_register', sprintf('off'), ...\n\t\t'dinb_implementation', sprintf('core'), ...\n\t\t'web_register', sprintf('off'), ...\n\t\t'web_implementation', sprintf('core'), ...\n\t\t'enb_register', sprintf('off'), ...\n\t\t'enb_implementation', sprintf('core'), ...\n\t\t'Position', sprintf('[320 254 395 330]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_delay']);\n\tbus_delay_gen([blk,'/bus_delay']);\n\tset_param([blk,'/bus_delay'], ...\n\t\t'n_bits', sprintf('8'), ...\n\t\t'latency', sprintf('-1'), ...\n\t\t'cmplx', sprintf('off'), ...\n\t\t'enable', sprintf('off'), ...\n\t\t'reg_retiming', sprintf('on'), ...\n\t\t'misc', sprintf('off'), ...\n\t\t'Position', sprintf('[220 372 295 448]'), ...\n\t\t'Tag', sprintf(''));\n\n\tadd_block('built-in/SubSystem', [blk,'/bus_constant']);\n\tbus_constant_gen([blk,'/bus_constant']);\n\tset_param([blk,'/bus_constant'], ...\n\t\t'values', sprintf('[]'), ...\n\t\t'n_bits', sprintf('[8]'), ...\n\t\t'bin_pts', sprintf('[7]'), ...\n\t\t'types', sprintf('[1]'), ...\n\t\t'Position', sprintf('[320 372 395 448]'), ...\n\t\t'Tag', sprintf(''));\n\n\tset_param(blk, ...\n\t\t'Name', sprintf('casper_library_bus'), ...\n\t\t'LibraryType', sprintf('BlockLibrary'), ...\n\t\t'Lock', sprintf('off'), ...\n\t\t'PreSaveFcn', sprintf('mdl2m(gcs, ''library'', ''on'');'), ...\n\t\t'SolverName', sprintf('ode45'), ...\n\t\t'SolverMode', sprintf('Auto'), ...\n\t\t'StartTime', sprintf('0.0'), ...\n\t\t'StopTime', sprintf('10.0'));\n\tfilename = save_system(mdl,[getenv('MLIB_DEVEL_PATH'), '/casper_library/', 'casper_library_bus']);\n\tif iscell(filename), filename = filename{1}; end;\n\tfileattrib(filename, '+w');\nend % casper_library_bus_init\n\nfunction bus_addsub_gen(blk)\n\n\tbus_addsub_mask(blk);\n\tbus_addsub_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_addsub_init(gcb, ...\\n ''opmode'', opmode, ...\\n ''n_bits_a'', n_bits_a, ...\\n ''bin_pt_a'', bin_pt_a, ...\\n ''type_a'', type_a, ...\\n ''n_bits_b'', n_bits_b, ...\\n ''bin_pt_b'', bin_pt_b, ...\\n ''type_b'', type_b, ...\\n ''n_bits_out'', n_bits_out, ...\\n ''bin_pt_out'', bin_pt_out, ...\\n ''type_out'', type_out, ...\\n ''overflow'', overflow, ... \\n ''quantization'', quantization, ...\\n ''add_implementation'', add_implementation, ...\\n ''latency'', latency, ...\\n ''cmplx'', cmplx, ...\\n ''misc'', misc, ...\\n ''async'', async);'));\n\nend % bus_addsub_gen\n\nfunction bus_addsub_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_addsub'), ...\n\t\t'MaskDescription', sprintf('Add/subtract components of two busses'), ...\n\t\t'MaskPromptString', sprintf('mode (Addition=0, Subtraction=1)|a input bit widths|a input binary points |a input type (Unsigned=0, Signed=1)|b input bit widths|b input binary points|b input type (Unsigned=0, Signed=1)|complex|misc support|asynchronous operation|output bit widths|output binary points|output type (Unsigned=0, Signed=1)|quantization strategy (Truncate=0, Round (unbiased: +/- Inf)=1)|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|adder implementation|latency'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,edit,checkbox,checkbox,checkbox,edit,edit,edit,edit,edit,popup(behavioral HDL|fabric core|DSP48 core),edit'), ...\n\t\t'MaskTabNameString', sprintf('input,input,input,input,input,input,input,input,input,input,output,output,output,implementation,implementation,implementation,latency'), ...\n\t\t'MaskCallbackString', sprintf('||||||||||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('opmode=@1;n_bits_a=@2;bin_pt_a=@3;type_a=@4;n_bits_b=@5;bin_pt_b=@6;type_b=@7;cmplx=&8;misc=&9;async=&10;n_bits_out=@11;bin_pt_out=@12;type_out=@13;quantization=@14;overflow=@15;add_implementation=&16;latency=@17;'), ...\n\t\t'MaskValueString', sprintf('0|0|3|1|4|3|1|on|on|off|8|3|1|0|1|fabric core|1'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_addsub_mask\n\nfunction bus_addsub_init(blk)\n\nend % bus_addsub_init\n\nfunction bus_register_gen(blk)\n\n\tbus_register_mask(blk);\n\tbus_register_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_register_init(gcb, ...\\n ''reset'', reset, ...\\n ''enable'', enable, ...\\n ''cmplx'', cmplx, ...\\n ''n_bits'', n_bits, ...\\n ''misc'', misc);'));\n\nend % bus_register_gen\n\nfunction bus_register_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_register'), ...\n\t\t'MaskDescription', sprintf('Register components of bus'), ...\n\t\t'MaskPromptString', sprintf('reset port|enable port|complex data|input bit widths|misc support'), ...\n\t\t'MaskStyleString', sprintf('checkbox,checkbox,checkbox,edit,checkbox'), ...\n\t\t'MaskCallbackString', sprintf('||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('reset=&1;enable=&2;cmplx=&3;n_bits=@4;misc=&5;'), ...\n\t\t'MaskValueString', sprintf('on|on|on|[]|on'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_register_mask\n\nfunction bus_register_init(blk)\n\nend % bus_register_init\n\nfunction bus_mux_gen(blk)\n\n\tbus_mux_mask(blk);\n\tbus_mux_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_mux_init(gcb, ...\\n ''n_inputs'', n_inputs, ...\\n ''n_bits'', n_bits, ...\\n ''cmplx'', cmplx, ...\\n ''misc'', misc, ...\\n ''mux_latency'', mux_latency);'));\n\nend % bus_mux_gen\n\nfunction bus_mux_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_mux'), ...\n\t\t'MaskDescription', sprintf('Mux components of bus'), ...\n\t\t'MaskPromptString', sprintf('number of inputs|input bit widths|mux latency|complex data|misc support'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,checkbox,checkbox'), ...\n\t\t'MaskTabNameString', sprintf('input,input,latency,input,input'), ...\n\t\t'MaskCallbackString', sprintf('||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_inputs=@1;n_bits=@2;mux_latency=@3;cmplx=&4;misc=&5;'), ...\n\t\t'MaskValueString', sprintf('0|8|0|off|off'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_mux_mask\n\nfunction bus_mux_init(blk)\n\nend % bus_mux_init\n\nfunction bus_mult_gen(blk)\n\n\tbus_mult_mask(blk);\n\tbus_mult_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_mult_init(gcb, ...\\n ''n_bits_a'', n_bits_a, ...\\n ''bin_pt_a'', bin_pt_a, ...\\n ''type_a'', type_a, ...\\n ''cmplx_a'', cmplx_a, ...\\n ''n_bits_b'', n_bits_b, ...\\n ''bin_pt_b'', bin_pt_b, ...\\n ''type_b'', type_b, ...\\n ''cmplx_b'', cmplx_b, ...\\n ''n_bits_out'', n_bits_out, ...\\n ''bin_pt_out'', bin_pt_out, ...\\n ''type_out'', type_out, ...\\n ''quantization'', quantization, ...\\n ''overflow'', overflow, ...\\n ''mult_latency'', mult_latency, ...\\n ''add_latency'', add_latency, ...\\n ''conv_latency'', conv_latency, ...\\n ''max_fanout'', max_fanout, ...\\n ''fan_latency'', fan_latency, ...\\n ''multiplier_implementation'', multiplier_implementation, ...\\n ''misc'', misc);'));\n\nend % bus_mult_gen\n\nfunction bus_mult_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_mult'), ...\n\t\t'MaskDescription', sprintf('Multiply components of two busses'), ...\n\t\t'MaskPromptString', sprintf('a input bit widths|a input binary points |a input type (Unsigned=0, Signed=1)|a input complex|b input bit widths|b input binary points|b input type (Unsigned=0, Signed=1)|b input complex|output bit widths|output binary points|output type (Unsigned=0, Signed=1)|quantization strategy (Truncate=0, Round (unbiased: +/- Inf)=1)|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|multiplier latency|adder latency|convert latency|limit fanout to ?|fanout register latency|multiplier implementation|misc support'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,checkbox,edit,edit,edit,checkbox,edit,edit,edit,edit,edit,edit,edit,edit,edit,edit,popup(behavioral HDL|standard core|embedded multiplier core),checkbox'), ...\n\t\t'MaskTabNameString', sprintf('input,input,input,input,input,input,input,input,output,output,output,output,output,latency,latency,latency,implementation,implementation,implementation,input'), ...\n\t\t'MaskCallbackString', sprintf('|||||||||||||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits_a=@1;bin_pt_a=@2;type_a=@3;cmplx_a=&4;n_bits_b=@5;bin_pt_b=@6;type_b=@7;cmplx_b=&8;n_bits_out=@9;bin_pt_out=@10;type_out=@11;quantization=@12;overflow=@13;mult_latency=@14;add_latency=@15;conv_latency=@16;max_fanout=@17;fan_latency=@18;multiplier_implementation=&19;misc=&20;'), ...\n\t\t'MaskValueString', sprintf('0|4|1|on|4|3|1|on|12|7|1|0|0|3|1|1|2|0|behavioral HDL|on'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_mult_mask\n\nfunction bus_mult_init(blk)\n\nend % bus_mult_init\n\nfunction bus_replicate_gen(blk)\n\n\tbus_replicate_mask(blk);\n\tbus_replicate_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_replicate_init(gcb, ...\\n ''replication'', replication, ...\\n ''latency'', latency, ...\\n ''implementation'', implementation, ...\\n ''misc'', misc);'));\n\nend % bus_replicate_gen\n\nfunction bus_replicate_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_replicate'), ...\n\t\t'MaskDescription', sprintf('Output bus formed by replicating input bus a number of times'), ...\n\t\t'MaskPromptString', sprintf('replication factor|latency|misc support|delay implementation'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,checkbox,popup(core|behavioral)'), ...\n\t\t'MaskCallbackString', sprintf('|||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('replication=@1;latency=@2;misc=&3;implementation=&4;'), ...\n\t\t'MaskValueString', sprintf('0|0|on|core'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_replicate_mask\n\nfunction bus_replicate_init(blk)\n\nend % bus_replicate_init\n\nfunction bus_logical_gen(blk)\n\n\tbus_logical_mask(blk);\n\tbus_logical_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_logical_init(gcb, ...\\n ''logical_function'', logical_function, ...\\n ''en'', en, ...\\n ''n_bits_a'', n_bits_a, ...\\n ''bin_pt_a'', bin_pt_a, ...\\n ''type_a'', type_a, ...\\n ''n_bits_b'', n_bits_b, ...\\n ''bin_pt_b'', bin_pt_b, ...\\n ''type_b'', type_b, ...\\n ''n_bits_out'', n_bits_out, ...\\n ''bin_pt_out'', bin_pt_out, ...\\n ''type_out'', type_out, ...\\n ''latency'', latency, ...\\n ''cmplx'', cmplx, ...\\n ''align_bp'', align_bp, ...\\n ''misc'', misc);'));\n\nend % bus_logical_gen\n\nfunction bus_logical_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_logical'), ...\n\t\t'MaskDescription', sprintf('Form the logical product of two busses'), ...\n\t\t'MaskPromptString', sprintf('logical function|align binary point|latency|a input bit widths|a input binary points |a input type (Unsigned=0, Signed=1)|b input bit widths|b input binary points|b input type (Unsigned=0, Signed=1)|complex|en port|misc support|output bit widths|output binary points|output type (Unsigned=0, Signed=1)'), ...\n\t\t'MaskStyleString', sprintf('popup(AND|NAND|OR|NOR|XOR|XNOR),checkbox,edit,edit,edit,edit,edit,edit,edit,checkbox,checkbox,checkbox,edit,edit,edit'), ...\n\t\t'MaskTabNameString', sprintf('operation,operation,operation,input,input,input,input,input,input,input,input,input,output,output,output'), ...\n\t\t'MaskCallbackString', sprintf('||||||||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('logical_function=&1;align_bp=&2;latency=@3;n_bits_a=@4;bin_pt_a=@5;type_a=@6;n_bits_b=@7;bin_pt_b=@8;type_b=@9;cmplx=&10;en=&11;misc=&12;n_bits_out=@13;bin_pt_out=@14;type_out=@15;'), ...\n\t\t'MaskValueString', sprintf('AND|on|1|[]|3|1|4|3|1|on|on|on|8|3|1'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_logical_mask\n\nfunction bus_logical_init(blk)\n\nend % bus_logical_init\n\nfunction bus_convert_gen(blk)\n\n\tbus_convert_mask(blk);\n\tbus_convert_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_convert_init(gcb, ...\\n ''n_bits_in'', n_bits_in, ...\\n ''bin_pt_in'', bin_pt_in, ...\\n ''cmplx'', cmplx, ...\\n ''n_bits_out'', n_bits_out, ...\\n ''bin_pt_out'', bin_pt_out, ...\\n ''quantization'', quantization, ...\\n ''overflow'', overflow, ...\\n ''latency'', latency, ...\\n ''misc'', misc, ...\\n ''of'', of);'));\n\nend % bus_convert_gen\n\nfunction bus_convert_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_convert'), ...\n\t\t'MaskDescription', sprintf('Convert components of busses'), ...\n\t\t'MaskPromptString', sprintf('input bit widths|input binary points |input complex|output bit widths|output binary points|quantization strategy (Truncate=0, Round (unbiased: +/- Inf)=1, Round (unbiased: Even Values)=2)|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|latency|overflow indication|misc support'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,checkbox,edit,edit,edit,edit,edit,checkbox,checkbox'), ...\n\t\t'MaskTabNameString', sprintf('input,input,input,output,output,output,output,operation,operation,input'), ...\n\t\t'MaskCallbackString', sprintf('|||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits_in=@1;bin_pt_in=@2;cmplx=&3;n_bits_out=@4;bin_pt_out=@5;quantization=@6;overflow=@7;latency=@8;of=&9;misc=&10;'), ...\n\t\t'MaskValueString', sprintf('[]|8|off|8|4|1|1|2|on|on'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_convert_mask\n\nfunction bus_convert_init(blk)\n\nend % bus_convert_init\n\nfunction bus_negate_gen(blk)\n\n\tbus_negate_mask(blk);\n\tbus_negate_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_negate_init(gcb, ...\\n ''n_bits_in'', n_bits_in, ...\\n ''bin_pt_in'', bin_pt_in, ...\\n ''cmplx'', cmplx, ...\\n ''overflow'', overflow, ...\\n ''latency'', latency, ...\\n ''misc'', misc);'));\n\nend % bus_negate_gen\n\nfunction bus_negate_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_negate'), ...\n\t\t'MaskDescription', sprintf('Negate components of busses'), ...\n\t\t'MaskPromptString', sprintf('input bit widths|input binary points |input complex|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|latency|misc support'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,checkbox,edit,edit,checkbox'), ...\n\t\t'MaskTabNameString', sprintf('input,input,input,operation,operation,input'), ...\n\t\t'MaskCallbackString', sprintf('|||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits_in=@1;bin_pt_in=@2;cmplx=&3;overflow=@4;latency=@5;misc=&6;'), ...\n\t\t'MaskValueString', sprintf('0|8|off|1|2|off'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_negate_mask\n\nfunction bus_negate_init(blk)\n\nend % bus_negate_init\n\nfunction bus_accumulator_gen(blk)\n\n\tbus_accumulator_mask(blk);\n\tbus_accumulator_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_accumulator_init(gcb, ...\\n ''reset'', reset, ...\\n ''enable'', enable, ...\\n ''n_bits_in'', n_bits_in, ...\\n ''bin_pt_in'', bin_pt_in, ...\\n ''type_in'', type_in, ...\\n ''cmplx'', cmplx, ...\\n ''n_bits_out'', n_bits_out, ...\\n ''overflow'', overflow, ...\\n ''misc'', misc);'));\n\nend % bus_accumulator_gen\n\nfunction bus_accumulator_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_accumulator'), ...\n\t\t'MaskDescription', sprintf('Accumulate components of bus'), ...\n\t\t'MaskPromptString', sprintf('reset port|enable port|input bit widths|input binary points|input types (Unsigned=0, Signed=1)|complex inputs|output bit widths|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|misc support'), ...\n\t\t'MaskStyleString', sprintf('checkbox,checkbox,edit,edit,edit,checkbox,edit,edit,checkbox'), ...\n\t\t'MaskCallbackString', sprintf('||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('reset=&1;enable=&2;n_bits_in=@3;bin_pt_in=@4;type_in=@5;cmplx=&6;n_bits_out=@7;overflow=@8;misc=&9;'), ...\n\t\t'MaskValueString', sprintf('on|on|[]|3|1|on|16|1|on'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_accumulator_mask\n\nfunction bus_accumulator_init(blk)\n\nend % bus_accumulator_init\n\nfunction bus_relational_gen(blk)\n\n\tbus_relational_mask(blk);\n\tbus_relational_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_relational_init(gcb, ...\\n ''n_bits_a'', n_bits_a, ...\\n ''bin_pt_a'', bin_pt_a, ...\\n ''type_a'', type_a, ...\\n ''n_bits_b'', n_bits_b, ...\\n ''bin_pt_b'', bin_pt_b, ...\\n ''type_b'', type_b, ...\\n ''en'', en, ...\\n ''misc'', misc, ...\\n ''mode'', mode, ...\\n ''latency'', latency);'));\n\nend % bus_relational_gen\n\nfunction bus_relational_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_relational'), ...\n\t\t'MaskDescription', sprintf('Find the relational product of two busses'), ...\n\t\t'MaskPromptString', sprintf('a input bit widths|a input binary points |a input type (Unsigned=0, Signed=1)|b input bit widths|b input binary points|b input type (Unsigned=0, Signed=1)|en port|misc support|comparison:|latency'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,checkbox,checkbox,popup(a=b|a!=b|ab|a<=b|a>=b),edit'), ...\n\t\t'MaskTabNameString', sprintf('input,input,input,input,input,input,input,input,operation,operation'), ...\n\t\t'MaskCallbackString', sprintf('|||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits_a=@1;bin_pt_a=@2;type_a=@3;n_bits_b=@4;bin_pt_b=@5;type_b=@6;en=&7;misc=&8;mode=&9;latency=@10;'), ...\n\t\t'MaskValueString', sprintf('0|0|1|8|0|1|off|off|a=b|1'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_relational_mask\n\nfunction bus_relational_init(blk)\n\nend % bus_relational_init\n\nfunction bus_scale_gen(blk)\n\n\tbus_scale_mask(blk);\n\tbus_scale_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_scale_init(gcb, ...\\n ''n_bits_in'', n_bits_in, ...\\n ''bin_pt_in'', bin_pt_in, ...\\n ''type_in'', type_in, ...\\n ''cmplx'', cmplx, ...\\n ''scale_factor'', scale_factor, ...\\n ''misc'', misc);'));\n\nend % bus_scale_gen\n\nfunction bus_scale_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_scale'), ...\n\t\t'MaskDescription', sprintf('Convert components of busses'), ...\n\t\t'MaskPromptString', sprintf('input bit widths|input binary points |input types|input complex|scale factor (2^?)|misc support'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,checkbox,edit,checkbox'), ...\n\t\t'MaskTabNameString', sprintf('input,input,input,input,output,input'), ...\n\t\t'MaskCallbackString', sprintf('|||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits_in=@1;bin_pt_in=@2;type_in=@3;cmplx=&4;scale_factor=@5;misc=&6;'), ...\n\t\t'MaskValueString', sprintf('[]|8|1|off|2|on'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_scale_mask\n\nfunction bus_scale_init(blk)\n\nend % bus_scale_init\n\nfunction bus_single_port_ram_gen(blk)\n\n\tbus_single_port_ram_mask(blk);\n\tbus_single_port_ram_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_single_port_ram_init(gcb, ...\\n ''n_bits'', n_bits, ...\\n ''bin_pts'', bin_pts, ...\\n ''init_vector'', init_vector, ...\\n ''max_fanout'', max_fanout, ...\\n ''mem_type'', mem_type, ...\\n ''bram_optimization'', bram_optimization, ...\\n ''async'', async, ...\\n ''misc'', misc, ...\\n ''bram_latency'', bram_latency, ...\\n ''fan_latency'', fan_latency, ...\\n ''addr_register'', addr_register, ...\\n ''addr_implementation'', addr_implementation, ...\\n ''din_register'', din_register, ...\\n ''din_implementation'', din_implementation, ...\\n ''we_register'', we_register, ...\\n ''we_implementation'', we_implementation, ...\\n ''en_register'', en_register, ...\\n ''en_implementation'', en_implementation);'));\n\nend % bus_single_port_ram_gen\n\nfunction bus_single_port_ram_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_single_port_ram'), ...\n\t\t'MaskDescription', sprintf('RAM for a bus allowing fanout control'), ...\n\t\t'MaskPromptString', sprintf('data word bit widths|data word binary points|initial value vector|limit fanout to ?|memory type|memory optimization|asynchronous |misc support|bram latency|input register latency|addr input register|addr register implementation|din input register|din register implementation|we input register|we register implementation|en input register|en register implementation'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,popup(Distributed memory|Block RAM),popup(Area|Speed),checkbox,checkbox,edit,edit,checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral)'), ...\n\t\t'MaskTabNameString', sprintf('basic,basic,basic,basic,basic,basic,basic,basic,latency,latency,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation'), ...\n\t\t'MaskCallbackString', sprintf('|||||||||||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits=@1;bin_pts=@2;init_vector=@3;max_fanout=@4;mem_type=&5;bram_optimization=&6;async=&7;misc=&8;bram_latency=@9;fan_latency=@10;addr_register=&11;addr_implementation=&12;din_register=&13;din_implementation=&14;we_register=&15;we_implementation=&16;en_register=&17;en_implementation=&18;'), ...\n\t\t'MaskValueString', sprintf('0|17|[[-2:1/(2^10):2-(1/(2^10))]'']|4|Block RAM|Speed|off|off|2|1|on|core|on|core|on|core|on|core'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_single_port_ram_mask\n\nfunction bus_single_port_ram_init(blk)\n\nend % bus_single_port_ram_init\n\nfunction bus_maddsub_gen(blk)\n\n\tbus_maddsub_mask(blk);\n\tbus_maddsub_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_maddsub_init(gcb, ...\\n ''n_bits_a'', n_bits_a, ...\\n ''bin_pt_a'', bin_pt_a, ...\\n ''type_a'', type_a, ...\\n ''cmplx_a'', cmplx_a, ...\\n ''n_bits_b'', n_bits_b, ...\\n ''bin_pt_b'', bin_pt_b, ...\\n ''type_b'', type_b, ...\\n ''mult_latency'', mult_latency, ...\\n ''multiplier_implementation'', multiplier_implementation, ...\\n ''replication_ab'', replication_ab, ...\\n ''opmode'', opmode, ...\\n ''n_bits_c'', n_bits_c, ...\\n ''bin_pt_c'', bin_pt_c, ...\\n ''type_c'', type_c, ...\\n ''add_implementation'', add_implementation, ...\\n ''add_latency'', add_latency, ...\\n ''async_add'', async_add, ...\\n ''align_c'', align_c, ...\\n ''replication_c'', replication_c, ...\\n ''n_bits_out'', n_bits_out, ...\\n ''bin_pt_out'', bin_pt_out, ...\\n ''type_out'', type_out, ...\\n ''quantization'', quantization, ...\\n ''overflow'', overflow, ...\\n ''max_fanout'', max_fanout);'));\n\nend % bus_maddsub_gen\n\nfunction bus_maddsub_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_maddsub'), ...\n\t\t'MaskDescription', sprintf('Multiply and add/subtract components of two busses'), ...\n\t\t'MaskPromptString', sprintf('a input bit widths|a input binary points |a input type (Unsigned=0, Signed=1)|a complex|b input bit widths|b input binary points|b input type (Unsigned=0, Signed=1)|multiplier latency|multiplier implementation|a and b input replication support|mode|c input bit widths|c input binary points|c input type (Unsigned=0, Signed=1)|adder implementation|adder latency|asynchronous addition|align c path with a and b|c input replication support|output bit widths|output binary points|output type (Unsigned=0, Signed=1)|quantization strategy (Truncate=0, Round (unbiased: +/- Inf)=1)|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|limit fanout to ?'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,checkbox,edit,edit,edit,edit,popup(behavioral HDL|standard core|embedded multiplier core),checkbox,popup(Addition|Subtraction),edit,edit,edit,popup(behavioral HDL|fabric core|DSP48 core),edit,checkbox,checkbox,checkbox,edit,edit,edit,edit,edit,edit'), ...\n\t\t'MaskTabNameString', sprintf('multiplication,multiplication,multiplication,multiplication,multiplication,multiplication,multiplication,multiplication,multiplication,multiplication,addsub,addsub,addsub,addsub,addsub,addsub,addsub,addsub,addsub,output,output,output,output,output,implementation'), ...\n\t\t'MaskCallbackString', sprintf('||||||||||||||||||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits_a=@1;bin_pt_a=@2;type_a=@3;cmplx_a=&4;n_bits_b=@5;bin_pt_b=@6;type_b=@7;mult_latency=@8;multiplier_implementation=&9;replication_ab=&10;opmode=&11;n_bits_c=@12;bin_pt_c=@13;type_c=@14;add_implementation=&15;add_latency=@16;async_add=&17;align_c=&18;replication_c=&19;n_bits_out=@20;bin_pt_out=@21;type_out=@22;quantization=@23;overflow=@24;max_fanout=@25;'), ...\n\t\t'MaskValueString', sprintf('0|7|1|on|[18 18]|17|1|3|behavioral HDL|on|Addition|[4 4 4 4]|3|0|behavioral HDL|1|on|off|off|26|24|1|0|0|2'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_maddsub_mask\n\nfunction bus_maddsub_init(blk)\n\nend % bus_maddsub_init\n\nfunction bus_dual_port_ram_gen(blk)\n\n\tbus_dual_port_ram_mask(blk);\n\tbus_dual_port_ram_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_dual_port_ram_init(gcb, ...\\n ''n_bits'', n_bits, ...\\n ''bin_pts'', bin_pts, ...\\n ''init_vector'', init_vector, ...\\n ''max_fanout'', max_fanout, ...\\n ''mem_type'', mem_type, ...\\n ''bram_optimization'', bram_optimization, ...\\n ''async_a'', async_a, ...\\n ''async_b'', async_b, ...\\n ''misc'', misc, ...\\n ''bram_latency'', bram_latency, ...\\n ''fan_latency'', fan_latency, ...\\n ''addra_register'', addra_register, ...\\n ''addra_implementation'', addra_implementation, ...\\n ''dina_register'', dina_register, ...\\n ''dina_implementation'', dina_implementation, ...\\n ''wea_register'', wea_register, ...\\n ''wea_implementation'', wea_implementation, ...\\n ''ena_register'', ena_register, ...\\n ''ena_implementation'', ena_implementation, ...\\n ''addrb_register'', addrb_register, ...\\n ''addrb_implementation'', addrb_implementation, ...\\n ''dinb_register'', dinb_register, ...\\n ''dinb_implementation'', dinb_implementation, ...\\n ''web_register'', web_register, ...\\n ''web_implementation'', web_implementation, ...\\n ''enb_register'', enb_register, ...\\n ''enb_implementation'', enb_implementation);'));\n\nend % bus_dual_port_ram_gen\n\nfunction bus_dual_port_ram_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_dual_port_ram'), ...\n\t\t'MaskDescription', sprintf('RAM for a bus allowing fanout control'), ...\n\t\t'MaskPromptString', sprintf('data word bit widths|data word binary points|initial value vector|limit fanout to ?|memory type|memory optimization|a asynchronous |b asynchronous|misc support|bram latency|input register latency|addra input register|addra register implementation|dina input register|dina register implementation|wea input register|wea register implementation|ena input register|ena register implementation|addrb input register|addrb register implementation|dinb input register|dinb register implementation|web input register|web register implementation|enb input register|enb register implementation'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit,popup(Distributed memory|Block RAM),popup(Area|Speed),checkbox,checkbox,checkbox,edit,edit,checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral)'), ...\n\t\t'MaskTabNameString', sprintf('basic,basic,basic,basic,basic,basic,basic,basic,basic,latency,latency,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation'), ...\n\t\t'MaskCallbackString', sprintf('||||||||||||||||||||||||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits=@1;bin_pts=@2;init_vector=@3;max_fanout=@4;mem_type=&5;bram_optimization=&6;async_a=&7;async_b=&8;misc=&9;bram_latency=@10;fan_latency=@11;addra_register=&12;addra_implementation=&13;dina_register=&14;dina_implementation=&15;wea_register=&16;wea_implementation=&17;ena_register=&18;ena_implementation=&19;addrb_register=&20;addrb_implementation=&21;dinb_register=&22;dinb_implementation=&23;web_register=&24;web_implementation=&25;enb_register=&26;enb_implementation=&27;'), ...\n\t\t'MaskValueString', sprintf('0|17|[[-2:1/(2^10):2-(1/(2^10))]'']|4|Block RAM|Area|off|off|off|2|1|off|core|off|core|off|core|off|core|off|core|off|core|off|core|off|core'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_dual_port_ram_mask\n\nfunction bus_dual_port_ram_init(blk)\n\nend % bus_dual_port_ram_init\n\nfunction bus_delay_gen(blk)\n\n\tbus_delay_mask(blk);\n\tbus_delay_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_delay_init(gcb, ...\\n ''enable'', enable, ...\\n ''cmplx'', cmplx, ...\\n ''n_bits'', n_bits, ...\\n ''latency'', latency, ...\\n ''reg_retiming'', reg_retiming, ...\\n ''misc'', misc);'));\n\nend % bus_delay_gen\n\nfunction bus_delay_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_delay'), ...\n\t\t'MaskDescription', sprintf('Delay components of a bus'), ...\n\t\t'MaskPromptString', sprintf('input bit widths|latency|complex data|enable port|implement using behavioral HDL|misc support'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,checkbox,checkbox,checkbox,checkbox'), ...\n\t\t'MaskCallbackString', sprintf('|||||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('n_bits=@1;latency=@2;cmplx=&3;enable=&4;reg_retiming=&5;misc=&6;'), ...\n\t\t'MaskValueString', sprintf('8|-1|off|off|on|off'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_delay_mask\n\nfunction bus_delay_init(blk)\n\nend % bus_delay_init\n\nfunction bus_constant_gen(blk)\n\n\tbus_constant_mask(blk);\n\tbus_constant_init(blk);\n\tset_param(blk, ...\n\t\t'MaskInitialization', sprintf('bus_constant_init(gcb, ...\\n ''values'', values, ...\\n ''n_bits'', n_bits, ...\\n ''bin_pts'', bin_pts, ...\\n ''types'', types);'));\n\nend % bus_constant_gen\n\nfunction bus_constant_mask(blk)\n\n\tset_param(blk, ...\n\t\t'Mask', sprintf('on'), ...\n\t\t'MaskSelfModifiable', sprintf('on'), ...\n\t\t'MaskType', sprintf('bus_constant'), ...\n\t\t'MaskDescription', sprintf('Combine constants into a bus'), ...\n\t\t'MaskPromptString', sprintf('values|bit widths|binary points|data type'), ...\n\t\t'MaskStyleString', sprintf('edit,edit,edit,edit'), ...\n\t\t'MaskCallbackString', sprintf('|||'), ...\n\t\t'MaskEnableString', sprintf('on,on,on,on'), ...\n\t\t'MaskVisibilityString', sprintf('on,on,on,on'), ...\n\t\t'MaskToolTipString', sprintf('on,on,on,on'), ...\n\t\t'MaskVariables', sprintf('values=@1;n_bits=@2;bin_pts=@3;types=@4;'), ...\n\t\t'MaskValueString', sprintf('[]|[8]|[7]|[1]'), ...\n\t\t'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'));\n\nend % bus_constant_mask\n\nfunction bus_constant_init(blk)\n\nend % bus_constant_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "square_transposer_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/square_transposer_init.m", "size": 6020, "source_encoding": "utf_8", "md5": "961ec46a987dd5eaa5ef2f8a8eab46ec", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction square_transposer_init(blk, varargin)\r\n% Initialize and configure the square transposer.\r\n%\r\n% square_transposer_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% n_inputs = The number of inputs to be transposed.\r\n\r\n% Declare any default values for arguments you might like.\r\n\r\ndefaults = { ...\r\n 'n_inputs', 1, ...\r\n 'async', 'on', ...\r\n};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'square_transposer');\r\nmunge_block(blk, varargin{:});\r\n\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\nasync = get_var('async', 'defaults', defaults, varargin{:});\r\n\r\nytick = 50;\r\n\r\nif n_inputs < 0,\r\n error('Number of inputs must be 2^0 or greater.');\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\nif n_inputs == 0,\r\n clean_blocks(blk);\r\n set_param(blk, 'AttributesFormatString', '');\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n return;\r\nend\r\n\r\n% Add ports\r\nreuse_block(blk, 'sync', 'built-in/inport', 'Position', [15 103 45 117], 'Port', '1');\r\nreuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [415 58 445 72], 'Port', '1');\r\n\r\nif strcmp(async, 'on'),\r\n reuse_block(blk, 'en', 'built-in/inport', 'Port', num2str(2+2^n_inputs), ...\r\n 'Position', [15 ((2^n_inputs)+1)*ytick+153 45 167+ytick*((2^n_inputs)+1)]);\r\n reuse_block(blk, 'dvalid', 'built-in/outport', 'Port', num2str(2+2^n_inputs), ...\r\n 'Position', [415 113+((2^n_inputs)*ytick) 445 127+(ytick*(2^n_inputs))]);\r\nend\r\n\r\nfor p=0:2^n_inputs-1,\r\n reuse_block(blk, ['in',num2str(p)], 'built-in/inport', 'Port', num2str(2+p),...\r\n 'Position', [15 (p*ytick)+153 45 167+(ytick*p)]);\r\n reuse_block(blk, ['out',num2str(p)], 'built-in/outport', 'Port', num2str(2+p),...\r\n 'Position', [415 113+(p*ytick) 445 127+(ytick*p)]);\r\nend\r\n\r\n% Add blocks\r\nreuse_block(blk, 'counter', 'xbsIndex_r4/Counter', ...\r\n 'Position', [180 44 220 76], 'cnt_type', 'Free Running', 'n_bits', 'n_inputs', ...\r\n 'arith_type', 'Unsigned', 'rst', 'on', 'en', async, 'operation', 'Down');\r\nadd_line(blk, 'sync/1', 'counter/1');\r\n\r\nreuse_block(blk, 'dsync', 'casper_library_delays/delay_slr', ...\r\n 'DelayLen', num2str(2^n_inputs - 1), 'async', async, 'Position', [370 52 400 78]);\r\nadd_line(blk, 'dsync/1', 'sync_out/1');\r\n\r\nreuse_block(blk, 'barrel_switcher', 'casper_library_reorder/barrel_switcher', ...\r\n 'async', async, 'n_inputs', num2str(n_inputs), 'Position', [245 22 305 22+(2^n_inputs+2)*ytick]);\r\nadd_line(blk, 'sync/1', 'barrel_switcher/2');\r\nadd_line(blk, 'counter/1', 'barrel_switcher/1');\r\nadd_line(blk, 'barrel_switcher/1', 'dsync/1');\r\n\r\nfor q=0:2^n_inputs-1,\r\n dport = mod(2^n_inputs - q, 2^n_inputs) + 3;\r\n if q ~= 0,\r\n df = ['df', num2str(q)];\r\n reuse_block(blk, df, 'casper_library_delays/delay_slr', ...\r\n 'DelayLen', num2str(q), 'async', async, 'Position', [70 (q*ytick)+148 100 (q*ytick)+172]);\r\n add_line(blk, ['in', num2str(q),'/1'], [df,'/1']);\r\n add_line(blk, [df, '/1'], ['barrel_switcher/', num2str(dport)]);\r\n \r\n if strcmp(async, 'on'), add_line(blk, 'en/1', [df,'/2']);\r\n end \r\n\r\n else,\r\n add_line(blk, ['in', num2str(q), '/1'], ['barrel_switcher/', num2str(dport)]);\r\n end\r\n if (2^n_inputs)-(q+1) ~= 0,\r\n db = ['db', num2str(q)];\r\n reuse_block(blk, db, 'casper_library_delays/delay_slr', ...\r\n 'DelayLen', num2str((2^n_inputs)-(q+1)), 'async', async, 'Position', [370 (q*ytick)+108 400 (q*ytick)+132]);\r\n add_line(blk, ['barrel_switcher/',num2str(q+2)], [db,'/1']);\r\n add_line(blk, [db,'/1'], ['out',num2str(q),'/1']);\r\n if strcmp(async, 'on'), add_line(blk, ['barrel_switcher/',num2str(2^n_inputs+2)], [db,'/2']);\r\n end \r\n else,\r\n add_line(blk, ['barrel_switcher/',num2str(q+2)], ['out',num2str(q),'/1']);\r\n end\r\nend\r\n\r\nif strcmp(async, 'on'),\r\n add_line(blk, 'en/1', 'counter/2');\r\n add_line(blk, 'en/1', ['barrel_switcher/',num2str(2^n_inputs+3)]);\r\n add_line(blk, ['barrel_switcher/',num2str(2^n_inputs+2)], 'dvalid/1');\r\n add_line(blk, ['barrel_switcher/',num2str(2^n_inputs+2)], 'dsync/2');\r\nend\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('n_inputs=%d', n_inputs);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fft_callback_arch.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fft_callback_arch.m", "size": 2182, "source_encoding": "utf_8", "md5": "a0497bc714337ac06795551eb88844ce", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://casper.berkeley.edu %\n% Copyright (C) 2010 William Mallard %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction fft_callback_arch(cursys)\n% Dialog callback for arch parameter in all fft blocks.\n\n % if arch is Virtex5, allow dsp48 adders.\n % otherwise: disable them, disallow them,\n % and ensure that add_latency is enabled.\n\n arch = get_param(gcb, 'arch');\n if strcmp(arch, 'Virtex5'),\n set_param_state(gcb, 'dsp48_adders', 'on');\n else\n set_param(gcb, 'dsp48_adders', 'off');\n set_param_state(gcb, 'dsp48_adders', 'off');\n set_param_state(gcb, 'add_latency', 'on');\n end\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "complex_conj_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/complex_conj_init.m", "size": 5644, "source_encoding": "utf_8", "md5": "4d08063798a1c7e3ec925039cbe7b691", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKASA %\n% www.kat.ac.za %\n% Copyright (C) Andrew Martens 2013 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction complex_conj_init(blk, varargin)\n\n clog('entering complex_conj_init', {'trace', 'complex_conj_init_debug'});\n\n % Set default vararg values.\n % reg_retiming is not an actual parameter of this block, but it is included\n % in defaults so that same_state will return false for blocks drawn prior to\n % adding reg_retiming='on' to some of the underlying Delay blocks.\n defaults = { ...\n 'n_inputs', 1, ...\n 'n_bits', 18, ...\n 'bin_pt', 17, ...\n 'latency', 1, ...\n 'overflow', 'Wrap', ...\n 'reg_retiming', 'on', ...\n };\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n check_mask_type(blk, 'complex_conj');\n munge_block(blk, varargin{:});\n\n % Retrieve values from mask fields.\n n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\n n_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\n bin_pt = get_var('bin_pt', 'defaults', defaults, varargin{:});\n latency = get_var('latency', 'defaults', defaults, varargin{:});\n overflow = get_var('overflow', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default setup for library\n if n_inputs == 0,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:});\n clog('exiting complex_conj_init',{'trace','complex_conj_init_debug'});\n return;\n end\n \n reuse_block(blk, 'z', 'built-in/Inport', 'Port', '1', 'Position', [10 92 40 108]);\n\n %move real and imaginary parts from multiple streams to be next to each other\n reuse_block(blk, 'munge_in', 'casper_library_flow_control/munge', ...\n 'divisions', num2str(2*n_inputs), ...\n 'div_size', mat2str(repmat(n_bits, 1, 2*n_inputs)), ...\n 'order', mat2str([[0:2:(n_inputs-1)*2],[1:2:(n_inputs-1)*2+1]]), ...\n 'Position', [70 87 110 113]);\n add_line(blk,'z/1','munge_in/1');\n\n reuse_block(blk, 'bus_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', '2', 'outputWidth', num2str(n_bits*n_inputs), ...\n 'outputBinaryPt', '0', 'outputArithmeticType', '0', ...\n 'Position', [140 52 190 148]);\n add_line(blk,'munge_in/1','bus_expand/1');\n\n reuse_block(blk, 'real_delay', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(latency), ...\n 'reg_retiming', 'on', ...\n 'Position', [230 59 290 91]);\n add_line(blk,'bus_expand/1','real_delay/1');\n\n if strcmp(overflow, 'Wrap'), of = '0';\n elseif strcmp(overflow, 'Saturate'), of = '1';\n elseif strcmp(overflow, 'Flag as error'), of = '2';\n else %TODO\n end\n\n reuse_block(blk, 'imag_negate', 'casper_library_bus/bus_negate', ...\n 'n_bits_in', mat2str(repmat(n_bits, 1, n_inputs)), 'bin_pt_in', num2str(bin_pt), ...\n 'cmplx', 'off', 'overflow', of, 'misc', 'off', 'latency', num2str(latency), ... \n 'Position', [230 109 290 141]);\n add_line(blk,'bus_expand/2','imag_negate/1');\n\n reuse_block(blk, 'bus_create', 'casper_library_flow_control/bus_create', ...\n 'inputNum', '2', 'Position', [330 51 380 149]);\n add_line(blk,'real_delay/1','bus_create/1');\n add_line(blk,'imag_negate/1','bus_create/2');\n\n % move real and imaginary parts from multiple streams back\n reuse_block(blk, 'munge_out', 'casper_library_flow_control/munge', ...\n 'divisions', num2str(n_inputs*2), ...\n 'div_size', mat2str(repmat(n_bits, 1, n_inputs*2)), ...\n 'order', mat2str(reshape([[0:(n_inputs-1)];[n_inputs:(n_inputs*2)-1]], 1, n_inputs*2)), ...\n 'Position', [410 87 450 113]);\n add_line(blk,'bus_create/1','munge_out/1');\n\n reuse_block(blk, 'z*', 'built-in/Outport', 'Port', '1', 'Position', [480 92 510 108]);\n add_line(blk,'munge_out/1','z*/1');\n \n % Delete all unconnected blocks.\n clean_blocks(blk);\n\n % Save block state to stop repeated init script runs.\n save_state(blk, 'defaults', defaults, varargin{:});\n\n clog('exiting complex_conj_init',{'trace','complex_conj_init_debug'});\n\nend %complex_conj_init\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "delay_srl_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/delay_srl_init.m", "size": 3979, "source_encoding": "utf_8", "md5": "1f53316360552c35a274dbd4c08e6552", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKASA %\n% www.kat.ac.za %\n% Copyright (C) Andrew Martens 2013 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction delay_srl_init(blk, varargin)\n\n clog('entering delay_srl_init', {'trace', 'delay_srl_init_debug'});\n\n % Set default vararg values.\n defaults = { ...\n 'DelayLen', 1, ...\n 'async', 'off', ...\n };\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n check_mask_type(blk, 'delay_srl');\n munge_block(blk, varargin{:});\n\n % Retrieve values from mask fields.\n DelayLen = get_var('DelayLen', 'defaults', defaults, varargin{:});\n async = get_var('async', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default setup for library\n if DelayLen < 0,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:});\n clog('exiting delay_srl_init',{'trace','delay_srl_init_debug'});\n return;\n end\n\n if (DelayLen > 0),\n ff_delay = 1;\n srl_delay = DelayLen - 1;\n else\n ff_delay = 0;\n srl_delay = 0;\n end\n\n if strcmp(async, 'on'),\n reuse_block(blk, 'en', 'built-in/Inport', 'Port', '1', 'Position', [25 92 55 108]);\n \n %terminate if no delay\n if ~(DelayLen > 0), \n reuse_block(blk, 'arnold', 'built-in/Terminator', 'Position', [80 90 100 110]);\n add_line(blk, 'en/1', 'arnold/1');\n end\n end\n\n reuse_block(blk, 'in', 'built-in/Inport', 'Port', '1', 'Position', [25 38 55 52]);\n prev_blk = 'in'; \n\n if ff_delay > 0,\n reuse_block(blk, 'delay_ff', 'xbsIndex_r4/Delay', ...\n 'en', async, 'latency', num2str(ff_delay), 'Position', [80 22 125 68]);\n add_line(blk, [prev_blk,'/1'], 'delay_ff/1');\n prev_blk = 'delay_ff';\n\n if strcmp(async, 'on'), add_line(blk, 'en/1', 'delay_ff/2'); \n end\n end\n\n if srl_delay > 0,\n reuse_block(blk, 'delay_sr', 'xbsIndex_r4/Delay', ...\n 'en', async, 'latency', num2str(srl_delay), 'reg_retiming', 'on', ...\n 'Position', [150 22 195 68]);\n add_line(blk, [prev_blk,'/1'], 'delay_sr/1');\n prev_blk = 'delay_sr';\n \n if strcmp(async, 'on'), add_line(blk, 'en/1', 'delay_sr/2'); \n end\n end\n\n reuse_block(blk, 'out', 'built-in/Outport', 'Port', '1', 'Position', [220 38 250 52]);\n add_line(blk, [prev_blk,'/1'], 'out/1');\n\n % Delete all unconnected blocks.\n clean_blocks(blk);\n\n % Save block state to stop repeated init script runs.\n save_state(blk, 'defaults', defaults, varargin{:});\nend % delay_srl_init\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "clean_blocks.m", "ext": ".m", "path": "mlib_devel-master/casper_library/clean_blocks.m", "size": 2807, "source_encoding": "utf_8", "md5": "1262b3dca13b1b2051b0b227e10f9cfb", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction clean_blocks(cursys)\r\n% Remove any blocks from a subsystem which are not connected\r\n% to the rest of the system.\r\n%\r\n% clean_blocks(cursys)\r\n\r\ntry\r\n\r\nblocks = get_param(cursys, 'Blocks');\r\nfor i=1:length(blocks),\r\n blk = [cursys,'/',blocks{i}];\r\n ports = get_param(blk, 'PortConnectivity');\r\n if ~isempty(ports),\r\n flag = 0;\r\n for j=1:length(ports),\r\n if ports(j).SrcBlock == -1,\r\n clog(['block ' cursys '/' get_param(blk,'Name') ...\r\n ' input port ' num2str(j) ...\r\n ' undriven (block will be deleted)'], ...\r\n 'clean_blocks_debug');\r\n flag = 0;\r\n break\r\n elseif ~flag && (~isempty(ports(j).SrcBlock) || ~isempty(ports(j).DstBlock)),\r\n flag = 1;\r\n end\r\n end\r\n if flag == 0,\r\n clog(['deleting block ' cursys '/' get_param(blk,'Name')], ...\r\n 'clean_blocks_debug');\r\n delete_block(blk);\r\n end\r\n end\r\nend\r\ncatch ex\r\n dump_and_rethrow(ex);\r\nend % try/catch\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_addsub_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_addsub_init.m", "size": 13544, "source_encoding": "utf_8", "md5": "1d514e3e96c6c12d5ac218209757b168", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (andrew@ska.ac.za) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_addsub_init(blk, varargin)\n\n clog('entering bus_addsub_init', {'trace', 'bus_addsub_init_debug'});\n \n defaults = { ...\n 'opmode', [0], ...\n 'n_bits_a', [8] , 'bin_pt_a', [3], 'type_a', 1, ...\n 'n_bits_b', [4 ] , 'bin_pt_b', [3], 'type_b', [1], ...\n 'n_bits_out', 8 , 'bin_pt_out', [3], 'type_out', [1], ...\n 'overflow', [1], 'quantization', [0], 'add_implementation', 'fabric core', ...\n 'latency', 1, 'async', 'off', 'cmplx', 'on', 'misc', 'on'\n }; \n \n check_mask_type(blk, 'bus_addsub');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 80;\n ypos = 50; yinc = 50;\n\n port_w = 30; port_d = 14;\n bus_expand_w = 50;\n bus_create_w = 50;\n add_w = 50; add_d = 60;\n del_w = 30; del_d = 20;\n\n opmode = get_var('opmode', 'defaults', defaults, varargin{:});\n n_bits_a = get_var('n_bits_a', 'defaults', defaults, varargin{:});\n bin_pt_a = get_var('bin_pt_a', 'defaults', defaults, varargin{:});\n type_a = get_var('type_a', 'defaults', defaults, varargin{:});\n n_bits_b = get_var('n_bits_b', 'defaults', defaults, varargin{:});\n bin_pt_b = get_var('bin_pt_b', 'defaults', defaults, varargin{:});\n type_b = get_var('type_b', 'defaults', defaults, varargin{:});\n n_bits_out = get_var('n_bits_out', 'defaults', defaults, varargin{:});\n bin_pt_out = get_var('bin_pt_out', 'defaults', defaults, varargin{:});\n type_out = get_var('type_out', 'defaults', defaults, varargin{:});\n overflow = get_var('overflow', 'defaults', defaults, varargin{:});\n quantization = get_var('quantization', 'defaults', defaults, varargin{:});\n add_implementation = get_var('add_implementation', 'defaults', defaults, varargin{:});\n latency = get_var('latency', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n cmplx = get_var('cmplx', 'defaults', defaults, varargin{:});\n async = get_var('async', 'defaults', defaults, varargin{:});\n \n delete_lines(blk);\n\n %default state, do nothing \n if (n_bits_a == 0) | (n_bits_b == 0),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_add_init',{'trace', 'bus_addsub_init_debug'});\n return;\n end\n \n lenba = length(n_bits_a); lenpa = length(bin_pt_a); lenta = length(type_a);\n a = [lenba, lenpa, lenta]; \n\n lenbb = length(n_bits_b); lenpb = length(bin_pt_b); lentb = length(type_b);\n b = [lenbb, lenpb, lentb]; \n\n lenbo = length(n_bits_out); lenpo = length(bin_pt_out); lento = length(type_out); \n lenm = length(opmode); lenq = length(quantization); leno = length(overflow);\n o = [lenbo, lenpo, lento, lenm, lenq, leno];\n\n comps = unique([a, b, o]);\n %if have more than 2 unique components or have two but one isn't 1\n if ((length(comps) > 2) | (length(comps) == 2 && comps(1) ~= 1)),\n clog('conflicting component sizes',{'bus_addsub_init_debug', 'error'});\n return;\n end\n\n %determine number of components from clues \n compa = max(a); compb = max(b); compo = max(o); comp = max(compa, compb);\n\n %need to specify at least one set of input components\n if compo > comp,\n clog('more output components than inputs',{'bus_addsub_init_debug','error'});\n return;\n end\n\n %replicate items if needed for a input\n n_bits_a = repmat(n_bits_a, 1, compa/lenba);\n bin_pt_a = repmat(bin_pt_a, 1, compa/lenpa);\n type_a = repmat(type_a, 1, compa/lenta);\n \n %replicate items if needed for b input\n n_bits_b = repmat(n_bits_b, 1, compb/lenbb);\n bin_pt_b = repmat(bin_pt_b, 1, compb/lenpb);\n type_b = repmat(type_b, 1, compb/lentb);\n\n %need to pad output if need more than one\n n_bits_out = repmat(n_bits_out, 1, comp/lenbo);\n bin_pt_out = repmat(bin_pt_out, 1, comp/lenpo);\n type_o = repmat(type_out, 1, comp/lento);\n overflow = repmat(overflow, 1, comp/leno);\n opmode = repmat(opmode, 1, comp/lenm);\n quantization = repmat(quantization, 1, comp/leno);\n\n %if complex we need to double down on some of these\n if strcmp(cmplx, 'on'),\n compa = compa*2;\n n_bits_a = reshape([n_bits_a; n_bits_a], 1, compa);\n bin_pt_a = reshape([bin_pt_a; bin_pt_a], 1, compa);\n type_a = reshape([type_a; type_a], 1, compa);\n \n compb = compb*2;\n n_bits_b = reshape([n_bits_b; n_bits_b], 1, compb);\n bin_pt_b = reshape([bin_pt_b; bin_pt_b], 1, compb);\n type_b = reshape([type_b; type_b], 1, compb);\n\n comp = comp*2;\n n_bits_out = reshape([n_bits_out; n_bits_out], 1, comp);\n bin_pt_out = reshape([bin_pt_out; bin_pt_out], 1, comp);\n type_o = reshape([type_o; type_o], 1, comp);\n overflow = reshape([overflow; overflow], 1, comp);\n opmode = reshape([opmode; opmode], 1, comp);\n quantization = reshape([quantization; quantization], 1, comp);\n end\n\n %input ports\n ypos_tmp = ypos + add_d*compa/2;\n reuse_block(blk, 'a', 'built-in/inport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + add_d*(compa/2 + compb/2);\n \n reuse_block(blk, 'b', 'built-in/inport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + add_d*compb/2;\n\n port_no = 3;\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/inport', ...\n 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n port_no = port_no+1;\n end\n ypos_tmp = ypos_tmp + yinc;\n\n xpos = xpos + xinc + port_w/2; \n\n if strcmp(async, 'on'),\n xpos = xpos + xinc + port_w/2; \n reuse_block(blk, 'en', 'built-in/inport', ...\n 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n end\n\n % bus expand\n ypos_tmp = ypos + add_d*compa/2; %reset ypos\n \n reuse_block(blk, 'a_debus', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', ['[',num2str(n_bits_a),']'], ...\n 'outputBinaryPt', ['[',num2str(bin_pt_a),']'], ...\n 'outputArithmeticType', ['[',num2str(type_a),']'], ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-add_d*compa/2 xpos+bus_expand_w/2 ypos_tmp+add_d*compa/2]);\n add_line(blk, 'a/1', 'a_debus/1');\n ypos_tmp = ypos_tmp + add_d*(compa/2+compb/2) + yinc;\n \n reuse_block(blk, 'b_debus', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', ['[',num2str(n_bits_b),']'], ...\n 'outputBinaryPt', ['[',num2str(bin_pt_b),']'], ...\n 'outputArithmeticType', ['[',num2str(type_b),']'], ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-add_d*compb/2 xpos+bus_expand_w/2 ypos_tmp+add_d*compb/2]);\n add_line(blk, 'b/1', 'b_debus/1');\n ypos_tmp = ypos_tmp + add_d*compa + yinc;\n\n %addsub\n xpos = xpos + xinc + add_w/2; \n ypos_tmp = ypos; %reset ypos \n\n %need addsub per component\n a_src = repmat([1:compa], 1, comp/compa);\n b_src = repmat([1:compb], 1, comp/compb);\n\n clog(['making ',num2str(comp),' AddSubs'],{'bus_addsub_init_debug'});\n\n for index = 1:comp\n switch type_o(index),\n case 0,\n arith_type = 'Unsigned';\n case 1,\n arith_type = 'Signed';\n end\n switch quantization(index),\n case 0,\n quant = 'Truncate';\n case 1,\n quant = 'Round (unbiased: +/- Inf)';\n end \n switch overflow(index),\n case 0,\n of = 'Wrap';\n case 1,\n of = 'Saturate';\n case 2,\n of = 'Flag as error';\n end \n switch opmode(index),\n case 0,\n m = 'Addition';\n symbol = '+';\n case 1,\n m = 'Subtraction'; \n symbol = '-';\n end \n \n clog(['output ',num2str(index),': ', ... \n ' a[',num2str(a_src(index)),'] ',symbol,' b[',num2str(b_src(index)),'] = ', ...\n '(',num2str(n_bits_out(index)), ' ', num2str(bin_pt_out(index)),') ' ...\n ,arith_type,' ',quant,' ', of], ...\n {'bus_addsub_init_debug'}); \n\n if strcmp(add_implementation, 'behavioral HDL'),\n use_behavioral_HDL = 'on';\n hw_selection = 'Fabric';\n elseif strcmp(add_implementation, 'fabric core'),\n use_behavioral_HDL = 'off';\n hw_selection = 'Fabric';\n elseif strcmp(add_implementation, 'DSP48 core'),\n use_behavioral_HDL = 'off';\n hw_selection = 'DSP48';\n end\n\n add_name = ['addsub',num2str(index)]; \n reuse_block(blk, add_name, 'xbsIndex_r4/AddSub', ...\n 'mode', m, 'latency', num2str(latency), ...\n 'en', async, 'precision', 'User Defined', ...\n 'n_bits', num2str(n_bits_out(index)), 'bin_pt', num2str(bin_pt_out(index)), ... \n 'arith_type', arith_type, 'quantization', quant, 'overflow', of, ... \n 'pipelined', 'on', 'use_behavioral_HDL', use_behavioral_HDL, 'hw_selection', hw_selection, ... \n 'Position', [xpos-add_w/2 ypos_tmp xpos+add_w/2 ypos_tmp+add_d-20]);\n ypos_tmp = ypos_tmp + add_d;\n \n add_line(blk, ['a_debus/',num2str(a_src(index))], [add_name,'/1']);\n add_line(blk, ['b_debus/',num2str(b_src(index))], [add_name,'/2']);\n\n if strcmp(async, 'on')\n add_line(blk, 'en/1', [add_name,'/3']);\n end\n\n end %for\n\n ypos_tmp = ypos + add_d*(compb+compa) + 2*yinc;\n if strcmp(misc, 'on'),\n reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(latency), ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, 'misci/1', 'dmisc/1');\n end\n ypos_tmp = ypos_tmp + yinc;\n \n if strcmp(async, 'on'),\n reuse_block(blk, 'den', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(latency), ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, 'en/1', 'den/1');\n end\n\n xpos = xpos + xinc + add_d/2;\n\n %bus create \n ypos_tmp = ypos + add_d*comp/2; %reset ypos\n \n reuse_block(blk, 'op_bussify', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(comp), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-add_d*comp/2 xpos+bus_create_w/2 ypos_tmp+add_d*comp/2]);\n \n for index = 1:comp,\n add_line(blk, ['addsub',num2str(index),'/1'], ['op_bussify/',num2str(index)]);\n end\n\n %output port/s\n ypos_tmp = ypos + add_d*comp/2;\n xpos = xpos + xinc + bus_create_w/2;\n reuse_block(blk, 'dout', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, ['op_bussify/1'], ['dout/1']);\n ypos_tmp = ypos_tmp + yinc + port_d; \n\n ypos_tmp = ypos + add_d*(compb+compa) + 2*yinc;\n port_no = 2;\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misco', 'built-in/outport', ...\n 'Port', num2str(port_no), ... \n 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n\n add_line(blk, 'dmisc/1', 'misco/1');\n port_no = port_no+1;\n end\n ypos_tmp = ypos_tmp + yinc;\n \n if strcmp(async, 'on'),\n reuse_block(blk, 'dvalid', 'built-in/outport', ...\n 'Port', num2str(port_no), ... \n 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n\n add_line(blk, 'den/1', 'dvalid/1');\n end\n \n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_addsub_init', {'bus_addsub_init_debug', 'trace'});\n\nend %function bus_addsub_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "dump_and_rethrow.m", "ext": ".m", "path": "mlib_devel-master/casper_library/dump_and_rethrow.m", "size": 1710, "source_encoding": "utf_8", "md5": "ef2f9cadf917f9417f31f10faeea525b", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2013 David MacMahon\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction dump_and_rethrow(ex)\n dump_exception(ex);\n rethrow(ex);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "dump_exception.m", "ext": ".m", "path": "mlib_devel-master/casper_library/dump_exception.m", "size": 2194, "source_encoding": "utf_8", "md5": "04c5177f30c57e32a81eea872633101f", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2013 David MacMahon\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction dump_exception(ex)\n\n persistent last_dumped;\n\n % An empty ex means to clear last_dumped\n if isempty(ex)\n last_dumped = [];\n % Do not re-dump ex if it has already been dumped\n elseif ~isa(last_dumped, 'MException') || last_dumped ~= ex\n last_dumped = ex;\n fprintf('%s: %s\\n', ex.identifier, ex.message);\n stack = ex.stack;\n for k=1:length(stack)\n fprintf('Backtrace %d: %s:%d\\n', ...\n k, stack(k).file, stack(k).line, stack(k).name, stack(k).line);\n end\n end\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "dds_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/dds_init.m", "size": 5191, "source_encoding": "utf_8", "md5": "8cff883aba91024d1bce2d6c0804b478", "text": "% dds_init(blk, varargin)\r\n%\r\n% blk = The block to initialize.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% freq_div = The (power of 2) denominator of the mixing frequency.\r\n% freq = The numerator of the mixing frequency\r\n% num_lo = The number of parallel streams provided\r\n% n_bits = The bitwidth of samples out\r\n% latency = The latency of sine/cos lookup table\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction dds_init(blk,varargin)\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {'num_lo', 1, 'n_bits', 8, 'latency', 2};\r\ncheck_mask_type(blk, 'dds');\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nmunge_block(blk, varargin{:});\r\n\r\nfreq_div = get_var('freq_div','defaults', defaults, varargin{:});\r\nfreq = get_var('freq','defaults', defaults, varargin{:});\r\nnum_lo = get_var('num_lo','defaults', defaults, varargin{:});\r\nn_bits = get_var('n_bits','defaults', defaults, varargin{:});\r\nlatency = get_var('latency','defaults', defaults, varargin{:});\r\n\r\ndelete_lines(blk);\r\n\r\n%default for storing in the library\r\nif num_lo == 0,\r\n clean_blocks(blk);\r\n set_param(blk,'AttributesFormatString','');\r\n save_state(blk, 'defaults', defaults, varargin{:}); \r\n return; \r\nend\r\n\r\ncounter_width = log2(freq_div);\r\ncounter_step = mod(num_lo*freq,freq_div);\r\n\r\nif num_lo < 1 || log2(num_lo) ~= round(log2(num_lo))\r\n error_string = 'The number of parallel LOs must be a power of 2 no less than 1';\r\n errordlg(error_string);\r\nend\r\nif freq < 0 || freq ~= round(freq)\r\n error_string = 'The frequency factor must be a positive integer';\r\n errordlg(error_string);\r\nend\r\n\r\nif freq_div <= 0 || freq_div < num_lo || freq_div ~= round(freq_div) || freq_div/num_lo ~= round(freq_div/num_lo) || log2(freq_div) ~= round(log2(freq_div))\r\n error_string = 'The frequency factor must be a positive power of 2 integer multiples of the number of LOs';\r\n errordlg(error_string);\r\nend\r\n\r\nfor i = 0 : num_lo - 1,\r\n sin_name = ['sin',num2str(i)];\r\n cos_name = ['cos',num2str(i)];\r\n % Add ports\r\n reuse_block(blk, sin_name, 'built-in/outport', 'Position', [175 45+i*100 205 60+100*i]);\r\n reuse_block(blk, cos_name, 'built-in/outport', 'Position', [175 70+i*100 205 85+100*i]);\r\n % Add LOs\r\n if counter_step == 0,\r\n lo_name = ['lo_const',num2str(i)];\r\n reuse_block(blk, lo_name, 'casper_library_downconverter/lo_const', 'Position', [100 i*100+50 140 i*100+90], ...\r\n 'n_bits', num2str(n_bits), 'phase', num2str(2*pi*freq*i/freq_div));\r\n else\r\n lo_name = ['lo_osc',num2str(i)];\r\n reuse_block(blk, 'sync', 'built-in/inport', 'Position', [30 100 60 115]);\r\n reuse_block(blk, lo_name, 'casper_library_downconverter/lo_osc', 'Position', [100 i*100+50 140 i*100+90], ...\r\n 'n_bits', num2str(n_bits), 'latency', num2str(latency), ...\r\n 'counter_width', num2str(counter_width), 'counter_start', num2str(mod(i*freq,freq_div)), ...\r\n 'counter_step', num2str(counter_step));\r\n add_line(blk,['sync','/1'],[lo_name,'/1']);\r\n end\r\n add_line(blk,[lo_name,'/1'],[sin_name,'/1']);\r\n add_line(blk,[lo_name,'/2'],[cos_name,'/1']); \r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\n% Set attribute format string (block annotation)\r\nannotation=sprintf('lo at -%d/%d',freq, freq_div);\r\nset_param(blk,'AttributesFormatString',annotation);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:}); \r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_create_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_create_init.m", "size": 4385, "source_encoding": "utf_8", "md5": "50ffeaa6f812e06e4f70d6e21762adee", "text": "% Create a 'bus' of similar signals\n%\n% bus_create_init(blk, varargin)\n%\n% blk = The block to be configured.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% inputNum = Number of inputs\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Meerkat radio telescope project %\n% www.kat.ac.za %\n% Copyright (C) Paul Prozesky 2011 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Create a 'bus' of similar signals.\n\nfunction bus_create_init(blk, varargin)\n\nclog('entering bus_create_init','trace');\n\ncheck_mask_type(blk, 'bus_create');\n\ndefaults = {'inputNum', 2};\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\n\n% check the params\ninputNum = get_var('inputNum', 'defaults', defaults, varargin{:});\nif (isnan(inputNum) || (~isnumeric(inputNum))),\n errordlg('Number of inputs must be natural number'); error('Number of inputs must be natural number'); end;\n\nmunge_block(blk, varargin{:});\n\n% delete all the lines\ndelete_lines(blk);\n\n% add the inputs, outputs and gateway out blocks, drawing lines between them\nxSize = 100;\nySize = 20;\nxStart = 100;\nxPos = xStart + (xSize * 2);\nyPos = 100;\n\n% one output for the bus\nreuse_block(blk, 'bus_out', 'built-in/outport', ...\n 'Position', [xStart + (xSize * 3 * 2), yPos + (ySize * (inputNum - 0.5)), xStart + (xSize * 3 * 2) + (xSize/2), yPos + (ySize * (inputNum + 0.5))]);\nconcatSize = ySize * inputNum;\n\nif inputNum > 1,\n reuse_block(blk, 'concatenate', 'xbsIndex_r4/Concat', ...\n 'Position', [xStart + (xSize * 2 * 2), yPos, xStart + (xSize * 2 * 2) + (xSize/2), yPos + (2 * ySize * inputNum) - ySize], ...\n 'num_inputs', num2str(inputNum));\n add_line(blk, ['concatenate', '/1'], ['bus_out', '/1'], 'autorouting', 'on');\nend\n\n% draw the inputs and convert blocks\nfor p = 1 : inputNum,\n xPos = xStart;\n % the output block\n inName = sprintf('in%i', p);\n reuse_block(blk, inName, 'built-in/inport', 'Position', [xPos, yPos, xPos + (xSize/2), yPos + ySize]);\n xPos = xPos + (xSize * 2);\n % the cast block\n reinterpretName = sprintf('reinterpret%i', p);\n reuse_block(blk, reinterpretName, 'xbsIndex_r4/Reinterpret', ...\n 'Position', [xPos, yPos, xPos + (xSize/2), yPos + ySize], ...\n 'force_arith_type', 'on', 'arith_type', 'Unsigned', ...\n 'force_bin_pt', 'on', 'bin_pt', '0');\n yPos = yPos + (ySize * 2);\n % connect up the blocks\n add_line(blk, [inName, '/1'], [reinterpretName, '/1'], 'autorouting', 'on');\n if inputNum > 1,\n add_line(blk, [reinterpretName, '/1'], ['concatenate', '/', num2str(p)], 'autorouting', 'on');\n else\n add_line(blk, [reinterpretName, '/1'], 'bus_out/1', 'autorouting', 'on');\n end\nend;\n\n% remove unconnected blocks\nclean_blocks(blk);\n\nsave_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\nclog('exiting bus_create_init','trace');\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "delete_lines.m", "ext": ".m", "path": "mlib_devel-master/casper_library/delete_lines.m", "size": 1962, "source_encoding": "utf_8", "md5": "74821081e848af88f2fd32cc3221a25d", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction delete_lines(cursys)\r\n% Remove all lines from a system.\r\n%\r\n% delete_lines(cursys)\r\n\r\ntry\r\n lines = get_param(cursys, 'Lines');\r\n for k=1:length(lines),\r\n delete_line(lines(k).Handle);\r\n end\r\ncatch ex\r\n dump_and_rethrow(ex);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "munge_block.m", "ext": ".m", "path": "mlib_devel-master/casper_library/munge_block.m", "size": 3319, "source_encoding": "utf_8", "md5": "bbdc399735f88a8da2ad5cc7c1f1387e", "text": "% Performs various munges on a block.\n%\n% munge_block(blk,varargin)\n%\n% blk - The block whose mask will be dumbed down or turned off\n% varargin - A cell array of strings indicating the munges to do.\n%\n% Supported munges:\n%\n% 'dumbdown'\n%\n% Dumbing down a block's mask makes the block's mask informative only;\n% the mask can no longer be used to configure the subsystem. Here is\n% a list of what happens to a mask that is dumbed down...\n%\n% o MaskInitialization code is deleted.\n% o All mask parameters are marked as disabled, non-tunable, and\n% do-not-evaluate. \n%\n% 'unmask'\n%\n% Turns off the block's mask.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction munge_block(blk, varargin)\n\ntry\n\n % Don't munge if blk lives in a library\n if is_library_block(blk), return, end\n \n % Disable link\n set_param(blk,'LinkStatus', 'inactive');\n \n % Take appropriate munge action\n switch get_var('munge', varargin{:})\n case 'dumbdown'\n % Nuke any mask initialization code\n set_param(blk, 'MaskInitialization','');\n % Make mask params disabled\n mes=get_param(blk, 'MaskEnableString');\n mes=strrep(mes, 'on','off');\n set_param(blk, 'MaskEnableString',mes);\n % Make mask params non-tunable\n mtvs=get_param(blk, 'MaskTunableValueString');\n mtvs=strrep(mtvs, 'on', 'off');\n set_param(blk, 'MaskTunableValueString', mtvs);\n % Make mask params literal (non-evaluated)\n mv=get_param(blk, 'MaskVariables');\n mv=strrep(mv, '@', '&');\n set_param(blk, 'MaskVariables', mv);\n case 'unmask'\n set_param(blk, 'Mask', 'off');\n end\ncatch ex\n dump_and_rethrow(ex);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fir_col_async_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fir_col_async_init.m", "size": 12037, "source_encoding": "utf_8", "md5": "7219a4b6b5ce61f2bd46ac804d22514e", "text": "% fir_col_init(blk, varargin)\r\n%\r\n% blk = The block to initialize.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% n_inputs = The number of parallel input samples.\r\n% coeff = The FIR coefficients, top-to-bottom.\r\n% add_latency = The latency of adders.\r\n% mult_latency = The latency of multipliers.\r\n% coeff_bit_width = The number of bits used for coefficients\r\n% coeff_bin_pt = The number of fractional bits in the coefficients\r\n% first_stage_hdl = Whether to implement the first stage in adder trees\r\n% as behavioral HDL so that adders are absorbed into DSP slices used for\r\n% multipliers where this is possible.\r\n% adder_imp = adder implementation (Fabric, behavioral HDL, DSP48)\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction fir_col_async_init(blk)\r\nclog('entering fir_col_async_init', 'trace');\r\n\r\nshowname = 'on';\r\nsizey_goto = 15;\r\n\r\nvarargin = make_varargin(blk);\r\n\r\n% declare any default values for arguments you might like.\r\ndefaults = {'n_inputs', 0, 'coeff', 0.1, 'add_latency', 2, ...\r\n 'mult_latency', 3, 'coeff_bit_width', 25, 'coeff_bin_pt', 24, ...\r\n 'first_stage_hdl', 'off', 'adder_imp', 'Fabric', 'async', 'off', ...\r\n 'bus_input', 'off', 'dbl', 'off', 'input_width', 16, ...\r\n 'input_bp', 0, 'input_type', 'Unsigned'};\r\n\r\ncheck_mask_type(blk, 'fir_col_async');\r\n% if same_state(blk, 'defaults', defaults, varargin{:}),\r\n% clog('fir_col_async_init same state', 'trace');\r\n% return;\r\n% end\r\nclog('fir_col_async_init post same_state', 'trace');\r\nmunge_block(blk, varargin{:});\r\n\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\ncoeff = get_var('coeff', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\ncoeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\r\ncoeff_bin_pt = get_var('coeff_bin_pt', 'defaults', defaults, varargin{:});\r\nfirst_stage_hdl = get_var('first_stage_hdl', 'defaults', defaults, varargin{:});\r\nadder_imp = get_var('adder_imp', 'defaults', defaults, varargin{:});\r\nasync_ops = strcmp('on', get_var('async', 'defaults', defaults, varargin{:}));\r\nbus_input = strcmp('on', get_var('bus_input', 'defaults', defaults, varargin{:}));\r\ndouble_blk = strcmp('on', get_var('dbl', 'defaults', defaults, varargin{:}));\r\n\r\n% default library state\r\nif n_inputs == 0,\r\n clog('fir_col_async_init no inputs', 'trace');\r\n clean_blocks(blk);\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting fir_col_async_init', 'trace');\r\n return;\r\nend\r\n\r\n% async_ops = false;\r\n% bus_input = false;\r\n% double_blk = false;\r\n\r\n% hand off to the double script if this is a doubled-up FIR\r\nif double_blk,\r\n fir_dbl_col_async_init(blk, varargin{:});\r\nelse\r\n if bus_input,\r\n input_width = get_var('input_width','defaults', defaults, varargin{:});\r\n input_bp = get_var('input_bp','defaults', defaults, varargin{:});\r\n input_type = get_var('input_type','defaults', defaults, varargin{:});\r\n if strcmp(input_type, 'Signed'),\r\n input_type_num = 1;\r\n else\r\n input_type_num = 0;\r\n end\r\n end\r\n\r\n delete_lines(blk);\r\n\r\n if length(coeff) ~= n_inputs,\r\n clog('number of coefficients must be the same as the number of inputs', {'fir_col_async_init_debug', 'error'});\r\n error('number of coefficients must be the same as the number of inputs');\r\n end\r\n\r\n % draw the inputs differently depending on whether we're taking a bus input or not\r\n if bus_input,\r\n reuse_block(blk, 'dbus_in', 'built-in/inport', 'Position', [0 30 30 46], 'Port', '1');\r\n reuse_block(blk, 'inbus', 'casper_library_flow_control/bus_expand', 'Position', [80 30 150 30+(n_inputs*sizey_goto*3)]);\r\n set_param([blk, '/inbus'], ...\r\n 'mode', 'divisions of equal size', ...\r\n 'outputNum', num2str(2*n_inputs), ...\r\n 'outputWidth', num2str(input_width), ...\r\n 'outputBinaryPt', num2str(input_bp), ...\r\n 'outputArithmeticType', num2str(input_type_num), ...\r\n 'show_format', 'off', ...\r\n 'outputToWorkspace', 'off');\r\n add_line(blk, 'dbus_in/1', 'inbus/1');\r\n port_num = 2;\r\n else\r\n port_num = 1;\r\n for ctr = 1 : n_inputs,\r\n ctrstr = num2str(ctr);\r\n reuse_block(blk, ['real', ctrstr], 'built-in/inport', 'Position', [30 ctr*80 60 15+80*ctr]);\r\n reuse_block(blk, ['imag', ctrstr], 'built-in/inport', 'Position', [30 ctr*80+30 60 45+80*ctr]);\r\n port_num = port_num + 2;\r\n end\r\n end\r\n if async_ops,\r\n reuse_block(blk, 'dv', 'built-in/inport', 'Position', [0 0 30 16], 'Port', num2str(port_num));\r\n reuse_block(blk, 'dv_in', 'built-in/goto', ...\r\n 'GotoTag', 'dv_in', 'showname', showname, ...\r\n 'Position', [50 0 120 16]);\r\n add_line(blk, 'dv/1', 'dv_in/1');\r\n end\r\n\r\n % tap blocks\r\n for ctr = 1 : n_inputs,\r\n ctrstr = num2str(ctr);\r\n blkname = ['fir_tap', ctrstr];\r\n full_blkname = [blk, '/', blkname];\r\n tap_ypos = ctr*160 - 160;\r\n reuse_block(blk, blkname, 'casper_library_downconverter/fir_tap_async', ...\r\n 'Position', [400 tap_ypos 470 tap_ypos+120], ...\r\n 'add_latency', num2str(add_latency), ...\r\n 'mult_latency', num2str(mult_latency), ...\r\n 'factor', num2str(coeff(ctr)), ...\r\n 'coeff_bit_width', num2str(coeff_bit_width), ...\r\n 'coeff_bin_pt', num2str(coeff_bin_pt), 'dbl', 'off');\r\n if async_ops,\r\n set_param(full_blkname, 'async', 'on');\r\n else\r\n set_param(full_blkname, 'async', 'off');\r\n end\r\n % connection to inputs\r\n if async_ops,\r\n reuse_block(blk, ['dv_in', ctrstr], 'built-in/from', 'GotoTag', 'dv_in', 'showname', showname, 'Position', [280 tap_ypos+104 360 tap_ypos+120]);\r\n add_line(blk, ['dv_in', ctrstr, '/1'], [blkname, '/3']);\r\n end\r\n if bus_input,\r\n pos = ((ctr-1)*2)+1;\r\n add_line(blk, ['inbus/', num2str(pos+0)], [blkname, '/1']);\r\n add_line(blk, ['inbus/', num2str(pos+1)], [blkname, '/2']);\r\n else\r\n add_line(blk, ['real', ctrstr, '/1'], [blkname, '/1']);\r\n add_line(blk, ['imag', ctrstr, '/1'], [blkname, '/2']);\r\n end\r\n end\r\n\r\n % output ports\r\n if bus_input,\r\n reuse_block(blk, 'outbus', 'casper_library_flow_control/bus_create', ...\r\n 'inputNum', num2str(n_inputs*2), ...\r\n 'Position', [600 30 650 30+(n_inputs*sizey_goto*3)]);\r\n reuse_block(blk, 'dbus_out', 'built-in/outport', 'Position', [700 30 730 46], 'Port', '1');\r\n add_line(blk, 'outbus/1', 'dbus_out/1');\r\n end\r\n for ctr = 1 : n_inputs,\r\n ctrstr = num2str(ctr);\r\n tapname = ['fir_tap', ctrstr];\r\n tap_ypos = ctr*160 - 160;\r\n if bus_input,\r\n pos = ((ctr-1)*2)+1;\r\n add_line(blk, [tapname, '/1'], ['outbus/', num2str(pos+0)]);\r\n add_line(blk, [tapname, '/2'], ['outbus/', num2str(pos+1)]);\r\n else\r\n reuse_block(blk, ['real_out',ctrstr], 'built-in/outport', 'Position', [550 tap_ypos 580 tap_ypos+16], 'Port', num2str(2*ctr-1));\r\n reuse_block(blk, ['imag_out',ctrstr], 'built-in/outport', 'Position', [550 tap_ypos+30 580 tap_ypos+46], 'Port', num2str(2*ctr));\r\n add_line(blk, [tapname, '/1'], ['real_out', ctrstr, '/1']);\r\n add_line(blk, [tapname, '/2'], ['imag_out', ctrstr, '/1']);\r\n end\r\n end\r\n\r\n % the output sum blocks\r\n if bus_input,\r\n reuse_block(blk, 'real_sum', 'built-in/outport', 'Position', [900 100+20*n_inputs 930 116+20*n_inputs], 'Port', '2');\r\n reuse_block(blk, 'imag_sum', 'built-in/outport', 'Position', [900 200+20*n_inputs 930 216+20*n_inputs], 'Port', '3');\r\n else\r\n reuse_block(blk, 'real_sum', 'built-in/outport', 'Position', [900 100+20*n_inputs 930 116+20*n_inputs], 'Port', num2str(n_inputs*2+1));\r\n reuse_block(blk, 'imag_sum', 'built-in/outport', 'Position', [900 200+20*n_inputs 930 216+20*n_inputs], 'Port', num2str(n_inputs*2+2));\r\n end\r\n\r\n % the adder trees\r\n if n_inputs > 1,\r\n reuse_block(blk, 'adder_tree1', 'casper_library_misc/adder_tree', ...\r\n 'Position', [800 100 850 100+20*n_inputs], 'n_inputs', num2str(n_inputs),...\r\n 'latency', num2str(add_latency), 'first_stage_hdl', first_stage_hdl, 'adder_imp', adder_imp);\r\n reuse_block(blk, 'adder_tree2', 'casper_library_misc/adder_tree', ...\r\n 'Position', [800 200+20*n_inputs 850 200+20*n_inputs+20*n_inputs], 'n_inputs', num2str(n_inputs),...\r\n 'latency', num2str(add_latency), 'first_stage_hdl', first_stage_hdl, 'adder_imp', adder_imp);\r\n reuse_block(blk, 'c1', 'xbsIndex_r4/Constant', ...\r\n 'explicit_period', 'on', 'Position', [750 100 780 110]);\r\n reuse_block(blk, 'c2', 'xbsIndex_r4/Constant', ...\r\n 'explicit_period', 'on', 'Position', [750 200+20*n_inputs 780 210+20*n_inputs]);\r\n reuse_block(blk, 'term1','built-in/Terminator', 'Position', [1000 100 1015 115]);\t\r\n add_line(blk, 'adder_tree1/1', 'term1/1');\r\n reuse_block(blk, 'term2','built-in/Terminator', 'Position', [1000 200+20*n_inputs 1015 215+20*n_inputs]);\t\r\n add_line(blk, 'adder_tree2/1', 'term2/1');\r\n add_line(blk, 'c1/1', 'adder_tree1/1');\r\n add_line(blk, 'c2/1', 'adder_tree2/1');\r\n add_line(blk,'adder_tree1/2','real_sum/1');\r\n add_line(blk,'adder_tree2/2','imag_sum/1');\r\n for ctr=1:n_inputs,\r\n add_line(blk, ['fir_tap', num2str(ctr), '/3'], ['adder_tree1/', num2str(ctr+1)]);\r\n add_line(blk, ['fir_tap', num2str(ctr), '/4'], ['adder_tree2/', num2str(ctr+1)]);\r\n end\r\n else\r\n add_line(blk, 'fir_tap1/3', 'real_sum/1');\r\n add_line(blk, 'fir_tap1/4', 'imag_sum/1');\r\n end\r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\nclog('exiting fir_col_async_init', 'trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "mdl2m.m", "ext": ".m", "path": "mlib_devel-master/casper_library/mdl2m.m", "size": 32302, "source_encoding": "utf_8", "md5": "3e9f0d85e5d3324b03bc488c41f12b93", "text": "%generate script to draw system specified\n% \n%usage: function mdl2m(mdl, varargin)\n%mdl \t\t- model to convert\n%varargin\t- 'name', value pairs where name can be;\n% script_name\t - name of initialization script ([.../casper_library/_init.m])\n% mode\t\t - mode to open initialization script in ('a'-append, ['w']-overwrite)\n% file\t\t - pass file pointer (created with fopen) directly\n% subsystem - the system is a subsystem (so don't generate system parameters etc) ('on', ['off'])\n% reuse - generated script uses reuse_block instead of add_block for more efficient drawing \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% MeerKAT Radio Telescope Project %\n% www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (meerKAT) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction mdl2m(mdl, varargin)\n \n base = 'getenv(''MLIB_DEVEL_PATH''), ''/casper_library/''';\n name = get_param(mdl, 'name');\n defaults = { ...\n 'script_name', [eval(['[',base,']']), name, '_init'], ... \n 'mode', 'w', ... \n 'subsystem', 'off', ...\n 'file', -1, ...\n };\n script_name = get_var('script_name', 'defaults', defaults, varargin{:});\n m = get_var('mode', 'defaults', defaults, varargin{:});\n fp = get_var('file', 'defaults', defaults, varargin{:});\n mdl_name = [base, ', ''', name, ''''];\n library = get_var('library', 'defaults', defaults, varargin{:});\n subsystem = get_var('subsystem', 'defaults', defaults, varargin{:});\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % get necessary system parameters %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n if strcmp(subsystem, 'off'),\n lt = get_param(mdl, 'LibraryType');\n if strcmp(lt, 'BlockLibrary'),\n library = 'on';\n else\n library = 'off';\n end\n\n clog(['getting system parameter values for ''',mdl,''''],'mdl2m_debug'); \n required_sys_params = ...\n { ...\n 'Name', ...\n 'LibraryType', ... %is this a library?\n 'Lock', ... %locked library\n\t'PreSaveFcn', ... %things to do before saving\n 'SolverName', ... %simulation type\n 'SolverMode', ... %\n 'StartTime', ... %simulation start time\n 'StopTime', ... %simulation stop time\n };\n sys_params = get_params(mdl, required_sys_params);\n else,\n library = 'off';\n clog(['skipping getting parameter values for ''',mdl,''''],'mdl2m_debug'); \n end\n\n %%%%%%%%%%%%%\n % open file %\n %%%%%%%%%%%%%\n \n if fp == -1,\n ntc = 1; %need to close file after\n clog(['opening ''',script_name,''''],'mdl2m_debug');\n fp = fopen([script_name,'.m'],m);\n if fp == -1,\n clog(['error opening ''',script_name,''''],{'error', 'mdl2m_debug'});\n error(['error opening ''',script_name,'''']);\n return;\n end\n else\n ntc = 0;\n end \n\n tokens = regexp(script_name, '/', 'split');\n f_name = tokens{length(tokens)};\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % set up top level function %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n if strcmp(subsystem, 'off'),\n fprintf(fp,'function %s()\\n',f_name); \n else,\n fprintf(fp,'function %s(blk)\\n',f_name); \n end\n fprintf(fp, '\\n'); \n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % generate creation of new system %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n if strcmp(subsystem, 'off'),\n clog(['setting up creation of new system ''',mdl,''''],'mdl2m_debug'); \n\n if strcmp(library, 'on'), sys_type = 'Library'; else, sys_type = 'Model'; end\n fprintf(fp,'\\twarning off Simulink:Engine:MdlFileShadowing;\\n'); \n fprintf(fp,'\\tclose_system(''%s'', 0);\\n', name); % close system if it's open\n fprintf(fp,'\\tmdl = new_system(''%s'', ''%s'');\\n', name, sys_type); %create a new system \n fprintf(fp,'\\tblk = get(mdl,''Name'');\\n'); %get the name for future use\n fprintf(fp,'\\twarning on Simulink:Engine:MdlFileShadowing;\\n'); \n fprintf(fp,'\\n'); \n else, \n clog(['configuring ''',mdl,'''...'],'mdl2m_debug'); \n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % generate logic to draw blocks in system %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %find all blocks in top level of system\n blks = find_system(mdl, 'SearchDepth', 1, 'LookUnderMasks', 'on', 'FollowLinks', 'on', 'type', 'block');\n\n %if a subsystem have to exclude first entry\n if strcmp(subsystem,'on'),\n if length(blks) > 1,\n clog(['excluding top block as subsystem'],'mdl2m_debug'); \n blks = blks(2:length(blks));\n else,\n %empty blocks\n blks = {};\n end\n end\n\n %place in order of processing (will determine order of blocks in text file)\n [blks, indices] = sort_blocks(blks, 'default'); \n\n clog(['adding block generation logic for ',num2str(length(blks)),' blocks'],'mdl2m_debug'); \n if strcmp(library,'on'), reuse = 'off';\n else reuse = 'on';\n end\n add_blocks(blks, fp, reuse);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % generate logic to draw lines in system %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n sys_lines = get_param(mdl, 'Lines');\n [sys_lines, indices] = sort_lines(sys_lines, 'default');\n\n clog(['adding line generation logic for ',num2str(length(sys_lines)),' lines'],'mdl2m_debug'); \n for line_index = 1:length(sys_lines),\n line = sys_lines(line_index);\n add_line(line, fp);\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % generate logic to set up system parameters %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n if strcmp(subsystem, 'off'),\n clog(['adding system parameters for ',mdl],'mdl2m_debug'); \n set_params(fp, 'blk', sys_params, 'no_empty'); \n else,\n clog(['skipping addition of system parameters for ',mdl,' as a subsystem'],'mdl2m_debug'); \n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % finalise generation logic %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %if a library, must be saved somewhere before can be used\n if strcmp(library, 'on'),\n fprintf(fp, '\\tfilename = save_system(mdl,[%s]);\\n', mdl_name);\n % Make sure other's can overwrite so we can share mlib_devel working copy\n % between users.\n fprintf(fp, '\\tif iscell(filename), filename = filename{1}; end;\\n');\n fprintf(fp, '\\tfileattrib(filename, ''+w'');\\n');\n end\n \n fprintf(fp,'end %% %s\\n\\n',f_name);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % generate functions to generate blocks %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n clog(['appending block generation functions'],'mdl2m_debug'); \n gen_blocks('blks', blks, 'file', fp);\n\n if ntc == 1, \n result = fclose(fp); \n if result ~= 0, clog(['error closing file ',script_name],{'mdl2m_debug', 'error'}); end\n % Make sure other's can overwrite so we can share mlib_devel working copy\n % between users.\n fileattrib([script_name,'.m'], '+w');\n end \nend %mdl2m\n\n%function to sort blocks into order they will appear in system generation script\n%strategy can be 'name', 'default'\nfunction[blocks, indices] = sort_blocks(blocks_in, strategy)\n %default is input ports first, then position from top left corner, then output ports\n if strcmp(strategy,'default'),\n %go through finding inports, outports, and position info\n inports = {}; outports = {}; remainder = {};\n inport_indices = []; outport_indices = []; remainder_indices = []; \n remainder_distances = [];\n for index = 1:length(blocks_in),\n blk = blocks_in{index};\n type = get_param(blk, 'BlockType');\n\n if strcmp(type, 'Inport'),\n inport_indices = [inport_indices, index];\n elseif strcmp(type, 'Outport'),\n outport_indices = [outport_indices, index];\n else,\n remainder_indices = [remainder_indices, index];\n position = get_param(blk, 'Position');\n %distance from top left to centre of block\n remainder_distances = [remainder_distances, sqrt(((position(3) + position(1))/2)^2+((position(4) + position(2))/2)^2)]; \n end %if\n end %for\n\n %now sort remainder_distances, finding indices\n [temp, sorted_indices] = sort(remainder_distances);\n\n %construct final vector of blocks and indices\n indices = [inport_indices, remainder_indices(sorted_indices), outport_indices];\n blocks = {blocks_in{indices}};\n\n %alphabetically by name\n elseif strcmp(strategy, 'name'),\n blocks = sort(blocks_in);\n else,\n clog(['unknown sort strategy ''',strategy,''''],{'mdl2m_debug','sort_blocks_debug', 'error'}); \n error(['unknown sort strategy ''',strategy,'''']); \n end\nend %sort_blocks\n\n%function to sort lines into order they will appear in system generation script\n%strategy can be 'default', 'name' and is based on line source\nfunction[lines_out, indices] = sort_lines(lines_in, strategy)\n\n %go through all lines finding blocks associated with source of lines\n blocks_in = {};\n for index = 1:length(lines_in),\n line = lines_in(index);\n srcblk = line.SrcBlock;\n %sanity check\n if isempty(srcblk),\n clog(['sanity check error: no SrcBlk for start of line!'],{'mdl2m_debug','sort_lines_debug', 'error'}); \n error(['sanity check error: no SrcBlk for start of line!']); \n end %if\n\n blocks_in = {blocks_in{:}, srcblk};\n end %for\n\n %sort source blocks with specified strategy\n [blocks, indices] = sort_blocks(blocks_in, strategy);\n\n %rearrange lines according to sort results\n lines_out = lines_in(indices);\n\nend %sort_lines\n\n%logic to add block to system\n%blks = blocks to be added, fp = file pointer, reuse = use reuse_block instead of add_block\nfunction add_blocks(blks, fp, reuse)\n \n %go through and process all blocks\n for index = 1:length(blks),\n blk = blks{index};\n name = get_param(blk, 'Name');\n sls = get_param(blk, 'StaticLinkStatus'); %library block or not (and does not update out-of-date linked blocks)\n block_type = get_param(blk, 'BlockType'); %for built-in blocks\n anc_block = get_param(blk, 'AncestorBlock'); %AncestorBlock (for disabled library links)\n\n position = get_param(blk, 'Position'); %once added, we put the block in the correct place\n tag = get_param(blk, 'Tag');\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % block not from any library (i.e built-in), %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n if strcmp(sls, 'none'), \n src = ['built-in/',block_type];\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % contained in a library block % \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n elseif strcmp(sls, 'implicit'),\n %if we are generating a library block, then the link to itself is not useful so ignore ReferenceBlock\n\n %asssume use of original library block (AncestorBlock) if implicit library block with AncestorBlock\n if ~isempty(anc_block)\n src = anc_block;\n clog(['assuming ok to use ', src,' for ',name,' with disabled link'],{'add_lib_blocks_debug', 'mdl2m_debug'}); \n else, \n src = ['built-in/',block_type];\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % library block, link resolved %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n elseif strcmp(sls, 'resolved'), \n src = get_param(blk, 'ReferenceBlock'); %for library blocks without disabled links\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % library block, link disabled %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n elseif strcmp(sls, 'inactive'), \n src = anc_block; %for library blocks with disabled (but not broken) links\n clog(['assuming ok to use ', src,' for ',name,' with disabled link'],{'add_lib_blocks_debug', 'mdl2m_debug'}); \n % link to library block that we can't figure out\n elseif strcmp(sls, 'unresolved'),\n clog(['can''t find library source for ',name,' with ''unresolved'' StaticLinkStatus'],{'error', 'add_blocks_debug', 'mdl2m_debug'}); \n error(['can''t find library source for ',name,' with ''unresolved'' StaticLinkStatus']); \n return; \n else,\n clog(['don''t know what to do with a ',sls,' StaticLinkStatus for ',name],{'error', 'add_blocks_debug', 'mdl2m_debug'}); \n error(['don''t know what to do with a ',sls,' StaticLinkStatus for ',name]);\n return; \n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % make block of required type %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n clog(['instantiating ',name,' of type ''',src,''''], {'add_blocks_debug', 'mdl2m_debug'});\n if strcmp(reuse, 'on'), \n func = sprintf('reuse_block(blk, ''%s'', ''%s'');',name, src);\n else \n func = sprintf('add_block(''%s'', [blk,''/%s'']);', src, name);\n end\n \n fprintf(fp, '\\t%s\\n', func); \n\n dialog_param_strategy = 'default'; %by default look at differences and include/exclude certain parameters\n %built-in or (implicit library block but not from original library block)\n if strcmp(sls, 'none') || (strcmp(sls, 'implicit') && isempty(anc_block)), \n %block is of type SubSystem so needs to be generated\n if strcmp(block_type,'SubSystem'),\n if strcmp(get_param(blk, 'Mask'), 'on'),\n dialog_param_strategy = 'all'; %take all dialog parameters if subsystem to be generated has a mask\n else,\n dialog_param_strategy = 'none';\n end\n clog(['generating logic to generate ''',name,''' block from SubSystem base'], {'add_blocks_debug', 'mdl2m_debug'}); \n \n fprintf(fp, '\\t%s_gen([blk,''/%s'']);\\n', name, name); %call block generation logic\n end\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % set up mask parameter values %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n required_params = determine_dialog_params(blk, src, dialog_param_strategy);\n clog(['setting up required dialog parameters for ',name], {'add_blocks_debug', 'mdl2m_debug'});\n params = get_params(blk, required_params); \n set_params(fp, ['[blk,''/',name,''']'], {params{:}, 'Position', position, 'Tag', tag}, 'all'); %appending Position guarantees at least one param\n fprintf(fp,'\\n');\n\n end %for index\nend %add_blocks\n\n%determine which dialog parameters need to be set up for the specified block\n%strategy can be 'default', 'all', 'delta', 'none'\nfunction[params] = determine_dialog_params(blk, src, strategy)\n\n dp = get_param(blk, 'DialogParameters');\n\n if ~isempty(dp),\n all_params = fieldnames(dp);\n else\n all_params = {};\n end\n \n %set parameter values for all parameters\n if strcmp(strategy,'none'),\n params = {};\n elseif strcmp(strategy,'all'),\n params = all_params;\n \n %get default mask parameter values, block mask parameter values and look for differences\n else,\n %look up parameters we need and ones that are unnecessary based on block type\n [required_params, unnecessary_params] = filter_dialog_parameters(src);\n\n params = {};\n blk_params = get_params(blk, all_params);\n src_params = get_params(src, all_params);\n \n %sanity check\n if(length(blk_params) ~= length(src_params)),\n clog(['block parameter length does not match source for ',blk],{'error', 'determine_dialog_params_debug', 'mdl2m_debug'}); \n error(['block parameter length does not match source for ',blk]);\n return; \n end\n\n %go through comparing names and values\n for index = 1:2:length(blk_params),\n blk_name = blk_params{index}; blk_value = blk_params{index+1};\n src_name = src_params{index}; src_value = src_params{index+1};\n \n %sanity check\n if ~strcmp(blk_name, src_name),\n clog(['block param name (''',blk_name,'''),does not match source param name (''',src_name,''') for ',blk],{'error', 'determine_dialog_params_debug', 'mdl2m_debug'}); \n error(['block param name (''',blk_name,'''),does not match source param name (''',src_name,''') for ',blk]); \n return; \n end\n\n unnecessary = (sum(strcmp(blk_name, unnecessary_params)) > 0);\n required = (sum(strcmp(blk_name, required_params)) > 0);\n diff = (~strcmp(to_string(blk_value), to_string(src_value)));\n clog(['block param (''',blk_name,''') for ',blk,' unnecessary: ',num2str(unnecessary),' required: ',num2str(required),' diff: ',num2str(diff)],{'determine_dialog_params_debug', 'mdl2m_debug'}); \n %include if (default strategy and not unnecessary and (required or if different from default) or (delta strategy and difference from default)\n if ((strcmp(strategy, 'default') && ~unnecessary) && (required || diff)) || (strcmp(strategy, 'delta') && diff), \n clog(['block param (''',blk_name,'''), included for ',blk],{'determine_dialog_params_debug', 'mdl2m_debug'}); \n params = {params{:}, blk_name};\n else,\n clog(['block param (''',blk_name,'''), not included'],{'determine_dialog_params_debug', 'mdl2m_debug'}); \n end\n end %for\n end %if\n\nend %determine_dialog_params\n\n%forces addition and removal of certain parameters based on block source\nfunction[force_include, force_exclude] = filter_dialog_parameters(src)\n tokens = regexp(src, '/', 'split');\n blk = tokens{length(tokens)};\n base_lib = tokens{1};\n\n force_include = {}; force_exclude = {};\n %Xilinx System Generator blockset\n if length(base_lib > 8) && strcmp(base_lib(1:8), 'xbsIndex'),\n\n clog(['including/excluding parameters for System Generator block ''',blk,''''], {'mdl2m_debug', 'filter_dialog_parameters_debug'});\n %exclude parameter values that are generated by other scripts\n force_exclude = {force_exclude{:}, ...\n 'infoedit', ...\n 'block_version', ...\n 'sg_icon_stat', ...\n 'sg_mask_display', ...\n 'sg_list_contents', ...\n 'sggui_pos', ...\n 'xl_area', ...\n }; \n\n %casper block\n elseif length(base_lib >= 6) && strcmp(base_lib(1:6), 'casper'),\n \n clog(['including/excluding parameters for casper block ''',blk,''''], {'mdl2m_debug', 'filter_dialog_parameters_debug'});\n\n force_include = {force_include{:}, ...\n %TODO \n% 'UserData', ... %UserData contains state and mask struct values\n% 'UserDataPersistent', ...\n };\n \n elseif length(base_lib >= 8) && strcmp(base_lib(1:8), 'built-in'),\n clog(['including/excluding parameters for built-in block ''',blk,''''], {'mdl2m_debug', 'filter_dialog_parameters_debug'});\n\n if strcmp(blk, 'Outport') || strcmp(blk, 'Inport'),\n force_include = {force_include{:}, 'Port'};\n end %if\n\n else,\n clog(['including/excluding parameters for unknown block ''',blk,''''], {'mdl2m_debug', 'filter_dialog_parameters_debug'});\n %don't know so include everything\n force_exclude = {}; force_include = {};\n end %if\n\n include_str = [''];\n for index = 1:length(force_include),\n if index ~= 1, include_str = [include_str, ', ']; end\n include_str = [include_str, '''', force_include{index}, ''''];\n end\n clog(['required parameters for block ''',blk,''': {',include_str,'}'], {'mdl2m_debug', 'filter_dialog_parameters_debug'});\n \n exclude_str = [''];\n for index = 1:length(force_exclude),\n if index ~= 1, exclude_str = [exclude_str, ', ']; end\n exclude_str = [exclude_str, '''', force_exclude{index}, ''''];\n end\n clog(['unnecessary parameters for block ''',blk,''': {',exclude_str,'}'], {'mdl2m_debug', 'filter_dialog_parameters_debug'});\n\nend %filter_dialog_parameters\n\n%add block generation logic \nfunction gen_blocks(varargin)\n defaults = {};\n blks = get_var('blks', 'defaults', defaults, varargin{:});\n fp = get_var('file', 'defaults', defaults, varargin{:});\n\n %generate functions for blocks that require it\n for index = 1:length(blks),\n blk = blks{index};\n name = get_param(blk, 'Name');\n bt = get_param(blk, 'BlockType'); %block type\n sls = get_param(blk, 'StaticLinkStatus'); %library block or not (and does not update out-of-date linked blocks)\n\n % need to generate logic for non-library blocks that are subsystems\n if (strcmp(sls, 'none') || strcmp(sls, 'implicit')) && strcmp(bt, 'SubSystem'),\n clog(['appending generation functions for ',blk],{'gen_blocks_debug','mdl2m_debug'}); \n blk2m(blk, 'file', fp); %append generation functions to same file\n else,\n %do nothing as don't need to generate this block\n end\n end %for\nend %gen_blocks\n\n%logic to generate lines for system \nfunction add_line(line, fp)\n \n %determine line parameters\n branches = get_line_parameters([], line);\n\n %sanity check\n if isempty(branches), \n srcport = line.SrcPort; srcblk = line.SrcBlock;\n \n clog(['Error determining parameters for line starting at ',get(srcblk,'Name'),'/',num2str(srcport)], {'error', 'mdl2m_debug', 'add_line_debug'});\n error(['Error determining parameters for line starting at ',get(srcblk,'Name'),'/',num2str(srcport)]);\n else,\n for branch_index = 1:length(branches),\n \n branch = branches(branch_index);\n\n srcblk = branch.SrcBlock; srcport = branch.SrcPort;\n destblk = branch.DstBlock; destport = branch.DstPort;\n points = branch.Points;\n\n% fprintf(fp, '\\t%% %s/%s -> %s/%s\\n', srcblk, srcport, destblk, destport);\n% fprintf(fp, '\\tadd_line(blk,%s);\\n',mat2str(points));\n fprintf(fp, '\\tadd_line(blk,''%s/%s'',''%s/%s'', ''autorouting'', ''on'');\\n', srcblk, srcport, destblk, destport);\n end %for\n end %if\nend %add_line\n\nfunction[params] = get_line_parameters(src, line)\n \n params = [];\n srcport = line.SrcPort; srcblk = get(line.SrcBlock,'Name');\n \n dstport = line.DstPort; dstblk = get(line.DstBlock,'Name'); \n points = line.Points;\n \n %if we have a source block then a line starts here\n if ~isempty(srcblk),\n clog(['line commencement at ',srcblk,'/',srcport,' found'], {'mdl2m_debug', 'get_line_parameters_debug'});\n %otherwise use passed in parameters\n else,\n if ~isempty(src),\n srcport = src.SrcPort; srcblk = src.SrcBlock;\n else,\n clog(['sanity error: empty source block and no src info passed in'], {'error', 'mdl2m_debug', 'get_line_parameters_debug'});\n error(['sanity error: empty source block and no src info passed in']);\n end\n end %if\n\n dst.SrcPort = srcport; dst.SrcBlock = srcblk;\n dst.DstPort = dstport; dst.DstBlock = dstblk; \n if ~isempty(src),\n dst.Points = [src.Points; points]; \n else\n dst.Points = points;\n end\n\n %if we have a destination then this line terminates\n if ~isempty(dstblk),\n params = [dst]; \n clog(['line termination at ',dstblk,'/',dstport,' found'], {'mdl2m_debug', 'get_line_parameters_debug'});\n return;\n %otherwise this line has one or more branches\n else,\n branches = line.Branch;\n clog([num2str(length(branches)), ' branches found'], {'mdl2m_debug', 'get_line_parameters_debug'});\n for branch_index = 1:length(branches),\n branch = branches(branch_index);\n branch_params = get_line_parameters(dst, branch);\n params = [params; branch_params];\n end %for\n end %if\nend %get_line_parameters\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% block generation functions %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%generates functions that will set up the mask etc of the block \nfunction blk2m(blk, varargin)\n defaults = { ...\n 'filename', [get_param(blk,'Name'),'_gen'], ... %filename for generator script\n 'mode', 'a', ... %mode to open file ('a'-append, 'w'-overwrite)\n };\n fn = get_var('filename', 'defaults', defaults, varargin{:});\n m = get_var('mode', 'defaults', defaults, varargin{:});\n fp = get_var('file', 'defaults', defaults, varargin{:});\n \n %%%%%%%%%%%%%\n % open file %\n %%%%%%%%%%%%%\n\n %open file if no file pointer\n if fp == NaN,\n ntc = 1; %remember that we need to close\n clog(['opening ',fn],'blk2m_debug');\n fp_init = fopen([fn,'.m'],m);\n if fp == -1,\n clog(['error opening ',fn, ' in mode ''',m,''''],{'mdl2m_debug', 'blk2m_debug', 'error'});\n return\n end %if\n else,\n ntc = 0;\n end %if\n\n name = get_param(blk, 'Name');\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % block generation function %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n clog(['block generation function for ',name],{'mdl2m_debug', 'blk2m_debug'}); \n blk_gen(blk, fp);\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % mask generation function %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n clog(['mask generation function for ',name],{'mdl2m_debug', 'blk2m_debug'}); \n mask_gen(blk, fp);\n\n %%%%%%%%%%%%%%%%%\n % init function %\n %%%%%%%%%%%%%%%%%\n \n clog(['init function for ',name],{'mdl2m_debug', 'blk2m_debug', 'error'}); \n mdl2m(blk, 'file', fp, 'subsystem', 'on'); %call generation logic to generate init \n\n %%%%%%%%%%%%%%\n % close file %\n %%%%%%%%%%%%%%\n\n if ntc == 1,\n result = fclose(fp);\n if result ~= 0, clog(['error closing file ',fn],{'blk2m_debug', 'mdl2m_debug', 'error'}); end \n % Make sure other's can overwrite so we can share mlib_devel working\n % copy between users.\n fileattrib([fn,'.m'], '+w');\n end %if\nend %blk2m\n\n%generate function that calls other functions to generate block\nfunction blk_gen(blk, file)\n\n name = get_param(blk, 'Name');\n\n %initialise block generator function \n clog(['adding block generation function for ',name],{'mdl2m_debug', 'blk_gen_debug'}); \n %setup function \n fprintf(file,'function %s_gen(blk)\\n',name); \n fprintf(file, '\\n'); \n\n fprintf(file, '\\t%s_mask(blk);\\n',name); %logic to generate the mask \n fprintf(file, '\\t%s_init(blk);\\n',name); %logic to generate the internal logic\n\n params = get_params(blk, {'MaskInitialization'});\n set_params(file, 'blk', params, 'no_empty');\n fprintf(file, '\\n'); \n\n %finalising\n clog(['finalising block generator function'],{'mdl2m_debug','blk_gen_debug'}); \n fprintf(file, 'end %% %s_gen\\n\\n',name);\n\nend %blk_gen\n\n%generate logic to generate block mask\nfunction mask_gen(blk, file)\n\n mask_params = ...\n { ...\n 'Mask', ... %is the block masked\n 'MaskSelfModifiable', ... %whether library blocks can modify themselves\n...%\t'MaskInitialization', ... %initialization commands\n 'MaskType', ... %library block or not\n 'MaskDescription', ... %description of block\n 'MaskHelp', ... %help for block\n 'MaskPromptString', ... %prompts for parameters\n 'MaskStyleString', ... %type of parameters\n 'MaskTabNameString', ... %tab names for parameters\n 'MaskCallbackString', ... %callback commands for parameters\n 'MaskEnableString', ... %whether parameters are enabled\n 'MaskVisibilityString', ... %whether parameters are visible\n 'MaskToolTipString', ... %tips for parameters\n 'MaskVariables', ... %variable names attached to parameters\n 'MaskValueString', ... %values attached to parameters\n\t'BackgroundColor', ... %background colour of block\n 'MaskDisplay', ... %appearance of block\n\t'Tag', ...\t\t %the block tag\n };\n\n params = get_params(blk, mask_params);\n\n if mod(length(params),2) ~= 0, \n clog(['parameters must be ''name'', value pairs'],{'mdl2m_debug','mask_gen_debug','error'});\n return;\n end\n\n blk_name = get_param(blk, 'Name');\n\n %initialise mask generator function \n clog(['adding mask function for ',blk_name],{'mask_gen_debug','mdl2m_debug'}); \n %setup function \n fprintf(file,'function %s_mask(blk)\\n',blk_name); \n fprintf(file, '\\n'); \n\n %set up mask parameters\n set_params(file, 'blk', params, 'no_empty');\n fprintf(file, '\\n'); \n\n %finalising\n clog(['finalising mask generation function'],{'mask_gen_debug', 'mdl2m_debug'}); \n fprintf(file, 'end %% %s_mask\\n\\n',blk_name);\nend %mask_gen\n\n%%%%%%%%%%%%%%%%%%%%\n% helper functions %\n%%%%%%%%%%%%%%%%%%%%\n\n%add logic to set up parameters\n%strategy can be 'all' or 'no_empty'\nfunction set_params(fp, target, params, strategy)\n\n if mod(length(params),2) ~= 0, \n clog(['parameters must be ''name'', value pairs'],{'error', 'set_params_debug', 'mdl2m_debug'});\n return;\n end\n\n init = 0;\n for index = 1:2:length(params),\n clog(['processing ',params{index}],{'set_params_debug', 'mdl2m_debug'}); \n value = params{index+1};\n name = params{index};\n if strcmp(strategy, 'all') || (~isempty(value) && strcmp(strategy, 'no_empty')), \n [value_s, result] = to_string(value);\n\n if (result ~= 0),\n clog(['error while converting ',name,' to string'],{'set_params_debug', 'mdl2m_debug', 'error'});\n return;\n end\n\n %start the function call if we have something\n if (init == 0), \n fprintf(fp, '\\tset_param(%s',target);\n init = 1;\n end\n \n fprintf(fp, ', ...\\n\\t\\t''%s'', sprintf(''%s'')', name, value_s);\n else,\n clog(['skipping ',name],{'set_params_debug', 'mdl2m_debug'});\n end\n end\n\n %close the function call if we started\n if (init == 1), fprintf(fp, ');\\n'); end\n\nend %set_params\n\n%determine values of all mask parameters we care about when generating a block\nfunction[params] = get_params(target, required_params)\n\n params = {};\n\n for param_index = 1:length(required_params),\n param = required_params{param_index};\n clog(['getting ',param],{'get_params_debug', 'mdl2m_debug'}); \n\n value = get_param(target, param);\n\n params = {params{:}, param, value};\n end %for\nend %get_params\n\n% converts items into strings that can be used to generate other strings\nfunction[output, result] = to_string(var)\n\n result = -1;\n output = '';\n if isempty(var),\n result = 0;\n return;\n end\n % if a cell array then iteratively convert \n if isa(var, 'cell'),\n [r,c] = size(var);\n output = '{';\n for row_index = 1:r,\n for col_index = 1:c,\n [sub, result] = to_string(var{row_index,col_index});\n if result == -1,\n return;\n end\n if c > 1, output = [output, ','];\n end\n end %col\n if r > 1, output = [output, ';'];\n end\n end %row\n output = [output,'}'];\n elseif isa(var, 'numeric'),\n output = ['',mat2str(var),''];\n result = 0;\n elseif isa(var, 'char'),\n var = regexprep(var, '''', ''''''); %make quotes double\n var = regexprep(var, '\\n', '\\\\n'); %escape new lines\n var = regexprep(var, '%', '%%'); %escape percentage symbols\n output = ['',var,''];\n result = 0;\n else\n clog(['don''t know how to convert variable of class ',class(var),' to string'], 'error');\n end\nend %to_string\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fir_tap_async_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fir_tap_async_init.m", "size": 6431, "source_encoding": "utf_8", "md5": "329f21d0e0b37dced1f66aa7235f550b", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% MeerKAT Radio Telescope Project %\n% www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (meerKAT) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction fir_tap_async_init(blk)\n clog('entering fir_tap_async_init', 'trace');\n varargin = make_varargin(blk);\n defaults = {};\n check_mask_type(blk, 'fir_tap_async');\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n clog('fir_tap_async_init post same_state', 'trace');\n munge_block(blk, varargin{:});\n% factor = get_var('factor','defaults', defaults, varargin{:});\n% mult_latency = get_var('mult_latency','defaults', defaults, varargin{:});\n coeff_bit_width = get_var('coeff_bit_width','defaults', defaults, varargin{:});\n% coeff_bin_pt = get_var('coeff_bin_pt','defaults', defaults, varargin{:});\n async_ops = strcmp('on', get_var('async','defaults', defaults, varargin{:}));\n double_blk = strcmp('on', get_var('dbl','defaults', defaults, varargin{:}));\n \n % hand off to the double script if this is a doubled-up FIR\n if double_blk,\n fir_dbl_tap_async_init(blk);\n return;\n end\n\n delete_lines(blk);\n\n % default state in library\n if coeff_bit_width == 0,\n clog('fir_tap_async_init saving library state', 'trace');\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); \n return; \n end\n\n % inputs\n reuse_block(blk, 'a', 'built-in/Inport', 'Port', '1', ...\n 'Position', '[205 68 235 82]');\n reuse_block(blk, 'b', 'built-in/Inport', 'Port', '2', ...\n 'Position', '[205 158 235 172]');\n if async_ops,\n reuse_block(blk, 'dv_in', 'built-in/Inport', 'Port', '3', ...\n 'Position', '[205 0 235 14]');\n end\n \n reuse_block(blk, 'Constant', 'xbsIndex_r4/Constant', ...\n 'const', 'factor', ...\n 'n_bits', 'coeff_bit_width', ...\n 'bin_pt', 'coeff_bin_pt', ...\n 'explicit_period', 'on', ...\n 'Position', '[25 36 150 64]');\n\n reuse_block(blk, 'Mult0', 'xbsIndex_r4/Mult', ...\n 'n_bits', '18', ...\n 'bin_pt', '17', ...\n 'latency', 'mult_latency', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'off', ...\n 'placement_style', 'Rectangular shape', ...\n 'Position', '[280 37 330 88]');\n\n reuse_block(blk, 'Mult1', 'xbsIndex_r4/Mult', ...\n 'n_bits', '18', ...\n 'bin_pt', '17', ...\n 'latency', 'mult_latency', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'off', ...\n 'placement_style', 'Rectangular shape', ...\n 'Position', '[280 127 330 178]');\n\n reuse_block(blk, 'Register0', 'xbsIndex_r4/Register', ...\n 'Position', '[410 86 455 134]');\n\n reuse_block(blk, 'Register1', 'xbsIndex_r4/Register', ...\n 'Position', '[410 181 455 229]');\n \n if async_ops,\n set_param([blk, '/Register0'], 'en', 'on');\n set_param([blk, '/Register1'], 'en', 'on');\n else\n set_param([blk, '/Register0'], 'en', 'off');\n set_param([blk, '/Register1'], 'en', 'off');\n end\n\n reuse_block(blk, 'a_out', 'built-in/Outport', ...\n 'Port', '1', ...\n 'Position', '[495 103 525 117]');\n\n reuse_block(blk, 'b_out', 'built-in/Outport', ...\n 'Port', '2', ...\n 'Position', '[495 198 525 212]');\n\n reuse_block(blk, 'real', 'built-in/Outport', ...\n 'Port', '3', ...\n 'Position', '[355 58 385 72]');\n\n reuse_block(blk, 'imag', 'built-in/Outport', ...\n 'Port', '4', ...\n 'Position', '[355 148 385 162]');\n\n if async_ops,\n add_line(blk, 'dv_in/1', 'Register0/2', 'autorouting', 'on');\n add_line(blk, 'dv_in/1', 'Register1/2', 'autorouting', 'on');\n end\n add_line(blk,'b/1','Mult1/2', 'autorouting', 'on');\n add_line(blk,'b/1','Register1/1', 'autorouting', 'on');\n add_line(blk,'a/1','Mult0/2', 'autorouting', 'on');\n add_line(blk,'a/1','Register0/1', 'autorouting', 'on');\n add_line(blk,'Constant/1','Mult1/1', 'autorouting', 'on');\n add_line(blk,'Constant/1','Mult0/1', 'autorouting', 'on');\n add_line(blk,'Mult0/1','real/1', 'autorouting', 'on');\n add_line(blk,'Mult1/1','imag/1', 'autorouting', 'on');\n add_line(blk,'Register0/1','a_out/1', 'autorouting', 'on');\n add_line(blk,'Register1/1','b_out/1', 'autorouting', 'on');\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:});\n clog('exiting fir_tap_async_init', 'trace');\nend % fir_tap_async_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fir_dbl_col_async_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fir_dbl_col_async_init.m", "size": 15223, "source_encoding": "utf_8", "md5": "8490f221752a9908a2c844ae5827d275", "text": "% fir_dbl_col_init(blk, varargin)\r\n%\r\n% blk = The block to initialize.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% n_inputs = The number of parallel input samples.\r\n% coeff = The FIR coefficients, top-to-bottom.\r\n% add_latency = The latency of adders.\r\n% mult_latency = The latency of multipliers.\r\n% coeff_bit_width = The number of bits used for coefficients\r\n% coeff_bin_pt = The number of fractional bits in the coefficients\r\n% first_stage_hdl = Whether to implement the first stage in adder trees\r\n% as behavioral HDL so that adders are absorbed into DSP slices used for\r\n% multipliers where this is possible.\r\n% adder_imp = adder implementation (Fabric, behavioral HDL, DSP48)\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction fir_dbl_col_async_init(blk, varargin)\r\nclog('entering fir_dbl_col_async_init', 'trace');\r\n\r\nshowname = 'on';\r\nsizey_goto = 15;\r\n \r\n% varargin = make_varargin(blk);\r\n% \r\n% % declare any default values for arguments you might like.\r\n% defaults = {'n_inputs', 0, 'coeff', 0.1, 'add_latency', 2, ...\r\n% 'mult_latency', 3, 'coeff_bit_width', 25, 'coeff_bin_pt', 24, ...\r\n% 'first_stage_hdl', 'off', 'adder_imp', 'Fabric', 'async', 'off', ...\r\n% 'bus_input', 'off', 'dbl', 'off', 'input_width', 16, ...\r\n% 'input_bp', 0, 'input_type', 'Unsigned'};\r\n% \r\n% check_mask_type(blk, 'fir_col_async');\r\n% if same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\n% clog('fir_dbl_col_async_init post same_state', 'trace');\r\n% munge_block(blk, varargin{:});\r\n\r\n% n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\n% coeff = get_var('coeff', 'defaults', defaults, varargin{:});\r\n% add_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\n% mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\n% coeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\r\n% coeff_bin_pt = get_var('coeff_bin_pt', 'defaults', defaults, varargin{:});\r\n% first_stage_hdl = get_var('first_stage_hdl', 'defaults', defaults, varargin{:});\r\n% adder_imp = get_var('adder_imp', 'defaults', defaults, varargin{:});\r\n% async_ops = strcmp('on', get_var('async', 'defaults', defaults, varargin{:}));\r\n% bus_input = strcmp('on', get_var('bus_input', 'defaults', defaults, varargin{:}));\r\n% double_blk = strcmp('on', get_var('dbl', 'defaults', defaults, varargin{:}));\r\n\r\nn_inputs = get_var('n_inputs', varargin{:});\r\ncoeff = get_var('coeff', varargin{:});\r\nadd_latency = get_var('add_latency', varargin{:});\r\nmult_latency = get_var('mult_latency', varargin{:});\r\ncoeff_bit_width = get_var('coeff_bit_width', varargin{:});\r\ncoeff_bin_pt = get_var('coeff_bin_pt', varargin{:});\r\nfirst_stage_hdl = get_var('first_stage_hdl', varargin{:});\r\nadder_imp = get_var('adder_imp', varargin{:});\r\nasync_ops = strcmp('on', get_var('async', varargin{:}));\r\nbus_input = strcmp('on', get_var('bus_input', varargin{:}));\r\ndouble_blk = strcmp('on', get_var('dbl', varargin{:}));\r\n\r\n% async_ops = false;\r\n% bus_input = false;\r\n% double_blk = false;\r\n\r\n% this should be a double block\r\nif ~double_blk,\r\n error('This script should only be called on a doubled-up tap block.');\r\nend\r\n\r\nif bus_input,\r\n input_width = get_var('input_width',varargin{:});\r\n input_bp = get_var('input_bp',varargin{:});\r\n input_type = get_var('input_type',varargin{:});\r\n if strcmp(input_type, 'Signed'),\r\n input_type_num = 1;\r\n else\r\n input_type_num = 0;\r\n end\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\n% % default library state\r\n% if n_inputs == 0,\r\n% clog('fir_dbl_col_async_init no inputs', 'trace');\r\n% clean_blocks(blk);\r\n% save_state(blk, 'defaults', defaults, varargin{:});\r\n% clog('exiting fir_dbl_col_async_init', 'trace');\r\n% return;\r\n% end\r\n\r\nif length(coeff) ~= n_inputs,\r\n clog('number of coefficients must be the same as the number of inputs', {'fir_dbl_col_async_init_debug', 'error'});\r\n error('number of coefficients must be the same as the number of inputs');\r\nend\r\n\r\n% draw the inputs differently depending on whether we're taking a bus input or not\r\nif bus_input,\r\n reuse_block(blk, 'dbus_in', 'built-in/inport', 'Position', [0 30 30 46], 'Port', '1');\r\n reuse_block(blk, 'inbus', 'casper_library_flow_control/bus_expand', ...\r\n 'Position', [80 30 150 30+(n_inputs*sizey_goto*3)]);\r\n set_param([blk, '/inbus'], ...\r\n 'mode', 'divisions of equal size', ...\r\n 'outputNum', num2str(2*n_inputs), ...\r\n 'outputWidth', num2str(input_width), ...\r\n 'outputBinaryPt', num2str(input_bp), ...\r\n 'outputArithmeticType', num2str(input_type_num), ...\r\n 'show_format', 'off', ...\r\n 'outputToWorkspace', 'off');\r\n add_line(blk, 'dbus_in/1', 'inbus/1');\r\n reuse_block(blk, 'dbus_back_in', 'built-in/inport', 'Position', [0 500 30 516], 'Port', '2');\r\n reuse_block(blk, 'inbus_back', 'casper_library_flow_control/bus_expand', ...\r\n 'Position', [80 500 150 500+(n_inputs*sizey_goto*3)]);\r\n set_param([blk, '/inbus_back'], ...\r\n 'mode', 'divisions of equal size', ...\r\n 'outputNum', num2str(2*n_inputs), ...\r\n 'outputWidth', num2str(input_width), ...\r\n 'outputBinaryPt', num2str(input_bp), ...\r\n 'outputArithmeticType', num2str(input_type_num), ...\r\n 'show_format', 'off', ...\r\n 'outputToWorkspace', 'off');\r\n add_line(blk, 'dbus_back_in/1', 'inbus_back/1');\r\n port_num = 3;\r\nelse\r\n port_num = 1;\r\n for ctr = 1 : n_inputs,\r\n ctrstr = num2str(ctr);\r\n reuse_block(blk, ['real', ctrstr], 'built-in/inport', ...\r\n 'Position', [30 ctr*80 60 15+80*ctr], ...\r\n 'Port', num2str(port_num));\r\n reuse_block(blk, ['imag', ctrstr], 'built-in/inport', ...\r\n 'Position', [30 ctr*80+30 60 45+80*ctr], ...\r\n 'Port', num2str(port_num+1));\r\n port_num = port_num + 2;\r\n end\r\n offset = n_inputs*50*2;\r\n for ctr = 1 : n_inputs,\r\n ctrstr = num2str(ctr);\r\n reuse_block(blk, ['real_back', ctrstr], 'built-in/inport', ...\r\n 'Position', [30 offset+ctr*80 60 offset+15+80*ctr], ...\r\n 'Port', num2str(port_num));\r\n reuse_block(blk, ['imag_back', ctrstr], 'built-in/inport', ...\r\n 'Position', [30 offset+ctr*80+30 60 offset+45+80*ctr], ...\r\n 'Port', num2str(port_num+1));\r\n port_num = port_num + 2;\r\n end\r\nend\r\nif async_ops,\r\n reuse_block(blk, 'dv', 'built-in/inport', 'Position', [0 0 30 16]);\r\n set_param([blk, '/dv'], 'Port', num2str(port_num));\r\n reuse_block(blk, 'dv_in', 'built-in/goto', ...\r\n 'GotoTag', 'dv_in', 'showname', showname, ...\r\n 'Position', [50 0 120 16]);\r\n add_line(blk, 'dv/1', 'dv_in/1');\r\nend\r\n\r\n% tap blocks and connections to the inputs\r\nfor ctr = 1 : n_inputs,\r\n ctrstr = num2str(ctr);\r\n blkname = ['fir_tap', ctrstr];\r\n full_blkname = [blk, '/', blkname];\r\n tap_ypos = ctr*160 - 160;\r\n reuse_block(blk, blkname, 'casper_library_downconverter/fir_tap_async', ...\r\n 'Position', [400 tap_ypos 470 tap_ypos+120], ...\r\n 'add_latency', num2str(add_latency), ...\r\n 'mult_latency', num2str(mult_latency), ...\r\n 'factor', num2str(coeff(ctr)), ...\r\n 'coeff_bit_width', num2str(coeff_bit_width), ...\r\n 'coeff_bin_pt', num2str(coeff_bin_pt), 'dbl', 'on');\r\n if async_ops,\r\n set_param(full_blkname, 'async', 'on');\r\n else\r\n set_param(full_blkname, 'async', 'off');\r\n end\r\n % connection to inputs\r\n if async_ops,\r\n reuse_block(blk, ['dv_in', ctrstr], 'built-in/from', 'GotoTag', 'dv_in', 'showname', showname, 'Position', [280 tap_ypos+104 360 tap_ypos+120]);\r\n if double_blk,\r\n add_line(blk, ['dv_in', ctrstr, '/1'], [blkname, '/5']);\r\n else\r\n add_line(blk, ['dv_in', ctrstr, '/1'], [blkname, '/3']);\r\n end\r\n end\r\n if bus_input,\r\n pos = ((ctr-1)*2)+1;\r\n add_line(blk, ['inbus/', num2str(pos+0)], [blkname, '/1']);\r\n add_line(blk, ['inbus/', num2str(pos+1)], [blkname, '/2']);\r\n add_line(blk, ['inbus_back/', num2str(n_inputs*2-pos)], [blkname, '/3']);\r\n add_line(blk, ['inbus_back/', num2str(n_inputs*2-pos+1)], [blkname, '/4']);\r\n else\r\n add_line(blk, ['real', ctrstr, '/1'], [blkname, '/1']);\r\n add_line(blk, ['imag', ctrstr, '/1'], [blkname, '/2']);\r\n add_line(blk, ['real_back', num2str(n_inputs-ctr+1), '/1'], [blkname, '/3']);\r\n add_line(blk, ['imag_back', num2str(n_inputs-ctr+1), '/1'], [blkname, '/4']);\r\n end\r\nend\r\n\r\n% output ports\r\nif bus_input,\r\n reuse_block(blk, 'outbus', 'casper_library_flow_control/bus_create', ...\r\n 'inputNum', num2str(n_inputs*2), ...\r\n 'Position', [600 30 650 30+(n_inputs*sizey_goto*3)]);\r\n reuse_block(blk, 'dbus_out', 'built-in/outport', 'Position', [700 30 730 46], 'Port', '1');\r\n add_line(blk, 'outbus/1', 'dbus_out/1');\r\n reuse_block(blk, 'outbus_back', 'casper_library_flow_control/bus_create', ...\r\n 'inputNum', num2str(n_inputs*2), ...\r\n 'Position', [600 500 650 500+(n_inputs*sizey_goto*3)]);\r\n reuse_block(blk, 'dbus_back_out', 'built-in/outport', 'Position', [700 500 730 516], 'Port', '2');\r\n add_line(blk, 'outbus_back/1', 'dbus_back_out/1');\r\n for ctr = 1 : n_inputs,\r\n ctrstr = num2str(ctr);\r\n tapname = ['fir_tap', ctrstr];\r\n pos = ((ctr-1)*2)+1;\r\n add_line(blk, [tapname, '/1'], ['outbus/', num2str(pos+0)]);\r\n add_line(blk, [tapname, '/2'], ['outbus/', num2str(pos+1)]);\r\n add_line(blk, [tapname, '/3'], ['outbus_back/', num2str(n_inputs*2-pos)]);\r\n add_line(blk, [tapname, '/4'], ['outbus_back/', num2str(n_inputs*2-pos+1)]);\r\n end\r\nelse\r\n for ctr = 1 : n_inputs,\r\n ctrstr = num2str(ctr);\r\n reuse_block(blk, ['real_out', ctrstr], 'built-in/outport', 'Position', [550 ctr*80 580 15+80*ctr], 'Port', num2str(ctr*2-1));\r\n reuse_block(blk, ['imag_out', ctrstr], 'built-in/outport', 'Position', [550 ctr*80+30 580 45+80*ctr], 'Port', num2str(ctr*2));\r\n end\r\n offset = n_inputs*50*2;\r\n for ctr = 1 : n_inputs,\r\n ctrstr = num2str(ctr);\r\n reuse_block(blk, ['real_back_out', ctrstr], 'built-in/outport', 'Position', [550 offset+ctr*80 580 offset+15+80*ctr], 'Port', num2str(ctr*2-1+n_inputs*2));\r\n reuse_block(blk, ['imag_back_out', ctrstr], 'built-in/outport', 'Position', [550 offset+ctr*80+30 580 offset+45+80*ctr], 'Port', num2str(ctr*2+n_inputs*2));\r\n end\r\n for ctr = 1 : n_inputs,\r\n ctrstr = num2str(ctr);\r\n blkname = ['fir_tap', ctrstr];\r\n add_line(blk, [blkname, '/1'], ['real_out', ctrstr,'/1']);\r\n add_line(blk, [blkname, '/2'], ['imag_out', ctrstr,'/1']);\r\n add_line(blk, [blkname, '/3'], ['real_back_out', num2str(n_inputs+1-ctr),'/1']);\r\n add_line(blk, [blkname, '/4'], ['imag_back_out', num2str(n_inputs+1-ctr),'/1']);\r\n end\r\nend\r\n\r\n% the output sum blocks\r\nif bus_input,\r\n reuse_block(blk, 'real_sum', 'built-in/outport', 'Position', [900 100+20*n_inputs 930 116+20*n_inputs], 'Port', '3');\r\n reuse_block(blk, 'imag_sum', 'built-in/outport', 'Position', [900 200+20*n_inputs 930 216+20*n_inputs], 'Port', '4');\r\nelse\r\n reuse_block(blk, 'real_sum', 'built-in/outport', 'Position', [900 100+20*n_inputs 930 116+20*n_inputs], 'Port', num2str(n_inputs*4+1));\r\n reuse_block(blk, 'imag_sum', 'built-in/outport', 'Position', [900 200+20*n_inputs 930 216+20*n_inputs], 'Port', num2str(n_inputs*4+2));\r\nend\r\n\r\n% the adder trees\r\nif n_inputs > 1,\r\n reuse_block(blk, 'adder_tree1', 'casper_library_misc/adder_tree', ...\r\n 'Position', [800 100 850 100+20*n_inputs], 'n_inputs', num2str(n_inputs),...\r\n 'latency', num2str(add_latency), 'first_stage_hdl', first_stage_hdl, 'adder_imp', adder_imp);\r\n reuse_block(blk, 'adder_tree2', 'casper_library_misc/adder_tree', ...\r\n 'Position', [800 200+20*n_inputs 850 200+20*n_inputs+20*n_inputs], 'n_inputs', num2str(n_inputs),...\r\n 'latency', num2str(add_latency), 'first_stage_hdl', first_stage_hdl, 'adder_imp', adder_imp);\r\n reuse_block(blk, 'c1', 'xbsIndex_r4/Constant', ...\r\n 'explicit_period', 'on', 'Position', [750 100 780 110]);\r\n reuse_block(blk, 'c2', 'xbsIndex_r4/Constant', ...\r\n 'explicit_period', 'on', 'Position', [750 200+20*n_inputs 780 210+20*n_inputs]);\r\n reuse_block(blk, 'term1','built-in/Terminator', 'Position', [1000 100 1015 115]);\t\r\n add_line(blk, 'adder_tree1/1', 'term1/1');\r\n reuse_block(blk, 'term2','built-in/Terminator', 'Position', [1000 200+20*n_inputs 1015 215+20*n_inputs]);\t\r\n add_line(blk, 'adder_tree2/1', 'term2/1');\r\n add_line(blk, 'c1/1', 'adder_tree1/1');\r\n add_line(blk, 'c2/1', 'adder_tree2/1');\r\n add_line(blk,'adder_tree1/2','real_sum/1');\r\n add_line(blk,'adder_tree2/2','imag_sum/1');\r\n for ctr=1:n_inputs,\r\n add_line(blk, ['fir_tap', num2str(ctr), '/5'], ['adder_tree1/', num2str(ctr+1)]);\r\n add_line(blk, ['fir_tap', num2str(ctr), '/6'], ['adder_tree2/', num2str(ctr+1)]);\r\n end\r\nelse\r\n add_line(blk, 'fir_tap1/5', 'real_sum/1');\r\n add_line(blk, 'fir_tap1/6', 'imag_sum/1');\r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\n% clean_blocks(blk);\r\n% save_state(blk, 'defaults', defaults, varargin{:});\r\n\r\nclog('exiting fir_dbl_col_async_init', 'trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_fir_real_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_fir_real_init.m", "size": 17083, "source_encoding": "utf_8", "md5": "081d3ad0b9f353455f4b0251083d0c83", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction pfb_fir_real_init(blk, varargin)\r\n% Initialize and configure the Real Polyphase Filter Bank.\r\n%\r\n% pfb_fir_real_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% PFBSize = The size of the PFB\r\n% TotalTaps = Total number of taps in the PFB\r\n% WindowType = The type of windowing function to use.\r\n% n_inputs = The number of parallel inputs\r\n% MakeBiplex = Double up the PFB to feed a biplex FFT\r\n% BitWidthIn = Input Bitwidth\r\n% BitWidthOut = Output Bitwidth (0 == as needed)\r\n% CoeffBitWidth = Bitwidth of Coefficients.\r\n% CoeffDistMem = Implement coefficients in distributed memory\r\n% add_latency = Latency through each adder.\r\n% mult_latency = Latency through each multiplier\r\n% bram_latency = Latency through each BRAM.\r\n% conv_latency = Latency through the convert (cast) blocks. Essential if you're doing saturate/rouding logic.\r\n% quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round\r\n% (unbiased: Even Values)'\r\n% fwidth = Scaling of the width of each PFB channel\r\n% coeffs_share = Both polarizations will share coefficients.\r\n\r\nclog('entering pfb_fir_real_init','trace');\r\n% Declare any default values for arguments you might like.\r\ndefaults = {'PFBSize', 5, 'TotalTaps', 2, ...\r\n 'WindowType', 'hamming', 'n_inputs', 1, 'MakeBiplex', 'off', ...\r\n 'BitWidthIn', 8, 'BitWidthOut', 0, 'CoeffBitWidth', 18, ...\r\n 'CoeffDistMem', 'off', 'add_latency', 1, 'mult_latency', 2, ...\r\n 'bram_latency', 2, 'conv_latency', 1, ...\r\n 'quantization', 'Round (unbiased: +/- Inf)', ...\r\n 'fwidth', 1, 'mult_spec', [2 2], ...\r\n 'adder_folding', 'on', 'adder_imp', 'Fabric', ...\r\n 'coeffs_share', 'off', 'coeffs_fold', 'off'};\r\n\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('pfb_fir_real_init post same_state','trace');\r\ncheck_mask_type(blk, 'pfb_fir_real');\r\nmunge_block(blk, varargin{:});\r\n\r\nPFBSize = get_var('PFBSize', 'defaults', defaults, varargin{:});\r\nTotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:});\r\nWindowType = get_var('WindowType', 'defaults', defaults, varargin{:});\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\nMakeBiplex = get_var('MakeBiplex', 'defaults', defaults, varargin{:});\r\nBitWidthIn = get_var('BitWidthIn', 'defaults', defaults, varargin{:});\r\nBitWidthOut = get_var('BitWidthOut', 'defaults', defaults, varargin{:});\r\nCoeffBitWidth = get_var('CoeffBitWidth', 'defaults', defaults, varargin{:});\r\nCoeffDistMem = get_var('CoeffDistMem', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nfan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\nconv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\nfwidth = get_var('fwidth', 'defaults', defaults, varargin{:});\r\nmult_spec = get_var('mult_spec', 'defaults', defaults, varargin{:});\r\nadder_folding = get_var('adder_folding', 'defaults', defaults, varargin{:});\r\nadder_imp = get_var('adder_imp', 'defaults', defaults, varargin{:});\r\ncoeffs_share = get_var('coeffs_share', 'defaults', defaults, varargin{:});\r\n\r\n% check the multiplier specifications first off\r\ntap_multipliers = multiplier_specification(mult_spec, TotalTaps, blk);\r\n\r\n% share coeffs in a 2-pol setup?\r\npols = 1;\r\nshare_coefficients = false;\r\nif strcmp(MakeBiplex, 'on'),\r\n pols = 2;\r\n if strcmp(coeffs_share, 'on')\r\n share_coefficients = true;\r\n end\r\nend\r\n\r\n% Compute the maximum gain through all of the 2^PFBSize sub-filters. This is\r\n% used to determine how much bit growth is really needed. The gain of each\r\n% filter is the sum of the absolute values of its coefficients. The maximum of\r\n% these gains sets the upper bound on bit growth through the pfb_fir. The\r\n% products, partial sums, and final sum throughout the pfb_fir (including the\r\n% adder tree) need not accomodate any more bit growth than the absolute maximum\r\n% gain requires, provided that any \"overflow\" is ignored (i.e. set to \"Wrap\").\r\n% This works thanks to the wonders of modulo math. Note that the \"gain\" for\r\n% typical signals will be different (less) than the absolute maximum gain of\r\n% each filter. For Gaussian noise, the gain of a filter is the square root of\r\n% the sum of the squares of the coefficients (aka root-sum-squares or RSS).\r\n\r\n% Get all coefficients of the pfb_fir in one vector (by passing -1 for a)\r\nall_coeffs = pfb_coeff_gen_calc(PFBSize, TotalTaps, WindowType, n_inputs, 0, fwidth, -1, false);\r\n% Rearrange into matrix with 2^PFBSize rows and TotalTaps columns.\r\n% Each row contains coefficients for one sub-filter.\r\nall_filters = reshape(all_coeffs, 2^PFBSize, TotalTaps);\r\n% Compute max gain (make sure it is at least 1).\r\n% NB: sum rows, not columns!\r\nmax_gain = max(sum(abs(all_filters), 2));\r\nif max_gain < 1; max_gain = 1; end\r\n% Compute bit growth\r\nbit_growth = nextpow2(max_gain);\r\n% Compute adder output width and binary point. We know that the adders in the\r\n% adder tree need to have (bit_growth+1) non-fractional bits to accommodate the\r\n% maximum gain. The products from the taps will have\r\n% (BitWidthIn+CoeffBitWidth-2) fractional bits. We will preserve them through\r\n% the adder tree.\r\nadder_bin_pt_out = BitWidthIn+CoeffBitWidth-2;\r\nadder_n_bits_out = bit_growth + 1 + adder_bin_pt_out;\r\n\r\n% If BitWidthOut is 0, set it to accomodate bit growth in the\r\n% non-fractional part and full-precision of the fractional part.\r\nif BitWidthOut == 0\r\n BitWidthOut = adder_n_bits_out;\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\n% Add ports\r\nclog('adding inports and outports','pfb_fir_real_init_debug');\r\nportnum = 1;\r\nreuse_block(blk, 'sync', 'built-in/inport', ...\r\n 'Position', [0 50 30 50+15], 'Port', num2str(portnum));\r\nreuse_block(blk, 'sync_out', 'built-in/outport', ...\r\n 'Position', [150*(TotalTaps+5) 50*portnum*TotalTaps 150*(TotalTaps+5)+30 50*portnum*TotalTaps+15], 'Port', num2str(portnum));\r\nfor p=1:pols,\r\n for n=1:2^n_inputs,\r\n portnum = portnum + 1; % Skip one to allow sync & sync_out to be 1\r\n in_name = ['pol',tostring(p),'_in',tostring(n)];\r\n out_name = ['pol',tostring(p),'_out',tostring(n)];\r\n reuse_block(blk, in_name, 'built-in/inport', ...\r\n 'Position', [0 50*portnum*TotalTaps 30 50*portnum*TotalTaps+15], 'Port', tostring(portnum));\r\n reuse_block(blk, out_name, 'built-in/outport', ...\r\n 'Position', [150*(TotalTaps+5) 50*portnum*TotalTaps 150*(TotalTaps+5)+30 50*portnum*TotalTaps+15], 'Port', tostring(portnum));\r\n end\r\nend\r\n\r\n% Add blocks\r\nportnum = 0;\r\nfor p=1:pols,\r\n for n=1:2^n_inputs,\r\n portnum = portnum + 1;\r\n in_name = ['pol',num2str(p),'_in',num2str(n)];\r\n \r\n % add the coefficient generators\r\n if (p == 2) && (share_coefficients == true)\r\n blk_name = [in_name,'_delay'];\r\n reuse_block(blk, blk_name, 'xbsIndex_r4/Delay', ...\r\n 'latency', 'bram_latency+1+fan_latency', 'Position', [150 50*portnum*TotalTaps 150+100 50*portnum*TotalTaps+30]);\r\n add_line(blk, [in_name,'/1'], [blk_name,'/1']);\r\n else\r\n blk_name = [in_name,'_coeffs'];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/pfb_coeff_gen', ...\r\n 'nput', num2str(n-1), 'CoeffDistMem', CoeffDistMem, 'Position', [150 50*portnum*TotalTaps 150+100 50*portnum*TotalTaps+30]);\r\n propagate_vars([blk,'/',blk_name], 'defaults', defaults, varargin{:});\r\n add_line(blk, [in_name,'/1'], [blk_name,'/1']);\r\n add_line(blk, 'sync/1', [blk_name,'/2']); \r\n end\r\n \r\n clog(['adding taps for pol ', num2str(p),' input ', num2str(n)],'pfb_fir_real_init_debug');\r\n for t = 1:TotalTaps,\r\n % first tap\r\n if t==1,\r\n blk_name = [in_name,'_first_tap'];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/first_tap_real', ...\r\n 'use_hdl', tap_multipliers(t).use_hdl, 'use_embedded', tap_multipliers(t).use_embedded, ...\r\n 'Position', [150*(t+1) 50*portnum*TotalTaps 150*(t+1)+100 50*portnum*TotalTaps+30]);\r\n propagate_vars([blk, '/', blk_name],'defaults', defaults, varargin{:});\r\n if (p == 2) && (share_coefficients == true)\r\n src_block = [strrep(in_name,'pol2','pol1'),'_coeffs'];\r\n data_source = [in_name,'_delay/1'];\r\n else\r\n src_block = [in_name,'_coeffs'];\r\n data_source = [src_block,'/1'];\r\n end\r\n add_line(blk, data_source, [blk_name,'/1']);\r\n add_line(blk, 'pol1_in1_coeffs/2', [blk_name,'/2']);\r\n add_line(blk, [src_block,'/3'], [blk_name,'/3']);\r\n % last tap\r\n elseif t==TotalTaps,\r\n blk_name = [in_name,'_last_tap'];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/last_tap_real', ...\r\n 'use_hdl', tap_multipliers(t).use_hdl, 'use_embedded', tap_multipliers(t).use_embedded, ...\r\n 'Position', [150*(t+1) 50*portnum*TotalTaps 150*(t+1)+100 50*portnum*TotalTaps+30]);\r\n propagate_vars([blk, '/', blk_name],'defaults', defaults, varargin{:});\r\n % intermediary taps\r\n else\r\n blk_name = [in_name,'_tap',tostring(t)];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/tap_real', ...\r\n 'use_hdl', tap_multipliers(t).use_hdl, 'use_embedded', tap_multipliers(t).use_embedded, ...\r\n 'bram_latency', tostring(bram_latency), ...\r\n 'mult_latency', tostring(mult_latency), ...\r\n 'data_width', tostring(BitWidthIn), ...\r\n 'coeff_width', tostring(CoeffBitWidth), ...\r\n 'coeff_frac_width', tostring(CoeffBitWidth-1), ...\r\n 'delay', tostring(2^(PFBSize-n_inputs)), ...\r\n 'Position', [150*(t+1) 50*portnum*TotalTaps 150*(t+1)+100 50*portnum*TotalTaps+30]);\r\n end\r\n end\r\n\r\n % add adder tree\r\n clog(['adder tree, scale and convert blocks for pol ',num2str(p),' input ',num2str(n)],'pfb_fir_real_init_debug');\r\n reuse_block(blk, ['adder_', tostring(p), '_' ,tostring(n)], 'casper_library_misc/adder_tree', ...\r\n 'n_inputs', tostring(TotalTaps), 'latency', tostring(add_latency), ...\r\n 'first_stage_hdl', adder_folding, 'adder_imp', adder_imp, ...\r\n 'Position', [150*(TotalTaps+2) 50*portnum*TotalTaps 150*(TotalTaps+2)+100 50*(portnum+1)*TotalTaps-20]);\r\n\r\n % Update adder blocks in the adder tree using our knowledge of maximum\r\n % bit growth.\r\n adders = find_system([blk, '/adder_', tostring(p), '_' ,tostring(n)], ...\r\n 'LookUnderMasks','all', 'FollowLinks','on', ...\r\n 'SearchDepth',1, 'RegExp','on', 'Name','^addr');\r\n for k=1:length(adders)\r\n set_param(adders{k}, ...\r\n 'precision', 'User Defined', ...\r\n 'arith_type', 'Signed (2''s comp)', ...\r\n 'n_bits', tostring(adder_n_bits_out), ...\r\n 'bin_pt', tostring(adder_bin_pt_out), ...\r\n 'quantization', 'Truncate', ...\r\n 'overflow', 'Wrap');\r\n end\r\n\r\n % add shift, convert blocks\r\n\r\n % Adder tree output has bit_growth more non-fractional bits than\r\n % BitWidthIn, but we want to keep the same number of non-fractional\r\n % bits, so we must scale by 2^(-bit_growth).\r\n scale_factor = -bit_growth;\r\n reuse_block(blk, ['scale_',tostring(p),'_',tostring(n)], 'xbsIndex_r4/Scale', ...\r\n 'scale_factor', tostring(scale_factor), ...\r\n 'Position', [150*(TotalTaps+3) 50*(portnum+1)*TotalTaps-50 150*(TotalTaps+3)+30 50*(portnum+1)*TotalTaps-25]);\r\n % Because we have handled bit growth for maximum gain, there can be no\r\n % overflow so it can be set to \"Wrap\" to avoid unnecessary logic. If\r\n % BitWidthOut is greater than adder_bin_pt_out, set quantization to\r\n % \"Truncate\" since there is no need to quantize.\r\n if BitWidthOut > adder_bin_pt_out\r\n quantization = 'Truncate';\r\n end\r\n reuse_block(blk, ['convert_', tostring(p),'_', tostring(n)], 'xbsIndex_r4/Convert', ...\r\n 'arith_type', 'Signed (2''s comp)', 'n_bits', tostring(BitWidthOut), ...\r\n 'bin_pt', tostring(BitWidthOut-1), 'quantization', quantization, ...\r\n 'overflow', 'Wrap', 'latency', tostring(add_latency), ...\r\n 'latency',tostring(conv_latency), 'pipeline', 'on', ...\r\n 'Position', [150*(TotalTaps+3)+60 50*(portnum+1)*TotalTaps-50 150*(TotalTaps+3)+90 50*(portnum+1)*TotalTaps-25]);\r\n end\r\nend\r\n\r\nclog('joining in ports to blocks','pfb_fir_real_init_debug');\r\nfor p=1:pols,\r\n for n=1:2^n_inputs,\r\n out_name = ['pol',tostring(p),'_out',tostring(n)];\r\n adder_name = ['adder_',tostring(p),'_',tostring(n)];\r\n convert_name = ['convert_',tostring(p), '_',tostring(n)];\r\n scale_name = ['scale_',tostring(p), '_',tostring(n)];\r\n\r\n % sync gets a delay before it is output\r\n if n==1 && p==1,\r\n reuse_block(blk, 'delay1', 'xbsIndex_r4/Delay', ...\r\n 'latency', tostring(conv_latency), ...\r\n 'Position', [150*(TotalTaps+3)+60 50 150*(TotalTaps+3)+90 80]);\r\n add_line(blk, [adder_name,'/1'], 'delay1/1');\r\n add_line(blk, 'delay1/1', 'sync_out/1');\r\n end\r\n\r\n add_line(blk, [adder_name,'/2'], [scale_name,'/1']);\r\n add_line(blk, [scale_name,'/1'], [convert_name,'/1']);\r\n add_line(blk, [convert_name,'/1'], [out_name,'/1']);\r\n end\r\nend\r\n\r\n% add other lines\r\nclog('joining blocks to outports','pfb_fir_real_init_debug');\r\nfor p=1:pols,\r\n for n=1:2^n_inputs,\r\n adder_name = ['adder_',tostring(p),'_',tostring(n)];\r\n for t=2:TotalTaps,\r\n blk_name = ['pol',tostring(p),'_in',tostring(n),'_tap',tostring(t)];\r\n\r\n if t == TotalTaps,\r\n blk_name = ['pol',tostring(p),'_in',tostring(n),'_last_tap'];\r\n add_line(blk, [blk_name,'/2'], [adder_name,'/1']);\r\n add_line(blk, [blk_name,'/1'], [adder_name,'/',tostring(t+1)]);\r\n end\r\n\r\n if t==2,\r\n prev_blk_name = ['pol',tostring(p),'_in',tostring(n),'_first_tap'];\r\n else\r\n prev_blk_name = ['pol',tostring(p),'_in',tostring(n),'_tap',tostring(t-1)];\r\n end\r\n\r\n for port=1:3, add_line(blk, [prev_blk_name,'/',tostring(port)], [blk_name,'/',tostring(port)]);\r\n end\r\n add_line (blk, [prev_blk_name,'/4'],[adder_name,'/',tostring(t)]);\r\n end\r\n end\r\nend\r\n\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('taps=%d, add_latency=%d', TotalTaps, add_latency);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\nclog('exiting pfb_fir_real_init','trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "lo_osc_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/lo_osc_init.m", "size": 3905, "source_encoding": "utf_8", "md5": "b45be18480995fe17cc30e48cdf4c94e", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction lo_osc_init(blk,varargin)\r\n\r\ndefaults = {};\r\ncheck_mask_type(blk, 'lo_osc');\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nmunge_block(blk, varargin{:});\r\n\r\nn_bits = get_var('n_bits','defaults', defaults, varargin{:});\r\ncounter_width = get_var('counter_width','defaults', defaults, varargin{:});\r\ncounter_start = get_var('counter_start','defaults', defaults, varargin{:});\r\ncounter_step = get_var('counter_step','defaults', defaults, varargin{:});\r\nlatency = get_var('latency','defaults', defaults, varargin{:});\r\n\r\ndelete_lines(blk);\r\n\r\n%default state in library\r\nif n_bits == 0,\r\n clean_blocks(blk);\r\n save_state(blk, 'defaults', defaults, varargin{:}); \r\n return; \r\nend\r\n\r\nreuse_block(blk, 'sync', 'built-in/Inport', ...\r\n 'Port', '1', ...\r\n 'Position', [20 63 50 77]);\r\n\r\nreuse_block(blk, 'counter', 'xbsIndex_r4/Counter', ...\r\n 'rst', 'on', ...\r\n 'use_rpm', 'off', ...\r\n 'Position', [80 42 125 98]);\r\n\r\n%forces counter to be larger than 3 bits so\r\n%that RAM has more than 2 bit address to prevent error\r\nif(counter_width < 3),\r\n count = 'counter_width+2';\r\n set_param([blk,'/counter'], 'n_bits', count, ...\r\n 'start_count', 'counter_start*4', 'cnt_by_val', 'counter_step*4');\r\nelse\r\n count = 'counter_width';\r\n set_param([blk,'/counter'],'n_bits', count, ... \r\n 'start_count','counter_start', 'cnt_by_val', 'counter_step');\r\nend\r\n\r\nreuse_block(blk, 'sincos', 'casper_library_downconverter/sincos', ...\r\n 'func', 'sine and cosine', 'neg_sin', 'on', ...\r\n 'neg_cos', 'off', 'symmetric', 'off', ...\r\n 'handle_sync', 'off', 'depth_bits', count, ...\r\n 'bit_width', 'n_bits', 'bram_latency', 'latency', ...\r\n 'Position', [150 42 200 98]);\r\n\r\nreuse_block(blk, 'sin', 'built-in/Outport', ...\r\n 'Port', '1', ...\r\n 'Position', [235 48 265 62]);\r\n\r\nreuse_block(blk, 'cos', 'built-in/Outport', ...\r\n 'Port', '2', ...\r\n 'Position', [235 78 265 92]);\r\n\r\nadd_line(blk,'sync/1','counter/1');\r\nadd_line(blk,'counter/1','sincos/1');\r\nadd_line(blk,'sincos/2','cos/1');\r\nadd_line(blk,'sincos/1','sin/1');\r\n\r\nclean_blocks(blk);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_maddsub_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_maddsub_init.m", "size": 24374, "source_encoding": "utf_8", "md5": "12cd9855df23575af61e36645d547570", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_maddsub_init(blk, varargin)\n log_group = 'bus_maddsub_init_debug';\n\n clog('entering bus_maddsub_init', {log_group, 'trace'});\n \n defaults = { ...\n 'n_bits_a', [8 8 8 8], 'bin_pt_a', 3, 'type_a', 1, 'cmplx_a', 'off', ...\n 'n_bits_b', [4], 'bin_pt_b', 3, 'type_b', 1, 'replicate_ab', 'on', ...\n 'mult_latency', 3, ...\n 'multiplier_implementation', 'behavioral HDL', ... 'embedded multiplier core' 'standard core' ...\n 'opmode', 'Addition', ...\n 'n_bits_c', [4 4 4 4], 'bin_pt_c', 3, 'type_c', 1, 'replicate_c', 'off', ...\n 'add_implementation', 'fabric core', ... 'behavioral HDL' 'DSP48 core'\n 'add_latency', 1, 'async_add', 'on', 'align_c', 'off', ...\n 'n_bits_out', 12, 'bin_pt_out', 7, 'type_out', 1, ...\n 'quantization', 0, 'overflow', 0, 'max_fanout', 2};\n \n check_mask_type(blk, 'bus_maddsub');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 80;\n ypos = 50; yinc = 50;\n\n port_w = 30; port_d = 14;\n rep_w = 50; rep_d = 30;\n bus_expand_w = 50;\n bus_create_w = 50;\n mult_w = 50; mult_d = 60;\n add_w = 50; add_d = 60;\n del_w = 30; del_d = 20;\n\n n_bits_a = get_var('n_bits_a', 'defaults', defaults, varargin{:});\n bin_pt_a = get_var('bin_pt_a', 'defaults', defaults, varargin{:});\n type_a = get_var('type_a', 'defaults', defaults, varargin{:});\n cmplx_a = get_var('cmplx_a', 'defaults', defaults, varargin{:});\n n_bits_b = get_var('n_bits_b', 'defaults', defaults, varargin{:});\n bin_pt_b = get_var('bin_pt_b', 'defaults', defaults, varargin{:});\n type_b = get_var('type_b', 'defaults', defaults, varargin{:});\n mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\n multiplier_implementation = get_var('multiplier_implementation', 'defaults', defaults, varargin{:});\n replicate_ab = get_var('replicate_ab', 'defaults', defaults, varargin{:});\n opmode = get_var('opmode', 'defaults', defaults, varargin{:});\n n_bits_c = get_var('n_bits_c', 'defaults', defaults, varargin{:});\n bin_pt_c = get_var('bin_pt_c', 'defaults', defaults, varargin{:});\n type_c = get_var('type_c', 'defaults', defaults, varargin{:});\n add_implementation = get_var('add_implementation', 'defaults', defaults, varargin{:});\n add_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\n async_add = get_var('async_add', 'defaults', defaults, varargin{:});\n align_c = get_var('align_c', 'defaults', defaults, varargin{:});\n replicate_c = get_var('replicate_c', 'defaults', defaults, varargin{:});\n n_bits_out = get_var('n_bits_out', 'defaults', defaults, varargin{:});\n bin_pt_out = get_var('bin_pt_out', 'defaults', defaults, varargin{:});\n type_out = get_var('type_out', 'defaults', defaults, varargin{:});\n quantization = get_var('quantization', 'defaults', defaults, varargin{:});\n overflow = get_var('overflow', 'defaults', defaults, varargin{:});\n max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state, do nothing \n if (~isempty(find([n_bits_a, n_bits_b, n_bits_c] == 0))),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_maddsub_init', {'trace', log_group});\n return;\n end\n\n %%%%%%%%%%%%%%%%%%%%%%\n % parameter checking %\n %%%%%%%%%%%%%%%%%%%%%%\n\n if max_fanout < 1,\n clog('Maximum fanout must be 1 or greater', {'error', log_group});\n error('Maximum fanout must be 1 or greater');\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % check input lists for consistency %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n lenba = length(n_bits_a); lenpa = length(bin_pt_a); lenta = length(type_a);\n a = [lenba, lenpa, lenta]; \n unique_a = unique(a);\n compa = unique_a(length(unique_a));\n\n lenbb = length(n_bits_b); lenpb = length(bin_pt_b); lentb = length(type_b);\n b = [lenbb, lenpb, lentb]; \n unique_b = unique(b);\n compb = unique_b(length(unique_b));\n\n lenbc = length(n_bits_c); lenpc = length(bin_pt_c); lentc = length(type_c);\n c = [lenbc, lenpc, lentc]; \n unique_c = unique(c);\n compc = unique_c(length(unique_c));\n\n lenbo = length(n_bits_out); lenpo = length(bin_pt_out); lento = length(type_out); \n lenq = length(quantization); leno = length(overflow);\n o = [lenbo, lenpo, lento, lenq, leno];\n unique_o = unique(o);\n compo = unique_o(length(unique_o));\n\n too_many_a = length(unique_a) > 2;\n conflict_a = (length(unique_a) == 2) && (unique_a(1) ~= 1);\n if too_many_a | conflict_a,\n error('conflicting component number for bus a');\n clog('conflicting component number for bus a', {'error', log_group});\n end\n\n too_many_b = length(unique_b) > 2;\n conflict_b = (length(unique_b) == 2) && (unique_b(1) ~= 1);\n if too_many_b | conflict_b,\n error('conflicting component number for bus b');\n clog('conflicting component number for bus b', {'error', log_group});\n end\n\n too_many_c = length(unique_c) > 2;\n conflict_c = (length(unique_c) == 2) && (unique_c(1) ~= 1);\n if too_many_c | conflict_c,\n error('conflicting component number for bus c');\n clog('conflicting component number for bus c', {'error', log_group});\n end\n\n too_many_o = length(unique_o) > 2;\n conflict_o = (length(unique_o) == 2) && (unique_o(1) ~= 1);\n if too_many_o | conflict_o,\n error('conflicting component number for output bus');\n clog('conflicting component number for output bus', {'error', log_group});\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % autocomplete input lists where necessary %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n comp = max([compa, compb, compc]);\n\n %replicate items if needed for a input\n n_bits_a = repmat(n_bits_a, 1, compa/lenba); \n bin_pt_a = repmat(bin_pt_a, 1, compa/lenpa); \n type_a = repmat(type_a, 1, compa/lenta); \n \n %replicate items if needed for b input\n n_bits_b = repmat(n_bits_b, 1, compb/lenbb); \n bin_pt_b = repmat(bin_pt_b, 1, compb/lenpb);\n type_b = repmat(type_b, 1, compb/lentb);\n \n %replicate items if needed for c input\n n_bits_c = repmat(n_bits_c, 1, compc/lenbc); \n bin_pt_c = repmat(bin_pt_c, 1, compc/lenpc);\n type_c = repmat(type_c, 1, compc/lentc);\n \n %replicate items if needed for output\n compo = comp;\n n_bits_out = repmat(n_bits_out, 1, comp/lenbo);\n bin_pt_out = repmat(bin_pt_out, 1, comp/lenpo);\n type_out = repmat(type_out, 1, comp/lento);\n overflow = repmat(overflow, 1, comp/leno);\n quantization = repmat(quantization, 1, comp/lenq);\n \n %%%%%%%%%%%%%%%%%%\n % fanout control %\n %%%%%%%%%%%%%%%%%%\n\n fa = compo/compa; \n max_fanouta = max_fanout; \n dupa = ceil(fa/max_fanouta); \n compa = compa*dupa; type_a = repmat(type_a, 1, dupa) ;\n n_bits_a = repmat(n_bits_a, 1, dupa); bin_pt_a = repmat(bin_pt_a, 1, dupa); \n a_src = repmat([1:compa], 1, ceil(compo/compa));\n\n fb = compo/compb;\n max_fanoutb = max_fanout; \n dupb = ceil(fb/max_fanoutb);\n compb = compb*dupb; type_b = repmat(type_b, 1, dupb) ;\n n_bits_b = repmat(n_bits_b, 1, dupb); bin_pt_b = repmat(bin_pt_b, 1, dupb); \n if strcmp(cmplx_a, 'on'),\n b_src = repmat(reshape([[1:compb];[1:compb]], 1, compb*2), 1, ceil(compo/(compb*2)));\n else, \n b_src = repmat([1:compb], 1, ceil(compo/compb));\n end \n\n fc = compo/compc;\n max_fanoutc = max_fanout; \n dupc = ceil(fc/max_fanoutc);\n compc = compc*dupc; type_c = repmat(type_c, 1, dupc) ;\n n_bits_c = repmat(n_bits_c, 1, dupc); bin_pt_c = repmat(bin_pt_c, 1, dupc); \n c_src = repmat([1:compc], 1, ceil(compo/compc));\n \n %required fanout of en\n fanout = ceil(comp/max_fanout);\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % at this point all a, b, c, output lists should match %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n clog(['n_bits_a = ', mat2str(n_bits_a)], log_group);\n clog(['n_bits_b = ', mat2str(n_bits_b)], log_group);\n clog(['n_bits_c = ', mat2str(n_bits_c)], log_group);\n clog(['n_bits_out = ', mat2str(n_bits_out)], log_group);\n clog(['bin_pt_out = ', mat2str(bin_pt_out)], log_group);\n clog(['type_out = ', mat2str(type_out)], log_group);\n clog(['overflow = ', mat2str(overflow)], log_group);\n clog(['quantization = ', mat2str(quantization)], log_group);\n clog(['duplication factors => a: ', num2str(dupa),' b: ', num2str(dupb),' c: ', num2str(dupc)], log_group);\n clog(['compa = ', num2str(compa), ' compb = ', num2str(compb), ' compc = ', num2str(compc),' compo = ', num2str(compo)], log_group);\n clog(['connection vector for port a = ', mat2str(a_src)], log_group);\n clog(['connection vector for port b = ', mat2str(b_src)], log_group);\n clog(['connection vector for port c = ', mat2str(c_src)], log_group);\n\n %%%%%%%%%%%%%%%\n % input ports %\n %%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + mult_d*compa/2;\n reuse_block(blk, 'a', 'built-in/inport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + mult_d*(compa/2 + compb/2);\n \n reuse_block(blk, 'b', 'built-in/inport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + mult_d*(compb/2 + compc/2);\n \n reuse_block(blk, 'c', 'built-in/inport', ...\n 'Port', '3', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + mult_d*(compc/2);\n\n port_offset = 4;\n if strcmp(async_add, 'on'),\n ypos_tmp = ypos_tmp + yinc + mult_d*fanout;\n\n reuse_block(blk, 'en', 'built-in/inport', ...\n 'Port', num2str(port_offset), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc;\n port_offset = port_offset + 1;\n end\n\n xpos = xpos + xinc + port_w/2 + rep_w/2; \n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\n % a,b replication control %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + mult_d*compa/2;\n\n %replicate busses\n\n if strcmp(replicate_ab, 'on'),\n reuse_block(blk, 'repa', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(dupa), 'latency', '1', 'misc', 'off', ... \n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'a/1', 'repa/1'); \n end\n\n ypos_tmp = ypos_tmp + yinc + mult_d*(compa/2 + compb/2);\n \n if strcmp(replicate_ab, 'on'),\n reuse_block(blk, 'repb', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(dupb), 'latency', '1', 'misc', 'off', ...\n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'b/1', 'repb/1'); \n end \n \n ypos_tmp = ypos_tmp + yinc + mult_d*(compb/2 + compc/2);\n\n ypos_tmp = ypos_tmp + 2*yinc + mult_d*(compc/2 + fanout);\n \n xpos = xpos + xinc + rep_w/2 + bus_expand_w/2;\n\n %%%%%%%%%%%%%%\n % bus expand %\n %%%%%%%%%%%%%%\n \n ypos_tmp = ypos + mult_d*compa/2; %reset ypos\n\n outputWidth = mat2str(n_bits_a);\n outputBinaryPt = mat2str(bin_pt_a);\n outputArithmeticType = mat2str(type_a);\n\n reuse_block(blk, 'a_debus', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', outputWidth, ...\n 'outputBinaryPt', outputBinaryPt, ...\n 'outputArithmeticType', outputArithmeticType, ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-mult_d*compa/2 xpos+bus_expand_w/2 ypos_tmp+mult_d*compa/2]);\n if strcmp(replicate_ab, 'on'), add_line(blk, 'repa/1', 'a_debus/1');\n else, add_line(blk, 'a/1', 'a_debus/1');\n end\n ypos_tmp = ypos_tmp + mult_d*(compa/2+compb/2) + yinc;\n \n outputWidth = mat2str(n_bits_b);\n outputBinaryPt = mat2str(bin_pt_b);\n outputArithmeticType = mat2str(type_b);\n \n reuse_block(blk, 'b_debus', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', outputWidth, ...\n 'outputBinaryPt', outputBinaryPt, ...\n 'outputArithmeticType', outputArithmeticType, ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-mult_d*compb/2 xpos+bus_expand_w/2 ypos_tmp+mult_d*compb/2]);\n if strcmp(replicate_ab, 'on'), add_line(blk, 'repb/1', 'b_debus/1');\n else, add_line(blk, 'b/1', 'b_debus/1');\n end\n ypos_tmp = ypos_tmp + mult_d*(compb/2+compc/2) + yinc;\n \n ypos_tmp = ypos_tmp + mult_d*(compc/2 + fanout/2)+ yinc;\n\n xpos = xpos + xinc + bus_expand_w/2 + mult_w/2; \n\n %%%%%%%%%%%%%%%%%%\n % multiplication %\n %%%%%%%%%%%%%%%%%%\n\n ypos_tmp = ypos; %reset ypos \n\n if strcmp(replicate_ab, 'on'), latency = mult_latency - 1;\n else, latency = mult_latency;\n end\n\n for index = 1:compo,\n clog([num2str(index),': type = ', num2str(type_out(index)), ...\n ' quantization = ', num2str(quantization(index)), ...\n ' overflow = ',num2str(overflow(index))], log_group);\n switch type_out(index),\n case 0,\n arith_type = 'Unsigned';\n case 1,\n arith_type = 'Signed';\n otherwise,\n clog(['unknown arithmetic type ',num2str(arith_type)], {'error', log_group});\n error(['bus_mult_init: unknown arithmetic type ',num2str(arith_type)]);\n end\n switch quantization(index),\n case 0,\n quant = 'Truncate';\n case 1,\n quant = 'Round (unbiased: +/- Inf)';\n end \n switch overflow(index),\n case 0,\n of = 'Wrap';\n case 1,\n of = 'Saturate';\n case 2,\n of = 'Flag as error';\n end \n clog(['output ',num2str(index),': (',num2str(n_bits_out(index)), ' ', ...\n num2str(bin_pt_out(index)),') ', arith_type,' ',quant,' ', of], ...\n log_group); \n\n mult_name = ['mult',num2str(index)]; \n clog(['drawing ',mult_name], log_group);\n \n %standard multiplication \n if strcmp(multiplier_implementation, 'behavioral HDL'),\n use_behavioral_HDL = 'on';\n use_embedded = 'off';\n else\n use_behavioral_HDL = 'off';\n if strcmp(multiplier_implementation, 'embedded multiplier core'),\n use_embedded = 'on';\n elseif strcmp(multiplier_implementation, 'standard core'),\n use_embedded = 'off';\n else,\n end\n end\n\n reuse_block(blk, mult_name, 'xbsIndex_r4/Mult', ...\n 'latency', num2str(latency), 'precision', 'Full', ...\n 'use_behavioral_HDL', use_behavioral_HDL, 'use_embedded', use_embedded, ...\n 'Position', [xpos-mult_w/2 ypos_tmp xpos+mult_w/2 ypos_tmp+mult_d-20]);\n \n ypos_tmp = ypos_tmp + mult_d;\n clog(['done'], log_group);\n \n add_line(blk, ['a_debus/', num2str(a_src(index))], [mult_name, '/1']);\n add_line(blk, ['b_debus/', num2str(b_src(index))], [mult_name, '/2']);\n end %for\n\n ypos_tmp = ypos + mult_d*(compb+compa+compc+fanout) + 4*yinc;\n \n if strcmp(async_add, 'on'),\n %en \n reuse_block(blk, 'den0', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(mult_latency-1), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, 'en/1', 'den0/1');\n end \n \n xpos = xpos + xinc + mult_w/2 + rep_w/2;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % replication of enable for add/sub %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n ypos_tmp = ypos + yinc*2 + mult_d*(compa+compb+compc/2);\n\n if strcmp(replicate_c, 'on'),\n latency = 1;\n reuse_block(blk, 'repc', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(dupc), 'latency', '1', 'misc', 'off', ...\n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'c/1', 'repc/1'); \n end \n\n ypos_tmp = ypos_tmp + yinc + mult_d*compc/2;\n \n if strcmp(async_add, 'on'),\n ypos_tmp = ypos_tmp + mult_d*fanout/2;\n\n reuse_block(blk, 'repen1', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(fanout), 'latency', num2str(mult_latency), 'misc', 'off', ...\n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'en/1', 'repen1/1'); \n \n ypos_tmp = ypos_tmp + yinc + mult_d*fanout/2;\n\n %en \n reuse_block(blk, 'den1', 'xbsIndex_r4/Delay', ...\n 'latency', '1', 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, 'den0/1', 'den1/1');\n end \n \n xpos = xpos + xinc + rep_w/2 + bus_expand_w/2;\n \n %%%%%%%%%%%%%%%%%%%%\n % debus for addsub %\n %%%%%%%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + mult_d*(compa + compb + compc/2) + yinc*2;\n\n outputWidth = mat2str(n_bits_c);\n outputBinaryPt = mat2str(bin_pt_c);\n outputArithmeticType = mat2str(type_c);\n \n reuse_block(blk, 'c_debus', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', outputWidth, ...\n 'outputBinaryPt', outputBinaryPt, ...\n 'outputArithmeticType', outputArithmeticType, ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-mult_d*compc/2 xpos+bus_expand_w/2 ypos_tmp+mult_d*compc/2]);\n if strcmp(replicate_c, 'on'), add_line(blk, 'repc/1', 'c_debus/1');\n else, add_line(blk, 'c/1', 'c_debus/1');\n end\n \n ypos_tmp = ypos_tmp + mult_d*compc/2 + yinc;\n\n if strcmp(async_add, 'on'),\n ypos_tmp = ypos_tmp + mult_d*fanout/2;\n\n reuse_block(blk, 'en_debus1', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', ...\n 'outputNum', num2str(fanout), ...\n 'outputWidth', '1', 'outputBinaryPt', '0', 'outputArithmeticType', '2', ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-mult_d*fanout/2 xpos+bus_expand_w/2 ypos_tmp+mult_d*fanout/2]);\n\n add_line(blk, 'repen1/1', 'en_debus1/1');\n end %if\n \n xpos = xpos + xinc + bus_expand_w/2 + add_w/2;\n \n %%%%%%%%%%%%%%%%%%%%%%%%\n % addition/subtraction %\n %%%%%%%%%%%%%%%%%%%%%%%%\n\n %addsub\n ypos_tmp = ypos; %reset ypos \n\n clog(['making ',num2str(compo),' AddSubs'], log_group);\n\n for index = 1:compo\n switch type_out(index),\n case 0,\n arith_type = 'Unsigned';\n case 1,\n arith_type = 'Signed';\n end\n switch quantization(index),\n case 0,\n quant = 'Truncate';\n case 1,\n quant = 'Round (unbiased: +/- Inf)';\n end \n switch overflow(index),\n case 0,\n of = 'Wrap';\n case 1,\n of = 'Saturate';\n case 2,\n of = 'Flag as error';\n end \n if strcmp(opmode, 'Addition'),\n symbol = '+';\n else,\n symbol = '-';\n end \n \n clog(['output ',num2str(index),': ', ... \n ' a[',num2str(a_src(index)),'] ',symbol,' b[',num2str(b_src(index)),'] = ', ...\n '(',num2str(n_bits_out(index)), ' ', num2str(bin_pt_out(index)),') ' ...\n ,arith_type,' ',quant,' ', of], log_group); \n\n if strcmp(add_implementation, 'behavioral HDL'),\n use_behavioral_HDL = 'on';\n hw_selection = 'Fabric';\n elseif strcmp(add_implementation, 'fabric core'),\n use_behavioral_HDL = 'off';\n hw_selection = 'Fabric';\n elseif strcmp(add_implementation, 'DSP48 core'),\n use_behavioral_HDL = 'off';\n hw_selection = 'DSP48';\n end\n\n add_name = ['addsub',num2str(index)]; \n \n reuse_block(blk, add_name, 'xbsIndex_r4/AddSub', ...\n 'mode', opmode, 'latency', num2str(add_latency), ...\n 'en', async_add, 'precision', 'User Defined', ...\n 'n_bits', num2str(n_bits_out(index)), 'bin_pt', num2str(bin_pt_out(index)), ... \n 'arith_type', arith_type, 'quantization', quant, 'overflow', of, ... \n 'pipelined', 'on', 'use_behavioral_HDL', use_behavioral_HDL, 'hw_selection', hw_selection, ... \n 'Position', [xpos-add_w/2 ypos_tmp xpos+add_w/2 ypos_tmp+add_d-20]);\n ypos_tmp = ypos_tmp + add_d;\n \n mult_name = ['mult',num2str(index)]; \n add_line(blk, [mult_name, '/1'], [add_name,'/1']);\n add_line(blk, ['c_debus/',num2str(c_src(index))], [add_name,'/2']);\n\n if strcmp(async_add, 'on')\n add_line(blk, ['en_debus1/', num2str(floor((index-1)/max_fanout)+1)], [add_name,'/3']);\n end\n\n end %for\n\n ypos_tmp = ypos + mult_d*(compa+compb+compc+fanout) + yinc*4;\n\n if strcmp(async_add, 'on'),\n %en \n reuse_block(blk, 'den2', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(add_latency), 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, 'den1/1', 'den2/1');\n end \n\n xpos = xpos + xinc + add_w/2 + bus_create_w/2;\n\n %%%%%%%%%%%%%%\n % bus create %\n %%%%%%%%%%%%%%\n\n ypos_tmp = ypos + mult_d*compo/2; %reset ypos\n\n if strcmp(opmode, 'Addition'), op = '+';\n else, op = '-';\n end\n\n reuse_block(blk, ['a*b', op, 'c_bussify'], 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(compo), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-mult_d*compo/2 xpos+bus_create_w/2 ypos_tmp+mult_d*compo/2]);\n \n for index = 1:compo, add_line(blk, ['addsub',num2str(index),'/1'], ['a*b', op, 'c_bussify/',num2str(index)]); end\n\n xpos = xpos + xinc + bus_create_w/2 + port_w/2;\n\n %%%%%%%%%%%%%%%%%\n % output port/s %\n %%%%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + mult_d*compo/2;\n reuse_block(blk, ['a*b', op, 'c'], 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, ['a*b', op, 'c_bussify/1'], ['a*b', op, 'c/1']);\n\n ypos_tmp = ypos + mult_d*(compb+compa+compc+fanout) + 4*yinc;\n\n if strcmp(async_add, 'on'),\n reuse_block(blk, 'dvalid', 'built-in/outport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, 'den2/1', 'dvalid/1');\n end \n \n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_maddsub_init', {'trace', log_group});\n\nend %function bus_maddsub_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "update_casper_block.m", "ext": ".m", "path": "mlib_devel-master/casper_library/update_casper_block.m", "size": 7668, "source_encoding": "utf_8", "md5": "0c9ce424ff0d01d5bb93ee081b9b2647", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2013 David MacMahon\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% This function updates oldblk using the most recent library version.\n% Mask parameters are copied over whenever possible.\nfunction update_casper_block(oldblk)\n\n % Clear last dumped exception to ensure that all exceptions are shown.\n dump_exception([]);\n\n % Check link status\n link_status = get_param(oldblk, 'StaticLinkStatus');\n\n % Inactive link (link disabled but not broken) so get AncestorBlock\n if strcmp(link_status, 'inactive'),\n srcblk = get_param(oldblk, 'AncestorBlock');\n\n % Resolved link (link in place) so get ReferenceBlock\n elseif strcmp(link_status, 'resolved'),\n srcblk = get_param(oldblk, 'ReferenceBlock');\n\n % Else, not supported\n else\n fprintf('%s is not a linked library block\\n', oldblk);\n return;\n end\n\n % Map srcblk through casper_library_forwarding_table in case it's a really\n % old name.\n srcblk = casper_library_forwarding_table(srcblk);\n\n % Special handling for deprecated \"edge\" blocks\n switch srcblk\n case {'casper_library_misc/edge', ...\n 'casper_library_misc/negedge', ...\n 'casper_library_misc/posedge'}\n % Get mask params for edge_detect block\n switch srcblk\n case 'casper_library_misc/edge'\n params = {'edge', 'Both', 'polarity', 'Active High'};\n case 'casper_library_misc/negedge'\n params = {'edge', 'Falling', 'polarity', 'Active High'};\n case 'casper_library_misc/posedge'\n params = {'edge', 'Rising', 'polarity', 'Active High'};\n end\n % Make sure casper_library_misc block diagram is loaded\n if ~bdIsLoaded('casper_library_misc')\n fprintf('loading library casper_library_misc\\n');\n load_system('casper_library_misc');\n end\n % Get position and orientation of oldblk\n p = get_param(oldblk, 'position');\n o = get_param(oldblk, 'orientation');\n % Delete oldblk\n delete_block(oldblk);\n % Add edge detect block using oldblk's name\n add_block('casper_library_misc/edge_detect', oldblk, ...\n 'orientation', o, ...\n 'position', p, ...\n params{:});\n % Done!\n return\n end % special deprecated handling\n\n % Make sure srcblk's block diagram is loaded\n srcblk_bd = regexprep(srcblk, '/.*', '');\n if ~bdIsLoaded(srcblk_bd)\n fprintf('loading library %s\\n', srcblk_bd);\n load_system(srcblk_bd);\n end\n\n % Get old and new mask names\n oldblk_mask_names = get_param(oldblk, 'MaskNames');\n newblk_mask_names = get_param(srcblk, 'MaskNames');\n\n % Save warning backtrace state then disable backtrace\n bt_state = warning('query', 'backtrace');\n warning off backtrace;\n\n % Try to populate newblk's mask parameters from oldblk\n newblk_params = {};\n for k = 1:length(newblk_mask_names)\n % If oldblk has the same mask parameter name\n if find(strcmp(oldblk_mask_names, newblk_mask_names{k}))\n % Add to new block parameters\n newblk_params{end+1} = newblk_mask_names{k};\n newblk_params{end+1} = get_param(oldblk, newblk_mask_names{k});\n else\n type = get_param(oldblk, 'MaskType');\n if ~isempty(type)\n type = [type ' '];\n end\n link = sprintf('%s', ...\n oldblk, oldblk);\n warning('old %sblock %s did not have mask parameter %s', ...\n type, link, newblk_mask_names{k});\n end\n end\n\n % Restore warning backtrace state\n warning(bt_state);\n\n % In addition to copying the mask parameters, we also copy the UserData\n % parameter, if it looks like it was set by save_state. We clear the state\n % field to ensure that the block gets re-initialized by the mask init script.\n ud = get_param(oldblk, 'UserData');\n if isstruct(ud) && isfield(ud, 'state') && isfield(ud, 'parameters')\n ud.state = [];\n newblk_params{end+1} = 'UserData';\n newblk_params{end+1} = ud;\n end\n\n % Get position and orientation of oldblk.\n p = get_param(oldblk, 'position');\n o = get_param(oldblk, 'orientation');\n\n % The new block must be added directly to the same parent subsystem since\n % some of its mask parameter values might use variable names that only exist\n % in the scope of the parent subsystem's mask. Adding a block to the parent\n % subsystem can cause the parent subsystem's mask initialization code to run\n % which may call \"clean_blocks\" which would see the block we're adding as\n % unconnected and delete it! To avoid this, we temporarily set the parent\n % subsystem's mask initialization parameter to an empty string, then restore\n % the original setting after adding the block.\n parent_mask_init = '';\n parent = get_param(oldblk, 'Parent');\n % If parent is a block (i.e. NOT a block diagram)\n if strcmp(get_param(parent, 'Type'), 'block')\n try\n parent_mask_init = get_param(parent, 'MaskInitialization');\n set_param(parent, 'MaskInitialization', '');\n end\n end\n\n % Delete old block\n delete_block(oldblk);\n\n % Add source block using new params. Note that we position the new block at\n % (0,0) with size of (0,0) to minimize the possibility of it connecting to\n % stray unconnected lines before the mask init script runs (which may change\n % the number of ports).\n add_block(srcblk, oldblk, ...\n 'position', [0,0,0,0], ...\n 'orientation', o, ...\n newblk_params{:});\n\n % Move block into position. Some blocks (e.g. software register blocks) need\n % to be resized to get port spacing correct and sometimes the block needs a\n % little nudge one way or the other to connect to existing lines. That's why\n % we set the position multiple times.\n set_param(oldblk, ...\n 'position', p, ...\n 'position', p + [-1, 0, 0, 0], ...\n 'position', p, ...\n 'position', p + [ 1, 0, 0, 0], ...\n 'position', p, ...\n 'position', p + [ 0, -1, 0, 0], ...\n 'position', p, ...\n 'position', p + [ 0, 1, 0, 0], ...\n 'position', p, ...\n 'position', p + [-1, -1, 2, 2], ...\n 'position', p);\n\n % Restore parent's mask init setting\n if ~isempty(parent_mask_init)\n set_param(parent, 'MaskInitialization', parent_mask_init);\n end\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_coeff_gen_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_coeff_gen_init.m", "size": 7916, "source_encoding": "utf_8", "md5": "3a8b8de3b410dded0593336d7521f5b0", "text": "% Initialize and configure the Polyphase Filter Bank coefficient generator.\r\n%\r\n% pfb_coeff_gen_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% PFBSize = Size of the FFT (2^FFTSize points).\r\n% CoeffBitWidth = Bit width of coefficients.\r\n% TotalTaps = Total number of taps in the PFB\r\n% CoeffDistMem = Implement coefficients in distributed memory\r\n% WindowType = The type of windowing function to use.\r\n% bram_latency = The latency of BRAM in the system.\r\n% n_inputs = Number of parallel input streams\r\n% nput = Which input this is (of the n_inputs parallel).\r\n% fwidth = The scaling of the bin width (1 is normal).\r\n% debug_mode = true or false, is the block being used in debug mode or not. Changes the coefficients.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction pfb_coeff_gen_init(blk, varargin)\r\n\r\n% declare any default values for arguments you might like.\r\ndefaults = {};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'pfb_coeff_gen');\r\nmunge_block(blk, varargin{:});\r\n\r\nPFBSize = get_var('PFBSize', 'defaults', defaults, varargin{:});\r\nCoeffBitWidth = get_var('CoeffBitWidth', 'defaults', defaults, varargin{:});\r\nTotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:});\r\nCoeffDistMem = get_var('CoeffDistMem', 'defaults', defaults, varargin{:});\r\nWindowType = get_var('WindowType', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\nfan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:});\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\nnput = get_var('nput', 'defaults', defaults, varargin{:});\r\nfwidth = get_var('fwidth', 'defaults', defaults, varargin{:});\r\ndebug_mode = get_var('debug_mode', 'defaults', defaults, varargin{:});\r\n\r\n% Set coefficient vector\r\ntry\r\n\twindow('hamming',1024);\r\ncatch\r\n\tdisp('pfb_coeff_gen_init:Signal Processing Library absent or not working correctly');\r\n\terror('pfb_coeff_gen_init:Signal Processing Library absent or not working correctly');\r\nend\r\n%alltaps = TotalTaps*2^PFBSize;\r\n%windowval = transpose(window(WindowType, alltaps));\r\n%total_coeffs = windowval .* sinc(fwidth*([0:alltaps-1]/(2^PFBSize)-TotalTaps/2));\r\n%for i=1:alltaps/2^n_inputs,\r\n% buf(i)=total_coeffs((i-1)*2^n_inputs + nput + 1);\r\n%end\r\n\r\ndelete_lines(blk);\r\n\r\n% Add Ports\r\nreuse_block(blk, 'din', 'built-in/inport', 'Position', [235 28 265 42], 'Port', '1');\r\nreuse_block(blk, 'sync', 'built-in/inport', 'Position', [15 93 45 107], 'Port', '2');\r\nreuse_block(blk, 'dout', 'built-in/outport', 'Position', [360 28 390 42], 'Port', '1');\r\nreuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [130 28 160 42], 'Port', '2');\r\nreuse_block(blk, 'coeff', 'built-in/outport', 'Position', [500 343 530 357], 'Port', '3');\r\n\r\n% Add Static Blocks\r\nreuse_block(blk, 'Delay', 'xbsIndex_r4/Delay', ...\r\n 'latency', 'bram_latency+1+fan_latency', 'Position', [65 12 110 58]);\r\nreuse_block(blk, 'Counter', 'xbsIndex_r4/Counter', ...\r\n 'cnt_type', 'Free Running', 'n_bits', tostring(PFBSize-n_inputs), 'arith_type', 'Unsigned', ...\r\n 'rst', 'on', 'explicit_period', 'on', 'Position', [65 75 115 125]);\r\nreuse_block(blk, 'Delay1', 'xbsIndex_r4/Delay', ...\r\n 'latency', 'bram_latency+1+fan_latency', 'Position', [290 12 335 58]);\r\nreuse_block(blk, 'Concat', 'xbsIndex_r4/Concat', ...\r\n 'num_inputs', tostring(TotalTaps), 'Position', [360 97 415 643]);\r\nreuse_block(blk, 'Register', 'xbsIndex_r4/Register', ...\r\n 'Position', [435 325 480 375]);\r\n\r\nadd_line(blk, 'din/1', 'Delay1/1');\r\nadd_line(blk, 'Delay1/1', 'dout/1');\r\nadd_line(blk, 'sync/1', 'Counter/1');\r\nadd_line(blk, 'sync/1', 'Delay/1');\r\nadd_line(blk, 'Delay/1', 'sync_out/1');\r\nadd_line(blk, 'Concat/1', 'Register/1');\r\nadd_line(blk, 'Register/1', 'coeff/1');\r\n\r\n% Add Dynamic Blocks\r\nfor a=1:TotalTaps,\r\n dblkname = ['fan_delay', tostring(a)];\r\n reuse_block(blk, dblkname, 'xbsIndex_r4/Delay', ...\r\n 'latency', 'fan_latency', 'Position', [150 65*(a-1)+74 180 65*(a-1)+126]);\r\n add_line(blk, 'Counter/1', [dblkname, '/1']);\r\n \r\n if strcmp(debug_mode, 'on'),\r\n atype = 'Unsigned';\r\n binpt = '0';\r\n debug_option = 'true';\r\n else\r\n atype = 'Signed (2''s comp)';\r\n binpt = tostring(CoeffBitWidth-1);\r\n debug_option = 'false';\r\n end\r\n vector_str = ['pfb_coeff_gen_calc(', tostring(PFBSize), ', ', ...\r\n tostring(TotalTaps), ',''', tostring(WindowType), ''',', ...\r\n tostring(n_inputs), ', ', tostring(nput), ',', ...\r\n tostring(fwidth), ',', tostring(a), ',', debug_option, ')'];\r\n blkname = ['ROM', tostring(a)];\r\n reuse_block(blk, blkname, 'xbsIndex_r4/ROM', ...\r\n 'depth', tostring(2^(PFBSize-n_inputs)), 'initVector', vector_str, 'arith_type', atype, ...\r\n 'n_bits', tostring(CoeffBitWidth), 'bin_pt', binpt, ...\r\n 'latency', 'bram_latency', 'use_rpm','on', 'Position', [200 65*(a-1)+74 250 65*(a-1)+126]);\r\n\r\n add_line(blk, [dblkname, '/1'], [blkname, '/1']);\r\n reintname = ['Reinterpret', tostring(a)];\r\n reuse_block(blk, reintname, 'xbsIndex_r4/Reinterpret', 'force_arith_type', 'On', ...\r\n 'force_bin_pt','On',...\r\n 'Position', [270 65*(a-1)+84 310 65*(a-1)+116]);\r\n set_param([blk,'/',reintname],'arith_type','Unsigned','bin_pt','0');\r\n add_line(blk, [blkname, '/1'], [reintname, '/1']);\r\n add_line(blk, [reintname, '/1'], ['Concat/', tostring(a)]);\r\nend\r\n\r\n% Set coefficient ROMs to use distribute memory (or not).\r\nfor a=1:TotalTaps,\r\n blkname = ['ROM', tostring(a)];\r\n if strcmp(CoeffDistMem, 'on'),\r\n set_param([blk,'/',blkname], 'distributed_mem', 'Distributed memory');\r\n else\r\n set_param([blk,'/',blkname], 'distributed_mem', 'Block RAM');\r\n end\r\nend\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('PFBSize=%d, n_inputs=%d,\\ntaps=%d, input=%d', PFBSize, n_inputs, TotalTaps, nput);\r\nif strcmp(debug_mode, 'on'),\r\n fmtstr = [fmtstr, '\\nDEBUG MODE!'];\r\nend\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "munge_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/munge_init.m", "size": 7733, "source_encoding": "utf_8", "md5": "54b730d57a4d8adbb957c2c2ac448aff", "text": "% Break input bus into divisions and reorder as specified.\n%\n% munge_init(blk, varargin)\n%\n% blk = The block to be configured.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% divisions = number of divisions\n% div_size = size in bits of each division\n% order = ouput order of divisions (referenced to input order)\n% arith_type_out = reinterpret resultant vector\n% bin_pt_out = output binary point\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% MeerKAT Radio Telescope Project %\n% www.kat.ac.za %\n% Copyright (C) 2010 Andrew Martens (meerKAT) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction munge_init(blk,varargin)\nlog_group = 'munge_init_debug';\n\nclog('entering munge_init', {log_group, 'trace'});\ncheck_mask_type(blk, 'munge');\n\ndefaults = {'divisions', 4, 'div_size', [32 0 16 16], 'order', [3 0 1 2], 'arith_type_out', 'Unsigned', 'bin_pt_out', 0};\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\nclog('munge_init: post same_state', {log_group, 'trace'});\nmunge_block(blk, varargin{:});\n\ndivisions = get_var('divisions', 'defaults', defaults, varargin{:});\ndiv_size = get_var('div_size', 'defaults', defaults, varargin{:});\noutput_order = get_var('order', 'defaults', defaults, varargin{:});\narith_type_out = get_var('arith_type_out', 'defaults', defaults, varargin{:});\nbin_pt_out = get_var('bin_pt_out', 'defaults', defaults, varargin{:});\n\n%default empty state\nif divisions < 1,\n delete_lines(blk);\n clean_blocks(blk);\n set_param(blk,'AttributesFormatString','');\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting munge_init', {log_group, 'trace'});\n return;\nend\n\nif divisions > 1 && length(find(div_size >= 1)) == 0,\n clog(['Some divisions must have non-zero size'], {log_group, 'error'});\n error(['Some divisions must have non-zero size']);\n return;\nend\n\nif length(div_size) ~= 1 && length(div_size) ~= divisions,\n clog(['Reported number of divisions, ',num2str(divisions),' does not match division description length ',num2str(length(div_size))], {log_group, 'error'});\n error(['Reported number of divisions, ',num2str(divisions),' does not match division description length ',num2str(length(div_size))]);\n return;\nend\n\nif length(find(output_order < 0)) ~= 0 || ... \n length(find(output_order > divisions-1)) ~= 0,\n clog(['Output order elements must be in range 0->',num2str(divisions-1)], {log_group, 'error'});\n error(['Output order elements must be in range 0->',num2str(divisions-1)]);\n return;\nend\n\n%remove 0 division sizes from div_size\nnzero_i = find(div_size ~= 0);\ndiv_size_mod = div_size(nzero_i);\ndivisions_mod = length(div_size_mod);\n\n%adjust output_order based on zeros found in div_size\nzero_i = find(div_size == 0);\noutput_order_mod = output_order;\nfor n = 1:length(zero_i),\n indices = find(output_order >= (zero_i(n) - 1));\n if ~isempty(indices), \n output_order_mod(indices) = output_order_mod(indices) - 1;\n end %if\nend %for\nfor m = 1:length(zero_i),\n indices = find(output_order == (zero_i(m)-1));\n output_order_mod(indices) = [];\nend\n\n%calculate resultant word size\nn_bits_out = 0;\nfor index = 1:length(output_order_mod),\n if length(div_size_mod) == 1,\n n_bits_out = n_bits_out+div_size_mod*(output_order_mod(index)+1);\n else\n n_bits_out = n_bits_out+div_size_mod(output_order_mod(index)+1);\n end\nend\n\nif n_bits_out < bin_pt_out,\n clog(['binary point position ',num2str(bin_pt_out),' greater than number of bits ',num2str(n_bits_out)], {log_group, 'error'});\n error(['binary point position ',num2str(bin_pt_out),' greater than number of bits ',num2str(n_bits_out)]);\n return;\nend\n\ndelete_lines(blk);\n\nytick = 20;\n\nif length(div_size_mod) == 1,\n mode = 'divisions of equal size';\n inputNum = divisions_mod;\nelse,\n mode = 'divisions of arbitrary size';\n inputNum = length(output_order_mod);\nend\n\n%input \nreuse_block(blk, 'din', 'built-in/inport', 'Position', [40 10+ytick*(divisions_mod+1)/2 70 30+ytick*(divisions_mod+1)/2], 'Port', '1');\n%output\nreuse_block(blk, 'reinterpret_out', 'xbsIndex_r4/Reinterpret', ...\n 'force_arith_type', 'on', 'arith_type', arith_type_out, ...\n 'force_bin_pt', 'on', 'bin_pt', mat2str(bin_pt_out), ...\n 'Position', [655 10+ytick*(inputNum+1)/2 710 30+ytick*(inputNum+1)/2]);\nreuse_block(blk, 'dout', 'built-in/outport', 'Position', [780 10+ytick*(inputNum+1)/2 810 30+ytick*(inputNum+1)/2], 'Port', '1');\nadd_line(blk, 'reinterpret_out/1', 'dout/1');\n\nif divisions < 2,\n add_line(blk, 'din/1', 'reinterpret_out/1');\nelse\n %reinterpret\n reuse_block(blk, 'reinterpret', 'xbsIndex_r4/Reinterpret', ...\n 'force_arith_type', 'on', 'arith_type', 'Unsigned', ...\n 'force_bin_pt', 'on', 'bin_pt', '0', ...\n 'Position', [95 12+ytick*(divisions_mod+1)/2 160 28+ytick*(divisions_mod+1)/2]);\n add_line(blk, 'din/1', 'reinterpret/1');\n\n %bus expand\n reuse_block(blk, 'split', 'casper_library_flow_control/bus_expand', ...\n 'mode', mode, ...\n 'outputNum', num2str(divisions_mod), ...\n 'outputWidth', mat2str(div_size_mod), ...\n 'outputBinaryPt', mat2str(zeros(1, divisions_mod)), ...\n 'outputArithmeticType', mat2str(zeros(1, divisions_mod)), ...\n 'outputToWorkSpace', 'off', ...\n 'Position', [190 10 270 30+ytick*divisions_mod]);\n add_line(blk, 'reinterpret/1', 'split/1');\n\n %bus create\n reuse_block(blk, 'join', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(inputNum), ...\n 'Position', [550 10 630 30+ytick*inputNum]);\n add_line(blk, 'join/1', 'reinterpret_out/1');\n\n %join\n for div = 1:length(output_order_mod),\n add_line(blk, ['split/',num2str(output_order_mod(div)+1)], ['join/',num2str(div)]);\n end \nend %if\n\n% When finished drawing blocks and lines, remove all unused blocks.\nclean_blocks(blk);\n\n% Set attribute format string (block annotation)\nannotation=sprintf('split:%s\\njoin:%s\\n%s [%d,%d]',mat2str(div_size), mat2str(output_order), arith_type_out, n_bits_out, bin_pt_out);\nset_param(blk,'AttributesFormatString',annotation);\n\nsave_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\nclog('exiting munge_init', {log_group, 'trace'});\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_add_tree_async_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_add_tree_async_init.m", "size": 8718, "source_encoding": "utf_8", "md5": "9960463e3d72db5bcf7525cfe8d935aa", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction pfb_add_tree_async_init(blk, varargin)\n% Initialize and configure the Polyphase Filter Bank final summing tree.\n%\n% pfb_add_tree_async_init(blk, varargin)\n%\n% blk = The block to configure.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% total_taps = Total number of taps in the PFB\n% data_in_bits = Input Bitwidth\n% data_out_bits = Output Bitwidth\n% coeff_bits = Bitwidth of Coefficients.\n% add_latency = Latency through each adder.\n% quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round\n% (unbiased: Even Values)'\n\n% Declare any default values for arguments you might like.\ndefaults = {};\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\ncheck_mask_type(blk, 'pfb_add_tree_async');\nmunge_block(blk, varargin{:});\n\ninput_num = get_var('input_num', 'defaults', defaults, varargin{:});\ntotal_taps = get_var('total_taps', 'defaults', defaults, varargin{:});\ndata_in_bits = get_var('data_in_bits', 'defaults', defaults, varargin{:});\ncoeff_bits = get_var('coeff_bits', 'defaults', defaults, varargin{:});\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\ndebug_mode = get_var('debug_mode', 'defaults', defaults, varargin{:});\n\ndelete_lines(blk);\n\n% ports\nreuse_block(blk, 'din', 'built-in/inport', 'Position', [15 123 45 137], 'Port', '1');\nreuse_block(blk, 'sync', 'built-in/inport', 'Position', [15 28 45 42], 'Port', '2');\nreuse_block(blk, 'dout', 'built-in/outport', 'Position', [600 25*total_taps+100 630 25*total_taps+115], 'Port', '1');\nreuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [600 28 630 42], 'Port', '2');\n\n% dv path\nreuse_block(blk, 'dv', 'built-in/inport', 'Position', [30 668 60 682], 'Port', '3');\nreuse_block(blk, 'dv_out', 'built-in/outport', 'Position', [875 668 905 682], 'Port', '3');\nadd_stages = ceil(log2(total_taps));\ndv_latency = (add_latency * add_stages) + 1;\nreuse_block(blk, 'delay_dv', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(dv_latency), ...\n 'Position', [450 660 480 690]);\nadd_line(blk, 'dv/1', 'delay_dv/1');\nadd_line(blk, 'delay_dv/1', 'dv_out/1');\n\n% static blocks\nreuse_block(blk, 'adder_tree1', 'casper_library_misc/adder_tree', ...\n 'n_inputs', num2str(total_taps), 'latency', 'add_latency', ...\n 'Position', [200 114 350 50*total_taps+114]);\nreuse_block(blk, 'adder_tree2', 'casper_library_misc/adder_tree', ...\n 'n_inputs', num2str(total_taps), 'latency', 'add_latency', ...\n 'Position', [200 164+50*total_taps 350 164+100*total_taps]);\nfor ctr = 1:2,\n if strcmp(debug_mode, 'on'),\n ttype = 'Unsigned';\n tbinpt = '0';\n else\n ttype = 'Signed (2''s comp)';\n tbinpt = 'data_out_bits-1';\n end\n reuse_block(blk, ['convert', num2str(ctr)], 'xbsIndex_r4/Convert', ...\n 'arith_type', ttype, 'n_bits', 'data_out_bits', ...\n 'bin_pt', tbinpt, 'quantization', quantization, ...\n 'overflow', 'Saturate', 'latency', 'add_latency', 'pipeline', 'on',...\n 'Position', [500 25*total_taps+114+(40*(ctr-1)) 530 25*total_taps+128+(40*(ctr-1))]);\nend\n\n% delay to compensate for latency of convert blocks\nreuse_block(blk, 'delay_convert', 'xbsIndex_r4/Delay', ...\n 'latency', 'add_latency', ...\n 'Position', [400 50+25*total_taps 430 80+25*total_taps]);\n\n% Scale Blocks are required before casting to n_(n-1) format\n% Input to adder tree seemes to be n_(n-2) format\n% each level in the adder tree requires one more shift\n% so with just two taps, there is one level in the adder tree\n% so we would have, eg, 17_14 format, so we need to shift by 2 to get\n% 17_16 which can be converted to 18_17 without overflow.\n% There are nextpow2(total_taps) levels in the adder tree.\nscale_factor = 1 + add_stages;\nreuse_block(blk, 'scale1', 'xbsIndex_r4/Scale', ...\n 'scale_factor', num2str(-scale_factor), ...\n 'Position', [400 25*total_taps+114 430 25*total_taps+128]);\nreuse_block(blk, 'scale2', 'xbsIndex_r4/Scale', ...\n 'scale_factor', num2str(-scale_factor), ...\n 'Position', [400 158+25*total_taps 430 172+25*total_taps]);\n\n% lines\n%add_line(blk, 'adder_tree1/2', 'convert1/1');\n%add_line(blk, 'adder_tree2/2', 'convert2/1');\nadd_line(blk, 'adder_tree1/2', 'scale1/1');\nadd_line(blk, 'scale1/1', 'convert1/1');\nadd_line(blk, 'adder_tree2/2', 'scale2/1');\nadd_line(blk, 'scale2/1', 'convert2/1');\nreuse_block(blk, 'ri_to_c', 'casper_library_misc/ri_to_c', ...\n 'Position', [550 114+25*total_taps 580 144+25*total_taps]);\nadd_line(blk, 'convert1/1', 'ri_to_c/1');\nadd_line(blk, 'convert2/1', 'ri_to_c/2');\nadd_line(blk, 'ri_to_c/1', 'dout/1');\nadd_line(blk, 'sync/1', 'adder_tree1/1');\nadd_line(blk, 'sync/1', 'adder_tree2/1');\n%add_line(blk, 'adder_tree1/1', 'sync_out/1');\nadd_line(blk, 'adder_tree1/1', 'delay_convert/1');\nadd_line(blk, 'delay_convert/1', 'sync_out/1');\n\nfor p=0:total_taps-1,\n for q=1:2,\n slice_name = ['Slice', num2str(p),'_',num2str(q)];\n reuse_block(blk, slice_name, 'xbsIndex_r4/Slice', ...\n 'mode', 'Upper Bit Location + Width', 'nbits', 'coeff_bits + data_in_bits', ...\n 'base0', 'MSB of Input', 'base1', 'MSB of Input', ...\n 'bit1', num2str(-(2*p+q-1)*(coeff_bits + data_in_bits)), 'Position', [70 50*p+25*q+116 115 50*p+25*q+128]);\n add_line(blk, 'din/1', [slice_name, '/1']);\n reint_name = ['Reint',num2str(p),'_',num2str(q)];\n if strcmp(debug_mode, 'on'),\n reuse_block(blk, reint_name, 'xbsIndex_r4/Reinterpret', ...\n 'force_arith_type', 'on', 'arith_type', 'Unsigned', ...\n 'force_bin_pt', 'on', 'bin_pt', '0', ...\n 'Position', [130 50*p+25*q+116 160 50*p+25*q+128]);\n else\n reuse_block(blk, reint_name, 'xbsIndex_r4/Reinterpret', ...\n 'force_arith_type', 'on', 'arith_type', 'Signed (2''s comp)', ...\n 'force_bin_pt', 'on', 'bin_pt', 'coeff_bits + data_in_bits - 2', ...\n 'Position', [130 50*p+25*q+116 160 50*p+25*q+128]);\n end\n add_line(blk, [slice_name, '/1'], [reint_name, '/1']);\n add_line(blk, [reint_name, '/1'], ['adder_tree',num2str(q),'/',num2str(p+2)]);\n end\nend\n\n% output data to the matlab workspace in debug mode\nif strcmp(debug_mode, 'on'),\n reuse_block(blk, 'wrkspc', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', 'total_taps * 2', ...\n 'outputWidth', 'coeff_bits + data_in_bits', 'outputBinaryPt', '0', ...\n 'outputArithmeticType', '0', 'outputToWorkspace', 'on', ...\n 'variablePrefix', ['lasttap', num2str(input_num)], 'outputToModelAsWell', 'off', ...\n 'Position', [200 19 250 66]);\n add_line(blk, 'din/1', 'wrkspc/1');\nend\n\nclean_blocks(blk);\n\nfmtstr = sprintf('input(%d), taps(%d), add_lat(%d)', input_num, total_taps, add_latency);\nset_param(blk, 'AttributesFormatString', fmtstr);\nsave_state(blk, 'defaults', defaults, varargin{:});\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "snapshot_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/snapshot_init.m", "size": 15200, "source_encoding": "utf_8", "md5": "dbae83f3bd93988157294d3214a625ab", "text": "% Create a snap block for capturing snapshots in various interesting ways.\n%\n% snapshot_init(blk, varargin)\n%\n% blk = The block to be configured.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% nsamples = size of buffer (2^nsamples)\n% data_width = the data width [8, 16, 32, 64, 128] \n% use_dsp48 = Use DSP48s to implement counters\n% circap = support continual capture after trigger until stop seen\n% offset = support delaying capture for configurable number of samples\n% value = capture value on input port at same time as data capture starts\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Meerkat telescope project %\n% http://www.kat.ac.za %\n% Copyright 2011 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction snapshot_init(blk, varargin)\n\nclog('entering snapshot_init', 'trace');\ncheck_mask_type(blk, 'snapshot');\nmunge_block(blk, varargin{:});\ndefaults = {'storage', 'bram', 'dram_dimm', '1', 'dram_clock', '200', ...\n 'nsamples', 10, 'data_width', '32', 'offset', 'on', ...\n 'circap', 'on', 'value', 'off','use_dsp48', 'on'};\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\nclog('snapshot_init: post same_state', 'trace');\n\nstorage = get_var('storage', 'defaults', defaults, varargin{:});\ndram_dimm = eval(get_var('dram_dimm', 'defaults', defaults, varargin{:}));\ndram_clock = eval(get_var('dram_clock', 'defaults', defaults, varargin{:}));\nnsamples = get_var('nsamples', 'defaults', defaults, varargin{:});\ndata_width = eval(get_var('data_width', 'defaults', defaults, varargin{:})); %value in drop down list\nuse_dsp48 = get_var('use_dsp48', 'defaults', defaults, varargin{:});\ncircap = get_var('circap', 'defaults', defaults, varargin{:});\noffset = get_var('offset', 'defaults', defaults, varargin{:});\nvalue = get_var('value', 'defaults', defaults, varargin{:});\n\n%we double path width and decimate rate for DRAM\nif strcmp(storage,'dram'),\n nsamples = nsamples - 1;\n data_width = 128;\nend\n\nif strcmp(storage,'dram') && ((log2(data_width/8) + nsamples + 1) > 31),\n errordlg('snapshot does not support capture of more than 1Gbytes using DRAM');\nend\n\n% useful constants\nif strcmp(circap,'on'), circ = 1; else circ = 0; end\nif strcmp(offset,'on'), off = 1; else off = 0; end\nif strcmp(value,'on'), val = 1; else val = 0; end\n\ndelete_lines(blk);\n\n% % do the info blocks first\n% reuse_block(blk, 'storage', 'casper_library_misc/info_block', 'info', storage, 'Position', [0,0,50,30]);\n% reuse_block(blk, 'dram_dimm', 'casper_library_misc/info_block', 'info', num2str(dram_dimm), 'Position', [0,0,50,30]);\n% reuse_block(blk, 'dram_clock', 'casper_library_misc/info_block', 'info', num2str(dram_clock), 'Position', [0,0,50,30]);\n% reuse_block(blk, 'length', 'casper_library_misc/info_block', 'info', num2str(pow2(nsamples)), 'Position', [0,0,50,30]);\n% reuse_block(blk, 'data_width', 'casper_library_misc/info_block', 'info', num2str(data_width), 'Position', [0,0,50,30]);\n% reuse_block(blk, 'start_offset', 'casper_library_misc/info_block', 'info', offset, 'Position', [0,0,50,30]);\n% reuse_block(blk, 'circular_capture', 'casper_library_misc/info_block', 'info', circap, 'Position', [0,0,50,30]);\n% reuse_block(blk, 'extra_value', 'casper_library_misc/info_block', 'info', value, 'Position', [0,0,50,30]);\n% reuse_block(blk, 'use_dsp48', 'casper_library_misc/info_block', 'info', use_dsp48, 'Position', [0,0,50,30]);\n\n% basic input ports\nreuse_block(blk, 'din', 'built-in/inport', 'Position', [180 122 210 138], 'Port', '1');\nreuse_block(blk, 'ri', 'xbsIndex_r4/Reinterpret', ...\n 'force_arith_type', 'on', 'arith_type', 'Unsigned', ...\n 'force_bin_pt', 'on', 'bin_pt', '0', ...\n 'Position', [240 122 300 138]); \nadd_line(blk, 'din/1', 'ri/1');\nreuse_block(blk, 'cast', 'xbsIndex_r4/Convert', ...\n 'arith_type', 'Unsigned', 'n_bits', num2str(data_width), ...\n 'bin_pt', '0', 'quantization', 'Truncate', 'overflow', 'Wrap', ...\n 'Position', [335 122 365 138]); \nadd_line(blk, 'ri/1', 'cast/1');\nreuse_block(blk, 'trig', 'built-in/inport', 'Position', [250 202 280 218], 'Port', '3');\nreuse_block(blk, 'we', 'built-in/inport', 'Position', [250 162 280 178], 'Port', '2');\n\n% basic_ctrl\nclog('basic_ctrl block', 'snapshot_init_detailed_trace');\n\nif strcmp(storage,'dram'), \n dram = 'on'; \n word_size = 144;\nelse\n dram = 'off';\n word_size = data_width;\nend\n\nreuse_block(blk, 'basic_ctrl', 'casper_library_scopes/snapshot/basic_ctrl', ...\n 'dram', dram, 'data_width', num2str(word_size), ...\n 'Position', [395 73 455 307]);\nadd_line(blk, 'cast/1', 'basic_ctrl/2');\nadd_line(blk, 'we/1', 'basic_ctrl/3');\nadd_line(blk, 'trig/1', 'basic_ctrl/4');\n\nif circ == 1\n reuse_block(blk, 'stop', 'built-in/inport', 'Position', [250 282 280 298], 'Port', '4');\n add_line(blk, 'stop/1', 'basic_ctrl/6');\nelse\n% constant so that always stop\n reuse_block(blk, 'never', 'xbsIndex_r4/Constant', ...\n 'arith_type', 'Boolean', 'const', '0', 'explicit_period', 'on', 'period', '1', ...\n 'Position', [250 282 280 298]);\n add_line(blk, 'never/1', 'basic_ctrl/6');\nend \n\n% ctrl reg\nreuse_block(blk, 'const0', 'built-in/Constant', 'Value', '0', 'Position', [180 240 200 260]);\nreuse_block(blk, 'ctrl', 'xps_library/software_register', ...\n 'io_dir', 'From Processor', 'arith_types', '0', ...\n 'Position', [215 235 315 265]);\nadd_line(blk, 'const0/1', 'ctrl/1');\nadd_line(blk, 'ctrl/1', 'basic_ctrl/5');\n\n% delay_block\nif off == 1,\n clog('delay block', 'snapshot_init_detailed_trace');\n \n % offset register\n reuse_block(blk, 'const1', 'built-in/Constant', 'Value', '10', 'Position', [180 320 200 340]);\n reuse_block(blk, 'trig_offset', 'xps_library/software_register', ...\n 'io_dir', 'From Processor', 'arith_types', '0', ...\n 'Position', [215 314 315 346]);\n add_line(blk, 'const1/1', 'trig_offset/1');\n\n % block doing delay\n reuse_block(blk, 'delay', 'casper_library_scopes/snapshot/delay', ...\n 'word_size', num2str(data_width/8), 'use_dsp48', use_dsp48, 'Position', [530 66 590 354]);\n\n add_line(blk, 'basic_ctrl/1', 'delay/1'); %vin\n add_line(blk, 'basic_ctrl/2', 'delay/2'); %din\n add_line(blk, 'basic_ctrl/3', 'delay/3'); %we\n add_line(blk, 'basic_ctrl/4', 'delay/4'); %goi\n add_line(blk, 'basic_ctrl/5', 'delay/5'); %stopi \n add_line(blk, 'basic_ctrl/6', 'delay/6'); %init \n add_line(blk, 'trig_offset/1', 'delay/7'); %delay\n\nelse\n % don't really have anything to do if no offset \nend\n\n% stop_gen block\n\nreuse_block(blk, 'g_tr_en_cnt', 'built-in/Terminator', ...\n 'Position', [1030 367 1045 383]);\n\nif circ == 1,\n clog('stop_gen block', 'snapshot_init_detailed_trace');\n\n reuse_block(blk, 'stop_gen', 'casper_library_scopes/snapshot/stop_gen', ...\n 'Position', [650 67 710 403]);\n \n %join with delay or basic_ctrl\n if off == 1, src = 'delay'; else src = 'basic_ctrl'; end \n \n add_line(blk, [src,'/1'], 'stop_gen/1'); %vin\n add_line(blk, [src,'/2'], 'stop_gen/2'); %din\n add_line(blk, [src,'/3'], 'stop_gen/3'); %we\n add_line(blk, [src,'/4'], 'stop_gen/4'); %go\n add_line(blk, [src,'/5'], 'stop_gen/5'); %stop\n add_line(blk, [src,'/6'], 'stop_gen/6'); %init\n \n add_line(blk, 'ctrl/1', 'stop_gen/7'); %circ bit\n\n %tr_en_cnt register \n reuse_block(blk, 'tr_en_cnt', 'xps_library/software_register', ...\n 'io_dir', 'To Processor', 'arith_types', '0', ...\n 'Position', [905 360 1005 390]);\n\n add_line(blk, 'tr_en_cnt/1', 'g_tr_en_cnt/1');\n\nelse\n\nend\n\n%add_gen block\n\n% address counter must be full 32 for circular capture\n% as used to track offset into vector\nif circ == 1,\n as = '32';\nelse\n as = [num2str(nsamples),'+',num2str(log2(data_width/8)),'+1'];\nend\n\n%if using DRAM, write twice per address\nif strcmp(storage,'dram'),\n burst_size = 1;\nelse\n burst_size = 0;\nend\nclog('add_gen block', 'snapshot_init_detailed_trace');\nreuse_block(blk, 'add_gen', 'casper_library_scopes/snapshot/add_gen', ...\n 'nsamples', num2str(nsamples), 'counter_size', as, 'burst_size', num2str(burst_size), ...\n 'increment', num2str(data_width/8), 'use_dsp48', use_dsp48, ...\n 'Position', [770 71 830 404]);\n% join to stop_gen block\nif circ == 1,\n src = 'stop_gen';\n% join add_gen to: delay block\nelseif off == 1, \n src = 'delay';\n% or basic block\nelse\n src = 'basic_ctrl';\nend\n\nadd_line(blk, [src,'/1'], 'add_gen/1'); % vin \nadd_line(blk, [src,'/2'], 'add_gen/2'); % din \nadd_line(blk, [src,'/3'], 'add_gen/3'); % we \nadd_line(blk, [src,'/4'], 'add_gen/4'); % go \nadd_line(blk, [src,'/5'], 'add_gen/5'); % cont \nadd_line(blk, [src,'/6'], 'add_gen/6'); % init \n\n% status registers\nreuse_block(blk, 'status', 'xps_library/software_register', ...\n 'io_dir', 'To Processor', 'arith_types', '0', ...\n 'Position', [905 305 1005 335]);\nadd_line(blk, 'add_gen/5', 'status/1');\nreuse_block(blk, 'gstatus', 'built-in/Terminator', ...\n 'Position', [1030 312 1045 328]);\nadd_line(blk, 'status/1', 'gstatus/1');\n\n%value in \nreuse_block(blk, 'gval', 'built-in/Terminator', ...\n 'Position', [1030 92 1045 108]);\nif val == 1,\n clog('value in', 'snapshot_init_detailed_trace');\n reuse_block(blk, 'vin', 'built-in/inport', 'Position', [180 82 210 98], 'Port', num2str(3+circ+1));\n add_line(blk, 'vin/1', 'basic_ctrl/1');\n\n % register\n reuse_block(blk, 'val', 'xps_library/software_register', ...\n 'io_dir', 'To Processor', 'arith_types', '0', ...\n 'Position', [905 85 1005 115]);\n\n add_line(blk, 'add_gen/1', 'val/1');\n add_line(blk,'val/1', 'gval/1'); \nelse %connect constant and terminate output\n \n reuse_block(blk, 'vin_const', 'xbsIndex_r4/Constant', ...\n 'arith_type', 'Boolean', 'const', '0', 'explicit_period', 'on', 'period', '1', ...\n 'Position', [250 82 280 98]);\n add_line(blk, 'vin_const/1', 'basic_ctrl/1');\n add_line(blk, 'add_gen/1', 'gval/1');\nend\n\nif circ == 1,\n add_line(blk, 'add_gen/6', 'tr_en_cnt/1');\nelse\n add_line(blk, 'add_gen/6', 'g_tr_en_cnt/1');\nend\n\n%storage\nclog('storage', 'snapshot_init_detailed_trace');\nreuse_block(blk, 'add_del', 'xbsIndex_r4/Delay', ...\n 'latency', '1', 'Position', [880 145 905 165]);\nadd_line(blk, 'add_gen/2', 'add_del/1'); %add\nreuse_block(blk, 'dat_del', 'xbsIndex_r4/Delay', ...\n 'latency', '1', 'Position', [880 200 905 220]);\nadd_line(blk, 'add_gen/3', 'dat_del/1'); %data\nreuse_block(blk, 'we_del', 'xbsIndex_r4/Delay', ...\n 'latency', '1', 'Position', [880 255 905 275]);\nadd_line(blk, 'add_gen/4', 'we_del/1'); %we\n\nif strcmp(storage, 'dram'),\n %DRAM block\n reuse_block(blk, 'dram', 'xps_library/dram', ...\n 'dimm', num2str(dram_dimm), 'ip_clock', num2str(dram_clock), ...\n 'disable_tag', 'on', 'use_sniffer', 'on', ...\n 'Position', [1110 108 1190 377]);\n \n %inputs\n reuse_block(blk, 'rst', 'xbsIndex_r4/Constant', ...\n 'arith_type', 'Boolean', 'const', '0', 'explicit_period', 'on', 'period', '1', ...\n 'Position', [1075 112 1090 128]);\n add_line(blk, 'rst/1', 'dram/1');\n add_line(blk, 'add_del/1', 'dram/2');\n add_line(blk, 'dat_del/1', 'dram/3');\n %wr_be\n reuse_block(blk, 'w_all', 'xbsIndex_r4/Constant', ...\n 'arith_type', 'Unsigned', 'const', '2^18-1', ... \n 'n_bits', '18', 'bin_pt', '0', ...\n 'explicit_period', 'on', 'period', '1', ...\n 'Position', [1045 217 1090 233]);\n add_line(blk, 'w_all/1', 'dram/4');\n %RWn\n reuse_block(blk, 'write', 'xbsIndex_r4/Constant', ...\n 'arith_type', 'Unsigned', 'const', '0', ... \n 'n_bits', '1', 'bin_pt', '0', ...\n 'explicit_period', 'on', 'period', '1', ...\n 'Position', [1075 252 1090 268]);\n add_line(blk, 'write/1', 'dram/5');\n %cmd_tag\n reuse_block(blk, 'tag', 'xbsIndex_r4/Constant', ...\n 'arith_type', 'Unsigned', 'const', '0', ... \n 'n_bits', '32', 'bin_pt', '0', ...\n 'explicit_period', 'on', 'period', '1', ...\n 'Position', [1075 287 1090 303]);\n add_line(blk, 'tag/1', 'dram/6');\n %cmd_valid\n add_line(blk, 'we_del/1', 'dram/7');\n %rd_ack\n reuse_block(blk, 'always', 'xbsIndex_r4/Constant', ...\n 'arith_type', 'Boolean', 'const', '1', ... \n 'explicit_period', 'on', 'period', '1', ...\n 'Position', [1075 357 1090 373]);\n add_line(blk, 'always/1', 'dram/8');\n\n %terminate outputs\n reuse_block(blk, 'gcmd_ack', 'built-in/Terminator', ...\n 'Position', [1215 127 1230 143]);\n add_line(blk, 'dram/1', 'gcmd_ack/1');\n reuse_block(blk, 'gdout', 'built-in/Terminator', ...\n 'Position', [1215 182 1230 198]);\n add_line(blk, 'dram/2', 'gdout/1');\n reuse_block(blk, 'grd_tag', 'built-in/Terminator', ...\n 'Position', [1215 237 1230 253]);\n add_line(blk, 'dram/3', 'grd_tag/1');\n reuse_block(blk, 'grd_valid', 'built-in/Terminator', ...\n 'Position', [1215 292 1230 308]);\n add_line(blk, 'dram/4', 'grd_valid/1');\n reuse_block(blk, 'ready', 'built-in/outport', ...\n 'Port', '1', 'Position', [1210 347 1240 363]);\n add_line(blk, 'dram/5', 'ready/1');\n\nelse\n % shared BRAM\n reuse_block(blk, 'bram', 'xps_library/Shared BRAM', ...\n 'data_width', num2str(data_width), 'addr_width', num2str(nsamples), ...\n 'Position', [930 129 1005 291]);\n add_line(blk, 'add_del/1', 'bram/1');\n add_line(blk, 'dat_del/1', 'bram/2');\n add_line(blk, 'we_del/1', 'bram/3');\n\n reuse_block(blk, 'gbram', 'built-in/Terminator', ...\n 'Position', [1030 202 1045 218]);\n add_line(blk, 'bram/1', 'gbram/1');\nend\n\n% When finished drawing blocks and lines, remove all unused blocks.\nclean_blocks(blk);\n\n% Set attribute format string (block annotation)\nannotation=sprintf('');\nset_param(blk,'AttributesFormatString',annotation);\n\nsave_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\nclog('exiting snapshot_init', 'trace');\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "clog.m", "ext": ".m", "path": "mlib_devel-master/casper_library/clog.m", "size": 3044, "source_encoding": "utf_8", "md5": "4263071e799ea029e6fa79f05636e726", "text": "% Output logging information depending on current logging strategy. \n%\n% clog(msg, groups)\n% \n% msg = text msg to display\n% groups = logging group/s\n%\n% All log messages contained in the groups specified by 'casper_log_groups' in your\n% Workspace will be displayed if they are not in 'casper_nolog_groups'. If casper_log_groups \n% is not defined, no log messages will be displayed.\n% \n% Pre-defined groups; \n% 'all': allows all log entries to be displayed \n% '_debug': low-level debugging log entries for specific file\n% 'trace': used to trace flow through files\n% 'error': errors\n% \n% e.g casper_log_groups='trace', casper_nolog_groups={} - only 'trace' messages will be displayed\n% e.g casper_log_groups={'all'}, casper_nolog_groups='trace' - log messages from any group except 'trace' will be dispalyed\n% e.g casper_log_groups={'trace', 'error', 'adder_tree_init_debug'}, casper_nolog_groups = {'snap_init_debug'} - 'trace', 'error' \n% and messages from the 'adder_tree_init_debug' groups will be displayed (where debug messages in 'adder_tree_init.m' are defined \n% as belonging to the 'adder_tree_init_debug' group. 'snap_init_debug' messages will not be displayed however.\n\nfunction clog(msg, groups)\n%default names of workspace log-level related variables\nsys_log_groups_var = 'casper_log_groups';\nsys_nolog_groups_var = 'casper_nolog_groups';\n%sys_log_file_var = 'casper_log_file'; %TODO output to file \n\nif ~isa(groups,'cell'), groups = {groups}; end \n\n% if a log level variable of the specified name does not exist in the base \n% workspace exit immediately\nif evalin('base', ['exist(''',sys_log_groups_var,''')']) == 0 return; end\nsys_log_groups = evalin('base',sys_log_groups_var);\nif ~isa(sys_log_groups,'cell'), sys_log_groups = {sys_log_groups}; end \n\nsys_nolog_groups = {};\nif evalin('base', ['exist(''',sys_nolog_groups_var,''')']) ~= 0,\n sys_nolog_groups = evalin('base',sys_nolog_groups_var);\nend\nif ~isa(sys_nolog_groups,'cell'), sys_nolog_groups = {sys_nolog_groups}; end \n\nloc_all = strmatch('all', sys_log_groups, 'exact');\nex_loc = [];\nloc = [];\n% convert single element into cell array for comparison\n\ngroup_string = [];\nfor n = 1:length(groups),\n group = groups{n}; \n\n %search for log group in log groups to exclude\n ex_loc = strmatch(group, sys_nolog_groups, 'exact');\n %bail out first time we find it in the list to exclude\n if ~isempty(ex_loc) break; end\n \n %search for log group in log groups to display\n if isempty(loc), loc = strmatch(group, sys_log_groups, 'exact'); end\n\n %generate group string as we go\n if n ~= 1, group_string = [group_string, ', ']; end\n group_string = [group_string, group]; \nend\n\n%check message for sanity\nif ~isa(msg,'char'),\n if isa(msg, 'cell') && (length(msg) == 1) && (isa(msg{1}, 'char')),\n msg = msg{1};\n else,\n error('clog: Not passing char arrays as messages');\n return;\n end\nend\n \n%display if found in one of groups to include and not excluded\nif ~(isempty(loc) && isempty(loc_all)) && isempty(ex_loc) , \n disp([group_string,': ',msg]);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_bitgrowth_calcs.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_bitgrowth_calcs.m", "size": 3735, "source_encoding": "utf_8", "md5": "087b16438f49f9e0bcde12f162751474", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [max_gain bit_growth adder_n_bits_out adder_bin_pt_out] = pfb_bitgrowth_calcs(window_type, pfb_bits, total_taps, par_input_bits, bin_scaling, data_bitwidth, coeff_bitwidth)\n\n% Compute the maximum gain through all of the 2^PFBSize sub-filters. This is\n% used to determine how much bit growth is really needed. The gain of each\n% filter is the sum of the absolute values of its coefficients. The maximum of\n% these gains sets the upper bound on bit growth through the pfb_fir. The\n% products, partial sums, and final sum throughout the pfb_fir (including the\n% adder tree) need not accomodate any more bit growth than the absolute maximum\n% gain requires, provided that any \"overflow\" is ignored (i.e. set to \"Wrap\").\n% This works thanks to the wonders of modulo math. Note that the \"gain\" for\n% typical signals will be different (less) than the absolute maximum gain of\n% each filter. For Gaussian noise, the gain of a filter is the square root of\n% the sum of the squares of the coefficients (aka root-sum-squares or RSS).\n\n% Get all coefficients of the pfb_fir in one vector (by passing -1 for the tap index)\nall_coeffs = pfb_coeff_gen_calc(window_type, pfb_bits, total_taps, -1, par_input_bits, 0, bin_scaling, 0, false);\n% Rearrange into matrix with 2^PFBSize rows and TotalTaps columns.\n% Each row contains coefficients for one sub-filter.\nall_filters = reshape(all_coeffs, 2^pfb_bits, total_taps);\n% Compute max gain (make sure it is at least 1).\n% NB: sum rows, not columns!\nmax_gain = max(sum(abs(all_filters), 2));\nif max_gain < 1\n max_gain = 1;\nend\n% Compute bit growth\nbit_growth = nextpow2(max_gain);\n% Compute adder output width and binary point. We know that the adders in the\n% adder tree need to have (bit_growth+1) non-fractional bits to accommodate the\n% maximum gain. The products from the taps will have\n% (BitWidthIn+CoeffBitWidth-2) fractional bits. We will preserve them through\n% the adder tree.\nadder_bin_pt_out = data_bitwidth + coeff_bitwidth - 2;\nadder_n_bits_out = bit_growth + 1 + adder_bin_pt_out;\n\n%end"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "spead_unpack_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/spead_unpack_init.m", "size": 10326, "source_encoding": "utf_8", "md5": "7db1b8f64a2e34c641db60fccf6da3f8", "text": "function spead_unpack_init(block)\n\nfunction rvname = get_port_name(counter)\n if counter == 1,\n rvname = 'hdr_heap_id';\n elseif counter == 2,\n rvname = 'hdr_heap_size';\n elseif counter == 3,\n rvname = 'hdr_heap_offset';\n elseif counter == 4,\n rvname = 'hdr_pkt_len';\n else\n if bitand(header_direct_mask, header_ids(counter)) == 0,\n rvname = ['hdr', num2str(counter), '_', sprintf('0x%04x', header_ids(counter))];\n else\n rvname = ['hdr', num2str(counter), '_', sprintf('0x%04x_DIR', bitand(header_ids(counter), header_direct_mask-1))];\n end\n end\nend\n\nset_param(block, 'LinkStatus', 'inactive');\n\nhdrs = get_param(block, 'header_ids');\nhdrs_ind = get_param(block, 'header_ind_ids');\nspead_msw = eval(get_param(block, 'spead_msw'));\nspead_lsw = eval(get_param(block, 'spead_lsw'));\nheader_width_bits = spead_msw - spead_lsw;\nheader_direct_mask = pow2(header_width_bits-1);\n\n% add a ONE on the MSb for the directly addressed headers\nheader_ids = spead_process_header_string(hdrs);\nheader_ids = [1,2,3,4,header_ids];\nfor ctr = 1 : length(header_ids),\n thisval = header_ids(ctr);\n newval = thisval + header_direct_mask;\n %fprintf('%i - %i -> %i\\n', ctr, header_ids(ctr), newval);\n header_ids(ctr) = newval;\nend\n% add the indirect ones\nheader_ind_ids = spead_process_header_string(hdrs_ind);\nheader_ids = [header_ids, header_ind_ids];\n\ncombine_errors = strcmp(get_param(block, 'combine_errors'), 'on');\ncurrent_consts = find_system(block, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'RegExp' ,'on', 'name', '.*header_const[0-9]');\nnum_headers = length(header_ids);\nif length(current_consts) == num_headers,\n headers_match = true;\n for ctr = 1 : num_headers,\n val = eval(get_param(current_consts{ctr}, 'const'));\n val2 = header_ids(ctr);\n if val ~= val2,\n headers_match = false;\n end\n end\nelse\n headers_match = false;\nend\n\n% has the error option changed?\nerror_or_blk = find_system(block, 'LookUnderMasks', 'all', 'name', 'error_or');\nerror_change = false;\nif (~isempty(error_or_blk) && (combine_errors == 0)) || (isempty(error_or_blk) && (combine_errors == 1)),\n error_change = true;\nend\n\n% everything still the same?\nif (headers_match == true) && (error_change == false),\n return\nend\n\nif num_headers < 5,\n error('Must have at least compulsory headers and data!');\nend\nnum_total_hdrs = num2str(num_headers+1);\ntotal_hdrs_bits = num2str(ceil(log2(num_headers+2)));\nset_param([block, '/num_item_pts'], 'const', num2str(num_headers));\nset_param([block, '/num_headers'], 'const', num_total_hdrs);\nset_param([block, '/num_headers'], 'n_bits', total_hdrs_bits);\nset_param([block, '/hdr_ctr'], 'n_bits', total_hdrs_bits);\ndelay = 1;\n\nshowname = 'off';\n\n% remove existing header blocks and their lines\nheader_blks = find_system(block, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'RegExp' ,'on', 'name', '.*(hdr|header_).*[0-9]');\nfor b = 1 : length(header_blks),\n blk = header_blks{b};\n delete_block_lines(blk);\n delete_block(blk);\nend\n\n% delete some lines that will be remade, possibly from other blocks\nerr_blks = find_system(block, 'LookUnderMasks', 'all', 'RegExp' ,'on', 'name', 'err.*');\nfor b = 1 : length(err_blks),\n blk = err_blks{b};\n delete_block_lines(blk);\nend\n\n% set the size of the error or block\nif combine_errors == 1,\n try delete_block([block, '/err_hdr']); catch eid, end\n try delete_block([block, '/err_pktlen']); catch eid, end\n reuse_block(block, 'error_or', 'xbsIndex_r4/Logical', ...\n 'showname', showname, 'logical_function', 'OR', ...\n 'inputs', num2str(2 + num_headers), ...\n 'Position', [1665, 150 + ((num_headers+1) * 75), 1720, 150 + ((num_headers+1) * 75) + ((num_headers+1) * 10)]);\n reuse_block(block, 'eof_out_from', 'built-in/from', ...\n 'GotoTag', 'eof_out', 'showname', showname, ...\n 'Position', [1665, 220 + ((num_headers+1) * 75), 1720, 234 + ((num_headers+1) * 75)]);\n reuse_block(block, 'error_gate', 'xbsIndex_r4/Logical', ...\n 'showname', showname, 'logical_function', 'AND', ...\n 'inputs', '2', ...\n 'Position', [1760, 150 + ((num_headers+1) * 75), 1800, 190 + ((num_headers+1) * 75)]);\n reuse_block(block, 'error', 'built-in/outport', ...\n 'showname', 'on', 'Port', '5', ...\n 'Position', [1840, 1143, 1880, 1157]);\n add_line(block, 'badpktand/1', 'error_or/1', 'autorouting', 'on');\n add_line(block, 'hdr_chk/1', 'error_or/2', 'autorouting', 'on');\n add_line(block, 'error_or/1', 'error_gate/1', 'autorouting', 'on');\n add_line(block, 'eof_out_from/1', 'error_gate/2', 'autorouting', 'on');\n add_line(block, 'error_gate/1', 'error/1', 'autorouting', 'on');\nelse\n try delete_block([block, '/error_or']); catch eid, end\n try delete_block([block, '/error']); catch eid, end\n try delete_block([block, '/error_gate']); catch eid, end\n reuse_block(block, 'err_pktlen', 'built-in/outport', ...\n 'showname', 'on', 'Port', '6', ...\n 'Position', [1755, 1143, 1785, 1157]);\n reuse_block(block, 'err_hdr', 'built-in/outport', ...\n 'showname', 'on', 'Port', '5', ...\n 'Position', [1755, 1103, 1785, 1123]);\n add_line(block, 'badpktand/1', 'err_pktlen/1', 'autorouting', 'on');\n add_line(block, 'hdr_chk/1', 'err_hdr/1', 'autorouting', 'on');\nend\n\n% draw the blocks\nfor ctr = 1 : num_headers,\n this_ctr = num2str(ctr);\n name_from = ['header_from', this_ctr];\n name_reg = ['header_reg', this_ctr];\n name_delay = ['header_delay', this_ctr];\n name_slice = ['header_slice', this_ctr];\n name_slice2 = ['header_vslice', this_ctr];\n name_relational = ['header_rel', this_ctr];\n name_error = ['err_hdr', this_ctr];\n name_constant = ['header_const', this_ctr];\n name_out = get_port_name(ctr);\n row_y = 70 + (ctr * 75);\n row_x = 1500 - (ctr * 50);\n reuse_block(block, name_from, 'built-in/from', ...\n 'GotoTag', 'hdr_word_change', 'showname', showname, ...\n 'Position', [row_x, row_y + 25, row_x + 10, row_y + 38]);\n reuse_block(block, name_constant, 'xbsIndex_r4/Constant', ...\n 'showname', showname, 'const', num2str(header_ids(ctr)), ...\n 'arith_type', 'Unsigned', 'bin_pt', '0', ...\n 'n_bits', 'spead_msw - spead_lsw', ...\n 'Position', [row_x + 50, row_y + 50, row_x + 100, row_y + 60]);\n reuse_block(block, name_reg, 'xbsIndex_r4/Register', ...\n 'showname', showname, 'en', 'on', ...\n 'Position', [row_x + 50, row_y, row_x + 100, row_y + 40]);\n reuse_block(block, name_delay, 'xbsIndex_r4/Delay', ...\n 'showname', showname, 'Latency', num2str(delay+1), ...\n 'Position', [row_x + 210, row_y, row_x + 230, row_y + 20]);\n reuse_block(block, name_slice2, 'xbsIndex_r4/Slice', ...\n 'showname', showname, 'nbits', 'spead_lsw', ...\n 'mode', 'Lower Bit Location + Width', ...\n 'bit0', '0', ...\n 'Position', [row_x + 150, row_y, row_x + 180, row_y + 20]);\n reuse_block(block, name_slice, 'xbsIndex_r4/Slice', ...\n 'showname', showname, 'nbits', 'spead_msw - spead_lsw', ...\n 'mode', 'Upper Bit Location + Width', ...\n 'bit1', '0', ...\n 'Position', [row_x + 150, row_y + 25, row_x + 180, row_y + 45]);\n reuse_block(block, name_relational, 'xbsIndex_r4/Relational', ...\n 'showname', showname, 'Latency', num2str(delay), ...\n 'mode', 'a!=b', ...\n 'Position', [row_x + 210, row_y + 28, row_x + 230, row_y + 48]);\n if combine_errors == 1,\n try delete_block([block, '/', name_error]); catch eid, end\n outportnum = 5 + ctr;\n else\n reuse_block(block, name_error, 'built-in/outport', ...\n 'showname', 'on', 'Port', num2str(6 + (ctr*2)), ...\n 'Position', [1755, row_y+33, 1785, row_y + 47]);\n outportnum = 6 + (ctr*2) - 1;\n end\n reuse_block(block, name_out, 'built-in/outport', ...\n 'showname', 'on', 'Port', num2str(outportnum), ...\n 'Position', [1755, row_y+3, 1785, row_y + 17]);\nend\n\n% connect them\nfor ctr = 1 : num_headers,\n this_ctr = num2str(ctr);\n name_from = ['header_from', this_ctr];\n name_reg = ['header_reg', this_ctr];\n name_delay = ['header_delay', this_ctr];\n name_slice = ['header_slice', this_ctr];\n name_slice2 = ['header_vslice', this_ctr];\n name_relational = ['header_rel', this_ctr];\n name_error = ['err_hdr', this_ctr];\n name_constant = ['header_const', this_ctr];\n name_out = get_port_name(ctr);\n if ctr == num_headers,\n add_line(block, ['from_gbe_data', '/1'], [name_reg, '/1'], 'autorouting', 'on');\n else\n last_reg = ['header_reg', num2str(ctr+1)];\n add_line(block, [last_reg, '/1'], [name_reg, '/1'], 'autorouting', 'on');\n end\n if ctr == 1,\n add_line(block, [name_reg, '/1'], 'reg_hdr_one/1', 'autorouting', 'on');\n end\n add_line(block, [name_from, '/1'], [name_reg, '/2'], 'autorouting', 'on');\n add_line(block, [name_reg, '/1'], [name_slice, '/1'], 'autorouting', 'on');\n add_line(block, [name_reg, '/1'], [name_slice2, '/1'], 'autorouting', 'on');\n add_line(block, [name_slice, '/1'], [name_relational, '/1'], 'autorouting', 'on');\n add_line(block, [name_slice2, '/1'], [name_delay, '/1'], 'autorouting', 'on');\n add_line(block, [name_constant, '/1'], [name_relational, '/2'], 'autorouting', 'on');\n add_line(block, [name_delay, '/1'], [name_out, '/1'], 'autorouting', 'on');\n if combine_errors == 1,\n add_line(block, [name_relational, '/1'], ['error_or/', num2str(ctr+2)], 'autorouting', 'on');\n else\n add_line(block, [name_relational, '/1'], [name_error, '/1'], 'autorouting', 'on');\n end\n ph = get_param([block, '/', name_delay], 'PortHandles');\n set_param(ph.Outport(1), 'name', name_out);\n ph = get_param([block, '/', name_slice], 'PortHandles');\n set_param(ph.Outport(1), 'name', ['spid', this_ctr]);\n ph = get_param([block, '/', name_relational], 'PortHandles');\n set_param(ph.Outport(1), 'name', ['err', this_ctr]);\n ph = get_param([block, '/', name_constant], 'PortHandles');\n set_param(ph.Outport(1), 'name', ['exp', this_ctr]);\nend\nadd_line(block, 'header_delay4/1', 'check_datalen/2', 'autorouting', 'on');\n\nclean_blocks(block);\n\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "test_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/test_init.m", "size": 3629, "source_encoding": "utf_8", "md5": "f5bef0cc276440735d97b2beb8941a23", "text": "% Run unit tests for a particular library\n%\n% test_init(blk, varargin)\n%\n% blk = The block to be configured.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% tests_location = location of unit tests and test scripts\n% tests_file - The file containing the module components to test\n% test_type = Type of test to run ('all', library 'section', individual 'unit')\n% section = Name of section when testing library subsection or section containing unit\n% block = Name of individual block to run unit tests for\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Karoo Array Telescope Project %\n% www.kat.ac.za %\n% Copyright (C) 2011 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction test_init(blk, varargin)\n clog('entering test_init','trace');\n\n check_mask_type(blk, 'test');\n \n defaults = {'tests_location', '/opt/casper_git_devel/casper_library/Tests', ...\n 'tests_file', 'tester_input.txt', 'test_type', 'unit', ...\n 'subsection', 'Misc', 'block', 'adder_tree', 'stop_first_fail', 'on'};\n \n tests_location = get_var('tests_location', 'defaults', defaults, varargin{:});\n tests_file = get_var('tests_file', 'defaults', defaults, varargin{:});\n test_type = get_var('test_type', 'defaults', defaults, varargin{:});\n subsection = get_var('subsection', 'defaults', defaults, varargin{:});\n block = get_var('block', 'defaults', defaults, varargin{:});\n stop_first_fail = get_var('stop_first_fail', 'defaults', defaults, varargin{:});\n clog('got variables','test_init_detailed_trace');\n\n %make tests folder accessible\n addpath(tests_location);\n clog('added tests_location path','test_init_detailed_trace');\n %may not actually be testing casper_library so unpollute namespace\n close_system('casper_library',0);\n clog('closed casper_library','test_init_detailed_trace');\n\n test_library('tests_file', tests_file, 'test_type', ...\n test_type, 'subsection', subsection, 'block', block, ...\n 'stop_first_fail', stop_first_fail); \n \n %reload casper_library\n load_system('casper_library');\n rmpath(tests_location);\n\n clog('exiting test_init', 'trace');\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_scale_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_scale_init.m", "size": 6194, "source_encoding": "utf_8", "md5": "9514b9bb28ae88fa484ab1feadca7dde", "text": "\nfunction bus_scale_init(blk, varargin)\n\n clog('entering bus_scale_init', 'trace');\n \n defaults = { ...\n 'n_bits_in', [9 9 9 9], 'bin_pt_in', 8 , 'type_in', 1, 'cmplx', 'off', ...\n 'scale_factor', -1, 'misc', 'on', ...\n }; \n \n check_mask_type(blk, 'bus_scale');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 80;\n ypos = 50; yinc = 50;\n\n port_w = 30; port_d = 14;\n bus_expand_w = 50;\n bus_create_w = 50;\n scale_w = 50; scale_d = 60;\n del_w = 30; del_d = 20;\n\n n_bits_in = get_var('n_bits_in', 'defaults', defaults, varargin{:});\n bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:});\n type_in = get_var('type_in', 'defaults', defaults, varargin{:});\n cmplx = get_var('cmplx', 'defaults', defaults, varargin{:});\n scale_factor = get_var('scale_factor', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n \n %default state, do nothing \n if isempty(n_bits_in),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_scale_init','trace');\n error('exiting bus_scale_init');\n return;\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % check input lists for consistency %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n lenbi = length(n_bits_in); lenpi = length(bin_pt_in); lenti = length(type_in); lensf = length(scale_factor);\n i = [lenbi, lenpi, lenti, lensf]; \n unique_i = unique(i);\n compi = unique_i(length(unique_i));\n \n too_many_i = length(unique_i) > 2;\n conflict_i = (length(unique_i) == 2) && (unique_i(1) ~= 1);\n if too_many_i | conflict_i,\n error('conflicting component number for input bus');\n clog('conflicting component number for input bus', 'error');\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % autocomplete input lists where necessary %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n comp = compi;\n\n %replicate items if needed for a input\n n_bits_in = repmat(n_bits_in, 1, compi/lenbi); \n bin_pt_in = repmat(bin_pt_in, 1, compi/lenpi); \n type_in = repmat(type_in, 1, compi/lenti); \n scale_factor = repmat(scale_factor, 1, compi/lensf); \n\n %if complex we need to double down on some of these\n if strcmp(cmplx, 'on'),\n compi = compi*2;\n n_bits_in = reshape([n_bits_in; n_bits_in], 1, compi); \n bin_pt_in = reshape([bin_pt_in; bin_pt_in], 1, compi); \n type_in = reshape([type_in; type_in], 1, compi); \n scale_factor = reshape([scale_factor; scale_factor], 1, compi); \n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % at this point all input, output lists should match %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n clog(['n_bits_in = ',mat2str(n_bits_in)],'bus_scale_init_debug');\n clog(['compi = ',num2str(compi)],'bus_scale_init_debug');\n\n %%%%%%%%%%%%%%%\n % input ports %\n %%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + scale_d*compi/2;\n reuse_block(blk, 'din', 'built-in/inport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + scale_d*compi/2;\n \n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/inport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n end\n xpos = xpos + xinc + port_w/2; \n\n %%%%%%%%%%%%%%\n % bus expand %\n %%%%%%%%%%%%%%\n \n ypos_tmp = ypos + scale_d*compi/2; %reset ypos\n\n outputWidth = mat2str(n_bits_in);\n outputBinaryPt = mat2str(bin_pt_in);\n outputArithmeticType = mat2str(type_in);\n\n reuse_block(blk, 'debus', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', outputWidth, ...\n 'outputBinaryPt', outputBinaryPt, ...\n 'outputArithmeticType', outputArithmeticType, ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-scale_d*compi/2 xpos+bus_expand_w/2 ypos_tmp+scale_d*compi/2]);\n add_line(blk, 'din/1', 'debus/1');\n ypos_tmp = ypos_tmp + scale_d*(compi/2) + yinc;\n xpos = xpos + xinc + bus_expand_w/2;\n\n %%%%%%%%%%%%%%%\n % scale layer %\n %%%%%%%%%%%%%%%\n\n ypos_tmp = ypos; %reset ypos \n\n for index = 1:compi,\n scale_name = ['scale',num2str(index)];\n reuse_block(blk, scale_name, 'xbsIndex_r4/Scale', ...\n 'scale_factor', num2str(scale_factor(index)), ...\n 'Position', [xpos-scale_w/2 ypos_tmp xpos+scale_w/2 ypos_tmp+scale_d-20]);\n ypos_tmp = ypos_tmp + scale_d;\n\n add_line(blk, ['debus/',num2str(index)], [scale_name,'/1']);\n end\n \n %%%%%%%%%%%%%%%%%%%%\n % create bus again %\n %%%%%%%%%%%%%%%%%%%%\n \n ypos_tmp = ypos + scale_d*compi/2;\n xpos = xpos + xinc + bus_expand_w/2;\n\n reuse_block(blk, 'bussify', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(compi), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-scale_d*compi/2 xpos+bus_create_w/2 ypos_tmp+scale_d*compi/2]);\n \n for index = 1:compi,\n add_line(blk, ['scale',num2str(index),'/1'], ['bussify/',num2str(index)]);\n end\n\n %%%%%%%%%%%%%%%%%\n % output port/s %\n %%%%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + scale_d*compi/2;\n xpos = xpos + xinc + bus_create_w/2;\n reuse_block(blk, 'dout', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, ['bussify/1'], ['dout/1']);\n \n ypos_tmp = ypos + yinc + scale_d*compi; \n if strcmp(misc, 'on'),\n reuse_block(blk, 'misco', 'built-in/outport', ...\n 'Port', '2', ... \n 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n\n add_line(blk, 'misci/1', 'misco/1');\n end\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_scale_init','trace');\n\nend %function bus_scale_init\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "check_mask_type.m", "ext": ".m", "path": "mlib_devel-master/casper_library/check_mask_type.m", "size": 2206, "source_encoding": "utf_8", "md5": "1ee2b6b19b40afbf86c7824fa268bc7f", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction check_mask_type(blk,typename)\r\n% Dumps/throws exception if mask type is incorrect.\r\n%\r\n% check_mask_type(blk,typename)\r\n%\r\n% blk - The block to check\r\n% typename - A string which should match blk's MaskType\r\n\r\nmasktype = get_param(blk, 'MaskType');\r\nif ~strcmp(masktype, typename),\r\n ex = MException('casper:MaskTypeMismatch', ...\r\n 'Mask type of selected block (%s) does not match expected type (%s)', ...\r\n masktype, typename);\r\n dump_exception(ex);\r\n throw(ex);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "flatstrcell.m", "ext": ".m", "path": "mlib_devel-master/casper_library/flatstrcell.m", "size": 2188, "source_encoding": "utf_8", "md5": "a900d5e6c6235ce45404221badf18a90", "text": "% Flattens a cell array into a string\r\n%\r\n% flatstrcell(c)\r\n%\r\n% c - The cell to flatten\r\n%\r\n% Recursively iterates through cell array provided, converting contents to\r\n% strings and appending to a new string.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nfunction flat = flatstrcell(c)\r\n flat = '';\r\n for i=1:length(c),\r\n if iscell(c{i}),\r\n flat = [flat, flatstrcell(c{i})];\r\n else\r\n flat = [flat, mat2str(c{i})];\r\n% flat = [flat, tostring(c{i})];\r\n end\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "is_library_block.m", "ext": ".m", "path": "mlib_devel-master/casper_library/is_library_block.m", "size": 1986, "source_encoding": "utf_8", "md5": "f65b1f65fb594f6b2f0ceafe078a6eb8", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction tf=is_library_block(blk)\n% Returns true if blk resides in a block diagram library.\n%\n% tf = is_library_block( blk )\n%\n% blk - The block whose residency is being checked\n%\n% tf = True is blk lives in a block diagram library\n\n tf = strcmp(get_param(bdroot(blk),'BlockDiagramType'),'library');\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "lo_const_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/lo_const_init.m", "size": 3612, "source_encoding": "utf_8", "md5": "e40d8d178b930f56740aa2a7d1cb9758", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% MeerKAT Radio Telescope Project %\n% www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (meerKAT) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction lo_const_init(blk, varargin)\n\n defaults = {};\n check_mask_type(blk, 'lo_const');\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n n_bits = get_var('n_bits','defaults', defaults, varargin{:});\n phase = get_var('phase','defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state in library\n if n_bits == 0,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); \n return; \n end\n\n reuse_block(blk, 'const1', 'xbsIndex_r4/Constant');\n set_param([blk,'/const1'], ...\n 'const', sprintf('-imag(exp(phase*1j))'), ...\n 'n_bits', sprintf('n_bits'), ...\n 'bin_pt', sprintf('n_bits - 1'), ...\n 'explicit_period', sprintf('on'), ...\n 'Position', sprintf('[145 37 205 63]'));\n\n reuse_block(blk, 'const', 'xbsIndex_r4/Constant');\n set_param([blk,'/const'], ...\n 'const', sprintf('real(exp(phase*1j))'), ...\n 'n_bits', sprintf('n_bits'), ...\n 'bin_pt', sprintf('n_bits - 1'), ...\n 'explicit_period', sprintf('on'), ...\n 'Position', sprintf('[145 77 205 103]'));\n\n reuse_block(blk, 'sin', 'built-in/Outport');\n set_param([blk,'/sin'], ...\n 'Port', sprintf('1'), ...\n 'Position', sprintf('[235 48 265 62]'));\n\n reuse_block(blk, 'cos', 'built-in/Outport');\n set_param([blk,'/cos'], ...\n 'Port', sprintf('2'), ...\n 'Position', sprintf('[235 78 265 92]'));\n\n add_line(blk,'const1/1','sin/1', 'autorouting', 'on');\n add_line(blk,'const/1','cos/1', 'autorouting', 'on');\n\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:});\nend % lo_const_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pipeline_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pipeline_init.m", "size": 3154, "source_encoding": "utf_8", "md5": "36aac4cd87d67b2e508b74dbcf594a34", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction pipeline_init(blk, varargin)\n% Initialize and configure the pipeline block.\n%\n% pipeline_init(blk, varargin)\n%\n% blk = The block to configure.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% latency = number of cycles N to delay (z^-N)\n\n% Declare any default values for arguments you might like.\ndefaults = {};\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\n\ncheck_mask_type(blk, 'pipeline');\nmunge_block(blk, varargin{:});\n\nlatency = get_var('latency', 'defaults', defaults, varargin{:});\n\ndelete_lines(blk);\n\nif (latency < 0)\n error('pipeline_init.m: Latency setting must be greater than or equal to 0');\n return;\nend\n\n% Add ports\nreuse_block(blk, 'd', 'built-in/inport', 'Position', [15 48 45 62], 'Port', '1');\nreuse_block(blk, 'q', 'built-in/outport', 'Position', [latency*100+115 48 latency*100+145 62], 'Port', '1');\n\n% Add register blocks\nfor z = 0:latency-1\n reuse_block(blk, ['Register',num2str(z)], 'xbsIndex_r4/Register', ...\n 'en', 'off', ...\n 'Position', [100*z+115 27 100*z+175 83]);\nend\n\n% Connect blocks\nif (latency == 0)\n add_line(blk, 'd/1', 'q/1');\nelse\n for z = 1:latency-1\n add_line(blk, ['Register', num2str(z-1), '/1'], ['Register', num2str(z), '/1']);\n end\n\n add_line(blk, 'd/1', 'Register0/1');\n add_line(blk, ['Register', num2str(latency-1), '/1'], 'q/1');\nend\n\nclean_blocks(blk);\n\nsave_state(blk, 'defaults', defaults, varargin{:});\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get_mask_params.m", "ext": ".m", "path": "mlib_devel-master/casper_library/get_mask_params.m", "size": 1972, "source_encoding": "utf_8", "md5": "cf7a84aeffd958a0789a7f07bb4c8698", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2013 David MacMahon\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Function for building cell array to pass into mask init scripts.\n%\n% Typical usage:\n%\n% params = get_mask_params(gcb);\n% my_mask_init(gcb, params{:});\n\nfunction params = get_mask_params(blk)\n mask_names = get_param(blk, 'MaskNames');\n mask_values = get_param(blk, 'MaskValues');\n params = [mask_names, mask_values]';\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "hashcell.m", "ext": ".m", "path": "mlib_devel-master/casper_library/hashcell.m", "size": 2009, "source_encoding": "utf_8", "md5": "d2ba57dde3c7eea12bc8d3a3ccee1498", "text": "% Compute a hash of a cell\r\n%\r\n% hashcell(c)\r\n%\r\n% c - The cell array to hash\r\n% \r\n% Converts a cell cell array to a text string using flatstrcell and then\r\n% returns a unique hash of that string using hashcode.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006-2007 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nfunction hash = hashcell(c)\r\n val = flatstrcell(c);\r\n hash = hashcode(val);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_constant_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_constant_init.m", "size": 5237, "source_encoding": "utf_8", "md5": "b6de17f1dcdf17a0002432f983c19bc1", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_constant_init(blk, varargin)\n log_group = 'bus_constant_init_debug';\n\n clog('entering bus_constant_init', {log_group, 'trace'});\n defaults = { ...\n 'values', [1 1 1], ...\n 'n_bits', [8 8 1], ...\n 'bin_pts', [7 0 0], ...\n 'types', [1 0 2]};\n \n check_mask_type(blk, 'bus_constant');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end %if\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 80;\n ypos = 50; yinc = 50;\n\n port_w = 30; port_d = 14;\n con_w = 100; con_d = 25;\n bus_create_w = 80;\n\n values = get_var('values', 'defaults', defaults, varargin{:});\n n_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\n bin_pts = get_var('bin_pts', 'defaults', defaults, varargin{:});\n types = get_var('types', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state, do nothing \n if isempty(values),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_constant_init', {log_group, 'trace'});\n return;\n end %if\n\n lenv = length(values); lenb = length(n_bits); lenp = length(bin_pts); lent = length(types);\n in = [lenv, lenb, lenp, lent]; \n\n comps = unique(in);\n %if have more than 2 unique components or have two but one isn't 1\n if ((length(comps) > 2) | (length(comps) == 2 && comps(1) ~= 1)),\n clog('conflicting component sizes',{log_group, 'error'});\n return;\n end %if\n \n comp_in = max(in);\n\n %replicate items if needed for a input\n values = repmat(values, 1, comp_in/lenv);\n n_bits = repmat(n_bits, 1, comp_in/lenb);\n bin_pts = repmat(bin_pts, 1, comp_in/lenp);\n types = repmat(types, 1, comp_in/lent);\n \n len = length(n_bits);\n\n ypos_tmp = ypos + yinc/2;\n xpos = xpos + con_w/2;\n \n %constant layer\n for index = 1:len,\n if types(index) == 0, arith_type = 'Unsigned';\n elseif types(index) == 1, arith_type = 'Signed (2''s comp)';\n elseif types(index) == 2, arith_type = 'Boolean';\n end\n\n reuse_block(blk, ['constant', num2str(index-1)], 'xbsIndex_r4/Constant', ...\n 'const', num2str(values(index)), 'arith_type', arith_type, ...\n 'n_bits', num2str(n_bits(index)), 'bin_pt', num2str(bin_pts(index)), ...\n 'explicit_period', 'on', 'period', '1', ... \n 'Position', [xpos-con_w/2 ypos_tmp-con_d/2 xpos+con_w/2 ypos_tmp+con_d/2]);\n \n ypos_tmp = ypos_tmp + yinc;\n end %for \n\n xpos = xpos + xinc + con_w/2;\n \n %create bus\n ypos_tmp = ypos + yinc*len/2;\n xpos = xpos + bus_create_w/2;\n\n reuse_block(blk, 'bus_create', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(len), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-yinc*len/2 xpos+bus_create_w/2 ypos_tmp+yinc*len/2]);\n \n for index = 0:len-1,\n add_line(blk, ['constant',num2str(index),'/1'], ['bus_create/',num2str(index+1)]);\n end %for\n \n xpos = xpos + xinc + bus_create_w/2;\n\n %output port/s\n xpos = xpos + port_w/2;\n ypos_tmp = ypos + yinc*len/2;\n reuse_block(blk, 'dout', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, ['bus_create/1'], ['dout/1']);\n ypos_tmp = ypos_tmp + yinc + port_d/2; \n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_constant_init', {log_group, 'trace'});\n\nend %function bus_constant_init\n\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "caddsub_dsp48e_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/caddsub_dsp48e_init.m", "size": 6134, "source_encoding": "utf_8", "md5": "dd07d0bc05e92f71a14f45451d1fe57e", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://casper.berkeley.edu %\n% Copyright (C) 2010 William Mallard %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction caddsub_dsp48e_init (blk, varargin)\n% Initialize and configure a cmult_dsp48e block.\n%\n% caddsub_dsp48e_init(blk, varargin)\n%\n% blk = The block to configure.\n% varargin = {'varname', 'value', ...} pairs.\n%\n% Valid varnames:\n% * n_bits_a\n% * bin_pt_a\n% * n_bits_b\n% * bin_pt_b\n% * mode\n\n% Set default vararg values.\ndefaults = { ...\n 'mode', 'Addition', ...\n 'n_bits_a', 18, ...\n 'bin_pt_a', 17, ...\n 'n_bits_b', 8, ...\n 'bin_pt_b', 7, ...\n 'full_precision', 'on', ...\n 'n_bits_c', 19, ...\n 'bin_pt_c', 17, ...\n 'quantization', 'Truncate', ...\n 'overflow', 'Wrap', ...\n 'cast_latency', 0, ...\n};\n\n% Skip init script if mask state has not changed.\nif same_state(blk, 'defaults', defaults, varargin{:}),\n return\nend\n\n% Verify that this is the right mask for the block.\ncheck_mask_type(blk, 'caddsub_dsp48e');\n\n% Disable link if state changes from default.\nmunge_block(blk, varargin{:});\n\n% Retrieve input fields.\nmode = get_var('mode', 'defaults', defaults, varargin{:});\nn_bits_a = get_var('n_bits_a', 'defaults', defaults, varargin{:});\nbin_pt_a = get_var('bin_pt_a', 'defaults', defaults, varargin{:});\nn_bits_b = get_var('n_bits_b', 'defaults', defaults, varargin{:});\nbin_pt_b = get_var('bin_pt_b', 'defaults', defaults, varargin{:});\nfull_precision = get_var('full_precision', 'defaults', defaults, varargin{:});\nn_bits_c = get_var('n_bits_c', 'defaults', defaults, varargin{:});\nbin_pt_c = get_var('bin_pt_c', 'defaults', defaults, varargin{:});\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\noverflow = get_var('overflow', 'defaults', defaults, varargin{:});\ncast_latency = get_var('cast_latency', 'defaults', defaults, varargin{:});\n\n% Validate input fields.\n\nif (n_bits_a < 1),\n errordlg([blk, ': Input ''a'' bit width must be greater than 0.']);\n return\nend\n\nif (n_bits_b < 1),\n errordlg([blk, ': Input ''b'' bit width must be greater than 0.']);\n return\nend\n\nif (bin_pt_a < 0),\n errordlg([blk, ': Input ''a'' binary point must be greater than 0.']);\n return\nend\n\nif (bin_pt_b < 0),\n errordlg([blk, ': Input ''b'' binary point must be greater than 0.']);\n return\nend\n\nif (bin_pt_a > n_bits_a),\n errordlg([blk, ': Input ''a'' binary point cannot exceed bit width.']);\n return\nend\n\nif (bin_pt_b > n_bits_b),\n errordlg([blk, ': Input ''b'' binary point cannot exceed bit width.']);\n return\nend\n\n% Calculate bit widths and binary points.\n\nmax_non_frac = max(n_bits_a - bin_pt_a, n_bits_b - bin_pt_b);\nmax_bin_pt = max(bin_pt_a, bin_pt_b);\nbin_pt_tmp = 24 - (max_non_frac + 2);\n\nif strcmp(full_precision, 'on'),\n n_bits_out = max_non_frac + max_bin_pt + 1;\n bin_pt_out = max_bin_pt;\nelse,\n n_bits_out = n_bits_c;\n bin_pt_out = bin_pt_c;\nend\n\n% Validate derived values.\n\nif (n_bits_out > 24),\n errordlg([blk, ': Output bit width cannot exceed 24 bits real/imag. ', ...\n 'Current settings require ', num2str(n_bits_out), ' bits.']);\n return\nend\n\n% Update sub-block parameters.\n\nset_param([blk, '/realign_a_re'], ...\n 'bin_pt', num2str(bin_pt_tmp));\nset_param([blk, '/realign_a_im'], ...\n 'bin_pt', num2str(bin_pt_tmp));\nset_param([blk, '/realign_b_re'], ...\n 'bin_pt', num2str(bin_pt_tmp));\nset_param([blk, '/realign_b_im'], ...\n 'bin_pt', num2str(bin_pt_tmp));\n\nif strcmp(mode, 'Addition'),\n set_param([blk, '/alumode'], 'const', '0');\nelseif strcmp(mode, 'Subtraction'),\n set_param([blk, '/alumode'], 'const', '3');\nelse,\n errordlg([blk, ': Invalid add/sub mode.']);\n return\nend\n\nset_param([blk, '/reinterp_c_re'], ...\n 'bin_pt', num2str(bin_pt_tmp));\nset_param([blk, '/reinterp_c_im'], ...\n 'bin_pt', num2str(bin_pt_tmp));\nset_param([blk, '/cast_c_re'], ...\n 'n_bits', num2str(n_bits_out), ...\n 'bin_pt', num2str(bin_pt_out), ...\n 'quantization', quantization, ...\n 'overflow', overflow, ...\n 'latency', num2str(cast_latency));\nset_param([blk, '/cast_c_im'], ...\n 'n_bits', num2str(n_bits_out), ...\n 'bin_pt', num2str(bin_pt_out), ...\n 'quantization', quantization, ...\n 'overflow', overflow, ...\n 'latency', num2str(cast_latency));\n\n% Set attribute format string (block annotation).\nannotation_fmt = '%d_%d + %d_%d ==> %d_%d\\nMode=%s\\nLatency=%d';\nannotation = sprintf(annotation_fmt, ...\n n_bits_a, bin_pt_a, ...\n n_bits_b, bin_pt_b, ...\n n_bits_out, bin_pt_out, ...\n mode, 2+cast_latency);\nset_param(blk, 'AttributesFormatString', annotation);\n\n% Save block state to stop repeated init script runs.\nsave_state(blk, 'defaults', defaults, varargin{:});\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "spead_pack_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/spead_pack_init.m", "size": 9435, "source_encoding": "utf_8", "md5": "c3efe807cd5bd499908d8a2fc5e6d6cc", "text": "function spead_pack_init(block)\n\nfunction rvname = get_port_name(counter)\n if counter == 1,\n rvname = 'hdr_heap_id';\n elseif counter == 2,\n rvname = 'hdr_heap_size';\n elseif counter == 3,\n rvname = 'hdr_heap_offset';\n elseif counter == 4,\n rvname = 'hdr_pkt_len_words';\n else\n if bitand(header_direct_mask, header_ids(counter)) == 0,\n rvname = ['hdr', num2str(counter), '_', sprintf('0x%04x', header_ids(counter))];\n else\n rvname = ['hdr', num2str(counter), '_', sprintf('0x%04x_DIR', bitand(header_ids(counter), header_direct_mask-1))];\n end\n end\nend\n\nset_param(block, 'LinkStatus', 'inactive');\n\nhdrs = get_param(block, 'header_ids');\nhdrs_ind = get_param(block, 'header_ind_ids');\nspead_msw = eval(get_param(block, 'spead_msw'));\nspead_lsw = eval(get_param(block, 'spead_lsw'));\nheader_width_bits = spead_msw - spead_lsw;\nheader_direct_mask = pow2(header_width_bits-1);\n\n% add a ONE on the MSb for the directly addressed headers\nheader_ids = spead_process_header_string(hdrs);\nheader_ids = [1,2,3,4,header_ids];\nfor ctr = 1 : length(header_ids),\n thisval = header_ids(ctr);\n newval = thisval + header_direct_mask;\n %fprintf('%i - %i -> %i\\n', ctr, header_ids(ctr), newval);\n header_ids(ctr) = newval;\nend\n% add the indirect ones\nheader_ind_ids = spead_process_header_string(hdrs_ind);\nheader_ids = [header_ids, header_ind_ids];\n\n\ncurrent_consts = find_system(block, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'RegExp' ,'on', 'name', '.*header_const[0-9]');\nnum_headers = length(header_ids);\nif length(current_consts) == num_headers,\n all_match = true;\n for ctr = 1 : num_headers,\n val = eval(get_param(current_consts{ctr}, 'const'));\n val2 = header_ids(ctr);\n if val ~= val2,\n all_match = false;\n end\n end\nelse\n all_match = false;\nend\n\nif num_headers < 5,\n error('Must have at least compulsory headers and data!');\nend\nnum_total_hdrs = num2str(num_headers+1);\ntotal_hdrs_bits = num2str(ceil(log2(num_headers+2)));\nset_param([block, '/num_item_pts'], 'const', num2str(num_headers));\nset_param([block, '/num_headers'], 'const', num_total_hdrs);\nset_param([block, '/num_headers'], 'n_bits', total_hdrs_bits);\nset_param([block, '/hdr_ctr'], 'cnt_to', num_total_hdrs, 'n_bits', total_hdrs_bits);\nset_param([block, '/delay_data'], 'latency', num_total_hdrs);\nset_param([block, '/delay_valid'], 'latency', num_total_hdrs);\n\n% has the number of bytes per word changed?\npadbits_new = log2(str2double(get_param(block, 'bytes_per_word')));\npadbits_old = str2double(get_param([block, '/header_4const4'], 'n_bits'));\nif padbits_new ~= padbits_old,\n all_match = false;\n %error(sprintf('fack %d %d', padbits_new, padbits_old))\nend\n\n% return if the headers were the same, nothing more to do\nif all_match == true\n return\nend\n\n% remove existing header blocks and their lines\nheader_blks = find_system(block, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'RegExp' ,'on', 'name', '.*(hdr|hdra_|header_).*[0-9]');\nfor b = 1 : length(header_blks),\n blk = header_blks{b};\n delete_block_lines(blk);\n delete_block(blk);\nend\n\n% set the size of the output mux\nset_param([block, '/mainmux'], 'inputs', num2str(2 + num_headers));\nph = get_param([block, '/', 'assert_data'], 'PortHandles');\nline = get_param(ph.Outport(1), 'Line');\nif line > -1,\n delete_line(line);\nend\n\n% draw the blocks\nshowname = 'off';\nfor ctr = 1 : num_headers,\n this_ctr = num2str(ctr);\n name_in = get_port_name(ctr);\n name_assert_in = ['hdra_', this_ctr];\n name_delay_in = ['hdrd_', this_ctr];\n name_to = ['header_to', this_ctr];\n name_constant = ['header_const', this_ctr];\n name_from = ['header_from', this_ctr];\n name_concat = ['header_cat', this_ctr];\n name_assert_id = ['header_assert', this_ctr];\n row_y = 150 + (ctr * 30);\n row_x = 20;\n reuse_block(block, name_in, 'built-in/inport', ...\n 'showname', 'on', 'Port', num2str(3 + ctr), ...\n 'Position', [row_x, row_y, row_x + 30, row_y + 14]);\n reuse_block(block, name_assert_in, 'xbsIndex_r4/Assert', ...\n 'showname', showname, 'assert_type', 'on', ...\n 'type_source', 'Explicitly', 'arith_type', 'Unsigned', ...\n 'bin_pt', '0', 'gui_display_data_type', 'Fixed-point', ...\n 'n_bits', 'spead_lsw', ...\n 'Position', [row_x + 50, row_y, row_x + 80, row_y + 14]);\n% reuse_block(block, name_delay_in, 'xbsIndex_r4/Delay', ...\n% 'showname', 'on', 'latency', num2str(num_headers + 1), ...\n% 'Position', [row_x + 100, row_y, row_x + 120, row_y + 14]);\n reuse_block(block, name_delay_in, 'xbsIndex_r4/Delay', ...\n 'showname', 'on', 'latency', num2str(ctr + 1), ...\n 'Position', [row_x + 100, row_y, row_x + 120, row_y + 14]);\n reuse_block(block, name_to, 'built-in/goto', ...\n 'GotoTag', ['hdr_', this_ctr], 'showname', showname, ...\n 'Position', [row_x + 140, row_y, row_x + 160, row_y + 14]);\n row_y = 150 + (ctr * 75);\n row_x = 1340;\n reuse_block(block, name_constant, 'xbsIndex_r4/Constant', ...\n 'showname', showname, 'const', num2str(header_ids(ctr)), ...\n 'arith_type', 'Unsigned', 'bin_pt', '0', ...\n 'n_bits', 'spead_msw - spead_lsw', ...\n 'Position', [row_x, row_y, row_x + 50, row_y + 14]);\n % the pkt len is a special case, we need to convert it to bytes\n if ctr == 4,\n name_cast = ['header_4cast', this_ctr];\n name_concat2 = ['header_4cat', this_ctr];\n name_const2 = ['header_4const', this_ctr];\n padbits = log2(str2double(get_param(block, 'bytes_per_word')));\n reuse_block(block, name_from, 'built-in/from', ...\n 'GotoTag', ['hdr_', this_ctr], 'showname', showname, ...\n 'Position', [row_x - 145, row_y + 25, row_x - 95, row_y + 39]);\n reuse_block(block, name_cast, 'xbsIndex_r4/Convert', ...\n 'showname', showname, 'arith_type', 'Unsigned', ...\n 'n_bits', ['spead_lsw - ', num2str(padbits)], ...\n 'bin_pt', '0', 'pipeline', 'on', ...\n 'Position', [row_x - 75, row_y + 25, row_x - 25, row_y + 39]);\n reuse_block(block, name_const2, 'xbsIndex_r4/Constant', ...\n 'showname', showname, 'const', '0', ...\n 'arith_type', 'Unsigned', 'bin_pt', '0', ...\n 'n_bits', num2str(padbits), ...\n 'Position', [row_x - 75, row_y + 25 + 14 + 5, row_x - 25, row_y + 25 + 14 + 5 + 14]);\n reuse_block(block, name_concat2, 'xbsIndex_r4/Concat', ...\n 'showname', showname, ...\n 'Position', [row_x, row_y + 25, row_x + 50, row_y + 39 + 14]);\n else\n reuse_block(block, name_from, 'built-in/from', ...\n 'GotoTag', ['hdr_', this_ctr], 'showname', showname, ...\n 'Position', [row_x, row_y + 25, row_x + 50, row_y + 39]);\n end\n reuse_block(block, name_concat, 'xbsIndex_r4/Concat', ...\n 'showname', showname, ...\n 'Position', [row_x + 75, row_y, row_x + 115, row_y + 40]);\n reuse_block(block, name_assert_id, 'xbsIndex_r4/Assert', ...\n 'showname', showname, 'assert_type', 'on', ...\n 'type_source', 'Explicitly', 'arith_type', 'Unsigned', ...\n 'bin_pt', '0', 'gui_display_data_type', 'Fixed-point', ...\n 'n_bits', 'spead_msw', ...\n 'Position', [row_x + 130, row_y, row_x + 160, row_y + 14]);\nend\n\n% connect them\nfor ctr = 1 : num_headers,\n this_ctr = num2str(ctr);\n name_in = get_port_name(ctr);\n name_assert_in = ['hdra_', this_ctr];\n name_delay_in = ['hdrd_', this_ctr];\n name_to = ['header_to', this_ctr];\n name_constant = ['header_const', this_ctr];\n name_from = ['header_from', this_ctr];\n name_concat = ['header_cat', this_ctr];\n name_assert_id = ['header_assert', this_ctr];\n add_line(block, [name_in, '/1'], [name_assert_in, '/1'], 'autorouting', 'on');\n add_line(block, [name_assert_in, '/1'], [name_delay_in, '/1'], 'autorouting', 'on');\n add_line(block, [name_delay_in, '/1'], [name_to, '/1'], 'autorouting', 'on');\n add_line(block, [name_constant, '/1'], [name_concat, '/1'], 'autorouting', 'on');\n if ctr == 4,\n name_cast = ['header_4cast', this_ctr];\n name_concat2 = ['header_4cat', this_ctr];\n name_const2 = ['header_4const', this_ctr];\n add_line(block, [name_from, '/1'], [name_cast, '/1'], 'autorouting', 'on');\n add_line(block, [name_cast, '/1'], [name_concat2, '/1'], 'autorouting', 'on');\n add_line(block, [name_const2, '/1'], [name_concat2, '/2'], 'autorouting', 'on');\n add_line(block, [name_concat2, '/1'], [name_concat, '/2'], 'autorouting', 'on');\n else\n add_line(block, [name_from, '/1'], [name_concat, '/2'], 'autorouting', 'on');\n end\n add_line(block, [name_concat, '/1'], [name_assert_id, '/1'], 'autorouting', 'on');\n add_line(block, [name_assert_id, '/1'], ['mainmux/', num2str(ctr+2)], 'autorouting', 'on');\n ph = get_param([block, '/', name_assert_in], 'PortHandles');\n set_param(ph.Outport(1), 'name', name_in);\n ph = get_param([block, '/', name_constant], 'PortHandles');\n set_param(ph.Outport(1), 'name', ['spid', this_ctr]);\nend\n\nadd_line(block, 'assert_data/1', ['mainmux/', num2str(3 + num_headers)], 'autorouting', 'on');\nph = get_param([block, '/', 'assert_data'], 'PortHandles');\nset_param(ph.Outport(1), 'name', 'pkt_data');\n\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "mixer_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/mixer_init.m", "size": 5274, "source_encoding": "utf_8", "md5": "b01aecded57a35193b273618d271f28b", "text": "% mixer_init(blk, varargin)\r\n%\r\n% blk = The block to initialize.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% freq_div = The (power of 2) denominator of the mixing frequency.\r\n% freq = The numerator of the mixing frequency\r\n% nstreams = The number of parallel streams provided\r\n% n_bits = The bitwidth of samples out\r\n% bram_latency = The latency of sine/cos lookup table\r\n% mult_latency = The latency of mixer multiplier\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction mixer_init(blk, varargin)\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {'n_bits', 8, 'bram_latency', 2, 'mult_latency', 3};\r\ncheck_mask_type(blk, 'mixer');\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nmunge_block(blk, varargin{:});\r\nfreq_div = get_var('freq_div','defaults', defaults, varargin{:});\r\nfreq = get_var('freq','defaults', defaults, varargin{:});\r\nnstreams = get_var('nstreams','defaults', defaults, varargin{:});\r\nn_bits = get_var('n_bits','defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency','defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency','defaults', defaults, varargin{:});\r\n\r\nif nstreams == 0,\r\n delete_lines(blk);\r\n clean_blocks(blk);\r\n set_param(blk,'AttributesFormatString','');\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n return;\r\nend\r\n\r\ncounter_step = mod(nstreams * freq, freq_div);\r\n\r\nif log2(nstreams) ~= round(log2(nstreams)),\r\n error_string = 'The number of inputs must be a positive power of 2 integer';\r\n errordlg(error_string);\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\nreuse_block(blk, 'sync', 'built-in/inport', ...\r\n 'Position', [50 20 80 35], 'Port', '1');\r\nreuse_block(blk, 'delay', 'xbsIndex_r4/Delay', ...\r\n 'latency', num2str(mult_latency), 'Position', [190 20 220 50]);\r\nreuse_block(blk, 'sync_out', 'built-in/outport', ...\r\n 'Position', [250 20 280 35], 'Port', '1');\r\nadd_line(blk, 'sync/1', 'delay/1');\r\nadd_line(blk, 'delay/1', 'sync_out/1');\r\n\r\nreuse_block(blk, 'dds', 'casper_library_downconverter/dds', ...\r\n 'Position', [20 100 80 100+30*nstreams], 'num_lo', num2str(nstreams), 'freq', num2str(freq),...\r\n 'freq_div', num2str(freq_div), 'n_bits', num2str(n_bits), 'latency','2');\r\n\r\nif counter_step ~= 0,\r\n add_line(blk, 'sync/1', 'dds/1')\r\nend\r\n\r\nfor i=1:nstreams,\r\n rcmult = ['rcmult',num2str(i)];\r\n din = ['din',num2str(i)];\r\n real = ['real',num2str(i)];\r\n imag = ['imag',num2str(i)];\r\n reuse_block(blk, din, 'built-in/inport', ...\r\n 'Position', [130 i*80-10 160 5+80*i], 'Port', num2str(i+1));\r\n reuse_block(blk, real, 'built-in/outport', ...\r\n 'Position', [330 i*80-10 360 5+80*i], 'Port', num2str(2*i));\r\n reuse_block(blk, imag, 'built-in/outport', ...\r\n 'Position', [330 i*80+25 360 40+80*i], 'Port', num2str(2*i+1));\r\n reuse_block(blk, rcmult, 'casper_library_downconverter/rcmult', ...\r\n 'Position', [230 i*80-10 280 50+80*i], 'latency', num2str(mult_latency));\r\n add_line(blk,[din,'/1'],[rcmult,'/1']);\r\n add_line(blk,['dds/',num2str(i*2-1)],[rcmult,'/2']);\r\n add_line(blk,['dds/',num2str(i*2)],[rcmult,'/3']);\r\n add_line(blk, [rcmult,'/1'], [real,'/1']);\r\n add_line(blk, [rcmult,'/2'], [imag,'/1']);\r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\n% Set attribute format string (block annotation)\r\nannotation=sprintf('lo at -%d/%d',freq, freq_div);\r\nset_param(blk,'AttributesFormatString',annotation);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "twiddle_general_callback.m", "ext": ".m", "path": "mlib_devel-master/casper_library/twiddle_general_callback.m", "size": 2169, "source_encoding": "utf_8", "md5": "0a9ffa7c12ff0b18463da9b04ee260be", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Meerkat radio telescope project %\n% www.kat.ac.za %\n% Copyright (C) Andrew Martens 2013 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction twiddle_general_callback(blk)\n\n check_mask_type(blk, 'twiddle_general');\n\n mask_names = get_param(blk, 'MaskNames');\n mask_visibs = get_param(blk, 'MaskVisibilities');\n\n use_hdl = get_param(blk,'use_hdl');\n\n if( strcmp(use_hdl,'on')), use_embedded = 'off';\n else, use_embedded = 'on';\n end\n set_param(blk, 'use_embedded', use_embedded);\n mask_visibs{ismember(mask_names,'use_embedded')} = use_embedded;\n\n set_param(blk, 'MaskVisibilities', mask_visibs);\n\nend %function\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "last_tap_async_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/last_tap_async_init.m", "size": 3932, "source_encoding": "utf_8", "md5": "15ca80a0a3975b7caa82a2b0b088e338", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction last_tap_async_init(blk, varargin)\r\n% Initialize and configure the last tap of the Polyphase Filter Bank.\r\n%\r\n% last_tap_async_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% total_taps = Total number of taps in the PFB\r\n% data_in_bits = Input Bitwidth\r\n% data_out_bits = Output Bitwidth\r\n% coeff_bits = Bitwidth of Coefficients.\r\n% add_latency = Latency through each adder.\r\n% mult_latency = Latency through each multiplier\r\n% quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round (unbiased: Even Values)'\r\n% async - Asynchronous mode\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'last_tap_async');\r\nmunge_block(blk, varargin{:});\r\n\r\npropagate_vars([blk,'/pfb_add_tree_async'], 'defaults', defaults, varargin{:});\r\n\r\nuse_hdl = get_var('use_hdl','defaults', defaults, varargin{:});\r\nuse_embedded = get_var('use_embedded','defaults', defaults, varargin{:});\r\ntotal_taps = get_var('total_taps', 'defaults', defaults, varargin{:});\r\ndebug_mode = get_var('debug_mode', 'defaults', defaults, varargin{:});\r\ninput_num = get_var('input_num', 'defaults', defaults, varargin{:});\r\n\r\nif strcmp(debug_mode, 'on'),\r\n set_param([blk,'/split_data'], 'outputWidth', 'data_in_bits', 'outputBinaryPt', '0', 'outputArithmeticType', '0');\r\n set_param([blk,'/interpret_coeff'], 'arith_type', 'Unsigned', 'bin_pt', '0');\r\nelse\r\n set_param([blk,'/split_data'], 'outputWidth', 'data_in_bits', 'outputBinaryPt', 'data_in_bits - 1', 'outputArithmeticType', '1');\r\n set_param([blk,'/interpret_coeff'], 'arith_type', 'Signed (2''s comp)', 'bin_pt', 'coeff_bits - 1');\r\nend\r\n\r\nset_param([blk,'/Mult'], 'use_embedded', use_embedded);\r\nset_param([blk,'/Mult'], 'use_behavioral_HDL', use_hdl);\r\nset_param([blk,'/Mult1'], 'use_embedded', use_embedded);\r\nset_param([blk,'/Mult1'], 'use_behavioral_HDL', use_hdl);\r\n\r\nfmtstr = sprintf('input(%d), tap(%d,%d)', input_num, total_taps, total_taps);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_fir_real_init_old.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_fir_real_init_old.m", "size": 7628, "source_encoding": "utf_8", "md5": "762380f37153b4d1d9b1ea5244879b05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction pfb_fir_real_init(blk, varargin)\r\n% Initialize and configure the Real Polyphase Filter Bank.\r\n%\r\n% pfb_fir_real_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% PFBSize = The size of the PFB\r\n% TotalTaps = Total number of taps in the PFB\r\n% WindowType = The type of windowing function to use.\r\n% n_inputs = The number of parallel inputs\r\n% MakeBiplex = Double up the PFB to feed a biplex FFT\r\n% BitWidthIn = Input Bitwidth\r\n% BitWidthOut = Output Bitwidth\r\n% CoeffBitWidth = Bitwidth of Coefficients.\r\n% CoeffDistMem = Implement coefficients in distributed memory\r\n% add_latency = Latency through each adder.\r\n% mult_latency = Latency through each multiplier\r\n% bram_latency = Latency through each BRAM.\r\n% quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round\r\n% (unbiased: Even Values)'\r\n% fwidth = Scaling of the width of each PFB channel\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'pfb_fir_real');\r\nmunge_block(blk, varargin{:});\r\n\r\nPFBSize = get_var('PFBSize', 'defaults', defaults, varargin{:});\r\nTotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:});\r\nWindowType = get_var('WindowType', 'defaults', defaults, varargin{:});\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\nMakeBiplex = get_var('MakeBiplex', 'defaults', defaults, varargin{:});\r\nBitWidthIn = get_var('BitWidthIn', 'defaults', defaults, varargin{:});\r\nBitWidthOut = get_var('BitWidthOut', 'defaults', defaults, varargin{:});\r\nCoeffBitWidth = get_var('CoeffBitWidth', 'defaults', defaults, varargin{:});\r\nCoeffDistMem = get_var('CoeffDistMem', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\nfwidth = get_var('fwidth', 'defaults', defaults, varargin{:});\r\n\r\nif MakeBiplex, pols = 2;\r\nelse, pols = 1;\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\n% Add ports\r\nportnum = 1;\r\nreuse_block(blk, 'sync', 'built-in/inport', ...\r\n 'Position', [0 50*portnum 30 50*portnum+15], 'Port', num2str(portnum));\r\nreuse_block(blk, 'sync_out', 'built-in/outport', ...\r\n 'Position', [150*(TotalTaps+1) 50*portnum 150*(TotalTaps+1)+30 50*portnum+15], 'Port', num2str(portnum));\r\nfor p=1:pols,\r\n for i=1:2^n_inputs,\r\n portnum = portnum + 1; % Skip one to allow sync & sync_out to be 1\r\n in_name = ['pol',num2str(p),'_in',num2str(i)];\r\n out_name = ['pol',num2str(p),'_out',num2str(i)];\r\n reuse_block(blk, in_name, 'built-in/inport', ...\r\n 'Position', [0 50*portnum 30 50*portnum+15], 'Port', num2str(portnum));\r\n reuse_block(blk, out_name, 'built-in/outport', ...\r\n 'Position', [150*(TotalTaps+1) 50*portnum 150*(TotalTaps+1)+30 50*portnum+15], 'Port', num2str(portnum));\r\n end\r\nend\r\n\r\n% Add Blocks\r\nportnum = 0;\r\nfor p=1:pols,\r\n for i=1:2^n_inputs,\r\n portnum = portnum + 1;\r\n for t=1:TotalTaps,\r\n if t==1,\r\n src_blk = 'casper_library/PFBs/first_tap_real';\r\n name = ['pol',num2str(p),'_in',num2str(i),'_first_tap'];\r\n elseif t==TotalTaps,\r\n src_blk = 'casper_library/PFBs/last_tap_real';\r\n name = ['pol',num2str(p),'_in',num2str(i),'_last_tap'];\r\n else,\r\n src_blk = 'casper_library/PFBs/tap_real';\r\n name = ['pol',num2str(p),'_in',num2str(i),'_tap',num2str(t)];\r\n end\r\n reuse_block(blk, name, src_blk, ...\r\n 'Position', [150*t 50*portnum 150*t+100 50*portnum+30]);\r\n propagate_vars([blk,'/',name],'defaults', defaults, varargin{:});\r\n if t==1,\r\n set_param([blk,'/',name], 'nput', num2str(i-1));\r\n end\r\n end\r\n end\r\nend\r\n\r\n% Add Lines\r\nfor p=1:pols,\r\n for i=1:2^n_inputs,\r\n for t=1:TotalTaps,\r\n in_name = ['pol',num2str(p),'_in',num2str(i)];\r\n out_name = ['pol',num2str(p),'_out',num2str(i)];\r\n if t==1,\r\n blk_name = ['pol',num2str(p),'_in',num2str(i),'_first_tap'];\r\n add_line(blk, [in_name,'/1'], [blk_name,'/1']);\r\n add_line(blk, 'sync/1', [blk_name,'/2']);\r\n elseif t==TotalTaps,\r\n blk_name = ['pol',num2str(p),'_in',num2str(i),'_last_tap'];\r\n if t==2,\r\n prev_blk_name = ['pol',num2str(p),'_in',num2str(i),'_first_tap'];\r\n else,\r\n prev_blk_name = ['pol',num2str(p),'_in',num2str(i),'_tap',num2str(t-1)];\r\n end\r\n for n=1:4, add_line(blk, [prev_blk_name,'/',num2str(n)], [blk_name,'/',num2str(n)]);\r\n end\r\n add_line(blk, [blk_name,'/1'], [out_name,'/1']);\r\n if i==1 && p==1, add_line(blk, [blk_name,'/2'], 'sync_out/1');\r\n end\r\n else,\r\n blk_name = ['pol',num2str(p),'_in',num2str(i),'_tap',num2str(t)];\r\n if t==2,\r\n prev_blk_name = ['pol',num2str(p),'_in',num2str(i),'_first_tap'];\r\n else,\r\n prev_blk_name = ['pol',num2str(p),'_in',num2str(i),'_tap',num2str(t-1)];\r\n end\r\n for n=1:4, add_line(blk, [prev_blk_name,'/',num2str(n)], [blk_name,'/',num2str(n)]);\r\n end\r\n end\r\n end\r\n end\r\nend\r\n\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('taps=%d, add_latency=%d', TotalTaps, add_latency);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bitsnap_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bitsnap_init.m", "size": 11624, "source_encoding": "utf_8", "md5": "44598ef7357819ba2a6ced2f6042edac", "text": "% A wrapped snapshot block\n%\n% bitsnap_init(blk, varargin)\n%\n% blk = The block to be configured.\n% varargin = {'varname', 'value', ...} pairs\n%\n% \n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% % %\n% % Meerkat radio telescope project %\n% % www.kat.ac.za %\n% % Copyright (C) Paul Prozesky 2013 %\n% % %\n% % This program is free software; you can redistribute it and/or modify %\n% % it under the terms of the GNU General Public License as published by %\n% % the Free Software Foundation; either version 2 of the License, or %\n% % (at your option) any later version. %\n% % %\n% % This program is distributed in the hope that it will be useful, %\n% % but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% % GNU General Public License for more details. %\n% % %\n% % You should have received a copy of the GNU General Public License along %\n% % with this program; if not, write to the Free Software Foundation, Inc., %\n% % 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% % %\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \n% Wrap a software_register and specify bit slices to and from the 32-bit\n% register. These will automatically be processed by the toolflow.\n% \nfunction bitsnap_init(blk)\n\n% get values from the mask\nsnap_storage = get_param(blk, 'snap_storage');\nsnap_dram_dimm = eval(get_param(blk, 'snap_dram_dimm'));\nsnap_dram_clock = eval(get_param(blk, 'snap_dram_clock'));\nsnap_nsamples = eval(get_param(blk, 'snap_nsamples'));\nsnap_data_width = eval(get_param(blk, 'snap_data_width'));\nsnap_circap = get_param(blk, 'snap_circap');\nsnap_offset = get_param(blk, 'snap_offset');\nsnap_value = get_param(blk, 'snap_value');\nsnap_use_dsp48 = get_param(blk, 'snap_use_dsp48');\nsnap_delay = eval(get_param(blk, 'snap_delay'));\nio_names = get_param(blk, 'io_names');\nio_widths = eval(get_param(blk, 'io_widths'));\nio_bps = eval(get_param(blk, 'io_bps'));\nio_types = eval(get_param(blk, 'io_types'));\nextra_names = get_param(blk, 'extra_names');\nextra_widths = eval(get_param(blk, 'extra_widths'));\nextra_bps = eval(get_param(blk, 'extra_bps'));\nextra_types = eval(get_param(blk, 'extra_types'));\n\nio_names = textscan(strtrim(strrep(strrep(strrep(strrep(io_names, ']', ''), '[', ''), ',', ' '), ' ', ' ')), '%s');\nio_names = io_names{1};\nextra_names = textscan(strtrim(strrep(strrep(strrep(strrep(extra_names, ']', ''), '[', ''), ',', ' '), ' ', ' ')), '%s');\nextra_names = extra_names{1};\n\n% check lengths and whatnot\nif (numel(io_names) ~= numel(io_widths)) || (numel(io_names) ~= numel(io_bps)) || (numel(io_names) ~= numel(io_types)) || (numel(io_names) < 1),\n error('Lengths of IO fields must match and be >0.');\nend\nnum_ios = numel(io_names);\n% check that the widths of the inputs are not greater than the snap width\nif sum(io_widths) > snap_data_width,\n error('%i-bit wide snapshot chosen, but %i bit inputs specified.', snap_data_width, sum(io_widths));\nend\n% extra vars\nif (numel(extra_names) ~= numel(extra_widths)) || (numel(extra_names) ~= numel(extra_bps)) || (numel(extra_names) ~= numel(extra_types)) || (numel(extra_names) < 1),\n error('Lengths of Extra fields must match and be >0.');\nend\nnum_extras = numel(extra_names);\n\n% check that the widths of the extras are not greater than the extra register width\nif sum(extra_widths) > 32,\n error('%i bit extras specified do not fit into 32-bit wide extra value register.', sum(extra_widths), 32);\nend\n\nmunge_block(blk);\ndelete_lines(blk);\n\n% add the inputs, outputs and gateway out blocks, drawing lines between them\nx_size = 100;\ny_size = 20;\nx_start = 100;\ny_pos = 100;\n\n% the bus create block\nreuse_block(blk, 'buscreate', 'casper_library_flow_control/bus_create', ...\n 'Position', [x_start + (x_size * 2), y_pos + (y_size * (num_ios - 0.5)), x_start + (x_size * 2) + x_size, y_pos + (y_size * (num_ios + 5.5))], ...\n 'inputNum', num2str(num_ios));\n\nif snap_delay > 0,\n %reuse_block(blk, 'io_delay', 'xbsIndex_r4/Delay', 'latency', num2str(snap_delay), 'reg_retiming', 'on', ...\n % 'Position', [x_start + (x_size * 3.5), y_pos - (y_size * 0.5), x_start + (x_size * 3.5) + x_size, y_pos + (y_size * 0.5)]); \n reuse_block(blk, 'io_delay', 'casper_library_delays/pipeline', 'latency', num2str(snap_delay), ...\n 'Position', [x_start + (x_size * 3.5), y_pos - (y_size * 0.5), x_start + (x_size * 3.5) + x_size, y_pos + (y_size * 0.5)]);\nend\n \n% the snapshot block\n%'Position', [x_start + (x_size * 5), y_pos + (y_size * (num_ios - 0.5)), x_start + (x_size * 5) + x_size, y_pos + (y_size * 10)], ...\nreuse_block(blk, 'ss', 'casper_library_scopes/snapshot', ...\n 'storage', snap_storage, ...\n 'dram_dimm', num2str(snap_dram_dimm), ...\n 'dram_clock', num2str(snap_dram_clock), ...\n 'nsamples', num2str(snap_nsamples), ...\n 'data_width', num2str(snap_data_width), ...\n 'offset', snap_offset, ...\n 'circap', snap_circap, ...\n 'value', snap_value, ...\n 'use_dsp48', snap_use_dsp48);\nif snap_delay > 0,\n add_line(blk, 'buscreate/1', 'io_delay/1');\n add_line(blk, 'io_delay/1', 'ss/1');\nelse\n add_line(blk, 'buscreate/1', 'ss/1');\nend\n\nfunction stype = type_to_string(arith_type)\n switch arith_type\n case 0\n stype = 'Unsigned';\n return\n case 1\n stype = 'Signed (2''s comp)';\n return\n case 2\n stype = 'Boolean';\n return\n otherwise\n error('Unknown type %i', arith_type);\n end\nend\n\n% io ports and assert blocks\ny_pos_row = y_pos;\nfor p = 1 : num_ios,\n x_start = 80;\n in_name = sprintf('in_%s', char(io_names(p)));\n assert_name = sprintf('assert_%s', char(io_names(p)));\n if io_types(p) == 2\n gddtype = 'Boolean';\n else\n gddtype = 'Fixed-point';\n end\n reuse_block(blk, in_name, 'built-in/inport', ...\n 'Port', num2str(p), ...\n 'Position', [x_start, y_pos_row, x_start + (x_size/2), y_pos_row + y_size]);\n x_start = x_start + (x_size*1.5);\n reuse_block(blk, assert_name, 'xbsIndex_r4/Assert', ...\n 'showname', 'off', 'assert_type', 'on', ...\n 'type_source', 'Explicitly', 'arith_type', type_to_string(io_types(p)), ...\n 'bin_pt', num2str(io_bps(p)), 'gui_display_data_type', gddtype, ...\n 'n_bits', num2str(io_widths(p)), ...\n 'Position', [x_start, y_pos_row, x_start + (x_size/2), y_pos_row + y_size]);\n add_line(blk, [in_name, '/1'], [assert_name, '/1']);\n add_line(blk, [assert_name, '/1'], ['buscreate/', num2str(p)]);\n y_pos_row = y_pos_row + (y_size * 2);\nend\n\n% we\nportnum = num_ios + 1;\nsnapport = 2;\ny1 = 165;\nreuse_block(blk, 'we', 'built-in/inport', ...\n 'Port', num2str(portnum), ...\n 'Position', [485, y1, 535, y1+y_size]);\nif snap_delay > 0,\n reuse_block(blk, 'we_delay', 'casper_library_delays/pipeline', 'latency', num2str(snap_delay), ...\n 'Position', [545, y1, 595, y1+y_size]);\n add_line(blk, 'we/1', 'we_delay/1');\n add_line(blk, 'we_delay/1', ['ss/', num2str(snapport)]);\nelse\n add_line(blk, 'we/1', ['ss/', num2str(snapport)]);\nend\n\n% trigger\nportnum = portnum + 1; y1 = y1 + 50; snapport = snapport + 1;\nreuse_block(blk, 'trig', 'built-in/inport', ...\n 'Port', num2str(portnum), ...\n 'Position', [485, y1, 535, y1+y_size]);\nif snap_delay > 0,\n reuse_block(blk, 'trig_delay', 'casper_library_delays/pipeline', 'latency', num2str(snap_delay), ...\n 'Position', [545, y1, 595, y1+y_size]);\n add_line(blk, 'trig/1', 'trig_delay/1');\n add_line(blk, 'trig_delay/1', ['ss/', num2str(snapport)]);\nelse\n add_line(blk, 'trig/1', ['ss/', num2str(snapport)]);\nend\n\n% stop\nif strcmp(snap_circap, 'on'),\n portnum = portnum + 1; y1 = y1 + 50; snapport = snapport + 1;\n reuse_block(blk, 'stop', 'built-in/inport', ...\n 'Port', num2str(portnum), ...\n 'Position', [485, y1, 535, y1+y_size]);\n if snap_delay > 0,\n reuse_block(blk, 'stop_delay', 'casper_library_delays/pipeline', 'latency', num2str(snap_delay), ...\n 'Position', [545, y1, 595, y1+y_size]);\n add_line(blk, 'stop/1', 'stop_delay/1');\n add_line(blk, 'stop_delay/1', ['ss/', num2str(snapport)]);\n else\n add_line(blk, 'stop/1', ['ss/', num2str(snapport)]);\n end\nend\n\n% extra value\nif strcmp(snap_value, 'on'),\n % buscreate block\n reuse_block(blk, 'extracreate', 'casper_library_flow_control/bus_create', ...\n 'Position', [x_start + (x_size * 1), y_pos + 500 + (y_size * (num_extras - 0.5)), x_start + (x_size * 1) + x_size, y_pos + 500 + (y_size * (num_extras + 5.5))], ...\n 'inputNum', num2str(num_extras));\n if snap_delay > 0,\n reuse_block(blk, 'extra_delay', 'casper_library_delays/pipeline', 'latency', num2str(snap_delay), ...\n 'Position', [x_start + (x_size * 3.5), y_pos + 500 - (y_size * 0.5), x_start + (x_size * 3.5) + x_size, y_pos + 500 + (y_size * 0.5)]);\n end\n snapport = snapport + 1;\n if snap_delay > 0,\n add_line(blk, 'extracreate/1', 'extra_delay/1');\n add_line(blk, 'extra_delay/1', ['ss/', num2str(snapport)]);\n else\n add_line(blk, 'extracreate/1', ['ss/', num2str(snapport)]);\n end\n % draw an input port for each field for the extra value\n for p = 1 : num_extras,\n x_start = 100;\n in_name = sprintf('extra_%s', char(extra_names(p)));\n assert_name = sprintf('assextra_%s', char(extra_names(p)));\n if extra_types(p) == 2\n gddtype = 'Boolean';\n else\n gddtype = 'Fixed-point';\n end\n reuse_block(blk, in_name, 'built-in/inport', ...\n 'Port', num2str(p + portnum), ...\n 'Position', [x_start, y_pos_row + 500, x_start + (x_size/2), y_pos_row + 500 + y_size]);\n x_start = x_start + (x_size*1.5);\n reuse_block(blk, assert_name, 'xbsIndex_r4/Assert', ...\n 'showname', 'off', 'assert_type', 'on', ...\n 'type_source', 'Explicitly', 'arith_type', type_to_string(extra_types(p)), ...\n 'bin_pt', num2str(extra_bps(p)), 'gui_display_data_type', gddtype, ...\n 'n_bits', num2str(extra_widths(p)), ...\n 'Position', [x_start, y_pos_row + 500, x_start + (x_size/2), y_pos_row + 500 + y_size]);\n add_line(blk, [in_name, '/1'], [assert_name, '/1']);\n add_line(blk, [assert_name, '/1'], ['extracreate/', num2str(p)]);\n y_pos_row = y_pos_row + (y_size*2.5);\n end\n \nend\n\n% remove unconnected blocks\nclean_blocks(blk);\n\n%save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\nclog('exiting bitsnap_init','trace');\n\n% end of main function\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "hashcode.m", "ext": ".m", "path": "mlib_devel-master/casper_library/hashcode.m", "size": 256, "source_encoding": "utf_8", "md5": "5a84c502ade173420a0c7046a083949d", "text": "%Generates 32-bit hash from character array\r\n%\r\n%hash = hashcode(str)\r\n%\r\n%str = character array\r\n\r\nfunction hash = hashcode(str)\r\n str = uint32(str(:))';\r\n hash = uint32(1234);\r\n for c = str\r\n hash = mod(hash*31 + c, 2^27);\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_async_tap_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_async_tap_init.m", "size": 5403, "source_encoding": "utf_8", "md5": "f143dfbd211110409f57c0c48f541f0b", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction pfb_async_tap_init(blk, varargin)\r\n% Initialize and configure the taps of the asynchronous Polyphase Filter Bank.\r\n%\r\n% pfb_async_tap_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% pfb_bits = The size of the PFB\r\n% coeff_bits = Bitwidth of coefficients.\r\n% total_taps = Total number of taps in the PFB\r\n% data_in_bits = Input bitwidth\r\n% mult_latency = Latency through each multiplier\r\n% bram_latency = Latency through each BRAM.\r\n% simul_bits = The number of parallel inputs\r\n% fwidth = Scaling of the width of each PFB channel\r\n% async = Enable the block to take a valid signal\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'tap_async');\r\nmunge_block(blk, varargin{:});\r\n\r\ntotal_taps = get_var('total_taps', 'defaults', defaults, varargin{:});\r\nthis_tap = get_var('this_tap', 'defaults', defaults, varargin{:});\r\nuse_hdl = get_var('use_hdl','defaults', defaults, varargin{:});\r\nuse_embedded = get_var('use_embedded','defaults', defaults, varargin{:});\r\n%async = get_var('async','defaults', defaults, varargin{:});\r\ndebug_mode = get_var('debug_mode','defaults', defaults, varargin{:});\r\n\r\nif (this_tap == 0) || (this_tap >= total_taps),\r\n error('Tap number must be >0 and <= %d\\n', total_taps)\r\nend\r\n\r\neblk = find_system(blk, 'lookUnderMasks', 'all', 'FollowLinks','on', 'SearchDepth', 1, 'Name', 'taps_in');\r\nif this_tap > 1,\r\n if isempty(eblk),\r\n % delete line from ri_to_c to port\r\n delete_line(blk, 'tapout_delay/1', 'taps_out/1');\r\n % the in port\r\n reuse_block(blk, 'taps_in', 'built-in/inport', ...\r\n 'Position', [35 247 65 263], 'Port', '5');\r\n % concat block\r\n reuse_block(blk, 'tapcat', 'xbsIndex_r4/Concat', ...\r\n 'Position', [985 217 1005 268], 'num_inputs', '2');\r\n % move the out port\r\n reuse_block(blk, 'taps_out', 'built-in/outport', ...\r\n 'Position', [1075 238 1105 252], 'Port', '5');\r\n % line from port to concat\r\n add_line(blk, 'taps_in/1', 'tapcat/2');\r\n % line from ri_to_c to concat\r\n add_line(blk, 'tapout_delay/1', 'tapcat/1');\r\n % line from concat to taps outport\r\n add_line(blk, 'tapcat/1', 'taps_out/1');\r\n end\r\nelse\r\n if ~isempty(eblk),\r\n delete_line(blk, 'taps_in/1', 'tapcat/2');\r\n delete_line(blk, 'tapout_delay/1', 'tapcat/1');\r\n delete_line(blk, 'tapcat/1', 'taps_out/1');\r\n reuse_block(blk, 'taps_out', 'built-in/outport', ...\r\n 'Position', [865 198 895 212], 'Port', '5');\r\n add_line(blk, 'tapout_delay/1', 'taps_out/1');\r\n end\r\nend\r\n\r\nif strcmp(debug_mode, 'on'),\r\n set_param([blk,'/split_data'], 'outputWidth', 'data_in_bits', 'outputBinaryPt', '0', 'outputArithmeticType', '0');\r\n set_param([blk,'/interpret_coeff'], 'arith_type', 'Unsigned', 'bin_pt', '0');\r\nelse\r\n set_param([blk,'/split_data'], 'outputWidth', 'data_in_bits', 'outputBinaryPt', 'data_in_bits - 1', 'outputArithmeticType', '1');\r\n set_param([blk,'/interpret_coeff'], 'arith_type', 'Signed (2''s comp)', 'bin_pt', 'coeff_bits - 1');\r\nend\r\n\r\nset_param([blk,'/Mult'],'use_embedded', use_embedded);\r\nset_param([blk,'/Mult'],'use_behavioral_HDL', use_hdl);\r\nset_param([blk,'/Mult1'],'use_embedded', use_embedded);\r\nset_param([blk,'/Mult1'],'use_behavioral_HDL', use_hdl)\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('tap(%d/%d)', this_tap, total_taps);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "adder_tree_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/adder_tree_init.m", "size": 6049, "source_encoding": "utf_8", "md5": "bd43ca24bfedee8d7e26d9c130ed1ff6", "text": "% Create a tree of adders.\r\n%\r\n% adder_tree_init(blk, varargin)\r\n%\r\n% blk = The block to be configured.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% n_inputs = Number of inputs\r\n% latency = Latency per adder\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction adder_tree_init(blk,varargin)\r\n\r\nclog('entering adder_tree_init', 'trace');\r\ncheck_mask_type(blk, 'adder_tree');\r\n\r\ndefaults = {'n_inputs', 3, 'latency', 1, 'first_stage_hdl', 'off', 'adder_imp', 'Fabric'};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('adder_tree_init: post same_state', 'trace');\r\nmunge_block(blk, varargin{:});\r\n\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\nlatency = get_var('latency', 'defaults', defaults, varargin{:});\r\nfirst_stage_hdl = get_var('first_stage_hdl', 'defaults', defaults, varargin{:});\r\nadder_imp = get_var('adder_imp', 'defaults', defaults, varargin{:});\r\n\r\nhw_selection = adder_imp;\r\n\r\nif strcmp(adder_imp,'on'), \r\n first_stage_hdl = 'on'; \r\nend\r\nif strcmp(adder_imp, 'Behavioral'),\r\n behavioral = 'on';\r\n hw_selection = 'Fabric';\r\nelse, \r\n behavioral = 'off';\r\nend\r\n\r\nstages = ceil(log2(n_inputs));\r\n\r\ndelete_lines(blk);\r\n\r\n% Take care of sync\r\nreuse_block(blk, 'sync', 'built-in/inport', 'Position', [30 10 60 25], 'Port', '1');\r\nreuse_block(blk, 'sync_delay', 'xbsIndex_r4/Delay', ...\r\n 'latency', num2str(stages*latency), 'reg_retiming', 'on', ...\r\n 'Position', [30+50 10 60+50 40]);\r\nreuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [30+(stages+1)*100 10 60+(stages+1)*100 25], ...\r\n 'Port', '1');\r\nadd_line(blk, 'sync/1', 'sync_delay/1');\r\nadd_line(blk, 'sync_delay/1', 'sync_out/1');\r\n\r\n% Take care of adder tree\r\nfor i=1:n_inputs,\r\n reuse_block(blk, ['din',num2str(i)], 'built-in/inport', 'Position', [30 i*40+20 60 35+40*i]);\r\nend\r\nreuse_block(blk, 'dout', 'built-in/outport', 'Position', [30+(stages+1)*100 40 60+(stages+1)*100 55]);\r\n\r\n% If nothing to add, connect in to out\r\nif stages==0\r\n add_line(blk,'din1/1','dout/1');\r\nelse\r\n % Make adder tree\r\n cur_n = n_inputs;\r\n stage = 0;\r\n blk_cnt = 0;\r\n blks = {};\r\n while cur_n > 1,\r\n n_adds = floor(cur_n / 2);\r\n n_dlys = mod(cur_n, 2);\r\n cur_n = n_adds + n_dlys;\r\n prev_blks = blks;\r\n blks = {};\r\n stage = stage + 1;\r\n for j=1:cur_n,\r\n blk_cnt = blk_cnt + 1;\r\n if j <= n_adds,\r\n addr = ['addr',num2str(blk_cnt)];\r\n blks{j} = addr;\r\n reuse_block(blk, addr, 'xbsIndex_r4/AddSub', ...\r\n 'latency', num2str(latency), ...\r\n 'use_behavioral_HDL', behavioral, 'hw_selection', hw_selection, ...\r\n 'pipelined', 'on', 'use_rpm', 'on', ...\r\n 'Position', [30+stage*100 j*80-40 70+stage*100 j*80+20]);\r\n if stage == 1,\r\n\t\t set_param([blk,'/',addr], 'use_behavioral_HDL', first_stage_hdl);\r\n add_line(blk,['din',num2str((j*2-1)),'/1'],[addr,'/1']);\r\n add_line(blk,['din',num2str((j*2)),'/1'],[addr,'/2']);\r\n else,\r\n add_line(blk,[prev_blks{2*j-1},'/1'],[addr,'/1']);\r\n add_line(blk,[prev_blks{2*j},'/1'],[addr,'/2']);\r\n end\r\n else,\r\n dly = ['dly',num2str(blk_cnt)];\r\n blks{j} = dly;\r\n reuse_block(blk, dly, 'xbsIndex_r4/Delay', ...\r\n 'latency', num2str(latency), ...\r\n 'reg_retiming', 'on', ...\r\n 'Position', [30+stage*100 j*80-40 70+stage*100 j*80+20]);\r\n if stage == 1,\r\n add_line(blk,['din',num2str((j*2-1)),'/1'],[dly,'/1']);\r\n else,\r\n add_line(blk,[prev_blks{2*j-1},'/1'],[dly,'/1']);\r\n end\r\n end\r\n end\r\n end\r\n add_line(blk,[blks{1},'/1'],['dout/1']);\r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\n% Set attribute format string (block annotation)\r\nannotation=sprintf('latency %d',stages*latency);\r\nset_param(blk,'AttributesFormatString',annotation);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\r\n\r\nclog('exiting adder_tree_init', 'trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "hilbert_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/hilbert_init.m", "size": 9507, "source_encoding": "utf_8", "md5": "d921e57eac167cbc024af072c883cc91", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKASA %\n% www.kat.ac.za %\n% Copyright (C) Andrew Martens 2013 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction hilbert_init(blk, varargin)\n\n clog('entering hilbert_init', {'trace', 'hilbert_init_debug'});\n\n % Set default vararg values.\n defaults = { ...\n 'n_inputs', 1, ...\n 'BitWidth', 18, ...\n 'bin_pt_in', 'BitWidth-1', ...\n 'add_latency', 1, ...\n 'conv_latency', 1, ...\n 'misc', 'off', ...\n };\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n check_mask_type(blk, 'hilbert');\n munge_block(blk, varargin{:});\n\n % Retrieve values from mask fields.\n n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\n BitWidth = get_var('BitWidth', 'defaults', defaults, varargin{:});\n bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:});\n add_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\n conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default setup for library\n if n_inputs == 0,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:});\n clog('exiting hilbert_init',{'trace','hilbert_init_debug'});\n return;\n end\n\n %\n % input ports\n %\n\n reuse_block(blk, 'a', 'built-in/Inport', 'Port', '1', 'Position', [25 48 55 62]);\n reuse_block(blk, 'b', 'built-in/Inport', 'Port', '2', 'Position', [25 198 55 212]);\n\n %\n % rearrange real and imaginary parts of inputs\n %\n\n reuse_block(blk, 'munge_a', 'casper_library_flow_control/munge', 'Position', [80 37 120 73]);\n reuse_block(blk, 'munge_b', 'casper_library_flow_control/munge', 'Position', [80 187 120 223]);\n \n for name = {'munge_a', 'munge_b'},\n set_param([blk, '/', name{1}], ...\n 'divisions', num2str(2*n_inputs), ...\n 'div_size', mat2str(repmat(BitWidth, 1, 2*n_inputs)), ...\n 'order', mat2str([[0:2:(n_inputs-1)*2],[1:2:(n_inputs-1)*2+1]]));\n end\n\n add_line(blk,'b/1','munge_b/1');\n add_line(blk,'a/1','munge_a/1');\n\n %\n % separate real and imaginary parts\n %\n\n reuse_block(blk, 'bus_expand_a', 'casper_library_flow_control/bus_expand', 'Position', [140 29 190 76]);\n reuse_block(blk, 'bus_expand_b', 'casper_library_flow_control/bus_expand', 'Position', [140 179 190 226]);\n\n for name = {'bus_expand_a', 'bus_expand_b'},\n set_param([blk, '/', name{1}], ...\n 'mode', 'divisions of equal size', ...\n 'outputNum', '2', 'OutputWidth', num2str(BitWidth*n_inputs), ...\n 'outputBinaryPt', '0', 'outputArithmeticType', '0');\n end\n add_line(blk,'munge_a/1','bus_expand_a/1');\n add_line(blk,'munge_b/1','bus_expand_b/1');\n\n %\n % do the addition and subtraction\n %\n\n reuse_block(blk, 'add_even_real', 'casper_library_bus/bus_addsub', 'opmode', '0', 'Position', [255 29 300 76]);\n reuse_block(blk, 'sub_odd_imag', 'casper_library_bus/bus_addsub', 'opmode', '1', 'Position', [255 104 300 151]);\n reuse_block(blk, 'sub_even_imag', 'casper_library_bus/bus_addsub', 'opmode', '1', 'Position', [255 179 300 226]);\n reuse_block(blk, 'add_odd_real', 'casper_library_bus/bus_addsub', 'opmode', '0', 'Position', [255 254 300 301]);\n\n for name = {'add_even_real', 'sub_odd_imag', 'sub_even_imag', 'add_odd_real'};\n set_param([blk,'/',name{1}], ...\n 'n_bits_a', mat2str(repmat(BitWidth, 1, n_inputs)), 'bin_pt_a', num2str(bin_pt_in), 'type_a', '1', ...\n 'n_bits_b', mat2str(repmat(BitWidth, 1, n_inputs)), 'bin_pt_b', num2str(bin_pt_in), 'type_b', '1', ...\n 'n_bits_out', mat2str(repmat(BitWidth+1, 1, n_inputs)), 'bin_pt_out', num2str(bin_pt_in), 'type_out', '1', ...\n 'cmplx', 'off', 'misc', 'off', 'latency', 'add_latency', ...\n 'quantization', '0', 'overflow', '0');\n end\n\n add_line(blk,'bus_expand_a/1','add_even_real/1');\n add_line(blk,'bus_expand_b/1','add_even_real/2');\n add_line(blk,'bus_expand_a/1','sub_odd_imag/2');\n add_line(blk,'bus_expand_b/1','sub_odd_imag/1');\n add_line(blk,'bus_expand_a/2','sub_even_imag/1');\n add_line(blk,'bus_expand_b/2','sub_even_imag/2');\n add_line(blk,'bus_expand_a/2','add_odd_real/1');\n add_line(blk,'bus_expand_b/2','add_odd_real/2');\n \n % \n % join components for common operations\n %\n\n reuse_block(blk, 'Concat', 'xbsIndex_r4/Concat', 'num_inputs', '4', 'Position', [330 20 360 315]);\n add_line(blk,'add_even_real/1','Concat/1');\n add_line(blk,'sub_odd_imag/1','Concat/2');\n add_line(blk,'sub_even_imag/1','Concat/3');\n add_line(blk,'add_odd_real/1','Concat/4');\n\n reuse_block(blk, 'bus_scale', 'casper_library_bus/bus_scale', ...\n 'n_bits_in', mat2str(repmat(BitWidth+1, 1, n_inputs*4)), 'bin_pt_in', 'bin_pt_in', 'type_in', '1', ...\n 'scale_factor', '-1', 'misc', 'off', 'cmplx', 'off', ...\n 'Position', [380 156 420 184]);\n add_line(blk,'Concat/1','bus_scale/1');\n\n reuse_block(blk, 'bus_convert', 'casper_library_bus/bus_convert', ...\n 'n_bits_in', mat2str(repmat(BitWidth+1, 1, n_inputs*4)), 'bin_pt_in', 'bin_pt_in+1', ...\n 'n_bits_out', num2str(BitWidth), 'bin_pt_out', 'bin_pt_in', ...\n 'quantization', '2', 'overflow', '0', ... %TODO Wrap for overflow? \n 'cmplx', 'off', 'of', 'off', 'latency', 'conv_latency', 'misc', 'off', ...\n 'Position', [440 156 480 184]);\n add_line(blk,'bus_scale/1','bus_convert/1');\n\n %\n % separate components so can put in correct place\n %\n\n reuse_block(blk, 'bus_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', ...\n 'outputNum', '4', 'OutputWidth', num2str(BitWidth*n_inputs), ...\n 'outputBinaryPt', '0', 'outputArithmeticType', '0', ...\n 'Position', [505 107 555 233]);\n add_line(blk,'bus_convert/1','bus_expand/1');\n\n reuse_block(blk, 'ri_to_c', 'casper_library_misc/ri_to_c', 'Position', [605 114 645 156]);\n add_line(blk,'bus_expand/3','ri_to_c/2');\n add_line(blk,'bus_expand/1','ri_to_c/1');\n\n reuse_block(blk, 'ri_to_c1', 'casper_library_misc/ri_to_c', 'Position', [605 204 645 246]);\n add_line(blk,'bus_expand/2','ri_to_c1/2');\n add_line(blk,'bus_expand/4','ri_to_c1/1');\n\n %\n % reorder outputs so that real and imaginary parts are interspersed \n %\n\n reuse_block(blk, 'munge_even', 'casper_library_flow_control/munge', ...\n 'Position', [670 117 710 153]);\n\n reuse_block(blk, 'munge_odd', 'casper_library_flow_control/munge', ...\n 'Position', [670 207 710 243]);\n\n for name = {'munge_even', 'munge_odd'},\n set_param([blk, '/', name{1}], ...\n 'divisions', num2str(n_inputs*2), ...\n 'div_size', mat2str(repmat(BitWidth, 1, n_inputs*2)), ...\n 'order', mat2str(reshape([[0:(n_inputs-1)];[n_inputs:(n_inputs*2)-1]], 1, n_inputs*2)));\n end\n add_line(blk,'ri_to_c/1','munge_even/1');\n add_line(blk,'ri_to_c1/1','munge_odd/1');\n\n %\n % output ports\n %\n\n reuse_block(blk, 'even', 'built-in/Outport', ...\n 'Port', sprintf('1'), ...\n 'Position', sprintf('[735 128 765 142]'));\n add_line(blk,'munge_even/1','even/1');\n\n reuse_block(blk, 'odd', 'built-in/Outport', ...\n 'Port', sprintf('2'), ...\n 'Position', sprintf('[735 218 765 232]'));\n add_line(blk,'munge_odd/1','odd/1');\n\n %\n % miscellaneous input\n %\n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/Inport', 'Port', '3', 'Position', [25 348 55 362]);\n\n reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'latency', 'add_latency+conv_latency', 'Position', [380 344 420 366]);\n add_line(blk,'misci/1', 'dmisc/1');\n \n reuse_block(blk, 'misco', 'built-in/Outport', 'Port', '3', 'Position', [735 348 765 362]);\n add_line(blk,'dmisc/1', 'misco/1');\n\n end\n\n\n % Delete all unconnected blocks.\n clean_blocks(blk);\n\n % Save block state to stop repeated init script runs.\n save_state(blk, 'defaults', defaults, varargin{:});\nend % hilbert_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "bus_mult_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/bus_mult_init.m", "size": 19945, "source_encoding": "utf_8", "md5": "5cebaf1b41fe199338001da05207d7b8", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction bus_mult_init(blk, varargin)\n log_group = 'bus_mult_init_debug';\n\n clog('entering bus_mult_init', {log_group, 'trace'});\n \n % Set default vararg values.\n % reg_retiming is not an actual parameter of this block, but it is included\n % in defaults so that same_state will return false for blocks drawn prior to\n % adding reg_retiming='on' to some of the underlying Delay blocks.\n defaults = { ...\n 'n_bits_a', 0, 'bin_pt_a', 4, 'type_a', 1, 'cmplx_a', 'off', ...\n 'n_bits_b', [4], 'bin_pt_b', 3, 'type_b', 1, 'cmplx_b', 'on', ...\n 'n_bits_out', 12 , 'bin_pt_out', 7, 'type_out', 1, ...\n 'overflow', 0, 'quantization', 0, 'misc', 'on', ...\n 'mult_latency', 3, 'add_latency', 1 , 'conv_latency', 1, ...\n 'max_fanout', 2, 'fan_latency', 0, ...\n 'multiplier_implementation', 'behavioral HDL', ...\n 'reg_retiming', 'on', ...\n }; \n \n check_mask_type(blk, 'bus_mult');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n xpos = 50; xinc = 80;\n ypos = 50; yinc = 50;\n\n port_w = 30; port_d = 14;\n rep_w = 50; rep_d = 30;\n bus_expand_w = 50;\n bus_create_w = 50;\n mult_w = 50; mult_d = 60;\n del_w = 30; del_d = 20;\n\n n_bits_a = get_var('n_bits_a', 'defaults', defaults, varargin{:});\n bin_pt_a = get_var('bin_pt_a', 'defaults', defaults, varargin{:});\n type_a = get_var('type_a', 'defaults', defaults, varargin{:});\n cmplx_a = get_var('cmplx_a', 'defaults', defaults, varargin{:});\n n_bits_b = get_var('n_bits_b', 'defaults', defaults, varargin{:});\n bin_pt_b = get_var('bin_pt_b', 'defaults', defaults, varargin{:});\n type_b = get_var('type_b', 'defaults', defaults, varargin{:});\n cmplx_b = get_var('cmplx_b', 'defaults', defaults, varargin{:});\n n_bits_out = get_var('n_bits_out', 'defaults', defaults, varargin{:});\n bin_pt_out = get_var('bin_pt_out', 'defaults', defaults, varargin{:});\n type_out = get_var('type_out', 'defaults', defaults, varargin{:});\n overflow = get_var('overflow', 'defaults', defaults, varargin{:});\n quantization = get_var('quantization', 'defaults', defaults, varargin{:});\n mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\n add_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\n conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\n max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:});\n fan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:});\n misc = get_var('misc', 'defaults', defaults, varargin{:});\n multiplier_implementation = get_var('multiplier_implementation', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state, do nothing \n if (n_bits_a == 0 | n_bits_b == 0),\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting bus_mult_init', {log_group, 'trace'});\n return;\n end\n\n %%%%%%%%%%%%%%%%%%%%%%\n % parameter checking %\n %%%%%%%%%%%%%%%%%%%%%%\n\n if max_fanout < 1,\n clog('Maximum fanout must be 1 or greater', {'error', log_group});\n error('Maximum fanout must be 1 or greater');\n end\n\n %need complex multiplication and will reduce fanout by two automatically\n if strcmp(cmplx_a, 'on') && strcmp(cmplx_b, 'on'), \n dup_latency = fan_latency - 1; \n max_fanout = max_fanout*2;\n else,\n dup_latency = fan_latency;\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % check input lists for consistency %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n lenba = length(n_bits_a); lenpa = length(bin_pt_a); lenta = length(type_a);\n a = [lenba, lenpa, lenta]; \n unique_a = unique(a);\n compa = unique_a(length(unique_a));\n\n lenbb = length(n_bits_b); lenpb = length(bin_pt_b); lentb = length(type_b);\n b = [lenbb, lenpb, lentb]; \n unique_b = unique(b);\n compb = unique_b(length(unique_b));\n\n lenbo = length(n_bits_out); lenpo = length(bin_pt_out); lento = length(type_out); \n lenq = length(quantization); leno = length(overflow);\n o = [lenbo, lenpo, lento, lenq, leno];\n unique_o = unique(o);\n compo = unique_o(length(unique_o));\n\n too_many_a = length(unique_a) > 2;\n conflict_a = (length(unique_a) == 2) && (unique_a(1) ~= 1);\n if too_many_a | conflict_a,\n error('conflicting component number for bus a');\n clog('conflicting component number for bus a', {'error', log_group});\n end\n\n too_many_b = length(unique_b) > 2;\n conflict_b = (length(unique_b) == 2) && (unique_b(1) ~= 1);\n if too_many_b | conflict_b,\n error('conflicting component number for bus b');\n clog('conflicting component number for bus b', {'error', log_group});\n end\n\n too_many_o = length(unique_o) > 2;\n conflict_o = (length(unique_o) == 2) && (unique_o(1) ~= 1);\n if too_many_o | conflict_o,\n error('conflicting component number for output bus');\n clog('conflicting component number for output bus', {'error', log_group});\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % autocomplete input lists where necessary %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n comp = max(compa, compb);\n\n %replicate items if needed for a input\n n_bits_a = repmat(n_bits_a, 1, compa/lenba); \n bin_pt_a = repmat(bin_pt_a, 1, compa/lenpa); \n type_a = repmat(type_a, 1, compa/lenta); \n\n %if complex we need to double down on some of these\n if strcmp(cmplx_a, 'on'),\n if ~strcmp(cmplx_b, 'on'),\n compa = compa*2;\n n_bits_a = reshape([n_bits_a; n_bits_a], 1, compa); \n bin_pt_a = reshape([bin_pt_a; bin_pt_a], 1, compa); \n type_a = reshape([type_a; type_a], 1, compa); \n end \n end\n \n %replicate items if needed for b input\n n_bits_b = repmat(n_bits_b, 1, compb/lenbb); \n bin_pt_b = repmat(bin_pt_b, 1, compb/lenpb);\n type_b = repmat(type_b, 1, compb/lentb);\n \n if strcmp(cmplx_b, 'on'), \n if ~strcmp(cmplx_a, 'on'), %if only one input complex, then double number outputs\n compb = compb*2;\n n_bits_b = reshape([n_bits_b; n_bits_b], 1, compb); \n bin_pt_b = reshape([bin_pt_b; bin_pt_b], 1, compb); \n type_b = reshape([type_b; type_b], 1, compb); \n end\n end\n\n %replicate items if needed for output\n compo = comp;\n n_bits_out = repmat(n_bits_out, 1, comp/lenbo);\n bin_pt_out = repmat(bin_pt_out, 1, comp/lenpo);\n type_out = repmat(type_out, 1, comp/lento);\n overflow = repmat(overflow, 1, comp/leno);\n quantization = repmat(quantization, 1, comp/lenq);\n \n if (strcmp(cmplx_b, 'on') & ~strcmp(cmplx_a, 'on')) || (strcmp(cmplx_a, 'on') & ~strcmp(cmplx_b, 'on')),\n compo = comp*2;\n n_bits_out = reshape([n_bits_out; n_bits_out], 1, compo); \n bin_pt_out = reshape([bin_pt_out; bin_pt_out], 1, compo); \n type_out = reshape([type_out; type_out], 1, compo); \n overflow = reshape([overflow; overflow], 1, compo); \n quantization= reshape([quantization; quantization], 1, compo); \n end\n\n %%%%%%%%%%%%%%%%%%\n % fanout control %\n %%%%%%%%%%%%%%%%%%\n\n fa = compo/compa; fb = compo/compb;\n if strcmp(cmplx_a, 'on'), \n fa = fa*2;\n %if complex, fanout can only be a multiple of 2 (on the conservative side)\n max_fanouta = max(1, floor(max_fanout/2)*2); \n else,\n max_fanouta = max_fanout; \n end\n if strcmp(cmplx_b, 'on'), \n fb = fb*2; \n %if complex, fanout can only be a multiple of 2 (on the conservative side)\n max_fanoutb = max(1, floor(max_fanout/2)*2); \n else\n max_fanoutb = max_fanout; \n end\n dupa = ceil(fa/max_fanouta); dupb = ceil(fb/max_fanoutb);\n\n %change constants to cater for fanout \n compa = compa*dupa; type_a = repmat(type_a, 1, dupa) ;\n n_bits_a = repmat(n_bits_a, 1, dupa); bin_pt_a = repmat(bin_pt_a, 1, dupa); \n\n compb = compb*dupb; type_b = repmat(type_b, 1, dupb) ;\n n_bits_b = repmat(n_bits_b, 1, dupb); bin_pt_b = repmat(bin_pt_b, 1, dupb); \n\n %initial connection vector\n if strcmp(cmplx_b, 'on') && ~strcmp(cmplx_a,'on'), \n a_src = reshape(repmat([1:compa], ceil(compo/compa), 1), 1, ceil(compo/compa)*compa);\n else,\n a_src = repmat([1:compa], 1, ceil(compo/compa));\n end\n \n if strcmp(cmplx_a, 'on') && ~strcmp(cmplx_b,'on'), \n b_src = reshape(repmat([1:compb], ceil(compo/compb), 1), 1, ceil(compo/compb)*compb);\n else,\n b_src = repmat([1:compb], 1, ceil(compo/compb));\n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % at this point all a, b, output lists should match %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n clog(['n_bits_a = ',mat2str(n_bits_a)], log_group);\n clog(['n_bits_b = ',mat2str(n_bits_b)], log_group);\n clog(['n_bits_out = ',mat2str(n_bits_out)], log_group);\n clog(['bin_pt_out = ',mat2str(bin_pt_out)], log_group);\n clog(['type_out = ',mat2str(type_out)], log_group);\n clog(['overflow = ',mat2str(overflow)], log_group);\n clog(['quantization = ',mat2str(quantization)], log_group);\n clog(['duplication factors => a: ',num2str(dupa),' b: ',num2str(dupb)], log_group);\n clog(['compa = ',num2str(compa), ' compb = ',num2str(compb), ' compo = ', num2str(compo)], log_group);\n clog(['connection vector for port a = ',mat2str(a_src)], log_group);\n clog(['connection vector for port b = ',mat2str(b_src)], log_group);\n\n %%%%%%%%%%%%%%%\n % input ports %\n %%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + mult_d*compa/2;\n reuse_block(blk, 'a', 'built-in/inport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + mult_d*(compa/2 + compb/2);\n \n reuse_block(blk, 'b', 'built-in/inport', ...\n 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n ypos_tmp = ypos_tmp + yinc + mult_d*compb/2;\n\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misci', 'built-in/inport', ...\n 'Port', '3', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n end\n xpos = xpos + xinc + port_w/2; \n\n %%%%%%%%%%%%%%%%%%\n % fanout control %\n %%%%%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + mult_d*compa/2;\n\n %replicate busses\n reuse_block(blk, 'repa', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(dupa), 'latency', num2str(max(0, dup_latency)), 'misc', 'off', ... \n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'a/1', 'repa/1'); \n\n ypos_tmp = ypos_tmp + yinc + mult_d*(compa/2 + compb/2);\n \n reuse_block(blk, 'repb', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(dupb), 'latency', num2str(max(0, dup_latency)), 'misc', 'off', ...\n 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]);\n add_line(blk, 'b/1', 'repb/1'); \n \n xpos = xpos + xinc + rep_d;\n\n %%%%%%%%%%%%%%\n % bus expand %\n %%%%%%%%%%%%%%\n \n ypos_tmp = ypos + mult_d*compa/2; %reset ypos\n\n if strcmp(cmplx_a, 'on') && strcmp(cmplx_b, 'on'),\n outputWidth = mat2str(n_bits_a*2);\n outputBinaryPt = mat2str(0*bin_pt_a);\n outputArithmeticType = mat2str(0*type_a); \n else\n outputWidth = mat2str(n_bits_a);\n outputBinaryPt = mat2str(bin_pt_a);\n outputArithmeticType = mat2str(type_a);\n end\n\n reuse_block(blk, 'a_debus', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', outputWidth, ...\n 'outputBinaryPt', outputBinaryPt, ...\n 'outputArithmeticType', outputArithmeticType, ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-mult_d*compa/2 xpos+bus_expand_w/2 ypos_tmp+mult_d*compa/2]);\n add_line(blk, 'repa/1', 'a_debus/1');\n ypos_tmp = ypos_tmp + mult_d*(compa/2+compb/2) + yinc;\n \n if strcmp(cmplx_a, 'on') && strcmp(cmplx_b, 'on'),\n outputWidth = mat2str(n_bits_b*2);\n outputBinaryPt = mat2str(0*bin_pt_b);\n outputArithmeticType = mat2str(0*type_b); \n else\n outputWidth = mat2str(n_bits_b);\n outputBinaryPt = mat2str(bin_pt_b);\n outputArithmeticType = mat2str(type_b);\n end\n \n reuse_block(blk, 'b_debus', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of arbitrary size', ...\n 'outputWidth', outputWidth, ...\n 'outputBinaryPt', outputBinaryPt, ...\n 'outputArithmeticType', outputArithmeticType, ...\n 'show_format', 'on', 'outputToWorkspace', 'off', ...\n 'variablePrefix', '', 'outputToModelAsWell', 'on', ...\n 'Position', [xpos-bus_expand_w/2 ypos_tmp-mult_d*compb/2 xpos+bus_expand_w/2 ypos_tmp+mult_d*compb/2]);\n add_line(blk, 'repb/1', 'b_debus/1');\n ypos_tmp = ypos_tmp + mult_d*compa + yinc;\n\n %%%%%%%%%%%%%%%%%%\n % multiplication %\n %%%%%%%%%%%%%%%%%%\n\n xpos = xpos + xinc + mult_w/2; \n ypos_tmp = ypos; %reset ypos \n\n for index = 1:compo,\n clog([num2str(index),': type= ', num2str(type_out(index)), ...\n ' quantization= ', num2str(quantization(index)), ...\n ' overflow= ',num2str(overflow(index))], log_group);\n switch type_out(index),\n case 0,\n arith_type = 'Unsigned';\n case 1,\n arith_type = 'Signed';\n otherwise,\n clog(['unknown arithmetic type ',num2str(arith_type)], {'error', log_group});\n error(['bus_mult_init: unknown arithmetic type ',num2str(arith_type)]);\n end\n switch quantization(index),\n case 0,\n quant = 'Truncate';\n case 1,\n quant = 'Round (unbiased: +/- Inf)';\n end \n switch overflow(index),\n case 0,\n of = 'Wrap';\n case 1,\n of = 'Saturate';\n case 2,\n of = 'Flag as error';\n end \n clog(['output ',num2str(index),': (',num2str(n_bits_out(index)), ' ', ...\n num2str(bin_pt_out(index)),') ', arith_type,' ',quant,' ', of], log_group); \n\n mult_name = ['mult',num2str(index)]; \n clog(['drawing ',mult_name], log_group);\n \n if strcmp(cmplx_a, 'on') && strcmp(cmplx_b, 'on'), %need complex multiplication\n if dup_latency >= 0, in_latency = 1;\n else, in_latency = 0;\n end\n reuse_block(blk, mult_name, 'casper_library_multipliers/cmult', ...\n 'n_bits_a', num2str(n_bits_a(a_src(index))), 'bin_pt_a', num2str(bin_pt_a(a_src(index))), ...\n 'n_bits_b', num2str(n_bits_b(b_src(index))), 'bin_pt_b', num2str(bin_pt_b(b_src(index))), ...\n 'n_bits_ab', num2str(n_bits_out(index)), 'bin_pt_ab', num2str(bin_pt_out(index)), ...\n 'quantization', quant, 'overflow', of, 'conjugated', 'off', ...\n 'multiplier_implementation', multiplier_implementation, ...\n 'in_latency', num2str(in_latency), 'mult_latency', num2str(mult_latency), ... \n 'add_latency', num2str(add_latency), 'conv_latency', num2str(conv_latency), ...\n 'Position', [xpos-mult_w/2 ypos_tmp xpos+mult_w/2 ypos_tmp+mult_d-20] );\n else, \n %standard multiplication \n if strcmp(multiplier_implementation, 'behavioral HDL'),\n use_behavioral_HDL = 'on';\n use_embedded = 'off';\n else\n use_behavioral_HDL = 'off';\n if strcmp(multiplier_implementation, 'embedded multiplier core'),\n use_embedded = 'on';\n elseif strcmp(multiplier_implementation, 'standard core'),\n use_embedded = 'off';\n else,\n end\n end\n reuse_block(blk, mult_name, 'xbsIndex_r4/Mult', ...\n 'latency', 'mult_latency', 'precision', 'User Defined', ...\n 'n_bits', num2str(n_bits_out(index)), 'bin_pt', num2str(bin_pt_out(index)), ... \n 'arith_type', arith_type, 'quantization', quant, 'overflow', of, ... \n 'use_behavioral_HDL', use_behavioral_HDL, 'use_embedded', use_embedded, ...\n 'Position', [xpos-mult_w/2 ypos_tmp xpos+mult_w/2 ypos_tmp+mult_d-20]);\n end\n ypos_tmp = ypos_tmp + mult_d;\n clog(['done'], 'bus_mult_init_debug');\n \n add_line(blk, ['a_debus/',num2str(a_src(index))], [mult_name,'/1']);\n add_line(blk, ['b_debus/',num2str(b_src(index))], [mult_name,'/2']);\n end %for\n\n ypos_tmp = ypos + mult_d*(compb+compa) + 2*yinc;\n if strcmp(misc, 'on'),\n if strcmp(cmplx_a, 'on') && strcmp(cmplx_b, 'on'),\n latency = ['mult_latency+add_latency+conv_latency+fan_latency'];\n else,\n latency = ['mult_latency+fan_latency'];\n end\n\n reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ...\n 'latency', latency, 'reg_retiming', 'on', ...\n 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]);\n add_line(blk, 'misci/1', 'dmisc/1');\n end\n xpos = xpos + xinc + mult_d/2;\n\n %%%%%%%%%%%%%%\n % bus create %\n %%%%%%%%%%%%%%\n\n ypos_tmp = ypos + mult_d*compo/2; %reset ypos\n \n reuse_block(blk, 'a*b_bussify', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(compo), ...\n 'Position', [xpos-bus_create_w/2 ypos_tmp-mult_d*compo/2 xpos+bus_create_w/2 ypos_tmp+mult_d*compo/2]);\n \n for index = 1:compo, add_line(blk, ['mult',num2str(index),'/1'], ['a*b_bussify/',num2str(index)]); end\n\n %%%%%%%%%%%%%%%%%\n % output port/s %\n %%%%%%%%%%%%%%%%%\n\n ypos_tmp = ypos + mult_d*compo/2;\n xpos = xpos + xinc + bus_create_w/2;\n reuse_block(blk, 'a*b', 'built-in/outport', ...\n 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n add_line(blk, ['a*b_bussify/1'], ['a*b/1']);\n ypos_tmp = ypos_tmp + yinc + port_d; \n\n ypos_tmp = ypos + mult_d*(compb+compa) + 2*yinc;\n if strcmp(misc, 'on'),\n reuse_block(blk, 'misco', 'built-in/outport', ...\n 'Port', '2', ... \n 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]);\n\n add_line(blk, 'dmisc/1', 'misco/1');\n end\n \n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('exiting bus_mult_init', {log_group, 'trace'});\n\nend %function bus_mult_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_fir_generic_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_fir_generic_init.m", "size": 16352, "source_encoding": "utf_8", "md5": "562351c87034977aab24580adf1fae25", "text": "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (andrew@ska.ac.za) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction pfb_fir_generic_init(blk, varargin)\n clog('entering pfb_fir_generic_init', 'trace');\n\n defaults = { ...\n 'n_streams', 1, ...\n 'PFBSize', 5, ...\n 'TotalTaps', 4, ...\n 'WindowType', 'hamming', ...\n 'n_inputs', 0, ...\n 'BitWidthIn', 8, ...\n 'BitWidthOut', 18, ...\n 'CoeffBitWidth', 12, ...\n 'complex', 'on', ...\n 'async', 'on', ...\n 'mult_latency', 2, ...\n 'add_latency', 1, ...\n 'bram_latency', 2, ...\n 'fan_latency', 1, ...\n 'conv_latency', 1, ...\n 'quantization', 'Truncate', ...\n 'fwidth', 1, ...\n 'fanout', 4, ...\n 'coeffs_bram_optimization', 'Area', ... %'Speed', 'Area'\n 'delays_bram_optimization', 'Area', ...%'Speed', 'Area'\n };\n \n check_mask_type(blk, 'pfb_fir_generic');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n n_streams = get_var('n_streams', 'defaults', defaults, varargin{:});\n PFBSize = get_var('PFBSize', 'defaults', defaults, varargin{:});\n TotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:});\n WindowType = get_var('WindowType', 'defaults', defaults, varargin{:});\n n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\n complex = get_var('complex', 'defaults', defaults, varargin{:});\n BitWidthIn = get_var('BitWidthIn', 'defaults', defaults, varargin{:});\n BitWidthOut = get_var('BitWidthOut', 'defaults', defaults, varargin{:});\n CoeffBitWidth = get_var('CoeffBitWidth', 'defaults', defaults, varargin{:});\n complex = get_var('complex', 'defaults', defaults, varargin{:});\n async = get_var('async', 'defaults', defaults, varargin{:});\n mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\n add_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\n bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\n fan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:});\n conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\n quantization = get_var('quantization', 'defaults', defaults, varargin{:});\n fwidth = get_var('fwidth', 'defaults', defaults, varargin{:});\n multiplier_implementation = get_var('multiplier_implementation', 'defaults', defaults, varargin{:});\n coeffs_bram_optimization = get_var('coeffs_bram_optimization', 'defaults', defaults, varargin{:});\n delays_bram_optimization = get_var('delays_bram_optimization', 'defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n % default empty block for storage in library\n if TotalTaps == 0,\n clean_blocks(blk);\n set_param(blk, 'AttributesFormatString', '');\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting pfb_fir_generic_init','trace');\n return;\n end\n\n %check parameters\n if TotalTaps < 3,\n clog('need at least 3 taps', {'error', 'pfb_fir_generic_init_debug'});\n error('need at least 3 taps');\n return;\n end\n \n if strcmp(async, 'on') && fan_latency < 1,\n clog('fanout latency must be at least 1 for asynchonrous operation', {'error', 'pfb_fir_generic_init_debug'});\n error('fanout latency must be at least 1 for asynchonrous operation');\n return;\n end\n\n % Compute the maximum gain through all of the 2^PFBSize sub-filters. This is\n % used to determine how much bit growth is really needed. The maximum gain of\n % each filter is the sum of the absolute values of its coefficients. The\n % maximum of these gains sets the upper bound on bit growth through the\n % pfb_fir. The products, partial sums, and final sum throughout the pfb_fir\n % (including the adder tree) need not accomodate any more bit growth than the\n % absolute maximum gain requires, provided that any \"overflow\" is ignored (i.e.\n % set to \"Wrap\"). This works thanks to the wonders of modulo math. Note that\n % the \"gain\" for typical signals will be different (less) than the absolute\n % maximum gain of each filter. For Gaussian noise, the gain of a filter is the\n % square root of the sum of the squares of the coefficients (aka\n % root-sum-squares or RSS).\n\n % Get all coefficients of the pfb_fir in one vector (by passing -1 for a)\n all_coeffs = pfb_coeff_gen_calc(PFBSize, TotalTaps, WindowType, n_inputs, 0, fwidth, -1, false);\n % Rearrange into matrix with 2^PFBSize rows and TotalTaps columns.\n % Each row contains coefficients for one sub-filter.\n all_filters = reshape(all_coeffs, 2^PFBSize, TotalTaps);\n % Compute max gain\n % NB: sum rows, not columns!\n max_gain = max(sum(abs(all_filters), 2));\n % Compute bit growth (make sure it is non-negative)\n bit_growth = max(0, nextpow2(max_gain));\n % Compute adder output width and binary point. We know that the adders in the\n % adder tree need to have (bit_growth+1) non-fractional bits to accommodate the\n % maximum gain. The products from the taps will have\n % (BitWidthIn+CoeffBitWidth-2) fractional bits. We will preserve them through\n % the adder tree.\n adder_bin_pt_out = BitWidthIn + CoeffBitWidth - 2;\n adder_n_bits_out = bit_growth + 1 + adder_bin_pt_out;\n\n %TODO add this optimisation\n\n % If BitWidthOut is 0, set it to accomodate bit growth in the\n % non-fractional part and full-precision of the fractional part.\n if BitWidthOut == 0\n BitWidthOut = adder_n_bits_out;\n end\n\n % input data pipeline\n\n yoff = 115;\n yinc = 40;\n n_inputs_total = n_streams*(2^n_inputs);\n\n reuse_block(blk, 'bus_create', 'casper_library_flow_control/bus_create', ...\n 'inputNum', num2str(n_inputs_total), 'Position', [80 yoff-15 140 yoff+((n_inputs_total-1)*yinc)+15]);\n\n if strcmp(complex, 'on'),\n outputWidth = BitWidthOut*2; outputBinaryPt = 0; outputArithmeticType = 0;\n else\n outputWidth = BitWidthOut; outputBinaryPt = BitWidthOut-1; outputArithmeticType = 1;\n end\n reuse_block(blk, 'bus_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', ...\n 'outputNum', num2str(n_inputs_total), ...\n 'outputWidth', num2str(outputWidth), ...\n 'outputBinaryPt', num2str(outputBinaryPt), ...\n 'outputArithmeticType', num2str(outputArithmeticType), ...\n 'Position', [1020 yoff-15 1100 yoff+((n_inputs_total-1)*yinc)+15]);\n\n % data ports\n\n for stream_index = 0:n_streams-1,\n for port_index = 0:2^n_inputs-1,\n in_port_name = ['pol',num2str(stream_index), '_in', num2str(port_index)];\n port_no = stream_index*2^n_inputs + port_index;\n port_offset = port_index*n_streams + stream_index;\n\n in_position = [0 yoff+(port_offset*yinc)-8 30 yoff+(port_offset*yinc)+8];\n reuse_block(blk, in_port_name, 'built-in/Inport', 'Port', num2str(port_no+1), 'Position', in_position);\n add_line(blk,[in_port_name,'/1'], ['bus_create/',num2str(port_offset+1)]);\n\n out_port_name = ['pol',num2str(stream_index), '_out', num2str(port_index)];\n out_position = [1155 yoff+(port_offset*yinc)-8 1185 yoff+(port_offset*yinc)+8];\n reuse_block(blk, out_port_name, 'built-in/Outport', 'Port', num2str(port_no+1), 'Position', out_position);\n add_line(blk, ['bus_expand/',num2str(port_offset+1)], [out_port_name,'/1']);\n\n end %for n_inputs\n end %for n_streams\n\n % block to generate basic coefficients\n\n reuse_block(blk, 'pfb_fir_coeff_gen', 'casper_library_pfbs/pfb_fir_coeff_gen', ...\n 'pfb_size', num2str(PFBSize), ...\n 'n_taps', num2str(TotalTaps), ...\n 'n_bits_coeff', num2str(CoeffBitWidth), ...\n 'WindowType', WindowType, ...\n 'n_inputs', num2str(n_inputs), ...\n 'fwidth', num2str(fwidth), ...\n 'async', async, ...\n 'bram_latency', num2str(bram_latency), ...\n 'fan_latency', num2str(fan_latency), ...\n 'add_latency', num2str(add_latency), ...\n 'bram_optimization', coeffs_bram_optimization, ...\n 'Position', [285 33 380 197]);\n add_line(blk, 'bus_create/1', 'pfb_fir_coeff_gen/2'); \n\n % replicate coefficients and pack them next to each other\n % also reverse the order of coefficients ...\n n_coeffs = TotalTaps*2^n_inputs;\n output_order = reshape([0:n_coeffs-1], 2^n_inputs, TotalTaps);\n output_order = output_order(:, TotalTaps:-1:1);\n output_order = reshape(repmat(reshape(output_order, 1, n_coeffs), n_streams, 1), 1, n_coeffs*n_streams);\n if strcmp(complex, 'on'), output_order = reshape([output_order; output_order], 1, length(output_order)*2);\n end\n\n reuse_block(blk, 'coeff_munge', 'casper_library_flow_control/munge', ...\n 'divisions', num2str(n_coeffs), ...\n 'div_size', mat2str(repmat(CoeffBitWidth, 1, n_coeffs)), ...\n 'order', mat2str(output_order), ...\n 'arith_type_out', 'Unsigned', ...\n 'bin_pt_out', '0', ...\n 'Position', [500 199 550 231]);\n add_line(blk, 'pfb_fir_coeff_gen/3', 'coeff_munge/1');\n\n reuse_block(blk, 'pfb_fir_taps', 'casper_library_pfbs/pfb_fir_taps', ...\n 'n_streams', num2str(n_streams), ...\n 'n_inputs', num2str(n_inputs), ...\n 'pfb_size', num2str(PFBSize), ...\n 'n_taps', num2str(TotalTaps), ...\n 'n_bits_data', num2str(BitWidthIn), ...\n 'n_bits_coeff', num2str(CoeffBitWidth), ...\n 'bin_pt_coeff', num2str(CoeffBitWidth-1), ...\n 'complex', complex, ...\n 'async', async, ...\n 'mult_latency', num2str(mult_latency), ...\n 'add_latency', num2str(add_latency), ...\n 'bram_latency', num2str(bram_latency), ...\n 'fan_latency', num2str(fan_latency), ...\n 'multiplier_implementation', 'behavioral HDL', ...\n 'bram_optimization', delays_bram_optimization, ...\n 'Position', [675 32 765 198]);\n add_line(blk, 'pfb_fir_coeff_gen/2', 'pfb_fir_taps/2');\n add_line(blk, 'coeff_munge/1', 'pfb_fir_taps/3');\n\n n_outputs_total = n_inputs_total;\n if strcmp(complex, 'on'), \n n_outputs_total = n_outputs_total*2;\n end\n\n reuse_block(blk, 'bus_scale', 'casper_library_bus/bus_scale', ...\n 'n_bits_in', mat2str(repmat(BitWidthIn+CoeffBitWidth+TotalTaps-1, 1, n_outputs_total)), ...\n 'bin_pt_in', num2str(BitWidthIn-1+CoeffBitWidth-1), ...\n 'scale_factor', num2str(-bit_growth), ...\n 'misc', 'off', 'Position', [825 101 865 129]);\n add_line(blk, 'pfb_fir_taps/2', 'bus_scale/1');\n\n if strcmp(quantization, 'Truncate'), quant = 0;\n elseif strcmp(quantization, 'Round (unbiased: +/- Inf)'), quant = 1;\n else quant = 2;\n end\n\n reuse_block(blk, 'bus_convert', 'casper_library_bus/bus_convert', ...\n 'n_bits_in', mat2str(repmat(BitWidthIn+CoeffBitWidth+TotalTaps-1, 1, n_outputs_total)), ...\n 'bin_pt_in', num2str(BitWidthIn-1+CoeffBitWidth-1+bit_growth), ...\n 'n_bits_out', num2str(BitWidthOut), 'bin_pt_out', num2str(BitWidthOut-1), ...\n 'quantization', num2str(quant), 'overflow', '0', ...\\\n 'latency', num2str(conv_latency), 'of', 'off', 'misc', 'off', ...\n 'Position', [920 101 960 129]);\n add_line(blk, 'bus_scale/1', 'bus_convert/1');\n add_line(blk, 'bus_convert/1', 'bus_expand/1');\n\n % sync chain \n\n reuse_block(blk, 'sync', 'built-in/Inport', 'Port', '1', 'Position', [0 52 30 68]);\n add_line(blk, 'sync/1', 'pfb_fir_coeff_gen/1');\n add_line(blk, 'pfb_fir_coeff_gen/1', 'pfb_fir_taps/1');\n\n reuse_block(blk, 'sync_delay','xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'latency', 'conv_latency', 'Position', [925 52 955 68]);\n add_line(blk, 'pfb_fir_taps/1', 'sync_delay/1');\n reuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '1', 'Position', [1155 52 1185 68]);\n add_line(blk, 'sync_delay/1', 'sync_out/1');\n\n % asynchronous infrastructure\n\n yoff = 115;\n if strcmp(async, 'on'),\n reuse_block(blk, 'en', 'built-in/Inport', 'Port', num2str(2+n_inputs_total), ...\n 'Position', [95 yoff+(n_inputs_total*yinc)-8 125 yoff+(n_inputs_total*yinc)+8]);\n add_line(blk, 'en/1', 'pfb_fir_coeff_gen/3');\n add_line(blk, 'pfb_fir_coeff_gen/4', 'pfb_fir_taps/4');\n reuse_block(blk, 'den', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'latency', 'conv_latency', 'Position', [925 162 955 178]);\n add_line(blk, 'pfb_fir_taps/3', 'den/1');\n reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', num2str(2+n_inputs_total), ...\n 'Position', [1035 yoff+(n_inputs_total*yinc)-8 1065 yoff+(n_inputs_total*yinc)+8]);\n add_line(blk, 'den/1', 'dvalid/1');\n end %if async\n\n clean_blocks(blk);\n set_param(blk, 'AttributesFormatString', '');\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting pfb_fir_generic_init','trace');\n\nend % pfb_fir_generic_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_real_add_tree_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_real_add_tree_init.m", "size": 7206, "source_encoding": "utf_8", "md5": "f32400926d004865800cd4799ad96967", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons, Glenn Jones %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction pfb_real_add_tree_init(blk, varargin)\n% Initialize and configure the Real Polyphase Filter Bank final summing tree.\n%\n% pfb_real_add_tree_init(blk, varargin)\n%\n% blk = The block to configure.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% TotalTaps = Total number of taps in the PFB\n% BitWidthIn = Input Bitwidth\n% BitWidthOut = Output Bitwidth\n% CoeffBitWidth = Bitwidth of Coefficients.\n% add_latency = Latency through each adder.\n% quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round\n% (unbiased: Even Values)'\n\n% Declare any default values for arguments you might like.\ndefaults = {};\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\ncheck_mask_type(blk, 'pfb_real_add_tree');\nmunge_block(blk, varargin{:});\n\nTotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:});\nBitWidthIn = get_var('BitWidthIn', 'defaults', defaults, varargin{:});\nBitWidthOut = get_var('BitWidthOut', 'defaults', defaults, varargin{:});\nCoeffBitWidth = get_var('CoeffBitWidth', 'defaults', defaults, varargin{:});\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\n\ndelete_lines(blk);\n\n% Add ports\nreuse_block(blk, 'din', 'built-in/inport', 'Position', [15 123 45 137], 'Port', '1');\nreuse_block(blk, 'sync', 'built-in/inport', 'Position', [15 28 45 42], 'Port', '2');\n%reuse_block(blk, 'dout', 'built-in/outport', 'Position', [500 25*TotalTaps+100 530 25*TotalTaps+115], 'Port', '1');\n%reuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [150 28 180 42], 'Port', '2');\nreuse_block(blk, 'dout', 'built-in/outport', 'Position', [600 25*TotalTaps+100 630 25*TotalTaps+115], 'Port', '1');\nreuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [600 28 630 42], 'Port', '2');\n\n% Add Static Blocks\nreuse_block(blk, 'adder_tree1', 'casper_library_misc/adder_tree', ...\n 'n_inputs', num2str(TotalTaps), 'latency', num2str(add_latency), ...\n 'Position', [200 114 350 50*TotalTaps+114]);\nreuse_block(blk, 'convert1', 'xbsIndex_r4/Convert', ...\n 'arith_type', 'Signed (2''s comp)', 'n_bits', 'BitWidthOut', ...\n 'bin_pt', 'BitWidthOut-1', ...\n 'overflow', 'Saturate', 'latency', 'add_latency', ...\n 'pipeline', 'on', 'quantization', quantization, ...\n 'Position', [500 25*TotalTaps+114 530 25*TotalTaps+128]);\n\n % Delay to compensate for latency of convert blocks\nreuse_block(blk, 'delay1', 'xbsIndex_r4/Delay', ...\n 'latency', num2str(add_latency), ...\n 'Position', [400 50+25*TotalTaps 430 80+25*TotalTaps]);\n % Scale Blocks are required before casting to n_(n-1) format\n % Input to adder tree seemes to be n_(n-2) format\n % each level in the adder tree requires one more shift\n % so with just two taps, there is one level in the adder tree\n % so we would have, eg, 17_14 format, so we need to shift by 2 to get\n % 17_16 which can be converted to 18_17 without overflow.\n % There are nextpow2(TotalTaps) levels in the adder tree.\nscale_factor = 1 + nextpow2(TotalTaps);\nreuse_block(blk, 'scale1', 'xbsIndex_r4/Scale', ...\n 'scale_factor', num2str(-scale_factor), ...\n 'Position', [400 25*TotalTaps+114 430 25*TotalTaps+128]);\nreuse_block(blk, 'scale2', 'xbsIndex_r4/Scale', ...\n 'scale_factor', num2str(-scale_factor), ...\n 'Position', [400 158+25*TotalTaps 430 172+25*TotalTaps]);\n\n% Add lines\n%add_line(blk, 'adder_tree1/2', 'convert1/1');\nadd_line(blk, 'adder_tree1/2', 'scale1/1');\nadd_line(blk, 'scale1/1', 'convert1/1');\nadd_line(blk, 'convert1/1', 'dout/1');\n\n% removed by Andrew as causes errors due to latency not working out to an integer,\n% causing script to fail even though, especially as the block is never used\n\n% %What is this delay block doing here. it looks like it was\n% % the old sync delay circuit\n% reuse_block(blk, 'delay', 'xbsIndex_r4/Delay', ...\n% 'latency', '(log2(TotalTaps)+1)*add_latency', ...\n% 'Position', [80 14 120 56]);\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n\nadd_line(blk, 'sync/1', 'adder_tree1/1');\n%add_line(blk, 'adder_tree1/1', 'sync_out/1');\n\nadd_line(blk, 'adder_tree1/1', 'delay1/1');\nadd_line(blk, 'delay1/1', 'sync_out/1');\n\nfor i=0:TotalTaps-1,\n slice_name = ['Slice', num2str(i)];\n reuse_block(blk, slice_name, 'xbsIndex_r4/Slice', ...\n 'mode', 'Upper Bit Location + Width', 'nbits', 'CoeffBitWidth + BitWidthIn', ...\n 'base0', 'MSB of Input', 'base1', 'MSB of Input', ...\n 'bit1', ['-',num2str(i),'*(CoeffBitWidth + BitWidthIn)'], 'Position', [70 50*i+116 115 50*i+128]);\n add_line(blk, 'din/1', [slice_name, '/1']);\n reint_name = ['Reint',num2str(i)];\n reuse_block(blk, reint_name, 'xbsIndex_r4/Reinterpret', ...\n 'force_arith_type', 'on', 'arith_type', 'Signed (2''s comp)', ...\n 'force_bin_pt', 'on', 'bin_pt', 'CoeffBitWidth + BitWidthIn - 2', ...\n 'Position', [130 50*i+116 160 50*i+128]);\n add_line(blk, [slice_name, '/1'], [reint_name, '/1']);\n add_line(blk, [reint_name, '/1'], ['adder_tree1','/',num2str(i+2)]);\nend\n\n% Set dynamic parameters\nif ~strcmp(get_param([blk,'/convert1'], 'quantization'), quantization),\n set_param([blk,'/convert1'], 'quantization', quantization);\n set_param([blk,'/convert2'], 'quantization', quantization);\nend\n\nclean_blocks(blk);\n\nfmtstr = sprintf('taps=%d, add_latency=%d', TotalTaps, add_latency);\nset_param(blk, 'AttributesFormatString', fmtstr);\nsave_state(blk, 'defaults', defaults, varargin{:});\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fir_dbl_col_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fir_dbl_col_init.m", "size": 8542, "source_encoding": "utf_8", "md5": "a80bb7be6c5ae1fcd8f0d2b0ef46c86c", "text": "% fir_dbl_col_init(blk, varargin)\r\n%\r\n% blk = The block to initialize.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% n_inputs = The number of parallel input samples.\r\n% coeff = The FIR coefficients, top-to-bottom.\r\n% add_latency = The latency of adders.\r\n% mult_latency = The latency of multipliers.\r\n% coeff_bit_width = The number of bits used for coefficients\r\n% coeff_bin_pt = The number of fractional bits in the coefficients\r\n% first_stage_hdl = Whether to implement the first stage in adder trees\r\n% as behavioral HDL so that adders are absorbed into DSP slices used for\r\n% multipliers where this is possible.\r\n% adder_imp = adder implementation (Fabric, behavioral HDL, DSP48)\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction fir_dbl_col_init(blk,varargin)\r\n\r\nclog('entering fir_dbl_col_init', 'trace');\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {'n_inputs', 1, 'coeff', 0.1, 'add_latency', 2, 'mult_latency', 3, ...\r\n 'coeff_bit_width', 25, 'coeff_bin_pt', 24, ...\r\n 'first_stage_hdl', 'off', 'adder_imp', 'Fabric'};\r\ncheck_mask_type(blk, 'fir_dbl_col');\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('fir_dbl_col_init post same_state', 'trace');\r\nmunge_block(blk, varargin{:});\r\n\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\ncoeff = get_var('coeff', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\ncoeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\r\ncoeff_bin_pt = get_var('coeff_bin_pt', 'defaults', defaults, varargin{:});\r\nfirst_stage_hdl = get_var('first_stage_hdl', 'defaults', defaults, varargin{:});\r\nadder_imp = get_var('adder_imp', 'defaults', defaults, varargin{:});\r\n\r\ndelete_lines(blk);\r\n\r\n%default library state\r\nif n_inputs == 0,\r\n clean_blocks(blk);\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting fir_dbl_col_init', 'trace');\r\n return;\r\nend\r\n\r\nif length(coeff) ~= n_inputs,\r\n clog('number of coefficients must be the same as the number of inputs', {'fir_dbl_col_init_debug', 'error'});\r\n error('number of coefficients must be the same as the number of inputs');\r\nend\r\n\r\n% Make sure these go through Ports in strictly increasing order, or\r\n% port assignments don't \"stick\".\r\nfor i=1:n_inputs,\r\n reuse_block(blk, ['real',num2str(i)], 'built-in/inport', 'Position', [30 i*80 60 15+80*i], 'Port', num2str(2*i-1));\r\n reuse_block(blk, ['imag',num2str(i)], 'built-in/inport', 'Position', [30 i*80+30 60 45+80*i], 'Port', num2str(2*i));\r\n\r\n reuse_block(blk, ['real_out',num2str(i)], 'built-in/outport', 'Position', [350 i*80 380 15+80*i], 'Port', num2str(2*i-1));\r\n reuse_block(blk, ['imag_out',num2str(i)], 'built-in/outport', 'Position', [350 i*80+30 380 45+80*i], 'Port', num2str(2*i));\r\n\r\n reuse_block(blk, ['fir_dbl_tap',num2str(i)], 'casper_library_downconverter/fir_dbl_tap', ...\r\n 'Position', [180 i*160-70 230 50+160*i], 'mult_latency', 'mult_latency',...\r\n 'add_latency', 'add_latency', 'factor', num2str(coeff(i)), ...\r\n\t'coeff_bit_width', 'coeff_bit_width', 'coeff_bin_pt', 'coeff_bin_pt');\r\nend\r\nfor i=1:n_inputs,\r\n reuse_block(blk, ['real_back',num2str(i)], 'built-in/inport', 'Position', [30 n_inputs*80+i*80 60 n_inputs*80+15+80*i], 'Port', num2str(2*i-1+2*n_inputs));\r\n reuse_block(blk, ['imag_back',num2str(i)], 'built-in/inport', 'Position', [30 n_inputs*80+i*80+30 60 n_inputs*80+45+80*i], 'Port', num2str(2*i+2*n_inputs));\r\n\r\n reuse_block(blk, ['real_back_out',num2str(i)], 'built-in/outport', 'Position', [350 n_inputs*80+i*80 380 n_inputs*80+15+80*i], 'Port', num2str(2*i-1+2*n_inputs));\r\n reuse_block(blk, ['imag_back_out',num2str(i)], 'built-in/outport', 'Position', [350 n_inputs*80+i*80+30 380 n_inputs*80+45+80*i], 'Port', num2str(2*i+2*n_inputs));\r\nend\r\nreuse_block(blk, 'real_sum', 'built-in/outport', 'Position', [600 10+20*n_inputs 630 30+20*n_inputs], 'Port', num2str(4*n_inputs+1));\r\nreuse_block(blk, 'imag_sum', 'built-in/outport', 'Position', [600 110+20*n_inputs 630 130+20*n_inputs], 'Port', num2str(4*n_inputs+2));\r\n\r\nif n_inputs > 1,\r\n reuse_block(blk, 'adder_tree1', 'casper_library_misc/adder_tree', ...\r\n 'Position', [500 100 550 100+20*n_inputs], 'n_inputs', num2str(n_inputs),...\r\n 'latency', num2str(add_latency), 'first_stage_hdl', first_stage_hdl, 'adder_imp', adder_imp);\r\n reuse_block(blk, 'adder_tree2', 'casper_library_misc/adder_tree', ...\r\n 'Position', [500 200+20*n_inputs 550 200+20*n_inputs+20*n_inputs], 'n_inputs', num2str(n_inputs),...\r\n 'latency', num2str(add_latency), 'first_stage_hdl', first_stage_hdl, 'adder_imp', adder_imp);\r\n reuse_block(blk, 'c1', 'xbsIndex_r4/Constant', ...\r\n 'explicit_period', 'on', 'Position', [450 100 480 110]);\r\n reuse_block(blk, 'c2', 'xbsIndex_r4/Constant', ...\r\n 'explicit_period', 'on', 'Position', [450 200+20*n_inputs 480 210+20*n_inputs]);\r\n reuse_block(blk, 'term1','built-in/Terminator', 'Position', [600 100 615 115]);\t\r\n add_line(blk, 'adder_tree1/1', 'term1/1');\r\n reuse_block(blk, 'term2','built-in/Terminator', 'Position', [600 200+20*n_inputs 615 215+20*n_inputs]);\t\r\n add_line(blk, 'adder_tree2/1', 'term2/1');\r\n\r\n add_line(blk, 'c1/1', 'adder_tree1/1');\r\n add_line(blk, 'c2/1', 'adder_tree2/1');\r\n add_line(blk,'adder_tree1/2','real_sum/1');\r\n add_line(blk,'adder_tree2/2','imag_sum/1');\r\nend\r\n\r\nfor i=1:n_inputs,\r\n add_line(blk,['real',num2str(i),'/1'],['fir_dbl_tap',num2str(i),'/1']);\r\n add_line(blk,['imag',num2str(i),'/1'],['fir_dbl_tap',num2str(i),'/2']);\r\n add_line(blk,['real_back',num2str(n_inputs+1-i),'/1'],['fir_dbl_tap',num2str(i),'/3']);\r\n add_line(blk,['imag_back',num2str(n_inputs+1-i),'/1'],['fir_dbl_tap',num2str(i),'/4']);\r\n add_line(blk,['fir_dbl_tap',num2str(i),'/1'],['real_out',num2str(i),'/1']);\r\n add_line(blk,['fir_dbl_tap',num2str(i),'/2'],['imag_out',num2str(i),'/1']);\r\n add_line(blk,['fir_dbl_tap',num2str(i),'/3'],['real_back_out',num2str(n_inputs+1-i),'/1']);\r\n add_line(blk,['fir_dbl_tap',num2str(i),'/4'],['imag_back_out',num2str(n_inputs+1-i),'/1']);\r\n if n_inputs > 1\r\n add_line(blk,['fir_dbl_tap',num2str(i),'/5'],['adder_tree1/',num2str(i+1)]);\r\n add_line(blk,['fir_dbl_tap',num2str(i),'/6'],['adder_tree2/',num2str(i+1)]);\r\n else\r\n add_line(blk,['fir_dbl_tap',num2str(i),'/5'],['real_sum/1']);\r\n add_line(blk,['fir_dbl_tap',num2str(i),'/6'],['imag_sum/1']);\r\n end\r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\nclog('exiting fir_dbl_col_init', 'trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "snapshot_callback.m", "ext": ".m", "path": "mlib_devel-master/casper_library/snapshot_callback.m", "size": 2621, "source_encoding": "utf_8", "md5": "a3c539b6ded1703f1f7ff73e99fe8b65", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Meerkat radio telescope project %\n% www.kat.ac.za %\n% Copyright (C) Andrew Martens 2011 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction snapshot_callback()\n\nclog('entering bus_expand_callback', 'trace');\n\nblk = gcb;\n\ncheck_mask_type(blk, 'snapshot');\n\nstorage = get_param(blk, 'storage');\n\nmask_names = get_param(blk, 'MaskNames');\nmask_enables = get_param(blk, 'MaskEnables');\nmask_visibilities = get_param(blk, 'MaskVisibilities');\n\nif strcmp(storage, 'bram'),\n mask_visibilities{ismember(mask_names, 'dram_dimm')} = 'off';\n mask_visibilities{ismember(mask_names, 'dram_clock')} = 'off';\n mask_enables{ismember(mask_names, 'data_width')} = 'on';\nelseif strcmp(storage, 'dram'),\n mask_visibilities{ismember(mask_names, 'dram_dimm')} = 'on';\n mask_visibilities{ismember(mask_names, 'dram_clock')} = 'on';\n set_param(blk, 'data_width', '64');\n mask_enables{ismember(mask_names, 'data_width')} = 'off';\nelse,\nend\n\nset_param(gcb, 'MaskEnables', mask_enables);\nset_param(gcb, 'MaskVisibilities', mask_visibilities);\n\nclog('exiting bus_expand_callback', 'trace');\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_fir_async_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_fir_async_init.m", "size": 17536, "source_encoding": "utf_8", "md5": "a4fe60832b27a5f4a905513b944056fe", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version.\r\n% %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction pfb_fir_async_init(blk, varargin)\r\n% Initialize and configure the Polyphase Filter Bank.\r\n%\r\n% pfb_fir_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% pfb_bits = The size of the PFB\r\n% total_taps = Total number of taps in the PFB\r\n% window_type = The type of windowing function to use.\r\n% simul_bits = The number of parallel inputs\r\n% make_biplex = Double up the PFB to feed a biplex FFT\r\n% data_in_bits = Input Bitwidth\r\n% data_out_bits = Output Bitwidth (0 == as needed)\r\n% coeff_bits = Bitwidth of Coefficients.\r\n% coeffs_in_distmem = Implement coefficients in distributed memory\r\n% add_latency = Latency through each adder.\r\n% mult_latency = Latency through each multiplier\r\n% bram_latency = Latency through each BRAM.\r\n% quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round\r\n% (unbiased: Even Values)'\r\n% fwidth = Scaling of the width of each PFB channel\r\n% coeffs_share = Both polarizations will share coefficients.\r\n% async = Should the PFB take a data valid signal so it can function asynchronously?\r\n\r\nclog('entering pfb_fir_async_init','trace');\r\n\r\nautoroute = 'off';\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {'pfb_bits', 5, 'total_taps', 2, ...\r\n 'window_type', 'hamming', 'simul_bits', 1, 'make_biplex', 'off', ...\r\n 'data_in_bits', 8, 'data_out_bits', 0, 'coeff_bits', 18, ...\r\n 'coeffs_in_distmem', 'off', 'add_latency', 1, 'mult_latency', 2, ...\r\n 'bram_latency', 2, ...\r\n 'quantization', 'Round (unbiased: +/- Inf)', ...\r\n 'fwidth', 1, 'mult_spec', [2 2], ...\r\n 'coeffs_share', 'off', 'async', 'off'};\r\n\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('pfb_fir_async_init post same_state','trace');\r\ncheck_mask_type(blk, 'pfb_fir_async');\r\nmunge_block(blk, varargin{:});\r\n\r\npfb_bits = get_var('pfb_bits', 'defaults', defaults, varargin{:});\r\ntotal_taps = get_var('total_taps', 'defaults', defaults, varargin{:});\r\nwindow_type = get_var('window_type', 'defaults', defaults, varargin{:});\r\nsimul_bits = get_var('simul_bits', 'defaults', defaults, varargin{:});\r\nmake_biplex = get_var('make_biplex', 'defaults', defaults, varargin{:});\r\ndata_in_bits = get_var('data_in_bits', 'defaults', defaults, varargin{:});\r\ndata_out_bits = get_var('data_out_bits', 'defaults', defaults, varargin{:});\r\ncoeff_bits = get_var('coeff_bits', 'defaults', defaults, varargin{:});\r\ncoeffs_in_distmem = get_var('coeffs_in_distmem', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\nfan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\nfwidth = get_var('fwidth', 'defaults', defaults, varargin{:});\r\nmult_spec = get_var('mult_spec', 'defaults', defaults, varargin{:});\r\ncoeffs_share = get_var('coeffs_share', 'defaults', defaults, varargin{:});\r\nasync = get_var('async', 'defaults', defaults, varargin{:});\r\ndebug_mode = get_var('debug_mode', 'defaults', defaults, varargin{:});\r\n\r\n% check the multiplier specifications first off\r\ntap_multipliers = multiplier_specification(mult_spec, total_taps, blk);\r\n\r\n% async?\r\nmake_async = false;\r\nif strcmp(async, 'on'),\r\n make_async = true;\r\nend\r\n\r\n% share coeffs in a 2-pol setup?\r\npols = 1;\r\nshare_coefficients = false;\r\nif strcmp(make_biplex, 'on'),\r\n pols = 2;\r\n if strcmp(coeffs_share, 'on')\r\n share_coefficients = true;\r\n end\r\nend\r\n\r\n% Compute the maximum gain through all of the 2^pfb_bits sub-filters. This is\r\n% used to determine how much bit growth is really needed. The maximum gain of\r\n% each filter is the sum of the absolute values of its coefficients. The\r\n% maximum of these gains sets the upper bound on bit growth through the\r\n% pfb_fir. The products, partial sums, and final sum throughout the pfb_fir\r\n% (including the adder tree) need not accomodate any more bit growth than the\r\n% absolute maximum gain requires, provided that any \"overflow\" is ignored (i.e.\r\n% set to \"Wrap\"). This works thanks to the wonders of modulo math. Note that\r\n% the \"gain\" for typical signals will be different (less) than the absolute\r\n% maximum gain of each filter. For Gaussian noise, the gain of a filter is the\r\n% square root of the sum of the squares of the coefficients (aka\r\n% root-sum-squares or RSS).\r\n\r\n% Get all coefficients of the pfb_fir in one vector (by passing -1 for a)\r\nall_coeffs = pfb_coeff_gen_calc(pfb_bits, total_taps, window_type, simul_bits, 0, fwidth, -1, false);\r\n% Rearrange into matrix with 2^pfb_bits rows and total_taps columns.\r\n% Each row contains coefficients for one sub-filter.\r\nall_filters = reshape(all_coeffs, 2^pfb_bits, total_taps);\r\n% Compute max gain\r\n% NB: sum rows, not columns!\r\nmax_gain = max(sum(abs(all_filters), 2));\r\n% Compute bit growth (make sure it is non-negative)\r\nbit_growth = max(0, nextpow2(max_gain));\r\n% Compute adder output width and binary point. We know that the adders in the\r\n% adder tree need to have (bit_growth+1) non-fractional bits to accommodate the\r\n% maximum gain. The products from the taps will have\r\n% (data_in_bits+coeff_bits-2) fractional bits. We will preserve them through\r\n% the adder tree.\r\nadder_bin_pt_out = data_in_bits + coeff_bits - 2;\r\nadder_n_bits_out = bit_growth + 1 + adder_bin_pt_out;\r\n\r\n% If data_out_bits is 0, set it to accomodate bit growth in the\r\n% non-fractional part and full-precision of the fractional part.\r\nif data_out_bits == 0\r\n data_out_bits = adder_n_bits_out;\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\n% Add ports\r\nclog('adding inports and outports', 'pfb_fir_init_debug');\r\nportnum = 1;\r\nreuse_block(blk, 'sync', 'built-in/inport', ...\r\n 'Position', [0 50*portnum 30 50*portnum+15], 'Port', num2str(portnum));\r\nreuse_block(blk, 'sync_out', 'built-in/outport', ...\r\n 'Position', [150*(total_taps+3) 50*portnum 150*(total_taps+3)+30 50*portnum+15], 'Port', num2str(portnum));\r\nif make_async,\r\n portnum = 2;\r\n reuse_block(blk, 'dv', 'built-in/inport', ...\r\n 'Position', [0 50*portnum 30 50*portnum+15], 'Port', num2str(portnum));\r\n reuse_block(blk, 'dv_out', 'built-in/outport', ...\r\n 'Position', [150*(total_taps+3) 50*portnum 150*(total_taps+3)+30 50*portnum+15], 'Port', num2str(portnum));\r\n reuse_block(blk, 'dv_delay', 'xbsIndex_r4/Delay', ...\r\n 'latency', 'bram_latency+1', 'Position', [75 50*portnum 100 50*portnum+15]);\r\n add_line(blk, 'dv/1', 'dv_delay/1', 'autorouting', autoroute);\r\nend\r\nfor p=1:pols,\r\n for n=1:2^simul_bits,\r\n portnum = portnum + 1;\r\n in_name = ['pol',num2str(p),'_in',num2str(n)];\r\n out_name = ['pol',num2str(p),'_out',num2str(n)];\r\n reuse_block(blk, in_name, 'built-in/inport', ...\r\n 'Position', [0 150*portnum 30 150*portnum+15], 'Port', num2str(portnum));\r\n reuse_block(blk, out_name, 'built-in/outport', ...\r\n 'Position', [150*(total_taps+3) 150*portnum 150*(total_taps+3)+30 150*portnum+15], 'Port', num2str(portnum));\r\n end\r\nend\r\n\r\n% add the coefficient generators - one per port\r\nportnum = 0;\r\nx_size = 100;\r\ny_size = 100;\r\nfor p = 1 : pols,\r\n for n = 1 : 2^simul_bits,\r\n portnum = portnum + 1;\r\n in_name = ['pol',num2str(p),'_in',num2str(n)];\r\n if (p == 2) && (share_coefficients == true)\r\n blk_name = [in_name,'_delay'];\r\n reuse_block(blk, blk_name, 'xbsIndex_r4/Delay', ...\r\n 'latency', 'bram_latency+1+fan_latency', 'Position', [150 150*portnum 150+x_size 150*portnum+y_size]);\r\n add_line(blk, [in_name,'/1'], [blk_name,'/1'], 'autorouting', autoroute);\r\n else\r\n blk_name = [in_name,'_coeffs'];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/pfb_coeff_gen', ...\r\n 'PFBSize', tostring(pfb_bits), 'CoeffBitWidth', tostring(coeff_bits), ...\r\n 'TotalTaps', tostring(total_taps), ...\r\n 'CoeffDistMem', coeffs_in_distmem, ...\r\n 'WindowType', window_type, ...\r\n 'n_inputs', tostring(simul_bits), ...\r\n 'nput', num2str(n-1), ...\r\n 'Position', [150 150*portnum 150+x_size 150*portnum+y_size]);\r\n propagate_vars([blk,'/',blk_name], 'defaults', defaults, varargin{:});\r\n add_line(blk, [in_name,'/1'], [blk_name,'/1'], 'autorouting', autoroute);\r\n add_line(blk, 'sync/1', [blk_name,'/2'], 'autorouting', autoroute);\r\n end\r\n end\r\nend\r\n \r\n% Add taps and lines\r\nportnum = 0;\r\nfor p = 1:pols,\r\n for n = 1:2^simul_bits,\r\n portnum = portnum + 1;\r\n in_name = ['pol',num2str(p),'_in',num2str(n)];\r\n out_name = ['pol',num2str(p),'_out',num2str(n)];\r\n clog(['adding taps for pol ', num2str(p), ' input ',num2str(n)], 'pfb_fir_init_debug');\r\n for t = 1:total_taps,\r\n % not last tap\r\n if t ~= total_taps,\r\n blk_name = [in_name, '_tap', tostring(t)];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/tap_async', ...\r\n 'use_hdl', tap_multipliers(t).use_hdl, 'use_embedded', tap_multipliers(t).use_embedded,...\r\n 'this_tap',tostring(t),...\r\n 'Position', [150*(t+1) 150*portnum 150*(t+1)+x_size 150*portnum+y_size]);\r\n propagate_vars([blk,'/',blk_name],'defaults', defaults, varargin{:});\r\n if t == 1,\r\n if (p == 2) && (share_coefficients == true)\r\n src_block = [strrep(in_name,'pol2','pol1'),'_coeffs'];\r\n data_source = [in_name,'_delay/1'];\r\n else\r\n src_block = [in_name,'_coeffs'];\r\n data_source = [src_block,'/1'];\r\n end\r\n add_line(blk, data_source, [blk_name,'/1'], 'autorouting', autoroute);\r\n add_line(blk, 'pol1_in1_coeffs/2', [blk_name,'/2'], 'autorouting', autoroute);\r\n add_line(blk, [src_block,'/3'], [blk_name,'/3'], 'autorouting', autoroute);\r\n if make_async,\r\n add_line(blk, 'dv_delay/1', [blk_name,'/4'], 'autorouting', autoroute);\r\n end\r\n end\r\n else\r\n blk_name = [in_name,'_last_tap'];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/last_tap_async', ...\r\n 'use_hdl', tap_multipliers(t).use_hdl, 'use_embedded', tap_multipliers(t).use_embedded,...\r\n 'input_num', num2str(portnum), ...\r\n 'Position', [150*(t+1) 150*portnum 150*(t+1)+x_size 150*portnum+y_size]);\r\n propagate_vars([blk,'/',blk_name],'defaults', defaults, varargin{:});\r\n % Update innards of the adder trees using our knowledge of\r\n % maximum bit growth. This uses knowledge of the\r\n % implementation of the \"last_tap\" block. This defeats the\r\n % benefits of encapsulation, but the alternative is to make the\r\n % underlying adder_tree block smarter and then make every block\r\n % that encapsulates or uses an adder_tree smarter. Forcing\r\n % such a global change for one or two specific cases seems a\r\n % greater evil, IMHO.\r\n pfb_add_tree = sprintf('%s/%s/pfb_add_tree_async', blk, blk_name);\r\n for k=1:2\r\n % Update adder blocks in the adder trees using our\r\n % knowledge of maximum bit growth.\r\n adders = find_system( ...\r\n sprintf('%s/adder_tree%d', pfb_add_tree, k), ...\r\n 'LookUnderMasks','all', 'FollowLinks','on', ...\r\n 'SearchDepth',1, 'RegExp','on', 'Name','^addr');\r\n for kk=1:length(adders)\r\n set_param(adders{kk}, ...\r\n 'precision', 'User Defined', ...\r\n 'arith_type', 'Signed (2''s comp)', ...\r\n 'n_bits', tostring(adder_n_bits_out), ...\r\n 'bin_pt', tostring(adder_bin_pt_out), ...\r\n 'quantization', 'Truncate', ...\r\n 'overflow', 'Wrap');\r\n end\r\n % Adder tree output has bit_growth more non-fractional bits\r\n % than data_in_bits, but we want to keep the same number of\r\n % non-fractional bits, so we must scale by 2^(-bit_growth).\r\n set_param(sprintf('%s/scale%d', pfb_add_tree, k), ...\r\n 'scale_factor', tostring(-bit_growth));\r\n % Because we have handled bit growth for maximum gain,\r\n % there can be no overflow so the convert blocks can be set\r\n % to \"Wrap\" to avoid unnecessary logic. If data_out_bits is\r\n % greater than adder_bin_pt_out, set their quantization to\r\n % \"Truncate\" since there is no need to quantize.\r\n if data_out_bits > adder_bin_pt_out\r\n conv_quant = 'Truncate';\r\n else\r\n conv_quant = quantization;\r\n end\r\n set_param(sprintf('%s/convert%d', pfb_add_tree, k), ...\r\n 'overflow', 'Wrap', 'quantization', conv_quant);\r\n end\r\n % join dataout, dv and sync\r\n add_line(blk, [blk_name,'/1'], [out_name,'/1'], 'autorouting', autoroute);\r\n if n==1 && p==1\r\n add_line(blk, [blk_name,'/2'], 'sync_out/1', 'autorouting', autoroute);\r\n add_line(blk, [blk_name,'/3'], 'dv_out/1', 'autorouting', autoroute);\r\n end\r\n end\r\n % join all the taps together\r\n if t > 1\r\n for ctr = 1 : 5,\r\n add_line(blk, [in_name, '_tap', tostring(t-1), '/', tostring(ctr)], [blk_name, '/', tostring(ctr)], 'autorouting', autoroute);\r\n end\r\n end\r\n end\r\n end\r\nend\r\n\r\n% the sync generate block\r\ndelete_line(blk, ['pol1_in1_tap', tostring(total_taps-1), '/2'], 'pol1_in1_last_tap/2');\r\nadd_line(blk, 'sync_generate/1', 'pol1_in1_last_tap/2', 'autorouting', autoroute);\r\nadd_line(blk, 'pol1_in1_coeffs/2', 'sync_generate/1', 'autorouting', autoroute);\r\nadd_line(blk, 'dv_delay/1', 'sync_generate/2', 'autorouting', autoroute);\r\n\r\n% add the adder trees\r\n%portnum = 0;\r\n%for p = 1 : pols,\r\n% for n = 1 : 2^simul_bits,\r\n% tree_name = ['adder', tostring(n), tostring(p)];\r\n% reuse_block(blk, tree_name, 'casper_library_pfbs/pfb_add_tree', ...\r\n% 'use_hdl', tostring(use_hdl), 'use_embedded', tostring(use_embedded),...\r\n% 'Position', [150*(total_taps+2) 150*portnum 150*(total_taps+2)+x_size 150*portnum+y_size]);\r\n% %propagate_vars([blk,'/',blk_name],'defaults', defaults,\r\n% %varargin{:});\r\n% add_line(blk, [tree_name, '/1'], ['pol',tostring(p),'_out',tostring(n),'/1'], 'autorouting', autoroute);\r\n% end\r\n%end\r\n\r\nclean_blocks(blk);\r\n\r\ndebug_string = '';\r\nif strcmp(debug_mode, 'on'),\r\n debug_string = '\\n-*-*-*-*-*-*-*-\\nDEBUG MODE!!\\n-*-*-*-*-*-*-*-';\r\nend\r\nfmtstr = [sprintf('taps=%d, add_latency=%d\\nmax scale %.3f', ...\r\n total_taps, add_latency, max_gain*2^-bit_growth), debug_string];\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\nclog('exiting pfb_fir_init','trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "dec_fir_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/dec_fir_init.m", "size": 12519, "source_encoding": "utf_8", "md5": "03f9c9ab6697471c38854b55a82757fc", "text": "% dec_fir_init(blk, varargin)\r\n%\r\n% blk = The block to initialize.\r\n% varargin = {'varname', 'value', ...} pairs\r\n%\r\n% Valid varnames for this block are:\r\n% n_inputs = The number of parallel input samples.\r\n% coeff = The FIR coefficients, top-to-bottom.\r\n% n_bits = Bit width out.\r\n% n_bits_bp = Binary point of output\r\n% quantization = Quantization behavior [Truncate, Round (unbiased: +/- Inf),\r\n% or Round (unbiased: Even Values)]\r\n% add_latency = The latency of adders.\r\n% mult_latency = The latency of multipliers.\r\n% conv_latency = The latency during bit resolution conversion\r\n% coeff_bit_width = Coefficient resolution\r\n% coeff_bin_pt = Number of bits after binary point in coefficients\r\n% absorb_adders = Attempt to absorb adders following multipliers into DSP \r\n% slices by making them be implemented at behavioral HDL\r\n% pre_conv_shift = How many bits to shift left before final output\r\n% conversion.\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% % \r\n% Copyright (C) 2010 Billy Mallard %\r\n% % \r\n% Karoo Array Telescope Project % \r\n% http://www.kat.ac.za % \r\n% Copyright (C) 2011 Andrew Martens %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction dec_fir_init(blk,varargin)\r\n\r\nclog('entering dec_fir_init', 'trace');\r\n\r\n% Declare any default values for arguments you might like.\r\n% Added defaults and fixed the quatization default for 10.1 tools AWL\r\ndefaults = {'n_inputs', 1, 'n_bits', 8, 'n_bits_bp', 7, ...\r\n 'coeff', 0.1, 'lshift', 1, ...\r\n 'quantization', 'Round (unbiased: +/- Inf)', ...\r\n 'add_latency', 1, 'mult_latency', 2, 'conv_latency', 2, ...\r\n 'coeff_bit_width', 25, 'coeff_bin_pt', 24, ...\r\n 'absorb_adders', 'on', 'adder_imp', 'DSP48'};\r\n\r\ncheck_mask_type(blk, 'dec_fir');\r\n\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('dec_fir_init post same_state', 'trace');\r\n\r\nmunge_block(blk, varargin{:});\r\nn_inputs = get_var('n_inputs','defaults', defaults, varargin{:});\r\ncoeff = get_var('coeff', 'defaults', defaults, varargin{:});\r\nn_bits = get_var('n_bits', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nconv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\r\ncoeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\r\ncoeff_bin_pt = get_var('coeff_bin_pt', 'defaults', defaults, varargin{:}); \r\nabsorb_adders = get_var('absorb_adders', 'defaults', defaults, varargin{:});\r\nadder_imp = get_var('adder_imp', 'defaults', defaults, varargin{:});\r\n\r\ntry\r\n get_param(blk, 'lshift');\r\n lshift = get_var('lshift', 'defaults', defaults, varargin{:});\r\ncatch err_inf,\r\n lshift = 1;\r\nend\r\n\r\ntry\r\n get_param(blk, 'n_bits_bp');\r\n n_bits_bp = get_var('n_bits_bp', 'defaults', defaults, varargin{:});\r\ncatch err_inf,\r\n n_bits_bp = n_bits - 1;\r\nend\r\n\r\n%default library state\r\nif n_inputs == 0,\r\n delete_lines(blk);\r\n clean_blocks(blk);\r\n set_param(blk,'AttributesFormatString','');\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting dec_fir_init', 'trace');\r\n return;\r\nend\r\n\r\n% round coefficients to make sure rounding error doesn't prevent us from\r\n% detecting symmetric coefficients\r\ncoeff_round = round(coeff * 1e16) * 1e-16;\r\n\r\n% check that the number of inputs and coefficients are compatible\r\nif mod(length(coeff) / n_inputs, 1) ~= 0,\r\n error_string = sprintf('The number of coefficients (%d) must be integer multiples of the number of inputs (%d).', length(coeff), n_inputs);\r\n clog(error_string, 'error');\r\n errordlg(error_string);\r\nend\r\n\r\nnum_fir_col = length(coeff) / n_inputs;\r\ncoeff_sym = 0;\r\nfir_col_type = 'fir_col';\r\n\r\nif mod(length(coeff),2) == 0 && mod(num_fir_col, 2)==0 \r\n if coeff_round(1:length(coeff)/2) == coeff_round(length(coeff):-1:length(coeff)/2+1),\r\n num_fir_col = num_fir_col / 2;\r\n fir_col_type = 'fir_dbl_col';\r\n coeff_sym = 1;\r\n end\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\nreuse_block(blk, 'sync_in', 'built-in/inport', ...\r\n 'Position', [0 90*n_inputs+100 30 90*n_inputs+115], 'Port', '1');\r\n\r\nfor i=1:n_inputs,\r\n reuse_block(blk, ['real',num2str(i)], 'built-in/inport', ...\r\n 'Position', [0 90*i 30 90*i+15], 'Port', num2str(2*i));\r\n reuse_block(blk, ['imag',num2str(i)], 'built-in/inport', ...\r\n 'Position', [0 90*i+45 30 90*i+60], 'Port', num2str(2*i+1));\r\nend\r\n\r\n% if we have only one input stream, then first stage of adders\r\n% after multipliers are these adder_trees (otherwise inside cols)\r\nif n_inputs == 1,\r\n first_stage_hdl_external = absorb_adders; \r\nelse\r\n first_stage_hdl_external = 'off';\r\nend\r\n\r\nreuse_block(blk, 'real_sum', 'casper_library_misc/adder_tree', ...\r\n 'Position', [200*num_fir_col+400 300 200*num_fir_col+460 num_fir_col*10+300], ...\r\n 'n_inputs',num2str(num_fir_col),'latency',num2str(add_latency), ...\r\n 'adder_imp', adder_imp, 'first_stage_hdl', first_stage_hdl_external);\r\nreuse_block(blk, 'imag_sum', 'casper_library_misc/adder_tree', ...\r\n 'Position', [200*num_fir_col+400 num_fir_col*10+400 200*num_fir_col+460 num_fir_col*20+400], ...\r\n 'n_inputs',num2str(num_fir_col),'latency',num2str(add_latency), ...\r\n 'adder_imp', adder_imp, 'first_stage_hdl', first_stage_hdl_external);\r\n\r\nfor i=1:num_fir_col,\r\n blk_name = [fir_col_type,num2str(i)];\r\n prev_blk_name = [fir_col_type,num2str(i-1)];\r\n reuse_block(blk, blk_name, ['casper_library_downconverter/', fir_col_type], ...\r\n 'Position', [200*i+200 50 200*i+300 250], 'n_inputs', num2str(n_inputs),...\r\n 'coeff', ['[',num2str(coeff(i*n_inputs:-1:(i-1)*n_inputs+1)),']'],...\r\n\t'mult_latency', num2str(mult_latency), 'add_latency', num2str(add_latency), ...\r\n\t'coeff_bit_width', num2str(coeff_bit_width), 'coeff_bin_pt', num2str(coeff_bin_pt), ...\r\n\t'adder_imp', adder_imp, 'first_stage_hdl', absorb_adders);\r\n\r\n if i == 1,\r\n for j=1:n_inputs,\r\n add_line(blk, ['real',num2str(j),'/1'], [blk_name,'/',num2str(2*j-1)]);\r\n add_line(blk, ['imag',num2str(j),'/1'], [blk_name,'/',num2str(2*j)]);\r\n end\r\n else,\r\n for j=1:n_inputs,\r\n add_line(blk,[prev_blk_name,'/',num2str(j*2-1)],[blk_name,'/',num2str(j*2-1)]);\r\n add_line(blk,[prev_blk_name,'/',num2str(j*2)],[blk_name,'/',num2str(j*2)]);\r\n end\r\n end\r\n\r\n if coeff_sym,\r\n add_line(blk,[blk_name,'/',num2str(n_inputs*4+1)],['real_sum/',num2str(i+1)]);\r\n add_line(blk,[blk_name,'/',num2str(n_inputs*4+2)],['imag_sum/',num2str(i+1)]);\r\n else\r\n add_line(blk,[blk_name,'/',num2str(n_inputs*2+1)],['real_sum/',num2str(i+1)]);\r\n add_line(blk,[blk_name,'/',num2str(n_inputs*2+2)],['imag_sum/',num2str(i+1)]);\r\n end\r\nend\r\n\r\nreuse_block(blk, 'shift1', 'xbsIndex_r4/Shift', ...\r\n 'shift_dir', 'Left', 'shift_bits', num2str(lshift), ...\r\n 'Position', [200*num_fir_col+500 300 200*num_fir_col+530 315]);\r\nreuse_block(blk, 'shift2', 'xbsIndex_r4/Shift', ...\r\n 'shift_dir', 'Left', 'shift_bits', num2str(lshift), ...\r\n 'Position', [200*num_fir_col+500 500 200*num_fir_col+530 515]);\r\nreuse_block(blk, 'convert1', 'xbsIndex_r4/Convert', ...\r\n 'Position', [200*num_fir_col+560 300 200*num_fir_col+590 315], ...\r\n 'n_bits', num2str(n_bits), 'bin_pt', num2str(n_bits_bp), 'arith_type', 'Signed (2''s comp)', ...\r\n 'latency', num2str(conv_latency), 'quantization', quantization);\r\nreuse_block(blk, 'convert2', 'xbsIndex_r4/Convert', ...\r\n 'Position', [200*num_fir_col+560 500 200*num_fir_col+590 515], ...\r\n 'n_bits', num2str(n_bits), 'bin_pt', num2str(n_bits-1), 'arith_type', 'Signed (2''s comp)', ...\r\n 'latency', num2str(conv_latency), 'quantization', quantization);\r\n\r\nreuse_block(blk, 'ri_to_c', 'casper_library_misc/ri_to_c', ...\r\n 'Position', [200*num_fir_col+620 400 200*num_fir_col+650 430]);\r\n\r\nreuse_block(blk, 'sync_out', 'built-in/outport', ...\r\n 'Position', [200*num_fir_col+500 250 200*num_fir_col+530 265], 'Port', '1');\r\nreuse_block(blk, 'dout', 'built-in/outport', ...\r\n 'Position', [200*num_fir_col+680 400 200*num_fir_col+710 415], 'Port', '2');\r\n\r\n% delay of sync\r\nif coeff_sym,\r\n % y(n) = sum(aix(n-i)) for i=0:N. sync is thus related to x(0)\r\n sync_latency = add_latency + mult_latency + ceil(log2(n_inputs))*add_latency + conv_latency;\r\nelse\r\n sync_latency = mult_latency + ceil(log2(n_inputs))*add_latency + conv_latency;\r\nend\r\n\r\n% if delay is greater than 17*3 then might as well use logic\r\n% as using more than 3 SRL16s and sync_delay uses approx 3 \r\n% (2 comparators, one counter) \r\n\r\nif sync_latency > 17*3,\r\n sync_delay_block = 'casper_library_delays/sync_delay';\r\nelse \r\n sync_delay_block = 'xbsIndex_r4/Delay';\r\nend\r\n\r\nreuse_block(blk, 'delay', sync_delay_block, ...\r\n 'Position', [60 90*n_inputs+100 90 90*n_inputs+130], ...\r\n 'latency', num2str(sync_latency));\r\n\r\nadd_line(blk,'real_sum/2','shift1/1');\r\nadd_line(blk,'imag_sum/2','shift2/1');\r\nadd_line(blk,'shift1/1','convert1/1');\r\nadd_line(blk,'shift2/1','convert2/1');\r\nadd_line(blk, 'convert1/1', 'ri_to_c/1');\r\nadd_line(blk, 'convert2/1', 'ri_to_c/2');\r\nadd_line(blk, 'ri_to_c/1', 'dout/1');\r\nadd_line(blk,'sync_in/1','delay/1');\r\nadd_line(blk,'delay/1','real_sum/1');\r\nadd_line(blk,'delay/1','imag_sum/1');\r\nadd_line(blk,'real_sum/1','sync_out/1');\r\n\r\n% backward links for symmetric coefficients\r\nif coeff_sym,\r\n for i=1:num_fir_col,\r\n blk_name = [fir_col_type,num2str(i)];\r\n prev_blk_name = [fir_col_type,num2str(i-1)];\r\n if i ~= 1\r\n for j=1:n_inputs,\r\n add_line(blk,[blk_name,'/',num2str(2*n_inputs+j*2-1)],[prev_blk_name,'/',num2str(2*n_inputs+j*2-1)]);\r\n add_line(blk,[blk_name,'/',num2str(2*n_inputs+j*2)],[prev_blk_name,'/',num2str(2*n_inputs+j*2)]);\r\n end\r\n end\r\n end\r\n\r\n for j=1:n_inputs,\r\n blk_name = [fir_col_type,num2str(num_fir_col)];\r\n add_line(blk,[blk_name,'/',num2str(j*2-1)],[blk_name,'/',num2str(2*n_inputs+j*2-1)]);\r\n add_line(blk,[blk_name,'/',num2str(j*2)],[blk_name,'/',num2str(2*n_inputs+j*2)]);\r\n end\r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\n% Set attribute format string (block annotation)\r\nannotation=sprintf('%d taps\\n%d_%d r/i', length(coeff), n_bits, n_bits_bp);\r\nset_param(blk,'AttributesFormatString',annotation);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\nclog('exiting dec_fir_init', 'trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "first_tap_real_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/first_tap_real_init.m", "size": 3081, "source_encoding": "utf_8", "md5": "554eace870023e00d6071b78687d8d51", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction first_tap_real_init(blk, varargin)\r\n% Initialize and configure the first tap of the Real Polyphase Filter Bank.\r\n%\r\n% first_tap_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% PFBSize = The size of the PFB\r\n% CoeffBitWidth = Bitwidth of Coefficients.\r\n% TotalTaps = Total number of taps in the PFB\r\n% BitWidthIn = Input Bitwidth\r\n% WindowType = The type of windowing function to use.\r\n% mult_latency = Latency through each multiplier\r\n% bram_latency = Latency through each BRAM.\r\n% n_inputs = The number of parallel inputs\r\n% fwidth = Scaling of the width of each PFB channel\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {};\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\ncheck_mask_type(blk, 'first_tap_real');\r\nmunge_block(blk, varargin{:});\r\n\r\nTotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:});\r\nuse_hdl = get_var('use_hdl','defaults', defaults, varargin{:});\r\nuse_embedded = get_var('use_embedded','defaults', defaults, varargin{:});\r\n\r\nset_param([blk,'/Mult'],'use_embedded', use_embedded);\r\nset_param([blk,'/Mult'],'use_behavioral_HDL', use_hdl);\r\n\r\nfmtstr = sprintf('taps=%d', TotalTaps);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "dec_fir_async_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/dec_fir_async_init.m", "size": 16870, "source_encoding": "utf_8", "md5": "e24a0803411821a299c507db97aaa60b", "text": "% dec_fir_async_init(blk)\r\n%\r\n% blk = The block to initialize.\r\n%\r\n% The script will pull the required variables from the block mask.\r\n%\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\r\n% % \r\n% Copyright (C) 2010 Billy Mallard %\r\n% % \r\n% Karoo Array Telescope Project % \r\n% http://www.kat.ac.za % \r\n% Copyright (C) 2011 Andrew Martens %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction dec_fir_async_init(blk)\r\nclog('entering dec_fir_async_init', 'trace');\r\n\r\ndebug_fullscale_output = false;\r\n\r\nvarargin = make_varargin(blk);\r\n\r\n% Declare any default values for arguments you might like.\r\n% Added defaults and fixed the quatization default for 10.1 tools AWL\r\ndefaults = {'n_inputs', 1, 'output_width', 8, 'output_bp', 7, ...\r\n 'coeff', 0.1, ...\r\n 'quantization', 'Round (unbiased: +/- Inf)', ...\r\n 'add_latency', 1, 'mult_latency', 2, 'conv_latency', 2, ...\r\n 'lshift', 1, ...\r\n 'coeff_bit_width', 25, 'coeff_bin_pt', 24, ...\r\n 'absorb_adders', 'on', 'adder_imp', 'DSP48', ...\r\n 'async', 'off', 'bus_input', 'off', 'input_width', 16, ...\r\n 'input_bp', 0, 'input_type', 'Unsigned'};\r\n\r\ncheck_mask_type(blk, 'dec_fir_async');\r\nif same_state(blk, 'defaults', defaults, varargin{:}),\r\n clog('dec_fir_async_init same state', 'trace');\r\n return;\r\nend\r\nclog('dec_fir_init post same_state', 'trace');\r\nmunge_block(blk, varargin{:});\r\n\r\nn_inputs = get_var('n_inputs','defaults', defaults, varargin{:});\r\ncoeff = get_var('coeff', 'defaults', defaults, varargin{:});\r\noutput_width = get_var('output_width', 'defaults', defaults, varargin{:});\r\noutput_bp = get_var('output_bp', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nconv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:});\r\ncoeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:});\r\ncoeff_bin_pt = get_var('coeff_bin_pt', 'defaults', defaults, varargin{:}); \r\nlshift = get_var('lshift', 'defaults', defaults, varargin{:}); \r\nabsorb_adders = get_var('absorb_adders', 'defaults', defaults, varargin{:});\r\nadder_imp = get_var('adder_imp', 'defaults', defaults, varargin{:});\r\nasync_ops = strcmp('on', get_var('async','defaults', defaults, varargin{:}));\r\nbus_input = strcmp('on', get_var('bus_input','defaults', defaults, varargin{:}));\r\ninput_width = get_var('input_width','defaults', defaults, varargin{:});\r\ninput_bp = get_var('input_bp','defaults', defaults, varargin{:});\r\ninput_type = get_var('input_type','defaults', defaults, varargin{:});\r\n\r\n% async_ops = true;\r\n% bus_input = false;\r\n\r\n% default library state\r\nif n_inputs == 0,\r\n clog('no inputs, clearing dec_fir_async block', 'trace');\r\n delete_lines(blk);\r\n clean_blocks(blk);\r\n set_param(blk,'AttributesFormatString','');\r\n save_state(blk, 'defaults', defaults, varargin{:});\r\n clog('exiting dec_fir_async_init', 'trace');\r\n return;\r\nend\r\n\r\n% round coefficients to make sure rounding error doesn't prevent us from\r\n% detecting symmetric coefficients\r\ncoeff_round = round(coeff * 1e16) * 1e-16;\r\n\r\n% check that the number of inputs and coefficients are compatible\r\nif mod(length(coeff) / n_inputs, 1) ~= 0,\r\n error_string = sprintf('The number of coefficients (%d) must be integer multiples of the number of inputs (%d).', length(coeff), n_inputs);\r\n clog(error_string, 'error');\r\n errordlg(error_string);\r\nend\r\n\r\n% how many tap-groups/columns do we need? are the coeffs symmetrical?\r\nnum_fir_col = length(coeff) / n_inputs;\r\ncoeff_sym = false;\r\nfir_col_type = 'fir_col_async';\r\nif mod(length(coeff),2) == 0 && mod(num_fir_col, 2)==0 \r\n if coeff_round(1:length(coeff)/2) == coeff_round(length(coeff):-1:length(coeff)/2+1),\r\n num_fir_col = num_fir_col / 2;\r\n coeff_sym = true;\r\n end\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\n% sync in\r\nsync_latency = mult_latency + (ceil(log2(n_inputs))*add_latency) + conv_latency;\r\nif coeff_sym,\r\n % y(n) = sum(aix(n-i)) for i=0:N. sync is thus related to x(0)\r\n sync_latency = add_latency + sync_latency;\r\nend\r\n% if delay is greater than 17*3 then might as well use logic as using more than 3 SRL16s and sync_delay uses approx 3 (2 comparators, one counter) \r\nif sync_latency > 17*3,\r\n sync_delay_block = 'casper_library_delays/sync_delay';\r\n parm_name = 'DelayLen';\r\nelse \r\n sync_delay_block = 'xbsIndex_r4/Delay';\r\n parm_name = 'latency';\r\nend\r\nreuse_block(blk, 'sync_in', 'built-in/inport', ...\r\n 'Position', [0 20 30 36], 'Port', '1');\r\nreuse_block(blk, 'sync_delay', sync_delay_block, ...\r\n 'Position', [60 8 100 48], ...\r\n parm_name, num2str(sync_latency));\r\n% reuse_block(blk, 'sync_goto', 'built-in/goto', ...\r\n% 'GotoTag', 'sync_in', 'showname', showname, ...\r\n% 'Position', [130, 20, 130+sizex_goto, 20+sizey_goto]);\r\nadd_line(blk, 'sync_in/1', 'sync_delay/1');\r\n% add_line(blk, 'sync_delay/1', 'sync_goto/1');\r\n\r\n% dv in\r\ndv_latency = sync_latency + (ceil(log2(num_fir_col))*add_latency);\r\ndata_port_start = 2;\r\nif async_ops,\r\n if bus_input,\r\n ypos = 200;\r\n else\r\n ypos = n_inputs*60 + 300;\r\n end\r\n data_port_start = 3;\r\n reuse_block(blk, 'dv_in', 'built-in/inport', ...\r\n 'Position', [0 ypos 30 ypos+16], 'Port', '2');\r\n reuse_block(blk, 'dv_delay', 'xbsIndex_r4/Delay', ...\r\n 'Position', [60 ypos-8 100 ypos+32], ...\r\n 'latency', num2str(dv_latency));\r\n reuse_block(blk, 'dv_out', 'built-in/outport', ...\r\n 'Position', [120 ypos 150 ypos+16], 'Port', '3');\r\n add_line(blk, 'dv_in/1', 'dv_delay/1');\r\n add_line(blk, 'dv_delay/1', 'dv_out/1');\r\n% reuse_block(blk, 'dv_goto', 'built-in/goto', ...\r\n% 'GotoTag', 'dv_in', 'showname', showname, ...\r\n% 'Position', [60, 50, 60+sizex_goto, 50+sizey_goto]);\r\n% add_line(blk, 'dv_in/1', 'dv_goto/1');\r\nend\r\n\r\n% data bus in\r\nif bus_input,\r\n reuse_block(blk, 'dbus_in', 'built-in/inport', ...\r\n 'Position', [0 100 30 116], 'Port', num2str(data_port_start));\r\n% reuse_block(blk, 'dbus_goto', 'built-in/goto', ...\r\n% 'GotoTag', 'dbus_in', 'showname', showname, ...\r\n% 'Position', [60, 100, 60+sizex_goto, 100+sizey_goto]);\r\n% add_line(blk, 'dbus_in/1', 'dbus_goto/1');\r\nelse\r\n for ctr = 1:n_inputs,\r\n port_start = data_port_start + ((ctr-1)*2);\r\n reuse_block(blk, ['real',num2str(ctr)], 'built-in/inport', ...\r\n 'Position', [0 90*ctr 30 90*ctr+15], 'Port', num2str(port_start));\r\n reuse_block(blk, ['imag',num2str(ctr)], 'built-in/inport', ...\r\n 'Position', [0 90*ctr+45 30 90*ctr+60], 'Port', num2str(port_start+1));\r\n end\r\nend\r\n\r\n% if we have only one input stream, then first stage of adders\r\n% after multipliers are these adder_trees (otherwise inside cols)\r\nif n_inputs == 1,\r\n first_stage_hdl_external = absorb_adders; \r\nelse\r\n first_stage_hdl_external = 'off';\r\nend\r\n\r\nreuse_block(blk, 'real_sum', 'casper_library_misc/adder_tree', ...\r\n 'Position', [200*num_fir_col+400 300 200*num_fir_col+460 num_fir_col*10+350], ...\r\n 'n_inputs',num2str(num_fir_col),'latency',num2str(add_latency), ...\r\n 'adder_imp', adder_imp, 'first_stage_hdl', first_stage_hdl_external);\r\nreuse_block(blk, 'imag_sum', 'casper_library_misc/adder_tree', ...\r\n 'Position', [200*num_fir_col+400 num_fir_col*10+400 200*num_fir_col+460 num_fir_col*20+450], ...\r\n 'n_inputs',num2str(num_fir_col),'latency',num2str(add_latency), ...\r\n 'adder_imp', adder_imp, 'first_stage_hdl', first_stage_hdl_external);\r\n\r\n% the tap columns\r\nfor ctr = 1:num_fir_col,\r\n blk_name = [fir_col_type, num2str(ctr)];\r\n prev_blk_name = [fir_col_type, num2str(ctr-1)];\r\n \r\n symmet_str = 'off';\r\n async_str = 'off';\r\n binput_str = 'off';\r\n if coeff_sym,\r\n symmet_str = 'on';\r\n end\r\n if async_ops,\r\n async_str = 'on';\r\n end\r\n if bus_input,\r\n binput_str = 'on';\r\n end\r\n reuse_block(blk, blk_name, ['casper_library_downconverter/', fir_col_type], ...\r\n 'Position', [200*ctr+200 50 200*ctr+300 250], 'n_inputs', num2str(n_inputs),...\r\n 'coeff', ['[',num2str(coeff(ctr*n_inputs:-1:(ctr-1)*n_inputs+1)),']'],...\r\n 'mult_latency', num2str(mult_latency), 'add_latency', num2str(add_latency), ...\r\n 'coeff_bit_width', num2str(coeff_bit_width), 'coeff_bin_pt', num2str(coeff_bin_pt), ...\r\n 'adder_imp', adder_imp, 'first_stage_hdl', absorb_adders, ...\r\n 'async', async_str, 'dbl', symmet_str, 'bus_input', binput_str, ...\r\n 'input_width', num2str(input_width), 'input_bp', num2str(input_bp), 'input_type', input_type);\r\n if bus_input,\r\n if ctr == 1,\r\n add_line(blk, 'dbus_in/1', [blk_name, '/1']);\r\n else\r\n add_line(blk, [prev_blk_name, '/1'], [blk_name, '/1']);\r\n end\r\n if coeff_sym,\r\n add_line(blk, [blk_name, '/3'], ['real_sum/', num2str(ctr+1)]);\r\n add_line(blk, [blk_name, '/4'], ['imag_sum/', num2str(ctr+1)]);\r\n else\r\n add_line(blk, [blk_name, '/2'], ['real_sum/', num2str(ctr+1)]);\r\n add_line(blk, [blk_name, '/3'], ['imag_sum/', num2str(ctr+1)]);\r\n end\r\n if async_ops,\r\n if coeff_sym,\r\n add_line(blk, 'dv_in/1', [blk_name, '/3']);\r\n else\r\n add_line(blk, 'dv_in/1', [blk_name, '/2']);\r\n end\r\n end\r\n else\r\n if ctr == 1,\r\n for ctr2 = 1:n_inputs,\r\n add_line(blk, ['real', num2str(ctr2), '/1'], [blk_name, '/', num2str(2*ctr2-1)]);\r\n add_line(blk, ['imag', num2str(ctr2), '/1'], [blk_name, '/', num2str(2*ctr2)]);\r\n end\r\n else\r\n for ctr2 = 1:n_inputs,\r\n add_line(blk, [prev_blk_name, '/', num2str(ctr2*2-1)], [blk_name, '/', num2str(ctr2*2-1)]);\r\n add_line(blk, [prev_blk_name, '/', num2str(ctr2*2)], [blk_name, '/', num2str(ctr2*2)]);\r\n end\r\n end\r\n if coeff_sym,\r\n add_line(blk, [blk_name, '/', num2str(n_inputs*4+1)], ['real_sum/', num2str(ctr+1)]);\r\n add_line(blk, [blk_name, '/', num2str(n_inputs*4+2)], ['imag_sum/', num2str(ctr+1)]);\r\n else\r\n add_line(blk, [blk_name, '/', num2str(n_inputs*2+1)], ['real_sum/', num2str(ctr+1)]);\r\n add_line(blk, [blk_name, '/', num2str(n_inputs*2+2)], ['imag_sum/', num2str(ctr+1)]);\r\n end\r\n if async_ops,\r\n if coeff_sym,\r\n add_line(blk, 'dv_in/1', [blk_name, '/', num2str(n_inputs*4+1)]);\r\n else\r\n add_line(blk, 'dv_in/1', [blk_name, '/', num2str(n_inputs*2+1)]);\r\n end\r\n end\r\n end\r\nend\r\n\r\nreuse_block(blk, 'shift1', 'xbsIndex_r4/Shift', ...\r\n 'shift_dir', 'Left', 'shift_bits', num2str(lshift), ...\r\n 'Position', [200*num_fir_col+500 300 200*num_fir_col+530 315]);\r\nreuse_block(blk, 'shift2', 'xbsIndex_r4/Shift', ...\r\n 'shift_dir', 'Left', 'shift_bits', num2str(lshift), ...\r\n 'Position', [200*num_fir_col+500 500 200*num_fir_col+530 515]);\r\nreuse_block(blk, 'convert1', 'xbsIndex_r4/Convert', ...\r\n 'Position', [200*num_fir_col+560 300 200*num_fir_col+590 315], ...\r\n 'n_bits', num2str(output_width), 'bin_pt', num2str(output_bp), 'arith_type', 'Signed (2''s comp)', ...\r\n 'latency', num2str(conv_latency), 'quantization', quantization);\r\nreuse_block(blk, 'convert2', 'xbsIndex_r4/Convert', ...\r\n 'Position', [200*num_fir_col+560 500 200*num_fir_col+590 515], ...\r\n 'n_bits', num2str(output_width), 'bin_pt', num2str(output_bp), 'arith_type', 'Signed (2''s comp)', ...\r\n 'latency', num2str(conv_latency), 'quantization', quantization);\r\n\r\nreuse_block(blk, 'ri_to_c', 'casper_library_misc/ri_to_c', ...\r\n 'Position', [200*num_fir_col+620 400 200*num_fir_col+650 430]);\r\n\r\nreuse_block(blk, 'sync_out', 'built-in/outport', ...\r\n 'Position', [200*num_fir_col+500 250 200*num_fir_col+530 265], 'Port', '1');\r\nreuse_block(blk, 'dout', 'built-in/outport', ...\r\n 'Position', [200*num_fir_col+680 400 200*num_fir_col+710 415], 'Port', '2');\r\n\r\nadd_line(blk, 'real_sum/2', 'shift1/1');\r\nadd_line(blk, 'imag_sum/2', 'shift2/1');\r\nadd_line(blk, 'shift1/1', 'convert1/1');\r\nadd_line(blk, 'shift2/1', 'convert2/1');\r\nadd_line(blk, 'convert1/1', 'ri_to_c/1');\r\nadd_line(blk, 'convert2/1', 'ri_to_c/2');\r\nadd_line(blk, 'ri_to_c/1', 'dout/1');\r\nadd_line(blk, 'sync_delay/1', 'real_sum/1');\r\nadd_line(blk, 'sync_delay/1', 'imag_sum/1');\r\nadd_line(blk, 'real_sum/1', 'sync_out/1');\r\n\r\n% backward links for symmetric coefficients\r\nif coeff_sym,\r\n if bus_input,\r\n for ctr = 2:num_fir_col,\r\n blk_name = [fir_col_type, num2str(ctr)];\r\n prev_blk_name = [fir_col_type, num2str(ctr-1)];\r\n add_line(blk, [blk_name, '/2'], [prev_blk_name, '/2']);\r\n end\r\n % and the last one feeds back to itself\r\n blk_name = [fir_col_type, num2str(num_fir_col)];\r\n add_line(blk, [blk_name, '/1'], [blk_name, '/2']);\r\n else\r\n for ctr = 1:num_fir_col,\r\n if ctr ~= 1\r\n blk_name = [fir_col_type,num2str(ctr)];\r\n prev_blk_name = [fir_col_type,num2str(ctr-1)];\r\n for ctr2=1:n_inputs,\r\n add_line(blk, [blk_name,'/', num2str(2*n_inputs+ctr2*2-1)], [prev_blk_name, '/', num2str(2*n_inputs+ctr2*2-1)]);\r\n add_line(blk, [blk_name,'/', num2str(2*n_inputs+ctr2*2)], [prev_blk_name, '/', num2str(2*n_inputs+ctr2*2)]);\r\n end\r\n end\r\n end\r\n for ctr = 1:n_inputs,\r\n blk_name = [fir_col_type, num2str(num_fir_col)];\r\n add_line(blk,[blk_name, '/', num2str(ctr*2-1)], [blk_name, '/', num2str(2*n_inputs+ctr*2-1)]);\r\n add_line(blk,[blk_name, '/', num2str(ctr*2)], [blk_name, '/', num2str(2*n_inputs+ctr*2)]);\r\n end\r\n end\r\nend\r\n\r\nif debug_fullscale_output,\r\n if async_ops,\r\n portnum = 4;\r\n else\r\n portnum = 3;\r\n end\r\n reuse_block(blk, 'real_fs', 'built-in/outport', ...\r\n 'Position', [200*num_fir_col+680 370 200*num_fir_col+710 385], 'Port', num2str(portnum));\r\n reuse_block(blk, 'imag_fs', 'built-in/outport', ...\r\n 'Position', [200*num_fir_col+680 430 200*num_fir_col+710 445], 'Port', num2str(portnum+1));\r\n add_line(blk,'real_sum/2','real_fs/1');\r\n add_line(blk,'imag_sum/2','imag_fs/1');\r\nend\r\n\r\n% When finished drawing blocks and lines, remove all unused blocks.\r\nclean_blocks(blk);\r\n\r\n% Set attribute format string (block annotation)\r\nannotation=sprintf('%d taps\\n%d_%d r/i', length(coeff), output_width, output_bp);\r\nset_param(blk,'AttributesFormatString',annotation);\r\n\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\n\r\nclog('exiting dec_fir_async_init', 'trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_fir_taps_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_fir_taps_init.m", "size": 15043, "source_encoding": "utf_8", "md5": "04feaa484e1ef983bbb20f092b49f22e", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% SKA Africa %\n% http://www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (andrew@ska.ac.za) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%TODO Dave's adder width optimisation\n\nfunction pfb_fir_taps_init(blk, varargin)\n clog('entering pfb_fir_taps_init', 'trace');\n\n defaults = { ...\n 'n_streams', 2, ...\n 'n_inputs', 0, ...\n 'pfb_size', 5, ...\n 'n_taps', 4, ...\n 'n_bits_data', 8, ...\n 'n_bits_coeff', 12, ...\n 'bin_pt_coeff', 11, ...\n 'complex', 'on', ...\n 'async', 'on', ...\n 'mult_latency', 2, ...\n 'add_latency', 1, ...\n 'fan_latency', 7, ... %TODO make a mask parameter\n 'bram_latency', 1, ...\n 'multiplier_implementation', 'behavioral HDL', ... 'embedded multiplier core' 'standard core' ...\n 'bram_optimization', 'Area', ... 'Speed', 'Area'\n };\n \n check_mask_type(blk, 'pfb_fir_taps');\n\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n n_streams = get_var('n_streams', 'defaults', defaults, varargin{:});\n n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\n pfb_size = get_var('pfb_size', 'defaults', defaults, varargin{:});\n n_taps = get_var('n_taps', 'defaults', defaults, varargin{:});\n n_bits_data = get_var('n_bits_data', 'defaults', defaults, varargin{:});\n n_bits_coeff = get_var('n_bits_coeff', 'defaults', defaults, varargin{:});\n bin_pt_coeff = get_var('bin_pt_coeff', 'defaults', defaults, varargin{:});\n complex = get_var('complex', 'defaults', defaults, varargin{:});\n async = get_var('async', 'defaults', defaults, varargin{:});\n mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\n add_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\n bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\n fan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:});\n multiplier_implementation = get_var('multiplier_implementation', 'defaults', defaults, varargin{:});\n bram_optimization = get_var('bram_optimization', 'defaults', defaults, varargin{:});\n\n if strcmp(complex, 'on'), mult_factor = 2;\n else, mult_factor = 1;\n end\n\n n_outputs = (2^n_inputs)*n_streams;\n\n delete_lines(blk);\n\n %default empty block for storage in library\n if n_taps == 0 | n_streams == 0,\n clean_blocks(blk);\n set_param(blk, 'AttributesFormatString', '');\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting pfb_fir_taps_init','trace');\n return;\n end\n\n % input ports\n\n reuse_block(blk, 'sync', 'built-in/Inport', 'Port', '1', 'Position', [70 23 100 37]);\n reuse_block(blk, 'dsync', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', 'latency', num2str(fan_latency), ...\n 'Position', [160 20 195 40]);\n add_line(blk, 'sync/1', 'dsync/1');\n \n reuse_block(blk, 'din', 'built-in/Inport', 'Port', '2', 'Position', [70 173 100 187]);\n \n % delays to reduce fanout and help timing\n \n reuse_block(blk, 'ddin0', 'xbsIndex_r4/Delay', 'reg_retiming', 'off', 'latency', num2str(fan_latency), ...\n 'Position', [160 170 195 190]);\n add_line(blk, 'din/1', 'ddin0/1');\n \n reuse_block(blk, 'ddin1', 'xbsIndex_r4/Delay', 'reg_retiming', 'off', 'latency', num2str(fan_latency), ...\n 'Position', [160 320 195 340]);\n add_line(blk, 'din/1', 'ddin1/1');\n\n reuse_block(blk, 'coeffs', 'built-in/Inport', 'Port', '3', 'Position', [70 398 100 412]);\n reuse_block(blk, 'dcoeffs', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', 'latency', num2str(fan_latency), ...\n 'Position', [160 395 195 415]);\n add_line(blk, 'coeffs/1', 'dcoeffs/1');\n\n if strcmp(async, 'on'),\n reuse_block(blk, 'en', 'built-in/Inport', 'Port', '4', 'Position', [70 518 100 532]);\n\n % reduce fanout\n \n reuse_block(blk, 'en_replicate0', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(n_streams * 2^n_inputs * (n_taps-1)), ...\n 'latency', num2str(fan_latency), 'misc', 'off', 'implementation', 'core', ...\n 'Position', [160 433 195 457]);\n add_line(blk, 'en/1', 'en_replicate0/1');\n \n reuse_block(blk, 'en_replicate1', 'casper_library_bus/bus_replicate', ...\n 'replication', num2str(n_streams * 2^n_inputs * n_taps), ...\n 'latency', num2str(fan_latency), 'misc', 'off', 'implementation', 'core', ...\n 'Position', [160 473 195 497]);\n add_line(blk, 'en/1', 'en_replicate1/1');\n \n reuse_block(blk, 'en_replicate2', 'casper_library_bus/bus_replicate', ...\n 'replication', '2', 'latency', num2str(fan_latency), 'implementation', 'core', ...\n 'misc', 'off', 'Position', [160 513 195 537]);\n add_line(blk, 'en/1', 'en_replicate2/1');\n\n reuse_block(blk, 'en_expand', 'casper_library_flow_control/bus_expand', ...\n 'mode', 'divisions of equal size', 'outputNum', '2', ...\n 'outputWidth', '1', 'outputBinaryPt', '0', 'outputArithmeticType', '2', ...\n 'Position', [325 484 375 526]);\n add_line(blk, 'en_replicate2/1', 'en_expand/1');\n\n reuse_block(blk, 'den', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', 'latency', '0', ...\n 'Position', [160 260 195 280]);\n add_line(blk, 'en/1', 'den/1');\n \n end\n\n % sync pipeline\n\n if strcmp(async, 'on'), delay_type = 'casper_library_delays/sync_delay_en';\n else delay_type = 'casper_library_delays/sync_delay';\n end\n\n reuse_block(blk, 'sync_delay', delay_type , ...\n 'DelayLen', '(2^(pfb_size-n_inputs)+add_latency)*(n_taps-1)', ...\n 'Position', [425 13 475 82]);\n add_line(blk, 'dsync/1', 'sync_delay/1');\n \n if strcmp(async, 'on'), add_line(blk, 'en_expand/1', 'sync_delay/2');\n end\n\n reuse_block(blk, 'sync_delay0', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'latency', 'mult_latency+1+add_latency+1', 'Position', [740 36 785 64]);\n add_line(blk, 'sync_delay/1', 'sync_delay0/1');\n \n reuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '1', 'Position', [1000 43 1030 57]);\n add_line(blk, 'sync_delay0/1', 'sync_out/1');\n\n % tap data delays\n\n reuse_block(blk, 'youngest', 'xbsIndex_r4/Slice', ...\n 'nbits', ['(', num2str(mult_factor), '*' , num2str(n_bits_data), ')*', num2str(n_taps-2), '*', num2str(2^n_inputs), '*', num2str(n_streams)], ...\n 'mode', 'Upper Bit Location + Width', 'bit1', '0', 'base1', 'MSB of Input', ...\n 'Position', [70 201 100 219]);\n \n reuse_block(blk, 'ddata0', 'casper_library_bus/bus_delay', ...\n 'n_bits', ['repmat(', num2str(n_bits_data*mult_factor),', 1, ', num2str(n_streams * 2^n_inputs * (n_taps-2)), ')'], ... \n 'latency', num2str(add_latency), 'reg_retiming', 'on', 'cmplx', 'off', 'misc', 'off', ...\n 'enable', async, 'Position', [245 200 275 235]);\n add_line(blk, 'youngest/1', 'ddata0/1');\n if strcmp(async, 'on'), add_line(blk, 'en_replicate0/1', 'ddata0/2');\n end \n\n reuse_block(blk, 'bram_din', 'xbsIndex_r4/Concat', 'num_inputs', '2', 'Position', [335 158 365 242]);\n add_line(blk, 'ddin0/1', 'bram_din/1');\n add_line(blk, 'ddata0/1', 'bram_din/2');\n\n reuse_block(blk, 'ddata1', 'casper_library_bus/bus_delay', ...\n 'n_bits', ['repmat(', num2str(n_bits_data*mult_factor),', 1, ', num2str(n_streams * 2^n_inputs * (n_taps-1)), ')'], ... \n 'latency', num2str(add_latency), 'reg_retiming', 'on', 'cmplx', 'off', 'misc', 'off', ...\n 'enable', async, 'Position', [565 342 595 373]);\n if strcmp(async, 'on'), add_line(blk, 'en_replicate1/1', 'ddata1/2');\n end \n \n reuse_block(blk, 'madd_din', 'xbsIndex_r4/Concat', 'num_inputs', '2', 'Position', [655 313 685 382]);\n add_line(blk, 'ddin1/1', 'madd_din/1');\n add_line(blk, 'ddata1/1', 'madd_din/2');\n\n reuse_block(blk, 'counter', 'xbsIndex_r4/Counter', ...\n 'cnt_type', 'Count Limited', ...\n 'cnt_to', num2str(2^(pfb_size-n_inputs)-bram_latency-1), ...\n 'n_bits', num2str(pfb_size-n_inputs), 'bin_pt', '0', ...\n 'en', async, 'Position', [160 92 220 118]);\n \n if strcmp(async, 'on'), add_line(blk, 'en/1', 'counter/1');\n end\n \n reuse_block(blk, 'we', 'xbsIndex_r4/Constant', ...\n 'const', '1', 'arith_type', 'Boolean', ...\n 'explicit_period', 'on', 'period', '1', ...\n 'Position', [380 227 395 243]);\n\n reuse_block(blk, 'delay_bram', 'casper_library_bus/bus_single_port_ram', ...\n 'n_bits', mat2str(repmat(n_bits_data, 1, mult_factor*n_outputs*(n_taps-1))), ...\n 'bin_pts', mat2str(zeros(1, mult_factor*n_outputs*(n_taps-1))), ...\n 'init_vector', ['repmat(zeros(', mat2str(2^(pfb_size-n_inputs)), ', 1), 1, ', num2str(mult_factor*n_outputs*(n_taps-1)), ')'], ...\n 'max_fanout', '1', 'mem_type', 'Block RAM', 'bram_optimization', bram_optimization, ...\n 'async', async, 'misc', 'off', ...\n 'bram_latency', num2str(bram_latency), 'fan_latency', num2str(fan_latency), ...\n 'addr_register', 'on', 'addr_implementation', 'core', ...\n 'din_register', 'off', 'din_implementation', 'behavioral', ...\n 'we_register', 'off', 'we_implementation', 'behavioral', ...\n 'en_register', 'on', 'en_implementation', 'core', ...\n 'Position', [425 142 480 292]);\n add_line(blk, 'counter/1', 'delay_bram/1');\n add_line(blk, 'bram_din/1', 'delay_bram/2');\n add_line(blk, 'we/1', 'delay_bram/3');\n if strcmp(async, 'on'), \n add_line(blk, 'den/1', 'delay_bram/4');\n reuse_block(blk, 'terminator', 'built-in/Terminator', 'Position', [500 245 520 265]);\n add_line(blk, 'delay_bram/2', 'terminator/1');\n end\n\n add_line(blk,'delay_bram/1', 'ddata1/1', 'autorouting', 'on');\n add_line(blk,'delay_bram/1', 'youngest/1', 'autorouting', 'on');\n\n % coefficient multiplication and add chain\n n_bits_mult = n_bits_coeff+n_bits_data; \n \n reuse_block(blk, 'dummy', 'xbsIndex_r4/Constant', ...\n 'const', '0', 'arith_type', 'Unsigned', ...\n 'n_bits', num2str(n_bits_mult*n_outputs*mult_factor), 'bin_pt', '0', ...\n 'explicit_period', 'on', 'period', '1', ...\n 'Position', [565 429 595 451]);\n \n reuse_block(blk, 'partial_sum', 'xbsIndex_r4/Slice', ...\n 'nbits', num2str(sum([n_bits_mult+n_taps-2:-1:n_bits_mult])*n_outputs*mult_factor), ...\n 'mode', 'Upper Bit Location + Width', 'bit1', '0', 'base1', 'MSB of Input', ...\n 'Position', [565 465 595 485]);\n\n reuse_block(blk, 'tap_chain', 'xbsIndex_r4/Concat', 'Position', [655 423 685 492]);\n add_line(blk, 'dummy/1', 'tap_chain/1');\n add_line(blk, 'partial_sum/1', 'tap_chain/2');\n\n n_bits_c = reshape(repmat([n_bits_mult, [n_bits_mult:n_bits_mult+n_taps-2]], n_outputs*mult_factor, 1), 1, n_outputs*n_taps*mult_factor, 1);\n n_bits_out = reshape(repmat([n_bits_mult:n_bits_mult+n_taps-1], n_outputs*mult_factor, 1), 1, n_outputs*mult_factor*n_taps, 1);\n reuse_block(blk, 'bus_madd', 'casper_library_bus/bus_maddsub', ...\n 'n_bits_a', mat2str(repmat(n_bits_data, 1, mult_factor*n_outputs*n_taps)), ... \n 'bin_pt_a', num2str(n_bits_data-1), 'type_a', '1', 'cmplx_a', 'off', ...\n 'n_bits_b', mat2str(repmat(n_bits_coeff, 1, mult_factor*n_outputs*n_taps)), ...\n 'bin_pt_b', num2str(bin_pt_coeff), 'type_b', '1', ...\n 'mult_latency', num2str(mult_latency+1), ...\n 'multiplier_implementation', 'behavioral HDL', 'replication_ab', 'on', 'opmode', 'Addition', ...\n 'n_bits_c', mat2str(n_bits_c), 'bin_pt_c', num2str(n_bits_data-1+bin_pt_coeff), 'type_c', '1', ...\n 'add_implementation', 'behavioral HDL', 'add_latency', num2str(add_latency), ...\n 'async_add', async, 'align_c', 'off', 'replication_c', 'off', ...\n 'n_bits_out', mat2str(n_bits_out), 'bin_pt_out', num2str(n_bits_data-1+bin_pt_coeff), ...\n 'type_out', '1', 'quantization', '0', 'overflow', '0', ...\n 'add_latency', 'add_latency', 'max_fanout', '1', ...\n 'Position', [735 320 785 545]);\n add_line(blk,'madd_din/1', 'bus_madd/1');\n add_line(blk,'dcoeffs/1', 'bus_madd/2');\n add_line(blk,'tap_chain/1', 'bus_madd/3');\n if strcmp(async, 'on'), add_line(blk, 'en_expand/2', 'bus_madd/4');\n end\n add_line(blk,'bus_madd/1', 'partial_sum/1', 'autorouting', 'on');\n\n reuse_block(blk, 'final_sum', 'xbsIndex_r4/Slice', ...\n 'nbits', num2str((n_bits_mult+n_taps-1)*n_outputs*mult_factor), ...\n 'mode', 'Lower Bit Location + Width', 'bit0', '0', 'base0', 'LSB of Input', ...\n 'Position', [850 369 880 391]);\n add_line(blk,'bus_madd/1', 'final_sum/1');\n\n reuse_block(blk, 'dfinal_sum', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'latency', '1', 'Position', [940 370 975 390]);\n add_line(blk, 'final_sum/1', 'dfinal_sum/1');\n\n reuse_block(blk, 'dout', 'built-in/Outport', 'Port', '2', 'Position', [1000 373 1030 387]);\n add_line(blk,'dfinal_sum/1', 'dout/1');\n\n if strcmp(async, 'on'),\n reuse_block(blk, 'dvalid', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ...\n 'latency', '1', 'Position', [940 480 975 500]);\n add_line(blk, 'bus_madd/2', 'dvalid/1');\n\n reuse_block(blk, 'valid', 'built-in/Outport', 'Port', '3', 'Position', [1000 483 1030 497]);\n add_line(blk, 'dvalid/1', 'valid/1');\n end\n\n clean_blocks(blk);\n set_param(blk, 'AttributesFormatString', '');\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n clog('exiting pfb_fir_taps_init','trace');\n\nend % pfb_fir_taps_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_coeff_gen_calc.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_coeff_gen_calc.m", "size": 2975, "source_encoding": "utf_8", "md5": "a048c53f96fc6d702a677520ae492cfa", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2008 Terry Filiba %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction coeff_vector = pfb_coeff_gen_calc(PFBSize, TotalTaps, WindowType, n_inputs, nput, fwidth, a, debug)\r\n% Calculate the bram coeffiecients for the pfb_coeff_gen block\r\n%\r\n% coeff_vector = pfb_coeff_gen_calc(PFBSize, TotalTaps, WindowType, n_inputs, nput, fwidth, a, debug)\r\n% \r\n% Valid arguments for this block are:\r\n% PFBSize = Size of the FFT (2^FFTSize points).\r\n% TotalTaps = Total number of taps in the PFB\r\n% WindowType = The type of windowing function to use.\r\n% n_inputs = Number of parallel input streams\r\n% nput = Which input this is (of the n_inputs parallel).\r\n% fwidth = The scaling of the bin width (1 is normal).\r\n% a = Index of this rom (passing less than 0 will return all coefficients).\r\n% debug = the coefficients across all inputs and taps form a ramp across the window.\r\n\r\n% set coefficient vector\r\nalltaps = TotalTaps*2^PFBSize;\r\nif a < 0\r\n index = 1 : alltaps;\r\nelse\r\n cs = ((a - 1) * 2^PFBSize) + 1 + nput;\r\n ce = ((a - 1) * 2^PFBSize) + 2^PFBSize;\r\n index = cs : 2^n_inputs : ce;\r\nend\r\nif debug,\r\n coeff_vector = index;\r\nelse\r\n windowval = transpose(window(WindowType, alltaps));\r\n total_coeffs = windowval .* sinc(fwidth * ([0:alltaps-1]/(2^PFBSize)-TotalTaps/2));\r\n coeff_vector = total_coeffs(index);\r\nend\r\n% end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "pfb_fir_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/pfb_fir_init.m", "size": 15476, "source_encoding": "utf_8", "md5": "873b5c5e3b9f1de89a21e95f8beea8dc", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2007 Terry Filiba, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction pfb_fir_init(blk, varargin)\r\n% Initialize and configure the Polyphase Filter Bank.\r\n%\r\n% pfb_fir_init(blk, varargin)\r\n%\r\n% blk = The block to configure.\r\n% varargin = {'varname', 'value', ...} pairs\r\n% \r\n% Valid varnames for this block are:\r\n% PFBSize = The size of the PFB\r\n% TotalTaps = Total number of taps in the PFB\r\n% WindowType = The type of windowing function to use.\r\n% n_inputs = The number of parallel inputs\r\n% MakeBiplex = Double up the PFB to feed a biplex FFT\r\n% BitWidthIn = Input Bitwidth\r\n% BitWidthOut = Output Bitwidth (0 == as needed)\r\n% CoeffBitWidth = Bitwidth of Coefficients.\r\n% CoeffDistMem = Implement coefficients in distributed memory\r\n% add_latency = Latency through each adder.\r\n% mult_latency = Latency through each multiplier\r\n% bram_latency = Latency through each BRAM.\r\n% quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round\r\n% (unbiased: Even Values)'\r\n% fwidth = Scaling of the width of each PFB channel\r\n% coeffs_share = Both polarizations will share coefficients.\r\n\r\nclog('entering pfb_fir_init','trace');\r\n\r\n% Declare any default values for arguments you might like.\r\ndefaults = {'PFBSize', 5, 'TotalTaps', 2, ...\r\n 'WindowType', 'hamming', 'n_inputs', 1, 'MakeBiplex', 'off', ...\r\n 'BitWidthIn', 8, 'BitWidthOut', 0, 'CoeffBitWidth', 18, ...\r\n 'CoeffDistMem', 'off', 'add_latency', 1, 'mult_latency', 2, ...\r\n 'bram_latency', 2, ...\r\n 'quantization', 'Round (unbiased: +/- Inf)', ...\r\n 'fwidth', 1, 'mult_spec', [2 2], ...\r\n 'coeffs_share', 'off', 'coeffs_fold', 'off'};\r\n\r\nif same_state(blk, 'defaults', defaults, varargin{:}), return, end\r\nclog('pfb_fir_init post same_state','trace');\r\ncheck_mask_type(blk, 'pfb_fir');\r\nmunge_block(blk, varargin{:});\r\n\r\nPFBSize = get_var('PFBSize', 'defaults', defaults, varargin{:});\r\nTotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:});\r\nWindowType = get_var('WindowType', 'defaults', defaults, varargin{:});\r\nn_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:});\r\nMakeBiplex = get_var('MakeBiplex', 'defaults', defaults, varargin{:});\r\nBitWidthIn = get_var('BitWidthIn', 'defaults', defaults, varargin{:});\r\nBitWidthOut = get_var('BitWidthOut', 'defaults', defaults, varargin{:});\r\nCoeffBitWidth = get_var('CoeffBitWidth', 'defaults', defaults, varargin{:});\r\nCoeffDistMem = get_var('CoeffDistMem', 'defaults', defaults, varargin{:});\r\nadd_latency = get_var('add_latency', 'defaults', defaults, varargin{:});\r\nmult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:});\r\nfan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:});\r\nbram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:});\r\nquantization = get_var('quantization', 'defaults', defaults, varargin{:});\r\nfwidth = get_var('fwidth', 'defaults', defaults, varargin{:});\r\nmult_spec = get_var('mult_spec', 'defaults', defaults, varargin{:});\r\ncoeffs_share = get_var('coeffs_share', 'defaults', defaults, varargin{:});\r\n\r\n% check the multiplier specifications first off\r\ntap_multipliers = multiplier_specification(mult_spec, TotalTaps, blk);\r\n\r\n% share coeffs in a 2-pol setup?\r\npols = 1;\r\nshare_coefficients = false;\r\nif strcmp(MakeBiplex, 'on'),\r\n pols = 2;\r\n if strcmp(coeffs_share, 'on')\r\n share_coefficients = true;\r\n end\r\nend\r\n\r\n% Compute the maximum gain through all of the 2^PFBSize sub-filters. This is\r\n% used to determine how much bit growth is really needed. The maximum gain of\r\n% each filter is the sum of the absolute values of its coefficients. The\r\n% maximum of these gains sets the upper bound on bit growth through the\r\n% pfb_fir. The products, partial sums, and final sum throughout the pfb_fir\r\n% (including the adder tree) need not accomodate any more bit growth than the\r\n% absolute maximum gain requires, provided that any \"overflow\" is ignored (i.e.\r\n% set to \"Wrap\"). This works thanks to the wonders of modulo math. Note that\r\n% the \"gain\" for typical signals will be different (less) than the absolute\r\n% maximum gain of each filter. For Gaussian noise, the gain of a filter is the\r\n% square root of the sum of the squares of the coefficients (aka\r\n% root-sum-squares or RSS).\r\n\r\n% Get all coefficients of the pfb_fir in one vector (by passing -1 for a)\r\nall_coeffs = pfb_coeff_gen_calc(PFBSize, TotalTaps, WindowType, n_inputs, 0, fwidth, -1, false);\r\n% Rearrange into matrix with 2^PFBSize rows and TotalTaps columns.\r\n% Each row contains coefficients for one sub-filter.\r\nall_filters = reshape(all_coeffs, 2^PFBSize, TotalTaps);\r\n% Compute max gain\r\n% NB: sum rows, not columns!\r\nmax_gain = max(sum(abs(all_filters), 2));\r\n% Compute bit growth (make sure it is non-negative)\r\nbit_growth = max(0, nextpow2(max_gain));\r\n% Compute adder output width and binary point. We know that the adders in the\r\n% adder tree need to have (bit_growth+1) non-fractional bits to accommodate the\r\n% maximum gain. The products from the taps will have\r\n% (BitWidthIn+CoeffBitWidth-2) fractional bits. We will preserve them through\r\n% the adder tree.\r\nadder_bin_pt_out = BitWidthIn + CoeffBitWidth - 2;\r\nadder_n_bits_out = bit_growth + 1 + adder_bin_pt_out;\r\n\r\n% If BitWidthOut is 0, set it to accomodate bit growth in the\r\n% non-fractional part and full-precision of the fractional part.\r\nif BitWidthOut == 0\r\n BitWidthOut = adder_n_bits_out;\r\nend\r\n\r\ndelete_lines(blk);\r\n\r\n% Add ports\r\nclog('adding inports and outports', 'pfb_fir_init_debug');\r\nportnum = 1;\r\nreuse_block(blk, 'sync', 'built-in/inport', ...\r\n 'Position', [0 50*portnum 30 50*portnum+15], 'Port', num2str(portnum));\r\nreuse_block(blk, 'sync_out', 'built-in/outport', ...\r\n 'Position', [150*(TotalTaps+2) 50*portnum 150*(TotalTaps+2)+30 50*portnum+15], 'Port', num2str(portnum));\r\nfor p=1:pols,\r\n for n=1:2^n_inputs,\r\n portnum = portnum + 1; % Skip one to allow sync & sync_out to be 1\r\n in_name = ['pol',num2str(p),'_in',num2str(n)];\r\n out_name = ['pol',num2str(p),'_out',num2str(n)];\r\n reuse_block(blk, in_name, 'built-in/inport', ...\r\n 'Position', [0 50*portnum 30 50*portnum+15], 'Port', num2str(portnum));\r\n reuse_block(blk, out_name, 'built-in/outport', ...\r\n 'Position', [150*(TotalTaps+2) 50*portnum 150*(TotalTaps+2)+30 50*portnum+15], 'Port', num2str(portnum));\r\n end\r\nend\r\n\r\n% Add blocks and Lines\r\nportnum = 0;\r\nfor p=1:pols,\r\n for n=1:2^n_inputs,\r\n portnum = portnum + 1;\r\n in_name = ['pol',num2str(p),'_in',num2str(n)];\r\n out_name = ['pol',num2str(p),'_out',num2str(n)];\r\n \r\n % add the coefficient generators\r\n if (p == 2) && (share_coefficients == true)\r\n blk_name = [in_name,'_delay'];\r\n reuse_block(blk, blk_name, 'xbsIndex_r4/Delay', ...\r\n 'latency', 'bram_latency+1+fan_latency', 'Position', [150 50*portnum 150+100 50*portnum+30]);\r\n add_line(blk, [in_name,'/1'], [blk_name,'/1']);\r\n else\r\n blk_name = [in_name,'_coeffs'];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/pfb_coeff_gen', ...\r\n 'nput', num2str(n-1), 'CoeffDistMem', CoeffDistMem, 'Position', [150 50*portnum 150+100 50*portnum+30]);\r\n propagate_vars([blk,'/',blk_name], 'defaults', defaults, varargin{:});\r\n add_line(blk, [in_name,'/1'], [blk_name,'/1']);\r\n add_line(blk, 'sync/1', [blk_name,'/2']); \r\n end\r\n\r\n clog(['adding taps for pol ', num2str(p), ' input ',num2str(n)], 'pfb_fir_init_debug');\r\n for t = 1:TotalTaps,\r\n % first tap\r\n if t==1,\r\n blk_name = [in_name,'_first_tap'];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/first_tap', ...\r\n 'use_hdl', tap_multipliers(t).use_hdl, 'use_embedded', tap_multipliers(t).use_embedded,...\r\n 'Position', [150*(t+1) 50*portnum 150*(t+1)+100 50*portnum+30]);\r\n propagate_vars([blk,'/',blk_name],'defaults', defaults, varargin{:});\r\n if (p == 2) && (share_coefficients == true)\r\n src_block = [strrep(in_name,'pol2','pol1'),'_coeffs'];\r\n data_source = [in_name,'_delay/1'];\r\n else\r\n src_block = [in_name,'_coeffs'];\r\n data_source = [src_block,'/1'];\r\n end\r\n add_line(blk, data_source, [blk_name,'/1']);\r\n add_line(blk, 'pol1_in1_coeffs/2', [blk_name,'/2']);\r\n add_line(blk, [src_block,'/3'], [blk_name,'/3']);\r\n % last tap\r\n elseif t==TotalTaps,\r\n blk_name = [in_name,'_last_tap'];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/last_tap', ...\r\n 'use_hdl', tap_multipliers(t).use_hdl, 'use_embedded', tap_multipliers(t).use_embedded,...\r\n 'Position', [150*(t+1) 50*portnum 150*(t+1)+100 50*portnum+30]);\r\n propagate_vars([blk,'/',blk_name],'defaults', defaults, varargin{:});\r\n % Update innards of the adder trees using our knowledge of\r\n % maximum bit growth. This uses knowledge of the\r\n % implementation of the \"last_tap\" block. This defeats the\r\n % benefits of encapsulation, but the alternative is to make the\r\n % underlying adder_tree block smarter and then make every block\r\n % that encapsulates or uses an adder_tree smarter. Forcing\r\n % such a global change for one or two specific cases seems a\r\n % greater evil, IMHO.\r\n pfb_add_tree = sprintf('%s/%s/pfb_add_tree', blk, blk_name);\r\n for k=1:2\r\n % Update adder blocks in the adder trees using our\r\n % knowledge of maximum bit growth.\r\n adders = find_system( ...\r\n sprintf('%s/adder_tree%d', pfb_add_tree, k), ...\r\n 'LookUnderMasks','all', 'FollowLinks','on', ...\r\n 'SearchDepth',1, 'RegExp','on', 'Name','^addr');\r\n for kk=1:length(adders)\r\n set_param(adders{kk}, ...\r\n 'precision', 'User Defined', ...\r\n 'arith_type', 'Signed (2''s comp)', ...\r\n 'n_bits', tostring(adder_n_bits_out), ...\r\n 'bin_pt', tostring(adder_bin_pt_out), ...\r\n 'quantization', 'Truncate', ...\r\n 'overflow', 'Wrap');\r\n end\r\n % Adder tree output has bit_growth more non-fractional bits\r\n % than BitWidthIn, but we want to keep the same number of\r\n % non-fractional bits, so we must scale by 2^(-bit_growth).\r\n set_param(sprintf('%s/scale%d', pfb_add_tree, k), ...\r\n 'scale_factor', tostring(-bit_growth));\r\n % Because we have handled bit growth for maximum gain,\r\n % there can be no overflow so the convert blocks can be set\r\n % to \"Wrap\" to avoid unnecessary logic. If BitWidthOut is\r\n % greater than adder_bin_pt_out, set their quantization to\r\n % \"Truncate\" since there is no need to quantize.\r\n if BitWidthOut > adder_bin_pt_out\r\n conv_quant = 'Truncate';\r\n else\r\n conv_quant = quantization;\r\n end\r\n set_param(sprintf('%s/convert%d', pfb_add_tree, k), ...\r\n 'overflow', 'Wrap', 'quantization', conv_quant);\r\n end\r\n if t==2\r\n prev_blk_name = ['pol',num2str(p),'_in',num2str(n),'_first_tap'];\r\n else\r\n prev_blk_name = ['pol',num2str(p),'_in',num2str(n),'_tap',num2str(t-1)];\r\n end\r\n for nn=1:4\r\n add_line(blk, [prev_blk_name,'/',num2str(nn)], [blk_name,'/',num2str(nn)]);\r\n end\r\n add_line(blk, [blk_name,'/1'], [out_name,'/1']);\r\n if n==1 && p==1\r\n add_line(blk, [blk_name,'/2'], 'sync_out/1');\r\n end\r\n % intermediary taps\r\n else\r\n blk_name = ['pol',num2str(p),'_in',num2str(n),'_tap',num2str(t)];\r\n reuse_block(blk, blk_name, 'casper_library_pfbs/tap', ...\r\n 'use_hdl', tap_multipliers(t).use_hdl, 'use_embedded', tap_multipliers(t).use_embedded,...\r\n 'mult_latency',tostring(mult_latency), 'coeff_width', tostring(CoeffBitWidth), ...\r\n 'coeff_frac_width',tostring(CoeffBitWidth-1), 'delay', tostring(2^(PFBSize-n_inputs)), ...\r\n 'data_width',tostring(BitWidthIn), 'bram_latency', tostring(bram_latency), ...\r\n 'Position', [150*(t+1) 50*portnum 150*(t+1)+100 50*portnum+30]);\r\n if t==2,\r\n prev_blk_name = ['pol',num2str(p),'_in',num2str(n),'_first_tap'];\r\n else\r\n prev_blk_name = ['pol',num2str(p),'_in',num2str(n),'_tap',num2str(t-1)];\r\n end\r\n for nn=1:4\r\n add_line(blk, [prev_blk_name,'/',num2str(nn)], [blk_name,'/',num2str(nn)]);\r\n end\r\n end\r\n end\r\n end\r\nend\r\n\r\nclean_blocks(blk);\r\n\r\nfmtstr = sprintf('taps=%d, add_latency=%d\\nmax scale %.3f', ...\r\n TotalTaps, add_latency, max_gain*2^-bit_growth);\r\nset_param(blk, 'AttributesFormatString', fmtstr);\r\nsave_state(blk, 'defaults', defaults, varargin{:});\r\nclog('exiting pfb_fir_init','trace');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "fir_tap_init.m", "ext": ".m", "path": "mlib_devel-master/casper_library/fir_tap_init.m", "size": 5585, "source_encoding": "utf_8", "md5": "e4d7b08fbc797a729c37965fae45537e", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% MeerKAT Radio Telescope Project %\n% www.kat.ac.za %\n% Copyright (C) 2013 Andrew Martens (meerKAT) %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction fir_tap_init(blk, varargin)\n\n defaults = {};\n check_mask_type(blk, 'fir_tap');\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n munge_block(blk, varargin{:});\n\n factor = get_var('factor','defaults', defaults, varargin{:});\n latency = get_var('latency','defaults', defaults, varargin{:});\n coeff_bit_width = get_var('coeff_bit_width','defaults', defaults, varargin{:});\n coeff_bin_pt = get_var('coeff_bin_pt','defaults', defaults, varargin{:});\n\n delete_lines(blk);\n\n %default state in library\n if coeff_bit_width == 0,\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); \n return; \n end\n\n reuse_block(blk, 'a', 'built-in/Inport');\n set_param([blk,'/a'], ...\n 'Port', '1', ...\n 'Position', '[205 68 235 82]');\n\n reuse_block(blk, 'b', 'built-in/Inport');\n set_param([blk,'/b'], ...\n 'Port', '2', ...\n 'Position', '[205 158 235 172]');\n\n reuse_block(blk, 'Constant', 'xbsIndex_r4/Constant');\n set_param([blk,'/Constant'], ...\n 'const', 'factor', ...\n 'n_bits', 'coeff_bit_width', ...\n 'bin_pt', 'coeff_bin_pt', ...\n 'explicit_period', 'on', ...\n 'Position', '[25 36 150 64]');\n\n reuse_block(blk, 'Mult0', 'xbsIndex_r4/Mult');\n set_param([blk,'/Mult0'], ...\n 'n_bits', '18', ...\n 'bin_pt', '17', ...\n 'latency', 'latency', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'off', ...\n 'placement_style', 'Rectangular shape', ...\n 'Position', '[280 37 330 88]');\n\n reuse_block(blk, 'Mult1', 'xbsIndex_r4/Mult');\n set_param([blk,'/Mult1'], ...\n 'n_bits', '18', ...\n 'bin_pt', '17', ...\n 'latency', 'latency', ...\n 'use_behavioral_HDL', 'on', ...\n 'use_rpm', 'off', ...\n 'placement_style', 'Rectangular shape', ...\n 'Position', '[280 127 330 178]');\n\n reuse_block(blk, 'Register0', 'xbsIndex_r4/Register');\n set_param([blk,'/Register0'], ...\n 'Position', '[410 86 455 134]');\n\n reuse_block(blk, 'Register1', 'xbsIndex_r4/Register');\n set_param([blk,'/Register1'], ...\n 'Position', '[410 181 455 229]');\n\n reuse_block(blk, 'a_out', 'built-in/Outport');\n set_param([blk,'/a_out'], ...\n 'Port', '1', ...\n 'Position', '[495 103 525 117]');\n\n reuse_block(blk, 'b_out', 'built-in/Outport');\n set_param([blk,'/b_out'], ...\n 'Port', '2', ...\n 'Position', '[495 198 525 212]');\n\n reuse_block(blk, 'real', 'built-in/Outport');\n set_param([blk,'/real'], ...\n 'Port', '3', ...\n 'Position', '[355 58 385 72]');\n\n reuse_block(blk, 'imag', 'built-in/Outport');\n set_param([blk,'/imag'], ...\n 'Port', '4', ...\n 'Position', '[355 148 385 162]');\n\n add_line(blk,'b/1','Mult1/2', 'autorouting', 'on');\n add_line(blk,'b/1','Register1/1', 'autorouting', 'on');\n add_line(blk,'a/1','Mult0/2', 'autorouting', 'on');\n add_line(blk,'a/1','Register0/1', 'autorouting', 'on');\n add_line(blk,'Constant/1','Mult1/1', 'autorouting', 'on');\n add_line(blk,'Constant/1','Mult0/1', 'autorouting', 'on');\n add_line(blk,'Mult0/1','real/1', 'autorouting', 'on');\n add_line(blk,'Mult1/1','imag/1', 'autorouting', 'on');\n add_line(blk,'Register0/1','a_out/1', 'autorouting', 'on');\n add_line(blk,'Register1/1','b_out/1', 'autorouting', 'on');\n\n % When finished drawing blocks and lines, remove all unused blocks.\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:});\n\nend % fir_tap_init\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "remove_unused_blocks.m", "ext": ".m", "path": "mlib_devel-master/casper_library/simulink_drawing_fns/remove_unused_blocks.m", "size": 2395, "source_encoding": "utf_8", "md5": "36fb8f02e3b72255ddb3d545cd1b4957", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction remove_unused_blocks( cursys )\n%REMOVE_UNUSED_BLOCKS \n% Complimentary block to function 'clean_blocks' which removes blocks\n% with unused input ports. This function deletes a block if all of its\n% output ports are unused.\n\nblocks = get_param(cursys, 'Blocks');\nfor i=1:length(blocks),\n blk = [cursys,'/',blocks{i}];\n ports = get_param(blk, 'PortConnectivity');\n keep_block = 0;\n for j=1:length(ports),\n if ports(j).DstBlock ~= -1,\n keep_block = 1;\n break\n% elseif ~flag && (length(ports(j).SrcBlock) ~= 0 || length(ports(j).DstBlock) ~= 0),\n% flag = 1;\n end\n end\n if keep_block == 0,\n delete_block(blk);\n end\nend\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "test_library.m", "ext": ".m", "path": "mlib_devel-master/casper_library/Tests/test_library.m", "size": 11837, "source_encoding": "utf_8", "md5": "0bb32344ffdd3aa8acc937ae7fc69656", "text": "% function test_library(varargin)\n%\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% tests_file - The file containing the module components to test\n% test_type = Type of test to run ('all', library 'section', individual 'unit')\n% subsection = Name of section when testing library subsection or section containing unit\n% block = Name of individual block to run unit tests for\n\nfunction test_library(varargin)\n\ndefaults = {'tests_file', 'tester_input.txt', 'test_type', 'unit', ...\n 'subsection', 'Misc', 'block', 'adder_tree', 'stop_first_fail', 'on' };\n\ntests_file = get_var('tests_file', 'defaults', defaults, varargin{:});\ntest_type = get_var('test_type', 'defaults', defaults, varargin{:});\nsubsection = get_var('subsection', 'defaults', defaults, varargin{:});\nblock = get_var('block', 'defaults', defaults, varargin{:});\nstop_first_fail = get_var('stop_first_fail', 'defaults', defaults, varargin{:});\n\n%variables used to track number of failures and lines ignored\npassed = 0;\nfailed = 0;\nignore = 0;\n\nfid = fopen(tests_file);\nif (fid == -1),\n fprintf(['File \"', tests_file, '\" not found in local directory.\\n']);\n return\nend\n\n%libraries needing to be loaded expected on first line of tests_file\nlibs_raw = fgetl(fid);\nlinenum = 1;\nif ~ischar(libs_raw),\n disp(['Libraries to load expected on first line of ',tests_file]);\n return;\nend\n\n%go through string getting libraries\nidx = 1;\nlibs = {};\n[lib, remainder] = strtok(libs_raw);\nwhile length(lib) ~= 0,\n libs{idx} = lib;\n idx = idx+1;\n [lib, remainder] = strtok(remainder);\nend;\n\n%load the appropriate libraries\nfor lib_idx = 1:length(libs),\n lib_name = libs{lib_idx};\n if (exist(lib_name, 'file') ~= 4),\n disp(['Library ', lib_name, ' not accessible. Aborting...\\n']);\n return\n else\n warning('off', 'Simulink:SL_LoadMdlParameterizedLink')\n load_system(lib_name);\n fprintf([lib_name, ' loaded\\n']);\n end\nend\n\n%search for subsection to test\nif ~strcmp(test_type, 'all'),\n comment = ' ';\n token = ' ';\n sec = ' ';\n\n %start of subsection demarcated with % # , keep searching till found\n while (~strcmp(comment, '%') || ~strcmp(token, '#') || ~strcmp(sec, subsection)),\n line = fgetl(fid);\n linenum = linenum + 1;\n if ~ischar(line),\n fprintf(['Error reading from file ',tests_file ,', or end of file before subsection ',subsection,' found.\\n']);\n fclose(fid);\n for lib_idx = 1:length(libs),\n close_system(libs{lib_idx})\n end\n return\n end\n [comment, remainder] = strtok(line);\n [token, remainder] = strtok(remainder);\n [sec, remainder] = strtok(remainder);\n end\n fprintf(['Begining of test subsection ', subsection, ' found at line ', num2str(linenum),'\\n']);\n\n blk = ' ';\n section = ' ';\n if strcmp(test_type, 'unit') || strcmp(test_type, 'section from block'),\n %search for tests for block specified until end of section or block found\n while ~((strcmp(blk, '%') && strcmp(section, '#')) || strcmp(blk, block)),\n line = fgetl(fid);\n linenum = linenum + 1;\n if ~ischar(line),\n fprintf(['Error reading from file ',tests_file ,', or end of file before block ',block,' or end of section ',subsection,' found.\\n']);\n fclose(fid);\n for lib_idx = 1:length(libs),\n close_system(libs{lib_idx})\n end\n return\n end\n [blk, remainder] = strtok(line);\n [section, remainder] = strtok(remainder);\n end\n\n %if found end of section without finding block\n if(~strcmp(blk, block)),\n fprintf(['End of subsection ',subsection,' found on line ',num2str(linenum), ' without test for block ',block,'\\n']);\n fclose(fid);\n for lib_idx = 1:length(libs),\n close_system(libs{lib_idx})\n end\n return;\n else\n fprintf(['Unit test(s) for block ', block,' found on line ', num2str(linenum),'\\n']);\n end\n end\nend\n\n%read one extra line if testing subsections\nif strcmp(test_type, 'section'),\n line = fgetl(fid);\n linenum = linenum+1;\nend\n\nfprintf('\\n');\n%run tests\nwhile ischar(line),\n\n %read in the block to be tested and the model file\n [blk, remainder] = strtok(line);\n [libloc, remainder] = strtok(remainder);\n [model, remainder] = strtok(remainder);\n\n %found end of section to be tested and not testing everything\n if (~strcmp(test_type, 'all') && strcmp(blk, '%') && strcmp('#', libloc)),\n fprintf(['End of test subsection ', subsection, ' found at line ', num2str(linenum), '.']);\n break;\n end\n\n %stop if unit testing and (encountered new library subsection or end of unit tests) \n if (strcmp(test_type, 'unit') && (... \n (~strcmp(blk, block) && ~strcmp(blk, '%')) || ...\n (strcmp(blk, '%') && strcmp(libloc, '#')))),\n fprintf(['End of tests for ', block, ' found at line ', num2str(linenum), '.']);\n break;\n end\n\n %if commment just continue\n if strcmp('%', blk) || blk(1) == '%',\n line = fgetl(fid);\n linenum = linenum + 1;\n continue;\n end\n\n err = 1;\n % if there is no block, library location or model file, ignore this line\n if isempty(blk) || isempty(libloc) || isempty(model),\n\n if isempty(blk), \n fprintf(['Library block not specified on line ',linenum, '.\\n']);\n end\n \n if isempty(libloc), \n fprintf(['Location of block in library not specified on line ',linenum, '.\\n']);\n end\n \n if isempty(model), \n fprintf(['Unit test model file not specified on line ',linenum, '.\\n']);\n end\n\n fprintf(['Line read: ',line, '\\n']);\n\n % if the model file does not exist, ignore this line\n elseif (exist(model, 'file') ~= 4),\n fprintf(['Model file ''', model, '.mdl'' does not exist.\\n']);\n % load model and try to find block specified\n else\n\n % try to find library block specified\n lib = [];\n fprintf(['Trying to find library block ', libloc, '...']);\n try\n lib = find_system(libloc);\n catch\n fprintf(' failure\\n');\n err = 1;\n end\n if isempty(lib),\n err = 1;\n else\n fprintf(' success\\n');\n end\n\n % try to find block in model\n fprintf(['Trying to find ', blk, ' in model file ', model, ' ...']);\n \n warning('off', 'Simulink:SL_LoadMdlParameterizedLink')\n load_system(model);\n % finds block with name followed by zero or more digits [0-9]\n thisblk = find_system(model, 'Regexp', 'on', 'name', ['\\<',blk,'[\\d]*\\>']);\n if isempty(thisblk),\n fprintf(' failure\\n');\n else\n fprintf(' success\\n');\n pos = get_param(thisblk, 'Position');\n\n err = 0;\n end\n\n end\n\n %error in unit test setup, ignore line\n if err,\n fprintf('\\n************************************\\n');\n fprintf(['* Ignoring line ', num2str(linenum), '.\\n']);\n fprintf('************************************\\n\\n');\n ignore = ignore + 1;\n \n %if we need to stop on first failure, exit here\n if strcmp(stop_first_fail, 'on'),\n close_system(model, 0);\n break;\n else\n close_system(model, 0);\n end\n\n else\n %add the latest library block to the model\n try\n add_block(libloc, [model, '/', blk, '1']);\n catch\n fprintf(['Error creating ',model,'/',blk,'1',' from ', libloc,'.\\n']);\n err = 1;\n close_system(model, 0);\n end\n\n %set up parameters if no error in creating block\n if ~err,\n %read in block parameters\n vars = {};\n i = 0;\n [name, remainder] = get_token(remainder);\n [value, remainder] = get_token(remainder);\n while (~isempty(name) && ~isempty(value)),\n fprintf(['setting ', name, ' to ', value, '\\n']);\n vars{(i*2)+1} = ['', name, ''];\n vars{(i*2)+2} = value;\n\n %if are dealing with Configurable Subsystem\n if strcmp('BlockChoice', name),\n fprintf('Reconfigurable subsystem detected. Unable to do those.\\n');\n err = 1; \n end\n\n [name, remainder] = get_token(remainder);\n [value, remainder] = get_token(remainder);\n i = i + 1;\n end\n\n set_mask([model, '/', blk, '1'], vars{:});\n end \n \n %set position to the same so lines join ports\n %NOTE must be *after* setting mask params as determine port locations, wont\n %lock on to old inputs\n if ~err,\n delete_block(thisblk{:});\n\n set_param([model, '/', blk, '1'], 'Position', pos{:});\n\n %if no error so far simulate\n fprintf(['simulating ', model, ' ...\\n']);\n sim(model);\n \n if exist([model, '_reference.mat']) ~= 2,\n fprintf([model, '_reference.mat containing reference output not found in path\\n']);\n err = 1; \n end\n\n if exist([model, '_output.mat']) ~= 2,\n fprintf([model, '_output.mat containing simulation output not found\\n']);\n err = 1; \n end\n end\n\n %load reference and output data from file\n if ~err, \n load([model, '_reference'],'reference');\n if exist('reference') ~= 1,\n fprintf(['Variable ''reference'' not found in Workspace\\n']);\n err = 1; \n end\n \n load([model, '_output'],'output');\n if exist('output') ~= 1,\n fprintf(['Variable ''output'' not found in Workspace\\n']);\n err = 1; \n end\n end\n\n %compare reference data to output\n if ~err, \n %check for NaNs and replace with zeros before making comparison\n reference(isnan(reference)) = 0;\n output(isnan(output)) = 0;\n\n if isequal(reference, output),\n fprintf([model, ' passed\\n']);\n passed = passed + 1;\n else\n fprintf('\\n*******************************************************************\\n');\n fprintf([model, ' failed, line ', num2str(linenum), '. Output and reference files differ.\\n']);\n fprintf('*******************************************************************\\n\\n');\n failed = failed + 1;\n\n %if we need to stop on first failure, exit here, leaving model open\n if strcmp(stop_first_fail, 'on'),\n fprintf(['Exiting on first failure as specified\\n\\n']);\n break;\n end\n end\n else\n fprintf('\\n************************************\\n');\n fprintf(['Ignoring line ', num2str(linenum), '.\\n']);\n fprintf('************************************\\n\\n');\n ignore = ignore + 1;\n \n %if we need to stop on first failure, exit here\n if strcmp(stop_first_fail, 'on'),\n fprintf(['Exiting on first failure as specified\\n\\n']);\n break; \n end\n end\n\n close_system(model, 0);\n fprintf('\\n');\n end\n\n line = fgetl(fid);\n linenum = linenum + 1;\nend\n%close unit test file\nfclose(fid);\n\n%close libraries\nfor lib_idx = 1:length(libs),\n close_system(libs{lib_idx})\nend\n\nfprintf('\\n\\n');\nfprintf(['lines ignored: ', num2str(ignore), '\\n']);\nfprintf(['tests passed: ', num2str(passed), '\\n']);\nfprintf(['tests failed: ', num2str(failed), '\\n']);\nif (failed || ignore),\n fprintf('Please see output for more details.\\n');\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get_v.m", "ext": ".m", "path": "mlib_devel-master/casper_library/Tests/get_v.m", "size": 2168, "source_encoding": "utf_8", "md5": "34aca4c2733ff9235a6df03313be4c5c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006-2007 David MacMahon, Aaron Parsons %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction value = get_v(varname, varargin)\r\n% Find the value of varname in varargin. If varname is not found, looks\r\n% for 'defaults' and tries to find varname in there. If any of this fails,\r\n% return Nan.\r\n%\r\n% value = get_var(varname, varargin)\r\n%\r\n% varname = the variable name to retrieve (as a string).\r\n% varargin = {'varname', value, ...} pairs\r\n\r\ni = find(strcmp(varname,varargin));\r\nif i >= 1,\r\n value = varargin{i+1};\r\nelse\r\n value = nan;\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set_mask.m", "ext": ".m", "path": "mlib_devel-master/casper_library/Tests/set_mask.m", "size": 2755, "source_encoding": "utf_8", "md5": "358c188816bbef003c44f5fce8da7023", "text": "% Rewrites mask parameters as strings if short enough, otherwise call to extract.\n%\n% ate_mask( blk, varargin )\n%\n% blk - The block whose mask will be modified\n% varargin - {'var', 'value', ...} pairs\n%\n% Cycles through the list of mask parameter variable names. Appends a new cell\n% with the variable value (extracted from varargin) as a string to a cell array if\n% value short enough, otherwise a call to its value in 'UserData'. Overwrites the\n% 'MaskValues' parameter with this new cell array. Essentially converts any pointers\n% or references to strings in the mask.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 David MacMahon, Aaron Parsons, %\n% Copyright (C) 2008 Andrew Martens %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nfunction set_mask(blk,varargin)\n\n % Match mask names to {variables, values} in varargin\n masknames = get_param(blk, 'MaskNames');\n mv = {};\n for i=1:length(masknames),\n\n varname = masknames{i};\n value = get_v(varname, varargin{:});\n\n if( isa(value,'char')), mv{i} = value;\n else, mv{i} = mat2str(value);\n end\n\n end\n %Back populate mask parameter values\n set_param(blk,'MaskValues',mv); \n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "x64_adc_mask.m", "ext": ".m", "path": "mlib_devel-master/xps_library/x64_adc_mask.m", "size": 5722, "source_encoding": "utf_8", "md5": "8347ff2bb1075c3b4e3d42d1a5eb3cc4", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction x64_adc_mask(blk, varargin)\n\ncheck_mask_type(blk, 'x64_adc');\nmyname = blk;\nuse_spi = get_var('spi', varargin{:});\n\nmunge_block(myname);\n\n\n% create SPI ports if interface enabled\nif use_spi == 1\n % try\n add_block(['built-in/inport'],[myname,'/sdata'],'Position', [510 190 540 210], 'Port', '19');\n add_block(['built-in/inport'],[myname,'/spi_strb' ],'Position', [510 270 540 290], 'Port', '20');\n\n add_block(['xbsIndex_r4/Gateway Out'],[myname,'/user_sdata' ],'Position', [705 190 765 210]);\n add_block(['xbsIndex_r4/Gateway Out'],[myname,'/user_spi_strb' ],'Position', [705 270 765 290]);\n\n add_block(['xbsIndex_r4/Convert'],[myname,'/sdata_conv' ],'Position', [595 185 640 215], ...\n 'arith_type', 'Unsigned', 'n_bits', '8', 'bin_pt', '0');\n add_block(['xbsIndex_r4/Convert'],[myname,'/spi_strb_conv' ],'Position', [595 265 640 295], ...\n 'arith_type', 'Unsigned', 'n_bits', '1', 'bin_pt', '0');\n\n add_block(['built-in/terminator'],[myname,'/sdata_term'],'Position', [845 190 865 210]);\n add_block(['built-in/terminator'],[myname,'/spi_strb_term' ],'Position', [845 270 865 290]);\n\n add_line(myname,'sdata/1','sdata_conv/1');\n add_line(myname,'spi_strb/1' ,'spi_strb_conv/1');\n\n add_line(myname,'sdata_conv/1','user_sdata/1');\n add_line(myname,'spi_strb_conv/1' ,'user_spi_strb/1');\n\n add_line(myname,'user_sdata/1','sdata_term/1');\n add_line(myname,'user_spi_strb/1' ,'spi_strb_term/1');\n %end\n\nelse %delete the SPI ports\n try\n delete_line(myname, 'sdata/1', 'sdata_conv/1');\n delete_line(myname, 'spi_strb/1' , 'spi_strb_conv/1');\n \n delete_line(myname, 'sdata_conv/1', [strrep([myname, '_user_sdata'], '/', '_'), '/1']);\n delete_line(myname, 'spi_strb_conv/1', [strrep([myname, '_user_spi_strb'], '/', '_'), '/1']);\n \n delete_line(myname, [strrep([myname, '_user_sdata'], '/', '_'), '/1'], 'sdata_term/1');\n delete_line(myname, [strrep([myname, '_user_spi_strb'], '/', '_'), '/1'], 'spi_strb_term/1');\n end\n try\n delete_block([myname,'/sdata']);\n delete_block([myname,'/spi_strb']);\n\n delete_block([myname,'/user_sdata']);\n delete_block([myname,'/user_spi_strb']);\n\n delete_block([myname,'/sdata_conv']);\n delete_block([myname,'/spi_strb_conv']);\n\n delete_block([myname,'/sdata_term']);\n delete_block([myname,'/spi_strb_term']);\n end\nend\n\nclean_blocks(myname);\n\n% relabel the gateway ins...\ngateway_ins = find_system(gcb,'searchdepth',1,'FollowLinks', 'on', 'lookundermasks','all','masktype','Xilinx Gateway In Block');\nfor n = 1:length(gateway_ins)\n gw = gateway_ins{n};\n if regexp(get_param(gw,'Name'),'(user_data\\d+)$')\n toks = regexp(get_param(gw,'Name'),'(user_data\\d+)$','tokens');\n set_param(gw,'Name',clear_name([gcb,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(user_chan_sync)$')\n toks = regexp(get_param(gw,'Name'),'(user_chan_sync)$','tokens');\n set_param(gw,'Name',clear_name([gcb,'_',toks{1}{1}]));\n else\n error(['Unknown gateway name: ',gw]);\n end\nend \n\n% relabel the gateway outs...\ngateway_outs = find_system(gcb,'searchdepth',1,'FollowLinks', 'on', 'lookundermasks','all','masktype','Xilinx Gateway Out Block');\nfor n = 1:length(gateway_outs)\n gw = gateway_outs{n};\n if regexp(get_param(gw,'Name'),'(user_rst)$')\n toks = regexp(get_param(gw,'Name'),'(user_rst)$','tokens');\n set_param(gw,'Name',clear_name([gcb,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(user_sdata)$')\n toks = regexp(get_param(gw,'Name'),'(user_sdata)$','tokens');\n set_param(gw,'Name',clear_name([gcb,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(user_spi_strb)$')\n toks = regexp(get_param(gw,'Name'),'(user_spi_strb)$','tokens');\n set_param(gw,'Name',clear_name([gcb,'_',toks{1}{1}]));\n else\n error(['Unknown gateway name: ',gw]);\n end\nend\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "eval_param.m", "ext": ".m", "path": "mlib_devel-master/xps_library/eval_param.m", "size": 3467, "source_encoding": "utf_8", "md5": "01ba08e7c4d8ea103d17775a17d054dc", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction result = eval_param(blk,param_name)\n\nparam_str = get_param(blk,param_name);\nresult = param_str;\n\n% If param_str is empty, we're done!\nif isempty(param_str)\n return;\nend\n\n% If it is not an evaluated parameter, we're done!\nmask_vars = get_param(blk, 'MaskVariables');\npattern = sprintf('(^|;)%s=@\\\\d+', param_name);\nmv_match = regexp(mask_vars, pattern, 'match', 'once');\nif isempty(mv_match)\n return;\nend\n\n% If it is not an edit field parameter, we're done! Some non-edit fields like\n% checkbox and popup are set to \"evaluate\" even though it makes no sense to\n% evaluate their values. Because of this, we need to check explicitly whether\n% this parameter value comes from an edit field.\n%\n% Parse mask variable index from matched portion of MaskVariables.\n% (Is there a better way to do this?)\nmv_idx = str2num(regexp(mv_match, '\\d+', 'match', 'once'));\n% Get cell array of all mask styles\nmask_styles = get_param(blk, 'MaskStyles');\nif ~strcmp(mask_styles{mv_idx}, 'edit')\n return;\nend\n\ntry\n result = eval(param_str);\ncatch\n\n\tparents = {};\n\tparent = blk;\n\twhile ~isempty(parent)\n\t\tparents = [{parent},parents];\n\t\tparent = get_param(parent,'parent');\n\tend\n\n\tfor i=1:length(parents)\n\t\tparent = parents{i};\n\t\tif strcmp(get_param(parent,'type'),'block_diagram')\n\t\t\tws = get_param(parent,'ModelWorkSpace');\n\t\t\tif ismethod(ws, 'whos')\n\t\t\t\tws_arry = ws.whos;\n\t\t\t\tfor i=1:length(ws_arry)\n\t\t\t\t\tws_var = ws_arry(i);\n\t\t\t\t\t\tval = ws.evalin(ws_var.name);\n\t\t\t\t\teval([ws_var.name,' = val;']);\n\t\t\t\tend\n\t\t\tend\n\t\telseif strcmp(get_param(parent,'type'),'block')\n\t\t\tws_arry = get_param(parent,'MaskWSVariables');\n\t\t\tfor i=1:length(ws_arry)\n\t\t\t eval([ws_arry(i).Name,' = ws_arry(i).Value;']);\n\t\t\tend\n\t\telse\n\t\t\terror('Unsupported block type');\n\t\tend\n\tend\n\n\tresult = eval(param_str);\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "load_hw_routes.m", "ext": ".m", "path": "mlib_devel-master/xps_library/load_hw_routes.m", "size": 1885, "source_encoding": "utf_8", "md5": "994fa2676c9628ed02e0b1f977da29fe", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://casper.berkeley.edu/ %\n% Copyright (C) 2013 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction load_hw_routes()\n hw_routes_file = getenv('CASPER_HW_ROUTES');\n if isempty(hw_routes_file)\n hw_routes_file = 'hw_routes.mat';\n end\n evalin('caller', ['load(''',hw_routes_file,''')']);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "casper_xps.m", "ext": ".m", "path": "mlib_devel-master/xps_library/casper_xps.m", "size": 15977, "source_encoding": "utf_8", "md5": "9b67c081216fb455b94770a3b6749194", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction varargout = casper_xps(varargin)\n% CASPER_XPS CASPER Xilinx ISE Batch Tools GUI\n\n% Last Modified by GUIDE v2.5 09-Oct-2012 12:36:59\n\nif nargin == 0 % LAUNCH GUI\n\n fig = openfig(mfilename,'reuse');\n\n % Use system color scheme for figure:\n set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));\n\n % Generate a structure of handles to pass to callbacks, and store it.\n handles = guihandles(fig);\n guidata(fig, handles);\n\n if nargout > 0\n varargout{1} = fig;\n end\n if ~isempty(gcs)\n set(handles.design_name,'String',gcs);\n end\n\n\n %get the Xilinx Sysgen version\n xsg = xlVersion;\n\n try\n xsg = strtok(xsg{1},' ');\n catch\n xsg = get_xlVersion('full');\n end\n\n switch xsg\n case {'11.3.2055'}\n set(handles.xsg_version,'String','11.3');\n case {'11.4.2254'}\n set(handles.xsg_version,'String','11.4');\n case {'11.5.2275'}\n set(handles.xsg_version,'String','11.5');\n case {'13.3'}\n set(handles.xsg_version,'String','13.3');\n case {'14.2'}\n set(handles.xsg_version,'String','14.2');\n case {'14.3'}\n set(handles.xsg_version,'String','14.3');\n case {'14.4'}\n set(handles.xsg_version,'String','14.4');\n case {'14.5'}\n set(handles.xsg_version,'String','14.5');\n case {'14.6'}\n set(handles.xsg_version,'String','14.6');\n case {'14.7'}\n set(handles.xsg_version,'String','14.7');\n otherwise\n errordlg(['Unsupported Xilinx System Generator version: ',xsg]);\n return;\n end\n\nelseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK\n\n try\n if (nargout)\n [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard\n else\n feval(varargin{:}); % FEVAL switchyard\n end\n catch ex\n disp(ex.message);\n end\n\nend\n\n\n%| ABOUT CALLBACKS:\n%| GUIDE automatically appends subfunction prototypes to this file, and\n%| sets objects' callback parameters to call them through the FEVAL\n%| switchyard above. This comment describes that mechanism.\n%|\n%| Each callback subfunction declaration has the following form:\n%| (H, EVENTDATA, HANDLES, VARARGIN)\n%|\n%| The subfunction name is composed using the object's Tag and the\n%| callback type separated by '_', e.g. 'slider2_Callback',\n%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.\n%|\n%| H is the callback object's handle (obtained using GCBO).\n%|\n%| EVENTDATA is empty, but reserved for future use.\n%|\n%| HANDLES is a structure containing handles of components in GUI using\n%| tags as fieldnames, e.g. handles.figure1, handles.slider2. This\n%| structure is created at GUI startup using GUIHANDLES and stored in\n%| the figure's application data using GUIDATA. A copy of the structure\n%| is passed to each callback. You can store additional information in\n%| this structure at GUI startup, and you can change the structure\n%| during callbacks. Call guidata(h, handles) after changing your\n%| copy to replace the stored original so that subsequent callbacks see\n%| the updates. Type \"help guihandles\" and \"help guidata\" for more\n%| information.\n%|\n%| VARARGIN contains any extra arguments you have passed to the\n%| callback. Specify the extra arguments by editing the callback\n%| property in the inspector. By default, GUIDE sets the property to:\n%| ('', gcbo, [], guidata(gcbo))\n%| Add any extra arguments after the last argument, before the final\n%| closing parenthesis.\n\n\n\n% --------------------------------------------------------------------\nfunction varargout = listbox1_Callback(h, eventdata, handles, varargin)\n\n\n\n\n% --------------------------------------------------------------------\nfunction varargout = run_Callback(h, eventdata, handles, varargin)\ndesign_name = get(handles.design_name,'String');\nxsg_version = get(handles.xsg_version,'Value');\n\nflow_vec.update = get(handles.run_update ,'Value');\nflow_vec.drc = get(handles.run_drc ,'Value');\nflow_vec.xsg = get(handles.run_xsg ,'Value');\nflow_vec.copy = get(handles.run_copy ,'Value');\nflow_vec.ip = get(handles.run_ip ,'Value');\nflow_vec.edkgen = get(handles.run_edkgen ,'Value');\nflow_vec.elab = get(handles.run_elab ,'Value');\nflow_vec.software = get(handles.run_software,'Value');\nflow_vec.edk = get(handles.run_edk ,'Value');\n\ntry\n [time_total, time_struct] = gen_xps_files(design_name,flow_vec);\n disp('===================================================================');\n disp(['Flow run time summary: (',datestr(time_total,13),' seconds total)']);\n disp([' System update............',datestr(time_struct.update ,13)]);\n disp([' Design Rules Check.......',datestr(time_struct.drc ,13)]);\n disp([' Xilinx System Generator..',datestr(time_struct.xsg ,13)]);\n disp([' Base system copy.........',datestr(time_struct.copy ,13)]);\n disp([' IP creation..............',datestr(time_struct.ip ,13)]);\n disp([' EDK files creation.......',datestr(time_struct.edkgen ,13)]);\n disp([' IP elaboration...........',datestr(time_struct.elab ,13)]);\n disp([' Software creation........',datestr(time_struct.software,13)]);\n disp([' EDK/ISE backend..........',datestr(time_struct.edk ,13)]);\n disp('===================================================================');\n msgbox(['CASPER XPS run successfully completed in ',datestr(time_total,13),'!']);\ncatch\n disp(lasterr);\n errordlg('Error detected running CASPER XPS, please check Matlab command window for error messages');\nend\n\n\n\n\n% --------------------------------------------------------------------\nfunction varargout = view_log_Callback(h, eventdata, handles, varargin)\nsys = get(handles.design_name,'String');\nview_choice = get(handles.log_menu,'Value');\nview_shortcuts = get(handles.log_menu,'String');\n\n\nxps_xsg_blks = find_system(sys,'FollowLinks','on','LookUnderMasks','all','Tag','xps:xsg');\nif length(xps_xsg_blks) ~= 1\n error('There has to be only 1 XPS_xsg block on each chip level (sub)system');\nend\nxsg_blk = xps_xsg_blks{1};\n\nsysgen_blk = find_system(sys, 'SearchDepth', 1,'FollowLinks','on','LookUnderMasks','all','Tag','genX');\nif length(sysgen_blk) ~= 1\n error('XPS_xsg block must be on the same level as the Xilinx SysGen block');\nend\n\n\n[hw_sys, hw_subsys] = xps_get_hw_plat(get_param(xsg_blk,'hw_sys'));\nwork_path = [pwd,'\\',clear_name(get_param(xsg_blk,'parent'))];\nxps_path = [work_path,'\\XPS_',hw_sys,'_base'];\nxsg_path = [work_path,'\\sysgen'];\n\nxsg_core_name = clear_name(get_param(xsg_blk,'parent'));\ndesign_name = [xsg_core_name,'_clk_wrapper'];\n\n\nswitch view_shortcuts{view_choice}\n case 'EDK Log'\n if ~exist([xps_path,'/system.log'])\n errordlg('EDK log file does not exist, please make sure you have run EDK/ISE step first.');\n return;\n end\n edit([xps_path,'/system.log']);\n case 'XFLOW Log'\n if ~exist([xps_path,'/implementation/xflow.log'])\n errordlg('XFLOW log file does not exist, please make sure you have run EDK/ISE step first.');\n return;\n end\n edit([xps_path,'/implementation/xflow.log']);\n case 'MAP Report'\n if ~exist([xps_path,'/implementation/system_map.mrp'])\n errordlg('MAP report file does not exist, please make sure you have run EDK/ISE step first.');\n return;\n end\n edit([xps_path,'/implementation/system_map.mrp']);\n case 'Timing Report'\n if ~exist([xps_path,'/implementation/system.twr'])\n errordlg('Timing report file does not exist, please make sure you have run EDK/ISE step first.');\n return;\n end\n edit([xps_path,'/implementation/system.twr']);\n otherwise\n error(['Unkown log choice: ',view_shortcuts{view_choice}]);\nend\nreturn;\n\n\n% --------------------------------------------------------------------\nfunction varargout = get_gcs_Callback(h, eventdata, handles, varargin)\nset(handles.design_name,'String',gcs);\nreturn;\n\n\n% --------------------------------------------------------------------\nfunction varargout = open_sys_Callback(h, eventdata, handles, varargin)\ndesign_name = get(handles.design_name,'String');\nif isempty(gcs) | ~strcmp(gcs,design_name)\n try\n open_system(design_name);\n catch\n errordlg(sprintf('Error cannot open system %c%s%c',39, design_name, 39));\n return;\n end\nend\nreturn;\n\n\n\n% --- Executes on button press in run_mode.\nfunction run_mode_Callback(hObject, eventdata, handles)\n% hObject handle to run_mode (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of run_mode\n\n\n\n\n% --- Executes on button press in run_elab.\nfunction run_elab_Callback(hObject, eventdata, handles)\n% hObject handle to run_elab (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of run_elab\n\n\n% --- Executes on selection change in design_flow.\nfunction design_flow_Callback(hObject, eventdata, handles)\n% hObject handle to design_flow (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = get(hObject,'String') returns design_flow contents as cell array\n% contents{get(hObject,'Value')} returns selected item from design_flow\n\nflow_shortcuts = get(handles.design_flow,'String');\nflow_choice = get(handles.design_flow,'Value');\nswitch flow_shortcuts{flow_choice}\n case 'Complete Build'\n \tset(handles.run_update ,'Value',1);\n \tset(handles.run_drc ,'Value',1);\n \tset(handles.run_xsg ,'Value',1);\n \tset(handles.run_copy ,'Value',1);\n \tset(handles.run_ip ,'Value',1);\n \tset(handles.run_edkgen ,'Value',1);\n \tset(handles.run_elab ,'Value',1);\n \tset(handles.run_software,'Value',1);\n \tset(handles.run_edk ,'Value',1);\n case 'Software Only'\n \tset(handles.run_update ,'Value',0);\n \tset(handles.run_drc ,'Value',0);\n \tset(handles.run_xsg ,'Value',0);\n \tset(handles.run_copy ,'Value',0);\n \tset(handles.run_ip ,'Value',0);\n \tset(handles.run_edkgen ,'Value',0);\n \tset(handles.run_elab ,'Value',0);\n \tset(handles.run_software,'Value',1);\n \tset(handles.run_edk ,'Value',1);\n case 'Download'\n \tset(handles.run_update ,'Value',0);\n \tset(handles.run_drc ,'Value',0);\n \tset(handles.run_xsg ,'Value',0);\n \tset(handles.run_copy ,'Value',0);\n \tset(handles.run_ip ,'Value',0);\n \tset(handles.run_edkgen ,'Value',0);\n \tset(handles.run_elab ,'Value',0);\n \tset(handles.run_software,'Value',0);\n \tset(handles.run_edk ,'Value',0);\n otherwise\n error(['Unknown design flow shortcut: ',flow_shortcuts{flow_choice}]);\nend\n\n\n\n% --- Executes on button press in run_ip.\nfunction run_ip_Callback(hObject, eventdata, handles)\n% hObject handle to run_ip (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of run_ip\n\n\n\n\n% --- Executes on button press in run_copy.\nfunction run_copy_Callback(hObject, eventdata, handles)\n% hObject handle to run_copy (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of run_copy\n\n\n\n\n\nfunction design_name_Callback(hObject, eventdata, handles)\n% hObject handle to design_name (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of design_name as text\n% str2double(get(hObject,'String')) returns contents of design_name as a double\n\n\n\n\n% --- Executes on button press in run_edk.\nfunction run_edk_Callback(hObject, eventdata, handles)\n% hObject handle to run_edk (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of run_edk\n\n\n\n\n% --- Executes on button press in run_xsg.\nfunction run_xsg_Callback(hObject, eventdata, handles)\n% hObject handle to run_xsg (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of run_xsg\n\n\n\n\n% --- Executes on button press in run_software.\nfunction run_software_Callback(hObject, eventdata, handles)\n% hObject handle to run_software (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of run_software\n\n\n\n\n% --- Executes on button press in run_edkgen.\nfunction run_edkgen_Callback(hObject, eventdata, handles)\n% hObject handle to run_edkgen (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of run_edkgen\n\n\n% --- Executes on button press in run_drc.\nfunction run_drc_Callback(hObject, eventdata, handles)\n% hObject handle to run_drc (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of run_drc\n\n\n% --- Executes on button press in run_update.\nfunction run_update_Callback(hObject, eventdata, handles)\n% hObject handle to run_update (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of run_update\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_get_hw_plat.m", "ext": ".m", "path": "mlib_devel-master/xps_library/xps_get_hw_plat.m", "size": 1951, "source_encoding": "utf_8", "md5": "fa0f186aeb058437f9c2fbc43e48ef28", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [hw_sys,hw_subsys] = xps_get_hw_plat(str)\ntmp = regexp(str, '^(\\w+)\\:?(.*)','tokens');\nif ~isempty(tmp)\n hw_sys = tmp{1}{1};\n hw_subsys = tmp{1}{2};\nelse\n error(['Hardware platform format should be \"hardware_system:hardware_subsystem\": ',str]);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_get_hw_info.m", "ext": ".m", "path": "mlib_devel-master/xps_library/xps_get_hw_info.m", "size": 1938, "source_encoding": "utf_8", "md5": "31031779c9681243c6814bd3eb6e7e5c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [hw_sys,info] = xps_get_hw_info(str)\ntmp = regexp(str,'^(\\w+)\\:(\\w+)','tokens');\nif ~isempty(tmp)\n hw_sys = tmp{1}{1};\n info = tmp{1}{2};\nelse\n error(['Hardware information format should be \"hardware_system:hardware_feature\": ',str]);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "clear_name.m", "ext": ".m", "path": "mlib_devel-master/xps_library/clear_name.m", "size": 2187, "source_encoding": "utf_8", "md5": "f5a3b1b57af8b6baf8028281312197b1", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction result = clear_name(str);\nfor i = 1:length(str)\n c = str(i);\n if c<48 | (c>57 & c<65) | (c>90 & c<95) | c==96 | c>122\n result(i) = '_';\n else\n result(i) = str(i);\n end\nend\n%recombine multiple '_'\nwhile ~isempty(findstr(result, '__'))\n result = strrep(result,'__','_');\nend\n%remove tail '_'\nif strcmp(result(length(result)),'_');\n result = result(1:length(result)-1);\nend\n%remove head '_'\nif strcmp(result(1),'_');\n result = result(2:length(result));\nend\nreturn;\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_xps_files.m", "ext": ".m", "path": "mlib_devel-master/xps_library/gen_xps_files.m", "size": 28175, "source_encoding": "utf_8", "md5": "a60739fb081cc1d97d5e9cfa7e7a33c9", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [time_total, time_struct] = gen_xps_files(sys, flow_vec)\n% Generate all necessary file and optionally run the Xilinx backend tools\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Initialization\n% At the end of initialization, the following variables are set:\n% run_* : 1 if that step is needed\n% xps_blks : All the blocks with tags xps:*\n% xsg_blk : Point to the Xilinx System Generator block of the system\n% xps_pcore_blks: All the pcore blocks tagged tiwh xps:pcore\n% XPS_BASE_PATH: Sets to the value of the environment var of same name\n% Also, all the necessary directories have been created.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% close all previously opened files\nfclose('all');\n\n% flow step options\nif nargin == 2 && isstruct(flow_vec),\n run_update = flow_vec.update ;\n run_drc = flow_vec.drc ;\n run_xsg = flow_vec.xsg ;\n run_copy = flow_vec.copy ;\n run_ip = flow_vec.ip ;\n run_edkgen = flow_vec.edkgen ;\n run_elab = flow_vec.elab ;\n run_software = flow_vec.software;\n run_edk = flow_vec.edk ;\nelse\n run_update = 1;\n run_drc = 1;\n run_xsg = 1;\n run_copy = 1;\n run_ip = 1;\n run_edkgen = 1;\n run_elab = 1;\n run_software = 1;\n run_edk = 1;\nend\n\nslash = '\\';\n[s, w] = system('uname -a');\n\nif s ~= 0\n [s, w] = system('ver');\n if s ~= 0,\n disp(sprint('Could not detect OS, assuming Windows'));\n elseif ~isempty(regexp(w,'Windows', 'ONCE')),\n fprintf('Detected Windows OS\\n');\n else\n fprintf('Detected Unknown Windows-like OS\\n');\n end\n system_os = 'windows';\nelseif ~isempty(regexp(w, 'Linux', 'ONCE')),\n slash = '/';\n fprintf('Detected Linux OS\\n');\n system_os = 'linux';\nelse\n slash = '/';\n fprintf('Detected Unknown Unix-like OS\\n');\n system_os = 'linux';\nend\n\n% search for blocks in the system\nxps_blks = find_system(sys, 'FollowLinks', 'on', 'LookUnderMasks', 'all','RegExp','on', 'Tag', '^xps:');\nxps_xsg_blks = find_system(sys, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'Tag', 'xps:xsg');\nxps_pcore_blks = find_system(sys, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'Tag', 'xps:pcore');\nsysgen_blk = find_system(sys, 'FollowLinks', 'on', 'LookUnderMasks', 'all','SearchDepth', 1, 'Tag', 'genX');\ncasper_blks = find_system(sys, 'FollowLinks', 'on', 'LookUnderMasks', 'all','RegExp','on', 'Tag', '^casper:');\n\n% check for spaces in xps or casper block names\nfor ctr = 1 : numel(xps_blks),\n % Allow 'XSG core config' block to have spaces\n if numel(strfind(xps_blks{ctr}, ' ')) > 0 && ~regexpi(xps_blks{ctr}, 'XSG core config$'),\n error('Block names may not have spaces - %s', xps_blks{ctr});\n end \nend\nfor ctr = 1 : numel(casper_blks),\n if numel(strfind(casper_blks{ctr}, ' ')) > 0,\n error('Block names may not have spaces - %s', casper_blks{ctr});\n end \nend\n\n% check if the system name is correct\nif upper(sys(1)) == sys(1),\n error('Due to EDK toolflow limitations, the system name cannot start with an upper case letter');\nend\n\nif length(xps_xsg_blks) ~= 1,\n error('There has to be exactly 1 XPS_XSG block on each chip level (sub)system (Is the current system the correct one ?)');\nend\n\nif length(sysgen_blk) == 1,\n xsg_blk = sysgen_blk{1};\nelse\n error('XPS_xsg block must be on the same level as the Xilinx SysGen block. Have you put a XSG block in you design, and is the current system the correct one?');\nend\n\n% cd into the design directory\nsys_file = get_param(sys,'FileName');\n[sys_dir, ~, ~] = fileparts(sys_file);\ncd(sys_dir);\n\n% comb for gateway in blocks that aren't part of a yellow block\ngateways_blk = find_system(sys, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'masktype', 'Xilinx Gateway In Block');\nfor i = 1:length(gateways_blk),\n found_xps_tag = 0;\n parent = get_param(gateways_blk(i), 'parent');\n gw_parent = parent;\n\n while ~strcmp(parent, '')\n parent_tag = char(get_param(parent, 'tag'));\n if ~isempty(regexp(parent_tag, '^xps:', 'ONCE')),\n found_xps_tag = 1;\n end\n parent = get_param(parent,'parent');\n end\n\n if found_xps_tag == 0,\n disregard_blocks = find_system(gw_parent, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'masktype', 'Xilinx Disregard Subsystem For Generation');\n if isempty(disregard_blocks),\n error('Xilinx input gateways cannot be used in a design. Only XPS GPIO blocks should be used.');\n end\n end\nend\n\n% set design paths\nXPS_BASE_PATH = getenv('XPS_BASE_PATH');\nif isempty(XPS_BASE_PATH),\n XPS_BASE_PATH = fullfile(getenv('MLIB_DEVEL_PATH'), 'xps_base');\n if isempty(XPS_BASE_PATH),\n error('Environment variable XPS_BASE_PATH or MLIB_DEVEL_PATH must be defined');\n end\nend\n\nsimulink_path = pwd;\ndesign_name = clear_name(get_param(xsg_blk,'parent'));\nwork_path = [simulink_path, slash, clear_name(get_param(xsg_blk,'parent'))];\nsrc_path = [work_path, slash, 'src'];\nxsg_path = [work_path, slash, 'sysgen'];\nbit_path = [work_path, slash, 'bit_files'];\nnetlist_path = [work_path, slash, 'netlist'];\n\n% check paths\nif ~isempty(strfind(simulink_path, ' ')),\n warndlg(['Working directory ', simulink_path, ' has a space in the pathname. This can cause problems with some of the tools. Please change your working directory.']);\n error('Working directory has a space in the pathname.');\nend\n\nif ~isempty(strfind(XPS_BASE_PATH, ' ')),\n warndlg(['Directory specified by the XPS_BASE_PATH environment variable (', XPS_BASE_PATH, ') has a space in the pathname. This can cause problems with some of the tools. Please change its directory.']);\n error('Directory specified by the XPS_BASE_PATH environment variable has a space in the pathname.');\nend\n\n% create design paths if non-existent\nif exist(work_path,'dir') ~= 7,\n mkdir(pwd,clear_name(get_param(xsg_blk,'parent')));\nend\n\nif exist(src_path,'dir') ~= 7,\n mkdir(work_path,'src');\nend\n\nif exist(bit_path,'dir') ~= 7,\n mkdir(work_path,'bit_files');\nend\n\nif exist(netlist_path,'dir') ~= 7,\n mkdir(work_path,'netlist');\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Task: System Update (run_update)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nstart_time = now;\nif run_update\ndisp('#############################');\ndisp('## System Update ##');\ndisp('#############################');\n % update the current system\n set_param(sys, 'SimulationCommand', 'update');\nend\ntime_update = now - start_time;\n\n% Access all XPS blocks\ndisp('#############################');\ndisp('## Block objects creation ##');\ndisp('#############################');\n\nxps_objs = {};\ncustom_xps_objs = {};\ncore_types = {};\n\n% Find and creates xsg_obj (An object of xps_xsg)\nfor n = 1:length(xps_blks),\n if strcmp(get_param(xps_blks(n),'tag'),'xps:xsg')\n try\n xsg_obj = xps_block(xps_blks{n},{});\n xsg_obj = xps_xsg(xsg_obj);\n catch ex\n disp(['Problem with XSG block: ',xps_blks{n}]);\n warning(ex.identifier, '%s', ex.getReport('basic'));\n error('Error found during Object creation.');\n end\n end\nend\n\n% Create objects for all blocks with xps:* tags.\n% All objects are stored in xps_objs.\ntarget_tags = {'xps_adc16' 'xps_adc5g' 'xps_adc083000x2' 'xps_adc' 'xps_katadc' 'xps_block'...\n 'xps_bram' 'xps_corr_adc' 'xps_corr_dac' 'xps_corr_mxfe' 'xps_corr_rf' 'xps_dram' 'xps_ethlite'...\n 'xps_framebuffer' 'xps_fifo' 'xps_gpio' 'xps_interchip' 'xps_lwip' 'xps_opb2opb' 'xps_probe'...\n 'xps_quadc' 'xps_sram' 'xps_sw_reg' 'xps_tengbe' 'xps_vsi' 'xps_xaui' 'xps_xsg'};\nfor n = 1 : length(xps_blks),\n if ~(strcmp(get_param(xps_blks(n), 'tag'), 'xps:xsg') || strcmp(get_param(xps_blks(n), 'tag'), 'xps:pcore')),\n try\n %tag = get_param(xps_blks(n), 'tag')\n blk_obj = xps_block(xps_blks{n}, xsg_obj);\n %fprintf('Created block! %s\\n', tag);\n assignin('base', 'last_blk_obj', blk_obj)\n eval(['blk_obj = ', get(blk_obj, 'type'), '(blk_obj);']);\n %fprintf('Evaluated block! %s\\n', tag);\n xps_objs = [xps_objs, {blk_obj}];\n if isempty(find(strcmp(get(blk_obj, 'type'), target_tags), 1)),\n custom_xps_objs = [custom_xps_objs, {blk_obj}];\n else\n if isempty(find(strcmp(get(blk_obj, 'type'), core_types), 1)),\n core_types = [core_types, {get(blk_obj, 'type')}];\n end\n end\n catch ex\n disp(['Problem with XPS: tag block: ', xps_blks{n}]);\n dump_exception(ex);\n error('Error found during Object creation.');\n end\n end\nend\n\n% add the xsg_object to the list\nxps_objs = [{xsg_obj}, xps_objs];\n\nhw_sys = get(xsg_obj, 'hw_sys');\nhw_subsys = get(xsg_obj, 'hw_subsys');\nsw_os = get(xsg_obj, 'sw_os');\napp_clk = get(xsg_obj, 'clk_src');\napp_clk_rate = get(xsg_obj, 'clk_rate');\nxsg_core_name = clear_name(get(xsg_obj, 'parent'));\nxps_path = [work_path, slash, 'XPS_', hw_sys, '_base'];\n\n% Create structure of commonly-used design parameters\nmssge_proj = {};\nmssge_proj.sys = sys;\nmssge_proj.design_name = design_name;\nmssge_proj.hw_sys = hw_sys;\nmssge_proj.hw_subsys = hw_subsys;\nmssge_proj.sw_os = sw_os;\nmssge_proj.app_clk = app_clk;\nmssge_proj.app_clk_rate = app_clk_rate;\nmssge_proj.xsg_core_name = xsg_core_name;\n\n% Create structure of commonly-used paths\nmssge_paths = {};\nmssge_paths.XPS_BASE_PATH = XPS_BASE_PATH;\nmssge_paths.simulink_path = simulink_path;\nmssge_paths.work_path = work_path;\nmssge_paths.src_path = src_path;\nmssge_paths.xsg_path = xsg_path;\nmssge_paths.netlist_path = netlist_path;\nmssge_paths.xps_path = xps_path;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Task: DRC (run_drc)\n% The drc() function of each object in xps_objs is called\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nstart_time = now;\nif run_drc,\n disp('######################');\n disp('## Checking objects ##');\n disp('######################');\n for n=1:length(xps_objs),\n [result, msg] = drc(xps_objs{n}, xps_objs);\n if result,\n disp('Error with block:');\n display(xps_objs{n});\n disp(msg);\n error('DRC failed!');\n end\n end\nend\ntime_drc = now - start_time;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Task: Execute System Generator (run_xsg)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nstart_time = now;\nif run_xsg,\n if exist(xsg_path,'dir'),\n rmdir(xsg_path,'s');\n end\n disp('Running system generator ...');\n xsg_result = xlGenerateButton(xsg_blk);\n if xsg_result == 0,\n disp('XSG generation complete.');\n else\n error(['XSG generation failed: ',xsg_result]);\n end\nend\ntime_xsg = now - start_time;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Task: Copy Base System\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nstart_time = now;\nif run_copy,\n disp('#########################');\n disp('## Copying base system ##');\n disp('#########################');\n\n%%%%% PCORE SETUP\n%%%% pcores_used = {};\n%%%%\n%%%% for n = 1 : length(xps_objs)\n%%%%\n%%%% curr_obj = xps_objs{n};\n%%%%\n%%%% obj_ip_name = get(curr_obj, 'ip_name');\n%%%% obj_ip_ver = get(curr_obj, 'ip_version');\n%%%% obj_supp_ip_names = get(curr_obj, 'supp_ip_names');\n%%%% obj_supp_ip_vers = get(curr_obj, 'supp_ip_versions');\n%%%%\n%%%% if isempty(obj_ip_ver)\n%%%% obj_ip_ver = '1.00.a';\n%%%% end\n%%%%\n%%%% if isempty(obj_supp_ip_names)\n%%%% try\n%%%% pcore_used = clear_name([obj_ip_name, ' v', obj_ip_ver]);\n%%%% pcores_used = [pcores_used, {pcore_used}];\n%%%% end\n%%%% else\n%%%% for p = 2 : length(obj_supp_ip_names),\n%%%% try\n%%%% pcore_used = clear_name([obj_supp_ip_names{p}, ' v', obj_supp_ip_vers{p}]);\n%%%% pcores_used = [pcores_used, {pcore_used}];\n%%%% end\n%%%% end\n%%%%\n%%%% % supp_ip_names{1} used to override ip_name; also include ip_name if {1} is empty\n%%%% if isempty(obj_supp_ip_names{1})\n%%%% try\n%%%% pcore_used = clear_name([get(curr_obj, 'ip_name'), ' v', get(curr_obj, 'ip_version')]);\n%%%% pcores_used = [pcores_used, {pcore_used}];\n%%%% end\n%%%% else\n%%%% try\n%%%% pcore_used = clear_name([obj_supp_ip_names{1}, ' v', obj_supp_ip_vers{1}]);\n%%%% pcores_used = [pcores_used, {pcore_used}];\n%%%% end\n%%%% end\n%%%% end\n%%%%\n%%%% end % for n = 1:length(xps_objs)\n%%%%\n%%%% pcores_used = unique(pcores_used);\n%%%%% /PCORE SETUP\n\n if exist(xps_path,'dir'),\n rmdir(xps_path,'s');\n end\n if exist([XPS_BASE_PATH, slash, 'XPS_',hw_sys,'_base'],'dir'),\n\n source_dir = [XPS_BASE_PATH, slash, 'XPS_', hw_sys, '_base'];\n destination_dir = xps_path;\n\n if strcmp(system_os, 'windows'),\n copy_fail = 1; % xcopy failure returns 1\n mkdir(xps_path);\n % use xcopy to avoid copying .svn directories\n [copy_result, ~] = dos(['xcopy /Q /E /Y ', source_dir, ' ', destination_dir,'\\.']);\n else\n copy_fail = 0; % copyfile failure returns 0\n [copy_result, ~, ~] = copyfile(source_dir,destination_dir,'f');\n fprintf('Copying base package from:\\n %s\\n', source_dir)\n end % if strcmp(system_os, 'windows')\n\n if copy_result == copy_fail,\n cd(simulink_path);\n error('Unpackage base system files failed.');\n else\n cd(simulink_path);\n end % copy_result == copy_fail\n else\n error(['Base XPS package \"','XPS_',hw_sys,'_base\" does not exist.']);\n end % exist([XPS_BASE_PATH,'\\XPS_',hw_sys,'_base'],'dir')\n\n%%%%% BEGIN PCORE COPYING CODE\n%%%%%\n%%%%% if exist([XPS_BASE_PATH,'\\pcores'], 'dir')\n%%%%% if ~exist([xps_path, '\\copied_pcores'], 'dir')\n%%%%% mkdir([xps_path, '\\copied_pcores']);\n%%%%% end\n%%%%%\n%%%%% for n=1:length(pcores_used)\n%%%%% disp(pcores_used{n})\n%%%%% pcore_path = [xps_path, '\\copied_pcores\\', pcores_used{n}];\n%%%%% mkdir(pcore_path);\n%%%%% [copy_result, copy_message] = dos(['xcopy /Q /E /Y ', XPS_BASE_PATH, '\\pcores\\', pcores_used{n}, ' ', pcore_path, '\\.']);\n%%%%%\n%%%%% if copy_result\n%%%%% cd(simulink_path);\n%%%%% disp(copy_message);\n%%%%% error(['Pcore copy failed: ', pcores_used{n}]);\n%%%%% else\n%%%%% cd(simulink_path);\n%%%%% end\n%%%%% end % for n=1:length(pcores_used)\n%%%%% else\n%%%%% cd(simulink_path);\n%%%%% error(['PCores directory \"', XPS_BASE_PATH, '\\pcores\" does not exist']);\n%%%%% end % if exist([XPS_BASE_PATH,'\\pcores'], 'dir') - else\n%%%%%\n%%%%% END PCORE COPYING CODE\n\nend % if run_copy\ntime_copy = now - start_time;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Task: Copy + Create custom IPs\n% Description: If the user specify a custom IP block, a EDK pcore\n% is automatically generated so that it can be integrated with the\n% rest of the system.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nstart_time = now;\nif run_ip,\n disp('########################');\n disp('## Copying custom IPs ##');\n disp('########################');\n\n cd(simulink_path);\n for n = 1:length(xps_pcore_blks),\n path_param = get_param(xps_pcore_blks(n), 'pcore_path');\n pcore_path = clear_path(path_param{1});\n\n destination_dir = [xps_path, slash, 'pcores', slash];\n\n [copy_result, ~, ~] = copyfile(pcore_path, destination_dir, 'f');\n\n if copy_result == 0,\n cd(simulink_path);\n error(['Error copying custom pcores from ', pcore_path]);\n end\n end\n\n gen_xps_create_pcore(xsg_obj, xps_objs, mssge_proj, mssge_paths, slash);\n\nend % if run_ip\ntime_ip = now - start_time;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Task: Create custom EDK\n% Description: Create custom system.mhs file based on the\n% yellowboxes that the user has used. At the end of this task three\n% files, system.mhs, core_info.m and core_info.tab are created.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nstart_time = now;\nif run_edkgen,\n disp('##########################');\n disp('## Creating EDK files ##');\n disp('##########################');\n\n % modifying XMP file\n xmpfile = 'system.xmp';\n\n if ~isempty(hw_subsys),\n xmpfile = [xmpfile, '.', hw_subsys];\n end % if ~isempty(hw_subsys)\n\n if ~exist([xps_path, slash, xmpfile, '.bac'],'file'),\n [copystatus, copymessage, ~] = copyfile([xps_path, slash, xmpfile],[xps_path, slash, xmpfile,'.bac']);\n if ~copystatus,\n disp('Error trying to backup system.xmp:');\n disp(copymessage);\n end % if ~copystatus\n\n [copystatus, copymessage, ~] = copyfile([xps_path, slash, xmpfile,'.bac'],[xps_path, slash, 'system.xmp']);\n if ~copystatus,\n disp('Error trying to overwrite system.xmp:');\n disp(copymessage);\n end % if ~copystatus\n end % if ~exist([xps_path, slash, xmpfile, '.bac'],'file')\n\n % modifying MHS file\n gen_xps_mod_mhs(xps_objs, mssge_proj, mssge_paths, slash);\n\n % modifying MSS file\n gen_xps_mod_mss(xsg_obj, xps_objs, mssge_proj, mssge_paths, slash);\n\n % modifying UCF file\n gen_xps_mod_ucf(xsg_obj, xps_objs, mssge_proj, mssge_paths, slash);\n\n % add extra register and snapshot info from the design\n gen_xps_add_design_info(sys, mssge_paths, slash);\n\n % shanly and mark's new format - generated from core_info and design_info\n if strcmp(hw_sys, 'ROACH') || strcmp(hw_sys, 'ROACH2') || strcmp(hw_sys, 'MKDIG'),\n kcpfpg_fid = fopen([xps_path, slash, 'extended_info.kcpfpg'], 'w');\n fprintf(kcpfpg_fid, '#!/bin/kcpfpg\\n');\n fprintf(kcpfpg_fid, '?uploadbin\\n');\n % read coreinfo.tab into the fpg file\n fid = fopen([xps_path, slash, 'core_info.tab'], 'r');\n while 1,\n tline = fgetl(fid);\n if ~ischar(tline), break, end\n linevals = textscan(tline, '%s %s %s %s');\n newline = ['?register ', sprintf('%s 0x%s 0x%s', linevals{1}{1}, linevals{3}{1}, linevals{4}{1})];\n fprintf(kcpfpg_fid, '%s\\n', newline);\n clear linevals newline tline;\n end\n fclose(fid);\n % read design meta info into the fpg file\n fid = fopen([xps_path, slash, 'design_info.tab'], 'r');\n while 1,\n tline = fgetl(fid);\n if ~ischar(tline), break, end\n newline = ['?meta ', tline];\n fprintf(kcpfpg_fid, '%s\\n', newline);\n end\n clear newline tline;\n fclose(fid);\n fprintf(kcpfpg_fid, '?quit\\n');\n fclose(kcpfpg_fid);\n end\n\nend % if run_edkgen\ntime_edkgen = now - start_time;\n\nstart_time = now;\nif run_elab,\n disp('#########################');\n disp('## Elaborating objects ##');\n disp('#########################');\n for n = 1:length(xps_objs),\n try\n xps_objs{n} = elaborate(xps_objs{n});\n catch ex\n display(xps_objs{n});\n warning(ex.identifier, '%s', ex.getReport('basic'));\n error('Elaboration of object failed.');\n end\n end\nend % if run_elab\ntime_elab = now - start_time;\n\nstart_time = now;\nif run_software,\n disp('##############################');\n disp('## Preparing software files ##');\n disp('##############################');\n\n switch sw_os\n case 'tinySH'\n %TODO: these functions might experience OS 'slash' errors\n % Creating software core info files\n gen_xps_tinysh_core_info(xsg_obj, xps_objs, custom_xps_objs, mssge_proj, mssge_paths);\n\n % Gathering information on the software files\n [headers, sources] = gen_xps_tinysh_get_src(xsg_obj, xps_objs, mssge_proj, mssge_paths);\n\n % Rewrite main.c based on user source code\n gen_xps_tinysh_mod_main(xsg_obj, xps_objs, mssge_proj, mssge_paths, headers, sources);\n\n % write project file\n gen_xps_tinysh_mod_xmp(xsg_obj, xps_objs, mssge_proj, mssge_paths, headers, sources);\n\n % end case 'tinySH'\n\n case 'linux'\n\n case 'none'\n\n otherwise\n error(['Unsupported OS: ', sw_os]);\n end % switch sw_os\n\n win_fid = fopen([xps_path, slash, 'gen_prog_files.bat'], 'w');\n unix_fid = fopen([xps_path, slash, 'gen_prog_files'], 'w');\n fprintf(unix_fid, '#!/bin/bash\\n');\n files_name = [design_name, '_', clear_name(datestr(now, 'yyyy-mmm-dd HHMM'))];\n\n switch sw_os\n case 'none'\n fprintf(win_fid, ['copy implementation\\\\system.bit ..\\\\bit_files\\\\',files_name,'.bit\\n']);\n fprintf(unix_fid, ['cp implementation/system.bit ../bit_files/',files_name,'.bit\\n']);\n % end case 'none'\n otherwise\n fprintf(win_fid, ['copy implementation\\\\download.bit ..\\\\bit_files\\\\',files_name,'.bit\\n']);\n fprintf(unix_fid, ['cp implementation/download.bit ../bit_files/',files_name,'.bit\\n']);\n % end otherwise\n end % switch sw_os\n\n [~, w] = system('uname -m');\n if strcmp(hw_sys, 'ROACH') || strcmp(hw_sys, 'ROACH2') || strcmp(hw_sys, 'MKDIG'),\n fprintf(win_fid, ['mkbof.exe -o implementation\\\\system.bof', ' -s core_info.tab -t 3 implementation\\\\system.bin\\n']);\n if strcmp(w(1:6), 'x86_64'),\n fprintf(unix_fid, ['./mkbof_64 -o implementation/system.bof', ' -s core_info.tab -t 3 implementation/system.bin\\n']);\n else\n fprintf(unix_fid, ['./mkbof -o implementation/system.bof', ' -s core_info.tab -t 3 implementation/system.bin\\n']);\n end\n fprintf(win_fid, ['copy implementation\\\\system.bof', ' ..\\\\bit_files\\\\', files_name,'.bof\\n']);\n if strcmp(hw_sys, 'ROACH'),\n fprintf(unix_fid,'chmod +x implementation/system.bof\\n');\n end\n fprintf(unix_fid, ['cp implementation/system.bof ../bit_files/', files_name,'.bof\\n']);\n if exist([xps_path, slash, 'design_info.tab'], 'file') == 2,\n fprintf(win_fid, ['copy design_info.tab ..\\\\bit_files\\\\', files_name,'.info\\n']);\n fprintf(unix_fid, ['cp design_info.tab ../bit_files/', files_name,'.info\\n']);\n end\n if strcmp(hw_sys, 'ROACH2') || strcmp(hw_sys, 'ROACH2'),\n fprintf(unix_fid, ['gzip -c ../bit_files/', files_name, '.bof > ../bit_files/', files_name,'.bof.gz\\n']);\n end\n if exist([xps_path, slash, 'extended_info.kcpfpg'], 'file') == 2,\n fprintf(unix_fid, 'gzip -c implementation/system.bin > implementation/system.bin.gz\\n');\n fprintf(unix_fid, ['cat implementation/system.bin.gz >> ', xps_path, slash, 'extended_info.kcpfpg\\n']);\n fprintf(unix_fid, ['cp extended_info.kcpfpg ../bit_files/', files_name,'.fpg\\n']);\n end\n end % strcmp(hw_sys, 'ROACH') || strcmp(hw_sys, 'ROACH2')\n\n fclose(win_fid);\n fclose(unix_fid);\n\nend % if run_software\ntime_software = now - start_time;\n\nstart_time = now;\nif run_edk,\n disp('#########################');\n disp('## Running EDK backend ##');\n disp('#########################');\n % erase download.bit to make sure a failing compilation will report an error\n delete([xps_path, slash, 'implementation', slash, 'system.bit']);\n delete([xps_path, slash, 'implementation', slash, 'download.bit']);\n fid = fopen([xps_path, slash, 'run_xps.tcl'],'w');\n hw_sys = get(xsg_obj,'hw_sys');\n switch hw_sys\n case 'ROACH'\n fprintf(fid, 'run bits\\n');\n % end case 'powerpc440_ext'\n case {'ROACH2', 'MKDIG'}\n fprintf(fid, 'run bits\\n');\n % end case 'powerpc440_ext'\n otherwise\n fprintf(fid, 'run init_bram\\n');\n % end otherwise\n end % switch hw_sys\n fprintf(fid, 'exit\\n');\n fclose(fid);\n eval(['cd ', xps_path]);\n status = system('xps -nw -scr run_xps.tcl system.xmp');\n if status ~= 0,\n cd(simulink_path);\n error('XPS failed.');\n else\n if (strcmp(slash, '\\')),\n % Windows case\n [status, ~] = dos('gen_prog_files.bat');\n if status ~= 0,\n cd(simulink_path);\n error('Programation files generation failed, EDK compilation probably also failed.');\n end % if dos('gen_prog_files.bat')\n else\n % Linux case\n [~, ~] = unix('chmod +x gen_prog_files');\n [status, message] = unix('./gen_prog_files');\n if status ~= 0,\n cd(simulink_path);\n disp(message);\n error('Programation files generation failed, EDK compilation probably also failed.');\n end % if unix('gen_prog_files.bat')\n end %if (strcmp(slash, '\\'))\n end % if(dos(['xps -nw -scr run_xps.tcl system.xmp']))\n cd(simulink_path);\nend % if run_edk\ntime_edk = now - start_time;\n\ntime_total = time_update + time_drc + time_xsg + time_copy + time_ip + time_edkgen + time_elab + time_software + time_edk;\n\ntime_struct.update = time_update ;\ntime_struct.drc = time_drc ;\ntime_struct.xsg = time_xsg ;\ntime_struct.copy = time_copy ;\ntime_struct.ip = time_ip ;\ntime_struct.edkgen = time_edkgen ;\ntime_struct.elab = time_elab ;\ntime_struct.software = time_software ;\ntime_struct.edk = time_edk ;\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "dram_sim.m", "ext": ".m", "path": "mlib_devel-master/xps_library/dram_sim.m", "size": 5430, "source_encoding": "utf_8", "md5": "0611a3c0a5bcd6222ee4caae2a5d973b", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction dram_sim (this_block)\n\n xps_library_path = getenv('XPS_LIBRARY_PATH');\n if isempty(xps_library_path)\n % try to fall back on MLIB_ROOT.\n mlib_root = getenv('MLIB_DEVEL_PATH');\n if isempty(mlib_root)\n error('MLIB_DEVEL_PATH environment variable must be set to point to xps_library directory.');\n else\n warning('MLIB_ROOT environment variable is deprecated.')\n xps_library_path = [mlib_root, '\\xps_library'];\n end\n end\n\n simwrapper = get_param(this_block.blockName, 'parent');\n xpswrapper = get_param(simwrapper, 'parent');\n\n half_burst = get_param(xpswrapper, 'half_burst');\n wide_data = get_param(xpswrapper, 'wide_data');\n\n ip_clock = str2num(get_param(xpswrapper, 'ip_clock'));\n sysclk_per = round(ip_clock/200 * 500);\n\n\n this_block.setTopLevelLanguage('VHDL');\n this_block.setEntityName('dram_sim');\n this_block.tagAsCombinational;\n\n\n this_block.addGeneric('C_WIDE_DATA', 'Integer', num2str(strcmp(wide_data, 'on')));\n this_block.addGeneric('C_HALF_BURST', 'Integer', num2str(strcmp(half_burst, 'on')));\n this_block.addGeneric('SYSCLK_PER', 'Time', [num2str(sysclk_per),' ms']);\n this_block.addGeneric('IP_CLOCK', 'Integer', num2str(ip_clock));\n\n\n this_block.addSimulinkInport('rst');\n this_block.addSimulinkInport('address');\n this_block.addSimulinkInport('data_in');\n this_block.addSimulinkInport('wr_be');\n this_block.addSimulinkInport('RWn');\n this_block.addSimulinkInport('cmd_tag');\n this_block.addSimulinkInport('cmd_valid');\n this_block.addSimulinkInport('rd_ack');\n\n this_block.addSimulinkOutport('cmd_ack');\n this_block.addSimulinkOutport('data_out');\n this_block.addSimulinkOutport('rd_tag');\n this_block.addSimulinkOutport('rd_valid');\n\n this_block.addSimulinkOutport('ddr_clock');\n this_block.addSimulinkOutport('ddr_clock90');\n this_block.port('ddr_clock').setType('Bool');\n this_block.port('ddr_clock').setRate(1);\n this_block.port('ddr_clock90').setType('Bool');\n this_block.port('ddr_clock90').setRate(1);\n\n\n this_block.addClkCEPair('clk', 'ce', 1);\n\n\n this_block.port('rst').setType('UFix_1_0');\n this_block.port('address').setType('UFix_32_0');\n\n if strcmp(wide_data, 'on')\n this_block.port('data_in').setType('UFix_288_0');\n this_block.port('wr_be').setType('UFix_36_0');\n else\n this_block.port('data_in').setType('UFix_144_0');\n this_block.port('wr_be').setType('UFix_18_0');\n end\n\n this_block.port('RWn').setType('UFix_1_0');\n this_block.port('cmd_tag').setType('UFix_32_0');\n this_block.port('cmd_valid').setType('UFix_1_0');\n this_block.port('rd_ack').setType('UFix_1_0');\n\n this_block.port('cmd_ack').setType('Bool');\n\n if strcmp(wide_data, 'on')\n this_block.port('data_out').setType('UFix_288_0');\n else\n this_block.port('data_out').setType('UFix_144_0');\n end\n\n this_block.port('rd_tag').setType('UFix_32_0');\n this_block.port('rd_valid').setType('Bool');\n\n this_block.port('cmd_ack').setRate(1);\n this_block.port('data_out').setRate(1);\n this_block.port('rd_tag').setRate(1);\n this_block.port('rd_valid').setRate(1);\n\n\n this_block.addFile([xps_library_path, '\\hdlsimfiles\\dram_sim\\xilinx_sim_src.vhd']);\n this_block.addFile([xps_library_path, '\\hdlsimfiles\\dram_sim\\ddr2_parameters.vh']);\n this_block.addFile([xps_library_path, '\\hdlsimfiles\\dram_sim\\ddr2_sim.v']);\n this_block.addFile([xps_library_path, '\\hdlsimfiles\\dram_sim\\ddr2_controller.vhd']);\n this_block.addFile([xps_library_path, '\\hdlsimfiles\\dram_sim\\async_ddr2.v']);\n this_block.addFile([xps_library_path, '\\hdlsimfiles\\dram_sim\\dram_sim.vhd']);\n\nreturn;\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "clk_factors.m", "ext": ".m", "path": "mlib_devel-master/xps_library/clk_factors.m", "size": 1675, "source_encoding": "utf_8", "md5": "6f920575e9a5b64e5c6e5cd228f3f956", "text": "% This function uses the input clock frequence and the target freq to calculate\n% the correct multiply and divide factors for the MMCM. Specifically for ROACH2\n% This is implemented by creating a 3D matrix of all possible values and \n% finding the one that closest matches the requirements.\n\n\nfunction [bestM, bestD, bestDD] = clk_factors(clk_freq, target_freq)\n \n bestM = 0;\n bestD = 0;\n bestDD = 0;\n\n % the Multiply value is a even number because we need to divide by 1/2 of\n % it to get the 200MHz clock, which is used for the QDR.\n M = (8:2:64);\n D = (2:1:128);\n % If the input clock freq >= 315 then DD cant be 3 or 4.\n if (clk_freq >= 315)\n DD = (5:1:80);\n else\n DD = (1:1:80);\n end\n best_diff = 1000;\n for i = 1:length(M)\n for j = 1:length(D)\n for k = 1:length(DD)\n %x = [x 100*M(i)/D(j)/DD(k)];\n % the VCO freq must be between 600 and 1200 for the -1 speed \n % grade vitrex 6, but we found being on the boundaries causes\n % issues, so we are using 650 -> 1150.\n if (clk_freq*M(i)/DD(k) < 1150 && clk_freq*M(i)/DD(k) > 650)\n diff = abs(clk_freq*M(i)/D(j)/DD(k) - target_freq);\n if diff < best_diff\n best_diff = diff;\n bestM = M(i);\n bestD = D(j);\n bestDD = DD(k);\n end\n end\n end\n end\n end\n \n closest_freq = clk_freq * bestM / bestD / bestDD;\n sys_clk_VCO = bestM * clk_freq / bestDD;\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "remove_all_blks.m", "ext": ".m", "path": "mlib_devel-master/xps_library/remove_all_blks.m", "size": 2175, "source_encoding": "utf_8", "md5": "52d896ba0e3f2295a50856a912533f48", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction remove_all_blks(sys)\n\n% Wrap whole function in try/catch\ntry\n\n blks = get_param(sys,'blocks');\n lines = get_param(sys,'lines');\n for i = 1:length(blks)\n switch get_param([sys,'/',blks{i}],'BlockType')\n case {'Inport' 'Outport'}\n % don't remove IO blocks\n otherwise\n delete_block([sys,'/',blks{i}]);\n end\n end\n for i = 1:length(lines)\n delete_line(lines(i).Handle);\n end\ncatch ex\n dump_and_rethrow(ex)\nend % try/catch\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "katadc_init.m", "ext": ".m", "path": "mlib_devel-master/xps_library/katadc_init.m", "size": 10161, "source_encoding": "utf_8", "md5": "8196f034a133a5aac55b5b7b169b52c1", "text": "% katadc initialisation script \n%\n% function katadc_init(blk, varargin) \n%\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Karoo Array Telescope Project %\n% www.ska.ac.za %\n% Copyright (C) 2010 Andrew Martens SKA/SA %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction katadc_init(blk, varargin)\n\n clog('katadc_init: pre same_state','trace');\n\n defaults = {'adc_brd', 'adc0', 'adc_interleave', 'off', 'bypass_auto', 'off', ...\n 'en_gain', 'on', 'adc_clk_rate', 800, 'sample_period', 1};\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n clog('katadc_init: post same_state','trace');\n\n check_mask_type(blk, 'katadc');\n munge_block(blk, varargin{:});\n delete_lines(blk);\n\n adc_brd = get_var('adc_brd', 'defaults', defaults, varargin{:});\n adc_interleave = get_var('adc_interleave', 'defaults', defaults, varargin{:});\n bypass_auto = get_var('bypass_auto', 'defaults', defaults, varargin{:});\n en_gain = get_var('en_gain', 'defaults', defaults, varargin{:});\n adc_clk_rate = get_var('adc_clk_rate', 'defaults', defaults, varargin{:});\n sample_period = get_var('sample_period', 'defaults', defaults, varargin{:});\n\n % generic ADC parameters\n if strcmp(adc_interleave, 'on'), \n or_per_input = 2;\n in = 1;\n out = 8;\n il = 1;\n else\n or_per_input = 1;\n in = 2;\n out = 4;\n il = 0;\n end\n bits = 8;\n or_support = 'on'; or = 1;\n sync_support = 'on'; sync = 1;\n dv_support = 'on'; dv = 1;\n xtick = 120; \n ytick = 40+5*(or*out); \n\n% % info blocks\n% reuse_block(blk, 'adc_brd', 'casper_library_misc/info_block', 'info', adc_brd, 'Position', [0,0,50,30]);\n% reuse_block(blk, 'adc_interleave', 'casper_library_misc/info_block', 'info', adc_interleave, 'Position', [0,0,50,30]);\n% reuse_block(blk, 'bypass_auto', 'casper_library_misc/info_block', 'info', bypass_auto, 'Position', [0,0,50,30]);\n% reuse_block(blk, 'en_gain', 'casper_library_misc/info_block', 'info', en_gain, 'Position', [0,0,50,30]);\n% reuse_block(blk, 'adc_clk_rate', 'casper_library_misc/info_block', 'info', num2str(adc_clk_rate), 'Position', [0,0,50,30]);\n% reuse_block(blk, 'sample_period', 'casper_library_misc/info_block', 'info', num2str(sample_period), 'Position', [0,0,50,30]);\n% reuse_block(blk, 'adc_bits', 'casper_library_misc/info_block', 'info', num2str(8), 'Position', [0,0,50,30]);\n \n clog('katadc_init: drawing common adc','trace');\n\n yoff = adc_common(blk, 'in', in, 'out', out, 'bits', bits, 'or_per_input', or_per_input, ...\n 'xoff', 0, 'xtick', xtick, 'yoff', 0, 'ytick', ytick, ...\n 'adc_interleave', adc_interleave, 'or_support', ...\n or_support, 'sync_support', sync_support, 'dv_support', dv_support);\n \n clog('katadc_init: done drawing common adc','trace');\n\n %%%% Rename generic ports to specific KATADC names %%%%%\n for input = 0:1,\n if strcmp(adc_interleave, 'off'), \n if input == 0, \n label = 'i';\n else\n label = 'q';\n end\n else\n if input == 0, \n label = 'q';\n else\n label = 'i';\n end\n end\n for offset = 0:3,\n name = clear_name([blk, '_user_data', num2str(input*4+offset)]);\n new_name = clear_name([blk, '_user_data', label, num2str(offset)]);\n old_port = find_system(blk, 'lookUnderMasks', 'all', 'Name', new_name);\n if ~isempty(old_port), \n delete_block(old_port{1});\n end\n port = find_system(blk, 'lookUnderMasks', 'all', 'Name', name);\n if isempty(port), \n clog(['katadc_init: missing data port: ', blk, '_user_data', num2str(input*4+offset)],'error');\n disp(['katadc_init: missing data port: ', blk, '_user_data', num2str(input*4+offset)]);\n else \n set_param(port{1}, 'Name', new_name);\n end\n end\n end\n \n %%%% KATADC specific ports %%%%\n \n reuse_block(blk, 'trigger', 'xbsIndex_r4/Constant', ...\n 'arith_type', 'Unsigned', 'const', '1', 'n_bits', '1', 'bin_pt', '0', ...\n 'Position', [xtick*4-15 ytick*yoff-7.5 xtick*4+15 ytick*yoff+7.5]);\n\n reuse_block(blk, 'en0', 'built-in/inport', 'Port', num2str(4-il+1), ... \n 'Position', [xtick*1-15 ytick*(yoff+1)-7.5 xtick*1+15 ytick*(yoff+1)+7.5]);\n reuse_block(blk, 'slc0', 'xbsIndex_r4/Slice', 'nbits', '1', 'mode', ...\n 'Lower Bit Location + Width', 'bit0', '0', 'base0', 'LSB of input', ...\n 'Position', [xtick*2-15 ytick*(yoff+1)-7.5 xtick*2+15 ytick*(yoff+1)+7.5]);\n add_line(blk, 'en0/1', 'slc0/1');\n \n reuse_block(blk, 'atten0', 'built-in/inport', 'Port', num2str(4-il+2), ...\n 'Position', [xtick*1-15 ytick*(yoff+2)-7.5 xtick*1+15 ytick*(yoff+2)+7.5]);\n reuse_block(blk, 'slc1', 'xbsIndex_r4/Slice', ...\n 'nbits', '6', 'mode', 'Lower Bit Location + Width', 'bit0', '0', 'base0', 'LSB of input', ...\n 'Position', [xtick*2-15 ytick*(yoff+2)-7.5 xtick*2+15 ytick*(yoff+2)+7.5]);\n add_line(blk, 'atten0/1', 'slc1/1');\n reuse_block(blk, 'inv0', 'xbsIndex_r4/Inverter', ...\n 'Position', [xtick*3-15 ytick*(yoff+2)-7.5 xtick*3+15 ytick*(yoff+2)+7.5]);\n add_line(blk, 'slc1/1', 'inv0/1'); \n\n %use input ports for non-interleaved mode, otherwise disable input with max attenuation on 'q' input\n if il == 0,\n en1_name = 'en1';\n atten1_name = 'atten1';\n reuse_block(blk, en1_name, 'built-in/inport', 'Port', num2str(4-il+3), ...\n 'Position', [xtick*1-15 ytick*(yoff+3)-7.5 xtick*1+15 ytick*(yoff+3)+7.5]);\n reuse_block(blk, atten1_name, 'built-in/inport', 'Port', num2str(4-il+4), ...\n 'Position', [xtick*1-15 ytick*(yoff+4)-7.5 xtick*1+15 ytick*(yoff+4)+7.5]);\n else\n en1_name = 'en0';\n atten1_name = 'atten0';\n end\n \n reuse_block(blk, 'slc2', 'xbsIndex_r4/Slice', ...\n 'nbits', '1', 'mode', 'Lower Bit Location + Width', 'bit0', '0', 'base0', 'LSB of input', ...\n 'Position', [xtick*2-15 ytick*(yoff+3)-7.5 xtick*2+15 ytick*(yoff+3)+7.5]);\n add_line(blk, [en1_name,'/1'], 'slc2/1');\n reuse_block(blk, 'slc3', 'xbsIndex_r4/Slice', ...\n 'nbits', '6', 'mode', 'Lower Bit Location + Width', 'bit0', '0', 'base0', 'LSB of input', ...\n 'Position', [xtick*2-15 ytick*(yoff+4)-7.5 xtick*2+15 ytick*(yoff+4)+7.5]);\n add_line(blk, [atten1_name,'/1'], 'slc3/1');\n reuse_block(blk, 'inv1', 'xbsIndex_r4/Inverter', ...\n 'Position', [xtick*3-15 ytick*(yoff+4)-7.5 xtick*3+15 ytick*(yoff+4)+7.5]);\n add_line(blk, 'slc3/1', 'inv1/1'); \n \n %concat block \n reuse_block(blk, 'con', 'xbsIndex_r4/Concat', ...\n 'num_inputs', '5', 'Position', [xtick*5-15 ytick*yoff-25 xtick*5+15 ytick*(yoff+4)+25]);\n add_line(blk, 'trigger/1', 'con/1');\n add_line(blk, 'slc0/1', 'con/4');\n add_line(blk, 'inv0/1', 'con/5');\n add_line(blk, 'slc2/1', 'con/2');\n add_line(blk, 'inv1/1', 'con/3');\n \n %trigger constant, combined with 0 initial value here forces load after reset\n reuse_block(blk, 'reg', 'xbsIndex_r4/Register', ...\n 'init', '0', 'Position', [xtick*6-25 ytick*(yoff+2)-20 xtick*6+25 ytick*(yoff+2)+20]);\n add_line(blk, 'con/1', 'reg/1');\n \n reuse_block(blk, 'changed', 'xbsIndex_r4/Relational', 'mode', 'a!=b', 'latency', '1', ...\n 'Position', [xtick*6-25 ytick*(yoff+3)-10 xtick*6+25 ytick*(yoff+4)+10]);\n add_line(blk, 'con/1', 'changed/2', 'autorouting', 'on');\n add_line(blk, 'reg/1', 'changed/1', 'autorouting', 'on');\n\n reuse_block(blk, 'slc4', 'xbsIndex_r4/Slice', ...\n 'nbits', '14', 'mode', 'Lower Bit Location + Width', 'bit0', '0', 'base0', 'LSB of input', ... \n 'Position', [xtick*7-15 ytick*(yoff+2)-7.5 xtick*7+15 ytick*(yoff+2)+7.5]);\n add_line(blk, 'reg/1', 'slc4/1');\n \n reuse_block(blk, 'cast0', 'xbsIndex_r4/Convert', ...\n 'arith_type', 'Unsigned', 'n_bits', '14', 'bin_pt', '0', ...\n 'Position', [xtick*8-25 ytick*(yoff+2)-20 xtick*8+25 ytick*(yoff+2)+20]);\n add_line(blk, 'slc4/1', 'cast0/1');\n \n gw = clear_name([blk, '_gain_value']);\n reuse_block(blk, gw, 'xbsIndex_r4/Gateway Out', ...\n 'Position', [xtick*9-20 ytick*(yoff+2)-10 xtick*9+20 ytick*(yoff+2)+10]);\n add_line(blk, 'cast0/1', [gw,'/1']);\n\n reuse_block(blk, 'cast1', 'xbsIndex_r4/Convert', 'arith_type', 'Boolean', ...\n 'Position', [xtick*8-25 ytick*(yoff+4)-20 xtick*8+25 ytick*(yoff+4)+20]);\n add_line(blk, 'changed/1', 'cast1/1');\n\n gw = clear_name([blk, '_gain_load']);\n reuse_block(blk, gw, 'xbsIndex_r4/Gateway Out', ...\n 'Position', [xtick*9-20 ytick*(yoff+4)-10 xtick*9+20 ytick*(yoff+4)+10]);\n add_line(blk, 'cast1/1', [gw,'/1']);\n \n %%%%\n\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('katadc_init: exiting','trace');\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "generic_adc_init.m", "ext": ".m", "path": "mlib_devel-master/xps_library/generic_adc_init.m", "size": 3807, "source_encoding": "utf_8", "md5": "c935377e22313ce4028a9c114f08b343", "text": "% generic adc initialisation script \n%\n% function generic_adc_init(blk, varargin) \n%\n% blk = The block to be configured.\n% varargin = {'varname', 'value', ...} pairs\n%\n% Valid varnames for this block are:\n% interleaved = simulate interleaved adcs\n% in = number of inputs\n% out = number of outputs per input (ADC demux factor)\n% bits = simulated ADC resolution\n% or_spport = simulate ADC over-range detection\n% sync_support = simulate ADC with sync line\n% dv_support = ADC with data valid output\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Karoo Array Telescope Project %\n% www.ska.ac.za %\n% Copyright (C) 2010 Andrew Martens SKA/SA %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction generic_adc_init(blk, varargin)\n\n clog('generic_adc_init: pre same_state','trace');\n\n defaults = { 'in', 2, 'out', 4, 'bits', 8, 'interleaved', 'off', ...\n 'or_support', 'off', 'sync_support', 'off', 'dv_support', 'off'};\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n clog('generic_adc_init: post same_state','trace');\n\n check_mask_type(blk, 'generic_adc');\n munge_block(blk, varargin{:});\n delete_lines(blk);\n\n interleaved = get_var('interleaved', 'defaults', defaults, varargin{:});\n in = get_var('in', 'defaults', defaults, varargin{:});\n out = get_var('out', 'defaults', defaults, varargin{:});\n bits = get_var('bits', 'defaults', defaults, varargin{:});\n or_support = get_var('or_support', 'defaults', defaults, varargin{:});\n sync_support = get_var('sync_support', 'defaults', defaults, varargin{:});\n dv_support = get_var('dv_support', 'defaults', defaults, varargin{:});\n \n or_per_input = 1;\n \n clog('generic_adc_init: drawing common adc','trace');\n xtick = 120; \n if strcmp(or_support,'on'), or = 1; else, or = 0; end\n ytick = 40+5*out*or; \n \n yoff = adc_common(blk, 'in', in, 'out', out, 'bits', bits, 'or_per_input', or_per_input, ...\n 'xoff', 0, 'xtick', xtick, 'yoff', 0, 'ytick', ytick, ...\n 'adc_interleave', interleaved, 'or_support', ...\n or_support, 'sync_support', sync_support, 'dv_support', dv_support);\n \n clog('generic_adc_init: done drawing common adc','trace');\n\n clean_blocks(blk);\n save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values\n\n clog('generic_adc_init: exiting','trace');\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "ports_struct.m", "ext": ".m", "path": "mlib_devel-master/xps_library/ports_struct.m", "size": 1888, "source_encoding": "utf_8", "md5": "cffd05e81108f3b3e9d4f97c79ba5989", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction result = ports_struct(ports)\r\nresult = [];\r\nfor i=1:length(ports)\r\n if isempty(result)\r\n result = struct(ports{i},0);\r\n else\r\n result = setfield(result,ports{i},0);\r\n end\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "adc16_init.m", "ext": ".m", "path": "mlib_devel-master/xps_library/adc16_init.m", "size": 3704, "source_encoding": "utf_8", "md5": "28ad49f65a077292f11f9ed9fecd5f54", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2013 David MacMahon\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nfunction adc16_init(blk, varargin)\n\ntry\n clog('adc16_init: pre same_state','trace');\n\n defaults = { ...\n 'block_name', blk, ...\n 'board_count', '1', ...\n 'roach2_rev', '2', ...\n 'zdok_rev', '2' ...\n };\n if same_state(blk, 'defaults', defaults, varargin{:}), return, end\n clog('adc16_init: post same_state','trace');\n\n check_mask_type(blk, 'ADC16');\n munge_block(blk, varargin{:});\n delete_lines(blk);\n\n gw_name = clear_name(blk);\n\n board_count = get_var('board_count', 'defaults', defaults, varargin{:});\n\n chips = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};\n\n x = 0;\n y = 20;\n\n for chip=1:8\n\n % Chip 5 is the first chip of the second board\n if chip == 5\n if board_count == 1\n break\n else\n % Second column\n x = 210+30+50;\n y = 20;\n end\n end\n\n for channel=1:4\n port_num = num2str((chip-1)*4 + channel);\n inport_name = sprintf('%s%d_sim', chips{chip}, channel);\n gateway_name = sprintf('%s_%s%d', gw_name, chips{chip}, channel);\n outport_name = sprintf('%s%d', chips{chip}, channel);\n\n inport_pos = [x+ 20, y, x+ 20+30, y+14];\n gateway_pos = [x+100, y-3, x+100+70, y+17];\n outport_pos = [x+210, y, x+210+30, y+14];\n y = y + 50;\n\n reuse_block(blk, inport_name, 'built-in/inport', ...\n 'Port', port_num, ...\n 'Position', inport_pos);\n\n reuse_block(blk, gateway_name, 'xbsIndex_r4/Gateway In', ...\n 'arith_type', 'Signed', ...\n 'n_bits', '8', ...\n 'bin_pt', '7', ...\n 'Position', gateway_pos);\n\n reuse_block(blk, outport_name, 'built-in/outport', ...\n 'Port', port_num, ...\n 'Position', outport_pos);\n\n\n add_line(blk, [inport_name, '/1'], [gateway_name, '/1']);\n h=add_line(blk, [gateway_name, '/1'], [outport_name, '/1']);\n set_param(h, 'Name', outport_name);\n end\n end\n clean_blocks(blk);\n\n save_state(blk, 'defaults', defaults, varargin{:});\n\n clog('adc16_init: exiting','trace');\n\ncatch ex\n dump_and_rethrow(ex);\nend % try/catch\nend % function\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "clean_ports.m", "ext": ".m", "path": "mlib_devel-master/xps_library/clean_ports.m", "size": 1875, "source_encoding": "utf_8", "md5": "fb66d8fec0e366dd308085b82188b810", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction clean_ports(sys,ports_struct)\r\nports = fieldnames(ports_struct);\r\nfor i=1:length(ports)\r\n if ~getfield(ports_struct,ports{i})\r\n delete_block([sys,'/',ports{i}]);\r\n end\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "sl_customization.m", "ext": ".m", "path": "mlib_devel-master/xps_library/sl_customization.m", "size": 2390, "source_encoding": "utf_8", "md5": "49705bd5074c1dc04186b5c96a06f334", "text": "% More information about this process can be found here:\r\n% http://www.mathworks.com/help/simulink/ug/adding-items-to-model-editor-menus.html\r\n\r\nfunction sl_customization(cm)\r\n %% Register custom menu function.\r\n cm.addCustomMenuFcn('Simulink:PreContextMenu', @getMyMenuItems);\r\nend\r\n\r\n%% Define the custom menu function.\r\nfunction schemaFcns = getMyMenuItems(~) \r\n\tschemaFcns = {@userFunctions}; \r\nend\r\n\r\n%% Define the schema function for first menu item.\r\nfunction schema = userFunctions(~)\r\n\t% Make a submenu label \r\n\tschema = sl_container_schema;\r\n\tschema.label = 'CASPER helpers'; \r\n\tschema.childrenFcns = {@userGetBlockSize, @userSetBlockSize, @userGotoPlusPlus, @userDannyFunc, @userGoto2From, @userGotoFromGlobal, @userGotoFromLocal, @userGotoFromScoped};\r\nend\r\n\r\nfunction schema = userGetBlockSize(~)\r\n schema = sl_action_schema;\r\n\tschema.label = 'Get block size';\r\n\tschema.callback = @helper_scripts.casper_sl_get_block_size; \r\nend\r\n\r\nfunction schema = userSetBlockSize(~)\r\n\tschema = sl_action_schema;\r\n\tschema.label = 'Set block sizes';\r\n\tschema.callback = @helper_scripts.casper_sl_set_block_size; \r\nend\r\n\r\nfunction schema = userGotoPlusPlus(~)\r\n\tschema = sl_action_schema;\r\n\tschema.label = 'Increment goto/from tags';\r\n schema.userdata = [-1, -1];\r\n\tschema.callback = @helper_scripts.casper_sl_incr_tag;\r\nend\r\n\r\nfunction schema = userDannyFunc(~)\r\n\tschema = sl_action_schema;\r\n\tschema.label = 'Goto -> Goto++';\r\n\tschema.callback = @helper_scripts.casper_sl_goto_plusplus; \r\nend\r\n\r\nfunction schema = userGoto2From(~)\r\n\tschema = sl_action_schema;\r\n\tschema.label = 'Goto -> From';\r\n\tschema.callback = @helper_scripts.casper_sl_goto2from; \r\nend\r\n\r\nfunction schema = userGotoFromGlobal(~)\r\n\tschema = sl_action_schema;\r\n\tschema.label = 'Goto/From scope -> Global';\r\n schema.userdata = 'global';\r\n\tschema.callback = @helper_scripts.casper_sl_tagscope; \r\nend\r\n\r\nfunction schema = userGotoFromLocal(~)\r\n\tschema = sl_action_schema;\r\n\tschema.label = 'Goto/From scope -> Local';\r\n schema.userdata = 'local';\r\n\tschema.callback = @helper_scripts.casper_sl_tagscope; \r\nend\r\n\r\nfunction schema = userGotoFromScoped(~)\r\n\tschema = sl_action_schema;\r\n\tschema.label = 'Goto/From scope -> Scoped';\r\n schema.userdata = 'scoped';\r\n\tschema.callback = @helper_scripts.casper_sl_tagscope; \r\nend\r\n\r\n% if you'd like to add more user functions duplicate 'userFunction1'\r\n% structure."} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "qdr_mask.m", "ext": ".m", "path": "mlib_devel-master/xps_library/qdr_mask.m", "size": 7738, "source_encoding": "utf_8", "md5": "bc07d38bd63724a05c86b4ac7695f2a0", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction qdr_mask(blk)\n\nmyname = blk;\n\n% get hardware platform from XSG block\ntry\n xsg_blk = find_system(bdroot(blk), 'SearchDepth', 1, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'Tag', 'xps:xsg');\n hw_sys = xps_get_hw_plat(get_param(xsg_blk{1}, 'hw_sys'));\ncatch\n if ~regexp(bdroot(blk), '(casper|xps)_library')\n warndlg('Could not find hardware platform for QDR configuration - is there an XSG block in this model? Defaulting platform to ROACH.');\n warning('Could not find hardware platform for QDR configuration - is there an XSG block in this model? Defaulting platform to ROACH.');\n hw_sys = 'ROACH';\n end\nend %try/catch\n\nclog(['Drawing QDR block for platform: ', hw_sys], 'qdr_mask_debug');\n\nswitch hw_sys\n case 'ROACH'\n data_width = 36;\n be_width = 4;\n n_qdr = 2;\n % end case 'ROACH'\n case 'ROACH2'\n data_width = 72;\n be_width = 8;\n n_qdr = 4;\n % end case 'ROACH2'\nend % end switch hw_sys\n\n% catch incorrect qdr selection\nwhich_qdr = get_param(myname, 'which_qdr');\nqdr_num = str2num(which_qdr(4));\nif (qdr_num > (n_qdr-1))\n warndlg(['Block configured for QDR ', num2str(qdr_num), '. ', hw_sys, ' only has ', num2str(n_qdr), ' QDR chips. Defaulting to QDR 0']);\n warning(['Block configured for QDR ', num2str(qdr_num), '. ', hw_sys, ' only has ', num2str(n_qdr), ' QDR chips. Defaulting to QDR 0']);\n set_param(myname, 'which_qdr', 'qdr0');\nend\n\nswitch hw_sys\n case 'ROACH'\n %construct bit remapping to move parity bits\n input_parity_map = 'b = {';\n output_parity_map = 'b = {';\n output_parity_map_top = '';\n output_parity_map_bottom = '';\n \n for i=[be_width-1:-1:0]\n input_parity_map = [input_parity_map, 'a[', num2str(data_width-(be_width-i)), '],a[', num2str((i+1)*8-1), ':', num2str(i*8), ']'];\n output_parity_map_top = [output_parity_map_top, 'a[', num2str(9*(i+1) - 1), ']'];\n output_parity_map_bottom = [output_parity_map_bottom, 'a[', num2str(9*(i+1)-1 - 1), ':', num2str(9*(i+1)-1 - 8), ']'];\n if i==0\n input_parity_map = [input_parity_map, '}'];\n output_parity_map = [output_parity_map, output_parity_map_top, ',', output_parity_map_bottom, '}'];\n else\n input_parity_map = [input_parity_map, ','];\n output_parity_map_top = [output_parity_map_top, ','];\n output_parity_map_bottom = [output_parity_map_bottom, ','];\n end\n input_parity_map\n end\n % end case 'ROACH'\n case 'ROACH2'\n input_parity_map = 'b = {a[71:68],a[63:32],a[67:64],a[31:0]}';\n %input_parity_map = 'b = {a[71:68],a[31:0],a[67:64],a[63:32]}';\n output_parity_map = 'b = {a[71:68],a[35:32],a[67:36],a[31:0]}';\n %output_parity_map = 'b = {a[71:68],a[35:32],a[31:0],a[67:36]}';\n % end case 'ROACH2'\nend % end switch hw_sys\n\n\n\n%update expressions in bitbasher blocks\nextract_parity_blk = [myname, '/extract_parity'];\ninsert_parity_blk = [myname, '/insert_parity'];\nset_param(insert_parity_blk, 'bitexpr', input_parity_map);\nset_param(extract_parity_blk, 'bitexpr', output_parity_map);\n\n\nset_param([myname, '/qdr_sim_model/sim_data_in'], 'n_bits', num2str(data_width));\nset_param([myname, '/convert_data_in'], 'n_bits', num2str(data_width));\nset_param([myname, '/convert_data_in1'], 'n_bits', num2str(data_width));\nset_param([myname, '/convert_be'], 'n_bits', num2str(be_width));\n\ngateway_outs = find_system(myname, 'searchdepth', 1, 'FollowLinks', 'on', 'lookundermasks', 'all', 'masktype', 'Xilinx Gateway Out Block');\nfor i =1:length(gateway_outs)\n gw = gateway_outs{i};\n if regexp(get_param(gw, 'Name'), '(wr_en)$')\n toks = regexp(get_param(gw, 'Name'), '(wr_en)$', 'tokens');\n set_param(gw, 'Name', clear_name([myname, '_', toks{1}{1}]));\n elseif regexp(get_param(gw, 'Name'), '(rd_en)$')\n toks = regexp(get_param(gw, 'Name'), '(rd_en)$', 'tokens');\n set_param(gw, 'Name', clear_name([myname, '_', toks{1}{1}]));\n elseif regexp(get_param(gw, 'Name'), '(be)$')\n toks = regexp(get_param(gw, 'Name'), '(be)$', 'tokens');\n set_param(gw, 'Name', clear_name([myname, '_', toks{1}{1}]));\n elseif regexp(get_param(gw, 'Name'), '(address)$')\n toks = regexp(get_param(gw, 'Name'), '(address)$', 'tokens');\n set_param(gw, 'Name', clear_name([myname, '_', toks{1}{1}]));\n elseif regexp(get_param(gw, 'Name'), '(data_in)$')\n toks = regexp(get_param(gw, 'Name'), '(data_in)$', 'tokens');\n set_param(gw, 'Name', clear_name([myname, '_', toks{1}{1}]));\n else\n error(['Unknown gateway name: ', gw]);\n end\nend\n\ngateway_ins =find_system(myname, 'searchdepth', 1, 'FollowLinks', 'on', 'lookundermasks', 'all', 'masktype', 'Xilinx Gateway In Block');\nfor i =1:length(gateway_ins)\n gw = gateway_ins{i};\n if regexp(get_param(gw, 'Name'), '(data_out)$')\n toks = regexp(get_param(gw, 'Name'), '(data_out)$', 'tokens');\n new_gw_name = clear_name([myname, '_', toks{1}{1}]);\n set_param(gw, 'n_bits', num2str(data_width));\n set_param(gw, 'Name', new_gw_name);\n gw = new_gw_name;\n elseif regexp(get_param(gw, 'Name'), '(data_valid)$')\n toks = regexp(get_param(gw, 'Name'), '(data_valid)$', 'tokens');\n set_param(gw, 'Name', clear_name([myname, '_', toks{1}{1}]));\n elseif regexp(get_param(gw, 'Name'), '(phy_ready)$')\n toks = regexp(get_param(gw, 'Name'), '(phy_ready)$', 'tokens');\n set_param(gw, 'Name', clear_name([myname, '_', toks{1}{1}]));\n elseif regexp(get_param(gw, 'Name'), '(cal_fail)$')\n toks = regexp(get_param(gw, 'Name'), '(cal_fail)$', 'tokens');\n set_param(gw, 'Name', clear_name([myname, '_', toks{1}{1}]));\n elseif regexp(get_param(gw, 'Name'), '(ack)$')\n toks = regexp(get_param(gw, 'Name'), '(ack)$', 'tokens');\n set_param(gw, 'Name', clear_name([myname, '_', toks{1}{1}]));\n else\n error(['Unknown gateway name: ', gw]);\n end\nend\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "tengbe_v2_mask.m", "ext": ".m", "path": "mlib_devel-master/xps_library/tengbe_v2_mask.m", "size": 25369, "source_encoding": "utf_8", "md5": "5fa8221ec632b0990d8d0329ea7598d3", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction tengbe_v2_mask(blk)\n\ncursys = blk;\n\n%set_param(cursys, 'LinkStatus', 'inactive');\n\n% rename gateways\ngateway_ins = find_system(cursys, 'searchdepth', 1, 'FollowLinks', 'on', 'lookundermasks', 'all', 'masktype', 'Xilinx Gateway In Block');\nfor i = 1 : length(gateway_ins),\n gw = gateway_ins{i};\n if regexp(get_param(gw, 'Name'), '_tx_afull$')\n set_param(gw, 'Name', clear_name([cursys, '_tx_afull']));\n elseif regexp(get_param(gw, 'Name'), '_tx_overflow$')\n set_param(gw, 'Name', clear_name([cursys, '_tx_overflow']));\n elseif regexp(get_param(gw, 'Name'), '_rx_valid$')\n set_param(gw, 'Name', clear_name([cursys, '_rx_valid']));\n elseif regexp(get_param(gw, 'Name'), '_rx_data$')\n set_param(gw, 'Name', clear_name([cursys, '_rx_data']));\n elseif regexp(get_param(gw, 'Name'), '_rx_source_ip$')\n set_param(gw, 'Name', clear_name([cursys, '_rx_source_ip']));\n elseif regexp(get_param(gw, 'Name'), '_rx_source_port$')\n set_param(gw, 'Name', clear_name([cursys, '_rx_source_port']));\n elseif regexp(get_param(gw, 'Name'), '_rx_end_of_frame$')\n set_param(gw, 'Name', clear_name([cursys, '_rx_end_of_frame']));\n elseif regexp(get_param(gw, 'Name'), '_rx_bad_frame$')\n set_param(gw, 'Name', clear_name([cursys, '_rx_bad_frame']));\n elseif regexp(get_param(gw, 'Name'), '_rx_overrun$')\n set_param(gw, 'Name', clear_name([cursys, '_rx_overrun']));\n elseif regexp(get_param(gw, 'Name'), '_led_up$')\n set_param(gw, 'Name', clear_name([cursys, '_led_up']));\n elseif regexp(get_param(gw, 'Name'), '_led_rx$')\n set_param(gw, 'Name', clear_name([cursys, '_led_rx']));\n elseif regexp(get_param(gw, 'Name'), '_led_tx$')\n set_param(gw, 'Name', clear_name([cursys, '_led_tx']));\n elseif regexp(get_param(gw, 'Name'), '_rx_size$')\n set_param(gw, 'Name', clear_name([cursys, '_rx_size']));\n else\n errordlg(['Unknown gateway: ', get_param(gw, 'Parent'), '/', get_param(gw, 'Name')]);\n end\nend\ngateway_outs = find_system(cursys, 'searchdepth', 1, 'FollowLinks', 'on', 'lookundermasks', 'all', 'masktype', 'Xilinx Gateway Out Block');\nfor i = 1 : length(gateway_outs),\n gw = gateway_outs{i};\n if regexp(get_param(gw, 'Name'), '_rst$')\n set_param(gw, 'Name', clear_name([cursys, '_rst']));\n elseif regexp(get_param(gw, 'Name'), '_tx_valid$')\n set_param(gw, 'Name', clear_name([cursys, '_tx_valid']));\n elseif regexp(get_param(gw, 'Name'), '_tx_end_of_frame$')\n set_param(gw, 'Name', clear_name([cursys, '_tx_end_of_frame']));\n elseif regexp(get_param(gw, 'Name'), '_tx_discard$')\n set_param(gw, 'Name', clear_name([cursys, '_tx_discard']));\n elseif regexp(get_param(gw, 'Name'), '_tx_data$')\n set_param(gw, 'Name', clear_name([cursys, '_tx_data']));\n elseif regexp(get_param(gw, 'Name'), '_tx_dest_ip$')\n set_param(gw, 'Name', clear_name([cursys, '_tx_dest_ip']));\n elseif regexp(get_param(gw, 'Name'), '_tx_dest_port$')\n set_param(gw, 'Name', clear_name([cursys, '_tx_dest_port']));\n elseif regexp(get_param(gw, 'Name'), '_rx_ack$')\n set_param(gw, 'Name', clear_name([cursys, '_rx_ack']));\n elseif regexp(get_param(gw, 'Name'), '_rx_overrun_ack$')\n set_param(gw, 'Name', clear_name([cursys, '_rx_overrun_ack']));\n else\n errordlg(['Unknown gateway: ', get_param(gw, 'Parent'), '/', get_param(gw, 'Name')]);\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% do debug counters and supporting logic\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ndebug_ctr_width = get_param(cursys, 'debug_ctr_width');\n% are any of the checkboxes actually checked?\nif strcmp(get_param(blk, 'txctr'), 'on') || strcmp(get_param(blk, 'txerrctr'), 'on') || ...\n strcmp(get_param(blk, 'txofctr'), 'on') || strcmp(get_param(blk, 'txfullctr'), 'on') || ...\n strcmp(get_param(blk, 'txvldctr'), 'on') || strcmp(get_param(blk, 'rxctr'), 'on') || ...\n strcmp(get_param(blk, 'rxerrctr'), 'on') || strcmp(get_param(blk, 'rxofctr'), 'on') || ...\n strcmp(get_param(blk, 'rxbadctr'), 'on') || strcmp(get_param(blk, 'rxvldctr'), 'on') || ...\n strcmp(get_param(blk, 'rxeofctr'), 'on'),\n\t% make sure the terminator and port are there\n reuse_block(cursys, 'debug_rst', 'built-in/inport', 'Port', '9', 'Position', [120 137 150 153]);\n reuse_block(cursys, 'debug_rst_goto', 'built-in/goto', 'GotoTag', 'debug_rst', 'Position', [200 135 280 150]);\n %reuse_block(cursys, 'term1', 'built-in/Terminator', 'Position', [200 135 220 155]);\n try add_line(cursys, 'debug_rst/1', 'debug_rst_goto/1'); catch e, end\nelse\n try delete_block_lines([blk, '/', 'debug_rst'], false); catch e, end\n try delete_block_lines([blk, '/', 'debug_rst_goto'], false); catch e, end\n %try delete_block_lines([blk, '/', 'term1'], false); catch e, end\nend\n\nfunction draw_counter(sys, ypos, targetname, source_tag)\n fromdbg_name = [targetname, '_fromdbg'];\n fromsrc_name = [targetname, '_fromsrc'];\n ctr_name = [targetname, '_ctr'];\n delay_name = [targetname, '_del'];\n if strcmp(get_param(sys, targetname), 'on')\n reuse_block(sys, fromdbg_name, 'built-in/from', ...\n 'GotoTag', 'debug_rst', ...\n 'Position', [280 ypos 400 ypos+12]);\n reuse_block(sys, fromsrc_name, 'built-in/from', ...\n 'GotoTag', source_tag, ...\n 'Position', [280 ypos+30 400 ypos+42]);\n reuse_block(sys, delay_name, 'xbsIndex_r4/Delay', ...\n 'reg_retiming', 'on', 'latency', '1', ...\n 'Position', [430 ypos 450 ypos+25]);\n reuse_block(sys, ctr_name, 'xbsIndex_r4/Counter', ...\n 'arith_type', 'Unsigned', 'n_bits', debug_ctr_width, 'explicit_period', 'on', ...\n 'period', '1', 'use_behavioral_HDL', 'on', 'rst', 'on', 'en', 'on', ...\n 'Position', [480 ypos 530 ypos+45]);\n reuse_block(sys, targetname, 'xps_library/software register', ...\n 'io_dir', 'To Processor', 'arith_types', '0', 'io_delay', '1', ...\n 'bitwidths', debug_ctr_width, ...\n 'sim_port', 'no', 'Position', [580 ypos 630 ypos+20]);\n try add_line(sys, [fromdbg_name, '/1'], [delay_name, '/1']); catch e, end\n try add_line(sys, [delay_name, '/1'], [ctr_name, '/1']); catch e, end\n try add_line(sys, [fromsrc_name, '/1'], [ctr_name, '/2']); catch e, end\n try add_line(sys, [ctr_name, '/1'], [targetname, '/1']); catch e, end\n else\n try delete_block_lines([sys, '/', fromdbg_name], false); catch e, end\n try delete_block_lines([sys, '/', fromsrc_name], false); catch e, end\n try delete_block_lines([sys, '/', targetname], false); catch e, end\n try delete_block_lines([sys, '/', ctr_name], false); catch e, end\n try delete_block_lines([sys, '/', delay_name], false); catch e, end\n try delete_block([sys, '/', fromdbg_name]); catch e, end\n try delete_block([sys, '/', fromsrc_name]); catch e, end\n try delete_block([sys, '/', delay_name]); catch e, end\n try delete_block([sys, '/', targetname]); catch e, end\n try delete_block([sys, '/', ctr_name]); catch e, end\n end\nend\n\nfunction draw_errorcounter(sys, ypos, targetname, frame_len, eof_tag, source_tag)\n fromdbg_name = [targetname, '_fromdbg'];\n fromeof_name = [targetname, '_fromeof'];\n fromsrc_name = [targetname, '_fromsrc'];\n ctr_name = [targetname, '_ctr'];\n nobad_name = [targetname, '_nobad'];\n errchk_name = [targetname, '_errchk'];\n delay_name = [targetname, '_del'];\n if strcmp(get_param(sys, targetname), 'on')\n reuse_block(sys, fromdbg_name, 'built-in/from', ...\n 'GotoTag', 'debug_rst', ...\n 'Position', [180 ypos 300 ypos+12]);\n reuse_block(sys, fromeof_name, 'built-in/from', ...\n 'GotoTag', eof_tag, ...\n 'Position', [180 ypos+15 300 ypos+27]);\n reuse_block(sys, fromsrc_name, 'built-in/from', ...\n 'GotoTag', source_tag, ...\n 'Position', [180 ypos+30 300 ypos+42]);\n reuse_block(sys, nobad_name, 'xbsIndex_r4/Constant', ...\n 'arith_type', 'Boolean', 'const', '0', 'explicit_period', 'on', 'period', '1', ...\n 'Position', [180 ypos+30 200 ypos+45]);\n reuse_block(sys, errchk_name, 'casper_library_communications/frame_len_checker', ...\n 'frame_len', frame_len, ...\n 'Position', [330, ypos, 420, ypos+45]);\n reuse_block(sys, delay_name, 'xbsIndex_r4/Delay', ...\n 'reg_retiming', 'on', 'latency', '1', ...\n 'Position', [430 ypos 450 ypos+25]);\n reuse_block(sys, ctr_name, 'xbsIndex_r4/Counter', ...\n 'arith_type', 'Unsigned', 'n_bits', debug_ctr_width, 'explicit_period', 'on', ...\n 'period', '1', 'use_behavioral_HDL', 'on', 'rst', 'on', 'en', 'on', ...\n 'Position', [480 ypos 530 ypos+45]);\n reuse_block(sys, targetname, 'xps_library/software register', ...\n 'io_dir', 'To Processor', 'arith_types', '0', 'io_delay', '1', ...\n 'bitwidths', debug_ctr_width, ...\n 'sim_port', 'no', 'Position', [580 ypos 630 ypos+20]);\n try add_line(sys, [fromsrc_name, '/1'], [errchk_name, '/1']); catch e, end\n try add_line(sys, [fromeof_name, '/1'], [errchk_name, '/2']); catch e, end\n try add_line(sys, [nobad_name, '/1'], [errchk_name, '/3']); catch e, end\n try add_line(sys, [fromdbg_name, '/1'], [delay_name, '/1']); catch e, end\n try add_line(sys, [delay_name, '/1'], [ctr_name, '/1']); catch e, end\n try add_line(sys, [errchk_name, '/1'], [ctr_name, '/2']); catch e, end\n try add_line(sys, [ctr_name, '/1'], [targetname, '/1']); catch e, end\n else\n try delete_block_lines([sys, '/', fromdbg_name], false); catch e, end\n try delete_block_lines([sys, '/', fromeof_name], false); catch e, end\n try delete_block_lines([sys, '/', fromsrc_name], false); catch e, end\n try delete_block_lines([sys, '/', errchk_name], false); catch e, end\n try delete_block_lines([sys, '/', nobad_name], false); catch e, end\n try delete_block_lines([sys, '/', targetname], false); catch e, end\n try delete_block_lines([sys, '/', ctr_name], false); catch e, end\n try delete_block_lines([sys, '/', delay_name], false); catch e, end\n try delete_block([sys, '/', fromdbg_name]); catch e, end\n try delete_block([sys, '/', fromeof_name]); catch e, end\n try delete_block([sys, '/', fromsrc_name]); catch e, end\n try delete_block([sys, '/', delay_name]); catch e, end\n try delete_block([sys, '/', errchk_name]); catch e, end\n try delete_block([sys, '/', nobad_name]); catch e, end\n try delete_block([sys, '/', targetname]); catch e, end\n try delete_block([sys, '/', ctr_name]); catch e, end\n end\nend\n\nfunction draw_rxcounter(sys, ypos, targetname, eof_tag, source_tag)\n fromdbg_name = [targetname, '_fromdbg'];\n fromeof_name = [targetname, '_fromeof'];\n fromsrc_name = [targetname, '_fromsrc'];\n ctr_name = [targetname, '_ctr'];\n and_name = [targetname, '_and'];\n ed_name = [targetname, '_ed'];\n delay_name = [targetname, '_del'];\n if strcmp(get_param(sys, targetname), 'on')\n reuse_block(sys, fromdbg_name, 'built-in/from', ...\n 'GotoTag', 'debug_rst', ...\n 'Position', [280 ypos 400 ypos+12]);\n reuse_block(sys, fromeof_name, 'built-in/from', ...\n 'GotoTag', eof_tag, ...\n 'Position', [280 ypos+15 400 ypos+27]);\n reuse_block(sys, fromsrc_name, 'built-in/from', ...\n 'GotoTag', source_tag, ...\n 'Position', [280 ypos+30 400 ypos+42]);\n reuse_block(sys, delay_name, 'xbsIndex_r4/Delay', ...\n 'reg_retiming', 'on', 'latency', '1', ...\n 'Position', [430 ypos 450 ypos+25]);\n reuse_block(sys, and_name, 'xbsIndex_r4/Logical', ...\n 'arith_type', 'Unsigned', 'logical_function', 'AND', 'inputs', '2', ...\n 'latency', '1', 'Position', [480 ypos 530 ypos+45]);\n reuse_block(sys, ed_name, 'casper_library_misc/edge_detect', ...\n 'edge', 'Rising', 'polarity', 'Active High',...\n 'Position', [580 ypos 630 ypos+20]);\n reuse_block(sys, ctr_name, 'xbsIndex_r4/Counter', ...\n 'arith_type', 'Unsigned', 'n_bits', debug_ctr_width, 'explicit_period', 'on', ...\n 'period', '1', 'use_behavioral_HDL', 'on', 'rst', 'on', 'en', 'on', ...\n 'Position', [680 ypos 730 ypos+45]);\n reuse_block(sys, targetname, 'xps_library/software_register', ...\n 'io_dir', 'To Processor', 'arith_types', '0', 'io_delay', '1', ...\n 'bitwidths', debug_ctr_width, ...\n 'sim_port', 'no', 'Position', [780 ypos 830 ypos+20]);\n try add_line(sys, [fromeof_name, '/1'], [and_name, '/1']); catch e, end\n try add_line(sys, [fromsrc_name, '/1'], [and_name, '/2']); catch e, end\n try add_line(sys, [and_name, '/1'], [ed_name, '/1']); catch e, end\n try add_line(sys, [fromdbg_name, '/1'], [delay_name, '/1']); catch e, end\n try add_line(sys, [delay_name, '/1'], [ctr_name, '/1']); catch e, end\n try add_line(sys, [ed_name, '/1'], [ctr_name, '/2']); catch e, end\n try add_line(sys, [ctr_name, '/1'], [targetname, '/1']); catch e, end\n else\n try delete_block_lines([sys, '/', fromdbg_name], false); catch e, end\n try delete_block_lines([sys, '/', fromeof_name], false); catch e, end\n try delete_block_lines([sys, '/', fromsrc_name], false); catch e, end\n try delete_block_lines([sys, '/', and_name], false); catch e, end\n try delete_block_lines([sys, '/', ed_name], false); catch e, end\n try delete_block_lines([sys, '/', targetname], false); catch e, end\n try delete_block_lines([sys, '/', ctr_name], false); catch e, end\n try delete_block_lines([sys, '/', delay_name], false); catch e, end\n try delete_block([sys, '/', fromdbg_name]); catch e, end\n try delete_block([sys, '/', fromeof_name]); catch e, end\n try delete_block([sys, '/', fromsrc_name]); catch e, end\n try delete_block([sys, '/', delay_name]); catch e, end\n try delete_block([sys, '/', and_name]); catch e, end\n try delete_block([sys, '/', ed_name]); catch e, end\n try delete_block([sys, '/', targetname]); catch e, end\n try delete_block([sys, '/', ctr_name]); catch e, end\n end\nend\n\nSPACING = 80;\n\n% tx counter\nstarty = 850;\ndraw_rxcounter(cursys, starty, 'txctr', 'gtx_eof', 'gtx_valid');\n\n% tx error counter\nstarty = starty + SPACING;\ndraw_errorcounter(cursys, starty, 'txerrctr', get_param(cursys, 'txerrctr_len'), 'gtx_eof', 'gtx_valid');\n\n% tx overflow counter\nstarty = starty + SPACING;\ndraw_counter(cursys, starty, 'txofctr', 'gtx_overflow');\n\n% tx full counter\nstarty = starty + SPACING;\ndraw_counter(cursys, starty, 'txfullctr', 'gtx_afull');\n\n% tx valid counter\nstarty = starty + SPACING;\ndraw_counter(cursys, starty, 'txvldctr', 'gtx_valid')\n\n% rx counter\nstarty = starty + SPACING;\ndraw_rxcounter(cursys, starty, 'rxctr', 'grx_eof', 'grx_valid')\n\n% rx error counter\nstarty = starty + SPACING;\ndraw_errorcounter(cursys, starty, 'rxerrctr', get_param(cursys, 'rxerrctr_len'), 'grx_eof', 'grx_valid');\n\n% rx overflow counter\nstarty = starty + SPACING;\ndraw_counter(cursys, starty, 'rxofctr', 'grx_overrun');\n\n% rx bad frame counter\nstarty = starty + SPACING;\ndraw_counter(cursys, starty, 'rxbadctr', 'grx_badframe');\n\n% rx valid counter\nstarty = starty + SPACING;\ndraw_counter(cursys, starty, 'rxvldctr', 'grx_valid');\n\n% rx eof counter\nstarty = starty + SPACING;\ndraw_counter(cursys, starty, 'rxeofctr', 'grx_eof');\n\n% rx snapshot\nsnaplen = get_param(cursys, 'rxsnaplen');\nsnapname = 'rxs';\nif strcmp(snaplen, '0 - no snap') == 0,\n ypos = 981;\n \n reuse_block(cursys, 'rxs_fr0', 'built-in/from', 'GotoTag', 'grx_led_up', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'rxs_fr1', 'built-in/from', 'GotoTag', 'grx_led_rx', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'rxs_fr2', 'built-in/from', 'GotoTag', 'grx_data', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'rxs_fr3', 'built-in/from', 'GotoTag', 'grx_valid', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'rxs_fr4', 'built-in/from', 'GotoTag', 'grx_src_ip', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'rxs_fr5', 'built-in/from', 'GotoTag', 'grx_eof', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'rxs_fr6', 'built-in/from', 'GotoTag', 'grx_badframe', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'rxs_fr7', 'built-in/from', 'GotoTag', 'grx_overrun', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'rxs_frwe', 'built-in/from', 'GotoTag', 'grx_valid', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'rxs_frtrig1', 'built-in/from', 'GotoTag', 'grx_valid', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'rxs_frtrig2', 'built-in/from', 'GotoTag', 'grx_eof', 'Position', [900 ypos 1000 ypos+12]);\n reuse_block(cursys, snapname, 'casper_library_scopes/bitfield snapshot', ...\n 'Position', [1155 981 1260 1234], ...\n 'io_names', '[led_up led_rx data_in valid_in ip_in eof_in bad_frame overrun]', ...\n 'io_widths', '[1 1 64 1 32 1 1 1]', ...\n 'io_bps', '[0 0 0 0 0 0 0 0]', ...\n 'io_types', '[2 2 0 2 0 2 2 2]', ...\n 'snap_storage', 'bram', ...\n 'snap_dram_dimm', '2', ...\n 'snap_dram_clock', '250', ...\n 'snap_nsamples', num2str(log2(str2double(snaplen))), ...\n 'snap_data_width', '128', ...\n 'snap_offset', 'off', ...\n 'snap_circap', 'off', ...\n 'snap_value', 'off', ...\n 'snap_use_dsp48', 'on', ...\n 'snap_delay', '5', ...\n 'extra_names', '[notused]', ...\n 'extra_widths', '[32]', ...\n 'extra_bps', '[0]', ...\n 'extra_types', '[0]');\n reuse_block(cursys, 'rxsnap_and', 'xbsIndex_r4/Logical', ...\n 'arith_type', 'Unsigned', 'logical_function', 'AND', 'inputs', '2', ...\n 'Position', [1070 1194 1120 1241]);\n try add_line(cursys, 'rxs_fr0/1',\t[snapname, '/1']); catch e, end\n try add_line(cursys, 'rxs_fr1/1', [snapname, '/2']); catch e, end\n try add_line(cursys, 'rxs_fr2/1', [snapname, '/3']); catch e, end\n try add_line(cursys, 'rxs_fr3/1', [snapname, '/4']); catch e, end\n try add_line(cursys, 'rxs_fr4/1', [snapname, '/5']); catch e, end\n try add_line(cursys, 'rxs_fr5/1', [snapname, '/6']); catch e, end\n try add_line(cursys, 'rxs_fr6/1', [snapname, '/7']); catch e, end\n try add_line(cursys, 'rxs_fr7/1', [snapname, '/8']); catch e, end\n try add_line(cursys, 'rxs_frwe/1', [snapname, '/9']); catch e, end\n try add_line(cursys, 'rxs_frtrig1/1', 'rxsnap_and/1'); catch e, end\n try add_line(cursys, 'rxs_frtrig2/1', 'rxsnap_and/2'); catch e, end\n try add_line(cursys, 'rxsnap_and/1',[snapname, '/10']); catch e, end\nelse\n try delete_block_lines([cursys, '/', snapname], false); catch e, end\n try delete_block_lines([cursys, '/rxsnap_and'], false); catch e, end\n try delete_block([cursys, '/', snapname]); catch e, end\n try delete_block([cursys, '/rxsnap_and']); catch e, end\nend\n% tx snapshot\nsnaplen = get_param(cursys, 'txsnaplen');\nsnapname = 'txs';\nif strcmp(snaplen, '0 - no snap') == 0,\n ypos = 1302;\n reuse_block(cursys, 'txs_fr0', 'built-in/from', 'GotoTag', 'grx_led_up', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'txs_fr1', 'built-in/from', 'GotoTag', 'grx_led_tx', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'txs_fr2', 'built-in/from', 'GotoTag', 'gtx_afull', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'txs_fr3', 'built-in/from', 'GotoTag', 'gtx_overflow', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'txs_fr4', 'built-in/from', 'GotoTag', 'gtx_valid', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'txs_fr5', 'built-in/from', 'GotoTag', 'gtx_eof', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'txs_fr6', 'built-in/from', 'GotoTag', 'gtx_data', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'txs_fr7', 'built-in/from', 'GotoTag', 'gtx_dest_ip', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'txs_frwe', 'built-in/from', 'GotoTag', 'gtx_valid', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'txs_frtrig1', 'built-in/from', 'GotoTag', 'gtx_valid', 'Position', [900 ypos 1000 ypos+12]); ypos = ypos + 15;\n reuse_block(cursys, 'txs_frtrig2', 'built-in/from', 'GotoTag', 'gtx_eof', 'Position', [900 ypos 1000 ypos+12]);\n reuse_block(cursys, snapname, 'casper_library_scopes/bitfield snapshot', ...\n 'Position', [1155 1302 1260 1528], ...\n 'io_names', '[link_up led_tx tx_full tx_over valid eof data ip]', ...\n 'io_widths', '[1 1 1 1 1 1 64 32]', ...\n 'io_bps', '[0 0 0 0 0 0 0 0]', ...\n 'io_types', '[2 2 2 2 2 2 0 0]', ...\n 'snap_storage', 'bram', ...\n 'snap_dram_dimm', '2', ...\n 'snap_dram_clock', '250', ...\n 'snap_nsamples', num2str(log2(str2double(snaplen))), ...\n 'snap_data_width', '128', ...\n 'snap_offset', 'off', ...\n 'snap_circap', 'off', ...\n 'snap_value', 'off', ...\n 'snap_use_dsp48', 'on', ...\n 'snap_delay', '5', ...\n 'extra_names', '[notused]', ...\n 'extra_widths', '[32]', ...\n 'extra_bps', '[0]', ...\n 'extra_types', '[0]');\n reuse_block(cursys, 'txsnap_and', 'xbsIndex_r4/Logical', ...\n 'arith_type', 'Unsigned', 'logical_function', 'AND', 'inputs', '2', ...\n 'Position', [1060 1479 1110 1526]);\n try add_line(cursys, 'txs_fr0/1',\t[snapname, '/1']); catch e, end\n try add_line(cursys, 'txs_fr1/1', [snapname, '/2']); catch e, end\n try add_line(cursys, 'txs_fr2/1', [snapname, '/3']); catch e, end\n try add_line(cursys, 'txs_fr3/1', [snapname, '/4']); catch e, end\n try add_line(cursys, 'txs_fr4/1', [snapname, '/5']); catch e, end\n try add_line(cursys, 'txs_fr5/1', [snapname, '/6']); catch e, end\n try add_line(cursys, 'txs_fr6/1', [snapname, '/7']); catch e, end\n try add_line(cursys, 'txs_fr7/1', [snapname, '/8']); catch e, end\n try add_line(cursys, 'txs_frwe/1', [snapname, '/9']); catch e, end\n try add_line(cursys, 'txs_frtrig1/1', 'txsnap_and/1'); catch e, end\n try add_line(cursys, 'txs_frtrig2/1', 'txsnap_and/2'); catch e, end\n try add_line(cursys, 'txsnap_and/1',[snapname, '/10']); catch e, end\nelse\n try delete_block_lines([cursys, '/', snapname], false); catch e, end\n try delete_block_lines([cursys, '/txsnap_and'], false); catch e, end\n try delete_block([cursys, '/', snapname]); catch e, end\n try delete_block([cursys, '/txsnap_and']); catch e, end\nend\n\n% remove unconnected blocks\nclean_blocks(cursys);\n\nend\n% end\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "clear_path.m", "ext": ".m", "path": "mlib_devel-master/xps_library/clear_path.m", "size": 2257, "source_encoding": "utf_8", "md5": "a91a0542b334e62a030a2b770c286441", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction result = clear_path(str);\n\nj = 1;\nresult='';\n\nfor i = 1:length(str)\n c = str(i);\n if c < 32 % don't include funky characters\n result = result;\n elseif (c==34) | (c==42) | (c==60) | (c==62) |(c==63) | (c==124) % don't include invalid windows characters\n result = result;\n elseif c == 47 % convert POSIX '/' to Windows '\\'\n result(j) = '\\';\n j = j + 1;\n else\n result(j) = str(i);\n j = j + 1;\n end\nend\n\n% trim trailing '\\'\nif result(length(result)) == '\\'\n result = result(1:length(result)-1);\nend\n\nreturn;\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "read_xps.m", "ext": ".m", "path": "mlib_devel-master/xps_library/read_xps.m", "size": 4167, "source_encoding": "utf_8", "md5": "18cabd9adf1c1faa71b23d0f63b3d287", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction out = read_xps(core_name, serial_port)\ntry\n % open serial port\n s = serial(serial_port);\n set(s,'BaudRate',115200);\n set(s,'InputBufferSize' ,127);\n set(s,'OutputBufferSize',127);\n set(s,'Timeout',3);\n set(s,'ByteOrder','bigEndian');\n fopen(s);\n\n % send a request information to the iBOB\n % special opcode\n fwrite(s,uint8(129));\n % block name\n fwrite(s,uint8(core_name));\n % zero string termination\n fwrite(s,uint8(0));\n % get the result code\n request_result = fread(s, 1, 'uint8');\n % get the result string\n request_string = '';\n c = fread(s,1,'uint8');\n while c ~= 0\n request_string = [request_string,char(c)];\n c = fread(s,1,'uint8');\n end\n if request_result ~= 0\n disp(['Error: ',request_string]);\n fclose(s);\n delete(s);\n clear s;\n return;\n end\n toks = regexp(request_string,'(\\w+)', 'tokens');\n type = toks{1};\n type = type{1};\n param = toks{5};\n param = param{1};\n address = toks{3};\n address = address{1};\n address = hex2dec(address(3:end));\n\n if strcmp(type,'xps_bram')\n size = str2num(param);\n out = [];\n\n while size > 0\n if size > 31\n block_size = 31;\n else\n block_size = size;\n end\n\n header(1) = uint8(128);\n header(2) = uint8(0 + block_size);\n header(3) = uint8(mod(floor(address/(2^24)),2^8));\n header(4) = uint8(mod(floor(address/(2^16)),2^8));\n header(5) = uint8(mod(floor(address/(2^8 )),2^8));\n header(6) = uint8(mod(floor(address/(2^0 )),2^8));\n\n fwrite(s, header);\n fprintf('.');\n\n out = [out; fread(s, block_size, 'uint32')];\n size = size - block_size;\n address = address + (block_size * 4);\n end\n fprintf('\\n');\n\n elseif strcmp(type,'xps_sw_reg')\n\n header(1) = uint8(128);\n header(2) = uint8(0 + 1);\n header(3) = uint8(mod(floor(address/(2^24)),2^8));\n header(4) = uint8(mod(floor(address/(2^16)),2^8));\n header(5) = uint8(mod(floor(address/(2^8 )),2^8));\n header(6) = uint8(mod(floor(address/(2^0 )),2^8));\n\n fwrite(s, header);\n\n out = fread(s, 1, 'uint32');\n end\n\n fclose(s);\n delete(s);\n clear s;\n\n out = cast(out, 'uint32');\ncatch\n fclose(s);\n delete(s);\n clear s;\n disp(lasterr);\n out = 0;\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "adc_common.m", "ext": ".m", "path": "mlib_devel-master/xps_library/adc_common.m", "size": 14293, "source_encoding": "utf_8", "md5": "d543da218311a52eb881ba0087ca0b99", "text": "% simulates a generic CASPER-style ADC\n%\n% function adc_common(blk, varargin) \n%\n% \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Collaboration for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2010 Andrew Martens SKA/SA %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [yoffset] = adc_common(blk, varargin)\n\n clog('adc_common: entering','trace');\n\n defaults = {'in', 1, 'out', 8, 'bits', 8, 'adc_interleave', 'off', ...\n 'xoff', 0, 'xtick', 120, 'yoff', 10, 'ytick', 80, ... \n 'or_support', 'on', 'sync_support', 'on', 'dv_support', 'on', ...\n 'or_per_input', 1};\n\n in = get_var('in', 'defaults', defaults, varargin{:});\n out = get_var('out', 'defaults', defaults, varargin{:});\n bits = get_var('bits', 'defaults', defaults, varargin{:});\n adc_interleave = get_var('adc_interleave', 'defaults', defaults, varargin{:});\n or_support = get_var('or_support', 'defaults', defaults, varargin{:});\n sync_support = get_var('sync_support', 'defaults', defaults, varargin{:});\n dv_support = get_var('dv_support', 'defaults', defaults, varargin{:});\n or_per_input = get_var('or_per_input', 'defaults', defaults, varargin{:});\n xoff = get_var('xoff', 'defaults', defaults, varargin{:});\n xtick = get_var('xtick', 'defaults', defaults, varargin{:});\n yoff = get_var('yoff', 'defaults', defaults, varargin{:});\n ytick = get_var('ytick', 'defaults', defaults, varargin{:});\n\n clog(['in: ',num2str(in),' out: ',num2str(out),' bits: ',num2str(bits),' adc_interleave: ',adc_interleave, ...\n ' or_support: ',or_support,' sync_support: ',sync_support,' dv_support: ',dv_support,' or_per_input: ',num2str(or_per_input)], 'adc_common_debug');\n\n %useful derivatives\n if strcmp(adc_interleave,'on'), il = 1; else, il = 0; end\n if strcmp(or_support,'on'), of = 1; else, of = 0; end\n if strcmp(sync_support,'on'), sync = 1; else, sync = 0; end\n if strcmp(dv_support,'on'), dv = 1; else, dv = 0; end\n\n %constants used in spacing blocks\n% xtick = 120; \n% ytick = 40+5*(of*out); \n% yoff = 0; %for relative positions \n\n %data input ports\n% xoff = 0;\n\n yw = 3+or_per_input; \n yoff = yoff+1+dv+sync*out;\n \n clog('doing data','adc_common_detailed_trace');\n yoff = yoff + 1;\n for d = 0:in-1\n\n reuse_block(blk, ['sim_data',num2str(d)], 'built-in/inport', 'Port', num2str(d+1), ...\n 'Position', [xtick-15 ytick*yoff-7.5 xtick+15 ytick*yoff+7.5]);\n\n %gain\n clog('doing gain and offset','adc_common_detailed_trace');\n reuse_block(blk, ['gain',num2str(d)], 'built-in/gain', 'Gain', num2str((2^bits-1)/2) , 'SampleTime', '-1', ...\n 'Position', [xtick*2-15 ytick*yoff-10 xtick*2+15 ytick*yoff+10]);\n add_line(blk, ['sim_data', num2str(d), '/1'], ['gain',num2str(d),'/1']);\n \n %bias\n reuse_block(blk, ['bias',num2str(d)], 'built-in/bias', 'Bias', num2str((2^bits-1)/2) , ...\n 'SaturateOnIntegerOverflow', 'on', ...\n 'Position', [xtick*3-15 ytick*yoff-10 xtick*3+15 ytick*yoff+10]);\n add_line(blk, ['gain', num2str(d), '/1'], ['bias',num2str(d),'/1']);\n\n %down sample \n clog('down sampling','adc_common_detailed_trace');\n for ds = 0:out-1,\n\n %downsampler\n clog(['downsampler_',num2str(d),'_ds',num2str(ds)],'adc_common_detailed_trace');\n reuse_block(blk, ['d',num2str(d),'_ds',num2str(ds)], 'dspsigops/Downsample', ...\n 'N', num2str(out), 'phase', num2str(ds), ...\n 'Position', [xtick*4-20 ytick*yoff-10 xtick*4+20 ytick*yoff+10]);\n % Try to set options required for Downsample block of newer DSP blockset\n % versions, but not available in older versions.\n try\n set_param([blk, '/d',num2str(d),'_ds',num2str(ds)], ...\n 'InputProcessing', 'Elements as channels (sample based)', ...\n 'RateOptions', 'Allow multirate processing');\n catch\n end;\n\n clog(['downsampler_',num2str(d),'_ds',num2str(ds),' line'],'adc_common_detailed_trace');\n add_line(blk, ['bias',num2str(d),'/1'], ['d',num2str(d),'_ds',num2str(ds),'/1']);\n\n %delay\n clog(['delay_',num2str(d),'_del',num2str(ds)],'adc_common_detailed_trace');\n \n if ds == 0, NumDelays = 2; else, NumDelays = 1; end\n\n reuse_block(blk, ['d',num2str(d),'_del',num2str(ds)], 'simulink/Discrete/Integer Delay', ...\n 'NumDelays', num2str(NumDelays), 'samptime', '-1', ...\n 'Position', [xtick*5-20 ytick*yoff-10 xtick*5+20 ytick*yoff+10]);\n add_line(blk,['d',num2str(d),'_ds',num2str(ds),'/1'], ['d',num2str(d),'_del',num2str(ds),'/1']);\n\n %input gateways for data\n clog(['data gateway ',num2str(d*out+ds)],'adc_common_detailed_trace');\n %gateway\n if il == 1, %need to generate name as though from interleaved ADC\n d_index = d*out+floor(ds/2) + (out/2)*rem(ds,2);\n else\n d_index = d*out+ds;\n end\n name = clear_name([blk, '_user_data', num2str(d_index)]);\n reuse_block(blk, name, 'xbsIndex_r4/Gateway In', ...\n 'arith_type', 'Unsigned', 'n_bits', num2str(bits), 'bin_pt', '0', ... \n 'Position', [xtick*8-20 ytick*yoff-10 xtick*8+20 ytick*yoff+10]);\n add_line(blk,['d',num2str(d),'_del',num2str(ds),'/1'], [name,'/1']);\n\n %convert to two's complement\n clog(['two''s complement ',num2str(d*out+ds)],'adc_common_detailed_trace');\n blk_name = ['sign',num2str(d),'_',num2str(ds)];\n reuse_block(blk, blk_name, 'xbsIndex_r4/Slice', ...\n 'nbits', '1', 'mode', 'Upper Bit Location + Width', 'bit0', '0', 'base0', 'MSB of Input', ... \n 'Position', [xtick*9-15 ytick*yoff-7.5 xtick*9+15 ytick*yoff+7.5]);\n add_line(blk, [name,'/1'], [blk_name, '/1']); \n prev = blk_name;\n inv_name = ['inv',num2str(d),'_',num2str(ds)];\n reuse_block(blk, inv_name, 'xbsIndex_r4/Inverter', ...\n 'latency', '0', ... \n 'Position', [xtick*10-15 ytick*yoff-7.5 xtick*10+15 ytick*yoff+7.5]);\n add_line(blk, [prev,'/1'], [inv_name, '/1']); \n \n blk_name = ['val',num2str(d),'_',num2str(ds)];\n reuse_block(blk, blk_name, 'xbsIndex_r4/Slice', ...\n 'nbits', num2str(bits-1), 'mode', 'Lower Bit Location + Width', 'bit1', '0', 'base1', 'LSB of Input', ... \n 'Position', [xtick*9-15 ytick*(yoff+1)-7.5 xtick*9+15 ytick*(yoff+1)+7.5]);\n add_line(blk, [name,'/1'], [blk_name, '/1']); \n prev = blk_name;\n \n blk_name = ['concat',num2str(d),'_',num2str(ds)];\n reuse_block(blk, blk_name, 'xbsIndex_r4/Concat', ...\n 'num_inputs', '2', ...\n 'Position', [xtick*11-15 ytick*yoff-15 xtick*11+15 ytick*yoff+15]);\n add_line(blk, [inv_name,'/1'], [blk_name, '/1']); \n add_line(blk, [prev,'/1'], [blk_name, '/2']); \n prev = blk_name;\n \n blk_name = ['reinterpret',num2str(d),'_',num2str(ds)];\n reuse_block(blk, blk_name, 'xbsIndex_r4/Reinterpret', ...\n 'force_arith_type', 'on', 'arith_type', 'Signed (2''s comp)', 'force_bin_pt', 'on', 'bin_pt', num2str(bits-1), ...\n 'Position', [xtick*12-30 ytick*yoff-7.5 xtick*12+30 ytick*yoff+7.5]);\n add_line(blk, [prev,'/1'], [blk_name, '/1']); \n prev = blk_name;\n\n %output ports\n clog(['data output port ',num2str(d*out+ds)],'adc_common_detailed_trace');\n %output\n reuse_block(blk, ['data',num2str(d),'_',num2str(ds)], 'built-in/outport', 'Port', num2str(d*(out+of*or_per_input)+ds+1), ...\n 'Position', [xtick*13-15 ytick*yoff-7.5 xtick*13+15 ytick*yoff+7.5]);\n add_line(blk, [prev,'/1'], ['data',num2str(d),'_',num2str(ds),'/1']);\n \n %overflow detection\n if of == 1,\n clog('overflow','adc_common_detailed_trace');\n blk_name = ['lt',num2str(d),'_',num2str(ds)]; \n reuse_block(blk, blk_name, 'simulink/Logic and Bit Operations/Compare To Constant', ...\n 'relop', '<', 'const', '0', 'LogicOutDataTypeMode', 'boolean', ...\n 'Position', [xtick*6-15 ytick*(yoff+1)-15 xtick*6+15 ytick*(yoff+1)+15]);\n add_line(blk, ['d',num2str(d),'_del',num2str(ds),'/1'], [blk_name,'/1']);\n \n blk_name = ['gt',num2str(d),'_',num2str(ds)]; \n reuse_block(blk, blk_name, 'simulink/Logic and Bit Operations/Compare To Constant', ...\n 'relop', '>', 'const', num2str((2^bits)-1), 'LogicOutDataTypeMode', 'boolean', ...\n 'Position', [xtick*6-15 ytick*(yoff+2)-15 xtick*6+15 ytick*(yoff+2)+15]);\n add_line(blk, ['d',num2str(d),'_del',num2str(ds),'/1'], [blk_name,'/1']);\n\n if ds == out-1,\n or_name = ['logical',num2str(d)];\n reuse_block(blk, or_name, 'built-in/Logical Operator', ...\n 'Inputs', num2str(out*2), 'Operator', 'OR', ...\n 'Position', [xtick*7-15 ytick*(yoff+2)-15 xtick*7+15 ytick*(yoff+2)+15]);\n for ofn = 0:out-1\n add_line(blk, ['lt',num2str(d),'_',num2str(ofn),'/1'],[or_name,'/',num2str(ofn*2+1)]);\n add_line(blk, ['gt',num2str(d),'_',num2str(ofn),'/1'],[or_name,'/',num2str(ofn*2+2)]);\n end\n\n for of_port = 0:or_per_input-1,\n gw = clear_name([blk, '_user_outofrange', num2str(d*or_per_input+of_port)]);\n reuse_block(blk, gw, 'xbsIndex_r4/Gateway In', ...\n 'arith_type', 'Boolean', ... \n 'Position', [xtick*8-20 ytick*(yoff+of_port+2)-10 xtick*8+20 ytick*(yoff+of_port+2)+10]);\n add_line(blk,[or_name,'/1'], [gw,'/1']);\n \n clog(['out of range output port ',num2str(d*or_per_input+of_port),' at ',num2str(d*(out+or_per_input)+out+of_port+1)],'adc_common_detailed_trace');\n reuse_block(blk, ['or',num2str(d*or_per_input+of_port)], 'built-in/outport', 'Port', num2str(d*(out+or_per_input)+out+of_port+1), ...\n 'Position', [xtick*13-15 ytick*(yoff+2+of_port)-7.5 xtick*13+15 ytick*(yoff+2+of_port)+7.5]);\n add_line(blk, [gw,'/1'], ['or',num2str(d*or_per_input+of_port),'/1']);\n end\n end \n end %if of\n \n yoff = yoff + yw;\n end %for ds\n end %for d\n\n clog(['sync '],'adc_common_detailed_trace');\n \n %sync support\n if sync == 1,\n reuse_block(blk, ['sim_sync'], 'built-in/inport', 'Port', num2str(in+1), 'Position', [xtick-15 ytick*(1+dv)-7.5 xtick+15 ytick*(dv+1)+7.5]);\n for ds = 0:out/(2^il)-1,\n reuse_block(blk, ['sync_ds',num2str(ds)], 'dspsigops/Downsample', ...\n 'N', num2str(out), 'phase', num2str(ds*(2^il)), ...\n 'Position', [xtick*4-20 ytick*(dv+1+ds)-10 xtick*4+20 ytick*(dv+1+ds)+10]);\n % Try to set options required for Downsample block of newer DSP blockset\n % versions, but not available in older versions.\n try\n set_param([blk, '/sync_ds',num2str(ds)], ...\n 'InputProcessing', 'Elements as channels (sample based)', ...\n 'RateOptions', 'Allow multirate processing');\n catch\n end;\n add_line(blk,'sim_sync/1', ['sync_ds',num2str(ds),'/1']);\n\n %delay\n if ds == 0, NumDelays = 2; else, NumDelays = 1; end\n reuse_block(blk, ['sync_del',num2str(ds)], 'simulink/Discrete/Integer Delay', ...\n 'NumDelays', num2str(NumDelays), 'samptime', '-1', ...\n 'Position', [xtick*5-20 ytick*(dv+1+ds)-10 xtick*5+20 ytick*(dv+1+ds)+10]);\n add_line(blk,['sync_ds',num2str(ds),'/1'], ['sync_del',num2str(ds),'/1']);\n \n %gateway\n name = clear_name([blk, '_user_sync', num2str(ds)]);\n reuse_block(blk, name, 'xbsIndex_r4/Gateway In', ...\n 'arith_type', 'Boolean', ... \n 'Position', [xtick*8-20 ytick*(dv+1+ds)-10 xtick*8+20 ytick*(dv+1+ds)+10]);\n add_line(blk,['sync_del',num2str(ds),'/1'], [name,'/1']);\n\n %output\n clog(['doing sync ', num2str(ds),' at ',num2str((in*out)+(of*in*or_per_input)+(ds+1))],'adc_common_detailed_trace');\n reuse_block(blk, ['sync',num2str(ds)], 'built-in/outport', 'Port', num2str((in*out)+(of*in*or_per_input)+(ds+1)), ...\n 'Position', [xtick*11-15 ytick*(dv+1+ds)-7.5 xtick*11+15 ytick*(dv+1+ds)+7.5]);\n add_line(blk, [name,'/1'], ['sync',num2str(ds),'/1']);\n end\n end\n \n clog('data valid','adc_common_detailed_trace');\n \n if dv == 1, \n %data valid support\n clog('doing data_valid','adc_common_detailed_trace');\n reuse_block(blk, 'sim_data_valid', 'built-in/inport', 'Port', num2str(in+sync+1), 'Position', [xtick*1-15 ytick-7.5 xtick*1+15 ytick+7.5]);\n name = clear_name([blk, '_user_data_valid']);\n reuse_block(blk, name, 'xbsIndex_r4/Gateway In', ...\n 'arith_type', 'Boolean', ...\n 'Position', [xtick*8-20 ytick-10 xtick*8+20 ytick+10 ]);\n add_line(blk,'sim_data_valid/1', [name,'/1']);\n reuse_block(blk, 'data_valid', 'built-in/outport', 'Port', num2str(out*in+out/(2^il)*sync+(of*in*or_per_input)+1),...\n 'Position', [xtick*11-15 ytick-7.5 xtick*11+15 ytick+7.5]);\n add_line(blk, [name,'/1'], 'data_valid/1');\n end\n\n yoffset = yoff+1; \n \n clog('adc_common: exiting','trace');\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "swreg_init.m", "ext": ".m", "path": "mlib_devel-master/xps_library/swreg_init.m", "size": 12294, "source_encoding": "utf_8", "md5": "4c6a9e7bea980df0e4710ccc3e35f74d", "text": "function swreg_init(blk)\n\nclog('entering swreg_init', 'trace');\ncheck_mask_type(blk, 'swreg');\ntry\n munge_block(blk);\n remove_all_blks(blk);\n delete_lines(blk);\ncatch ex\n if regexp(ex.identifier, 'CallbackDelete')\n return\n end\n dump_and_rethrow(ex);\nend\n\n% perform a sanity check on the mask values\n[numios, current_names, current_widths, current_bins, current_types] = swreg_maskcheck(blk);\n\n% should we make a sim in/out?\nsimport = true;\ntry\n if strcmp(get_param(blk, 'sim_port'), 'off'),\n simport = false;\n end\ncatch ex\nend\n\n% add the inputs, outputs and gateway out blocks, drawing lines between them\nx_size = 100;\ny_size = 20;\nx_start = 100;\ny_pos = 100;\n\n% the rest depends on whether it's an in or out reg\n% mode = get_param(blk, 'mode');\n% current_names = textscan(strtrim(strrep(strrep(strrep(strrep(get_param(blk, 'names'), ']', ''), '[', ''), ',', ' '), ' ', ' ')), '%s');\n% current_names = current_names{1};\n% numios = length(current_names);\n% current_types = eval(get_param(blk, 'arith_types'));\n% current_bins = eval(get_param(blk, 'bin_pts'));\n% current_widths = eval(get_param(blk, 'bitwidths'));\n% if strcmp(mode, 'fields of equal size'),\n% ctypes = current_types;\n% cbins = current_bins;\n% cwidths = current_widths;\n% current_types = zeros(numios, 1);\n% current_bins = zeros(numios, 1);\n% current_widths = zeros(numios, 1);\n% for ctr = 1 : numios,\n% current_types(ctr) = ctypes(1);\n% current_bins(ctr) = cbins(1);\n% current_widths(ctr) = cwidths(1);\n% end\n% end\nio_dir = get_param(blk, 'io_dir');\nif strcmp(io_dir, 'To Processor'),\n iodir = 'output';\n draw_to();\nelse\n iodir = 'input';\n draw_from();\nend\n\n% remove unconnected blocks\nclean_blocks(blk);\n\n% update format string so we know what's going on with this block\nshow_format = get_param(blk, 'show_format');\nif numios == 1,\n display_string = strcat('1', ' ', iodir);\nelse\n display_string = sprintf('%d %ss', numios, iodir);\nend\nif strcmp(show_format, 'on'),\n config_string = '';\n for ctr = 1 : numios,\n switch current_types(ctr),\n case 1 \n config_string = strcat(config_string, sprintf('f%i.%i,', current_widths(ctr), current_bins(ctr)));\n case 2\n config_string = strcat(config_string, 'b,');\n otherwise \n config_string = strcat(config_string, sprintf('uf%i.%i,', current_widths(ctr), current_bins(ctr)));\n end\n end\n display_string = strcat(display_string, ': ', config_string);\nend\nset_param(blk, 'AttributesFormatString', display_string);\n\nclog('exiting swreg_init','trace');\n\nfunction stype = type_to_string(arith_type)\n switch arith_type\n case 0\n stype = 'Unsigned';\n return\n case 1\n stype = 'Signed (2''s comp)';\n return\n case 2\n stype = 'Boolean';\n return\n otherwise\n error('Unknown type %i', arith_type);\n end\nend\n\nfunction draw_to()\n y_pos_row = y_pos;\n if numios > 1,\n % concat block\n reuse_block(blk, 'concatenate', 'xbsIndex_r4/Concat', ...\n 'Position', [x_start + (x_size * 2 * 2), y_pos_row, x_start + (x_size * 2 * 2) + (x_size/2), y_pos_row + (numios * y_size)], ...\n 'num_inputs', num2str(numios));\n end\n % io delay\n reuse_block(blk, 'io_delay', 'xbsIndex_r4/Delay', 'latency', get_param(blk, 'io_delay'), 'reg_retiming', 'on', ...\n 'Position', [x_start + (x_size * 2.5 * 2), y_pos_row, x_start + (x_size * 2.5 * 2) + (x_size/2), y_pos_row + y_size]);\n % cast block\n reuse_block(blk, 'cast_gw', 'xbsIndex_r4/Convert', ...\n 'Position', [x_start + (x_size * 3 * 2), y_pos_row, x_start + (x_size * 3 * 2) + (x_size/2), y_pos_row + y_size], ...\n 'arith_type', 'Unsigned', 'n_bits', '32', ...\n 'bin_pt', '0');\n % gateway out block\n gwout_name = [strrep(blk, '/', '_'), '_user_data_in'];\n reuse_block(blk, gwout_name, 'xbsIndex_r4/Gateway Out', ...\n 'Position', [x_start + (x_size * 4 * 2), y_pos_row, x_start + (x_size * 4 * 2) + (x_size/2), y_pos_row + y_size], ...\n 'hdl_port', 'on');\n if simport,\n reuse_block(blk, 'sim_out', 'built-in/outport', 'Port', '1', ...\n 'Position', [x_start + (x_size * 6 * 2), y_pos_row, x_start + (x_size * 6 * 2) + (x_size/2), y_pos_row + y_size]);\n else\n reuse_block(blk, 'sim_out', 'built-in/terminator', ...\n 'Position', [x_start + (x_size * 6 * 2), y_pos_row, x_start + (x_size * 6 * 2) + (x_size/2), y_pos_row + y_size]);\n end\n if numios > 1,\n add_line(blk, 'concatenate/1', 'io_delay/1', 'autorouting', 'on');\n end\n add_line(blk, 'io_delay/1', 'cast_gw/1', 'autorouting', 'on');\n add_line(blk, 'cast_gw/1', [gwout_name, '/1'], 'autorouting', 'on');\n add_line(blk, [gwout_name, '/1'], 'sim_out/1', 'autorouting', 'on');\n % ports\n for pindex = 1 : numios,\n in_name = sprintf('out_%s', current_names{pindex});\n assert_name = sprintf('assert_%s', current_names{pindex});\n reinterpret_name = sprintf('reint%i', pindex);\n if current_types(pindex) == 2\n gddtype = 'Boolean';\n else\n gddtype = 'Fixed-point';\n end\n reuse_block(blk, in_name, 'built-in/inport', ...\n 'Port', num2str(pindex), ...\n 'Position', [x_start, y_pos_row, x_start + (x_size/2), y_pos_row + y_size]);\n reuse_block(blk, assert_name, 'xbsIndex_r4/Assert', ...\n 'showname', 'off', 'assert_type', 'on', ...\n 'type_source', 'Explicitly', 'arith_type', type_to_string(current_types(pindex)), ...\n 'bin_pt', num2str(current_bins(pindex)), 'gui_display_data_type', gddtype, ...\n 'n_bits', num2str(current_widths(pindex)), ...\n 'Position', [x_start + (x_size * 1 * 1), y_pos_row, x_start + (x_size * 1 * 1) + (x_size/2), y_pos_row + y_size]);\n reuse_block(blk, reinterpret_name, 'xbsIndex_r4/Reinterpret', ...\n 'Position', [x_start + (x_size * 1 * 2), y_pos_row, x_start + (x_size * 1 * 2) + (x_size/2), y_pos_row + y_size], ...\n 'force_arith_type', 'on', 'arith_type', 'Unsigned', ...\n 'force_bin_pt', 'on', 'bin_pt', '0');\n add_line(blk, [in_name, '/1'], [assert_name, '/1'], 'autorouting', 'on');\n add_line(blk, [assert_name, '/1'], [reinterpret_name, '/1'], 'autorouting', 'on');\n if numios > 1,\n add_line(blk, [reinterpret_name, '/1'], ['concatenate/', num2str(pindex)], 'autorouting', 'on');\n else\n add_line(blk, [reinterpret_name, '/1'], 'io_delay/1', 'autorouting', 'on');\n end\n y_pos_row = y_pos_row + (y_size * 2);\n end\nend\n\nfunction draw_from()\n y_pos_row = y_pos;\n gwin_name = [strrep(blk, '/', '_'), '_user_data_out'];\n reuse_block(blk, gwin_name, 'xbsIndex_r4/Gateway In', ...\n 'Position', [x_start + (x_size * 4 * 2), y_pos_row, x_start + (x_size * 4 * 2) + (x_size/2), y_pos_row + y_size], ...\n 'arith_type', 'Unsigned', 'n_bits', '32', 'bin_pt', '0', 'period', get_param(blk, 'sample_period'));\n reuse_block(blk, 'io_delay', 'xbsIndex_r4/Delay', 'latency', get_param(blk, 'io_delay'), 'reg_retiming', 'on', ...\n 'Position', [x_start + (x_size * 4.5 * 2), y_pos_row, x_start + (x_size * 4.5 * 2) + (x_size/2), y_pos_row + y_size]);\n add_line(blk, [gwin_name, '/1'], 'io_delay/1', 'autorouting', 'on');\n if numios > 1,\n addstr = '';\n for pindex = 1 : numios,\n addstr = [addstr, '+'];\n end\n reuse_block(blk, 'sim_add', 'simulink/Math Operations/Add', 'Inputs', addstr, 'OutDataTypeStr', 'uint32', ...\n 'Position', [x_start + (x_size * 3 * 2), y_pos_row, x_start + (x_size * 3 * 2) + (x_size/2), y_pos_row + (y_size * numios)]);\n clear addstr;\n add_line(blk, 'sim_add/1', [gwin_name, '/1'], 'autorouting', 'on');\n end\n % ports\n total_width = sum(current_widths);\n for pindex = 1 : numios,\n io_arith_type = current_types(pindex);\n if io_arith_type == 2,\n sliceboolean = 'on';\n else\n sliceboolean = 'off';\n end\n if strcmp(io_arith_type, 'Signed (2''s comp)'),\n shorttype = 'sfix';\n else\n shorttype = 'ufix';\n end\n io_bin_pt = current_bins(pindex);\n io_bitwidth = current_widths(pindex);\n total_width = total_width - io_bitwidth;\n in_name = sprintf('sim_%i', pindex);\n convert_name1 = ['convert1_', num2str(pindex)];\n convert_name2 = ['convert2_', num2str(pindex)];\n gain_name = ['gain_', num2str(pindex)];\n out_name = sprintf('in_%s', current_names{pindex});\n slice_name = sprintf('slice_%s', current_names{pindex});\n reinterpret_name = sprintf('reint%i', pindex);\n if simport,\n reuse_block(blk, in_name, 'built-in/inport', 'Port', num2str(pindex), ...\n 'Position', [x_start, y_pos_row, x_start + (x_size/2), y_pos_row + y_size]);\n else\n reuse_block(blk, in_name, 'built-in/constant', 'Value', '0', ...\n 'Position', [x_start, y_pos_row, x_start + (x_size/2), y_pos_row + y_size]);\n end\n reuse_block(blk, convert_name1, 'simulink/Commonly Used Blocks/Data Type Conversion', 'OutDataTypeStr', sprintf('fixdt(''%s%i_En%i'')', shorttype, io_bitwidth, io_bin_pt), ...\n 'LockScale', 'on', 'ConvertRealWorld', 'Real World Value (RWV)', ...\n 'Position', [x_start + (x_size * 1 * 2), y_pos_row, x_start + (x_size * 1 * 2) + (x_size/2), y_pos_row + y_size]);\n reuse_block(blk, convert_name2, 'simulink/Commonly Used Blocks/Data Type Conversion', 'OutDataTypeStr', sprintf('fixdt(''ufix%i_En0'')', io_bitwidth), ...\n 'LockScale', 'on', 'ConvertRealWorld', 'Stored Integer (SI)', ...\n 'Position', [x_start + (x_size * 1.5 * 2), y_pos_row, x_start + (x_size * 1.5 * 2) + (x_size/2), y_pos_row + y_size]);\n reuse_block(blk, gain_name, 'simulink/Commonly Used Blocks/Gain', 'Gain', num2str(pow2(total_width)), ...\n 'Position', [x_start + (x_size * 2 * 2), y_pos_row, x_start + (x_size * 2 * 2) + (x_size/2), y_pos_row + y_size]);\n if numios > 1,\n add_line(blk, [in_name, '/1'], [convert_name1, '/1'], 'autorouting', 'on');\n add_line(blk, [convert_name1, '/1'], [convert_name2, '/1'], 'autorouting', 'on');\n add_line(blk, [convert_name2, '/1'], [gain_name, '/1'], 'autorouting', 'on');\n add_line(blk, [gain_name, '/1'], ['sim_add/', num2str(pindex)], 'autorouting', 'on');\n else\n add_line(blk, [in_name, '/1'], [gwin_name, '/1'], 'autorouting', 'on');\n end\n reuse_block(blk, slice_name, 'xbsIndex_r4/Slice', ...\n 'Position', [x_start + (x_size * 5 * 2), y_pos_row, x_start + (x_size * 5 * 2) + (x_size/2), y_pos_row + y_size], ...\n 'nbits', num2str(io_bitwidth), 'boolean_output', sliceboolean, 'mode', 'Lower Bit Location + Width', 'bit0', num2str(total_width));\n if strcmp(sliceboolean, 'off'),\n reuse_block(blk, reinterpret_name, 'xbsIndex_r4/Reinterpret', ...\n 'Position', [x_start + (x_size * 6 * 2), y_pos_row, x_start + (x_size * 6 * 2) + (x_size/2), y_pos_row + y_size], ...\n 'force_arith_type', 'on', 'arith_type', io_arith_type, ...\n 'force_bin_pt', 'on', 'bin_pt', num2str(io_bin_pt));\n end\n reuse_block(blk, out_name, 'built-in/outport', ...\n 'Port', num2str(pindex), ...\n 'Position', [x_start + (x_size * 7 * 2), y_pos_row, x_start + (x_size * 7 * 2) + (x_size/2), y_pos_row + y_size]);\n add_line(blk, 'io_delay/1', [slice_name, '/1'], 'autorouting', 'on');\n if strcmp(sliceboolean, 'off'),\n add_line(blk, [slice_name, '/1'], [reinterpret_name, '/1'], 'autorouting', 'on');\n add_line(blk, [reinterpret_name, '/1'], [out_name, '/1'], 'autorouting', 'on');\n else\n add_line(blk, [slice_name, '/1'], [out_name, '/1'], 'autorouting', 'on');\n end\n y_pos_row = y_pos_row + (y_size * 2);\n end\nend\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "tengbe_v2_callback.m", "ext": ".m", "path": "mlib_devel-master/xps_library/tengbe_v2_callback.m", "size": 5754, "source_encoding": "utf_8", "md5": "ac8490c901ed851d2d3a602a4f412241", "text": "% ten_gbe_v2_callback\n% \n% mask callback function\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Meerkat radio telescope project %\n% www.kat.ac.za %\n% Copyright (C) Andrew Martens 2011 %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction tengbe_v2_callback()\n\nclog('entering ten_gbe_v2_callback', 'trace');\n\nblk = gcb;\n\ncheck_mask_type(blk, 'ten_GbE_v2');\n\n%search for sysgen block and get target\nxps_xsg_blks = find_system(bdroot,'SearchDepth',1,'FollowLinks','on','LookUnderMasks','all','Tag','xps:xsg');\nif length(xps_xsg_blks) ~= 1,\n errordlg('ten_Gbe_v2 requires a single MSSGE (XSG core config) block to be instantiated at the top level');\n return;\nend\n\n%get the target board for the design\nhw_sys = get_param(xps_xsg_blks(1),'hw_sys');\nflavour = get_param(blk,'flavour');\nshow_param = get_param(blk, 'show_param');\nmask_names = get_param(blk, 'MaskNames');\nmask_visibilities = get_param(blk, 'MaskVisibilities');\n\n%turn everything off by default\n\nfor p = 1:length(mask_visibilities), \n mask_visibilities{p} = 'off';\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%\n%these are visible always\n%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nmask_visibilities{ismember(mask_names, 'rx_dist_ram')} = 'on';\nmask_visibilities{ismember(mask_names, 'large_frames')} = 'on';\nmask_visibilities{ismember(mask_names, 'show_param')} = 'on';\n\n% debug counter checkboxes\nmask_visibilities{ismember(mask_names, 'debug_ctr_width')} = 'on';\nmask_visibilities{ismember(mask_names, 'txctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'txerrctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'txofctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'txfullctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'txvldctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'txsnaplen')} = 'on';\nmask_visibilities{ismember(mask_names, 'rxctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'rxerrctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'rxofctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'rxbadctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'rxvldctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'rxeofctr')} = 'on';\nmask_visibilities{ismember(mask_names, 'rxsnaplen')} = 'on';\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%these are visible always depending on architecture\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif strcmp(hw_sys,'ROACH2:sx475t'),\n mask_visibilities{ismember(mask_names, 'flavour')} = 'on';\n mask_visibilities{ismember(mask_names, 'slot')} = 'on';\n\n if strcmp(flavour,'cx4'), %CX4 mezzanine card for ROACH2 has only 3 (external) ports\n mask_visibilities{ismember(mask_names, 'port_r2_cx4')} = 'on';\n elseif strcmp(flavour, 'sfp+'), %SFP+ mezzanine card 4 external ports \n mask_visibilities{ismember(mask_names, 'port_r2_sfpp')} = 'on';\n end\nelse\n mask_visibilities{ismember(mask_names, 'port_r1')} = 'on';\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%these are visible if low level parameters enabled\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif strcmp(show_param, 'on'),\n %these are visible regardless of target hardware\n mask_visibilities{ismember(mask_names, 'fab_en')} = 'on';\n mask_visibilities{ismember(mask_names, 'fab_mac')} = 'on';\n mask_visibilities{ismember(mask_names, 'fab_ip')} = 'on';\n mask_visibilities{ismember(mask_names, 'fab_udp')} = 'on';\n mask_visibilities{ismember(mask_names, 'fab_gate')} = 'on';\n mask_visibilities{ismember(mask_names, 'cpu_rx_en')} = 'on';\n mask_visibilities{ismember(mask_names, 'cpu_tx_en')} = 'on';\n \n if strcmp(hw_sys,'ROACH2:sx475t'),\n mask_visibilities{ismember(mask_names, 'pre_emph_r2')} = 'on';\n mask_visibilities{ismember(mask_names, 'swing_r2')} = 'on';\n mask_visibilities{ismember(mask_names, 'post_emph_r2')} = 'on';\n mask_visibilities{ismember(mask_names, 'rxeqmix_r2')} = 'on';\n mask_visibilities{ismember(mask_names, 'ttl')} = 'on';\n mask_visibilities{ismember(mask_names, 'promisc_mode')} = 'on';\n else\n mask_visibilities{ismember(mask_names, 'pre_emph')} = 'on';\n mask_visibilities{ismember(mask_names, 'swing')} = 'on';\n end\nend\n\n% enable and make visible relevant parameters\nset_param(blk, 'MaskVisibilities', mask_visibilities);\n\nclog('exiting ten_gbe_v2_callback', 'trace');\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "add_port.m", "ext": ".m", "path": "mlib_devel-master/xps_library/add_port.m", "size": 1980, "source_encoding": "utf_8", "md5": "e81ce344a2b90471d7aff121955a3963", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction old_ports = add_port(sys,old_ports,type,port_name, position)\r\nif ~isfield(old_ports,port_name)\r\n add_block(['built-in/',type],[sys,'/',port_name],'Position', position);\r\nelse\r\n set_param([sys,'/',port_name],'Position', position);\r\n old_ports = setfield(old_ports,port_name,1);\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "dram_mask.m", "ext": ".m", "path": "mlib_devel-master/xps_library/dram_mask.m", "size": 6948, "source_encoding": "utf_8", "md5": "b93345b0b39bb21748b534157c647061", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction dram_mask(myname, wide_data)\n\nset_param([myname,'/convert_data_in'], 'arith_type', get_param(myname,'arith_type'));\nset_param([myname,'/convert_data_in'], 'bin_pt', num2str(get_param(myname,'bin_pt')));\nset_param([myname,'/force_rd_dout'], 'arith_type', get_param(myname,'arith_type'));\nset_param([myname,'/force_rd_dout'], 'bin_pt', num2str(get_param(myname,'bin_pt')));\n\n%get hardware platform from XSG block\ntry\n xsg_blk = find_system(bdroot, 'SearchDepth', 1,'FollowLinks','on','LookUnderMasks','all','Tag','xps:xsg');\n hw_sys = xps_get_hw_plat(get_param(xsg_blk{1},'hw_sys'));\ncatch\n warndlg('Count not find hardware platform for DRAM configuration - is there an XSG block in this model? Defaulting platform to ROACH.');\n warning('Count not find hardware platform for DRAM configuration - is there an XSG block in this model? Defaulting platform to ROACH.');\n hw_sys = 'ROACH';\nend %try/catch\n\n%TODO --> Add code to check whether the DRAM clock period (in ps) is an integer value, if this is not the case choose the next closest value\n\nswitch hw_sys\n case 'ROACH'\n\tif strcmp(get_param(myname, 'wide_data'), 'on')\n \tset_param([myname,'/convert_data_in'],'n_bits', '288');\n \tset_param([myname,'/convert_wr_be'], 'n_bits', '36');\n\telse\n \tset_param([myname,'/convert_data_in'],'n_bits', '144');\n \tset_param([myname,'/convert_wr_be'], 'n_bits', '18');\n \tend\t\n case 'ROACH2'\n\tset_param([myname,'/convert_data_in'],'n_bits', '288');\n \tset_param([myname,'/convert_wr_be'], 'n_bits', '36');\n \t%Change the bit widths of the DRAM simulation model for the ROACH-2\n\tset_param([myname,'/dram_sim/cast_narrow'], 'n_bits', '288');\n\tset_param([myname,'/dram_sim/cast_narrow1'], 'n_bits', '36');\n \tset_param([myname,'/dram_sim/msbs'], 'nbits', '288');\n \tset_param([myname,'/dram_sim/msbs'], 'bit0', '288');\n\tset_param([myname,'/dram_sim/lsbs'], 'nbits', '288');\n \tset_param([myname,'/dram_sim/memory/cast_narrow2'], 'n_bits', '576');\n \tset_param([myname,'/dram_sim/memory/cast_narrow3'], 'n_bits', '576');\nend\n\ngateway_outs = find_system(myname,'searchdepth',1,'FollowLinks', 'on','lookundermasks','all','masktype','Xilinx Gateway Out Block');\nfor i =1:length(gateway_outs)\n gw = gateway_outs{i};\n if regexp(get_param(gw,'Name'),'(Mem_Rst)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Rst)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(Mem_Cmd_Address)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Cmd_Address)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(Mem_Wr_Din)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Wr_Din)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(Mem_Wr_BE)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Wr_BE)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(Mem_Cmd_RNW)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Cmd_RNW)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(Mem_Cmd_Tag)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Cmd_Tag)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(Mem_Cmd_Valid)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Cmd_Valid)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(Mem_Rd_Ack)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Rd_Ack)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n else\n error(['Unknown gateway name: ',gw]);\n end\nend\n\ngateway_ins = find_system(myname,'searchdepth',1,'FollowLinks', 'on','lookundermasks','all','masktype','Xilinx Gateway In Block');\nfor i =1:length(gateway_ins)\n gw = gateway_ins{i};\n if regexp(get_param(gw,'Name'),'(Mem_Cmd_Ack)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Cmd_Ack)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(Mem_Rd_Dout)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Rd_Dout)$','tokens');\n if strcmp(get_param(myname,'wide_data'),'on') || strcmp(hw_sys,'ROACH2')\n set_param(gw, 'n_bits', '288');\n else\n set_param(gw, 'n_bits', '144');\n end\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(Mem_Rd_Tag)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Rd_Tag)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(Mem_Rd_Valid)$')\n toks = regexp(get_param(gw,'Name'),'(Mem_Rd_Valid)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n elseif regexp(get_param(gw,'Name'),'(phy_ready)$')\n toks = regexp(get_param(gw,'Name'),'(phy_ready)$','tokens');\n set_param(gw,'Name',clear_name([myname,'_',toks{1}{1}]));\n else\n error(['Unkown gateway name: ',gw]);\n end\nend\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "write_xps.m", "ext": ".m", "path": "mlib_devel-master/xps_library/write_xps.m", "size": 5261, "source_encoding": "utf_8", "md5": "6d57bad54e2d1e8650d4f9c83ee2186b", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction write_xps(data, core_name, serial_port)\ntry\n\n\t% open serial port\n\ts = serial(serial_port);\n\tset(s,'BaudRate',115200);\n\tset(s,'InputBufferSize' ,127);\n\tset(s,'OutputBufferSize',127);\n\tset(s,'Timeout',3);\n\tset(s,'ByteOrder','bigEndian');\n\n\tfopen(s);\n\n\n % send a request information to the iBOB\n % special opcode\n fwrite(s,uint8(129));\n % block name\n fwrite(s,uint8(core_name));\n % zero string termination\n fwrite(s,uint8(0));\n % get the result code\n request_result = fread(s, 1, 'uint8');\n % get the result string\n request_string = '';\n c = fread(s,1,'uint8');\n while c ~= 0\n request_string = [request_string,char(c)];\n c = fread(s,1,'uint8');\n end\n if request_result ~= 0\n\t\tdisp(['Error: ',request_string]);\n\t\tfclose(s);\n\t\tdelete(s);\n\t\tclear s;\n\t\treturn;\n end\n toks = regexp(request_string,'(\\w+)', 'tokens');\n type = toks{1};\n type = type{1};\n param = toks{5};\n param = param{1};\n address = toks{3};\n address = address{1};\n address = hex2dec(address(3:end));\n\n\tif strcmp(type,'xps_bram')\n\t\tsize = str2num(param);\n\n\t\tif length(data) ~= size || ~isinteger(data)\n\t\t\tdisp(['Input data is not of the right size or right type. Should be a Uint32 array of size ', num2str(size)]);\n\t\t\tfclose(s);\n\t\t\tdelete(s);\n\t\t\tclear s;\n\t return;\n\t\tend\n\n\t\ti = 1;\n\n\t\twhile size > 0\n\t\t\tif size > 31\n\t\t\t\tblock_size = 31;\n\t\t\telse\n\t\t\t\tblock_size = size;\n\t\t\tend\n\n\t\t\theader(1) = uint8(128);\n\t\t\theader(2) = uint8(128 + (block_size));\n\t\t\theader(3) = uint8(mod(floor(address/(2^24)),2^8));\n\t\t\theader(4) = uint8(mod(floor(address/(2^16)),2^8));\n\t\t\theader(5) = uint8(mod(floor(address/(2^8 )),2^8));\n\t\t\theader(6) = uint8(mod(floor(address/(2^0 )),2^8));\n\n\t\t\tfwrite(s, header);\n\t\t\tfprintf('.');\n % Inject a snooze every few packets.\n transfert_done = 0;\n while transfert_done == 0\n pause(0.01);\n try\n \t\t\tfwrite(s, data(i:(i+block_size-1)), 'uint32');\n transfert_done = 1;\n catch\n % flood the ibob with dummy values to finish the\n % previously aborted transfer\n dummy_done = 0;\n while dummy_done == 0\n pause(0.01);\n try\n fwrite(s, zeros(1,31), 'uint32');\n dummy_done = 1;\n catch\n disp('problem');\n disp(lasterr);\n end\n end\n end\n end\n\t\t\tsize = size - block_size;\n\t\t\taddress = address + (block_size * 4);\n\t\t\ti = i + block_size;\n\t\tend\n\t\tfprintf('\\n');\n\n\telseif strcmp(type,'xps_sw_reg')\n\t\tdir = param;\n\t\tif strcmp(dir,'out')\n\t\t\tdisp(['Core \"',core_name,'\" is an OUTPUT register, and cannot be written.']);\n\t\t\tfclose(s);\n\t\t\tdelete(s);\n\t\t\tclear s;\n\t\t\treturn;\n\t\tend\n\n\t\tif length(data) ~= 1 || ~isinteger(data)\n\t\t\tdisp(['Input data is not of the right size or right type. Should be a single Uint32']);\n\t\t\tfclose(s);\n\t\t\tdelete(s);\n\t\t\tclear s;\n\t\t return;\n\t\tend\n\n\t\theader(1) = uint8(128);\n\t\theader(2) = uint8(128 + 1);\n\t\theader(3) = uint8(mod(floor(address/(2^24)),2^8));\n\t\theader(4) = uint8(mod(floor(address/(2^16)),2^8));\n\t\theader(5) = uint8(mod(floor(address/(2^8 )),2^8));\n\t\theader(6) = uint8(mod(floor(address/(2^0 )),2^8));\n\n\t\tfwrite(s, header);\n\n\t\tfwrite(s, data, 'uint32');\n\tend\n\n\tfclose(s);\n\tdelete(s);\n\tclear s;\n\ncatch\n\tfclose(s);\n\tdelete(s);\n\tclear s;\n\tdisp(lasterr);\n\tout = 0;\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc_mkid/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc_mkid/drc.m", "size": 1751, "source_encoding": "utf_8", "md5": "805b22d398f2f8ef4c982d1cd1e67683", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\nresult = 0;\nmsg = '';\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc_mkid/gen_ucf.m", "size": 2924, "source_encoding": "utf_8", "md5": "89a6841bb7cfff129da7b6ae1f5e67d7", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\n\n\nstr = '';\n\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\n\nI_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_p'];\nI_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_n'];\n\nQ_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_p'];\nQ_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_n'];\n\nstr = [str, 'NET ', I_clk_p_str, ' TNM_NET = ', I_clk_p_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', I_clk_p_str, ' = PERIOD ', I_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\nstr = [str, 'NET ', I_clk_n_str, ' TNM_NET = ', I_clk_n_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', I_clk_n_str, ' = PERIOD ', I_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\nstr = [str, '\\n'];\n\nstr = [str, 'NET ', Q_clk_p_str, ' TNM_NET = ', Q_clk_p_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', Q_clk_p_str, ' = PERIOD ', Q_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\nstr = [str, 'NET ', Q_clk_n_str, ' TNM_NET = ', Q_clk_n_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', Q_clk_n_str, ' = PERIOD ', Q_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\nstr = [str, '\\n'];\n\nstr = [str, gen_ucf(blk_obj.xps_block)];\n\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc_mkid/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adc_mkid.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc_mkid/xps_adc_mkid.m", "size": 5471, "source_encoding": "utf_8", "md5": "667c046f4d1ffebc63ac4851b97ea4a6", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_adc_mkid(blk_obj)\nif ~isa(blk_obj,'xps_block')\n error('xps_quadc class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_adc_mkid')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.adc_brd = get_param(blk_name, 'adc_brd');\ns.adc_str = ['adc', s.adc_brd];\n\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.clk_sys = get(xsg_obj,'clk_src');\n \n \nb = class(s,'xps_adc_mkid',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','adc_mkid_interface');\nb = set(b,'ip_version','1.00.a');\n\nparameters.OUTPUT_CLK = '0';\nif strfind(s.clk_sys,'adc')\n parameters.OUTPUT_CLK = '1';\nend\n \nb = set(b,'parameters',parameters);\n\n\n\n\n%%%%%%%%%%%%%%%%%\n% external ports\n%%%%%%%%%%%%%%%%%\nucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(2*1000/s.adc_clk_rate),' ns']);\nucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\nucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(1e6*s.adc_clk_rate/2));\n\n\next_ports.DRDY_I_p = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_I_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[20],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.DRDY_I_n = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_I_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[20],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\n\next_ports.DRDY_Q_p = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_Q_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[40],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.DRDY_Q_n = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_Q_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[40],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\n\next_ports.DI_p = {12 'in' ['adcmkid',s.adc_brd,'_DI_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[17 37 7 27 26 36 25 35 16 15 6 5],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.DI_n = {12 'in' ['adcmkid',s.adc_brd,'_DI_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[17 37 7 27 26 36 25 35 16 15 6 5],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.DQ_p = {12 'in' ['adcmkid',s.adc_brd,'_DQ_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[13 33 3 23 22 32 21 31 12 11 2 1],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.DQ_n = {12 'in' ['adcmkid',s.adc_brd,'_DQ_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[13 33 3 23 22 32 21 31 12 11 2 1],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.ADC_ext_in_p = {1 'in' ['adcmkid',s.adc_brd,'_ADC_ext_in_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[29],:}}'] 'vector=false' struct() ucf_constraints_term};\next_ports.ADC_ext_in_n = {1 'in' ['adcmkid',s.adc_brd,'_ADC_ext_in_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[29],:}}'] 'vector=false' struct() ucf_constraints_term};\n\n\nb = set(b,'ext_ports',ext_ports);\n\n%%%%%%%%%%%%%\n% misc ports\n%%%%%%%%%%%%%\nmisc_ports.fpga_clk = {1 'in' get(xsg_obj,'clk_src')};\n\nif strfind(s.clk_sys,'adc')\n misc_ports.adc_clk_out = {1 'out' [s.adc_str,'_clk']};\n misc_ports.adc_clk90_out = {1 'out' [s.adc_str,'_clk90']};\n misc_ports.adc_clk180_out = {1 'out' [s.adc_str,'_clk180']};\n misc_ports.adc_clk270_out = {1 'out' [s.adc_str,'_clk270']};\nend\n\nmisc_ports.adc_dcm_locked = {1 'out' [s.adc_str, '_dcm_locked']};\n\nb = set(b,'misc_ports',misc_ports);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac_mkid_4x/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac_mkid_4x/drc.m", "size": 2992, "source_encoding": "utf_8", "md5": "3ab77bfce809915097a39d56418ecd9a", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'hw_dac'), get(xps_objs{i},'hw_dac'))\r\n\t\t\tif ~strcmp(get(blk_obj, 'simulink_name'), get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['DAC ', get(blk_obj, 'simulink_name'),' and DAC ', get(xps_objs{i}, 'simulink_name'), ' are using the same connector.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\n\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'type'),'xps_dac') && strcmp(get(xps_objs{i},'type'), 'xps_adc')\r\n\t\t if (strcmp(get(blk_obj,'hw_dac'),'dac0') && strcmp(get(xps_objs{i},'hw_adc'),'adc0')) || (strcmp(get(blk_obj,'hw_dac'),'dac1') && strcmp(get(xps_objs{i},'hw_adc'),'adc1'))\r\n\t\t msg = ['DAC ', get(blk_obj,'simulink_name'), ' and ADC ', get(xps_objs{i},'simulink_name'),' are located on the same Z-DOK connector.'];\r\n\t\t result = 1;\r\n\t\t end\r\n\t\tend\r\n end\r\n\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'type'),'xps_dac') && strcmp(get(xps_objs{i},'type'), 'xps_vsi')\r\n\t\t if strcmp(get(blk_obj,'hw_dac'),'dac1') && strcmp(get(xps_objs{i},'hw_vsi'),'ZDOK 1')\r\n\t\t msg = ['DAC ', get(blk_obj,'simulink_name'), ' and VSI ', get(xps_objs{i},'simulink_name'),' are located on the same Z-DOK connector.'];\r\n\t\t result = 1;\r\n\t\t end\r\n\t\tend\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac_mkid_4x/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_dac_mkid_4x.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac_mkid_4x/xps_dac_mkid_4x.m", "size": 8196, "source_encoding": "utf_8", "md5": "1044bffb3420afff6aadb14ea45d1f8f", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = xps_dac_mkid_4x(blk_obj)\r\nif ~isa(blk_obj,'xps_block')\r\n error('XPS_DAC_MKID class requires a xps_block class object');\r\nend\r\nif ~strcmp(get(blk_obj,'type'),'xps_dac_mkid_4x')\r\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\r\nend\r\n\r\n\r\nblk_name = get(blk_obj,'simulink_name');\r\nxsg_obj = get(blk_obj,'xsg_obj');\r\n\r\n % s.hw_dac = 'dac0' or 'dac1' as specified by the user in the yellow\r\n % block.\r\ns.hw_sys = get(xsg_obj,'hw_sys');\r\ns.dac_brd = get_param(blk_name, 'dac_brd');\r\ns.dac_str = ['dac', s.dac_brd];\r\n\r\n % The clock coming from the zdok to the fpga is reduced by a physical\r\n % circuit on the DAC_MKID board to half of the rate of the external \r\n % clock provided by the user. The external clock rate is provided by\r\n % the user (in MHz) on the dac_mkid yellow block. The clock period \r\n % will be used in units of 1/GHz.\r\ns.dac_clk_rate = eval_param(blk_name,'dac_clk_rate')/2;\r\ndac_clk_period = 1000/s.dac_clk_rate;\r\n\r\n% get name fpga clock source\r\ns.clk_sys = get(xsg_obj,'clk_src');\r\n\r\n\r\n\r\n\r\nb = class(s,'xps_dac_mkid_4x',blk_obj);\r\nb = set(b,'ip_name','dac_mkid_4x_interface');\r\nb = set(b, 'ip_version', '1.01.a');\r\n\r\nparameters.OUTPUT_CLK = '0';\r\nif strfind(s.clk_sys,'dac')\r\n parameters.OUTPUT_CLK = '1';\r\nend\r\nb = set(b,'parameters',parameters);\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% external ports\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n % Collection of parameters used to define ports.\r\nucf_constraints_clk = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(dac_clk_period),' ns']);\r\nucf_constraints = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\r\nmhs_constraints_clk = struct('SIGIS','CLK', 'CLK_FREQ',num2str(1e6*s.dac_clk_rate));\r\n\r\n\r\n % The system clock for the FPGA fabric is generated from the CLK_to_FPGA \r\n % pins on the zdok from the MKID DAC. Reminder: s.dac_str = dac0 or\r\n % dac1.\r\n \r\next_ports.dac_clk_p = {1 'in' [s.dac_str,'_clk_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[40],:}}'] 'vector=false' mhs_constraints_clk ucf_constraints_clk};\r\next_ports.dac_clk_n = {1 'in' [s.dac_str,'_clk_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[40],:}}'] 'vector=false' mhs_constraints_clk ucf_constraints_clk};\r\n\r\n % DCLK is used to clock out data to the DAC.\r\next_ports.dac_smpl_clk_i_p = {1 'out' [s.dac_str,'_smpl_clk_i_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[30],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_smpl_clk_i_n = {1 'out' [s.dac_str,'_smpl_clk_i_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[30],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_smpl_clk_q_p = {1 'out' [s.dac_str,'_smpl_clk_q_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[29],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_smpl_clk_q_n = {1 'out' [s.dac_str,'_smpl_clk_q_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[29],:}}'] 'vector=false' struct() ucf_constraints};\r\n\r\n % I and Q output.\r\next_ports.dac_data_i_p = {16 'out' [s.dac_str,'_data_i_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[26 15 35 5 25 16 36 6 37 17 27 7 18 38 8 28],:}}'] 'vector=true' struct() ucf_constraints};\r\next_ports.dac_data_i_n = {16 'out' [s.dac_str,'_data_i_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[26 15 35 5 25 16 36 6 37 17 27 7 18 38 8 28],:}}'] 'vector=true' struct() ucf_constraints};\r\next_ports.dac_data_q_p = {16 'out' [s.dac_str,'_data_q_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[22 11 31 1 21 12 32 2 33 13 23 3 14 34 4 24],:}}'] 'vector=true' struct() ucf_constraints};\r\next_ports.dac_data_q_n = {16 'out' [s.dac_str,'_data_q_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[22 11 31 1 21 12 32 2 33 13 23 3 14 34 4 24],:}}'] 'vector=true' struct() ucf_constraints};\r\n\r\n % When dac_sync is high, dac output is enabled.\r\next_ports.dac_sync_i_p = {1 'out' [s.dac_str,'_sync_i_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[39],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_sync_i_n = {1 'out' [s.dac_str,'_sync_i_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[39],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_sync_q_p = {1 'out' [s.dac_str,'_sync_q_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[20],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_sync_q_n = {1 'out' [s.dac_str,'_sync_q_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[20],:}}'] 'vector=false' struct() ucf_constraints};\r\n \r\n \r\n% Serial data enabled on low, which is why it's controlled by a not\r\n % sdenb.\r\next_ports.dac_not_sdenb_i = {1 'out' [s.dac_str,'_not_sdenb_i'] ['{',s.hw_sys,'.zdok',s.dac_brd,'{[18],:}}'] 'vector=false' struct() struct()};\r\next_ports.dac_not_sdenb_q = {1 'out' [s.dac_str,'_not_sdenb_q'] ['{',s.hw_sys,'.zdok',s.dac_brd,'{[19],:}}'] 'vector=false' struct() struct()};\r\n\r\n % SCLK is the clock used to write data to the DAC for configuration.\r\next_ports.dac_sclk = {1 'out' [s.dac_str,'_sclk'] ['{',s.hw_sys,'.zdok',s.dac_brd,'{[17],:}}'] 'vector=false' struct() struct()};\r\n\r\n % Each dac chip is wired for 4-wire interface, with only the input\r\n % available on the zdok.\r\next_ports.dac_sdi = {1 'out' [s.dac_str,'_sdi'] ['{',s.hw_sys,'.zdok',s.dac_brd,'{[37],:}}'] 'vector=false' struct() struct()};\r\n\r\n % Resets the dac when low.\r\next_ports.dac_not_reset = {1 'out' [s.dac_str,'_not_reset'] ['{',s.hw_sys,'.zdok',s.dac_brd,'{[38],:}}'] 'vector=false' struct() struct()};\r\n\r\n % This is mapped to a circuit on the board, and not on the chips\r\n % themselves. If dac_phase is low, both dac chips are in phase.\r\n%ext_ports.dac_phase = {1 'in' [s.dac_str,'_pase'] '{ROACH.zdok0{[20],:}}' 'vector=false' struct() struct()};\r\n\r\n\r\n\r\nb = set(b, 'ext_ports', ext_ports);\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% misc ports\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n \r\nmisc_ports.dac_dcm_locked = {1 'out' [s.dac_str, '_dcm_locked']};\r\n \r\nif strfind(s.clk_sys,'dac')\r\n misc_ports.dac_clk_out = {1 'out' [s.dac_str,'_clk']};\r\n misc_ports.dac_clk90_out = {1 'out' [s.dac_str,'_clk90']};\r\n misc_ports.dac_clk180_out = {1 'out' [s.dac_str,'_clk180']};\r\n misc_ports.dac_clk270_out = {1 'out' [s.dac_str,'_clk270']};\r\nelse\r\n misc_ports.fpga_clk = {1 'in' get(xsg_obj,'clk_src')};\r\nend\r\n\r\nb = set(b,'misc_ports',misc_ports);\r\n\r\n\r\n\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc5g/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc5g/drc.m", "size": 2120, "source_encoding": "utf_8", "md5": "82e2ccc1d1128259537cf26f2bbaa9e0", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'hw_adc'),get(xps_objs{i},'hw_adc'))\r\n\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['ADC ',get(blk_obj,'simulink_name'),' and ADC ',get(xps_objs{i},'simulink_name'),' are located on the same port.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc5g/gen_ucf.m", "size": 6578, "source_encoding": "utf_8", "md5": "7815d35e50045bf09ca4a1b823a6931a", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\n\nhw_sys = blk_obj.hw_sys;\nblk_name = get(blk_obj,'simulink_name');\n\n% Get some parameters we're intereset in\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\nadc_per = 1e6/(blk_obj.adc_clk_rate);\nstr = gen_ucf(blk_obj.xps_block);\nadc_str = blk_obj.adc_str;\ndemux = blk_obj.demux;\n\n% Load the routes file\nload_hw_routes();\n\n% Set the ADC clock setup/hold constraints\n%str = [str, 'NET \"', adc_str, 'clk_p\" TNM_NET = \"', adc_str, '_clk\";\\n'];\n%str = [str, 'TIMESPEC \"TS_', adc_str, '_clk\" = PERIOD \"', ...\n% adc_str, '_clk\" ', num2str(adc_per), ' ps HIGH 50%%;\\n'];\n%str = [str, 'OFFSET = IN 400 ps VALID ', num2str(adc_per/2), ...\n% ' ps BEFORE \"', adc_str, 'clk_p\" RISING;\\n'];\n%str = [str, 'OFFSET = IN 400 ps VALID ', num2str(adc_per/2), ...\n% ' ps BEFORE \"', adc_str, 'clk_p\" FALLING;\\n'];\n\nswitch hw_sys\n case 'ROACH'\n % pass\n case 'ROACH2'\n if blk_obj.use_adc0\n % Manually place the BUFR components\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/DIVBUF\" LOC = BUFR_X1Y11 ;\\n'];\n\t if exist('routes_vers')\n\t switch demux\n\t % Create an area group to place the FD close to the IOPAD\n\t\t% which for some reason was traced to the other side of the\n\t % chip on ROACH2\n case '1:2'\n\t\t str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/fifo_din_33\" AREA_GROUP = IDDR_1 ;\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/fifo_din_41\" AREA_GROUP = IDDR_1 ;\\n'];\n str = [str, 'AREA_GROUP \"IDDR_1\" RANGE = ', ...\n 'SLICE_X0Y279:SLICE_X23Y321 ;\\n'];\n case '1:1'\n\t\t % First the trouble-some bunch...\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[1].D1?_1\" AREA_GROUP = ZDOK_0_1_1 ;\\n'];\n str = [str, 'AREA_GROUP \"ZDOK_0_1_1\" RANGE = ', ...\n 'SLICE_X0Y300:SLICE_X27Y320 ;\\n'];\n\t\t % And then the rest...\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[0].D*_1\" AREA_GROUP = ZDOK_0_REST ;\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[1].D0?_1\" AREA_GROUP = ZDOK_0_REST ;\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[1].D2?_1\" AREA_GROUP = ZDOK_0_REST ;\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[1].D3?_1\" AREA_GROUP = ZDOK_0_REST ;\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[2].D*_1\" AREA_GROUP = ZDOK_0_REST ;\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[3].D*_1\" AREA_GROUP = ZDOK_0_REST ;\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[4].D*_1\" AREA_GROUP = ZDOK_0_REST ;\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[5].D*_1\" AREA_GROUP = ZDOK_0_REST ;\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[6].D*_1\" AREA_GROUP = ZDOK_0_REST ;\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[7].D*_1\" AREA_GROUP = ZDOK_0_REST ;\\n'];\n str = [str, 'AREA_GROUP \"ZDOK_0_REST\" RANGE = ', ...\n\t\t\t 'SLICE_X76Y220:SLICE_X87Y259 ;\\n'];\n otherwise\n % pass\n end\n\t else\n\t str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n\t\t '/data_buf[?].D??_1\" AREA_GROUP = ZDOK_0_ALL ;\\n'];\n\t str = [str, 'AREA_GROUP \"ZDOK_0_ALL\" RANGE = ', ...\n\t\t 'SLICE_X76Y220:SLICE_X87Y259 ;\\n'];\n\t end\n\telseif blk_obj.use_adc1\n % Manually place the BUFR components\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/DIVBUF\" LOC = BUFR_X1Y9 ;\\n'];\n\n\t % This is for ZDOK1, we need to place the first buffers\n\t % close to the I/O pads to help timing\n\t str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/data_buf[?].D??_1\" AREA_GROUP = ZDOK_1_ALL ;\\n'];\n\t str = [str, 'AREA_GROUP \"ZDOK_1_ALL\" RANGE = ', ...\n 'SLICE_X0Y270:SLICE_X11Y309 ;\\n'];\t\n end\n otherwise \n % pass\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc5g/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc083000x2/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc083000x2/drc.m", "size": 2118, "source_encoding": "utf_8", "md5": "60145324772f7335c69b7970ae3e68e3", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'hw_adc'),get(xps_objs{i},'hw_adc'))\r\n\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['ADC ',get(blk_obj,'simulink_name'),' and ADC ',get(xps_objs{i},'simulink_name'),' are located on the same port.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc083000x2/gen_ucf.m", "size": 25126, "source_encoding": "utf_8", "md5": "655f8863445950ebfad48f56d7f1e373", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\ndisp('adc086000 gen_ucf')\n\nhw_sys = blk_obj.hw_sys;\nadc_str = blk_obj.adc_str;\ndisp('adc086000 trying generic ucf generation')\nstr = gen_ucf(blk_obj.xps_block);\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\ndisp('adc08600 trying specific ucf generation')\nswitch hw_sys\n case 'ROACH'\n switch adc_str\n case 'adc0'\n %\t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 1ns;\\n'];\n % end case 'adc0'\n case 'adc1'\n %\t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 1ns;\\n'];\n % end case 'adc1'\n end % switch adc_str\n\n case 'iBOB'\n switch adc_str\n case 'adc0'\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" PERIOD = ',num2str(1000/blk_obj.adc_clk_rate*4),'ns;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" MAXDELAY = 452ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_dcm\" MAXDELAY = 853ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk90_dcm\" MAXDELAY = 853ps;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK_CLKBUF\" LOC = BUFGMUX1P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK90_CLKBUF\" LOC = BUFGMUX3P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" LOC = DCM_X2Y1;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" CLKOUT_PHASE_SHIFT = VARIABLE;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 323ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" ROUTE = \"{3;1;2vp50ff1152;46c47c12!-1;156520;5632;S!0;-159;0!1;-1884;-1248!1;-1884;744!2;-1548;992!2;-1548;304!3;-1548;-656!3;-1548;-1344!4;327;0;L!5;167;0;L!6;327;0;L!7;167;0;L!}\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_3\" LOC = SLICE_X139Y91;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_2\" LOC = SLICE_X138Y91;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_1\" LOC = SLICE_X139Y90;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_0\" LOC = SLICE_X138Y90;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_0\" LOC = \"SLICE_X138Y128\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_1\" LOC = \"SLICE_X138Y126\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_2\" LOC = \"SLICE_X139Y122\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_3\" LOC = \"SLICE_X138Y120\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_4\" LOC = \"SLICE_X138Y102\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_5\" LOC = \"SLICE_X139Y98\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_6\" LOC = \"SLICE_X138Y96\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_7\" LOC = \"SLICE_X138Y94\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_8\" LOC = \"SLICE_X139Y126\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_9\" LOC = \"SLICE_X138Y124\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_10\" LOC = \"SLICE_X138Y122\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_11\" LOC = \"SLICE_X139Y118\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_12\" LOC = \"SLICE_X138Y100\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_13\" LOC = \"SLICE_X138Y98\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_14\" LOC = \"SLICE_X139Y94\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_15\" LOC = \"SLICE_X138Y92\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_16\" LOC = \"SLICE_X138Y128\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_17\" LOC = \"SLICE_X138Y126\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_18\" LOC = \"SLICE_X139Y122\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_19\" LOC = \"SLICE_X138Y120\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_20\" LOC = \"SLICE_X138Y102\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_21\" LOC = \"SLICE_X139Y98\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_22\" LOC = \"SLICE_X138Y96\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_23\" LOC = \"SLICE_X138Y94\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_24\" LOC = \"SLICE_X139Y126\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_25\" LOC = \"SLICE_X138Y124\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_26\" LOC = \"SLICE_X138Y122\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_27\" LOC = \"SLICE_X139Y118\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_28\" LOC = \"SLICE_X138Y100\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_29\" LOC = \"SLICE_X138Y98\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_30\" LOC = \"SLICE_X139Y94\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_31\" LOC = \"SLICE_X138Y92\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_0\" LOC = \"SLICE_X138Y132\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_1\" LOC = \"SLICE_X139Y134\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_2\" LOC = \"SLICE_X138Y170\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_3\" LOC = \"SLICE_X138Y172\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_4\" LOC = \"SLICE_X139Y106\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_5\" LOC = \"SLICE_X138Y110\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_6\" LOC = \"SLICE_X138Y112\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_7\" LOC = \"SLICE_X139Y114\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_8\" LOC = \"SLICE_X138Y134\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_9\" LOC = \"SLICE_X138Y168\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_10\" LOC = \"SLICE_X139Y170\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_11\" LOC = \"SLICE_X138Y174\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_12\" LOC = \"SLICE_X138Y108\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_13\" LOC = \"SLICE_X139Y110\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_14\" LOC = \"SLICE_X138Y114\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_15\" LOC = \"SLICE_X138Y116\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_16\" LOC = \"SLICE_X138Y132\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_17\" LOC = \"SLICE_X139Y134\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_18\" LOC = \"SLICE_X138Y170\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_19\" LOC = \"SLICE_X138Y172\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_20\" LOC = \"SLICE_X139Y106\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_21\" LOC = \"SLICE_X138Y110\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_22\" LOC = \"SLICE_X138Y112\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_23\" LOC = \"SLICE_X139Y114\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_24\" LOC = \"SLICE_X138Y134\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_25\" LOC = \"SLICE_X138Y168\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_26\" LOC = \"SLICE_X139Y170\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_27\" LOC = \"SLICE_X138Y174\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_28\" LOC = \"SLICE_X138Y108\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_29\" LOC = \"SLICE_X139Y110\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_30\" LOC = \"SLICE_X138Y114\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_31\" LOC = \"SLICE_X138Y116\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_0\" LOC = \"SLICE_X138Y118\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_1\" LOC = \"SLICE_X138Y118\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_0\" LOC = \"SLICE_X138Y104\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_1\" LOC = \"SLICE_X138Y104\" | BEL = \"FFY\";\\n'];\n % end case 'adc0'\n\n case 'adc1'\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" PERIOD = ',num2str(1000/blk_obj.adc_clk_rate*4),'ns;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" MAXDELAY = 452ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_dcm\" MAXDELAY = 854ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk90_dcm\" MAXDELAY = 854ps;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK_CLKBUF\" LOC = BUFGMUX0P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK90_CLKBUF\" LOC = BUFGMUX2P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" LOC = DCM_X2Y0;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" CLKOUT_PHASE_SHIFT = VARIABLE;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 323ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" ROUTE = \"{3;1;2vp50ff1152;6b4b9e45!-1;156520;-144648;S!0;-159;0!1;-1884;-1248!1;-1884;744!2;-1548;992!2;-1548;304!3;-1548;-656!3;-1548;-1344!4;327;0;L!5;167;0;L!6;327;0;L!7;167;0;L!}\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_3\" LOC = SLICE_X139Y3;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_2\" LOC = SLICE_X138Y3;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_1\" LOC = SLICE_X139Y2;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_0\" LOC = SLICE_X138Y2;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_0\" LOC = \"SLICE_X139Y70\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_1\" LOC = \"SLICE_X138Y68\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_2\" LOC = \"SLICE_X139Y64\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_3\" LOC = \"SLICE_X139Y62\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_4\" LOC = \"SLICE_X139Y44\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_5\" LOC = \"SLICE_X139Y42\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_6\" LOC = \"SLICE_X138Y40\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_7\" LOC = \"SLICE_X139Y4\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_8\" LOC = \"SLICE_X139Y68\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_9\" LOC = \"SLICE_X139Y66\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_10\" LOC = \"SLICE_X138Y64\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_11\" LOC = \"SLICE_X139Y60\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_12\" LOC = \"SLICE_X138Y44\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_13\" LOC = \"SLICE_X139Y40\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_14\" LOC = \"SLICE_X139Y6\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_15\" LOC = \"SLICE_X138Y4\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_16\" LOC = \"SLICE_X139Y70\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_17\" LOC = \"SLICE_X138Y68\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_18\" LOC = \"SLICE_X139Y64\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_19\" LOC = \"SLICE_X139Y62\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_20\" LOC = \"SLICE_X139Y44\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_21\" LOC = \"SLICE_X139Y42\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_22\" LOC = \"SLICE_X138Y40\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_23\" LOC = \"SLICE_X139Y4\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_24\" LOC = \"SLICE_X139Y68\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_25\" LOC = \"SLICE_X139Y66\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_26\" LOC = \"SLICE_X138Y64\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_27\" LOC = \"SLICE_X139Y60\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_28\" LOC = \"SLICE_X138Y44\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_29\" LOC = \"SLICE_X139Y40\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_30\" LOC = \"SLICE_X139Y6\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_31\" LOC = \"SLICE_X138Y4\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_0\" LOC = \"SLICE_X139Y74\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_1\" LOC = \"SLICE_X139Y78\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_2\" LOC = \"SLICE_X139Y80\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_3\" LOC = \"SLICE_X138Y84\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_4\" LOC = \"SLICE_X139Y48\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_5\" LOC = \"SLICE_X138Y52\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_6\" LOC = \"SLICE_X139Y54\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_7\" LOC = \"SLICE_X139Y56\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_8\" LOC = \"SLICE_X138Y76\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_9\" LOC = \"SLICE_X138Y80\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_10\" LOC = \"SLICE_X139Y82\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_11\" LOC = \"SLICE_X139Y84\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_12\" LOC = \"SLICE_X139Y50\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_13\" LOC = \"SLICE_X139Y52\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_14\" LOC = \"SLICE_X138Y56\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_15\" LOC = \"SLICE_X139Y58\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_16\" LOC = \"SLICE_X139Y74\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_17\" LOC = \"SLICE_X139Y78\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_18\" LOC = \"SLICE_X139Y80\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_19\" LOC = \"SLICE_X138Y84\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_20\" LOC = \"SLICE_X139Y48\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_21\" LOC = \"SLICE_X138Y52\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_22\" LOC = \"SLICE_X139Y54\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_23\" LOC = \"SLICE_X139Y56\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_24\" LOC = \"SLICE_X138Y76\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_25\" LOC = \"SLICE_X138Y80\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_26\" LOC = \"SLICE_X139Y82\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_27\" LOC = \"SLICE_X139Y84\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_28\" LOC = \"SLICE_X139Y50\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_29\" LOC = \"SLICE_X139Y52\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_30\" LOC = \"SLICE_X138Y56\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_31\" LOC = \"SLICE_X139Y58\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_0\" LOC = \"SLICE_X138Y60\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_1\" LOC = \"SLICE_X138Y60\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_0\" LOC = \"SLICE_X138Y48\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_1\" LOC = \"SLICE_X138Y48\" | BEL = \"FFY\";\\n'];\n % end case 'adc1'\n end % switch adc_str\n % end case 'iBOB'\nend % switch hw_sys\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adc083000x2.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc083000x2/xps_adc083000x2.m", "size": 12140, "source_encoding": "utf_8", "md5": "f43641ee3b31b164ddc4e4fc74fcd3be", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_adc083000x2(blk_obj)\n\nfprintf('Creating block object: xps_adc083000x2\\n')\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_ADC class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_adc083000x2')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\n% Retrieve block configuration parameters\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.use_adc0 = strcmp( get_param(blk_name, 'use_adc0'), 'on');\ns.use_adc1 = strcmp( get_param(blk_name, 'use_adc1'), 'on');\ns.demux_adc = strcmp( get_param(blk_name, 'demux_adc'), 'on');\ns.using_ctrl = strcmp( get_param(blk_name, 'using_ctrl'), 'on' );\n\n\nif s.demux_adc\n s.sysclk_rate = eval_param(blk_name,'adc_clk_rate')/8;\nelse\n s.sysclk_rate = eval_param(blk_name,'adc_clk_rate')/4;\nend\nif s.use_adc0\n s.adc_str = 'adc0';\nelse\n s.adc_str = 'adc1';\nend\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.adc_interleave = strcmp( get_param(blk_name,'clock_sync'), 'on');\ns.adc_str = 'adc0'; % \"dominant\" ADC is in ZDOK 0\n\nswitch s.hw_sys\n case 'ROACH'\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(1000/s.adc_clk_rate*4),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n ucf_constraints_single = struct('IOSTANDARD', 'LVCMOS25');\n % end case 'ROACH'\n case 'ROACH2'\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(1000/s.adc_clk_rate*4),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n ucf_constraints_single = struct('IOSTANDARD', 'LVCMOS25'); \n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend % end switch s.hw_sys\n\nb = class(s,'xps_adc083000x2',blk_obj);\n\n% ip name and version\nb = set(b, 'ip_name', 'adc083000x2_interface');\nswitch s.hw_sys\n case 'ROACH'\n b = set(b, 'ip_version', '1.00.a');\n case 'ROACH2'\n b = set(b, 'ip_version', '1.00.a');\nend % switch s.hw_sys\n\n% misc ports\n% misc_ports.ctrl_reset = {1 'in' [s.adc_str,'_ddrb']};\nmisc_ports.ctrl_clk_in = {1 'in' get(xsg_obj,'clk_src')};\nmisc_ports.ctrl_clk_out = {1 'out' [s.adc_str,'_clk']};\nmisc_ports.ctrl_clk90_out = {1 'out' [s.adc_str,'_clk90']};\nmisc_ports.ctrl_dcm_locked = {1 'out' [s.adc_str,'_dcm_locked']};\nif strcmp(get(b,'ip_version'), '1.01.a')\n misc_ports.dcm_reset = {1 'in' [s.adc_str,'_dcm_reset']};\n misc_ports.dcm_psdone = {1 'out' [s.adc_str,'_psdone']};\n misc_ports.ctrl_clk180_out = {1 'out' [s.adc_str,'_clk180']};\n misc_ports.ctrl_clk270_out = {1 'out' [s.adc_str,'_clk270']};\nend\nmisc_ports.sys_clk = {1 'in' 'sys_clk'};\n\n% if s.using_ctrl,\n% misc_ports.adc_ctrl_notSCS = {1 'in' 'adc_ctrl_notSCS'};\n% misc_ports.adc_ctrl_clk = {1 'in' 'adc_ctrl_clk'};\n% misc_ports.adc_ctrl_sdata = {1 'in' 'adc_ctrl_sdata'};\n% end\n\n% misc_ports.dcm_psen = {1 'in' [s.adc_str,'_psen']};\n% misc_ports.dcm_psincdec = {1 'in' [s.adc_str,'_psincdec']};\n% misc_ports.control_data = {1, 'in', 'adc_control_data'};\nb = set(b,'misc_ports',misc_ports);\n\n% external ports\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(s.adc_clk_rate*1e6));\n\n% adcport = [s.hw_sys, '.', 'zdok', s.adc_str(length(s.adc_str))];\nadc0port = [s.hw_sys, '.', 'zdok0'];%, s.adc_str(length(s.adc_str))];\nadc1port = [s.hw_sys, '.', 'zdok1'];%, s.adc_str(length(s.adc_str))];\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ADC0\next_ports.adc0_clk_p = {1 'in' ['adc0','clk_p'] ['{',adc0port,'_p{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc0_clk_n = {1 'in' ['adc0','clk_n'] ['{',adc0port,'_n{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc0_sync_p = {1 'in' ['adc0','sync_p'] ['{',adc0port,'_p{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc0_sync_n = {1 'in' ['adc0','sync_n'] ['{',adc0port,'_n{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc0_outofrange_p = {1 'in' ['adc0','outofrange_p'] ['{',adc0port,'_p{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc0_outofrange_n = {1 'in' ['adc0','outofrange_n'] ['{',adc0port,'_n{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc0_dataeveni_p = {8 'in' ['adc0','dataeveni_p'] ['{',adc0port,'_p{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataeveni_n = {8 'in' ['adc0','dataeveni_n'] ['{',adc0port,'_n{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataoddi_p = {8 'in' ['adc0','dataoddi_p'] ['{',adc0port,'_p{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataoddi_n = {8 'in' ['adc0','dataoddi_n'] ['{',adc0port,'_n{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataevenq_p = {8 'in' ['adc0','dataevenq_p'] ['{',adc0port,'_p{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataevenq_n = {8 'in' ['adc0','dataevenq_n'] ['{',adc0port,'_n{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataoddq_p = {8 'in' ['adc0','dataoddq_p'] ['{',adc0port,'_p{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataoddq_n = {8 'in' ['adc0','dataoddq_n'] ['{',adc0port,'_n{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_reset = {1 'out' ['adc0','_reset'] ['{',adc0port,'_p{[19]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n% ext_ports.adc0_notSCS = {1 'out' ['adc0','_notSCS'] ['{',adc0port,'_p{[9]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n% ext_ports.adc0_sdata = {1 'out' ['adc0','_sdata'] ['{',adc0port,'_n{[9]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n% ext_ports.adc0_sclk = {1 'out' ['adc0','_sclk'] ['{',adc0port,'_n{[8]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ADC1\next_ports.adc1_clk_p = {1 'in' ['adc1','clk_p'] ['{',adc1port,'_p{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc1_clk_n = {1 'in' ['adc1','clk_n'] ['{',adc1port,'_n{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc1_sync_p = {1 'in' ['adc1','sync_p'] ['{',adc1port,'_p{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc1_sync_n = {1 'in' ['adc1','sync_n'] ['{',adc1port,'_n{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc1_outofrange_p = {1 'in' ['adc1','outofrange_p'] ['{',adc1port,'_p{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc1_outofrange_n = {1 'in' ['adc1','outofrange_n'] ['{',adc1port,'_n{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc1_dataeveni_p = {8 'in' ['adc1','dataeveni_p'] ['{',adc1port,'_p{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataeveni_n = {8 'in' ['adc1','dataeveni_n'] ['{',adc1port,'_n{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataoddi_p = {8 'in' ['adc1','dataoddi_p'] ['{',adc1port,'_p{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataoddi_n = {8 'in' ['adc1','dataoddi_n'] ['{',adc1port,'_n{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataevenq_p = {8 'in' ['adc1','dataevenq_p'] ['{',adc1port,'_p{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataevenq_n = {8 'in' ['adc1','dataevenq_n'] ['{',adc1port,'_n{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataoddq_p = {8 'in' ['adc1','dataoddq_p'] ['{',adc1port,'_p{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataoddq_n = {8 'in' ['adc1','dataoddq_n'] ['{',adc1port,'_n{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_reset = {1 'out' ['adc1','_reset'] ['{',adc1port,'_p{[19]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n% ext_ports.adc1_notSCS = {1 'out' ['adc1','_notSCS'] ['{',adc1port,'_p{[9]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n% ext_ports.adc1_sdata = {1 'out' ['adc1','_sdata'] ['{',adc1port,'_n{[9]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n% ext_ports.adc1_sclk = {1 'out' ['adc1','_sclk'] ['{',adc1port,'_n{[8]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n\n\nb = set(b,'ext_ports',ext_ports);\nparameters.DEMUX_DATA_OUT = num2str(s.demux_adc);\nparameters.USE_ADC0 = num2str(s.use_adc0);\nparameters.USE_ADC1 = num2str(s.use_adc1);\nparameters.INTERLEAVE_BOARDS = num2str(s.adc_interleave);\n\nb = set(b,'parameters',parameters);\n% Software parameters\nb = set(b,'c_params',['adc = ',s.adc_str,' / interleave = ',num2str(s.adc_interleave)]);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc083000x2/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_onegbe/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_onegbe/drc.m", "size": 2128, "source_encoding": "utf_8", "md5": "2e726d7b126a771e1269442e30fbe8cc", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\n%for i=1:length(xps_objs)\r\n%\ttry\r\n%\t\tif strcmp(get(blk_obj,'port'),get(xps_objs{i},'port'))\r\n%\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n%\t\t\t\tmsg = ['XAUI ',get(blk_obj,'simulink_name'),' and XAUI ',get(xps_objs{i},'simulink_name'),' are located on the same port.'];\r\n%\t\t\t\tresult = 1;\r\n%\t\t\tend\r\n%\t\tend\r\n%\tend\r\n%end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_onegbe.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_onegbe/xps_onegbe.m", "size": 5078, "source_encoding": "utf_8", "md5": "7fe3afe635ef879ec8ae11294cc36b14", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_onegbe(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_ONEGBE class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_onegbe')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\n% Get MASK paramters from the one_GbE yellow block\ns.hw_sys = get(xsg_obj,'hw_sys');\n\ns.local_en = num2str(strcmp(get_param(blk_name, 'local_en'), 'on'));\ns.cpu_promiscuous = num2str(strcmp(get_param(blk_name, 'cpu_promiscuous'), 'on'));\ns.dis_cpu_tx = num2str(strcmp(get_param(blk_name, 'dis_cpu_tx'), 'on'));\ns.dis_cpu_rx = num2str(strcmp(get_param(blk_name, 'dis_cpu_rx'), 'on'));\ns.local_mac = ['0x', dec2hex(eval(get_param(blk_name, 'local_mac'))) ];\ns.local_ip = ['0x', dec2hex(eval(get_param(blk_name, 'local_ip'))) ];\ns.local_port = ['0x', dec2hex(eval(get_param(blk_name, 'local_port'))) ];\ns.local_gateway = ['0x', dec2hex(eval(get_param(blk_name, 'local_gateway'))) ];\n\n% These MASK parameters ends up to be generics for the HDL (gbe_udp.v)\n% also see gbe_udp_v2_1_0.mpd for connections and parameter declarations\nparameters.LOCAL_ENABLE = s.local_en;\nparameters.LOCAL_MAC = s.local_mac;\nparameters.LOCAL_IP = s.local_ip;\nparameters.LOCAL_PORT = s.local_port;\nparameters.LOCAL_GATEWAY = s.local_gateway;\nparameters.CPU_PROMISCUOUS = s.cpu_promiscuous;\nparameters.DIS_CPU_TX = s.dis_cpu_tx;\nparameters.DIS_CPU_RX = s.dis_cpu_rx;\n\nb = class(s,'xps_onegbe',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','gbe_udp');\n\nswitch s.hw_sys\n case 'ROACH2'\n b = set(b,'ip_version','1.00.a');\n otherwise\n error(['1GbE not supported for platform ', s.hw_sys]);\nend\n\n% ROACH2 has an OPB One Gig Eth interface\nswitch s.hw_sys\n case 'ROACH2'\n b = set(b,'opb_clk','epb_clk');\n %b = set(b,'opb_clk',get(xsg_obj,'clk_src'));\n b = set(b,'opb_address_offset',16384);\n b = set(b,'opb_address_align', hex2dec('4000'));\n % end case 'ROACH'\n otherwise\n error(['1GbE not supported for platform ', s.hw_sys]);\n % end otherwise\nend % switch s.hw_sys\n\nb = set(b,'parameters',parameters);\n\n% bus interfaces\nswitch s.hw_sys\n case 'ROACH2'\n interfaces.MAC = ['mac'];\n b = set(b,'interfaces',interfaces);\n otherwise\n error(['1GbE not supported for platform ', s.hw_sys]);\n % end otherwise\nend % switch s.hw_sys\n\n% miscellaneous and external ports\n\n% also see gbe_udp_v2_1_0.mpd for connections and parameter declarations\n\n% Connect yellow block app clk to the selected XSG Core Config clk_src\nmisc_ports.app_clk = {1 'in' get(xsg_obj,'clk_src')};\n\n% connect mac_tx_rst & mac_rx_rst ports to the yellow block app_tx_rst & app_rx_rst\nmisc_ports.mac_tx_rst = {1 'in' clear_name([blk_name,'_app_tx_rst'])}\nmisc_ports.mac_rx_rst = {1 'in' clear_name([blk_name,'_app_rx_rst'])}\n\nb = set(b,'misc_ports',misc_ports);\n\n% This yellow block does not have any FPGA pins\next_ports = {};\n\nb = set(b,'ext_ports',ext_ports);\n\n% borf parameters\nswitch s.hw_sys\n case 'ROACH2'\n borph_info.size = hex2dec('4000');\n borph_info.mode = 3;\n b = set(b,'borph_info',borph_info);\n otherwise\n borph_info.size = 1;\n borph_info.mode = 7;\n b = set(b,'borph_info',borph_info);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_onegbe/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_onegbe/gen_mhs_ip.m", "size": 2817, "source_encoding": "utf_8", "md5": "f27b4b34794be32d0c9aa8e82da0fbdf", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj,opb_addr_start,opb_name)\n\nhw_sys = get(blk_obj, 'hw_sys');\n\n[str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj.xps_block, opb_addr_start, opb_name);\nstr = [str, '\\n'];\n\nswitch hw_sys\n case 'ROACH2'\n\n %mgt_clk_num = num2str(floor(str2num(xaui_port)/2));\n\n %str = [str, 'BEGIN xaui_phy', '\\n'];\n %str = [str, ' PARAMETER INSTANCE = xaui_phy_', xaui_port, '\\n'];\n %str = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\n %str = [str, ' PARAMETER USE_KAT_XAUI = 0', '\\n'];\n %str = [str, ' BUS_INTERFACE XAUI_SYS = xaui_sys', xaui_port, '\\n'];\n %str = [str, ' BUS_INTERFACE XGMII = xgmii', xaui_port, '\\n'];\n %str = [str, ' PORT reset = sys_reset' , '\\n'];\n %str = [str, ' PORT mgt_clk = mgt_clk_', mgt_clk_num, '\\n'];\n %str = [str, 'END', '\\n'];\n % end case 'ROACH2'\n\n otherwise\n % end otherwise\nend % switch hw_sys\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xaui/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xaui/drc.m", "size": 2116, "source_encoding": "utf_8", "md5": "0c715a8c93631ecbfda7541640cf62af", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'port'),get(xps_objs{i},'port'))\r\n\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['XAUI ',get(blk_obj,'simulink_name'),' and XAUI ',get(xps_objs{i},'simulink_name'),' are located on the same port.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xaui/gen_ucf.m", "size": 3142, "source_encoding": "utf_8", "md5": "052a099f34368675f60e03be6815324b", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction str = gen_ucf(blk_obj)\r\nboard = blk_obj.board;\r\nport = blk_obj.port;\r\n\r\nstr = gen_ucf(blk_obj.xps_block);\r\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\r\n\r\nif ~strcmp(board, 'ROACH')\r\n str = [str, 'INST \"', simulink_name, '/', simulink_name, '/transceiver0/mgt\" CHAN_BOND_MODE = \"MASTER\"; \\n'];\r\n str = [str, 'INST \"', simulink_name, '/', simulink_name, '/transceiver1/mgt\" CHAN_BOND_MODE = \"SLAVE_1_HOP\"; \\n'];\r\n str = [str, 'INST \"', simulink_name, '/', simulink_name, '/transceiver2/mgt\" CHAN_BOND_MODE = \"SLAVE_1_HOP\"; \\n'];\r\n str = [str, 'INST \"', simulink_name, '/', simulink_name, '/transceiver3/mgt\" CHAN_BOND_MODE = \"SLAVE_1_HOP\"; \\n'];\r\n str = [str, 'INST \"', simulink_name, '/', simulink_name, '/transceiver?/mgt\" REF_CLK_V_SEL = \"1\"; \\n'];\r\n str = [str, 'INST \"', simulink_name, '/', simulink_name, '/transceiver?/mgt\" RX_LOSS_OF_SYNC_FSM = \"TRUE\"; \\n'];\r\n str = [str, 'INST \"', simulink_name, '/', simulink_name, '/transceiver?/mgt\" CHAN_BOND_ONE_SHOT = \"FALSE\"; \\n'];\r\n str = [str, 'INST \"', simulink_name, '/', simulink_name, '/transceiver?/mgt\" TX_PREEMPHASIS = \"', blk_obj.preemph, '\"; \\n'];\r\n str = [str, 'INST \"', simulink_name, '/', simulink_name, '/transceiver?/mgt\" TX_DIFF_CTRL = \"', blk_obj.swing, '\"; \\n'];\r\n str = [str, 'INST \"', simulink_name, '/', simulink_name, '/transceiver?/reclock_align\" ASYNC_REG = TRUE; \\n'];\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xaui/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xaui/gen_mhs_ip.m", "size": 2881, "source_encoding": "utf_8", "md5": "76eeed5f26c19fb68f49b04e427cae7e", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj,opb_addr_start,opb_name)\n\nxaui_port = get(blk_obj, 'port');\nopen_phy = get(blk_obj, 'open_phy');\nhw_sys = get(blk_obj, 'hw_sys');\n\n[str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj.xps_block, opb_addr_start, opb_name);\nstr = [str, '\\n'];\n\nswitch hw_sys\n case 'ROACH'\n\n mgt_clk_num = num2str(floor(str2num(xaui_port)/2));\n\n str = [str, 'BEGIN xaui_phy', '\\n'];\n str = [str, ' PARAMETER INSTANCE = xaui_phy_', xaui_port, '\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\n str = [str, ' PARAMETER USE_KAT_XAUI = ', open_phy, '\\n'];\n str = [str, ' BUS_INTERFACE XAUI_SYS = xaui_sys', xaui_port, '\\n'];\n str = [str, ' BUS_INTERFACE XGMII = xgmii', xaui_port, '\\n'];\n str = [str, ' PORT reset = sys_reset' , '\\n'];\n str = [str, ' PORT mgt_clk = mgt_clk_', mgt_clk_num, '\\n'];\n str = [str, 'END', '\\n'];\n % end case 'ROACH'\n\n otherwise\n % end otherwise\nend % switch hw_sys\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_xaui.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xaui/xps_xaui.m", "size": 5339, "source_encoding": "utf_8", "md5": "1b4a0df22c44eeb1094f35fe8221881b", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_xaui(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_XAUI class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_xaui')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\ntoks = regexp(get_param(blk_name,'port'),'^(.*):(.*)$','tokens');\n\ns.board = toks{1}{1};\ns.port = toks{1}{2};\ns.hw_sys = s.board;\ns.preemph = get_param(blk_name, 'pre_emph');\ns.swing = get_param(blk_name, 'swing');\ns.open_phy = num2str(strcmp(get_param(blk_name, 'open_phy'), 'on'));\n\nb = class(s,'xps_xaui',blk_obj);\n\n% ip name\nb = set(b,'ip_name','XAUI_interface');\n\n% misc ports\nmisc_ports.app_clk = {1 'in' get(xsg_obj,'clk_src')};\n\nswitch s.board\n case 'ROACH'\n if strcmp(s.port, '0') || strcmp(s.port, '1')\n misc_ports.xaui_clk = {1 'in' 'mgt_clk_0'};\n else\n misc_ports.xaui_clk = {1 'in' 'mgt_clk_1'};\n end\nend % switch s.board\n\nb = set(b,'misc_ports',misc_ports);\n\n% parameters\nparameters.DEMUX = get_param(blk_name,'demux');\nb = set(b,'parameters',parameters);\n\n% external ports\nportnum = ['XAUI', s.port];\nxauiport = [s.board,'.',portnum];\n\nif ~strcmp(s.board,'ROACH')\n ext_ports.mgt_tx_l0_p = {1 'out' [portnum,'_tx_l0_p'] [xauiport, '.tx_l0_p'] 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l0_n = {1 'out' [portnum,'_tx_l0_n'] [xauiport, '.tx_l0_n'] 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l1_p = {1 'out' [portnum,'_tx_l1_p'] [xauiport, '.tx_l1_p'] 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l1_n = {1 'out' [portnum,'_tx_l1_n'] [xauiport, '.tx_l1_n'] 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l2_p = {1 'out' [portnum,'_tx_l2_p'] [xauiport, '.tx_l2_p'] 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l2_n = {1 'out' [portnum,'_tx_l2_n'] [xauiport, '.tx_l2_n'] 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l3_p = {1 'out' [portnum,'_tx_l3_p'] [xauiport, '.tx_l3_p'] 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l3_n = {1 'out' [portnum,'_tx_l3_n'] [xauiport, '.tx_l3_n'] 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l0_p = {1 'in' [portnum,'_rx_l0_p'] [xauiport, '.rx_l0_p'] 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l0_n = {1 'in' [portnum,'_rx_l0_n'] [xauiport, '.rx_l0_n'] 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l1_p = {1 'in' [portnum,'_rx_l1_p'] [xauiport, '.rx_l1_p'] 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l1_n = {1 'in' [portnum,'_rx_l1_n'] [xauiport, '.rx_l1_n'] 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l2_p = {1 'in' [portnum,'_rx_l2_p'] [xauiport, '.rx_l2_p'] 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l2_n = {1 'in' [portnum,'_rx_l2_n'] [xauiport, '.rx_l2_n'] 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l3_p = {1 'in' [portnum,'_rx_l3_p'] [xauiport, '.rx_l3_p'] 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l3_n = {1 'in' [portnum,'_rx_l3_n'] [xauiport, '.rx_l3_n'] 'vector=false' struct() struct()};\n b = set(b,'ext_ports',ext_ports);\nend\n\nif strcmp(s.board,'ROACH')\n interfaces.XAUI_CONF = ['xaui_conf',s.port];\n interfaces.XGMII = ['xgmii',s.port];\n b = set(b,'interfaces',interfaces);\nend\n\n% Only ROACH has an OPB attachment for XAUI\nswitch s.hw_sys\n case 'ROACH'\n b = set(b,'opb_clk','epb_clk');\n b = set(b,'opb_address_offset', 256);\nend % switch s.hw_sys\n\n% borf parameters\nswitch s.hw_sys\n case 'ROACH'\n borph_info.size = 32;\n borph_info.mode = 3;\n b = set(b,'borph_info',borph_info);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/get.m", "size": 1965, "source_encoding": "utf_8", "md5": "e4447d00c910af45efa20e63d8451e64", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknown to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "display.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/display.m", "size": 2764, "source_encoding": "utf_8", "md5": "62f4f91b74e07c78c12ce46dd12fa0fa", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction display(b)\r\n%DISPLAY text display of the XPS_Block class object\r\n% DISPLAY(obj) displays the property values of the object\r\ndisp('==============================================================');\r\ndisp([' Simulink Name: ' b.simulink_name]);\r\ndisp([' Parent System: ' b.parent]);\r\ndisp([' Block type: ' b.type]);\r\nif ~isempty(b.ports)\r\n\tdisp([' Ports: ']);\r\n\tdisp(b.ports);\r\nend\r\nparams = fieldnames(b);\r\nfor i=[1:length(params)]\r\n\tif ~strcmp(params{i},'xps_block')\r\n\t\tif ischar(get(b,params{i}))\r\n\t\t\tdisp([' ',params{i},' = ',get(b,params{i})]);\r\n\t\telseif isnumeric(get(b,params{i}))\r\n\t\t\tdisp([' ',params{i},' = ',num2str(get(b,params{i}))]);\r\n\t\telseif islogical(get(b,params{i}))\r\n\t\t\tif get(b,params{i})\r\n\t\t\t\tdisp([' ',params{i},' = true']);\r\n\t\t\telse\r\n\t\t\t\tdisp([' ',params{i},' = false']);\r\n\t\t\tend\r\n\t\telseif iscellstr(get(b,params{i}))\r\n\t\t\tdisp([' ',params{i},' = ']);\r\n\t\t\tdisp(get(b,params{i}));\r\n\t\telse\r\n\t\t\tdisp([' ',params{i},' [Unknown object type]']);\r\n\t\tend\r\n\tend\r\nend\r\ndisp('==============================================================');\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mss.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_mss.m", "size": 2258, "source_encoding": "utf_8", "md5": "b289c311cdfc9c776a8752533a27d0aa", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction str = gen_mss(blk_obj)\r\nstr = '';\r\n\r\ntry\r\n\tip_name = blk_obj.ip_name;\r\ncatch\r\n\tip_name = '';\r\nend\r\n\r\ntry\r\n\tsoft_driver = blk_obj.soft_driver;\r\ncatch\r\n\tsoft_driver = {};\r\nend\r\nif isempty(soft_driver)\r\n\tsoft_driver = {'generic' '1.00.a'};\r\nend\r\n\r\nif ~isempty(ip_name)\r\n\tstr = [str, 'BEGIN DRIVER\\n'];\r\n\tstr = [str, ' PARAMETER DRIVER_NAME = ',soft_driver{1},'\\n'];\r\n\tstr = [str, ' PARAMETER DRIVER_VER = ',soft_driver{2},'\\n'];\r\n\tstr = [str, ' PARAMETER HW_INSTANCE = ',clear_name(get(blk_obj,'simulink_name')),'\\n'];\r\n\tstr = [str, 'END\\n'];\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_xsg.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_mhs_xsg.m", "size": 2690, "source_encoding": "utf_8", "md5": "f3e7a8397702abf51eb99c1aa4764715", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [str,opb_addr_end] = gen_mhs_xsg(blk_obj,opb_addr_start,opb_name)\r\nstr = '';\r\nopb_addr_end = opb_addr_start;\r\n\r\nports = blk_obj.ports;\r\nbuses = blk_obj.buses;\r\n\r\nif (isempty(ports) && isempty(buses))\r\n return;\r\nend\r\n\r\ninst_name = clear_name(get(blk_obj,'simulink_name'));\r\n\r\nif ~isempty(ports)\r\n port_names = fieldnames(ports);\r\nelse\r\n port_names = {};\r\nend\r\n\r\nif ~isempty(buses)\r\n bus_names = fieldnames(buses);\r\nelse\r\n bus_names = {};\r\nend\r\n\r\nbus_ports = {};\r\n\r\nfor k = 1:length(bus_names)\r\n cur_bus = getfield(buses, bus_names{k});\r\n bus_if_name = getfield(cur_bus, 'busif');\r\n\r\n bus_ports = [bus_ports, getfield(cur_bus, 'ports')];\r\n str = [str, ' BUS_INTERFACE ', bus_if_name{1}, ' = ', inst_name, '_', bus_names{k}, '\\n'];\r\nend\r\n\r\nfor j = 1:length(port_names)\r\n cur_port = getfield(ports,port_names{j});\r\n\r\n if isempty(strmatch(cur_port{3}, bus_ports))\r\n str = [str, ' PORT ',port_names{j},' = ',port_names{j},'\\n'];\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/drc.m", "size": 1773, "source_encoding": "utf_8", "md5": "6d25a3bea82cda253b51738ad271aa4f", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_ucf.m", "size": 4009, "source_encoding": "utf_8", "md5": "e11e507c44eea86013a76878986ea4c7", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\nstr = '';\n\ntry\n ext_ports = blk_obj.ext_ports;\ncatch\n ext_ports = {};\nend\n\nif ~isempty(ext_ports)\n load_hw_routes();\n ext_port_names = fieldnames(ext_ports);\n for j = 1:length(ext_port_names)\n cur_ext_port = getfield(ext_ports,ext_port_names{j});\n if length(cur_ext_port) > 3\n locs = cur_ext_port{4};\n\n try\n ucf_constraints = cur_ext_port{7};\n ucf_constraints_fields = fieldnames(ucf_constraints);\n ucf_constraints_str = '';\n\n for n = 1:length(ucf_constraints_fields)\n ucf_constraint_value = eval(['ucf_constraints.',ucf_constraints_fields{n}]);\n\n if isempty(ucf_constraint_value)\n ucf_constraints_str = [ucf_constraints_str, ' | ', ucf_constraints_fields{n}];\n else\n ucf_constraints_str = [ucf_constraints_str, ' | ', ucf_constraints_fields{n}, ' = ', ucf_constraint_value];\n end % if isempty(ucf_constraint_value)\n end % for n = 1:length(ucf_constraints_fields)\n catch\n ucf_constraints_str = '';\n end % try\n\n if ~strcmp(locs,'null')\n if isstr(locs)\n pin = eval(locs);\n else\n pin = locs;\n end% if isstr(locs)\n\n if length(pin) ~= cur_ext_port{1}\n error(['Number of pin locations for external port ',ext_port_names{j},' does not correspond to bitwidth']);\n end % length(locs) ~= cur_ext_port{1}\n\n if cur_ext_port{1} == 1 & ~strcmp(cur_ext_port{5},'vector=true')\n str = [str,'NET \\\"',cur_ext_port{3},'\\\" LOC = ', pin{1}, ucf_constraints_str, ' ;\\n'];\n else\n for i = [1:cur_ext_port{1}]\n str = [str,'NET \\\"',cur_ext_port{3},'<',num2str(i-1),'>\\\" LOC = ', pin{i}, ucf_constraints_str, ' ;\\n'];\n end % i = [1:cur_ext_port{1}]\n end % cur_ext_port{1} == 1 & ~strcmp(cur_ext_port{5},'vector=true')\n end % if ~strcmp(locs,'null')\n end % if length(cur_ext_port) > 3\n end % for j = 1:length(ext_port_names)\nend % ~isempty(ext_ports)\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_block.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/xps_block.m", "size": 7916, "source_encoding": "utf_8", "md5": "1b9765619e3234ba661ae203656ff233", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_block(blk, xsg_obj)\n\ns.ip_name = {};\ns.ip_version = {};\ns.supp_ip_names = {};\ns.supp_ip_versions = {};\ns.opb_clk = '';\ns.opb0_devices = 0; % bus interfaces hard coded to opb0\ns.opb_address_offset = 0;\ns.opb_address_align = 0;\ns.ports = {};\ns.ext_ports = {};\ns.misc_ports = {};\ns.parameters = {};\ns.soft_driver = {};\ns.c_params = '';\ns.buses = {};\ns.interfaces = {};\ns.borph_info = {};\n\nif ~isempty(blk)\n tmp = regexp(get_param(blk,'Tag'),'^xps:(\\w+)','tokens');\n if isempty(tmp)\n error('Simulink block is not tagged as a XPS block.');\n end\n\n s.simulink_name = [get_param(blk,'parent'), '/', get_param(blk,'name')];\n s.parent = get_param(blk, 'parent');\n s.xsg_obj = xsg_obj;\n s.type = ['xps_', tmp{1}{1}];\n b = class(s, 'xps_block');\n\n % add ports to the object\n gateways_blk_in = find_system(blk, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'masktype', 'Xilinx Gateway In Block');\n gateways_blk_out = find_system(blk, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'masktype', 'Xilinx Gateway Out Block');\n ports = {};\n\n % process gateway in blocks\n for n = 1:length(gateways_blk_in),\n parent = get_param(gateways_blk_in(n), 'parent');\n % only include gateway blocks directly inside this block\n if strcmp(parent{1}, blk),\n if isempty(find_system(parent, 'SearchDepth', 1, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'masktype', 'Xilinx Disregard Subsystem For Generation Block')),\n % extract the interface IO name\n io_name = get_param(gateways_blk_in{n}, 'name');\n parent_name = clear_name(parent{1});\n if_io_name = io_name(length(parent_name)+2:length(io_name));\n if length(clear_name(io_name)) >= 63,\n error(['The Gateway block ', io_name, ' of interface block ', parent_name, ' has a name longer than 63 characters, which will be truncated due to Matlab limitations']);\n end\n if ~strcmp([parent_name,'_'], io_name(1:length(parent_name)+1)),\n error(['The Gateway block ', io_name, ' does not respect the hierachical naming convention (it should start with ', parent_name, ').']);\n end\n % port width\n if strcmp(get_param(gateways_blk_in{n}, 'arith_type'), 'Boolean')\n io_bitwidth = 1;\n else\n io_bitwidth = eval_param(gateways_blk_in{n}, 'n_bits');\n end % if strcmp(get_param(gateways_blk_in{n},'arith_type'),'Boolean')\n % set the port\n eval(['ports.', io_name, ' = {', num2str(io_bitwidth), ' ''in'',''', if_io_name, '''};']);\n end % if isempty(find_system(parent,'SearchDepth', 1, 'FollowLinks','on','LookUnderMasks','all','masktype','Xilinx Disregard Subsystem For Generation Block'))\n end % if strcmp(parent{1}, blk),\n end % for n=[1:length(gateways_blk_in)]\n\n % and now gateway out blocks\n for n = 1:length(gateways_blk_out),\n parent = get_param(gateways_blk_out(n), 'parent');\n % only include gateway blocks directly inside this block\n if strcmp(parent{1}, blk),\n if isempty(find_system(parent, 'SearchDepth', 1, 'FollowLinks', 'on', 'LookUnderMasks', 'all', 'masktype', 'Xilinx Disregard Subsystem For Generation Block')),\n % extract the interface IO name\n io_name = get_param(gateways_blk_out{n}, 'name');\n parent_name = clear_name(parent{1});\n if_io_name = io_name(length(parent_name)+2:length(io_name));\n if length(clear_name(io_name)) >= 63,\n error(['The Gateway block ', io_name, ' of interface block ', parent_name, ' has a name longer than 63 characters, which will be truncated due to Matlab limitations']);\n end\n if ~strcmp([parent_name,'_'], io_name(1:length(parent_name)+1)),\n error(['The Gateway block ', io_name, ' does not respect the hierachical naming convention (it should start with ', parent_name,').']);\n end\n % find closest convert block\n portconnectivity = get_param(gateways_blk_out{n}, 'PortConnectivity');\n convert_block = find_system(parent, 'FollowLinks', 'on', 'lookundermasks', 'all', 'Handle', portconnectivity(1).SrcBlock, 'masktype', 'Xilinx Type Converter Block Block');\n if isempty(convert_block),\n force_block = find_system(parent, 'FollowLinks', 'on', 'lookundermasks', 'all', 'Handle', portconnectivity(1).SrcBlock, 'masktype', 'Xilinx Type Reinterpreter Block');\n if ~isempty(force_block),\n portconnectivity = get_param(force_block{1}, 'PortConnectivity');\n end\n convert_block = find_system(parent, 'FollowLinks', 'on', 'lookundermasks', 'all', 'Handle', portconnectivity(1).SrcBlock, 'masktype', 'Xilinx Type Converter Block');\n if isempty(convert_block),\n error(['The gateway : ', gateways_blk_out{n}, ' is not preceded by a Xilinx converter block as it should be.']);\n end\n end % if isempty(convert_block)\n % port width\n if strcmp(get_param(convert_block{1}, 'arith_type'), 'Boolean')\n io_bitwidth = 1;\n else\n io_bitwidth = eval_param(convert_block{1}, 'n_bits');\n end % if strcmp(get_param(convert_block{1}, 'arith_type'), 'Boolean')\n % set the port\n eval(['ports.', io_name, ' = {', num2str(io_bitwidth), ' ''out'',''', if_io_name, '''};']);\n end % if isempty(find_system(parent,'SearchDepth', 1, 'FollowLinks','on','LookUnderMasks','all','masktype','Xilinx Disregard Subsystem For Generation Block'))\n end % if strcmp(parent{1}, blk),\n end % for n = 1:length(gateways_blk_out)\n\n if ~isempty(ports),\n b = set(b, 'ports', ports);\n end\nelse\n s.simulink_name = '';\n s.parent = '';\n s.xsg_obj = '';\n s.type = '';\n b = class(s, 'xps_block');\nend % if ~isempty(blk)\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_cmds.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_cmds.m", "size": 1805, "source_encoding": "utf_8", "md5": "9c4b66822e301a629c7ae2de74189f67", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [str, num_cmds, include_str] = gen_cmds(blk_obj)\r\nstr = '';\r\ninclude_str = '';\r\nnum_cmds = 0;"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "elaborate.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/elaborate.m", "size": 1742, "source_encoding": "utf_8", "md5": "054abf5fc5c4d1f414b72ad76e4d1870", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction blk_obj = elaborate(blk_obj)\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_c_core_info.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_c_core_info.m", "size": 2285, "source_encoding": "utf_8", "md5": "e65a4cbf294ce1676affd93a38e8ceb1", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction str = gen_c_core_info(blk_obj)\r\nstr = '';\r\n\r\ntry\r\n\trange_opb = blk_obj.opb_address_offset;\r\ncatch\r\n\trange_opb = 0;\r\nend\r\n\r\nshort_name = regexp(blk_obj.simulink_name,'^\\w*\\/(.*)','tokens');\r\ntry\r\n\tshort_name = short_name{1}{1};\r\ncatch\r\n\tshort_name = blk_obj.simulink_name;\r\nend\r\n\r\nshort_name = char(cellstr(short_name));\r\n\r\nif range_opb ~= 0\r\n\tstr = ['{\"',short_name,'\",',blk_obj.type,',','XPAR_',upper(clear_name(blk_obj.simulink_name)),'_BASEADDR',',\"',blk_obj.c_params,'\"},\\n'];\r\nelse\r\n\tstr = ['{\"',short_name,'\",',blk_obj.type,',-1,\"',blk_obj.c_params,'\"},\\n'];\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mpd.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_mpd.m", "size": 3348, "source_encoding": "utf_8", "md5": "936139e3a519e43a2591e88c10ac29cd", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_mpd(blk_obj)\nstr = '';\n\nports = blk_obj.ports;\nbuses = blk_obj.buses;\n\ninst_name = clear_name(get(blk_obj,'simulink_name'));\n\nif (isempty(ports) && isempty(buses))\n return;\nend\n\nif ~isempty(ports)\n port_names = fieldnames(ports);\nelse\n port_names = {};\nend\n\nif ~isempty(buses)\n bus_names = fieldnames(buses);\nelse\n bus_names = {};\nend\n\nbus_ports = {};\n\nfor k = 1:length(bus_names)\n cur_bus = getfield(buses, bus_names{k});\n\n bus_ports = [bus_ports, getfield(cur_bus, 'ports')];\n bus_if_name = getfield(cur_bus, 'busif');\n\n str = [str, 'BUS_INTERFACE BUS = ', bus_if_name{1}, ', BUS_STD = TRANSPARENT, BUS_TYPE = UNDEF\\n'];\nend\n\nfor j = 1:length(port_names)\n cur_port = getfield(ports,port_names{j});\n\n str = [str, 'PORT ', port_names{j}, ' = '];\n\n if ~isempty(strmatch(cur_port{3}, bus_ports))\n for k = 1:length(bus_names)\n cur_bus = getfield(buses, bus_names{k});\n\n if strmatch(cur_port{3}, getfield(cur_bus, 'ports'));\n bus_if_name = getfield(cur_bus, 'busif');\n str = [str, cur_port{3}, ', BUS = ', bus_if_name{1}];\n break;\n end\n end\n else\n str = [str, '\"\"'];\n end\n\n if cur_port{1} == 1\n try\n if strcmp(cur_port{6}, 'vector=true')\n str = [str, ', DIR = ',cur_port{2},', VEC = [0:0]\\n'];\n else\n str = [str, ', DIR = ',cur_port{2},'\\n'];\n end\n catch\n str = [str, ', DIR = ',cur_port{2},'\\n'];\n end\n else\n str = [str, ', DIR = ',cur_port{2},', VEC = [',num2str(cur_port{1}-1),':0]\\n'];\n end\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "probe_bus_usage.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/probe_bus_usage.m", "size": 2738, "source_encoding": "utf_8", "md5": "5998940701d4557ffe606a6d018f6ada", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [opbs, opb_addr_end, opb0_devices] = probe_bus_usage(blk_obj, opb_addr_start)\r\n\r\n%the number of interfaces hard-coded to reside on opb0\r\nopb0_devices = 0;\r\ntry\r\n opb0_devices = blk_obj.opb0_devices;\r\nend;\r\n\r\nopbs = 0;\r\nrange_opb = 0;\r\ntry\r\n range_opb = blk_obj.opb_address_offset;\r\nend\r\nopbs = sum(range_opb ~= 0);\r\n\r\nalign_opb = 0;\r\ntry\r\n align_opb = blk_obj.opb_address_align;\r\nend\r\n\r\nif length(align_opb) ~= length(range_opb),\r\n error(['opb_address_align and opb_address_offset lengths are different for ',blk_obj.simulink_name]); \r\nend\r\n\r\nopb_addr_end = opb_addr_start;\r\nfor opb = 1:length(range_opb),\r\n if range_opb(opb) ~= 0, \r\n if align_opb(opb) ~= 0,\r\n opb_addr_start = ceil(opb_addr_start/align_opb(opb)) * align_opb(opb);\r\n end\r\n opb_addr_end = opb_addr_start + range_opb(opb); \r\n end\r\nend\r\nclog([get(blk_obj,'simulink_name'),': align (0x',dec2hex(align_opb,8),') range (0x',dec2hex(range_opb,8),') (0x',dec2hex(opb_addr_start,8),'-0x',dec2hex(opb_addr_end-1,8),')'],{'probe_bus_usage_debug'});\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_src_main.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_src_main.m", "size": 1756, "source_encoding": "utf_8", "md5": "d40bec92dd77afcc5cd28805f9ebb878", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction str = gen_src_main(blk_obj,sw_os)\r\nstr = '';"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_m_core_info.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_m_core_info.m", "size": 2481, "source_encoding": "utf_8", "md5": "1d29175a347e9c2a124b20e0f8f00556", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction str = gen_m_core_info(blk_obj, mhs_str)\r\nstr = '';\r\n\r\ninst_name = clear_name(blk_obj.simulink_name);\r\n\r\nbaseaddr = regexp(mhs_str, 'C_BASEADDR\\s*=\\s*0x(\\w*)\\s*', 'tokens');\r\nhighaddr = regexp(mhs_str, 'C_HIGHADDR\\s*=\\s*0x(\\w*)\\s*', 'tokens');\r\n\r\nstr = [str, sprintf('%s_type = ''%s'';\\n', inst_name, blk_obj.type)];\r\nstr = [str, sprintf('%s_param = ''%s'';\\n', inst_name, blk_obj.c_params)];\r\n\r\ntry\r\n str = [str, sprintf('%s_ip_name = ''%s'';\\n', inst_name, blk_obj.ip_name)];\r\ncatch\r\n str = [str, ''];\r\nend\r\n\r\ntry\r\n str = [str, sprintf('%s_addr_start = hex2dec(''%s'');\\n', inst_name, baseaddr{1}{1})];\r\n str = [str, sprintf('%s_addr_end = hex2dec(''%s'');\\n', inst_name, highaddr{1}{1})];\r\ncatch\r\n str = [str, ''];\r\nend\r\n\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/set.m", "size": 1848, "source_encoding": "utf_8", "md5": "8f6bcb1986f5a4f0ffc15ac98a48f7ff", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n error(['Field name unknow to block object: ', field]);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_mhs_ip.m", "size": 7383, "source_encoding": "utf_8", "md5": "49f76a4937bec7313ff12e9a89380276", "text": "%% -*- indent-tabs-mode:t; matlab-indent-level:4; tab-width:4; -*- %%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [str, opb_addr_end, opb_addr_start] = gen_mhs_ip(blk_obj, opb_addr_start, opb_name)\n\nstr = '';\nopb_addr_end = opb_addr_start;\n\ntry\n\tip_name = blk_obj.ip_name;\ncatch\n\tip_name = '';\nend\n\ntry\n\tip_version = blk_obj.ip_version;\ncatch\n\tip_version = '';\nend\n\ntry\n\tports = blk_obj.ports;\ncatch\n\tports = {};\nend\n\ntry\n\tinterfaces = blk_obj.interfaces;\ncatch\n\tinterfaces = {};\nend\n\ntry\n\text_ports = blk_obj.ext_ports;\ncatch\n\text_ports = {};\nend\n\ntry\n\tmisc_ports = blk_obj.misc_ports;\ncatch\n\tmisc_ports = {};\nend\n\ntry\n\tparameters = blk_obj.parameters;\ncatch\n\tparameters = {};\nend\n\ntry\n opb_clk = blk_obj.opb_clk;\ncatch\n opb_clk = '';\nend\n\ntry\n\trange_opb = blk_obj.opb_address_offset;\ncatch\n\trange_opb = 0;\nend\n\ntry\n align_opb = blk_obj.opb_address_align;\ncatch\n align_opb = 0;\nend\n\nif ~isempty(ip_name)\n\tstr = [str, 'BEGIN ', get(blk_obj, 'ip_name'), '\\n'];\n\tstr = [str, ' PARAMETER INSTANCE = ', clear_name(get(blk_obj, 'simulink_name')), '\\n'];\n\n if isempty(ip_version)\n \tstr = [str, ' PARAMETER HW_VER = 1.00.a\\n'];\n else\n \tstr = [str, ' PARAMETER HW_VER = ', ip_version, '\\n'];\n end % if is empty(ip_version)\n\n if isempty(opb_clk)\n opb_clk = 'sys_clk';\n end % if isempty(opb_clk)\n\n\tif ~isempty(parameters)\n\t\tprop_names = fieldnames(parameters);\n\t\tfor n = 1:length(prop_names)\n\t\t cur_prop = getfield(parameters, prop_names{n});\n\t\t str = [str, ' PARAMETER ', prop_names{n}, ' = ', cur_prop, '\\n'];\n\t\tend % for n = 1:length(prop_names)\n\tend % if ~isempty(parameters)\n\n\tif range_opb ~= 0\n\t\tif align_opb ~= 0\n\t\t\topb_addr_start = ceil(opb_addr_start/align_opb) * align_opb;\n\t\tend % if align_opb ~= 0\n\n\t\topb_addr_end = opb_addr_start + range_opb;\n\n\t\tstr = [str, ' PARAMETER C_BASEADDR = 0x', dec2hex(opb_addr_start, 8), '\\n'];\n\t\tstr = [str, ' PARAMETER C_HIGHADDR = 0x', dec2hex(opb_addr_end-1, 8), '\\n'];\n\t\tstr = [str, ' BUS_INTERFACE SOPB = ', opb_name, '\\n'];\n\t\tstr = [str, ' PORT OPB_Clk = ', opb_clk, '\\n'];\n\n\tend % if range_opb ~= 0\n \n clog([get(blk_obj, 'simulink_name'), ': align (0x', dec2hex(align_opb, 8), ') range (0x', dec2hex(range_opb, 8), ') (0x', dec2hex(opb_addr_start, 8), '-0x', dec2hex(opb_addr_end-1, 8), ')'], {'gen_mhs_ip_debug'});\n\n\tif ~isempty(interfaces)\n\t\tinterfaces_names = fieldnames(interfaces);\n\n\t\tfor n = 1:length(interfaces_names)\n\t\t cur_interface = getfield(interfaces, interfaces_names{n});\n\t\t str = [str, ' BUS_INTERFACE ', interfaces_names{n}, ' = ', cur_interface, '\\n'];\n\t\tend % for n = 1:length(interfaces_names)\n end % if ~isempty(interfaces)\n\n\tif ~isempty(ports)\n\t\tport_names = fieldnames(ports);\n\t\tfor n = 1:length(port_names)\n\t\t cur_port = getfield(ports, port_names{n});\n\t\t str = [str, ' PORT ', cur_port{3}, ' = ', port_names{n}, '\\n'];\n\t\tend\n\tend % if ~isempty(ports)\n\n\tif ~isempty(ext_ports)\n\t\text_port_names = fieldnames(ext_ports);\n\n\t\tfor n = 1:length(ext_port_names)\n\t\t cur_ext_port = getfield(ext_ports, ext_port_names{n});\n\t\t if cur_ext_port{1} == 1\n\t\t str = [str, ' PORT ', ext_port_names{n}, ' = ', cur_ext_port{3}, '\\n'];\n else\n str = [str, ' PORT ', ext_port_names{n}, ' = ', cur_ext_port{3}, '\\n'];\n end % if cur_ext_port{1} == 1\n\t\tend % for n = 1:length(ext_port_names)\n\tend % if ~isempty(ext_ports)\n\n\tif ~isempty(misc_ports)\n\t\tmisc_port_names = fieldnames(misc_ports);\n\n\t\tfor n = 1:length(misc_port_names)\n cur_misc_port = getfield(misc_ports, misc_port_names{n});\n if cur_misc_port{1} == 1\n str = [str, ' PORT ', misc_port_names{n}, ' = ', cur_misc_port{3}, '\\n'];\n else\n str = [str, ' PORT ', misc_port_names{n}, ' = ', cur_misc_port{3}, '\\n'];\n\t\t end % if cur_misc_port{1} == 1\n\t\tend % for n = 1:length(misc_port_names)\n\tend % if ~isempty(misc_ports)\n\n\tstr = [str, 'END\\n'];\nend %if ~isempty(ip_name)\n\nif ~isempty(ext_ports)\n\text_port_names = fieldnames(ext_ports);\n\n\tfor k = 1:length(ext_port_names)\n\t cur_ext_port = getfield(ext_ports, ext_port_names{k});\n\n\t try\n\t mhs_constraints = cur_ext_port{6};\n\t mhs_constraints_fields = fieldnames(mhs_constraints);\n\t mhs_constraints_str = '';\n\n\t for n = 1:length(mhs_constraints_fields)\n\t mhs_constraint_value = eval(['mhs_constraints.', mhs_constraints_fields{n}]);\n\n\t if isempty(mhs_constraint_value)\n\t mhs_constraints_str = [mhs_constraints_str, ', ', mhs_constraints_fields{n}];\n\t else\n\t mhs_constraints_str = [mhs_constraints_str, ', ', mhs_constraints_fields{n}, ' = ', mhs_constraint_value];\n\t end % if isempty(mhs_constraint_value)\n\t end % for n = 1:length(mhs_constraints_fields)\n catch\n mhs_constraints_str = '';\n end % try\n\n\t if cur_ext_port{1} == 1\n try\n if strcmp(cur_ext_port{5}, 'vector=true')\n str = [str, 'PORT ', cur_ext_port{3}, ' = ', cur_ext_port{3}, ', DIR = ', cur_ext_port{2}, ', VEC = [0:0]', mhs_constraints_str, '\\n'];\n else\n str = [str, 'PORT ', cur_ext_port{3}, ' = ', cur_ext_port{3}, ', DIR = ', cur_ext_port{2}, mhs_constraints_str, '\\n'];\n end % strcmp(cur_ext_port{5}, 'vector=true')\n catch\n str = [str, 'PORT ', cur_ext_port{3}, ' = ', cur_ext_port{3}, ', DIR = ', cur_ext_port{2}, mhs_constraints_str, '\\n'];\n end % try\n\t else\n\t str = [str, 'PORT ', cur_ext_port{3}, ' = ', cur_ext_port{3}, ', DIR = ', cur_ext_port{2}, ', VEC = [', num2str(cur_ext_port{1}-1), ':0]', mhs_constraints_str, '\\n'];\n\t end % if cur_ext_port{1} == 1\n\tend % for j = 1:length(ext_port_names)\nend % ~isempty(ext_ports)\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_src_files.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_src_files.m", "size": 1761, "source_encoding": "utf_8", "md5": "f9eeaed3b342324281228b23617998d8", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction files = gen_src_files(blk_obj,sw_os)\r\nfiles = {};"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_borf_info.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_block/gen_borf_info.m", "size": 2434, "source_encoding": "utf_8", "md5": "92d609a55a0caa9793549e82bec2b34c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [str, loc] = gen_borf_info(loc, blk_obj, real_address)\r\nstr = '';\r\n\r\nshort_name = regexp(blk_obj.simulink_name, '^\\w*\\/(.*)', 'tokens');\r\ntry\r\n short_name = short_name{1}{1};\r\ncatch\r\n short_name = blk_obj.simulink_name;\r\nend\r\n\r\ninst_name = clear_name(short_name);\r\n\r\ntry \r\n borph_info = blk_obj.borph_info;\r\ncatch\r\n borph_info = {};\r\nend\r\n\r\nif isempty(borph_info),\r\n str = '';\r\nelse\r\n if ~isempty(real_address),\r\n str = [str, sprintf('%s %d %s %s\\n', inst_name, borph_info.mode, dec2hex(real_address), dec2hex(borph_info.size))];\r\n else\r\n str = [str, sprintf('%s %d %s %s\\n', inst_name, borph_info.mode, dec2hex(loc), dec2hex(borph_info.size))];\r\n end\r\nend\r\n\r\nloc = loc + 1;\r\n\r\n%end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_qdr/get.m", "size": 1931, "source_encoding": "utf_8", "md5": "f84252bb20e9c7686c459f7de2c2c6f6", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction result = get(b,field)\n\n try\n eval(['result = b.',field,';']);\n catch\n try\n result = get(b.xps_block,field);\n catch \n error(['Field name unknow to block object: ', field]);\n end\n end\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_qdr.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_qdr/xps_qdr.m", "size": 2683, "source_encoding": "utf_8", "md5": "ee83c5d0e916932657188328b89b3500", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_qdr(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_ADC class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_qdr')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.clk_src = get(xsg_obj,'clk_src');\ns.clk_rate = get(xsg_obj,'clk_rate');\n\ns.hw_qdr = get_param(blk_name,'which_qdr');\ns.use_sniffer = num2str(strcmp(get_param(blk_name, 'use_sniffer'), 'on')); \n\nswitch s.hw_sys\n case 'ROACH'\n s.addr_width = '22';\n s.data_width = '18';\n s.bw_width = '2';\n % end case 'ROACH'\n case 'ROACH2'\n s.addr_width = '21';\n s.data_width = '36';\n s.bw_width = '4';\n % end case 'ROACH2'\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend % end switch s.hw_sys\n\nb = class(s,'xps_qdr',blk_obj);\n\nb = set(b, 'opb0_devices', 2); %sniffer and controller\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_qdr/drc.m", "size": 2841, "source_encoding": "utf_8", "md5": "96d2b4430ebc40c4a816a430a40f7374", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\nresult = 0;\nmsg = '';\n\nfor i=1:length(xps_objs)\n\ttry\n\t\tif strcmp(get(blk_obj,'hw_qdr'),get(xps_objs{i},'hw_qdr'))\n\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\n\t\t\t\tmsg = ['QDR ',get(blk_obj,'simulink_name'),' and QDR ',get(xps_objs{i},'simulink_name'),' are located on the same port.'];\n\t\t\t\tresult = 1;\n\t\t\tend\n\t\tend\n\tend\nend\n\nif strcmp(get(blk_obj,'hw_sys'), 'ROACH')\n\tif ~(strcmp(get(blk_obj,'hw_qdr'),'qdr0') || strcmp(get(blk_obj,'hw_qdr'),'qdr1'))\n\t\tmsg = ['QDR ',get(blk_obj,'simulink_name'), ' is located on port ',get(blk_obj,'hw_qdr'),'. This is not possible on ROACH 1, which only has 2 QDR ports (qdr0 & qdr1)'];\n result = 1;\n end\nend\n\nif strcmp(get(blk_obj,'hw_sys'), 'ROACH2')\n\tif ~(strcmp(get(blk_obj,'hw_qdr'),'qdr0') || strcmp(get(blk_obj,'hw_qdr'),'qdr1') || strcmp(get(blk_obj,'hw_qdr'),'qdr2') || strcmp(get(blk_obj,'hw_qdr'),'qdr3'))\n\t\tmsg = ['QDR ',get(blk_obj,'simulink_name'), ' is located on port ',get(blk_obj,'hw_qdr'),'. This is not possible on ROACH 2, which only has 4 QDR ports (qdr0 & qdr1 & qdr2 & qdr3)'];\n result = 1;\n end\nend\n\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_qdr/set.m", "size": 1809, "source_encoding": "utf_8", "md5": "9375b55b323be80fbf3181e12deeeee1", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = set(b,field,value)\ntry\n eval(['b.',field,'=value;']);\ncatch\n b.xps_block = set(b.xps_block,field,value);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/get.m", "size": 2337, "source_encoding": "utf_8", "md5": "ef8fc67c8cfc98f94a3adb28629ee8c6", "text": "%GET Get KATCP object properties.\n%\n% V = GET(OBJ, PROPERTY) returns the value V of the specified property\n% PROPERTY for KATCP object OBJ.\n%\n% See also KATCP/SET\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction result = get(obj, field)\n\n try\n result = eval(['obj.', field]);\n catch\n error(['Unknown field for KATCP object: ', field]);\n end\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "read.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/read.m", "size": 8652, "source_encoding": "utf_8", "md5": "f94b2028a8846d63df2404c9289e06f3", "text": "%READ Read data stream from a device via KATCP.\n%\n% DATA = READ(KATCP_OBJ, IOREG) reads and returns the first word of data\n% from IOREG on a KATCP connection returns it as a HEX string.\n%\n% DATA = READ(KATCP_OBJ, IOREG, OFFSET) reads and returns a word of data\n% with an integer byte offset OFFSET.\n%\n% DATA = READ(KATCP_OBJ, IOREG, OFFSET, SIZE) reads and returns SIZE bytes\n% of data with an integer byte offset OFFSET. SIZE must be an integer\n% multiple of 4. The maximum supported read size is 262144 (2^18) bytes.\n%\n% DATA = READ(KATCP_OBJ, IOREG, OFFSET, SIZE, FORMAT) reads and returns SIZE\n% bytes of data with an integer byte offset OFFSET. SIZE must be an integer\n% multiple of 4 using a return output format specified by FORMAT:\n%\n% FORMAT RETURN TYPE\n% -------- -------------\n% 'ub' Unsigned Bytes (uint8)\n% 'uw' Unsigned Words (uint32)\n% 'hw' Hex Words (string)\n%\n% Example:\n% roach=katcp('myroach.domain.edu');\n% readback = read(roach, my_bram, 8, 256, 'ub');\n% would return a 256-element vector \"readback\" of uint8s that are\n% words 3-67 of \"my_bram.\"\n%\n% See also KATCP/WRITE, KATCP/WORDREAD, KATCP/WORDWRITE\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction data = read(obj, varargin)\n\n%tic;\n\n num_optargs = size(varargin, 2);\n\n MAX_READSIZE = 256*1024;\n\n\n %%% Process input arguments\n\n switch num_optargs\n\n case 1\n reg_name = varargin{1};\n read_offset = 0;\n read_size = 4;\n read_format = 'hw';\n % end case 1\n\n case 2\n reg_name = varargin{1};\n read_offset = varargin{2};\n read_size = 4;\n read_format = 'hw';\n % end case 2\n\n case 3\n reg_name = varargin{1};\n read_offset = varargin{2};\n read_size = varargin{3};\n read_format = 'hw';\n % end case 3\n\n case 4\n reg_name = varargin{1};\n read_offset = varargin{2};\n read_size = varargin{3};\n read_format = varargin{4};\n\n otherwise\n error('Read must have [read offset (bytes)] [read size (bytes)] [output format]');\n % end otherwise\n\n end % switch num_optargs\n\n if ( read_offset < 0 )\n disp('Read offset must be a positive integer.');\n data = [];\n return;\n end\n\n if ( mod(read_size, 4) ~= 0 || read_size < 1)\n disp('Read size must be a positive integer multiple of 4.');\n data = [];\n return;\n end\n\n if read_size > MAX_READSIZE\n disp(['Maximum supported read size is ', num2str(MAX_READSIZE), ' bytes.'])\n data = [];\n return;\n end\n\n%toc\n%disp('process arguments');\n\n%tic;\n\n %%% Send read command to KATCP\n\n cmd_string = ['?read ', reg_name, ' ', num2str(read_offset), ' ', num2str(read_size)];\n% disp(cmd_string);\n\n fwrite(obj.tcpip_obj, uint8(cmd_string));\n fprintf(obj.tcpip_obj, '');\n\n%toc\n%disp('send command')\n%\n%tic;\n\n while 1\n bytes_available = get(obj.tcpip_obj, 'BytesAvailable');\n\n pause(0.05);\n\n if ( bytes_available ~= get(obj.tcpip_obj, 'BytesAvailable') || bytes_available < 1 )\n continue;\n else\n break;\n end\n end\n\n%toc\n%disp('wait for bytes')\n%\n%tic;\n\n readback = '';\n\n readback = transpose(fread(obj.tcpip_obj, get(obj.tcpip_obj, 'BytesAvailable')));\n\n if ~strcmp( char(readback(1:9)), '!read ok ')\n\n %error(char(readback));\n toks = regexp(char(readback), '(.*)!read(\\s+)(.*)', 'tokens');\n\n if ~isempty(toks)\n error(toks{1}{3});\n end\n\n end % if ~strcmp( char(readback(1:9)), '!read ok ')\n\n readback = readback(10:end-1);\n\n%toc\n%disp('read from buffer')\n\n%tic;\n\n %%% De-escape data stream.\n % CAN THIS BE MADE MORE EFFICIENT??\n % Pre-allocating result vector gives major speedup. Others?\n\n data = zeros(1,read_size);\n m = 1;\n\n for n=1:length(readback)\n\n switch readback(n)\n\n case -1 % should only be artificially inserted by de-escaper\n continue;\n\n case 92 % escape character '\\'\n\n switch readback(n+1)\n\n case 48 % 0x30; '0'\n readback(n+1) = uint8(0);\n\n case 92 % 0x5C; '\\'\n %data = [data, uint8(92)];\n data(m) = uint8(92);\n m = m+1;\n readback(n+1) = -1;\n\n case 95 % 0x5F; '_'\n readback(n+1) = uint8(32);\n\n case 101 % 0x65; 'e'\n readback(n+1) = uint8(27);\n\n case 110 % 0x6E; 'n'\n readback(n+1) = uint8(10);\n\n case 114 % 0x72; 'r'\n readback(n+1) = uint8(13);\n\n case 116 %0x74; 't'\n readback(n+1) = uint8(9);\n\n end % switch char(readback(n+1))\n\n continue;\n\n % end case 92\n\n otherwise\n %data = [data, readback(n)];\n data(m) = readback(n);\n m = m+1;\n\n end % switch char(readback(n))\n\n end % for n=1:length(readback)\n\n readback = data;\n\n%toc\n%disp('de-escape')\n\n\n%tic\n\n %%% Get into output radix/format\n\n switch read_format\n\n case 'ub'\n data = readback;\n % end case 'ub'\n\n case 'uw'\n\n data = zeros(1,read_size/4);\n m = 1;\n\n for n=1:4:length(readback)\n data(m) = (uint32(readback(n)) * 2^24 + ...\n uint32(readback(n+1)) * 2^16 + ...\n uint32(readback(n+2)) * 2^8 + ...\n uint32(readback(n+3)) * 2^0);\n\n m = m+1;\n end\n % end case 'uw'\n\n case 'hw'\n\n data = cell(1,read_size/4);\n m = 1;\n\n for n=1:4:length(readback)\n data(m) = {dec2hex(( ...\n uint32(readback(n)) * 2^24 + ...\n uint32(readback(n+1)) * 2^16 + ...\n uint32(readback(n+2)) * 2^8 + ...\n uint32(readback(n+3)) * 2^0), ...\n 8)};\n\n m = m+1;\n end\n % end case 'hw'\n\n otherwise\n disp(['Unsupported format: ', read_format]);\n data = readback;\n\n end % switch read_format\n\n%toc\n%disp('output formatting')\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "wordread.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/wordread.m", "size": 2998, "source_encoding": "utf_8", "md5": "7a266a8d514a23136513dbb3ee31c8e4", "text": "%WORDREAD Read a single word from a device via KATCP.\n%\n% [WORD, STATUS] = WORDREAD(OBJ, IOREG) peforms a single-word read from\n% IOREG on a KATCP connection.\n%\n% See also KATCP/HELP, KATCP/WORDWRITE, KATCP/READ, KATCP/WRITE\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [word, status] = wordread(obj, varargin)\n\n% num_optargs = size(varargin, 2);\n\n try\n reg_name = varargin{1};\n catch\n error('Read must have .');\n end\n\n try\n read_offset = num2str(varargin{2});\n catch\n read_offset = '0';\n end\n\n cmd_string = ['?wordread ', reg_name, ' ', read_offset];\n% disp(cmd_string);\n\n fprintf(obj.tcpip_obj, cmd_string);\n pause(0.1);\n\n rb = '';\n status = '';\n word = 0;\n\n while (get(obj.tcpip_obj, 'BytesAvailable') > 0)\n rb = [rb, fscanf(obj.tcpip_obj)];\n end\n\n status = rb(1:13);\n% disp(status);\n\n if ~strcmp('!wordread ok ', status)\n status = rb;\n return;\n end\n\n word = dec2hex(hex2dec(rb(16:end-1)),8);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "tapstart.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/tapstart.m", "size": 4303, "source_encoding": "utf_8", "md5": "d40b14d9d12ac0388c8c0bbc61467f46", "text": "%TAPSTART Program a 10GbE device and start the TAP driver.\r\n%\r\n% TAPSTART(KATCP_OBJ, DEVICE, MAC, IP, PORT) requests that the KATCP\r\n% configures a 10GbE device with the following parameters:\r\n%\r\n% DEVICE: name of the device (string)\r\n% MAC: MAC address to set (string of 6 colon-delimited hex bytes)\r\n% IP: IP address to set (string of 4 period-delimited integer bytes)\r\n% PORT: Fabric port number (integer up to 16 bits)\r\n%\r\n% Example:\r\n% roach = katcp('myroach.domain.edu');\r\n% tapstart(roach, 'gbe0', '00:1A:2B:3C:4D:5E', '10.0.0.21', 12345);\r\n%\r\n% See also KATCP/HELP\r\n%\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% %\r\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\r\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\r\n% %\r\n% Copyright (C) 2010 University of California %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction varargout = tapstart(obj, dev_name, mac_addr, ip_addr, port_num)\r\n\r\n if isempty(regexp(mac_addr, '00:[0-9a-f_A-F]{2,2}:[0-9a-f_A-F]{2,2}:[0-9a-f_A-F]{2,2}:[0-9a-f_A-F]{2,2}:[0-9a-f_A-F]{2,2}'))\r\n\r\n if ~strcmp(mac_addr(1:2), '00')\r\n disp('First octet of MAC address must be 00');\r\n return;\r\n end\r\n\r\n disp('Invalid MAC address format.');\r\n return;\r\n\r\n end\r\n\r\n if isempty(regexp(ip_addr, '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'))\r\n\r\n disp('Invalid IP address format.');\r\n return;\r\n\r\n end\r\n\r\n if (port_num < 0) || (port_num > 65535)\r\n\r\n disp('Invalid port number.');\r\n return;\r\n\r\n end\r\n\r\n fprintf(obj.tcpip_obj,['?tap-start ', dev_name, ' ', mac_addr, ' ', ip_addr, ' ', num2str(port_num)]);\r\n\r\n while 1\r\n\r\n bytes_available = get(obj.tcpip_obj, 'BytesAvailable');\r\n\r\n pause(0.001);\r\n\r\n if ( bytes_available ~= get(obj.tcpip_obj, 'BytesAvailable') || bytes_available < 1 )\r\n continue;\r\n else\r\n msg = [msg, transpose(fread(obj.tcpip_obj, get(obj.tcpip_obj, 'BytesAvailable')))];\r\n if isempty(strfind(char(msg), '!tap-start'))\r\n continue;\r\n else\r\n break;\r\n end\r\n end % if ( bytes_available ~= get(obj.tcpip_obj, 'BytesAvailable') || bytes_available < 1 )\r\n\r\n end % while 1\r\n\r\n if (get(obj.tcpip_obj, 'BytesAvailable') > 0)\r\n msg = [msg, fread(obj.tcpip_obj, get(obj.tcpip_obj, 'BytesAvailable'))];\r\n end\r\n\r\n msg = char(msg);\r\n msg = regexprep(msg, '\\\\\\_', ' ');\r\n\r\n disp(msg);\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "status.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/status.m", "size": 2701, "source_encoding": "utf_8", "md5": "ba2169074daa9576a764a153dbe6f9c9", "text": "%STATUS Displays the status of the KATCP server.\n%\n% STATUS(KATCP_OBJ) prints the status of the KATCP server to the Matlab\n% command window.\n%\n% MESSAGE = STATUS(KATCP_OBJ) returns the status message as a character\n% string.\n%\n% See also KATCP/HELP, KATCP/LISTBOF, KATCP/LISTCMD, KATCP/LISTDEV\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction varargout = status(obj)\n\n fprintf(obj.tcpip_obj, ' ?status');\n pause(0.1);\n\n msg = '';\n\n while (get(obj.tcpip_obj, 'BytesAvailable') > 0)\n msg = [msg, fscanf(obj.tcpip_obj)];\n end\n\n switch nargout\n\n case 0\n disp(msg);\n\n case 1\n varargout(1) = {msg};\n\n otherwise\n disp(msg);\n\n end % switch nargout\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "katcp.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/katcp.m", "size": 3978, "source_encoding": "utf_8", "md5": "22cd9b865ca718e428d99fc93cea70fe", "text": "%KATCP Construct a KATCP-class object.\n%\n% KATCP_OBJ = KATCP('RHOST') constructs a KATCP object KATCP_OBJ, that\n% opens and represents the connection to a remote host RHOST running a\n% KATCP server on port 7147.\n%\n% Example:\n% roach = katcp('myroach.domain.edu');\n%\n% [KATCP_OBJ, MESSAGE] = KATCP('RHOST') returns the status message response\n% to the connection attempt from the KATCP server.\n%\n% See also KATCP/HELP, KATCP/LISTBOF, KATCP/LISTCMD, KATCP/LISTDEV,\n% KATCP/STATUS, KATCP/CLOSE, KATCP/READ, KATCP/WRITE, KATCP/WORDREAD,\n% KATCP/WORDWRITE\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [katcp_obj, varargout] = katcp(rhost, varargin)\n\n tcpip_obj = tcpip(rhost, 7147);\n\n set(tcpip_obj, 'OutputBufferSize', 524288); % Increase TCP/IP output buffer size to 512KB (from 512B default)\n set(tcpip_obj, 'InputBufferSize', 524288); % Increase TCP/IP input buffer size to 512KB (from 512B default)\n\n try\n fopen(tcpip_obj);\n catch\n error(['Unable to open connection to remote host ', rhost, ' on port 7147.']);\n end % try\n\n pause(0.25);\n\n fprintf(tcpip_obj, '\\n\\n');\n\n pause(0.25);\n\n msg = '';\n\n timeout = 2^15;\n\n while timeout > 0\n\n pause(0.01);\n\n try\n msg = [msg, transpose(fread(tcpip_obj, get(tcpip_obj, 'BytesAvailable')))];\n catch\n end\n\n % wait for BORPH server to return OK status message\n if ~isempty(strfind(msg, '#log')) && ~isempty(strfind(msg, 'new\\_connection\\_'))\n break;\n else\n timeout = timeout-1;\n end % if ~isempty(strfind(out, '#log')) && ~isempty(strfind(out, 'new\\_connection\\_'))\n\n end % while timeout > 0\n\n if (timeout == 0)\n error(['KATCP connection to host ', rhost, ' timed out.'])\n end\n\n if (nargout == 2)\n varargout(1) = {msg};\n end\n\n disp(['Connection established to board ', rhost]);\n\n s.tcpip_obj = tcpip_obj;\n s.hostname = rhost;\n\n katcp_obj = class(s, 'katcp');\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "close.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/close.m", "size": 2790, "source_encoding": "utf_8", "md5": "a008e1d8ed2425bb6bad167e01230a16", "text": "%CLOSE Closes connection to KATCP server.\n%\n% CLOSE(KATCP_OBJ) closes the TCP/IP connection to the KATCP server.\n%\n% STATUS = CLOSE(KATCP_OBJ) returns 0 if the connection was\n% successfully closed, and -1 if an error occurred.\n%\n% See also KATCP/KATCP, KATCP/HELP, KATCP/LISTBOF, KATCP/LISTDEV,\n% KATCP/STATUS\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nfunction varargout = close(obj)\n\n status = 0;\n\n disp(['Trying to close KATCP connection to ', obj.hostname, '...']);\n\n try\n fclose(obj.tcpip_obj);\n delete(obj.tcpip_obj);\n catch\n status = -1;\n error(['Error trying to close KATCP connection to ', obj.hostname, '.']);\n end\n\n disp(['Connection to ', obj.hostname, ' closed.']);\n\n results = [{status}];\n\n for n=1:nargout\n varargout = results(n);\n end\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "listdev.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/listdev.m", "size": 4240, "source_encoding": "utf_8", "md5": "043045a3046629724641b311dbd9b7aa", "text": "%LISTDEV List devices available on KATCP BORPH process.\n%\n% LISTDEV(KATCP_OBJ) queries the remote host associated with the KATCP_OBJ\n% KATCP object for a list of available device registers in the running BOF\n% process. The list is printed to the Matlab command window.\n%\n% DEVS = LISTDEV(KATCP_OBJ) returns a cell array DEVS in which each cell in\n% the array contains a character string with the filename of a shared-memory\n% device for the process.\n%\n% DEVS = LISTDEV(KATCP_OBJ, 'verbose') Can be used to print the list to the\n% Matlab command window along with the returned cell array.\n%\n% See also KATCP/HELP, KATCP/LISTBOF, KATCP/LISTCMD\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction varargout = listdev(obj, varargin)\n\n fprintf(obj.tcpip_obj, '?listdev');\n pause(0.1);\n\n msg = '';\n\n timeout = 2^10;\n\n while timeout > 0\n\n pause(0.01);\n\n while (get(obj.tcpip_obj, 'BytesAvailable') > 0)\n msg = [msg, fscanf(obj.tcpip_obj)];\n end\n\n % wait for BORPH server to return OK status message\n if ~isempty(strfind(msg, '!listdev ok'))\n break;\n else\n timeout = timeout-1;\n end % if ~isempty(strfind(out, '!listbof ok')\n\n if ~isempty(strfind(msg, '!listdev fail'))\n errmsg = msg(strfind(msg, '!listdev fail'):end);\n warning(['listdev failed to remote host ', get(obj.tcpip_obj, 'RemoteHost'), ': ', errmsg]);\n return;\n end\n\n end % while timeout > 0\n\n if (timeout == 0)\n error(['KATCP connection to host ', get(obj.tcpip_obj, 'RemoteHost') , ' timed out.'])\n end\n\n msg = msg(1:strfind(msg, '!listdev ok')-1);\n\n switch nargout\n\n case 0 % just print out the list\n disp(msg);\n\n case 1 % return a cell array of strings\n devs = {};\n\n toks = regexp(msg, '#listdev (\\w+)', 'tokens');\n\n for n=1:length(toks)\n devs= [devs, toks{n}{1}];\n end\n\n varargout(1) = {devs};\n\n % if verbose, print out the list as well\n if ( (nargin == 2) && (strcmpi(varargin(1), 'verbose')) )\n disp(msg);\n end\n\n otherwise\n disp(msg);\n\n end % switch nargout\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "progdev.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/progdev.m", "size": 4287, "source_encoding": "utf_8", "md5": "e7a85bb7485338070f7fa5ca7ac0a17c", "text": "%PROGDEV Execute BOF on KATCP server.\n%\n% PROGDEV(KATCP_OBJ, 'BOFFILE') requests that the KATCP server try to\n% program its FPGA device with the BORPH executable 'BOFFILE'.\n%\n% Example:\n% roach=katcp('myroach.domain.edu');\n% progdev(roach, 'my_borph_file.bof');\n%\n% The specified .BOF file must be available to the TCPBORPHSERVER as\n% viewable through KATCP/LISTBOF.\n%\n% PROGDEV will print an abbreviated status response to the Matlab command\n% window:\n%\n% '!progdev ok' or '!progdev fail'\n%\n% This output can be suppressed by calling PROGDEV with the 'quiet' option:\n% PROGDEV(KATCP_OBJ, 'BOFFILE', 'quiet')\n%\n% STATUS = PROGDEV(KATCP_OBJ, 'BOFFILE') returns 0 if device programming\n% was successful, and -1 if an error occurred.\n%\n% [STATUS, MESSAGE] = PROGDEV(KATCP_OBJ, 'BOFFILE') returns the full KATCP\n% response message to the command request.\n%\n% See also KATCP/HELP, KATCP/LISTBOF, KATCP/LISTDEV\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction varargout = progdev(obj, boffile, varargin)\n\n status = 0;\n msg = '';\n\n fprintf(obj.tcpip_obj, ['?progdev ', boffile]);\n\n while 1\n\n bytes_available = get(obj.tcpip_obj, 'BytesAvailable');\n\n pause(0.001);\n\n if ( bytes_available ~= get(obj.tcpip_obj, 'BytesAvailable') || bytes_available < 1 )\n continue;\n else\n msg = [msg, transpose(fread(obj.tcpip_obj, get(obj.tcpip_obj, 'BytesAvailable')))];\n if isempty(strfind(char(msg), '!progdev'))\n continue;\n else\n break;\n end\n end % if ( bytes_available ~= get(obj.tcpip_obj, 'BytesAvailable') || bytes_available < 1 )\n\n end % while 1\n\n if (get(obj.tcpip_obj, 'BytesAvailable') > 0)\n msg = [msg, fread(obj.tcpip_obj, get(obj.tcpip_obj, 'BytesAvailable'))];\n end\n\n msg = char(msg);\n msg = regexprep(msg, '\\\\\\_', ' ');\n\n quiet = ((nargin==3) && (strcmpi(varargin(1), 'quiet')));\n\n if ~isempty(strfind(msg, '!progdev fail'))\n status = -1;\n\n if ~quiet\n disp('!progdev fail');\n end\n else\n status = 0;\n\n if ~quiet\n disp('!progdev ok');\n end\n end\n\n results = [{status}, {msg}];\n\n for n=1:nargout\n varargout(n) = results(n);\n end\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "listcmd.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/listcmd.m", "size": 2376, "source_encoding": "utf_8", "md5": "fe392a6b36bf19d4ec9a18a7e9aa4414", "text": "%LISTCMD List commands available on KATCP BORPH process.\n%\n% COMMANDS = LISTCMD(OBJ)\n%\n% See also KATCP/HELP, KATCP/LISTBOF, KATCP/LISTDEV\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction cmds = listdev(obj)\n\n fprintf(obj.tcpip_obj, '?listcmd');\n pause(0.1);\n\n cmds = '';\n\n while (get(obj.tcpip_obj, 'BytesAvailable') > 0)\n cmds = [cmds, fscanf(obj.tcpip_obj)];\n end\n\n disp(cmds);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/set.m", "size": 2035, "source_encoding": "utf_8", "md5": "24a2bdcc9219be6f69fa4aa4e04f1cea", "text": "%SET Set KATCP object properties.\n%\n% SET(OBJ, 'PropertyName', PropertyValue) sets the value V of the specified\n% property for a KATCP object.\n%\n% See also KATCP/GET\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction obj = set(obj, field, value)\n\n try\n eval(['obj.',field,'=value;']);\n catch\n error(['Attempt to set field ', field, ' of object failed.']);\n end\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "clearbuffer.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/clearbuffer.m", "size": 2336, "source_encoding": "utf_8", "md5": "8f870f95841bbe474084b6e33b06c951", "text": "%CLEARBUFFER Clears the KATCP TCP/IP input buffer.\n%\n% CLEARBUFFER(OBJ) empties the TCP/IP input buffer of a KATCP\n% connection in the event that a previous action failed and left\n% data in the buffer.\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction clearbuffer(obj)\n\n try\n fread(obj.tcpip_obj, get(obj.tcpip_obj, 'BytesAvailable'));\n catch\n end\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "write.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/write.m", "size": 9135, "source_encoding": "utf_8", "md5": "56afa4addd55de1ad1119bc6ec9f89df", "text": "%WRITE Write data stream to device via KATCP.\n%\n% WRITE(KATCP_OBJ, IOREG, DATA) writes a vector DATA of unsigned bytes\n% (uint8) to IOREG starting at the first byte in its memory space. DATA\n% must have a length that is an integer multiple of 4.\n%\n% WRITE(KATCP_OBJ, IOREG, OFFSET, DATA) writes a vector DATA of unsigned\n% bytes (uint8) to IOREG with an integer byte offset of OFFSET. DATA must\n% have a length that is an integer multiple of 4.\n%\n% WRITE(KATCP_OBJ, IOREG, FORMAT, OFFSET, DATA) writes a vector DATA to\n% IOREG with an integer byte offset of OFFSET. DATA must have a length that\n% is an integer multiple of 4. The data type of DATA is specified by FORMAT:\n%\n% FORMAT DATA TYPE\n% -------- -----------\n% 'ub' Unsigned Bytes (uint8)\n% 'uw' Unsigned Words (uint32)\n% 'hw' Hex Words (string)\n%\n% Example:\n% roach=katcp('myroach.domain.edu');\n% write(roach, my_bram, 'ub', 8, uint8([0:255]));\n% would write a 256-element vector of uint8s to words 3-67 of\n% \"my_bram.\"\n\n% See also KATCP/READ, KATCP/WORDREAD, KATCP/WORDWRITE\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction varargout = write(obj, reg_name, varargin)\n\n num_optargs = size(varargin, 2);\n\n MAX_WRITESIZE = 256*1024;\n\n status = 0;\n message = '';\n\n\n %%% Process input arguments\n\n%tic;\n switch num_optargs\n\n case 1\n write_offset = 0;\n write_data = varargin{1};\n write_format = 'ub';\n % end case 1\n\n case 2\n write_offset = varargin{1};\n write_data = varargin{2};\n write_format = 'ub';\n % end case 2\n\n case 3\n write_offset = varargin{1};\n write_data = varargin{2};\n write_format = varargin{3};\n\n otherwise\n error('Write must have [data format] [write offset (bytes)] ');\n % end otherwise\n\n end % switch num_optargs\n\n if ( write_offset < 0 )\n disp('Write offset must be a positive integer.');\n status = -1;\n message = 'Invalid write offset.'\n return;\n end\n\n switch write_format\n case 'ub'\n INPUT_MOD = 4;\n case 'uw'\n INPUT_MOD = 1;\n case 'hw'\n INPUT_MOD = 1;\n otherwise\n INPUT_MOD = 4;\n end % switch write_format\n\n data_size = length(write_data);\n\n if mod(data_size, INPUT_MOD) ~= 0\n disp(['Data vector must be a multiple of 4 bytes']);\n status = -1;\n message = 'Invalid data vector length';\n return;\n end\n\n if ( (data_size*4/INPUT_MOD > MAX_WRITESIZE) || (data_size < 1) )\n disp(['Maximum data vector size is ', num2str(MAX_WRITESIZE), ' bytes.'])\n status = -1;\n message = 'Invalid data vector length.';\n return;\n end\n%toc;\n%disp('process input arguments');\n\n\n %%% Get into input radix/format\n\n%tic;\n switch write_format\n\n case 'ub'\n data = uint8(write_data);\n % end case 'ub'\n\n case 'uw'\n\n data = zeros(1, data_size*4);\n m = 1;\n\n for n=1:data_size\n\n word = write_data(n);\n\n data(m:m+3) = [uint8(mod(floor(word/2^24), 2^8)), ...\n uint8(mod(floor(word/2^16), 2^8)), ...\n uint8(mod(floor(word/2^8 ), 2^8)), ...\n uint8(mod(floor(word/2^0 ), 2^8))];\n\n m = m + 4;\n\n end % for n=1:length(write_data);\n\n % end case 'uw'\n\n case 'hw'\n\n data = zeros(1, data_size*4);\n m = 1;\n\n for n=1:data_size\n\n word = write_data{n};\n\n data(m:m+3) = [uint8(hex2dec(word(1:2))), ...\n uint8(hex2dec(word(3:4))), ...\n uint8(hex2dec(word(5:6))), ...\n uint8(hex2dec(word(7:8)))];\n\n m = m + 4;\n\n end % for n=1:length(write_data)\n\n % end case 'hw'\n\n otherwise\n disp(['Unsupported format: ', write_format]);\n return;\n\n end % switch read_format\n%toc;\n%disp('reformat input vector');\n\n %%% Escape data stream\n % CAN THIS BE MADE MORE EFFICIENT?\n\n%tic;\n vector_size = 0;\n\n for n=1:data_size\n\n switch data(n)\n\n case 9 % corresponds to TAB (^I) -> escape as \\t\n vector_size = vector_size + 2;\n\n case 10 % corresponds to LF (^J) -> escape as \\n\n vector_size = vector_size + 2;\n\n case 13 % corresponds to CR (^M) -> escape as \\r\n vector_size = vector_size + 2;\n\n case 32 % corresonds to SPACE ( ) -> escape as \\_\n vector_size = vector_size + 2;\n\n case 92 % corresponds to \\ -> escape as \\\\\n vector_size = vector_size + 2;\n\n otherwise\n vector_size = vector_size + 1;\n\n end % switch data(n)\n\n end % for n=1:data_size\n\n write_vector = zeros(1, vector_size);\n m = 1;\n\n for n=1:data_size\n\n switch data(n)\n\n case 9 % corresponds to TAB (^I) -> escape as \\t\n write_vector(m:m+1) = [uint8(92), uint8(9)];\n m = m + 2;\n\n case 10 % corresponds to LF (^J) -> escape as \\n\n write_vector(m:m+1) = [uint8(92), uint8(110)];\n m = m + 2;\n\n case 13 % corresponds to CR (^M) -> escape as \\r\n write_vector(m:m+1) = [uint8(92), uint8(114)];\n m = m + 2;\n\n case 32 % corresonds to SPACE ( ) -> escape as \\_\n write_vector(m:m+1) = [uint8(92), uint8(95)];\n m = m + 2;\n\n case 92 % corresponds to \\ -> escape as \\\\\n write_vector(m:m+1) = [uint8(92), uint8(92)];\n m = m + 2;\n\n otherwise\n write_vector(m) = data(n);\n m = m + 1;\n\n end % switch data(n)\n\n end % for n=1:data_size\n%toc;\n%disp('escape characters in vector');\n\n %%% Send read command to KATCP\n\n cmd_string = ['?write ', reg_name, ' ', num2str(write_offset), ' ', write_vector];\n% disp(cmd_string);\n\n%tic;\n% fwrite(obj.tcpip_obj, uint8(cmd_string));\n% fprintf(obj.tcpip_obj, '');\n%toc;\n%disp('send command/data');\n%\n%tic;\n while 1\n pause(0.001);\n\n bytes_available = get(obj.tcpip_obj, 'BytesAvailable');\n\n if ( bytes_available ~= get(obj.tcpip_obj, 'BytesAvailable') || bytes_available < 1 )\n continue;\n else\n break;\n end\n end\n%toc;\n%disp('wait for response');\n\n readback = '';\n\n readback = transpose(fread(obj.tcpip_obj, get(obj.tcpip_obj, 'BytesAvailable')));\n% disp(char(readback));\n\n if ~strcmp( char(readback(1:10)), '!write ok ')\n\n %error(char(readback));\n toks = regexp(char(readback), '(.*)!read(\\s+)(.*)', 'tokens');\n\n if ~isempty(toks)\n error(toks{1}{3});\n end\n\n end % if ~strcmp( char(readback(1:9)), '!write ok ')\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "listbof.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/listbof.m", "size": 4196, "source_encoding": "utf_8", "md5": "d913635a3027f01258a3152b059466e7", "text": "%LISTBOF List BOF files available on KATCP BORPH process.\n%\n% LISTBOF(KATCP_OBJ) queries the remote host associated with the KATCP_OBJ\n% KATCP object for a list of available BOF files. The list is printed to\n% the Matlab command window.\n%\n% BOFFILES = LISTBOF(KATCP_OBJ) returns a cell array BOFFILES in which each\n% cell in the array contains a character string with the filename of a BOF\n% file.\n%\n% BOFFILES = LISTBOF(KATCP_OBJ, 'verbose') Can be used to print the list to\n% the Matlab command window along with the returned cell array.\n%\n% See also KATCP/HELP, KATCP/LISTCMD, KATCP/LISTDEV\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction varargout = listbof(obj, varargin)\n\n fprintf(obj.tcpip_obj, '?listbof');\n pause(0.1);\n\n msg = '';\n\n timeout = 2^10;\n\n while timeout > 0\n\n pause(0.01);\n\n while (get(obj.tcpip_obj, 'BytesAvailable') > 0)\n msg = [msg, fscanf(obj.tcpip_obj)];\n end\n\n % wait for BORPH server to return OK status message\n if ~isempty(strfind(msg, '!listbof ok'))\n break;\n else\n timeout = timeout-1;\n end % if ~isempty(strfind(out, '!listbof ok')\n\n if ~isempty(strfind(msg, '!listbof fail'))\n errmsg = msg(strfind(msg, '!listbof fail'):end);\n warning(['listbof failed to remote host ', get(obj.tcpip_obj, 'RemoteHost'), ': ', errmsg]);\n return;\n end\n\n end % while timeout > 0\n\n if (timeout == 0)\n error(['KATCP connection to host ', get(obj.tcpip_obj, 'RemoteHost') , ' timed out.'])\n end\n\n msg = msg(1:strfind(msg, '!listbof ok')-1);\n\n switch nargout\n\n case 0 % just print out the list\n disp(msg);\n\n case 1 % return a cell array of strings\n bofs = {};\n\n toks = regexp(msg, '#listbof (\\w+.bof)', 'tokens');\n\n for n=1:length(toks)\n bofs = [bofs, toks{n}{1}];\n end\n\n varargout(1) = {bofs};\n\n % if verbose, print out the list as well\n if ( (nargin == 2) && (strcmpi(varargin(1), 'verbose')) )\n disp(msg);\n end\n\n otherwise\n disp(msg);\n\n end % switch nargout\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "help.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/help.m", "size": 3756, "source_encoding": "utf_8", "md5": "19a413f41e0cbac74394442630d5fb4a", "text": "%HELP Displays HELP from KATCP server.\n%\n% HELP(KATCP_OBJ) displays a list of KATCP commands available to the KATCP\n% server that the KATCP object is connected to. Some of the commands listed\n% may not be implemented or supported by KATCP member functions.\n%\n% See also KATCP/LISTBOF, KATCP/LISTCMD, KATCP/LISTDEV, KATCP/STATUS\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction help(obj)\n\n fprintf(obj.tcpip_obj, '?help');\n pause(0.1);\n\n msg = '';\n\n timeout = 2^10;\n\n while timeout > 0\n\n pause(0.01);\n\n while (get(obj.tcpip_obj, 'BytesAvailable') > 0)\n msg = [msg, fscanf(obj.tcpip_obj)];\n end\n\n % wait for BORPH server to return OK status message\n if ~isempty(strfind(msg, '!help ok'))\n break;\n else\n timeout = timeout-1;\n end % if ~isempty(strfind(out, '!listbof ok')\n\n if ~isempty(strfind(msg, '!help fail'))\n errmsg = msg(strfind(msg, '!listdev fail'):end);\n warning(['listdev failed to remote host ', get(obj.tcpip_obj, 'RemoteHost'), ': ', errmsg]);\n return;\n end\n\n end % while timeout > 0\n\n msg = msg(1:strfind(msg, '!help ok')-1);\n\n toks = regexp(msg, '#help (\\S+) (\\S+)\\n', 'tokens');\n\n helpmsg = '';\n\n % finds length of longest command string\n maxcmdlen = 0;\n for n=1:length(toks)\n maxcmdlen = max(maxcmdlen, length(toks{n}{1}));\n end\n\n for n=1:length(toks)\n\n % adds spaces to match length of longest command string\n padding = ' ';\n for m=1:(maxcmdlen-length(toks{n}{1}))\n padding = [padding, ' '];\n end\n\n cmd = toks{n}{1};\n desc = regexprep(toks{n}{2}, '\\\\\\_', ' ');\n\n disp([cmd, padding, desc]);\n\n end % for n=1:length(toks)\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "wordwrite.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@katcp/wordwrite.m", "size": 3088, "source_encoding": "utf_8", "md5": "188ed4d039e5296c114806582cc7c414", "text": "%WORDWRITE Write a single word to a device via KATCP.\n%\n% STATUS = WORDWRITE(OBJ, IOREG, WORD) writes a single word WORD to\n% IOREG on a KATCP connection.\n%\n% See also KATCP/HELP, KATCP/WORDREAD, KATCP/READ, KATCP/WRITE\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% %\n% Parallel Data Architectures Group, UCLA Electrical Engineering %\n% http://icslwebs.ee.ucla.edu/dejan/researchwiki/index.php/Main_Page %\n% %\n% Copyright (C) 2010 University of California %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction status = wordwrite(obj, varargin)\n\n try\n reg_name = varargin{1};\n catch\n error('Write must have .');\n end\n\n try\n write_word = num2str(varargin{3});\n write_offset = num2str(varargin{2});\n catch\n try\n write_word = num2str(varargin{2});\n write_offset = '0';\n catch\n error('Missing value to write.');\n end\n end\n\n cmd_string = ['?wordwrite ', reg_name, ' ', write_offset, ' ', write_word];\n% disp(cmd_string);\n\n fprintf(obj.tcpip_obj, cmd_string);\n pause(0.1);\n\n rb = '';\n status = '';\n\n while (get(obj.tcpip_obj, 'BytesAvailable') > 0)\n rb = [rb, fscanf(obj.tcpip_obj)];\n end\n\n status = rb(1:14);\n\n% disp(status);\n if ~strcmp('!wordwrite ok ', status)\n status = rb;\n return;\n end\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_sw_reg/get.m", "size": 1965, "source_encoding": "utf_8", "md5": "e4447d00c910af45efa20e63d8451e64", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknown to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_sw_reg/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_sw_reg.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_sw_reg/xps_sw_reg.m", "size": 3055, "source_encoding": "utf_8", "md5": "7e0fe1e3dadee209aa6831b4253b5699", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_sw_register(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_SW_REG class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_sw_reg')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\ns.hw_sys = 'any';\n\nswitch get_param(blk_name,'io_dir')\n case 'From Processor'\n s.io_dir = 'in';\n case 'To Processor'\n s.io_dir = 'out';\nend\nb = class(s,'xps_sw_reg',blk_obj);\n\n% ip name\nswitch get_param(blk_name,'io_dir')\n case 'From Processor'\n\t\tb = set(b,'ip_name','opb_register_ppc2simulink');\n case 'To Processor'\n\t\tb = set(b,'ip_name','opb_register_simulink2ppc');\nend\n\n% bus clock\nswitch get(xsg_obj,'hw_sys')\n case {'ROACH', 'ROACH2', 'MKDIG'}\n b = set(b, 'opb_clk','epb_clk');\n otherwise\n b = set(b, 'opb_clk','sys_clk');\nend % switch get(xsg_obj,'hw_sys')\n\n% bus offset\nb = set(b,'opb_address_offset',256);\n\n% misc ports\nmisc_ports.user_clk = {1 'in' get(xsg_obj,'clk_src')};\nb = set(b,'misc_ports',misc_ports);\n\n% software parameters\nb = set(b,'c_params',s.io_dir);\n\n% borf parameters\nswitch get_param(blk_name,'io_dir')\n case 'From Processor'\n borph_info.mode = 3;\n case 'To Processor'\n borph_info.mode = 1;\nend\n\nborph_info.size = 4;\nb = set(b,'borph_info',borph_info);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_bram/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mss.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_bram/gen_mss.m", "size": 2015, "source_encoding": "utf_8", "md5": "fd6d4b707721d9aebb44d33dc9926305", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction str = gen_mss(blk_obj)\r\nstr = '';\r\n\r\ninst_name = clear_name(get(blk_obj,'simulink_name'));\r\n\r\nstr = [str,'BEGIN DRIVER\\n'];\r\nstr = [str,' PARAMETER DRIVER_NAME = bram\\n'];\r\nstr = [str,' PARAMETER DRIVER_VER = 1.00.a\\n'];\r\nstr = [str,' PARAMETER HW_INSTANCE = ',inst_name,'\\n'];\r\nstr = [str,'END\\n'];\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_bram.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_bram/xps_bram.m", "size": 3408, "source_encoding": "utf_8", "md5": "4bd7a74b6b8556b7e8f87d7c0ff99dd9", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_bram(blk_obj)\nif ~isa(blk_obj,'xps_block')\n error('XPS_GPIO class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_bram')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\ns.hw_sys = 'any';\ns.addr_width = eval_param(blk_name,'addr_width');\ns.data_width = str2num(get_param(blk_name,'data_width'));\n\n% Set s.optimation to default value, then try to set it\n% from block parameters. Old blocks may not have this parameter.\ns.optimization = 'Minimum_Area';\ntry\n s.optimization = get_param(blk_name,'optimization');\ncatch\n % Issue warning that use might want to update links\n warning('Shared BRAM block \"%s\" is out of date (needs its link restored)', blk_name);\nend\n\n% Old blocks may not have this parameter, start with default value.\ns.reg_core_output = 'false';\ntry\n if strcmpi(get_param(blk_name,'reg_core_output'), 'on')\n s.reg_core_output = 'true';\n end\nend\n\n% Old blocks may not have this parameter, start with default value.\ns.reg_prim_output = 'false';\ntry\n if strcmpi(get_param(blk_name,'reg_prim_output'), 'on')\n s.reg_prim_output = 'true';\n end\nend\n\nb = class(s,'xps_bram',blk_obj);\n\n% ip name\nb = set(b,'ip_name','bram_if');\n\n% software driver\nb = set(b,'soft_driver',{'bram' '1.00.a'});\n\n% address offset\nb = set(b,'opb_address_offset',s.data_width/8*(2^s.addr_width));\n\n% address alignment \nb = set(b,'opb_address_align',(32/8) * 2^(s.addr_width+log2(s.data_width/32)));\n\n% software parameters\nb = set(b,'c_params',num2str((2^s.addr_width)*s.data_width/32));\n\n% borf parameters\nborph_info.size = (2^s.addr_width)*s.data_width/8;\nborph_info.mode = 3;\nb = set(b,'borph_info',borph_info);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_bram/drc.m", "size": 2992, "source_encoding": "utf_8", "md5": "be87e21f87dde6de6717ab06e950833c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\n\nresult = 0;\nmsg = '';\n\nsysgen_blk = find_system(gcs, 'SearchDepth', 1,'FollowLinks','on','LookUnderMasks','all','Tag','genX');\nif length(sysgen_blk) == 1\n xsg_blk = sysgen_blk{1};\nelse\n error('XPS block must be on the same level as the Xilinx SysGen block');\nend\n\nhw_sys = get(xps_objs{1}, 'hw_sys');\n\naddr_width = blk_obj.addr_width;\ndata_width = blk_obj.data_width;\n\nswitch hw_sys\n case {'ROACH2', 'MKDIG'}\n if addr_width < 2\n msg = 'Shared BRAM address width cannot be less than 2 on on ROACH boards';\n result = 1;\n end\n case 'ROACH'\n if (addr_width + ceil(log2(data_width))) < 15,\n msg = ['Shared BRAM address width cannot be less than ',num2str(15-ceil(log2(data_width))),' when using a data width of ',num2str(data_width),' on Virtex-5 boards'];\n result = 1;\n end\n otherwise\n if addr_width < 11\n msg = 'Shared BRAM address width cannot be less than 11 on unknown platform';\n result = 1;\n end\nend\nif addr_width > 16\n msg = 'Shared BRAM address width cannot be greater than 16';\n result = 1;\nend\n\nif isempty(find([8 16 32 64 128] == data_width))\n msg = 'Shared BRAM data width can only be 8,16,32,64 or 128';\n result = 1;\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_bram/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_bram/gen_mhs_ip.m", "size": 5426, "source_encoding": "utf_8", "md5": "2610f1750badfaf361976f2e9eb776be", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nfunction [str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj,opb_addr_start,opb_name)\r\n\r\nstr = '';\r\nopb_addr_end = opb_addr_start;\r\n\r\ndata_width = blk_obj.data_width;\r\naddr_width = blk_obj.addr_width;\r\nportb_width = addr_width + log2(data_width/32);\r\noptimization = blk_obj.optimization;\r\nreg_core_output = blk_obj.reg_core_output;\r\nreg_prim_output = blk_obj.reg_prim_output;\r\nnum_we = data_width/8;\r\n\r\ninst_name = clear_name(get(blk_obj,'simulink_name'));\r\nxsg_obj = get(blk_obj,'xsg_obj');\r\nif (data_width == 32 && strcmpi(reg_core_output,'false') && strcmpi(reg_prim_output,'false'))\r\n % Use the non-coregen scheme for the 32 bit case which is a lot faster.\r\n str = [str, 'BEGIN bram_if\\n'];\r\n str = [str, ' PARAMETER INSTANCE = ',inst_name,'_ramif\\n'];\r\n str = [str, ' PARAMETER HW_VER = 1.00.a\\n'];\r\n str = [str, ' PARAMETER ADDR_SIZE = ',num2str(blk_obj.addr_width) ,'\\n'];\r\n str = [str, ' BUS_INTERFACE PORTA = ',inst_name,'_ramblk_porta\\n'];\r\n \r\n str = [str, ' PORT clk_in = ',get(xsg_obj,'clk_src'),'\\n'];\r\n \r\n str = [str, ' PORT addr = ',inst_name,'_addr \\n'];\r\n str = [str, ' PORT data_in = ',inst_name,'_data_in \\n'];\r\n str = [str, ' PORT data_out = ',inst_name,'_data_out\\n'];\r\n str = [str, ' PORT we = ',inst_name,'_we \\n'];\r\n \r\n str = [str, 'END\\n\\n'];\r\n \r\n \r\n str = [str, 'BEGIN bram_block\\n'];\r\n str = [str, ' PARAMETER INSTANCE = ',inst_name,'_ramblk\\n'];\r\n str = [str, ' PARAMETER HW_VER = 1.00.a\\n'];\r\n str = [str, ' BUS_INTERFACE PORTA = ',inst_name,'_ramblk_porta\\n'];\r\n str = [str, ' BUS_INTERFACE PORTB = ',inst_name,'_ramblk_portb\\n'];\r\n str = [str, 'END\\n\\n'];\r\nelse\r\n % Use the bram_block_custom block which calls coregen to generate multiport bram netlist\r\n str = [str, 'BEGIN bram_block_custom\\n'];\r\n str = [str, ' PARAMETER INSTANCE = ',inst_name,'_ramblk\\n'];\r\n str = [str, ' PARAMETER HW_VER = 1.00.a\\n'];\r\n\r\n str = [str, ' PARAMETER C_PORTA_DWIDTH = ', num2str(data_width), '\\n'];\r\n str = [str, ' PARAMETER C_PORTA_NUM_WE = ', num2str(num_we), '\\n'];\r\n str = [str, ' PARAMETER C_PORTA_DEPTH = ', num2str(addr_width), '\\n'];\r\n str = [str, ' PARAMETER C_PORTB_DEPTH = ', num2str(portb_width), '\\n'];\r\n str = [str, ' PARAMETER OPTIMIZATION = ', optimization, '\\n'];\r\n str = [str, ' PARAMETER REG_CORE_OUTPUT = ', reg_core_output, '\\n'];\r\n str = [str, ' PARAMETER REG_PRIM_OUTPUT = ', reg_prim_output, '\\n'];\r\n\r\n str = [str, ' PORT clk = ',get(xsg_obj,'clk_src'),'\\n'];\r\n str = [str, ' PORT bram_addr = ',inst_name,'_addr \\n'];\r\n str = [str, ' PORT bram_rd_data = ',inst_name,'_data_out\\n'];\r\n str = [str, ' PORT bram_wr_data = ',inst_name,'_data_in \\n'];\r\n str = [str, ' PORT bram_we = ',inst_name,'_we \\n'];\r\n\r\n str = [str, ' BUS_INTERFACE PORTB = ',inst_name,'_ramblk_portb\\n'];\r\n str = [str, 'END\\n\\n'];\r\nend\r\n\r\n% need to calculate address range based on the portb (ie cpu) width\r\n% as this can vary depending on port widths\r\nopb_addr_start = ceil(opb_addr_start / (4*2^portb_width))*4*2^portb_width;\r\nstr = [str, 'BEGIN opb_bram_if_cntlr\\n'];\r\nstr = [str, ' PARAMETER INSTANCE = ',inst_name,'\\n'];\r\nstr = [str, ' PARAMETER HW_VER = 1.00.a\\n'];\r\nstr = [str, ' PARAMETER C_OPB_CLK_PERIOD_PS = 10000\\n'];\r\nstr = [str, ' PARAMETER C_BASEADDR = 0x',dec2hex(opb_addr_start,32/4),'\\n'];\r\nstr = [str, ' PARAMETER C_HIGHADDR = 0x',dec2hex(opb_addr_start+4*2^portb_width-1,(32/4)),'\\n'];\r\nstr = [str, ' BUS_INTERFACE SOPB = ',opb_name,'\\n'];\r\nopb_addr_end = opb_addr_start + 4*2^portb_width;\r\n\r\nstr = [str, ' BUS_INTERFACE PORTA = ',inst_name,'_ramblk_portb\\n'];\r\nstr = [str, 'END\\n\\n'];\r\n\r\nset(blk_obj,'borph_info.base_address', opb_addr_start);\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adcdac_2g/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adcdac_2g.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adcdac_2g/xps_adcdac_2g.m", "size": 7661, "source_encoding": "utf_8", "md5": "e7ef66966414dd913b125311c68f84dc", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Make sure this is an XPS object\nfunction b = xps_adcdac_2g(blk_obj)\ndisp('calling xps_adcdac_2g!');\nif ~isa(blk_obj,'xps_block')\n error('xps_adcdac_2g class requires a xps_block class object');\nend\n% Then check that it's the right type\nif ~strcmp(get(blk_obj,'type'),'xps_adcdac_2g')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.adc_str = ['adc', '0'];\n\n% Get the mask parameters we need to know\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.clk_sys = get(xsg_obj,'clk_src');\n \n \nb = class(s,'xps_adcdac_2g',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','adcdac_2g_interface');\nb = set(b,'ip_version','1.00.a');\n\n%b = set(b,'parameters',parameters);\n\n\nn_adc_samples_per_fabric_cycle = 8\n\n\n% external ports\nucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', '8 ns');\nucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\nucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ','125000000');\n\n%data in\nadcport1 = [s.hw_sys, '.', 'zdok1'];\nadcport0 = [s.hw_sys, '.', 'zdok0'];\nadcport_sync = [s.hw_sys, '.', 'sync_in'];\nadcport_sync_out = [s.hw_sys, '.', 'sync_out'];\n\next_ports.valid_p = {1 'in' ['adc_valid_p'] ['{',adcport1,'_p{[5],:}}'] 'vector=false' struct() ucf_constraints_term};\next_ports.valid_n = {1 'in' ['adc_valid_n'] ['{',adcport1,'_n{[5],:}}'] 'vector=false' struct() ucf_constraints_term};\n%last 2 bits in each are (sysref,overrange)\next_ports.data0_p = {12 'in' ['adc_data0_p'] ['{',adcport1,'_p{[1 21 11 31 2 22 12 32 3 23 13 33],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.data0_n = {12 'in' ['adc_data0_n'] ['{',adcport1,'_n{[1 21 11 31 2 22 12 32 3 23 13 33],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.info0_p = {2 'in' ['adc_info0_p'] ['{',adcport1,'_p{[4 24],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.info0_n = {2 'in' ['adc_info0_n'] ['{',adcport1,'_n{[4 24],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.data1_p = {12 'in' ['adc_data1_p'] ['{',adcport1,'_p{[6 26 16 36 7 27 17 37 8 28 18 38],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.data1_n = {12 'in' ['adc_data1_n'] ['{',adcport1,'_n{[6 26 16 36 7 27 17 37 8 28 18 38],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.info1_p = {2 'in' ['adc_info1_p'] ['{',adcport1,'_p{[9 29],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.info1_n = {2 'in' ['adc_info1_n'] ['{',adcport1,'_n{[9 29],:}}'] 'vector=true' struct() ucf_constraints_term};\n\n\next_ports.data2_p = {12 'in' ['adc_data2z0_p'] ['{',adcport0,'_p{[1 21 11 31 2 22 12 32 3 23 13 33],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.data2_n = {12 'in' ['adc_data2z0_n'] ['{',adcport0,'_n{[1 21 11 31 2 22 12 32 3 23 13 33],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.info2_p = {2 'in' ['adc_info2_p'] ['{',adcport0,'_p{[4 24],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.info2_n = {2 'in' ['adc_info2_n'] ['{',adcport0,'_n{[4 24],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.data3_p = {12 'in' ['adc_data3_p'] ['{',adcport0,'_p{[6 26 16 36 7 27 17 37 8 28 18 38],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.data3_n = {12 'in' ['adc_data3_n'] ['{',adcport0,'_n{[6 26 16 36 7 27 17 37 8 28 18 38],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.info3_p = {2 'in' ['adc_info3_p'] ['{',adcport0,'_p{[9 29],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.info3_n = {2 'in' ['adc_info3_n'] ['{',adcport0,'_n{[9 29],:}}'] 'vector=true' struct() ucf_constraints_term};\n\n%sample clock - fabric clock is derived from this\next_ports.data0_smpl_clk_p = {1 'in' ['adc_data0_smpl_clk_p'] ['{',adcport1,'_p{[20],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.data0_smpl_clk_n = {1 'in' ['adc_data0_smpl_clk_n'] ['{',adcport1,'_n{[20],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\n\n%PPS coming through the sma sync in port\next_ports.sync_pps_p = {1 'in' ['adc_sync_pps_p'] ['{',adcport_sync,'_p{[1],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.sync_pps_n = {1 'in' ['adc_sync_pps_n'] ['{',adcport_sync,'_n{[1],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\n\n\n%handshake from roach enabling ADC streams\next_ports.data0_rdy_p = {1 'out' ['adc_data0_rdy_p'] ['{',adcport1,'_p{[25],:}}'] 'vector=false' struct() ucf_constraints_term};\next_ports.data0_rdy_n = {1 'out' ['adc_data0_rdy_n'] ['{',adcport1,'_n{[25],:}}'] 'vector=false' struct() ucf_constraints_term};\n\next_ports.sync_out_p = {1 'out' ['adc_sync_out_p'] ['{',adcport_sync_out,'_p{[1],:}}'] 'vector=false' struct() ucf_constraints_term};\next_ports.sync_out_n = {1 'out' ['adc_sync_out_n'] ['{',adcport_sync_out,'_n{[1],:}}'] 'vector=false' struct() ucf_constraints_term};\n\nb = set(b,'ext_ports',ext_ports);\n\n% Add ports not explicitly provided in the yellow block\n\n%clock from fpga (used if clock is not set to adc_clk in XSG)\n%misc_ports.fpga_clk = {1 'in' get(xsg_obj,'clk_src')};\n\n%clocks to send to fpga\nif strfind(s.clk_sys,'adc')\n misc_ports.adc_clk_out = {1 'out' [s.adc_str,'_clk']};\n misc_ports.adc_clk90_out = {1 'out' [s.adc_str,'_clk90']};\n misc_ports.adc_clk180_out = {1 'out' [s.adc_str,'_clk180']};\n misc_ports.adc_clk270_out = {1 'out' [s.adc_str,'_clk270']};\nend\n\n%lock for clock manager\nmisc_ports.adc_mmcm_locked = {1 'out' [s.adc_str, '_mmcm_locked']};\n%internal clock is useful for a few things\nmisc_ports.sys_clk = {1 'in' 'sys_clk'};\n\nb = set(b,'misc_ports',misc_ports);\n\ndisp('done calling xps_adcdac_2g!');\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adcdac_2g/drc.m", "size": 1751, "source_encoding": "utf_8", "md5": "805b22d398f2f8ef4c982d1cd1e67683", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\nresult = 0;\nmsg = '';\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adcdac_2g/gen_ucf.m", "size": 3032, "source_encoding": "utf_8", "md5": "26e3675df4b10667893187319a84bbc2", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\n\nstr = gen_ucf(blk_obj.xps_block);\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\n\n%str = '';\n%simulink_name = clear_name(get(blk_obj,'simulink_name'));\n\n%I_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_p'];\n%I_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_n'];\n\n%Q_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_p'];\n%Q_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_n'];\n\n%str = [str, 'NET ', I_clk_p_str, ' TNM_NET = ', I_clk_p_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', I_clk_p_str, ' = PERIOD ', I_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n%str = [str, 'NET ', I_clk_n_str, ' TNM_NET = ', I_clk_n_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', I_clk_n_str, ' = PERIOD ', I_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\n%str = [str, '\\n'];\n\n%str = [str, 'NET ', Q_clk_p_str, ' TNM_NET = ', Q_clk_p_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', Q_clk_p_str, ' = PERIOD ', Q_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n%str = [str, 'NET ', Q_clk_n_str, ' TNM_NET = ', Q_clk_n_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', Q_clk_n_str, ' = PERIOD ', Q_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\n%str = [str, '\\n'];\n\n%str = [str, gen_ucf(blk_obj.xps_block)];\n\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adcdac_2g/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc/drc.m", "size": 2118, "source_encoding": "utf_8", "md5": "60145324772f7335c69b7970ae3e68e3", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'hw_adc'),get(xps_objs{i},'hw_adc'))\r\n\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['ADC ',get(blk_obj,'simulink_name'),' and ADC ',get(xps_objs{i},'simulink_name'),' are located on the same port.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc/gen_ucf.m", "size": 25529, "source_encoding": "utf_8", "md5": "d21ccb8542cd46414bf982b26371d742", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\ndisp('adc086000 gen_ucf')\n\nhw_sys = blk_obj.hw_sys;\nadc_str = blk_obj.adc_str;\ndisp('adc086000 trying generic ucf generation')\nstr = gen_ucf(blk_obj.xps_block);\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\ndisp('adc08600 trying specific ucf generation')\nswitch hw_sys\n case 'ROACH'\n switch adc_str\n case 'adc0'\n %\t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 1ns;\\n'];\n % end case 'adc0'\n case 'adc1'\n %\t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 1ns;\\n'];\n % end case 'adc1'\n end % switch adc_str\n case 'ROACH2'\n switch adc_str\n case 'adc0'\n %\t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 1ns;\\n'];\n % end case 'adc0'\n case 'adc1'\n %\t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 1ns;\\n'];\n % end case 'adc1'\n end % switch adc_str\n case 'iBOB'\n switch adc_str\n case 'adc0'\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" PERIOD = ',num2str(1000/blk_obj.adc_clk_rate*4),'ns;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" MAXDELAY = 452ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_dcm\" MAXDELAY = 853ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk90_dcm\" MAXDELAY = 853ps;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK_CLKBUF\" LOC = BUFGMUX1P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK90_CLKBUF\" LOC = BUFGMUX3P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" LOC = DCM_X2Y1;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" CLKOUT_PHASE_SHIFT = VARIABLE;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 559ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" ROUTE = \"{3;1;2vp50ff1152;46c47c12!-1;156520;5632;S!0;-159;0!1;-1884;-1248!1;-1884;744!2;-1548;992!2;-1548;304!3;-1548;-656!3;-1548;-1344!4;327;0;L!5;167;0;L!6;327;0;L!7;167;0;L!}\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_3\" LOC = SLICE_X139Y91;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_2\" LOC = SLICE_X138Y91;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_1\" LOC = SLICE_X139Y90;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_0\" LOC = SLICE_X138Y90;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_0\" LOC = \"SLICE_X138Y128\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_1\" LOC = \"SLICE_X138Y126\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_2\" LOC = \"SLICE_X139Y122\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_3\" LOC = \"SLICE_X138Y120\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_4\" LOC = \"SLICE_X138Y102\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_5\" LOC = \"SLICE_X139Y98\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_6\" LOC = \"SLICE_X138Y96\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_7\" LOC = \"SLICE_X138Y94\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_8\" LOC = \"SLICE_X139Y126\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_9\" LOC = \"SLICE_X138Y124\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_10\" LOC = \"SLICE_X138Y122\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_11\" LOC = \"SLICE_X139Y118\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_12\" LOC = \"SLICE_X138Y100\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_13\" LOC = \"SLICE_X138Y98\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_14\" LOC = \"SLICE_X139Y94\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_15\" LOC = \"SLICE_X138Y92\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_16\" LOC = \"SLICE_X138Y128\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_17\" LOC = \"SLICE_X138Y126\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_18\" LOC = \"SLICE_X139Y122\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_19\" LOC = \"SLICE_X138Y120\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_20\" LOC = \"SLICE_X138Y102\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_21\" LOC = \"SLICE_X139Y98\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_22\" LOC = \"SLICE_X138Y96\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_23\" LOC = \"SLICE_X138Y94\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_24\" LOC = \"SLICE_X139Y126\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_25\" LOC = \"SLICE_X138Y124\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_26\" LOC = \"SLICE_X138Y122\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_27\" LOC = \"SLICE_X139Y118\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_28\" LOC = \"SLICE_X138Y100\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_29\" LOC = \"SLICE_X138Y98\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_30\" LOC = \"SLICE_X139Y94\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_31\" LOC = \"SLICE_X138Y92\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_0\" LOC = \"SLICE_X138Y132\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_1\" LOC = \"SLICE_X139Y134\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_2\" LOC = \"SLICE_X138Y170\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_3\" LOC = \"SLICE_X138Y172\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_4\" LOC = \"SLICE_X139Y106\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_5\" LOC = \"SLICE_X138Y110\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_6\" LOC = \"SLICE_X138Y112\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_7\" LOC = \"SLICE_X139Y114\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_8\" LOC = \"SLICE_X138Y134\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_9\" LOC = \"SLICE_X138Y168\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_10\" LOC = \"SLICE_X139Y170\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_11\" LOC = \"SLICE_X138Y174\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_12\" LOC = \"SLICE_X138Y108\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_13\" LOC = \"SLICE_X139Y110\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_14\" LOC = \"SLICE_X138Y114\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_15\" LOC = \"SLICE_X138Y116\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_16\" LOC = \"SLICE_X138Y132\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_17\" LOC = \"SLICE_X139Y134\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_18\" LOC = \"SLICE_X138Y170\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_19\" LOC = \"SLICE_X138Y172\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_20\" LOC = \"SLICE_X139Y106\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_21\" LOC = \"SLICE_X138Y110\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_22\" LOC = \"SLICE_X138Y112\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_23\" LOC = \"SLICE_X139Y114\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_24\" LOC = \"SLICE_X138Y134\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_25\" LOC = \"SLICE_X138Y168\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_26\" LOC = \"SLICE_X139Y170\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_27\" LOC = \"SLICE_X138Y174\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_28\" LOC = \"SLICE_X138Y108\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_29\" LOC = \"SLICE_X139Y110\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_30\" LOC = \"SLICE_X138Y114\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_31\" LOC = \"SLICE_X138Y116\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_0\" LOC = \"SLICE_X138Y118\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_1\" LOC = \"SLICE_X138Y118\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_0\" LOC = \"SLICE_X138Y104\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_1\" LOC = \"SLICE_X138Y104\" | BEL = \"FFY\";\\n'];\n % end case 'adc0'\n\n case 'adc1'\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" PERIOD = ',num2str(1000/blk_obj.adc_clk_rate*4),'ns;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" MAXDELAY = 452ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_dcm\" MAXDELAY = 854ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk90_dcm\" MAXDELAY = 854ps;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK_CLKBUF\" LOC = BUFGMUX0P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK90_CLKBUF\" LOC = BUFGMUX2P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" LOC = DCM_X2Y0;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" CLKOUT_PHASE_SHIFT = VARIABLE;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 559ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" ROUTE = \"{3;1;2vp50ff1152;6b4b9e45!-1;156520;-144648;S!0;-159;0!1;-1884;-1248!1;-1884;744!2;-1548;992!2;-1548;304!3;-1548;-656!3;-1548;-1344!4;327;0;L!5;167;0;L!6;327;0;L!7;167;0;L!}\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_3\" LOC = SLICE_X139Y3;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_2\" LOC = SLICE_X138Y3;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_1\" LOC = SLICE_X139Y2;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_0\" LOC = SLICE_X138Y2;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_0\" LOC = \"SLICE_X139Y70\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_1\" LOC = \"SLICE_X138Y68\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_2\" LOC = \"SLICE_X139Y64\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_3\" LOC = \"SLICE_X139Y62\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_4\" LOC = \"SLICE_X139Y44\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_5\" LOC = \"SLICE_X139Y42\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_6\" LOC = \"SLICE_X138Y40\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_7\" LOC = \"SLICE_X139Y4\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_8\" LOC = \"SLICE_X139Y68\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_9\" LOC = \"SLICE_X139Y66\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_10\" LOC = \"SLICE_X138Y64\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_11\" LOC = \"SLICE_X139Y60\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_12\" LOC = \"SLICE_X138Y44\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_13\" LOC = \"SLICE_X139Y40\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_14\" LOC = \"SLICE_X139Y6\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_15\" LOC = \"SLICE_X138Y4\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_16\" LOC = \"SLICE_X139Y70\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_17\" LOC = \"SLICE_X138Y68\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_18\" LOC = \"SLICE_X139Y64\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_19\" LOC = \"SLICE_X139Y62\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_20\" LOC = \"SLICE_X139Y44\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_21\" LOC = \"SLICE_X139Y42\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_22\" LOC = \"SLICE_X138Y40\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_23\" LOC = \"SLICE_X139Y4\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_24\" LOC = \"SLICE_X139Y68\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_25\" LOC = \"SLICE_X139Y66\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_26\" LOC = \"SLICE_X138Y64\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_27\" LOC = \"SLICE_X139Y60\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_28\" LOC = \"SLICE_X138Y44\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_29\" LOC = \"SLICE_X139Y40\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_30\" LOC = \"SLICE_X139Y6\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_31\" LOC = \"SLICE_X138Y4\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_0\" LOC = \"SLICE_X139Y74\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_1\" LOC = \"SLICE_X139Y78\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_2\" LOC = \"SLICE_X139Y80\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_3\" LOC = \"SLICE_X138Y84\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_4\" LOC = \"SLICE_X139Y48\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_5\" LOC = \"SLICE_X138Y52\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_6\" LOC = \"SLICE_X139Y54\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_7\" LOC = \"SLICE_X139Y56\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_8\" LOC = \"SLICE_X138Y76\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_9\" LOC = \"SLICE_X138Y80\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_10\" LOC = \"SLICE_X139Y82\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_11\" LOC = \"SLICE_X139Y84\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_12\" LOC = \"SLICE_X139Y50\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_13\" LOC = \"SLICE_X139Y52\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_14\" LOC = \"SLICE_X138Y56\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_15\" LOC = \"SLICE_X139Y58\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_16\" LOC = \"SLICE_X139Y74\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_17\" LOC = \"SLICE_X139Y78\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_18\" LOC = \"SLICE_X139Y80\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_19\" LOC = \"SLICE_X138Y84\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_20\" LOC = \"SLICE_X139Y48\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_21\" LOC = \"SLICE_X138Y52\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_22\" LOC = \"SLICE_X139Y54\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_23\" LOC = \"SLICE_X139Y56\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_24\" LOC = \"SLICE_X138Y76\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_25\" LOC = \"SLICE_X138Y80\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_26\" LOC = \"SLICE_X139Y82\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_27\" LOC = \"SLICE_X139Y84\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_28\" LOC = \"SLICE_X139Y50\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_29\" LOC = \"SLICE_X139Y52\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_30\" LOC = \"SLICE_X138Y56\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_31\" LOC = \"SLICE_X139Y58\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_0\" LOC = \"SLICE_X138Y60\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_1\" LOC = \"SLICE_X138Y60\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_0\" LOC = \"SLICE_X138Y48\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_1\" LOC = \"SLICE_X138Y48\" | BEL = \"FFY\";\\n'];\n % end case 'adc1'\n end % switch adc_str\n % end case 'iBOB'\nend % switch hw_sys\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adc086000.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc/xps_adc086000.m", "size": 10741, "source_encoding": "utf_8", "md5": "ecbf643ce18bbd0f7e0e184ccd2a634a", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_adc086000(blk_obj)\n\ndisp('xps_adc086000 called')\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_ADC class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_adc086000')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.hw_adc = get_param(blk_name,'adc_brd');\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.adc_interleave = get_param(blk_name,'adc_interleave');\n\nswitch s.hw_sys\n case 'iBOB'\n if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n s.adc_str = s.hw_adc;\n else\n error(['Unsupported adc board: ',s.hw_adc]);\n end % if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25_DT', 'PERIOD', [num2str(1000/s.adc_clk_rate*4),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25_DT');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n % end case 'iBOB'\n case 'ROACH'\n if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n s.adc_str = s.hw_adc;\n else\n error(['Unsupported adc board: ',s.hw_adc]);\n end % if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(1000/s.adc_clk_rate*4),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n ucf_constraints_single = struct('IOSTANDARD', 'LVCMOS25');\n % end case 'ROACH'\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend % end switch s.hw_sys\n\nb = class(s,'xps_adc086000',blk_obj);\n\n% ip name and version\nb = set(b, 'ip_name', 'adc086000_interface');\nswitch s.hw_sys\n case 'iBOB'\n b = set(b, 'ip_version', '1.00.a');\n case 'ROACH'\n b = set(b, 'ip_version', '1.01.a');\nend % switch s.hw_sys\n\n% misc ports\nmisc_ports.ctrl_reset = {1 'in' [s.adc_str,'_ddrb']};\nmisc_ports.ctrl_clk_in = {1 'in' get(xsg_obj,'clk_src')};\nmisc_ports.ctrl_clk_out = {1 'out' [s.adc_str,'_clk']};\nmisc_ports.ctrl_clk90_out = {1 'out' [s.adc_str,'_clk90']};\nmisc_ports.ctrl_dcm_locked = {1 'out' [s.adc_str,'_dcm_locked']};\nif strcmp(get(b,'ip_version'), '1.01.a')\n misc_ports.dcm_reset = {1 'in' [s.adc_str,'_dcm_reset']};\n misc_ports.dcm_psdone = {1 'out' [s.adc_str,'_psdone']};\n misc_ports.ctrl_clk180_out = {1 'out' [s.adc_str,'_clk180']};\n misc_ports.ctrl_clk270_out = {1 'out' [s.adc_str,'_clk270']};\nend\nmisc_ports.dcm_psclk = {1 'in' [s.adc_str,'_psclk']};\nmisc_ports.dcm_psen = {1 'in' [s.adc_str,'_psen']};\nmisc_ports.dcm_psincdec = {1 'in' [s.adc_str,'_psincdec']};\nb = set(b,'misc_ports',misc_ports);\n\n% external ports\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(s.adc_clk_rate*1e6));\n\nadcport = [s.hw_sys, '.', 'zdok', s.adc_str(length(s.adc_str))];\nadc0port = [s.hw_sys, '.', 'zdok0']%, s.adc_str(length(s.adc_str))];\nadc1port = [s.hw_sys, '.', 'zdok1']%, s.adc_str(length(s.adc_str))];\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ADC0\next_ports.adc0_clk_p = {1 'in' ['adc0','clk_p'] ['{',adc0port,'_p{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc0_clk_n = {1 'in' ['adc0','clk_n'] ['{',adc0port,'_n{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc0_sync_p = {1 'in' ['adc0','sync_p'] ['{',adc0port,'_p{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc0_sync_n = {1 'in' ['adc0','sync_n'] ['{',adc0port,'_n{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc0_outofrange_p = {1 'in' ['adc0','outofrange_p'] ['{',adc0port,'_p{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc0_outofrange_n = {1 'in' ['adc0','outofrange_n'] ['{',adc0port,'_n{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc0_dataeveni_p = {8 'in' ['adc0','dataeveni_p'] ['{',adc0port,'_p{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataeveni_n = {8 'in' ['adc0','dataeveni_n'] ['{',adc0port,'_n{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataevenq_p = {8 'in' ['adc0','dataevenq_p'] ['{',adc0port,'_p{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataevenq_n = {8 'in' ['adc0','dataevenq_n'] ['{',adc0port,'_n{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataoddi_p = {8 'in' ['adc0','dataoddi_p'] ['{',adc0port,'_p{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataoddi_n = {8 'in' ['adc0','dataoddi_n'] ['{',adc0port,'_n{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataoddq_p = {8 'in' ['adc0','dataoddq_p'] ['{',adc0port,'_p{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_dataoddq_n = {8 'in' ['adc0','dataoddq_n'] ['{',adc0port,'_n{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc0_reset = {1 'out' ['adc0','_reset'] ['{',adc0port,'_p{[19]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n%ext_ports.adc0_ddrb_n = {1 'out' ['adc0','ddrb_n'] ['{',adc0port,'_n{[19]+1,:}}'] 'vector=false' struct() ucf_constraints_noterm };\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ADC1\next_ports.adc1_clk_p = {1 'in' ['adc1','clk_p'] ['{',adc1port,'_p{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc1_clk_n = {1 'in' ['adc1','clk_n'] ['{',adc1port,'_n{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc1_sync_p = {1 'in' ['adc1','sync_p'] ['{',adc1port,'_p{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc1_sync_n = {1 'in' ['adc1','sync_n'] ['{',adc1port,'_n{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc1_outofrange_p = {1 'in' ['adc1','outofrange_p'] ['{',adc1port,'_p{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc1_outofrange_n = {1 'in' ['adc1','outofrange_n'] ['{',adc1port,'_n{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc1_dataeveni_p = {8 'in' ['adc1','dataeveni_p'] ['{',adc1port,'_p{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataeveni_n = {8 'in' ['adc1','dataeveni_n'] ['{',adc1port,'_n{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataevenq_p = {8 'in' ['adc1','dataevenq_p'] ['{',adc1port,'_p{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataevenq_n = {8 'in' ['adc1','dataevenq_n'] ['{',adc1port,'_n{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataoddi_p = {8 'in' ['adc1','dataoddi_p'] ['{',adc1port,'_p{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataoddi_n = {8 'in' ['adc1','dataoddi_n'] ['{',adc1port,'_n{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataoddq_p = {8 'in' ['adc1','dataoddq_p'] ['{',adc1port,'_p{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_dataoddq_n = {8 'in' ['adc1','dataoddq_n'] ['{',adc1port,'_n{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc1_reset = {1 'out' ['adc1','_reset'] ['{',adc1port,'_p{[19]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n%ext_ports.adc1_ddrb_n = {1 'out' ['adc1','ddrb_n'] ['{',adc1port,'_n{[19]+1,:}}'] 'vector=false' struct() ucf_constraints_noterm };\n\n\nb = set(b,'ext_ports',ext_ports);\n\n% Software parameters\nb = set(b,'c_params',['adc = ',s.adc_str,' / interleave = ',s.adc_interleave]);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc/xps_adc.m", "size": 8676, "source_encoding": "utf_8", "md5": "648b9adaabe511fd30f1dcb026a1e0eb", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_adc(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_ADC class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_adc')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.hw_adc = get_param(blk_name,'adc_brd');\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.adc_interleave = get_param(blk_name,'adc_interleave');\n\nswitch s.hw_sys\n case 'iBOB'\n if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n s.adc_str = s.hw_adc;\n else\n error(['Unsupported adc board: ',s.hw_adc]);\n end % if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25_DT', 'PERIOD', [num2str(1000/s.adc_clk_rate*4),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25_DT');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n % end case 'iBOB'\n case {'ROACH', 'ROACH2'}\n if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n s.adc_str = s.hw_adc;\n else\n error(['Unsupported adc board: ',s.hw_adc]);\n end % if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(1000/s.adc_clk_rate*4),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n % end case {'ROACH', 'ROACH2'}\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend % end switch s.hw_sys\n\nb = class(s,'xps_adc',blk_obj);\n\n% ip name and version\nb = set(b, 'ip_name', 'adc_interface');\nswitch s.hw_sys\n case 'iBOB'\n b = set(b, 'ip_version', '1.00.a');\n case {'ROACH', 'ROACH2'}\n b = set(b, 'ip_version', '1.01.a');\n b = set(b, 'opb0_devices', 1); %controller\nend % switch s.hw_sys\n\nsupp_ip_names = {'', 'opb_adccontroller'};\nsupp_ip_versions = {'', '1.00.a'};\n\nb = set(b, 'supp_ip_names', supp_ip_names);\nb = set(b, 'supp_ip_versions', supp_ip_versions);\n\n% misc ports\nmisc_ports.ctrl_reset = {1 'in' [s.adc_str,'_ddrb']};\nmisc_ports.ctrl_clk_in = {1 'in' get(xsg_obj,'clk_src')};\nmisc_ports.ctrl_clk_out = {1 'out' [s.adc_str,'_clk']};\nmisc_ports.ctrl_clk90_out = {1 'out' [s.adc_str,'_clk90']};\nmisc_ports.ctrl_dcm_locked = {1 'out' [s.adc_str,'_dcm_locked']};\nif strcmp(get(b,'ip_version'), '1.01.a')\n switch s.hw_sys\n case 'iBOB'\n misc_ports.dcm_reset = {1 'in' [s.adc_str,'_dcm_reset']};\n misc_ports.dcm_psdone = {1 'out' [s.adc_str,'_psdone']};\n case 'ROACH'\n misc_ports.dcm_reset = {1 'in' [s.adc_str,'_dcm_reset']};\n misc_ports.dcm_psdone = {1 'out' [s.adc_str,'_psdone']};\n case 'ROACH2'\n misc_ports.mmcm_reset = {1 'in' [s.adc_str,'_mmcm_reset']};\n misc_ports.mmcm_psdone = {1 'out' [s.adc_str,'_psdone']};\n end\n misc_ports.ctrl_clk180_out = {1 'out' [s.adc_str,'_clk180']};\n misc_ports.ctrl_clk270_out = {1 'out' [s.adc_str,'_clk270']};\nend\nmisc_ports.dcm_psclk = {1 'in' [s.adc_str,'_psclk']};\nmisc_ports.dcm_psen = {1 'in' [s.adc_str,'_psen']};\nmisc_ports.dcm_psincdec = {1 'in' [s.adc_str,'_psincdec']};\nb = set(b,'misc_ports',misc_ports);\n\n% external ports\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(s.adc_clk_rate*1e6));\n\nadcport = [s.hw_sys, '.', 'zdok', s.adc_str(length(s.adc_str))];\n\next_ports.adc_clk_p = {1 'in' [s.adc_str,'clk_p'] ['{',adcport,'_p{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc_clk_n = {1 'in' [s.adc_str,'clk_n'] ['{',adcport,'_n{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc_sync_p = {1 'in' [s.adc_str,'sync_p'] ['{',adcport,'_p{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc_sync_n = {1 'in' [s.adc_str,'sync_n'] ['{',adcport,'_n{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc_outofrangei_p = {1 'in' [s.adc_str,'outofrangei_p'] ['{',adcport,'_p{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc_outofrangei_n = {1 'in' [s.adc_str,'outofrangei_n'] ['{',adcport,'_n{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc_outofrangeq_p = {1 'in' [s.adc_str,'outofrangeq_p'] ['{',adcport,'_p{[28]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc_outofrangeq_n = {1 'in' [s.adc_str,'outofrangeq_n'] ['{',adcport,'_n{[28]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc_dataeveni_p = {8 'in' [s.adc_str,'dataeveni_p'] ['{',adcport,'_p{[11 13 15 17 31 33 35 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dataeveni_n = {8 'in' [s.adc_str,'dataeveni_n'] ['{',adcport,'_n{[11 13 15 17 31 33 35 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dataoddi_p = {8 'in' [s.adc_str,'dataoddi_p'] ['{',adcport,'_p{[10 12 14 16 30 32 34 36]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dataoddi_n = {8 'in' [s.adc_str,'dataoddi_n'] ['{',adcport,'_n{[10 12 14 16 30 32 34 36]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dataevenq_p = {8 'in' [s.adc_str,'dataevenq_p'] ['{',adcport,'_p{[ 6 4 2 0 26 24 22 20]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dataevenq_n = {8 'in' [s.adc_str,'dataevenq_n'] ['{',adcport,'_n{[ 6 4 2 0 26 24 22 20]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dataoddq_p = {8 'in' [s.adc_str,'dataoddq_p'] ['{',adcport,'_p{[ 7 5 3 1 27 25 23 21]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dataoddq_n = {8 'in' [s.adc_str,'dataoddq_n'] ['{',adcport,'_n{[ 7 5 3 1 27 25 23 21]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_ddrb_p = {1 'out' [s.adc_str,'ddrb_p'] ['{',adcport,'_p{[29]+1,:}}'] 'vector=false' struct() ucf_constraints_noterm };\next_ports.adc_ddrb_n = {1 'out' [s.adc_str,'ddrb_n'] ['{',adcport,'_n{[29]+1,:}}'] 'vector=false' struct() ucf_constraints_noterm };\n\nb = set(b,'ext_ports',ext_ports);\n\n% Software parameters\nb = set(b,'c_params',['adc = ',s.adc_str,' / interleave = ',s.adc_interleave]);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_opb2opb/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_opb2opb.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_opb2opb/xps_opb2opb.m", "size": 2024, "source_encoding": "utf_8", "md5": "ca5c17c5c5c81bd869a6b36ce8c11f2d", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_opb2opb(opb_name,opb_addr,addr_size)\n\ns.hw_sys = 'any';\ns.opb_name = opb_name;\ns.opb_addr_start = opb_addr;\ns.addr_size = addr_size;\ns.opb_clk = 'epb_clk';\n\nb = class(s,'xps_opb2opb',xps_block({},{}));\n\nb = set(b, 'type','xps_opb2opb');\nb = set(b, 'simulink_name',['OPB to OPB bridge added at 0x',dec2hex(s.opb_addr_start)]);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_opb2opb/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_opb2opb/gen_mhs_ip.m", "size": 2965, "source_encoding": "utf_8", "md5": "a05511554174adbf46bd2d4c30472f49", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj,opb_addr_start,opb_name)\n\n\nstr = '';\n\n%does not affect the allocation of address space\nopb_addr_end = opb_addr_start;\n\nopb_name = blk_obj.opb_name;\nopb_addr_start = blk_obj.opb_addr_start;\naddr_size = blk_obj.addr_size;\n\ntry\n opb_clk = blk_obj.opb_clk;\ncatch\n opb_clk = 'epb_clk';\nend\n\nopb_slave = 'opb0';\n\nstr = [str, 'BEGIN opb_v20\\n'];\nstr = [str, ' PARAMETER INSTANCE = ',opb_name,'\\n'];\nstr = [str, ' PARAMETER HW_VER = 1.10.c\\n'];\nstr = [str, ' PARAMETER C_EXT_RESET_HIGH = 1\\n'];\nstr = [str, ' PORT SYS_Rst = sys_reset\\n'];\nstr = [str, ' PORT OPB_Clk = ', opb_clk, '\\n'];\nstr = [str, 'END\\n'];\nstr = [str, '\\n'];\nstr = [str, 'BEGIN opb_opb_lite\\n'];\nstr = [str, ' PARAMETER INSTANCE = opb2opb_bridge_',opb_name,'\\n'];\nstr = [str, ' PARAMETER HW_VER = 1.00.a\\n'];\nstr = [str, ' PARAMETER C_NUM_DECODES = 1\\n'];\nstr = [str, ' PARAMETER C_DEC0_BASEADDR = 0x',dec2hex(opb_addr_start,8),'\\n'];\nstr = [str, ' PARAMETER C_DEC0_HIGHADDR = 0x',dec2hex(opb_addr_start+addr_size-1,8),'\\n'];\nstr = [str, ' BUS_INTERFACE SOPB = ',opb_slave,'\\n'];\nstr = [str, ' BUS_INTERFACE MOPB = ',opb_name,'\\n'];\nstr = [str, ' PORT MOPB_Clk = ', opb_clk, '\\n'];\nstr = [str, ' PORT SOPB_Clk = ', opb_clk, '\\n'];\nstr = [str, 'END\\n'];\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_tengbe/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_tengbe/drc.m", "size": 2116, "source_encoding": "utf_8", "md5": "0c715a8c93631ecbfda7541640cf62af", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'port'),get(xps_objs{i},'port'))\r\n\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['XAUI ',get(blk_obj,'simulink_name'),' and XAUI ',get(xps_objs{i},'simulink_name'),' are located on the same port.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_tengbe/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_tengbe/gen_mhs_ip.m", "size": 2881, "source_encoding": "utf_8", "md5": "76eeed5f26c19fb68f49b04e427cae7e", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj,opb_addr_start,opb_name)\n\nxaui_port = get(blk_obj, 'port');\nopen_phy = get(blk_obj, 'open_phy');\nhw_sys = get(blk_obj, 'hw_sys');\n\n[str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj.xps_block, opb_addr_start, opb_name);\nstr = [str, '\\n'];\n\nswitch hw_sys\n case 'ROACH'\n\n mgt_clk_num = num2str(floor(str2num(xaui_port)/2));\n\n str = [str, 'BEGIN xaui_phy', '\\n'];\n str = [str, ' PARAMETER INSTANCE = xaui_phy_', xaui_port, '\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\n str = [str, ' PARAMETER USE_KAT_XAUI = ', open_phy, '\\n'];\n str = [str, ' BUS_INTERFACE XAUI_SYS = xaui_sys', xaui_port, '\\n'];\n str = [str, ' BUS_INTERFACE XGMII = xgmii', xaui_port, '\\n'];\n str = [str, ' PORT reset = sys_reset' , '\\n'];\n str = [str, ' PORT mgt_clk = mgt_clk_', mgt_clk_num, '\\n'];\n str = [str, 'END', '\\n'];\n % end case 'ROACH'\n\n otherwise\n % end otherwise\nend % switch hw_sys\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_tengbe.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_tengbe/xps_tengbe.m", "size": 6914, "source_encoding": "utf_8", "md5": "dc2f6767c4b75179aee5c00372a33380", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_tengbe(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_TENGBE class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_tengbe')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\ntoks = regexp(get_param(blk_name,'port'),'^(.*):(.*)$','tokens');\n\ns.board = toks{1}{1};\ns.port = toks{1}{2};\ns.hw_sys = s.board;\ns.mac_lite = num2str(strcmp(get_param(blk_name, 'mac_lite'), 'on'));\ns.open_phy = num2str(strcmp(get_param(blk_name, 'open_phy'), 'on'));\ns.preemph = get_param(blk_name, 'pre_emph');\ns.swing = get_param(blk_name, 'swing');\n\ns.fab_mac = ['0x', dec2hex(eval(get_param(blk_name, 'fab_mac'))) ];\ns.fab_ip = ['0x', dec2hex(eval(get_param(blk_name, 'fab_ip'))) ];\ns.fab_udp = ['0x', dec2hex(eval(get_param(blk_name, 'fab_udp'))) ];\ns.fab_gate = ['0x', dec2hex(eval(get_param(blk_name, 'fab_gate'))) ];\ns.fab_en = num2str(strcmp(get_param(blk_name, 'fab_en'),'on'));\n\nb = class(s,'xps_tengbe',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','ten_gb_eth');\n\nswitch s.hw_sys\n case 'ROACH'\n b = set(b,'ip_version','3.00.a');\n otherwise\n error(['10GbE not supported for platform ', s.board]);\nend\n\n% bus offset\n\n% ROACH has an OPB Ten Gig Eth interface\nswitch s.hw_sys\n case 'ROACH'\n b = set(b,'opb_clk','epb_clk');\n b = set(b,'opb_address_offset',16384);\n b = set(b,'opb_address_align', hex2dec('4000'));\n % end case 'ROACH'\nend % switch s.hw_sys\n\nparameters.SWING = s.swing;\nparameters.PREEMPHASYS = s.preemph;\n\n% parameters\nswitch s.hw_sys\n case 'ROACH'\n parameters.DEFAULT_FABRIC_MAC = s.fab_mac;\n parameters.DEFAULT_FABRIC_IP = s.fab_ip;\n parameters.DEFAULT_FABRIC_PORT = s.fab_udp;\n parameters.DEFAULT_FABRIC_GATEWAY = s.fab_gate;\n parameters.FABRIC_RUN_ON_STARTUP = s.fab_en;\n % end case 'ROACH'\n \n otherwise\n parameters.CONNECTOR = s.port;\n\n if strcmp(s.mac_lite, '1')\n parameters.USE_XILINX_MAC = '0';\n parameters.USE_UCB_MAC = '1';\n else\n parameters.USE_XILINX_MAC = '1';\n parameters.USE_UCB_MAC = '0';\n end\n % end otherwise\nend % switch s.hw_sys\n\nb = set(b,'parameters',parameters);\n\n% bus interfaces\nswitch s.hw_sys\n case 'ROACH'\n % end case 'ROACH'\n interfaces.XAUI_CONF = ['xaui_conf',s.port];\n interfaces.XGMII = ['xgmii',s.port];\n b = set(b,'interfaces',interfaces);\n otherwise\n interfaces.XAUI_SYS = ['xaui_sys',s.port];\n b = set(b,'interfaces',interfaces);\n % end otherwise\nend % switch s.hw_sys\n\n% miscellaneous and external ports\n\nmisc_ports.clk = {1 'in' get(xsg_obj,'clk_src')};\n\next_ports = {};\n\nswitch s.hw_sys\n case 'ROACH'\n if strcmp(s.port, '0') || strcmp(s.port, '1')\n misc_ports.xaui_clk = {1 'in' 'mgt_clk_0'};\n else\n misc_ports.xaui_clk = {1 'in' 'mgt_clk_1'};\n end\n otherwise\n ext_ports.mgt_tx_l0_p = {1 'out' ['XAUI',s.port,'_tx_l0_p'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l0_n = {1 'out' ['XAUI',s.port,'_tx_l0_n'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l1_p = {1 'out' ['XAUI',s.port,'_tx_l1_p'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l1_n = {1 'out' ['XAUI',s.port,'_tx_l1_n'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l2_p = {1 'out' ['XAUI',s.port,'_tx_l2_p'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l2_n = {1 'out' ['XAUI',s.port,'_tx_l2_n'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l3_p = {1 'out' ['XAUI',s.port,'_tx_l3_p'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_tx_l3_n = {1 'out' ['XAUI',s.port,'_tx_l3_n'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l0_p = {1 'in' ['XAUI',s.port,'_rx_l0_p'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l0_n = {1 'in' ['XAUI',s.port,'_rx_l0_n'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l1_p = {1 'in' ['XAUI',s.port,'_rx_l1_p'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l1_n = {1 'in' ['XAUI',s.port,'_rx_l1_n'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l2_p = {1 'in' ['XAUI',s.port,'_rx_l2_p'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l2_n = {1 'in' ['XAUI',s.port,'_rx_l2_n'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l3_p = {1 'in' ['XAUI',s.port,'_rx_l3_p'] 'null' 'vector=false' struct() struct()};\n ext_ports.mgt_rx_l3_n = {1 'in' ['XAUI',s.port,'_rx_l3_n'] 'null' 'vector=false' struct() struct()};\n % end otherwise\nend % switch s.hw_sys\n\nb = set(b,'misc_ports',misc_ports);\nb = set(b,'ext_ports',ext_ports);\n\n% borf parameters\nswitch s.hw_sys\n case 'ROACH'\n borph_info.size = hex2dec('4000');\n borph_info.mode = 3;\n b = set(b,'borph_info',borph_info);\n otherwise\n borph_info.size = 1;\n borph_info.mode = 7;\n b = set(b,'borph_info',borph_info);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac_mkid/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac_mkid/drc.m", "size": 2992, "source_encoding": "utf_8", "md5": "3ab77bfce809915097a39d56418ecd9a", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'hw_dac'), get(xps_objs{i},'hw_dac'))\r\n\t\t\tif ~strcmp(get(blk_obj, 'simulink_name'), get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['DAC ', get(blk_obj, 'simulink_name'),' and DAC ', get(xps_objs{i}, 'simulink_name'), ' are using the same connector.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\n\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'type'),'xps_dac') && strcmp(get(xps_objs{i},'type'), 'xps_adc')\r\n\t\t if (strcmp(get(blk_obj,'hw_dac'),'dac0') && strcmp(get(xps_objs{i},'hw_adc'),'adc0')) || (strcmp(get(blk_obj,'hw_dac'),'dac1') && strcmp(get(xps_objs{i},'hw_adc'),'adc1'))\r\n\t\t msg = ['DAC ', get(blk_obj,'simulink_name'), ' and ADC ', get(xps_objs{i},'simulink_name'),' are located on the same Z-DOK connector.'];\r\n\t\t result = 1;\r\n\t\t end\r\n\t\tend\r\n end\r\n\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'type'),'xps_dac') && strcmp(get(xps_objs{i},'type'), 'xps_vsi')\r\n\t\t if strcmp(get(blk_obj,'hw_dac'),'dac1') && strcmp(get(xps_objs{i},'hw_vsi'),'ZDOK 1')\r\n\t\t msg = ['DAC ', get(blk_obj,'simulink_name'), ' and VSI ', get(xps_objs{i},'simulink_name'),' are located on the same Z-DOK connector.'];\r\n\t\t result = 1;\r\n\t\t end\r\n\t\tend\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_dac_mkid.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac_mkid/xps_dac_mkid.m", "size": 8300, "source_encoding": "utf_8", "md5": "e6816542a14a3dd28dc29edecfd3512d", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = xps_dac_mkid(blk_obj)\r\nif ~isa(blk_obj,'xps_block')\r\n error('XPS_DAC_MKID class requires a xps_block class object');\r\nend\r\nif ~strcmp(get(blk_obj,'type'),'xps_dac_mkid')\r\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\r\nend\r\n\r\n\r\nblk_name = get(blk_obj,'simulink_name');\r\nxsg_obj = get(blk_obj,'xsg_obj');\r\n\r\n % s.hw_dac = 'dac0' or 'dac1' as specified by the user in the yellow\r\n % block.\r\ns.hw_sys = get(xsg_obj,'hw_sys');\r\ns.dac_brd = get_param(blk_name, 'dac_brd');\r\ns.dac_str = ['dac', s.dac_brd];\r\n\r\ns.clk_sys = get(xsg_obj,'clk_src');\r\n\r\n\r\n % The clock coming from the zdok to the fpga is reduced by a physical\r\n % circuit on the DAC_MKID board to half of the rate of the external \r\n % clock provided by the user. The external clock rate is provided by\r\n % the user (in MHz) on the dac_mkid yellow block. The clock period \r\n % will be used in units of 1/GHz.\r\ns.dac_clk_rate = eval_param(blk_name,'dac_clk_rate')/2;\r\ndac_clk_period = 1000/s.dac_clk_rate;\r\n\r\n % The DAC sample rate is provided by the user on the yellow block.\r\n%s.dac_smpl_rate = eval_param(blk_name,'dac_smpl_rate');\r\n%dac_smpl_period = 1000/s.dac_smpl_rate;\r\n\r\nb = class(s,'xps_dac_mkid',blk_obj);\r\nb = set(b,'ip_name','dac_mkid_interface');\r\nb = set(b, 'ip_version', '1.01.a');\r\n \r\nparameters.OUTPUT_CLK = '0';\r\nif strfind(s.clk_sys,'dac')\r\n parameters.OUTPUT_CLK = '1';\r\nend\r\nb = set(b,'parameters',parameters);\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% external ports\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n % Collection of parameters used to define ports.\r\nucf_constraints_clk = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(dac_clk_period),' ns']);\r\nucf_constraints = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\r\nmhs_constraints_clk = struct('SIGIS','CLK', 'CLK_FREQ',num2str(s.dac_clk_rate));\r\n\r\n\r\n % The system clock for the FPGA fabric is generated from the CLK_to_FPGA \r\n % pins on the zdok from the MKID DAC. Reminder: s.dac_str = dac0 or\r\n % dac1.\r\next_ports.dac_clk_p = {1 'in' [s.dac_str,'_clk_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[40],:}}'] 'vector=false' mhs_constraints_clk ucf_constraints_clk};\r\next_ports.dac_clk_n = {1 'in' [s.dac_str,'_clk_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[40],:}}'] 'vector=false' mhs_constraints_clk ucf_constraints_clk};\r\n\r\n % DCLK is used to clock out data to the DAC.\r\next_ports.dac_smpl_clk_i_p = {1 'out' [s.dac_str,'_smpl_clk_i_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[30],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_smpl_clk_i_n = {1 'out' [s.dac_str,'_smpl_clk_i_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[30],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_smpl_clk_q_p = {1 'out' [s.dac_str,'_smpl_clk_q_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[29],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_smpl_clk_q_n = {1 'out' [s.dac_str,'_smpl_clk_q_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[29],:}}'] 'vector=false' struct() ucf_constraints};\r\n\r\n % I and Q output.\r\next_ports.dac_data_i_p = {16 'out' [s.dac_str,'_data_i_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[26 15 35 5 25 16 36 6 37 17 27 7 18 38 8 28],:}}'] 'vector=true' struct() ucf_constraints};\r\next_ports.dac_data_i_n = {16 'out' [s.dac_str,'_data_i_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[26 15 35 5 25 16 36 6 37 17 27 7 18 38 8 28],:}}'] 'vector=true' struct() ucf_constraints};\r\next_ports.dac_data_q_p = {16 'out' [s.dac_str,'_data_q_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[22 11 31 1 21 12 32 2 33 13 23 3 14 34 4 24],:}}'] 'vector=true' struct() ucf_constraints};\r\next_ports.dac_data_q_n = {16 'out' [s.dac_str,'_data_q_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[22 11 31 1 21 12 32 2 33 13 23 3 14 34 4 24],:}}'] 'vector=true' struct() ucf_constraints};\r\n\r\n % When dac_sync is high, dac output is enabled.\r\next_ports.dac_sync_i_p = {1 'out' [s.dac_str,'_sync_i_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[39],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_sync_i_n = {1 'out' [s.dac_str,'_sync_i_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[39],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_sync_q_p = {1 'out' [s.dac_str,'_sync_q_p'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_p{[20],:}}'] 'vector=false' struct() ucf_constraints};\r\next_ports.dac_sync_q_n = {1 'out' [s.dac_str,'_sync_q_n'] ['{',s.hw_sys,'.zdok',s.dac_brd,'_n{[20],:}}'] 'vector=false' struct() ucf_constraints};\r\n\r\n % Serial data enabled on low, which is why it's controlled by a not\r\n % sdenb.\r\next_ports.dac_not_sdenb_i = {1 'out' [s.dac_str,'_not_sdenb_i'] ['{',s.hw_sys,'.zdok',s.dac_brd,'{[18],:}}'] 'vector=false' struct() struct()};\r\next_ports.dac_not_sdenb_q = {1 'out' [s.dac_str,'_not_sdenb_q'] ['{',s.hw_sys,'.zdok',s.dac_brd,'{[19],:}}'] 'vector=false' struct() struct()};\r\n\r\n % SCLK is the clock used to write data to the DAC for configuration.\r\next_ports.dac_sclk = {1 'out' [s.dac_str,'_sclk'] ['{',s.hw_sys,'.zdok',s.dac_brd,'{[17],:}}'] 'vector=false' struct() struct()};\r\n\r\n % Each dac chip is wired for 4-wire interface, with only the input\r\n % available on the zdok.\r\next_ports.dac_sdi = {1 'out' [s.dac_str,'_sdi'] ['{',s.hw_sys,'.zdok',s.dac_brd,'{[37],:}}'] 'vector=false' struct() struct()};\r\n\r\n % Resets the dac when low.\r\next_ports.dac_not_reset = {1 'out' [s.dac_str,'_not_reset'] ['{',s.hw_sys,'.zdok',s.dac_brd,'{[38],:}}'] 'vector=false' struct() struct()};\r\n\r\n % This is mapped to a circuit on the board, and not on the chips\r\n % themselves. If dac_phase is low, both dac chips are in phase.\r\n%ext_ports.dac_phase = {1 'in' [s.dac_str,'_pase'] '{ROACH.zdok0{[20],:}}' 'vector=false' struct() struct()};\r\n\r\nb = set(b, 'ext_ports', ext_ports);\r\n\r\n\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% misc ports\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nmisc_ports.dac_smpl_clk = {1 'in' get(xsg_obj,'clk_src')};\r\n\r\nif strfind(s.clk_sys,'dac')\r\n misc_ports.dac_clk_out = {1 'out' [s.dac_str,'_clk']};\r\n misc_ports.dac_clk90_out = {1 'out' [s.dac_str,'_clk90']};\r\n misc_ports.dac_clk180_out = {1 'out' [s.dac_str,'_clk180']};\r\n misc_ports.dac_clk270_out = {1 'out' [s.dac_str,'_clk270']};\r\n misc_ports.dac_dcm_locked = {1 'out' [s.dac_str, '_dcm_locked']};\r\nend\r\n\r\nb = set(b,'misc_ports',misc_ports);\r\n\r\n\r\n\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac_mkid/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_katadc/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_katadc/drc.m", "size": 2118, "source_encoding": "utf_8", "md5": "60145324772f7335c69b7970ae3e68e3", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'hw_adc'),get(xps_objs{i},'hw_adc'))\r\n\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['ADC ',get(blk_obj,'simulink_name'),' and ADC ',get(xps_objs{i},'simulink_name'),' are located on the same port.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_katadc/gen_ucf.m", "size": 24748, "source_encoding": "utf_8", "md5": "3c603f1413ebb996764e586141bca3b1", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\n\nhw_sys = blk_obj.hw_sys;\nadc_str = blk_obj.adc_str;\nstr = gen_ucf(blk_obj.xps_block);\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\nswitch hw_sys\n case 'ROACH'\n switch adc_str\n case 'adc0'\n case 'adc1'\n % end case 'adc1'\n end % switch adc_str\n\n case 'iBOB'\n switch adc_str\n case 'adc0'\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" PERIOD = ',num2str(1000/blk_obj.adc_clk_rate*4),'ns;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" MAXDELAY = 452ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_dcm\" MAXDELAY = 853ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk90_dcm\" MAXDELAY = 853ps;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK_CLKBUF\" LOC = BUFGMUX1P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK90_CLKBUF\" LOC = BUFGMUX3P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" LOC = DCM_X2Y1;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" CLKOUT_PHASE_SHIFT = VARIABLE;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 559ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" ROUTE = \"{3;1;2vp50ff1152;46c47c12!-1;156520;5632;S!0;-159;0!1;-1884;-1248!1;-1884;744!2;-1548;992!2;-1548;304!3;-1548;-656!3;-1548;-1344!4;327;0;L!5;167;0;L!6;327;0;L!7;167;0;L!}\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_3\" LOC = SLICE_X139Y91;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_2\" LOC = SLICE_X138Y91;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_1\" LOC = SLICE_X139Y90;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_0\" LOC = SLICE_X138Y90;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_0\" LOC = \"SLICE_X138Y128\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_1\" LOC = \"SLICE_X138Y126\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_2\" LOC = \"SLICE_X139Y122\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_3\" LOC = \"SLICE_X138Y120\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_4\" LOC = \"SLICE_X138Y102\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_5\" LOC = \"SLICE_X139Y98\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_6\" LOC = \"SLICE_X138Y96\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_7\" LOC = \"SLICE_X138Y94\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_8\" LOC = \"SLICE_X139Y126\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_9\" LOC = \"SLICE_X138Y124\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_10\" LOC = \"SLICE_X138Y122\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_11\" LOC = \"SLICE_X139Y118\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_12\" LOC = \"SLICE_X138Y100\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_13\" LOC = \"SLICE_X138Y98\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_14\" LOC = \"SLICE_X139Y94\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_15\" LOC = \"SLICE_X138Y92\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_16\" LOC = \"SLICE_X138Y128\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_17\" LOC = \"SLICE_X138Y126\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_18\" LOC = \"SLICE_X139Y122\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_19\" LOC = \"SLICE_X138Y120\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_20\" LOC = \"SLICE_X138Y102\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_21\" LOC = \"SLICE_X139Y98\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_22\" LOC = \"SLICE_X138Y96\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_23\" LOC = \"SLICE_X138Y94\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_24\" LOC = \"SLICE_X139Y126\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_25\" LOC = \"SLICE_X138Y124\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_26\" LOC = \"SLICE_X138Y122\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_27\" LOC = \"SLICE_X139Y118\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_28\" LOC = \"SLICE_X138Y100\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_29\" LOC = \"SLICE_X138Y98\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_30\" LOC = \"SLICE_X139Y94\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_31\" LOC = \"SLICE_X138Y92\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_0\" LOC = \"SLICE_X138Y132\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_1\" LOC = \"SLICE_X139Y134\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_2\" LOC = \"SLICE_X138Y170\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_3\" LOC = \"SLICE_X138Y172\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_4\" LOC = \"SLICE_X139Y106\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_5\" LOC = \"SLICE_X138Y110\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_6\" LOC = \"SLICE_X138Y112\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_7\" LOC = \"SLICE_X139Y114\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_8\" LOC = \"SLICE_X138Y134\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_9\" LOC = \"SLICE_X138Y168\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_10\" LOC = \"SLICE_X139Y170\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_11\" LOC = \"SLICE_X138Y174\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_12\" LOC = \"SLICE_X138Y108\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_13\" LOC = \"SLICE_X139Y110\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_14\" LOC = \"SLICE_X138Y114\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_15\" LOC = \"SLICE_X138Y116\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_16\" LOC = \"SLICE_X138Y132\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_17\" LOC = \"SLICE_X139Y134\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_18\" LOC = \"SLICE_X138Y170\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_19\" LOC = \"SLICE_X138Y172\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_20\" LOC = \"SLICE_X139Y106\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_21\" LOC = \"SLICE_X138Y110\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_22\" LOC = \"SLICE_X138Y112\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_23\" LOC = \"SLICE_X139Y114\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_24\" LOC = \"SLICE_X138Y134\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_25\" LOC = \"SLICE_X138Y168\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_26\" LOC = \"SLICE_X139Y170\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_27\" LOC = \"SLICE_X138Y174\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_28\" LOC = \"SLICE_X138Y108\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_29\" LOC = \"SLICE_X139Y110\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_30\" LOC = \"SLICE_X138Y114\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_31\" LOC = \"SLICE_X138Y116\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_0\" LOC = \"SLICE_X138Y118\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_1\" LOC = \"SLICE_X138Y118\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_0\" LOC = \"SLICE_X138Y104\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_1\" LOC = \"SLICE_X138Y104\" | BEL = \"FFY\";\\n'];\n % end case 'adc0'\n\n case 'adc1'\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" PERIOD = ',num2str(1000/blk_obj.adc_clk_rate*4),'ns;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" MAXDELAY = 452ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_dcm\" MAXDELAY = 854ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk90_dcm\" MAXDELAY = 854ps;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK_CLKBUF\" LOC = BUFGMUX0P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK90_CLKBUF\" LOC = BUFGMUX2P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" LOC = DCM_X2Y0;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" CLKOUT_PHASE_SHIFT = VARIABLE;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 559ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" ROUTE = \"{3;1;2vp50ff1152;6b4b9e45!-1;156520;-144648;S!0;-159;0!1;-1884;-1248!1;-1884;744!2;-1548;992!2;-1548;304!3;-1548;-656!3;-1548;-1344!4;327;0;L!5;167;0;L!6;327;0;L!7;167;0;L!}\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_3\" LOC = SLICE_X139Y3;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_2\" LOC = SLICE_X138Y3;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_1\" LOC = SLICE_X139Y2;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_0\" LOC = SLICE_X138Y2;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_0\" LOC = \"SLICE_X139Y70\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_1\" LOC = \"SLICE_X138Y68\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_2\" LOC = \"SLICE_X139Y64\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_3\" LOC = \"SLICE_X139Y62\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_4\" LOC = \"SLICE_X139Y44\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_5\" LOC = \"SLICE_X139Y42\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_6\" LOC = \"SLICE_X138Y40\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_7\" LOC = \"SLICE_X139Y4\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_8\" LOC = \"SLICE_X139Y68\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_9\" LOC = \"SLICE_X139Y66\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_10\" LOC = \"SLICE_X138Y64\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_11\" LOC = \"SLICE_X139Y60\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_12\" LOC = \"SLICE_X138Y44\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_13\" LOC = \"SLICE_X139Y40\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_14\" LOC = \"SLICE_X139Y6\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_15\" LOC = \"SLICE_X138Y4\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_16\" LOC = \"SLICE_X139Y70\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_17\" LOC = \"SLICE_X138Y68\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_18\" LOC = \"SLICE_X139Y64\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_19\" LOC = \"SLICE_X139Y62\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_20\" LOC = \"SLICE_X139Y44\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_21\" LOC = \"SLICE_X139Y42\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_22\" LOC = \"SLICE_X138Y40\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_23\" LOC = \"SLICE_X139Y4\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_24\" LOC = \"SLICE_X139Y68\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_25\" LOC = \"SLICE_X139Y66\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_26\" LOC = \"SLICE_X138Y64\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_27\" LOC = \"SLICE_X139Y60\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_28\" LOC = \"SLICE_X138Y44\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_29\" LOC = \"SLICE_X139Y40\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_30\" LOC = \"SLICE_X139Y6\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_31\" LOC = \"SLICE_X138Y4\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_0\" LOC = \"SLICE_X139Y74\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_1\" LOC = \"SLICE_X139Y78\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_2\" LOC = \"SLICE_X139Y80\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_3\" LOC = \"SLICE_X138Y84\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_4\" LOC = \"SLICE_X139Y48\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_5\" LOC = \"SLICE_X138Y52\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_6\" LOC = \"SLICE_X139Y54\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_7\" LOC = \"SLICE_X139Y56\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_8\" LOC = \"SLICE_X138Y76\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_9\" LOC = \"SLICE_X138Y80\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_10\" LOC = \"SLICE_X139Y82\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_11\" LOC = \"SLICE_X139Y84\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_12\" LOC = \"SLICE_X139Y50\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_13\" LOC = \"SLICE_X139Y52\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_14\" LOC = \"SLICE_X138Y56\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_15\" LOC = \"SLICE_X139Y58\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_16\" LOC = \"SLICE_X139Y74\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_17\" LOC = \"SLICE_X139Y78\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_18\" LOC = \"SLICE_X139Y80\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_19\" LOC = \"SLICE_X138Y84\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_20\" LOC = \"SLICE_X139Y48\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_21\" LOC = \"SLICE_X138Y52\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_22\" LOC = \"SLICE_X139Y54\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_23\" LOC = \"SLICE_X139Y56\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_24\" LOC = \"SLICE_X138Y76\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_25\" LOC = \"SLICE_X138Y80\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_26\" LOC = \"SLICE_X139Y82\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_27\" LOC = \"SLICE_X139Y84\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_28\" LOC = \"SLICE_X139Y50\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_29\" LOC = \"SLICE_X139Y52\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_30\" LOC = \"SLICE_X138Y56\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_31\" LOC = \"SLICE_X139Y58\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_0\" LOC = \"SLICE_X138Y60\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_1\" LOC = \"SLICE_X138Y60\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_0\" LOC = \"SLICE_X138Y48\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_1\" LOC = \"SLICE_X138Y48\" | BEL = \"FFY\";\\n'];\n % end case 'adc1'\n end % switch adc_str\n % end case 'iBOB'\nend % switch hw_sys\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_katadc/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_katadc/gen_mhs_ip.m", "size": 5798, "source_encoding": "utf_8", "md5": "f368bf415bee0af6efc348b9437930e9", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj,opb_addr_start,opb_name)\n\nhw_adc = get(blk_obj, 'hw_adc');\n\n% HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK \n% Remove gain control ports from adc_interface intstantiation\ngain_load_port = '';\ngain_value_port = '';\nclk_src = get(blk_obj,'clk_src'); \nen_gain = get(blk_obj,'en_gain'); \n\nfoo = get(blk_obj,'ports');\nportname = fieldnames(foo);\nfor n = 1:length(portname)\n if (~isempty(regexp(portname{n},'gain_value')))\n gain_value_port = portname{n};\n foo = rmfield(foo, portname{n});\n end\n if (~isempty(regexp(portname{n},'gain_load')))\n gain_load_port = portname{n};\n foo = rmfield(foo, portname{n});\n end\n %port_names{n}\nend\n\nblk_obj = set(blk_obj,'ports',foo);\n\n% Add the MHS entry for the ADC Interface\n[str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj.xps_block, opb_addr_start, opb_name);\nstr = [str, '\\n'];\n\nif (strcmp(hw_adc, 'adc1'))\n base_addr = '0x00048000';\n high_addr = '0x000487ff';\nelse\n base_addr = '0x00040000';\n high_addr = '0x000407ff';\nend\n\n% Add IIC controller\nstr = [str, 'BEGIN kat_adc_iic_controller', '\\n'];\nstr = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\nstr = [str, ' PARAMETER INSTANCE = iic_', hw_adc, '\\n'];\nstr = [str, ' PARAMETER C_BASEADDR = ', base_addr, '\\n'];\nstr = [str, ' PARAMETER C_HIGHADDR = ', high_addr, '\\n'];\n\nif (strcmp(en_gain,'on'))\n str = [str, ' PARAMETER EN_GAIN = 1', '\\n'];\nend\n\nstr = [str, ' PARAMETER CORE_FREQ = 83333', '\\n'];\nstr = [str, ' PARAMETER IIC_FREQ = 100', '\\n'];\nstr = [str, ' BUS_INTERFACE SOPB = opb0', '\\n'];\nstr = [str, ' PORT OPB_Clk = epb_clk', '\\n'];\nstr = [str, '', '\\n'];\nstr = [str, ' PORT sda_i = iic_', hw_adc, '_sda_i', '\\n'];\nstr = [str, ' PORT sda_o = iic_', hw_adc, '_sda_o', '\\n'];\nstr = [str, ' PORT sda_t = iic_', hw_adc, '_sda_t', '\\n'];\nstr = [str, ' PORT scl_i = iic_', hw_adc, '_scl_i', '\\n'];\nstr = [str, ' PORT scl_o = iic_', hw_adc, '_scl_o', '\\n'];\nstr = [str, ' PORT scl_t = iic_', hw_adc, '_scl_t', '\\n'];\nstr = [str, ' PORT gain_value = ', gain_value_port, '\\n'];\nstr = [str, ' PORT gain_load = ', gain_load_port, '\\n'];\nstr = [str, ' PORT app_clk = ', clk_src, '\\n'];\nstr = [str, 'END', '\\n'];\nstr = [str, '', '\\n'];\nstr = [str, 'PORT ', hw_adc, '_iic_sda = ', hw_adc, '_iic_sda, DIR = IO', '\\n'];\nstr = [str, 'PORT ', hw_adc, '_iic_scl = ', hw_adc, '_iic_scl, DIR = IO', '\\n'];\nstr = [str, '', '\\n'];\nstr = [str, 'BEGIN iic_infrastructure', '\\n'];\nstr = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\nstr = [str, ' PARAMETER INSTANCE = iic_infrastructure_', hw_adc, '\\n'];\nstr = [str, ' PORT Sda_I = iic_', hw_adc, '_sda_i', '\\n'];\nstr = [str, ' PORT Sda_O = iic_', hw_adc, '_sda_o', '\\n'];\nstr = [str, ' PORT Sda_T = iic_', hw_adc, '_sda_t', '\\n'];\nstr = [str, ' PORT Scl_I = iic_', hw_adc, '_scl_i', '\\n'];\nstr = [str, ' PORT Scl_O = iic_', hw_adc, '_scl_o', '\\n'];\nstr = [str, ' PORT Scl_T = iic_', hw_adc, '_scl_t', '\\n'];\nstr = [str, ' PORT Sda = ', hw_adc, '_iic_sda', '\\n'];\nstr = [str, ' PORT Scl = ', hw_adc, '_iic_scl', '\\n'];\nstr = [str, 'END', '\\n'];\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_katadc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_katadc/xps_katadc.m", "size": 8293, "source_encoding": "utf_8", "md5": "ef9e33d6c36da8cdc4823bb0d8cc468a", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_katadc(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_ADC class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_katadc')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.hw_adc = get_param(blk_name,'adc_brd');\ns.clk_src = get(xsg_obj,'clk_src');\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.adc_interleave = get_param(blk_name,'adc_interleave');\ns.bypass_auto = get_param(blk_name,'bypass_auto');\ns.en_gain = get_param(blk_name,'en_gain');\n\nswitch s.hw_sys\n case {'ROACH2', 'ROACH'}\n if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n s.adc_str = s.hw_adc;\n else\n error(['Unsupported adc board: ',s.hw_adc]);\n end % if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(1000/s.adc_clk_rate*4),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n % end case {'ROACH2', 'ROACH'}\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend % end switch s.hw_sys\n\nb = class(s,'xps_katadc',blk_obj);\n\n% ip name and version\nb = set(b, 'ip_name', 'kat_adc_interface');\nswitch s.hw_sys\n case {'ROACH', 'ROACH2'},\n b = set(b, 'ip_version', '1.00.a');\n %hard-coded opb0 devices\n b = set(b, 'opb0_devices', 2); %IIC and controller\nend % switch s.hw_sys\n\nsupp_ip_names = {'', 'opb_katadccontroller'};\nsupp_ip_versions = {'', '1.00.a'};\n\nb = set(b, 'supp_ip_names', supp_ip_names);\nb = set(b, 'supp_ip_versions', supp_ip_versions);\n\n% misc ports\nmisc_ports.ctrl_reset = {1 'in' [s.adc_str,'_adc_reset']}; % We have an active high signal\nmisc_ports.ctrl_clk_in = {1 'in' get(xsg_obj,'clk_src')};\nmisc_ports.ctrl_clk_out = {1 'out' [s.adc_str,'_clk']};\nmisc_ports.ctrl_clk90_out = {1 'out' [s.adc_str,'_clk90']};\nmisc_ports.ctrl_clk180_out = {1 'out' [s.adc_str,'_clk180']};\nmisc_ports.ctrl_clk270_out = {1 'out' [s.adc_str,'_clk270']};\n\nswitch s.hw_sys\n case 'iBOB'\n misc_ports.ctrl_dcm_locked = {1 'out' [s.adc_str,'_dcm_locked']};\n misc_ports.dcm_reset = {1 'in' [s.adc_str,'_dcm_reset']};\n misc_ports.dcm_psdone = {1 'out' [s.adc_str,'_psdone']};\n misc_ports.dcm_psclk = {1 'in' [s.adc_str,'_psclk']};\n misc_ports.dcm_psen = {1 'in' [s.adc_str,'_psen']};\n misc_ports.dcm_psincdec = {1 'in' [s.adc_str,'_psincdec']};\n case 'ROACH'\n misc_ports.ctrl_dcm_locked = {1 'out' [s.adc_str,'_dcm_locked']};\n misc_ports.dcm_reset = {1 'in' [s.adc_str,'_dcm_reset']};\n misc_ports.dcm_psdone = {1 'out' [s.adc_str,'_psdone']};\n misc_ports.dcm_psclk = {1 'in' [s.adc_str,'_psclk']};\n misc_ports.dcm_psen = {1 'in' [s.adc_str,'_psen']};\n misc_ports.dcm_psincdec = {1 'in' [s.adc_str,'_psincdec']};\n case 'ROACH2'\n misc_ports.ctrl_mmcm_locked = {1 'out' [s.adc_str,'_mmcm_locked']};\n misc_ports.mmcm_reset = {1 'in' [s.adc_str,'_mmcm_reset']};\n misc_ports.mmcm_psdone = {1 'out' [s.adc_str,'_psdone']};\n misc_ports.mmcm_psclk = {1 'in' [s.adc_str,'_psclk']};\n misc_ports.mmcm_psen = {1 'in' [s.adc_str,'_psen']};\n misc_ports.mmcm_psincdec = {1 'in' [s.adc_str,'_psincdec']};\nend\n\nb = set(b,'misc_ports',misc_ports);\n\n% external ports\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(s.adc_clk_rate*1e6));\n\nadcport = [s.hw_sys, '.', 'zdok', s.adc_str(length(s.adc_str))];\n\next_ports.adc_clk_p = {1 'in' [s.adc_str,'clk_p'] ['{',adcport,'_p{[19]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc_clk_n = {1 'in' [s.adc_str,'clk_n'] ['{',adcport,'_n{[19]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc_sync_p = {1 'in' [s.adc_str,'sync_p'] ['{',adcport,'_p{[31]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc_sync_n = {1 'in' [s.adc_str,'sync_n'] ['{',adcport,'_n{[31]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc_overrange_p = {1 'in' [s.adc_str,'overrange_p'] ['{',adcport,'_p{[39]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc_overrange_n = {1 'in' [s.adc_str,'overrange_n'] ['{',adcport,'_n{[39]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.adc_di_d_p = {8 'in' [s.adc_str,'di_d_p'] ['{',adcport,'_p{[21 1 11 22 2 32 12 23]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_di_d_n = {8 'in' [s.adc_str,'di_d_n'] ['{',adcport,'_n{[21 1 11 22 2 32 12 23]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_di_p = {8 'in' [s.adc_str,'di_p'] ['{',adcport,'_p{[3 33 13 24 4 34 14 25]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_di_n = {8 'in' [s.adc_str,'di_n'] ['{',adcport,'_n{[3 33 13 24 4 34 14 25]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dq_d_p = {8 'in' [s.adc_str,'dq_d_p'] ['{',adcport,'_p{[9 29 18 38 8 28 17 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dq_d_n = {8 'in' [s.adc_str,'dq_d_n'] ['{',adcport,'_n{[9 29 18 38 8 28 17 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dq_p = {8 'in' [s.adc_str,'dq_p'] ['{',adcport,'_p{[7 27 16 36 6 26 15 35]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_dq_n = {8 'in' [s.adc_str,'dq_n'] ['{',adcport,'_n{[7 27 16 36 6 26 15 35]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.adc_rst = {1 'out' [s.adc_str,'rst'] ['{',adcport,'_p{[5]+1,:}}'] 'vector=false' struct() };\next_ports.adc_powerdown = {1 'out' [s.adc_str,'powerdown'] ['{',adcport,'_p{[10]+1,:}}'] 'vector=false' struct() };\n\nb = set(b,'ext_ports',ext_ports);\n\n% Software parameters\nb = set(b,'c_params',['adc = ',s.adc_str,' / interleave = ',s.adc_interleave]);\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc16/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adc16.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc16/xps_adc16.m", "size": 14989, "source_encoding": "utf_8", "md5": "61380db7777f7b248426b11f1d2960db", "text": "\nfunction b = xps_adc16(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_ADC class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_adc16')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\ninst_name = clear_name(blk_name);\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.roach2_rev = get_param(blk_name,'roach2_rev');\nzdok_rev = str2num(get_param(blk_name,'zdok_rev'));\nboard_count = get_param(blk_name,'board_count'); % Number of ADC boards\ns.num_units = 4*str2num(board_count); % Number of ADC chips\ns.fabric_mhz = get(xsg_obj,'clk_rate');\ns.line_mhz = 2 * s.fabric_mhz;\n% Default num_clocks to board_count (i.e. one clock per board)\nnum_clocks = str2num(board_count);\n% If zdok_rev is 1, we have one clock per chip\nif zdok_rev == 1\n num_clocks = s.num_units;\nend\n\n% Validate hw_sys\nswitch s.hw_sys\n case {'ROACH2'} %,'ROACH'}\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend \n\n% Validate num_units\nif s.num_units ~= 4 && s.num_units ~= 8\n error('Number of ADC16 boards must be 1 or 2');\nend\n\n% Validate fabric_mhz\nif s.fabric_mhz> 250\n error('Max fabric clock rate with ADC16 is 250 MHz');\nend\n\n% Miscellaneous UCF related items\nif zdok_rev == 1\n %b = set(b,'line_clk_index',3);\n s.line_clk_index = 3;\n\n % Control singal pins for zdok revision 1 are the same for both ROACH2\n % revisions because the control signals went via GPIO headers and ribbon\n % cables to ADC baords.\n\n % Control signal pins for ADC in ZDOK 0\n s.pin_csn1 = 'LOC = F16 | IOSTANDARD = LVCMOS15';\n s.pin_csn2 = 'LOC = H18 | IOSTANDARD = LVCMOS15';\n s.pin_csn3 = 'LOC = N20 | IOSTANDARD = LVCMOS15';\n s.pin_csn4 = 'LOC = N19 | IOSTANDARD = LVCMOS15';\n s.pin_sdata0 = 'LOC = K30 | IOSTANDARD = LVCMOS15';\n s.pin_sclk0 = 'LOC = M28 | IOSTANDARD = LVCMOS15';\n % Control signal pins for ADC in ZDOK 1\n s.pin_csn5 = 'LOC = H30 | IOSTANDARD = LVCMOS15';\n s.pin_csn6 = 'LOC = L30 | IOSTANDARD = LVCMOS15';\n s.pin_csn7 = 'LOC = AG33 | IOSTANDARD = LVCMOS15';\n s.pin_csn8 = 'LOC = AF32 | IOSTANDARD = LVCMOS15';\n s.pin_sdata1 = 'LOC = H31 | IOSTANDARD = LVCMOS15';\n s.pin_sclk1 = 'LOC = G31 | IOSTANDARD = LVCMOS15';\n\nelse % ZDOK revision 2\n %b = set(b,'line_clk_index',0);\n s.line_clk_index = 0;\n\n % Control singal pins for zdok revision 2 are different for ROACH2 rev 1 and\n % rev 2 because they go through the ZDOK connectors now. Set them all for\n % ROACH2 rev2, then tweak the ones that need changing for ROACH2 rev 1.\n\n % Control signal pins for ZDOK 0\n s.pin_csn1 = 'LOC = R29 | IOSTANDARD = LVCMOS25';\n s.pin_csn2 = 'LOC = P28 | IOSTANDARD = LVCMOS25';\n s.pin_csn3 = 'LOC = N31 | IOSTANDARD = LVCMOS25'; % Rev 1: M32\n s.pin_csn4 = 'LOC = N28 | IOSTANDARD = LVCMOS25';\n s.pin_sdata0 = 'LOC = R28 | IOSTANDARD = LVCMOS25';\n s.pin_sclk0 = 'LOC = M31 | IOSTANDARD = LVCMOS25'; % Rev 1: M33\n % Control signal pins for ZDOK 1\n s.pin_csn5 = 'LOC = Y35 | IOSTANDARD = LVCMOS25';\n s.pin_csn6 = 'LOC = Y32 | IOSTANDARD = LVCMOS25';\n s.pin_csn7 = 'LOC = Y37 | IOSTANDARD = LVCMOS25';\n s.pin_csn8 = 'LOC = AA32 | IOSTANDARD = LVCMOS25';\n s.pin_sdata1 = 'LOC = AA35 | IOSTANDARD = LVCMOS25';\n s.pin_sclk1 = 'LOC = W37 | IOSTANDARD = LVCMOS25';\n\n % Tweak pins for ROACH2 Revision 1\n if strcmp(s.roach2_rev,'1')\n s.pin_csn3 = 'LOC = M32 | IOSTANDARD = LVCMOS25';\n s.pin_sclk0 = 'LOC = M33 | IOSTANDARD = LVCMOS25';\n end\nend\n\nb = class(s,'xps_adc16',blk_obj);\n\n% ip name and version\nb = set(b, 'ip_name', 'adc16_interface');\nswitch s.hw_sys\n case {'ROACH', 'ROACH2'},\n b = set(b, 'ip_version', '1.00.a');\nend\n\nb = set(b, 'opb0_devices', 1 + s.num_units); % controller plus snap BRAMs\n\n% Tells which other PCORES are needed for this block\nsupp_ip_names = {'', 'opb_adc16_controller'};\nsupp_ip_versions = {'','1.00.a'};\nb = set(b, 'supp_ip_names', supp_ip_names);\nb = set(b, 'supp_ip_versions', supp_ip_versions);\n\n% These parameters become generics of the adc16_interface. Even though we\n% really want G_ROACH2_REV to be a generic of adc16_controller, that is not\n% possible (at least to this yellow block developer) so we set them up as\n% generics of the adc16_interface which simply outputs them to the\n% adc16_controller (via wires in system.mhs).\nparameters.G_ROACH2_REV = s.roach2_rev;\nparameters.G_ZDOK_REV = num2str(zdok_rev);\nparameters.G_NUM_UNITS = num2str(s.num_units);\nparameters.G_NUM_CLOCKS = num2str(num_clocks);\nb = set(b,'parameters',parameters);\n\n% ports\n\n%b = set(b,'ports', ports);\n\n% misc ports\n\nmisc_ports.fabric_clk = {1 'out' 'adc0_clk'};\nmisc_ports.fabric_clk_90 = {1 'out' 'adc0_clk90'};\nmisc_ports.fabric_clk_180 = {1 'out' 'adc0_clk180'};\nmisc_ports.fabric_clk_270 = {1 'out' 'adc0_clk270'};\n\nmisc_ports.reset = {1 'in' 'adc16_reset'};\nmisc_ports.iserdes_bitslip = {8 'in' 'adc16_iserdes_bitslip'};\nmisc_ports.demux_mode = {2 'in' 'adc16_demux_mode'};\n\nmisc_ports.delay_rst = {32 'in' 'adc16_delay_rst'};\nmisc_ports.delay_tap = { 5 'in' 'adc16_delay_tap'};\n\nmisc_ports.snap_req = { 1 'in' 'adc16_snap_req'};\nmisc_ports.snap_we = { 1 'out' 'adc16_snap_we'};\nmisc_ports.snap_addr = {10 'out' 'adc16_snap_addr'};\n\nmisc_ports.locked = {2 'out' 'adc16_locked'};\nmisc_ports.roach2_rev = {2 'out' 'adc16_roach2_rev'};\nmisc_ports.zdok_rev = {2 'out' 'adc16_zdok_rev'};\nmisc_ports.num_units = {4 'out' 'adc16_num_units'};\n\nif zdok_rev == 2\n misc_ports.clk_frame_p = {num_clocks 'in' 'net_gnd'};\n misc_ports.clk_frame_n = {num_clocks 'in' 'net_gnd'};\nend\n\nb = set(b,'misc_ports',misc_ports);\n\n% external ports\nmhs_constraints = struct();\nucf_constraints_lvds = struct( ...\n 'IOSTANDARD', 'LVDS_25', ...\n 'DIFF_TERM', 'TRUE');\n\n% Setup pins_1 and pins_2 for roach2 (rev2) zdok0 and zdok1\n% \"...pins_1\" are for zdok revision 1\n% \"...pins_2\" are for zdok revision 2\n\nr2_zdok0_clk_p_pins_1 = {'R28', 'H39', 'J42', 'P30'};\nr2_zdok0_clk_n_pins_1 = {'R29', 'H38', 'K42', 'P31'};\n\nr2_zdok0_frm_p_pins_1 = {'P27', 'G34', 'F39', 'B37'};\nr2_zdok0_frm_n_pins_1 = {'R27', 'H34', 'G39', 'A37'};\n\nr2_zdok0_ser_a_p_pins_1 = {\n 'J37',\n 'L35',\n 'K37', % rev1: L34\n 'L31',\n 'J35',\n 'K38',\n 'K39',\n 'N29',\n 'F40',\n 'E42',\n 'H36',\n 'D40',\n 'B38',\n 'D38',\n 'F35',\n 'B39',\n};\n\nr2_zdok0_ser_a_n_pins_1 = {\n 'J36',\n 'L36',\n 'L37', % rev1: M34\n 'L32',\n 'H35',\n 'J38',\n 'K40',\n 'N30',\n 'F41',\n 'F42',\n 'G36',\n 'E40',\n 'A39',\n 'C38',\n 'F36',\n 'C39',\n};\n\nr2_zdok0_ser_b_p_pins_1 = {\n 'K33',\n 'M33', % rev1: M36\n 'M31', % rev1: M33\n 'N28',\n 'H40',\n 'L34', % rev1: K37\n 'K35',\n 'J40',\n 'C40',\n 'F37',\n 'G41',\n 'G37',\n 'B41',\n 'A40',\n 'E39',\n 'D42',\n};\n\nr2_zdok0_ser_b_n_pins_1 = {\n 'K32',\n 'M32', % rev1: M37\n 'N31', % rev1: M32\n 'P28',\n 'H41',\n 'M34', % rev1: L37\n 'K34',\n 'J41',\n 'C41',\n 'E37',\n 'G42',\n 'G38',\n 'B42',\n 'A41',\n 'E38',\n 'D41',\n};\n\nr2_zdok1_clk_p_pins_1 = {'AA35', 'V34', 'W30', 'AE30'};\nr2_zdok1_clk_n_pins_1 = {'Y35', 'U34', 'V30', 'AF30'};\n\nr2_zdok1_frm_p_pins_1 = {'AA34', 'U37', 'T39', 'N40'};\nr2_zdok1_frm_n_pins_1 = {'Y34', 'U38', 'R38', 'N41'};\n\nr2_zdok1_ser_a_p_pins_1 = {\n 'W42',\n 'W35',\n 'Y38',\n 'AA36',\n 'U42',\n 'V38',\n 'V41',\n 'W36',\n 'R40',\n 'T41',\n 'R35',\n 'T34',\n 'M41',\n 'N38',\n 'M36', % rev1: N36\n 'P36',\n};\n\nr2_zdok1_ser_a_n_pins_1 = {\n 'Y42',\n 'V35',\n 'AA39',\n 'AA37',\n 'U41',\n 'W38',\n 'W41',\n 'V36',\n 'T40',\n 'T42',\n 'R34',\n 'T35',\n 'M42',\n 'N39',\n 'M37', % rev1: P37\n 'P35',\n};\n\nr2_zdok1_ser_b_p_pins_1 = {\n 'V33',\n 'W32',\n 'W37',\n 'AA32',\n 'U39',\n 'V40',\n 'U32',\n 'Y40',\n 'R39',\n 'P42',\n 'R37',\n 'U36',\n 'L41',\n 'M38',\n 'N36', % rev1: M31\n 'P40',\n};\n\nr2_zdok1_ser_b_n_pins_1 = {\n 'W33',\n 'Y33',\n 'Y37',\n 'Y32',\n 'V39',\n 'W40',\n 'U33',\n 'Y39',\n 'P38',\n 'R42',\n 'T37',\n 'T36',\n 'L42',\n 'M39',\n 'P37', % rev1: N31\n 'P41',\n};\n\nr2_zdok0_clk_p_pins_2 = {'P30'};\nr2_zdok0_clk_n_pins_2 = {'P31'};\n\n%r2_zdok0_frm_p_pins_2 = {};\n%r2_zdok0_frm_n_pins_2 = {};\n\nr2_zdok0_ser_a_p_pins_2 = {\n 'K39',\n 'J40',\n 'N29',\n 'L35',\n 'G37',\n 'H39',\n 'G34',\n 'K38',\n 'F35',\n 'B39',\n 'F37',\n 'H36',\n 'B41',\n 'J42',\n 'E39',\n 'B38',\n};\n\nr2_zdok0_ser_a_n_pins_2 = {\n 'K40',\n 'J41',\n 'N30',\n 'L36',\n 'G38',\n 'H38',\n 'H34',\n 'J38',\n 'F36',\n 'C39',\n 'E37',\n 'G36',\n 'B42',\n 'K42',\n 'E38',\n 'A39',\n};\n\nr2_zdok0_ser_b_p_pins_2 = {\n 'L34', % rev1: K37\n 'K35',\n 'K33',\n 'J37',\n 'F39',\n 'G41',\n 'H40',\n 'J35',\n 'C40',\n 'F40',\n 'E42',\n 'D40',\n 'B37',\n 'A40',\n 'D38',\n 'D42',\n};\n\nr2_zdok0_ser_b_n_pins_2 = {\n 'M34', % rev1: L37\n 'K34',\n 'K32',\n 'J36',\n 'G39',\n 'G42',\n 'H41',\n 'H35',\n 'C41',\n 'F41',\n 'F42',\n 'E40',\n 'A37',\n 'A41',\n 'C38',\n 'D41',\n};\n\nr2_zdok1_clk_p_pins_2 = {'AE30'};\nr2_zdok1_clk_n_pins_2 = {'AF30'};\n\n%r2_zdok1_frm_p_pins_2 = {};\n%r2_zdok1_frm_n_pins_2 = {};\n\nr2_zdok1_ser_a_p_pins_2 = {\n 'V41',\n 'Y40',\n 'W36',\n 'W35',\n 'U36',\n 'V34',\n 'U37',\n 'V38',\n 'M36', % rev1: N36\n 'P36',\n 'P42',\n 'R35',\n 'L41',\n 'W30',\n 'N36', % rev1: M31\n 'M41',\n};\n\nr2_zdok1_ser_a_n_pins_2 = {\n 'W41',\n 'Y39',\n 'V36',\n 'V35',\n 'T36',\n 'U34',\n 'U38',\n 'W38',\n 'M37', % rev1: P37\n 'P35',\n 'R42',\n 'R34',\n 'L42',\n 'V30',\n 'P37', % rev1: N31\n 'M42',\n};\n\nr2_zdok1_ser_b_p_pins_2 = {\n 'V40',\n 'U32',\n 'V33',\n 'W42',\n 'T39',\n 'R37',\n 'U39',\n 'U42',\n 'R39',\n 'R40',\n 'T41',\n 'T34',\n 'N40',\n 'M38',\n 'N38',\n 'P40',\n};\n\nr2_zdok1_ser_b_n_pins_2 = {\n 'W40',\n 'U33',\n 'W33',\n 'Y42',\n 'R38',\n 'T37',\n 'V39',\n 'U41',\n 'P38',\n 'T40',\n 'T42',\n 'T35',\n 'N41',\n 'M39',\n 'N39',\n 'P41',\n};\n\n% Tweak pins for ROACH2 Revision 1\nif strcmp(s.roach2_rev,'1')\n % ZDOK revision 1\n r2_zdok0_ser_a_p_pins_1{3} = 'L34';\n r2_zdok0_ser_a_n_pins_1{3} = 'M34';\n\n r2_zdok0_ser_b_p_pins_1{2} = 'M36';\n r2_zdok0_ser_b_n_pins_1{2} = 'M37';\n\n r2_zdok0_ser_b_p_pins_1{3} = 'M33';\n r2_zdok0_ser_b_n_pins_1{3} = 'M32';\n\n r2_zdok0_ser_b_p_pins_1{6} = 'K37';\n r2_zdok0_ser_b_n_pins_1{6} = 'L37';\n\n r2_zdok1_ser_a_p_pins_1{15} = 'N36';\n r2_zdok1_ser_a_n_pins_1{15} = 'P37';\n\n r2_zdok1_ser_b_p_pins_1{15} = 'M31';\n r2_zdok1_ser_b_n_pins_1{15} = 'N31';\n\n % ZDOK revision 2\n r2_zdok0_ser_b_p_pins_2{1} = 'K37';\n r2_zdok0_ser_b_n_pins_2{1} = 'L37';\n\n r2_zdok1_ser_a_p_pins_2{9} = 'N36';\n r2_zdok1_ser_a_n_pins_2{9} = 'P37';\n\n r2_zdok1_ser_1_p_pins_2{15} = 'M31';\n r2_zdok1_ser_1_n_pins_2{15} = 'N31';\nend\n\n% TODO Select roach1 or roach2 and zdok0 or zdok1, but for now only roach2 zdok0\nif zdok_rev == 1\n zdok0_clock_p_str = sprintf('''%s'',', r2_zdok0_clk_p_pins_1{:});\n zdok0_clock_n_str = sprintf('''%s'',', r2_zdok0_clk_n_pins_1{:});\n zdok0_frame_p_str = sprintf('''%s'',', r2_zdok0_frm_p_pins_1{:});\n zdok0_frame_n_str = sprintf('''%s'',', r2_zdok0_frm_n_pins_1{:});\n zdok0_ser_a_p_str = sprintf('''%s'',', r2_zdok0_ser_a_p_pins_1{:});\n zdok0_ser_a_n_str = sprintf('''%s'',', r2_zdok0_ser_a_n_pins_1{:});\n zdok0_ser_b_p_str = sprintf('''%s'',', r2_zdok0_ser_b_p_pins_1{:});\n zdok0_ser_b_n_str = sprintf('''%s'',', r2_zdok0_ser_b_n_pins_1{:});\n\n zdok1_clock_p_str = sprintf('''%s'',', r2_zdok1_clk_p_pins_1{:});\n zdok1_clock_n_str = sprintf('''%s'',', r2_zdok1_clk_n_pins_1{:});\n zdok1_frame_p_str = sprintf('''%s'',', r2_zdok1_frm_p_pins_1{:});\n zdok1_frame_n_str = sprintf('''%s'',', r2_zdok1_frm_n_pins_1{:});\n zdok1_ser_a_p_str = sprintf('''%s'',', r2_zdok1_ser_a_p_pins_1{:});\n zdok1_ser_a_n_str = sprintf('''%s'',', r2_zdok1_ser_a_n_pins_1{:});\n zdok1_ser_b_p_str = sprintf('''%s'',', r2_zdok1_ser_b_p_pins_1{:});\n zdok1_ser_b_n_str = sprintf('''%s'',', r2_zdok1_ser_b_n_pins_1{:});\nelse\n zdok0_clock_p_str = sprintf('''%s'',', r2_zdok0_clk_p_pins_2{:});\n zdok0_clock_n_str = sprintf('''%s'',', r2_zdok0_clk_n_pins_2{:});\n zdok0_frame_p_str = ',';\n zdok0_frame_n_str = ',';\n zdok0_ser_a_p_str = sprintf('''%s'',', r2_zdok0_ser_a_p_pins_2{:});\n zdok0_ser_a_n_str = sprintf('''%s'',', r2_zdok0_ser_a_n_pins_2{:});\n zdok0_ser_b_p_str = sprintf('''%s'',', r2_zdok0_ser_b_p_pins_2{:});\n zdok0_ser_b_n_str = sprintf('''%s'',', r2_zdok0_ser_b_n_pins_2{:});\n\n zdok1_clock_p_str = sprintf('''%s'',', r2_zdok1_clk_p_pins_2{:});\n zdok1_clock_n_str = sprintf('''%s'',', r2_zdok1_clk_n_pins_2{:});\n zdok1_frame_p_str = ',';\n zdok1_frame_n_str = ',';\n zdok1_ser_a_p_str = sprintf('''%s'',', r2_zdok1_ser_a_p_pins_2{:});\n zdok1_ser_a_n_str = sprintf('''%s'',', r2_zdok1_ser_a_n_pins_2{:});\n zdok1_ser_b_p_str = sprintf('''%s'',', r2_zdok1_ser_b_p_pins_2{:});\n zdok1_ser_b_n_str = sprintf('''%s'',', r2_zdok1_ser_b_n_pins_2{:});\nend\n\nif s.num_units == 4\n % Remove trainling comma from pin strings and surround with braces\n clock_p_str = ['{', zdok0_clock_p_str(1:end-1), '}'];\n clock_n_str = ['{', zdok0_clock_n_str(1:end-1), '}'];\n frame_p_str = ['{', zdok0_frame_p_str(1:end-1), '}'];\n frame_n_str = ['{', zdok0_frame_n_str(1:end-1), '}'];\n ser_a_p_str = ['{', zdok0_ser_a_p_str(1:end-1), '}'];\n ser_a_n_str = ['{', zdok0_ser_a_n_str(1:end-1), '}'];\n ser_b_p_str = ['{', zdok0_ser_b_p_str(1:end-1), '}'];\n ser_b_n_str = ['{', zdok0_ser_b_n_str(1:end-1), '}'];\nelse\n % Remove trainling comma from pin strings and surround with braces\n clock_p_str = ['{', zdok0_clock_p_str, zdok1_clock_p_str(1:end-1), '}'];\n clock_n_str = ['{', zdok0_clock_n_str, zdok1_clock_n_str(1:end-1), '}'];\n frame_p_str = ['{', zdok0_frame_p_str, zdok1_frame_p_str(1:end-1), '}'];\n frame_n_str = ['{', zdok0_frame_n_str, zdok1_frame_n_str(1:end-1), '}'];\n ser_a_p_str = ['{', zdok0_ser_a_p_str, zdok1_ser_a_p_str(1:end-1), '}'];\n ser_a_n_str = ['{', zdok0_ser_a_n_str, zdok1_ser_a_n_str(1:end-1), '}'];\n ser_b_p_str = ['{', zdok0_ser_b_p_str, zdok1_ser_b_p_str(1:end-1), '}'];\n ser_b_n_str = ['{', zdok0_ser_b_n_str, zdok1_ser_b_n_str(1:end-1), '}'];\nend\n\next_ports.clk_line_p = {num_clocks 'in' 'adc16_clk_line_p' clock_p_str 'vector=true' mhs_constraints ucf_constraints_lvds };\next_ports.clk_line_n = {num_clocks 'in' 'adc16_clk_line_n' clock_n_str 'vector=true' mhs_constraints ucf_constraints_lvds };\n\nif zdok_rev == 1\n ext_ports.clk_frame_p = {s.num_units 'in' 'adc16_clk_frame_p' frame_p_str 'vector=true' mhs_constraints ucf_constraints_lvds };\n ext_ports.clk_frame_n = {s.num_units 'in' 'adc16_clk_frame_n' frame_n_str 'vector=true' mhs_constraints ucf_constraints_lvds };\nend\n\next_ports.ser_a_p = {4*s.num_units 'in' 'adc16_ser_a_p' ser_a_p_str 'vector=true' mhs_constraints ucf_constraints_lvds };\next_ports.ser_a_n = {4*s.num_units 'in' 'adc16_ser_a_n' ser_a_n_str 'vector=true' mhs_constraints ucf_constraints_lvds };\next_ports.ser_b_p = {4*s.num_units 'in' 'adc16_ser_b_p' ser_b_p_str 'vector=true' mhs_constraints ucf_constraints_lvds };\next_ports.ser_b_n = {4*s.num_units 'in' 'adc16_ser_b_n' ser_b_n_str 'vector=true' mhs_constraints ucf_constraints_lvds };\n\nb = set(b,'ext_ports',ext_ports);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc16/drc.m", "size": 2138, "source_encoding": "utf_8", "md5": "790f7b0ee6445715562ff90d177efc3e", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\n% for i=1:length(xps_objs)\r\n% \ttry\r\n% \t\tif strcmp(get(blk_obj,'hw_adc'),get(xps_objs{i},'hw_adc'))\r\n% \t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n% \t\t\t\tmsg = ['ADC ',get(blk_obj,'simulink_name'),' and ADC ',get(xps_objs{i},'simulink_name'),' are located on the same port.'];\r\n% \t\t\t\tresult = 1;\r\n% \t\t\tend\r\n% \t\tend\r\n% \tend\r\n% end"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc16/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc16/gen_mhs_ip.m", "size": 5607, "source_encoding": "utf_8", "md5": "b30b167c4c1c28523d36cf15e73049ec", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2012 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj,opb_addr_start,opb_name)\n\n% Generate MHS stanzas for ADC16's built-in snapshot BRAMs.\n%\n% The adc16_interface pcore has no OPB interfaces itself, but it does provide\n% outputs to drive embedded (i.e. not in the Simulink model) shared BRAMs. The\n% shared BRAMs are \"attached\" to the OPB bus by the MHS stanzas returned by\n% this function. The ADC16 yellow block also has an embedded\n% \"opb_adc16_controller\" instance that drives the 3-wire interface to the ADCs\n% and the IODELAY tap settings to the adc16_interface instance. The ADC16\n% yellow block appears in the OPB address space as a 20 KB block ram. The\n% first 4KB of address space holds the control registers. The remaining 16 KB\n% of address space holds the shared BRAMs for the 4 ADC chips (4 KB per ADC).\n%\n% Note that ADCs are special yellow blocks in that they have a fixed starting\n% address within the OPB address space, namely 0x0020_0000.\n%\n% Here is the adc16_controller memory map:\n%\n% 0x0002_0000 - 0x0002_0FFF : Control registers\n% 0x0002_1000 - 0x0002_1FFF : Snapshot buffer for ADC A\n% 0x0002_2000 - 0x0002_2FFF : Snapshot buffer for ADC B\n% 0x0002_3000 - 0x0002_3FFF : Snapshot buffer for ADC C\n% 0x0002_4000 - 0x0002_4FFF : Snapshot buffer for ADC D\n%\n% Note that a single Shared BRAM consists of a trio of separate pcores:\n%\n% * bram_if - This is the \"fabric\" (i.e. Simulink) side of the Shared BRAM.\n% * bram_block - This is the actual dual-port BRAM primitive.\n% * opb_bram_if_cntlr - This is the OPB side of the Shared BRAM.\n\n% Call gen_mhs_ip for superclass xps_block to create adc16_interface instance\n[str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj.xps_block,opb_addr_start,opb_name);\n\n% Then generate embedded Shared BRAM blocks to follow opb_adc16_controller in\n% OPB address space.\n\nblk_name = get(blk_obj,'simulink_name');\ninst_name = clear_name(blk_name);\nxsg_obj = get(blk_obj,'xsg_obj');\n\n% Start address for embedded opb_adc16_controller instance\nadc_addr_start = hex2dec('00020000');\n\nsnap_chan = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};\n\nstr = [str, '\\n'];\n\nfor k = 1:blk_obj.num_units\n snap_name = ['adc16_snap_', snap_chan{k}];\n\n str = [str, '# ', blk_name, ' - Embedded Shared BRAM for ADC ', upper(snap_chan{k}), '\\n'];\n str = [str, 'BEGIN bram_if\\n'];\n str = [str, ' PARAMETER INSTANCE = ',snap_name,'_ramif\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a\\n'];\n str = [str, ' PARAMETER ADDR_SIZE = 10\\n'];\n str = [str, ' BUS_INTERFACE PORTA = ',snap_name,'_ramblk_porta\\n'];\n str = [str, ' PORT clk_in = ',get(xsg_obj,'clk_src'),'\\n'];\n str = [str, ' PORT addr = adc16_snap_addr\\n'];\n str = [str, ' PORT data_in = ',inst_name,'_',snap_chan{k}, '1 & ', ...\n inst_name,'_',snap_chan{k}, '2 & ', ...\n inst_name,'_',snap_chan{k}, '3 & ', ...\n inst_name,'_',snap_chan{k}, '4\\n'];\n %str = [str, ' PORT data_out = \\n'];\n str = [str, ' PORT we = adc16_snap_we\\n'];\n str = [str, 'END\\n\\n'];\n\n str = [str, 'BEGIN bram_block\\n'];\n str = [str, ' PARAMETER INSTANCE = ',snap_name,'_ramblk\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a\\n'];\n str = [str, ' BUS_INTERFACE PORTA = ',snap_name,'_ramblk_porta\\n'];\n str = [str, ' BUS_INTERFACE PORTB = ',snap_name,'_ramblk_portb\\n'];\n str = [str, 'END\\n\\n'];\n\n str = [str, 'BEGIN opb_bram_if_cntlr\\n'];\n str = [str, ' PARAMETER INSTANCE = ',snap_name,'\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a\\n'];\n str = [str, ' PARAMETER C_OPB_CLK_PERIOD_PS = 10000\\n'];\n str = [str, ' PARAMETER C_BASEADDR = 0x',dec2hex(adc_addr_start+k*4096),'\\n'];\n str = [str, ' PARAMETER C_HIGHADDR = 0x',dec2hex(adc_addr_start+k*4096+4095),'\\n'];\n str = [str, ' BUS_INTERFACE SOPB = ',opb_name,'\\n'];\n str = [str, ' BUS_INTERFACE PORTA = ',snap_name,'_ramblk_portb\\n'];\n str = [str, 'END\\n\\n'];\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dram/get.m", "size": 1927, "source_encoding": "utf_8", "md5": "98f0b7f6dd83a86b5b8dea1b90d5f312", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\ntry\r\n eval(['result = b.',field,';']);\r\ncatch\r\n try\r\n result = get(b.xps_block,field);\r\n catch\r\n error(['Field name unknow to block object: ', field]);\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dram/drc.m", "size": 2143, "source_encoding": "utf_8", "md5": "86e08fcb6dd0eec1736c7d6247f8a222", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\nfor i=1:length(xps_objs)\r\n\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'dimm'),get(xps_objs{i},'dimm'))\r\n\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['DRAM ',get(blk_obj,'simulink_name'),' and DRAM ',get(xps_objs{i},'simulink_name'),' are both trying to use DIMM ', get(blk_obj,'dimm'), '.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dram/gen_ucf.m", "size": 9297, "source_encoding": "utf_8", "md5": "eefece86291bdd94fc6543e22ff51c6a", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\ndisp('DDR3 gen_ucf')\n\nhw_sys \t\t= blk_obj.hw_sys;\nparent_name \t= clear_name(get(blk_obj,'parent'));\nblk_name \t= get(blk_obj,'simulink_name');\nxsg_obj\t\t= get(blk_obj,'xsg_obj');\nstr \t\t= gen_ucf(blk_obj.xps_block);\ndisp('DDR3 trying specific ucf generation')\nswitch hw_sys\n case 'ROACH2'\n\tstr = [str,'CONFIG PROHIBIT = AK28,AN35;\\n'];\n\tstr = [str,'#######################################################################################\\n'];\n\tstr = [str,'###Place RSYNC OSERDES and IODELAY: ###\\n'];\n \tstr = [str,'#######################################################################################\\n\\n'];\n \tstr = [str,'##Site: AK28 -- Bank 23\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_loop_col0.u_oserdes_rsync\" LOC = \"OLOGIC_X1Y143\";\\n'];\n\tstr = [str, 'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_loop_col0.u_odelay_rsync\" LOC = \"IODELAY_X1Y143\";\\n\\n'];\n \tstr = [str,'##Site: AN35 -- Bank 12\\n'];\n\tstr = [str,'#INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_loop_col2.u_oserdes_rsync\" LOC = \"OLOGIC_X0Y101\";\\n'];\n\tstr = [str,'#INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_loop_col2.u_odelay_rsync\" LOC = \"IODELAY_X0Y101\";\\n\\n'];\n \tstr = [str,'###############################################################################################\\n'];\n \tstr = [str,'## The logic of this pin is used internally to drive a BUFIO for the byte group. Any clock\\n'];\n \tstr = [str,'## capable pin in the same bank as the data byte group (DQS, DQ, DM if used) can be used for\\n'];\n \tstr = [str,'## this pin. This pin cannot be used for other functions and should not be connected externally.\\n'];\n \tstr = [str, '## If a different pin is chosen, the corresponding LOC constraint must also be changed.\\n'];\n \tstr = [str, '################################################################################################\\n\\n'];\n \tstr = [str,'CONFIG PROHIBIT = AR34,AN28,AM26,BA30,AJ25,AT40,AL34,AR40;\\n\\n'];\n \tstr = [str,'#######################################################################################\\n'];\n \tstr = [str,'###Place CPT OSERDES and IODELAY: ##\\n'];\n \tstr = [str,'#######################################################################################\\n\\n'];\n \tstr= [str,'##Site: AR26 -- Bank 23\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[0].u_oserdes_cpt\" LOC = \"OLOGIC_X1Y137\";\\n'];\n\tstr =[str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[0].u_odelay_cpt\" LOC = \"IODELAY_X1Y137\";\\n\\n'];\n \tstr = [str,'##Site: AN28 -- Bank 22\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[1].u_oserdes_cpt\" LOC = \"OLOGIC_X1Y99\";\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[1].u_odelay_cpt\" LOC = \"IODELAY_X1Y99\";\\n\\n'];\n \tstr = [str,'##Site: AM26 -- Bank 22\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[2].u_oserdes_cpt\" LOC = \"OLOGIC_X1Y101\";\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[2].u_odelay_cpt\" LOC = \"IODELAY_X1Y101\";\\n\\n'];\n \tstr = [str,'##Site: BA30 -- Bank 22\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[3].u_oserdes_cpt\" LOC = \"OLOGIC_X1Y103\";\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[3].u_odelay_cpt\" LOC = \"IODELAY_X1Y103\";\\n\\n'];\n\tstr = [str,'##Site: AJ25 -- Bank 23\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[4].u_oserdes_cpt\" LOC = \"OLOGIC_X1Y141\";\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[4].u_odelay_cpt\" LOC = \"IODELAY_X1Y141\";\\n\\n'];\n \tstr = [str,'##Site: AT40 -- Bank 13\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[5].u_oserdes_cpt\" LOC = \"OLOGIC_X0Y139\";\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[5].u_odelay_cpt\" LOC = \"IODELAY_X0Y139\";\\n\\n'];\n\tstr = [str,'##Site: AL34 -- Bank 13\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[6].u_oserdes_cpt\" LOC = \"OLOGIC_X0Y141\";\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[6].u_odelay_cpt\" LOC = \"IODELAY_X0Y141\";\\n\\n'];\n \tstr = [str,'##Site: AR40 -- Bank 13\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[7].u_oserdes_cpt\" LOC = \"OLOGIC_X0Y143\";\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[7].u_odelay_cpt\" LOC = \"IODELAY_X0Y143\";\\n\\n'];\n \tstr = [str,'##Site: AH24 -- Bank 23\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[8].u_oserdes_cpt\" LOC = \"OLOGIC_X1Y139\";\\n'];\n\tstr = [str,'INST \"ddr3_controller_inst/ddr3_controller_inst/u_memc_ui_top/u_mem_intfc/phy_top0/u_phy_read/u_phy_rdclk_gen/gen_ck_cpt[8].u_odelay_cpt\" LOC = \"IODELAY_X1Y139\";\\n\\n'];\n \tstr = [str,'#######################################################################################\\n'];\n \tstr = [str,'### MMCM_ADV CONSTRAINTS ##\\n'];\n \tstr = [str,'#######################################################################################\\n\\n'];\n\t\n\tstr = [str,'INST \"ddr3_clk_inst/ddr3_clk_inst/u_mmcm_adv\" LOC = \"MMCM_ADV_X0Y6\";\\n'];\n str = [str,'#ROACH infrastructure MMCM constraint for sys_clk\\n'];\n str = [str,'INST \"infrastructure_inst/infrastructure_inst/MMCM_BASE_sys_clk\" LOC = \"MMCM_ADV_X0Y7\";\\n'];\n\t\n\tstr = [str,'#######################################################################################\\n'];\n \tstr = [str,'### ASYNC TX/RX FIFO CONSTRAINTS ##\\n'];\n \tstr = [str,'#######################################################################################\\n\\n'];\n str = [str,'##TIG constraints for de-referencing the rd and wr clks of the async fifos\\n'];\n\tstr = [str,'TIMESPEC \"TS_XDOMAIN_ASYNC_FIFO_R2W\" = FROM \"ddr3_clk_inst_ddr3_clk_inst_clk_app_mmcm\" TO \"infrastructure_inst_infrastructure_inst_sys_clk_mmcm\" TIG;\\n'];\n\tstr = [str,'TIMESPEC \"TS_XDOMAIN_ASYNC_FIFO_W2R\" = FROM \"infrastructure_inst_infrastructure_inst_sys_clk_mmcm\" TO \"ddr3_clk_inst_ddr3_clk_inst_clk_app_mmcm\" TIG;\\n'];\nend % switch hw_sys\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_dram.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dram/xps_dram.m", "size": 4322, "source_encoding": "utf_8", "md5": "7d82d01bfb65c08cc91cf7409d7895c0", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = xps_dram(blk_obj)\r\n\r\nif ~isa(blk_obj,'xps_block')\r\n error('XPS_DRAM class requires a xps_block class object');\r\nend\r\n\r\nif ~strcmp(get(blk_obj,'type'),'xps_dram')\r\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\r\nend\r\n\r\nblk_name = get(blk_obj,'simulink_name');\r\nxsg_obj = get(blk_obj,'xsg_obj');\r\n\r\nxsg_obj_name = get(xsg_obj,'simulink_name');\r\n[xsg_hw_sys, xsg_hw_subsys] = xps_get_hw_plat(get_param(xsg_obj_name,'hw_sys'));\r\n\r\ns.half_burst = num2str(strcmp(get_param(blk_name, 'half_burst'), 'on'));\r\ns.bank_mgt = num2str(strcmp(get_param(blk_name, 'bank_mgt'), 'on'));\r\ns.wide_data = num2str(strcmp(get_param(blk_name, 'wide_data'), 'on'));\r\ns.bram_fifos = num2str(strcmp(get_param(blk_name, 'bram_fifos'), 'on'));\r\ns.disable_tag = num2str(strcmp(get_param(blk_name, 'disable_tag'), 'on'));\r\ns.use_sniffer = num2str(strcmp(get_param(blk_name, 'use_sniffer'), 'on')); \r\ns.dimm = 1; %only one dimm on ROACH and ROACH2. BEE2 support removed.\r\ns.hw_sys = xsg_hw_sys;\r\ns.clk_freq = str2num(get_param(blk_name,'ip_clock'));\r\n\r\nb = class(s, 'xps_dram', blk_obj);\r\n% IP name\r\n%b = set(b, 'ip_name', 'opb_dram_sniffer');\r\n% opb bus offset\r\n%b = set(b, 'opb_address_offset', hex2dec('100'));\r\n%b = set(b, 'plb_address_offset', 0);\r\n%number of hard-coded opb0 interfaces\r\n%b = set(b, 'opb0_devices', 2); %data and control interfaces on sniffer\r\n\r\n% interfaces\r\ninterfaces.DDR2_USER = ['ddr2_user_dimm', s.dimm, '_async'];\r\ninterfaces.DDR2_CTRL = ['ddr2_user_dimm', s.dimm, '_ctrl'];\r\nb = set(b,'interfaces',interfaces);\r\n\r\n% borph parameters\r\nif (strcmp(xsg_hw_sys,'ROACH'))\r\n borph_info.size = 2^30;\r\n borph_info.mode = 3;\r\n b = set(b,'borph_info',borph_info);\r\nend\r\n\r\n\r\n% misc ports\r\nmisc_ports.ddr_clk = {1 'in' 'ddr2_user_clk'};\r\nb = set(b,'misc_ports',misc_ports);\r\n\r\n% bus connections\r\nbuses.MEM_CMD.busif = {[clear_name(blk_name), '_MEM_CMD']};\r\nbuses.MEM_CMD.ports = {};\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Cmd_Address'];\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Cmd_RNW'];\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Cmd_Valid'];\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Cmd_Tag'];\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Cmd_Ack'];\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Rd_Dout'];\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Rd_Tag'];\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Rd_Ack'];\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Rd_Valid'];\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Wr_Din'];\r\nbuses.MEM_CMD.ports = [buses.MEM_CMD.ports, 'Mem_Wr_BE'];\r\nb = set(b, 'buses', buses);\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dram/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dram/gen_mhs_ip.m", "size": 15668, "source_encoding": "utf_8", "md5": "7ab3d15c2831b6019db92a50c3d8aca3", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj,opb_addr_start,opb_name)\nfprintf('Calling DRAM function...')\n\nstr = '';\nopb_addr_end = opb_addr_start;\n\nip_name = get(blk_obj,'ip_name');\ninterfaces = get(blk_obj,'interfaces');\nmisc_ports = get(blk_obj,'misc_ports');\nhw_sys = get(blk_obj,'hw_sys');\nclk_freq = get(blk_obj,'clk_freq');\ninst_name = clear_name(get(blk_obj,'simulink_name'));\nxsg_obj = get(blk_obj,'xsg_obj');\nfprintf('Looking for dimm number...')\ndimm = num2str(get(blk_obj,'dimm'));\nhalf_burst = get(blk_obj,'half_burst');\nwide_data = get(blk_obj,'wide_data');\nbank_mgt = get(blk_obj,'bank_mgt');\nbram_fifos = get(blk_obj,'bram_fifos');\ndisable_tag = get(blk_obj,'disable_tag');\nuse_sniffer = get(blk_obj,'use_sniffer'); \n\n[M,O,D] = clk_factors(100,2*clk_freq);\n% Generate 'infrastructure' MHS entry\n\nswitch hw_sys\n case 'ROACH'\n str = [str, 'BEGIN dram_infrastructure', '\\n'];\n str = [str, ' PARAMETER INSTANCE = dram_infrastructure_inst', '\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\n str = [str, ' PARAMETER CLK_FREQ = ', num2str(clk_freq), '\\n'];\n str = [str, ' BUS_INTERFACE DRAM_SYS = dram_sys', '\\n'];\n str = [str, ' PORT reset = sys_reset', '\\n'];\n str = [str, ' PORT clk_in = dly_clk', '\\n'];\n str = [str, ' PORT clk_in_locked = 0b1', '\\n'];\n str = [str, ' PORT clk_out = dram_user_clk', '\\n'];\n str = [str, 'END\\n'];\n str = [str, '\\n'];\n case 'ROACH2'\n str = [str, 'BEGIN ddr3_clk', \t \t\t\t'\\n'];\n str = [str, ' PARAMETER INSTANCE = ddr3_clk_inst', \t\t\t'\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', \t\t\t'\\n'];\n str = [str, ' PARAMETER DRAM_FREQUENCY = ',num2str(2*clk_freq),\t \t'\\n'];\n str = [str, ' PARAMETER CLKFBOUT_MULT_F = ',num2str(M),\t \t\t\t'\\n'];\n str = [str, ' PARAMETER DIVCLK_DIVIDE = ', num2str(D), \t \t\t\t'\\n'];\n str = [str, ' PARAMETER CLKOUT0_DIVIDE_F = ',num2str(O), \t\t\t'\\n'];\n str = [str, ' PARAMETER CLKOUT1_DIVIDE = ',num2str(O*2), \t \t \t\t'\\n'];\n str = [str, ' PARAMETER CLKOUT2_DIVIDE = ',num2str(O), \t \t\t\t'\\n'];\n str = [str, ' PARAMETER PERIOD = ',num2str(1000*(1/(100))),\t \t\t'\\n'];\n str = [str, ' BUS_INTERFACE DDR3_CLK = ddr3_clk ', \t\t\t'\\n'];\n str = [str, ' PORT clk_100 = clk_100',\t \t\t\t'\\n'];\n str = [str, ' PORT iodelay_ctrl_rdy = idelay_rdy', \t\t\t'\\n'];\n str = [str, ' PORT clk_app = ddr3_clk_app', \t\t \t'\\n'];\n str = [str, 'END', \t\t\t'\\n'];\n str = [str, \t\t\t'\\n'];\n otherwise % case ROACH/ROACH2*\nend % switch hw_sys\n\n% Generate 'controller' MHS entry\n\nswitch hw_sys\n case 'ROACH'\n str = [str, 'BEGIN dram_controller', '\\n'];\n str = [str, ' PARAMETER INSTANCE = dram_controller_inst', '\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\n str = [str, ' PARAMETER CLK_FREQ = ', num2str(clk_freq), '\\n'];\n str = [str, ' BUS_INTERFACE DRAM_USER = dram_ctrl', '\\n'];\n str = [str, ' BUS_INTERFACE DRAM_SYS = dram_sys', '\\n'];\n str = [str, ' PORT phy_rdy = ', inst_name, '_phy_ready', '\\n'];\n str = [str, ' PORT dram_ck = dram_ck', '\\n'];\n str = [str, ' PORT dram_ck_n = dram_ck_n', '\\n'];\n str = [str, ' PORT dram_a = dram_a', '\\n'];\n str = [str, ' PORT dram_ba = dram_ba', '\\n'];\n str = [str, ' PORT dram_ras_n = dram_ras_n', '\\n'];\n str = [str, ' PORT dram_cas_n = dram_cas_n', '\\n'];\n str = [str, ' PORT dram_we_n = dram_we_n', '\\n'];\n str = [str, ' PORT dram_cs_n = dram_cs_n', '\\n'];\n str = [str, ' PORT dram_cke = dram_cke', '\\n'];\n str = [str, ' PORT dram_odt = dram_odt', '\\n'];\n str = [str, ' PORT dram_dm = dram_dm', '\\n'];\n str = [str, ' PORT dram_dqs = dram_dqs', '\\n'];\n str = [str, ' PORT dram_dqs_n = dram_dqs_n', '\\n'];\n str = [str, ' PORT dram_dq = dram_dq', '\\n'];\n str = [str, ' PORT dram_reset_n = dram_reset_n', '\\n'];\n str = [str, 'END\\n'];\n str = [str, 'PORT dram_ck = dram_ck, DIR = O, VEC = [2:0]', '\\n'];\n str = [str, 'PORT dram_ck_n = dram_ck_n, DIR = O, VEC = [2:0]', '\\n'];\n str = [str, 'PORT dram_a = dram_a, DIR = O, VEC = [15:0]', '\\n'];\n str = [str, 'PORT dram_ba = dram_ba, DIR = O, VEC = [2:0]', '\\n'];\n str = [str, 'PORT dram_ras_n = dram_ras_n, DIR = O', '\\n'];\n str = [str, 'PORT dram_cas_n = dram_cas_n, DIR = O', '\\n'];\n str = [str, 'PORT dram_we_n = dram_we_n, DIR = O', '\\n'];\n str = [str, 'PORT dram_cs_n = dram_cs_n, DIR = O, VEC = [1:0]', '\\n'];\n str = [str, 'PORT dram_cke = dram_cke, DIR = O, VEC = [1:0]', '\\n'];\n str = [str, 'PORT dram_odt = dram_odt, DIR = O, VEC = [1:0]', '\\n'];\n str = [str, 'PORT dram_dm = dram_dm, DIR = O, VEC = [8:0]', '\\n'];\n str = [str, 'PORT dram_dqs = dram_dqs, DIR = IO, VEC = [8:0]', '\\n'];\n str = [str, 'PORT dram_dqs_n = dram_dqs_n, DIR = IO, VEC = [8:0]', '\\n'];\n str = [str, 'PORT dram_dq = dram_dq, DIR = IO, VEC = [71:0]', '\\n'];\n str = [str, 'PORT dram_reset_n = dram_reset_n, DIR = O', '\\n'];\n str = [str, '\\n'];\n case 'ROACH2'\n str = [str, 'BEGIN ddr3_controller', \t\t '\\n'];\n str = [str, ' PARAMETER INSTANCE = ddr3_controller_inst', \t\t '\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', \t\t '\\n'];\n str = [str, ' PARAMETER tCK = ',num2str(floor(1000*1000*(1/(clk_freq*2)))), '\\n'];\n str = [str, ' BUS_INTERFACE DDR3_CLK = ddr3_clk', \t\t '\\n'];\n str = [str, ' BUS_INTERFACE DDR3_APP = ddr3_ctrl',\t\t\t\t '\\n'];\n str = [str, ' PORT clk_div2 = ddr3_clk_app',\t \t \t '\\n'];\n str = [str, ' PORT ddr3_dq = ddr3_dq', \t\t '\\n'];\n str = [str, ' PORT ddr3_addr = ddr3_a', \t\t '\\n'];\n str = [str, ' PORT ddr3_ba = ddr3_ba', \t\t '\\n'];\n str = [str, ' PORT ddr3_ras_n = ddr3_rasn', \t\t '\\n'];\n str = [str, ' PORT ddr3_cas_n = ddr3_casn', \t\t '\\n'];\n str = [str, ' PORT ddr3_we_n = ddr3_wen', \t\t '\\n'];\n str = [str, ' PORT ddr3_reset_n = ddr3_resetn', \t '\\n'];\n str = [str, ' PORT ddr3_cs_n = ddr3_sn_2', \t '\\n'];\n str = [str, ' PORT ddr3_odt = ddr3_odt', \t '\\n'];\n str = [str, ' PORT ddr3_cke = ddr3_cke', '\\n'];\n str = [str, ' PORT ddr3_dm = ddr3_dm', '\\n'];\n str = [str, ' PORT ddr3_dqs_p = ddr3_dqs_p', '\\n'];\n str = [str, ' PORT ddr3_dqs_n = ddr3_dqs_n', '\\n'];\n str = [str, ' PORT ddr3_ck_p = ddr3_ck_p', '\\n'];\n str = [str, ' PORT ddr3_ck_n = ddr3_ck_n', '\\n'];\n str = [str, ' PORT phy_rdy = ', inst_name, '_phy_ready', '\\n'];\n str = [str, 'END',\t\t\t\t\t\t '\\n'];\n str = [str, 'PORT ddr3_dq = ddr3_dq, DIR = IO , VEC = [71:0]', \t '\\n'];\n str = [str, 'PORT ddr3_a = ddr3_a, DIR = O, VEC = [15:0]', \t '\\n'];\n str = [str, 'PORT ddr3_ba = ddr3_ba, DIR = O, VEC = [2:0]', \t '\\n'];\n str = [str, 'PORT ddr3_rasn = ddr3_rasn , DIR = O', \t '\\n'];\n str = [str, 'PORT ddr3_casn = ddr3_casn, DIR = O', \t '\\n'];\n str = [str, 'PORT ddr3_wen = ddr3_wen, DIR = O', \t '\\n'];\n str = [str, 'PORT ddr3_resetn = ddr3_resetn, DIR = O', \t '\\n'];\n str = [str, 'PORT ddr3_sn = 0b111 & ddr3_sn_2, DIR = O, VEC = [3:0]',\t '\\n'];\n str = [str, 'PORT ddr3_odt = ddr3_odt, DIR = O, VEC = [1:0]',\t\t '\\n'];\n str = [str, 'PORT ddr3_cke = ddr3_cke, DIR = O, VEC = [1:0]',\t\t '\\n'];\n str = [str, 'PORT ddr3_dm = ddr3_dm, DIR = O, VEC = [8:0]', \t\t '\\n'];\n str = [str, 'PORT ddr3_dqs_p = ddr3_dqs_p, DIR = IO, VEC = [8:0]', \t '\\n'];\n str = [str, 'PORT ddr3_dqs_n = ddr3_dqs_n, DIR = IO, VEC = [8:0]', \t '\\n'];\n str = [str, 'PORT ddr3_ck_p = ddr3_ck_p, DIR = O', \t\t\t '\\n'];\n str = [str, 'PORT ddr3_ck_n = ddr3_ck_n, DIR = O', \t '\\n'];\n str = [str, \t '\\n'];\nend % switch hw_sys\n\n% Generate 'sniffer' MHS entry\n\nswitch hw_sys\n case 'ROACH'\n str = [str, 'BEGIN opb_dram_sniffer', '\\n'];\n str = [str, ' PARAMETER INSTANCE = opb_dram_sniffer_inst', '\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\n str = [str, ' PARAMETER CTRL_C_BASEADDR = 0x00050000', '\\n'];\n str = [str, ' PARAMETER CTRL_C_HIGHADDR = 0x0005FFFF', '\\n'];\n str = [str, ' PARAMETER MEM_C_BASEADDR = 0x04000000', '\\n'];\n str = [str, ' PARAMETER MEM_C_HIGHADDR = 0x07FFFFFF', '\\n'];\n str = [str, ' PARAMETER ENABLE = ', use_sniffer, '\\n'];\n str = [str, ' BUS_INTERFACE SOPB_CTRL = opb0', '\\n'];\n str = [str, ' BUS_INTERFACE SOPB_MEM = opb0', '\\n'];\n str = [str, ' BUS_INTERFACE DRAM_CTRL = dram_ctrl', '\\n'];\n str = [str, ' BUS_INTERFACE DRAM_APP = dram_user_dimm', dimm,'_async', '\\n'];\n str = [str, ' PORT dram_clk = dram_user_clk', '\\n'];\n str = [str, ' PORT dram_rst = dram_user_reset', '\\n'];\n str = [str, ' PORT phy_ready = ', inst_name, '_phy_ready', '\\n'];\n str = [str, 'END', '\\n'];\n str = [str, '\\n'];\n case 'ROACH2'\n str = [str, 'BEGIN opb_dram_sniffer',\t\t\t\t '\\n'];\n str = [str, ' PARAMETER INSTANCE = opb_dram_sniffer_inst',\t\t '\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a',\t\t\t\t '\\n'];\n str = [str, ' PARAMETER CTRL_C_BASEADDR = 0x00050000',\t\t '\\n'];\n str = [str, ' PARAMETER CTRL_C_HIGHADDR = 0x0005FFFF',\t\t '\\n'];\n str = [str, ' PARAMETER MEM_C_BASEADDR = 0x010B0000',\t\t '\\n'];\n str = [str, ' PARAMETER MEM_C_HIGHADDR = 0x010BFFFF',\t\t '\\n'];\n str = [str, ' PARAMETER ENABLE = 1',\t\t\t '\\n'];\n str = [str, ' BUS_INTERFACE SOPB_CTRL = opb0',\t\t\t '\\n'];\n str = [str, ' BUS_INTERFACE SOPB_MEM = opb0',\t\t\t '\\n'];\n str = [str, ' BUS_INTERFACE DRAM_CTRL = ddr3_ctrl',\t\t '\\n'];\n str = [str, ' BUS_INTERFACE DRAM_APP = ddr3_app',\t\t\t '\\n'];\n str = [str, ' PORT dram_clk = ddr3_clk_app',\t\t\t '\\n'];\n str = [str, ' PORT dram_rst = ', inst_name, '_Mem_Rst', \t '\\n'];\n str = [str, ' PORT phy_ready = ', inst_name, '_phy_ready',\t \t '\\n'];\n str = [str, 'END',\t\t\t\t \t\t\t '\\n'];\n str = [str,\t\t\t\t\t\t\t '\\n'];\t\nend % switch hw_sys\n\n% Generate 'async_ddr' MHS entry\n\nswitch hw_sys\n case 'ROACH'\n str = [str, 'BEGIN async_dram\\n'];\n str = [str, ' PARAMETER INSTANCE = async_dram_', dimm, '\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\n str = [str, ' PARAMETER C_WIDE_DATA = ', wide_data, '\\n'];\n str = [str, ' PARAMETER C_HALF_BURST = ', half_burst, '\\n'];\n str = [str, ' PARAMETER BRAM_FIFOS = ', bram_fifos, '\\n'];\n str = [str, ' PARAMETER TAG_BUFFER_EN = ', disable_tag, '\\n'];\n str = [str, ' BUS_INTERFACE MEM_CMD = ', inst_name, '_MEM_CMD', '\\n'];\n str = [str, ' BUS_INTERFACE DRAM_USER = dram_user_dimm', dimm, '_async', '\\n'];\n str = [str, ' PORT Mem_Clk = ', get(xsg_obj, 'clk_src'), '\\n'];\n str = [str, ' PORT Mem_Rst = ', inst_name, '_Mem_Rst', '\\n'];\n str = [str, ' PORT dram_clk = dram_user_clk', '\\n'];\n str = [str, ' PORT dram_reset = dram_user_reset', '\\n'];\n str = [str, 'END\\n'];\n str = [str, '\\n'];\n case 'ROACH2'\n str = [str, 'BEGIN ddr3_async_fifo', \t \t\t\t'\\n'];\n str = [str, ' PARAMETER INSTANCE = ddr3_async_fifo_inst', \t\t\t'\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', \t\t\t'\\n'];\n str = [str, ' PORT ui_app_clk = ',get(xsg_obj, 'clk_src'), \t \t'\\n'];\n str = [str, ' PORT ddr3_app_clk = ddr3_clk_app', \t\t \t'\\n'];\n str = [str, ' PORT ui_rst = ', inst_name, '_Mem_Rst', \t '\\n'];\n str = [str, ' BUS_INTERFACE DDR3_UI = ', inst_name, '_MEM_CMD' \t\t\t'\\n'];\n str = [str, ' BUS_INTERFACE DDR3_APP = ddr3_app',\t\t\t\t\t'\\n'];\n str = [str, 'END', \t\t\t'\\n'];\n str = [str, \t\t\t'\\n'];\nend % switch hw_sys\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_x64_adc/get.m", "size": 1963, "source_encoding": "utf_8", "md5": "d565195cea642f1d9159e99a3b5c975a", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';'])\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_x64_adc/drc.m", "size": 1777, "source_encoding": "utf_8", "md5": "88a823a8e1aec61219004afbe0b08646", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_x64_adc/gen_ucf.m", "size": 17423, "source_encoding": "utf_8", "md5": "b3fa6ca62c0796c6df36312ad2320d8d", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\nfunction str = gen_ucf(blk_obj)\ndisp('x64_adc gen_ucf');\ndisp('x64_adc trying generic ucf generation');\nstr = gen_ucf(blk_obj.xps_block);\nblk_name = get(blk_obj, 'simulink_name');\ninst_name = clear_name(blk_name);\n\ndisp('x64_adc trying specific ucf generation');\n\nclk_rate = get(blk_obj,'adc_clk_rate'); \nclk_period = 1000/(6*clk_rate);\nuse_spi = get(blk_obj,'use_spi'); \n\n%str = [str, 'NET \"adc_clk_p\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | PERIOD = ', num2str(clk_period), ' ns | LOC = H19;', '\\n'];\n%str = [str, 'NET \"adc_clk_n\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | PERIOD = ', num2str(clk_period), ' ns | LOC = H20;', '\\n'];\n%str = [str, 'NET \"fc_0_p\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = C34;', '\\n'];\n%str = [str, 'NET \"fc_0_n\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = D34;', '\\n'];\n%str = [str, 'NET \"fc_1_p\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = B33;', '\\n'];\n%str = [str, 'NET \"fc_1_n\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = C33;', '\\n'];\n%str = [str, 'NET \"fc_2_p\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = E28;', '\\n'];\n%str = [str, 'NET \"fc_2_n\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = F28;', '\\n'];\n%str = [str, 'NET \"fc_3_p\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = C32;', '\\n'];\n%str = [str, 'NET \"fc_3_n\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = D32;', '\\n'];\n%str = [str, 'NET \"fc_4_p\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AB27;', '\\n'];\n%str = [str, 'NET \"fc_4_n\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AC27;', '\\n'];\n%str = [str, 'NET \"fc_5_p\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AD31;', '\\n'];\n%str = [str, 'NET \"fc_5_n\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AE31;', '\\n'];\n%str = [str, 'NET \"fc_6_p\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AD32;', '\\n'];\n%str = [str, 'NET \"fc_6_n\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AE32;', '\\n'];\n%str = [str, 'NET \"fc_7_p\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AC34;', '\\n'];\n%str = [str, 'NET \"fc_7_n\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AD34;', '\\n'];\n%str = [str, 'NET \"in_0_p<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = L30;', '\\n'];\n%str = [str, 'NET \"in_0_n<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = M30;', '\\n'];\n%str = [str, 'NET \"in_0_p<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = K31;', '\\n'];\n%str = [str, 'NET \"in_0_n<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = L31;', '\\n'];\n%str = [str, 'NET \"in_0_p<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = H34;', '\\n'];\n%str = [str, 'NET \"in_0_n<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = J34;', '\\n'];\n%str = [str, 'NET \"in_0_p<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = J27;', '\\n'];\n%str = [str, 'NET \"in_0_n<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = J26;', '\\n'];\n%str = [str, 'NET \"in_0_p<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = G32;', '\\n'];\n%str = [str, 'NET \"in_0_n<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = H32;', '\\n'];\n%str = [str, 'NET \"in_0_p<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = F33;', '\\n'];\n%str = [str, 'NET \"in_0_n<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = E34;', '\\n'];\n%str = [str, 'NET \"in_0_p<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = E32;', '\\n'];\n%str = [str, 'NET \"in_0_n<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = E33;', '\\n'];\n%str = [str, 'NET \"in_0_p<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = F25;', '\\n'];\n%str = [str, 'NET \"in_0_n<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = F26;', '\\n'];\n%str = [str, 'NET \"in_1_p<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = L34;', '\\n'];\n%str = [str, 'NET \"in_1_n<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = K34;', '\\n'];\n%str = [str, 'NET \"in_1_p<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = K33;', '\\n'];\n%str = [str, 'NET \"in_1_n<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = K32;', '\\n'];\n%str = [str, 'NET \"in_1_p<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = J32;', '\\n'];\n%str = [str, 'NET \"in_1_n<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = H33;', '\\n'];\n%str = [str, 'NET \"in_1_p<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = K27;', '\\n'];\n%str = [str, 'NET \"in_1_n<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = K26;', '\\n'];\n%str = [str, 'NET \"in_1_p<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = H30;', '\\n'];\n%str = [str, 'NET \"in_1_n<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = G31;', '\\n'];\n%str = [str, 'NET \"in_1_p<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = J24;', '\\n'];\n%str = [str, 'NET \"in_1_n<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = J25;', '\\n'];\n%str = [str, 'NET \"in_1_p<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = G27;', '\\n'];\n%str = [str, 'NET \"in_1_n<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = H27;', '\\n'];\n%str = [str, 'NET \"in_1_p<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = G25;', '\\n'];\n%str = [str, 'NET \"in_1_n<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = G26;', '\\n'];\n%str = [str, 'NET \"in_2_p<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = M31;', '\\n'];\n%str = [str, 'NET \"in_2_n<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = N30;', '\\n'];\n%str = [str, 'NET \"in_2_p<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = M28;', '\\n'];\n%str = [str, 'NET \"in_2_n<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = N28;', '\\n'];\n%str = [str, 'NET \"in_2_p<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = M25;', '\\n'];\n%str = [str, 'NET \"in_2_n<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = M26;', '\\n'];\n%str = [str, 'NET \"in_2_p<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = K28;', '\\n'];\n%str = [str, 'NET \"in_2_n<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = L28;', '\\n'];\n%str = [str, 'NET \"in_2_p<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = K24;', '\\n'];\n%str = [str, 'NET \"in_2_n<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = L24;', '\\n'];\n%str = [str, 'NET \"in_2_p<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = H29;', '\\n'];\n%str = [str, 'NET \"in_2_n<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = J29;', '\\n'];\n%str = [str, 'NET \"in_2_p<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = H28;', '\\n'];\n%str = [str, 'NET \"in_2_n<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = G28;', '\\n'];\n%str = [str, 'NET \"in_2_p<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = F31;', '\\n'];\n%str = [str, 'NET \"in_2_n<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = E31;', '\\n'];\n%str = [str, 'NET \"in_3_p<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = N27;', '\\n'];\n%str = [str, 'NET \"in_3_n<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = M27;', '\\n'];\n%str = [str, 'NET \"in_3_p<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = L29;', '\\n'];\n%str = [str, 'NET \"in_3_n<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = K29;', '\\n'];\n%str = [str, 'NET \"in_3_p<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = L25;', '\\n'];\n%str = [str, 'NET \"in_3_n<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = L26;', '\\n'];\n%str = [str, 'NET \"in_3_p<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = J30;', '\\n'];\n%str = [str, 'NET \"in_3_n<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = J31;', '\\n'];\n%str = [str, 'NET \"in_3_p<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = G33;', '\\n'];\n%str = [str, 'NET \"in_3_n<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = F34;', '\\n'];\n%str = [str, 'NET \"in_3_p<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = G30;', '\\n'];\n%str = [str, 'NET \"in_3_n<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = F30;', '\\n'];\n%str = [str, 'NET \"in_3_p<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = H25;', '\\n'];\n%str = [str, 'NET \"in_3_n<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = H24;', '\\n'];\n%str = [str, 'NET \"in_3_p<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = E29;', '\\n'];\n%str = [str, 'NET \"in_4_n<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = F29;', '\\n'];\n%str = [str, 'NET \"in_4_p<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AK26;', '\\n'];\n%str = [str, 'NET \"in_4_n<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AJ27;', '\\n'];\n%str = [str, 'NET \"in_4_p<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AK28;', '\\n'];\n%str = [str, 'NET \"in_4_n<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AK27;', '\\n'];\n%str = [str, 'NET \"in_4_p<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AJ30;', '\\n'];\n%str = [str, 'NET \"in_4_n<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AH30;', '\\n'];\n%str = [str, 'NET \"in_4_p<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AF24;', '\\n'];\n%str = [str, 'NET \"in_4_n<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AG25;', '\\n'];\n%str = [str, 'NET \"in_4_p<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AG28;', '\\n'];\n%str = [str, 'NET \"in_4_n<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AH28;', '\\n'];\n%str = [str, 'NET \"in_4_p<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AG32;', '\\n'];\n%str = [str, 'NET \"in_4_n<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AH32;', '\\n'];\n%str = [str, 'NET \"in_4_p<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AF31;', '\\n'];\n%str = [str, 'NET \"in_4_n<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AG31;', '\\n'];\n%str = [str, 'NET \"in_4_p<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AF33;', '\\n'];\n%str = [str, 'NET \"in_4_n<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AE33;', '\\n'];\n%str = [str, 'NET \"in_5_p<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AN32;', '\\n'];\n%str = [str, 'NET \"in_5_n<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AP32;', '\\n'];\n%str = [str, 'NET \"in_5_p<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AM33;', '\\n'];\n%str = [str, 'NET \"in_5_n<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AM32;', '\\n'];\n%str = [str, 'NET \"in_5_p<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AH27;', '\\n'];\n%str = [str, 'NET \"in_5_n<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AJ26;', '\\n'];\n%str = [str, 'NET \"in_5_p<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AH29;', '\\n'];\n%str = [str, 'NET \"in_5_n<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AG30;', '\\n'];\n%str = [str, 'NET \"in_5_p<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AF25;', '\\n'];\n%str = [str, 'NET \"in_5_n<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AF26;', '\\n'];\n%str = [str, 'NET \"in_5_p<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AD24;', '\\n'];\n%str = [str, 'NET \"in_5_n<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AE24;', '\\n'];\n%str = [str, 'NET \"in_5_p<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AE28;', '\\n'];\n%str = [str, 'NET \"in_5_n<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AF28;', '\\n'];\n%str = [str, 'NET \"in_5_p<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AC25;', '\\n'];\n%str = [str, 'NET \"in_5_n<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AC24;', '\\n'];\n%str = [str, 'NET \"in_6_p<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AN34;', '\\n'];\n%str = [str, 'NET \"in_6_n<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AN33;', '\\n'];\n%str = [str, 'NET \"in_6_p<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AK29;', '\\n'];\n%str = [str, 'NET \"in_6_n<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AJ29;', '\\n'];\n%str = [str, 'NET \"in_6_p<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AJ31;', '\\n'];\n%str = [str, 'NET \"in_6_n<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AK31;', '\\n'];\n%str = [str, 'NET \"in_6_p<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AJ32;', '\\n'];\n%str = [str, 'NET \"in_6_n<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AK32;', '\\n'];\n%str = [str, 'NET \"in_6_p<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AH34;', '\\n'];\n%str = [str, 'NET \"in_6_n<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AJ34;', '\\n'];\n%str = [str, 'NET \"in_6_p<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AE27;', '\\n'];\n%str = [str, 'NET \"in_6_n<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AE26;', '\\n'];\n%str = [str, 'NET \"in_6_p<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AD26;', '\\n'];\n%str = [str, 'NET \"in_6_n<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AD25;', '\\n'];\n%str = [str, 'NET \"in_6_p<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AF34;', '\\n'];\n%str = [str, 'NET \"in_6_n<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AE34;', '\\n'];\n%str = [str, 'NET \"in_7_p<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AJ25;', '\\n'];\n%str = [str, 'NET \"in_7_n<0>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AH25;', '\\n'];\n%str = [str, 'NET \"in_7_p<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AL34;', '\\n'];\n%str = [str, 'NET \"in_7_n<1>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AL33;', '\\n'];\n%str = [str, 'NET \"in_7_p<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AK34;', '\\n'];\n%str = [str, 'NET \"in_7_n<2>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AK33;', '\\n'];\n%str = [str, 'NET \"in_7_p<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AG27;', '\\n'];\n%str = [str, 'NET \"in_7_n<3>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AG26;', '\\n'];\n%str = [str, 'NET \"in_7_p<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AF29;', '\\n'];\n%str = [str, 'NET \"in_7_n<4>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AF30;', '\\n'];\n%str = [str, 'NET \"in_7_p<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AG33;', '\\n'];\n%str = [str, 'NET \"in_7_n<5>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AH33;', '\\n'];\n%str = [str, 'NET \"in_7_p<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AE29;', '\\n'];\n%str = [str, 'NET \"in_7_n<6>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AD29;', '\\n'];\n%str = [str, 'NET \"in_7_p<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AD30;', '\\n'];\n%str = [str, 'NET \"in_7_n<7>\" IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE | LOC = AC29;', '\\n'];\n\nstr = [str, '', '\\n'];\nstr = [str, 'INST \"*async_data_fifo_inst/BU2/U0/grf.rf/mem/gdm.dm/Mram*\" TNM= RAMSOURCE;', '\\n'];\nstr = [str, 'INST \"*async_data_fifo_inst/BU2/U0/grf.rf/mem/gdm.dm/dout*\" TNM= FFDEST;', '\\n'];\nstr = [str, 'TIMESPEC TS_RAM_FF= FROM \"RAMSOURCE\" TO \"FFDEST\" ', num2str(clk_period*(6/4)), ' ns DATAPATHONLY;', '\\n'];\nstr = [str, 'NET \"*BU2/U0/grf.rf/gcx.clkx/wr_pntr_gc*\" TIG;', '\\n'];\nstr = [str, 'NET \"*BU2/U0/grf.rf/gcx.clkx/rd_pntr_gc*\" TIG;', '\\n'];\n%str = [str, '', '\\n'];\n%str = [str, '', '\\n'];\n\n%str = [str, 'NET \"', inst_name, '_rst_gpio_ext<0>\" LOC = R33 | IOSTANDARD = LVCMOS25;', '\\n'];\n\n%str = [str, '', '\\n'];\n\n%if strcmp(use_spi,'on')\n% str = [str, 'NET \"', inst_name, '_spi_data_gpio_ext<0>\" LOC = P34 | IOSTANDARD = LVCMOS25;', '\\n'];\n% str = [str, 'NET \"', inst_name, '_spi_clk_gpio_ext<0>\" LOC = N34 | IOSTANDARD = LVCMOS25;', '\\n'];\n% str = [str, 'NET \"', inst_name, '_spi_cs_gpio_ext<0>\" LOC = N33 | IOSTANDARD = LVCMOS25;', '\\n'];\n% str = [str, '', '\\n'];\n% str = [str, '', '\\n'];\n%end\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_x64_adc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_x64_adc/xps_x64_adc.m", "size": 10359, "source_encoding": "utf_8", "md5": "ebd6ee0d8bbe271207787ba3c8d222bc", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_x64_adc(blk_obj)\nif ~isa(blk_obj,'xps_block')\n error('XPS_ADC class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_x64_adc')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\ninst_name = clear_name(blk_name);\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.use_spi = eval_param(blk_name,'spi');\ns.ctrl_gpio = get_param(blk_name,'ctrl_gpio');\n\n\nswitch s.hw_sys\n case 'ROACH'\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(1000/(s.adc_clk_rate*6)),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n if strcmp(s.ctrl_gpio, 'GPIO_A')\n s.ctrl_gpio = 'gpioa';\n elseif strcmp(s.ctrl_gpio, 'GPIO_B')\n s.ctrl_gpio = 'gpiob';\n else\n error('X64_ADC block ctrl interface is neither GPIO_A or GPIO_B');\n end\n case 'ROACH2'\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(1000/(s.adc_clk_rate*6)),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n s.ctrl_gpio = 'gpio'; %ROACH2 only has one gpio bank\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend\n\nb = class(s,'xps_x64_adc',blk_obj);\n\n% ip name and version\nb = set(b, 'ip_name', 'x64_adc_interface');\nb = set(b, 'ip_version', '1.00.a');\n\nsupp_ip_names = {'', 'opb_x64_adc', 'spi_controller'};\nsupp_ip_versions = {'', '1.00.a', '1.00.a'};\n\nb = set(b, 'supp_ip_names', supp_ip_names);\nb = set(b, 'supp_ip_versions', supp_ip_versions);\n\n% misc ports\n%misc_ports.ctrl_reset = {1 'in' [s.adc_str,'_ddrb']};\n%misc_ports.ctrl_clk_in = {1 'in' get(xsg_obj,'clk_src')};\n%misc_ports.ctrl_clk_out = {1 'out' [s.adc_str,'_clk']};\n%misc_ports.ctrl_clk90_out = {1 'out' [s.adc_str,'_clk90']};\n%misc_ports.ctrl_dcm_locked = {1 'out' [s.adc_str,'_dcm_locked']};\n%\n%end\n%misc_ports.dcm_psclk = {1 'in' [s.adc_str,'_psclk']};\n%misc_ports.dcm_psen = {1 'in' [s.adc_str,'_psen']};\n%misc_ports.dcm_psincdec = {1 'in' [s.adc_str,'_psincdec']};\n%\n%b = set(b,'misc_ports',misc_ports);\n\n\n% external ports\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(s.adc_clk_rate*1e6));\nctrl_iobname = [s.hw_sys, '.', s.ctrl_gpio];\nswitch s.hw_sys\n case 'ROACH'\n ctrl_out_en_iobname = [s.hw_sys, '.', s.ctrl_gpio, '_oe_n'];\n gpio_oe_n_constraints = struct('IOSTANDARD', 'LVCMOS33');\n if strcmp(s.ctrl_gpio, 'gpioa')\n gpio_constraints = struct('IOSTANDARD', 'LVCMOS25');\n else\n gpio_constraints = struct('IOSTANDARD', 'LVCMOS15');\n end\n case 'ROACH2'\n gpio_constraints = struct('IOSTANDARD', 'LVCMOS15');\nend\n \n\ns.adc_str = 'adc0';\nadcport0 = [s.hw_sys, '.', 'zdok', s.adc_str(length(s.adc_str))];\ns.adc_str = 'adc1';\nadcport1 = [s.hw_sys, '.', 'zdok', s.adc_str(length(s.adc_str))];\n\next_ports.in_0_n = {8 'in' 'in_0_n' ['{',adcport1,'_n{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_1_n = {8 'in' 'in_1_n' ['{',adcport1,'_n{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_2_n = {8 'in' 'in_2_n' ['{',adcport1,'_n{[0 1 2 3 4 5 6 7 ]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_3_n = {8 'in' 'in_3_n' ['{',adcport1,'_n{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_4_n = {8 'in' 'in_4_n' ['{',adcport0,'_n{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_5_n = {8 'in' 'in_5_n' ['{',adcport0,'_n{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_6_n = {8 'in' 'in_6_n' ['{',adcport0,'_n{[0 1 2 3 4 5 6 7 ]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_7_n = {8 'in' 'in_7_n' ['{',adcport0,'_n{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n\next_ports.in_0_p = {8 'in' 'in_0_p' ['{',adcport1,'_p{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_1_p = {8 'in' 'in_1_p' ['{',adcport1,'_p{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_2_p = {8 'in' 'in_2_p' ['{',adcport1,'_p{[0 1 2 3 4 5 6 7 ]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_3_p = {8 'in' 'in_3_p' ['{',adcport1,'_p{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_4_p = {8 'in' 'in_4_p' ['{',adcport0,'_p{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_5_p = {8 'in' 'in_5_p' ['{',adcport0,'_p{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_6_p = {8 'in' 'in_6_p' ['{',adcport0,'_p{[0 1 2 3 4 5 6 7 ]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\next_ports.in_7_p = {8 'in' 'in_7_p' ['{',adcport0,'_p{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n\next_ports.fc_0_n = {1 'in' 'fc_0_n' ['{',adcport1,'_n{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_1_n = {1 'in' 'fc_1_n' ['{',adcport1,'_n{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_2_n = {1 'in' 'fc_2_n' ['{',adcport1,'_n{[8 ]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_3_n = {1 'in' 'fc_3_n' ['{',adcport1,'_n{[9 ]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_4_n = {1 'in' 'fc_4_n' ['{',adcport0,'_n{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_5_n = {1 'in' 'fc_5_n' ['{',adcport0,'_n{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_6_n = {1 'in' 'fc_6_n' ['{',adcport0,'_n{[8 ]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_7_n = {1 'in' 'fc_7_n' ['{',adcport0,'_n{[9 ]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_0_p = {1 'in' 'fc_0_p' ['{',adcport1,'_p{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_1_p = {1 'in' 'fc_1_p' ['{',adcport1,'_p{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_2_p = {1 'in' 'fc_2_p' ['{',adcport1,'_p{[8 ]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_3_p = {1 'in' 'fc_3_p' ['{',adcport1,'_p{[9 ]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_4_p = {1 'in' 'fc_4_p' ['{',adcport0,'_p{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_5_p = {1 'in' 'fc_5_p' ['{',adcport0,'_p{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_6_p = {1 'in' 'fc_6_p' ['{',adcport0,'_p{[8 ]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\next_ports.fc_7_p = {1 'in' 'fc_7_p' ['{',adcport0,'_p{[9 ]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\n\next_ports.adc_clk_p = {1 'in' 'adc_clk_p' ['{',adcport0,'_p{[39]+1,:}}'] 'vector=false' struct() ucf_constraints_clock};\next_ports.adc_clk_n = {1 'in' 'adc_clk_n' ['{',adcport0,'_n{[39]+1,:}}'] 'vector=false' struct() ucf_constraints_clock};\n\next_ports.adc_rst = {1 'out' [inst_name, '_rst_gpio_ext'] [ctrl_iobname, ' ([','0',']+1)'] 'vector=true' struct() gpio_constraints };\n\nif strcmp(s.hw_sys,'ROACH')\n % ROACH 1 needs an external port to drive the GPIO buffers\n ext_ports.ctrl_out_en = {1 'out' [inst_name, '_ctrl_out_en' ] [ctrl_out_en_iobname, ' ([','0',']+1)'] 'vector=true' struct() gpio_oe_n_constraints };\nend\nif strcmp(s.use_spi,'on')\n ext_ports.spi_data = {1 'out' [inst_name, '_spi_data_gpio_ext'] [ctrl_iobname, ' ([','1',']+1)'] 'vector=true' struct() gpio_constraints};\n ext_ports.spi_sclk = {1 'out' [inst_name, '_spi_sclk_gpio_ext'] [ctrl_iobname, ' ([','2',']+1)'] 'vector=true' struct() gpio_constraints };\n ext_ports.spi_cs_n = {1 'out' [inst_name, '_spi_cs_gpio_ext' ] [ctrl_iobname, ' ([','3',']+1)'] 'vector=true' struct() gpio_constraints };\nend\n\nb = set(b,'ext_ports',ext_ports);\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_x64_adc/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc083000_ctrl/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc083000_ctrl/drc.m", "size": 2118, "source_encoding": "utf_8", "md5": "60145324772f7335c69b7970ae3e68e3", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'hw_adc'),get(xps_objs{i},'hw_adc'))\r\n\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['ADC ',get(blk_obj,'simulink_name'),' and ADC ',get(xps_objs{i},'simulink_name'),' are located on the same port.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc083000_ctrl/gen_ucf.m", "size": 25126, "source_encoding": "utf_8", "md5": "655f8863445950ebfad48f56d7f1e373", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\ndisp('adc086000 gen_ucf')\n\nhw_sys = blk_obj.hw_sys;\nadc_str = blk_obj.adc_str;\ndisp('adc086000 trying generic ucf generation')\nstr = gen_ucf(blk_obj.xps_block);\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\ndisp('adc08600 trying specific ucf generation')\nswitch hw_sys\n case 'ROACH'\n switch adc_str\n case 'adc0'\n %\t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 1ns;\\n'];\n % end case 'adc0'\n case 'adc1'\n %\t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 1ns;\\n'];\n % end case 'adc1'\n end % switch adc_str\n\n case 'iBOB'\n switch adc_str\n case 'adc0'\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" PERIOD = ',num2str(1000/blk_obj.adc_clk_rate*4),'ns;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" MAXDELAY = 452ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_dcm\" MAXDELAY = 853ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk90_dcm\" MAXDELAY = 853ps;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK_CLKBUF\" LOC = BUFGMUX1P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK90_CLKBUF\" LOC = BUFGMUX3P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" LOC = DCM_X2Y1;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" CLKOUT_PHASE_SHIFT = VARIABLE;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 323ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" ROUTE = \"{3;1;2vp50ff1152;46c47c12!-1;156520;5632;S!0;-159;0!1;-1884;-1248!1;-1884;744!2;-1548;992!2;-1548;304!3;-1548;-656!3;-1548;-1344!4;327;0;L!5;167;0;L!6;327;0;L!7;167;0;L!}\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_3\" LOC = SLICE_X139Y91;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_2\" LOC = SLICE_X138Y91;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_1\" LOC = SLICE_X139Y90;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_0\" LOC = SLICE_X138Y90;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_0\" LOC = \"SLICE_X138Y128\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_1\" LOC = \"SLICE_X138Y126\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_2\" LOC = \"SLICE_X139Y122\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_3\" LOC = \"SLICE_X138Y120\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_4\" LOC = \"SLICE_X138Y102\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_5\" LOC = \"SLICE_X139Y98\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_6\" LOC = \"SLICE_X138Y96\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_7\" LOC = \"SLICE_X138Y94\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_8\" LOC = \"SLICE_X139Y126\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_9\" LOC = \"SLICE_X138Y124\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_10\" LOC = \"SLICE_X138Y122\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_11\" LOC = \"SLICE_X139Y118\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_12\" LOC = \"SLICE_X138Y100\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_13\" LOC = \"SLICE_X138Y98\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_14\" LOC = \"SLICE_X139Y94\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_15\" LOC = \"SLICE_X138Y92\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_16\" LOC = \"SLICE_X138Y128\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_17\" LOC = \"SLICE_X138Y126\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_18\" LOC = \"SLICE_X139Y122\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_19\" LOC = \"SLICE_X138Y120\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_20\" LOC = \"SLICE_X138Y102\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_21\" LOC = \"SLICE_X139Y98\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_22\" LOC = \"SLICE_X138Y96\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_23\" LOC = \"SLICE_X138Y94\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_24\" LOC = \"SLICE_X139Y126\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_25\" LOC = \"SLICE_X138Y124\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_26\" LOC = \"SLICE_X138Y122\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_27\" LOC = \"SLICE_X139Y118\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_28\" LOC = \"SLICE_X138Y100\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_29\" LOC = \"SLICE_X138Y98\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_30\" LOC = \"SLICE_X139Y94\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_31\" LOC = \"SLICE_X138Y92\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_0\" LOC = \"SLICE_X138Y132\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_1\" LOC = \"SLICE_X139Y134\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_2\" LOC = \"SLICE_X138Y170\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_3\" LOC = \"SLICE_X138Y172\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_4\" LOC = \"SLICE_X139Y106\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_5\" LOC = \"SLICE_X138Y110\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_6\" LOC = \"SLICE_X138Y112\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_7\" LOC = \"SLICE_X139Y114\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_8\" LOC = \"SLICE_X138Y134\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_9\" LOC = \"SLICE_X138Y168\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_10\" LOC = \"SLICE_X139Y170\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_11\" LOC = \"SLICE_X138Y174\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_12\" LOC = \"SLICE_X138Y108\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_13\" LOC = \"SLICE_X139Y110\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_14\" LOC = \"SLICE_X138Y114\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_15\" LOC = \"SLICE_X138Y116\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_16\" LOC = \"SLICE_X138Y132\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_17\" LOC = \"SLICE_X139Y134\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_18\" LOC = \"SLICE_X138Y170\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_19\" LOC = \"SLICE_X138Y172\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_20\" LOC = \"SLICE_X139Y106\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_21\" LOC = \"SLICE_X138Y110\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_22\" LOC = \"SLICE_X138Y112\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_23\" LOC = \"SLICE_X139Y114\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_24\" LOC = \"SLICE_X138Y134\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_25\" LOC = \"SLICE_X138Y168\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_26\" LOC = \"SLICE_X139Y170\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_27\" LOC = \"SLICE_X138Y174\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_28\" LOC = \"SLICE_X138Y108\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_29\" LOC = \"SLICE_X139Y110\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_30\" LOC = \"SLICE_X138Y114\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_31\" LOC = \"SLICE_X138Y116\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_0\" LOC = \"SLICE_X138Y118\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_1\" LOC = \"SLICE_X138Y118\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_0\" LOC = \"SLICE_X138Y104\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_1\" LOC = \"SLICE_X138Y104\" | BEL = \"FFY\";\\n'];\n % end case 'adc0'\n\n case 'adc1'\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" PERIOD = ',num2str(1000/blk_obj.adc_clk_rate*4),'ns;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_buf\" MAXDELAY = 452ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk_dcm\" MAXDELAY = 854ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_clk90_dcm\" MAXDELAY = 854ps;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK_CLKBUF\" LOC = BUFGMUX0P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLK90_CLKBUF\" LOC = BUFGMUX2P;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" LOC = DCM_X2Y0;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/CLKSHIFT_DCM\" CLKOUT_PHASE_SHIFT = VARIABLE;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" MAXDELAY = 323ps;\\n'];\n \t\tstr = [str, 'NET \"',simulink_name,'/',simulink_name,'/adc_sync\" ROUTE = \"{3;1;2vp50ff1152;6b4b9e45!-1;156520;-144648;S!0;-159;0!1;-1884;-1248!1;-1884;744!2;-1548;992!2;-1548;304!3;-1548;-656!3;-1548;-1344!4;327;0;L!5;167;0;L!6;327;0;L!7;167;0;L!}\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_3\" LOC = SLICE_X139Y3;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_2\" LOC = SLICE_X138Y3;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_1\" LOC = SLICE_X139Y2;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_sync_ddr_0\" LOC = SLICE_X138Y2;\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_0\" LOC = \"SLICE_X139Y70\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_1\" LOC = \"SLICE_X138Y68\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_2\" LOC = \"SLICE_X139Y64\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_3\" LOC = \"SLICE_X139Y62\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_4\" LOC = \"SLICE_X139Y44\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_5\" LOC = \"SLICE_X139Y42\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_6\" LOC = \"SLICE_X138Y40\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_7\" LOC = \"SLICE_X139Y4\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_8\" LOC = \"SLICE_X139Y68\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_9\" LOC = \"SLICE_X139Y66\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_10\" LOC = \"SLICE_X138Y64\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_11\" LOC = \"SLICE_X139Y60\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_12\" LOC = \"SLICE_X138Y44\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_13\" LOC = \"SLICE_X139Y40\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_14\" LOC = \"SLICE_X139Y6\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_15\" LOC = \"SLICE_X138Y4\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_16\" LOC = \"SLICE_X139Y70\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_17\" LOC = \"SLICE_X138Y68\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_18\" LOC = \"SLICE_X139Y64\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_19\" LOC = \"SLICE_X139Y62\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_20\" LOC = \"SLICE_X139Y44\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_21\" LOC = \"SLICE_X139Y42\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_22\" LOC = \"SLICE_X138Y40\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_23\" LOC = \"SLICE_X139Y4\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_24\" LOC = \"SLICE_X139Y68\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_25\" LOC = \"SLICE_X139Y66\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_26\" LOC = \"SLICE_X138Y64\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_27\" LOC = \"SLICE_X139Y60\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_28\" LOC = \"SLICE_X138Y44\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_29\" LOC = \"SLICE_X139Y40\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_30\" LOC = \"SLICE_X139Y6\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_datai_recapture_31\" LOC = \"SLICE_X138Y4\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_0\" LOC = \"SLICE_X139Y74\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_1\" LOC = \"SLICE_X139Y78\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_2\" LOC = \"SLICE_X139Y80\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_3\" LOC = \"SLICE_X138Y84\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_4\" LOC = \"SLICE_X139Y48\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_5\" LOC = \"SLICE_X138Y52\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_6\" LOC = \"SLICE_X139Y54\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_7\" LOC = \"SLICE_X139Y56\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_8\" LOC = \"SLICE_X138Y76\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_9\" LOC = \"SLICE_X138Y80\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_10\" LOC = \"SLICE_X139Y82\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_11\" LOC = \"SLICE_X139Y84\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_12\" LOC = \"SLICE_X139Y50\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_13\" LOC = \"SLICE_X139Y52\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_14\" LOC = \"SLICE_X138Y56\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_15\" LOC = \"SLICE_X139Y58\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_16\" LOC = \"SLICE_X139Y74\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_17\" LOC = \"SLICE_X139Y78\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_18\" LOC = \"SLICE_X139Y80\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_19\" LOC = \"SLICE_X138Y84\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_20\" LOC = \"SLICE_X139Y48\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_21\" LOC = \"SLICE_X138Y52\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_22\" LOC = \"SLICE_X139Y54\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_23\" LOC = \"SLICE_X139Y56\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_24\" LOC = \"SLICE_X138Y76\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_25\" LOC = \"SLICE_X138Y80\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_26\" LOC = \"SLICE_X139Y82\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_27\" LOC = \"SLICE_X139Y84\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_28\" LOC = \"SLICE_X139Y50\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_29\" LOC = \"SLICE_X139Y52\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_30\" LOC = \"SLICE_X138Y56\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_dataq_recapture_31\" LOC = \"SLICE_X139Y58\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_0\" LOC = \"SLICE_X138Y60\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangei_recapture_1\" LOC = \"SLICE_X138Y60\" | BEL = \"FFY\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_0\" LOC = \"SLICE_X138Y48\" | BEL = \"FFX\";\\n'];\n \t\tstr = [str, 'INST \"',simulink_name,'/',simulink_name,'/adc_outofrangeq_recapture_1\" LOC = \"SLICE_X138Y48\" | BEL = \"FFY\";\\n'];\n % end case 'adc1'\n end % switch adc_str\n % end case 'iBOB'\nend % switch hw_sys\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adc083000_ctrl.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc083000_ctrl/xps_adc083000_ctrl.m", "size": 12028, "source_encoding": "utf_8", "md5": "ea808c81245c80dcd9690a19915c1d88", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_adc083000_ctrl(blk_obj)\n\nfprintf('Creating block object: xps_adc083000_ctrl\\n')\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_ADC class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_adc083000_ctrl')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n% \n% % Most of these parameters are hacks on top of the existing toolflow...\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.adc_str = 'adc0';\n% s.use_adc0 = strcmp( get_param(blk_name, 'use_adc0'), 'on');\n% s.use_adc1 = strcmp( get_param(blk_name, 'use_adc1'), 'on');\n% s.demux_adc = strcmp( get_param(blk_name, 'demux_adc'), 'on');\n% if s.demux_adc\n% s.sysclk_rate = eval_param(blk_name,'adc_clk_rate')/8;\n% else\n% s.sysclk_rate = eval_param(blk_name,'adc_clk_rate')/4;\n% end\n% if s.use_adc0\n% s.adc_str = 'adc0';\n% else\n% s.adc_str = 'adc1';\n% end\n% s.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\n% s.adc_interleave = strcmp( get_param(blk_name,'clock_sync'), 'on');\n% s.adc_str = 'adc0'; % \"dominant\" ADC is in ZDOK 0\n% \n% switch s.hw_sys\n% case 'ROACH'\n% ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(1000/s.adc_clk_rate*4),' ns']);\n% ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\n% ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n% ucf_constraints_single = struct('IOSTANDARD', 'LVCMOS25');\n% % end case 'ROACH'\n% otherwise\n% error(['Unsupported hardware system: ',s.hw_sys]);\n% end % end switch s.hw_sys\n% \nb = class(s,'xps_adc083000_ctrl',blk_obj);\n% \n% % ip name and version\nb = set(b, 'ip_name', 'opb_adc083000ctrl');\nswitch s.hw_sys\n case 'ROACH'\n b = set(b, 'ip_version', '1.00.a');\nend % switch s.hw_sys\n% \n% % misc ports\n% % misc_ports.ctrl_reset = {1 'in' [s.adc_str,'_ddrb']};\n% misc_ports.ctrl_clk_in = {1 'in' get(xsg_obj,'clk_src')};\n% misc_ports.ctrl_clk_out = {1 'out' [s.adc_str,'_clk']};\n% misc_ports.ctrl_clk90_out = {1 'out' [s.adc_str,'_clk90']};\n% misc_ports.ctrl_dcm_locked = {1 'out' [s.adc_str,'_dcm_locked']};\n% if strcmp(get(b,'ip_version'), '1.01.a')\n% misc_ports.dcm_reset = {1 'in' [s.adc_str,'_dcm_reset']};\n% misc_ports.dcm_psdone = {1 'out' [s.adc_str,'_psdone']};\n% misc_ports.ctrl_clk180_out = {1 'out' [s.adc_str,'_clk180']};\n% misc_ports.ctrl_clk270_out = {1 'out' [s.adc_str,'_clk270']};\n% end\nmisc_ports.sys_clk = {1 'in' 'sys_clk'};\n% misc_ports.adc_ctrl_notSCS = {1 'out' 'adc_ctrl_notSCS'};\n% misc_ports.adc_ctrl_clk = {1 'out' 'adc_ctrl_clk'};\n% misc_ports.adc_ctrl_sdata = {1 'out' 'adc_ctrl_sdata'};\n% % misc_ports.dcm_psen = {1 'in' [s.adc_str,'_psen']};\n% % misc_ports.dcm_psincdec = {1 'in' [s.adc_str,'_psincdec']};\n% % misc_ports.control_data = {1, 'in', 'adc_control_data'};\nb = set(b,'misc_ports',misc_ports);\n% \n% % external ports\n% mhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(s.adc_clk_rate*1e6));\n% \n% % adcport = [s.hw_sys, '.', 'zdok', s.adc_str(length(s.adc_str))];\n% adc0port = [s.hw_sys, '.', 'zdok0'];%, s.adc_str(length(s.adc_str))];\n% adc1port = [s.hw_sys, '.', 'zdok1'];%, s.adc_str(length(s.adc_str))];\n% \n% \n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ADC0\n% ext_ports.adc0_clk_p = {1 'in' ['adc0','clk_p'] ['{',adc0port,'_p{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\n% ext_ports.adc0_clk_n = {1 'in' ['adc0','clk_n'] ['{',adc0port,'_n{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\n% ext_ports.adc0_sync_p = {1 'in' ['adc0','sync_p'] ['{',adc0port,'_p{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\n% ext_ports.adc0_sync_n = {1 'in' ['adc0','sync_n'] ['{',adc0port,'_n{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\n% ext_ports.adc0_outofrange_p = {1 'in' ['adc0','outofrange_p'] ['{',adc0port,'_p{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\n% ext_ports.adc0_outofrange_n = {1 'in' ['adc0','outofrange_n'] ['{',adc0port,'_n{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\n% ext_ports.adc0_dataeveni_p = {8 'in' ['adc0','dataeveni_p'] ['{',adc0port,'_p{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc0_dataeveni_n = {8 'in' ['adc0','dataeveni_n'] ['{',adc0port,'_n{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc0_dataoddi_p = {8 'in' ['adc0','dataoddi_p'] ['{',adc0port,'_p{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc0_dataoddi_n = {8 'in' ['adc0','dataoddi_n'] ['{',adc0port,'_n{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc0_dataevenq_p = {8 'in' ['adc0','dataevenq_p'] ['{',adc0port,'_p{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc0_dataevenq_n = {8 'in' ['adc0','dataevenq_n'] ['{',adc0port,'_n{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc0_dataoddq_p = {8 'in' ['adc0','dataoddq_p'] ['{',adc0port,'_p{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc0_dataoddq_n = {8 'in' ['adc0','dataoddq_n'] ['{',adc0port,'_n{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc0_reset = {1 'out' ['adc0','_reset'] ['{',adc0port,'_p{[19]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n% \n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ADC1\n% ext_ports.adc1_clk_p = {1 'in' ['adc1','clk_p'] ['{',adc1port,'_p{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\n% ext_ports.adc1_clk_n = {1 'in' ['adc1','clk_n'] ['{',adc1port,'_n{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\n% ext_ports.adc1_sync_p = {1 'in' ['adc1','sync_p'] ['{',adc1port,'_p{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\n% ext_ports.adc1_sync_n = {1 'in' ['adc1','sync_n'] ['{',adc1port,'_n{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\n% ext_ports.adc1_outofrange_p = {1 'in' ['adc1','outofrange_p'] ['{',adc1port,'_p{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\n% ext_ports.adc1_outofrange_n = {1 'in' ['adc1','outofrange_n'] ['{',adc1port,'_n{[18]+1,:}}'] 'vector=false' struct() ucf_constraints_term };\n% ext_ports.adc1_dataeveni_p = {8 'in' ['adc1','dataeveni_p'] ['{',adc1port,'_p{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc1_dataeveni_n = {8 'in' ['adc1','dataeveni_n'] ['{',adc1port,'_n{[0 1 2 3 4 5 6 7]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc1_dataoddi_p = {8 'in' ['adc1','dataoddi_p'] ['{',adc1port,'_p{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc1_dataoddi_n = {8 'in' ['adc1','dataoddi_n'] ['{',adc1port,'_n{[10 11 12 13 14 15 16 17]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc1_dataevenq_p = {8 'in' ['adc1','dataevenq_p'] ['{',adc1port,'_p{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc1_dataevenq_n = {8 'in' ['adc1','dataevenq_n'] ['{',adc1port,'_n{[20 21 22 23 24 25 26 27]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc1_dataoddq_p = {8 'in' ['adc1','dataoddq_p'] ['{',adc1port,'_p{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc1_dataoddq_n = {8 'in' ['adc1','dataoddq_n'] ['{',adc1port,'_n{[30 31 32 33 34 35 36 37]+1,:}}'] 'vector=true' struct() ucf_constraints_term };\n% ext_ports.adc1_reset = {1 'out' ['adc1','_reset'] ['{',adc1port,'_p{[19]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\n\n\nadc0port = [s.hw_sys, '.', 'zdok0'];%, s.adc_str(length(s.adc_str))];\nadc1port = [s.hw_sys, '.', 'zdok1'];%, s.adc_str(length(s.adc_str))];\nucf_constraints_single = struct('IOSTANDARD', 'LVCMOS25');\n\next_ports.adc1_notSCS = {1 'out' ['adc1','_notSCS'] ['{',adc1port,'_p{[9]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\next_ports.adc1_sdata = {1 'out' ['adc1','_sdata'] ['{',adc1port,'_n{[9]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\next_ports.adc1_sclk = {1 'out' ['adc1','_sclk'] ['{',adc1port,'_n{[8]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\next_ports.adc0_notSCS = {1 'out' ['adc0','_notSCS'] ['{',adc0port,'_p{[9]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\next_ports.adc0_sdata = {1 'out' ['adc0','_sdata'] ['{',adc0port,'_n{[9]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\next_ports.adc0_sclk = {1 'out' ['adc0','_sclk'] ['{',adc0port,'_n{[8]+1,:}}'] 'vector=false' struct() ucf_constraints_single };\nb = set(b,'ext_ports',ext_ports);\n\n% parameters.DEMUX_DATA_OUT = num2str(s.demux_adc);\n% parameters.USE_ADC0 = num2str(s.use_adc0);\n% parameters.USE_ADC1 = num2str(s.use_adc1);\n% parameters.INTERLEAVE_BOARDS = num2str(s.adc_interleave);\n \n% b = set(b,'parameters',parameters);\n % Software parameters\n% b = set(b,'c_params',['adc = ',s.adc_str,' / interleave = ',num2str(s.adc_interleave)]);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc083000_ctrl/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_tengbe_v2/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_tengbe_v2/drc.m", "size": 3505, "source_encoding": "utf_8", "md5": "1356c1b0a660474d8e7554de2a61e6b2", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n try\r\n our_hw = get(blk_obj, 'hw_sys');\r\n\r\n our_port = get(blk_obj, 'port');\r\n their_port = get(xps_objs{i},'port');\r\n our_name = get(blk_obj, 'simulink_name');\r\n their_name = get(xps_objs{i},'simulink_name');\r\n\r\n %check two blocks not assigned to same port\r\n if strcmp(our_port, their_port), %same port\r\n if ~strcmp(our_name, their_name) % and name not the same\r\n msg = ['10Ge port ', our_name,' and 10Ge port ', their_name,' are located on the same port.'];\r\n result = 1;\r\n end\r\n end\r\n \r\n %check ports in the same slot are using the same mezzanine flavour\r\n our_flavour = get(blk_obj,'flavour'); \r\n their_flavour = get(xps_objs{i},'flavour'); \r\n our_slot = get(blk_obj,'slot'); \r\n their_slot = get(xps_objs{i},'slot'); \r\n if strcmp(our_hw, 'ROACH2'), %roach2\r\n if strcmp(our_slot, their_slot), % and card in the same slot\r\n if ~strcmp(our_flavour, their_flavour), % and not the same mezzanine flavour\r\n msg = ['10Ge ports ''', our_name,''' and ''', their_name,''' are both located in mezzanine slot ',our_slot,', but have different mezzanine flavours.'];\r\n result = 1;\r\n end\r\n end\r\n end\r\n if strcmp(our_hw, 'MKDIG'), %mkdig\r\n if strcmp(our_slot, their_slot), % and card in the same slot\r\n if ~strcmp(our_flavour, their_flavour), % and not the same mezzanine flavour\r\n msg = ['10Ge ports ''', our_name,''' and ''', their_name,''' are both located in mezzanine slot ',our_slot,', but have different mezzanine flavours.'];\r\n result = 1;\r\n end\r\n end\r\n end\r\n\r\n end %try\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_tengbe_v2.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_tengbe_v2/xps_tengbe_v2.m", "size": 8128, "source_encoding": "utf_8", "md5": "44f808b56e60b384ac86bcf4e622af26", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_tengbe_v2(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_TENGBE class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_tengbe_v2')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.flavour = get_param(blk_name, 'flavour');\ns.slot = get_param(blk_name, 'slot');\ns.preemph = get_param(blk_name, 'pre_emph');\ns.preemph_r2 = get_param(blk_name, 'pre_emph_r2');\ns.postemph_r2 = get_param(blk_name, 'post_emph_r2');\ns.rxeqmix_r2 = get_param(blk_name, 'rxeqmix_r2');\ns.swing = get_param(blk_name, 'swing');\ns.swing_r2 = get_param(blk_name, 'swing_r2');\ns.rx_dist_ram = num2str(strcmp(get_param(blk_name, 'rx_dist_ram'), 'on'));\ns.cpu_rx_enable = num2str(strcmp(get_param(blk_name, 'cpu_rx_en'), 'on'));\ns.cpu_tx_enable = num2str(strcmp(get_param(blk_name, 'cpu_tx_en'), 'on'));\ns.fab_mac = ['0x', dec2hex(eval(get_param(blk_name, 'fab_mac'))) ];\ns.fab_ip = ['0x', dec2hex(eval(get_param(blk_name, 'fab_ip'))) ];\ns.fab_udp = ['0x', dec2hex(eval(get_param(blk_name, 'fab_udp'))) ];\ns.fab_gate = ['0x', dec2hex(eval(get_param(blk_name, 'fab_gate'))) ];\ns.fab_en = num2str(strcmp(get_param(blk_name, 'fab_en'),'on'));\ns.large_packets = num2str(strcmp(get_param(blk_name, 'large_frames'),'on'));\ns.ttl = ['0x', dec2hex(eval(get_param(blk_name, 'ttl'))) ];\ns.promisc_mode = num2str(strcmp(get_param(blk_name, 'promisc_mode'),'on'));\n\n%convert (more intuitive) mask values to defines to be passed on if using ROACH2\nswitch s.hw_sys\n case {'ROACH'},\n s.port = get_param(blk_name, 'port_r1');\n\n case {'ROACH2','MKDIG'}, \n %get the port from the appropriate parameter, roach2 mezzanine slot 0 has 4-7, roach2 mezzanine slot 1 has 0-3, so barrel shift\n if(strcmp(s.flavour,'cx4')),\n s.port = num2str(str2num(get_param(blk_name, 'port_r2_cx4')) + 4*(mod(s.slot+1,2)));\n elseif strcmp(s.flavour,'sfp+'),\n s.port = num2str(str2num(get_param(blk_name, 'port_r2_sfpp')) + 4*(mod(s.slot+1,2)));\n else\n end\n\n %values below taken from ug366 transceiver user guide (should match with tengbe_v2_loadfcn)\n\n postemph_lookup = [0.18;0.19;0.18;0.18;0.18;0.18;0.18;0.18;0.19;0.2;0.39;0.63;0.82;1.07;1.32;1.6;1.65;1.94;2.21;2.52;2.76;3.08;3.41;3.77;3.97;4.36;4.73;5.16;5.47;5.93;6.38;6.89];\n index = find(postemph_lookup == str2num(s.postemph_r2));\n if isempty(index), \n error(['xps_tengbe_v2:''',str2num(s.postemph_r2),''' not found in ''',postemph_lookup,'''']);\n return; \n end\n s.postemph_r2 = num2str(index(1)-1);\n\n preemph_lookup = [0.15;0.3;0.45;0.61;0.74;0.91;1.07;1.25;1.36;1.55;1.74;1.94;2.11;2.32;2.54;2.77];\n index = find(preemph_lookup == str2num(s.preemph_r2));\n if index == [], \n error(['xps_tengbe_v2:''',str2num(s.preemph_r2),''' not found in ''',preemph_lookup,'''']);\n return; \n end\n s.preemph_r2 = num2str(index(1)-1);\n\n swing_lookup = [110;210;310;400;480;570;660;740;810;880;940;990;1040;1080;1110;1130];\n index = find(swing_lookup == str2num(s.swing_r2));\n if index == [], \n error(['xps_tengbe_v2:''',str2num(s.swing_r2),''' not found in ''',swing_lookup,'''']);\n return; \n end\n s.swing_r2 = num2str(index(1)-1);\n otherwise\nend\n\nb = class(s,'xps_tengbe_v2',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','kat_ten_gb_eth');\n\nswitch s.hw_sys\n case {'ROACH','ROACH2','MKDIG'},\n b = set(b,'ip_version','1.00.a');\n otherwise\n error(['10GbE not supported for platform ', s.hw_sys]);\nend\n\n% bus offset\n\n% ROACH/ROACH2 have OPB Ten Gig Eth interfaces\nswitch s.hw_sys\n case {'ROACH','ROACH2','MKDIG'},\n b = set(b,'opb_clk','epb_clk');\n b = set(b,'opb_address_offset',16384);\n b = set(b,'opb_address_align', hex2dec('4000'));\n % end case {'ROACH','ROACH2'}\nend % switch s.hw_sys\n\nparameters.FABRIC_MAC = s.fab_mac;\nparameters.FABRIC_IP = s.fab_ip;\nparameters.FABRIC_PORT = s.fab_udp;\nparameters.FABRIC_GATEWAY = s.fab_gate;\nparameters.FABRIC_ENABLE = s.fab_en;\nparameters.LARGE_PACKETS = s.large_packets;\nparameters.RX_DIST_RAM = s.rx_dist_ram;\nparameters.CPU_RX_ENABLE = s.cpu_rx_enable;\nparameters.CPU_TX_ENABLE = s.cpu_tx_enable;\nparameters.TTL = s.ttl;\n\nswitch s.hw_sys\n case {'MKDIG'}, \n parameters.PREEMPHASIS = s.preemph_r2; \n parameters.POSTEMPHASIS = s.postemph_r2;\n parameters.DIFFCTRL = s.swing_r2;\n parameters.RXEQMIX = s.rxeqmix_r2;\n case {'ROACH2'}, \n parameters.PREEMPHASIS = s.preemph_r2; \n parameters.POSTEMPHASIS = s.postemph_r2;\n parameters.DIFFCTRL = s.swing_r2;\n parameters.RXEQMIX = s.rxeqmix_r2;\n parameters.PROMISC_MODE = s.promisc_mode;\n otherwise,\n s.swing = get_param(blk_name, 'swing');\n parameters.SWING = s.swing;\n parameters.PREEMPHASYS = s.preemph;\nend\n\nb = set(b,'parameters',parameters);\n\n% bus interfaces\nswitch s.hw_sys\n case {'ROACH'},\n interfaces.XAUI_CONF = ['xaui_conf',s.port];\n interfaces.XGMII = ['xgmii',s.port];\n b = set(b,'interfaces',interfaces);\n % end case 'ROACH'\n case {'ROACH2','MKDIG'},\n interfaces.PHY_CONF = ['phy_conf',s.port];\n interfaces.XAUI_CONF = ['xaui_conf',s.port];\n interfaces.XGMII = ['xgmii',s.port];\n b = set(b,'interfaces',interfaces);\n % end case 'ROACH2'\nend % switch s.hw_sys\n\n% miscellaneous and external ports\n\nmisc_ports.clk = {1 'in' get(xsg_obj,'clk_src')};\n\next_ports = {};\n\nswitch s.hw_sys\n case {'ROACH'}, \n if strcmp(s.port, '0') || strcmp(s.port, '1')\n misc_ports.xaui_clk = {1 'in' 'mgt_clk_0'};\n else\n misc_ports.xaui_clk = {1 'in' 'mgt_clk_1'};\n end\n case {'ROACH2','MKDIG'},\n misc_ports.xaui_clk = {1 'in' 'xaui_clk'};\n misc_ports.xaui_reset = {1 'in' 'sys_reset'};\n \nend % switch s.hw_sys\n\nb = set(b,'misc_ports',misc_ports);\nb = set(b,'ext_ports',ext_ports);\n\n% borf parameters\nswitch s.hw_sys\n case {'ROACH','ROACH2','MKDIG'},\n borph_info.size = hex2dec('4000');\n borph_info.mode = 3;\n b = set(b,'borph_info',borph_info);\n otherwise\n borph_info.size = 1;\n borph_info.mode = 7;\n b = set(b,'borph_info',borph_info);\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_tengbe_v2/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_tengbe_v2/gen_mhs_ip.m", "size": 3638, "source_encoding": "utf_8", "md5": "86e0eb5822538ade94beb9891e89f228", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj,opb_addr_start,opb_name)\n\nxaui_port = get(blk_obj, 'port');\nhw_sys = get(blk_obj, 'hw_sys');\n\n[str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj.xps_block, opb_addr_start, opb_name);\nstr = [str, '\\n'];\n\nswitch hw_sys\n case {'ROACH'}\n\n mgt_clk_num = num2str(floor(str2num(xaui_port)/2)); \n\n str = [str, 'BEGIN xaui_phy', '\\n'];\n str = [str, ' PARAMETER INSTANCE = xaui_phy_', xaui_port, '\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\n str = [str, ' PARAMETER USE_KAT_XAUI = 0', '\\n'];\n str = [str, ' BUS_INTERFACE XAUI_SYS = xaui_sys', xaui_port, '\\n'];\n str = [str, ' BUS_INTERFACE XGMII = xgmii', xaui_port, '\\n'];\n str = [str, ' PORT reset = sys_reset' , '\\n'];\n str = [str, ' PORT mgt_clk = mgt_clk_', mgt_clk_num, '\\n'];\n str = [str, 'END', '\\n'];\n % end case {'ROACH'}\n case {'ROACH2','MKDIG'}\n str = [str, 'BEGIN xaui_phy', '\\n'];\n str = [str, ' PARAMETER INSTANCE = xaui_phy_', xaui_port, '\\n'];\n str = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\n str = [str, ' BUS_INTERFACE XAUI_SYS = xaui_sys', xaui_port, '\\n']; \n str = [str, ' BUS_INTERFACE XAUI_CONF = xaui_conf', xaui_port, '\\n']; \n str = [str, ' BUS_INTERFACE XGMII = xgmii', xaui_port, '\\n']; \n str = [str, ' PORT reset = sys_reset' , '\\n'];\n str = [str, ' PORT xaui_clk = xaui_clk', '\\n']; %from xaui_infrastructure\n str = [str, 'END', '\\n'];\n % end case {'ROACH'}\n otherwise\n % end otherwise\nend % switch hw_sys\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_fifo/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_fifo.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_fifo/xps_fifo.m", "size": 3265, "source_encoding": "utf_8", "md5": "d661803b23ad9780d87e1825f78d00ad", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_fifo(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_FIFO class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_fifo')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\ns.hw_sys = 'any';\n\nswitch get_param(blk_name,'io_dir')\n case 'From Processor'\n s.io_dir = 'in';\n case 'To Processor'\n s.io_dir = 'out';\nend % switch get_param(blk_name','io_dir')\n\nb = class(s,'xps_fifo',blk_obj);\n\n% opb clk\n\n% bus clock\nswitch get(xsg_obj,'hw_sys')\n case 'ROACH'\n b = set(b,'opb_clk','epb_clk');\n otherwise\n b = set(b,'opb_clk','sys_clk');\nend % switch get(xsg_obj,'hw_sys')\n\n% address offset\nb = set(b,'opb_address_offset',256);\n\n% misc ports\nmisc_ports.user_clk = {1 'in' get(xsg_obj,'clk_src')};\nb = set(b,'misc_ports',misc_ports);\n\n% %ip name, software parameters, borph mode\nswitch get_param(blk_name,'io_dir')\n case 'From Processor'\n b = set(b,'ip_name','opb_asyncfifo_ppc2simulink');\n\t\t b = set(b,'c_params','in');\n\t\t borph_info.mode = 6;\n case 'To Processor'\n\t\t b = set(b,'c_params','out');\n\t\t b = set(b,'ip_name','opb_asyncfifo_simulink2ppc');\n\t\t borph_info.mode = 5;\nend % switch get_param('blk_name,'io_dir')\n\n%parameters\nparameters.FIFO_LENGTH = num2str(eval_param(blk_name,'fifo_length'));\nparameters.FIFO_WIDTH = num2str(eval_param(blk_name,'data_width'));\n\nb = set(b,'parameters',parameters);\n\n% borph parameters\nborph_info.size = 512;\nb = set(b,'borph_info',borph_info);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_fifo/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc2x14_400/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc2x14_400/drc.m", "size": 1751, "source_encoding": "utf_8", "md5": "805b22d398f2f8ef4c982d1cd1e67683", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\nresult = 0;\nmsg = '';\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc2x14_400/gen_ucf.m", "size": 2924, "source_encoding": "utf_8", "md5": "89a6841bb7cfff129da7b6ae1f5e67d7", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\n\n\nstr = '';\n\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\n\nI_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_p'];\nI_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_n'];\n\nQ_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_p'];\nQ_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_n'];\n\nstr = [str, 'NET ', I_clk_p_str, ' TNM_NET = ', I_clk_p_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', I_clk_p_str, ' = PERIOD ', I_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\nstr = [str, 'NET ', I_clk_n_str, ' TNM_NET = ', I_clk_n_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', I_clk_n_str, ' = PERIOD ', I_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\nstr = [str, '\\n'];\n\nstr = [str, 'NET ', Q_clk_p_str, ' TNM_NET = ', Q_clk_p_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', Q_clk_p_str, ' = PERIOD ', Q_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\nstr = [str, 'NET ', Q_clk_n_str, ' TNM_NET = ', Q_clk_n_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', Q_clk_n_str, ' = PERIOD ', Q_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\nstr = [str, '\\n'];\n\nstr = [str, gen_ucf(blk_obj.xps_block)];\n\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adc2x14_400.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc2x14_400/xps_adc2x14_400.m", "size": 5504, "source_encoding": "utf_8", "md5": "a00952e81b80fcb5368968e7edb699a1", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_adc2x14_400(blk_obj)\nif ~isa(blk_obj,'xps_block')\n error('xps_quadc class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_adc2x14_400')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.adc_brd = get_param(blk_name, 'adc_brd');\ns.adc_str = ['adc', s.adc_brd];\n\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.clk_sys = get(xsg_obj,'clk_src');\n \n \nb = class(s,'xps_adc2x14_400',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','adc2x14_400_interface');\nb = set(b,'ip_version','1.00.a');\n\nparameters.OUTPUT_CLK = '0';\nif strfind(s.clk_sys,'adc')\n parameters.OUTPUT_CLK = '1';\nend\n \nb = set(b,'parameters',parameters);\n\n\n\n\n%%%%%%%%%%%%%%%%%\n% external ports\n%%%%%%%%%%%%%%%%%\nucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(2*1000/s.adc_clk_rate),' ns']);\nucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\nucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(1e6*s.adc_clk_rate/2));\n\n\next_ports.DRDY_I_p = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_I_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[20],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.DRDY_I_n = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_I_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[20],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\n\next_ports.DRDY_Q_p = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_Q_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[40],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.DRDY_Q_n = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_Q_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[40],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\n\next_ports.DI_p = {14 'in' ['adcmkid',s.adc_brd,'_DI_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[8 28 17 37 7 27 26 36 25 35 16 15 6 5],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.DI_n = {14 'in' ['adcmkid',s.adc_brd,'_DI_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[8 28 17 37 7 27 26 36 25 35 16 15 6 5],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.DQ_p = {14 'in' ['adcmkid',s.adc_brd,'_DQ_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[4 24 13 33 3 23 22 32 21 31 12 11 2 1],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.DQ_n = {14 'in' ['adcmkid',s.adc_brd,'_DQ_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[4 24 13 33 3 23 22 32 21 31 12 11 2 1],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.ADC_ext_in_p = {1 'in' ['adcmkid',s.adc_brd,'_ADC_ext_in_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[29],:}}'] 'vector=false' struct() ucf_constraints_term};\next_ports.ADC_ext_in_n = {1 'in' ['adcmkid',s.adc_brd,'_ADC_ext_in_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[29],:}}'] 'vector=false' struct() ucf_constraints_term};\n\n \nb = set(b,'ext_ports',ext_ports);\n\n%%%%%%%%%%%%%\n% misc ports\n%%%%%%%%%%%%%\nmisc_ports.fpga_clk = {1 'in' get(xsg_obj,'clk_src')};\n\nif strfind(s.clk_sys,'adc')\n misc_ports.adc_clk_out = {1 'out' [s.adc_str,'_clk']};\n misc_ports.adc_clk90_out = {1 'out' [s.adc_str,'_clk90']};\n misc_ports.adc_clk180_out = {1 'out' [s.adc_str,'_clk180']};\n misc_ports.adc_clk270_out = {1 'out' [s.adc_str,'_clk270']};\nend\n\nmisc_ports.adc_dcm_locked = {1 'out' [s.adc_str, '_dcm_locked']};\n\nb = set(b,'misc_ports',misc_ports);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc2x14_400/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc2x14_400_4x/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc2x14_400_4x/drc.m", "size": 1751, "source_encoding": "utf_8", "md5": "805b22d398f2f8ef4c982d1cd1e67683", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\nresult = 0;\nmsg = '';\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc2x14_400_4x/gen_ucf.m", "size": 2925, "source_encoding": "utf_8", "md5": "189c0d343b00d74728a5855a98569d17", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\n\nstr = '';\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\n\n\nI_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_p'];\nI_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_n'];\n\nQ_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_p'];\nQ_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_n'];\n\nstr = [str, 'NET ', I_clk_p_str, ' TNM_NET = ', I_clk_p_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', I_clk_p_str, ' = PERIOD ', I_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\nstr = [str, 'NET ', I_clk_n_str, ' TNM_NET = ', I_clk_n_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', I_clk_n_str, ' = PERIOD ', I_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\nstr = [str, '\\n'];\n\nstr = [str, 'NET ', Q_clk_p_str, ' TNM_NET = ', Q_clk_p_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', Q_clk_p_str, ' = PERIOD ', Q_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\nstr = [str, 'NET ', Q_clk_n_str, ' TNM_NET = ', Q_clk_n_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', Q_clk_n_str, ' = PERIOD ', Q_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\nstr = [str, '\\n'];\n\nstr = [str, gen_ucf(blk_obj.xps_block)];\n\n\n\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adc2x14_400_4x.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc2x14_400_4x/xps_adc2x14_400_4x.m", "size": 5526, "source_encoding": "utf_8", "md5": "3031c113c5a1ec3af9b37277baaad0c8", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_adc2x14_400_4x(blk_obj)\nif ~isa(blk_obj,'xps_block')\n error('xps_adc2x14_400_4x class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_adc2x14_400_4x')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.adc_brd = get_param(blk_name, 'adc_brd');\ns.adc_str = ['adc', s.adc_brd];\n\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.clk_sys = get(xsg_obj,'clk_src');\n \n \nb = class(s,'xps_adc2x14_400_4x',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','adc2x14_400_4x_interface');\nb = set(b,'ip_version','1.00.a');\n\nparameters.OUTPUT_CLK = '0';\nif strfind(s.clk_sys,'adc')\n parameters.OUTPUT_CLK = '1';\nend\n \nb = set(b,'parameters',parameters);\n\n\n\n\n%%%%%%%%%%%%%%%%%\n% external ports\n%%%%%%%%%%%%%%%%%\nucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(2*1000/s.adc_clk_rate),' ns']);\nucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\nucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(1e6*s.adc_clk_rate/2));\n\next_ports.DRDY_I_p = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_I_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[20],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.DRDY_I_n = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_I_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[20],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\n\next_ports.DRDY_Q_p = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_Q_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[40],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.DRDY_Q_n = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_Q_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[40],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\n\next_ports.DI_p = {14 'in' ['adcmkid',s.adc_brd,'_DI_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[8 28 17 37 7 27 26 36 25 35 16 15 6 5],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.DI_n = {14 'in' ['adcmkid',s.adc_brd,'_DI_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[8 28 17 37 7 27 26 36 25 35 16 15 6 5],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.DQ_p = {14 'in' ['adcmkid',s.adc_brd,'_DQ_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[4 24 13 33 3 23 22 32 21 31 12 11 2 1],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.DQ_n = {14 'in' ['adcmkid',s.adc_brd,'_DQ_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[4 24 13 33 3 23 22 32 21 31 12 11 2 1],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.ADC_ext_in_p = {1 'in' ['adcmkid',s.adc_brd,'_ADC_ext_in_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[29],:}}'] 'vector=false' struct() ucf_constraints_term};\next_ports.ADC_ext_in_n = {1 'in' ['adcmkid',s.adc_brd,'_ADC_ext_in_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[29],:}}'] 'vector=false' struct() ucf_constraints_term};\n\n \n\n\nb = set(b,'ext_ports',ext_ports);\n\n%%%%%%%%%%%%%\n% misc ports\n%%%%%%%%%%%%%\nmisc_ports.fpga_clk = {1 'in' get(xsg_obj,'clk_src')};\n\nif strfind(s.clk_sys,'adc')\n misc_ports.adc_clk_out = {1 'out' [s.adc_str,'_clk']};\n misc_ports.adc_clk90_out = {1 'out' [s.adc_str,'_clk90']};\n misc_ports.adc_clk180_out = {1 'out' [s.adc_str,'_clk180']};\n misc_ports.adc_clk270_out = {1 'out' [s.adc_str,'_clk270']};\nend\n\nmisc_ports.adc_dcm_locked = {1 'out' [s.adc_str, '_dcm_locked']};\n\nb = set(b,'misc_ports',misc_ports);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc2x14_400_4x/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_quadc/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_quadc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_quadc/xps_quadc.m", "size": 7993, "source_encoding": "utf_8", "md5": "2021aaf6e4fb0394de620b949e3b8b39", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_quadc(blk_obj)\nif ~isa(blk_obj,'xps_block')\n error('xps_quadc class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_quadc')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\n[hw_sys, hw_subsys] = xps_get_hw_plat(get(xsg_obj, 'hw_sys'));\n\ns.hw_sys = hw_sys;\ns.adc_brd = get_param(blk_name, 'adc_brd');\ns.adc_str = ['adc', s.adc_brd];\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\n\nswitch s.hw_sys\n case 'iBOB'\n if isempty(find(strcmp(s.adc_brd, {'0', '1'})))\n error(['Unsupported adc board: ',s.adc_brd]);\n end % if isempty(find(strcmp(s.hw_adc, {'0', '1'})))\n\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25_DT', 'PERIOD', [num2str(1000/s.adc_clk_rate),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25_DT');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n\n parameters = '';\n % end case 'iBOB'\n case 'ROACH'\n if isempty(find(strcmp(s.adc_brd, {'0', '1'})))\n error(['Unsupported adc board: ',s.adc_brd]);\n end % if ~isempty(find(strcmp(s.hw_adc, {'0', '1'})))\n\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(1000/s.adc_clk_rate),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n\n parameters.CLK_FREQ = num2str(s.adc_clk_rate);\n % end case 'ROACH'\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend % end switch s.hw_sys\n\nb = class(s,'xps_quadc',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','quadc_interface');\nb = set(b,'ip_version','1.00.a');\n\n% parameters\n\nb = set(b,'parameters',parameters);\n\n\n% misc ports\nmisc_ports.user_clk = {1 'in' get(xsg_obj,'clk_src')};\nmisc_ports.dcm_reset = {1 'in' 'net_gnd'};\nmisc_ports.reset = {1 'in' 'net_gnd'};\nmisc_ports.adc0_clk = {1 'out' [s.adc_str, '_clk']};\nmisc_ports.adc1_clk = {1 'out' ['quadc0_', s.adc_brd, '_adc1_clk']};\nmisc_ports.adc2_clk = {1 'out' ['quadc0_', s.adc_brd, '_adc2_clk']};\nmisc_ports.adc3_clk = {1 'out' ['quadc0_', s.adc_brd, '_adc3_clk']};\nmisc_ports.adc0_clk90 = {1 'out' [s.adc_str, '_clk90']};\nmisc_ports.adc0_clk180 = {1 'out' [s.adc_str, '_clk180']};\nmisc_ports.adc0_clk270 = {1 'out' [s.adc_str, '_clk270']};\n\nb = set(b,'misc_ports',misc_ports);\n\n% external ports\n\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(s.adc_clk_rate*1e6));\n\n% port indices are 0-indexed, +1 to convert to Matlab 1-indexing\next_ports.adc0_clk_in_p = {1 'in' ['quadc',s.adc_brd,'_adc0_clk_in_p'] ['{',hw_sys,'.zdok',s.adc_brd,'_p{[19]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.adc1_clk_in_p = {1 'in' ['quadc',s.adc_brd,'_adc1_clk_in_p'] ['{',hw_sys,'.zdok',s.adc_brd,'_p{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.adc2_clk_in_p = {1 'in' ['quadc',s.adc_brd,'_adc2_clk_in_p'] ['{',hw_sys,'.zdok',s.adc_brd,'_p{[32]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.adc3_clk_in_p = {1 'in' ['quadc',s.adc_brd,'_adc3_clk_in_p'] ['{',hw_sys,'.zdok',s.adc_brd,'_p{[30]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.adc0_data_in_p = {8 'in' ['quadc',s.adc_brd,'_adc0_data_in_p'] ['{',hw_sys,'.zdok',s.adc_brd,'_p{[29 9 18 28 8 7 17 27]+1 ,:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.adc1_data_in_p = {8 'in' ['quadc',s.adc_brd,'_adc1_data_in_p'] ['{',hw_sys,'.zdok',s.adc_brd,'_p{[37 6 16 26 36 5 15 25]+1 ,:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.adc2_data_in_p = {8 'in' ['quadc',s.adc_brd,'_adc2_data_in_p'] ['{',hw_sys,'.zdok',s.adc_brd,'_p{[35 4 14 24 34 3 13 23]+1 ,:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.adc3_data_in_p = {8 'in' ['quadc',s.adc_brd,'_adc3_data_in_p'] ['{',hw_sys,'.zdok',s.adc_brd,'_p{[33 2 12 22 20 10 11 21]+1 ,:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.adc0_clk_in_n = {1 'in' ['quadc',s.adc_brd,'_adc0_clk_in_n'] ['{',hw_sys,'.zdok',s.adc_brd,'_n{[19]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.adc1_clk_in_n = {1 'in' ['quadc',s.adc_brd,'_adc1_clk_in_n'] ['{',hw_sys,'.zdok',s.adc_brd,'_n{[39]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.adc2_clk_in_n = {1 'in' ['quadc',s.adc_brd,'_adc2_clk_in_n'] ['{',hw_sys,'.zdok',s.adc_brd,'_n{[32]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.adc3_clk_in_n = {1 'in' ['quadc',s.adc_brd,'_adc3_clk_in_n'] ['{',hw_sys,'.zdok',s.adc_brd,'_n{[30]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.adc0_data_in_n = {8 'in' ['quadc',s.adc_brd,'_adc0_data_in_n'] ['{',hw_sys,'.zdok',s.adc_brd,'_n{[29 9 18 28 8 7 17 27]+1 ,:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.adc1_data_in_n = {8 'in' ['quadc',s.adc_brd,'_adc1_data_in_n'] ['{',hw_sys,'.zdok',s.adc_brd,'_n{[37 6 16 26 36 5 15 25]+1 ,:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.adc2_data_in_n = {8 'in' ['quadc',s.adc_brd,'_adc2_data_in_n'] ['{',hw_sys,'.zdok',s.adc_brd,'_n{[35 4 14 24 34 3 13 23]+1 ,:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.adc3_data_in_n = {8 'in' ['quadc',s.adc_brd,'_adc3_data_in_n'] ['{',hw_sys,'.zdok',s.adc_brd,'_n{[33 2 12 22 20 10 11 21]+1 ,:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.sync_in_p = {1 'in' ['quadc',s.adc_brd,'_sync_in_p'] ['{',hw_sys,'.zdok',s.adc_brd,'_p{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term};\next_ports.sync_in_n = {1 'in' ['quadc',s.adc_brd,'_sync_in_n'] ['{',hw_sys,'.zdok',s.adc_brd,'_n{[38]+1,:}}'] 'vector=false' struct() ucf_constraints_term};\n\nb = set(b,'ext_ports',ext_ports);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_quadc/drc.m", "size": 1751, "source_encoding": "utf_8", "md5": "805b22d398f2f8ef4c982d1cd1e67683", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\nresult = 0;\nmsg = '';\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_quadc/gen_ucf.m", "size": 2408, "source_encoding": "utf_8", "md5": "acd646b9d25811dc1c75024b656787ce", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\n\nstr = '';\n\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\n\nadc0_clk_p_str = ['quadc', blk_obj.adc_brd,'_adc0_clk_in_p'];\nadc0_clk_n_str = ['quadc', blk_obj.adc_brd,'_adc0_clk_in_n'];\n\nstr = [str, 'NET ', adc0_clk_p_str, ' TNM_NET = ', adc0_clk_p_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', adc0_clk_p_str, ' = PERIOD ', adc0_clk_p_str, ' ', num2str(1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\nstr = [str, 'NET ', adc0_clk_n_str, ' TNM_NET = ', adc0_clk_n_str, ';\\n'];\nstr = [str, 'TIMESPEC TS_', adc0_clk_n_str, ' = PERIOD ', adc0_clk_n_str, ' ', num2str(1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\nstr = [str, '\\n'];\n\nstr = [str, gen_ucf(blk_obj.xps_block)];\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_quadc/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac/drc.m", "size": 2992, "source_encoding": "utf_8", "md5": "3ab77bfce809915097a39d56418ecd9a", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'hw_dac'), get(xps_objs{i},'hw_dac'))\r\n\t\t\tif ~strcmp(get(blk_obj, 'simulink_name'), get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['DAC ', get(blk_obj, 'simulink_name'),' and DAC ', get(xps_objs{i}, 'simulink_name'), ' are using the same connector.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\n\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'type'),'xps_dac') && strcmp(get(xps_objs{i},'type'), 'xps_adc')\r\n\t\t if (strcmp(get(blk_obj,'hw_dac'),'dac0') && strcmp(get(xps_objs{i},'hw_adc'),'adc0')) || (strcmp(get(blk_obj,'hw_dac'),'dac1') && strcmp(get(xps_objs{i},'hw_adc'),'adc1'))\r\n\t\t msg = ['DAC ', get(blk_obj,'simulink_name'), ' and ADC ', get(xps_objs{i},'simulink_name'),' are located on the same Z-DOK connector.'];\r\n\t\t result = 1;\r\n\t\t end\r\n\t\tend\r\n end\r\n\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'type'),'xps_dac') && strcmp(get(xps_objs{i},'type'), 'xps_vsi')\r\n\t\t if strcmp(get(blk_obj,'hw_dac'),'dac1') && strcmp(get(xps_objs{i},'hw_vsi'),'ZDOK 1')\r\n\t\t msg = ['DAC ', get(blk_obj,'simulink_name'), ' and VSI ', get(xps_objs{i},'simulink_name'),' are located on the same Z-DOK connector.'];\r\n\t\t result = 1;\r\n\t\t end\r\n\t\tend\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_dac.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac/xps_dac.m", "size": 4674, "source_encoding": "utf_8", "md5": "a64840961507464b332f4452efda00b2", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_dac(blk_obj)\nif ~isa(blk_obj,'xps_block')\n error('XPS_DAC class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_dac')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\ns.dac_clk_rate = eval_param(blk_name,'dac_clk_rate');\n[s.hw_sys,s.hw_dac] = xps_get_hw_info(get_param(blk_name,'dac_brd'));\n\nswitch s.hw_sys\n case 'iBOB'\n switch s.hw_dac\n case 'dac0'\n s.dac_str = 'dac0';\n case 'dac1'\n s.dac_str = 'dac1';\n otherwise\n error(['Unsupported dac board: ',s.hw_dac]);\n end\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend\n\ns.invert_clk = get_param(gcb, 'invert_clock');\n\nb = class(s,'xps_dac',blk_obj);\n\n% ip name\nb = set(b,'ip_name','dac_interface');\nb = set(b,'ip_version','1.00.b');\n\n% parameters\nparameters.CTRL_CLK_PHASE = num2str(strcmp(s.invert_clk, 'on'));\nb = set(b,'parameters',parameters);\n\n% misc ports\nmisc_ports.user_data_clk = {1 'out' [s.dac_str,'_clk']};\nmisc_ports.user_data_clk90 = {1 'out' [s.dac_str,'_clk90']};\nb = set(b,'misc_ports',misc_ports);\n\n% external ports\n\nucf_constraints = struct('IOSTANDARD', 'LVDS_25');\n\next_ports.dac_dsp_clk_p = {1 'in' [s.dac_str,'_dsp_clk_p'] ['iBOB.',s.dac_str,'.dsp_clk_p'] 'vector=false' struct() ucf_constraints};\next_ports.dac_dsp_clk_n = {1 'in' [s.dac_str,'_dsp_clk_n'] ['iBOB.',s.dac_str,'.dsp_clk_n'] 'vector=false' struct() ucf_constraints};\n\next_ports.dac_data_clk_p = {1 'out' [s.dac_str,'_data_clk_p'] ['iBOB.',s.dac_str,'.data_clk_p'] 'vector=false' struct() ucf_constraints};\next_ports.dac_data_clk_n = {1 'out' [s.dac_str,'_data_clk_n'] ['iBOB.',s.dac_str,'.data_clk_n'] 'vector=false' struct() ucf_constraints};\next_ports.dac_data_a_p = {9 'out' [s.dac_str,'_data_a_p'] ['iBOB.',s.dac_str,'.data_a_p'] 'vector=true' struct() ucf_constraints};\next_ports.dac_data_a_n = {9 'out' [s.dac_str,'_data_a_n'] ['iBOB.',s.dac_str,'.data_a_n'] 'vector=true' struct() ucf_constraints};\next_ports.dac_data_b_p = {9 'out' [s.dac_str,'_data_b_p'] ['iBOB.',s.dac_str,'.data_b_p'] 'vector=true' struct() ucf_constraints};\next_ports.dac_data_b_n = {9 'out' [s.dac_str,'_data_b_n'] ['iBOB.',s.dac_str,'.data_b_n'] 'vector=true' struct() ucf_constraints};\next_ports.dac_data_c_p = {9 'out' [s.dac_str,'_data_c_p'] ['iBOB.',s.dac_str,'.data_c_p'] 'vector=true' struct() ucf_constraints};\next_ports.dac_data_c_n = {9 'out' [s.dac_str,'_data_c_n'] ['iBOB.',s.dac_str,'.data_c_n'] 'vector=true' struct() ucf_constraints};\next_ports.dac_data_d_p = {9 'out' [s.dac_str,'_data_d_p'] ['iBOB.',s.dac_str,'.data_d_p'] 'vector=true' struct() ucf_constraints};\next_ports.dac_data_d_n = {9 'out' [s.dac_str,'_data_d_n'] ['iBOB.',s.dac_str,'.data_d_n'] 'vector=true' struct() ucf_constraints};\n\nb = set(b, 'ext_ports', ext_ports);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_dac/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adcdac_2g_ctrl/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adcdac_2g_ctrl.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adcdac_2g_ctrl/xps_adcdac_2g_ctrl.m", "size": 3717, "source_encoding": "utf_8", "md5": "7bbd49bb50610152e5e78aca47a6c116", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Make sure this is an XPS object\nfunction b = xps_adcdac_2g_ctrl(blk_obj)\ndisp('calling xps_adcdac_2g_ctrl!');\nif ~isa(blk_obj,'xps_block')\n error('xps_adcdac_2g_ctrl class requires a xps_block class object');\nend\n% Then check that it's the right type\nif ~strcmp(get(blk_obj,'type'),'xps_adcdac_2g_ctrl')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\ndisp('.1');\ndisp('.1');\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\n\n% Get the mask parameters we need to know\ns.clk_sys = get(xsg_obj,'clk_src');\ndisp('.1');\n \n \nb = class(s,'xps_adcdac_2g_ctrl',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','adcdac_2g_ctrl');\nb = set(b,'ip_version','1.00.a');\n\ndisp('.1');\n%b = set(b,'parameters',parameters);\n\n\nn_adc_samples_per_fabric_cycle = 8;\n\n\n% external ports\nucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\nucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\ndisp('.1');\n\n%data in\nadcport1 = [s.hw_sys, '.', 'zdok1'];\nadcport0 = [s.hw_sys, '.', 'zdok0'];\n\n%first 3 bits in each are (valid,sysref,overrange)\next_ports.zdok_tx_data_p = {1 'out' ['adc_ctrl_tx_data_p'] ['{',adcport1,'_p{[10],:}}'] 'vector=false' struct() ucf_constraints_term};\next_ports.zdok_tx_data_n = {1 'out' ['adc_ctrl_tx_data_n'] ['{',adcport1,'_n{[10],:}}'] 'vector=false' struct() ucf_constraints_term};\n\next_ports.zdok_rx_data_p = {1 'in' ['adc_ctrl_rx_data_p'] ['{',adcport1,'_p{[30],:}}'] 'vector=false' struct() ucf_constraints_term};\next_ports.zdok_rx_data_n = {1 'in' ['adc_ctrl_rx_data_n'] ['{',adcport1,'_n{[30],:}}'] 'vector=false' struct() ucf_constraints_term};\n\n\nb = set(b,'ext_ports',ext_ports);\n\n% Add ports not explicitly provided in the yellow block\n\n%clock from fpga \nmisc_ports.fpga_clk = {1 'in' get(xsg_obj,'clk_src')};\n%100 MHz clock for the uart\n%misc_ports.sys_clk = {1 'in' 'sys_clk'};\n\nb = set(b,'misc_ports',misc_ports);\n\ndisp('done calling xps_adcdac_2g_ctrl!');\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adcdac_2g_ctrl/drc.m", "size": 1751, "source_encoding": "utf_8", "md5": "805b22d398f2f8ef4c982d1cd1e67683", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\nresult = 0;\nmsg = '';\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adcdac_2g_ctrl/gen_ucf.m", "size": 3032, "source_encoding": "utf_8", "md5": "26e3675df4b10667893187319a84bbc2", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\n\nstr = gen_ucf(blk_obj.xps_block);\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\n\n%str = '';\n%simulink_name = clear_name(get(blk_obj,'simulink_name'));\n\n%I_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_p'];\n%I_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_n'];\n\n%Q_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_p'];\n%Q_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_n'];\n\n%str = [str, 'NET ', I_clk_p_str, ' TNM_NET = ', I_clk_p_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', I_clk_p_str, ' = PERIOD ', I_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n%str = [str, 'NET ', I_clk_n_str, ' TNM_NET = ', I_clk_n_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', I_clk_n_str, ' = PERIOD ', I_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\n%str = [str, '\\n'];\n\n%str = [str, 'NET ', Q_clk_p_str, ' TNM_NET = ', Q_clk_p_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', Q_clk_p_str, ' = PERIOD ', Q_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n%str = [str, 'NET ', Q_clk_n_str, ' TNM_NET = ', Q_clk_n_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', Q_clk_n_str, ' = PERIOD ', Q_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\n%str = [str, '\\n'];\n\n%str = [str, gen_ucf(blk_obj.xps_block)];\n\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adcdac_2g_ctrl/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_ucf/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_ucf/drc.m", "size": 1750, "source_encoding": "utf_8", "md5": "1182852afc273984ab70c6751547f164", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\nresult = 0;\nmsg = '';\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_ucf/gen_ucf.m", "size": 1793, "source_encoding": "utf_8", "md5": "9383c96970079c7bcd7e637f32c43718", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\nfunction str = gen_ucf(blk_obj)\n\ndisp('Adding custom UCF entries:');\nstr = fileread(get(blk_obj,'ucf_file'))\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_ucf/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_ucf/xps_ucf.m", "size": 2109, "source_encoding": "utf_8", "md5": "9e3b552cf030f5556e63ce0600c82728", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_ucf(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_UCF class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_ucf')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj, 'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\ns.ucf_file = get_param(blk_name,'ucf_file')\ns.hw_sys = get(xsg_obj,'hw_sys');\n\nb = class(s,'xps_ucf',blk_obj);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_gpio/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_gpio/drc.m", "size": 7117, "source_encoding": "utf_8", "md5": "cab0cd6351bb291c5d27b8c1a5784ba3", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\nresult = 0;\nmsg = '';\n\nif ~exist(blk_obj.hw_sys) | ~isstruct(blk_obj.hw_sys)\n load_hw_routes();\nend % ~exist(blk_obj.hw_sys) | ~isstruct(blk_obj.hw_sys)\n\ntry\n eval(['pads = ',blk_obj.hw_sys,'.',blk_obj.io_group,';']);\ncatch\n try\n eval(['pads = ',blk_obj.hw_sys,'.',blk_obj.io_group,'_p;']);\n catch\n msg = ['Undefined routing table for hardware system: ',blk_obj.hw_sys,'(',blk_obj.io_group,')'];\n result = 1;\n end % try\nend % try\n\nif ~isempty(find(blk_obj.bit_index>=length(pads)))\n msg = 'Gateway bit index contain values that exceeds the io_bitwidth';\n result = 1;\nend % ~isempty(find(blk_obj.bit_index>=length(pads)))\n\nif blk_obj.use_ddr\n if ~blk_obj.reg_iob\n msg = 'When using DDR signaling mode, \"Pack register in the pad\" option must be on';\n result = 1;\n end % ~blk_obj.reg_iob\n if blk_obj.io_bitwidth/2 > length(pads)\n msg = 'Gateway io_bitwidth is larger than the number of available pads';\n result = 1;\n end % blk_obj.io_bitwidth/2 > length(pads)\n if length(blk_obj.bit_index) ~= blk_obj.io_bitwidth/2\n msg = 'Gateway bit index does not have half the number of elements of the I/O io_bitwidth';\n result = 1;\n end % length(blk_obj.bit_index) ~= blk_obj.io_bitwidth/2\nelse\n if blk_obj.io_bitwidth > length(pads)\n msg = 'Gateway io_bitwidth is larger than the number of available pads';\n result = 1;\n end % if blk_obj.io_bitwidth > length(pads)\n if length(blk_obj.bit_index) ~= blk_obj.io_bitwidth\n msg = 'Gateway bit index does not have the same number of elements as the I/O io_bitwidth';\n result = 1;\n end % if length(blk_obj.bit_index) ~= blk_obj.io_bitwidth\nend %blk_obj.use_ddr\n\nxsg_obj = get(blk_obj,'xsg_obj');\nclk_src = get(xsg_obj,'clk_src');\n\nif strcmp(blk_obj.hw_sys, 'iBOB') & strmatch('usr_clk', clk_src)\n try\n if strcmp(get(xsg_obj, 'gpioclk_grp'), blk_obj.io_group)\n bit_index = blk_obj.bit_index;\n for n=1:length(bit_index)\n if ~isempty(find(get(xsg_obj,'gpioclkbit')==bit_index(n)))\n msg = ['User clock input and GPIO ',get(blk_obj,'simulink_name'),' share the same I/O pin.'];\n result = 1;\n end % if ~isempty(find(get(xsg_obj,'gpioclkbit')==bit_index(n)))\n end % for n=1:length(bit_index)\n end % if strcmp(get(xsg_obj, 'gpioclk_grp'), blk_obj.io_group)\n end % try\nend % if strcmp(blk_obj.hw_sys, 'iBOB') & strmatch('usr_clk', clk_src)\n\n\nfor n=1:length(xps_objs)\n try\n if strcmp(blk_obj.hw_sys,get(xps_objs{n},'hw_sys')) && strcmp(blk_obj.io_group,get(xps_objs{n},'io_group'))\n if ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{n},'simulink_name'))\n\n bit_index = blk_obj.bit_index;\n\n\t\t\t % Check for single-ended/differential I/O conflicts\n if ~isempty(find(strcmp(blk_obj.io_group,{'zdok0', 'zdok1', 'mdr'})))\n if strcmp(get(blk_obj,'single_ended'), 'on') & strcmp(get(xps_objs{n},'single_ended'), 'off')\n for k=1:length(bit_index)\n\t\t \t\t\t if ~isempty(find(get(xps_objs{n},'bit_index')==floor(bit_index(k)/2)))\n\t\t\t \t\t\t msg = ['GPIO ',get(blk_obj,'simulink_name'),' and GPIO ',get(xps_objs{n},'simulink_name'),' share the same I/O pin.'];\n\t\t\t\t \t\t result = 1;\n\t\t\t\t\t end % if ~isempty(find(get(xps_objs{n},'bit_index')==floor(bit_index(k)/2)))\n\t\t\t\t\t end % for k=1:length(bit_index)\n elseif strcmp(get(blk_obj,'single_ended'), 'off') & strcmp(get(xps_objs{n}, 'single_ended'), 'on')\n for k=1:length(bit_index)\n\t\t \t\t\t if ~isempty(find(get(xps_objs{i},'bit_index')==floor(bit_index(j)/2)))\n\t\t\t \t\t\t msg = ['GPIO ',get(blk_obj,'simulink_name'),' and GPIO ',get(xps_objs{n},'simulink_name'),' share the same I/O pin.'];\n\t\t\t\t \t\t result = 1;\n\t\t\t\t\t end % if ~isempty(find(get(xps_objs{i},'bit_index')==floor(bit_index(j)/2)))\n\t\t\t\t\t end % for k=1:length(bit_index)\n else\n\t \t\t\t for k=1:length(bit_index)\n\t\t \t\t\t if ~isempty(find(get(xps_objs{n},'bit_index')==bit_index(k)))\n\t\t\t \t\t\t msg = ['GPIO ',get(blk_obj,'simulink_name'),' and GPIO ',get(xps_objs{n},'simulink_name'),' share the same I/O pin.'];\n\t\t\t\t \t\t result = 1;\n\t\t\t\t\t end % if ~isempty(find(get(xps_objs{n},'bit_index')==bit_index(k)))\n\t\t\t\t end % for k=1:length(bit_index)\n\t\t\t\t end % if strcmp(get(blk_obj,'single_ended'), 'on') & strcmp(get(xps_objs{n},'single_ended'), 'off')\n\t\t\t\telse\n for k=1:length(bit_index)\n if ~isempty(find(get(xps_objs{n},'bit_index')==bit_index(k)))\n msg = ['GPIO ',get(blk_obj,'simulink_name'),' and GPIO ',get(xps_objs{n},'simulink_name'),' share the same I/O pin.'];\n result = 1;\n end % if ~isempty(find(get(xps_objs{n},'bit_index')==bit_index(k)))\n end % for k=1:length(bit_index)\n end % if ~isempty(find(strcmp(blk_obj.io_group,{'zdok0', 'zdok1', 'mdr'})))\n end % if ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{n},'simulink_name'))\n end % if strcmp(blk_obj.hw_sys,get(xps_objs{n},'hw_sys')) && strcmp(blk_obj.io_group,get(xps_objs{n},'io_group'))\n end % try\nend % for n=1:length(xps_objs)\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_gpio.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_gpio/xps_gpio.m", "size": 5834, "source_encoding": "utf_8", "md5": "117f464211a8a12255f6b15482755002", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_gpio(blk_obj)\nif ~isa(blk_obj,'xps_block')\n error('XPS_GPIO class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_gpio')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\nblk_name = get(blk_obj,'simulink_name');\n[s.hw_sys,s.io_group] = xps_get_hw_info(get_param(blk_name,'io_group'));\ns.bit_index = eval_param(blk_name,'bit_index');\ns.io_dir = get_param(blk_name,'io_dir');\ns.reg_iob = get_param(blk_name,'reg_iob');\ns.arith_type = get_param(blk_name,'arith_type');\nif strcmp(s.arith_type,'Boolean')\n\ts.io_bitwidth = 1;\nelse\n\ts.io_bitwidth = eval_param(blk_name,'bitwidth');\nend\ns.reg_clk_phase = get_param(blk_name,'reg_clk_phase');\ns.use_ddr = strcmp(get_param(blk_name,'use_ddr'),'on');\ns.termtype = get_param(blk_name,'termination');\ns.single_ended = get_param(blk_name,'use_single_ended');\nb = class(s,'xps_gpio',blk_obj);\n\nuse_diffio = ~isempty(strmatch(s.io_group, {'zdok0', 'zdok1', 'mdr', 'qsh', 'sync_in', 'sync_out'})) & strcmp(s.single_ended, 'off');\n\nif ~isempty(strmatch(s.termtype, {'Pullup', 'Pulldown'}))\n termination = s.termtype;\nelse\n termination = '';\nend % ~isempty(strmatch(s.termtype, {'Pullup', 'Pulldown'}))\n\n\n% ip name\nif use_diffio\n switch s.io_dir\n case 'in'\n b = set(b, 'ip_name','diffgpio_ext2simulink');\n case 'out'\n b = set(b, 'ip_name','diffgpio_simulink2ext');\n end\nelse\n switch s.io_dir\n case 'in'\n b = set(b, 'ip_name','gpio_ext2simulink');\n case 'out'\n b = set(b, 'ip_name','gpio_simulink2ext');\n end\nend\n\n% external ports\n\nswitch s.hw_sys\n case 'ROACH'\n if use_diffio\n iostandard = 'LVDS_25';\n else\n switch s.io_group\n case 'led'\n iostandard = 'LVCMOS18';\n case 'gpioa_oe_n'\n iostandard = 'LVCMOS33';\n case 'gpiob_oe_n'\n iostandard = 'LVCMOS33';\n case 'gpiob'\n iostandard = 'LVCMOS15';\n otherwise\n iostandard = 'LVCMOS25';\n end \n end % if use_diffio\n % end case 'ROACH'\n case 'ROACH2'\n if use_diffio\n iostandard = 'LVDS_25';\n else\n iostandard = 'LVCMOS15';\n end % if use_diffio\n % end case 'ROACH2'\n otherwise\n iostandard = 'LVCMOS25';\nend % switch 'hw_sys'\n\nucf_fields = {};\nucf_values = {};\n\n%ucf_fields = [ucf_fields, 'IOSTANDARD', termination];\n%ucf_values = [ucf_values, iostandard, ''];\n\nif ~isempty(termination)\n ucf_constraints = struct('IOSTANDARD',iostandard, termination,'');\nelse\n ucf_constraints = struct('IOSTANDARD',iostandard);\nend % if ~isempty(termination)\n\nswitch s.use_ddr\n case 0\n pad_bitwidth = s.io_bitwidth;\n case 1\n pad_bitwidth = s.io_bitwidth/2;\nend % switch s.use_ddr\n\nextportname = [clear_name(blk_name), '_ext'];\niobname = [s.hw_sys, '.', s.io_group];\n\n%ucf_constraints = cell2struct(ucf_values, ucf_fields, length(ucf_fields));\n\nswitch use_diffio\n case 0\n ext_ports.io_pad = {pad_bitwidth s.io_dir extportname [iobname,' ([',num2str(s.bit_index),']+1)'] 'vector=true' struct() ucf_constraints };\n case 1\n ext_ports.io_pad_p = {pad_bitwidth s.io_dir [extportname, '_p'] [iobname,'_p([',num2str(s.bit_index),']+1)'] 'vector=true' struct() ucf_constraints };\n ext_ports.io_pad_n = {pad_bitwidth s.io_dir [extportname, '_n'] [iobname,'_n([',num2str(s.bit_index),']+1)'] 'vector=true' struct() ucf_constraints };\nend % switch use_diffio\n\nb = set(b,'ext_ports',ext_ports);\n\n% parameters\nparameters.DDR = num2str(s.use_ddr);\nparameters.WIDTH = num2str(s.io_bitwidth);\nparameters.CLK_PHASE = num2str(s.reg_clk_phase);\nif strcmp(s.reg_iob,'on')\n\tparameters.REG_IOB = 'true';\nelse\n\tparameters.REG_IOB = 'false';\nend % if strcmp(s.reg_iob,'on')\nb = set(b,'parameters',parameters);\n\n% misc ports\nxsg_obj = get(blk_obj,'xsg_obj');\nmisc_ports.clk = {1 'in' get(xsg_obj,'clk_src')};\nmisc_ports.clk90 = {1 'in' get(xsg_obj,'clk90_src')};\nb = set(b,'misc_ports',misc_ports);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_gpio/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_ethlite/get.m", "size": 1965, "source_encoding": "utf_8", "md5": "e4447d00c910af45efa20e63d8451e64", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknown to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_ethlite/drc.m", "size": 2036, "source_encoding": "utf_8", "md5": "41e9985e657e9783c74f5507be37bbff", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\ntry\r\n if ( strcmp(get(xps_objs{i},'type'), 'xps_xsg') && ~strcmp(get(xps_objs{i},'hw_sys'), 'iBOB'))\r\n msg = ['Ethernetlite ', get(blk_obj,'simulink_name'), ' can not be used on a platform other than IBOB.'];\r\n result = 1;\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_ethlite/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_ethlite.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_ethlite/xps_ethlite.m", "size": 3692, "source_encoding": "utf_8", "md5": "8b52790b2798d513add9f5b003e18f64", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_ethlite(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_ETHLITE class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_ethlite')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = 'iBOB';\n\nb = class(s,'xps_ethlite',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','opb_ethernetlite');\nb = set(b,'ip_version','1.01.b');\n\n% software driver\nb = set(b, 'soft_driver', {'emaclite','1.01.a'});\n\n% bus offset\nb = set(b,'opb_address_offset',hex2dec('2000'));\nb = set(b,'opb_address_align', hex2dec('2000'));\n\n% parameters\nparameters.C_OPB_CLK_PERIOD_PS = '10000';\nb = set(b,'parameters',parameters);\n\n% external ports\nucf_constraints = struct('IOSTANDARD', 'LVCMOS25');\n\next_ports.PHY_col = {1 'in' 'opb_ethlite_phy_col' {'J32'} 'vector=false' struct() ucf_constraints};\next_ports.PHY_crs = {1 'in' 'opb_ethlite_phy_crs' {'J31'} 'vector=false' struct() ucf_constraints};\next_ports.PHY_dv = {1 'in' 'opb_ethlite_phy_dv' {'F33'} 'vector=false' struct() ucf_constraints};\next_ports.PHY_rx_clk = {1 'in' 'opb_ethlite_phy_rx_clk' {'H29'} 'vector=false' struct() ucf_constraints};\next_ports.PHY_rx_data = {4 'in' 'opb_ethlite_phy_rx_data' {'G30' 'G29' 'G32' 'G31'} 'vector=false' struct() ucf_constraints};\next_ports.PHY_rx_er = {1 'in' 'opb_ethlite_phy_rx_err' {'F34'} 'vector=false' struct() ucf_constraints};\next_ports.PHY_tx_clk = {1 'in' 'opb_ethlite_phy_tx_clk' {'H30'} 'vector=false' struct() ucf_constraints};\next_ports.PHY_tx_data = {4 'out' 'opb_ethlite_phy_tx_data' {'J30' 'J29' 'G34' 'G33'} 'vector=false' struct() ucf_constraints};\next_ports.PHY_tx_en = {1 'out' 'opb_ethlite_phy_tx_en' {'L26'} 'vector=false' struct() ucf_constraints};\nb = set(b,'ext_ports',ext_ports);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_probe/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_probe/drc.m", "size": 2780, "source_encoding": "utf_8", "md5": "2942cff975cd5cc6481184f3341b1a34", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\nfor i=1:length(xps_objs)\r\n\ttry\r\n\t\tif strcmp(get(blk_obj,'ila_number'),get(xps_objs{i},'ila_number'))\r\n\t\t\tif ~strcmp(get(blk_obj,'simulink_name'),get(xps_objs{i},'simulink_name'))\r\n\t\t\t\tmsg = ['Probe ',get(blk_obj,'simulink_name'),' and probe ',get(xps_objs{i},'simulink_name'),' have the same ILA number.'];\r\n\t\t\t\tresult = 1;\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\nend\r\n\r\nnb_probes = 0;\r\nmax_ila_n = 0;\r\nfor i=1:length(xps_objs)\r\n\tif strcmp(get(xps_objs{i},'type'),'xps_probe')\r\n\t\tnb_probes = nb_probes + 1;\r\n\t\tila_n = get(xps_objs{i},'ila_number');\r\n\t\tif ila_n > max_ila_n\r\n\t\t\tmax_ila_n = ila_n;\r\n\t\tend\r\n\tend\r\nend\r\nif nb_probes ~= max_ila_n + 1\r\n\tmsg = ['ILA numbers not organized correctly for the chipscope probes. They should be growing from 0 to ',num2str(nb_probes-1)];\r\n\tresult = 1;\r\nend\r\n\r\n% EDK 7.1 limits the number of ILA probes to 1\r\nif nb_probes ~= 1\r\n\tmsg = 'Due to current implementation limitations in EDK 7.1, you can only use one probe in a design and it has to have the ILA number 0';\r\n\tresult = 1;\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_probe.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_probe/xps_probe.m", "size": 3006, "source_encoding": "utf_8", "md5": "fd3e447973d24f0c52dc4a1adf8a2af4", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = xps_probe(blk_obj)\r\n\r\nif ~isa(blk_obj,'xps_block')\r\n error('XPS_PROBE class requires a xps_block class object');\r\nend\r\nif ~strcmp(get(blk_obj,'type'),'xps_probe')\r\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\r\nend\r\nblk_name = get(blk_obj,'simulink_name');\r\ns.hw_sys = 'any';\r\ns.match_type = get_param(blk_name,'match_type');\r\ns.match_counter_width = get_param(blk_name,'match_counter_width');\r\ns.ila_number = str2num(get_param(blk_name,'ila_number'));\r\ns.capture_depth = get_param(blk_name, 'capture_depth');\r\nif strcmp(get_param(blk_name,'arith_type'),'Boolean')\r\n\ts.bitwidth = 1;\r\nelse\r\n\ts.bitwidth = get_param(blk_name,'bitwidth');\r\nend\r\nb = class(s,'xps_probe',blk_obj);\r\n\r\n% ip name\r\nb = set(b,'ip_name','chipscope_ila');\r\n\r\n% misc ports\r\nmisc_ports.chipscope_ila_control = {36 'in' ['chipscope_icon_control',num2str(s.ila_number)]};\r\nxsg_obj = get(blk_obj,'xsg_obj');\r\nmisc_ports.clk = {1 'in' get(xsg_obj,'clk_src')};\r\nb = set(b,'misc_ports',misc_ports);\r\n\r\n% parameters\r\nparameters.C_TRIG0_UNITS = '1';\r\nparameters.C_TRIG0_TRIGGER_IN_WIDTH = num2str(s.bitwidth);\r\nparameters.C_TRIG0_UNIT_MATCH_TYPE = s.match_type;\r\nparameters.C_TRIG0_UNIT_COUNTER_WIDTH = s.match_counter_width;\r\nparameters.C_NUM_DATA_SAMPLES = s.capture_depth;\r\nb = set(b,'parameters',parameters);"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_probe/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xsg/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_xsg.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xsg/gen_mhs_xsg.m", "size": 2117, "source_encoding": "utf_8", "md5": "765b8f9469a275a56eb973e06fa66959", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [str,opb_addr_end] = gen_mhs_xsg(blk_obj, opb_addr_start, opb_name)\r\nstr = '';\r\nopb_addr_end = opb_addr_start;\r\n\r\nstr = [str, ' PARAMETER INSTANCE = ',clear_name(get(blk_obj,'simulink_name')),'\\n'];\r\nstr = [str, ' PARAMETER HW_VER = 1.00.a\\n'];\r\n\r\nstr = [str, ' PORT clk = ',blk_obj.clk_src,'\\n'];\r\n%fprintf('\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nNew call to gen_mhs_xsg\\n');\r\n%fprintf(str);\r\n%fprintf('\\n\\n\\n\\n');\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xsg/drc.m", "size": 2359, "source_encoding": "utf_8", "md5": "6cc498c1bcad6131e8bdc5101c82a019", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction [result,msg] = drc(blk_obj, xps_objs)\r\nresult = 0;\r\nmsg = '';\r\n\r\n%check hw_sys consistancy\r\nhw_sys = get(blk_obj,'hw_sys');\r\nfor i=1:length(xps_objs)\r\n tmp = get(xps_objs{i},'hw_sys');\r\n if ~strcmp(hw_sys,tmp) & ~strcmp(tmp,'any') & isempty(strfind(hw_sys,tmp))\r\n result = 1;\r\n msg = ['Block ',get(xps_objs{i},'simulink_name'),' has an inconsistent hardware platform: ',tmp];\r\n return;\r\n end\r\nend\r\n\r\nclk_src = get(blk_obj,'clk_src');\r\nif strcmp(hw_sys,'CORR')\r\n\tif strcmp(clk_src,'usr_clk') || strcmp(clk_src,'usr_clk2x')\r\n msg = ['Cannot use usr_clk or usr_clk2x on the CORR',tmp];\r\n return;\r\n\tend\r\nend"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xsg/gen_ucf.m", "size": 2771, "source_encoding": "utf_8", "md5": "efd06701d7ccbd8ea5814ae735cae97f", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\n\nstr = '';\n\nhw_sys = blk_obj.hw_sys;\napp_clk = blk_obj.clk_src;\napp_clk_rate = blk_obj.clk_rate;\n\nif ~isempty(strmatch(app_clk, {'aux_clk', 'aux_clk2x', 'aux0_clk', 'aux1_clk', 'aux0_clk2x'}))\n\n toks = regexp(app_clk, '(.+_clk)2x', 'tokens');\n\n if isempty(toks)\n clk_rate_constraint = num2str(app_clk_rate);\n timespec_clk = app_clk;\n else\n clk_rate_constraint = num2str(app_clk_rate/2);\n timespec_clk = toks{1}{1};\n end % if isempty(toks)\n\n str = [str, '##############################################\\n'];\n str = [str, '# External Clock constraints #\\n'];\n str = [str, '##############################################\\n'];\n str = [str, '\\n'];\n str = [str, 'NET \"', timespec_clk,'_p\" TNM_NET = \"', timespec_clk,'_p\" ;\\n'];\n\n str = [str, 'TIMESPEC \"TS_', timespec_clk,'_p\" = PERIOD \"', timespec_clk, '_p\" ', clk_rate_constraint,' MHz ;\\n'];\n\n str = [str, '\\n\\n'];\nend % if ~isempty(strmatch(app_clk, {'aux0_clk', 'aux1_clk', 'aux0_clk2x'}))\n\nstr = [str, gen_ucf(blk_obj.xps_block)];\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xsg/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_xsg.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_xsg/xps_xsg.m", "size": 2876, "source_encoding": "utf_8", "md5": "6261238cc0ed593263f9d73503125a03", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_xsg(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_PPC class requires a xps_block class object');\nend % if ~isa(blk_obj,'xps_block')\n\nif ~strcmp(get(blk_obj,'type'),'xps_xsg')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend % if ~strcmp(get(blk_obj,'type'),'xps_xsg')\n\nblk_name = get(blk_obj,'simulink_name');\n\n[hw_sys, hw_subsys] = xps_get_hw_plat(get_param(blk_name,'hw_sys'));\n\ns.hw_sys = hw_sys;\ns.hw_subsys = hw_subsys;\n\nsupp_ip_names = {};\nsupp_ip_versions = {};\n\nswitch s.hw_sys\n\tcase 'ROACH'\n\t s.sw_os = 'none';\n % end case 'ROACH'\n\n\tcase 'ROACH2'\n\t s.sw_os = 'none';\n % end case 'ROACH2'\n\t\n case 'MKDIG'\n\t s.sw_os = 'none';\n % end case 'MKDIG'\n\n otherwise\n \t\terror(['Unsupported Platform: ',s.hw_sys]);\nend % switch s.hw_sys\n\ns.clk_src = get_param(blk_name,'clk_src');\ns.clk90_src = [s.clk_src,'90'];\ns.clk180_src = [s.clk_src,'180'];\ns.clk270_src = [s.clk_src,'270'];\ns.clk_rate = eval_param(blk_name,'clk_rate');\n\nb = class(s,'xps_xsg',blk_obj);\n\nb = set(b, 'supp_ip_names', supp_ip_names);\nb = set(b, 'supp_ip_versions', supp_ip_versions);\n\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(s.clk_rate*1e6));\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc_mkid_4x/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "drc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc_mkid_4x/drc.m", "size": 1751, "source_encoding": "utf_8", "md5": "805b22d398f2f8ef4c982d1cd1e67683", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [result,msg] = drc(blk_obj, xps_objs)\nresult = 0;\nmsg = '';\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc_mkid_4x/gen_ucf.m", "size": 3032, "source_encoding": "utf_8", "md5": "26e3675df4b10667893187319a84bbc2", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\n\nstr = gen_ucf(blk_obj.xps_block);\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\n\n%str = '';\n%simulink_name = clear_name(get(blk_obj,'simulink_name'));\n\n%I_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_p'];\n%I_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_I_n'];\n\n%Q_clk_p_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_p'];\n%Q_clk_n_str = ['adcmkid', blk_obj.adc_brd,'_DRDY_Q_n'];\n\n%str = [str, 'NET ', I_clk_p_str, ' TNM_NET = ', I_clk_p_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', I_clk_p_str, ' = PERIOD ', I_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n%str = [str, 'NET ', I_clk_n_str, ' TNM_NET = ', I_clk_n_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', I_clk_n_str, ' = PERIOD ', I_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\n%str = [str, '\\n'];\n\n%str = [str, 'NET ', Q_clk_p_str, ' TNM_NET = ', Q_clk_p_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', Q_clk_p_str, ' = PERIOD ', Q_clk_p_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n%str = [str, 'NET ', Q_clk_n_str, ' TNM_NET = ', Q_clk_n_str, ';\\n'];\n%str = [str, 'TIMESPEC TS_', Q_clk_n_str, ' = PERIOD ', Q_clk_n_str, ' ', num2str(2*1000/blk_obj.adc_clk_rate, '%3.3f'), ' ns;\\n'];\n\n%str = [str, '\\n'];\n\n%str = [str, gen_ucf(blk_obj.xps_block)];\n\n\nend\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_adc_mkid_4x.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc_mkid_4x/xps_adc_mkid_4x.m", "size": 5483, "source_encoding": "utf_8", "md5": "87ec020d87ad9081c8e08a80d0aeb73b", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_adc_mkid_4x(blk_obj)\nif ~isa(blk_obj,'xps_block')\n error('xps_quadc class requires a xps_block class object');\nend\nif ~strcmp(get(blk_obj,'type'),'xps_adc_mkid_4x')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.adc_brd = get_param(blk_name, 'adc_brd');\ns.adc_str = ['adc', s.adc_brd];\n\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.clk_sys = get(xsg_obj,'clk_src');\n \n \nb = class(s,'xps_adc_mkid_4x',blk_obj);\n\n% ip name & version\nb = set(b,'ip_name','adc_mkid_4x_interface');\nb = set(b,'ip_version','1.00.a');\n\nparameters.OUTPUT_CLK = '0';\nif strfind(s.clk_sys,'adc')\n parameters.OUTPUT_CLK = '1';\nend\n \nb = set(b,'parameters',parameters);\n\n\n\n\n%%%%%%%%%%%%%%%%%\n% external ports\n%%%%%%%%%%%%%%%%%\nucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(2*1000/s.adc_clk_rate),' ns']);\nucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\nucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(1e6*s.adc_clk_rate/2));\n\n\next_ports.DRDY_I_p = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_I_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[20],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.DRDY_I_n = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_I_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[20],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\n\next_ports.DRDY_Q_p = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_Q_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[40],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\next_ports.DRDY_Q_n = {1 'in' ['adcmkid',s.adc_brd,'_DRDY_Q_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[40],:}}'] 'vector=false' mhs_constraints ucf_constraints_clock};\n\next_ports.DI_p = {12 'in' ['adcmkid',s.adc_brd,'_DI_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[17 37 7 27 26 36 25 35 16 15 6 5],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.DI_n = {12 'in' ['adcmkid',s.adc_brd,'_DI_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[17 37 7 27 26 36 25 35 16 15 6 5],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.DQ_p = {12 'in' ['adcmkid',s.adc_brd,'_DQ_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[13 33 3 23 22 32 21 31 12 11 2 1],:}}'] 'vector=true' struct() ucf_constraints_term};\next_ports.DQ_n = {12 'in' ['adcmkid',s.adc_brd,'_DQ_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[13 33 3 23 22 32 21 31 12 11 2 1],:}}'] 'vector=true' struct() ucf_constraints_term};\n\next_ports.ADC_ext_in_p = {1 'in' ['adcmkid',s.adc_brd,'_ADC_ext_in_p'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_p{[29],:}}'] 'vector=false' struct() ucf_constraints_term};\next_ports.ADC_ext_in_n = {1 'in' ['adcmkid',s.adc_brd,'_ADC_ext_in_n'] ['{',s.hw_sys,'.zdok',s.adc_brd,'_n{[29],:}}'] 'vector=false' struct() ucf_constraints_term};\n\n\nb = set(b,'ext_ports',ext_ports);\n\n%%%%%%%%%%%%%\n% misc ports\n%%%%%%%%%%%%%\nmisc_ports.fpga_clk = {1 'in' get(xsg_obj,'clk_src')};\n\nif strfind(s.clk_sys,'adc')\n misc_ports.adc_clk_out = {1 'out' [s.adc_str,'_clk']};\n misc_ports.adc_clk90_out = {1 'out' [s.adc_str,'_clk90']};\n misc_ports.adc_clk180_out = {1 'out' [s.adc_str,'_clk180']};\n misc_ports.adc_clk270_out = {1 'out' [s.adc_str,'_clk270']};\nend\n\nmisc_ports.adc_dcm_locked = {1 'out' [s.adc_str, '_dcm_locked']};\n\nb = set(b,'misc_ports',misc_ports);\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_adc_mkid_4x/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "get.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_mkadc/get.m", "size": 1964, "source_encoding": "utf_8", "md5": "b339b0c993e6a4d4c7245ee5a81c130c", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction result = get(b,field)\r\n\r\n try\r\n eval(['result = b.',field,';']);\r\n catch\r\n try\r\n result = get(b.xps_block,field);\r\n catch \r\n error(['Field name unknow to block object: ', field]);\r\n end\r\n end\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_ucf.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_mkadc/gen_ucf.m", "size": 21511, "source_encoding": "utf_8", "md5": "e61f6c429fe372c562e3b95094a78704", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction str = gen_ucf(blk_obj)\ndisp('meerKAT ADC gen_ucf')\n\nhw_sys = blk_obj.hw_sys;\nadc_str = blk_obj.adc_str;\ndisp('meerKAT ADC trying generic ucf generation')\nstr = gen_ucf(blk_obj.xps_block);\nsimulink_name = clear_name(get(blk_obj,'simulink_name'));\nblk_name = get(blk_obj,'simulink_name');\nadc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ndisp('meerKAT ADC trying specific ucf generation')\nswitch hw_sys\n case {'ROACH2', 'MKDIG'}\n\n switch adc_str\n case 'adc0'\n % MeerKAT ADC ZDOK 0\n str = [str,'#MeerKAT ADC ZDOK 0 Constraints\\n'];\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/adc5g_inst/data_buf[?].D*_1\" AREA_GROUP = ZDOK_0 ;\\n'];\n str = [str, 'AREA_GROUP \"ZDOK_0\" RANGE = ', ...\n 'SLICE_X88Y200:SLICE_X89Y276 ;\\n'];\n str = [str,'\\n'];\n % MeerKAT ADC Setup & Hold Constraints for FPGA\n str = [str,'#ZDOK0 MeerKAT ADC Setup & Hold Constraints for FPGA\\n'];\n %str = [str, 'OFFSET=IN ',sprintf('%1.3f',(2000.0/adc_clk_rate)-0.4),' ns VALID 1.1 ns BEFORE \"adc0_adc_clk_p\" RISING;\\n'];\n %str = [str, 'OFFSET=IN ',sprintf('%1.3f',(2000.0/adc_clk_rate)-0.4),' ns VALID 1.1 ns BEFORE \"adc0_adc_clk_p\" FALLING;\\n']; \n str = [str,'\\n'];\n str = [str,'# meerKAT ADC0 Pins\\n'];\n str = [str,'\\n'];\n str = [str,'# ZDOK A\\n'];\n str = [str,'NET \"adc0_adc_data_b_p<9>\" LOC = L35 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB9+ ZDOK A5, P<2>\\n'];\n str = [str,'NET \"adc0_adc_data_b_n<9>\" LOC = L36 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB9- ZDOK A6, N<2>\\n'];\n str = [str,'NET \"adc0_adc_data_b_p<6>\" LOC = K35 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB6+ ZDOK A7, P<3>\\n'];\n str = [str,'NET \"adc0_adc_data_b_n<6>\" LOC = K34 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB6- ZDOK A8, N<3>\\n'];\n str = [str,'NET \"adc0_adc_data_b_p<4>\" LOC = J35 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB4+ ZDOK A9 P<4>\\n'];\n str = [str,'NET \"adc0_adc_data_b_n<4>\" LOC = H35 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB4- ZDOK A10, N<4>\\n'];\n str = [str,'\\n'];\n str = [str,'# ZDOK D\\n'];\n str = [str,'NET \"adc0_adc_reset\" LOC = N28 | IOSTANDARD = LVCMOS25; # ASYNC_RST ZDOK D1, P<10>\\n'];\n str = [str,'#NET \"adc0_adc_i2c_sda\" LOC = P28 | IOSTANDARD = LVCMOS25; # i2c_sda ZDOK D2, N<10>\\n'];\n str = [str,'NET \"adc0_adc_data_b_p<7>\" LOC = K39 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB7+ ZDOK D7, P<13>\\n'];\n str = [str,'NET \"adc0_adc_data_b_n<7>\" LOC = K40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB7- ZDOK D8, N<13>\\n'];\n str = [str,'NET \"adc0_adc_or_a_p\" LOC = E42 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # AOR+ ZDOK D13, P<16>\\n'];\n str = [str,'NET \"adc0_adc_or_a_n\" LOC = F42 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # AOR- ZDOK D14, N<16>\\n'];\n str = [str,'NET \"adc0_adc_data_a_p<6>\" LOC = C40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA6+ ZDOK D15, P<17>\\n'];\n str = [str,'NET \"adc0_adc_data_a_n<6>\" LOC = C41 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA6- ZDOK D16, N<17>\\n'];\n str = [str,'NET \"adc0_adc_data_a_p<3>\" LOC = E39 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA3+ ZDOK D17, P<18>\\n'];\n str = [str,'NET \"adc0_adc_data_a_n<3>\" LOC = E38 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA3- ZDOK D18, N<18>\\n'];\n str = [str,'NET \"adc0_adc_data_a_p<1>\" LOC = B37 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA1+ ZDOK D19, P<19>\\n'];\n str = [str,'NET \"adc0_adc_data_a_n<1>\" LOC = A37 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA1- ZDOK D20, N<19>\\n'];\n str = [str,'\\n'];\n str = [str,'# ZDOK C\\n'];\n str = [str,'NET \"adc0_adc_or_b_p\" LOC = M33 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # BOR+ ZDOK C3, P<21>\\n'];\n str = [str,'NET \"adc0_adc_or_b_n\" LOC = M32 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # BOR- ZDOK C4, N<21>\\n'];\n str = [str,'NET \"adc0_adc_data_b_p<8>\" LOC = N29 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB8+ ZDOK C5, P<22>\\n'];\n str = [str,'NET \"adc0_adc_data_b_n<8>\" LOC = N30 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB8- ZDOK C6, N<22>\\n'];\n str = [str,'NET \"adc0_adc_data_b_p<5>\" LOC = L34 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB5+ ZDOK C7, P<23>\\n'];\n str = [str,'NET \"adc0_adc_data_b_n<5>\" LOC = M34 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB5- ZDOK C8, N<23>\\n'];\n str = [str,'NET \"adc0_adc_data_b_p<3>\" LOC = G34 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB3+ ZDOK C9, P<24>\\n'];\n str = [str,'NET \"adc0_adc_data_b_n<3>\" LOC = H34 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB3- ZDOK C10, N<24>\\n'];\n str = [str,'NET \"adc0_adc_data_b_p<1>\" LOC = F39 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB1+ ZDOK C11, P<25>\\n'];\n str = [str,'NET \"adc0_adc_data_b_n<1>\" LOC = G39 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB1- ZDOK C12, N<25>\\n'];\n str = [str,'NET \"adc0_adc_data_a_p<9>\" LOC = F37 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA9+ ZDOK C13, P<26>\\n'];\n str = [str,'NET \"adc0_adc_data_a_n<9>\" LOC = E37 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA9- ZDOK C14, N<26>\\n'];\n str = [str,'NET \"adc0_adc_data_a_p<7>\" LOC = D42 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA7+ ZDOK C15, P<27>\\n'];\n str = [str,'NET \"adc0_adc_data_a_n<7>\" LOC = D41 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA7- ZDOK C16, N<27>\\n'];\n str = [str,'NET \"adc0_adc_data_a_p<4>\" LOC = A40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA4+ ZDOK C17, P<28>\\n'];\n str = [str,'NET \"adc0_adc_data_a_n<4>\" LOC = A41 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA4- ZDOK C18, N<28>\\n'];\n str = [str,'\\n'];\n str = [str,'# ZDOK F\\n'];\n str = [str,'NET \"adc0_adc_demux_bist\" LOC = L31 | IOSTANDARD = LVCMOS25; # DMUX_BIST ZDOK F1, P<29>\\n'];\n str = [str,'#NET \"adc0_adc_i2c_scl\" LOC = L32 | IOSTANDARD = LVCMOS25; # I2C_SCL ZDOK F2, N<29>\\n'];\n str = [str,'NET \"adc0_adc_sync_p\" LOC = J37 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # SYNC+ ZDOK F3 P<30>\\n'];\n str = [str,'NET \"adc0_adc_sync_n\" LOC = J36 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # SYNC- ZDOK F4 N<30>\\n'];\n str = [str,'NET \"adc0_adc_data_b_p<2>\" LOC = H39 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB2+ ZDOK F9 P<33>\\n'];\n str = [str,'NET \"adc0_adc_data_b_n<2>\" LOC = H38 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB2- ZDOK F10 N<33>\\n'];\n str = [str,'NET \"adc0_adc_data_b_p<0>\" LOC = D40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB0+ ZDOK F11 P<34>\\n'];\n str = [str,'NET \"adc0_adc_data_b_n<0>\" LOC = E40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB0- ZDOK F12 N<34>\\n'];\n str = [str,'NET \"adc0_adc_data_a_p<8>\" LOC = F40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA8+ ZDOK F13 P<35>\\n'];\n str = [str,'NET \"adc0_adc_data_a_n<8>\" LOC = F41 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA8- ZDOK F14 N<35>\\n'];\n str = [str,'NET \"adc0_adc_data_a_p<5>\" LOC = F35 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA5+ ZDOK F15, P<36>\\n'];\n str = [str,'NET \"adc0_adc_data_a_n<5>\" LOC = F36 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA5- ZDOK F16, N<36>\\n'];\n str = [str,'NET \"adc0_adc_data_a_p<2>\" LOC = D38 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA2+ ZDOK F17, P<37>\\n'];\n str = [str,'NET \"adc0_adc_data_a_n<2>\" LOC = C38 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA2- ZDOK F18, N<37>\\n'];\n str = [str,'NET \"adc0_adc_data_a_p<0>\" LOC = P30 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA0+ ZDOK F19, adc0_clk_p<1>\\n'];\n str = [str,'NET \"adc0_adc_data_a_n<0>\" LOC = P31 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA0- ZDOK F20, adc0_clk_n<1>\\n'];\n str = [str,'\\n'];\n str = [str,'NET \"adc0_iic_sda\" LOC = P28 | IOSTANDARD = LVCMOS25 | SLEW = SLOW;\\n'];\n str = [str,'NET \"adc0_iic_scl\" LOC = L32 | IOSTANDARD = LVCMOS25 | SLEW = SLOW;\\n'];\n str = [str,'\\n']; \n str = [str,'NET \"adc0_ser_clk\" LOC = P27 | IOSTANDARD = LVCMOS25 | SLEW = SLOW;\\n'];\n str = [str,'NET \"adc0_ser_dat\" LOC = M31 | IOSTANDARD = LVCMOS25 | SLEW = SLOW;\\n'];\n str = [str,'NET \"adc0_ser_cs\" LOC = R27 | IOSTANDARD = LVCMOS25 | SLEW = SLOW;\\n'];\n str = [str,'\\n'];\n % end case 'adc0'\n\n case 'adc1'\n\n % MeerKAT ADC ZDOK 1\n str = [str,'\\n'];\n str = [str,'#MeerKAT ADC ZDOK 1 Constraints\\n'];\n str = [str,'\\n'];\n \n\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/adc5g_inst/data_buf[?].D*_1\" AREA_GROUP = ZDOK_1 ;\\n'];\n str = [str, 'AREA_GROUP \"ZDOK_1\" RANGE = ', ...\n 'SLICE_X0Y246:SLICE_X1Y308 ;\\n'];\n\n str = [str, 'INST \"', simulink_name, '/', simulink_name, ...\n '/adc5g_inst/data_buf[0].D0?_1\" AREA_GROUP = ZDOK_1_0 ;\\n'];\n str = [str, 'AREA_GROUP \"ZDOK_1_r0\" RANGE = ', ...\n 'SLICE_X86Y197:SLICE_X87Y198 ;\\n'];\n\n % MeerKAT ADC Setup & Hold Constraints for FPGA\n str = [str,'#ZDOK1 MeerKAT ADC Setup & Hold Constraints for FPGA\\n'];\n %str = [str, 'OFFSET=IN ',sprintf('%1.3f',(2000.0/adc_clk_rate)-0.4),' ns BEFORE \"adc1_adc_clk_p\" RISING;\\n'];\n %str = [str, 'OFFSET=IN ',sprintf('%1.3f',(2000.0/adc_clk_rate)-0.4),' ns BEFORE \"adc1_adc_clk_p\" FALLING;\\n']; \n str = [str,'\\n'];\n str = [str,'# meerKAT ADC1 Pins\\n'];\n str = [str,'\\n'];\n str = [str,'# ZDOK A\\n'];\n str = [str,'NET \"adc1_adc_data_b_p<9>\" LOC = W35 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB9+ ZDOK A5, P<2>\\n'];\n str = [str,'NET \"adc1_adc_data_b_n<9>\" LOC = V35 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB9- ZDOK A6, N<2>\\n'];\n str = [str,'NET \"adc1_adc_data_b_p<6>\" LOC = U32 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB6+ ZDOK A7, P<3>\\n'];\n str = [str,'NET \"adc1_adc_data_b_n<6>\" LOC = U33 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB6- ZDOK A8, N<3>\\n'];\n str = [str,'NET \"adc1_adc_data_b_p<4>\" LOC = U42 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB4+ ZDOK A9 P<4>\\n'];\n str = [str,'NET \"adc1_adc_data_b_n<4>\" LOC = U41 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB4- ZDOK A10, N<4>\\n'];\n str = [str,'\\n'];\n str = [str,'# ZDOK D\\n'];\n str = [str,'NET \"adc1_adc_reset\" LOC = AA32 | IOSTANDARD = LVCMOS25; # ASYNC_RST ZDOK D1, P<10>\\n'];\n str = [str,'#NET \"adc1_adc_i2c_sda\" LOC = Y32 | IOSTANDARD = LVCMOS25; # i2c_sda ZDOK D2, N<10>\\n'];\n str = [str,'NET \"adc1_adc_data_b_p<7>\" LOC = V41 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB7+ ZDOK D7, P<13>\\n'];\n str = [str,'NET \"adc1_adc_data_b_n<7>\" LOC = W41 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB7- ZDOK D8, N<13>\\n'];\n str = [str,'NET \"adc1_adc_or_a_p\" LOC = T41 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # AOR+ ZDOK D13, P<16>\\n'];\n str = [str,'NET \"adc1_adc_or_a_n\" LOC = T42 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # AOR- ZDOK D14, N<16>\\n'];\n str = [str,'NET \"adc1_adc_data_a_p<6>\" LOC = R39 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA6+ ZDOK D15, P<17>\\n'];\n str = [str,'NET \"adc1_adc_data_a_n<6>\" LOC = P38 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA6- ZDOK D16, N<17>\\n'];\n str = [str,'NET \"adc1_adc_data_a_p<3>\" LOC = N36 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA3+ ZDOK D17, P<18>\\n'];\n str = [str,'NET \"adc1_adc_data_a_n<3>\" LOC = P37 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA3- ZDOK D18, N<18>\\n'];\n str = [str,'NET \"adc1_adc_data_a_p<1>\" LOC = N40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA1+ ZDOK D19, P<19>\\n'];\n str = [str,'NET \"adc1_adc_data_a_n<1>\" LOC = N41 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA1- ZDOK D20, N<19>\\n'];\n str = [str,'\\n'];\n str = [str,'# ZDOK C\\n'];\n str = [str,'NET \"adc1_adc_or_b_p\" LOC = W32 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # BOR+ ZDOK C3, P<21>\\n'];\n str = [str,'NET \"adc1_adc_or_b_n\" LOC = Y33 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # BOR- ZDOK C4, N<21>\\n'];\n str = [str,'NET \"adc1_adc_data_b_p<8>\" LOC = W36 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB8+ ZDOK C5, P<22>\\n'];\n str = [str,'NET \"adc1_adc_data_b_n<8>\" LOC = V36 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB8- ZDOK C6, N<22>\\n'];\n str = [str,'NET \"adc1_adc_data_b_p<5>\" LOC = V40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB5+ ZDOK C7, P<23>\\n'];\n str = [str,'NET \"adc1_adc_data_b_n<5>\" LOC = W40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB5- ZDOK C8, N<23>\\n'];\n str = [str,'NET \"adc1_adc_data_b_p<3>\" LOC = U37 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB3+ ZDOK C9, P<24>\\n'];\n str = [str,'NET \"adc1_adc_data_b_n<3>\" LOC = U38 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB3- ZDOK C10, N<24>\\n'];\n str = [str,'NET \"adc1_adc_data_b_p<1>\" LOC = T39 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB1+ ZDOK C11, P<25>\\n'];\n str = [str,'NET \"adc1_adc_data_b_n<1>\" LOC = R38 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB1- ZDOK C12, N<25>\\n'];\n str = [str,'NET \"adc1_adc_data_a_p<9>\" LOC = P42 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA9+ ZDOK C13, P<26>\\n'];\n str = [str,'NET \"adc1_adc_data_a_n<9>\" LOC = R42 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA9- ZDOK C14, N<26>\\n'];\n str = [str,'NET \"adc1_adc_data_a_p<7>\" LOC = P40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA7+ ZDOK C15, P<27>\\n'];\n str = [str,'NET \"adc1_adc_data_a_n<7>\" LOC = P41 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA7- ZDOK C16, N<27>\\n'];\n str = [str,'NET \"adc1_adc_data_a_p<4>\" LOC = M38 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA4+ ZDOK C17, P<28>\\n'];\n str = [str,'NET \"adc1_adc_data_a_n<4>\" LOC = M39 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA4- ZDOK C18, N<28>\\n'];\n str = [str,'\\n'];\n str = [str,'# ZDOK F\\n'];\n str = [str,'NET \"adc1_adc_demux_bist\" LOC = AA36 | IOSTANDARD = LVCMOS25; # DMUX_BIST ZDOK F1, P<29>\\n'];\n str = [str,'#NET \"adc1_adc_i2c_scl\" LOC = AA37 | IOSTANDARD = LVCMOS25; # I2C_SCL ZDOK F2, N<29>\\n'];\n str = [str,'NET \"adc1_adc_sync_p\" LOC = W42 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # SYNC+ ZDOK F3 P<30>\\n'];\n str = [str,'NET \"adc1_adc_sync_n\" LOC = Y42 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # SYNC- ZDOK F4 N<30>\\n'];\n str = [str,'NET \"adc1_adc_data_b_p<2>\" LOC = V34 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB2+ ZDOK F9 P<33>\\n'];\n str = [str,'NET \"adc1_adc_data_b_n<2>\" LOC = U34 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB2- ZDOK F10 N<33>\\n'];\n str = [str,'NET \"adc1_adc_data_b_p<0>\" LOC = T34 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB0+ ZDOK F11 P<34>\\n'];\n str = [str,'NET \"adc1_adc_data_b_n<0>\" LOC = T35 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DB0- ZDOK F12 N<34>\\n'];\n str = [str,'NET \"adc1_adc_data_a_p<8>\" LOC = R40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA8+ ZDOK F13 P<35>\\n'];\n str = [str,'NET \"adc1_adc_data_a_n<8>\" LOC = T40 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA8- ZDOK F14 N<35>\\n'];\n str = [str,'NET \"adc1_adc_data_a_p<5>\" LOC = M36 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA5+ ZDOK F15, P<36>\\n'];\n str = [str,'NET \"adc1_adc_data_a_n<5>\" LOC = M37 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA5- ZDOK F16, N<36>\\n'];\n str = [str,'NET \"adc1_adc_data_a_p<2>\" LOC = N38 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA2+ ZDOK F17, P<37>\\n'];\n str = [str,'NET \"adc1_adc_data_a_n<2>\" LOC = N39 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA2- ZDOK F18, N<37>\\n'];\n str = [str,'NET \"adc1_adc_data_a_p<0>\" LOC = AE30 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA0+ ZDOK F19, adc1_clk_p<1>\\n'];\n str = [str,'NET \"adc1_adc_data_a_n<0>\" LOC = AF30 | IOSTANDARD = LVDS_25 | DIFF_TERM = TRUE; # DA0- ZDOK F20, adc1_clk_n<1>\\n'];\n str = [str,'\\n'];\n str = [str,'NET \"adc1_iic_sda\" LOC = Y32 | IOSTANDARD = LVCMOS25 | SLEW = SLOW;\\n'];\n str = [str,'NET \"adc1_iic_scl\" LOC = AA37 | IOSTANDARD = LVCMOS25 | SLEW = SLOW;\\n'];\n str = [str,'\\n']; \n str = [str,'NET \"adc1_ser_clk\" LOC = AA34 | IOSTANDARD = LVCMOS25 | SLEW = SLOW;\\n'];\n str = [str,'NET \"adc1_ser_dat\" LOC = Y34 | IOSTANDARD = LVCMOS25 | SLEW = SLOW;\\n'];\n str = [str,'NET \"adc1_ser_cs\" LOC = Y37 | IOSTANDARD = LVCMOS25 | SLEW = SLOW;\\n'];\n str = [str,'\\n'];\n % end case 'adc1'\n end % switch adc_str\n % end case 'ROACH2'\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend % switch hw_sys\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "set.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_mkadc/set.m", "size": 1837, "source_encoding": "utf_8", "md5": "36e88663abfc3840e2a2596d6628fb05", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% %\r\n% Center for Astronomy Signal Processing and Electronics Research %\r\n% http://seti.ssl.berkeley.edu/casper/ %\r\n% Copyright (C) 2006 University of California, Berkeley %\r\n% %\r\n% This program is free software; you can redistribute it and/or modify %\r\n% it under the terms of the GNU General Public License as published by %\r\n% the Free Software Foundation; either version 2 of the License, or %\r\n% (at your option) any later version. %\r\n% %\r\n% This program is distributed in the hope that it will be useful, %\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\r\n% GNU General Public License for more details. %\r\n% %\r\n% You should have received a copy of the GNU General Public License along %\r\n% with this program; if not, write to the Free Software Foundation, Inc., %\r\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\r\n% %\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\nfunction b = set(b,field,value)\r\ntry\r\n eval(['b.',field,'=value;']);\r\ncatch\r\n b.xps_block = set(b.xps_block,field,value);\r\nend\r\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "gen_mhs_ip.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_mkadc/gen_mhs_ip.m", "size": 5823, "source_encoding": "utf_8", "md5": "35fd1f212f1606710287df4f4021f557", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj,opb_addr_start,opb_name)\n\nhw_adc = get(blk_obj, 'hw_adc');\n\n%% HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK \n%% Remove gain control ports from adc_interface intstantiation\n%gain_load_port = '';\n%gain_value_port = '';\n%clk_src = get(blk_obj,'clk_src'); \n%en_gain = get(blk_obj,'en_gain'); \n\n%foo = get(blk_obj,'ports');\n%portname = fieldnames(foo);\n%for n = 1:length(portname)\n% if (~isempty(regexp(portname{n},'gain_value')))\n% gain_value_port = portname{n};\n% foo = rmfield(foo, portname{n});\n% end\n% if (~isempty(regexp(portname{n},'gain_load')))\n% gain_load_port = portname{n};\n% foo = rmfield(foo, portname{n});\n% end\n% %port_names{n}\n%end\n\n%blk_obj = set(blk_obj,'ports',foo);\n\n% Add the MHS entry for the ADC Interface\n[str,opb_addr_end,opb_addr_start] = gen_mhs_ip(blk_obj.xps_block, opb_addr_start, opb_name);\nstr = [str, '\\n'];\n\nif (strcmp(hw_adc, 'adc1'))\n base_addr = '0x00048000';\n high_addr = '0x000487ff';\nelse\n base_addr = '0x00040000';\n high_addr = '0x000407ff';\nend\n\n% Add IIC controller\nstr = [str, 'BEGIN kat_adc_iic_controller', '\\n'];\nstr = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\nstr = [str, ' PARAMETER INSTANCE = iic_', hw_adc, '\\n'];\nstr = [str, ' PARAMETER C_BASEADDR = ', base_addr, '\\n'];\nstr = [str, ' PARAMETER C_HIGHADDR = ', high_addr, '\\n'];\n\n%if (strcmp(en_gain,'on'))\n% str = [str, ' PARAMETER EN_GAIN = 1', '\\n'];\n%end\n\nstr = [str, ' PARAMETER CORE_FREQ = 66666', '\\n'];\nstr = [str, ' PARAMETER IIC_FREQ = 100', '\\n'];\nstr = [str, ' BUS_INTERFACE SOPB = opb0', '\\n'];\nstr = [str, ' PORT OPB_Clk = epb_clk', '\\n'];\nstr = [str, '', '\\n'];\nstr = [str, ' PORT sda_i = iic_', hw_adc, '_sda_i', '\\n'];\nstr = [str, ' PORT sda_o = iic_', hw_adc, '_sda_o', '\\n'];\nstr = [str, ' PORT sda_t = iic_', hw_adc, '_sda_t', '\\n'];\nstr = [str, ' PORT scl_i = iic_', hw_adc, '_scl_i', '\\n'];\nstr = [str, ' PORT scl_o = iic_', hw_adc, '_scl_o', '\\n'];\nstr = [str, ' PORT scl_t = iic_', hw_adc, '_scl_t', '\\n'];\n%str = [str, ' PORT gain_value = ', gain_value_port, '\\n'];\n%str = [str, ' PORT gain_load = ', gain_load_port, '\\n'];\nstr = [str, ' PORT app_clk = epb_clk', '\\n'];\nstr = [str, 'END', '\\n'];\nstr = [str, '', '\\n'];\nstr = [str, 'PORT ', hw_adc, '_iic_sda = ', hw_adc, '_iic_sda, DIR = IO', '\\n'];\nstr = [str, 'PORT ', hw_adc, '_iic_scl = ', hw_adc, '_iic_scl, DIR = IO', '\\n'];\nstr = [str, '', '\\n'];\nstr = [str, 'BEGIN iic_infrastructure', '\\n'];\nstr = [str, ' PARAMETER HW_VER = 1.00.a', '\\n'];\nstr = [str, ' PARAMETER INSTANCE = iic_infrastructure_', hw_adc, '\\n'];\nstr = [str, ' PORT Sda_I = iic_', hw_adc, '_sda_i', '\\n'];\nstr = [str, ' PORT Sda_O = iic_', hw_adc, '_sda_o', '\\n'];\nstr = [str, ' PORT Sda_T = iic_', hw_adc, '_sda_t', '\\n'];\nstr = [str, ' PORT Scl_I = iic_', hw_adc, '_scl_i', '\\n'];\nstr = [str, ' PORT Scl_O = iic_', hw_adc, '_scl_o', '\\n'];\nstr = [str, ' PORT Scl_T = iic_', hw_adc, '_scl_t', '\\n'];\nstr = [str, ' PORT Sda = ', hw_adc, '_iic_sda', '\\n'];\nstr = [str, ' PORT Scl = ', hw_adc, '_iic_scl', '\\n'];\nstr = [str, 'END', '\\n'];\n\n"} +{"plateform": "github", "repo_name": "mstrader/mlib_devel-master", "name": "xps_mkadc.m", "ext": ".m", "path": "mlib_devel-master/xps_library/@xps_mkadc/xps_mkadc.m", "size": 6159, "source_encoding": "utf_8", "md5": "6092f2e173a6a4c90471cfdbb7f80b76", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% Center for Astronomy Signal Processing and Electronics Research %\n% http://seti.ssl.berkeley.edu/casper/ %\n% Copyright (C) 2006 University of California, Berkeley %\n% %\n% This program is free software; you can redistribute it and/or modify %\n% it under the terms of the GNU General Public License as published by %\n% the Free Software Foundation; either version 2 of the License, or %\n% (at your option) any later version. %\n% %\n% This program is distributed in the hope that it will be useful, %\n% but WITHOUT ANY WARRANTY; without even the implied warranty of %\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %\n% GNU General Public License for more details. %\n% %\n% You should have received a copy of the GNU General Public License along %\n% with this program; if not, write to the Free Software Foundation, Inc., %\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction b = xps_mkadc(blk_obj)\n\nif ~isa(blk_obj,'xps_block')\n error('XPS_ADC class requires a xps_block class object');\nend\n\nif ~strcmp(get(blk_obj,'type'),'xps_mkadc')\n error(['Wrong XPS block type: ',get(blk_obj,'type')]);\nend\n\nblk_name = get(blk_obj,'simulink_name');\nxsg_obj = get(blk_obj,'xsg_obj');\n\n\ns.hw_sys = get(xsg_obj,'hw_sys');\ns.hw_adc = get_param(blk_name,'adc_brd');\ns.adc_clk_rate = eval_param(blk_name,'adc_clk_rate');\ns.clk_src = get(xsg_obj,'clk_src');\n\n% Get MASK paramters from the one_GbE yellow block\ns.hw_sys = get(xsg_obj,'hw_sys');\n\ns.gray_en = num2str(strcmp(get_param(blk_name, 'gray_en'), 'on'));\n\n% These MASK parameters ends up to be generics for the HDL (mkadc_interface.vhd)\n% also see mkadc_interface_v2_1_0.mpd for connections and parameter declarations\nparameters.G_GRAY_EN = s.gray_en;\n\nswitch s.hw_sys\n case {'ROACH2', 'MKDIG'}\n if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n s.adc_str = s.hw_adc;\n else\n error(['Unsupported adc board: ',s.hw_adc]);\n end % if ~isempty(find(strcmp(s.hw_adc, {'adc0', 'adc1'})))\n\n ucf_constraints_clock = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE', 'PERIOD', [num2str(1000/s.adc_clk_rate*4),' ns']);\n ucf_constraints_term = struct('IOSTANDARD', 'LVDS_25', 'DIFF_TERM', 'TRUE');\n ucf_constraints_noterm = struct('IOSTANDARD', 'LVDS_25');\n % end case {'ROACH', 'ROACH2'}\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend % end switch s.hw_sys\n\nb = class(s,'xps_mkadc',blk_obj);\n\n% ip name and version\nb = set(b, 'ip_name', 'mkadc_interface');\n\nswitch s.hw_sys\n case {'ROACH2', 'MKDIG'}\n b = set(b, 'ip_version', '1.00.a');\n %hard-coded opb0 devices\n b = set(b, 'opb0_devices', 2); %IIC and controller\nend % switch s.hw_sys\n\nsupp_ip_names = {'', 'opb_katadccontroller'};\nsupp_ip_versions = {'', '1.00.a'};\n\nb = set(b, 'supp_ip_names', supp_ip_names);\nb = set(b, 'supp_ip_versions', supp_ip_versions);\n\nb = set(b,'parameters',parameters);\n\n% misc ports\nmisc_ports.ctrl_clk_in = {1 'in' get(xsg_obj,'clk_src')};\nmisc_ports.ctrl_clk_out = {1 'out' [s.adc_str,'_clk']};\nmisc_ports.ctrl_clk90_out = {1 'out' [s.adc_str,'_clk90']};\nmisc_ports.ctrl_clk180_out = {1 'out' [s.adc_str,'_clk180']};\nmisc_ports.ctrl_clk270_out = {1 'out' [s.adc_str,'_clk270']};\nmisc_ports.power_on_rst = {1 'in' ['power_on_rst']};\nswitch s.hw_sys\n case {'ROACH2', 'MKDIG'}\n misc_ports.ctrl_mmcm_locked = {1 'out' [s.adc_str,'_mmcm_locked']};\n misc_ports.mmcm_reset = {1 'in' [s.adc_str,'_mmcm_reset']};\n misc_ports.mmcm_psdone = {1 'out' [s.adc_str,'_psdone']};\n misc_ports.mmcm_psclk = {1 'in' ['epb_clk']};\n misc_ports.mmcm_psen = {1 'in' [s.adc_str,'_psen']};\n misc_ports.mmcm_psincdec = {1 'in' [s.adc_str,'_psincdec']};\n otherwise\n error(['Unsupported hardware system: ',s.hw_sys]);\nend\n\nb = set(b,'misc_ports',misc_ports);\n\n% external ports\nmhs_constraints = struct('SIGIS','CLK', 'CLK_FREQ',num2str(s.adc_clk_rate*1e6*2));\n\nadcport = [s.hw_sys, '.', 'zdok', s.adc_str(length(s.adc_str))];\n\next_ports.adc_clk_p = {1 'in' [s.adc_str,'_adc_clk_p'] ['{',adcport,'_p{[19]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc_clk_n = {1 'in' [s.adc_str,'_adc_clk_n'] ['{',adcport,'_n{[19]+1,:}}'] 'vector=false' mhs_constraints ucf_constraints_clock };\next_ports.adc_sync_p = {1 'in' [s.adc_str,'_adc_sync_p'] };\next_ports.adc_sync_n = {1 'in' [s.adc_str,'_adc_sync_n'] };\next_ports.adc_or_a_p = {1 'in' [s.adc_str,'_adc_or_a_p'] };\next_ports.adc_or_a_n = {1 'in' [s.adc_str,'_adc_or_a_n'] };\next_ports.adc_or_b_p = {1 'in' [s.adc_str,'_adc_or_b_p'] };\next_ports.adc_or_b_n = {1 'in' [s.adc_str,'_adc_or_b_n'] };\next_ports.adc_data_a_p = {10 'in' [s.adc_str,'_adc_data_a_p'] };\next_ports.adc_data_a_n = {10 'in' [s.adc_str,'_adc_data_a_n'] };\next_ports.adc_data_b_p = {10 'in' [s.adc_str,'_adc_data_b_p'] };\next_ports.adc_data_b_n = {10 'in' [s.adc_str,'_adc_data_b_n'] };\next_ports.adc_reset = {1 'out' [s.adc_str,'_adc_reset'] };\next_ports.adc_demux_bist = {1 'out' [s.adc_str,'_adc_demux_bist'] };\n\nb = set(b,'ext_ports',ext_ports);\n"} +{"plateform": "github", "repo_name": "roboticslab-uc3m/yarp-devices-master", "name": "testRemoteVelEnc_sfun.m", "ext": ".m", "path": "yarp-devices-master/examples/simulink/testRemoteVelEnc_sfun.m", "size": 11273, "source_encoding": "utf_8", "md5": "e13541a729d0c52f84759a0ffbb91504", "text": "function [sys,x0,str,ts,simStateCompliance] = testRemoteVelEnc_sfun(t,x,u,flag,theName,theNumAxes)\n%SFUNTMPL General M-file S-function template\n% With M-file S-functions, you can define you own ordinary differential\n% equations (ODEs), discrete system equations, and/or just about\n% any type of algorithm to be used within a Simulink block diagram.\n%\n% The general form of an M-File S-function syntax is:\n% [SYS,X0,STR,TS,SIMSTATECOMPLIANCE] = SFUNC(T,X,U,FLAG,P1,...,Pn)\n%\n% What is returned by SFUNC at a given point in time, T, depends on the\n% value of the FLAG, the current state vector, X, and the current\n% input vector, U.\n%\n% FLAG RESULT DESCRIPTION\n% ----- ------ --------------------------------------------\n% 0 [SIZES,X0,STR,TS] Initialization, return system sizes in SYS,\n% initial state in X0, state ordering strings\n% in STR, and sample times in TS.\n% 1 DX Return continuous state derivatives in SYS.\n% 2 DS Update discrete states SYS = X(n+1)\n% 3 Y Return outputs in SYS.\n% 4 TNEXT Return next time hit for variable step sample\n% time in SYS.\n% 5 Reserved for future (root finding).\n% 9 [] Termination, perform any cleanup SYS=[].\n%\n%\n% The state vectors, X and X0 consists of continuous states followed\n% by discrete states.\n%\n% Optional parameters, P1,...,Pn can be provided to the S-function and\n% used during any FLAG operation.\n%\n% When SFUNC is called with FLAG = 0, the following information\n% should be returned:\n%\n% SYS(1) = Number of continuous states.\n% SYS(2) = Number of discrete states.\n% SYS(3) = Number of outputs.\n% SYS(4) = Number of inputs.\n% Any of the first four elements in SYS can be specified\n% as -1 indicating that they are dynamically sized. The\n% actual length for all other flags will be equal to the\n% length of the input, U.\n% SYS(5) = Reserved for root finding. Must be zero.\n% SYS(6) = Direct feedthrough flag (1=yes, 0=no). The s-function\n% has direct feedthrough if U is used during the FLAG=3\n% call. Setting this to 0 is akin to making a promise that\n% U will not be used during FLAG=3. If you break the promise\n% then unpredictable results will occur.\n% SYS(7) = Number of sample times. This is the number of rows in TS.\n%\n%\n% X0 = Initial state conditions or [] if no states.\n%\n% STR = State ordering strings which is generally specified as [].\n%\n% TS = An m-by-2 matrix containing the sample time\n% (period, offset) information. Where m = number of sample\n% times. The ordering of the sample times must be:\n%\n% TS = [0 0, : Continuous sample time.\n% 0 1, : Continuous, but fixed in minor step\n% sample time.\n% PERIOD OFFSET, : Discrete sample time where\n% PERIOD > 0 & OFFSET < PERIOD.\n% -2 0]; : Variable step discrete sample time\n% where FLAG=4 is used to get time of\n% next hit.\n%\n% There can be more than one sample time providing\n% they are ordered such that they are monotonically\n% increasing. Only the needed sample times should be\n% specified in TS. When specifying more than one\n% sample time, you must check for sample hits explicitly by\n% seeing if\n% abs(round((T-OFFSET)/PERIOD) - (T-OFFSET)/PERIOD)\n% is within a specified tolerance, generally 1e-8. This\n% tolerance is dependent upon your model's sampling times\n% and simulation time.\n%\n% You can also specify that the sample time of the S-function\n% is inherited from the driving block. For functions which\n% change during minor steps, this is done by\n% specifying SYS(7) = 1 and TS = [-1 0]. For functions which\n% are held during minor steps, this is done by specifying\n% SYS(7) = 1 and TS = [-1 1].\n%\n% SIMSTATECOMPLIANCE = Specifices how to handle this block when saving and\n% restoring the complete simulation state of the\n% model. The allowed values are: 'DefaultSimState',\n% 'HasNoSimState' or 'DisallowSimState'. If this value\n% is not speficified, then the block's compliance with\n% simState feature is set to 'UknownSimState'.\n%\n% Copyright 1990-2007 The MathWorks, Inc.\n% $Revision: 1.18.2.3 $\n%\n% The following outlines the general structure of an S-function.\n%\nswitch flag,\n\n %%%%%%%%%%%%%%%%%%\n % Initialization %\n %%%%%%%%%%%%%%%%%%\n case 0,\n [sys,x0,str,ts,simStateCompliance]=mdlInitializeSizes(theName,theNumAxes); \n\n %%%%%%%%%%%%%%%\n % Derivatives %\n %%%%%%%%%%%%%%%\n case 1,\n sys=mdlDerivatives(t,x,u);\n\n %%%%%%%%%%\n % Update %\n %%%%%%%%%%\n case 2,\n sys=mdlUpdate(t,x,u);\n\n %%%%%%%%%%%\n % Outputs %\n %%%%%%%%%%%\n case 3,\n sys=mdlOutputs(t,x,u);\n\n %%%%%%%%%%%%%%%%%%%%%%%\n % GetTimeOfNextVarHit %\n %%%%%%%%%%%%%%%%%%%%%%%\n case 4,\n sys=mdlGetTimeOfNextVarHit(t,x,u);\n\n %%%%%%%%%%%%%\n % Terminate %\n %%%%%%%%%%%%%\n case 9,\n sys=mdlTerminate(t,x,u);\n\n %%%%%%%%%%%%%%%%%%%%\n % Unexpected flags %\n %%%%%%%%%%%%%%%%%%%%\n otherwise\n DAStudio.error('Simulink:blocks:unhandledFlag', num2str(flag));\n\nend\n% end testRemoteVelEnc\n\n\n%=============================================================================\n% mdlInitializeSizes\n% Return the sizes, initial conditions, and sample times for the S-function.\n%=============================================================================\n%\nfunction [sys,x0,str,ts,simStateCompliance]=mdlInitializeSizes(fName,fAxes)\n%\n% call simsizes for a sizes structure, fill it in and convert it to a\n% sizes array.\n%\n% Note that in this example, the values are hard coded. This is not a\n% recommended practice as the characteristics of the block are typically\n% defined by the S-function parameters.\n%\nsizes = simsizes;\n\nglobal keepAxes;\nkeepAxes = fAxes;\nsizes.NumContStates = 0;\nsizes.NumDiscStates = 0;\nsizes.NumOutputs = fAxes;\nsizes.NumInputs = fAxes;\nsizes.DirFeedthrough = 1;\nsizes.NumSampleTimes = 1; % at least one sample time is needed\n\nsys = simsizes(sizes);\n\n%\n% initialize the initial conditions\n%\nx0 = [];\n\n%\n% str is always an empty matrix\n%\nstr = [];\n\n%\n% initialize the array of sample times\n%\nts = [0 0];\n\n% Specify the block simStateComliance. The allowed values are:\n% 'UnknownSimState', < The default setting; warn and assume DefaultSimState\n% 'DefaultSimState', < Same sim state as a built-in block\n% 'HasNoSimState', < No sim state\n% 'DisallowSimState' < Error out when saving or restoring the model sim state\nsimStateCompliance = 'UnknownSimState';\n\n% Now do all the YARP stuff.\nfprintf('Welcome to testRemoteVelEnc. This program tries to open a port\\n');\nfprintf('called /testRemoteVelEnc, connect to a remote controlboard called\\n');\nfprintf('%s, and then stream some doubles!!!\\n',fName);\nLoadYarp;\nglobal dd;\nglobal vel;\nglobal enc;\noptions = yarp.Property; % create an instance of Property, a nice YARP class for storing name-value (key-value) pairs\noptions.put('device','remote_controlboard'); % we add a name-value pair that indicates the YARP device\noptions.put('remote',fName); % we add info on to whom we will connect\noptions.put('local','/testRemoteVelEnc'); % we add info on how we will call ourselves on the YARP network\ndd = yarp.PolyDriver(options); % create a YARP multi-use driver with the given options\nif isequal(dd.isValid,1)\n disp '[success] robot available';\nelse\n disp '[warning] robot NOT available, does it exist?';\nend\nvel = dd.viewIVelocityControl; % make a velocity controller object we call 'vel'\nif isequal(vel,[])\n disp '[warning] velocity NOT available, does it exist?';\nelse\n disp '[success] robot velocity interface available';\nend\nenc = dd.viewIEncoders; % make an encoder controller object we call 'enc'\nif isequal(enc,[])\n disp '[warning] encoders NOT available, does it exist?';\nelse\n disp '[success] robot encoder interface available';\nend\nif isequal(enc.getAxes,fAxes)\n fprintf('[success] robot reports %d axes as configured in block\\n',fAxes);\nelse\n fprintf('[warning] block configured for %d axes but robot reports %d axes\\n',fAxes,enc.getAxes);\nend\nglobal dUpdated;\ndUpdated = zeros(fAxes,1);\nvel.setVelocityMode;\n% end mdlInitializeSizes\n\n\n%=============================================================================\n% mdlDerivatives\n% Return the derivatives for the continuous states.\n%=============================================================================\n%\nfunction sys=mdlDerivatives(t,x,u)\nsys = [];\n% end mdlDerivatives\n\n\n%=============================================================================\n% mdlUpdate\n% Handle discrete state updates, sample time hits, and major time step\n% requirements.\n%=============================================================================\n%\nfunction sys=mdlUpdate(t,x,u)\nglobal keepAxes;\nglobal enc;\nglobal vel;\nglobal dUpdated;\nvEnc = yarp.DVector(keepAxes); % create a YARP vector of doubles the size of the number of axes\nenc.getEncoders(vEnc);\nfor i=1:1:keepAxes\n dUpdated(i) = vEnc.get(i-1);\nend\n%vVel = yarp.DVector; % create a YARP vector of doubles\n%for i=1:1:keepAxes\n% vVel.add(u(i));\n%end\n%vel.velocityMove(vVel);\nfor i=1:1:keepAxes\n vel.velocityMove(i-1,u(i));\nend\nsys = [];\n% end mdlUpdate\n\n\n%=============================================================================\n% mdlOutputs\n% Return the block outputs.\n%=============================================================================\n%\nfunction sys=mdlOutputs(t,x,u)\nglobal dUpdated;\nsys = [dUpdated];\n% end mdlOutputs\n\n\n%=============================================================================\n% mdlGetTimeOfNextVarHit\n% Return the time of the next hit for this block. Note that the result is\n% absolute time. Note that this function is only used when you specify a\n% variable discrete-time sample time [-2 0] in the sample time array in\n% mdlInitializeSizes.\n%=============================================================================\n%\nfunction sys=mdlGetTimeOfNextVarHit(t,x,u)\nsampleTime = 1; % Example, set the next hit to be one second later.\nsys = t + sampleTime;\n% end mdlGetTimeOfNextVarHit\n\n\n%=============================================================================\n% mdlTerminate\n% Perform any end of simulation tasks.\n%=============================================================================\n%\nfunction sys=mdlTerminate(t,x,u)\nglobal dd;\nglobal vel;\nvel.stop;\ndd.close;\ndisp '[success] called for device close'\nsys = [];\n% end mdlTerminate\n\n"}